Compare commits

..

4 Commits

Author SHA1 Message Date
Brendan Allan 55874ccaeb simplify repalceServerConnection 2026-08-07 19:34:47 +08:00
Brendan Allan b8ed70d6d3 refactor(app): split server management controllers 2026-08-07 17:37:35 +08:00
Aiden Cline 2092350cfa fix(core): align shell output limits (#41007) 2026-08-07 00:18:16 -05:00
Aiden Cline 5fb0d7c99c feat(core): bound tool output (#40929) 2026-08-07 00:02:14 -05:00
55 changed files with 1350 additions and 1225 deletions
@@ -1,4 +1,4 @@
import type { FormAnswer, IntegrationMethod, IntegrationOauthConnectOutput } from "@opencode-ai/client/promise" import type { IntegrationMethod, IntegrationOauthConnectOutput } from "@opencode-ai/client/promise"
import { Button } from "@opencode-ai/ui/button" import { Button } from "@opencode-ai/ui/button"
import { useDialog } from "@opencode-ai/ui/context/dialog" import { useDialog } from "@opencode-ai/ui/context/dialog"
import { Dialog } from "@opencode-ai/ui/dialog" import { Dialog } from "@opencode-ai/ui/dialog"
@@ -40,8 +40,6 @@ import { decode64 } from "@/utils/base64"
const CUSTOM_ID = "_custom" const CUSTOM_ID = "_custom"
type ConnectMethod = Extract<IntegrationMethod, { type: "key" | "oauth" }> type ConnectMethod = Extract<IntegrationMethod, { type: "key" | "oauth" }>
type IntegrationForm = NonNullable<ConnectMethod["forms"]>[number]
type StringForm = Extract<IntegrationForm, { type: "string" }>
export function useProviderConnectController(options: { onBack?: () => void } = {}) { export function useProviderConnectController(options: { onBack?: () => void } = {}) {
const [store, setStore] = createStore({ selected: undefined as string | undefined }) const [store, setStore] = createStore({ selected: undefined as string | undefined })
@@ -436,16 +434,16 @@ function ProviderConnection(props: {
const [store, setStore] = createStore({ const [store, setStore] = createStore({
methodIndex: undefined as undefined | number, methodIndex: undefined as undefined | number,
authorization: undefined as undefined | IntegrationOauthConnectOutput["data"], authorization: undefined as undefined | IntegrationOauthConnectOutput["data"],
formAnswers: undefined as FormAnswer | undefined, promptInputs: undefined as undefined | Record<string, string>,
state: "pending" as undefined | "pending" | "complete" | "error" | "form", state: "pending" as undefined | "pending" | "complete" | "error" | "prompt",
error: undefined as string | undefined, error: undefined as string | undefined,
}) })
type Action = type Action =
| { type: "method.select"; index: number } | { type: "method.select"; index: number }
| { type: "method.reset" } | { type: "method.reset" }
| { type: "auth.form" } | { type: "auth.prompt" }
| { type: "auth.answers"; answers: FormAnswer } | { type: "auth.inputs"; inputs: Record<string, string> }
| { type: "auth.pending" } | { type: "auth.pending" }
| { type: "auth.complete"; authorization: IntegrationOauthConnectOutput["data"] } | { type: "auth.complete"; authorization: IntegrationOauthConnectOutput["data"] }
| { type: "auth.error"; error: string } | { type: "auth.error"; error: string }
@@ -456,7 +454,7 @@ function ProviderConnection(props: {
if (action.type === "method.select") { if (action.type === "method.select") {
draft.methodIndex = action.index draft.methodIndex = action.index
draft.authorization = undefined draft.authorization = undefined
draft.formAnswers = undefined draft.promptInputs = undefined
draft.state = undefined draft.state = undefined
draft.error = undefined draft.error = undefined
return return
@@ -464,18 +462,18 @@ function ProviderConnection(props: {
if (action.type === "method.reset") { if (action.type === "method.reset") {
draft.methodIndex = undefined draft.methodIndex = undefined
draft.authorization = undefined draft.authorization = undefined
draft.formAnswers = undefined draft.promptInputs = undefined
draft.state = undefined draft.state = undefined
draft.error = undefined draft.error = undefined
return return
} }
if (action.type === "auth.form") { if (action.type === "auth.prompt") {
draft.state = "form" draft.state = "prompt"
draft.error = undefined draft.error = undefined
return return
} }
if (action.type === "auth.answers") { if (action.type === "auth.inputs") {
draft.formAnswers = action.answers draft.promptInputs = action.inputs
draft.state = undefined draft.state = undefined
draft.error = undefined draft.error = undefined
return return
@@ -533,7 +531,7 @@ function ProviderConnection(props: {
return fallback return fallback
} }
async function selectMethod(index: number, answers?: FormAnswer) { async function selectMethod(index: number, inputs?: Record<string, string>) {
if (timer.current !== undefined) { if (timer.current !== undefined) {
clearTimeout(timer.current) clearTimeout(timer.current)
timer.current = undefined timer.current = undefined
@@ -542,17 +540,9 @@ function ProviderConnection(props: {
const method = methods()[index] const method = methods()[index]
dispatch({ type: "method.select", index }) dispatch({ type: "method.select", index })
if (method.forms?.length && !answers) {
dispatch({ type: "auth.form" })
return
}
if (method.type === "key") {
dispatch({ type: "auth.answers", answers: answers ?? {} })
return
}
if (method.type === "oauth") { if (method.type === "oauth") {
if (method.forms?.some((field) => field.type !== "string")) { if (method.prompts?.length && !inputs) {
dispatch({ type: "auth.error", error: "This authentication form contains unsupported fields" }) dispatch({ type: "auth.prompt" })
return return
} }
dispatch({ type: "auth.pending" }) dispatch({ type: "auth.pending" })
@@ -560,7 +550,7 @@ function ProviderConnection(props: {
.api.integration.oauth.connect({ .api.integration.oauth.connect({
integrationID: props.provider, integrationID: props.provider,
methodID: method.id, methodID: method.id,
answers: answers ?? {}, inputs: inputs ?? {},
location: location(), location: location(),
}) })
.then((x) => { .then((x) => {
@@ -574,42 +564,41 @@ function ProviderConnection(props: {
} }
} }
function AuthFormsView() { function AuthPromptsView() {
const [formStore, setFormStore] = createStore({ const [formStore, setFormStore] = createStore({
value: {} as Record<string, string>, value: {} as Record<string, string>,
index: 0, index: 0,
}) })
const forms = createMemo<StringForm[]>(() => { const prompts = createMemo(() => {
const value = method() const value = method()
return (value?.forms ?? []).flatMap((field) => (field.type === "string" ? [field] : [])) return value?.type === "oauth" ? (value.prompts ?? []) : []
}) })
const matches = (field: StringForm, value: Record<string, string>) => { const matches = (prompt: NonNullable<ReturnType<typeof prompts>[number]>, value: Record<string, string>) => {
return (field.when ?? []).every((condition) => { if (!prompt.when) return true
const actual = value[condition.key] const actual = value[prompt.when.key]
if (actual === undefined) return false if (actual === undefined) return false
return condition.op === "eq" ? actual === condition.value : actual !== condition.value return prompt.when.op === "eq" ? actual === prompt.when.value : actual !== prompt.when.value
})
} }
const current = createMemo(() => { const current = createMemo(() => {
const all = forms() const all = prompts()
const index = all.findIndex((field, index) => index >= formStore.index && matches(field, formStore.value)) const index = all.findIndex((prompt, index) => index >= formStore.index && matches(prompt, formStore.value))
if (index === -1) return if (index === -1) return
return { return {
index, index,
field: all[index], prompt: all[index],
} }
}) })
const valid = createMemo(() => { const valid = createMemo(() => {
const item = current() const item = current()
if (!item || item.field.options) return false if (!item || item.prompt.type !== "text") return false
if (!item.field.required) return true const value = formStore.value[item.prompt.key] ?? ""
return (formStore.value[item.field.key] ?? "").trim().length > 0 return value.trim().length > 0
}) })
async function next(index: number, value: Record<string, string>) { async function next(index: number, value: Record<string, string>) {
if (store.methodIndex === undefined) return if (store.methodIndex === undefined) return
const next = forms().findIndex((field, i) => i > index && matches(field, value)) const next = prompts().findIndex((prompt, i) => i > index && matches(prompt, value))
if (next !== -1) { if (next !== -1) {
setFormStore("index", next) setFormStore("index", next)
return return
@@ -620,60 +609,60 @@ function ProviderConnection(props: {
async function handleSubmit(e: SubmitEvent) { async function handleSubmit(e: SubmitEvent) {
e.preventDefault() e.preventDefault()
const item = current() const item = current()
if (!item || item.field.options) return if (!item || item.prompt.type !== "text") return
if (!valid()) return if (!valid()) return
await next(item.index, formStore.value) await next(item.index, formStore.value)
} }
const item = () => current() const item = () => current()
const text = createMemo(() => { const text = createMemo(() => {
const field = item()?.field const prompt = item()?.prompt
if (!field || field.options) return if (!prompt || prompt.type !== "text") return
return field return prompt
}) })
const select = createMemo(() => { const select = createMemo(() => {
const field = item()?.field const prompt = item()?.prompt
if (!field?.options) return if (!prompt || prompt.type !== "select") return
return field return prompt
}) })
return ( return (
<form onSubmit={handleSubmit} class="flex flex-col items-start gap-4"> <form onSubmit={handleSubmit} class="flex flex-col items-start gap-4">
<Switch> <Switch>
<Match when={item()?.field.options === undefined}> <Match when={item()?.prompt.type === "text"}>
<TextField <TextField
type="text" type="text"
label={text()?.title ?? ""} label={text()?.message ?? ""}
placeholder={text()?.placeholder} placeholder={text()?.placeholder}
value={text() ? (formStore.value[text()!.key] ?? "") : ""} value={text() ? (formStore.value[text()!.key] ?? "") : ""}
onChange={(value) => { onChange={(value) => {
const field = text() const prompt = text()
if (!field) return if (!prompt) return
setFormStore("value", field.key, value) setFormStore("value", prompt.key, value)
}} }}
/> />
<Button class="w-auto" type="submit" size="large" variant="primary" disabled={!valid()}> <Button class="w-auto" type="submit" size="large" variant="primary" disabled={!valid()}>
{language.t("common.continue")} {language.t("common.continue")}
</Button> </Button>
</Match> </Match>
<Match when={item()?.field.options !== undefined}> <Match when={item()?.prompt.type === "select"}>
<div class="w-full flex flex-col gap-1.5"> <div class="w-full flex flex-col gap-1.5">
<div class="text-14-regular text-text-base">{select()?.title}</div> <div class="text-14-regular text-text-base">{select()?.message}</div>
<div> <div>
<List <List
class="px-3" class="px-3"
items={select()?.options ?? []} items={select()?.options ?? []}
key={(x) => x.value} key={(x) => x.value}
current={select()?.options?.find((x) => x.value === formStore.value[select()!.key])} current={select()?.options.find((x) => x.value === formStore.value[select()!.key])}
onSelect={(value) => { onSelect={(value) => {
if (!value) return if (!value) return
const field = select() const prompt = select()
if (!field) return if (!prompt) return
const nextValue = { const nextValue = {
...formStore.value, ...formStore.value,
[field.key]: value.value, [prompt.key]: value.value,
} }
setFormStore("value", field.key, value.value) setFormStore("value", prompt.key, value.value)
void next(item()!.index, nextValue) void next(item()!.index, nextValue)
}} }}
> >
@@ -683,7 +672,7 @@ function ProviderConnection(props: {
<div class="w-2.5 h-0.5 ml-0 bg-icon-strong-base hidden" data-slot="list-item-extra-icon" /> <div class="w-2.5 h-0.5 ml-0 bg-icon-strong-base hidden" data-slot="list-item-extra-icon" />
</div> </div>
<span>{option.label}</span> <span>{option.label}</span>
<span class="text-14-regular text-text-weak">{option.description}</span> <span class="text-14-regular text-text-weak">{option.hint}</span>
</div> </div>
)} )}
</List> </List>
@@ -831,7 +820,6 @@ function ProviderConnection(props: {
integrationID: props.provider, integrationID: props.provider,
location: location(), location: location(),
key: apiKey, key: apiKey,
answers: store.formAnswers ?? {},
}) })
await complete() await complete()
} }
@@ -1155,8 +1143,8 @@ function ProviderConnection(props: {
</div> </div>
</div> </div>
</Match> </Match>
<Match when={store.state === "form"}> <Match when={store.state === "prompt"}>
<AuthFormsView /> <AuthPromptsView />
</Match> </Match>
<Match when={store.state === "error"}> <Match when={store.state === "error"}>
<div class="text-14-regular text-text-base"> <div class="text-14-regular text-text-base">
@@ -6,21 +6,17 @@ import { Icon } from "@opencode-ai/ui/icon"
import { IconButton } from "@opencode-ai/ui/icon-button" import { IconButton } from "@opencode-ai/ui/icon-button"
import { List } from "@opencode-ai/ui/list" import { List } from "@opencode-ai/ui/list"
import { TextField } from "@opencode-ai/ui/text-field" import { TextField } from "@opencode-ai/ui/text-field"
import { useMutation } from "@tanstack/solid-query" import { Show } from "solid-js"
import { showToast } from "@/utils/toast"
import { useNavigate } from "@solidjs/router"
import { createEffect, createMemo, createResource, Show } from "solid-js"
import { createStore } from "solid-js/store"
import { ServerHealthIndicator, ServerRow } from "@/components/server/server-row" import { ServerHealthIndicator, ServerRow } from "@/components/server/server-row"
import { useGlobal } from "@/context/global"
import { useLanguage } from "@/context/language" import { useLanguage } from "@/context/language"
import { usePlatform } from "@/context/platform" import { ServerConnection } from "@/context/server"
import { normalizeServerUrl, ServerConnection, useServer } from "@/context/server"
import { type ServerHealth, useCheckServerHealth } from "@/utils/server-health"
import { useSettings } from "@/context/settings" import { useSettings } from "@/context/settings"
import { useTabs } from "@/context/tabs" import {
type ServerDomainController,
const DEFAULT_USERNAME = "opencode" type ServerFormController,
useServerDomainController,
useServerFormController,
} from "@/components/server/server-management-controller"
interface ServerFormProps { interface ServerFormProps {
value: string value: string
@@ -39,76 +35,6 @@ interface ServerFormProps {
onBack: () => void onBack: () => void
} }
function showRequestError(language: ReturnType<typeof useLanguage>, err: unknown) {
showToast({
variant: "error",
title: language.t("common.requestFailed"),
description: err instanceof Error ? err.message : String(err),
})
}
function useDefaultServer() {
const language = useLanguage()
const platform = usePlatform()
const [defaultKey, defaultUrlActions] = createResource(
async () => {
try {
const key = await platform.getDefaultServer?.()
if (!key) return null
return key
} catch (err) {
showRequestError(language, err)
return null
}
},
{ initialValue: null },
)
const canDefault = createMemo(() => !!platform.getDefaultServer && !!platform.setDefaultServer)
const setDefault = async (key: ServerConnection.Key | null) => {
try {
await platform.setDefaultServer?.(key)
defaultUrlActions.mutate(key)
} catch (err) {
showRequestError(language, err)
}
}
return { defaultKey: () => defaultKey.latest, canDefault, setDefault }
}
function useServerPreview() {
const checkServerHealth = useCheckServerHealth()
const looksComplete = (value: string) => {
const normalized = normalizeServerUrl(value)
if (!normalized) return false
const host = normalized.replace(/^https?:\/\//, "").split("/")[0]
if (!host) return false
if (host.includes("localhost") || host.startsWith("127.0.0.1")) return true
return host.includes(".") || host.includes(":")
}
const previewStatus = async (
value: string,
username: string,
password: string,
setStatus: (value: boolean | undefined) => void,
) => {
setStatus(undefined)
if (!looksComplete(value)) return
const normalized = normalizeServerUrl(value)
if (!normalized) return
const http: ServerConnection.HttpBase = { url: normalized }
if (username) http.username = username
if (password) http.password = password
const result = await checkServerHealth(http)
setStatus(result.healthy)
}
return { previewStatus }
}
function ServerForm(props: ServerFormProps) { function ServerForm(props: ServerFormProps) {
const language = useLanguage() const language = useLanguage()
const keyDown = (event: KeyboardEvent) => { const keyDown = (event: KeyboardEvent) => {
@@ -176,385 +102,40 @@ function ServerForm(props: ServerFormProps) {
export function DialogSelectServer() { export function DialogSelectServer() {
const dialog = useDialog() const dialog = useDialog()
const controller = useServerManagementController({ onSelect: dialog.close }) const language = useLanguage()
const domain = useServerDomainController({ onSelect: () => dialog.close() })
const form = useServerFormController({ onSelect: () => dialog.close() })
const title = () => {
if (!form.state.open()) return language.t("dialog.server.title")
return (
<div class="flex items-center gap-2 -ml-2">
<IconButton icon="arrow-left" variant="ghost" onClick={form.reset} aria-label={language.t("common.goBack")} />
<span>
{form.state.adding() ? language.t("dialog.server.add.title") : language.t("dialog.server.edit.title")}
</span>
</div>
)
}
return ( return (
<Dialog title={controller.formTitle()}> <Dialog title={title()}>
<div class="flex flex-1 min-h-0 flex-col px-5"> <div class="flex flex-1 min-h-0 flex-col px-5">
<Show when={controller.isFormMode()} fallback={<ServerConnectionList controller={controller} />}> <Show
<ServerConnectionForm controller={controller} /> when={form.state.open()}
fallback={<ServerConnectionList domain={domain} onAdd={form.start.add} onEdit={form.start.edit} />}
>
<ServerConnectionForm form={form} />
</Show> </Show>
</div> </div>
</Dialog> </Dialog>
) )
} }
export function useServerManagementController(options: { onSelect?: () => void; navigateOnAdd?: boolean } = {}) { export function ServerConnectionList(props: {
const navigate = useNavigate() domain: ServerDomainController
const server = useServer() onAdd: () => void
const tabs = useTabs() onEdit: (server: ServerConnection.Http) => void
const global = useGlobal() }) {
const platform = usePlatform()
const language = useLanguage()
const { defaultKey, canDefault, setDefault } = useDefaultServer()
const { previewStatus } = useServerPreview()
const checkServerHealth = useCheckServerHealth()
const [store, setStore] = createStore({
addServer: {
url: "",
name: "",
username: DEFAULT_USERNAME,
password: "",
error: "",
showForm: false,
status: undefined as boolean | undefined,
},
editServer: {
id: undefined as string | undefined,
value: "",
name: "",
username: "",
password: "",
error: "",
status: undefined as boolean | undefined,
},
})
const resetAdd = () => {
setStore("addServer", {
url: "",
name: "",
username: DEFAULT_USERNAME,
password: "",
error: "",
showForm: false,
status: undefined,
})
}
const resetEdit = () => {
setStore("editServer", {
id: undefined,
value: "",
name: "",
username: "",
password: "",
error: "",
status: undefined,
})
}
const addMutation = useMutation(() => ({
mutationFn: async (value: string) => {
const normalized = normalizeServerUrl(value)
if (!normalized) {
resetAdd()
return
}
const conn: ServerConnection.Http = {
type: "http",
http: { url: normalized },
}
if (store.addServer.name.trim()) conn.displayName = store.addServer.name.trim()
if (store.addServer.password) conn.http.password = store.addServer.password
if (store.addServer.password && store.addServer.username) conn.http.username = store.addServer.username
const result = await checkServerHealth(conn.http)
if (!result.healthy) {
setStore("addServer", { error: language.t("dialog.server.add.error") })
return
}
resetAdd()
if (options.navigateOnAdd === false) {
server.add(conn)
options.onSelect?.()
return
}
await select(conn, true)
},
}))
const editMutation = useMutation(() => ({
mutationFn: async (input: { original: ServerConnection.Any; value: string }) => {
if (input.original.type !== "http") return
const normalized = normalizeServerUrl(input.value)
if (!normalized) {
resetEdit()
return
}
const name = store.editServer.name.trim() || undefined
const username = store.editServer.username || undefined
const password = store.editServer.password || undefined
const existingName = input.original.displayName
if (
normalized === input.original.http.url &&
name === existingName &&
username === input.original.http.username &&
password === input.original.http.password
) {
resetEdit()
return
}
const conn: ServerConnection.Http = {
type: "http",
displayName: name,
http: { url: normalized, username, password },
}
const result = await checkServerHealth(conn.http)
if (!result.healthy) {
setStore("editServer", { error: language.t("dialog.server.add.error") })
return
}
if (normalized === input.original.http.url) {
server.add(conn)
} else {
replaceServer(input.original, conn)
}
resetEdit()
},
}))
const replaceServer = (original: ServerConnection.Http, next: ServerConnection.Http) => {
const originalKey = ServerConnection.key(original)
const active = server.key
tabs.removeServer(originalKey)
const newConn = server.add(next)
if (!newConn) return
const nextActive = active === originalKey ? ServerConnection.key(newConn) : active
if (nextActive) server.setActive(nextActive)
server.remove(originalKey)
}
const items = createMemo(() => {
const current = server.current
const list = server.list
if (!current) return list
if (!list.includes(current)) return [current, ...list]
return [current, ...list.filter((x) => x !== current)]
})
const settings = useSettings()
const current = createMemo<ServerConnection.Any | undefined>(() =>
settings.general.newLayoutDesigns()
? undefined
: (items().find((x) => ServerConnection.key(x) === server.key) ?? items()[0]),
)
const sortedItems = createMemo(() => {
const raw = items()
const list = raw
if (!list.length) return list
const active = current()
const order = new Map(list.map((url, index) => [url, index] as const))
const rank = (value?: ServerHealth) => {
if (value?.healthy === true) return 0
if (value?.healthy === false) return 2
return 1
}
return list.slice().sort((a, b) => {
if (a === active) return -1
if (b === active) return 1
const diff =
rank(global.servers.health[ServerConnection.key(a)]) - rank(global.servers.health[ServerConnection.key(b)])
if (diff !== 0) return diff
return (order.get(a) ?? 0) - (order.get(b) ?? 0)
})
})
async function select(conn: ServerConnection.Any, persist?: boolean) {
if (!persist && global.servers.health[ServerConnection.key(conn)]?.healthy === false) return
options.onSelect?.()
if (persist && conn.type === "http") {
server.add(conn)
navigate("/")
return
}
navigate("/")
queueMicrotask(() => server.setActive(ServerConnection.key(conn)))
}
const handleAddChange = (value: string) => {
if (addMutation.isPending) return
setStore("addServer", { url: value, error: "" })
void previewStatus(value, store.addServer.username, store.addServer.password, (next) =>
setStore("addServer", { status: next }),
)
}
const handleAddNameChange = (value: string) => {
if (addMutation.isPending) return
setStore("addServer", { name: value, error: "" })
}
const handleAddUsernameChange = (value: string) => {
if (addMutation.isPending) return
setStore("addServer", { username: value, error: "" })
void previewStatus(store.addServer.url, value, store.addServer.password, (next) =>
setStore("addServer", { status: next }),
)
}
const handleAddPasswordChange = (value: string) => {
if (addMutation.isPending) return
setStore("addServer", { password: value, error: "" })
void previewStatus(store.addServer.url, store.addServer.username, value, (next) =>
setStore("addServer", { status: next }),
)
}
const handleEditChange = (value: string) => {
if (editMutation.isPending) return
setStore("editServer", { value, error: "" })
void previewStatus(value, store.editServer.username, store.editServer.password, (next) =>
setStore("editServer", { status: next }),
)
}
const handleEditNameChange = (value: string) => {
if (editMutation.isPending) return
setStore("editServer", { name: value, error: "" })
}
const handleEditUsernameChange = (value: string) => {
if (editMutation.isPending) return
setStore("editServer", { username: value, error: "" })
void previewStatus(store.editServer.value, value, store.editServer.password, (next) =>
setStore("editServer", { status: next }),
)
}
const handleEditPasswordChange = (value: string) => {
if (editMutation.isPending) return
setStore("editServer", { password: value, error: "" })
void previewStatus(store.editServer.value, store.editServer.username, value, (next) =>
setStore("editServer", { status: next }),
)
}
const mode = createMemo<"list" | "add" | "edit">(() => {
if (store.editServer.id) return "edit"
if (store.addServer.showForm) return "add"
return "list"
})
const editing = createMemo(() => {
if (!store.editServer.id) return
return items().find((x) => x.type === "http" && x.http.url === store.editServer.id)
})
const resetForm = () => {
resetAdd()
resetEdit()
}
const startAdd = () => {
resetEdit()
setStore("addServer", {
showForm: true,
url: "",
name: "",
username: DEFAULT_USERNAME,
password: "",
error: "",
status: undefined,
})
}
const startEdit = (conn: ServerConnection.Http) => {
resetAdd()
setStore("editServer", {
id: conn.http.url,
value: conn.http.url,
name: conn.displayName ?? "",
username: conn.http.username ?? "",
password: conn.http.password ?? "",
error: "",
status: global.servers.health[ServerConnection.key(conn)]?.healthy,
})
}
const submitForm = () => {
if (mode() === "add") {
if (addMutation.isPending) return
setStore("addServer", { error: "" })
addMutation.mutate(store.addServer.url)
return
}
const original = editing()
if (!original) return
if (editMutation.isPending) return
setStore("editServer", { error: "" })
editMutation.mutate({ original, value: store.editServer.value })
}
const isFormMode = createMemo(() => mode() !== "list")
const isAddMode = createMemo(() => mode() === "add")
const formBusy = createMemo(() => (isAddMode() ? addMutation.isPending : editMutation.isPending))
const formTitle = createMemo(() => {
if (!isFormMode()) return language.t("dialog.server.title")
return (
<div class="flex items-center gap-2 -ml-2">
<IconButton icon="arrow-left" variant="ghost" onClick={resetForm} aria-label={language.t("common.goBack")} />
<span>{isAddMode() ? language.t("dialog.server.add.title") : language.t("dialog.server.edit.title")}</span>
</div>
)
})
createEffect(() => {
if (!store.editServer.id) return
if (editing()) return
resetEdit()
})
async function handleRemove(key: ServerConnection.Key) {
try {
if (key.startsWith("wsl:")) await platform.wslServers?.removeServer(key)
tabs.removeServer(key)
server.remove(key)
if ((await platform.getDefaultServer?.()) === key) {
await setDefault(null)
}
} catch (err) {
showRequestError(language, err)
}
}
return {
defaultKey,
canDefault,
current,
sortedItems,
status: () => global.servers.health,
isFormMode,
isAddMode,
formTitle,
formBusy,
formValue: () => (isAddMode() ? store.addServer.url : store.editServer.value),
formName: () => (isAddMode() ? store.addServer.name : store.editServer.name),
formUsername: () => (isAddMode() ? store.addServer.username : store.editServer.username),
formPassword: () => (isAddMode() ? store.addServer.password : store.editServer.password),
formError: () => (isAddMode() ? store.addServer.error : store.editServer.error),
formStatus: () => (isAddMode() ? store.addServer.status : store.editServer.status),
select,
setDefault,
startAdd,
startEdit,
resetForm,
submitForm,
canRemove: server.canRemove,
handleRemove,
handleFormChange: () => (isAddMode() ? handleAddChange : handleEditChange),
handleFormNameChange: () => (isAddMode() ? handleAddNameChange : handleEditNameChange),
handleFormUsernameChange: () => (isAddMode() ? handleAddUsernameChange : handleEditUsernameChange),
handleFormPasswordChange: () => (isAddMode() ? handleAddPasswordChange : handleEditPasswordChange),
}
}
export function ServerConnectionList(props: { controller: ReturnType<typeof useServerManagementController> }) {
const language = useLanguage() const language = useLanguage()
const settings = useSettings() const settings = useSettings()
@@ -568,10 +149,10 @@ export function ServerConnectionList(props: { controller: ReturnType<typeof useS
}} }}
noInitialSelection noInitialSelection
emptyMessage={language.t("dialog.server.empty")} emptyMessage={language.t("dialog.server.empty")}
items={props.controller.sortedItems} items={props.domain.collection.items}
key={(x) => x.http.url} key={(x) => x.http.url}
onSelect={(x) => { onSelect={(x) => {
if (x && !settings.general.newLayoutDesigns()) void props.controller.select(x) if (x && !settings.general.newLayoutDesigns()) void props.domain.selection.select(x)
}} }}
divider={true} divider={true}
> >
@@ -580,15 +161,15 @@ export function ServerConnectionList(props: { controller: ReturnType<typeof useS
return ( return (
<div class="flex items-center gap-3 min-w-0 flex-1 w-full group/item"> <div class="flex items-center gap-3 min-w-0 flex-1 w-full group/item">
<div class="flex flex-col h-full items-center w-5"> <div class="flex flex-col h-full items-center w-5">
<ServerHealthIndicator health={props.controller.status()[key]} /> <ServerHealthIndicator health={props.domain.collection.health()[key]} />
</div> </div>
<ServerRow <ServerRow
conn={i} conn={i}
dimmed={props.controller.status()[key]?.healthy === false} dimmed={props.domain.collection.health()[key]?.healthy === false}
status={props.controller.status()[key]} status={props.domain.collection.health()[key]}
class="flex items-center gap-3 min-w-0 flex-1" class="flex items-center gap-3 min-w-0 flex-1"
badge={ badge={
<Show when={props.controller.defaultKey() === ServerConnection.key(i)}> <Show when={props.domain.defaults.key() === ServerConnection.key(i)}>
<span class="text-text-base bg-surface-base text-14-regular px-1.5 rounded-xs"> <span class="text-text-base bg-surface-base text-14-regular px-1.5 rounded-xs">
{language.t("dialog.server.status.default")} {language.t("dialog.server.status.default")}
</span> </span>
@@ -597,7 +178,12 @@ export function ServerConnectionList(props: { controller: ReturnType<typeof useS
showCredentials showCredentials
/> />
<div class="flex items-center justify-center gap-4 pl-4"> <div class="flex items-center justify-center gap-4 pl-4">
<Show when={props.controller.current() && ServerConnection.key(props.controller.current()!) === key}> <Show
when={
props.domain.collection.current() &&
ServerConnection.key(props.domain.collection.current()!) === key
}
>
<Icon name="check" class="h-6" /> <Icon name="check" class="h-6" />
</Show> </Show>
@@ -616,27 +202,27 @@ export function ServerConnectionList(props: { controller: ReturnType<typeof useS
<DropdownMenu.Item <DropdownMenu.Item
onSelect={() => { onSelect={() => {
if (i.type !== "http") return if (i.type !== "http") return
props.controller.startEdit(i) props.onEdit(i)
}} }}
> >
<DropdownMenu.ItemLabel>{language.t("dialog.server.menu.edit")}</DropdownMenu.ItemLabel> <DropdownMenu.ItemLabel>{language.t("dialog.server.menu.edit")}</DropdownMenu.ItemLabel>
</DropdownMenu.Item> </DropdownMenu.Item>
<Show when={props.controller.canDefault() && props.controller.defaultKey() !== key}> <Show when={props.domain.defaults.available() && props.domain.defaults.key() !== key}>
<DropdownMenu.Item onSelect={() => props.controller.setDefault(key)}> <DropdownMenu.Item onSelect={() => props.domain.defaults.set(key)}>
<DropdownMenu.ItemLabel>{language.t("dialog.server.menu.default")}</DropdownMenu.ItemLabel> <DropdownMenu.ItemLabel>{language.t("dialog.server.menu.default")}</DropdownMenu.ItemLabel>
</DropdownMenu.Item> </DropdownMenu.Item>
</Show> </Show>
<Show when={props.controller.canDefault() && props.controller.defaultKey() === key}> <Show when={props.domain.defaults.available() && props.domain.defaults.key() === key}>
<DropdownMenu.Item onSelect={() => props.controller.setDefault(null)}> <DropdownMenu.Item onSelect={() => props.domain.defaults.set(null)}>
<DropdownMenu.ItemLabel> <DropdownMenu.ItemLabel>
{language.t("dialog.server.menu.defaultRemove")} {language.t("dialog.server.menu.defaultRemove")}
</DropdownMenu.ItemLabel> </DropdownMenu.ItemLabel>
</DropdownMenu.Item> </DropdownMenu.Item>
</Show> </Show>
<Show when={props.controller.canRemove(key)}> <Show when={props.domain.connection.canRemove(key)}>
<DropdownMenu.Separator /> <DropdownMenu.Separator />
<DropdownMenu.Item <DropdownMenu.Item
onSelect={() => props.controller.handleRemove(ServerConnection.key(i))} onSelect={() => props.domain.connection.remove(key)}
class="text-text-on-critical-base hover:bg-surface-critical-weak" class="text-text-on-critical-base hover:bg-surface-critical-weak"
> >
<DropdownMenu.ItemLabel>{language.t("dialog.server.menu.delete")}</DropdownMenu.ItemLabel> <DropdownMenu.ItemLabel>{language.t("dialog.server.menu.delete")}</DropdownMenu.ItemLabel>
@@ -657,7 +243,7 @@ export function ServerConnectionList(props: { controller: ReturnType<typeof useS
variant="secondary" variant="secondary"
icon="plus-small" icon="plus-small"
size="large" size="large"
onClick={props.controller.startAdd} onClick={props.onAdd}
class="py-1.5 pl-1.5 pr-3 flex items-center gap-1.5" class="py-1.5 pl-1.5 pr-3 flex items-center gap-1.5"
> >
{language.t("dialog.server.add.button")} {language.t("dialog.server.add.button")}
@@ -667,38 +253,38 @@ export function ServerConnectionList(props: { controller: ReturnType<typeof useS
) )
} }
export function ServerConnectionForm(props: { controller: ReturnType<typeof useServerManagementController> }) { export function ServerConnectionForm(props: { form: ServerFormController }) {
const language = useLanguage() const language = useLanguage()
return ( return (
<div class="flex flex-1 min-h-0 flex-col gap-4"> <div class="flex flex-1 min-h-0 flex-col gap-4">
<ServerForm <ServerForm
value={props.controller.formValue()} value={props.form.state.value()}
name={props.controller.formName()} name={props.form.state.name()}
username={props.controller.formUsername()} username={props.form.state.username()}
password={props.controller.formPassword()} password={props.form.state.password()}
placeholder={language.t("dialog.server.add.placeholder")} placeholder={language.t("dialog.server.add.placeholder")}
busy={props.controller.formBusy()} busy={props.form.state.busy()}
error={props.controller.formError()} error={props.form.state.error()}
status={props.controller.formStatus()} status={props.form.state.status()}
onChange={props.controller.handleFormChange()} onChange={props.form.change.value}
onNameChange={props.controller.handleFormNameChange()} onNameChange={props.form.change.name}
onUsernameChange={props.controller.handleFormUsernameChange()} onUsernameChange={props.form.change.username}
onPasswordChange={props.controller.handleFormPasswordChange()} onPasswordChange={props.form.change.password}
onSubmit={props.controller.submitForm} onSubmit={props.form.submit}
onBack={props.controller.resetForm} onBack={props.form.reset}
/> />
<div class="shrink-0 pb-5"> <div class="shrink-0 pb-5">
<Button <Button
variant="primary" variant="primary"
size="large" size="large"
onClick={props.controller.submitForm} onClick={props.form.submit}
disabled={props.controller.formBusy()} disabled={props.form.state.busy()}
class="px-3 py-1.5" class="px-3 py-1.5"
> >
{props.controller.formBusy() {props.form.state.busy()
? language.t("dialog.server.add.checking") ? language.t("dialog.server.add.checking")
: props.controller.isAddMode() : props.form.state.adding()
? language.t("dialog.server.add.button") ? language.t("dialog.server.add.button")
: language.t("common.save")} : language.t("common.save")}
</Button> </Button>
@@ -0,0 +1,323 @@
import { useNavigate } from "@solidjs/router"
import { useMutation } from "@tanstack/solid-query"
import { createEffect, createMemo, createResource, onCleanup } from "solid-js"
import { createStore } from "solid-js/store"
import { useGlobal } from "@/context/global"
import { useLanguage } from "@/context/language"
import { usePlatform } from "@/context/platform"
import { normalizeServerUrl, ServerConnection, useServer } from "@/context/server"
import { useSettings } from "@/context/settings"
import { useTabs } from "@/context/tabs"
import { type ServerHealth, useCheckServerHealth } from "@/utils/server-health"
import { showToast } from "@/utils/toast"
import { createServerHealthPreview, replaceServerConnection, type ServerFormValues } from "./server-management"
const DEFAULT_USERNAME = "opencode"
type FormMode = "list" | "add" | "edit"
function showRequestError(language: ReturnType<typeof useLanguage>, err: unknown) {
showToast({
variant: "error",
title: language.t("common.requestFailed"),
description: err instanceof Error ? err.message : String(err),
})
}
function useDefaultServer() {
const language = useLanguage()
const platform = usePlatform()
const [defaultKey, defaultKeyActions] = createResource(
async () => {
try {
return (await platform.getDefaultServer?.()) ?? null
} catch (err) {
showRequestError(language, err)
return null
}
},
{ initialValue: null },
)
const set = async (key: ServerConnection.Key | null) => {
try {
await platform.setDefaultServer?.(key)
defaultKeyActions.mutate(key)
} catch (err) {
showRequestError(language, err)
}
}
return {
key: () => defaultKey.latest,
available: createMemo(() => !!platform.getDefaultServer && !!platform.setDefaultServer),
set,
}
}
function useServerMutations() {
const server = useServer()
const tabs = useTabs()
return {
add: (connection: ServerConnection.Http) => server.add(connection),
replace: (originalKey: ServerConnection.Key, next: ServerConnection.Http) =>
replaceServerConnection(originalKey, next, {
active: () => server.key,
removeTabs: (key) => tabs.removeServer(key),
add: (connection) => server.add(connection),
setActive: (key) => server.setActive(key),
remove: (key) => server.remove(key),
}),
}
}
export function useServerActionsController() {
const server = useServer()
const tabs = useTabs()
const platform = usePlatform()
const language = useLanguage()
const defaults = useDefaultServer()
const remove = async (key: ServerConnection.Key) => {
try {
if (key.startsWith("wsl:")) await platform.wslServers?.removeServer(key)
tabs.removeServer(key)
server.remove(key)
if ((await platform.getDefaultServer?.()) === key) await defaults.set(null)
} catch (err) {
showRequestError(language, err)
}
}
return { defaults, connection: { canRemove: server.canRemove, remove } }
}
export type ServerActionsController = ReturnType<typeof useServerActionsController>
export function useServerCollectionController() {
const server = useServer()
const global = useGlobal()
const settings = useSettings()
const actions = useServerActionsController()
const items = createMemo(() => {
const current = server.current
const list = server.list
if (!current) return list
if (!list.includes(current)) return [current, ...list]
return [current, ...list.filter((item) => item !== current)]
})
const current = createMemo<ServerConnection.Any | undefined>(() =>
settings.general.newLayoutDesigns()
? undefined
: (items().find((item) => ServerConnection.key(item) === server.key) ?? items()[0]),
)
const sorted = createMemo(() => {
const raw = items()
const list = raw
if (!list.length) return list
const active = current()
const order = new Map(list.map((item, index) => [item, index] as const))
const rank = (value?: ServerHealth) => {
if (value?.healthy === true) return 0
if (value?.healthy === false) return 2
return 1
}
return list.slice().sort((a, b) => {
if (a === active) return -1
if (b === active) return 1
const diff =
rank(global.servers.health[ServerConnection.key(a)]) - rank(global.servers.health[ServerConnection.key(b)])
if (diff !== 0) return diff
return (order.get(a) ?? 0) - (order.get(b) ?? 0)
})
})
return {
collection: {
items: sorted,
current,
health: () => global.servers.health,
},
...actions,
}
}
export type ServerCollectionController = ReturnType<typeof useServerCollectionController>
export function useServerDomainController(options: { onSelect?: () => void } = {}) {
const navigate = useNavigate()
const server = useServer()
const global = useGlobal()
const collection = useServerCollectionController()
const select = async (connection: ServerConnection.Any) => {
if (global.servers.health[ServerConnection.key(connection)]?.healthy === false) return
options.onSelect?.()
navigate("/")
queueMicrotask(() => server.setActive(ServerConnection.key(connection)))
}
return { ...collection, selection: { select } }
}
export type ServerDomainController = ReturnType<typeof useServerDomainController>
export function useServerFormController(options: { onSelect?: () => void; navigateOnAdd?: boolean } = {}) {
const navigate = useNavigate()
const server = useServer()
const global = useGlobal()
const language = useLanguage()
const mutations = useServerMutations()
const checkServerHealth = useCheckServerHealth()
const healthPreview = createServerHealthPreview(checkServerHealth)
const [store, setStore] = createStore({
mode: "list" as FormMode,
originalUrl: undefined as string | undefined,
values: { url: "", name: "", username: DEFAULT_USERNAME, password: "" },
error: "",
status: undefined as boolean | undefined,
})
onCleanup(healthPreview.cancel)
const reset = () => {
healthPreview.cancel()
setStore({
mode: "list",
originalUrl: undefined,
values: { url: "", name: "", username: DEFAULT_USERNAME, password: "" },
error: "",
status: undefined,
})
}
const allServers = () => {
if (!server.current || server.list.includes(server.current)) return server.list
return [server.current, ...server.list]
}
const editing = createMemo(() =>
allServers().find((item) => item.type === "http" && item.http.url === store.originalUrl),
)
const request = useMutation(() => ({
mutationFn: async () => {
const normalized = normalizeServerUrl(store.values.url)
if (!normalized) {
reset()
return
}
const original = store.mode === "edit" ? editing() : undefined
if (store.mode === "edit" && !original) return
const name = store.values.name.trim() || undefined
const username = store.values.username || undefined
const password = store.values.password || undefined
if (
original?.type === "http" &&
normalized === original.http.url &&
name === original.displayName &&
username === original.http.username &&
password === original.http.password
) {
reset()
return
}
const connection: ServerConnection.Http = {
type: "http",
displayName: name,
http: {
url: normalized,
username: store.mode === "add" && !password ? undefined : username,
password,
},
}
const result = await checkServerHealth(connection.http)
if (!result.healthy) {
setStore("error", language.t("dialog.server.add.error"))
return
}
if (original?.type === "http") {
if (normalized === original.http.url) mutations.add(connection)
if (normalized !== original.http.url) mutations.replace(ServerConnection.key(original), connection)
reset()
return
}
reset()
if (options.navigateOnAdd === false) {
mutations.add(connection)
options.onSelect?.()
return
}
mutations.add(connection)
options.onSelect?.()
navigate("/")
},
}))
const preview = () => void healthPreview.preview(store.values, (status) => setStore("status", status))
const change = (field: keyof ServerFormValues, value: string) => {
if (request.isPending) return
setStore("values", field, value)
setStore("error", "")
if (field !== "name") preview()
}
const startAdd = () => {
reset()
setStore("mode", "add")
}
const startEdit = (connection: ServerConnection.Http) => {
reset()
setStore({
mode: "edit",
originalUrl: connection.http.url,
values: {
url: connection.http.url,
name: connection.displayName ?? "",
username: connection.http.username ?? "",
password: connection.http.password ?? "",
},
error: "",
status: global.servers.health[ServerConnection.key(connection)]?.healthy,
})
}
const submit = () => {
if (store.mode === "list" || request.isPending) return
setStore("error", "")
request.mutate()
}
createEffect(() => {
if (store.mode !== "edit") return
if (editing()) return
reset()
})
return {
state: {
mode: () => store.mode,
open: () => store.mode !== "list",
adding: () => store.mode === "add",
busy: () => request.isPending,
value: () => store.values.url,
name: () => store.values.name,
username: () => store.values.username,
password: () => store.values.password,
error: () => store.error,
status: () => store.status,
},
change: {
value: (value: string) => change("url", value),
name: (value: string) => change("name", value),
username: (value: string) => change("username", value),
password: (value: string) => change("password", value),
},
start: { add: startAdd, edit: startEdit },
reset,
submit,
}
}
export type ServerFormController = ReturnType<typeof useServerFormController>
@@ -0,0 +1,99 @@
import { describe, expect, test } from "bun:test"
import { ServerConnection } from "@/context/server"
import { createServerHealthPreview, replaceServerConnection, type ServerFormValues } from "./server-management"
function deferred<T>() {
let resolve!: (value: T) => void
const promise = new Promise<T>((done) => {
resolve = done
})
return { promise, resolve }
}
const values = (url: string): ServerFormValues => ({ url, name: "", username: "opencode", password: "" })
describe("createServerHealthPreview", () => {
test("ignores an older response that resolves after the latest response", async () => {
const first = deferred<{ healthy: boolean }>()
const second = deferred<{ healthy: boolean }>()
const requests = [first, second]
const status: Array<boolean | undefined> = []
const preview = createServerHealthPreview(() => requests.shift()!.promise)
const older = preview.preview(values("old.example.com"), (value) => status.push(value))
const latest = preview.preview(values("new.example.com"), (value) => status.push(value))
second.resolve({ healthy: true })
await latest
first.resolve({ healthy: false })
await older
expect(status).toEqual([undefined, undefined, true])
})
test("an incomplete value invalidates an in-flight response", async () => {
const request = deferred<{ healthy: boolean }>()
const status: Array<boolean | undefined> = []
const preview = createServerHealthPreview(() => request.promise)
const pending = preview.preview(values("server.example.com"), (value) => status.push(value))
await preview.preview(values("server"), (value) => status.push(value))
request.resolve({ healthy: true })
await pending
expect(status).toEqual([undefined, undefined])
})
test("cancellation prevents an in-flight response from updating status", async () => {
const request = deferred<{ healthy: boolean }>()
const status: Array<boolean | undefined> = []
const preview = createServerHealthPreview(() => request.promise)
const pending = preview.preview(values("server.example.com"), (value) => status.push(value))
preview.cancel()
request.resolve({ healthy: true })
await pending
expect(status).toEqual([undefined])
})
})
describe("replaceServerConnection", () => {
const original: ServerConnection.Http = { type: "http", http: { url: "https://old.example.com" } }
const next: ServerConnection.Http = { type: "http", http: { url: "https://new.example.com" } }
test("moves active selection after adding the replacement and removes the original", () => {
const calls: string[] = []
replaceServerConnection(ServerConnection.key(original), next, {
active: () => ServerConnection.key(original),
removeTabs: (key) => calls.push(`tabs:${key}`),
add: (server) => {
calls.push(`add:${ServerConnection.key(server)}`)
return server
},
setActive: (key) => calls.push(`active:${key}`),
remove: (key) => calls.push(`remove:${key}`),
})
expect(calls).toEqual([
"tabs:https://old.example.com",
"add:https://new.example.com",
"active:https://new.example.com",
"remove:https://old.example.com",
])
})
test("keeps the original when the replacement cannot be added", () => {
const removed: ServerConnection.Key[] = []
replaceServerConnection(ServerConnection.key(original), next, {
active: () => ServerConnection.key(original),
removeTabs: () => {},
add: () => undefined,
setActive: () => {},
remove: (key) => removed.push(key),
})
expect(removed).toEqual([])
})
})
@@ -0,0 +1,59 @@
import { normalizeServerUrl, ServerConnection } from "@/context/server"
import type { ServerHealth } from "@/utils/server-health"
export type ServerFormValues = {
url: string
name: string
username: string
password: string
}
export function createServerHealthPreview(
check: (server: ServerConnection.HttpBase) => Promise<Pick<ServerHealth, "healthy">>,
) {
let generation = 0
const cancel = () => {
generation += 1
}
const preview = async (values: ServerFormValues, setStatus: (value: boolean | undefined) => void) => {
const current = ++generation
setStatus(undefined)
const normalized = normalizeServerUrl(values.url)
if (!normalized) return
const host = normalized.replace(/^https?:\/\//, "").split("/")[0]
if (!host) return
if (!host.includes("localhost") && !host.startsWith("127.0.0.1") && !host.includes(".") && !host.includes(":"))
return
const http: ServerConnection.HttpBase = { url: normalized }
if (values.username) http.username = values.username
if (values.password) http.password = values.password
const result = await check(http)
if (current !== generation) return
setStatus(result.healthy)
}
return { cancel, preview }
}
export function replaceServerConnection(
originalKey: ServerConnection.Key,
next: ServerConnection.Http,
operations: {
active: () => ServerConnection.Key | undefined
removeTabs: (key: ServerConnection.Key) => void
add: (server: ServerConnection.Http) => ServerConnection.Any | undefined
setActive: (key: ServerConnection.Key) => void
remove: (key: ServerConnection.Key) => void
},
) {
const active = operations.active()
operations.removeTabs(originalKey)
const added = operations.add(next)
if (!added) return
const nextActive = active === originalKey ? ServerConnection.key(added) : active
if (nextActive) operations.setActive(nextActive)
operations.remove(originalKey)
}
@@ -2,13 +2,13 @@ import { Icon as IconV2 } from "@opencode-ai/ui/v2/icon"
import { IconButtonV2 } from "@opencode-ai/ui/v2/icon-button-v2" import { IconButtonV2 } from "@opencode-ai/ui/v2/icon-button-v2"
import { MenuV2 } from "@opencode-ai/ui/v2/menu-v2" import { MenuV2 } from "@opencode-ai/ui/v2/menu-v2"
import { type Component, Show } from "solid-js" import { type Component, Show } from "solid-js"
import { useServerManagementController } from "@/components/dialog-select-server" import type { ServerActionsController } from "@/components/server/server-management-controller"
import { useLanguage } from "@/context/language" import { useLanguage } from "@/context/language"
import { ServerConnection } from "@/context/server" import { ServerConnection } from "@/context/server"
export const ServerRowMenu: Component<{ export const ServerRowMenu: Component<{
server: ServerConnection.Any server: ServerConnection.Any
controller: ReturnType<typeof useServerManagementController> domain: ServerActionsController
onEdit: (server: ServerConnection.Http) => void onEdit: (server: ServerConnection.Http) => void
open?: boolean open?: boolean
onOpenChange?: (open: boolean) => void onOpenChange?: (open: boolean) => void
@@ -19,13 +19,13 @@ export const ServerRowMenu: Component<{
<ServerRowMenuView <ServerRowMenuView
server={props.server} server={props.server}
labels={serverMenuLabels(language)} labels={serverMenuLabels(language)}
canDefault={props.controller.canDefault()} canDefault={props.domain.defaults.available()}
isDefault={props.controller.defaultKey() === key} isDefault={props.domain.defaults.key() === key}
canRemove={props.controller.canRemove(key)} canRemove={props.domain.connection.canRemove(key)}
onEdit={props.onEdit} onEdit={props.onEdit}
onSetDefault={() => props.controller.setDefault(key)} onSetDefault={() => props.domain.defaults.set(key)}
onRemoveDefault={() => props.controller.setDefault(null)} onRemoveDefault={() => props.domain.defaults.set(null)}
onRemove={() => props.controller.handleRemove(key)} onRemove={() => props.domain.connection.remove(key)}
open={props.open} open={props.open}
onOpenChange={props.onOpenChange} onOpenChange={props.onOpenChange}
/> />
@@ -6,7 +6,7 @@ import { useDialog } from "@opencode-ai/ui/context/dialog"
import { type Component, Show, createEffect, createSignal, onCleanup, onMount } from "solid-js" import { type Component, Show, createEffect, createSignal, onCleanup, onMount } from "solid-js"
import { useLanguage } from "@/context/language" import { useLanguage } from "@/context/language"
import { type ServerConnection } from "@/context/server" import { type ServerConnection } from "@/context/server"
import { useServerManagementController } from "../dialog-select-server" import { useServerFormController } from "../server/server-management-controller"
import "./settings-v2.css" import "./settings-v2.css"
export const DialogServerV2: Component<{ export const DialogServerV2: Component<{
@@ -15,39 +15,39 @@ export const DialogServerV2: Component<{
}> = (props) => { }> = (props) => {
const dialog = useDialog() const dialog = useDialog()
const language = useLanguage() const language = useLanguage()
const controller = useServerManagementController({ const form = useServerFormController({
onSelect: () => dialog.close(), onSelect: () => dialog.close(),
navigateOnAdd: false, navigateOnAdd: false,
}) })
const [opened, setOpened] = createSignal(false) const [opened, setOpened] = createSignal(false)
onMount(() => { onMount(() => {
if (props.mode === "add") controller.startAdd() if (props.mode === "add") form.start.add()
if (props.mode === "edit" && props.server) controller.startEdit(props.server) if (props.mode === "edit" && props.server) form.start.edit(props.server)
setOpened(true) setOpened(true)
}) })
onCleanup(() => { onCleanup(() => {
controller.resetForm() form.reset()
}) })
createEffect(() => { createEffect(() => {
if (!opened()) return if (!opened()) return
if (controller.isFormMode()) return if (form.state.open()) return
dialog.close() dialog.close()
}) })
const keyDown = (event: KeyboardEvent) => { const keyDown = (event: KeyboardEvent) => {
if (event.key !== "Enter" || event.isComposing) return if (event.key !== "Enter" || event.isComposing) return
event.preventDefault() event.preventDefault()
controller.submitForm() form.submit()
} }
const title = () => const title = () =>
props.mode === "add" ? language.t("dialog.server.add.title") : language.t("dialog.server.edit.title") props.mode === "add" ? language.t("dialog.server.add.title") : language.t("dialog.server.edit.title")
const submitLabel = () => { const submitLabel = () => {
if (controller.formBusy()) return language.t("dialog.server.add.checking") if (form.state.busy()) return language.t("dialog.server.add.checking")
if (props.mode === "add") return language.t("dialog.server.add.button") if (props.mode === "add") return language.t("dialog.server.add.button")
return language.t("common.save") return language.t("common.save")
} }
@@ -66,16 +66,16 @@ export const DialogServerV2: Component<{
type="text" type="text"
appearance="large" appearance="large"
class="!w-full self-stretch" class="!w-full self-stretch"
value={controller.formValue()} value={form.state.value()}
placeholder={language.t("dialog.server.add.placeholder")} placeholder={language.t("dialog.server.add.placeholder")}
invalid={!!controller.formError()} invalid={!!form.state.error()}
disabled={controller.formBusy()} disabled={form.state.busy()}
autofocus autofocus
onInput={(event) => controller.handleFormChange()(event.currentTarget.value)} onInput={(event) => form.change.value(event.currentTarget.value)}
onKeyDown={keyDown} onKeyDown={keyDown}
/> />
<Show when={controller.formError()}> <Show when={form.state.error()}>
<span class="settings-v2-server-dialog-error">{controller.formError()}</span> <span class="settings-v2-server-dialog-error">{form.state.error()}</span>
</Show> </Show>
</div> </div>
<div class="flex w-full min-w-0 flex-col gap-2"> <div class="flex w-full min-w-0 flex-col gap-2">
@@ -84,10 +84,10 @@ export const DialogServerV2: Component<{
type="text" type="text"
appearance="large" appearance="large"
class="!w-full self-stretch" class="!w-full self-stretch"
value={controller.formName()} value={form.state.name()}
placeholder={language.t("dialog.server.add.namePlaceholder")} placeholder={language.t("dialog.server.add.namePlaceholder")}
disabled={controller.formBusy()} disabled={form.state.busy()}
onInput={(event) => controller.handleFormNameChange()(event.currentTarget.value)} onInput={(event) => form.change.name(event.currentTarget.value)}
onKeyDown={keyDown} onKeyDown={keyDown}
/> />
</div> </div>
@@ -98,10 +98,10 @@ export const DialogServerV2: Component<{
type="text" type="text"
appearance="large" appearance="large"
class="!w-full self-stretch" class="!w-full self-stretch"
value={controller.formUsername()} value={form.state.username()}
placeholder={language.t("dialog.server.add.usernamePlaceholder")} placeholder={language.t("dialog.server.add.usernamePlaceholder")}
disabled={controller.formBusy()} disabled={form.state.busy()}
onInput={(event) => controller.handleFormUsernameChange()(event.currentTarget.value)} onInput={(event) => form.change.username(event.currentTarget.value)}
onKeyDown={keyDown} onKeyDown={keyDown}
/> />
</div> </div>
@@ -111,10 +111,10 @@ export const DialogServerV2: Component<{
type="password" type="password"
appearance="large" appearance="large"
class="!w-full self-stretch" class="!w-full self-stretch"
value={controller.formPassword()} value={form.state.password()}
placeholder={language.t("dialog.server.add.passwordPlaceholder")} placeholder={language.t("dialog.server.add.passwordPlaceholder")}
disabled={controller.formBusy()} disabled={form.state.busy()}
onInput={(event) => controller.handleFormPasswordChange()(event.currentTarget.value)} onInput={(event) => form.change.password(event.currentTarget.value)}
onKeyDown={keyDown} onKeyDown={keyDown}
/> />
</div> </div>
@@ -122,10 +122,10 @@ export const DialogServerV2: Component<{
</div> </div>
</DialogBody> </DialogBody>
<DialogFooter> <DialogFooter>
<ButtonV2 variant="neutral" disabled={controller.formBusy()} onClick={() => dialog.close()}> <ButtonV2 variant="neutral" disabled={form.state.busy()} onClick={() => dialog.close()}>
{language.t("common.cancel")} {language.t("common.cancel")}
</ButtonV2> </ButtonV2>
<ButtonV2 variant="contrast" disabled={controller.formBusy()} onClick={controller.submitForm}> <ButtonV2 variant="contrast" disabled={form.state.busy()} onClick={form.submit}>
{submitLabel()} {submitLabel()}
</ButtonV2> </ButtonV2>
</DialogFooter> </DialogFooter>
@@ -10,7 +10,7 @@ import { ServerRowMenu } from "@/components/server/server-row-menu"
import { ServerHealthIndicator } from "@/components/server/server-row" import { ServerHealthIndicator } from "@/components/server/server-row"
import { useLanguage } from "@/context/language" import { useLanguage } from "@/context/language"
import { ServerConnection, serverName } from "@/context/server" import { ServerConnection, serverName } from "@/context/server"
import { useServerManagementController } from "../dialog-select-server" import { useServerCollectionController } from "../server/server-management-controller"
import { DialogServerV2 } from "./dialog-server-v2" import { DialogServerV2 } from "./dialog-server-v2"
import { SettingsListV2 } from "./parts/list" import { SettingsListV2 } from "./parts/list"
import { AddServerMenu, isWslServer, useFilteredWslServers, WslServerSettings } from "@/wsl/settings" import { AddServerMenu, isWslServer, useFilteredWslServers, WslServerSettings } from "@/wsl/settings"
@@ -19,16 +19,16 @@ import "./settings-v2.css"
export const SettingsServersV2: Component = () => { export const SettingsServersV2: Component = () => {
const dialog = useDialog() const dialog = useDialog()
const language = useLanguage() const language = useLanguage()
const controller = useServerManagementController() const domain = useServerCollectionController()
const [store, setStore] = createStore({ filter: "" }) const [store, setStore] = createStore({ filter: "" })
const wslServers = useFilteredWslServers(() => store.filter) const wslServers = useFilteredWslServers(() => store.filter)
const showSearch = createMemo( const showSearch = createMemo(
() => controller.sortedItems().filter((item) => !isWslServer(item)).length + wslServers().length > 1, () => domain.collection.items().filter((item) => !isWslServer(item)).length + wslServers().length > 1,
) )
const filtered = createMemo(() => { const filtered = createMemo(() => {
const items = controller.sortedItems().filter((item) => !isWslServer(item)) const items = domain.collection.items().filter((item) => !isWslServer(item))
const query = store.filter.trim() const query = store.filter.trim()
if (!query) return items if (!query) return items
return fuzzysort return fuzzysort
@@ -39,11 +39,11 @@ export const SettingsServersV2: Component = () => {
}) })
const openAdd = () => { const openAdd = () => {
dialog.push(() => <DialogServerV2 mode="add" />) void dialog.push(() => <DialogServerV2 mode="add" />)
} }
const openEdit = (server: ServerConnection.Http) => { const openEdit = (server: ServerConnection.Http) => {
dialog.push(() => <DialogServerV2 mode="edit" server={server} />) void dialog.push(() => <DialogServerV2 mode="edit" server={server} />)
} }
return ( return (
@@ -97,12 +97,12 @@ export const SettingsServersV2: Component = () => {
} }
> >
<SettingsListV2> <SettingsListV2>
<WslServerSettings controller={controller} servers={wslServers} /> <WslServerSettings domain={domain} servers={wslServers} />
<For each={filtered()}> <For each={filtered()}>
{(item) => { {(item) => {
const key = ServerConnection.key(item) const key = ServerConnection.key(item)
const health = () => controller.status()[key] const health = () => domain.collection.health()[key]
const isDefault = () => controller.defaultKey() === key const isDefault = () => domain.defaults.key() === key
return ( return (
<div class="settings-v2-servers-row"> <div class="settings-v2-servers-row">
<div class="settings-v2-servers-lead"> <div class="settings-v2-servers-lead">
@@ -122,10 +122,10 @@ export const SettingsServersV2: Component = () => {
</div> </div>
</div> </div>
<div class="settings-v2-servers-actions"> <div class="settings-v2-servers-actions">
<Show when={controller.canDefault() && isDefault()}> <Show when={domain.defaults.available() && isDefault()}>
<Tag>{language.t("dialog.server.status.default")}</Tag> <Tag>{language.t("dialog.server.status.default")}</Tag>
</Show> </Show>
<ServerRowMenu server={item} controller={controller} onEdit={openEdit} /> <ServerRowMenu server={item} domain={domain} onEdit={openEdit} />
</div> </div>
</div> </div>
) )
+2 -2
View File
@@ -671,13 +671,13 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
integrationID: server.integrationID, integrationID: server.integrationID,
location: { directory: key }, location: { directory: key },
}) })
const method = integration.data?.methods.find((item) => item.type === "oauth" && !item.forms?.length) const method = integration.data?.methods.find((item) => item.type === "oauth" && !item.prompts?.length)
if (!method || method.type !== "oauth") if (!method || method.type !== "oauth")
throw new Error(`MCP server ${name} requires an interactive authentication form`) throw new Error(`MCP server ${name} requires an interactive authentication form`)
const attempt = await serverSDK.api.integration.oauth.connect({ const attempt = await serverSDK.api.integration.oauth.connect({
integrationID: server.integrationID, integrationID: server.integrationID,
methodID: method.id, methodID: method.id,
answers: {}, inputs: {},
location: { directory: key }, location: { directory: key },
}) })
platform.openLink(attempt.data.url) platform.openLink(attempt.data.url)
@@ -1,5 +1,5 @@
import { useDirectoryPicker } from "@/components/directory-picker" import { useDirectoryPicker } from "@/components/directory-picker"
import { useServerManagementController } from "@/components/dialog-select-server" import { useServerActionsController } from "@/components/server/server-management-controller"
import { useSettingsCommand } from "@/components/settings-dialog" import { useSettingsCommand } from "@/components/settings-dialog"
import { DialogServerV2 } from "@/components/settings-v2/dialog-server-v2" import { DialogServerV2 } from "@/components/settings-v2/dialog-server-v2"
import { type LocalProject } from "@/context/layout" import { type LocalProject } from "@/context/layout"
@@ -22,7 +22,7 @@ export function createHomeProjectsController(home: HomeController) {
const language = useLanguage() const language = useLanguage()
const notification = useNotification() const notification = useNotification()
const openSettings = useSettingsCommand() const openSettings = useSettingsCommand()
const serverManagement = useServerManagementController({ navigateOnAdd: false }) const serverManagement = useServerActionsController()
const [_state, setState, _, ready] = persisted( const [_state, setState, _, ready] = persisted(
Persist.global("home.servers", ["home.servers.v1"]), Persist.global("home.servers", ["home.servers.v1"]),
createStore({ collapsed: {} as Record<string, boolean> }), createStore({ collapsed: {} as Record<string, boolean> }),
@@ -56,12 +56,12 @@ export function createHomeProjectsController(home: HomeController) {
const key = ServerConnection.key(conn) const key = ServerConnection.key(conn)
setState("collapsed", key, !state().collapsed[key]) setState("collapsed", key, !state().collapsed[key])
}, },
canDefault: serverManagement.canDefault, canDefault: serverManagement.defaults.available,
defaultKey: serverManagement.defaultKey, defaultKey: serverManagement.defaults.key,
setDefault: (conn: ServerConnection.Any | undefined) => setDefault: (conn: ServerConnection.Any | undefined) =>
serverManagement.setDefault(conn ? ServerConnection.key(conn) : null), serverManagement.defaults.set(conn ? ServerConnection.key(conn) : null),
canRemove: (conn: ServerConnection.Any) => serverManagement.canRemove(ServerConnection.key(conn)), canRemove: (conn: ServerConnection.Any) => serverManagement.connection.canRemove(ServerConnection.key(conn)),
remove: (conn: ServerConnection.Any) => serverManagement.handleRemove(ServerConnection.key(conn)), remove: (conn: ServerConnection.Any) => serverManagement.connection.remove(ServerConnection.key(conn)),
edit: (conn: ServerConnection.Http) => dialog.show(() => <DialogServerV2 mode="edit" server={conn} />), edit: (conn: ServerConnection.Http) => dialog.show(() => <DialogServerV2 mode="edit" server={conn} />),
focus: home.selection.focusServer, focus: home.selection.focusServer,
}, },
+10 -12
View File
@@ -7,7 +7,7 @@ import { MenuV2 } from "@opencode-ai/ui/v2/menu-v2"
import { useMutation } from "@tanstack/solid-query" import { useMutation } from "@tanstack/solid-query"
import fuzzysort from "fuzzysort" import fuzzysort from "fuzzysort"
import { type Accessor, For, Show, createMemo } from "solid-js" import { type Accessor, For, Show, createMemo } from "solid-js"
import type { useServerManagementController } from "@/components/dialog-select-server" import type { ServerCollectionController } from "@/components/server/server-management-controller"
import { ServerHealthIndicator } from "@/components/server/server-row" import { ServerHealthIndicator } from "@/components/server/server-row"
import { useLanguage } from "@/context/language" import { useLanguage } from "@/context/language"
import { usePlatform } from "@/context/platform" import { usePlatform } from "@/context/platform"
@@ -17,8 +17,6 @@ import { DialogAddWslServer } from "./dialog-add-server"
import { useWslServers } from "./context" import { useWslServers } from "./context"
import { wslOpencodeAction, wslRuntimeRetryable } from "./settings-model" import { wslOpencodeAction, wslRuntimeRetryable } from "./settings-model"
type Controller = ReturnType<typeof useServerManagementController>
export function isWslServer(server: ServerConnection.Any) { export function isWslServer(server: ServerConnection.Any) {
return server.type === "sidecar" && server.variant === "wsl" return server.type === "sidecar" && server.variant === "wsl"
} }
@@ -28,7 +26,7 @@ export function AddServerMenu(props: { onAddServer: () => void }) {
const dialog = useDialog() const dialog = useDialog()
const language = useLanguage() const language = useLanguage()
const openAddWsl = () => { const openAddWsl = () => {
dialog.push(() => <DialogAddWslServer />) void dialog.push(() => <DialogAddWslServer />)
} }
return ( return (
<Show <Show
@@ -67,7 +65,7 @@ export function useFilteredWslServers(filter: Accessor<string>) {
} }
export function WslServerSettings(props: { export function WslServerSettings(props: {
controller: Controller domain: Pick<ServerCollectionController, "collection" | "defaults" | "connection">
servers: ReturnType<typeof useFilteredWslServers> servers: ReturnType<typeof useFilteredWslServers>
}) { }) {
const platform = usePlatform() const platform = usePlatform()
@@ -86,7 +84,7 @@ export function WslServerSettings(props: {
})) }))
const remove = (key: ServerConnection.Key) => { const remove = (key: ServerConnection.Key) => {
request.mutate(() => props.controller.handleRemove(key)) request.mutate(() => props.domain.connection.remove(key))
} }
return ( return (
@@ -100,7 +98,7 @@ export function WslServerSettings(props: {
return ( return (
<div class="settings-v2-servers-row"> <div class="settings-v2-servers-row">
<div class="settings-v2-servers-lead"> <div class="settings-v2-servers-lead">
<ServerHealthIndicator health={props.controller.status()[key]} /> <ServerHealthIndicator health={props.domain.collection.health()[key]} />
<div class="settings-v2-servers-copy"> <div class="settings-v2-servers-copy">
<span class="flex min-w-0 items-center gap-1"> <span class="flex min-w-0 items-center gap-1">
<span class="settings-v2-servers-name">{item.config.distro}</span> <span class="settings-v2-servers-name">{item.config.distro}</span>
@@ -114,7 +112,7 @@ export function WslServerSettings(props: {
</div> </div>
</div> </div>
<div class="settings-v2-servers-actions"> <div class="settings-v2-servers-actions">
<Show when={props.controller.canDefault() && props.controller.defaultKey() === key}> <Show when={props.domain.defaults.available() && props.domain.defaults.key() === key}>
<Tag>{language.t("dialog.server.status.default")}</Tag> <Tag>{language.t("dialog.server.status.default")}</Tag>
</Show> </Show>
<Show when={opencodeAction()}> <Show when={opencodeAction()}>
@@ -145,13 +143,13 @@ export function WslServerSettings(props: {
{language.t("wsl.server.retryStart")} {language.t("wsl.server.retryStart")}
</MenuV2.Item> </MenuV2.Item>
</Show> </Show>
<Show when={props.controller.canDefault() && props.controller.defaultKey() !== key}> <Show when={props.domain.defaults.available() && props.domain.defaults.key() !== key}>
<MenuV2.Item onSelect={() => props.controller.setDefault(key)}> <MenuV2.Item onSelect={() => props.domain.defaults.set(key)}>
{language.t("dialog.server.menu.default")} {language.t("dialog.server.menu.default")}
</MenuV2.Item> </MenuV2.Item>
</Show> </Show>
<Show when={props.controller.canDefault() && props.controller.defaultKey() === key}> <Show when={props.domain.defaults.available() && props.domain.defaults.key() === key}>
<MenuV2.Item onSelect={() => props.controller.setDefault(null)}> <MenuV2.Item onSelect={() => props.domain.defaults.set(null)}>
{language.t("dialog.server.menu.defaultRemove")} {language.t("dialog.server.menu.defaultRemove")}
</MenuV2.Item> </MenuV2.Item>
</Show> </Show>
@@ -50,7 +50,7 @@ const login = Effect.fn("cli.console.login.run")(function* (timeline: TimelineHo
{ {
integrationID, integrationID,
methodID: method.id, methodID: method.id,
answers: server ? { server } : {}, inputs: server ? { server } : {},
location, location,
}, },
{ signal }, { signal },
@@ -32,7 +32,7 @@ export default Runtime.handler(
return yield* Effect.fail(new Error(`MCP server "${input.name}" is not an OAuth-capable remote server`)) return yield* Effect.fail(new Error(`MCP server "${input.name}" is not an OAuth-capable remote server`))
const started = yield* Effect.promise(() => const started = yield* Effect.promise(() =>
client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, answers: {}, location }), client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, inputs: {}, location }),
) )
const attempt = started.data const attempt = started.data
if (attempt.mode === "code") if (attempt.mode === "code")
+2 -3
View File
@@ -23,9 +23,9 @@ import type { Shell } from "@opencode-ai/schema/shell"
import type { DateTime } from "effect" import type { DateTime } from "effect"
import type { Provider } from "@opencode-ai/schema/provider" import type { Provider } from "@opencode-ai/schema/provider"
import type { Integration } from "@opencode-ai/schema/integration" import type { Integration } from "@opencode-ai/schema/integration"
import type { Form } from "@opencode-ai/schema/form"
import type { Mcp } from "@opencode-ai/schema/mcp" import type { Mcp } from "@opencode-ai/schema/mcp"
import type { Credential } from "@opencode-ai/schema/credential" import type { Credential } from "@opencode-ai/schema/credential"
import type { Form } from "@opencode-ai/schema/form"
import type { Permission } from "@opencode-ai/schema/permission" import type { Permission } from "@opencode-ai/schema/permission"
import type { PermissionSaved } from "@opencode-ai/schema/permission-saved" import type { PermissionSaved } from "@opencode-ai/schema/permission-saved"
import type { FileSystem } from "@opencode-ai/schema/filesystem" import type { FileSystem } from "@opencode-ai/schema/filesystem"
@@ -1006,7 +1006,6 @@ export type Endpoint10_3Input = {
readonly integrationID: Integration.ID readonly integrationID: Integration.ID
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
readonly key: string readonly key: string
readonly answers: Form.Answer
readonly label?: string | undefined readonly label?: string | undefined
} }
export type Endpoint10_3Output = void export type Endpoint10_3Output = void
@@ -1018,7 +1017,7 @@ export type Endpoint10_4Input = {
readonly integrationID: Integration.ID readonly integrationID: Integration.ID
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
readonly methodID: Integration.MethodID readonly methodID: Integration.MethodID
readonly answers: Form.Answer readonly inputs: { readonly [x: string]: string }
readonly label?: string | undefined readonly label?: string | undefined
} }
export type Endpoint10_4Output = { readonly location: Location.Info; readonly data: Integration.Attempt } export type Endpoint10_4Output = { readonly location: Location.Info; readonly data: Integration.Attempt }
@@ -688,7 +688,7 @@ const Endpoint10_3 = (raw: RawClient["server.integration"]) => (input: Endpoint1
raw["integration.connect.key"]({ raw["integration.connect.key"]({
params: { integrationID: input["integrationID"] }, params: { integrationID: input["integrationID"] },
query: { location: input["location"] }, query: { location: input["location"] },
payload: { key: input["key"], answers: input["answers"], label: input["label"] }, payload: { key: input["key"], label: input["label"] },
}).pipe(Effect.mapError(mapClientError)), }).pipe(Effect.mapError(mapClientError)),
) )
@@ -697,7 +697,7 @@ const Endpoint10_4 = (raw: RawClient["server.integration"]) => (input: Endpoint1
raw["integration.oauth.connect"]({ raw["integration.oauth.connect"]({
params: { integrationID: input["integrationID"] }, params: { integrationID: input["integrationID"] },
query: { location: input["location"] }, query: { location: input["location"] },
payload: { methodID: input["methodID"], answers: input["answers"], label: input["label"] }, payload: { methodID: input["methodID"], inputs: input["inputs"], label: input["label"] },
}).pipe(Effect.mapError(mapClientError)), }).pipe(Effect.mapError(mapClientError)),
) )
@@ -991,7 +991,7 @@ export function make(options: ClientOptions) {
method: "POST", method: "POST",
path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/key`, path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/key`,
query: { location: input["location"] }, query: { location: input["location"] },
body: { key: input["key"], answers: input["answers"], label: input["label"] }, body: { key: input["key"], label: input["label"] },
successStatus: 204, successStatus: 204,
declaredStatuses: [400, 401], declaredStatuses: [400, 401],
empty: true, empty: true,
@@ -1006,7 +1006,7 @@ export function make(options: ClientOptions) {
method: "POST", method: "POST",
path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/oauth`, path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/oauth`,
query: { location: input["location"] }, query: { location: input["location"] },
body: { methodID: input["methodID"], answers: input["answers"], label: input["label"] }, body: { methodID: input["methodID"], inputs: input["inputs"], label: input["label"] },
successStatus: 200, successStatus: 200,
declaredStatuses: [400, 401], declaredStatuses: [400, 401],
empty: false, empty: false,
+80 -70
View File
@@ -195,18 +195,12 @@ export type ProviderInfo = {
body?: { [x: string]: any } body?: { [x: string]: any }
} }
export type FormWhen = { export type IntegrationWhen = { key: string; op: "eq" | "neq"; value: string }
key: string
op: "eq" | "neq"
value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean
}
export type FormOption = { value: string; label: string; description?: string }
export type FormExternalField = { key: string; type: "external"; url: string; title?: string; description?: string }
export type IntegrationCommandMethod = { id: string; type: "command"; label: string; command: Array<string> } export type IntegrationCommandMethod = { id: string; type: "command"; label: string; command: Array<string> }
export type IntegrationKeyMethod = { type: "key"; label?: string }
export type IntegrationEnvMethod = { type: "env"; names: Array<string> } export type IntegrationEnvMethod = { type: "env"; names: Array<string> }
export type ConnectionCredentialInfo = { type: "credential"; id: string; label: string } export type ConnectionCredentialInfo = { type: "credential"; id: string; label: string }
@@ -291,6 +285,16 @@ export type ProjectDirectory = { directory: string; strategy?: string }
export type FormMetadata = { [x: string]: JsonValue } export type FormMetadata = { [x: string]: JsonValue }
export type FormWhen = {
key: string
op: "eq" | "neq"
value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean
}
export type FormOption = { value: string; label: string; description?: string }
export type FormExternalField = { key: string; type: "external"; url: string; title?: string; description?: string }
export type FormValue = string | number | boolean | Array<string> export type FormValue = string | number | boolean | Array<string>
export type PermissionSource = { type: "tool"; messageID: string; id: string } export type PermissionSource = { type: "tool"; messageID: string; id: string }
@@ -1241,6 +1245,45 @@ export type ModelCost = {
cache: { read: MoneyUSDPerMillionTokens; write: MoneyUSDPerMillionTokens } cache: { read: MoneyUSDPerMillionTokens; write: MoneyUSDPerMillionTokens }
} }
export type IntegrationTextPrompt = {
type: "text"
key: string
message: string
placeholder?: string
when?: IntegrationWhen
}
export type IntegrationSelectPrompt = {
type: "select"
key: string
message: string
options: Array<{ label: string; value: string; hint?: string }>
when?: IntegrationWhen
}
export type ConnectionInfo = ConnectionCredentialInfo | ConnectionEnvInfo
export type McpServer = {
name: string
status: McpStatusConnected | McpStatusPending | McpStatusDisabled | McpStatusFailed | McpStatusNeedsAuth
integrationID?: string
}
export type McpResourceCatalog = { resources: Array<McpResource>; templates: Array<McpResourceTemplate> }
export type Project = {
id: string
canonical: string
vcs?: ProjectVcs
name?: string
icon?: ProjectIcon
commands?: ProjectCommands
time: ProjectTime
sandboxes: Array<string>
}
export type ProjectDirectories = Array<ProjectDirectory>
export type FormNumberField = { export type FormNumberField = {
key: string key: string
title?: string title?: string
@@ -1306,29 +1349,6 @@ export type FormMultiselectField = {
default?: Array<string> default?: Array<string>
} }
export type ConnectionInfo = ConnectionCredentialInfo | ConnectionEnvInfo
export type McpServer = {
name: string
status: McpStatusConnected | McpStatusPending | McpStatusDisabled | McpStatusFailed | McpStatusNeedsAuth
integrationID?: string
}
export type McpResourceCatalog = { resources: Array<McpResource>; templates: Array<McpResourceTemplate> }
export type Project = {
id: string
canonical: string
vcs?: ProjectVcs
name?: string
icon?: ProjectIcon
commands?: ProjectCommands
time: ProjectTime
sandboxes: Array<string>
}
export type ProjectDirectories = Array<ProjectDirectory>
export type FormAnswer = { [x: string]: FormValue } export type FormAnswer = { [x: string]: FormValue }
export type PermissionRequest = { export type PermissionRequest = {
@@ -1609,6 +1629,13 @@ export type ModelInfo = {
limit: { context: number; input?: number; output: number } limit: { context: number; input?: number; output: number }
} }
export type IntegrationOAuthMethod = {
id: string
type: "oauth"
label: string
prompts?: Array<IntegrationTextPrompt | IntegrationSelectPrompt>
}
export type FormField = export type FormField =
| FormStringField | FormStringField
| FormNumberField | FormNumberField
@@ -1862,9 +1889,15 @@ export type SessionMessageAssistantTool = {
time: { created: number; ran?: number; completed?: number } time: { created: number; ran?: number; completed?: number }
} }
export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationEnvMethod
export type FormFields = [FormField, ...Array<FormField>] export type FormFields = [FormField, ...Array<FormField>]
export type FormFields3 = [FormField1, ...Array<FormField1>] export type FormFields1 = [FormField1, ...Array<FormField1>]
export type SessionPendingInfo = SessionPendingUser | SessionPendingSynthetic | SessionPendingCompaction export type SessionPendingInfo = SessionPendingUser | SessionPendingSynthetic | SessionPendingCompaction
@@ -1886,13 +1919,16 @@ export type SessionMessageAssistant = {
retry?: SessionMessageAssistantRetry retry?: SessionMessageAssistantRetry
} }
export type IntegrationOAuthMethod = { id: string; type: "oauth"; label: string; forms?: FormFields } export type IntegrationInfo = {
id: string
export type IntegrationKeyMethod = { type: "key"; label?: string; forms?: FormFields } name: string
methods: Array<IntegrationMethod>
connections: Array<ConnectionInfo>
}
export type FormInfo = { id: string; sessionID: string; title: string; metadata?: FormMetadata; fields: FormFields } export type FormInfo = { id: string; sessionID: string; title: string; metadata?: FormMetadata; fields: FormFields }
export type FormInfo1 = { id: string; sessionID: string; title: string; metadata?: FormMetadata1; fields: FormFields3 } export type FormInfo1 = { id: string; sessionID: string; title: string; metadata?: FormMetadata1; fields: FormFields1 }
export type SessionInputAdmitted = { export type SessionInputAdmitted = {
id: string id: string
@@ -1915,12 +1951,6 @@ export type SessionMessageInfo =
| SessionMessageAssistant | SessionMessageAssistant
| SessionMessageCompaction | SessionMessageCompaction
export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationEnvMethod
export type FormCreated = { export type FormCreated = {
id: string id: string
created: number created: number
@@ -1978,13 +2008,6 @@ export type SessionMessagesResponse = {
cursor: { previous?: string | null; next?: string | null } cursor: { previous?: string | null; next?: string | null }
} }
export type IntegrationInfo = {
id: string
name: string
methods: Array<IntegrationMethod>
connections: Array<ConnectionInfo>
}
export type V2Event = export type V2Event =
| ModelsDevRefreshed | ModelsDevRefreshed
| IntegrationUpdated | IntegrationUpdated
@@ -3834,21 +3857,8 @@ export type IntegrationConnectKeyInput = {
readonly location?: { readonly location?: {
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
}["location"] }["location"]
readonly key: { readonly key: { readonly key: string; readonly label?: string | undefined }["key"]
readonly key: string readonly label?: { readonly key: string; readonly label?: string | undefined }["label"]
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> }
readonly label?: string | undefined
}["key"]
readonly answers: {
readonly key: string
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> }
readonly label?: string | undefined
}["answers"]
readonly label?: {
readonly key: string
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> }
readonly label?: string | undefined
}["label"]
} }
export type IntegrationConnectKeyOutput = void export type IntegrationConnectKeyOutput = void
@@ -3860,17 +3870,17 @@ export type IntegrationOauthConnectInput = {
}["location"] }["location"]
readonly methodID: { readonly methodID: {
readonly methodID: string readonly methodID: string
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } readonly inputs: { readonly [x: string]: string }
readonly label?: string | undefined readonly label?: string | undefined
}["methodID"] }["methodID"]
readonly answers: { readonly inputs: {
readonly methodID: string readonly methodID: string
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } readonly inputs: { readonly [x: string]: string }
readonly label?: string | undefined readonly label?: string | undefined
}["answers"] }["inputs"]
readonly label?: { readonly label?: {
readonly methodID: string readonly methodID: string
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } readonly inputs: { readonly [x: string]: string }
readonly label?: string | undefined readonly label?: string | undefined
}["label"] }["label"]
} }
-39
View File
@@ -147,45 +147,6 @@ test("experimental wellknown integration add uses the public HTTP contract", asy
expect(await request?.json()).toEqual({ url: "https://example.com" }) expect(await request?.json()).toEqual({ url: "https://example.com" })
}) })
test("integration connections submit form answers", async () => {
const requests: Request[] = []
const client = OpenCode.make({
baseUrl: "http://localhost:3000",
fetch: async (input, init) => {
const request = input instanceof Request ? input : new Request(input, init)
requests.push(request)
if (request.url.endsWith("/connect/key")) return new Response(null, { status: 204 })
return Response.json({
location: { directory: "/tmp/project", project: { id: "proj_test", directory: "/tmp/project" } },
data: {
attemptID: "con_test",
url: "https://example.com/authorize",
instructions: "Authorize",
mode: "auto",
time: { created: 1, expires: 2 },
},
})
},
})
await client.integration.connect.key({
integrationID: "cloudflare-workers-ai",
key: "secret",
answers: { accountId: "account" },
})
await client.integration.oauth.connect({
integrationID: "github-copilot",
methodID: "device",
answers: { deploymentType: "enterprise", enabled: true, scopes: ["read:user"] },
})
expect(await requests[0].json()).toEqual({ key: "secret", answers: { accountId: "account" } })
expect(await requests[1].json()).toEqual({
methodID: "device",
answers: { deploymentType: "enterprise", enabled: true, scopes: ["read:user"] },
})
})
test("health.stop sends exact replacement identity", async () => { test("health.stop sends exact replacement identity", async () => {
let request: Request | undefined let request: Request | undefined
const client = OpenCode.make({ const client = OpenCode.make({
+6 -10
View File
@@ -180,14 +180,10 @@ export const layer = Layer.effect(
Effect.gen(function* () { Effect.gen(function* () {
const entry = yield* find(input.id) const entry = yield* find(input.id)
if (entry.state.status !== "pending") return yield* new AlreadySettledError({ id: input.id }) if (entry.state.status !== "pending") return yield* new AlreadySettledError({ id: input.id })
const invalid = validateAnswer(entry.form.fields, input.answer) const invalid = validateAnswer(entry.form, input.answer)
if (invalid) return yield* new InvalidAnswerError({ id: input.id, message: invalid }) if (invalid) return yield* new InvalidAnswerError({ id: input.id, message: invalid })
const next: TerminalState = { status: "answered", answer: input.answer } const next: TerminalState = { status: "answered", answer: input.answer }
yield* bus.publish(Form.Event.Replied, { yield* bus.publish(Form.Event.Replied, { id: input.id, sessionID: entry.form.sessionID, answer: input.answer })
id: input.id,
sessionID: entry.form.sessionID,
answer: input.answer,
})
yield* Cache.set(forms, input.id, { ...entry, state: next }) yield* Cache.set(forms, input.id, { ...entry, state: next })
yield* Deferred.succeed(entry.deferred, next) yield* Deferred.succeed(entry.deferred, next)
}), }),
@@ -227,12 +223,12 @@ export const locationLayer = layer
export const node = makeLocationNode({ service: Service, layer, deps: [Bus.node] }) export const node = makeLocationNode({ service: Service, layer, deps: [Bus.node] })
export function validateAnswer(forms: ReadonlyArray<Form.Field>, answer: Answer) { function validateAnswer(form: Info, answer: Answer) {
const fields = new Map(forms.map((field) => [field.key, field] as const)) const fields = new Map(form.fields.map((field) => [field.key, field] as const))
for (const key of Object.keys(answer)) { for (const key of Object.keys(answer)) {
if (!fields.has(key)) return `Unknown form field: ${key}` if (!fields.has(key)) return `Unknown form field: ${key}`
} }
for (const field of forms) { for (const field of form.fields) {
const value = answer[field.key] const value = answer[field.key]
if (field.type === "external") { if (field.type === "external") {
if (value !== true) return `External form field must be acknowledged: ${field.key}` if (value !== true) return `External form field must be acknowledged: ${field.key}`
@@ -268,7 +264,7 @@ function matches(when: Form.When, value: Form.Value | undefined) {
// carry a value matching that field's type, and use a declared option when the field's options // carry a value matching that field's type, and use a declared option when the field's options
// are closed. Rejecting these at creation surfaces authoring mistakes to the caller instead of // are closed. Rejecting these at creation surfaces authoring mistakes to the caller instead of
// silently never matching. // silently never matching.
export function validateFields(fields: ReadonlyArray<Form.Field>) { function validateFields(fields: ReadonlyArray<Form.Field>) {
if (fields.length === 0) return "Form must have at least one field" if (fields.length === 0) return "Form must have at least one field"
const earlier = new Map<string, InputField>() const earlier = new Map<string, InputField>()
const keys = new Set<string>() const keys = new Set<string>()
+22 -26
View File
@@ -24,7 +24,6 @@ import { Bus } from "./bus"
import { IntegrationConnection } from "./integration/connection" import { IntegrationConnection } from "./integration/connection"
import { AppProcess } from "@opencode-ai/util/process" import { AppProcess } from "@opencode-ai/util/process"
import { ChildProcess } from "effect/unstable/process" import { ChildProcess } from "effect/unstable/process"
import { Form } from "./form"
export const ID = Integration.ID export const ID = Integration.ID
export type ID = Integration.ID export type ID = Integration.ID
@@ -35,6 +34,18 @@ export type MethodID = Integration.MethodID
export const AttemptID = Integration.AttemptID export const AttemptID = Integration.AttemptID
export type AttemptID = typeof AttemptID.Type export type AttemptID = typeof AttemptID.Type
export const When = Integration.When
export type When = Integration.When
export const TextPrompt = Integration.TextPrompt
export type TextPrompt = Integration.TextPrompt
export const SelectPrompt = Integration.SelectPrompt
export type SelectPrompt = Integration.SelectPrompt
export const Prompt = Integration.Prompt
export type Prompt = Integration.Prompt
export const OAuthMethod = Integration.OAuthMethod export const OAuthMethod = Integration.OAuthMethod
export type OAuthMethod = Integration.OAuthMethod export type OAuthMethod = Integration.OAuthMethod
@@ -53,6 +64,9 @@ export type Method = Integration.Method
export const Info = Integration.Info export const Info = Integration.Info
export type Info = Integration.Info export type Info = Integration.Info
export const Inputs = Integration.Inputs
export type Inputs = Integration.Inputs
export type OAuthAuthorization = { export type OAuthAuthorization = {
readonly url: string readonly url: string
readonly instructions: string readonly instructions: string
@@ -71,7 +85,7 @@ export type OAuthAuthorization = {
export interface OAuthImplementation { export interface OAuthImplementation {
readonly integrationID: ID readonly integrationID: ID
readonly method: OAuthMethod readonly method: OAuthMethod
readonly authorize: (answers: Form.Answer) => Effect.Effect<OAuthAuthorization, unknown, Scope.Scope> readonly authorize: (inputs: Inputs) => Effect.Effect<OAuthAuthorization, unknown, Scope.Scope>
readonly refresh?: (credential: Credential.OAuth) => Effect.Effect<Credential.OAuth, unknown> readonly refresh?: (credential: Credential.OAuth) => Effect.Effect<Credential.OAuth, unknown>
readonly label?: (credential: Credential.OAuth) => string | undefined readonly label?: (credential: Credential.OAuth) => string | undefined
} }
@@ -161,8 +175,6 @@ export interface Interface extends State.Transformable<Draft> {
readonly integrationID: ID readonly integrationID: ID
/** Secret entered by the user. */ /** Secret entered by the user. */
readonly key: string readonly key: string
/** Values collected from the method's form fields. */
readonly answers: Form.Answer
/** User-facing label for the stored credential. */ /** User-facing label for the stored credential. */
readonly label?: string readonly label?: string
}) => Effect.Effect<void, AuthorizationError> }) => Effect.Effect<void, AuthorizationError>
@@ -179,7 +191,7 @@ export interface Interface extends State.Transformable<Draft> {
readonly connect: (input: { readonly connect: (input: {
readonly integrationID: ID readonly integrationID: ID
readonly methodID: MethodID readonly methodID: MethodID
readonly answers: Form.Answer readonly inputs: Inputs
readonly label?: string readonly label?: string
}) => Effect.Effect<Attempt, AuthorizationError> }) => Effect.Effect<Attempt, AuthorizationError>
/** Returns the current state of an OAuth attempt. */ /** Returns the current state of an OAuth attempt. */
@@ -344,7 +356,7 @@ const layer = Layer.effect(
return [...credentials, ...env] return [...credentials, ...env]
} }
const project = (entry: Entry, connections: IntegrationConnection.Info[]): Info => const project = (entry: Entry, connections: IntegrationConnection.Info[]) =>
Info.make({ Info.make({
id: entry.ref.id, id: entry.ref.id,
name: entry.ref.name, name: entry.ref.name,
@@ -535,20 +547,15 @@ const layer = Layer.effect(
const connectOAuth = Effect.fn("Integration.oauth.connect")(function* (input: { const connectOAuth = Effect.fn("Integration.oauth.connect")(function* (input: {
readonly integrationID: ID readonly integrationID: ID
readonly methodID: MethodID readonly methodID: MethodID
readonly answers: Form.Answer readonly inputs: Inputs
readonly label?: string readonly label?: string
}) { }) {
const method = state.get().integrations.get(input.integrationID)?.implementations.get(input.methodID) const method = state.get().integrations.get(input.integrationID)?.implementations.get(input.methodID)
if (!method) { if (!method) {
return yield* Effect.die(new Error(`OAuth method not found: ${input.integrationID}/${input.methodID}`)) return yield* Effect.die(new Error(`OAuth method not found: ${input.integrationID}/${input.methodID}`))
} }
if (method.method.forms) {
const invalid =
Form.validateFields(method.method.forms) ?? Form.validateAnswer(method.method.forms, input.answers)
if (invalid) return yield* new AuthorizationError({ cause: new Error(invalid) })
}
const attemptScope = yield* Scope.fork(scope) const attemptScope = yield* Scope.fork(scope)
const authorization = yield* authorize(method.authorize(input.answers)).pipe( const authorization = yield* authorize(method.authorize(input.inputs)).pipe(
Scope.provide(attemptScope), Scope.provide(attemptScope),
Effect.onExit((exit) => (Exit.isFailure(exit) ? Scope.close(attemptScope, exit) : Effect.void)), Effect.onExit((exit) => (Exit.isFailure(exit) ? Scope.close(attemptScope, exit) : Effect.void)),
) )
@@ -692,23 +699,12 @@ const layer = Layer.effect(
const method = state const method = state
.get() .get()
.integrations.get(input.integrationID) .integrations.get(input.integrationID)
?.methods.find((method) => method.type === "key") ?.methods.some((method) => method.type === "key")
if (!method) return yield* Effect.die(new Error(`Key method not found: ${input.integrationID}`)) if (!method) return yield* Effect.die(new Error(`Key method not found: ${input.integrationID}`))
if (method.type === "key" && method.forms) {
const invalid = Form.validateFields(method.forms) ?? Form.validateAnswer(method.forms, input.answers)
if (invalid) return yield* new AuthorizationError({ cause: new Error(invalid) })
}
if (method.type === "key" && !method.forms && Object.keys(input.answers).length > 0) {
return yield* new AuthorizationError({ cause: new Error("Key method does not accept form answers") })
}
yield* credentials.create({ yield* credentials.create({
integrationID: input.integrationID, integrationID: input.integrationID,
label: input.label, label: input.label,
value: Credential.Key.make({ value: Credential.Key.make({ type: "key", key: input.key }),
type: "key",
key: input.key,
...(Object.keys(input.answers).length > 0 ? { configuration: input.answers } : {}),
}),
}) })
yield* bus.publish(Integration.Event.ConnectionUpdated, { integrationID: input.integrationID }) yield* bus.publish(Integration.Event.ConnectionUpdated, { integrationID: input.integrationID })
yield* bus.publish(Integration.Event.Updated, {}) yield* bus.publish(Integration.Event.Updated, {})
+2
View File
@@ -46,6 +46,7 @@ import { SessionGenerateNode } from "./session/generate-node"
import { McpTool } from "./tool/mcp" import { McpTool } from "./tool/mcp"
import { ReadToolFileSystem } from "./tool/read-filesystem" import { ReadToolFileSystem } from "./tool/read-filesystem"
import { Tool } from "./tool" import { Tool } from "./tool"
import { ToolOutput } from "./tool-output"
import { Vcs } from "./vcs" import { Vcs } from "./vcs"
export { LocationServiceMap } from "./location-service-map" export { LocationServiceMap } from "./location-service-map"
@@ -78,6 +79,7 @@ const locationServiceNodes = [
MCP.node, MCP.node,
Permission.node, Permission.node,
Tool.node, Tool.node,
ToolOutput.node,
Image.node, Image.node,
SkillInstructions.node, SkillInstructions.node,
ReferenceInstructions.node, ReferenceInstructions.node,
+1 -3
View File
@@ -149,7 +149,6 @@ export const fromCatalogModel = (
}) })
const packageName = Provider.packageName(resolved.package) const packageName = Provider.packageName(resolved.package)
const key = apiKey(resolved, credential) const key = apiKey(resolved, credential)
const configuration = credential?.type === "key" ? credential.configuration : undefined
if (Provider.isAISDK(resolved.package) && packageName === "@ai-sdk/openai") { if (Provider.isAISDK(resolved.package) && packageName === "@ai-sdk/openai") {
return Effect.succeed( return Effect.succeed(
@@ -176,7 +175,7 @@ export const fromCatalogModel = (
.model({ id: resolved.modelID ?? resolved.id, compatibility: resolved.compatibility }), .model({ id: resolved.modelID ?? resolved.id, compatibility: resolved.compatibility }),
) )
} }
const configured = { ...resolved.settings, ...credential?.metadata, ...configuration } const configured = { ...resolved.settings, ...credential?.metadata }
const mapping = Provider.isAISDK(resolved.package) const mapping = Provider.isAISDK(resolved.package)
? AISDKNative.map({ ? AISDKNative.map({
packageName, packageName,
@@ -191,7 +190,6 @@ export const fromCatalogModel = (
draft.settings = Provider.mergeOverlay(draft.settings, { draft.settings = Provider.mergeOverlay(draft.settings, {
...nativeCredentialSettings(resolved.package ?? "", credential), ...nativeCredentialSettings(resolved.package ?? "", credential),
...credential?.metadata, ...credential?.metadata,
...configuration,
}) })
}) })
return dependencies.loadAISDK(runtime).pipe(Effect.mapError(() => unsupported(resolved))) return dependencies.loadAISDK(runtime).pipe(Effect.mapError(() => unsupported(resolved)))
+14 -24
View File
@@ -47,13 +47,17 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
workspaceID: location.workspaceID, workspaceID: location.workspaceID,
project: location.project, project: location.project,
}) })
const locationRef = (input?: { readonly location?: { readonly directory?: string; readonly workspace?: string } }) => const locationRef = (input?: {
readonly location?: { readonly directory?: string; readonly workspace?: string }
}) =>
input?.location === undefined input?.location === undefined
? undefined ? undefined
: Location.Ref.make({ : Location.Ref.make({
directory: AbsolutePath.make(input.location.directory ?? location.directory), directory: AbsolutePath.make(input.location.directory ?? location.directory),
workspaceID: workspaceID:
input.location.workspace === undefined ? location.workspaceID : Workspace.ID.make(input.location.workspace), input.location.workspace === undefined
? location.workspaceID
: Workspace.ID.make(input.location.workspace),
}) })
const isCurrentLocation = (ref: Location.Ref) => const isCurrentLocation = (ref: Location.Ref) =>
ref.directory === location.directory && ref.workspaceID === location.workspaceID ref.directory === location.directory && ref.workspaceID === location.workspaceID
@@ -70,12 +74,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
ref && !isCurrentLocation(ref) ref && !isCurrentLocation(ref)
? runtime.location.agent ? runtime.location.agent
.list(ref) .list(ref)
.pipe( .pipe(Effect.map((result) => ({ ...result, data: result.data.find((agent) => agent.id === input.agentID) })))
Effect.map((result) => ({
...result,
data: result.data.find((agent) => agent.id === input.agentID),
})),
)
: response(agents.get(input.agentID)) : response(agents.get(input.agentID))
return output.pipe( return output.pipe(
Effect.flatMap((result) => Effect.flatMap((result) =>
@@ -163,7 +162,8 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
mutable(draft.model.get(Provider.ID.make(providerID), Model.ID.make(modelID))), mutable(draft.model.get(Provider.ID.make(providerID), Model.ID.make(modelID))),
update: (providerID, modelID, update) => update: (providerID, modelID, update) =>
draft.model.update(Provider.ID.make(providerID), Model.ID.make(modelID), update), draft.model.update(Provider.ID.make(providerID), Model.ID.make(modelID), update),
remove: (providerID, modelID) => draft.model.remove(Provider.ID.make(providerID), Model.ID.make(modelID)), remove: (providerID, modelID) =>
draft.model.remove(Provider.ID.make(providerID), Model.ID.make(modelID)),
default: { default: {
get: draft.model.default.get, get: draft.model.default.get,
set: (providerID, modelID) => set: (providerID, modelID) =>
@@ -192,7 +192,6 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
integration.connection.key({ integration.connection.key({
integrationID: Integration.ID.make(input.integrationID), integrationID: Integration.ID.make(input.integrationID),
key: input.key, key: input.key,
answers: input.answers,
label: input.label, label: input.label,
}), }),
}, },
@@ -202,7 +201,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
integration.oauth.connect({ integration.oauth.connect({
integrationID: Integration.ID.make(input.integrationID), integrationID: Integration.ID.make(input.integrationID),
methodID: Integration.MethodID.make(input.methodID), methodID: Integration.MethodID.make(input.methodID),
answers: input.answers, inputs: input.inputs,
label: input.label, label: input.label,
}), }),
), ),
@@ -365,14 +364,9 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
const refresh = input.refresh const refresh = input.refresh
return { return {
integrationID: Integration.ID.make(input.integrationID), integrationID: Integration.ID.make(input.integrationID),
method: Schema.decodeUnknownSync(Integration.OAuthMethod)({ method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
id: Integration.MethodID.make(input.method.id), authorize: (inputs) =>
type: "oauth", input.authorize(inputs).pipe(
label: input.method.label,
...(input.method.forms === undefined ? {} : { forms: input.method.forms }),
}),
authorize: (answers) =>
input.authorize(answers).pipe(
Effect.map((authorization) => { Effect.map((authorization) => {
if (authorization.mode === "auto") { if (authorization.mode === "auto") {
return { return {
@@ -404,11 +398,7 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
} }
return { return {
integrationID: Integration.ID.make(input.integrationID), integrationID: Integration.ID.make(input.integrationID),
method: Schema.decodeUnknownSync(Integration.KeyMethod)({ method: { type: "key", label: input.method.label },
type: "key",
...(input.method.label === undefined ? {} : { label: input.method.label }),
...(input.method.forms === undefined ? {} : { forms: input.method.forms }),
}),
} }
} }
+7 -13
View File
@@ -179,8 +179,8 @@ export function fromPromise(plugin: Plugin) {
const refresh = input.refresh const refresh = input.refresh
draft.method.update({ draft.method.update({
...input, ...input,
authorize: (answers) => authorize: (inputs) =>
Effect.promise(() => input.authorize(answers)).pipe( Effect.promise(() => input.authorize(inputs)).pipe(
Effect.map((authorization) => Effect.map((authorization) =>
authorization.mode === "auto" authorization.mode === "auto"
? { ? {
@@ -359,17 +359,11 @@ type Wire<Value> = unknown extends Value
? Value ? Value
: Value extends DateTime.DateTime : Value extends DateTime.DateTime
? number ? number
: Value extends readonly [infer Head, ...infer Tail] : Value extends ReadonlyArray<infer Item>
? [Wire<Head>, ...WireTuple<Tail>] ? Array<Wire<Item>>
: Value extends ReadonlyArray<infer Item> : Value extends object
? Array<Wire<Item>> ? { -readonly [Key in keyof Value]: Wire<Value[Key]> }
: Value extends object : Value
? { -readonly [Key in keyof Value]: Wire<Value[Key]> }
: Value
type WireTuple<Value extends ReadonlyArray<unknown>> = {
-readonly [Key in keyof Value]: Wire<Value[Key]>
}
function wire<Value>(value: Value): Wire<Value> function wire<Value>(value: Value): Wire<Value>
function wire(value: unknown): unknown { function wire(value: unknown): unknown {
@@ -1,7 +1,6 @@
import { Effect } from "effect" import { Effect } from "effect"
import { define } from "@opencode-ai/plugin/effect/plugin" import { define } from "@opencode-ai/plugin/effect/plugin"
import { Provider } from "../../provider" import { Provider } from "../../provider"
import { configuredSettings } from "./configured"
function selectLanguage(sdk: any, modelID: string, useChat: boolean) { function selectLanguage(sdk: any, modelID: string, useChat: boolean) {
if (useChat && sdk.chat) return sdk.chat(modelID) if (useChat && sdk.chat) return sdk.chat(modelID)
@@ -14,28 +13,6 @@ function selectLanguage(sdk: any, modelID: string, useChat: boolean) {
export const AzurePlugin = define({ export const AzurePlugin = define({
id: "opencode.provider.azure", id: "opencode.provider.azure",
effect: Effect.fn(function* (ctx) { effect: Effect.fn(function* (ctx) {
const configured = yield* configuredSettings(Provider.ID.azure)
yield* ctx.integration.transform((draft) => {
draft.method.update({
integrationID: Provider.ID.azure,
method: {
type: "key",
label: "API key",
forms:
resolveResourceName(configured) || typeof configured?.baseURL === "string"
? undefined
: [
{
type: "string",
key: "resourceName",
title: "Enter Azure Resource Name",
placeholder: "e.g. my-models",
required: true,
},
],
},
})
})
yield* ctx.catalog.transform((evt) => { yield* ctx.catalog.transform((evt) => {
for (const item of evt.provider.list()) { for (const item of evt.provider.list()) {
if (item.provider.id !== Provider.ID.azure && Provider.packageName(item.provider.package) !== "@ai-sdk/azure") if (item.provider.id !== Provider.ID.azure && Provider.packageName(item.provider.package) !== "@ai-sdk/azure")
@@ -2,56 +2,10 @@ import os from "os"
import { App } from "../../app" import { App } from "../../app"
import { Effect, Option, Schema } from "effect" import { Effect, Option, Schema } from "effect"
import { define } from "@opencode-ai/plugin/effect/plugin" import { define } from "@opencode-ai/plugin/effect/plugin"
import { Provider } from "../../provider"
import { configuredSettings } from "./configured"
const providerID = Provider.ID.make("cloudflare-ai-gateway")
export const CloudflareAIGatewayPlugin = define({ export const CloudflareAIGatewayPlugin = define({
id: "opencode.provider.cloudflare-ai-gateway", id: "opencode.provider.cloudflare-ai-gateway",
effect: Effect.fn(function* (ctx) { effect: Effect.fn(function* (ctx) {
const configured = yield* configuredSettings(providerID)
const hasBaseURL = typeof configured?.baseURL === "string"
yield* ctx.integration.transform((draft) => {
const hasAccountId =
hasBaseURL || Boolean(process.env.CLOUDFLARE_ACCOUNT_ID || stringOption(configured ?? {}, "accountId"))
const hasGatewayId =
hasBaseURL ||
Boolean(
process.env.CLOUDFLARE_GATEWAY_ID ||
stringOption(configured ?? {}, "gatewayId") ||
stringOption(configured ?? {}, "gateway"),
)
const accountIdForm = {
type: "string" as const,
key: "accountId",
title: "Enter your Cloudflare Account ID",
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
required: true,
}
const gatewayIdForm = {
type: "string" as const,
key: "gatewayId",
title: "Enter your Cloudflare AI Gateway ID",
placeholder: "e.g. my-gateway",
required: true,
}
draft.method.update({
integrationID: providerID,
method: {
type: "key",
label: "Gateway API token",
forms:
!hasAccountId && !hasGatewayId
? [accountIdForm, gatewayIdForm]
: !hasAccountId
? [accountIdForm]
: !hasGatewayId
? [gatewayIdForm]
: undefined,
},
})
})
yield* ctx.aisdk.hook( yield* ctx.aisdk.hook(
"sdk", "sdk",
Effect.fn(function* (evt) { Effect.fn(function* (evt) {
@@ -92,7 +46,7 @@ const decodeJson = Schema.decodeUnknownOption(Schema.UnknownFromJsonString)
function gatewayConfig(options: Record<string, unknown>): GatewayConfig | undefined { function gatewayConfig(options: Record<string, unknown>): GatewayConfig | undefined {
const accountId = process.env.CLOUDFLARE_ACCOUNT_ID ?? stringOption(options, "accountId") const accountId = process.env.CLOUDFLARE_ACCOUNT_ID ?? stringOption(options, "accountId")
// Credential projection copies key metadata into options. The form stores the // Credential projection copies key metadata into options. The prompt stores the
// gateway as gatewayId, while older config examples may use gateway. // gateway as gatewayId, while older config examples may use gateway.
const gatewayId = const gatewayId =
process.env.CLOUDFLARE_GATEWAY_ID ?? stringOption(options, "gatewayId") ?? stringOption(options, "gateway") process.env.CLOUDFLARE_GATEWAY_ID ?? stringOption(options, "gatewayId") ?? stringOption(options, "gateway")
@@ -3,35 +3,12 @@ import { App } from "../../app"
import { Effect } from "effect" import { Effect } from "effect"
import { define } from "@opencode-ai/plugin/effect/plugin" import { define } from "@opencode-ai/plugin/effect/plugin"
import { Provider } from "../../provider" import { Provider } from "../../provider"
import { configuredSettings } from "./configured"
const providerID = Provider.ID.make("cloudflare-workers-ai") const providerID = Provider.ID.make("cloudflare-workers-ai")
export const CloudflareWorkersAIPlugin = define({ export const CloudflareWorkersAIPlugin = define({
id: "opencode.provider.cloudflare-workers-ai", id: "opencode.provider.cloudflare-workers-ai",
effect: Effect.fn(function* (ctx) { effect: Effect.fn(function* (ctx) {
const configured = yield* configuredSettings(providerID)
yield* ctx.integration.transform((draft) => {
draft.method.update({
integrationID: providerID,
method: {
type: "key",
label: "API key",
forms:
typeof configured?.baseURL === "string" || resolveAccountId(configured ?? {})
? undefined
: [
{
type: "string",
key: "accountId",
title: "Enter your Cloudflare Account ID",
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
required: true,
},
],
},
})
})
yield* ctx.catalog.transform((evt) => { yield* ctx.catalog.transform((evt) => {
const item = evt.provider.get(providerID) const item = evt.provider.get(providerID)
if (!item) return if (!item) return
@@ -1,15 +0,0 @@
import { Effect, Option } from "effect"
import type { Document } from "@opencode-ai/schema/config"
import { Catalog } from "../../catalog"
import { Config } from "../../config"
import { Provider } from "../../provider"
export const configuredSettings = Effect.fn("ProviderPlugin.configuredSettings")(function* (id: Provider.ID) {
const catalog = yield* Catalog.Service
const current = (yield* catalog.provider.get(id))?.settings
const service = yield* Effect.serviceOption(Config.Service)
const entries = Option.isSome(service) ? yield* service.value.entries() : []
return entries
.filter((entry): entry is Document => entry.type === "document")
.reduce((settings, entry) => Provider.mergeOverlay(settings, entry.info.providers?.[id]?.settings), current)
})
@@ -46,33 +46,30 @@ const oauth = (app: App.Info) => ({
id: methodID, id: methodID,
type: "oauth", type: "oauth",
label: "Login with GitHub Copilot", label: "Login with GitHub Copilot",
forms: [ prompts: [
{ {
type: "string", type: "select",
key: "deploymentType", key: "deploymentType",
title: "Select GitHub deployment type", message: "Select GitHub deployment type",
required: true,
options: [ options: [
{ label: "GitHub.com", value: "github.com", description: "Public" }, { label: "GitHub.com", value: "github.com", hint: "Public" },
{ label: "GitHub Enterprise", value: "enterprise", description: "Data residency or self-hosted" }, { label: "GitHub Enterprise", value: "enterprise", hint: "Data residency or self-hosted" },
], ],
}, },
{ {
type: "string", type: "text",
key: "enterpriseUrl", key: "enterpriseUrl",
title: "Enter your GitHub Enterprise URL or domain", message: "Enter your GitHub Enterprise URL or domain",
placeholder: "company.ghe.com or https://company.ghe.com", placeholder: "company.ghe.com or https://company.ghe.com",
required: true, when: { key: "deploymentType", op: "eq", value: "enterprise" },
when: [{ key: "deploymentType", op: "eq", value: "enterprise" }],
}, },
], ],
}, },
authorize: (answers) => authorize: (inputs) =>
Effect.gen(function* () { Effect.gen(function* () {
const enterprise = answers.deploymentType === "enterprise" const enterprise = inputs.deploymentType === "enterprise"
const enterpriseUrl = typeof answers.enterpriseUrl === "string" ? answers.enterpriseUrl : undefined if (enterprise && !inputs.enterpriseUrl) return yield* Effect.fail(new Error("Enterprise URL is required"))
if (enterprise && !enterpriseUrl) return yield* Effect.fail(new Error("Enterprise URL is required")) const domain = enterprise ? normalizeDomain(inputs.enterpriseUrl ?? "") : "github.com"
const domain = enterprise ? normalizeDomain(enterpriseUrl ?? "") : "github.com"
const urls = oauthURLs(domain) const urls = oauthURLs(domain)
const device = yield* request(urls.device, { const device = yield* request(urls.device, {
method: "POST", method: "POST",
@@ -43,9 +43,9 @@ function oauth(http: HttpClient.HttpClient) {
type: "oauth", type: "oauth",
label: "OpenCode Console account", label: "OpenCode Console account",
}, },
authorize: (answers) => authorize: (inputs) =>
Effect.gen(function* () { Effect.gen(function* () {
const server = yield* normalizeServer(typeof answers.server === "string" ? answers.server : defaultServer) const server = yield* normalizeServer(inputs.server ?? defaultServer)
const device = yield* post(http, `${server}/auth/device/code`, { client_id: clientID }, Device) const device = yield* post(http, `${server}/auth/device/code`, { client_id: clientID }, Device)
const verification = URL.canParse(device.verification_uri_complete) const verification = URL.canParse(device.verification_uri_complete)
? new URL(device.verification_uri_complete) ? new URL(device.verification_uri_complete)
+4
View File
@@ -32,6 +32,7 @@ import { StepFailedError } from "../error"
import { toSessionError } from "../to-session-error" import { toSessionError } from "../to-session-error"
import { SessionRunnerRetry } from "./retry" import { SessionRunnerRetry } from "./retry"
import { SessionUsage } from "../usage" import { SessionUsage } from "../usage"
import { ToolOutput } from "../../tool-output"
/** How one model call ended: settled, awaiting a scheduled retry, or restarted by compaction. */ /** How one model call ended: settled, awaiting a scheduled retry, or restarted by compaction. */
type CallOutcome = Data.TaggedEnum<{ type CallOutcome = Data.TaggedEnum<{
@@ -107,6 +108,7 @@ const layer = Layer.effect(
const db = (yield* Database.Service).db const db = (yield* Database.Service).db
const compaction = yield* SessionCompaction.Service const compaction = yield* SessionCompaction.Service
const title = yield* SessionTitle.Service const title = yield* SessionTitle.Service
const toolOutput = yield* ToolOutput.Service
// Title generation is a side effect of a successful step; it must not delay continuation. // Title generation is a side effect of a successful step; it must not delay continuation.
// The in-flight set coalesces overlapping steps while title presence records success durably. // The in-flight set coalesces overlapping steps while title presence records success durably.
const titlesRunning = new Set<SessionSchema.ID>() const titlesRunning = new Set<SessionSchema.ID>()
@@ -334,6 +336,7 @@ const layer = Layer.effect(
).pipe( ).pipe(
// The fiber owns its call: it publishes its own completion, masked so a // The fiber owns its call: it publishes its own completion, masked so a
// finished execution always reaches its durable settlement. // finished execution always reaches its durable settlement.
Effect.flatMap(toolOutput.truncate),
Effect.flatMap((outcome) => publisher.toolExecution(event.id, event.name, outcome)), Effect.flatMap((outcome) => publisher.toolExecution(event.id, event.name, outcome)),
Effect.catchTag("Tool.Error", (error) => Effect.catchTag("Tool.Error", (error) =>
publisher.failTool(event.id, toSessionError(error)).pipe(Effect.asVoid), publisher.failTool(event.id, toSessionError(error)).pipe(Effect.asVoid),
@@ -562,6 +565,7 @@ export const node = makeLocationNode({
SessionCompaction.node, SessionCompaction.node,
SessionTitle.node, SessionTitle.node,
Snapshot.node, Snapshot.node,
ToolOutput.node,
Database.node, Database.node,
], ],
}) })
+131
View File
@@ -0,0 +1,131 @@
export * as ToolOutput from "./tool-output"
import path from "path"
import type { Tool } from "@opencode-ai/schema/tool"
import { Context, Duration, Effect, Layer, Schedule } from "effect"
import { makeGlobalNode, makeLocationNode } from "@opencode-ai/util/effect/app-node"
import { FSUtil } from "@opencode-ai/util/fs-util"
import { Global } from "@opencode-ai/util/global"
import { Config } from "./config"
import { Identifier } from "./id/id"
export const MAX_LINES = 2_000
export const MAX_BYTES = 50 * 1024 // 50 KiB
export const RETENTION = Duration.days(7)
export const DIRECTORY = "tool-output"
type Result = Tool.Result
export interface Interface {
readonly truncate: (result: Result) => Effect.Effect<Result>
readonly cleanup: () => Effect.Effect<void>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/ToolOutput") {}
const cleanup = Effect.fn("ToolOutput.cleanup")(function* (fs: FSUtil.Interface, directory: string) {
const cutoff = Identifier.timestamp(
Identifier.create("tool", "ascending", Date.now() - Duration.toMillis(RETENTION)),
)
const entries = yield* fs.readDirectory(directory).pipe(
Effect.map((entries) => entries.filter((entry) => /^tool_[0-9a-f]{12}/.test(entry))),
Effect.catch(() => Effect.succeed([])),
)
for (const entry of entries) {
if (Identifier.timestamp(entry) >= cutoff) continue
yield* fs.remove(path.join(directory, entry)).pipe(Effect.catch(() => Effect.void))
}
})
const layer = Layer.effect(
Service,
Effect.gen(function* () {
const config = yield* Config.Service
const fs = yield* FSUtil.Service
const global = yield* Global.Service
const directory = path.join(global.data, DIRECTORY)
const truncate = Effect.fn("ToolOutput.truncate")(function* (result: Result) {
if (result.metadata?.truncated !== undefined) return result
const content =
typeof result.content === "string" ? [{ type: "text" as const, text: result.content }] : (result.content ?? [])
const text = content.flatMap((item) => (item.type === "text" ? [item.text] : [])).join("\n")
const configured = Config.latest(yield* config.entries(), "tool_output")
const maxLines = configured?.max_lines ?? MAX_LINES
const maxBytes = configured?.max_bytes ?? MAX_BYTES
const lines = text.split("\n")
if (text.endsWith("\n")) lines.pop()
const totalBytes = Buffer.byteLength(text, "utf-8")
if (lines.length <= maxLines && totalBytes <= maxBytes)
return { ...result, metadata: { ...result.metadata, truncated: false } }
const kept: string[] = []
let bytes = 0
let hitBytes = false
for (const line of lines.slice(0, maxLines)) {
const size = Buffer.byteLength(line, "utf-8") + (kept.length > 0 ? 1 : 0)
if (bytes + size > maxBytes) {
hitBytes = true
break
}
kept.push(line)
bytes += size
}
if (!hitBytes && kept.length === lines.length && totalBytes > bytes) hitBytes = true
const removed = hitBytes ? totalBytes - bytes : lines.length - kept.length
const unit = hitBytes ? (removed === 1 ? "byte" : "bytes") : removed === 1 ? "line" : "lines"
const file = path.join(directory, Identifier.ascending("tool"))
yield* fs.ensureDir(directory).pipe(Effect.orDie)
yield* fs.writeFileString(file, text).pipe(Effect.orDie)
const marker = `... ${removed} ${unit} truncated; full content saved to ${file} ...`
const bounded: Tool.Content[] = []
let remaining = kept.join("\n").length
let seenText = false
let marked = false
for (const item of content) {
if (item.type === "file") {
bounded.push(item)
continue
}
if (seenText && remaining > 0) remaining--
seenText = true
if (remaining >= item.text.length) {
bounded.push(item)
remaining -= item.text.length
continue
}
if (remaining > 0) bounded.push({ ...item, text: item.text.slice(0, remaining) })
if (!marked) bounded.push({ type: "text", text: marker })
remaining = 0
marked = true
}
if (!marked) bounded.push({ type: "text", text: marker })
return {
...result,
content: bounded,
metadata: { ...result.metadata, truncated: true, outputPath: file },
}
})
return Service.of({ truncate, cleanup: () => cleanup(fs, directory) })
}),
)
const cleanupLayer = Layer.effectDiscard(
Effect.gen(function* () {
const fs = yield* FSUtil.Service
const global = yield* Global.Service
yield* cleanup(fs, path.join(global.data, DIRECTORY)).pipe(
Effect.repeat(Schedule.spaced(Duration.hours(1))),
Effect.forkScoped,
)
}),
)
const cleanupNode = makeGlobalNode({ name: "tool-output-cleanup", layer: cleanupLayer, deps: [FSUtil.node, Global.node] })
export const node = makeLocationNode({
service: Service,
layer,
deps: [Config.node, FSUtil.node, Global.node, cleanupNode],
})
+1
View File
@@ -114,6 +114,7 @@ export const Plugin = {
Effect.map((output) => ({ Effect.map((output) => ({
output, output,
content: toModelContent(input.path, input.offset, output), content: toModelContent(input.path, input.offset, output),
metadata: { truncated: output.type === "file" ? false : output.truncated },
})), })),
Effect.mapError((error) => { Effect.mapError((error) => {
if (error instanceof ToolFailure) return error if (error instanceof ToolFailure) return error
+13 -5
View File
@@ -6,6 +6,7 @@ import type { Content } from "@opencode-ai/schema/tool"
import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin" import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin"
import { Deferred, Effect, Schema, Scope } from "effect" import { Deferred, Effect, Schema, Scope } from "effect"
import { FSUtil } from "@opencode-ai/util/fs-util" import { FSUtil } from "@opencode-ai/util/fs-util"
import { Config } from "../../config"
import { LocationMutation } from "../../location-mutation" import { LocationMutation } from "../../location-mutation"
import { Permission } from "../../permission" import { Permission } from "../../permission"
import { PluginRuntime } from "../../plugin/runtime" import { PluginRuntime } from "../../plugin/runtime"
@@ -13,10 +14,10 @@ import { NonNegativeInt } from "../../schema"
import { SessionSchema } from "../../session/schema" import { SessionSchema } from "../../session/schema"
import { Shell } from "../../shell" import { Shell } from "../../shell"
import { ShellParse } from "../../shell/parse" import { ShellParse } from "../../shell/parse"
import { ToolOutput } from "../../tool-output"
export const name = "shell" export const name = "shell"
export const DEFAULT_TIMEOUT_MS = 2 * 60 * 1_000 export const DEFAULT_TIMEOUT_MS = 2 * 60 * 1_000
export const MAX_CAPTURE_BYTES = 1024 * 1024
const BACKGROUND_STARTED = "The command was moved to the background." const BACKGROUND_STARTED = "The command was moved to the background."
const BACKGROUND_INSTRUCTION = const BACKGROUND_INSTRUCTION =
@@ -86,6 +87,7 @@ export const Plugin = {
const mutation = yield* LocationMutation.Service const mutation = yield* LocationMutation.Service
const shell = yield* Shell.Service const shell = yield* Shell.Service
const permission = yield* Permission.Service const permission = yield* Permission.Service
const config = yield* Config.Service
const notifyWhenDone = Effect.fn("ShellTool.notifyWhenDone")(function* ( const notifyWhenDone = Effect.fn("ShellTool.notifyWhenDone")(function* (
sessionID: SessionSchema.ID, sessionID: SessionSchema.ID,
@@ -191,15 +193,21 @@ export const Plugin = {
yield* context.progress({ shellID: info.id }) yield* context.progress({ shellID: info.id })
const captureShell = Effect.fn("ShellTool.captureShell")(function* () { const captureShell = Effect.fn("ShellTool.captureShell")(function* () {
const configured = Config.latest(yield* config.entries(), "tool_output")
const maxLines = configured?.max_lines ?? ToolOutput.MAX_LINES
const maxBytes = configured?.max_bytes ?? ToolOutput.MAX_BYTES
const latest = yield* shell.output(info.id, { cursor: Number.MAX_SAFE_INTEGER }) const latest = yield* shell.output(info.id, { cursor: Number.MAX_SAFE_INTEGER })
const truncated = latest.size > MAX_CAPTURE_BYTES
const page = yield* shell.output(info.id, { const page = yield* shell.output(info.id, {
cursor: Math.max(0, latest.size - MAX_CAPTURE_BYTES), cursor: Math.max(0, latest.size - maxBytes),
limit: MAX_CAPTURE_BYTES, limit: maxBytes,
}) })
const lines = page.output.split("\n")
if (page.output.endsWith("\n")) lines.pop()
const truncated = latest.size > maxBytes || lines.length > maxLines
const output = lines.length > maxLines ? lines.slice(-maxLines).join("\n") : page.output
const notice = truncated ? `\n\n[output truncated; full output saved to: ${info.file}]` : "" const notice = truncated ? `\n\n[output truncated; full output saved to: ${info.file}]` : ""
return { return {
output: `${page.output || "(no output)"}${notice}`, output: `${output || "(no output)"}${notice}`,
truncated, truncated,
} }
}) })
+8 -20
View File
@@ -140,11 +140,7 @@ describe("Integration", () => {
yield* integrations.transform((editor) => yield* integrations.transform((editor) =>
editor.method.update({ editor.method.update({
integrationID, integrationID,
method: { method: { type: "key", label: "API key" },
type: "key",
label: "API key",
forms: [{ type: "string", key: "accountId", title: "Account ID", required: true }],
},
}), }),
) )
const updated = yield* bus const updated = yield* bus
@@ -152,17 +148,9 @@ describe("Integration", () => {
.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped) .pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped)
yield* Effect.yieldNow yield* Effect.yieldNow
expect(
yield* integrations.connection.key({ integrationID, key: "secret", answers: {} }).pipe(
Effect.flip,
Effect.map((error) => error.cause),
),
).toEqual(expect.objectContaining({ message: "Missing required form field: accountId" }))
yield* integrations.connection.key({ yield* integrations.connection.key({
integrationID, integrationID,
key: "secret", key: "secret",
answers: { accountId: "account" },
label: "Work", label: "Work",
}) })
@@ -170,7 +158,7 @@ describe("Integration", () => {
expect.objectContaining({ expect.objectContaining({
integrationID, integrationID,
label: "Work", label: "Work",
value: Credential.Key.make({ type: "key", key: "secret", configuration: { accountId: "account" } }), value: Credential.Key.make({ type: "key", key: "secret" }),
}), }),
]) ])
expect((yield* Fiber.join(updated)).length).toBe(1) expect((yield* Fiber.join(updated)).length).toBe(1)
@@ -255,7 +243,7 @@ describe("Integration", () => {
const attempt = yield* integrations.oauth.connect({ const attempt = yield* integrations.oauth.connect({
integrationID, integrationID,
methodID, methodID,
answers: {}, inputs: {},
label: "Personal", label: "Personal",
}) })
expect(attempt.mode).toBe("code") expect(attempt.mode).toBe("code")
@@ -301,7 +289,7 @@ describe("Integration", () => {
}), }),
) )
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, answers: {} }) const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
expect( expect(
yield* integrations.oauth.complete({ integrationID, attemptID: attempt.attemptID }).pipe(Effect.flip), yield* integrations.oauth.complete({ integrationID, attemptID: attempt.attemptID }).pipe(Effect.flip),
).toBeInstanceOf(Integration.CodeRequiredError) ).toBeInstanceOf(Integration.CodeRequiredError)
@@ -339,7 +327,7 @@ describe("Integration", () => {
}), }),
) )
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, answers: {} }) const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
yield* Effect.yieldNow yield* Effect.yieldNow
expect(yield* integrations.oauth.status({ integrationID, attemptID: attempt.attemptID })).toEqual({ expect(yield* integrations.oauth.status({ integrationID, attemptID: attempt.attemptID })).toEqual({
status: "complete", status: "complete",
@@ -377,7 +365,7 @@ describe("Integration", () => {
}), }),
) )
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, answers: {} }) const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
const exit = yield* integrations.oauth const exit = yield* integrations.oauth
.complete({ integrationID, attemptID: attempt.attemptID, code: "1234" }) .complete({ integrationID, attemptID: attempt.attemptID, code: "1234" })
.pipe(Effect.exit) .pipe(Effect.exit)
@@ -413,7 +401,7 @@ describe("Integration", () => {
}), }),
) )
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, answers: {} }) const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
expect(attempt.time.expires - attempt.time.created).toBe(Duration.toMillis(Duration.minutes(10))) expect(attempt.time.expires - attempt.time.created).toBe(Duration.toMillis(Duration.minutes(10)))
yield* TestClock.adjust(Duration.minutes(10)) yield* TestClock.adjust(Duration.minutes(10))
yield* Effect.yieldNow yield* Effect.yieldNow
@@ -454,7 +442,7 @@ describe("Integration", () => {
}), }),
) )
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, answers: {} }) const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
expect(attempt.time).toEqual({ created, expires: expiresAt }) expect(attempt.time).toEqual({ created, expires: expiresAt })
}) })
}) })
+2 -6
View File
@@ -736,11 +736,7 @@ describe("ModelResolver", () => {
headers: { "x-aisdk": "header" }, headers: { "x-aisdk": "header" },
body: { custom: true }, body: { custom: true },
}), }),
Credential.Key.make({ Credential.Key.make({ type: "key", key: "fallback-secret" }),
type: "key",
key: "fallback-secret",
configuration: { accountId: "account" },
}),
{ {
loadAISDK: (runtime) => loadAISDK: (runtime) =>
Effect.sync(() => { Effect.sync(() => {
@@ -749,7 +745,7 @@ describe("ModelResolver", () => {
modelID: "mistral-api-model", modelID: "mistral-api-model",
providerID: "test-provider", providerID: "test-provider",
package: Provider.aisdk("@ai-sdk/mistral"), package: Provider.aisdk("@ai-sdk/mistral"),
settings: { project: "test", apiKey: "fallback-secret", accountId: "account" }, settings: { project: "test", apiKey: "fallback-secret" },
headers: { "x-aisdk": "header" }, headers: { "x-aisdk": "header" },
body: { custom: true }, body: { custom: true },
}) })
+21 -46
View File
@@ -10,7 +10,7 @@ import { Project } from "@opencode-ai/core/project"
import { Provider } from "@opencode-ai/core/provider" import { Provider } from "@opencode-ai/core/provider"
import { AbsolutePath } from "@opencode-ai/core/schema" import { AbsolutePath } from "@opencode-ai/core/schema"
import { WebSearch } from "@opencode-ai/core/websearch" import { WebSearch } from "@opencode-ai/core/websearch"
import { Effect, Schema, Stream } from "effect" import { Effect, Stream } from "effect"
type Overrides = Partial<Omit<Plugin.Context, "options" | "session">> & { type Overrides = Partial<Omit<Plugin.Context, "options" | "session">> & {
readonly session?: Partial<Plugin.Context["session"]> readonly session?: Partial<Plugin.Context["session"]>
@@ -226,7 +226,8 @@ export function catalogHost(catalog: Catalog.Interface): Plugin.Context["catalog
})), })),
}) })
}), }),
remove: (providerID, modelID) => draft.model.remove(Provider.ID.make(providerID), Model.ID.make(modelID)), remove: (providerID, modelID) =>
draft.model.remove(Provider.ID.make(providerID), Model.ID.make(modelID)),
default: { default: {
get: () => { get: () => {
const value = draft.model.default.get() const value = draft.model.default.get()
@@ -285,9 +286,9 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
const refresh = input.refresh const refresh = input.refresh
draft.method.update({ draft.method.update({
integrationID: Integration.ID.make(input.integrationID), integrationID: Integration.ID.make(input.integrationID),
method: oauthMethod(input.method, methodID), method: { ...input.method, id: methodID },
authorize: (answers) => authorize: (inputs) =>
input.authorize(answers).pipe( input.authorize(inputs).pipe(
Effect.map((authorization) => { Effect.map((authorization) => {
if (authorization.mode === "auto") { if (authorization.mode === "auto") {
return { return {
@@ -353,7 +354,7 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
} }
draft.method.update({ draft.method.update({
integrationID: Integration.ID.make(input.integrationID), integrationID: Integration.ID.make(input.integrationID),
method: keyMethod(input.method), method: input.method,
}) })
}, },
remove: (id, item) => draft.method.remove(Integration.ID.make(id), internalMethod(item)), remove: (id, item) => draft.method.remove(Integration.ID.make(id), internalMethod(item)),
@@ -401,21 +402,26 @@ function oauthCredential(value: Credential.OAuth) {
return Credential.OAuth.make({ ...value, methodID: Integration.MethodID.make(value.methodID) }) return Credential.OAuth.make({ ...value, methodID: Integration.MethodID.make(value.methodID) })
} }
function method(value: Integration.Method): IntegrationMethodRegistration["method"] { function method(value: Integration.Method) {
if (value.type === "env") return { type: value.type, names: [...value.names] } if (value.type === "env") return { type: value.type, names: [...value.names] }
if (value.type === "key") return { type: value.type, label: value.label, forms: mutable(value.forms) } if (value.type === "key") return { type: value.type, label: value.label }
if (value.type === "command") return { ...value, command: [...value.command] } if (value.type === "command") return { ...value, command: [...value.command] }
return { return {
type: value.type, type: value.type,
id: value.id, id: value.id,
label: value.label, label: value.label,
forms: mutable(value.forms), prompts: value.prompts?.map((prompt) => {
if (prompt.type === "text") return { ...prompt }
return { ...prompt, options: prompt.options.map((option) => ({ ...option })) }
}),
} }
} }
function internalMethod(value: IntegrationMethodRegistration["method"]): Integration.Method { function internalMethod(
value: IntegrationMethodRegistration["method"],
): Integration.Method {
if (value.type === "env") return value if (value.type === "env") return value
if (value.type === "key") return keyMethod(value) if (value.type === "key") return value
if (value.type === "command") { if (value.type === "command") {
return { return {
...value, ...value,
@@ -423,41 +429,10 @@ function internalMethod(value: IntegrationMethodRegistration["method"]): Integra
command: [...value.command], command: [...value.command],
} }
} }
return oauthMethod(value, Integration.MethodID.make(value.id)) return {
} ...value,
id: Integration.MethodID.make(value.id),
type Mutable<Value> = Value extends readonly [infer Head, ...infer Tail] }
? [Mutable<Head>, ...MutableTuple<Tail>]
: Value extends ReadonlyArray<infer Item>
? Array<Mutable<Item>>
: Value extends object
? { -readonly [Key in keyof Value]: Mutable<Value[Key]> }
: Value
type MutableTuple<Value extends ReadonlyArray<unknown>> = {
-readonly [Key in keyof Value]: Mutable<Value[Key]>
}
function mutable<Value>(value: Value): Mutable<Value>
function mutable(value: unknown): unknown {
return structuredClone(value)
}
function keyMethod(value: IntegrationMethodRegistration["method"] & { type: "key" }) {
return Schema.decodeUnknownSync(Integration.KeyMethod)({
type: "key",
...(value.label === undefined ? {} : { label: value.label }),
...(value.forms === undefined ? {} : { forms: value.forms }),
})
}
function oauthMethod(value: IntegrationMethodRegistration["method"] & { type: "oauth" }, id: Integration.MethodID) {
return Schema.decodeUnknownSync(Integration.OAuthMethod)({
id,
type: "oauth",
label: value.label,
...(value.forms === undefined ? {} : { forms: value.forms }),
})
} }
function agentInfo(value: Agent.Info) { function agentInfo(value: Agent.Info) {
@@ -8,7 +8,6 @@ import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHost } from "@opencode-ai/core/plugin/host" import { PluginHost } from "@opencode-ai/core/plugin/host"
import { AzurePlugin } from "@opencode-ai/core/plugin/provider/azure" import { AzurePlugin } from "@opencode-ai/core/plugin/provider/azure"
import { Provider } from "@opencode-ai/core/provider" import { Provider } from "@opencode-ai/core/provider"
import { Integration } from "@opencode-ai/core/integration"
import { testEffect } from "../lib/effect" import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture" import { PluginTestLayer } from "./fixture"
@@ -61,27 +60,6 @@ function fakeSelectorSdk(calls: string[]) {
} }
describe("AzurePlugin", () => { describe("AzurePlugin", () => {
it.effect("registers a resource name form when the environment does not provide one", () =>
withEnv({ AZURE_RESOURCE_NAME: undefined, AZURE_COGNITIVE_SERVICES_RESOURCE_NAME: undefined }, () =>
Effect.gen(function* () {
yield* addPlugin()
expect((yield* (yield* Integration.Service).get(Integration.ID.make("azure")))?.methods).toContainEqual({
type: "key",
label: "API key",
forms: [
{
type: "string",
key: "resourceName",
title: "Enter Azure Resource Name",
placeholder: "e.g. my-models",
required: true,
},
],
})
}),
),
)
it.effect("resolves resourceName from env", () => it.effect("resolves resourceName from env", () =>
withEnv({ AZURE_RESOURCE_NAME: "from-env" }, () => withEnv({ AZURE_RESOURCE_NAME: "from-env" }, () =>
Effect.gen(function* () { Effect.gen(function* () {
@@ -217,17 +195,7 @@ describe("AzurePlugin", () => {
Effect.gen(function* () { Effect.gen(function* () {
const plugin = yield* Plugin.Service const plugin = yield* Plugin.Service
const aisdk = yield* AISDK.Service const aisdk = yield* AISDK.Service
const catalog = yield* Catalog.Service
yield* catalog.transform((catalog) =>
catalog.provider.update(Provider.ID.azure, (provider) => {
provider.settings = { ...provider.settings, baseURL: "https://proxy.example.com/openai" }
}),
)
yield* addPlugin() yield* addPlugin()
expect((yield* (yield* Integration.Service).get(Integration.ID.make("azure")))?.methods).toContainEqual({
type: "key",
label: "API key",
})
const result = yield* aisdk.runSDK({ const result = yield* aisdk.runSDK({
model: Model.Info.make({ model: Model.Info.make({
...Model.Info.default(Provider.ID.azure, Model.ID.make("deployment")), ...Model.Info.default(Provider.ID.azure, Model.ID.make("deployment")),
@@ -1,13 +1,11 @@
import { AISDK } from "@opencode-ai/core/aisdk" import { AISDK } from "@opencode-ai/core/aisdk"
import { describe, expect, mock } from "bun:test" import { describe, expect, mock } from "bun:test"
import { Effect } from "effect" import { Effect } from "effect"
import { Catalog } from "@opencode-ai/core/catalog"
import { Model } from "@opencode-ai/core/model" import { Model } from "@opencode-ai/core/model"
import { Plugin } from "@opencode-ai/core/plugin" import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHost } from "@opencode-ai/core/plugin/host" import { PluginHost } from "@opencode-ai/core/plugin/host"
import { CloudflareAIGatewayPlugin } from "@opencode-ai/core/plugin/provider/cloudflare-ai-gateway" import { CloudflareAIGatewayPlugin } from "@opencode-ai/core/plugin/provider/cloudflare-ai-gateway"
import { Provider } from "@opencode-ai/core/provider" import { Provider } from "@opencode-ai/core/provider"
import { Integration } from "@opencode-ai/core/integration"
import { testEffect } from "../lib/effect" import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture" import { PluginTestLayer } from "./fixture"
@@ -104,24 +102,6 @@ mock.module("ai-gateway-provider/providers/unified", () => ({
})) }))
describe("CloudflareAIGatewayPlugin", () => { describe("CloudflareAIGatewayPlugin", () => {
it.effect("registers account and gateway forms when the environment does not provide them", () =>
withEnv({ CLOUDFLARE_ACCOUNT_ID: undefined, CLOUDFLARE_GATEWAY_ID: undefined }, () =>
Effect.gen(function* () {
yield* addPlugin()
expect(
(yield* (yield* Integration.Service).get(Integration.ID.make("cloudflare-ai-gateway")))?.methods,
).toContainEqual({
type: "key",
label: "Gateway API token",
forms: [
expect.objectContaining({ type: "string", key: "accountId", required: true }),
expect.objectContaining({ type: "string", key: "gatewayId", required: true }),
],
})
}),
),
)
it.effect("requires account, gateway, and token before creating the unified SDK", () => it.effect("requires account, gateway, and token before creating the unified SDK", () =>
withEnv( withEnv(
{ {
@@ -377,16 +357,7 @@ describe("CloudflareAIGatewayPlugin", () => {
resetCalls() resetCalls()
const plugin = yield* Plugin.Service const plugin = yield* Plugin.Service
const aisdk = yield* AISDK.Service const aisdk = yield* AISDK.Service
const catalog = yield* Catalog.Service
yield* catalog.transform((catalog) =>
catalog.provider.update(Provider.ID.make("cloudflare-ai-gateway"), (provider) => {
provider.settings = { ...provider.settings, baseURL: "https://proxy.example/v1" }
}),
)
yield* addPlugin() yield* addPlugin()
expect(
(yield* (yield* Integration.Service).get(Integration.ID.make("cloudflare-ai-gateway")))?.methods,
).toContainEqual({ type: "key", label: "Gateway API token" })
const result = yield* aisdk.runSDK({ const result = yield* aisdk.runSDK({
model: Model.Info.make({ model: Model.Info.make({
@@ -7,7 +7,6 @@ import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHost } from "@opencode-ai/core/plugin/host" import { PluginHost } from "@opencode-ai/core/plugin/host"
import { CloudflareWorkersAIPlugin } from "@opencode-ai/core/plugin/provider/cloudflare-workers-ai" import { CloudflareWorkersAIPlugin } from "@opencode-ai/core/plugin/provider/cloudflare-workers-ai"
import { Provider } from "@opencode-ai/core/provider" import { Provider } from "@opencode-ai/core/provider"
import { Integration } from "@opencode-ai/core/integration"
import type { LanguageModelV3 } from "@ai-sdk/provider" import type { LanguageModelV3 } from "@ai-sdk/provider"
import { testEffect } from "../lib/effect" import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture" import { PluginTestLayer } from "./fixture"
@@ -80,29 +79,6 @@ function cloudflareHeaders(sdk: unknown, modelID = "@cf/model") {
} }
describe("CloudflareWorkersAIPlugin", () => { describe("CloudflareWorkersAIPlugin", () => {
it.effect("registers an account form when the environment does not provide one", () =>
withEnv({ CLOUDFLARE_ACCOUNT_ID: undefined }, () =>
Effect.gen(function* () {
yield* addPlugin()
expect(
(yield* (yield* Integration.Service).get(Integration.ID.make("cloudflare-workers-ai")))?.methods,
).toContainEqual({
type: "key",
label: "API key",
forms: [
{
type: "string",
key: "accountId",
title: "Enter your Cloudflare Account ID",
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
required: true,
},
],
})
}),
),
)
it.effect("maps account ID to endpoint URL and creates an OpenAI-compatible SDK", () => it.effect("maps account ID to endpoint URL and creates an OpenAI-compatible SDK", () =>
withEnv({ CLOUDFLARE_ACCOUNT_ID: "acct", CLOUDFLARE_API_KEY: "key" }, () => withEnv({ CLOUDFLARE_ACCOUNT_ID: "acct", CLOUDFLARE_API_KEY: "key" }, () =>
Effect.gen(function* () { Effect.gen(function* () {
@@ -115,9 +91,6 @@ describe("CloudflareWorkersAIPlugin", () => {
}), }),
) )
yield* addPlugin() yield* addPlugin()
expect(
(yield* (yield* Integration.Service).get(Integration.ID.make("cloudflare-workers-ai")))?.methods,
).toContainEqual({ type: "key", label: "API key" })
const provider = required(yield* catalog.provider.get(Provider.ID.make("cloudflare-workers-ai"))) const provider = required(yield* catalog.provider.get(Provider.ID.make("cloudflare-workers-ai")))
const sdk = yield* aisdk.runSDK({ const sdk = yield* aisdk.runSDK({
model: Model.Info.make({ model: Model.Info.make({
@@ -162,16 +135,7 @@ describe("CloudflareWorkersAIPlugin", () => {
Effect.gen(function* () { Effect.gen(function* () {
const plugin = yield* Plugin.Service const plugin = yield* Plugin.Service
const aisdk = yield* AISDK.Service const aisdk = yield* AISDK.Service
const catalog = yield* Catalog.Service
yield* catalog.transform((catalog) =>
catalog.provider.update(Provider.ID.make("cloudflare-workers-ai"), (provider) => {
provider.settings = { ...provider.settings, baseURL: "https://proxy.example/v1" }
}),
)
yield* addPlugin() yield* addPlugin()
expect(
(yield* (yield* Integration.Service).get(Integration.ID.make("cloudflare-workers-ai")))?.methods,
).toContainEqual({ type: "key", label: "API key" })
const result = yield* aisdk.runSDK({ const result = yield* aisdk.runSDK({
model: Model.Info.make({ model: Model.Info.make({
...Model.Info.default(Provider.ID.make("cloudflare-workers-ai"), Model.ID.make("@cf/model")), ...Model.Info.default(Provider.ID.make("cloudflare-workers-ai"), Model.ID.make("@cf/model")),
@@ -57,7 +57,7 @@ describe("GithubCopilotPlugin", () => {
id: Integration.MethodID.make("device"), id: Integration.MethodID.make("device"),
type: "oauth", type: "oauth",
label: "Login with GitHub Copilot", label: "Login with GitHub Copilot",
forms: expect.any(Array), prompts: expect.any(Array),
}) })
}), }),
) )
@@ -128,7 +128,7 @@ describe("OpencodePlugin", () => {
const attempt = yield* integrations.oauth.connect({ const attempt = yield* integrations.oauth.connect({
integrationID, integrationID,
methodID: Integration.MethodID.make("device"), methodID: Integration.MethodID.make("device"),
answers: { server: `${server.url.origin}/console///?ignored=true#ignored` }, inputs: { server: `${server.url.origin}/console///?ignored=true#ignored` },
}) })
expect(attempt.url).toBe(`${server.url.origin}/verify`) expect(attempt.url).toBe(`${server.url.origin}/verify`)
yield* eventually( yield* eventually(
@@ -155,7 +155,7 @@ describe("OpencodePlugin", () => {
.connect({ .connect({
integrationID: Integration.ID.make("opencode"), integrationID: Integration.ID.make("opencode"),
methodID: Integration.MethodID.make("device"), methodID: Integration.MethodID.make("device"),
answers: { server: "ftp://console.example.com" }, inputs: { server: "ftp://console.example.com" },
}) })
.pipe(Effect.flip) .pipe(Effect.flip)
expect(error).toBeInstanceOf(Integration.AuthorizationError) expect(error).toBeInstanceOf(Integration.AuthorizationError)
+2 -6
View File
@@ -67,7 +67,7 @@ describe("built-in web search providers", () => {
name: "Exa", name: "Exa",
methods: [{ type: "key" }, { type: "env", names: ["EXA_API_KEY"] }], methods: [{ type: "key" }, { type: "env", names: ["EXA_API_KEY"] }],
}) })
yield* integrations.connection.key({ integrationID: Integration.ID.make("exa"), key: "exa secret", answers: {} }) yield* integrations.connection.key({ integrationID: Integration.ID.make("exa"), key: "exa secret" })
expect(yield* websearch.query({ query: "effect typescript", providerID: WebSearch.ID.make("exa") })).toEqual( expect(yield* websearch.query({ query: "effect typescript", providerID: WebSearch.ID.make("exa") })).toEqual(
new WebSearch.Response({ new WebSearch.Response({
providerID: WebSearch.ID.make("exa"), providerID: WebSearch.ID.make("exa"),
@@ -129,11 +129,7 @@ describe("built-in web search providers", () => {
yield* WebSearchParallel.Plugin.effect( yield* WebSearchParallel.Plugin.effect(
host({ integration: integrationHost(integrations), websearch: webSearchHost(websearch) }), host({ integration: integrationHost(integrations), websearch: webSearchHost(websearch) }),
) )
yield* integrations.connection.key({ yield* integrations.connection.key({ integrationID: Integration.ID.make("parallel"), key: "parallel-secret" })
integrationID: Integration.ID.make("parallel"),
key: "parallel-secret",
answers: {},
})
const output = yield* websearch.query({ const output = yield* websearch.query({
query: "effect layers", query: "effect layers",
+5
View File
@@ -90,10 +90,15 @@ test("Core reuses the canonical shared schemas", async () => {
[coreFileSystem.Match, FileSystem.Match], [coreFileSystem.Match, FileSystem.Match],
[coreIntegration.ID, Integration.ID], [coreIntegration.ID, Integration.ID],
[coreIntegration.MethodID, Integration.MethodID], [coreIntegration.MethodID, Integration.MethodID],
[coreIntegration.When, Integration.When],
[coreIntegration.TextPrompt, Integration.TextPrompt],
[coreIntegration.SelectPrompt, Integration.SelectPrompt],
[coreIntegration.Prompt, Integration.Prompt],
[coreIntegration.OAuthMethod, Integration.OAuthMethod], [coreIntegration.OAuthMethod, Integration.OAuthMethod],
[coreIntegration.KeyMethod, Integration.KeyMethod], [coreIntegration.KeyMethod, Integration.KeyMethod],
[coreIntegration.EnvMethod, Integration.EnvMethod], [coreIntegration.EnvMethod, Integration.EnvMethod],
[coreIntegration.Method, Integration.Method], [coreIntegration.Method, Integration.Method],
[coreIntegration.Inputs, Integration.Inputs],
[coreIntegration.Ref, Integration.Ref], [coreIntegration.Ref, Integration.Ref],
[coreLocation.Ref, Location.Ref], [coreLocation.Ref, Location.Ref],
[coreAI.ProviderMetadata, AI.ProviderMetadata], [coreAI.ProviderMetadata, AI.ProviderMetadata],
+164
View File
@@ -0,0 +1,164 @@
import { describe, expect } from "bun:test"
import path from "path"
import { Effect, Layer, Stream } from "effect"
import { Config } from "@opencode-ai/core/config"
import { Document, Info } from "@opencode-ai/schema/config"
import { ConfigToolOutput } from "@opencode-ai/schema/config/tool-output"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
import { ToolOutput } from "@opencode-ai/core/tool-output"
import { FSUtil } from "@opencode-ai/util/fs-util"
import { Global } from "@opencode-ai/util/global"
import { Identifier } from "@opencode-ai/core/id/id"
import { tmpdir } from "./fixture/tmpdir"
import { it } from "./lib/effect"
const withStore = <A, E, R>(
body: (output: ToolOutput.Interface, fs: FSUtil.Interface, root: string) => Effect.Effect<A, E, R>,
info = new Info(),
) =>
Effect.acquireUseRelease(
Effect.promise(() => tmpdir()),
(tmp) => {
const config = Layer.succeed(
Config.Service,
Config.Service.of({
entries: () => Effect.succeed([new Document({ type: "document", info })]),
changes: () => Stream.empty,
}),
)
const layer = AppNodeBuilder.build(LayerNode.group([ToolOutput.node, FSUtil.node]), [
[Config.node, config],
[Global.node, Global.layerWith({ data: tmp.path })],
])
return Effect.gen(function* () {
return yield* body(yield* ToolOutput.Service, yield* FSUtil.Service, tmp.path)
}).pipe(Effect.provide(layer))
},
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
)
describe("ToolOutput", () => {
it.live("writes oversized text and returns a bounded preview", () =>
withStore(
(service, fs) =>
Effect.gen(function* () {
const output = { items: [1, 2, 3] }
const result = yield* service.truncate({ output, content: "one\ntwo\nthree" })
expect(result.output).toBe(output)
expect(result.metadata).toMatchObject({ truncated: true })
const outputPath = result.metadata?.outputPath
expect(typeof outputPath).toBe("string")
if (typeof outputPath !== "string") return
expect(yield* fs.readFileString(outputPath)).toBe("one\ntwo\nthree")
expect(result.content).toEqual([
{ type: "text", text: "one\ntwo" },
{ type: "text", text: `... 1 line truncated; full content saved to ${outputPath} ...` },
])
}),
new Info({ tool_output: new ConfigToolOutput.Info({ max_lines: 2, max_bytes: 1_000 }) }),
),
)
it.live("reports bytes omitted by the byte limit", () =>
withStore(
(output) =>
Effect.gen(function* () {
const result = yield* output.truncate({ content: "one\ntwo" })
expect(result.content).toEqual([
{ type: "text", text: "one" },
{
type: "text",
text: expect.stringMatching(/^\.\.\. 4 bytes truncated; full content saved to .+ \.\.\.$/),
},
])
}),
new Info({ tool_output: new ConfigToolOutput.Info({ max_lines: 100, max_bytes: 5 }) }),
),
)
it.live("preserves mixed content ordering", () =>
withStore(
(output) =>
Effect.gen(function* () {
const file = { type: "file" as const, uri: "file:///image.png", mime: "image/png" }
const result = yield* output.truncate({
content: [{ type: "text", text: "before" }, file, { type: "text", text: "after\nomitted" }],
})
expect(result.content).toEqual([
{ type: "text", text: "before" },
file,
{ type: "text", text: "after" },
{ type: "text", text: expect.stringMatching(/^\.\.\. 1 line truncated; full content saved to /) },
])
}),
new Info({ tool_output: new ConfigToolOutput.Info({ max_lines: 2, max_bytes: 1_000 }) }),
),
)
it.live("skips results that report a truncation state", () =>
withStore((output) =>
Effect.gen(function* () {
const truncated = { content: "one\ntwo", metadata: { truncated: true, source: "tool" } }
const retained = { content: "one\ntwo", metadata: { truncated: false, source: "tool" } }
expect(yield* output.truncate(truncated)).toBe(truncated)
expect(yield* output.truncate(retained)).toBe(retained)
}),
),
)
it.live("marks results that fit without changing their content", () =>
withStore((output) =>
Effect.gen(function* () {
const content = [{ type: "text" as const, text: "small" }]
expect(yield* output.truncate({ content })).toEqual({ content, metadata: { truncated: false } })
}),
),
)
it.live("does not count a trailing newline as another line", () =>
withStore(
(output) =>
Effect.gen(function* () {
expect(yield* output.truncate({ content: "one\ntwo\n" })).toEqual({
content: "one\ntwo\n",
metadata: { truncated: false },
})
}),
new Info({ tool_output: new ConfigToolOutput.Info({ max_lines: 2, max_bytes: 1_000 }) }),
),
)
it.live("reports a trailing newline omitted by the byte limit", () =>
withStore(
(output) =>
Effect.gen(function* () {
const result = yield* output.truncate({ content: "one\n" })
expect(result.content).toEqual([
{ type: "text", text: "one" },
{ type: "text", text: expect.stringMatching(/^\.\.\. 1 byte truncated; full content saved to /) },
])
}),
new Info({ tool_output: new ConfigToolOutput.Info({ max_lines: 2, max_bytes: 3 }) }),
),
)
it.live("removes expired managed files", () =>
withStore((output, fs, root) =>
Effect.gen(function* () {
const directory = path.join(root, ToolOutput.DIRECTORY)
const old = path.join(
directory,
Identifier.create("tool", "ascending", Date.now() - 8 * 24 * 60 * 60 * 1_000),
)
const recent = path.join(directory, Identifier.ascending("tool"))
yield* fs.ensureDir(directory)
yield* fs.writeFileString(old, "old")
yield* fs.writeFileString(recent, "recent")
yield* output.cleanup()
expect(yield* fs.exists(old)).toBe(false)
expect(yield* fs.exists(recent)).toBe(true)
}),
),
)
})
+3 -3
View File
@@ -311,9 +311,7 @@ describe("ReadTool", () => {
}) })
expect(settled.status).toBe("completed") expect(settled.status).toBe("completed")
if (settled.status !== "completed") return if (settled.status !== "completed") return
// Image base64 is carried by the content file item only; read produces no expect(settled.metadata).toEqual({ truncated: false })
// metadata, so the original bytes are never persisted twice.
expect(settled.metadata).toBeUndefined()
expect(settled.content).toMatchObject([ expect(settled.content).toMatchObject([
{ type: "text", text: "Image read successfully" }, { type: "text", text: "Image read successfully" },
{ type: "file", mime: "image/png", uri: `data:image/png;base64,${png}` }, { type: "file", mime: "image/png", uri: `data:image/png;base64,${png}` },
@@ -731,6 +729,7 @@ describe("ReadTool", () => {
output: { entries: listResult.entries, truncated: true, next: 4 }, output: { entries: listResult.entries, truncated: true, next: 4 },
}) })
if (result.status !== "completed") return if (result.status !== "completed") return
expect(result.metadata).toEqual({ truncated: true })
expect(result.content).toEqual([ expect(result.content).toEqual([
{ {
type: "text", type: "text",
@@ -805,6 +804,7 @@ describe("ReadTool", () => {
output: { type: "text-page", content: "hello", mime: "text/plain", offset: 2, truncated: true, next: 3 }, output: { type: "text-page", content: "hello", mime: "text/plain", offset: 2, truncated: true, next: 3 },
}) })
if (result.status !== "completed") return if (result.status !== "completed") return
expect(result.metadata).toEqual({ truncated: true })
expect(result.content).toEqual([ expect(result.content).toEqual([
{ {
type: "text", type: "text",
+33 -2
View File
@@ -30,6 +30,7 @@ import { PluginRuntime } from "@opencode-ai/core/plugin/runtime"
import { Shell } from "@opencode-ai/core/shell" import { Shell } from "@opencode-ai/core/shell"
import { Shell as ShellSchema } from "@opencode-ai/schema/shell" import { Shell as ShellSchema } from "@opencode-ai/schema/shell"
import { ShellTool } from "@opencode-ai/core/tool/plugin/shell" import { ShellTool } from "@opencode-ai/core/tool/plugin/shell"
import { ToolOutput } from "@opencode-ai/core/tool-output"
import { Tool } from "@opencode-ai/core/tool" import { Tool } from "@opencode-ai/core/tool"
import { tmpdir } from "./fixture/tmpdir" import { tmpdir } from "./fixture/tmpdir"
import { testEffect } from "./lib/effect" import { testEffect } from "./lib/effect"
@@ -171,6 +172,9 @@ const overflowCommand = (bytes: number) =>
isWindows isWindows
? `[Console]::Out.Write('output-start' + ('x' * ${bytes}) + 'output-end'); Start-Sleep -Milliseconds 100` ? `[Console]::Out.Write('output-start' + ('x' * ${bytes}) + 'output-end'); Start-Sleep -Milliseconds 100`
: `printf output-start; head -c ${bytes} /dev/zero | tr '\\0' 'x'; printf output-end` : `printf output-start; head -c ${bytes} /dev/zero | tr '\\0' 'x'; printf output-end`
const lineOverflowCommand = isWindows
? "[Console]::Out.Write('one' + [Environment]::NewLine + 'two' + [Environment]::NewLine + 'three')"
: "printf 'one\\ntwo\\nthree'"
const progressOverflowCommand = (bytes: number, release: string) => const progressOverflowCommand = (bytes: number, release: string) =>
isWindows isWindows
? `[Console]::Out.Write(('x' * ${bytes})); while (!(Test-Path -LiteralPath '${release}')) { Start-Sleep -Milliseconds 50 }` ? `[Console]::Out.Write(('x' * ${bytes})); while (!(Test-Path -LiteralPath '${release}')) { Start-Sleep -Milliseconds 50 }`
@@ -477,7 +481,7 @@ describe("ShellTool", () => {
Effect.promise(() => tmpdir()), Effect.promise(() => tmpdir()),
(tmp) => { (tmp) => {
reset() reset()
const bytes = ShellTool.MAX_CAPTURE_BYTES + 1024 const bytes = ToolOutput.MAX_BYTES + 1024
return withSession(tmp.path, (registry) => return withSession(tmp.path, (registry) =>
executeTool(registry, call({ command: overflowCommand(bytes) }, "call-overflow")), executeTool(registry, call({ command: overflowCommand(bytes) }, "call-overflow")),
).pipe( ).pipe(
@@ -501,6 +505,33 @@ describe("ShellTool", () => {
{ timeout: 15_000 }, { timeout: 15_000 },
) )
it.live("uses configured line limits", () =>
Effect.acquireUseRelease(
Effect.promise(() => tmpdir()),
(tmp) => {
reset()
return Effect.gen(function* () {
yield* Effect.promise(() =>
Bun.write(
path.join(tmp.path, "opencode.json"),
JSON.stringify({ tool_output: { max_lines: 2, max_bytes: 1_000 } }),
),
)
const settled = yield* withSession(tmp.path, (registry) =>
executeTool(registry, call({ command: lineOverflowCommand }, "call-line-overflow")),
)
expect(settled.metadata).toMatchObject({ exit: 0, truncated: true })
const content = settled.content?.[0]
if (!content || content.type !== "text") throw new Error("Expected text content")
expect(content.text).not.toContain("one")
expect(content.text).toStartWith("two\nthree")
expect(content.text).toContain("output truncated; full output saved to:")
})
},
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
),
)
it.live( it.live(
"reports the shell ID for a running command", "reports the shell ID for a running command",
() => () =>
@@ -515,7 +546,7 @@ describe("ShellTool", () => {
const observed = yield* Deferred.make<string>() const observed = yield* Deferred.make<string>()
yield* executeTool(registry, { yield* executeTool(registry, {
...call( ...call(
{ command: progressOverflowCommand(ShellTool.MAX_CAPTURE_BYTES + 1024, release) }, { command: progressOverflowCommand(ToolOutput.MAX_BYTES + 1024, release) },
"call-progress", "call-progress",
), ),
progress: (update) => progress: (update) =>
+2 -2
View File
@@ -8,10 +8,10 @@ import type {
} from "@opencode-ai/client" } from "@opencode-ai/client"
import type { IntegrationApi } from "@opencode-ai/client/effect/api" import type { IntegrationApi } from "@opencode-ai/client/effect/api"
import { Credential } from "@opencode-ai/schema/credential" import { Credential } from "@opencode-ai/schema/credential"
import { Form } from "@opencode-ai/schema/form"
import type { Effect, Scope } from "effect" import type { Effect, Scope } from "effect"
import type { Transform } from "./registration.js" import type { Transform } from "./registration.js"
type IntegrationInputs = Record<string, string>
type IntegrationRef = { id: string; name: string } type IntegrationRef = { id: string; name: string }
export type IntegrationOAuthAuthorization = { export type IntegrationOAuthAuthorization = {
@@ -31,7 +31,7 @@ export type IntegrationOAuthAuthorization = {
export type IntegrationOAuthMethodRegistration = { export type IntegrationOAuthMethodRegistration = {
readonly integrationID: string readonly integrationID: string
readonly method: IntegrationOAuthMethod readonly method: IntegrationOAuthMethod
readonly authorize: (answers: Form.Answer) => Effect.Effect<IntegrationOAuthAuthorization, unknown, Scope.Scope> readonly authorize: (inputs: IntegrationInputs) => Effect.Effect<IntegrationOAuthAuthorization, unknown, Scope.Scope>
readonly refresh?: (credential: Credential.OAuth) => Effect.Effect<Credential.OAuth, unknown> readonly refresh?: (credential: Credential.OAuth) => Effect.Effect<Credential.OAuth, unknown>
readonly label?: (credential: Credential.OAuth) => string | undefined readonly label?: (credential: Credential.OAuth) => string | undefined
} }
+2 -2
View File
@@ -8,9 +8,9 @@ import type {
} from "@opencode-ai/client" } from "@opencode-ai/client"
import type { IntegrationApi } from "@opencode-ai/client/promise/api" import type { IntegrationApi } from "@opencode-ai/client/promise/api"
import { Credential } from "@opencode-ai/schema/credential" import { Credential } from "@opencode-ai/schema/credential"
import { Form } from "@opencode-ai/schema/form"
import type { Transform } from "./registration.js" import type { Transform } from "./registration.js"
type IntegrationInputs = Record<string, string>
type IntegrationRef = { id: string; name: string } type IntegrationRef = { id: string; name: string }
export type IntegrationOAuthAuthorization = { export type IntegrationOAuthAuthorization = {
@@ -31,7 +31,7 @@ export type IntegrationOAuthAuthorization = {
export type IntegrationOAuthMethodRegistration = { export type IntegrationOAuthMethodRegistration = {
readonly integrationID: string readonly integrationID: string
readonly method: IntegrationOAuthMethod readonly method: IntegrationOAuthMethod
readonly authorize: (answers: Form.Answer) => Promise<IntegrationOAuthAuthorization> readonly authorize: (inputs: IntegrationInputs) => Promise<IntegrationOAuthAuthorization>
readonly refresh?: (credential: Credential.OAuth) => Promise<Credential.OAuth> readonly refresh?: (credential: Credential.OAuth) => Promise<Credential.OAuth>
readonly label?: (credential: Credential.OAuth) => string | undefined readonly label?: (credential: Credential.OAuth) => string | undefined
} }
+3 -3
View File
@@ -1,11 +1,12 @@
import { Integration } from "@opencode-ai/schema/integration" import { Integration } from "@opencode-ai/schema/integration"
import { Location } from "@opencode-ai/schema/location" import { Location } from "@opencode-ai/schema/location"
import { Form } from "@opencode-ai/schema/form"
import { Schema } from "effect" import { Schema } from "effect"
import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi" import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
import { InvalidRequestError } from "../errors.js" import { InvalidRequestError } from "../errors.js"
import { LocationQuery, locationQueryOpenApi } from "./location.js" import { LocationQuery, locationQueryOpenApi } from "./location.js"
const Inputs = Schema.Record(Schema.String, Schema.String)
export const IntegrationGroup = HttpApiGroup.make("server.integration") export const IntegrationGroup = HttpApiGroup.make("server.integration")
.add( .add(
HttpApiEndpoint.get("integration.list", "/api/integration", { HttpApiEndpoint.get("integration.list", "/api/integration", {
@@ -58,7 +59,6 @@ export const IntegrationGroup = HttpApiGroup.make("server.integration")
query: LocationQuery, query: LocationQuery,
payload: Schema.Struct({ payload: Schema.Struct({
key: Schema.String, key: Schema.String,
answers: Form.Answer,
label: Schema.optional(Schema.String), label: Schema.optional(Schema.String),
}), }),
success: HttpApiSchema.NoContent, success: HttpApiSchema.NoContent,
@@ -79,7 +79,7 @@ export const IntegrationGroup = HttpApiGroup.make("server.integration")
query: LocationQuery, query: LocationQuery,
payload: Schema.Struct({ payload: Schema.Struct({
methodID: Integration.MethodID, methodID: Integration.MethodID,
answers: Form.Answer, inputs: Inputs,
label: Schema.optional(Schema.String), label: Schema.optional(Schema.String),
}), }),
success: Location.response(Integration.Attempt), success: Location.response(Integration.Attempt),
-2
View File
@@ -5,7 +5,6 @@ import { optional } from "./schema.js"
import { IntegrationMethodID } from "./integration-id.js" import { IntegrationMethodID } from "./integration-id.js"
import { ascending } from "./identifier.js" import { ascending } from "./identifier.js"
import { NonNegativeInt, statics } from "./schema.js" import { NonNegativeInt, statics } from "./schema.js"
import { Form } from "./form.js"
export const ID = Schema.String.pipe( export const ID = Schema.String.pipe(
Schema.brand("Credential.ID"), Schema.brand("Credential.ID"),
@@ -28,7 +27,6 @@ export const Key = Schema.Struct({
type: Schema.Literal("key"), type: Schema.Literal("key"),
key: Schema.String, key: Schema.String,
metadata: optional(Schema.Record(Schema.String, Schema.Unknown)), metadata: optional(Schema.Record(Schema.String, Schema.Unknown)),
configuration: optional(Form.Answer),
}).annotate({ identifier: "Credential.Key" }) }).annotate({ identifier: "Credential.Key" })
export const Value = Schema.Union([OAuth, Key]) export const Value = Schema.Union([OAuth, Key])
+38 -3
View File
@@ -7,7 +7,6 @@ import { Connection } from "./connection.js"
import { ascending } from "./identifier.js" import { ascending } from "./identifier.js"
import { statics } from "./schema.js" import { statics } from "./schema.js"
import { IntegrationID, IntegrationMethodID } from "./integration-id.js" import { IntegrationID, IntegrationMethodID } from "./integration-id.js"
import { Form } from "./form.js"
export const ID = IntegrationID export const ID = IntegrationID
export type ID = typeof ID.Type export type ID = typeof ID.Type
@@ -15,12 +14,46 @@ export type ID = typeof ID.Type
export const MethodID = IntegrationMethodID export const MethodID = IntegrationMethodID
export type MethodID = typeof MethodID.Type export type MethodID = typeof MethodID.Type
export interface When extends Schema.Schema.Type<typeof When> {}
export const When = Schema.Struct({
key: Schema.String,
op: Schema.Literals(["eq", "neq"]),
value: Schema.String,
}).annotate({ identifier: "Integration.When" })
export interface TextPrompt extends Schema.Schema.Type<typeof TextPrompt> {}
export const TextPrompt = Schema.Struct({
type: Schema.Literal("text"),
key: Schema.String,
message: Schema.String,
placeholder: optional(Schema.String),
when: optional(When),
}).annotate({ identifier: "Integration.TextPrompt" })
export interface SelectPrompt extends Schema.Schema.Type<typeof SelectPrompt> {}
export const SelectPrompt = Schema.Struct({
type: Schema.Literal("select"),
key: Schema.String,
message: Schema.String,
options: Schema.Array(
Schema.Struct({
label: Schema.String,
value: Schema.String,
hint: optional(Schema.String),
}),
),
when: optional(When),
}).annotate({ identifier: "Integration.SelectPrompt" })
export const Prompt = Schema.Union([TextPrompt, SelectPrompt]).pipe(Schema.toTaggedUnion("type"))
export type Prompt = typeof Prompt.Type
export interface OAuthMethod extends Schema.Schema.Type<typeof OAuthMethod> {} export interface OAuthMethod extends Schema.Schema.Type<typeof OAuthMethod> {}
export const OAuthMethod = Schema.Struct({ export const OAuthMethod = Schema.Struct({
id: MethodID, id: MethodID,
type: Schema.Literal("oauth"), type: Schema.Literal("oauth"),
label: Schema.String, label: Schema.String,
forms: optional(Form.Fields), prompts: optional(Schema.Array(Prompt)),
}).annotate({ identifier: "Integration.OAuthMethod" }) }).annotate({ identifier: "Integration.OAuthMethod" })
export interface CommandMethod extends Schema.Schema.Type<typeof CommandMethod> {} export interface CommandMethod extends Schema.Schema.Type<typeof CommandMethod> {}
@@ -35,7 +68,6 @@ export interface KeyMethod extends Schema.Schema.Type<typeof KeyMethod> {}
export const KeyMethod = Schema.Struct({ export const KeyMethod = Schema.Struct({
type: Schema.Literal("key"), type: Schema.Literal("key"),
label: optional(Schema.String), label: optional(Schema.String),
forms: optional(Form.Fields),
}).annotate({ identifier: "Integration.KeyMethod" }) }).annotate({ identifier: "Integration.KeyMethod" })
export interface EnvMethod extends Schema.Schema.Type<typeof EnvMethod> {} export interface EnvMethod extends Schema.Schema.Type<typeof EnvMethod> {}
@@ -49,6 +81,9 @@ export const Method = Schema.Union([OAuthMethod, CommandMethod, KeyMethod, EnvMe
.annotate({ identifier: "Integration.Method" }) .annotate({ identifier: "Integration.Method" })
export type Method = typeof Method.Type export type Method = typeof Method.Type
export const Inputs = Schema.Record(Schema.String, Schema.String).annotate({ identifier: "Integration.Inputs" })
export type Inputs = typeof Inputs.Type
const Updated = ephemeral({ const Updated = ephemeral({
type: "integration.updated", type: "integration.updated",
schema: {}, schema: {},
+1 -2
View File
@@ -58,7 +58,6 @@ export const IntegrationHandler = HttpApiBuilder.group(Api, "server.integration"
service.connection.key({ service.connection.key({
integrationID: ctx.params.integrationID, integrationID: ctx.params.integrationID,
key: ctx.payload.key, key: ctx.payload.key,
answers: ctx.payload.answers,
label: ctx.payload.label, label: ctx.payload.label,
}), }),
) )
@@ -74,7 +73,7 @@ export const IntegrationHandler = HttpApiBuilder.group(Api, "server.integration"
service.oauth.connect({ service.oauth.connect({
integrationID: ctx.params.integrationID, integrationID: ctx.params.integrationID,
methodID: ctx.payload.methodID, methodID: ctx.payload.methodID,
answers: ctx.payload.answers, inputs: ctx.payload.inputs,
label: ctx.payload.label, label: ctx.payload.label,
}), }),
), ),
@@ -5,8 +5,6 @@ import type {
IntegrationInfo, IntegrationInfo,
IntegrationOauthConnectOutput, IntegrationOauthConnectOutput,
IntegrationOAuthMethod, IntegrationOAuthMethod,
FormAnswer,
FormFields,
} from "@opencode-ai/client" } from "@opencode-ai/client"
import open from "open" import open from "open"
import { createMemo, createSignal, onCleanup, onMount, Show } from "solid-js" import { createMemo, createSignal, onCleanup, onMount, Show } from "solid-js"
@@ -20,7 +18,6 @@ import { DialogPrompt } from "../ui/dialog-prompt"
import { DialogSelect } from "../ui/dialog-select" import { DialogSelect } from "../ui/dialog-select"
import { Link } from "../ui/link" import { Link } from "../ui/link"
import { useToast } from "../ui/toast" import { useToast } from "../ui/toast"
import { FormInput } from "../routes/session/form"
const INTEGRATION_PRIORITY: Record<string, number> = { const INTEGRATION_PRIORITY: Record<string, number> = {
opencode: 0, opencode: 0,
@@ -184,7 +181,7 @@ function openMethod(
onConnected?: OnIntegrationConnected, onConnected?: OnIntegrationConnected,
) { ) {
if (method.type === "key") { if (method.type === "key") {
void beginKey(integration, method, dialog, onConnected) dialog.replace(() => <KeyMethod integration={integration} method={method} onConnected={onConnected} />)
return return
} }
if (method.type === "command") { if (method.type === "command") {
@@ -194,21 +191,6 @@ function openMethod(
void beginOAuth(integration, method, dialog, onConnected) void beginOAuth(integration, method, dialog, onConnected)
} }
async function beginKey(
integration: IntegrationInfo,
method: Extract<ConnectMethod, { type: "key" }>,
dialog: ReturnType<typeof useDialog>,
onConnected?: OnIntegrationConnected,
) {
const answers = method.forms
? await formAnswers(dialog, method.label ?? `Connect ${integration.name}`, method.forms)
: {}
if (answers === null) return
dialog.replace(() => (
<KeyMethod integration={integration} method={method} answers={answers} onConnected={onConnected} />
))
}
function CommandStarting(props: { function CommandStarting(props: {
integration: IntegrationInfo integration: IntegrationInfo
method: Extract<ConnectMethod, { type: "command" }> method: Extract<ConnectMethod, { type: "command" }>
@@ -354,7 +336,6 @@ function CommandView(props: { title: string; output: string; message: string })
function KeyMethod(props: { function KeyMethod(props: {
integration: IntegrationInfo integration: IntegrationInfo
method: Extract<ConnectMethod, { type: "key" }> method: Extract<ConnectMethod, { type: "key" }>
answers: FormAnswer
onConnected?: OnIntegrationConnected onConnected?: OnIntegrationConnected
}) { }) {
const data = useData() const data = useData()
@@ -375,7 +356,6 @@ function KeyMethod(props: {
integrationID: props.integration.id, integrationID: props.integration.id,
location: location(data), location: location(data),
key, key,
answers: props.answers,
}) })
.then(() => connected(props.integration, data, dialog, toast, props.onConnected)) .then(() => connected(props.integration, data, dialog, toast, props.onConnected))
.catch((cause) => setError(message(cause))) .catch((cause) => setError(message(cause)))
@@ -393,17 +373,17 @@ async function beginOAuth(
dialog: ReturnType<typeof useDialog>, dialog: ReturnType<typeof useDialog>,
onConnected?: OnIntegrationConnected, onConnected?: OnIntegrationConnected,
) { ) {
const answers = method.forms ? await formAnswers(dialog, method.label, method.forms) : {} const inputs = method.prompts?.length ? await promptInputs(dialog, method.prompts) : {}
if (answers === null) return if (inputs === null) return
dialog.replace(() => ( dialog.replace(() => (
<OAuthStarting integration={integration} method={method} answers={answers} onConnected={onConnected} /> <OAuthStarting integration={integration} method={method} inputs={inputs} onConnected={onConnected} />
)) ))
} }
function OAuthStarting(props: { function OAuthStarting(props: {
integration: IntegrationInfo integration: IntegrationInfo
method: IntegrationOAuthMethod method: IntegrationOAuthMethod
answers: FormAnswer inputs: Record<string, string>
onConnected?: OnIntegrationConnected onConnected?: OnIntegrationConnected
}) { }) {
const data = useData() const data = useData()
@@ -417,7 +397,7 @@ function OAuthStarting(props: {
integrationID: props.integration.id, integrationID: props.integration.id,
location: location(data), location: location(data),
methodID: props.method.id, methodID: props.method.id,
answers: props.answers, inputs: props.inputs,
}) })
.then((result) => { .then((result) => {
if (result.data.mode === "code") { if (result.data.mode === "code") {
@@ -641,23 +621,49 @@ function OAuthView(props: {
) )
} }
async function formAnswers(dialog: ReturnType<typeof useDialog>, title: string, forms: FormFields) { async function promptInputs(
return new Promise<FormAnswer | null>((resolve) => { dialog: ReturnType<typeof useDialog>,
dialog.replace( prompts: NonNullable<IntegrationOAuthMethod["prompts"]>,
() => ( ) {
<FormInput const inputs: Record<string, string> = {}
form={{ title, fields: forms }} for (const prompt of prompts) {
onSubmit={resolve} if (prompt.when) {
onCancel={() => { const value = inputs[prompt.when.key]
dialog.clear() if (value === undefined) continue
resolve(null) const matches = prompt.when.op === "eq" ? value === prompt.when.value : value !== prompt.when.value
}} if (!matches) continue
/> }
), if (prompt.type === "select") {
() => resolve(null), const value = await new Promise<string | null>((resolve) => {
) dialog.replace(
dialog.setSize("large") () => (
}) <DialogSelect
title={prompt.message}
options={prompt.options.map((option) => ({
title: option.label,
value: option.value,
description: option.hint,
}))}
onSelect={(option) => resolve(option.value)}
/>
),
() => resolve(null),
)
})
if (value === null) return null
inputs[prompt.key] = value
continue
}
const value = await new Promise<string | null>((resolve) => {
dialog.replace(
() => <DialogPrompt title={prompt.message} placeholder={prompt.placeholder} onConfirm={resolve} />,
() => resolve(null),
)
})
if (value === null) return null
inputs[prompt.key] = value
}
return inputs
} }
async function connected( async function connected(
+43 -47
View File
@@ -4,7 +4,7 @@ import { useRenderer, useTerminalDimensions } from "@opentui/solid"
import type { ScrollBoxRenderable, TextareaRenderable } from "@opentui/core" import type { ScrollBoxRenderable, TextareaRenderable } from "@opentui/core"
import open from "open" import open from "open"
import { useTheme, useThemes } from "../../context/theme" import { useTheme, useThemes } from "../../context/theme"
import type { FormAnswer, FormField, FormValue } from "@opencode-ai/client" import type { FormField, FormValue } from "@opencode-ai/client"
import type { FormWithLocation } from "../../context/data" import type { FormWithLocation } from "../../context/data"
import { useClient } from "../../context/client" import { useClient } from "../../context/client"
import { useClipboard } from "../../context/clipboard" import { useClipboard } from "../../context/clipboard"
@@ -44,27 +44,6 @@ function requestOptions(form: FormWithLocation) {
export function FormPrompt(props: { form: FormWithLocation }) { export function FormPrompt(props: { form: FormWithLocation }) {
const client = useClient() const client = useClient()
return (
<FormInput
form={props.form}
onSubmit={(answer) =>
client.api.form.reply(
{ sessionID: props.form.sessionID, formID: props.form.id, answer },
requestOptions(props.form),
)
}
onCancel={() =>
client.api.form.cancel({ sessionID: props.form.sessionID, formID: props.form.id }, requestOptions(props.form))
}
/>
)
}
export function FormInput(props: {
form: Pick<FormWithLocation, "title" | "fields" | "metadata">
onSubmit: (answer: FormAnswer) => Promise<unknown> | void
onCancel: () => Promise<unknown> | void
}) {
const themes = useThemes() const themes = useThemes()
const theme = useTheme("elevated") const theme = useTheme("elevated")
const themeMode = themes.mode const themeMode = themes.mode
@@ -202,14 +181,23 @@ export function FormInput(props: {
} }
function replySingle(field: FormAnswerField, value: FormValue) { function replySingle(field: FormAnswerField, value: FormValue) {
Promise.resolve(props.onSubmit({ [field.key]: value })).catch((error: unknown) => { client.api.form
setStore( .reply(
"error", {
typeof error === "object" && error !== null && "message" in error && typeof error.message === "string" sessionID: props.form.sessionID,
? error.message formID: props.form.id,
: "Invalid answer", answer: { [field.key]: value },
},
requestOptions(props.form),
) )
}) .catch((error: unknown) => {
setStore(
"error",
typeof error === "object" && error !== null && "message" in error && typeof error.message === "string"
? error.message
: "Invalid answer",
)
})
} }
function pick(value: FormValue, customValue?: string) { function pick(value: FormValue, customValue?: string) {
@@ -362,7 +350,7 @@ export function FormInput(props: {
} }
function cancel() { function cancel() {
void props.onCancel() void client.api.form.cancel({ sessionID: props.form.sessionID, formID: props.form.id }, requestOptions(props.form))
} }
function openExternal() { function openExternal() {
@@ -414,23 +402,28 @@ export function FormInput(props: {
setStore("error", formValidateValue(invalid, store.answers[invalid.key]) ?? "Invalid answer") setStore("error", formValidateValue(invalid, store.answers[invalid.key]) ?? "Invalid answer")
return return
} }
Promise.resolve( client.api.form
props.onSubmit( .reply(
Object.fromEntries( {
fields().flatMap((field) => { sessionID: props.form.sessionID,
const value = store.answers[field.key] formID: props.form.id,
return value === undefined ? [] : [[field.key, value] as const] answer: Object.fromEntries(
}), fields().flatMap((field) => {
), const value = store.answers[field.key]
), return value === undefined ? [] : [[field.key, value] as const]
).catch((error: unknown) => { }),
setStore( ),
"error", },
typeof error === "object" && error !== null && "message" in error && typeof error.message === "string" requestOptions(props.form),
? error.message
: "Invalid answer",
) )
}) .catch((error: unknown) => {
setStore(
"error",
typeof error === "object" && error !== null && "message" in error && typeof error.message === "string"
? error.message
: "Invalid answer",
)
})
} }
onMount(() => onCleanup(keymap.mode.push(FORM_MODE))) onMount(() => onCleanup(keymap.mode.push(FORM_MODE)))
@@ -458,7 +451,10 @@ export function FormInput(props: {
group: "Form", group: "Form",
run: () => { run: () => {
if (textual()) { if (textual()) {
void props.onCancel() void client.api.form.cancel(
{ sessionID: props.form.sessionID, formID: props.form.id },
requestOptions(props.form),
)
return return
} }
setStore("editing", false) setStore("editing", false)