Compare commits

..

2 Commits

Author SHA1 Message Date
Kit Langton 7cc63f99d8 refactor(tui): drop legacy slot names, migrate builtins to region claims 2026-08-08 20:22:05 -04:00
Kit Langton 8239ae886f feat(tui): region structure for plugin slot placement 2026-08-08 20:21:41 -04:00
81 changed files with 3010 additions and 3083 deletions
@@ -422,12 +422,14 @@ const lowerMedia = Effect.fn("AnthropicMessages.lowerMedia")(function* (part: Me
// Tool results may carry structured text, images, and documents. Keep media as provider-native
// content instead of JSON-stringifying base64 into a prompt string.
const lowerToolResultContentItem = Effect.fnUntraced(function* (item: Tool.Content) {
const lowerToolResultContentItem = Effect.fn("AnthropicMessages.lowerToolResultContentItem")(function* (
item: Tool.Content,
) {
if (item.type === "text") return { type: "text" as const, text: item.text } satisfies AnthropicTextBlock
return yield* lowerMedia({ type: "media", mediaType: item.mime, data: item.uri, filename: item.name })
})
const lowerToolResultContent = Effect.fnUntraced(function* (part: ToolResultPart) {
const lowerToolResultContent = Effect.fn("AnthropicMessages.lowerToolResultContent")(function* (part: ToolResultPart) {
// Text / json / error results stay as a string for backward compatibility
// with existing cassettes and provider expectations.
if (part.result.type !== "content") return ProviderShared.toolResultText(part)
+3 -3
View File
@@ -358,7 +358,7 @@ const lowerMedia = Effect.fn("OpenResponses.lowerMedia")(function* (
return { type: "input_image" as const, image_url: media.dataUrl }
})
const lowerUserContent = Effect.fnUntraced(function* (
const lowerUserContent = Effect.fn("OpenResponses.lowerUserContent")(function* (
part: LLMRequest["messages"][number]["content"][number],
request: LLMRequest,
extension: Extension,
@@ -370,7 +370,7 @@ const lowerUserContent = Effect.fnUntraced(function* (
// Tool results may carry structured text, images, and files. Keep media as provider-native
// content instead of JSON-stringifying base64 into a prompt string.
const lowerToolResultContentItem = Effect.fnUntraced(function* (
const lowerToolResultContentItem = Effect.fn("OpenResponses.lowerToolResultContentItem")(function* (
item: Content,
request: LLMRequest,
extension: Extension,
@@ -383,7 +383,7 @@ const lowerToolResultContentItem = Effect.fnUntraced(function* (
)
})
const lowerToolResultOutput = Effect.fnUntraced(function* (
const lowerToolResultOutput = Effect.fn("OpenResponses.lowerToolResultOutput")(function* (
part: ToolResultPart,
request: LLMRequest,
extension: Extension,
@@ -0,0 +1,71 @@
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options"
import type { RouteDefaultsInput } from "../route/client"
import { ProviderID, type ModelID } from "../schema"
import * as OpenAIChat from "../protocols/openai-chat"
import * as OpenAIResponses from "../protocols/openai-responses"
import { withOpenAIOptions, type OpenAIProviderOptionsInput } from "./openai-options"
export const id = ProviderID.make("github-copilot")
// GitHub Copilot has no canonical public URL — callers (opencode, etc.) must
// supply `baseURL` explicitly.
export type LanguageModelOptions = Omit<RouteDefaultsInput, "providerOptions"> &
ProviderAuthOption<"optional"> & {
readonly baseURL: string
readonly endpoint?: "chat" | "responses"
readonly providerOptions?: OpenAIProviderOptionsInput
}
export const shouldUseResponsesApi = (modelID: string | ModelID, endpoint?: LanguageModelOptions["endpoint"]) => {
if (endpoint) return endpoint === "responses"
const model = String(modelID)
const match = /^gpt-(\d+)/.exec(model)
if (!match) return false
return Number(match[1]) >= 5 && !model.startsWith("gpt-5-mini")
}
export const routes = [OpenAIResponses.route, OpenAIChat.route]
const chatRoute = OpenAIChat.route.with({ provider: id })
const responsesRoute = OpenAIResponses.route.with({ provider: id })
const defaults = (options: LanguageModelOptions) => {
const { apiKey: _, auth: _auth, baseURL: _baseURL, endpoint: _endpoint, ...rest } = options
return rest
}
const configuredResponsesRoute = (options: LanguageModelOptions) =>
responsesRoute.with({
endpoint: { baseURL: options.baseURL },
auth: AuthOptions.bearer(options, []),
})
const configuredChatRoute = (options: LanguageModelOptions) =>
chatRoute.with({
endpoint: { baseURL: options.baseURL },
auth: AuthOptions.bearer(options, []),
})
export const configure = (options: LanguageModelOptions) => {
const responsesRoute = configuredResponsesRoute(options)
const chatRoute = configuredChatRoute(options)
const responses = (modelID: string | ModelID) =>
responsesRoute
.with(withOpenAIOptions(modelID, defaults(options)))
.model<OpenAIProviderOptionsInput>({ id: modelID })
const chat = (modelID: string | ModelID) =>
chatRoute.with(withOpenAIOptions(modelID, defaults(options))).model<OpenAIProviderOptionsInput>({ id: modelID })
return {
id,
model: (modelID: string | ModelID) =>
shouldUseResponsesApi(modelID, options.endpoint) ? responses(modelID) : chat(modelID),
responses,
chat,
configure,
}
}
export const provider = {
id,
configure,
}
+1
View File
@@ -5,6 +5,7 @@ export * as AmazonBedrockMantle from "./amazon-bedrock-mantle"
export * as Azure from "./azure"
export * as Cloudflare from "./cloudflare"
export { CloudflareAIGateway, CloudflareWorkersAI } from "./cloudflare"
export * as GitHubCopilot from "./github-copilot"
export * as Google from "./google"
export * as GoogleVertex from "./google-vertex"
export * as GoogleVertexChat from "./google-vertex-chat"
+5
View File
@@ -7,6 +7,7 @@ import * as Anthropic from "../src/providers/anthropic"
import * as AnthropicCompatible from "../src/providers/anthropic-compatible"
import * as Azure from "../src/providers/azure"
import * as Cloudflare from "../src/providers/cloudflare"
import * as GitHubCopilot from "../src/providers/github-copilot"
import * as Google from "../src/providers/google"
import * as GoogleVertex from "../src/providers/google-vertex"
import * as GoogleVertexChat from "../src/providers/google-vertex-chat"
@@ -269,3 +270,7 @@ OpenAICompatible.deepseek.configure({ apiKey: "deepseek-key" }).model("deepseek-
Cloudflare.CloudflareWorkersAI.configure({ accountId: "account", apiKey: "cf-key" }).model("@cf/meta/llama")
// @ts-expect-error Cloudflare Workers AI model selectors only accept model ids.
Cloudflare.CloudflareWorkersAI.configure({ accountId: "account", apiKey: "cf-key" }).model("@cf/meta/llama", {})
GitHubCopilot.configure({ baseURL: "https://copilot.test", apiKey: "copilot-key" }).model("gpt-4.1")
// @ts-expect-error GitHub Copilot model selectors only accept model ids.
GitHubCopilot.configure({ baseURL: "https://copilot.test", apiKey: "copilot-key" }).model("gpt-4.1", {})
+18
View File
@@ -10,6 +10,7 @@ import {
OpenRouter,
XAI,
} from "@opencode-ai/ai/providers"
import * as GitHubCopilot from "@opencode-ai/ai/providers/github-copilot"
import {
OpenAIChat,
OpenAICompatibleChat,
@@ -59,6 +60,23 @@ describe("public exports", () => {
expect(XAI.provider.chat).toBe(XAI.chat)
expect(XAI.configure({ apiKey: "fixture" }).responses("grok-4.3").route.id).toBe("openai-responses")
expect(XAI.configure({ apiKey: "fixture" }).chat("grok-4.3").route.id).toBe("openai-compatible-chat")
expect(
GitHubCopilot.configure({ baseURL: "https://api.githubcopilot.test", apiKey: "fixture" }).model,
).toBeFunction()
expect(
GitHubCopilot.configure({
baseURL: "https://api.githubcopilot.test",
apiKey: "fixture",
endpoint: "responses",
}).model("mai-code-1-flash-picker").route.id,
).toBe("openai-responses")
expect(
GitHubCopilot.configure({
baseURL: "https://api.githubcopilot.test",
apiKey: "fixture",
endpoint: "chat",
}).model("gpt-5").route.id,
).toBe("openai-chat")
})
test("protocol barrels expose supported low-level routes", () => {
@@ -0,0 +1,13 @@
import { LLM } from "../../src"
import { GitHubCopilot } from "../../src/providers"
const model = GitHubCopilot.configure({ baseURL: "https://example.com" }).model("gpt-5")
LLM.request({ model, prompt: "Hello", providerOptions: { openai: { reasoningSummary: "auto" } } })
LLM.request({
model,
prompt: "Hello",
// @ts-expect-error Copilot reasoning summaries use the OpenAI union.
providerOptions: { openai: { reasoningSummary: "full" } },
})
@@ -1,4 +1,4 @@
import type { FormAnswer, IntegrationMethod, IntegrationOauthConnectOutput } from "@opencode-ai/client/promise"
import type { IntegrationMethod, IntegrationOauthConnectOutput } from "@opencode-ai/client/promise"
import { Button } from "@opencode-ai/ui/button"
import { useDialog } from "@opencode-ai/ui/context/dialog"
import { Dialog } from "@opencode-ai/ui/dialog"
@@ -40,8 +40,6 @@ import { decode64 } from "@/utils/base64"
const CUSTOM_ID = "_custom"
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 } = {}) {
const [store, setStore] = createStore({ selected: undefined as string | undefined })
@@ -436,16 +434,16 @@ function ProviderConnection(props: {
const [store, setStore] = createStore({
methodIndex: undefined as undefined | number,
authorization: undefined as undefined | IntegrationOauthConnectOutput["data"],
formAnswer: undefined as FormAnswer | undefined,
state: "pending" as undefined | "pending" | "complete" | "error" | "form",
promptInputs: undefined as undefined | Record<string, string>,
state: "pending" as undefined | "pending" | "complete" | "error" | "prompt",
error: undefined as string | undefined,
})
type Action =
| { type: "method.select"; index: number }
| { type: "method.reset" }
| { type: "auth.form" }
| { type: "auth.answer"; answer: FormAnswer | undefined }
| { type: "auth.prompt" }
| { type: "auth.inputs"; inputs: Record<string, string> }
| { type: "auth.pending" }
| { type: "auth.complete"; authorization: IntegrationOauthConnectOutput["data"] }
| { type: "auth.error"; error: string }
@@ -456,7 +454,7 @@ function ProviderConnection(props: {
if (action.type === "method.select") {
draft.methodIndex = action.index
draft.authorization = undefined
draft.formAnswer = undefined
draft.promptInputs = undefined
draft.state = undefined
draft.error = undefined
return
@@ -464,18 +462,18 @@ function ProviderConnection(props: {
if (action.type === "method.reset") {
draft.methodIndex = undefined
draft.authorization = undefined
draft.formAnswer = undefined
draft.promptInputs = undefined
draft.state = undefined
draft.error = undefined
return
}
if (action.type === "auth.form") {
draft.state = "form"
if (action.type === "auth.prompt") {
draft.state = "prompt"
draft.error = undefined
return
}
if (action.type === "auth.answer") {
draft.formAnswer = action.answer
if (action.type === "auth.inputs") {
draft.promptInputs = action.inputs
draft.state = undefined
draft.error = undefined
return
@@ -533,7 +531,7 @@ function ProviderConnection(props: {
return fallback
}
async function selectMethod(index: number, answer?: FormAnswer) {
async function selectMethod(index: number, inputs?: Record<string, string>) {
if (timer.current !== undefined) {
clearTimeout(timer.current)
timer.current = undefined
@@ -542,17 +540,9 @@ function ProviderConnection(props: {
const method = methods()[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.form?.some((field) => field.type !== "string")) {
dispatch({ type: "auth.error", error: "This authentication form contains unsupported fields" })
if (method.prompts?.length && !inputs) {
dispatch({ type: "auth.prompt" })
return
}
dispatch({ type: "auth.pending" })
@@ -560,7 +550,7 @@ function ProviderConnection(props: {
.api.integration.oauth.connect({
integrationID: props.provider,
methodID: method.id,
...(answer ? { answer } : {}),
inputs: inputs ?? {},
location: location(),
})
.then((x) => {
@@ -574,42 +564,41 @@ function ProviderConnection(props: {
}
}
function AuthFormView() {
function AuthPromptsView() {
const [formStore, setFormStore] = createStore({
value: {} as Record<string, string>,
index: 0,
})
const fields = createMemo<StringForm[]>(() => {
const prompts = createMemo(() => {
const value = method()
return (value?.form ?? []).flatMap((field) => (field.type === "string" ? [field] : []))
return value?.type === "oauth" ? (value.prompts ?? []) : []
})
const matches = (field: StringForm, value: Record<string, string>) => {
return (field.when ?? []).every((condition) => {
const actual = value[condition.key]
if (actual === undefined) return false
return condition.op === "eq" ? actual === condition.value : actual !== condition.value
})
const matches = (prompt: NonNullable<ReturnType<typeof prompts>[number]>, value: Record<string, string>) => {
if (!prompt.when) return true
const actual = value[prompt.when.key]
if (actual === undefined) return false
return prompt.when.op === "eq" ? actual === prompt.when.value : actual !== prompt.when.value
}
const current = createMemo(() => {
const all = fields()
const index = all.findIndex((field, index) => index >= formStore.index && matches(field, formStore.value))
const all = prompts()
const index = all.findIndex((prompt, index) => index >= formStore.index && matches(prompt, formStore.value))
if (index === -1) return
return {
index,
field: all[index],
prompt: all[index],
}
})
const valid = createMemo(() => {
const item = current()
if (!item || item.field.options) return false
if (!item.field.required) return true
return (formStore.value[item.field.key] ?? "").trim().length > 0
if (!item || item.prompt.type !== "text") return false
const value = formStore.value[item.prompt.key] ?? ""
return value.trim().length > 0
})
async function next(index: number, value: Record<string, string>) {
if (store.methodIndex === undefined) return
const next = fields().findIndex((field, i) => i > index && matches(field, value))
const next = prompts().findIndex((prompt, i) => i > index && matches(prompt, value))
if (next !== -1) {
setFormStore("index", next)
return
@@ -620,60 +609,60 @@ function ProviderConnection(props: {
async function handleSubmit(e: SubmitEvent) {
e.preventDefault()
const item = current()
if (!item || item.field.options) return
if (!item || item.prompt.type !== "text") return
if (!valid()) return
await next(item.index, formStore.value)
}
const item = () => current()
const text = createMemo(() => {
const field = item()?.field
if (!field || field.options) return
return field
const prompt = item()?.prompt
if (!prompt || prompt.type !== "text") return
return prompt
})
const select = createMemo(() => {
const field = item()?.field
if (!field?.options) return
return field
const prompt = item()?.prompt
if (!prompt || prompt.type !== "select") return
return prompt
})
return (
<form onSubmit={handleSubmit} class="flex flex-col items-start gap-4">
<Switch>
<Match when={item()?.field.options === undefined}>
<Match when={item()?.prompt.type === "text"}>
<TextField
type="text"
label={text()?.title ?? ""}
label={text()?.message ?? ""}
placeholder={text()?.placeholder}
value={text() ? (formStore.value[text()!.key] ?? "") : ""}
onChange={(value) => {
const field = text()
if (!field) return
setFormStore("value", field.key, value)
const prompt = text()
if (!prompt) return
setFormStore("value", prompt.key, value)
}}
/>
<Button class="w-auto" type="submit" size="large" variant="primary" disabled={!valid()}>
{language.t("common.continue")}
</Button>
</Match>
<Match when={item()?.field.options !== undefined}>
<Match when={item()?.prompt.type === "select"}>
<div class="w-full flex flex-col gap-1.5">
<div class="text-14-regular text-text-base">{select()?.title}</div>
<div class="text-14-regular text-text-base">{select()?.message}</div>
<div>
<List
class="px-3"
items={select()?.options ?? []}
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) => {
if (!value) return
const field = select()
if (!field) return
const prompt = select()
if (!prompt) return
const nextValue = {
...formStore.value,
[field.key]: value.value,
[prompt.key]: value.value,
}
setFormStore("value", field.key, value.value)
setFormStore("value", prompt.key, value.value)
void next(item()!.index, nextValue)
}}
>
@@ -683,7 +672,7 @@ function ProviderConnection(props: {
<div class="w-2.5 h-0.5 ml-0 bg-icon-strong-base hidden" data-slot="list-item-extra-icon" />
</div>
<span>{option.label}</span>
<span class="text-14-regular text-text-weak">{option.description}</span>
<span class="text-14-regular text-text-weak">{option.hint}</span>
</div>
)}
</List>
@@ -831,7 +820,6 @@ function ProviderConnection(props: {
integrationID: props.provider,
location: location(),
key: apiKey,
...(store.formAnswer ? { answer: store.formAnswer } : {}),
})
await complete()
}
@@ -1155,8 +1143,8 @@ function ProviderConnection(props: {
</div>
</div>
</Match>
<Match when={store.state === "form"}>
<AuthFormView />
<Match when={store.state === "prompt"}>
<AuthPromptsView />
</Match>
<Match when={store.state === "error"}>
<div class="text-14-regular text-text-base">
+2 -1
View File
@@ -662,12 +662,13 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
integrationID: server.integrationID,
location: { directory: key },
})
const method = integration.data?.methods.find((item) => item.type === "oauth" && !item.form?.length)
const method = integration.data?.methods.find((item) => item.type === "oauth" && !item.prompts?.length)
if (!method || method.type !== "oauth")
throw new Error(`MCP server ${name} requires an interactive authentication form`)
const attempt = await serverSDK.api.integration.oauth.connect({
integrationID: server.integrationID,
methodID: method.id,
inputs: {},
location: { directory: key },
})
platform.openLink(attempt.data.url)
@@ -50,7 +50,7 @@ const login = Effect.fn("cli.console.login.run")(function* (timeline: TimelineHo
{
integrationID,
methodID: method.id,
...(server ? { answer: { server } } : {}),
inputs: server ? { server } : {},
location,
},
{ 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`))
const started = yield* Effect.promise(() =>
client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, location }),
client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, inputs: {}, location }),
)
const attempt = started.data
if (attempt.mode === "code")
+4
View File
@@ -92,6 +92,10 @@ const processEffect = Effect.fnUntraced(function* (options: Options) {
file: process.env.OPENCODE_MODELS_PATH,
fetch: !truthy(process.env.OPENCODE_DISABLE_MODELS_FETCH),
},
observability: {
endpoint: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,
headers: process.env.OTEL_EXPORTER_OTLP_HEADERS,
},
config: {
directory: process.env.OPENCODE_CONFIG_DIR,
project: !truthy(
+2 -3
View File
@@ -23,9 +23,9 @@ import type { Shell } from "@opencode-ai/schema/shell"
import type { DateTime } from "effect"
import type { Provider } from "@opencode-ai/schema/provider"
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 { Credential } from "@opencode-ai/schema/credential"
import type { Form } from "@opencode-ai/schema/form"
import type { Permission } from "@opencode-ai/schema/permission"
import type { PermissionSaved } from "@opencode-ai/schema/permission-saved"
import type { FileSystem } from "@opencode-ai/schema/filesystem"
@@ -1054,7 +1054,6 @@ export type Endpoint10_3Input = {
readonly integrationID: Integration.ID
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
readonly key: string
readonly answer?: Form.Answer | undefined
readonly label?: string | undefined
}
export type Endpoint10_3Output = void
@@ -1066,7 +1065,7 @@ export type Endpoint10_4Input = {
readonly integrationID: Integration.ID
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
readonly methodID: Integration.MethodID
readonly answer?: Form.Answer | undefined
readonly inputs: { readonly [x: string]: string }
readonly label?: string | undefined
}
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"]({
params: { integrationID: input["integrationID"] },
query: { location: input["location"] },
payload: { key: input["key"], answer: input["answer"], label: input["label"] },
payload: { key: input["key"], label: input["label"] },
}).pipe(Effect.mapError(mapClientError)),
)
@@ -726,7 +726,7 @@ const Endpoint10_4 = (raw: RawClient["server.integration"]) => (input: Endpoint1
raw["integration.oauth.connect"]({
params: { integrationID: input["integrationID"] },
query: { location: input["location"] },
payload: { methodID: input["methodID"], answer: input["answer"], label: input["label"] },
payload: { methodID: input["methodID"], inputs: input["inputs"], label: input["label"] },
}).pipe(Effect.mapError(mapClientError)),
)
@@ -1032,7 +1032,7 @@ export function make(options: ClientOptions) {
method: "POST",
path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/key`,
query: { location: input["location"] },
body: { key: input["key"], answer: input["answer"], label: input["label"] },
body: { key: input["key"], label: input["label"] },
successStatus: 204,
declaredStatuses: [400, 401],
empty: true,
@@ -1047,7 +1047,7 @@ export function make(options: ClientOptions) {
method: "POST",
path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/oauth`,
query: { location: input["location"] },
body: { methodID: input["methodID"], answer: input["answer"], label: input["label"] },
body: { methodID: input["methodID"], inputs: input["inputs"], label: input["label"] },
successStatus: 200,
declaredStatuses: [400, 401],
empty: false,
+80 -74
View File
@@ -41,7 +41,6 @@ export type SessionMessageAgentSelected = {
time: { created: number }
type: "agent-switched"
agent: string
previous?: string
}
export type PromptBase64 = string
@@ -196,18 +195,12 @@ export type ProviderInfo = {
body?: { [x: string]: any }
}
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 IntegrationWhen = { key: string; op: "eq" | "neq"; value: 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 ConnectionCredentialInfo = { type: "credential"; id: string; label: string }
@@ -292,6 +285,16 @@ export type ProjectDirectory = { directory: string; strategy?: string }
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 PermissionSource = { type: "tool"; messageID: string; id: string }
@@ -1274,6 +1277,45 @@ export type ModelCost = {
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 = {
key: string
title?: string
@@ -1339,29 +1381,6 @@ export type FormMultiselectField = {
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 PermissionRequest = {
@@ -1645,6 +1664,13 @@ export type ModelInfo = {
limit: { context: number; input?: number; output: number }
}
export type IntegrationOAuthMethod = {
id: string
type: "oauth"
label: string
prompts?: Array<IntegrationTextPrompt | IntegrationSelectPrompt>
}
export type FormField =
| FormStringField
| FormNumberField
@@ -1898,9 +1924,15 @@ export type SessionMessageAssistantTool = {
time: { created: number; ran?: number; completed?: number }
}
export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationEnvMethod
export type FormFields = [FormField, ...Array<FormField>]
export type FormFields3 = [FormField1, ...Array<FormField1>]
export type FormFields1 = [FormField1, ...Array<FormField1>]
export type SessionPendingInfo = SessionPendingUser | SessionPendingSynthetic | SessionPendingCompaction
@@ -1922,13 +1954,16 @@ export type SessionMessageAssistant = {
retry?: SessionMessageAssistantRetry
}
export type IntegrationOAuthMethod = { id: string; type: "oauth"; label: string; form?: FormFields }
export type IntegrationKeyMethod = { type: "key"; label?: string; form?: FormFields }
export type IntegrationInfo = {
id: string
name: string
methods: Array<IntegrationMethod>
connections: Array<ConnectionInfo>
}
export type FormInfo = { id: string; sessionID: string; title: string; metadata?: FormMetadata; fields: FormFields }
export type FormInfo1 = { id: string; sessionID: string; title: string; metadata?: FormMetadata1; fields: FormFields3 }
export type FormInfo1 = { id: string; sessionID: string; title: string; metadata?: FormMetadata1; fields: FormFields1 }
export type SessionInputAdmitted = {
id: string
@@ -1951,12 +1986,6 @@ export type SessionMessageInfo =
| SessionMessageAssistant
| SessionMessageCompaction
export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationEnvMethod
export type FormCreated = {
id: string
created: number
@@ -2017,13 +2046,6 @@ export type SessionMessagesResponse = {
cursor: { previous?: string | null; next?: string | null }
}
export type IntegrationInfo = {
id: string
name: string
methods: Array<IntegrationMethod>
connections: Array<ConnectionInfo>
}
export type V2Event =
| ModelsDevRefreshed
| IntegrationUpdated
@@ -2536,7 +2558,6 @@ export type SessionImportInput = {
readonly time: { readonly created: number }
readonly type: "agent-switched"
readonly agent: string
readonly previous?: string
}
| {
readonly id: string
@@ -2788,7 +2809,6 @@ export type SessionImportInput = {
readonly time: { readonly created: number }
readonly type: "agent-switched"
readonly agent: string
readonly previous?: string
}
| {
readonly id: string
@@ -3040,7 +3060,6 @@ export type SessionImportInput = {
readonly time: { readonly created: number }
readonly type: "agent-switched"
readonly agent: string
readonly previous?: string
}
| {
readonly id: string
@@ -4026,21 +4045,8 @@ export type IntegrationConnectKeyInput = {
readonly location?: {
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
}["location"]
readonly key: {
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"]
readonly key: { readonly key: string; readonly label?: string | undefined }["key"]
readonly label?: { readonly key: string; readonly label?: string | undefined }["label"]
}
export type IntegrationConnectKeyOutput = void
@@ -4052,17 +4058,17 @@ export type IntegrationOauthConnectInput = {
}["location"]
readonly methodID: {
readonly methodID: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly inputs: { readonly [x: string]: string }
readonly label?: string | undefined
}["methodID"]
readonly answer?: {
readonly inputs: {
readonly methodID: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly inputs: { readonly [x: string]: string }
readonly label?: string | undefined
}["answer"]
}["inputs"]
readonly label?: {
readonly methodID: string
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
readonly inputs: { readonly [x: string]: string }
readonly label?: string | undefined
}["label"]
}
-43
View File
@@ -148,49 +148,6 @@ test("experimental wellknown integration add uses the public HTTP contract", asy
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 () => {
let request: Request | undefined
const client = OpenCode.make({
+5 -5
View File
@@ -180,7 +180,7 @@ export const layer = Layer.effect(
Effect.gen(function* () {
const entry = yield* find(input.id)
if (entry.state.status !== "pending") return yield* new AlreadySettledError({ id: input.id })
const invalid = validateAnswer(entry.form.fields, input.answer)
const invalid = validateAnswer(entry.form, input.answer)
if (invalid) return yield* new InvalidAnswerError({ id: input.id, message: invalid })
const next: TerminalState = { status: "answered", answer: input.answer }
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 function validateAnswer(form: ReadonlyArray<Form.Field>, answer: Answer) {
const fields = new Map(form.map((field) => [field.key, field] as const))
function validateAnswer(form: Info, answer: Answer) {
const fields = new Map(form.fields.map((field) => [field.key, field] as const))
for (const key of Object.keys(answer)) {
if (!fields.has(key)) return `Unknown form field: ${key}`
}
for (const field of form) {
for (const field of form.fields) {
const value = answer[field.key]
if (field.type === "external") {
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
// are closed. Rejecting these at creation surfaces authoring mistakes to the caller instead of
// silently never matching.
export function validateFields(fields: ReadonlyArray<Form.Field>) {
function validateFields(fields: ReadonlyArray<Form.Field>) {
if (fields.length === 0) return "Form must have at least one field"
const earlier = new Map<string, InputField>()
const keys = new Set<string>()
@@ -127,7 +127,7 @@ export async function convertToOpenAIResponsesInput({
input.push({
role: "assistant",
content: [{ type: "output_text", text: part.text }],
id: store ? ((part.providerOptions?.copilot?.itemId as string) ?? undefined) : undefined,
id: (part.providerOptions?.copilot?.itemId as string) ?? undefined,
})
break
}
@@ -143,7 +143,7 @@ export async function convertToOpenAIResponsesInput({
input.push({
type: "local_shell_call",
call_id: part.toolCallId,
id: store ? ((part.providerOptions?.copilot?.itemId as string) ?? undefined) : undefined,
id: (part.providerOptions?.copilot?.itemId as string) ?? undefined,
action: {
type: "exec",
command: parsedInput.action.command,
@@ -162,7 +162,7 @@ export async function convertToOpenAIResponsesInput({
call_id: part.toolCallId,
name: part.toolName,
arguments: JSON.stringify(part.input),
id: store ? ((part.providerOptions?.copilot?.itemId as string) ?? undefined) : undefined,
id: (part.providerOptions?.copilot?.itemId as string) ?? undefined,
})
break
}
@@ -206,14 +206,35 @@ export async function convertToOpenAIResponsesInput({
summary: [],
}
}
} else if (providerOptions?.reasoningEncryptedContent != null && reasoningMessage === undefined) {
reasoningMessages[reasoningId] = {
type: "reasoning",
id: reasoningId,
encrypted_content: providerOptions.reasoningEncryptedContent,
summary: [],
} else {
const summaryParts: Array<{
type: "summary_text"
text: string
}> = []
if (part.text.length > 0) {
summaryParts.push({
type: "summary_text",
text: part.text,
})
} else if (reasoningMessage !== undefined) {
warnings.push({
type: "other",
message: `Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(part)}.`,
})
}
if (reasoningMessage === undefined) {
reasoningMessages[reasoningId] = {
type: "reasoning",
id: reasoningId,
encrypted_content: providerOptions?.reasoningEncryptedContent,
summary: summaryParts,
}
input.push(reasoningMessages[reasoningId])
} else {
reasoningMessage.summary.push(...summaryParts)
}
input.push(reasoningMessages[reasoningId])
}
} else {
warnings.push({
@@ -71,7 +71,7 @@ export type OpenAIResponsesComputerCall = {
export type OpenAIResponsesLocalShellCall = {
type: "local_shell_call"
id?: string
id: string
call_id: string
action: {
type: "exec"
@@ -198,13 +198,12 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV3 {
providerOptions,
schema: openaiResponsesProviderOptionsSchema,
})
const store = openaiOptions?.store ?? false
const { input, warnings: inputWarnings } = await convertToOpenAIResponsesInput({
prompt,
systemMessageMode: modelConfig.systemMessageMode,
fileIdPrefixes: this.config.fileIdPrefixes,
store,
store: openaiOptions?.store ?? true,
hasLocalShellTool: hasOpenAITool("openai.local_shell"),
})
@@ -215,12 +214,9 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV3 {
let include: OpenAIResponsesIncludeOptions = openaiOptions?.include
function addInclude(key: OpenAIResponsesIncludeValue) {
if (include?.includes(key)) return
include = include != null ? [...include, key] : [key]
}
addInclude("reasoning.encrypted_content")
function hasOpenAITool(id: string) {
return tools?.find((tool) => tool.type === "provider" && tool.id === id) != null
}
@@ -286,7 +282,7 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV3 {
metadata: openaiOptions?.metadata,
parallel_tool_calls: openaiOptions?.parallelToolCalls,
previous_response_id: openaiOptions?.previousResponseId,
store,
store: openaiOptions?.store,
user: openaiOptions?.user,
instructions: openaiOptions?.instructions,
service_tier: openaiOptions?.serviceTier,
@@ -844,7 +840,7 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV3 {
{
canonicalId: string // the item.id from output_item.added
encryptedContent?: string | null
summaryParts: Record<number, "active" | "can-conclude" | "concluded">
summaryParts: number[]
}
> = {}
@@ -964,14 +960,10 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV3 {
},
})
} else if (isResponseOutputItemAddedReasoningChunk(value)) {
if (activeReasoning[value.output_index]) {
currentReasoningOutputIndex = value.output_index
return
}
activeReasoning[value.output_index] = {
canonicalId: value.item.id,
encryptedContent: value.item.encrypted_content,
summaryParts: { 0: "active" },
summaryParts: [0],
}
currentReasoningOutputIndex = value.output_index
@@ -1125,14 +1117,13 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV3 {
} else if (isResponseOutputItemDoneReasoningChunk(value)) {
const activeReasoningPart = activeReasoning[value.output_index]
if (activeReasoningPart) {
for (const [summaryIndex, status] of Object.entries(activeReasoningPart.summaryParts)) {
if (status === "concluded") continue
for (const summaryIndex of activeReasoningPart.summaryParts) {
controller.enqueue({
type: "reasoning-end",
id: `${activeReasoningPart.canonicalId}:${summaryIndex}`,
providerMetadata: {
copilot: {
itemId: value.item.id,
itemId: activeReasoningPart.canonicalId,
reasoningEncryptedContent: value.item.encrypted_content ?? null,
},
},
@@ -1237,19 +1228,8 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV3 {
currentReasoningOutputIndex !== null ? activeReasoning[currentReasoningOutputIndex] : null
// the first reasoning start is pushed in isResponseOutputItemAddedReasoningChunk.
if (activeItem && value.summary_index > 0 && activeItem.summaryParts[value.summary_index] === undefined) {
for (const [summaryIndex, status] of Object.entries(activeItem.summaryParts)) {
if (status !== "can-conclude") continue
controller.enqueue({
type: "reasoning-end",
id: `${activeItem.canonicalId}:${summaryIndex}`,
providerMetadata: {
copilot: { itemId: activeItem.canonicalId },
},
})
activeItem.summaryParts[Number(summaryIndex)] = "concluded"
}
activeItem.summaryParts[value.summary_index] = "active"
if (activeItem && value.summary_index > 0) {
activeItem.summaryParts.push(value.summary_index)
controller.enqueue({
type: "reasoning-start",
@@ -1262,22 +1242,6 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV3 {
},
})
}
} else if (isResponseReasoningSummaryPartDoneChunk(value)) {
const activeItem =
currentReasoningOutputIndex !== null ? activeReasoning[currentReasoningOutputIndex] : null
if (!activeItem || activeItem.summaryParts[value.summary_index] !== "active") return
if (body.store === false) {
activeItem.summaryParts[value.summary_index] = "can-conclude"
return
}
controller.enqueue({
type: "reasoning-end",
id: `${activeItem.canonicalId}:${value.summary_index}`,
providerMetadata: {
copilot: { itemId: activeItem.canonicalId },
},
})
activeItem.summaryParts[value.summary_index] = "concluded"
} else if (isResponseReasoningSummaryTextDeltaChunk(value)) {
const activeItem =
currentReasoningOutputIndex !== null ? activeReasoning[currentReasoningOutputIndex] : null
@@ -1340,16 +1304,6 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV3 {
controller.enqueue({ type: "text-end", id: currentTextId })
currentTextId = null
}
for (const activeItem of Object.values(activeReasoning)) {
for (const [summaryIndex, status] of Object.entries(activeItem.summaryParts)) {
if (status === "concluded") continue
controller.enqueue({
type: "reasoning-end",
id: `${activeItem.canonicalId}:${summaryIndex}`,
providerMetadata: { copilot: { itemId: activeItem.canonicalId } },
})
}
}
const providerMetadata: SharedV3ProviderMetadata = {
copilot: {
@@ -1598,12 +1552,6 @@ const responseReasoningSummaryTextDeltaSchema = z.object({
delta: z.string(),
})
const responseReasoningSummaryPartDoneSchema = z.object({
type: z.literal("response.reasoning_summary_part.done"),
item_id: z.string(),
summary_index: z.number(),
})
const openaiResponsesChunkSchema = z.union([
textDeltaChunkSchema,
responseFinishedChunkSchema,
@@ -1616,7 +1564,6 @@ const openaiResponsesChunkSchema = z.union([
responseCodeInterpreterCallCodeDoneSchema,
responseAnnotationAddedSchema,
responseReasoningSummaryPartAddedSchema,
responseReasoningSummaryPartDoneSchema,
responseReasoningSummaryTextDeltaSchema,
errorChunkSchema,
z.object({ type: z.string() }).loose(), // fallback for unknown chunks
@@ -1705,12 +1652,6 @@ function isResponseReasoningSummaryPartAddedChunk(
return chunk.type === "response.reasoning_summary_part.added"
}
function isResponseReasoningSummaryPartDoneChunk(
chunk: z.infer<typeof openaiResponsesChunkSchema>,
): chunk is z.infer<typeof responseReasoningSummaryPartDoneSchema> {
return chunk.type === "response.reasoning_summary_part.done"
}
function isResponseReasoningSummaryTextDeltaChunk(
chunk: z.infer<typeof openaiResponsesChunkSchema>,
): chunk is z.infer<typeof responseReasoningSummaryTextDeltaSchema> {
+22 -27
View File
@@ -24,7 +24,6 @@ import { Bus } from "./bus"
import { IntegrationConnection } from "./integration/connection"
import { AppProcess } from "@opencode-ai/util/process"
import { ChildProcess } from "effect/unstable/process"
import { Form } from "./form"
export const ID = Integration.ID
export type ID = Integration.ID
@@ -35,6 +34,18 @@ export type MethodID = Integration.MethodID
export const AttemptID = Integration.AttemptID
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 type OAuthMethod = Integration.OAuthMethod
@@ -53,6 +64,9 @@ export type Method = Integration.Method
export const Info = Integration.Info
export type Info = Integration.Info
export const Inputs = Integration.Inputs
export type Inputs = Integration.Inputs
export type OAuthAuthorization = {
readonly url: string
readonly instructions: string
@@ -71,7 +85,7 @@ export type OAuthAuthorization = {
export interface OAuthImplementation {
readonly integrationID: ID
readonly method: OAuthMethod
readonly authorize: (answer: Form.Answer) => Effect.Effect<OAuthAuthorization, unknown, Scope.Scope>
readonly authorize: (inputs: Inputs) => Effect.Effect<OAuthAuthorization, unknown, Scope.Scope>
readonly refresh?: (credential: Credential.OAuth) => Effect.Effect<Credential.OAuth, unknown>
readonly label?: (credential: Credential.OAuth) => string | undefined
}
@@ -161,8 +175,6 @@ export interface Interface extends State.Transformable<Draft> {
readonly integrationID: ID
/** Secret entered by the user. */
readonly key: string
/** Values collected from the method's form fields. */
readonly answer?: Form.Answer
/** User-facing label for the stored credential. */
readonly label?: string
}) => Effect.Effect<void, AuthorizationError>
@@ -179,7 +191,7 @@ export interface Interface extends State.Transformable<Draft> {
readonly connect: (input: {
readonly integrationID: ID
readonly methodID: MethodID
readonly answer?: Form.Answer
readonly inputs: Inputs
readonly label?: string
}) => Effect.Effect<Attempt, AuthorizationError>
/** Returns the current state of an OAuth attempt. */
@@ -344,7 +356,7 @@ const layer = Layer.effect(
return [...credentials, ...env]
}
const project = (entry: Entry, connections: IntegrationConnection.Info[]): Info =>
const project = (entry: Entry, connections: IntegrationConnection.Info[]) =>
Info.make({
id: entry.ref.id,
name: entry.ref.name,
@@ -535,20 +547,15 @@ const layer = Layer.effect(
const connectOAuth = Effect.fn("Integration.oauth.connect")(function* (input: {
readonly integrationID: ID
readonly methodID: MethodID
readonly answer?: Form.Answer
readonly inputs: Inputs
readonly label?: string
}) {
const method = state.get().integrations.get(input.integrationID)?.implementations.get(input.methodID)
if (!method) {
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 authorization = yield* authorize(method.authorize(answer)).pipe(
const authorization = yield* authorize(method.authorize(input.inputs)).pipe(
Scope.provide(attemptScope),
Effect.onExit((exit) => (Exit.isFailure(exit) ? Scope.close(attemptScope, exit) : Effect.void)),
)
@@ -692,24 +699,12 @@ const layer = Layer.effect(
const method = state
.get()
.integrations.get(input.integrationID)
?.methods.find((method) => method.type === "key")
?.methods.some((method) => method.type === "key")
if (!method) return yield* Effect.die(new Error(`Key method not found: ${input.integrationID}`))
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({
integrationID: input.integrationID,
label: input.label,
value: Credential.Key.make({
type: "key",
key: input.key,
...(Object.keys(answer).length > 0 ? { configuration: answer } : {}),
}),
value: Credential.Key.make({ type: "key", key: input.key }),
})
yield* bus.publish(Integration.Event.ConnectionUpdated, { integrationID: input.integrationID })
yield* bus.publish(Integration.Event.Updated, {})
+1 -3
View File
@@ -149,7 +149,6 @@ export const fromCatalogModel = (
})
const packageName = Provider.packageName(resolved.package)
const key = apiKey(resolved, credential)
const configuration = credential?.type === "key" ? credential.configuration : undefined
if (Provider.isAISDK(resolved.package) && packageName === "@ai-sdk/openai") {
return Effect.succeed(
@@ -176,7 +175,7 @@ export const fromCatalogModel = (
.model({ id: resolved.modelID ?? resolved.id, compatibility: resolved.compatibility }),
)
}
const configured = { ...resolved.settings, ...credential?.metadata, ...configuration }
const configured = { ...resolved.settings, ...credential?.metadata }
const mapping = Provider.isAISDK(resolved.package)
? AISDKNative.map({
packageName,
@@ -191,7 +190,6 @@ export const fromCatalogModel = (
draft.settings = Provider.mergeOverlay(draft.settings, {
...nativeCredentialSettings(resolved.package ?? "", credential),
...credential?.metadata,
...configuration,
})
})
return dependencies.loadAISDK(runtime).pipe(Effect.mapError(() => unsupported(resolved)))
+7 -8
View File
@@ -190,7 +190,6 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
integration.connection.key({
integrationID: Integration.ID.make(input.integrationID),
key: input.key,
answer: input.answer,
label: input.label,
}),
},
@@ -200,7 +199,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
integration.oauth.connect({
integrationID: Integration.ID.make(input.integrationID),
methodID: Integration.MethodID.make(input.methodID),
answer: input.answer,
inputs: input.inputs,
label: input.label,
}),
),
@@ -261,7 +260,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
update: (id, update) => draft.update(Integration.ID.make(id), update),
remove: (id) => draft.remove(Integration.ID.make(id)),
method: {
list: (id) => draft.method.list(Integration.ID.make(id)),
list: (id) => mutable(draft.method.list(Integration.ID.make(id))),
update: (input) => draft.method.update(methodImplementation(input)),
remove: (id, method) =>
draft.method.remove(Integration.ID.make(id), Schema.decodeUnknownSync(Integration.Method)(method)),
@@ -364,8 +363,8 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
return {
integrationID: Integration.ID.make(input.integrationID),
method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
authorize: (answer) =>
input.authorize(answer).pipe(
authorize: (inputs) =>
input.authorize(inputs).pipe(
Effect.map((authorization) => {
if (authorization.mode === "auto") {
return {
@@ -386,18 +385,18 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
if (input.method.type === "env") {
return {
integrationID: Integration.ID.make(input.integrationID),
method: input.method,
method: { type: "env", names: input.method.names },
}
}
if (input.method.type === "command") {
return {
integrationID: Integration.ID.make(input.integrationID),
method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
method: Schema.decodeUnknownSync(Integration.CommandMethod)(input.method),
}
}
return {
integrationID: Integration.ID.make(input.integrationID),
method: input.method,
method: { type: "key", label: input.method.label },
}
}
+7 -13
View File
@@ -180,8 +180,8 @@ export function fromPromise(plugin: Plugin) {
const refresh = input.refresh
draft.method.update({
...input,
authorize: (answer) =>
Effect.promise(() => input.authorize(answer)).pipe(
authorize: (inputs) =>
Effect.promise(() => input.authorize(inputs)).pipe(
Effect.map((authorization) =>
authorization.mode === "auto"
? {
@@ -362,17 +362,11 @@ type Wire<Value> = unknown extends Value
? Value
: Value extends DateTime.DateTime
? number
: Value extends readonly [infer Head, ...infer Tail]
? [Wire<Head>, ...WireTuple<Tail>]
: Value extends ReadonlyArray<infer Item>
? Array<Wire<Item>>
: 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]>
}
: Value extends ReadonlyArray<infer Item>
? Array<Wire<Item>>
: Value extends object
? { -readonly [Key in keyof Value]: Wire<Value[Key]> }
: Value
function wire<Value>(value: Value): Wire<Value>
function wire(value: unknown): unknown {
@@ -1,9 +1,6 @@
import { Effect } from "effect"
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"
function selectLanguage(sdk: any, modelID: string, useChat: boolean) {
if (useChat && sdk.chat) return sdk.chat(modelID)
@@ -16,29 +13,6 @@ function selectLanguage(sdk: any, modelID: string, useChat: boolean) {
export const AzurePlugin = define({
id: "opencode.provider.azure",
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) => {
for (const item of evt.provider.list()) {
if (item.provider.id !== Provider.ID.azure && Provider.packageName(item.provider.package) !== "@ai-sdk/azure")
@@ -2,53 +2,10 @@ import os from "os"
import { App } from "../../app"
import { Effect, Option, Schema } from "effect"
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({
id: "opencode.provider.cloudflare-ai-gateway",
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(
"sdk",
Effect.fn(function* (evt) {
@@ -89,7 +46,7 @@ const decodeJson = Schema.decodeUnknownOption(Schema.UnknownFromJsonString)
function gatewayConfig(options: Record<string, unknown>): GatewayConfig | undefined {
const accountId = process.env.CLOUDFLARE_ACCOUNT_ID ?? stringOption(options, "accountId")
// Credential projection copies key metadata into options. The form stores the
// Credential projection copies key metadata into options. The prompt stores the
// gateway as gatewayId, while older config examples may use gateway.
const gatewayId =
process.env.CLOUDFLARE_GATEWAY_ID ?? stringOption(options, "gatewayId") ?? stringOption(options, "gateway")
@@ -2,39 +2,13 @@ import os from "os"
import { App } from "../../app"
import { Effect } from "effect"
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-workers-ai")
export const CloudflareWorkersAIPlugin = define({
id: "opencode.provider.cloudflare-workers-ai",
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) => {
const item = evt.provider.get(providerID)
if (!item) return
@@ -1,15 +0,0 @@
import { Effect, Option } from "effect"
import type { Document } from "@opencode-ai/schema/config"
import { Catalog } from "../../catalog"
import { Config } from "../../config"
import { Provider } from "../../provider"
export const configuredSettings = Effect.fn("ProviderPlugin.configuredSettings")(function* (id: Provider.ID) {
const catalog = yield* Catalog.Service
const current = (yield* catalog.provider.get(id))?.settings
const service = yield* Effect.serviceOption(Config.Service)
const entries = Option.isSome(service) ? yield* service.value.entries() : []
return entries
.filter((entry): entry is Document => entry.type === "document")
.reduce((settings, entry) => Provider.mergeOverlay(settings, entry.info.providers?.[id]?.settings), current)
})
@@ -1,4 +1,5 @@
import type { IntegrationOAuthMethodRegistration } from "@opencode-ai/plugin/effect/integration"
import { shouldUseResponsesApi } from "@opencode-ai/ai/providers/github-copilot"
import { Effect, Option, Schema, Semaphore, Stream } from "effect"
import { Catalog } from "../../catalog"
import { Credential } from "../../credential"
@@ -46,33 +47,30 @@ const oauth = (app: App.Info) =>
id: methodID,
type: "oauth",
label: "Login with GitHub Copilot",
form: [
prompts: [
{
type: "string",
type: "select",
key: "deploymentType",
title: "Select GitHub deployment type",
required: true,
message: "Select GitHub deployment type",
options: [
{ label: "GitHub.com", value: "github.com", description: "Public" },
{ label: "GitHub Enterprise", value: "enterprise", description: "Data residency or self-hosted" },
{ label: "GitHub.com", value: "github.com", hint: "Public" },
{ label: "GitHub Enterprise", value: "enterprise", hint: "Data residency or self-hosted" },
],
},
{
type: "string",
type: "text",
key: "enterpriseUrl",
title: "Enter your GitHub Enterprise URL or domain",
message: "Enter your GitHub Enterprise URL or domain",
placeholder: "company.ghe.com or https://company.ghe.com",
required: true,
when: [{ key: "deploymentType", op: "eq", value: "enterprise" }],
when: { key: "deploymentType", op: "eq", value: "enterprise" },
},
],
},
authorize: (answer) =>
authorize: (inputs) =>
Effect.gen(function* () {
const enterprise = answer.deploymentType === "enterprise"
const enterpriseUrl = typeof answer.enterpriseUrl === "string" ? answer.enterpriseUrl : undefined
if (enterprise && !enterpriseUrl) return yield* Effect.fail(new Error("Enterprise URL is required"))
const domain = enterprise ? normalizeDomain(enterpriseUrl ?? "") : "github.com"
const enterprise = inputs.deploymentType === "enterprise"
if (enterprise && !inputs.enterpriseUrl) return yield* Effect.fail(new Error("Enterprise URL is required"))
const domain = enterprise ? normalizeDomain(inputs.enterpriseUrl ?? "") : "github.com"
const urls = oauthURLs(domain)
const device = yield* request(urls.device, {
method: "POST",
@@ -190,7 +188,6 @@ export const GithubCopilotPlugin = define({
})
yield* ctx.integration.transform((draft) => {
draft.method.remove("github-copilot", { type: "key" })
draft.method.update(oauth(ctx.app))
})
yield* ctx.catalog.transform((evt) => {
@@ -229,26 +226,26 @@ export const GithubCopilotPlugin = define({
"sdk",
Effect.fn(function* (evt) {
if (evt.model.providerID !== Provider.ID.githubCopilot) return
if (evt.package !== "@ai-sdk/github-copilot") return
if (evt.package !== "@ai-sdk/github-copilot" && evt.package !== "@ai-sdk/anthropic") return
evt.options.fetch = copilotFetch(
typeof evt.options.apiKey === "string" ? evt.options.apiKey : undefined,
evt.options.fetch,
evt.package === "@ai-sdk/anthropic",
ctx.app,
)
if (evt.package === "@ai-sdk/anthropic") {
evt.options.headers = {
...evt.options.headers,
"anthropic-beta": "interleaved-thinking-2025-05-14",
}
const mod = yield* Effect.promise(() => import("@ai-sdk/anthropic"))
evt.sdk = mod.createAnthropic(evt.options)
return
}
const mod = yield* Effect.promise(() => import("../../github-copilot/copilot-provider"))
evt.sdk = mod.createOpenaiCompatible(evt.options)
}),
)
yield* ctx.session.hook("http.request", (evt) =>
Effect.gen(function* () {
if (evt.model.providerID !== Provider.ID.githubCopilot) return
const token = evt.request.headers.get("x-api-key")
if (!token) return
const text = yield* Effect.promise(() => evt.request.clone().text())
const body = Option.getOrUndefined(decodeBody(text))
applyHeaders(evt.request.headers, token, ctx.app, requestMetadata(evt.request.url, body), true)
}),
)
yield* ctx.aisdk.hook(
"language",
Effect.fn(function* (evt) {
@@ -266,9 +263,7 @@ export const GithubCopilotPlugin = define({
return
}
const id = evt.model.modelID ?? evt.model.id
const match = /^gpt-(\d+)/.exec(id)
evt.language =
match && Number(match[1]) >= 5 && !id.startsWith("gpt-5-mini") ? evt.sdk.responses(id) : evt.sdk.chat(id)
evt.language = shouldUseResponsesApi(id) ? evt.sdk.responses(id) : evt.sdk.chat(id)
}),
)
}),
@@ -317,39 +312,34 @@ function request(url: string, init: RequestInit) {
type Fetch = (input: Parameters<typeof fetch>[0], init?: RequestInit) => Promise<Response>
export function copilotFetch(token: string | undefined, upstream: Fetch | undefined, app: App.Info): Fetch {
export function copilotFetch(
token: string | undefined,
upstream: Fetch | undefined,
anthropic: boolean,
app: App.Info,
): Fetch {
const send = upstream ?? fetch
return async (input, init) => {
const requestHeaders = new Headers(init?.headers)
if (token) {
requestHeaders.delete("authorization")
requestHeaders.delete("x-api-key")
requestHeaders.set("Authorization", `Bearer ${token}`)
}
requestHeaders.set("User-Agent", App.useragent(app))
requestHeaders.set("Openai-Intent", "conversation-edits")
requestHeaders.set("X-GitHub-Api-Version", apiVersion)
if (anthropic) requestHeaders.set("anthropic-beta", "interleaved-thinking-2025-05-14")
const url = input instanceof URL ? input.href : typeof input === "string" ? input : input.url
const body = typeof init?.body === "string" ? Option.getOrUndefined(decodeBody(init.body)) : undefined
applyHeaders(requestHeaders, token, app, requestMetadata(url, body), false)
const metadata = requestMetadata(url, body)
requestHeaders.set("x-initiator", metadata.agent ? "agent" : "user")
if (metadata.vision) requestHeaders.set("Copilot-Vision-Request", "true")
return send(input, { ...init, headers: requestHeaders })
}
}
function applyHeaders(
headers: Headers,
token: string | undefined,
app: App.Info,
metadata: RequestMetadata,
anthropic: boolean,
) {
if (token) {
headers.delete("authorization")
headers.delete("x-api-key")
headers.set("Authorization", `Bearer ${token}`)
}
headers.set("User-Agent", App.useragent(app))
headers.set("Openai-Intent", "conversation-edits")
headers.set("X-GitHub-Api-Version", apiVersion)
headers.set("x-initiator", metadata.agent ? "agent" : "user")
if (metadata.vision) headers.set("Copilot-Vision-Request", "true")
if (anthropic) headers.set("anthropic-beta", "interleaved-thinking-2025-05-14")
}
type RequestMetadata = ReturnType<typeof requestMetadata>
function requestMetadata(url: string, body: unknown) {
if (!record(body)) return { agent: false, vision: false }
if (Array.isArray(body.input)) {
@@ -43,9 +43,9 @@ function oauth(http: HttpClient.HttpClient) {
type: "oauth",
label: "OpenCode Console account",
},
authorize: (answer) =>
authorize: (inputs) =>
Effect.gen(function* () {
const server = yield* normalizeServer(answer.server ?? defaultServer)
const server = yield* normalizeServer(inputs.server ?? defaultServer)
const device = yield* post(http, `${server}/auth/device/code`, { client_id: clientID }, Device)
const verification = URL.canParse(device.verification_uri_complete)
? new URL(device.verification_uri_complete)
@@ -226,10 +226,9 @@ function withoutCredentials(body: Readonly<Record<string, unknown>> | undefined)
return Object.fromEntries(Object.entries(body ?? {}).filter(([key]) => key !== "apiKey" && key !== "headers"))
}
function normalizeServer(input: unknown) {
function normalizeServer(input: string) {
return Effect.try({
try: () => {
if (typeof input !== "string") throw new Error("expected string")
const url = new URL(input)
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("expected HTTP(S)")
return `${url.origin}${url.pathname.replace(/\/+$/, "")}`
+9 -14
View File
@@ -4,7 +4,6 @@ import { SessionEvent } from "./event"
import { SessionMessage } from "./message"
export interface Adapter {
readonly getAgent: () => Effect.Effect<SessionMessage.AgentSelected["agent"] | undefined, never, never>
readonly getModel: () => Effect.Effect<SessionMessage.ModelSelected["model"] | undefined, never, never>
readonly getCurrentAssistant: () => Effect.Effect<SessionMessage.Assistant | undefined, never, never>
readonly getAssistant: (
@@ -60,19 +59,15 @@ export function update(adapter: Adapter, event: SessionEvent.DurableEvent) {
"session.created": () => Effect.void,
"session.usage.recorded": () => Effect.void,
"session.agent.selected": (event) => {
return Effect.gen(function* () {
const previous = yield* adapter.getAgent()
yield* adapter.appendMessage(
SessionMessage.AgentSelected.make({
id: SessionMessage.ID.fromEvent(event.id),
type: "agent-switched",
metadata: event.metadata,
agent: event.data.agent,
previous,
time: { created: event.created },
}),
)
})
return adapter.appendMessage(
SessionMessage.AgentSelected.make({
id: SessionMessage.ID.fromEvent(event.id),
type: "agent-switched",
metadata: event.metadata,
agent: event.data.agent,
time: { created: event.created },
}),
)
},
"session.model.selected": (event) => {
return Effect.gen(function* () {
+6 -21
View File
@@ -6,7 +6,6 @@ import { Database } from "../database/database"
import { Bus } from "../bus"
import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
import { Model } from "../model"
import { Agent } from "../agent"
import { SessionEvent } from "./event"
import { SessionMessage } from "./message"
import { SessionMessageUpdater } from "./message-updater"
@@ -231,17 +230,6 @@ function run(db: DatabaseService, event: MessageEvent) {
}
const appendMessage = (message: SessionMessage.Info) => insertMessage(db, event, message)
const adapter: SessionMessageUpdater.Adapter = {
getAgent() {
return db
.select({ agent: SessionTable.agent })
.from(SessionTable)
.where(eq(SessionTable.id, event.data.sessionID))
.get()
.pipe(
Effect.orDie,
Effect.map((row) => (row?.agent ? Agent.ID.make(row.agent) : undefined)),
)
},
getModel() {
return db
.select({ model: SessionTable.model })
@@ -410,15 +398,12 @@ const layer = Layer.effectDiscard(
db.delete(SessionTable).where(eq(SessionTable.id, event.data.sessionID)).run().pipe(Effect.orDie),
)
yield* bus.project(SessionEvent.AgentSelected, (event) =>
Effect.gen(function* () {
yield* run(db, event)
yield* db
.update(SessionTable)
.set({ agent: event.data.agent, time_updated: DateTime.toEpochMillis(event.created) })
.where(eq(SessionTable.id, event.data.sessionID))
.run()
.pipe(Effect.orDie)
}),
db
.update(SessionTable)
.set({ agent: event.data.agent, time_updated: DateTime.toEpochMillis(event.created) })
.where(eq(SessionTable.id, event.data.sessionID))
.run()
.pipe(Effect.orDie, Effect.andThen(run(db, event))),
)
yield* bus.project(SessionEvent.ModelSelected, (event) =>
Effect.gen(function* () {
@@ -1,7 +1,7 @@
import { OpenAIResponsesLanguageModel } from "@opencode-ai/core/github-copilot/responses/openai-responses-language-model"
import { convertToOpenAIResponsesInput } from "@opencode-ai/core/github-copilot/responses/convert-to-openai-responses-input"
import { describe, test, expect, mock } from "bun:test"
import type { LanguageModelV3Prompt, LanguageModelV3StreamPart } from "@ai-sdk/provider"
import type { LanguageModelV3Prompt } from "@ai-sdk/provider"
const TEST_PROMPT: LanguageModelV3Prompt = [{ role: "user", content: [{ type: "text", text: "Hello" }] }]
@@ -11,16 +11,6 @@ function createMockFetch(body: unknown) {
)
}
function createStreamFetch(events: ReadonlyArray<Record<string, unknown>>) {
return mock(
async () =>
new Response(events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""), {
status: 200,
headers: { "Content-Type": "text/event-stream" },
}),
)
}
function createModel(fetchFn: ReturnType<typeof mock>) {
return new OpenAIResponsesLanguageModel("test-model", {
provider: "copilot",
@@ -87,173 +77,10 @@ describe("doGenerate", () => {
expect(providerMetadata?.copilot?.responseId).toBe("resp_1")
expect(providerMetadata?.openai).toBeUndefined()
})
test("defaults to stateless encrypted reasoning and keeps previousResponseId opt-in", async () => {
const requests: Array<Record<string, unknown>> = []
const fetchFn = mock(async (_input: Parameters<typeof fetch>[0], init?: RequestInit) => {
requests.push(JSON.parse(init?.body as string))
return new Response(
JSON.stringify({
id: "resp_1",
created_at: 0,
model: "gpt-5.5",
output: [],
usage: { input_tokens: 1, output_tokens: 1 },
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
)
})
const model = createModel(fetchFn)
await model.doGenerate({ prompt: TEST_PROMPT, includeRawChunks: false } as any)
await model.doGenerate({
prompt: TEST_PROMPT,
includeRawChunks: false,
providerOptions: { copilot: { previousResponseId: "resp_previous", store: false } },
} as any)
await model.doGenerate({
prompt: TEST_PROMPT,
includeRawChunks: false,
providerOptions: { copilot: { store: true } },
} as any)
expect(requests[0]?.previous_response_id).toBeUndefined()
expect(requests[0]?.store).toBe(false)
expect(requests[0]?.include).toEqual(["reasoning.encrypted_content"])
expect(requests[1]?.previous_response_id).toBe("resp_previous")
expect(requests[1]?.store).toBe(false)
expect(requests[1]?.include).toEqual(["reasoning.encrypted_content"])
expect(requests[2]?.store).toBe(true)
expect(requests[2]?.include).toEqual(["reasoning.encrypted_content"])
})
})
describe("doStream", () => {
test("streams sequential Copilot reasoning summary blocks", async () => {
const model = createModel(
createStreamFetch([
{
type: "response.output_item.added",
output_index: 0,
item: { type: "reasoning", id: "rs_1", encrypted_content: null },
},
{
type: "response.output_item.added",
output_index: 0,
item: { type: "reasoning", id: "rs_rotated", encrypted_content: null },
},
{ type: "response.reasoning_summary_part.added", item_id: "rs_1", summary_index: 0 },
{ type: "response.reasoning_summary_text.delta", item_id: "rs_1", summary_index: 0, delta: "First" },
{ type: "response.reasoning_summary_part.done", item_id: "rs_1", summary_index: 0 },
{ type: "response.reasoning_summary_part.added", item_id: "rs_1", summary_index: 1 },
{ type: "response.reasoning_summary_part.added", item_id: "rs_1", summary_index: 1 },
{ type: "response.reasoning_summary_text.delta", item_id: "rs_1", summary_index: 1, delta: "Second" },
{ type: "response.reasoning_summary_part.done", item_id: "rs_1", summary_index: 1 },
{
type: "response.output_item.done",
output_index: 0,
item: { type: "reasoning", id: "rs_rotated", encrypted_content: "encrypted-state" },
},
]),
)
const result = await model.doStream({
prompt: TEST_PROMPT,
includeRawChunks: false,
providerOptions: { copilot: { store: false } },
} as any)
const reader = result.stream.getReader()
const events: LanguageModelV3StreamPart[] = []
while (true) {
const item = await reader.read()
if (item.done) break
if (item.value.type.startsWith("reasoning-")) events.push(item.value)
}
expect(events).toMatchObject([
{
type: "reasoning-start",
id: "rs_1:0",
providerMetadata: { copilot: { itemId: "rs_1", reasoningEncryptedContent: null } },
},
{ type: "reasoning-delta", id: "rs_1:0", delta: "First" },
{ type: "reasoning-end", id: "rs_1:0", providerMetadata: { copilot: { itemId: "rs_1" } } },
{
type: "reasoning-start",
id: "rs_1:1",
providerMetadata: { copilot: { itemId: "rs_1", reasoningEncryptedContent: null } },
},
{ type: "reasoning-delta", id: "rs_1:1", delta: "Second" },
{
type: "reasoning-end",
id: "rs_1:1",
providerMetadata: { copilot: { itemId: "rs_rotated", reasoningEncryptedContent: "encrypted-state" } },
},
])
const deltas = new Map(
events.filter((event) => event.type === "reasoning-delta").map((event) => [event.id, event.delta] as const),
)
const { input } = await convertToOpenAIResponsesInput({
prompt: [
{
role: "assistant",
content: events
.filter((event) => event.type === "reasoning-end")
.map((event) => ({
type: "reasoning" as const,
text: deltas.get(event.id) ?? "",
providerOptions: event.providerMetadata,
})),
},
],
systemMessageMode: "system",
store: false,
})
expect(input).toEqual([
{
type: "reasoning",
id: "rs_rotated",
encrypted_content: "encrypted-state",
summary: [],
},
])
})
test("closes reasoning when a Copilot stream ends before output_item.done", async () => {
const model = createModel(
createStreamFetch([
{
type: "response.output_item.added",
output_index: 0,
item: { type: "reasoning", id: "rs_1", encrypted_content: null },
},
{ type: "response.reasoning_summary_text.delta", item_id: "rs_rotated", summary_index: 0, delta: "First" },
]),
)
const result = await model.doStream({
prompt: TEST_PROMPT,
includeRawChunks: false,
providerOptions: { copilot: { store: false } },
} as any)
const reader = result.stream.getReader()
const events: LanguageModelV3StreamPart[] = []
while (true) {
const item = await reader.read()
if (item.done) break
if (item.value.type.startsWith("reasoning-")) events.push(item.value)
}
expect(events.map((event) => event.type)).toEqual(["reasoning-start", "reasoning-delta", "reasoning-end"])
expect(events.at(-1)).toMatchObject({
type: "reasoning-end",
id: "rs_1:0",
providerMetadata: { copilot: { itemId: "rs_1" } },
})
})
})
describe("convertToOpenAIResponsesInput", () => {
test("omits response item IDs from stateless function calls", async () => {
test("echoes a stale tool-call itemId from the copilot namespace as the function_call id", async () => {
const { input } = await convertToOpenAIResponsesInput({
prompt: [
{
@@ -279,11 +106,12 @@ describe("convertToOpenAIResponsesInput", () => {
call_id: "call_1",
name: "bash",
arguments: JSON.stringify({ command: "ls" }),
id: "fc_999",
},
])
})
test("preserves response item IDs for stored function calls", async () => {
test("omits the function_call id once the stale copilot itemId has been stripped", async () => {
const { input } = await convertToOpenAIResponsesInput({
prompt: [
{
@@ -294,16 +122,16 @@ describe("convertToOpenAIResponsesInput", () => {
toolCallId: "call_1",
toolName: "bash",
input: { command: "ls" },
providerOptions: { copilot: { itemId: "fc_999" } },
providerOptions: {},
},
],
},
],
systemMessageMode: "system",
store: true,
store: false,
})
expect((input[0] as any).id).toBe("fc_999")
expect((input[0] as any).id).toBeUndefined()
})
test("preserves reasoning items keyed by the copilot namespace instead of dropping them", async () => {
@@ -330,34 +158,12 @@ describe("convertToOpenAIResponsesInput", () => {
type: "reasoning",
id: "rs_1",
encrypted_content: "enc_1",
summary: [],
summary: [{ type: "summary_text", text: "thinking..." }],
},
])
})
test("drops encrypted reasoning with no completed copilot itemId", async () => {
const { input, warnings } = await convertToOpenAIResponsesInput({
prompt: [
{
role: "assistant",
content: [
{
type: "reasoning",
text: "thinking...",
providerOptions: { copilot: { reasoningEncryptedContent: "enc_1" } },
},
],
},
],
systemMessageMode: "system",
store: false,
})
expect(input).toEqual([])
expect(warnings).toHaveLength(1)
})
test("drops reasoning with neither a copilot itemId nor encrypted content", async () => {
test("drops reasoning items with no copilot itemId and warns, as before", async () => {
const { input, warnings } = await convertToOpenAIResponsesInput({
prompt: [
{
+8 -19
View File
@@ -140,11 +140,7 @@ describe("Integration", () => {
yield* integrations.transform((editor) =>
editor.method.update({
integrationID,
method: {
type: "key",
label: "API key",
form: [{ type: "string", key: "accountId", title: "Account ID", required: true }],
},
method: { type: "key", label: "API key" },
}),
)
const updated = yield* bus
@@ -152,17 +148,9 @@ describe("Integration", () => {
.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped)
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({
integrationID,
key: "secret",
answer: { accountId: "account" },
label: "Work",
})
@@ -170,7 +158,7 @@ describe("Integration", () => {
expect.objectContaining({
integrationID,
label: "Work",
value: Credential.Key.make({ type: "key", key: "secret", configuration: { accountId: "account" } }),
value: Credential.Key.make({ type: "key", key: "secret" }),
}),
])
expect((yield* Fiber.join(updated)).length).toBe(1)
@@ -255,6 +243,7 @@ describe("Integration", () => {
const attempt = yield* integrations.oauth.connect({
integrationID,
methodID,
inputs: {},
label: "Personal",
})
expect(attempt.mode).toBe("code")
@@ -300,7 +289,7 @@ describe("Integration", () => {
}),
)
const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
expect(
yield* integrations.oauth.complete({ integrationID, attemptID: attempt.attemptID }).pipe(Effect.flip),
).toBeInstanceOf(Integration.CodeRequiredError)
@@ -338,7 +327,7 @@ describe("Integration", () => {
}),
)
const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
yield* Effect.yieldNow
expect(yield* integrations.oauth.status({ integrationID, attemptID: attempt.attemptID })).toEqual({
status: "complete",
@@ -376,7 +365,7 @@ describe("Integration", () => {
}),
)
const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
const exit = yield* integrations.oauth
.complete({ integrationID, attemptID: attempt.attemptID, code: "1234" })
.pipe(Effect.exit)
@@ -412,7 +401,7 @@ describe("Integration", () => {
}),
)
const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
expect(attempt.time.expires - attempt.time.created).toBe(Duration.toMillis(Duration.minutes(10)))
yield* TestClock.adjust(Duration.minutes(10))
yield* Effect.yieldNow
@@ -453,7 +442,7 @@ describe("Integration", () => {
}),
)
const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
expect(attempt.time).toEqual({ created, expires: expiresAt })
})
})
+2 -6
View File
@@ -736,11 +736,7 @@ describe("ModelResolver", () => {
headers: { "x-aisdk": "header" },
body: { custom: true },
}),
Credential.Key.make({
type: "key",
key: "fallback-secret",
configuration: { accountId: "account" },
}),
Credential.Key.make({ type: "key", key: "fallback-secret" }),
{
loadAISDK: (runtime) =>
Effect.sync(() => {
@@ -749,7 +745,7 @@ describe("ModelResolver", () => {
modelID: "mistral-api-model",
providerID: "test-provider",
package: Provider.aisdk("@ai-sdk/mistral"),
settings: { project: "test", apiKey: "fallback-secret", accountId: "account" },
settings: { project: "test", apiKey: "fallback-secret" },
headers: { "x-aisdk": "header" },
body: { custom: true },
})
+35 -9
View File
@@ -1,5 +1,5 @@
import { Plugin } from "@opencode-ai/plugin/effect"
import type { IntegrationMethod, IntegrationMethodRegistration } from "@opencode-ai/plugin/effect/integration"
import type { IntegrationMethodRegistration } from "@opencode-ai/plugin/effect/integration"
import { Agent } from "@opencode-ai/core/agent"
import { Catalog } from "@opencode-ai/core/catalog"
import { Credential } from "@opencode-ai/core/credential"
@@ -15,6 +15,7 @@ import { Effect, Stream } from "effect"
type Overrides = Partial<Omit<Plugin.Context, "options" | "session">> & {
readonly session?: Partial<Plugin.Context["session"]>
}
export function host(overrides: Overrides = {}): Plugin.Context {
return {
app: overrides.app ?? { name: "test", version: "test", channel: "test" },
@@ -277,7 +278,7 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
update: (id, update) => draft.update(Integration.ID.make(id), update),
remove: (id) => draft.remove(Integration.ID.make(id)),
method: {
list: (id) => draft.method.list(Integration.ID.make(id)),
list: (id) => draft.method.list(Integration.ID.make(id)).map(method),
update: (input) => {
if ("authorize" in input) {
const methodID = Integration.MethodID.make(input.method.id)
@@ -285,8 +286,8 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
draft.method.update({
integrationID: Integration.ID.make(input.integrationID),
method: { ...input.method, id: methodID },
authorize: (answer) =>
input.authorize(answer).pipe(
authorize: (inputs) =>
input.authorize(inputs).pipe(
Effect.map((authorization) => {
if (authorization.mode === "auto") {
return {
@@ -335,7 +336,7 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
if (input.method.type === "env") {
draft.method.update({
integrationID: Integration.ID.make(input.integrationID),
method: input.method,
method: { ...input.method, names: [...input.method.names] },
})
return
}
@@ -345,6 +346,7 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
method: {
...input.method,
id: Integration.MethodID.make(input.method.id),
command: [...input.method.command],
},
})
return
@@ -399,11 +401,35 @@ function oauthCredential(value: Credential.OAuth) {
return Credential.OAuth.make({ ...value, methodID: Integration.MethodID.make(value.methodID) })
}
function internalMethod(value: IntegrationMethod): Integration.Method {
if (value.type === "oauth" || value.type === "command") {
return { ...value, id: Integration.MethodID.make(value.id) }
function method(value: Integration.Method) {
if (value.type === "env") return { type: value.type, names: [...value.names] }
if (value.type === "key") return { type: value.type, label: value.label }
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) {
@@ -8,7 +8,6 @@ import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHost } from "@opencode-ai/core/plugin/host"
import { AzurePlugin } from "@opencode-ai/core/plugin/provider/azure"
import { Provider } from "@opencode-ai/core/provider"
import { Integration } from "@opencode-ai/core/integration"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -61,27 +60,6 @@ function fakeSelectorSdk(calls: string[]) {
}
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", () =>
withEnv({ AZURE_RESOURCE_NAME: "from-env" }, () =>
Effect.gen(function* () {
@@ -217,17 +195,7 @@ describe("AzurePlugin", () => {
Effect.gen(function* () {
const plugin = yield* Plugin.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()
expect((yield* (yield* Integration.Service).get(Integration.ID.make("azure")))?.methods).toContainEqual({
type: "key",
label: "API key",
})
const result = yield* aisdk.runSDK({
model: Model.Info.make({
...Model.Info.default(Provider.ID.azure, Model.ID.make("deployment")),
@@ -1,13 +1,11 @@
import { AISDK } from "@opencode-ai/core/aisdk"
import { describe, expect, mock } from "bun:test"
import { Effect } from "effect"
import { Catalog } from "@opencode-ai/core/catalog"
import { Model } from "@opencode-ai/core/model"
import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHost } from "@opencode-ai/core/plugin/host"
import { CloudflareAIGatewayPlugin } from "@opencode-ai/core/plugin/provider/cloudflare-ai-gateway"
import { Provider } from "@opencode-ai/core/provider"
import { Integration } from "@opencode-ai/core/integration"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -104,24 +102,6 @@ mock.module("ai-gateway-provider/providers/unified", () => ({
}))
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", () =>
withEnv(
{
@@ -377,16 +357,7 @@ describe("CloudflareAIGatewayPlugin", () => {
resetCalls()
const plugin = yield* Plugin.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()
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({
model: Model.Info.make({
@@ -7,7 +7,6 @@ import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHost } from "@opencode-ai/core/plugin/host"
import { CloudflareWorkersAIPlugin } from "@opencode-ai/core/plugin/provider/cloudflare-workers-ai"
import { Provider } from "@opencode-ai/core/provider"
import { Integration } from "@opencode-ai/core/integration"
import type { LanguageModelV3 } from "@ai-sdk/provider"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -80,29 +79,6 @@ function cloudflareHeaders(sdk: unknown, modelID = "@cf/model") {
}
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", () =>
withEnv({ CLOUDFLARE_ACCOUNT_ID: "acct", CLOUDFLARE_API_KEY: "key" }, () =>
Effect.gen(function* () {
@@ -115,9 +91,6 @@ describe("CloudflareWorkersAIPlugin", () => {
}),
)
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 sdk = yield* aisdk.runSDK({
model: Model.Info.make({
@@ -162,16 +135,7 @@ describe("CloudflareWorkersAIPlugin", () => {
Effect.gen(function* () {
const plugin = yield* Plugin.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()
expect(
(yield* (yield* Integration.Service).get(Integration.ID.make("cloudflare-workers-ai")))?.methods,
).toContainEqual({ type: "key", label: "API key" })
const result = yield* aisdk.runSDK({
model: Model.Info.make({
...Model.Info.default(Provider.ID.make("cloudflare-workers-ai"), Model.ID.make("@cf/model")),
@@ -1,14 +1,11 @@
import { AISDK } from "@opencode-ai/core/aisdk"
import { App } from "@opencode-ai/core/app"
import { Agent } from "@opencode-ai/schema/agent"
import { Session } from "@opencode-ai/schema/session"
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
import { Catalog } from "@opencode-ai/core/catalog"
import { Model } from "@opencode-ai/core/model"
import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHost } from "@opencode-ai/core/plugin/host"
import { PluginHooks } from "@opencode-ai/core/plugin/hooks"
import { copilotBaseURL, copilotFetch, GithubCopilotPlugin } from "@opencode-ai/core/plugin/provider/github-copilot"
import { Provider } from "@opencode-ai/core/provider"
import { Integration } from "@opencode-ai/core/integration"
@@ -60,37 +57,11 @@ describe("GithubCopilotPlugin", () => {
id: Integration.MethodID.make("device"),
type: "oauth",
label: "Login with GitHub Copilot",
form: expect.any(Array),
prompts: 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", () =>
Effect.gen(function* () {
const requests: Headers[] = []
@@ -100,6 +71,7 @@ describe("GithubCopilotPlugin", () => {
requests.push(new Headers(init?.headers))
return Response.json({ ok: true })
},
false,
App.make({ name: "test", version: "1.2.3", channel: "beta" }),
)
yield* Effect.promise(() =>
@@ -120,27 +92,6 @@ describe("GithubCopilotPlugin", () => {
}),
)
it.effect("adds Copilot authentication to native Anthropic requests", () =>
Effect.gen(function* () {
yield* addPlugin()
const event = yield* (yield* PluginHooks.Service).trigger("session", "http.request", {
sessionID: Session.ID.make("ses_test"),
agent: Agent.ID.make("build"),
model: Model.Ref.make({ providerID: Provider.ID.githubCopilot, id: Model.ID.make("claude-sonnet-4.5") }),
request: new Request("https://api.githubcopilot.com/v1/messages", {
method: "POST",
headers: { "Content-Type": "application/json", "x-api-key": "token" },
body: JSON.stringify({ messages: [{ role: "user", content: [{ type: "text", text: "hello" }] }] }),
}),
})
expect(event.request.headers.get("authorization")).toBe("Bearer token")
expect(event.request.headers.has("x-api-key")).toBe(false)
expect(event.request.headers.get("x-initiator")).toBe("user")
expect(event.request.headers.get("anthropic-beta")).toBe("interleaved-thinking-2025-05-14")
expect(event.request.headers.get("x-github-api-version")).toBe("2026-06-01")
}),
)
it.effect("creates the bundled Copilot SDK for the GitHub Copilot package", () =>
Effect.gen(function* () {
const plugin = yield* Plugin.Service
@@ -128,7 +128,7 @@ describe("OpencodePlugin", () => {
const attempt = yield* integrations.oauth.connect({
integrationID,
methodID: Integration.MethodID.make("device"),
answer: { server: `${server.url.origin}/console///?ignored=true#ignored` },
inputs: { server: `${server.url.origin}/console///?ignored=true#ignored` },
})
expect(attempt.url).toBe(`${server.url.origin}/verify`)
yield* eventually(
@@ -155,7 +155,7 @@ describe("OpencodePlugin", () => {
.connect({
integrationID: Integration.ID.make("opencode"),
methodID: Integration.MethodID.make("device"),
answer: { server: "ftp://console.example.com" },
inputs: { server: "ftp://console.example.com" },
})
.pipe(Effect.flip)
expect(error).toBeInstanceOf(Integration.AuthorizationError)
@@ -163,21 +163,6 @@ 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", () =>
Effect.acquireUseRelease(
Effect.sync(() => {
+1 -4
View File
@@ -129,10 +129,7 @@ describe("built-in web search providers", () => {
yield* WebSearchParallel.Plugin.effect(
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({
query: "effect layers",
+2 -12
View File
@@ -358,7 +358,6 @@ describe("SessionProjector", () => {
directory: "/project",
title: "test",
version: "test",
agent: build,
model: previousModel,
})
.run()
@@ -367,11 +366,7 @@ describe("SessionProjector", () => {
yield* bus.publish(SessionEvent.AgentSelected, {
sessionID,
agent: Agent.ID.make("plan"),
})
yield* bus.publish(SessionEvent.AgentSelected, {
sessionID,
agent: Agent.ID.make("general"),
agent: build,
})
yield* bus.publish(SessionEvent.ModelSelected, {
sessionID,
@@ -454,7 +449,6 @@ describe("SessionProjector", () => {
)
expect(messages.map((message) => message.type)).toEqual([
"agent-switched",
"agent-switched",
"model-switched",
"synthetic",
@@ -465,10 +459,6 @@ describe("SessionProjector", () => {
text: "synthetic context",
metadata: { source: "projector-test" },
})
expect(messages.filter((message) => message.type === "agent-switched")).toMatchObject([
{ agent: "plan", previous: "build" },
{ agent: "general", previous: "plan" },
])
expect(messages.find((message) => message.type === "model-switched")).toMatchObject({ previous: previousModel })
expect(messages.find((message) => message.type === "shell")).toMatchObject({
command: "pwd",
@@ -484,7 +474,7 @@ describe("SessionProjector", () => {
expect(
yield* db.select().from(SessionTable).where(eq(SessionTable.id, sessionID)).get().pipe(Effect.orDie),
).toMatchObject({
agent: "general",
agent: "build",
model,
time_updated: DateTime.toEpochMillis(created),
})
+5
View File
@@ -90,10 +90,15 @@ test("Core reuses the canonical shared schemas", async () => {
[coreFileSystem.Match, FileSystem.Match],
[coreIntegration.ID, Integration.ID],
[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.KeyMethod, Integration.KeyMethod],
[coreIntegration.EnvMethod, Integration.EnvMethod],
[coreIntegration.Method, Integration.Method],
[coreIntegration.Inputs, Integration.Inputs],
[coreIntegration.Ref, Integration.Ref],
[coreLocation.Ref, Location.Ref],
[coreAI.ProviderMetadata, AI.ProviderMetadata],
+1 -9
View File
@@ -1316,15 +1316,7 @@ export function write(
}).pipe(Effect.flatMap((content) => fs.writeFileString(join(directory, file.path), content))),
{ concurrency: 8, discard: true },
)
// 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)
yield* fs.writeFileString(manifest, JSON.stringify(output.files.map((file) => file.path).sort(), null, 2) + "\n")
})
}
+1 -1
View File
@@ -16,7 +16,7 @@ describe("HttpApiCodegen.write", () => {
expect(writes).toEqual([
{ path: "/generated/session.ts", content: "export const session = {}\n" },
{ path: "/generated/.httpapi-codegen.json", content: '["session.ts"]\n' },
{ path: "/generated/.httpapi-codegen.json", content: '[\n "session.ts"\n]\n' },
])
}).pipe(
Effect.provideService(
+10 -34
View File
@@ -1,43 +1,19 @@
import type { ConnectionInfo } from "@opencode-ai/client"
import type {
ConnectionInfo,
IntegrationCommandMethod,
IntegrationEnvMethod,
IntegrationKeyMethod,
IntegrationMethod,
IntegrationOAuthMethod,
} from "@opencode-ai/client"
import type { IntegrationApi } from "@opencode-ai/client/effect/api"
import { Credential } from "@opencode-ai/schema/credential"
import { Form } from "@opencode-ai/schema/form"
import type { Effect, Scope } from "effect"
import type { Transform } from "./registration.js"
type IntegrationInputs = Record<string, 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 = {
readonly url: string
readonly instructions: string
@@ -55,7 +31,7 @@ export type IntegrationOAuthAuthorization = {
export type IntegrationOAuthMethodRegistration = {
readonly integrationID: string
readonly method: IntegrationOAuthMethod
readonly authorize: (answer: Form.Answer) => Effect.Effect<IntegrationOAuthAuthorization, unknown, Scope.Scope>
readonly authorize: (inputs: IntegrationInputs) => Effect.Effect<IntegrationOAuthAuthorization, unknown, Scope.Scope>
readonly refresh?: (credential: Credential.OAuth) => Effect.Effect<Credential.OAuth, unknown>
readonly label?: (credential: Credential.OAuth) => string | undefined
}
+11 -38
View File
@@ -1,42 +1,18 @@
import type { ConnectionInfo } from "@opencode-ai/client"
import type {
ConnectionInfo,
IntegrationCommandMethod,
IntegrationEnvMethod,
IntegrationKeyMethod,
IntegrationMethod,
IntegrationOAuthMethod,
} from "@opencode-ai/client"
import type { IntegrationApi } from "@opencode-ai/client/promise/api"
import { Credential } from "@opencode-ai/schema/credential"
import { Form } from "@opencode-ai/schema/form"
import type { Transform } from "./registration.js"
type IntegrationInputs = Record<string, 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 = {
readonly url: string
readonly instructions: string
@@ -55,7 +31,7 @@ export type IntegrationOAuthAuthorization = {
export type IntegrationOAuthMethodRegistration = {
readonly integrationID: string
readonly method: IntegrationOAuthMethod
readonly authorize: (answer: Form.Answer) => Promise<IntegrationOAuthAuthorization>
readonly authorize: (inputs: IntegrationInputs) => Promise<IntegrationOAuthAuthorization>
readonly refresh?: (credential: Credential.OAuth) => Promise<Credential.OAuth>
readonly label?: (credential: Credential.OAuth) => string | undefined
}
@@ -63,10 +39,7 @@ export type IntegrationOAuthMethodRegistration = {
export type IntegrationMethodRegistration =
| IntegrationOAuthMethodRegistration
| { readonly integrationID: string; readonly method: IntegrationCommandMethod }
| {
readonly integrationID: string
readonly method: IntegrationKeyMethod
}
| { readonly integrationID: string; readonly method: IntegrationKeyMethod }
| { readonly integrationID: string; readonly method: IntegrationEnvMethod }
export interface IntegrationDraft {
+47 -16
View File
@@ -150,24 +150,54 @@ export interface Page {
readonly render: (input: { readonly data?: Record<string, any> }) => JSX.Element
}
export interface SlotMap {
readonly app: Readonly<Record<string, never>>
readonly "home.footer": Readonly<Record<string, never>>
readonly "prompt.footer.end": {
readonly sessionID?: string
readonly mode: "normal" | "shell"
/**
* The host UI's extensible regions. Each region publishes an input (reactive
* props passed to every claim render) and a part vocabulary: the stable ids
* of host furniture that placements may anchor to. Part ids are documented
* API coarse, few, and kept stable across host refactors.
*/
export interface RegionMap {
readonly app: { readonly input: Readonly<Record<string, never>>; readonly part: never }
readonly "home.footer": { readonly input: Readonly<Record<string, never>>; readonly part: never }
readonly "prompt.footer": {
readonly input: { readonly sessionID?: string; readonly mode: "normal" | "shell" }
readonly part: "status" | "file"
}
readonly "session.composer.top": {
readonly sessionID: string
}
readonly "sidebar.content": {
readonly sessionID: string
}
readonly "sidebar.footer": Readonly<Record<string, never>>
readonly "session.composer.top": { readonly input: { readonly sessionID: string }; readonly part: never }
readonly "sidebar.content": { readonly input: { readonly sessionID: string }; readonly part: never }
readonly "sidebar.footer": { readonly input: Readonly<Record<string, never>>; readonly part: never }
}
export type RegionName = keyof RegionMap
export type SlotName = keyof SlotMap
export type Slot<Name extends SlotName = SlotName> = (props: SlotMap[Name]) => JSX.Element
/**
* Where a claim lands in a region's structure. Exactly one of:
* - `at`: the region's edge `"end"` is the ceremony-free default position
* - `before` / `after`: adjacent to a host part, wherever the host keeps it
* - `replace`: take over one part or the whole region by naming it.
* Replace is takeover: anything anchored inside the replaced subtree is
* suppressed and recorded, never silently dropped. At the same target the
* last-enabled claim wins; an ancestor takeover beats a descendant one
* regardless of order.
* A placement aimed at a part the host no longer publishes degrades to the
* region's end (after end-edge claims) rather than disappearing.
*
* The `?: never` fields make the variants mutually exclusive: a claim with
* two placement keys is a type error, not a silent priority pick.
*/
export type RegionPlacement<Name extends RegionName = RegionName> =
| { readonly at: "start" | "end"; readonly before?: never; readonly after?: never; readonly replace?: never }
| { readonly before: RegionMap[Name]["part"]; readonly at?: never; readonly after?: never; readonly replace?: never }
| { readonly after: RegionMap[Name]["part"]; readonly at?: never; readonly before?: never; readonly replace?: never }
| {
readonly replace: RegionMap[Name]["part"] | Name
readonly at?: never
readonly before?: never
readonly after?: never
}
export type RegionClaim<Name extends RegionName = RegionName> = RegionPlacement<Name> & {
readonly render: (input: RegionMap[Name]["input"]) => JSX.Element
}
export interface App {
readonly version: string
@@ -394,7 +424,8 @@ export interface UI {
/** Closes an open tab, or the active tab when omitted, and returns false when no tab matched. */
close(sessionID?: string): boolean
}
readonly slot: <Name extends SlotName>(name: Name, render: Slot<Name>) => () => void
/** Claims a place in a region's structure; see RegionPlacement. */
readonly slot: <Name extends RegionName>(region: Name, claim: RegionClaim<Name>) => () => void
}
export interface Context {
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -1,11 +1,12 @@
import { Integration } from "@opencode-ai/schema/integration"
import { Location } from "@opencode-ai/schema/location"
import { Form } from "@opencode-ai/schema/form"
import { Schema } from "effect"
import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
import { InvalidRequestError } from "../errors.js"
import { LocationQuery, locationQueryOpenApi } from "./location.js"
const Inputs = Schema.Record(Schema.String, Schema.String)
export const IntegrationGroup = HttpApiGroup.make("server.integration")
.add(
HttpApiEndpoint.get("integration.list", "/api/integration", {
@@ -58,7 +59,6 @@ export const IntegrationGroup = HttpApiGroup.make("server.integration")
query: LocationQuery,
payload: Schema.Struct({
key: Schema.String,
answer: Schema.optional(Form.Answer),
label: Schema.optional(Schema.String),
}),
success: HttpApiSchema.NoContent,
@@ -79,7 +79,7 @@ export const IntegrationGroup = HttpApiGroup.make("server.integration")
query: LocationQuery,
payload: Schema.Struct({
methodID: Integration.MethodID,
answer: Schema.optional(Form.Answer),
inputs: Inputs,
label: Schema.optional(Schema.String),
}),
success: Location.response(Integration.Attempt),
-2
View File
@@ -5,7 +5,6 @@ import { optional } from "./schema.js"
import { IntegrationMethodID } from "./integration-id.js"
import { ascending } from "./identifier.js"
import { NonNegativeInt, statics } from "./schema.js"
import { Form } from "./form.js"
export const ID = Schema.String.pipe(
Schema.brand("Credential.ID"),
@@ -28,7 +27,6 @@ export const Key = Schema.Struct({
type: Schema.Literal("key"),
key: Schema.String,
metadata: optional(Schema.Record(Schema.String, Schema.Unknown)),
configuration: optional(Form.Answer),
}).annotate({ identifier: "Credential.Key" })
export const Value = Schema.Union([OAuth, Key])
+38 -3
View File
@@ -7,7 +7,6 @@ import { Connection } from "./connection.js"
import { ascending } from "./identifier.js"
import { statics } from "./schema.js"
import { IntegrationID, IntegrationMethodID } from "./integration-id.js"
import { Form } from "./form.js"
export const ID = IntegrationID
export type ID = typeof ID.Type
@@ -15,12 +14,46 @@ export type ID = typeof ID.Type
export const MethodID = IntegrationMethodID
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 const OAuthMethod = Schema.Struct({
id: MethodID,
type: Schema.Literal("oauth"),
label: Schema.String,
form: optional(Form.Fields),
prompts: optional(Schema.Array(Prompt)),
}).annotate({ identifier: "Integration.OAuthMethod" })
export interface CommandMethod extends Schema.Schema.Type<typeof CommandMethod> {}
@@ -35,7 +68,6 @@ export interface KeyMethod extends Schema.Schema.Type<typeof KeyMethod> {}
export const KeyMethod = Schema.Struct({
type: Schema.Literal("key"),
label: optional(Schema.String),
form: optional(Form.Fields),
}).annotate({ identifier: "Integration.KeyMethod" })
export interface EnvMethod extends Schema.Schema.Type<typeof EnvMethod> {}
@@ -49,6 +81,9 @@ export const Method = Schema.Union([OAuthMethod, CommandMethod, KeyMethod, EnvMe
.annotate({ identifier: "Integration.Method" })
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({
type: "integration.updated",
schema: {},
-1
View File
@@ -42,7 +42,6 @@ export const AgentSelected = Schema.Struct({
...Base,
type: Schema.tag("agent-switched"),
agent: Agent.ID,
previous: Agent.ID.pipe(optional),
}).annotate({ identifier: "Session.Message.AgentSelected" })
export interface ModelSelected extends Schema.Schema.Type<typeof ModelSelected> {}
+1 -2
View File
@@ -58,7 +58,6 @@ export const IntegrationHandler = HttpApiBuilder.group(Api, "server.integration"
service.connection.key({
integrationID: ctx.params.integrationID,
key: ctx.payload.key,
answer: ctx.payload.answer,
label: ctx.payload.label,
}),
)
@@ -74,7 +73,7 @@ export const IntegrationHandler = HttpApiBuilder.group(Api, "server.integration"
service.oauth.connect({
integrationID: ctx.params.integrationID,
methodID: ctx.payload.methodID,
answer: ctx.payload.answer,
inputs: ctx.payload.inputs,
label: ctx.payload.label,
}),
),
+2
View File
@@ -1,5 +1,6 @@
import { Database } from "@opencode-ai/core/database/database"
import { ModelsDev } from "@opencode-ai/core/models-dev"
import { Observability } from "@opencode-ai/util/observability"
import { Schema } from "effect"
export const ServerOptions = Schema.Struct({
@@ -21,6 +22,7 @@ export const ServerOptions = Schema.Struct({
}),
),
models: Schema.optional(ModelsDev.Options),
observability: Schema.optional(Observability.Options),
config: Schema.optional(
Schema.Struct({
directory: Schema.optional(Schema.String),
+9
View File
@@ -7,6 +7,7 @@ import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { Bus } from "@opencode-ai/core/bus"
import { EventLogger } from "@opencode-ai/core/event-logger"
import { FileSystemSearch } from "@opencode-ai/core/filesystem/search"
import { Observability } from "@opencode-ai/util/observability"
import { Credential } from "@opencode-ai/core/credential"
import { Config } from "@opencode-ai/core/config"
import { Command } from "@opencode-ai/core/command"
@@ -130,6 +131,13 @@ function makeRoutes<AuthError, AuthServices>(
}),
)
: AppNodeBuilder.build(applicationServices, replacements)
const observability = Observability.layer({
...options.observability,
client: options.app?.name,
version: options.app?.version,
channel: options.app?.channel,
})
return serviceLayer.pipe(
Layer.flatMap((context) => {
const services = Layer.succeedContext(context)
@@ -153,5 +161,6 @@ function makeRoutes<AuthError, AuthServices>(
)
return Layer.merge(api, V1Migration.layer.pipe(Layer.provide(services)))
}),
Layer.provide(observability),
)
}
+2 -2
View File
@@ -87,7 +87,7 @@ import { PromptRefProvider, usePromptRef } from "./context/prompt"
import { Config, ConfigProvider, useConfig } from "./config"
import { PluginProvider, usePlugin, type PackageResolver } from "./plugin/context"
import { tuiPluginDirectories } from "./plugin/discovery"
import { PluginRoute, PluginSlot } from "./plugin/render"
import { PluginRoute, Region } from "./plugin/render"
import { CommandPaletteDialog } from "./component/command-palette"
import { COMMAND_PALETTE_COMMAND, Keymap, type KeymapCommand } from "./context/keymap"
@@ -1225,7 +1225,7 @@ function App(props: { pair?: DialogPairCredentials }) {
</Match>
</Switch>
</box>
<PluginSlot name="app" input={{}} mode="all" />
<Region name="app" input={{}} />
</Show>
</box>
</box>
+41 -252
View File
@@ -5,10 +5,6 @@ import type {
IntegrationInfo,
IntegrationOauthConnectOutput,
IntegrationOAuthMethod,
FormAnswer,
FormField,
FormFields,
FormValue,
} from "@opencode-ai/client"
import open from "open"
import { createMemo, createSignal, onCleanup, onMount, Show } from "solid-js"
@@ -22,7 +18,6 @@ import { DialogPrompt } from "../ui/dialog-prompt"
import { DialogSelect } from "../ui/dialog-select"
import { Link } from "../ui/link"
import { useToast } from "../ui/toast"
import { formLabel, formToggleMultiselect, formValidateValue, type FormAnswerField } from "../util/form"
const INTEGRATION_PRIORITY: Record<string, number> = {
opencode: 0,
@@ -37,10 +32,6 @@ type ConnectMethod = Exclude<IntegrationInfo["methods"][number], { type: "env" }
type IntegrationAttempt = IntegrationOauthConnectOutput["data"]
type CommandAttempt = IntegrationCommandConnectOutput["data"]
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[]) {
return list.toSorted(
@@ -190,7 +181,7 @@ function openMethod(
onConnected?: OnIntegrationConnected,
) {
if (method.type === "key") {
void beginKey(integration, method, dialog, onConnected)
dialog.replace(() => <KeyMethod integration={integration} method={method} onConnected={onConnected} />)
return
}
if (method.type === "command") {
@@ -200,21 +191,6 @@ function openMethod(
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: {
integration: IntegrationInfo
method: Extract<ConnectMethod, { type: "command" }>
@@ -360,7 +336,6 @@ function CommandView(props: { title: string; output: string; message: string })
function KeyMethod(props: {
integration: IntegrationInfo
method: Extract<ConnectMethod, { type: "key" }>
answer?: FormAnswer
onConnected?: OnIntegrationConnected
}) {
const data = useData()
@@ -381,7 +356,6 @@ function KeyMethod(props: {
integrationID: props.integration.id,
location: location(data),
key,
...(props.answer ? { answer: props.answer } : {}),
})
.then(() => connected(props.integration, data, dialog, toast, props.onConnected))
.catch((cause) => setError(message(cause)))
@@ -399,17 +373,17 @@ async function beginOAuth(
dialog: ReturnType<typeof useDialog>,
onConnected?: OnIntegrationConnected,
) {
const answer = method.form ? await formAnswer(dialog, method.label, method.form) : undefined
if (answer === null) return
const inputs = method.prompts?.length ? await promptInputs(dialog, method.prompts) : {}
if (inputs === null) return
dialog.replace(() => (
<OAuthStarting integration={integration} method={method} answer={answer} onConnected={onConnected} />
<OAuthStarting integration={integration} method={method} inputs={inputs} onConnected={onConnected} />
))
}
function OAuthStarting(props: {
integration: IntegrationInfo
method: IntegrationOAuthMethod
answer?: FormAnswer
inputs: Record<string, string>
onConnected?: OnIntegrationConnected
}) {
const data = useData()
@@ -423,7 +397,7 @@ function OAuthStarting(props: {
integrationID: props.integration.id,
location: location(data),
methodID: props.method.id,
...(props.answer ? { answer: props.answer } : {}),
inputs: props.inputs,
})
.then((result) => {
if (result.data.mode === "code") {
@@ -647,234 +621,49 @@ function OAuthView(props: {
)
}
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(
async function promptInputs(
dialog: ReturnType<typeof useDialog>,
title: string,
field: FormField,
): Promise<FormValue | undefined | typeof CANCELLED> {
if (field.type === "external") return externalAnswer(dialog, title, field)
if (field.type === "multiselect") return multiselectAnswer(dialog, title, field)
if (field.type === "boolean" || (field.type === "string" && field.options)) {
return selectAnswer(dialog, title, field)
}
return textAnswer(dialog, title, field)
}
async function selectAnswer(
dialog: ReturnType<typeof useDialog>,
title: string,
field: Extract<FormAnswerField, { type: "boolean" | "string" }>,
): Promise<FormValue | undefined | typeof CANCELLED> {
const options =
field.type === "boolean"
? field.default === false
? [
{ title: "No", value: false as FormValue },
{ title: "Yes", value: true as FormValue },
]
: [
{ 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>
)}
/>
)
},
() => resolve(CANCELLED),
)
})
}
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(
() => (
<DialogSelect<string | typeof CUSTOM | typeof SUBMIT>
title={formLabel(field) || title}
options={[
...field.options.map((option) => ({
title: `[${selected.includes(option.value) ? "x" : " "}] ${option.label}`,
prompts: NonNullable<IntegrationOAuthMethod["prompts"]>,
) {
const inputs: Record<string, string> = {}
for (const prompt of prompts) {
if (prompt.when) {
const value = inputs[prompt.when.key]
if (value === undefined) continue
const matches = prompt.when.op === "eq" ? value === prompt.when.value : value !== prompt.when.value
if (!matches) continue
}
if (prompt.type === "select") {
const value = await new Promise<string | null>((resolve) => {
dialog.replace(
() => (
<DialogSelect
title={prompt.message}
options={prompt.options.map((option) => ({
title: 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 (choice === CANCELLED) return CANCELLED
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)
description: option.hint,
}))}
onSelect={(option) => resolve(option.value)}
/>
),
() => resolve(null),
)
})
if (value === null) return null
inputs[prompt.key] = 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) => {
const value = await new Promise<string | null>((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),
() => <DialogPrompt title={prompt.message} placeholder={prompt.placeholder} onConfirm={resolve} />,
() => resolve(null),
)
})
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
if (value === null) return null
inputs[prompt.key] = value
}
return inputs
}
async function connected(
+87 -70
View File
@@ -53,7 +53,7 @@ import { useData } from "../../context/data"
import { useLocation } from "../../context/location"
import { Keymap, type KeymapCommand } from "../../context/keymap"
import { abbreviateHome } from "../../runtime"
import { PluginSlot } from "../../plugin/render"
import { Region } from "../../plugin/render"
import type { SessionPending } from "@opencode-ai/schema/session-pending"
export type PromptProps = {
@@ -1631,76 +1631,93 @@ export function Prompt(props: PromptProps) {
/>
</box>
<box width="100%" flexDirection="row" justifyContent="space-between" gap={2}>
<box flexGrow={1} flexShrink={1} minWidth={0}>
<Switch>
<Match when={status() === "running"}>
<box flexDirection="row" gap={1} flexGrow={1} justifyContent="flex-start">
<box marginLeft={1}>
<Show when={config.animations ?? true} fallback={<text fg={theme.text.subdued}>[]</text>}>
<spinner color={spinnerDef().color} frames={spinnerDef().frames} interval={40} />
</Show>
</box>
<text
fg={store.interrupt > 0 ? theme.background.action.primary.default : theme.text.default}
wrapMode="none"
truncate
flexShrink={1}
>
esc{" "}
<span
style={{
fg: store.interrupt > 0 ? theme.background.action.primary.default : theme.text.subdued,
}}
>
{store.interrupt > 0 ? "again to interrupt" : "interrupt"}
</span>
</text>
</box>
</Match>
<Match when={move.progress()}>
{(progress) => (
<box paddingLeft={3} height={1} minHeight={0} flexShrink={1}>
<Spinner color={theme.hue.accent[500]}>
{progress()}
<span style={{ fg: theme.text.subdued }}>{".".repeat(move.creatingDots())}</span>
</Spinner>
</box>
)}
</Match>
<Match when={move.pendingNew()}>
<box paddingLeft={3} height={1} minHeight={0} flexShrink={1}>
<text fg={theme.hue.accent[500]} wrapMode="none" truncate>
(new working copy)
</text>
</box>
</Match>
<Match when={true}>
<Show when={!props.hint && locationLabel()} fallback={props.hint ?? <text />}>
{(location) => (
<text fg={theme.text.subdued} wrapMode="none" truncate flexGrow={1} flexShrink={1}>
{location()}
</text>
)}
</Show>
</Match>
</Switch>
</box>
<Show when={editorContextLabelState() !== "none" ? editorFileLabelDisplay() : undefined}>
{(file) => (
<text
wrapMode="none"
truncate
flexShrink={1}
fg={editorContextLabelState() === "pending" ? theme.hue.accent[500] : theme.text.subdued}
>
{file()}
</text>
)}
</Show>
<PluginSlot
name="prompt.footer.end"
<Region
name="prompt.footer"
input={{ sessionID: props.sessionID, mode: store.mode }}
mode="replace"
parts={[
{
id: "status",
render: () => (
<box flexGrow={1} flexShrink={1} minWidth={0}>
<Switch>
<Match when={status() === "running"}>
<box flexDirection="row" gap={1} flexGrow={1} justifyContent="flex-start">
<box marginLeft={1}>
<Show
when={config.animations ?? true}
fallback={<text fg={theme.text.subdued}>[]</text>}
>
<spinner color={spinnerDef().color} frames={spinnerDef().frames} interval={40} />
</Show>
</box>
<text
fg={store.interrupt > 0 ? theme.background.action.primary.default : theme.text.default}
wrapMode="none"
truncate
flexShrink={1}
>
esc{" "}
<span
style={{
fg:
store.interrupt > 0
? theme.background.action.primary.default
: theme.text.subdued,
}}
>
{store.interrupt > 0 ? "again to interrupt" : "interrupt"}
</span>
</text>
</box>
</Match>
<Match when={move.progress()}>
{(progress) => (
<box paddingLeft={3} height={1} minHeight={0} flexShrink={1}>
<Spinner color={theme.hue.accent[500]}>
{progress()}
<span style={{ fg: theme.text.subdued }}>{".".repeat(move.creatingDots())}</span>
</Spinner>
</box>
)}
</Match>
<Match when={move.pendingNew()}>
<box paddingLeft={3} height={1} minHeight={0} flexShrink={1}>
<text fg={theme.hue.accent[500]} wrapMode="none" truncate>
(new working copy)
</text>
</box>
</Match>
<Match when={true}>
<Show when={!props.hint && locationLabel()} fallback={props.hint ?? <text />}>
{(location) => (
<text fg={theme.text.subdued} wrapMode="none" truncate flexGrow={1} flexShrink={1}>
{location()}
</text>
)}
</Show>
</Match>
</Switch>
</box>
),
},
{
id: "file",
render: () => (
<Show when={editorContextLabelState() !== "none" ? editorFileLabelDisplay() : undefined}>
{(file) => (
<text
wrapMode="none"
truncate
flexShrink={1}
fg={editorContextLabelState() === "pending" ? theme.hue.accent[500] : theme.text.subdued}
>
{file()}
</text>
)}
</Show>
),
},
]}
/>
</box>
</box>
@@ -62,6 +62,8 @@ function View(props: { context: Plugin.Context }) {
export default Plugin.define({
id: "opencode.home-footer",
setup(context) {
context.ui.slot("home.footer", () => <View context={context} />)
// Root takeover: an external plugin replacing home.footer wins (last-
// enabled) and this builtin shows as suppressed, not silently gone.
context.ui.slot("home.footer", { replace: "home.footer", render: () => <View context={context} /> })
},
})
@@ -85,8 +85,9 @@ export function PromptFooter(props: { context: Plugin.Context; sessionID?: strin
export default Plugin.define({
id: "opencode.prompt-footer",
setup(context) {
context.ui.slot("prompt.footer.end", (props) => (
<PromptFooter context={context} sessionID={props.sessionID} mode={props.mode} />
))
context.ui.slot("prompt.footer", {
at: "end",
render: (props) => <PromptFooter context={context} sessionID={props.sessionID} mode={props.mode} />,
})
},
})
@@ -44,6 +44,9 @@ export function SidebarContext(props: { context: Plugin.Context; sessionID: stri
export default Plugin.define({
id: "internal:sidebar-context",
setup(context) {
context.ui.slot("sidebar.content", (props) => <SidebarContext context={context} sessionID={props.sessionID} />)
context.ui.slot("sidebar.content", {
at: "end",
render: (props) => <SidebarContext context={context} sessionID={props.sessionID} />,
})
},
})
@@ -19,6 +19,6 @@ function View(props: { context: Plugin.Context }) {
export default Plugin.define({
id: "opencode.sidebar-footer",
setup(context) {
context.ui.slot("sidebar.footer", () => <View context={context} />)
context.ui.slot("sidebar.footer", { replace: "sidebar.footer", render: () => <View context={context} /> })
},
})
@@ -73,6 +73,9 @@ function View(props: { context: Plugin.Context; sessionID: string }) {
export default Plugin.define({
id: "internal:sidebar-mcp",
setup(context) {
context.ui.slot("sidebar.content", (props) => <View context={context} sessionID={props.sessionID} />)
context.ui.slot("sidebar.content", {
at: "end",
render: (props) => <View context={context} sessionID={props.sessionID} />,
})
},
})
@@ -1090,6 +1090,6 @@ export default Plugin.define({
name: ROUTE,
render: () => <DiffViewer context={context} />,
})
context.ui.slot("app", () => <Commands context={context} />)
context.ui.slot("app", { at: "end", render: () => <Commands context={context} /> })
},
})
@@ -85,6 +85,6 @@ function Commands(props: { context: Plugin.Context }) {
export default Plugin.define({
id,
setup(context) {
context.ui.slot("app", () => <Commands context={context} />)
context.ui.slot("app", { at: "end", render: () => <Commands context={context} /> })
},
})
@@ -137,6 +137,6 @@ export default Plugin.define({
return <StorybookIndex context={context} />
},
})
context.ui.slot("app", () => <Commands context={context} />)
context.ui.slot("app", { at: "end", render: () => <Commands context={context} /> })
},
})
+47 -8
View File
@@ -1,6 +1,26 @@
import { PluginContextProvider } from "@opencode-ai/plugin/tui"
import type { JSX } from "solid-js"
import type { Context, Dialog, Page, Slot, SlotMap, Toast } from "@opencode-ai/plugin/tui/context"
import type {
Context,
Dialog,
Page,
RegionClaim,
RegionMap,
RegionName,
Toast,
} from "@opencode-ai/plugin/tui/context"
import type { Placement } from "./structure"
// Region inputs erased to their union: the registry stores one render shape
// regardless of which region a claim targets.
export type RegionRender = (input: RegionMap[RegionName]["input"]) => JSX.Element
// A registered claim as stored by the plugin provider's registry.
export type SlotClaim = {
readonly region: RegionName
readonly placement: Placement
readonly render: RegionRender
}
import { infoStringToFiletype, type MarkdownCodeBlockRenderer } from "@opentui/core"
import { useRenderer } from "@opentui/solid"
import { useClient } from "../context/client"
@@ -29,12 +49,14 @@ export type Dispose = () => Promise<void>
export type Registry = {
has(kind: "routes" | "slots" | "markdown", name: string): boolean
set(kind: "routes", name: string, page: Page): void
set(kind: "slots", name: string, slot: Slot): void
set(kind: "slots", name: string, claim: SlotClaim): void
set(kind: "markdown", name: string, render: MarkdownCodeBlockRenderer): void
remove(kind: "routes" | "slots" | "markdown", name: string): void
active(): boolean
}
// The host services a plugin context adapts. Collected once by the provider
// (hooks must run during component setup) and shared by every activation.
export function usePluginHost() {
@@ -70,6 +92,7 @@ export function createPluginContext(input: {
}): Context {
const host = input.host
let context: Context
let claims = 0
// Every dialog and registered render is wrapped so plugin components can
// reach their own context through usePlugin().
const provide = (render: () => JSX.Element) => (
@@ -184,12 +207,28 @@ export function createPluginContext(input: {
return true
},
},
slot(name, render) {
if (input.registry.has("slots", name)) throw new Error(`Slot already registered: ${name}`)
// The registration map erases the slot-specific input type.
input.registry.set("slots", name, ((slotInput: SlotMap[typeof name]) =>
provide(() => render(slotInput))) as Slot)
return registration("slots", name)
slot(name: RegionName, value: RegionClaim) {
// Keys are counter-suffixed so one plugin may claim several places
// in the same region; order within the plugin is registration order.
const key = `${name}#${claims++}`
// Rebuilt field-by-field rather than rest-spread so malformed input
// from untyped plugins normalizes to exactly one placement key — a
// claim carrying two keys would match twice in the resolver.
const placement: Placement =
value.at !== undefined
? { at: value.at }
: value.before !== undefined
? { before: value.before }
: value.after !== undefined
? { after: value.after }
: { replace: value.replace }
input.registry.set("slots", key, {
region: name,
placement,
// The registration map erases the region-specific input type.
render: (slotInput) => provide(() => (value.render as RegionRender)(slotInput)),
})
return registration("slots", key)
},
},
}
+29 -22
View File
@@ -14,15 +14,16 @@ import {
import path from "path"
import { stat } from "fs/promises"
import { fileURLToPath, pathToFileURL } from "url"
import type { Page, Slot, SlotName } from "@opencode-ai/plugin/tui/context"
import { createStore, produce, reconcile as reconcileStore } from "solid-js/store"
import type { Page } from "@opencode-ai/plugin/tui/context"
import type { Claim } from "./structure"
import { createStore, produce, reconcile as reconcileStore, unwrap } from "solid-js/store"
import { isDeepEqual } from "remeda"
import "#runtime-plugin-support"
import { useConfig } from "../config"
import { useTuiLifecycle } from "../context/runtime"
import { errorMessage } from "../util/error"
import { builtins } from "./builtins"
import { createPluginContext, usePluginHost, type Dispose } from "./api"
import { createPluginContext, usePluginHost, type Dispose, type RegionRender, type SlotClaim } from "./api"
import { createSourceWatcher } from "./watch"
import { discoverTuiPlugins, freshSpecifier, localSource } from "./discovery"
@@ -46,9 +47,7 @@ type Value = {
readonly list: () => ReadonlyArray<State>
readonly registered: () => ReadonlyArray<RegisteredPlugin>
readonly route: (id: string, name: string) => Page["render"] | undefined
readonly slot: <Name extends SlotName>(
name: Name,
) => ReadonlyArray<{ readonly id: string; readonly render: Slot<Name> }>
readonly claims: (region: string) => ReadonlyArray<Claim<RegionRender>>
readonly markdown: () => MarkdownOptions["renderNode"]
readonly activate: (id: string) => Promise<boolean>
readonly deactivate: (id: string) => Promise<boolean>
@@ -62,7 +61,7 @@ type Registration = {
options?: Readonly<Record<string, any>>
active: boolean
routes: Record<string, Page>
slots: Record<string, Slot>
slots: Record<string, SlotClaim>
markdown: Record<string, MarkdownCodeBlockRenderer>
cleanups: Dispose[]
}
@@ -119,7 +118,7 @@ export function PluginProvider(props: ParentProps<{ packages: PackageResolver; d
owned,
registry: {
has: (kind, name) => Boolean(store.registrations[id]?.[kind][name]),
set: (kind: "routes" | "slots" | "markdown", name: string, value: Page | Slot | MarkdownCodeBlockRenderer) =>
set: (kind: "routes" | "slots" | "markdown", name: string, value: Page | SlotClaim | MarkdownCodeBlockRenderer) =>
setStore("registrations", id, kind, name, () => value),
remove: (kind, name) =>
setStore(
@@ -387,7 +386,7 @@ export function PluginProvider(props: ParentProps<{ packages: PackageResolver; d
host.toast.show({ variant: "error", title: "Plugin", message: `${state.target}: ${state.error}` })
setStore("states", reconcileStore(states))
}
const slotItems = new WeakMap<Slot, { readonly id: string; readonly render: Slot }>()
const slotItems = new WeakMap<RegionRender, Claim<RegionRender>>()
createEffect(
on(
() => JSON.stringify(config.data.plugins ?? []),
@@ -436,19 +435,27 @@ export function PluginProvider(props: ParentProps<{ packages: PackageResolver; d
active: plugin.active,
})),
route: (id, name) => store.registrations[id]?.routes[name]?.render,
slot: (name) =>
Object.entries(store.registrations).flatMap(([id, registration]) => {
const render = registration.active ? registration.slots[name] : undefined
if (!render) return []
// <For> diffs rows by reference; a stable wrapper per render
// function keeps untouched plugins' slot rows (and their state)
// alive across other plugins' reloads.
const cached = slotItems.get(render)
if (cached) return [cached]
const item = { id, render }
slotItems.set(render, item)
return [item]
}),
// Claims come back in enable order: registration-store key order
// across plugins (generations preserve key positions in place), then
// registration order within one plugin. The resolver's last-wins
// rules depend on it.
claims: (region) =>
Object.entries(store.registrations).flatMap(([id, registration]) =>
Object.entries(registration.active ? registration.slots : {}).flatMap(([key, slot]) => {
if (slot.region !== region) return []
// <For> diffs rows by reference; a stable claim per render
// function keeps untouched plugins' slot rows (and their
// state) alive across other plugins' reloads.
const cached = slotItems.get(slot.render)
if (cached) return [cached]
// Placements are immutable once registered; unwrap the store
// proxy so the resolver's `in` checks hit plain objects
// instead of subscribing tracked scopes to every key probe.
const item = { key: `${id}/${key}`, plugin: id, placement: unwrap(slot.placement), render: slot.render }
slotItems.set(slot.render, item)
return [item]
}),
),
markdown,
// Manual dialog toggles join the same chain as reconciles so a
// toggle mid-reload cannot mix registrations across generations.
+62 -22
View File
@@ -9,7 +9,9 @@ import {
type JSX,
type ParentProps,
} from "solid-js"
import type { SlotMap, SlotName } from "@opencode-ai/plugin/tui/context"
import type { RegionMap, RegionName } from "@opencode-ai/plugin/tui/context"
import type { RegionRender } from "./api"
import { resolveStructure, type Entry, type Part } from "./structure"
import { useRoute } from "../context/route"
import { useToast } from "../ui/toast"
import { errorMessage } from "../util/error"
@@ -64,31 +66,69 @@ export function PluginRoute(props: { readonly fallback: (id: string, name: strin
)
}
export function PluginSlot<Name extends SlotName>(props: {
type HostRender = () => JSX.Element
// One extensible area of the host UI: the host's parts plus every active
// plugin claim, resolved into one ordered child list. Placement policy —
// takeover suppression, last-enabled-wins, missing-anchor degradation —
// lives in resolveStructure; this component only renders the result.
export function Region<Name extends RegionName>(props: {
readonly name: Name
readonly input: SlotMap[Name]
readonly mode: "all" | "replace"
readonly input: RegionMap[Name]["input"]
readonly parts?: ReadonlyArray<Part<HostRender, RegionMap[Name]["part"]>>
}) {
const plugins = usePlugin()
const renderers = createMemo(() => {
const items = plugins.slot(props.name)
if (props.mode === "replace") return items.slice(-1)
return items
})
// resolveStructure builds fresh entry objects each run, but <For> diffs
// rows by reference: cache entries so untouched rows (and the plugin
// state inside them) survive unrelated claim changes. Part entries key on
// their documented-stable id — render-function identity would break if
// the compiled parts prop ever rebuilt its closures. Claim entries key on
// the render function (weakly, so hot-reloaded generations collect).
const partEntries = new Map<string, Entry<HostRender, RegionRender>>()
const claimEntries = new WeakMap<RegionRender, Entry<HostRender, RegionRender>>()
const entries = createMemo(
() =>
resolveStructure<HostRender, RegionRender>({
region: props.name,
parts: props.parts ?? [],
claims: plugins.claims(props.name),
}).entries.map((entry) => {
if (entry.kind === "part") {
const cached = partEntries.get(entry.id)
if (cached) return cached
partEntries.set(entry.id, entry)
return entry
}
const cached = claimEntries.get(entry.claim.render)
if (cached) return cached
claimEntries.set(entry.claim.render, entry)
return entry
}),
[] as ReadonlyArray<Entry<HostRender, RegionRender>>,
// Rows are reference-stable, so an elementwise comparison makes a claim
// change in some other region a complete no-op for this one.
{ equals: (a, b) => a.length === b.length && a.every((entry, index) => entry === b[index]) },
)
return (
<For each={renderers()}>
{(item) => (
<PluginBoundary id={item.id} where={`slot ${props.name}`}>
{
// Component semantics: the render body runs once and untracked, so
// signals and intervals created inside are stable, while props stay
// reactive through the merged getter. A bare item.render(props.input)
// call would run inside the host's tracked scope and re-execute the
// whole body (resetting plugin state) on every tracked read.
createComponent(item.render, mergeProps(() => props.input) as SlotMap[Name])
}
</PluginBoundary>
)}
<For each={entries()}>
{(entry) =>
// A row's entry object is cached, so its kind never changes within
// the row's lifetime — a plain branch is safe here.
entry.kind === "part" ? (
entry.render()
) : (
<PluginBoundary id={entry.claim.plugin} where={`region ${props.name}`}>
{
// Component semantics: the render body runs once and untracked, so
// signals and intervals created inside are stable, while props stay
// reactive through the merged getter. A bare render(props.input)
// call would run inside the host's tracked scope and re-execute the
// whole body (resetting plugin state) on every tracked read.
createComponent(entry.claim.render, mergeProps(() => props.input) as RegionMap[RegionName]["input"])
}
</PluginBoundary>
)
}
</For>
)
}
+125
View File
@@ -0,0 +1,125 @@
// Pure resolution of a region's structure: the host's part tree plus plugin
// claims in, an ordered render list plus suppressions out. No solid, no I/O —
// every policy rule (takeover, hierarchy-beats-timeline, last-enabled-wins,
// missing-anchor degradation) is testable as a data transform.
// Mirrors the public RegionPlacement type (plugin package) with part ids
// erased to strings so the resolver stays independent of the region map.
// Keep the two unions' variants in sync.
export type Placement =
| { readonly at: "start" | "end" }
| { readonly before: string }
| { readonly after: string }
| { readonly replace: string }
// One plugin's registered slot, in enable order within the claims array.
export type Claim<Render> = {
readonly key: string
readonly plugin: string
readonly placement: Placement
readonly render: Render
}
// Host furniture: a leaf renders, a container groups — never both. Part ids
// are the stable anchor vocabulary and must be unique within a region.
export type Part<Render, Id extends string = string> =
| { readonly id: Id; readonly render: Render; readonly parts?: never }
| { readonly id: Id; readonly parts: ReadonlyArray<Part<Render, Id>>; readonly render?: never }
export type Entry<PartRender, ClaimRender> =
| { readonly kind: "part"; readonly id: string; readonly render: PartRender }
| { readonly kind: "claim"; readonly claim: Claim<ClaimRender> }
export function resolveStructure<PartRender extends {}, ClaimRender>(input: {
readonly region: string
readonly parts: ReadonlyArray<Part<PartRender>>
readonly claims: ReadonlyArray<Claim<ClaimRender>>
}): {
readonly entries: ReadonlyArray<Entry<PartRender, ClaimRender>>
readonly suppressed: ReadonlyArray<{ readonly claim: Claim<ClaimRender>; readonly by: Claim<ClaimRender> }>
readonly degraded: ReadonlyArray<Claim<ClaimRender>>
} {
// Root takeover: the region's content is the winning claim, full stop.
// Every other claim — including edge-anchored ones — is suppressed, so a
// theme can never be silently decorated by chips it didn't plan for.
const takeover = input.claims
.filter((claim) => "replace" in claim.placement && claim.placement.replace === input.region)
.at(-1)
if (takeover)
return {
entries: [{ kind: "claim", claim: takeover }],
suppressed: input.claims.filter((claim) => claim !== takeover).map((claim) => ({ claim, by: takeover })),
degraded: [],
}
const known = new Set<string>()
const register = (parts: ReadonlyArray<Part<PartRender>>) => {
for (const part of parts) {
known.add(part.id)
if (part.parts !== undefined) register(part.parts)
}
}
register(input.parts)
const entries: Entry<PartRender, ClaimRender>[] = []
const suppressed: { claim: Claim<ClaimRender>; by: Claim<ClaimRender> }[] = []
// A container takeover orphans everything anchored to (or replacing) the
// parts inside it. Recorded so the host can surface it (plugins dialog,
// in a follow-up) — never silently dropped.
const suppressSubtree = (parts: ReadonlyArray<Part<PartRender>>, by: Claim<ClaimRender>) => {
for (const part of parts) {
for (const claim of input.claims) if (anchor(claim.placement) === part.id) suppressed.push({ claim, by })
if (part.parts !== undefined) suppressSubtree(part.parts, by)
}
}
const walk = (parts: ReadonlyArray<Part<PartRender>>) => {
for (const part of parts) {
for (const claim of input.claims)
if ("before" in claim.placement && claim.placement.before === part.id) entries.push({ kind: "claim", claim })
// Replacing keeps the part's position: before/after anchors on the
// replaced id stay valid, only the content (and subtree) changes hands.
const replacers = input.claims.filter(
(claim) => "replace" in claim.placement && claim.placement.replace === part.id,
)
const winner = replacers.at(-1)
if (winner) {
for (const loser of replacers.slice(0, -1)) suppressed.push({ claim: loser, by: winner })
entries.push({ kind: "claim", claim: winner })
// Hierarchy beats timeline: claims into the subtree lose to the
// container's winner no matter when they were enabled.
if (part.parts !== undefined) suppressSubtree(part.parts, winner)
}
if (!winner && part.parts !== undefined) walk(part.parts)
if (!winner && part.render !== undefined) entries.push({ kind: "part", id: part.id, render: part.render })
for (const claim of input.claims)
if ("after" in claim.placement && claim.placement.after === part.id) entries.push({ kind: "claim", claim })
}
}
for (const claim of input.claims)
if ("at" in claim.placement && claim.placement.at === "start") entries.push({ kind: "claim", claim })
walk(input.parts)
for (const claim of input.claims)
if ("at" in claim.placement && claim.placement.at === "end") entries.push({ kind: "claim", claim })
// A claim aimed at a part the host no longer publishes degrades to the
// region's end rather than vanishing: an anchor rename must never silently
// cost a plugin its render. Degraded claims land after end-edge claims,
// in enable order.
const degraded = input.claims.filter((claim) => {
const id = anchor(claim.placement)
return id !== undefined && !known.has(id)
})
for (const claim of degraded) entries.push({ kind: "claim", claim })
return { entries, suppressed, degraded }
}
function anchor(placement: Placement) {
if ("before" in placement) return placement.before
if ("after" in placement) return placement.after
if ("replace" in placement) return placement.replace
return undefined
}
+2 -2
View File
@@ -9,7 +9,7 @@ import { useEditorContext } from "../context/editor"
import { useData } from "../context/data"
import { useLocation } from "../context/location"
import { FormPrompt } from "./session/form"
import { PluginSlot } from "../plugin/render"
import { Region } from "../plugin/render"
import { useTerminalDimensions } from "@opentui/solid"
let once = false
@@ -91,7 +91,7 @@ export function Home() {
<box flexGrow={1} minHeight={0} />
</box>
<box width="100%" flexShrink={0}>
<PluginSlot name="home.footer" input={{}} mode="replace" />
<Region name="home.footer" input={{}} />
</box>
<Show when={forms()[0]?.id} keyed>
{(_) => {
+2 -2
View File
@@ -82,7 +82,7 @@ import { collapseToolOutput } from "../../util/collapse-tool-output"
import { Keymap, type KeymapCommand } from "../../context/keymap"
import { usePathFormatter } from "../../context/path-format"
import { useLocation } from "../../context/location"
import { PluginSlot } from "../../plugin/render"
import { Region } from "../../plugin/render"
import { usePlugin } from "../../plugin/context"
import {
cacheReuseDrop,
@@ -1072,7 +1072,7 @@ export function Session() {
<Show when={!composer.open && !disabled() && queuedPrompts().length > 0}>
<QueuedPromptDock prompts={queuedPrompts()} onOpen={openQueuedPrompts} />
</Show>
<PluginSlot name="session.composer.top" input={{ sessionID: route.sessionID }} mode="all" />
<Region name="session.composer.top" input={{ sessionID: route.sessionID }} />
<Composer
sessionID={route.sessionID}
open={composer.open || (!!session()?.parentID && forms().length === 0)}
+3 -3
View File
@@ -2,7 +2,7 @@ import { useData } from "../../context/data"
import { createMemo, Show } from "solid-js"
import { useTheme } from "../../context/theme"
import { useConfig } from "../../config"
import { PluginSlot } from "../../plugin/render"
import { Region } from "../../plugin/render"
import { withTimestampedFallback } from "@opencode-ai/util/session-title-fallback"
import { getScrollAcceleration } from "../../util/scroll"
@@ -52,12 +52,12 @@ export function Sidebar(props: { sessionID: string; overlay?: boolean }) {
<text fg={theme.text.subdued}>{session()!.location.workspaceID}</text>
</Show>
</box>
<PluginSlot name="sidebar.content" input={{ sessionID: props.sessionID }} mode="all" />
<Region name="sidebar.content" input={{ sessionID: props.sessionID }} />
</box>
</scrollbox>
<box flexShrink={0} gap={1} paddingTop={1}>
<PluginSlot name="sidebar.footer" input={{}} mode="replace" />
<Region name="sidebar.footer" input={{}} />
</box>
</box>
</Show>
@@ -8,8 +8,8 @@ import type {
KeymapCommand,
KeymapLayer,
Page,
RegionClaim,
Route,
Slot,
} from "@opencode-ai/plugin/tui/context"
import { ThemeProvider, useThemes } from "../../../src/context/theme"
import { ConfigProvider } from "../../../src/config"
@@ -142,7 +142,7 @@ async function renderDiffViewer(vcsDiff: unknown[], height = 20, initialRoute?:
const commands = new Map<string, KeymapCommand>()
let current = initialRoute ?? startRoute
let renderDiff: Page["render"] | undefined
let renderCommands: Slot | undefined
let renderCommands: RegionClaim<"app">["render"] | undefined
let vcsDiffInput: unknown
const config = createTuiResolvedConfig()
const transport = createFetch((url) => {
@@ -199,8 +199,8 @@ async function renderDiffViewer(vcsDiff: unknown[], height = 20, initialRoute?:
},
current: () => current,
},
slot(_name: string, render: Slot) {
renderCommands = render
slot(_name: string, claim: RegionClaim<"app">) {
renderCommands = claim.render
return () => {}
},
},
+5 -2
View File
@@ -140,8 +140,11 @@ import { appendFile } from "node:fs/promises"
export default {
id: "test.crash",
setup: async (context: any) => {
context.ui.slot("home.footer", () => {
throw new Error("boom")
context.ui.slot("home.footer", {
replace: "home.footer",
render: () => {
throw new Error("boom")
},
})
await appendFile(${JSON.stringify(markerCrash)}, "setup\\n")
},
+148
View File
@@ -0,0 +1,148 @@
import { expect, test } from "bun:test"
import type { RegionClaim } from "@opencode-ai/plugin/tui/context"
import { resolveStructure, type Claim, type Part, type Placement } from "../src/plugin/structure"
// Type-level canaries, checked by `bun typecheck`: the placement sum and the
// part union are exclusive — nonsense shapes must not compile.
export const canaries = () => {
const claims: RegionClaim<"prompt.footer">[] = []
claims.push({ at: "end", render: () => null })
// @ts-expect-error two placement keys cannot coexist
claims.push({ at: "end", before: "status", render: () => null })
// @ts-expect-error replace does not combine with an anchor
claims.push({ replace: "status", after: "file", render: () => null })
// @ts-expect-error a part is a leaf or a container, never both
const hybrid: Part<string> = { id: "x", render: "x", parts: [] }
return { claims, hybrid }
}
// The resolver is generic over render types; strings make ordering
// assertions read as layouts.
function claim(plugin: string, placement: Placement, render?: string): Claim<string> {
return { key: `${plugin}/${render ?? JSON.stringify(placement)}`, plugin, placement, render: render ?? plugin }
}
function layout(result: ReturnType<typeof resolveStructure<string, string>>) {
return result.entries.map((entry) => (entry.kind === "part" ? entry.id : entry.claim.render))
}
const footer: Part<string>[] = [
{ id: "status", render: "status" },
{ id: "file", render: "file" },
]
const tree: Part<string>[] = [
{ id: "left", parts: [{ id: "mode", render: "mode" }] },
{
id: "right",
parts: [
{ id: "directory", render: "directory" },
{ id: "model", render: "model" },
{ id: "tokens", render: "tokens" },
],
},
]
test("no claims renders the host parts in order", () => {
const result = resolveStructure<string, string>({ region: "prompt.footer", parts: footer, claims: [] })
expect(layout(result)).toEqual(["status", "file"])
expect(result.suppressed).toEqual([])
expect(result.degraded).toEqual([])
})
test("edge claims land at the region's edges, several in enable order", () => {
const result = resolveStructure({
region: "prompt.footer",
parts: footer,
claims: [
claim("a", { at: "end" }, "a1"),
claim("b", { at: "start" }, "b1"),
claim("a", { at: "end" }, "a2"),
],
})
expect(layout(result)).toEqual(["b1", "status", "file", "a1", "a2"])
})
test("before and after anchor to a part, wherever the host keeps it", () => {
const result = resolveStructure({
region: "prompt.footer",
parts: footer,
claims: [claim("a", { after: "status" }, "chip"), claim("b", { before: "status" }, "vim")],
})
expect(layout(result)).toEqual(["vim", "status", "chip", "file"])
})
test("a missing anchor degrades to the end instead of disappearing", () => {
const result = resolveStructure({
region: "prompt.footer",
parts: footer,
claims: [claim("a", { after: "tokens" }, "chip")],
})
expect(layout(result)).toEqual(["status", "file", "chip"])
expect(result.degraded.map((item) => item.render)).toEqual(["chip"])
})
test("replacing a part swaps content but keeps the position and its anchors", () => {
const result = resolveStructure({
region: "prompt.footer",
parts: footer,
claims: [claim("a", { replace: "status" }, "fancy-status"), claim("b", { after: "status" }, "chip")],
})
expect(layout(result)).toEqual(["fancy-status", "chip", "file"])
expect(result.suppressed).toEqual([])
})
test("same target: the last-enabled claim wins and the loser is recorded", () => {
const first = claim("a", { replace: "status" }, "first")
const second = claim("b", { replace: "status" }, "second")
const result = resolveStructure({ region: "prompt.footer", parts: footer, claims: [first, second] })
expect(layout(result)).toEqual(["second", "file"])
expect(result.suppressed).toEqual([{ claim: first, by: second }])
})
test("container takeover suppresses everything anchored in the subtree", () => {
const takeover = claim("theme", { replace: "right" }, "my-right")
const chip = claim("pr", { after: "model" }, "chip")
const inner = claim("x", { replace: "tokens" }, "cost")
const result = resolveStructure({ region: "prompt.footer", parts: tree, claims: [takeover, chip, inner] })
expect(layout(result)).toEqual(["mode", "my-right"])
expect(result.suppressed).toEqual([
{ claim: chip, by: takeover },
{ claim: inner, by: takeover },
])
})
test("hierarchy beats timeline: an ancestor takeover wins over a later descendant claim", () => {
// The descendant replace was enabled after the container takeover; the
// container still wins because its target contains the descendant's.
const inner = claim("x", { replace: "model" }, "swap-model")
const outer = claim("theme", { replace: "right" }, "my-right")
const result = resolveStructure({ region: "prompt.footer", parts: tree, claims: [outer, inner] })
expect(layout(result)).toEqual(["mode", "my-right"])
expect(result.suppressed).toEqual([{ claim: inner, by: outer }])
})
test("root takeover: nothing original survives, all other claims suppressed", () => {
const theme = claim("powerline", { replace: "prompt.footer" }, "powerline")
const chip = claim("pr", { at: "end" }, "chip")
const result = resolveStructure({ region: "prompt.footer", parts: tree, claims: [chip, theme] })
expect(layout(result)).toEqual(["powerline"])
expect(result.suppressed).toEqual([{ claim: chip, by: theme }])
})
test("root takeover at the same node: last enabled wins", () => {
const first = claim("a", { replace: "home.footer" }, "first")
const second = claim("b", { replace: "home.footer" }, "second")
const result = resolveStructure<string, string>({ region: "home.footer", parts: [], claims: [first, second] })
expect(layout(result)).toEqual(["second"])
expect(result.suppressed).toEqual([{ claim: first, by: second }])
})
test("containers flatten in order and anchors on a container wrap its whole span", () => {
const result = resolveStructure({
region: "prompt.footer",
parts: tree,
claims: [claim("a", { before: "right" }, "divider"), claim("b", { after: "right" }, "clock")],
})
expect(layout(result)).toEqual(["mode", "divider", "directory", "model", "tokens", "clock"])
})
+613 -541
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff