Compare commits

..

20 Commits

Author SHA1 Message Date
Aiden Cline ad8f2033a7 fix(core): restore Copilot request authentication 2026-08-09 00:00:33 -05:00
Aiden Cline 15efcf90fa chore(core): revert provider URL expansion 2026-08-08 23:42:44 -05:00
Aiden Cline 5ae05c1ee2 fix(core): expand provider URL variables 2026-08-08 23:27:18 -05:00
Aiden Cline dd6c5fcb7b fix(integration): restore tailored auth flows 2026-08-08 22:44:47 -05:00
Aiden Cline 5cfb70e93a refactor(plugin): own integration method types 2026-08-08 21:53:11 -05:00
Aiden Cline 9fed1e9764 fix(integration): make form answer optional 2026-08-08 21:29:55 -05:00
Aiden Cline 2be2993289 refactor(integration): use singular form naming 2026-08-08 21:21:19 -05:00
Aiden Cline 3434fd0c6e refactor(core): simplify integration registration 2026-08-08 21:02:24 -05:00
Aiden Cline 905ccc3c54 refactor(core): centralize server validation 2026-08-08 20:57:28 -05:00
Aiden Cline b36f50eacf fix(core): separate integration method types 2026-08-08 20:54:20 -05:00
Aiden Cline d9572f9c0f refactor(plugin): simplify integration forms 2026-08-08 20:40:19 -05:00
Aiden Cline f44e75657d refactor(core): clarify provider form selection 2026-08-08 20:30:10 -05:00
Aiden Cline a3e8ba9ff3 refactor(core): simplify provider forms 2026-08-08 20:30:09 -05:00
Aiden Cline 26ae7d4a6a fix(cli): remove redundant MCP form guard 2026-08-08 20:30:09 -05:00
Aiden Cline cdae7ccebf fix(app): migrate integration forms 2026-08-08 20:30:09 -05:00
Aiden Cline bab1cceede fix(core): isolate integration form configuration 2026-08-08 20:30:09 -05:00
Aiden Cline f2d744b55d refactor(core): replace integration prompts with forms 2026-08-08 20:30:09 -05:00
Kit Langton 84fd347afa fix(codegen): write prettier-stable generated manifests (#41343) 2026-08-08 20:52:04 -04:00
opencode-agent[bot] e8f215bfbc chore: generate 2026-08-09 00:29:22 +00:00
opencode-agent[bot] 445af9ce70 docs: fix install command rendering (#41340)
Co-authored-by: Kit Langton <7587245+kitlangton@users.noreply.github.com>
2026-08-08 20:28:07 -04:00
53 changed files with 1591 additions and 939 deletions
@@ -1,4 +1,4 @@
import type { IntegrationMethod, IntegrationOauthConnectOutput } from "@opencode-ai/client/promise" import type { FormAnswer, 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,6 +40,8 @@ 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["form"]>[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 })
@@ -434,16 +436,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"],
promptInputs: undefined as undefined | Record<string, string>, formAnswer: undefined as FormAnswer | undefined,
state: "pending" as undefined | "pending" | "complete" | "error" | "prompt", state: "pending" as undefined | "pending" | "complete" | "error" | "form",
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.prompt" } | { type: "auth.form" }
| { type: "auth.inputs"; inputs: Record<string, string> } | { type: "auth.answer"; answer: FormAnswer | undefined }
| { 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 }
@@ -454,7 +456,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.promptInputs = undefined draft.formAnswer = undefined
draft.state = undefined draft.state = undefined
draft.error = undefined draft.error = undefined
return return
@@ -462,18 +464,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.promptInputs = undefined draft.formAnswer = undefined
draft.state = undefined draft.state = undefined
draft.error = undefined draft.error = undefined
return return
} }
if (action.type === "auth.prompt") { if (action.type === "auth.form") {
draft.state = "prompt" draft.state = "form"
draft.error = undefined draft.error = undefined
return return
} }
if (action.type === "auth.inputs") { if (action.type === "auth.answer") {
draft.promptInputs = action.inputs draft.formAnswer = action.answer
draft.state = undefined draft.state = undefined
draft.error = undefined draft.error = undefined
return return
@@ -531,7 +533,7 @@ function ProviderConnection(props: {
return fallback return fallback
} }
async function selectMethod(index: number, inputs?: Record<string, string>) { async function selectMethod(index: number, answer?: FormAnswer) {
if (timer.current !== undefined) { if (timer.current !== undefined) {
clearTimeout(timer.current) clearTimeout(timer.current)
timer.current = undefined timer.current = undefined
@@ -540,9 +542,17 @@ function ProviderConnection(props: {
const method = methods()[index] const method = methods()[index]
dispatch({ type: "method.select", index }) dispatch({ type: "method.select", index })
if (method.form?.length && !answer) {
dispatch({ type: "auth.form" })
return
}
if (method.type === "key") {
dispatch({ type: "auth.answer", answer })
return
}
if (method.type === "oauth") { if (method.type === "oauth") {
if (method.prompts?.length && !inputs) { if (method.form?.some((field) => field.type !== "string")) {
dispatch({ type: "auth.prompt" }) dispatch({ type: "auth.error", error: "This authentication form contains unsupported fields" })
return return
} }
dispatch({ type: "auth.pending" }) dispatch({ type: "auth.pending" })
@@ -550,7 +560,7 @@ function ProviderConnection(props: {
.api.integration.oauth.connect({ .api.integration.oauth.connect({
integrationID: props.provider, integrationID: props.provider,
methodID: method.id, methodID: method.id,
inputs: inputs ?? {}, ...(answer ? { answer } : {}),
location: location(), location: location(),
}) })
.then((x) => { .then((x) => {
@@ -564,41 +574,42 @@ function ProviderConnection(props: {
} }
} }
function AuthPromptsView() { function AuthFormView() {
const [formStore, setFormStore] = createStore({ const [formStore, setFormStore] = createStore({
value: {} as Record<string, string>, value: {} as Record<string, string>,
index: 0, index: 0,
}) })
const prompts = createMemo(() => { const fields = createMemo<StringForm[]>(() => {
const value = method() const value = method()
return value?.type === "oauth" ? (value.prompts ?? []) : [] return (value?.form ?? []).flatMap((field) => (field.type === "string" ? [field] : []))
}) })
const matches = (prompt: NonNullable<ReturnType<typeof prompts>[number]>, value: Record<string, string>) => { const matches = (field: StringForm, value: Record<string, string>) => {
if (!prompt.when) return true return (field.when ?? []).every((condition) => {
const actual = value[prompt.when.key] const actual = value[condition.key]
if (actual === undefined) return false if (actual === undefined) return false
return prompt.when.op === "eq" ? actual === prompt.when.value : actual !== prompt.when.value return condition.op === "eq" ? actual === condition.value : actual !== condition.value
})
} }
const current = createMemo(() => { const current = createMemo(() => {
const all = prompts() const all = fields()
const index = all.findIndex((prompt, index) => index >= formStore.index && matches(prompt, formStore.value)) const index = all.findIndex((field, index) => index >= formStore.index && matches(field, formStore.value))
if (index === -1) return if (index === -1) return
return { return {
index, index,
prompt: all[index], field: all[index],
} }
}) })
const valid = createMemo(() => { const valid = createMemo(() => {
const item = current() const item = current()
if (!item || item.prompt.type !== "text") return false if (!item || item.field.options) return false
const value = formStore.value[item.prompt.key] ?? "" if (!item.field.required) return true
return value.trim().length > 0 return (formStore.value[item.field.key] ?? "").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 = prompts().findIndex((prompt, i) => i > index && matches(prompt, value)) const next = fields().findIndex((field, i) => i > index && matches(field, value))
if (next !== -1) { if (next !== -1) {
setFormStore("index", next) setFormStore("index", next)
return return
@@ -609,60 +620,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.prompt.type !== "text") return if (!item || item.field.options) 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 prompt = item()?.prompt const field = item()?.field
if (!prompt || prompt.type !== "text") return if (!field || field.options) return
return prompt return field
}) })
const select = createMemo(() => { const select = createMemo(() => {
const prompt = item()?.prompt const field = item()?.field
if (!prompt || prompt.type !== "select") return if (!field?.options) return
return prompt return field
}) })
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()?.prompt.type === "text"}> <Match when={item()?.field.options === undefined}>
<TextField <TextField
type="text" type="text"
label={text()?.message ?? ""} label={text()?.title ?? ""}
placeholder={text()?.placeholder} placeholder={text()?.placeholder}
value={text() ? (formStore.value[text()!.key] ?? "") : ""} value={text() ? (formStore.value[text()!.key] ?? "") : ""}
onChange={(value) => { onChange={(value) => {
const prompt = text() const field = text()
if (!prompt) return if (!field) return
setFormStore("value", prompt.key, value) setFormStore("value", field.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()?.prompt.type === "select"}> <Match when={item()?.field.options !== undefined}>
<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()?.message}</div> <div class="text-14-regular text-text-base">{select()?.title}</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 prompt = select() const field = select()
if (!prompt) return if (!field) return
const nextValue = { const nextValue = {
...formStore.value, ...formStore.value,
[prompt.key]: value.value, [field.key]: value.value,
} }
setFormStore("value", prompt.key, value.value) setFormStore("value", field.key, value.value)
void next(item()!.index, nextValue) void next(item()!.index, nextValue)
}} }}
> >
@@ -672,7 +683,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.hint}</span> <span class="text-14-regular text-text-weak">{option.description}</span>
</div> </div>
)} )}
</List> </List>
@@ -820,6 +831,7 @@ function ProviderConnection(props: {
integrationID: props.provider, integrationID: props.provider,
location: location(), location: location(),
key: apiKey, key: apiKey,
...(store.formAnswer ? { answer: store.formAnswer } : {}),
}) })
await complete() await complete()
} }
@@ -1143,8 +1155,8 @@ function ProviderConnection(props: {
</div> </div>
</div> </div>
</Match> </Match>
<Match when={store.state === "prompt"}> <Match when={store.state === "form"}>
<AuthPromptsView /> <AuthFormView />
</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">
+1 -2
View File
@@ -662,13 +662,12 @@ 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.prompts?.length) const method = integration.data?.methods.find((item) => item.type === "oauth" && !item.form?.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,
inputs: {},
location: { directory: key }, location: { directory: key },
}) })
platform.openLink(attempt.data.url) platform.openLink(attempt.data.url)
+65 -6
View File
@@ -1,5 +1,7 @@
import type { AgentSideConnection, PermissionOption, ToolCallLocation } from "@agentclientprotocol/sdk" import type { AgentSideConnection, PermissionOption, ToolCallContent, ToolCallLocation } from "@agentclientprotocol/sdk"
import type { EventSubscribeOutput, OpenCodeClient } from "@opencode-ai/client/promise" import type { EventSubscribeOutput, OpenCodeClient } from "@opencode-ai/client/promise"
import { Patch } from "@opencode-ai/util/patch"
import { Result } from "effect"
import { isAbsolute, resolve } from "node:path" import { isAbsolute, resolve } from "node:path"
import { pendingToolCall, stringValue, toLocations, toToolKind, type ToolInput } from "./tool" import { pendingToolCall, stringValue, toLocations, toToolKind, type ToolInput } from "./tool"
@@ -26,8 +28,9 @@ export async function replyPermission(input: {
}) { }) {
const toolName = input.tool?.name ?? input.event.data.action const toolName = input.tool?.name ?? input.event.data.action
const toolInput = { ...input.event.data.metadata, ...input.tool?.input } const toolInput = { ...input.event.data.metadata, ...input.tool?.input }
const previews = await permissionPreviews(toolName, toolInput, input.cwd)
const toolCallID = input.event.data.source?.id ?? input.event.data.id const toolCallID = input.event.data.source?.id ?? input.event.data.id
const title = permissionTitle(toolName, toolInput, input.event.data.resources) const title = permissionTitle(toolName, toolInput, previews)
const result = await input.connection const result = await input.connection
.requestPermission({ .requestPermission({
sessionId: input.clientSessionID ?? input.sessionID, sessionId: input.clientSessionID ?? input.sessionID,
@@ -41,7 +44,8 @@ export async function replyPermission(input: {
}, },
cwd: input.cwd, cwd: input.cwd,
}), }),
locations: permissionLocations(toolName, toolInput, input.event.data.resources, input.cwd), locations: permissionLocations(toolName, toolInput, input.event.data.resources, input.cwd, previews),
...(previews.length > 0 ? { content: previews } : {}),
}, },
options, options,
}) })
@@ -90,8 +94,54 @@ export async function syncEditedFiles(input: {
) )
} }
function permissionTitle(toolName: string, input: ToolInput, resources: ReadonlyArray<string>) { async function permissionPreviews(toolName: string, input: ToolInput, cwd: string): Promise<ToolCallContent[]> {
if (toToolKind(toolName) === "edit" && resources.length > 1) return `${resources.length} files` const tool = toolName.toLocaleLowerCase()
if (tool === "patch" || tool === "apply_patch") return patchPreviews(input, cwd)
const path = filePath(input)
if (!path) return []
const oldText = await readText(path, cwd)
if (tool === "write") {
const content = stringValue(input.content)
return content === undefined ? [] : [{ type: "diff", path, oldText, newText: content }]
}
if (tool !== "edit") return []
const oldString = stringValue(input.oldString)
const newString = stringValue(input.newString)
if (oldString === undefined || newString === undefined) return []
const newText =
input.replaceAll === true ? oldText.replaceAll(oldString, newString) : oldText.replace(oldString, newString)
return [{ type: "diff", path, oldText, newText }]
}
async function patchPreviews(input: ToolInput, cwd: string): Promise<ToolCallContent[]> {
const patchText = stringValue(input.patchText)
if (!patchText) return []
try {
const parsed = Patch.parse(patchText)
if (Result.isFailure(parsed)) return []
return await Promise.all(
parsed.success.map(async (hunk): Promise<ToolCallContent> => {
const oldText = hunk.type === "add" ? "" : await readText(hunk.path, cwd)
if (hunk.type === "add") {
const newText = hunk.contents.endsWith("\n") || hunk.contents === "" ? hunk.contents : `${hunk.contents}\n`
return { type: "diff", path: hunk.path, oldText, newText }
}
if (hunk.type === "delete") return { type: "diff", path: hunk.path, oldText, newText: "" }
return {
type: "diff",
path: hunk.movePath ?? hunk.path,
oldText,
newText: Patch.derive(hunk.path, hunk.chunks, oldText).content,
}
}),
)
} catch {
return []
}
}
function permissionTitle(toolName: string, input: ToolInput, previews: ReadonlyArray<ToolCallContent>) {
if (previews.length > 1) return `${previews.length} files`
switch (toolName.toLocaleLowerCase()) { switch (toolName.toLocaleLowerCase()) {
case "external_directory": case "external_directory":
return stringValue(input.description) ?? stringValue(input.command) ?? stringValue(input.parentDir) return stringValue(input.description) ?? stringValue(input.command) ?? stringValue(input.parentDir)
@@ -107,7 +157,7 @@ function permissionTitle(toolName: string, input: ToolInput, resources: Readonly
case "write": case "write":
case "patch": case "patch":
case "apply_patch": case "apply_patch":
return filePath(input) return filePath(input) ?? (previews[0]?.type === "diff" ? previews[0].path : undefined)
default: default:
return undefined return undefined
} }
@@ -118,12 +168,21 @@ function permissionLocations(
input: ToolInput, input: ToolInput,
resources: ReadonlyArray<string>, resources: ReadonlyArray<string>,
cwd: string, cwd: string,
previews: ReadonlyArray<ToolCallContent>,
): ToolCallLocation[] { ): ToolCallLocation[] {
const paths = previews.flatMap((preview) => (preview.type === "diff" ? [preview.path] : []))
if (paths.length > 0) return [...new Set(paths)].map((path) => ({ path }))
const locations = toLocations(toolName, input, cwd) const locations = toLocations(toolName, input, cwd)
if (locations.length > 0) return locations if (locations.length > 0) return locations
return resources.filter((resource) => resource !== "*").map((path) => ({ path })) return resources.filter((resource) => resource !== "*").map((path) => ({ path }))
} }
function readText(path: string, cwd: string) {
return Bun.file(resolvePath(path, cwd))
.text()
.catch(() => "")
}
function filePath(input: ToolInput) { function filePath(input: ToolInput) {
return stringValue(input.path) ?? stringValue(input.filePath) ?? stringValue(input.filepath) return stringValue(input.path) ?? stringValue(input.filePath) ?? stringValue(input.filepath)
} }
@@ -50,7 +50,7 @@ const login = Effect.fn("cli.console.login.run")(function* (timeline: TimelineHo
{ {
integrationID, integrationID,
methodID: method.id, methodID: method.id,
inputs: server ? { server } : {}, ...(server ? { answer: { 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, inputs: {}, location }), client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, location }),
) )
const attempt = started.data const attempt = started.data
if (attempt.mode === "code") if (attempt.mode === "code")
@@ -211,7 +211,7 @@ describe("acp permission behavior", () => {
} }
}) })
test("authorizes edit resources and syncs the completed file", async () => { test("previews edits during approval and syncs the completed file", async () => {
const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-acp-permission-")) const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-acp-permission-"))
const file = path.join(cwd, "file.ts") const file = path.join(cwd, "file.ts")
await fs.writeFile(file, "before") await fs.writeFile(file, "before")
@@ -240,7 +240,6 @@ describe("acp permission behavior", () => {
send( send(
permissionAsked("ses_edit", "perm_edit", { permissionAsked("ses_edit", "perm_edit", {
action: "edit", action: "edit",
resources: ["file.ts"],
source: { type: "tool", messageID: "msg_edit", id: "call_edit" }, source: { type: "tool", messageID: "msg_edit", id: "call_edit" },
}), }),
) )
@@ -279,8 +278,8 @@ describe("acp permission behavior", () => {
title: "file.ts", title: "file.ts",
kind: "edit", kind: "edit",
locations: [{ path: "file.ts" }], locations: [{ path: "file.ts" }],
content: [{ type: "diff", path: "file.ts", oldText: "before", newText: "after" }],
}) })
expect(permissionRequests[0]?.toolCall.content).toBeUndefined()
expect(writes).toEqual([{ sessionId: "ses_edit", path: file, content: "after" }]) expect(writes).toEqual([{ sessionId: "ses_edit", path: file, content: "after" }])
} finally { } finally {
await fixture.stop() await fixture.stop()
@@ -288,7 +287,7 @@ describe("acp permission behavior", () => {
} }
}) })
test("authorizes and syncs each file in a patch", async () => { test("previews and syncs each file in a patch", async () => {
const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-acp-patch-permission-")) const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-acp-patch-permission-"))
await Promise.all([ await Promise.all([
fs.writeFile(path.join(cwd, "first.ts"), "one\n"), fs.writeFile(path.join(cwd, "first.ts"), "one\n"),
@@ -331,7 +330,6 @@ describe("acp permission behavior", () => {
send( send(
permissionAsked("ses_patch", "perm_patch", { permissionAsked("ses_patch", "perm_patch", {
action: "edit", action: "edit",
resources: ["first.ts", "second.ts"],
source: { type: "tool", messageID: "msg_patch", id: "call_patch" }, source: { type: "tool", messageID: "msg_patch", id: "call_patch" },
}), }),
) )
@@ -373,8 +371,11 @@ describe("acp permission behavior", () => {
title: "2 files", title: "2 files",
kind: "edit", kind: "edit",
locations: [{ path: "first.ts" }, { path: "second.ts" }], locations: [{ path: "first.ts" }, { path: "second.ts" }],
content: [
{ type: "diff", path: "first.ts", oldText: "one\n", newText: "two\n" },
{ type: "diff", path: "second.ts", oldText: "alpha\n", newText: "beta\n" },
],
}) })
expect(permissionRequests[0]?.toolCall.content).toBeUndefined()
expect(writes.toSorted((a, b) => a.path.localeCompare(b.path))).toEqual([ expect(writes.toSorted((a, b) => a.path.localeCompare(b.path))).toEqual([
{ sessionId: "ses_patch", path: path.join(cwd, "first.ts"), content: "two\n" }, { sessionId: "ses_patch", path: path.join(cwd, "first.ts"), content: "two\n" },
{ sessionId: "ses_patch", path: path.join(cwd, "second.ts"), content: "beta\n" }, { sessionId: "ses_patch", path: path.join(cwd, "second.ts"), content: "beta\n" },
@@ -555,7 +556,6 @@ function permissionAsked(
id: string, id: string,
input: { input: {
readonly action?: string readonly action?: string
readonly resources?: ReadonlyArray<string>
readonly metadata?: Record<string, unknown> readonly metadata?: Record<string, unknown>
readonly source?: { readonly type: "tool"; readonly messageID: string; readonly id: string } readonly source?: { readonly type: "tool"; readonly messageID: string; readonly id: string }
} = {}, } = {},
@@ -564,7 +564,7 @@ function permissionAsked(
id, id,
sessionID, sessionID,
action: input.action ?? "shell", action: input.action ?? "shell",
resources: [...(input.resources ?? ["*"])], resources: ["*"],
metadata: input.metadata ?? { command: "printf hello" }, metadata: input.metadata ?? { command: "printf hello" },
...(input.source ? { source: input.source } : {}), ...(input.source ? { source: input.source } : {}),
}) })
+3 -2
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"
@@ -1054,6 +1054,7 @@ 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 answer?: Form.Answer | undefined
readonly label?: string | undefined readonly label?: string | undefined
} }
export type Endpoint10_3Output = void export type Endpoint10_3Output = void
@@ -1065,7 +1066,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 inputs: { readonly [x: string]: string } readonly answer?: Form.Answer | undefined
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 }
@@ -717,7 +717,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"], label: input["label"] }, payload: { key: input["key"], answer: input["answer"], label: input["label"] },
}).pipe(Effect.mapError(mapClientError)), }).pipe(Effect.mapError(mapClientError)),
) )
@@ -726,7 +726,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"], inputs: input["inputs"], label: input["label"] }, payload: { methodID: input["methodID"], answer: input["answer"], label: input["label"] },
}).pipe(Effect.mapError(mapClientError)), }).pipe(Effect.mapError(mapClientError)),
) )
@@ -1032,7 +1032,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"], label: input["label"] }, body: { key: input["key"], answer: input["answer"], label: input["label"] },
successStatus: 204, successStatus: 204,
declaredStatuses: [400, 401], declaredStatuses: [400, 401],
empty: true, empty: true,
@@ -1047,7 +1047,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"], inputs: input["inputs"], label: input["label"] }, body: { methodID: input["methodID"], answer: input["answer"], label: input["label"] },
successStatus: 200, successStatus: 200,
declaredStatuses: [400, 401], declaredStatuses: [400, 401],
empty: false, empty: false,
+70 -80
View File
@@ -195,12 +195,18 @@ export type ProviderInfo = {
body?: { [x: string]: any } body?: { [x: string]: any }
} }
export type IntegrationWhen = { key: string; op: "eq" | "neq"; value: string } 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 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 }
@@ -285,16 +291,6 @@ 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 }
@@ -1277,45 +1273,6 @@ 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
@@ -1381,6 +1338,29 @@ 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 = {
@@ -1664,13 +1644,6 @@ 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
@@ -1924,15 +1897,9 @@ 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 FormFields1 = [FormField1, ...Array<FormField1>] export type FormFields3 = [FormField1, ...Array<FormField1>]
export type SessionPendingInfo = SessionPendingUser | SessionPendingSynthetic | SessionPendingCompaction export type SessionPendingInfo = SessionPendingUser | SessionPendingSynthetic | SessionPendingCompaction
@@ -1954,16 +1921,13 @@ export type SessionMessageAssistant = {
retry?: SessionMessageAssistantRetry retry?: SessionMessageAssistantRetry
} }
export type IntegrationInfo = { export type IntegrationOAuthMethod = { id: string; type: "oauth"; label: string; form?: FormFields }
id: string
name: string export type IntegrationKeyMethod = { type: "key"; label?: string; form?: FormFields }
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: FormFields1 } export type FormInfo1 = { id: string; sessionID: string; title: string; metadata?: FormMetadata1; fields: FormFields3 }
export type SessionInputAdmitted = { export type SessionInputAdmitted = {
id: string id: string
@@ -1986,6 +1950,12 @@ 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
@@ -2046,6 +2016,13 @@ 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
@@ -4045,8 +4022,21 @@ 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: string; readonly label?: string | undefined }["key"] readonly key: {
readonly label?: { readonly key: string; readonly label?: string | undefined }["label"] readonly key: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly label?: string | undefined
}["key"]
readonly answer?: {
readonly key: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly label?: string | undefined
}["answer"]
readonly label?: {
readonly key: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly label?: string | undefined
}["label"]
} }
export type IntegrationConnectKeyOutput = void export type IntegrationConnectKeyOutput = void
@@ -4058,17 +4048,17 @@ export type IntegrationOauthConnectInput = {
}["location"] }["location"]
readonly methodID: { readonly methodID: {
readonly methodID: string readonly methodID: string
readonly inputs: { readonly [x: string]: string } readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly label?: string | undefined readonly label?: string | undefined
}["methodID"] }["methodID"]
readonly inputs: { readonly answer?: {
readonly methodID: string readonly methodID: string
readonly inputs: { readonly [x: string]: string } readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly label?: string | undefined readonly label?: string | undefined
}["inputs"] }["answer"]
readonly label?: { readonly label?: {
readonly methodID: string readonly methodID: string
readonly inputs: { readonly [x: string]: string } readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly label?: string | undefined readonly label?: string | undefined
}["label"] }["label"]
} }
+43
View File
@@ -148,6 +148,49 @@ 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 optionally submit a form answer", 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",
answer: { accountId: "account" },
})
await client.integration.oauth.connect({
integrationID: "github-copilot",
methodID: "device",
answer: { deploymentType: "enterprise", enabled: true, scopes: ["read:user"] },
})
await client.integration.connect.key({ integrationID: "openai", key: "secret" })
await client.integration.oauth.connect({ integrationID: "openai", methodID: "device" })
expect(await requests[0].json()).toEqual({ key: "secret", answer: { accountId: "account" } })
expect(await requests[1].json()).toEqual({
methodID: "device",
answer: { deploymentType: "enterprise", enabled: true, scopes: ["read:user"] },
})
expect(await requests[2].json()).toEqual({ key: "secret" })
expect(await requests[3].json()).toEqual({ methodID: "device" })
})
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({
+41 -30
View File
@@ -48,13 +48,15 @@ export const readText = Effect.fn("FileMutation.readText")(function* (files: Fil
return Bom.decodeBytes((yield* files.read(target)).bytes) return Bom.decodeBytes((yield* files.read(target)).bytes)
}) })
export const syncTextBom = Effect.fn("FileMutation.syncTextBom")((files: Files, target: string, bom: boolean) => export const syncTextBom = Effect.fn("FileMutation.syncTextBom")(function* (
Effect.gen(function* () { files: Files,
const synced = Bom.syncBytes((yield* files.read(target)).bytes, bom) target: string,
if (synced.bytes) yield* files.write(target, synced.bytes) bom: boolean,
return synced.text ) {
}).pipe(Effect.uninterruptible), const synced = Bom.syncBytes((yield* files.read(target)).bytes, bom)
) if (synced.bytes) yield* files.write(target, synced.bytes)
return synced.text
})
/** Share transaction locks across Location graphs that address the same file. */ /** Share transaction locks across Location graphs that address the same file. */
const transactionLocks = KeyedMutex.makeUnsafe<string>() const transactionLocks = KeyedMutex.makeUnsafe<string>()
@@ -68,10 +70,15 @@ const layer = Layer.effect(
Service, Service,
Effect.gen(function* () { Effect.gen(function* () {
const environment = yield* Environment.Service const environment = yield* Environment.Service
const locks = KeyedMutex.makeUnsafe<string>()
const withLock: Interface["withLock"] = (targets) => (effect) => const withLock: Interface["withLock"] = (targets) => (effect) =>
[...new Set(targets.map(FSUtil.resolve))] [...new Set(targets.map(FSUtil.resolve))]
.sort() .sort()
.reduceRight((result, target) => transactionLocks.withLock(target)(result), effect) .reduceRight((result, target) => transactionLocks.withLock(target)(result), effect)
const withTargetLock =
(target: Target) =>
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
locks.withLock(target.absolute)(Effect.uninterruptible(effect))
const writeResult = (target: Target, existed: boolean): WriteResult => ({ const writeResult = (target: Target, existed: boolean): WriteResult => ({
operation: "write", operation: "write",
@@ -81,32 +88,36 @@ const layer = Layer.effect(
}) })
const write = Effect.fn("FileMutation.write")((input: WriteInput) => const write = Effect.fn("FileMutation.write")((input: WriteInput) =>
Effect.gen(function* () { withTargetLock(input.target)(
const existed = yield* environment.files.stat(input.target.absolute).pipe( Effect.gen(function* () {
Effect.as(true), const existed = yield* environment.files.stat(input.target.absolute).pipe(
Effect.catchTag("Environment.NotFound", () => Effect.succeed(false)), Effect.as(true),
) Effect.catchTag("Environment.NotFound", () => Effect.succeed(false)),
yield* environment.files.write( )
input.target.absolute, yield* environment.files.write(
typeof input.content === "string" ? new TextEncoder().encode(input.content) : input.content, input.target.absolute,
) typeof input.content === "string" ? new TextEncoder().encode(input.content) : input.content,
return writeResult(input.target, existed) )
}).pipe(Effect.uninterruptible), return writeResult(input.target, existed)
}),
),
) )
const writeTextPreservingBom = Effect.fn("FileMutation.writeTextPreservingBom")((input: TextWriteInput) => const writeTextPreservingBom = Effect.fn("FileMutation.writeTextPreservingBom")((input: TextWriteInput) =>
Effect.gen(function* () { withTargetLock(input.target)(
const next = Bom.split(input.content) Effect.gen(function* () {
const current = yield* environment.files.read(input.target.absolute, { offset: 0, length: 3 }).pipe( const next = Bom.split(input.content)
Effect.map((result) => result.bytes), const current = yield* environment.files.read(input.target.absolute, { offset: 0, length: 3 }).pipe(
Effect.catchTag("Environment.NotFound", () => Effect.succeed(undefined)), Effect.map((result) => result.bytes),
) Effect.catchTag("Environment.NotFound", () => Effect.succeed(undefined)),
yield* environment.files.write( )
input.target.absolute, yield* environment.files.write(
new TextEncoder().encode(Bom.join(next.text, Boolean(current && Bom.has(current)) || next.bom)), input.target.absolute,
) new TextEncoder().encode(Bom.join(next.text, Boolean(current && Bom.has(current)) || next.bom)),
return writeResult(input.target, current !== undefined) )
}).pipe(Effect.uninterruptible), return writeResult(input.target, current !== undefined)
}),
),
) )
return Service.of({ withLock, write, writeTextPreservingBom }) return Service.of({ withLock, write, writeTextPreservingBom })
+5 -5
View File
@@ -180,7 +180,7 @@ 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, input.answer) const invalid = validateAnswer(entry.form.fields, 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, {
@@ -227,12 +227,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] })
function validateAnswer(form: Info, answer: Answer) { export function validateAnswer(form: ReadonlyArray<Form.Field>, answer: Answer) {
const fields = new Map(form.fields.map((field) => [field.key, field] as const)) const fields = new Map(form.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 form.fields) { for (const field of form) {
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 +268,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.
function validateFields(fields: ReadonlyArray<Form.Field>) { export 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>()
+6 -1
View File
@@ -70,6 +70,11 @@ type UsableModel = RemoteModel & {
} }
} }
export const Package = {
OpenAI: "@ai-sdk/github-copilot",
Anthropic: "@ai-sdk/github-copilot/anthropic",
} as const
export async function get(baseURL: string, headers: RequestInit["headers"], existing: readonly Model.Info[]) { export async function get(baseURL: string, headers: RequestInit["headers"], existing: readonly Model.Info[]) {
const response = await fetch(`${baseURL}/models`, { const response = await fetch(`${baseURL}/models`, {
headers, headers,
@@ -141,7 +146,7 @@ function build(id: Model.ID, remote: UsableModel, baseURL: string, previous?: Mo
providerID: Provider.ID.githubCopilot, providerID: Provider.ID.githubCopilot,
family: previous?.family ?? Model.Family.make(remote.capabilities.family), family: previous?.family ?? Model.Family.make(remote.capabilities.family),
name: previous?.name ?? remote.name, name: previous?.name ?? remote.name,
package: Provider.aisdk(messages ? "@ai-sdk/anthropic" : "@ai-sdk/github-copilot"), package: Provider.aisdk(messages ? Package.Anthropic : Package.OpenAI),
settings: Provider.mergeOverlay(previous?.settings, { settings: Provider.mergeOverlay(previous?.settings, {
baseURL: messages ? `${baseURL}/v1` : baseURL, baseURL: messages ? `${baseURL}/v1` : baseURL,
...(endpoint ? { endpoint } : {}), ...(endpoint ? { endpoint } : {}),
+27 -22
View File
@@ -24,6 +24,7 @@ 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
@@ -34,18 +35,6 @@ 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
@@ -64,9 +53,6 @@ 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
@@ -85,7 +71,7 @@ export type OAuthAuthorization = {
export interface OAuthImplementation { export interface OAuthImplementation {
readonly integrationID: ID readonly integrationID: ID
readonly method: OAuthMethod readonly method: OAuthMethod
readonly authorize: (inputs: Inputs) => Effect.Effect<OAuthAuthorization, unknown, Scope.Scope> readonly authorize: (answer: Form.Answer) => 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
} }
@@ -175,6 +161,8 @@ 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 answer?: 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>
@@ -191,7 +179,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 inputs: Inputs readonly answer?: Form.Answer
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. */
@@ -356,7 +344,7 @@ const layer = Layer.effect(
return [...credentials, ...env] return [...credentials, ...env]
} }
const project = (entry: Entry, connections: IntegrationConnection.Info[]) => const project = (entry: Entry, connections: IntegrationConnection.Info[]): Info =>
Info.make({ Info.make({
id: entry.ref.id, id: entry.ref.id,
name: entry.ref.name, name: entry.ref.name,
@@ -547,15 +535,20 @@ 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 inputs: Inputs readonly answer?: Form.Answer
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}`))
} }
const answer = input.answer ?? {}
if (method.method.form) {
const invalid = Form.validateFields(method.method.form) ?? Form.validateAnswer(method.method.form, answer)
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.inputs)).pipe( const authorization = yield* authorize(method.authorize(answer)).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)),
) )
@@ -699,12 +692,24 @@ const layer = Layer.effect(
const method = state const method = state
.get() .get()
.integrations.get(input.integrationID) .integrations.get(input.integrationID)
?.methods.some((method) => method.type === "key") ?.methods.find((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}`))
const answer = input.answer ?? {}
if (method.type === "key" && method.form) {
const invalid = Form.validateFields(method.form) ?? Form.validateAnswer(method.form, answer)
if (invalid) return yield* new AuthorizationError({ cause: new Error(invalid) })
}
if (method.type === "key" && !method.form && Object.keys(answer).length > 0) {
return yield* new AuthorizationError({ cause: new Error("Key method does not accept a form answer") })
}
yield* credentials.create({ yield* credentials.create({
integrationID: input.integrationID, integrationID: input.integrationID,
label: input.label, label: input.label,
value: Credential.Key.make({ type: "key", key: input.key }), value: Credential.Key.make({
type: "key",
key: input.key,
...(Object.keys(answer).length > 0 ? { configuration: answer } : {}),
}),
}) })
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, {})
+3 -1
View File
@@ -149,6 +149,7 @@ 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(
@@ -175,7 +176,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 } const configured = { ...resolved.settings, ...credential?.metadata, ...configuration }
const mapping = Provider.isAISDK(resolved.package) const mapping = Provider.isAISDK(resolved.package)
? AISDKNative.map({ ? AISDKNative.map({
packageName, packageName,
@@ -190,6 +191,7 @@ 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)))
+8 -7
View File
@@ -190,6 +190,7 @@ 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,
answer: input.answer,
label: input.label, label: input.label,
}), }),
}, },
@@ -199,7 +200,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),
inputs: input.inputs, answer: input.answer,
label: input.label, label: input.label,
}), }),
), ),
@@ -260,7 +261,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
update: (id, update) => draft.update(Integration.ID.make(id), update), update: (id, update) => draft.update(Integration.ID.make(id), update),
remove: (id) => draft.remove(Integration.ID.make(id)), remove: (id) => draft.remove(Integration.ID.make(id)),
method: { method: {
list: (id) => mutable(draft.method.list(Integration.ID.make(id))), list: (id) => draft.method.list(Integration.ID.make(id)),
update: (input) => draft.method.update(methodImplementation(input)), update: (input) => draft.method.update(methodImplementation(input)),
remove: (id, method) => remove: (id, method) =>
draft.method.remove(Integration.ID.make(id), Schema.decodeUnknownSync(Integration.Method)(method)), draft.method.remove(Integration.ID.make(id), Schema.decodeUnknownSync(Integration.Method)(method)),
@@ -363,8 +364,8 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
return { return {
integrationID: Integration.ID.make(input.integrationID), integrationID: Integration.ID.make(input.integrationID),
method: { ...input.method, id: Integration.MethodID.make(input.method.id) }, method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
authorize: (inputs) => authorize: (answer) =>
input.authorize(inputs).pipe( input.authorize(answer).pipe(
Effect.map((authorization) => { Effect.map((authorization) => {
if (authorization.mode === "auto") { if (authorization.mode === "auto") {
return { return {
@@ -385,18 +386,18 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
if (input.method.type === "env") { if (input.method.type === "env") {
return { return {
integrationID: Integration.ID.make(input.integrationID), integrationID: Integration.ID.make(input.integrationID),
method: { type: "env", names: input.method.names }, method: input.method,
} }
} }
if (input.method.type === "command") { if (input.method.type === "command") {
return { return {
integrationID: Integration.ID.make(input.integrationID), integrationID: Integration.ID.make(input.integrationID),
method: Schema.decodeUnknownSync(Integration.CommandMethod)(input.method), method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
} }
} }
return { return {
integrationID: Integration.ID.make(input.integrationID), integrationID: Integration.ID.make(input.integrationID),
method: { type: "key", label: input.method.label }, method: input.method,
} }
} }
+13 -7
View File
@@ -180,8 +180,8 @@ export function fromPromise(plugin: Plugin) {
const refresh = input.refresh const refresh = input.refresh
draft.method.update({ draft.method.update({
...input, ...input,
authorize: (inputs) => authorize: (answer) =>
Effect.promise(() => input.authorize(inputs)).pipe( Effect.promise(() => input.authorize(answer)).pipe(
Effect.map((authorization) => Effect.map((authorization) =>
authorization.mode === "auto" authorization.mode === "auto"
? { ? {
@@ -362,11 +362,17 @@ type Wire<Value> = unknown extends Value
? Value ? Value
: Value extends DateTime.DateTime : Value extends DateTime.DateTime
? number ? number
: Value extends ReadonlyArray<infer Item> : Value extends readonly [infer Head, ...infer Tail]
? Array<Wire<Item>> ? [Wire<Head>, ...WireTuple<Tail>]
: Value extends object : Value extends ReadonlyArray<infer Item>
? { -readonly [Key in keyof Value]: Wire<Value[Key]> } ? Array<Wire<Item>>
: Value : Value extends object
? { -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,6 +1,9 @@
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 { Form } from "@opencode-ai/schema/form"
import { Provider } from "../../provider" import { Provider } from "../../provider"
import { iife } from "../../util/iife"
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)
@@ -13,6 +16,29 @@ 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)
const form = iife(() => {
if (resolveResourceName(configured) || typeof configured?.baseURL === "string") return
return Form.Fields.make([
{
type: "string",
key: "resourceName",
title: "Enter Azure Resource Name",
placeholder: "e.g. my-models",
required: true,
},
])
})
yield* ctx.integration.transform((draft) => {
draft.method.update({
integrationID: Provider.ID.azure,
method: {
type: "key",
label: "API key",
form,
},
})
})
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,10 +2,53 @@ 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 { Form } from "@opencode-ai/schema/form"
import { Provider } from "../../provider"
import { iife } from "../../util/iife"
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 form = iife(() => {
if (typeof configured?.baseURL === "string") return
const accountId = process.env.CLOUDFLARE_ACCOUNT_ID || stringOption(configured ?? {}, "accountId")
const gatewayId =
process.env.CLOUDFLARE_GATEWAY_ID ||
stringOption(configured ?? {}, "gatewayId") ||
stringOption(configured ?? {}, "gateway")
if (accountId && gatewayId) return
const accountIdForm = Form.StringField.make({
type: "string",
key: "accountId",
title: "Enter your Cloudflare Account ID",
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
required: true,
})
const gatewayIdForm = Form.StringField.make({
type: "string",
key: "gatewayId",
title: "Enter your Cloudflare AI Gateway ID",
placeholder: "e.g. my-gateway",
required: true,
})
if (accountId) return Form.Fields.make([gatewayIdForm])
if (gatewayId) return Form.Fields.make([accountIdForm])
return Form.Fields.make([accountIdForm, gatewayIdForm])
})
yield* ctx.integration.transform((draft) => {
draft.method.update({
integrationID: providerID,
method: {
type: "key",
label: "Gateway API token",
form,
},
})
})
yield* ctx.aisdk.hook( yield* ctx.aisdk.hook(
"sdk", "sdk",
Effect.fn(function* (evt) { Effect.fn(function* (evt) {
@@ -46,7 +89,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 prompt stores the // Credential projection copies key metadata into options. The form 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")
@@ -2,13 +2,39 @@ import os from "os"
import { App } from "../../app" 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 { Form } from "@opencode-ai/schema/form"
import { Provider } from "../../provider" import { Provider } from "../../provider"
import { iife } from "../../util/iife"
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)
const form = iife(() => {
if (typeof configured?.baseURL === "string" || resolveAccountId(configured ?? {})) return
return Form.Fields.make([
{
type: "string",
key: "accountId",
title: "Enter your Cloudflare Account ID",
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
required: true,
},
])
})
yield* ctx.integration.transform((draft) => {
draft.method.update({
integrationID: providerID,
method: {
type: "key",
label: "API key",
form,
},
})
})
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
@@ -0,0 +1,15 @@
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)
})
@@ -15,6 +15,8 @@ import type { PluginInternal } from "../internal"
const clientID = "Ov23li8tweQw6odWQebz" const clientID = "Ov23li8tweQw6odWQebz"
const apiVersion = "2026-06-01" const apiVersion = "2026-06-01"
const userApiVersion = "2025-04-01" const userApiVersion = "2025-04-01"
const copilotVersion = "0.26.7"
const editorVersion = "vscode/1.99.3"
const pollingSafetyMargin = 3000 const pollingSafetyMargin = 3000
const methodID = Integration.MethodID.make("device") const methodID = Integration.MethodID.make("device")
@@ -47,30 +49,33 @@ const oauth = (app: App.Info) =>
id: methodID, id: methodID,
type: "oauth", type: "oauth",
label: "Login with GitHub Copilot", label: "Login with GitHub Copilot",
prompts: [ form: [
{ {
type: "select", type: "string",
key: "deploymentType", key: "deploymentType",
message: "Select GitHub deployment type", title: "Select GitHub deployment type",
required: true,
options: [ options: [
{ label: "GitHub.com", value: "github.com", hint: "Public" }, { label: "GitHub.com", value: "github.com", description: "Public" },
{ label: "GitHub Enterprise", value: "enterprise", hint: "Data residency or self-hosted" }, { label: "GitHub Enterprise", value: "enterprise", description: "Data residency or self-hosted" },
], ],
}, },
{ {
type: "text", type: "string",
key: "enterpriseUrl", key: "enterpriseUrl",
message: "Enter your GitHub Enterprise URL or domain", title: "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",
when: { key: "deploymentType", op: "eq", value: "enterprise" }, required: true,
when: [{ key: "deploymentType", op: "eq", value: "enterprise" }],
}, },
], ],
}, },
authorize: (inputs) => authorize: (answer) =>
Effect.gen(function* () { Effect.gen(function* () {
const enterprise = inputs.deploymentType === "enterprise" const enterprise = answer.deploymentType === "enterprise"
if (enterprise && !inputs.enterpriseUrl) return yield* Effect.fail(new Error("Enterprise URL is required")) const enterpriseUrl = typeof answer.enterpriseUrl === "string" ? answer.enterpriseUrl : undefined
const domain = enterprise ? normalizeDomain(inputs.enterpriseUrl ?? "") : "github.com" if (enterprise && !enterpriseUrl) return yield* Effect.fail(new Error("Enterprise URL is required"))
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",
@@ -188,11 +193,28 @@ export const GithubCopilotPlugin = define({
}) })
yield* ctx.integration.transform((draft) => { yield* ctx.integration.transform((draft) => {
draft.method.remove("github-copilot", { type: "key" })
draft.method.update(oauth(ctx.app)) draft.method.update(oauth(ctx.app))
}) })
yield* ctx.catalog.transform((evt) => { yield* ctx.catalog.transform((evt) => {
const item = evt.provider.get(Provider.ID.githubCopilot) const item = evt.provider.get(Provider.ID.githubCopilot)
if (!item) return if (!item) return
evt.provider.update(item.provider.id, (provider) => {
if (Provider.packageName(provider.package) === "@ai-sdk/openai-compatible") {
provider.package = Provider.aisdk(CopilotModels.Package.OpenAI)
}
})
for (const model of item.models.values()) {
evt.model.update(item.provider.id, model.id, (draft) => {
const packageName = Provider.packageName(draft.package)
if (packageName === "@ai-sdk/openai-compatible") {
draft.package = Provider.aisdk(CopilotModels.Package.OpenAI)
}
if (packageName === "@ai-sdk/anthropic") {
draft.package = Provider.aisdk(CopilotModels.Package.Anthropic)
}
})
}
if (loaded.models) { if (loaded.models) {
for (const id of item.models.keys()) { for (const id of item.models.keys()) {
if (!loaded.models.has(Model.ID.make(id))) evt.model.remove(item.provider.id, id) if (!loaded.models.has(Model.ID.make(id))) evt.model.remove(item.provider.id, id)
@@ -226,14 +248,14 @@ export const GithubCopilotPlugin = define({
"sdk", "sdk",
Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.model.providerID !== Provider.ID.githubCopilot) return if (evt.model.providerID !== Provider.ID.githubCopilot) return
if (evt.package !== "@ai-sdk/github-copilot" && evt.package !== "@ai-sdk/anthropic") return if (evt.package !== CopilotModels.Package.OpenAI && evt.package !== CopilotModels.Package.Anthropic) return
const anthropic = evt.package === CopilotModels.Package.Anthropic
evt.options.fetch = copilotFetch( evt.options.fetch = copilotFetch(
typeof evt.options.apiKey === "string" ? evt.options.apiKey : undefined, typeof evt.options.apiKey === "string" ? evt.options.apiKey : undefined,
evt.options.fetch, evt.options.fetch,
evt.package === "@ai-sdk/anthropic", anthropic,
ctx.app,
) )
if (evt.package === "@ai-sdk/anthropic") { if (anthropic) {
evt.options.headers = { evt.options.headers = {
...evt.options.headers, ...evt.options.headers,
"anthropic-beta": "interleaved-thinking-2025-05-14", "anthropic-beta": "interleaved-thinking-2025-05-14",
@@ -312,12 +334,7 @@ function request(url: string, init: RequestInit) {
type Fetch = (input: Parameters<typeof fetch>[0], init?: RequestInit) => Promise<Response> type Fetch = (input: Parameters<typeof fetch>[0], init?: RequestInit) => Promise<Response>
export function copilotFetch( export function copilotFetch(token: string | undefined, upstream: Fetch | undefined, anthropic: boolean): Fetch {
token: string | undefined,
upstream: Fetch | undefined,
anthropic: boolean,
app: App.Info,
): Fetch {
const send = upstream ?? fetch const send = upstream ?? fetch
return async (input, init) => { return async (input, init) => {
const requestHeaders = new Headers(init?.headers) const requestHeaders = new Headers(init?.headers)
@@ -326,7 +343,10 @@ export function copilotFetch(
requestHeaders.delete("x-api-key") requestHeaders.delete("x-api-key")
requestHeaders.set("Authorization", `Bearer ${token}`) requestHeaders.set("Authorization", `Bearer ${token}`)
} }
requestHeaders.set("User-Agent", App.useragent(app)) requestHeaders.set("User-Agent", `GitHubCopilotChat/${copilotVersion}`)
requestHeaders.set("Editor-Version", editorVersion)
requestHeaders.set("Editor-Plugin-Version", `copilot-chat/${copilotVersion}`)
requestHeaders.set("Copilot-Integration-Id", "vscode-chat")
requestHeaders.set("Openai-Intent", "conversation-edits") requestHeaders.set("Openai-Intent", "conversation-edits")
requestHeaders.set("X-GitHub-Api-Version", apiVersion) requestHeaders.set("X-GitHub-Api-Version", apiVersion)
if (anthropic) requestHeaders.set("anthropic-beta", "interleaved-thinking-2025-05-14") if (anthropic) requestHeaders.set("anthropic-beta", "interleaved-thinking-2025-05-14")
@@ -43,9 +43,9 @@ function oauth(http: HttpClient.HttpClient) {
type: "oauth", type: "oauth",
label: "OpenCode Console account", label: "OpenCode Console account",
}, },
authorize: (inputs) => authorize: (answer) =>
Effect.gen(function* () { Effect.gen(function* () {
const server = yield* normalizeServer(inputs.server ?? defaultServer) const server = yield* normalizeServer(answer.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)
@@ -226,9 +226,10 @@ function withoutCredentials(body: Readonly<Record<string, unknown>> | undefined)
return Object.fromEntries(Object.entries(body ?? {}).filter(([key]) => key !== "apiKey" && key !== "headers")) return Object.fromEntries(Object.entries(body ?? {}).filter(([key]) => key !== "apiKey" && key !== "headers"))
} }
function normalizeServer(input: string) { function normalizeServer(input: unknown) {
return Effect.try({ return Effect.try({
try: () => { try: () => {
if (typeof input !== "string") throw new Error("expected string")
const url = new URL(input) const url = new URL(input)
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("expected HTTP(S)") if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("expected HTTP(S)")
return `${url.origin}${url.pathname.replace(/\/+$/, "")}` return `${url.origin}${url.pathname.replace(/\/+$/, "")}`
+61 -55
View File
@@ -11,9 +11,11 @@ import { ToolFailure } from "@opencode-ai/ai"
import { FileDiff } from "@opencode-ai/schema/file-diff" import { FileDiff } from "@opencode-ai/schema/file-diff"
import { Bom } from "@opencode-ai/util/bom" import { Bom } from "@opencode-ai/util/bom"
import { Effect, Schema } from "effect" import { Effect, Schema } from "effect"
import path from "path"
import { Environment } from "../../environment" import { Environment } from "../../environment"
import { FileMutation } from "../../file-mutation" import { FileMutation } from "../../file-mutation"
import { Formatter } from "../../formatter" import { Formatter } from "../../formatter"
import { Location } from "../../location"
import { LocationMutation } from "../../location-mutation" import { LocationMutation } from "../../location-mutation"
import { Permission } from "../../permission" import { Permission } from "../../permission"
import { fileDiff } from "./file-diff" import { fileDiff } from "./file-diff"
@@ -85,7 +87,7 @@ const findLineOccurrences = (content: string, search: string) => {
if ( if (
!actual.every( !actual.every(
(item, lineIndex) => (item, lineIndex) =>
normalizeForMatch(item.text.trimEnd()) === normalizeForMatch(expected[lineIndex].trimEnd()), normalizeForMatch(item.text.trimEnd()) === normalizeForMatch(expected[lineIndex]!.trimEnd()),
) )
) )
return [] return []
@@ -112,6 +114,7 @@ export const Plugin = {
const fileMutation = yield* FileMutation.Service const fileMutation = yield* FileMutation.Service
const environment = yield* Environment.Service const environment = yield* Environment.Service
const formatter = yield* Formatter.Service const formatter = yield* Formatter.Service
const location = yield* Location.Service
const permission = yield* Permission.Service const permission = yield* Permission.Service
yield* ctx.tool yield* ctx.tool
@@ -151,69 +154,72 @@ export const Plugin = {
source: permissionSource, source: permissionSource,
}) })
} }
const original = yield* FileMutation.readText(environment.files, target.absolute).pipe(
Effect.catchTag("Environment.NotFound", () =>
Effect.fail(new ToolFailure({ message: `File not found: ${input.path}` })),
),
Effect.catchTag("Environment.WrongKind", (error) =>
error.actual === "directory"
? Effect.fail(new ToolFailure({ message: `Path is a directory, not a file: ${input.path}` }))
: Effect.fail(new ToolFailure({ message: `Unable to edit ${input.path}`, error })),
),
)
const source = original.text
const ending = source.includes(crlf) ? crlf : "\n"
const oldString = input.oldString.replaceAll(crlf, "\n").replaceAll("\n", ending)
const newString = input.newString.replaceAll(crlf, "\n").replaceAll("\n", ending)
const exact = findOccurrences(source, oldString)
// These one-to-one mappings preserve offsets into the original source.
const unicode =
exact.length > 0 ? [] : findOccurrences(normalizeForMatch(source), normalizeForMatch(oldString))
const trailing = exact.length > 0 || unicode.length > 0 ? [] : findLineOccurrences(source, oldString)
const matches = exact.length > 0 ? exact : unicode.length > 0 ? unicode : trailing
const replacements = matches.length
const replaced = (input.replaceAll === true ? matches : matches.slice(0, 1))
.toReversed()
.reduce(
(content, match) => `${content.slice(0, match.start)}${newString}${content.slice(match.end)}`,
source,
)
const preview =
replacements > 0 && (replacements === 1 || input.replaceAll === true)
? fileDiff(target.resource, source, replaced)
: undefined
yield* permission.assert({ yield* permission.assert({
action: "edit", action: "edit",
resources: [target.resource], resources: [target.resource],
save: ["*"], save: ["*"],
metadata: preview ? { files: [preview] } : undefined,
sessionID: context.sessionID, sessionID: context.sessionID,
agent: context.agent, agent: context.agent,
source: permissionSource, source: permissionSource,
}) })
return yield* fileMutation.withLock([target.absolute])( if (replacements === 0) {
Effect.gen(function* () { return yield* new ToolFailure({
const original = yield* FileMutation.readText(environment.files, target.absolute).pipe( message: `Could not find oldString in ${input.path}. It must match exactly, including whitespace and indentation.`,
Effect.catchTag("Environment.NotFound", () => })
Effect.fail(new ToolFailure({ message: `File not found: ${input.path}` })), }
), if (replacements > 1 && input.replaceAll !== true) {
Effect.catchTag("Environment.WrongKind", (error) => return yield* new ToolFailure({
error.actual === "directory" message: `Found ${replacements} matches for oldString, but expected exactly one. Add more surrounding context to make oldString unique, or set replaceAll to true to replace every occurrence.`,
? Effect.fail(new ToolFailure({ message: `Path is a directory, not a file: ${input.path}` })) })
: Effect.fail(new ToolFailure({ message: `Unable to edit ${input.path}`, error })), }
), const replacementBom = replaced.startsWith("\uFEFF")
) const result = yield* fileMutation.write({
const source = original.text target,
const ending = source.includes(crlf) ? crlf : "\n" content: Bom.join(replaced, original.bom || replacementBom),
const oldString = input.oldString.replaceAll(crlf, "\n").replaceAll("\n", ending) })
const newString = input.newString.replaceAll(crlf, "\n").replaceAll("\n", ending) const bom = original.bom || replacementBom
const exact = findOccurrences(source, oldString) const formatted = (yield* formatter.file(target.absolute))
// These one-to-one mappings preserve offsets into the original source. ? yield* FileMutation.syncTextBom(environment.files, target.absolute, bom)
const unicode = : (yield* FileMutation.readText(environment.files, target.absolute)).text
exact.length > 0 ? [] : findOccurrences(normalizeForMatch(source), normalizeForMatch(oldString)) return {
const trailing = exact.length > 0 || unicode.length > 0 ? [] : findLineOccurrences(source, oldString) files: [fileDiff(result.resource, source, formatted)],
const matches = exact.length > 0 ? exact : unicode.length > 0 ? unicode : trailing replacements,
const replacements = matches.length } satisfies Output
const replaced = (input.replaceAll === true ? matches : matches.slice(0, 1))
.toReversed()
.reduce(
(content, match) => `${content.slice(0, match.start)}${newString}${content.slice(match.end)}`,
source,
)
if (replacements === 0) {
return yield* new ToolFailure({
message: `Could not find oldString in ${input.path}. It must match exactly, including whitespace and indentation.`,
})
}
if (replacements > 1 && input.replaceAll !== true) {
return yield* new ToolFailure({
message: `Found ${replacements} matches for oldString, but expected exactly one. Add more surrounding context to make oldString unique, or set replaceAll to true to replace every occurrence.`,
})
}
const replacementBom = replaced.startsWith("\uFEFF")
const result = yield* fileMutation.write({
target,
content: Bom.join(replaced, original.bom || replacementBom),
})
const bom = original.bom || replacementBom
const formatted = (yield* formatter.file(target.absolute))
? yield* FileMutation.syncTextBom(environment.files, target.absolute, bom)
: (yield* FileMutation.readText(environment.files, target.absolute)).text
return {
files: [fileDiff(result.resource, source, formatted)],
replacements,
} satisfies Output
}),
)
}).pipe( }).pipe(
fileMutation.withLock([path.resolve(location.directory, input.path)]),
Effect.map((output) => ({ Effect.map((output) => ({
output, output,
content: `Edited ${output.files[0]?.file} (${output.replacements} replacement${output.replacements === 1 ? "" : "s"})`, content: `Edited ${output.files[0]?.file} (${output.replacements} replacement${output.replacements === 1 ? "" : "s"})`,
+187 -175
View File
@@ -3,7 +3,7 @@ export * as PatchTool from "./patch"
import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin" import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin"
import { ToolFailure } from "@opencode-ai/ai" import { ToolFailure } from "@opencode-ai/ai"
import { FileDiff } from "@opencode-ai/schema/file-diff" import { FileDiff } from "@opencode-ai/schema/file-diff"
import { Effect, Schema } from "effect" import { Effect, Result, Schema } from "effect"
import path from "path" import path from "path"
import { Bom } from "@opencode-ai/util/bom" import { Bom } from "@opencode-ai/util/bom"
import { FSUtil } from "@opencode-ai/util/fs-util" import { FSUtil } from "@opencode-ai/util/fs-util"
@@ -93,6 +93,12 @@ export const Plugin = {
execute: (input, context) => { execute: (input, context) => {
const applied: Array<typeof Applied.Type> = [] const applied: Array<typeof Applied.Type> = []
const parsed = Patch.parse(input.patchText) const parsed = Patch.parse(input.patchText)
const lockTargets = Result.isSuccess(parsed)
? parsed.success.flatMap((hunk) => [
path.resolve(location.directory, hunk.path),
...(hunk.type === "update" && hunk.movePath ? [path.resolve(location.directory, hunk.movePath)] : []),
])
: []
const fail = (operation: string, error: unknown) => { const fail = (operation: string, error: unknown) => {
const completed = applied.map((item) => item.resource).join(", ") const completed = applied.map((item) => item.resource).join(", ")
return new ToolFailure({ return new ToolFailure({
@@ -112,196 +118,202 @@ export const Plugin = {
if (hunks.length === 0) { if (hunks.length === 0) {
return yield* new ToolFailure({ message: "patch rejected: empty patch" }) return yield* new ToolFailure({ message: "patch rejected: empty patch" })
} }
const plans = hunks.map((hunk) => ({ const prepared: Prepared[] = []
hunk, const targets: Target[] = []
target: resolveTarget(location, hunk.path), const updates = new Map<string, string>()
moveTarget: for (const hunk of hunks) {
hunk.type === "update" && hunk.movePath ? resolveTarget(location, hunk.movePath) : undefined, yield* Effect.gen(function* () {
})) const target = resolveTarget(location, hunk.path)
const targets = plans.flatMap((plan) => [plan.target, ...(plan.moveTarget ? [plan.moveTarget] : [])]) targets.push(target)
for (const target of targets) { if (target.externalDirectory) {
if (target.externalDirectory) { yield* permission.assert({
yield* permission.assert({ action: "external_directory",
action: "external_directory", resources: [target.externalDirectory.resource],
resources: [target.externalDirectory.resource], save: [target.externalDirectory.resource],
save: [target.externalDirectory.resource], metadata: {
metadata: { filepath: target.absolute,
filepath: target.absolute, parentDir: target.externalDirectory.directory,
parentDir: target.externalDirectory.directory, },
}, sessionID: context.sessionID,
sessionID: context.sessionID, agent: context.agent,
agent: context.agent, source,
source, })
}
if (hunk.type === "add") {
const content =
hunk.contents.endsWith("\n") || hunk.contents === "" ? hunk.contents : `${hunk.contents}\n`
prepared.push({
...hunk,
target,
content,
before: "",
after: Bom.split(content).text,
})
return
}
if (hunk.type === "delete") {
const content = yield* FileMutation.readText(environment.files, target.absolute).pipe(
Effect.mapError(
(error) =>
new ToolFailure({
message: `patch verification failed: Failed to delete ${target.resource}: ${errorMessage(error)}`,
}),
),
)
prepared.push({ ...hunk, target, before: content.text, after: "" })
return
}
const previous = updates.get(target.absolute)
const original =
previous ??
(yield* Effect.gen(function* () {
const content = yield* FileMutation.readText(environment.files, target.absolute).pipe(
Effect.mapError(
(error) =>
new ToolFailure({
message: `patch verification failed: Failed to read file to update ${target.absolute}: ${errorMessage(error)}`,
}),
),
)
return Bom.join(content.text, content.bom)
}))
const before = Bom.split(original).text
const update = yield* Effect.try({
try: () => Patch.derive(hunk.path, hunk.chunks, original),
catch: (error) => new ToolFailure({ message: `patch verification failed: ${errorMessage(error)}` }),
}) })
} const moveTarget = hunk.movePath ? resolveTarget(location, hunk.movePath) : undefined
if (moveTarget) targets.push(moveTarget)
if (moveTarget?.externalDirectory) {
yield* permission.assert({
action: "external_directory",
resources: [moveTarget.externalDirectory.resource],
save: [moveTarget.externalDirectory.resource],
metadata: {
filepath: moveTarget.absolute,
parentDir: moveTarget.externalDirectory.directory,
},
sessionID: context.sessionID,
agent: context.agent,
source,
})
}
prepared.push({
...hunk,
target,
content: Patch.joinBom(update.content, update.bom),
before,
after: update.content,
moveTarget,
})
if (!moveTarget) updates.set(target.absolute, Patch.joinBom(update.content, update.bom))
}).pipe(
Effect.mapError((error) =>
error instanceof ToolFailure
? error
: new ToolFailure({ message: `Unable to prepare patch at ${hunk.path}`, error }),
),
)
} }
const patchFiles = prepared.map((change) => patchFile(change))
yield* permission.assert({ yield* permission.assert({
action: "edit", action: "edit",
resources: [...new Set(targets.map((target) => target.resource))], resources: [...new Set(targets.map((target) => target.resource))],
save: ["*"], save: ["*"],
metadata: {
filepath: targets.map((target) => target.resource).join(", "),
diff: patchFiles.map((file) => `${file.patch}\n`).join(""),
files: patchFiles,
},
sessionID: context.sessionID, sessionID: context.sessionID,
agent: context.agent, agent: context.agent,
source, source,
}) })
return yield* mutation.withLock(targets.map((target) => target.absolute))( yield* Effect.forEach(
Effect.gen(function* () { prepared,
const prepared: Prepared[] = [] (change) =>
const updates = new Map<string, string>() Effect.gen(function* () {
for (const plan of plans) { if (change.type === "add") {
const hunk = plan.hunk yield* environment.files
const target = plan.target .write(change.target.absolute, new TextEncoder().encode(change.content))
yield* Effect.gen(function* () { .pipe(Effect.mapError((error) => fail(`Failed to write ${change.target.resource}`, error)))
if (hunk.type === "add") { applied.push({
const content = type: change.type,
hunk.contents.endsWith("\n") || hunk.contents === "" ? hunk.contents : `${hunk.contents}\n` resource: change.target.resource,
prepared.push({ target: change.target.absolute,
...hunk, })
target, return
content, }
before: "", if (change.type === "delete") {
after: Bom.split(content).text, yield* environment.files
}) .remove(change.target.absolute)
return .pipe(Effect.mapError((error) => fail(`Failed to delete ${change.target.resource}`, error)))
} applied.push({
if (hunk.type === "delete") { type: change.type,
const content = yield* FileMutation.readText(environment.files, target.absolute).pipe( resource: change.target.resource,
Effect.mapError( target: change.target.absolute,
(error) => })
new ToolFailure({ return
message: `patch verification failed: Failed to delete ${target.resource}: ${errorMessage(error)}`, }
}), if (change.moveTarget) {
const moveTarget = change.moveTarget
yield* environment.files
.write(moveTarget.absolute, new TextEncoder().encode(change.content))
.pipe(Effect.mapError((error) => fail(`Failed to write ${moveTarget.resource}`, error)))
yield* environment.files
.remove(change.target.absolute)
.pipe(
Effect.mapError((error) =>
fail(`Wrote ${moveTarget.resource} but failed to remove ${change.target.resource}`, error),
), ),
) )
prepared.push({ ...hunk, target, before: content.text, after: "" }) applied.push({
return type: change.type,
} resource: change.moveTarget.resource,
const previous = updates.get(target.absolute) target: change.moveTarget.absolute,
const original =
previous ??
(yield* Effect.gen(function* () {
const content = yield* FileMutation.readText(environment.files, target.absolute).pipe(
Effect.mapError(
(error) =>
new ToolFailure({
message: `patch verification failed: Failed to read file to update ${target.absolute}: ${errorMessage(error)}`,
}),
),
)
return Bom.join(content.text, content.bom)
}))
const before = Bom.split(original).text
const update = yield* Effect.try({
try: () => Patch.derive(hunk.path, hunk.chunks, original),
catch: (error) =>
new ToolFailure({ message: `patch verification failed: ${errorMessage(error)}` }),
}) })
const moveTarget = plan.moveTarget return
prepared.push({ }
...hunk, yield* environment.files
target, .write(change.target.absolute, new TextEncoder().encode(change.content))
content: Patch.joinBom(update.content, update.bom), .pipe(Effect.mapError((error) => fail(`Failed to write ${change.target.resource}`, error)))
before, applied.push({
after: update.content, type: change.type,
moveTarget, resource: change.target.resource,
}) target: change.target.absolute,
if (!moveTarget) updates.set(target.absolute, Patch.joinBom(update.content, update.bom)) })
}).pipe( }),
Effect.mapError((error) => { discard: true },
error instanceof ToolFailure
? error
: new ToolFailure({ message: `Unable to prepare patch at ${hunk.path}`, error }),
),
)
}
yield* Effect.forEach(
prepared,
(change) =>
Effect.gen(function* () {
if (change.type === "add") {
yield* environment.files
.write(change.target.absolute, new TextEncoder().encode(change.content))
.pipe(Effect.mapError((error) => fail(`Failed to write ${change.target.resource}`, error)))
applied.push({
type: change.type,
resource: change.target.resource,
target: change.target.absolute,
})
return
}
if (change.type === "delete") {
yield* environment.files
.remove(change.target.absolute)
.pipe(Effect.mapError((error) => fail(`Failed to delete ${change.target.resource}`, error)))
applied.push({
type: change.type,
resource: change.target.resource,
target: change.target.absolute,
})
return
}
if (change.moveTarget) {
const moveTarget = change.moveTarget
yield* environment.files
.write(moveTarget.absolute, new TextEncoder().encode(change.content))
.pipe(Effect.mapError((error) => fail(`Failed to write ${moveTarget.resource}`, error)))
yield* environment.files
.remove(change.target.absolute)
.pipe(
Effect.mapError((error) =>
fail(
`Wrote ${moveTarget.resource} but failed to remove ${change.target.resource}`,
error,
),
),
)
applied.push({
type: change.type,
resource: change.moveTarget.resource,
target: change.moveTarget.absolute,
})
return
}
yield* environment.files
.write(change.target.absolute, new TextEncoder().encode(change.content))
.pipe(Effect.mapError((error) => fail(`Failed to write ${change.target.resource}`, error)))
applied.push({
type: change.type,
resource: change.target.resource,
target: change.target.absolute,
})
}),
{ discard: true },
)
const formatted = new Map<string, string>()
yield* Effect.forEach(
[...new Set(applied.filter((item) => item.type !== "delete").map((item) => item.target))],
(target) =>
Effect.gen(function* () {
const current = yield* FileMutation.readText(environment.files, target).pipe(
Effect.mapError((error) => fail(`Failed to read ${target}`, error)),
)
formatted.set(
target,
(yield* formatter.file(target))
? yield* FileMutation.syncTextBom(environment.files, target, current.bom).pipe(
Effect.mapError((error) => fail(`Failed to sync ${target}`, error)),
)
: current.text,
)
}),
{ discard: true },
)
const files = yield* Effect.forEach(prepared, (change) => {
if (change.type === "delete") return Effect.succeed(patchFile(change))
const target = change.type === "update" && change.moveTarget ? change.moveTarget : change.target
return Effect.succeed(patchFile(change, formatted.get(target.absolute)))
})
return { applied, files }
}),
) )
const formatted = new Map<string, string>()
yield* Effect.forEach(
[...new Set(applied.filter((item) => item.type !== "delete").map((item) => item.target))],
(target) =>
Effect.gen(function* () {
const current = yield* FileMutation.readText(environment.files, target).pipe(
Effect.mapError((error) => fail(`Failed to read ${target}`, error)),
)
formatted.set(
target,
(yield* formatter.file(target))
? yield* FileMutation.syncTextBom(environment.files, target, current.bom).pipe(
Effect.mapError((error) => fail(`Failed to sync ${target}`, error)),
)
: current.text,
)
}),
{ discard: true },
)
const files = yield* Effect.forEach(prepared, (change) => {
if (change.type === "delete") return Effect.succeed(patchFile(change))
const target = change.type === "update" && change.moveTarget ? change.moveTarget : change.target
return Effect.succeed(patchFile(change, formatted.get(target.absolute)))
})
return { applied, files }
}).pipe( }).pipe(
mutation.withLock(lockTargets),
Effect.map((output) => ({ Effect.map((output) => ({
output, output,
content: toModelOutput(output), content: toModelOutput(output),
+14 -10
View File
@@ -9,11 +9,13 @@ export * as WriteTool from "./write"
import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin" import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin"
import { ToolFailure } from "@opencode-ai/ai" import { ToolFailure } from "@opencode-ai/ai"
import { Effect, Schema } from "effect" import { Effect, Schema } from "effect"
import { Bom } from "@opencode-ai/util/bom"
import { Environment } from "../../environment" import { Environment } from "../../environment"
import { FileMutation } from "../../file-mutation" import { FileMutation } from "../../file-mutation"
import { Formatter } from "../../formatter" import { Formatter } from "../../formatter"
import { LocationMutation } from "../../location-mutation" import { LocationMutation } from "../../location-mutation"
import { Permission } from "../../permission" import { Permission } from "../../permission"
import { fileDiff } from "./file-diff"
export const name = "write" export const name = "write"
@@ -75,24 +77,26 @@ export const Plugin = {
agent: context.agent, agent: context.agent,
source, source,
}) })
const current = yield* FileMutation.readText(environment.files, target.absolute).pipe(
Effect.catchTag("Environment.NotFound", () => Effect.succeed(undefined)),
)
const next = Bom.split(input.content)
const preview = fileDiff(target.resource, current?.text ?? "", next.text, current ? "modified" : "added")
yield* permission.assert({ yield* permission.assert({
action: "edit", action: "edit",
resources: [target.resource], resources: [target.resource],
save: ["*"], save: ["*"],
metadata: { files: [preview] },
sessionID: context.sessionID, sessionID: context.sessionID,
agent: context.agent, agent: context.agent,
source, source,
}) })
return yield* fileMutation.withLock([target.absolute])( const result = yield* fileMutation.writeTextPreservingBom({ target, content: input.content })
Effect.gen(function* () { const bom = (yield* FileMutation.readText(environment.files, target.absolute)).bom
const result = yield* fileMutation.writeTextPreservingBom({ target, content: input.content }) if (yield* formatter.file(target.absolute)) {
const bom = (yield* FileMutation.readText(environment.files, target.absolute)).bom yield* FileMutation.syncTextBom(environment.files, target.absolute, bom)
if (yield* formatter.file(target.absolute)) { }
yield* FileMutation.syncTextBom(environment.files, target.absolute, bom) return result
}
return result
}),
)
}).pipe( }).pipe(
Effect.map((output) => ({ output, content: toModelOutput(output) })), Effect.map((output) => ({ output, content: toModelOutput(output) })),
Effect.mapError((error) => new ToolFailure({ message: `Unable to write ${input.path}`, error })), Effect.mapError((error) => new ToolFailure({ message: `Unable to write ${input.path}`, error })),
+85
View File
@@ -110,6 +110,49 @@ describe("FileMutation", () => {
), ),
) )
it.live("serializes concurrent writes to the same absolute target", () =>
withTmp((directory) =>
Effect.gen(function* () {
const targetPath = path.join(directory, "shared.txt")
yield* Effect.promise(() => fs.writeFile(targetPath, "initial"))
const firstStarted = yield* Deferred.make<void>()
const releaseFirst = yield* Deferred.make<void>()
const secondStarted = yield* Deferred.make<void>()
let writes = 0
const filesystem = instrumentWrites((write) =>
Effect.gen(function* () {
writes++
if (writes === 1) {
yield* Deferred.succeed(firstStarted, undefined)
yield* Deferred.await(releaseFirst)
} else {
yield* Deferred.succeed(secondStarted, undefined)
}
yield* write
}),
)
yield* Effect.gen(function* () {
const mutation = yield* LocationMutation.Service
const files = yield* FileMutation.Service
const firstPlan = yield* mutation.resolve({ path: "shared.txt" })
const secondPlan = yield* mutation.resolve({ path: "shared.txt" })
const first = yield* files.write({ target: firstPlan, content: "first" }).pipe(Effect.forkChild)
yield* Deferred.await(firstStarted)
const second = yield* files.write({ target: secondPlan, content: "second" }).pipe(Effect.forkChild)
yield* Effect.yieldNow
expect(yield* Deferred.isDone(secondStarted)).toBe(false)
yield* Deferred.succeed(releaseFirst, undefined)
yield* Deferred.await(secondStarted)
yield* Fiber.join(first)
yield* Fiber.join(second)
expect(yield* Effect.promise(() => fs.readFile(targetPath, "utf8"))).toBe("second")
}).pipe(provide(directory, filesystem))
}),
),
)
it.live("shares transaction locks across Location service instances", () => it.live("shares transaction locks across Location service instances", () =>
withTmp((directory) => withTmp((directory) =>
Effect.gen(function* () { Effect.gen(function* () {
@@ -160,4 +203,46 @@ describe("FileMutation", () => {
}).pipe(provide(directory)), }).pipe(provide(directory)),
), ),
) )
it.live("allows distinct absolute targets to proceed independently", () =>
withTmp((directory) =>
Effect.gen(function* () {
const firstStarted = yield* Deferred.make<void>()
const releaseFirst = yield* Deferred.make<void>()
const secondFinished = yield* Deferred.make<void>()
const secondPath = path.join(directory, "second.txt")
let writes = 0
const filesystem = instrumentWrites((write) =>
++writes === 1
? Deferred.succeed(firstStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseFirst)),
Effect.andThen(write),
)
: write.pipe(Effect.andThen(Deferred.succeed(secondFinished, undefined))),
)
yield* Effect.gen(function* () {
const mutation = yield* LocationMutation.Service
const files = yield* FileMutation.Service
const firstPlan = yield* mutation.resolve({ path: "first.txt" })
const secondPlan = yield* mutation.resolve({ path: "second.txt" })
const first = yield* files.write({ target: firstPlan, content: "first" }).pipe(Effect.forkChild)
yield* Deferred.await(firstStarted)
const second = yield* files.write({ target: secondPlan, content: "second" }).pipe(Effect.forkChild)
yield* Deferred.await(secondFinished)
expect(yield* Effect.promise(() => fs.readFile(secondPath, "utf8"))).toBe("second")
yield* Deferred.succeed(releaseFirst, undefined)
yield* Fiber.join(first)
yield* Fiber.join(second)
}).pipe(provide(directory, filesystem))
}),
),
)
}) })
function instrumentWrites(
run: <E>(write: Effect.Effect<void, E>, target: string) => Effect.Effect<void, E>,
): EnvironmentFilesTransform {
return (files) => ({ write: (target, content) => run(files.write(target, content), target) })
}
@@ -42,6 +42,18 @@ test("defensively syncs advertised Copilot models", async () => {
supports: { tool_calls: false }, supports: { tool_calls: false },
}, },
}, },
{
model_picker_enabled: true,
id: "claude-sonnet",
name: "Claude Sonnet",
version: "claude-sonnet-2026-06-01",
supported_endpoints: ["/v1/messages"],
capabilities: {
family: "claude",
limits: { max_output_tokens: 16000, max_prompt_tokens: 180000 },
supports: { tool_calls: true },
},
},
{ model_picker_enabled: true, id: "incomplete" }, { model_picker_enabled: true, id: "incomplete" },
], ],
}), }),
@@ -68,6 +80,7 @@ test("defensively syncs advertised Copilot models", async () => {
Model.VariantID.make("high"), Model.VariantID.make("high"),
]) ])
expect(models.get(Model.ID.make("utility"))?.enabled).toBe(false) expect(models.get(Model.ID.make("utility"))?.enabled).toBe(false)
expect(models.get(Model.ID.make("claude-sonnet"))?.package).toBe(Provider.aisdk(CopilotModels.Package.Anthropic))
expect(models.has(Model.ID.make("stale"))).toBe(false) expect(models.has(Model.ID.make("stale"))).toBe(false)
expect(models.has(Model.ID.make("incomplete"))).toBe(false) expect(models.has(Model.ID.make("incomplete"))).toBe(false)
} finally { } finally {
+19 -8
View File
@@ -140,7 +140,11 @@ describe("Integration", () => {
yield* integrations.transform((editor) => yield* integrations.transform((editor) =>
editor.method.update({ editor.method.update({
integrationID, integrationID,
method: { type: "key", label: "API key" }, method: {
type: "key",
label: "API key",
form: [{ type: "string", key: "accountId", title: "Account ID", required: true }],
},
}), }),
) )
const updated = yield* bus const updated = yield* bus
@@ -148,9 +152,17 @@ 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" }).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",
answer: { accountId: "account" },
label: "Work", label: "Work",
}) })
@@ -158,7 +170,7 @@ describe("Integration", () => {
expect.objectContaining({ expect.objectContaining({
integrationID, integrationID,
label: "Work", label: "Work",
value: Credential.Key.make({ type: "key", key: "secret" }), value: Credential.Key.make({ type: "key", key: "secret", configuration: { accountId: "account" } }),
}), }),
]) ])
expect((yield* Fiber.join(updated)).length).toBe(1) expect((yield* Fiber.join(updated)).length).toBe(1)
@@ -243,7 +255,6 @@ describe("Integration", () => {
const attempt = yield* integrations.oauth.connect({ const attempt = yield* integrations.oauth.connect({
integrationID, integrationID,
methodID, methodID,
inputs: {},
label: "Personal", label: "Personal",
}) })
expect(attempt.mode).toBe("code") expect(attempt.mode).toBe("code")
@@ -289,7 +300,7 @@ describe("Integration", () => {
}), }),
) )
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} }) const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
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)
@@ -327,7 +338,7 @@ describe("Integration", () => {
}), }),
) )
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} }) const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
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",
@@ -365,7 +376,7 @@ describe("Integration", () => {
}), }),
) )
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} }) const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
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)
@@ -401,7 +412,7 @@ describe("Integration", () => {
}), }),
) )
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} }) const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
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
@@ -442,7 +453,7 @@ describe("Integration", () => {
}), }),
) )
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} }) const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
expect(attempt.time).toEqual({ created, expires: expiresAt }) expect(attempt.time).toEqual({ created, expires: expiresAt })
}) })
}) })
+6 -2
View File
@@ -736,7 +736,11 @@ describe("ModelResolver", () => {
headers: { "x-aisdk": "header" }, headers: { "x-aisdk": "header" },
body: { custom: true }, body: { custom: true },
}), }),
Credential.Key.make({ type: "key", key: "fallback-secret" }), Credential.Key.make({
type: "key",
key: "fallback-secret",
configuration: { accountId: "account" },
}),
{ {
loadAISDK: (runtime) => loadAISDK: (runtime) =>
Effect.sync(() => { Effect.sync(() => {
@@ -745,7 +749,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" }, settings: { project: "test", apiKey: "fallback-secret", accountId: "account" },
headers: { "x-aisdk": "header" }, headers: { "x-aisdk": "header" },
body: { custom: true }, body: { custom: true },
}) })
+9 -35
View File
@@ -1,5 +1,5 @@
import { Plugin } from "@opencode-ai/plugin/effect" import { Plugin } from "@opencode-ai/plugin/effect"
import type { IntegrationMethodRegistration } from "@opencode-ai/plugin/effect/integration" import type { IntegrationMethod, IntegrationMethodRegistration } from "@opencode-ai/plugin/effect/integration"
import { Agent } from "@opencode-ai/core/agent" import { Agent } from "@opencode-ai/core/agent"
import { Catalog } from "@opencode-ai/core/catalog" import { Catalog } from "@opencode-ai/core/catalog"
import { Credential } from "@opencode-ai/core/credential" import { Credential } from "@opencode-ai/core/credential"
@@ -15,7 +15,6 @@ 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"]>
} }
export function host(overrides: Overrides = {}): Plugin.Context { export function host(overrides: Overrides = {}): Plugin.Context {
return { return {
app: overrides.app ?? { name: "test", version: "test", channel: "test" }, app: overrides.app ?? { name: "test", version: "test", channel: "test" },
@@ -278,7 +277,7 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
update: (id, update) => draft.update(Integration.ID.make(id), update), update: (id, update) => draft.update(Integration.ID.make(id), update),
remove: (id) => draft.remove(Integration.ID.make(id)), remove: (id) => draft.remove(Integration.ID.make(id)),
method: { method: {
list: (id) => draft.method.list(Integration.ID.make(id)).map(method), list: (id) => draft.method.list(Integration.ID.make(id)),
update: (input) => { update: (input) => {
if ("authorize" in input) { if ("authorize" in input) {
const methodID = Integration.MethodID.make(input.method.id) const methodID = Integration.MethodID.make(input.method.id)
@@ -286,8 +285,8 @@ 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: { ...input.method, id: methodID }, method: { ...input.method, id: methodID },
authorize: (inputs) => authorize: (answer) =>
input.authorize(inputs).pipe( input.authorize(answer).pipe(
Effect.map((authorization) => { Effect.map((authorization) => {
if (authorization.mode === "auto") { if (authorization.mode === "auto") {
return { return {
@@ -336,7 +335,7 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
if (input.method.type === "env") { if (input.method.type === "env") {
draft.method.update({ draft.method.update({
integrationID: Integration.ID.make(input.integrationID), integrationID: Integration.ID.make(input.integrationID),
method: { ...input.method, names: [...input.method.names] }, method: input.method,
}) })
return return
} }
@@ -346,7 +345,6 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
method: { method: {
...input.method, ...input.method,
id: Integration.MethodID.make(input.method.id), id: Integration.MethodID.make(input.method.id),
command: [...input.method.command],
}, },
}) })
return return
@@ -401,35 +399,11 @@ 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) { function internalMethod(value: IntegrationMethod): Integration.Method {
if (value.type === "env") return { type: value.type, names: [...value.names] } if (value.type === "oauth" || value.type === "command") {
if (value.type === "key") return { type: value.type, label: value.label } return { ...value, id: Integration.MethodID.make(value.id) }
if (value.type === "command") return { ...value, command: [...value.command] }
return {
type: value.type,
id: value.id,
label: value.label,
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 {
if (value.type === "env") return value
if (value.type === "key") return value
if (value.type === "command") {
return {
...value,
id: Integration.MethodID.make(value.id),
command: [...value.command],
}
}
return {
...value,
id: Integration.MethodID.make(value.id),
} }
return value
} }
function agentInfo(value: Agent.Info) { function agentInfo(value: Agent.Info) {
@@ -8,6 +8,7 @@ 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"
@@ -60,6 +61,27 @@ 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",
form: [
{
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* () {
@@ -195,7 +217,17 @@ 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,11 +1,13 @@
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"
@@ -102,6 +104,24 @@ 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",
form: [
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(
{ {
@@ -357,7 +377,16 @@ 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,6 +7,7 @@ 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"
@@ -79,6 +80,29 @@ 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",
form: [
{
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* () {
@@ -91,6 +115,9 @@ 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({
@@ -135,7 +162,16 @@ 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")),
@@ -1,5 +1,4 @@
import { AISDK } from "@opencode-ai/core/aisdk" import { AISDK } from "@opencode-ai/core/aisdk"
import { App } from "@opencode-ai/core/app"
import { describe, expect, test } from "bun:test" import { describe, expect, test } from "bun:test"
import { Effect } from "effect" import { Effect } from "effect"
import { Catalog } from "@opencode-ai/core/catalog" import { Catalog } from "@opencode-ai/core/catalog"
@@ -7,8 +6,11 @@ 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 { copilotBaseURL, copilotFetch, GithubCopilotPlugin } from "@opencode-ai/core/plugin/provider/github-copilot" import { copilotBaseURL, copilotFetch, GithubCopilotPlugin } from "@opencode-ai/core/plugin/provider/github-copilot"
import { CopilotModels } from "@opencode-ai/core/github-copilot/models"
import { Provider } from "@opencode-ai/core/provider" import { Provider } from "@opencode-ai/core/provider"
import { Integration } from "@opencode-ai/core/integration" import { Integration } from "@opencode-ai/core/integration"
import { Credential } from "@opencode-ai/core/credential"
import { ModelResolver } from "@opencode-ai/core/model-resolver"
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"
@@ -57,11 +59,37 @@ 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",
prompts: expect.any(Array), form: expect.any(Array),
}) })
}), }),
) )
it.effect("removes the generic key method", () =>
Effect.gen(function* () {
const integrations = yield* Integration.Service
yield* integrations.transform((draft) => {
draft.method.update({
integrationID: Integration.ID.make("github-copilot"),
method: { type: "key" },
})
draft.method.update({
integrationID: Integration.ID.make("github-copilot"),
method: { type: "env", names: ["GITHUB_TOKEN"] },
})
})
yield* addPlugin()
expect((yield* integrations.get(Integration.ID.make("github-copilot")))?.methods).toEqual([
{ type: "env", names: ["GITHUB_TOKEN"] },
{
id: Integration.MethodID.make("device"),
type: "oauth",
label: "Login with GitHub Copilot",
form: expect.any(Array),
},
])
}),
)
it.live("adds Copilot authentication and request metadata headers", () => it.live("adds Copilot authentication and request metadata headers", () =>
Effect.gen(function* () { Effect.gen(function* () {
const requests: Headers[] = [] const requests: Headers[] = []
@@ -72,7 +100,6 @@ describe("GithubCopilotPlugin", () => {
return Response.json({ ok: true }) return Response.json({ ok: true })
}, },
false, false,
App.make({ name: "test", version: "1.2.3", channel: "beta" }),
) )
yield* Effect.promise(() => yield* Effect.promise(() =>
send("https://api.githubcopilot.com/chat/completions", { send("https://api.githubcopilot.com/chat/completions", {
@@ -88,7 +115,10 @@ describe("GithubCopilotPlugin", () => {
expect(requests[0]?.get("x-initiator")).toBe("user") expect(requests[0]?.get("x-initiator")).toBe("user")
expect(requests[0]?.get("copilot-vision-request")).toBe("true") expect(requests[0]?.get("copilot-vision-request")).toBe("true")
expect(requests[0]?.get("x-github-api-version")).toBe("2026-06-01") expect(requests[0]?.get("x-github-api-version")).toBe("2026-06-01")
expect(requests[0]?.get("user-agent")).toBe("opencode/beta/1.2.3/test") expect(requests[0]?.get("user-agent")).toBe("GitHubCopilotChat/0.26.7")
expect(requests[0]?.get("editor-version")).toBe("vscode/1.99.3")
expect(requests[0]?.get("editor-plugin-version")).toBe("copilot-chat/0.26.7")
expect(requests[0]?.get("copilot-integration-id")).toBe("vscode-chat")
}), }),
) )
@@ -120,6 +150,54 @@ describe("GithubCopilotPlugin", () => {
}), }),
) )
it.effect("routes all Copilot protocols through Copilot-owned SDK hooks", () =>
Effect.gen(function* () {
const catalog = yield* Catalog.Service
yield* catalog.transform((draft) => {
draft.provider.update(Provider.ID.githubCopilot, (provider) => {
provider.package = Provider.aisdk("@ai-sdk/openai-compatible")
})
draft.model.update(Provider.ID.githubCopilot, Model.ID.make("claude-sonnet"), (model) => {
model.package = Provider.aisdk("@ai-sdk/anthropic")
})
})
yield* addPlugin()
expect(required(yield* catalog.provider.get(Provider.ID.githubCopilot)).package).toBe(
Provider.aisdk(CopilotModels.Package.OpenAI),
)
expect(
required(yield* catalog.model.get(Provider.ID.githubCopilot, Model.ID.make("claude-sonnet"))).package,
).toBe(Provider.aisdk(CopilotModels.Package.Anthropic))
const fallback = yield* ModelResolver.fromCatalogModel(
Model.Info.make({
...Model.Info.default(Provider.ID.openai, Model.ID.make("fallback")),
package: Provider.aisdk("@ai-sdk/openai"),
settings: { baseURL: "https://openai.example/v1" },
}),
)
const resolved = yield* ModelResolver.fromCatalogModel(
required(yield* catalog.model.get(Provider.ID.githubCopilot, Model.ID.make("claude-sonnet"))),
Credential.OAuth.make({
type: "oauth",
methodID: Integration.MethodID.make("device"),
refresh: "github-token",
access: "github-token",
expires: 0,
}),
{
loadAISDK: (runtime) =>
Effect.sync(() => {
expect(runtime.settings?.apiKey).toBe("github-token")
return fallback
}),
},
)
expect(resolved).toBe(fallback)
}),
)
it.effect("selects languageModel when responses and chat are absent", () => it.effect("selects languageModel when responses and chat are absent", () =>
Effect.gen(function* () { Effect.gen(function* () {
const plugin = yield* Plugin.Service const plugin = yield* Plugin.Service
@@ -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"),
inputs: { server: `${server.url.origin}/console///?ignored=true#ignored` }, answer: { 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"),
inputs: { server: "ftp://console.example.com" }, answer: { server: "ftp://console.example.com" },
}) })
.pipe(Effect.flip) .pipe(Effect.flip)
expect(error).toBeInstanceOf(Integration.AuthorizationError) expect(error).toBeInstanceOf(Integration.AuthorizationError)
@@ -163,6 +163,21 @@ describe("OpencodePlugin", () => {
}), }),
) )
it.effect("rejects non-string OpenCode servers", () =>
Effect.gen(function* () {
yield* addPlugin()
const error = yield* (yield* Integration.Service).oauth
.connect({
integrationID: Integration.ID.make("opencode"),
methodID: Integration.MethodID.make("device"),
answer: { server: true },
})
.pipe(Effect.flip)
expect(error).toBeInstanceOf(Integration.AuthorizationError)
expect(String(error.cause)).toContain("Invalid OpenCode server URL: expected string")
}),
)
it.live("loads providers and models from the connected OpenCode server", () => it.live("loads providers and models from the connected OpenCode server", () =>
Effect.acquireUseRelease( Effect.acquireUseRelease(
Effect.sync(() => { Effect.sync(() => {
+4 -1
View File
@@ -129,7 +129,10 @@ 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({ integrationID: Integration.ID.make("parallel"), key: "parallel-secret" }) yield* integrations.connection.key({
integrationID: Integration.ID.make("parallel"),
key: "parallel-secret",
})
const output = yield* websearch.query({ const output = yield* websearch.query({
query: "effect layers", query: "effect layers",
-5
View File
@@ -90,15 +90,10 @@ 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],
+55 -67
View File
@@ -1,7 +1,7 @@
import fs from "fs/promises" import fs from "fs/promises"
import path from "path" import path from "path"
import { describe, expect } from "bun:test" import { describe, expect } from "bun:test"
import { Deferred, Effect, Fiber, Layer } from "effect" import { Effect, Layer } from "effect"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { LayerNode } from "@opencode-ai/util/effect/layer-node" import { LayerNode } from "@opencode-ai/util/effect/layer-node"
import { Environment } from "@opencode-ai/core/environment" import { Environment } from "@opencode-ai/core/environment"
@@ -40,7 +40,6 @@ const assertions: Permission.AssertInput[] = []
const writes: string[] = [] const writes: string[] = []
let reads = 0 let reads = 0
let denyAction: string | undefined let denyAction: string | undefined
let afterPermission = (_input: Permission.AssertInput): Effect.Effect<void> => Effect.void
let afterRead = (_target: string, _content: Uint8Array): Effect.Effect<void> => Effect.void let afterRead = (_target: string, _content: Uint8Array): Effect.Effect<void> => Effect.void
let formatFile = (_target: string): Effect.Effect<boolean> => Effect.succeed(false) let formatFile = (_target: string): Effect.Effect<boolean> => Effect.succeed(false)
@@ -49,7 +48,6 @@ const permission = Layer.succeed(
Permission.Service.of({ Permission.Service.of({
assert: (input) => assert: (input) =>
Effect.sync(() => assertions.push(input)).pipe( Effect.sync(() => assertions.push(input)).pipe(
Effect.andThen(Effect.suspend(() => afterPermission(input))),
Effect.andThen( Effect.andThen(
input.action === denyAction input.action === denyAction
? Effect.fail( ? Effect.fail(
@@ -79,7 +77,6 @@ const reset = () => {
writes.length = 0 writes.length = 0
reads = 0 reads = 0
denyAction = undefined denyAction = undefined
afterPermission = () => Effect.void
afterRead = () => Effect.void afterRead = () => Effect.void
formatFile = () => Effect.succeed(false) formatFile = () => Effect.succeed(false)
} }
@@ -177,7 +174,17 @@ describe("EditTool", () => {
}) })
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\nrest\n") expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\nrest\n")
expect(assertions).toMatchObject([{ sessionID, action: "edit", resources: ["hello.txt"], save: ["*"] }]) expect(assertions).toMatchObject([{ sessionID, action: "edit", resources: ["hello.txt"], save: ["*"] }])
expect(assertions[0]?.metadata).toBeUndefined() expect(assertions[0]?.metadata).toMatchObject({
files: [
{
file: "hello.txt",
status: "modified",
additions: 1,
deletions: 1,
patch: expect.stringContaining("-before\n+after"),
},
],
})
expect(writes).toEqual([yield* Effect.promise(() => fs.realpath(target))]) expect(writes).toEqual([yield* Effect.promise(() => fs.realpath(target))])
}), }),
), ),
@@ -342,7 +349,7 @@ describe("EditTool", () => {
error: { type: "permission.rejected", message: "Permission denied: edit" }, error: { type: "permission.rejected", message: "Permission denied: edit" },
}) })
expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"]) expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
expect(reads).toBe(0) expect(reads).toBe(1)
expect(writes).toEqual([]) expect(writes).toEqual([])
expect(yield* Effect.promise(() => fs.readFile(external, "utf8"))).toBe("before") expect(yield* Effect.promise(() => fs.readFile(external, "utf8"))).toBe("before")
}), }),
@@ -379,7 +386,7 @@ describe("EditTool", () => {
}) })
expect(missing).toEqual(matching) expect(missing).toEqual(matching)
expect(assertions.map((input) => input.action)).toEqual(["edit", "edit"]) expect(assertions.map((input) => input.action)).toEqual(["edit", "edit"])
expect(reads).toBe(0) expect(reads).toBe(2)
expect(writes).toEqual([]) expect(writes).toEqual([])
}), }),
), ),
@@ -636,77 +643,58 @@ describe("EditTool", () => {
(tmp) => { (tmp) => {
reset() reset()
const target = path.join(tmp.path, "concurrent.txt") const target = path.join(tmp.path, "concurrent.txt")
return Effect.gen(function* () { afterRead = () => (reads === 1 ? Effect.sleep("50 millis") : Effect.void)
yield* Effect.promise(() => fs.writeFile(target, "one\ntwo\n")) return Effect.promise(() => fs.writeFile(target, "one\ntwo\n")).pipe(
const firstRead = yield* Deferred.make<void>() Effect.andThen(
const releaseFirst = yield* Deferred.make<void>() withTool(tmp.path, (registry) =>
const secondApproved = yield* Deferred.make<void>() Effect.all(
afterRead = () => [
reads === 1 executeTool(
? Deferred.succeed(firstRead, undefined).pipe(Effect.andThen(Deferred.await(releaseFirst))) registry,
: Effect.void call({ path: "concurrent.txt", oldString: "one", newString: "ONE" }, "call-edit-one"),
afterPermission = (input) => ),
input.source?.id === "call-edit-two" executeTool(
? Deferred.succeed(secondApproved, undefined).pipe(Effect.asVoid) registry,
: Effect.void call({ path: "concurrent.txt", oldString: "two", newString: "TWO" }, "call-edit-two"),
),
const first = yield* withTool(tmp.path, (registry) => ],
executeTool( { concurrency: "unbounded" },
registry, ),
call({ path: "concurrent.txt", oldString: "one", newString: "ONE" }, "call-edit-one"),
), ),
).pipe(Effect.forkChild) ),
yield* Deferred.await(firstRead) Effect.andThen((results) =>
const second = yield* withTool(tmp.path, (registry) => Effect.gen(function* () {
executeTool( expect(results.map((result) => result.status)).toEqual(["completed", "completed"])
registry, expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("ONE\nTWO\n")
call({ path: "concurrent.txt", oldString: "two", newString: "TWO" }, "call-edit-two"), }),
), ),
).pipe(Effect.forkChild) )
yield* Deferred.await(secondApproved)
expect(reads).toBe(1)
yield* Deferred.succeed(releaseFirst, undefined)
expect((yield* Fiber.join(first)).status).toBe("completed")
expect((yield* Fiber.join(second)).status).toBe("completed")
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("ONE\nTWO\n")
})
}, },
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
), ),
) )
it.live("validates current content after permission succeeds", () => it.live("applies the edit when content changes after matching", () =>
Effect.acquireUseRelease( Effect.acquireUseRelease(
Effect.promise(() => tmpdir()), Effect.promise(() => tmpdir()),
(tmp) => { (tmp) => {
reset() reset()
const target = path.join(tmp.path, "concurrent.txt") const target = path.join(tmp.path, "concurrent.txt")
return Effect.gen(function* () { afterRead = () => (reads === 1 ? Effect.promise(() => fs.writeFile(target, "newer\n")) : Effect.void)
yield* Effect.promise(() => fs.writeFile(target, "before\n")) return Effect.promise(() => fs.writeFile(target, "before\n")).pipe(
const permissionReached = yield* Deferred.make<void>() Effect.andThen(
const releasePermission = yield* Deferred.make<void>() withTool(tmp.path, (registry) =>
afterPermission = (input) => executeTool(registry, call({ path: "concurrent.txt", oldString: "before", newString: "after" })),
input.action === "edit" ),
? Deferred.succeed(permissionReached, undefined).pipe(Effect.andThen(Deferred.await(releasePermission))) ),
: Effect.void Effect.andThen((result) =>
Effect.gen(function* () {
const edit = yield* withTool(tmp.path, (registry) => expect(result).toMatchObject({ status: "completed", output: { replacements: 1 } })
executeTool(registry, call({ path: "concurrent.txt", oldString: "before", newString: "after" })), expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n")
).pipe(Effect.forkChild) expect(writes).toEqual([target])
yield* Deferred.await(permissionReached) }),
expect(reads).toBe(0) ),
yield* Effect.promise(() => fs.writeFile(target, "newer\n")) )
yield* Deferred.succeed(releasePermission, undefined)
expect(yield* Fiber.join(edit)).toMatchObject({
status: "error",
error: { message: expect.stringContaining("Could not find oldString") },
})
expect(reads).toBe(1)
expect(writes).toEqual([])
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("newer\n")
})
}, },
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
), ),
+45 -78
View File
@@ -1,7 +1,7 @@
import fs from "fs/promises" import fs from "fs/promises"
import path from "path" import path from "path"
import { describe, expect } from "bun:test" import { describe, expect } from "bun:test"
import { Deferred, Effect, Exit, Fiber, Layer, Schema } from "effect" import { Effect, Exit, Layer, Schema } from "effect"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { LayerNode } from "@opencode-ai/util/effect/layer-node" import { LayerNode } from "@opencode-ai/util/effect/layer-node"
import { Environment } from "@opencode-ai/core/environment" import { Environment } from "@opencode-ai/core/environment"
@@ -33,11 +33,9 @@ let denyAction: string | undefined
let failRemoveTarget: string | undefined let failRemoveTarget: string | undefined
let failRemoveErrorTarget: string | undefined let failRemoveErrorTarget: string | undefined
let failWriteTarget: string | undefined let failWriteTarget: string | undefined
let reads = 0
let readsBeforeEditApproval = 0 let readsBeforeEditApproval = 0
let editApproved = false let editApproved = false
let afterEditApproval = (_input: Permission.AssertInput): Effect.Effect<void> => Effect.void let afterEditApproval = (): Effect.Effect<void> => Effect.void
let afterRead = (_target: string, _content: Uint8Array): Effect.Effect<void> => Effect.void
let formatFile = (_target: string): Effect.Effect<boolean> => Effect.succeed(false) let formatFile = (_target: string): Effect.Effect<boolean> => Effect.succeed(false)
const permission = Layer.succeed( const permission = Layer.succeed(
@@ -48,7 +46,7 @@ const permission = Layer.succeed(
assertions.push(input) assertions.push(input)
if (input.action === "edit") editApproved = true if (input.action === "edit") editApproved = true
}).pipe( }).pipe(
Effect.andThen(input.action === "edit" ? Effect.suspend(() => afterEditApproval(input)) : Effect.void), Effect.andThen(input.action === "edit" ? Effect.suspend(afterEditApproval) : Effect.void),
Effect.andThen( Effect.andThen(
input.action === denyAction input.action === denyAction
? Effect.fail( ? Effect.fail(
@@ -79,11 +77,9 @@ const reset = () => {
failRemoveTarget = undefined failRemoveTarget = undefined
failRemoveErrorTarget = undefined failRemoveErrorTarget = undefined
failWriteTarget = undefined failWriteTarget = undefined
reads = 0
readsBeforeEditApproval = 0 readsBeforeEditApproval = 0
editApproved = false editApproved = false
afterEditApproval = () => Effect.void afterEditApproval = () => Effect.void
afterRead = () => Effect.void
formatFile = () => Effect.succeed(false) formatFile = () => Effect.succeed(false)
} }
@@ -108,12 +104,8 @@ const withTool = <A, E, R>(
transformEnvironmentFiles(activeLocation, (files) => ({ transformEnvironmentFiles(activeLocation, (files) => ({
read: (target, range) => read: (target, range) =>
Effect.sync(() => { Effect.sync(() => {
reads++
if (!editApproved) readsBeforeEditApproval++ if (!editApproved) readsBeforeEditApproval++
}).pipe( }).pipe(Effect.andThen(files.read(target, range))),
Effect.andThen(files.read(target, range)),
Effect.tap((result) => Effect.suspend(() => afterRead(target, result.bytes))),
),
remove: (target) => { remove: (target) => {
if (failRemoveTarget && path.basename(target) === failRemoveTarget) if (failRemoveTarget && path.basename(target) === failRemoveTarget)
return Effect.die("forced remove failure") return Effect.die("forced remove failure")
@@ -227,10 +219,14 @@ describe("PatchTool", () => {
action: "edit", action: "edit",
resources: ["nested/new.txt", "update.txt", "remove.txt"], resources: ["nested/new.txt", "update.txt", "remove.txt"],
save: ["*"], save: ["*"],
metadata: {
filepath: "nested/new.txt, update.txt, remove.txt",
diff: expect.stringContaining("Index:"),
files: expect.any(Array),
},
}, },
]) ])
expect(assertions[0]?.metadata).toBeUndefined() expect(readsBeforeEditApproval).toBe(2)
expect(readsBeforeEditApproval).toBe(0)
expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "nested/new.txt"), "utf8"))).toBe( expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "nested/new.txt"), "utf8"))).toBe(
"created\n", "created\n",
) )
@@ -271,69 +267,40 @@ describe("PatchTool", () => {
it.live("serializes concurrent patch transactions", () => it.live("serializes concurrent patch transactions", () =>
withTempTool((directory, registry) => { withTempTool((directory, registry) => {
const target = path.join(directory, "concurrent.txt") const target = path.join(directory, "concurrent.txt")
return Effect.gen(function* () { afterEditApproval = () =>
yield* Effect.promise(() => fs.writeFile(target, "one\ntwo\n")) assertions.filter((input) => input.action === "edit").length === 1 ? Effect.sleep("50 millis") : Effect.void
const firstRead = yield* Deferred.make<void>() return Effect.promise(() => fs.writeFile(target, "one\ntwo\n")).pipe(
const releaseFirst = yield* Deferred.make<void>() Effect.andThen(
const secondApproved = yield* Deferred.make<void>() Effect.all(
afterRead = () => [
reads === 1 executeTool(
? Deferred.succeed(firstRead, undefined).pipe(Effect.andThen(Deferred.await(releaseFirst))) registry,
: Effect.void call(
afterEditApproval = (input) => "*** Begin Patch\n*** Update File: concurrent.txt\n@@\n-one\n+ONE\n*** End Patch",
input.source?.id === "call-patch-two" "call-patch-one",
? Deferred.succeed(secondApproved, undefined).pipe(Effect.asVoid) ),
: Effect.void ),
executeTool(
const first = yield* executeTool( registry,
registry, call(
call("*** Begin Patch\n*** Update File: concurrent.txt\n@@\n-one\n+ONE\n*** End Patch", "call-patch-one"), "*** Begin Patch\n*** Update File: concurrent.txt\n@@\n-two\n+TWO\n*** End Patch",
).pipe(Effect.forkChild) "call-patch-two",
yield* Deferred.await(firstRead) ),
const second = yield* executeTool( ),
registry, ],
call("*** Begin Patch\n*** Update File: concurrent.txt\n@@\n-two\n+TWO\n*** End Patch", "call-patch-two"), { concurrency: "unbounded" },
).pipe(Effect.forkChild) ),
yield* Deferred.await(secondApproved) ),
expect(reads).toBe(1) Effect.andThen((results) =>
Effect.gen(function* () {
yield* Deferred.succeed(releaseFirst, undefined) expect(results.map((result) => result.status)).toEqual(["completed", "completed"])
expect((yield* Fiber.join(first)).status).toBe("completed") expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("ONE\nTWO\n")
expect((yield* Fiber.join(second)).status).toBe("completed") }),
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("ONE\nTWO\n") ),
}) )
}), }),
) )
it.live("validates patch context after permission succeeds", () =>
withTempTool((directory, registry) =>
Effect.gen(function* () {
const target = path.join(directory, "current.txt")
yield* Effect.promise(() => fs.writeFile(target, "before\n"))
const permissionReached = yield* Deferred.make<void>()
const releasePermission = yield* Deferred.make<void>()
afterEditApproval = () =>
Deferred.succeed(permissionReached, undefined).pipe(Effect.andThen(Deferred.await(releasePermission)))
const patch = yield* executeTool(
registry,
call("*** Begin Patch\n*** Update File: current.txt\n@@\n-before\n+after\n*** End Patch"),
).pipe(Effect.forkChild)
yield* Deferred.await(permissionReached)
expect(reads).toBe(0)
yield* Effect.promise(() => fs.writeFile(target, "newer\n"))
yield* Deferred.succeed(releasePermission, undefined)
expect(yield* Fiber.join(patch)).toMatchObject({
status: "error",
error: { message: expect.stringContaining("Failed to find expected lines") },
})
expect(reads).toBe(1)
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("newer\n")
}),
),
)
it.live("returns file diffs for final formatted content", () => it.live("returns file diffs for final formatted content", () =>
withTempTool((directory, registry) => { withTempTool((directory, registry) => {
const target = path.join(directory, "formatted.txt") const target = path.join(directory, "formatted.txt")
@@ -816,7 +783,7 @@ describe("PatchTool", () => {
), ),
) )
it.live("approves external-directory and edit access before reading", () => it.live("approves an external directory before reading and requests edit permission afterward", () =>
Effect.acquireUseRelease( Effect.acquireUseRelease(
Effect.promise(() => Promise.all([tmpdir(), tmpdir()])), Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
([active, outside]) => { ([active, outside]) => {
@@ -833,7 +800,7 @@ describe("PatchTool", () => {
), ),
).toMatchObject({ status: "completed" }) ).toMatchObject({ status: "completed" })
expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"]) expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
expect(readsBeforeEditApproval).toBe(0) expect(readsBeforeEditApproval).toBe(1)
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n") expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n")
}), }),
), ),
@@ -964,7 +931,7 @@ describe("PatchTool", () => {
), ),
) )
it.live("approves a relative external target before reading", () => it.live("approves a relative external target before reading and requests edit permission afterward", () =>
Effect.acquireUseRelease( Effect.acquireUseRelease(
Effect.promise(() => Promise.all([tmpdir(), tmpdir()])), Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
([active, outside]) => { ([active, outside]) => {
@@ -982,7 +949,7 @@ describe("PatchTool", () => {
), ),
).toMatchObject({ status: "completed" }) ).toMatchObject({ status: "completed" })
expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"]) expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
expect(readsBeforeEditApproval).toBe(0) expect(readsBeforeEditApproval).toBe(1)
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n") expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n")
}), }),
), ),
+25 -131
View File
@@ -1,7 +1,7 @@
import fs from "fs/promises" import fs from "fs/promises"
import path from "path" import path from "path"
import { describe, expect } from "bun:test" import { describe, expect } from "bun:test"
import { Deferred, Effect, Fiber, Layer } from "effect" import { Effect, Layer } from "effect"
import { FileMutation } from "@opencode-ai/core/file-mutation" import { FileMutation } from "@opencode-ai/core/file-mutation"
import { Formatter } from "@opencode-ai/core/formatter" import { Formatter } from "@opencode-ai/core/formatter"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
@@ -13,7 +13,6 @@ import { Permission } from "@opencode-ai/core/permission"
import { AbsolutePath } from "@opencode-ai/core/schema" import { AbsolutePath } from "@opencode-ai/core/schema"
import { Session } from "@opencode-ai/core/session" import { Session } from "@opencode-ai/core/session"
import { Tool } from "@opencode-ai/core/tool" import { Tool } from "@opencode-ai/core/tool"
import { EditTool } from "@opencode-ai/core/tool/plugin/edit"
import { WriteTool } from "@opencode-ai/core/tool/plugin/write" import { WriteTool } from "@opencode-ai/core/tool/plugin/write"
import { transformEnvironmentFiles } from "./fixture/environment" import { transformEnvironmentFiles } from "./fixture/environment"
import { location } from "./fixture/location" import { location } from "./fixture/location"
@@ -28,26 +27,10 @@ const writeToolNode = makeLocationNode({
deps: [Tool.node, LocationMutation.node, FileMutation.node, Environment.node, Formatter.node, Permission.node], deps: [Tool.node, LocationMutation.node, FileMutation.node, Environment.node, Formatter.node, Permission.node],
}) })
const editToolNode = makeLocationNode({
name: "test/edit-tool-plugin",
layer: Layer.effectDiscard(registerToolPlugin(EditTool.Plugin)),
deps: [
Tool.node,
LocationMutation.node,
FileMutation.node,
Environment.node,
Formatter.node,
Location.node,
Permission.node,
],
})
const sessionID = Session.ID.make("ses_write_tool_test") const sessionID = Session.ID.make("ses_write_tool_test")
const assertions: Permission.AssertInput[] = [] const assertions: Permission.AssertInput[] = []
const writes: string[] = [] const writes: string[] = []
let reads = 0
let formatFile = (_target: string): Effect.Effect<boolean> => Effect.succeed(false) let formatFile = (_target: string): Effect.Effect<boolean> => Effect.succeed(false)
let afterPermission = (_input: Permission.AssertInput): Effect.Effect<void> => Effect.void
let denyAction: string | undefined let denyAction: string | undefined
const permission = Layer.succeed( const permission = Layer.succeed(
@@ -55,7 +38,6 @@ const permission = Layer.succeed(
Permission.Service.of({ Permission.Service.of({
assert: (input) => assert: (input) =>
Effect.sync(() => assertions.push(input)).pipe( Effect.sync(() => assertions.push(input)).pipe(
Effect.andThen(Effect.suspend(() => afterPermission(input))),
Effect.andThen( Effect.andThen(
input.action === denyAction input.action === denyAction
? Effect.fail( ? Effect.fail(
@@ -83,17 +65,11 @@ const formatter = Layer.mock(Formatter.Service, {
const reset = () => { const reset = () => {
assertions.length = 0 assertions.length = 0
writes.length = 0 writes.length = 0
reads = 0
formatFile = () => Effect.succeed(false) formatFile = () => Effect.succeed(false)
afterPermission = () => Effect.void
denyAction = undefined denyAction = undefined
} }
const withTool = <A, E, R>( const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) => Effect.Effect<A, E, R>) => {
directory: string,
body: (registry: Tool.Interface) => Effect.Effect<A, E, R>,
options?: { edit?: boolean },
) => {
const activeLocation = Layer.succeed( const activeLocation = Layer.succeed(
Location.Service, Location.Service,
Location.Service.of(location({ directory: AbsolutePath.make(directory) })), Location.Service.of(location({ directory: AbsolutePath.make(directory) })),
@@ -103,18 +79,11 @@ const withTool = <A, E, R>(
}).pipe( }).pipe(
Effect.provide( Effect.provide(
AppNodeBuilder.build( AppNodeBuilder.build(
LayerNode.group([ LayerNode.group([Tool.node, Tool.node, LocationMutation.node, FileMutation.node, writeToolNode]),
Tool.node,
LocationMutation.node,
FileMutation.node,
writeToolNode,
...(options?.edit ? [editToolNode] : []),
]),
[ [
[ [
Environment.node, Environment.node,
transformEnvironmentFiles(activeLocation, (files) => ({ transformEnvironmentFiles(activeLocation, (files) => ({
read: (target, range) => Effect.sync(() => reads++).pipe(Effect.andThen(files.read(target, range))),
write: (target, content) => write: (target, content) =>
Effect.sync(() => writes.push(target)).pipe(Effect.andThen(files.write(target, content))), Effect.sync(() => writes.push(target)).pipe(Effect.andThen(files.write(target, content))),
})), })),
@@ -134,12 +103,6 @@ const call = (input: typeof WriteTool.Input.Type, id = "call-write") => ({
call: { type: "tool-call" as const, id, name: "write", input }, call: { type: "tool-call" as const, id, name: "write", input },
}) })
const editCall = (input: typeof EditTool.Input.Type, id = "call-edit") => ({
sessionID,
...toolIdentity,
call: { type: "tool-call" as const, id, name: "edit", input },
})
const it = testEffect(Layer.empty) const it = testEffect(Layer.empty)
describe("WriteTool", () => { describe("WriteTool", () => {
@@ -166,7 +129,17 @@ describe("WriteTool", () => {
"created", "created",
) )
expect(assertions).toMatchObject([{ sessionID, action: "edit", resources: ["src/new.txt"], save: ["*"] }]) expect(assertions).toMatchObject([{ sessionID, action: "edit", resources: ["src/new.txt"], save: ["*"] }])
expect(assertions[0]?.metadata).toBeUndefined() expect(assertions[0]?.metadata).toMatchObject({
files: [
{
file: "src/new.txt",
status: "added",
additions: 1,
deletions: 0,
patch: expect.stringContaining("+created"),
},
],
})
expect(writes).toEqual([path.join(yield* Effect.promise(() => fs.realpath(tmp.path)), "src", "new.txt")]) expect(writes).toEqual([path.join(yield* Effect.promise(() => fs.realpath(tmp.path)), "src", "new.txt")])
}), }),
) )
@@ -214,7 +187,17 @@ describe("WriteTool", () => {
if (settled.status !== "completed") return if (settled.status !== "completed") return
expect(settled.content).toEqual([{ type: "text", text: "Wrote file successfully: existing.txt" }]) expect(settled.content).toEqual([{ type: "text", text: "Wrote file successfully: existing.txt" }])
expect(settled.output).toMatchObject({ resource: "existing.txt", existed: true }) expect(settled.output).toMatchObject({ resource: "existing.txt", existed: true })
expect(assertions[0]?.metadata).toBeUndefined() expect(assertions[0]?.metadata).toMatchObject({
files: [
{
file: "existing.txt",
status: "modified",
additions: 1,
deletions: 1,
patch: expect.stringMatching(/-before[\s\S]*\+after/),
},
],
})
expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "existing.txt"), "utf8"))).toBe( expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "existing.txt"), "utf8"))).toBe(
"after", "after",
) )
@@ -429,93 +412,4 @@ describe("WriteTool", () => {
), ),
), ),
) )
it.live("authorizes an edit while a write holds the same-path execution lock", () =>
Effect.acquireUseRelease(
Effect.promise(() => tmpdir()),
(tmp) => {
reset()
const target = path.join(tmp.path, "shared.txt")
return Effect.gen(function* () {
yield* Effect.promise(() => fs.writeFile(target, "initial"))
const formatting = yield* Deferred.make<void>()
const releaseFormatting = yield* Deferred.make<void>()
const editApproved = yield* Deferred.make<void>()
let formats = 0
formatFile = () =>
++formats === 1
? Deferred.succeed(formatting, undefined).pipe(
Effect.andThen(Deferred.await(releaseFormatting)),
Effect.as(false),
)
: Effect.succeed(false)
afterPermission = (input) =>
input.source?.id === "call-serialized-edit" && input.action === "edit"
? Deferred.succeed(editApproved, undefined).pipe(Effect.asVoid)
: Effect.void
const write = yield* withTool(
tmp.path,
(registry) =>
executeTool(registry, call({ path: "shared.txt", content: "before" }, "call-serialized-write")),
{ edit: true },
).pipe(Effect.forkChild)
yield* Deferred.await(formatting)
const edit = yield* withTool(
tmp.path,
(registry) =>
executeTool(
registry,
editCall({ path: "shared.txt", oldString: "before", newString: "after" }, "call-serialized-edit"),
),
{ edit: true },
).pipe(Effect.forkChild)
yield* Deferred.await(editApproved)
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("before")
yield* Deferred.succeed(releaseFormatting, undefined)
expect((yield* Fiber.join(write)).status).toBe("completed")
expect((yield* Fiber.join(edit)).status).toBe("completed")
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after")
})
},
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
),
)
it.live("does not hold the execution lock while waiting for permission", () =>
Effect.acquireUseRelease(
Effect.promise(() => tmpdir()),
(tmp) => {
reset()
const target = path.join(tmp.path, "shared.txt")
return Effect.gen(function* () {
yield* Effect.promise(() => fs.writeFile(target, "initial"))
const firstAsked = yield* Deferred.make<void>()
const releaseFirst = yield* Deferred.make<void>()
afterPermission = (input) =>
input.source?.id === "call-waiting-write" && input.action === "edit"
? Deferred.succeed(firstAsked, undefined).pipe(Effect.andThen(Deferred.await(releaseFirst)))
: Effect.void
const first = yield* withTool(tmp.path, (registry) =>
executeTool(registry, call({ path: "shared.txt", content: "first" }, "call-waiting-write")),
).pipe(Effect.forkChild)
yield* Deferred.await(firstAsked)
expect(reads).toBe(0)
const second = yield* withTool(tmp.path, (registry) =>
executeTool(registry, call({ path: "shared.txt", content: "second" }, "call-approved-write")),
)
expect(second.status).toBe("completed")
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("second")
yield* Deferred.succeed(releaseFirst, undefined)
expect((yield* Fiber.join(first)).status).toBe("completed")
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("first")
})
},
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
),
)
}) })
+9 -1
View File
@@ -1316,7 +1316,15 @@ export function write(
}).pipe(Effect.flatMap((content) => fs.writeFileString(join(directory, file.path), content))), }).pipe(Effect.flatMap((content) => fs.writeFileString(join(directory, file.path), content))),
{ concurrency: 8, discard: true }, { concurrency: 8, discard: true },
) )
yield* fs.writeFileString(manifest, JSON.stringify(output.files.map((file) => file.path).sort(), null, 2) + "\n") // Format the manifest with the same prettier settings as the repo-wide
// format pass, so `check:generated` stays clean after the generate bot
// reformats the tree.
const manifestJson = JSON.stringify(output.files.map((file) => file.path).sort())
const manifestContent = yield* Effect.tryPromise({
try: () => format(manifestJson, { filepath: manifest, parser: "json", printWidth: 120 }),
catch: (error) => new GenerationError({ reason: `Failed to format ${manifest}: ${String(error)}` }),
})
yield* fs.writeFileString(manifest, manifestContent)
}) })
} }
+1 -1
View File
@@ -16,7 +16,7 @@ describe("HttpApiCodegen.write", () => {
expect(writes).toEqual([ expect(writes).toEqual([
{ path: "/generated/session.ts", content: "export const session = {}\n" }, { path: "/generated/session.ts", content: "export const session = {}\n" },
{ path: "/generated/.httpapi-codegen.json", content: '[\n "session.ts"\n]\n' }, { path: "/generated/.httpapi-codegen.json", content: '["session.ts"]\n' },
]) ])
}).pipe( }).pipe(
Effect.provideService( Effect.provideService(
+34 -10
View File
@@ -1,19 +1,43 @@
import type { import type { ConnectionInfo } from "@opencode-ai/client"
ConnectionInfo,
IntegrationCommandMethod,
IntegrationEnvMethod,
IntegrationKeyMethod,
IntegrationMethod,
IntegrationOAuthMethod,
} 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 interface IntegrationOAuthMethod {
readonly id: string
readonly type: "oauth"
readonly label: string
readonly form?: Form.Fields
}
export interface IntegrationCommandMethod {
readonly id: string
readonly type: "command"
readonly label: string
readonly command: ReadonlyArray<string>
}
export interface IntegrationKeyMethod {
readonly type: "key"
readonly label?: string
readonly form?: Form.Fields
}
export interface IntegrationEnvMethod {
readonly type: "env"
readonly names: ReadonlyArray<string>
}
export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationEnvMethod
export type IntegrationOAuthAuthorization = { export type IntegrationOAuthAuthorization = {
readonly url: string readonly url: string
readonly instructions: string readonly instructions: string
@@ -31,7 +55,7 @@ export type IntegrationOAuthAuthorization = {
export type IntegrationOAuthMethodRegistration = { export type IntegrationOAuthMethodRegistration = {
readonly integrationID: string readonly integrationID: string
readonly method: IntegrationOAuthMethod readonly method: IntegrationOAuthMethod
readonly authorize: (inputs: IntegrationInputs) => Effect.Effect<IntegrationOAuthAuthorization, unknown, Scope.Scope> readonly authorize: (answer: Form.Answer) => 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
} }
+38 -11
View File
@@ -1,18 +1,42 @@
import type { import type { ConnectionInfo } from "@opencode-ai/client"
ConnectionInfo,
IntegrationCommandMethod,
IntegrationEnvMethod,
IntegrationKeyMethod,
IntegrationMethod,
IntegrationOAuthMethod,
} 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 interface IntegrationOAuthMethod {
readonly id: string
readonly type: "oauth"
readonly label: string
readonly form?: Form.Fields
}
export interface IntegrationCommandMethod {
readonly id: string
readonly type: "command"
readonly label: string
readonly command: ReadonlyArray<string>
}
export interface IntegrationKeyMethod {
readonly type: "key"
readonly label?: string
readonly form?: Form.Fields
}
export interface IntegrationEnvMethod {
readonly type: "env"
readonly names: ReadonlyArray<string>
}
export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationEnvMethod
export type IntegrationOAuthAuthorization = { export type IntegrationOAuthAuthorization = {
readonly url: string readonly url: string
readonly instructions: string readonly instructions: string
@@ -31,7 +55,7 @@ export type IntegrationOAuthAuthorization = {
export type IntegrationOAuthMethodRegistration = { export type IntegrationOAuthMethodRegistration = {
readonly integrationID: string readonly integrationID: string
readonly method: IntegrationOAuthMethod readonly method: IntegrationOAuthMethod
readonly authorize: (inputs: IntegrationInputs) => Promise<IntegrationOAuthAuthorization> readonly authorize: (answer: Form.Answer) => 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
} }
@@ -39,7 +63,10 @@ export type IntegrationOAuthMethodRegistration = {
export type IntegrationMethodRegistration = export type IntegrationMethodRegistration =
| IntegrationOAuthMethodRegistration | IntegrationOAuthMethodRegistration
| { readonly integrationID: string; readonly method: IntegrationCommandMethod } | { readonly integrationID: string; readonly method: IntegrationCommandMethod }
| { readonly integrationID: string; readonly method: IntegrationKeyMethod } | {
readonly integrationID: string
readonly method: IntegrationKeyMethod
}
| { readonly integrationID: string; readonly method: IntegrationEnvMethod } | { readonly integrationID: string; readonly method: IntegrationEnvMethod }
export interface IntegrationDraft { export interface IntegrationDraft {
+3 -3
View File
@@ -1,12 +1,11 @@
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", {
@@ -59,6 +58,7 @@ export const IntegrationGroup = HttpApiGroup.make("server.integration")
query: LocationQuery, query: LocationQuery,
payload: Schema.Struct({ payload: Schema.Struct({
key: Schema.String, key: Schema.String,
answer: Schema.optional(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,
inputs: Inputs, answer: Schema.optional(Form.Answer),
label: Schema.optional(Schema.String), label: Schema.optional(Schema.String),
}), }),
success: Location.response(Integration.Attempt), success: Location.response(Integration.Attempt),
+2
View File
@@ -5,6 +5,7 @@ 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"),
@@ -27,6 +28,7 @@ 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])
+3 -38
View File
@@ -7,6 +7,7 @@ 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
@@ -14,46 +15,12 @@ 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,
prompts: optional(Schema.Array(Prompt)), form: optional(Form.Fields),
}).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> {}
@@ -68,6 +35,7 @@ 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),
form: 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> {}
@@ -81,9 +49,6 @@ 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: {},
+2 -1
View File
@@ -58,6 +58,7 @@ 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,
answer: ctx.payload.answer,
label: ctx.payload.label, label: ctx.payload.label,
}), }),
) )
@@ -73,7 +74,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,
inputs: ctx.payload.inputs, answer: ctx.payload.answer,
label: ctx.payload.label, label: ctx.payload.label,
}), }),
), ),
+254 -43
View File
@@ -5,6 +5,10 @@ import type {
IntegrationInfo, IntegrationInfo,
IntegrationOauthConnectOutput, IntegrationOauthConnectOutput,
IntegrationOAuthMethod, IntegrationOAuthMethod,
FormAnswer,
FormField,
FormFields,
FormValue,
} 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"
@@ -18,6 +22,7 @@ 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 { formLabel, formToggleMultiselect, formValidateValue, type FormAnswerField } from "../util/form"
const INTEGRATION_PRIORITY: Record<string, number> = { const INTEGRATION_PRIORITY: Record<string, number> = {
opencode: 0, opencode: 0,
@@ -32,6 +37,10 @@ type ConnectMethod = Exclude<IntegrationInfo["methods"][number], { type: "env" }
type IntegrationAttempt = IntegrationOauthConnectOutput["data"] type IntegrationAttempt = IntegrationOauthConnectOutput["data"]
type CommandAttempt = IntegrationCommandConnectOutput["data"] type CommandAttempt = IntegrationCommandConnectOutput["data"]
type OnIntegrationConnected = (providerID?: string) => void type OnIntegrationConnected = (providerID?: string) => void
const CANCELLED = Symbol("cancelled")
const CUSTOM = Symbol("custom")
const OPEN = Symbol("open")
const SUBMIT = Symbol("submit")
export function integrationOptions(list: IntegrationInfo[]) { export function integrationOptions(list: IntegrationInfo[]) {
return list.toSorted( return list.toSorted(
@@ -181,7 +190,7 @@ function openMethod(
onConnected?: OnIntegrationConnected, onConnected?: OnIntegrationConnected,
) { ) {
if (method.type === "key") { if (method.type === "key") {
dialog.replace(() => <KeyMethod integration={integration} method={method} onConnected={onConnected} />) void beginKey(integration, method, dialog, onConnected)
return return
} }
if (method.type === "command") { if (method.type === "command") {
@@ -191,6 +200,21 @@ 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 answer = method.form
? await formAnswer(dialog, method.label ?? `Connect ${integration.name}`, method.form)
: undefined
if (answer === null) return
dialog.replace(() => (
<KeyMethod integration={integration} method={method} answer={answer} onConnected={onConnected} />
))
}
function CommandStarting(props: { function CommandStarting(props: {
integration: IntegrationInfo integration: IntegrationInfo
method: Extract<ConnectMethod, { type: "command" }> method: Extract<ConnectMethod, { type: "command" }>
@@ -336,6 +360,7 @@ 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" }>
answer?: FormAnswer
onConnected?: OnIntegrationConnected onConnected?: OnIntegrationConnected
}) { }) {
const data = useData() const data = useData()
@@ -356,6 +381,7 @@ function KeyMethod(props: {
integrationID: props.integration.id, integrationID: props.integration.id,
location: location(data), location: location(data),
key, key,
...(props.answer ? { answer: props.answer } : {}),
}) })
.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)))
@@ -373,17 +399,17 @@ async function beginOAuth(
dialog: ReturnType<typeof useDialog>, dialog: ReturnType<typeof useDialog>,
onConnected?: OnIntegrationConnected, onConnected?: OnIntegrationConnected,
) { ) {
const inputs = method.prompts?.length ? await promptInputs(dialog, method.prompts) : {} const answer = method.form ? await formAnswer(dialog, method.label, method.form) : undefined
if (inputs === null) return if (answer === null) return
dialog.replace(() => ( dialog.replace(() => (
<OAuthStarting integration={integration} method={method} inputs={inputs} onConnected={onConnected} /> <OAuthStarting integration={integration} method={method} answer={answer} onConnected={onConnected} />
)) ))
} }
function OAuthStarting(props: { function OAuthStarting(props: {
integration: IntegrationInfo integration: IntegrationInfo
method: IntegrationOAuthMethod method: IntegrationOAuthMethod
inputs: Record<string, string> answer?: FormAnswer
onConnected?: OnIntegrationConnected onConnected?: OnIntegrationConnected
}) { }) {
const data = useData() const data = useData()
@@ -397,7 +423,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,
inputs: props.inputs, ...(props.answer ? { answer: props.answer } : {}),
}) })
.then((result) => { .then((result) => {
if (result.data.mode === "code") { if (result.data.mode === "code") {
@@ -621,49 +647,234 @@ function OAuthView(props: {
) )
} }
async function promptInputs( async function formAnswer(dialog: ReturnType<typeof useDialog>, title: string, fields: FormFields) {
const answer: FormAnswer = {}
for (const field of fields) {
if (!active(field, answer)) continue
const value = await fieldAnswer(dialog, title, field)
if (value === CANCELLED) return null
if (value !== undefined) answer[field.key] = value
}
return answer
}
function active(field: FormField, answer: FormAnswer) {
if (field.type === "external" || !field.when) return true
return field.when.every((when) => {
const value = answer[when.key]
if (value === undefined) return false
const hit = Array.isArray(value) ? value.includes(String(when.value)) : value === when.value
return when.op === "eq" ? hit : !hit
})
}
function fieldAnswer(
dialog: ReturnType<typeof useDialog>, dialog: ReturnType<typeof useDialog>,
prompts: NonNullable<IntegrationOAuthMethod["prompts"]>, title: string,
) { field: FormField,
const inputs: Record<string, string> = {} ): Promise<FormValue | undefined | typeof CANCELLED> {
for (const prompt of prompts) { if (field.type === "external") return externalAnswer(dialog, title, field)
if (prompt.when) { if (field.type === "multiselect") return multiselectAnswer(dialog, title, field)
const value = inputs[prompt.when.key] if (field.type === "boolean" || (field.type === "string" && field.options)) {
if (value === undefined) continue return selectAnswer(dialog, title, field)
const matches = prompt.when.op === "eq" ? value === prompt.when.value : value !== prompt.when.value }
if (!matches) continue return textAnswer(dialog, title, field)
} }
if (prompt.type === "select") {
const value = await new Promise<string | null>((resolve) => { async function selectAnswer(
dialog.replace( dialog: ReturnType<typeof useDialog>,
() => ( title: string,
<DialogSelect field: Extract<FormAnswerField, { type: "boolean" | "string" }>,
title={prompt.message} ): Promise<FormValue | undefined | typeof CANCELLED> {
options={prompt.options.map((option) => ({ const options =
title: option.label, field.type === "boolean"
value: option.value, ? field.default === false
description: option.hint, ? [
}))} { title: "No", value: false as FormValue },
onSelect={(option) => resolve(option.value)} { title: "Yes", value: true as FormValue },
/> ]
), : [
() => resolve(null), { title: "Yes", value: true as FormValue },
{ title: "No", value: false as FormValue },
]
: (field.options ?? []).map((option) => ({
title: option.label,
value: option.value as FormValue,
description: option.description,
}))
const choice = await new Promise<FormValue | typeof CUSTOM | undefined | typeof CANCELLED>((resolve) => {
dialog.replace(
() => (
<DialogSelect<FormValue | typeof CUSTOM | undefined>
title={formLabel(field) || title}
options={[
...options,
...(field.type === "string" && field.custom
? [{ title: "Type your own answer", value: CUSTOM as typeof CUSTOM }]
: []),
...(!field.required ? [{ title: "Skip", value: undefined }] : []),
]}
current={field.type === "string" ? field.default : undefined}
onSelect={(option) => resolve(option.value)}
/>
),
() => resolve(CANCELLED),
)
})
if (choice === CUSTOM) {
if (field.type !== "string") return CANCELLED
return textAnswer(dialog, title, field, "")
}
return choice
}
function textAnswer(
dialog: ReturnType<typeof useDialog>,
title: string,
field: Extract<FormAnswerField, { type: "string" | "number" | "integer" }>,
initial = field.default === undefined ? undefined : String(field.default),
): Promise<FormValue | undefined | typeof CANCELLED> {
return new Promise<FormValue | undefined | typeof CANCELLED>((resolve) => {
dialog.replace(
() => {
const theme = useTheme("elevated")
const [error, setError] = createSignal<string>()
return (
<DialogPrompt
title={formLabel(field) || title}
placeholder={field.type === "string" ? field.placeholder : undefined}
value={initial}
onConfirm={(input) => {
const text = input.trim()
const value = text === "" && !field.required ? undefined : field.type === "string" ? text : Number(text)
const invalid = formValidateValue(field, value)
if (invalid) {
setError(invalid)
return
}
resolve(value)
}}
description={() => (
<box gap={1}>
<Show when={field.description}>
{(description) => <text fg={theme.text.subdued}>{description()}</text>}
</Show>
<Show when={error()}>{(value) => <text fg={theme.text.feedback.error.default}>{value()}</text>}</Show>
</box>
)}
/>
) )
}) },
if (value === null) return null () => resolve(CANCELLED),
inputs[prompt.key] = value )
continue })
} }
const value = await new Promise<string | null>((resolve) => {
async function multiselectAnswer(
dialog: ReturnType<typeof useDialog>,
title: string,
field: Extract<FormAnswerField, { type: "multiselect" }>,
): Promise<FormValue | typeof CANCELLED> {
const selected = field.default ? [...field.default] : []
while (true) {
const invalid = formValidateValue(field, selected)
const choice = await new Promise<string | typeof CUSTOM | typeof SUBMIT | typeof CANCELLED>((resolve) => {
dialog.replace( dialog.replace(
() => <DialogPrompt title={prompt.message} placeholder={prompt.placeholder} onConfirm={resolve} />, () => (
() => resolve(null), <DialogSelect<string | typeof CUSTOM | typeof SUBMIT>
title={formLabel(field) || title}
options={[
...field.options.map((option) => ({
title: `[${selected.includes(option.value) ? "x" : " "}] ${option.label}`,
value: option.value,
description: option.description,
disabled:
!selected.includes(option.value) && field.maxItems !== undefined && selected.length >= field.maxItems,
})),
...(field.custom ? [{ title: "Type your own answer", value: CUSTOM as typeof CUSTOM }] : []),
{
title: "Continue",
value: SUBMIT as typeof SUBMIT,
description: invalid,
disabled: invalid !== undefined,
},
]}
onSelect={(option) => resolve(option.value)}
/>
),
() => resolve(CANCELLED),
) )
}) })
if (value === null) return null if (choice === CANCELLED) return CANCELLED
inputs[prompt.key] = value if (choice === SUBMIT) return selected
if (choice === CUSTOM) {
const value = await customAnswer(dialog, title, field)
if (value === CANCELLED) return CANCELLED
if (value && !selected.includes(value)) selected.push(value)
continue
}
selected.splice(0, selected.length, ...formToggleMultiselect(selected, choice))
}
}
function customAnswer(
dialog: ReturnType<typeof useDialog>,
title: string,
field: Extract<FormAnswerField, { type: "multiselect" }>,
): Promise<string | typeof CANCELLED> {
return new Promise<string | typeof CANCELLED>((resolve) => {
dialog.replace(
() => (
<DialogPrompt
title={formLabel(field) || title}
placeholder="Type your own answer"
onConfirm={(value) => {
if (value) resolve(value)
}}
/>
),
() => resolve(CANCELLED),
)
})
}
async function externalAnswer(
dialog: ReturnType<typeof useDialog>,
title: string,
field: Extract<FormField, { type: "external" }>,
): Promise<true | typeof CANCELLED> {
let opened = false
while (true) {
const choice = await new Promise<true | typeof OPEN | typeof CANCELLED>((resolve) => {
dialog.replace(
() => (
<DialogSelect<true | typeof OPEN>
title={formLabel(field) || title}
options={[
{ title: opened ? "Open link again" : "Open link", value: OPEN as typeof OPEN, description: field.url },
{ title: "I finished", value: true as const, description: field.description, disabled: !opened },
]}
onSelect={(option) => resolve(option.value)}
/>
),
() => resolve(CANCELLED),
)
})
if (choice === CANCELLED) return CANCELLED
if (choice === true) return true
const result = await new Promise<boolean | typeof CANCELLED>((resolve) => {
dialog.replace(
() => <OAuthView title={formLabel(field) || title} message="Opening link..." />,
() => resolve(CANCELLED),
)
void open(field.url).then(
() => resolve(true),
() => resolve(false),
)
})
if (result === CANCELLED) return CANCELLED
opened ||= result
} }
return inputs
} }
async function connected( async function connected(
+1
View File
@@ -38,6 +38,7 @@ export function permissionPresentation(
title: `Edit ${formatPath(file)}`, title: `Edit ${formatPath(file)}`,
lines: [], lines: [],
diff, diff,
patch: diff ? undefined : text(input.patchText) || undefined,
file, file,
} }
} }
@@ -152,7 +152,7 @@ describe("run permission shared", () => {
}) })
}) })
test("uses the resource display when an edit has no generated diff", () => { test("uses source patch text when an edit has no generated diff", () => {
const patch = '*** Begin Patch\n*** Update File: src/index.ts\n@@\n-old\n+const arrow = "→"\n*** End Patch' const patch = '*** Begin Patch\n*** Update File: src/index.ts\n@@\n-old\n+const arrow = "→"\n*** End Patch'
const request = req({ const request = req({
action: "edit", action: "edit",
@@ -171,11 +171,13 @@ describe("run permission shared", () => {
expect(permissionInfo(request)).toMatchObject({ expect(permissionInfo(request)).toMatchObject({
title: "Edit src/index.ts", title: "Edit src/index.ts",
diff: undefined, diff: undefined,
patch,
}) })
expect(permissionInfo(request, undefined, true)).toMatchObject({ expect(permissionInfo(request, undefined, true)).toMatchObject({
title: "Edit src/index.ts", title: "Edit src/index.ts",
lines: [], lines: [patch],
diff: undefined, diff: undefined,
patch: undefined,
}) })
}) })