Compare commits

..

2 Commits

Author SHA1 Message Date
Aiden Cline 941b3fc7bb feat(core): clarify restart continuation notice 2026-08-06 22:56:44 -05:00
Aiden Cline a39b20ee36 fix(core): continue sessions after server restart 2026-08-06 22:51:47 -05:00
38 changed files with 360 additions and 603 deletions
@@ -50,7 +50,7 @@ const login = Effect.fn("cli.console.login.run")(function* (timeline: TimelineHo
{
integrationID,
methodID: method.id,
answers: server ? { server } : {},
inputs: server ? { server } : {},
location,
},
{ signal },
@@ -30,11 +30,9 @@ export default Runtime.handler(
)
if (!method)
return yield* Effect.fail(new Error(`MCP server "${input.name}" is not an OAuth-capable remote server`))
if (method.forms)
return yield* Effect.fail(new Error(`MCP server "${input.name}" requires an interactive authentication form`))
const started = yield* Effect.promise(() =>
client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, answers: {}, location }),
client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, inputs: {}, location }),
)
const attempt = started.data
if (attempt.mode === "code")
+2 -3
View File
@@ -23,9 +23,9 @@ import type { Shell } from "@opencode-ai/schema/shell"
import type { DateTime } from "effect"
import type { 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"
@@ -1006,7 +1006,6 @@ export type Endpoint10_3Input = {
readonly integrationID: Integration.ID
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
readonly key: string
readonly answers: Form.Answer
readonly label?: string | undefined
}
export type Endpoint10_3Output = void
@@ -1018,7 +1017,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 answers: Form.Answer
readonly inputs: { readonly [x: string]: string }
readonly label?: string | undefined
}
export type Endpoint10_4Output = { readonly location: Location.Info; readonly data: Integration.Attempt }
@@ -688,7 +688,7 @@ const Endpoint10_3 = (raw: RawClient["server.integration"]) => (input: Endpoint1
raw["integration.connect.key"]({
params: { integrationID: input["integrationID"] },
query: { location: input["location"] },
payload: { key: input["key"], answers: input["answers"], label: input["label"] },
payload: { key: input["key"], label: input["label"] },
}).pipe(Effect.mapError(mapClientError)),
)
@@ -697,7 +697,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"], answers: input["answers"], label: input["label"] },
payload: { methodID: input["methodID"], inputs: input["inputs"], label: input["label"] },
}).pipe(Effect.mapError(mapClientError)),
)
@@ -991,7 +991,7 @@ export function make(options: ClientOptions) {
method: "POST",
path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/key`,
query: { location: input["location"] },
body: { key: input["key"], answers: input["answers"], label: input["label"] },
body: { key: input["key"], label: input["label"] },
successStatus: 204,
declaredStatuses: [400, 401],
empty: true,
@@ -1006,7 +1006,7 @@ export function make(options: ClientOptions) {
method: "POST",
path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/oauth`,
query: { location: input["location"] },
body: { methodID: input["methodID"], answers: input["answers"], label: input["label"] },
body: { methodID: input["methodID"], inputs: input["inputs"], label: input["label"] },
successStatus: 200,
declaredStatuses: [400, 401],
empty: false,
+80 -70
View File
@@ -195,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 }
@@ -291,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 }
@@ -1241,6 +1245,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
@@ -1306,29 +1349,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 = {
@@ -1609,6 +1629,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
@@ -1862,9 +1889,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
@@ -1886,13 +1919,16 @@ export type SessionMessageAssistant = {
retry?: SessionMessageAssistantRetry
}
export type IntegrationOAuthMethod = { id: string; type: "oauth"; label: string; forms?: FormFields }
export type IntegrationKeyMethod = { type: "key"; label?: string; forms?: 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
@@ -1915,12 +1951,6 @@ export type SessionMessageInfo =
| SessionMessageAssistant
| SessionMessageCompaction
export type IntegrationMethod =
| IntegrationOAuthMethod
| IntegrationCommandMethod
| IntegrationKeyMethod
| IntegrationEnvMethod
export type FormCreated = {
id: string
created: number
@@ -1978,13 +2008,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
@@ -3834,21 +3857,8 @@ export type IntegrationConnectKeyInput = {
readonly location?: {
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
}["location"]
readonly key: {
readonly key: string
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> }
readonly label?: string | undefined
}["key"]
readonly answers: {
readonly key: string
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> }
readonly label?: string | undefined
}["answers"]
readonly label?: {
readonly key: string
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> }
readonly label?: string | undefined
}["label"]
readonly key: { readonly key: string; readonly label?: string | undefined }["key"]
readonly label?: { readonly key: string; readonly label?: string | undefined }["label"]
}
export type IntegrationConnectKeyOutput = void
@@ -3860,17 +3870,17 @@ export type IntegrationOauthConnectInput = {
}["location"]
readonly methodID: {
readonly methodID: string
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> }
readonly inputs: { readonly [x: string]: string }
readonly label?: string | undefined
}["methodID"]
readonly answers: {
readonly inputs: {
readonly methodID: string
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> }
readonly inputs: { readonly [x: string]: string }
readonly label?: string | undefined
}["answers"]
}["inputs"]
readonly label?: {
readonly methodID: string
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> }
readonly inputs: { readonly [x: string]: string }
readonly label?: string | undefined
}["label"]
}
-39
View File
@@ -147,45 +147,6 @@ test("experimental wellknown integration add uses the public HTTP contract", asy
expect(await request?.json()).toEqual({ url: "https://example.com" })
})
test("integration connections submit form answers", async () => {
const requests: Request[] = []
const client = OpenCode.make({
baseUrl: "http://localhost:3000",
fetch: async (input, init) => {
const request = input instanceof Request ? input : new Request(input, init)
requests.push(request)
if (request.url.endsWith("/connect/key")) return new Response(null, { status: 204 })
return Response.json({
location: { directory: "/tmp/project", project: { id: "proj_test", directory: "/tmp/project" } },
data: {
attemptID: "con_test",
url: "https://example.com/authorize",
instructions: "Authorize",
mode: "auto",
time: { created: 1, expires: 2 },
},
})
},
})
await client.integration.connect.key({
integrationID: "cloudflare-workers-ai",
key: "secret",
answers: { accountId: "account" },
})
await client.integration.oauth.connect({
integrationID: "github-copilot",
methodID: "device",
answers: { deploymentType: "enterprise", enabled: true, scopes: ["read:user"] },
})
expect(await requests[0].json()).toEqual({ key: "secret", answers: { accountId: "account" } })
expect(await requests[1].json()).toEqual({
methodID: "device",
answers: { deploymentType: "enterprise", enabled: true, scopes: ["read:user"] },
})
})
test("health.stop sends exact replacement identity", async () => {
let request: Request | undefined
const client = OpenCode.make({
+6 -10
View File
@@ -180,14 +180,10 @@ 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, {
id: input.id,
sessionID: entry.form.sessionID,
answer: input.answer,
})
yield* bus.publish(Form.Event.Replied, { id: input.id, sessionID: entry.form.sessionID, answer: input.answer })
yield* Cache.set(forms, input.id, { ...entry, state: next })
yield* Deferred.succeed(entry.deferred, next)
}),
@@ -227,12 +223,12 @@ export const locationLayer = layer
export const node = makeLocationNode({ service: Service, layer, deps: [Bus.node] })
export function validateAnswer(forms: ReadonlyArray<Form.Field>, answer: Answer) {
const fields = new Map(forms.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 forms) {
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 +264,7 @@ function matches(when: Form.When, value: Form.Value | undefined) {
// carry a value matching that field's type, and use a declared option when the field's options
// 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>()
+22 -26
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: (answers: Form.Answer) => Effect.Effect<OAuthAuthorization, unknown, Scope.Scope>
readonly authorize: (inputs: Inputs) => Effect.Effect<OAuthAuthorization, unknown, Scope.Scope>
readonly refresh?: (credential: Credential.OAuth) => Effect.Effect<Credential.OAuth, unknown>
readonly 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 answers: 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 answers: 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 answers: 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}`))
}
if (method.method.forms) {
const invalid =
Form.validateFields(method.method.forms) ?? Form.validateAnswer(method.method.forms, input.answers)
if (invalid) return yield* new AuthorizationError({ cause: new Error(invalid) })
}
const attemptScope = yield* Scope.fork(scope)
const authorization = yield* authorize(method.authorize(input.answers)).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,23 +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}`))
if (method.type === "key" && method.forms) {
const invalid = Form.validateFields(method.forms) ?? Form.validateAnswer(method.forms, input.answers)
if (invalid) return yield* new AuthorizationError({ cause: new Error(invalid) })
}
if (method.type === "key" && !method.forms && Object.keys(input.answers).length > 0) {
return yield* new AuthorizationError({ cause: new Error("Key method does not accept form answers") })
}
yield* credentials.create({
integrationID: input.integrationID,
label: input.label,
value: Credential.Key.make({
type: "key",
key: input.key,
...(Object.keys(input.answers).length > 0 ? { configuration: input.answers } : {}),
}),
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)))
+14 -24
View File
@@ -47,13 +47,17 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
workspaceID: location.workspaceID,
project: location.project,
})
const locationRef = (input?: { readonly location?: { readonly directory?: string; readonly workspace?: string } }) =>
const locationRef = (input?: {
readonly location?: { readonly directory?: string; readonly workspace?: string }
}) =>
input?.location === undefined
? undefined
: Location.Ref.make({
directory: AbsolutePath.make(input.location.directory ?? location.directory),
workspaceID:
input.location.workspace === undefined ? location.workspaceID : Workspace.ID.make(input.location.workspace),
input.location.workspace === undefined
? location.workspaceID
: Workspace.ID.make(input.location.workspace),
})
const isCurrentLocation = (ref: Location.Ref) =>
ref.directory === location.directory && ref.workspaceID === location.workspaceID
@@ -70,12 +74,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
ref && !isCurrentLocation(ref)
? runtime.location.agent
.list(ref)
.pipe(
Effect.map((result) => ({
...result,
data: result.data.find((agent) => agent.id === input.agentID),
})),
)
.pipe(Effect.map((result) => ({ ...result, data: result.data.find((agent) => agent.id === input.agentID) })))
: response(agents.get(input.agentID))
return output.pipe(
Effect.flatMap((result) =>
@@ -163,7 +162,8 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
mutable(draft.model.get(Provider.ID.make(providerID), Model.ID.make(modelID))),
update: (providerID, modelID, update) =>
draft.model.update(Provider.ID.make(providerID), Model.ID.make(modelID), update),
remove: (providerID, modelID) => draft.model.remove(Provider.ID.make(providerID), Model.ID.make(modelID)),
remove: (providerID, modelID) =>
draft.model.remove(Provider.ID.make(providerID), Model.ID.make(modelID)),
default: {
get: draft.model.default.get,
set: (providerID, modelID) =>
@@ -192,7 +192,6 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
integration.connection.key({
integrationID: Integration.ID.make(input.integrationID),
key: input.key,
answers: input.answers,
label: input.label,
}),
},
@@ -202,7 +201,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),
answers: input.answers,
inputs: input.inputs,
label: input.label,
}),
),
@@ -365,14 +364,9 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
const refresh = input.refresh
return {
integrationID: Integration.ID.make(input.integrationID),
method: Schema.decodeUnknownSync(Integration.OAuthMethod)({
id: Integration.MethodID.make(input.method.id),
type: "oauth",
label: input.method.label,
...(input.method.forms === undefined ? {} : { forms: input.method.forms }),
}),
authorize: (answers) =>
input.authorize(answers).pipe(
method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
authorize: (inputs) =>
input.authorize(inputs).pipe(
Effect.map((authorization) => {
if (authorization.mode === "auto") {
return {
@@ -404,11 +398,7 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
}
return {
integrationID: Integration.ID.make(input.integrationID),
method: Schema.decodeUnknownSync(Integration.KeyMethod)({
type: "key",
...(input.method.label === undefined ? {} : { label: input.method.label }),
...(input.method.forms === undefined ? {} : { forms: input.method.forms }),
}),
method: { type: "key", label: input.method.label },
}
}
+7 -13
View File
@@ -179,8 +179,8 @@ export function fromPromise(plugin: Plugin) {
const refresh = input.refresh
draft.method.update({
...input,
authorize: (answers) =>
Effect.promise(() => input.authorize(answers)).pipe(
authorize: (inputs) =>
Effect.promise(() => input.authorize(inputs)).pipe(
Effect.map((authorization) =>
authorization.mode === "auto"
? {
@@ -359,17 +359,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,7 +1,6 @@
import { Effect } from "effect"
import { define } from "@opencode-ai/plugin/effect/plugin"
import { Provider } from "../../provider"
import { configuredSettings } from "./configured"
function selectLanguage(sdk: any, modelID: string, useChat: boolean) {
if (useChat && sdk.chat) return sdk.chat(modelID)
@@ -14,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)
yield* ctx.integration.transform((draft) => {
draft.method.update({
integrationID: Provider.ID.azure,
method: {
type: "key",
label: "API key",
...(resolveResourceName(configured) || typeof configured?.baseURL === "string"
? {}
: {
forms: [
{
type: "string",
key: "resourceName",
title: "Enter Azure Resource Name",
placeholder: "e.g. my-models",
required: true,
},
],
}),
},
})
})
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 { Provider } from "../../provider"
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 complete = typeof configured?.baseURL === "string"
yield* ctx.integration.transform((draft) => {
const forms = [
...(complete || process.env.CLOUDFLARE_ACCOUNT_ID || stringOption(configured ?? {}, "accountId")
? []
: [
{
type: "string" as const,
key: "accountId",
title: "Enter your Cloudflare Account ID",
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
required: true,
},
]),
...(complete ||
process.env.CLOUDFLARE_GATEWAY_ID ||
stringOption(configured ?? {}, "gatewayId") ||
stringOption(configured ?? {}, "gateway")
? []
: [
{
type: "string" as const,
key: "gatewayId",
title: "Enter your Cloudflare AI Gateway ID",
placeholder: "e.g. my-gateway",
required: true,
},
]),
]
draft.method.update({
integrationID: providerID,
method: {
type: "key",
label: "Gateway API token",
...(forms[0] ? { forms: [forms[0], ...forms.slice(1)] } : {}),
},
})
})
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")
@@ -3,36 +3,12 @@ import { App } from "../../app"
import { Effect } from "effect"
import { define } from "@opencode-ai/plugin/effect/plugin"
import { Provider } from "../../provider"
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)
yield* ctx.integration.transform((draft) => {
draft.method.update({
integrationID: providerID,
method: {
type: "key",
label: "API key",
...(typeof configured?.baseURL === "string" || resolveAccountId(configured ?? {})
? {}
: {
forms: [
{
type: "string",
key: "accountId",
title: "Enter your Cloudflare Account ID",
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
required: true,
},
],
}),
},
})
})
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)
})
@@ -46,33 +46,30 @@ const oauth = (app: App.Info) => ({
id: methodID,
type: "oauth",
label: "Login with GitHub Copilot",
forms: [
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: (answers) =>
authorize: (inputs) =>
Effect.gen(function* () {
const enterprise = answers.deploymentType === "enterprise"
const enterpriseUrl = typeof answers.enterpriseUrl === "string" ? answers.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",
@@ -43,9 +43,9 @@ function oauth(http: HttpClient.HttpClient) {
type: "oauth",
label: "OpenCode Console account",
},
authorize: (answers) =>
authorize: (inputs) =>
Effect.gen(function* () {
const server = yield* normalizeServer(typeof answers.server === "string" ? answers.server : defaultServer)
const server = yield* normalizeServer(inputs.server ?? defaultServer)
const device = yield* post(http, `${server}/auth/device/code`, { client_id: clientID }, Device)
const verification = URL.canParse(device.verification_uri_complete)
? new URL(device.verification_uri_complete)
+16 -1
View File
@@ -2,9 +2,14 @@ export * as SessionRestart from "./restart"
import { Context, Effect, Layer } from "effect"
import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
import { Bus } from "../../bus"
import { SessionEvent } from "../event"
import { SessionExecution } from "../execution"
import { SessionStore } from "../store"
const CONTINUE_AFTER_SERVER_RESTART =
"The server restarted while you were working. Continue from where you left off without repeating completed work."
export interface Interface {
/**
* Marks every execution active in this process for resumption by the next server start.
@@ -26,6 +31,7 @@ export const layer = Layer.effect(
Effect.gen(function* () {
const store = yield* SessionStore.Service
const execution = yield* SessionExecution.Service
const bus = yield* Bus.Service
return Service.of({
suspendActiveSessions: Effect.gen(function* () {
yield* store.suspend(yield* execution.active)
@@ -37,6 +43,11 @@ export const layer = Layer.effect(
(sessionID) =>
Effect.gen(function* () {
if (!(yield* store.consumeSuspended(sessionID))) return
yield* bus.publish(SessionEvent.Synthetic, {
sessionID,
text: CONTINUE_AFTER_SERVER_RESTART,
description: "Continuing after restart",
})
// Drain failures are already logged and durably recorded by the execution layer.
yield* Effect.ignore(execution.resume(sessionID))
}),
@@ -47,4 +58,8 @@ export const layer = Layer.effect(
}),
)
export const node = makeGlobalNode({ service: Service, layer, deps: [SessionStore.node, SessionExecution.node] })
export const node = makeGlobalNode({
service: Service,
layer,
deps: [SessionStore.node, SessionExecution.node, Bus.node],
})
+8 -20
View File
@@ -140,11 +140,7 @@ describe("Integration", () => {
yield* integrations.transform((editor) =>
editor.method.update({
integrationID,
method: {
type: "key",
label: "API key",
forms: [{ 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", answers: {} }).pipe(
Effect.flip,
Effect.map((error) => error.cause),
),
).toEqual(expect.objectContaining({ message: "Missing required form field: accountId" }))
yield* integrations.connection.key({
integrationID,
key: "secret",
answers: { 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,7 +243,7 @@ describe("Integration", () => {
const attempt = yield* integrations.oauth.connect({
integrationID,
methodID,
answers: {},
inputs: {},
label: "Personal",
})
expect(attempt.mode).toBe("code")
@@ -301,7 +289,7 @@ describe("Integration", () => {
}),
)
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, answers: {} })
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
expect(
yield* integrations.oauth.complete({ integrationID, attemptID: attempt.attemptID }).pipe(Effect.flip),
).toBeInstanceOf(Integration.CodeRequiredError)
@@ -339,7 +327,7 @@ describe("Integration", () => {
}),
)
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, answers: {} })
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
yield* Effect.yieldNow
expect(yield* integrations.oauth.status({ integrationID, attemptID: attempt.attemptID })).toEqual({
status: "complete",
@@ -377,7 +365,7 @@ describe("Integration", () => {
}),
)
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, answers: {} })
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
const exit = yield* integrations.oauth
.complete({ integrationID, attemptID: attempt.attemptID, code: "1234" })
.pipe(Effect.exit)
@@ -413,7 +401,7 @@ describe("Integration", () => {
}),
)
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, answers: {} })
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
expect(attempt.time.expires - attempt.time.created).toBe(Duration.toMillis(Duration.minutes(10)))
yield* TestClock.adjust(Duration.minutes(10))
yield* Effect.yieldNow
@@ -454,7 +442,7 @@ describe("Integration", () => {
}),
)
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, answers: {} })
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
expect(attempt.time).toEqual({ created, expires: expiresAt })
})
})
+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 },
})
+21 -46
View File
@@ -10,7 +10,7 @@ import { Project } from "@opencode-ai/core/project"
import { Provider } from "@opencode-ai/core/provider"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { WebSearch } from "@opencode-ai/core/websearch"
import { Effect, Schema, Stream } from "effect"
import { Effect, Stream } from "effect"
type Overrides = Partial<Omit<Plugin.Context, "options" | "session">> & {
readonly session?: Partial<Plugin.Context["session"]>
@@ -226,7 +226,8 @@ export function catalogHost(catalog: Catalog.Interface): Plugin.Context["catalog
})),
})
}),
remove: (providerID, modelID) => draft.model.remove(Provider.ID.make(providerID), Model.ID.make(modelID)),
remove: (providerID, modelID) =>
draft.model.remove(Provider.ID.make(providerID), Model.ID.make(modelID)),
default: {
get: () => {
const value = draft.model.default.get()
@@ -285,9 +286,9 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
const refresh = input.refresh
draft.method.update({
integrationID: Integration.ID.make(input.integrationID),
method: oauthMethod(input.method, methodID),
authorize: (answers) =>
input.authorize(answers).pipe(
method: { ...input.method, id: methodID },
authorize: (inputs) =>
input.authorize(inputs).pipe(
Effect.map((authorization) => {
if (authorization.mode === "auto") {
return {
@@ -353,7 +354,7 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
}
draft.method.update({
integrationID: Integration.ID.make(input.integrationID),
method: keyMethod(input.method),
method: input.method,
})
},
remove: (id, item) => draft.method.remove(Integration.ID.make(id), internalMethod(item)),
@@ -401,21 +402,26 @@ function oauthCredential(value: Credential.OAuth) {
return Credential.OAuth.make({ ...value, methodID: Integration.MethodID.make(value.methodID) })
}
function method(value: Integration.Method): IntegrationMethodRegistration["method"] {
function method(value: Integration.Method) {
if (value.type === "env") return { type: value.type, names: [...value.names] }
if (value.type === "key") return { type: value.type, label: value.label, forms: mutable(value.forms) }
if (value.type === "key") return { type: value.type, label: value.label }
if (value.type === "command") return { ...value, command: [...value.command] }
return {
type: value.type,
id: value.id,
label: value.label,
forms: mutable(value.forms),
prompts: value.prompts?.map((prompt) => {
if (prompt.type === "text") return { ...prompt }
return { ...prompt, options: prompt.options.map((option) => ({ ...option })) }
}),
}
}
function internalMethod(value: IntegrationMethodRegistration["method"]): Integration.Method {
function internalMethod(
value: IntegrationMethodRegistration["method"],
): Integration.Method {
if (value.type === "env") return value
if (value.type === "key") return keyMethod(value)
if (value.type === "key") return value
if (value.type === "command") {
return {
...value,
@@ -423,41 +429,10 @@ function internalMethod(value: IntegrationMethodRegistration["method"]): Integra
command: [...value.command],
}
}
return oauthMethod(value, Integration.MethodID.make(value.id))
}
type Mutable<Value> = Value extends readonly [infer Head, ...infer Tail]
? [Mutable<Head>, ...MutableTuple<Tail>]
: Value extends ReadonlyArray<infer Item>
? Array<Mutable<Item>>
: Value extends object
? { -readonly [Key in keyof Value]: Mutable<Value[Key]> }
: Value
type MutableTuple<Value extends ReadonlyArray<unknown>> = {
-readonly [Key in keyof Value]: Mutable<Value[Key]>
}
function mutable<Value>(value: Value): Mutable<Value>
function mutable(value: unknown): unknown {
return structuredClone(value)
}
function keyMethod(value: IntegrationMethodRegistration["method"] & { type: "key" }) {
return Schema.decodeUnknownSync(Integration.KeyMethod)({
type: "key",
...(value.label === undefined ? {} : { label: value.label }),
...(value.forms === undefined ? {} : { forms: value.forms }),
})
}
function oauthMethod(value: IntegrationMethodRegistration["method"] & { type: "oauth" }, id: Integration.MethodID) {
return Schema.decodeUnknownSync(Integration.OAuthMethod)({
id,
type: "oauth",
label: value.label,
...(value.forms === undefined ? {} : { forms: value.forms }),
})
return {
...value,
id: Integration.MethodID.make(value.id),
}
}
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",
forms: [
{
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",
forms: [
expect.objectContaining({ type: "string", key: "accountId", required: true }),
expect.objectContaining({ type: "string", key: "gatewayId", required: true }),
],
})
}),
),
)
it.effect("requires account, gateway, and token before creating the unified SDK", () =>
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",
forms: [
{
type: "string",
key: "accountId",
title: "Enter your Cloudflare Account ID",
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
required: true,
},
],
})
}),
),
)
it.effect("maps account ID to endpoint URL and creates an OpenAI-compatible SDK", () =>
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")),
@@ -57,7 +57,7 @@ describe("GithubCopilotPlugin", () => {
id: Integration.MethodID.make("device"),
type: "oauth",
label: "Login with GitHub Copilot",
forms: expect.any(Array),
prompts: expect.any(Array),
})
}),
)
@@ -128,7 +128,7 @@ describe("OpencodePlugin", () => {
const attempt = yield* integrations.oauth.connect({
integrationID,
methodID: Integration.MethodID.make("device"),
answers: { server: `${server.url.origin}/console///?ignored=true#ignored` },
inputs: { server: `${server.url.origin}/console///?ignored=true#ignored` },
})
expect(attempt.url).toBe(`${server.url.origin}/verify`)
yield* eventually(
@@ -155,7 +155,7 @@ describe("OpencodePlugin", () => {
.connect({
integrationID: Integration.ID.make("opencode"),
methodID: Integration.MethodID.make("device"),
answers: { server: "ftp://console.example.com" },
inputs: { server: "ftp://console.example.com" },
})
.pipe(Effect.flip)
expect(error).toBeInstanceOf(Integration.AuthorizationError)
+2 -6
View File
@@ -67,7 +67,7 @@ describe("built-in web search providers", () => {
name: "Exa",
methods: [{ type: "key" }, { type: "env", names: ["EXA_API_KEY"] }],
})
yield* integrations.connection.key({ integrationID: Integration.ID.make("exa"), key: "exa secret", answers: {} })
yield* integrations.connection.key({ integrationID: Integration.ID.make("exa"), key: "exa secret" })
expect(yield* websearch.query({ query: "effect typescript", providerID: WebSearch.ID.make("exa") })).toEqual(
new WebSearch.Response({
providerID: WebSearch.ID.make("exa"),
@@ -129,11 +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",
answers: {},
})
yield* integrations.connection.key({ integrationID: Integration.ID.make("parallel"), key: "parallel-secret" })
const output = yield* websearch.query({
query: "effect layers",
@@ -13,6 +13,7 @@ import { Session } from "@opencode-ai/core/session"
import { SessionExecution } from "@opencode-ai/core/session/execution"
import { SessionRestart } from "@opencode-ai/core/session/execution/restart"
import { UserInterruptedError } from "@opencode-ai/core/session/error"
import { SessionEvent } from "@opencode-ai/core/session/event"
import { SessionRunner } from "@opencode-ai/core/session/runner"
import { SessionTable } from "@opencode-ai/core/session/sql"
import { SessionStore } from "@opencode-ai/core/session/store"
@@ -127,23 +128,34 @@ describe("SessionExecution lifecycle", () => {
it.effect("resumes each suspended Session at most once", () =>
Effect.gen(function* () {
const database = yield* Database.Service
const bus = yield* Bus.Service
const first = Session.ID.make("ses_resume_first")
const second = Session.ID.make("ses_resume_second")
yield* seedSessions(database, [first, second], { time_suspended: Date.now() })
const drained: string[] = []
const continued: SessionEvent.Synthetic[] = []
const scope = yield* Scope.make()
const context = yield* buildExecution(scope, ({ sessionID }) => Effect.sync(() => void drained.push(sessionID)))
const execution = Context.get(context, SessionExecution.Service)
const restart = Context.get(context, SessionRestart.Service)
yield* bus.project(SessionEvent.Synthetic, (event) => Effect.sync(() => void continued.push(event)))
yield* restart.resumeSuspendedSessions
yield* Effect.forEach([first, second], execution.awaitIdle, { discard: true })
expect(drained.toSorted()).toEqual([first, second])
expect(continued.map((event) => event.data).toSorted((a, b) => a.sessionID.localeCompare(b.sessionID))).toEqual(
[first, second].map((sessionID) => ({
sessionID,
text: "The server restarted while you were working. Continue from where you left off without repeating completed work.",
description: "Continuing after restart",
})),
)
expect(yield* suspensions(database)).toEqual({ [first]: false, [second]: false })
yield* restart.resumeSuspendedSessions
expect(drained.length).toBe(2)
expect(continued.length).toBe(2)
yield* Scope.close(scope, Exit.void)
}),
)
+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],
+2 -2
View File
@@ -8,10 +8,10 @@ import type {
} 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 type IntegrationOAuthAuthorization = {
@@ -31,7 +31,7 @@ export type IntegrationOAuthAuthorization = {
export type IntegrationOAuthMethodRegistration = {
readonly integrationID: string
readonly method: IntegrationOAuthMethod
readonly authorize: (answers: Form.Answer) => Effect.Effect<IntegrationOAuthAuthorization, unknown, Scope.Scope>
readonly authorize: (inputs: IntegrationInputs) => Effect.Effect<IntegrationOAuthAuthorization, unknown, Scope.Scope>
readonly refresh?: (credential: Credential.OAuth) => Effect.Effect<Credential.OAuth, unknown>
readonly label?: (credential: Credential.OAuth) => string | undefined
}
+2 -2
View File
@@ -8,9 +8,9 @@ import type {
} 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 type IntegrationOAuthAuthorization = {
@@ -31,7 +31,7 @@ export type IntegrationOAuthAuthorization = {
export type IntegrationOAuthMethodRegistration = {
readonly integrationID: string
readonly method: IntegrationOAuthMethod
readonly authorize: (answers: Form.Answer) => Promise<IntegrationOAuthAuthorization>
readonly authorize: (inputs: IntegrationInputs) => Promise<IntegrationOAuthAuthorization>
readonly refresh?: (credential: Credential.OAuth) => Promise<Credential.OAuth>
readonly label?: (credential: Credential.OAuth) => string | undefined
}
+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,
answers: 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,
answers: 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,
forms: 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),
forms: 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 -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,
answers: ctx.payload.answers,
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,
answers: ctx.payload.answers,
inputs: ctx.payload.inputs,
label: ctx.payload.label,
}),
),
@@ -5,8 +5,6 @@ import type {
IntegrationInfo,
IntegrationOauthConnectOutput,
IntegrationOAuthMethod,
FormAnswer,
FormFields,
} from "@opencode-ai/client"
import open from "open"
import { createMemo, createSignal, onCleanup, onMount, Show } from "solid-js"
@@ -20,7 +18,6 @@ import { DialogPrompt } from "../ui/dialog-prompt"
import { DialogSelect } from "../ui/dialog-select"
import { Link } from "../ui/link"
import { useToast } from "../ui/toast"
import { FormInput } from "../routes/session/form"
const INTEGRATION_PRIORITY: Record<string, number> = {
opencode: 0,
@@ -184,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") {
@@ -194,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 answers = method.forms
? await formAnswers(dialog, method.label ?? `Connect ${integration.name}`, method.forms)
: {}
if (answers === null) return
dialog.replace(() => (
<KeyMethod integration={integration} method={method} answers={answers} onConnected={onConnected} />
))
}
function CommandStarting(props: {
integration: IntegrationInfo
method: Extract<ConnectMethod, { type: "command" }>
@@ -354,7 +336,6 @@ function CommandView(props: { title: string; output: string; message: string })
function KeyMethod(props: {
integration: IntegrationInfo
method: Extract<ConnectMethod, { type: "key" }>
answers: FormAnswer
onConnected?: OnIntegrationConnected
}) {
const data = useData()
@@ -375,7 +356,6 @@ function KeyMethod(props: {
integrationID: props.integration.id,
location: location(data),
key,
answers: props.answers,
})
.then(() => connected(props.integration, data, dialog, toast, props.onConnected))
.catch((cause) => setError(message(cause)))
@@ -393,17 +373,17 @@ async function beginOAuth(
dialog: ReturnType<typeof useDialog>,
onConnected?: OnIntegrationConnected,
) {
const answers = method.forms ? await formAnswers(dialog, method.label, method.forms) : {}
if (answers === null) return
const inputs = method.prompts?.length ? await promptInputs(dialog, method.prompts) : {}
if (inputs === null) return
dialog.replace(() => (
<OAuthStarting integration={integration} method={method} answers={answers} onConnected={onConnected} />
<OAuthStarting integration={integration} method={method} inputs={inputs} onConnected={onConnected} />
))
}
function OAuthStarting(props: {
integration: IntegrationInfo
method: IntegrationOAuthMethod
answers: FormAnswer
inputs: Record<string, string>
onConnected?: OnIntegrationConnected
}) {
const data = useData()
@@ -417,7 +397,7 @@ function OAuthStarting(props: {
integrationID: props.integration.id,
location: location(data),
methodID: props.method.id,
answers: props.answers,
inputs: props.inputs,
})
.then((result) => {
if (result.data.mode === "code") {
@@ -641,23 +621,49 @@ function OAuthView(props: {
)
}
async function formAnswers(dialog: ReturnType<typeof useDialog>, title: string, forms: FormFields) {
return new Promise<FormAnswer | null>((resolve) => {
dialog.replace(
() => (
<FormInput
form={{ title, fields: forms }}
onSubmit={resolve}
onCancel={() => {
dialog.clear()
resolve(null)
}}
/>
),
() => resolve(null),
)
dialog.setSize("large")
})
async function promptInputs(
dialog: ReturnType<typeof useDialog>,
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.hint,
}))}
onSelect={(option) => resolve(option.value)}
/>
),
() => resolve(null),
)
})
if (value === null) return null
inputs[prompt.key] = value
continue
}
const value = await new Promise<string | null>((resolve) => {
dialog.replace(
() => <DialogPrompt title={prompt.message} placeholder={prompt.placeholder} onConfirm={resolve} />,
() => resolve(null),
)
})
if (value === null) return null
inputs[prompt.key] = value
}
return inputs
}
async function connected(
+43 -47
View File
@@ -4,7 +4,7 @@ import { useRenderer, useTerminalDimensions } from "@opentui/solid"
import type { ScrollBoxRenderable, TextareaRenderable } from "@opentui/core"
import open from "open"
import { useTheme, useThemes } from "../../context/theme"
import type { FormAnswer, FormField, FormValue } from "@opencode-ai/client"
import type { FormField, FormValue } from "@opencode-ai/client"
import type { FormWithLocation } from "../../context/data"
import { useClient } from "../../context/client"
import { useClipboard } from "../../context/clipboard"
@@ -44,27 +44,6 @@ function requestOptions(form: FormWithLocation) {
export function FormPrompt(props: { form: FormWithLocation }) {
const client = useClient()
return (
<FormInput
form={props.form}
onSubmit={(answer) =>
client.api.form.reply(
{ sessionID: props.form.sessionID, formID: props.form.id, answer },
requestOptions(props.form),
)
}
onCancel={() =>
client.api.form.cancel({ sessionID: props.form.sessionID, formID: props.form.id }, requestOptions(props.form))
}
/>
)
}
export function FormInput(props: {
form: Pick<FormWithLocation, "title" | "fields" | "metadata">
onSubmit: (answer: FormAnswer) => Promise<unknown> | void
onCancel: () => Promise<unknown> | void
}) {
const themes = useThemes()
const theme = useTheme("elevated")
const themeMode = themes.mode
@@ -202,14 +181,23 @@ export function FormInput(props: {
}
function replySingle(field: FormAnswerField, value: FormValue) {
Promise.resolve(props.onSubmit({ [field.key]: value })).catch((error: unknown) => {
setStore(
"error",
typeof error === "object" && error !== null && "message" in error && typeof error.message === "string"
? error.message
: "Invalid answer",
client.api.form
.reply(
{
sessionID: props.form.sessionID,
formID: props.form.id,
answer: { [field.key]: value },
},
requestOptions(props.form),
)
})
.catch((error: unknown) => {
setStore(
"error",
typeof error === "object" && error !== null && "message" in error && typeof error.message === "string"
? error.message
: "Invalid answer",
)
})
}
function pick(value: FormValue, customValue?: string) {
@@ -362,7 +350,7 @@ export function FormInput(props: {
}
function cancel() {
void props.onCancel()
void client.api.form.cancel({ sessionID: props.form.sessionID, formID: props.form.id }, requestOptions(props.form))
}
function openExternal() {
@@ -414,23 +402,28 @@ export function FormInput(props: {
setStore("error", formValidateValue(invalid, store.answers[invalid.key]) ?? "Invalid answer")
return
}
Promise.resolve(
props.onSubmit(
Object.fromEntries(
fields().flatMap((field) => {
const value = store.answers[field.key]
return value === undefined ? [] : [[field.key, value] as const]
}),
),
),
).catch((error: unknown) => {
setStore(
"error",
typeof error === "object" && error !== null && "message" in error && typeof error.message === "string"
? error.message
: "Invalid answer",
client.api.form
.reply(
{
sessionID: props.form.sessionID,
formID: props.form.id,
answer: Object.fromEntries(
fields().flatMap((field) => {
const value = store.answers[field.key]
return value === undefined ? [] : [[field.key, value] as const]
}),
),
},
requestOptions(props.form),
)
})
.catch((error: unknown) => {
setStore(
"error",
typeof error === "object" && error !== null && "message" in error && typeof error.message === "string"
? error.message
: "Invalid answer",
)
})
}
onMount(() => onCleanup(keymap.mode.push(FORM_MODE)))
@@ -458,7 +451,10 @@ export function FormInput(props: {
group: "Form",
run: () => {
if (textual()) {
void props.onCancel()
void client.api.form.cancel(
{ sessionID: props.form.sessionID, formID: props.form.id },
requestOptions(props.form),
)
return
}
setStore("editing", false)