From 473e4a960dc7d95e3640f9e4994bc1d8172c7640 Mon Sep 17 00:00:00 2001 From: Shoubhit Dash Date: Mon, 5 Oct 2026 14:43:10 +0530 Subject: [PATCH] refactor(acp): simplify config options and catalog (#52825) --- packages/cli/src/acp/agent.ts | 28 ++- packages/cli/src/acp/catalog.ts | 52 +--- packages/cli/src/acp/config-option.ts | 248 +++++++++----------- packages/cli/src/acp/error.ts | 17 +- packages/cli/src/acp/service.ts | 77 ++---- packages/cli/src/acp/sessions.ts | 16 +- packages/cli/test/acp/config-option.test.ts | 72 ++++-- 7 files changed, 238 insertions(+), 272 deletions(-) diff --git a/packages/cli/src/acp/agent.ts b/packages/cli/src/acp/agent.ts index 94c458b77f2..bb2f7c809fd 100644 --- a/packages/cli/src/acp/agent.ts +++ b/packages/cli/src/acp/agent.ts @@ -20,20 +20,30 @@ import { ACPService } from "./service" import { ACPSessions } from "./sessions" import { ACPTurn } from "./turn" +type HandlerContext = AgentHandlerContext & { readonly requestId?: JsonRpcId } + // Untraced so request spans parent to the caller's span instead of a setup span that has already ended. export const connect = Effect.fnUntraced(function* (client: OpenCodeClient, stream: Stream) { const run = Effect.runPromiseWith(yield* Effect.context()) const catalog = yield* ACPCatalog.make(client) // Requests can dispatch before the service below is built. - const ready = yield* Deferred.make() + const ready = yield* Deferred.make<{ + readonly service: ACPService.Interface + readonly connection: ACPConnection.Interface + }>() const handle = ( call: (service: ACPService.Interface, ctx: AgentHandlerContext) => Effect.Effect, ) => (name: string) => { const handler = Effect.fn(name)( - (ctx: AgentHandlerContext) => - Deferred.await(ready).pipe(Effect.flatMap((service) => call(service, ctx))), + function* (ctx: HandlerContext) { + const connected = yield* Deferred.await(ready) + if (ctx.requestId === undefined) return yield* call(connected.service, ctx) + return yield* call(connected.service, ctx).pipe( + Effect.provideService(ACPConnection.Responded, connected.connection.responded(ctx.requestId)), + ) + }, Effect.catchTags({ ACPCatalogLoadError: (error) => ACPClient.classify(error.cause), ACPCatalogNotReadyError: (error) => @@ -43,12 +53,7 @@ export const connect = Effect.fnUntraced(function* (client: OpenCodeClient, stre Effect.tapCauseIf(Cause.hasDies, (cause) => Effect.logError("ACP request failed", cause)), Effect.catchDefect((defect) => Effect.fail(ACPError.toRequestError(ACPError.fromUnknown(defect)))), ) - return (ctx: AgentHandlerContext & { readonly requestId?: JsonRpcId }) => { - if (ctx.requestId === undefined) return run(handler(ctx)) - return run( - handler(ctx).pipe(Effect.provideService(ACPConnection.Responded, acp.connection.responded(ctx.requestId))), - ) - } + return (ctx: HandlerContext) => run(handler(ctx)) } const app = agent({ name: "opencode" }) const request = ( @@ -117,7 +122,10 @@ export const connect = Effect.fnUntraced(function* (client: OpenCodeClient, stre const sessions = yield* ACPSessions.make({ client, connection, catalog }) const capabilities = yield* Ref.make(ACPCapabilities.parse(undefined)) const turn = yield* ACPTurn.make({ client, connection, sessions, catalog, capabilities }) - yield* Deferred.succeed(ready, ACPService.make({ client, connection, catalog, sessions, capabilities, turn })) + yield* Deferred.succeed(ready, { + service: ACPService.make({ client, connection, catalog, sessions, capabilities, turn }), + connection, + }) return acp.agent }) diff --git a/packages/cli/src/acp/catalog.ts b/packages/cli/src/acp/catalog.ts index ca95eacf71f..b98fb8e4cf8 100644 --- a/packages/cli/src/acp/catalog.ts +++ b/packages/cli/src/acp/catalog.ts @@ -3,15 +3,14 @@ import type { Agent } from "@opencode/schema/agent" import type { Command } from "@opencode/schema/command" import type { Model } from "@opencode/schema/model" import { FSUtil } from "@opencode/util/fs-util" -import { Cause, Deferred, Effect, Exit, Schedule, Schema, Semaphore, Stream, SubscriptionRef } from "effect" -import type { ConfigOptionProvider } from "./config-option" +import { Cause, Deferred, Effect, Exit, Schedule, Semaphore, Stream, SubscriptionRef } from "effect" +import { ACPError } from "./error" export const builtinCommands = new Map([ ["compact", { description: "Compact the session", start: "compaction" as const }], ]) export type Catalog = { - readonly providers: ConfigOptionProvider[] readonly models: ReadonlyArray readonly defaultModel: Model.Ref readonly modes: ReadonlyArray<{ id: Agent.ID; name: string; description?: string }> @@ -19,24 +18,14 @@ export type Catalog = { readonly commands: ReadonlyArray } -class NotReadyError extends Schema.TaggedError()("ACPCatalogNotReadyError", { - reason: Schema.Literals(["models", "agents"]), -}) { - override get message() { - return this.reason === "models" ? "No models are available" : "No primary agents are available" - } +export function findModel(models: ReadonlyArray, ref: Model.Ref) { + return models.find((model) => model.providerID === ref.providerID && model.id === ref.id) } -class LoadError extends Schema.TaggedError()("ACPCatalogLoadError", { - cause: Schema.Defect(), -}) {} - -export type Error = NotReadyError | LoadError - export interface Interface { - readonly get: (cwd: string) => Effect.Effect - readonly reload: (cwd: string) => Effect.Effect - readonly changes: (cwd: string) => Stream.Stream + readonly get: (cwd: string) => Effect.Effect + readonly reload: (cwd: string) => Effect.Effect + readonly changes: (cwd: string) => Stream.Stream } type Entry = { @@ -51,7 +40,7 @@ const reloadOn = new Set(["model.updated", "agent.updated export const make = Effect.fnUntraced(function* (client: OpenCodeClient) { const scope = yield* Effect.scope - const entries = new Map>() + const entries = new Map>() const connected = yield* Deferred.make() // Requests queued behind a running load share the next one. @@ -111,7 +100,7 @@ export const make = Effect.fnUntraced(function* (client: OpenCodeClient) { const key = FSUtil.resolve(cwd) const cached = entries.get(key) if (cached) return Deferred.await(cached) - const loading = Deferred.makeUnsafe() + const loading = Deferred.makeUnsafe() entries.set(key, loading) return create(cwd).pipe( Effect.onExit((exit) => { @@ -155,20 +144,17 @@ const read = Effect.fnUntraced(function* (client: OpenCodeClient, cwd: string) { client.command.list({ location }), ], { concurrency: "unbounded" }, - ).pipe(Effect.mapError((cause) => new LoadError({ cause }))) + ).pipe(Effect.mapError((cause) => new ACPError.CatalogLoadError({ cause }))) const models = modelResult.data.filter((model) => model.enabled) const preferred = defaultResult.data // The parallel default read can name a model missing from this list. - const defaultModel = preferred - ? models.find((model) => model.providerID === preferred.providerID && model.id === preferred.id) - : models[0] - if (!defaultModel) return yield* new NotReadyError({ reason: "models" }) + const defaultModel = preferred ? findModel(models, preferred) : models[0] + if (!defaultModel) return yield* new ACPError.CatalogNotReadyError({ reason: "models" }) const agents = agentResult.data.filter((agent) => agent.mode !== "subagent" && !agent.hidden) // Core lists its resolved default agent first, the same one a new session runs. const defaultAgent = agents[0] - if (!defaultAgent) return yield* new NotReadyError({ reason: "agents" }) + if (!defaultAgent) return yield* new ACPError.CatalogNotReadyError({ reason: "agents" }) return { - providers: providers(models), models, defaultModel: { providerID: defaultModel.providerID, @@ -181,16 +167,4 @@ const read = Effect.fnUntraced(function* (client: OpenCodeClient, cwd: string) { } satisfies Catalog }) -function providers(models: ReadonlyArray) { - return Array.from(new Set(models.map((model) => model.providerID))) - .toSorted() - .map((providerID) => ({ - id: providerID, - name: providerID, - models: models - .filter((model) => model.providerID === providerID) - .map((model) => ({ id: model.id, name: model.name, variants: model.variants.map((variant) => variant.id) })), - })) -} - export * as ACPCatalog from "./catalog" diff --git a/packages/cli/src/acp/config-option.ts b/packages/cli/src/acp/config-option.ts index 565d570dd97..b930a3d5691 100644 --- a/packages/cli/src/acp/config-option.ts +++ b/packages/cli/src/acp/config-option.ts @@ -1,51 +1,70 @@ import type { SessionConfigOption } from "@agentclientprotocol/sdk" import type { Agent } from "@opencode/schema/agent" -import type { Model } from "@opencode/schema/model" -import { builtinCommands, type Catalog } from "./catalog" +import { Model } from "@opencode/schema/model" +import { Provider } from "@opencode/schema/provider" +import { Effect, Order } from "effect" +import { builtinCommands, findModel, type Catalog } from "./catalog" +import { ACPError } from "./error" -export const DEFAULT_VARIANT_VALUE = "default" - -type ConfigOptionModel = { - id: string - name: string - variants?: ReadonlyArray -} - -export type ConfigOptionProvider = { - id: string - name: string - models: ReadonlyArray -} - -type ConfigOptionMode = { - id: string - name: string - description?: string -} - -export type ModelSelection = { - model: { providerID: string; modelID: string } - variant?: string -} +const DEFAULT_VARIANT_VALUE = "default" export type Selection = { readonly model?: Model.Ref readonly modeID?: Agent.ID } +export type Change = { readonly model: Model.Ref } | { readonly modeID: Agent.ID } + export function currentModel(catalog: Catalog, selection: Selection) { return selection.model ?? catalog.defaultModel } -export function configOptions(catalog: Catalog, selection: Selection) { +export function configOptions(catalog: Catalog, selection: Selection): SessionConfigOption[] { const model = currentModel(catalog, selection) - return buildConfigOptions({ - providers: catalog.providers, - currentModel: { providerID: model.providerID, modelID: model.id }, - currentVariant: model.variant, - modes: catalog.modes, - currentModeId: selection.modeID ?? catalog.defaultModeID, - }) + const variants = findModel(catalog.models, model)?.variants.map((variant) => variant.id) ?? [] + return [ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: `${model.providerID}/${model.id}`, + options: catalog.models + .toSorted((a, b) => Order.String(a.providerID, b.providerID) || a.name.localeCompare(b.name)) + .map((item) => ({ value: `${item.providerID}/${item.id}`, name: `${item.providerID}/${item.name}` })), + }, + ...(variants.length > 0 + ? [ + { + id: "effort", + name: "Effort", + description: "Available effort levels for this model", + category: "thought_level", + type: "select", + currentValue: selectVariant(model.variant, variants), + options: [...new Set([...variants, DEFAULT_VARIANT_VALUE])].map((variant) => ({ + value: variant, + name: variant + .split(/[_-]/) + .map((part) => (part ? part.charAt(0).toUpperCase() + part.slice(1) : part)) + .join(" "), + })), + } satisfies SessionConfigOption, + ] + : []), + { + id: "mode", + name: "Session Mode", + category: "mode", + type: "select", + currentValue: selection.modeID ?? catalog.defaultModeID, + options: catalog.modes.map((mode) => ({ + value: mode.id, + name: mode.name, + ...(mode.description ? { description: mode.description } : {}), + })), + }, + ] } export function availableCommands(catalog: Catalog) { @@ -55,111 +74,72 @@ export function availableCommands(catalog: Catalog) { ] } -export function buildConfigOptions(input: { - providers: readonly ConfigOptionProvider[] - currentModel: ModelSelection["model"] - currentVariant?: string - modes?: readonly ConfigOptionMode[] - currentModeId?: string -}): SessionConfigOption[] { - const variants = - input.providers - .find((provider) => provider.id === input.currentModel.providerID) - ?.models.find((model) => model.id === input.currentModel.modelID)?.variants ?? [] - const effort = - variants.length > 0 ? buildEffortSelectOption({ variants, currentVariant: input.currentVariant }) : undefined - return [ - buildModelSelectOption({ providers: input.providers, currentModel: input.currentModel }), - ...(effort ? [effort] : []), - ...(input.modes && input.currentModeId - ? [buildModeSelectOption({ modes: input.modes, currentModeId: input.currentModeId })] - : []), - ] +export const resolveChange = Effect.fnUntraced(function* ( + catalog: Catalog, + selection: Selection, + configId: string, + value: string, +) { + const current = currentModel(catalog, selection) + switch (configId) { + case "model": + return { model: yield* requireModel(catalog, value, current) } + case "effort": { + const model = findModel(catalog.models, current) + if (!model || (value !== DEFAULT_VARIANT_VALUE && !model.variants.some((variant) => variant.id === value))) + return yield* new ACPError.InvalidEffortError({ effort: value }) + return { model: { ...current, variant: Model.VariantID.make(value) } } + } + case "mode": { + const mode = catalog.modes.find((item) => item.id === value) + if (!mode) return yield* new ACPError.InvalidModeError({ mode: value }) + return { modeID: mode.id } + } + default: + return yield* new ACPError.InvalidConfigOptionError({ configId }) + } +}) + +export function parseModelSelection(value: string, models: ReadonlyArray): Model.Ref { + const providerID = models + .map((model) => model.providerID) + .toSorted() + .find((id) => value.startsWith(`${id}/`)) + if (!providerID) { + const separator = value.indexOf("/") + if (separator === -1) return { providerID: Provider.ID.make(value), id: Model.ID.make("") } + return { providerID: Provider.ID.make(value.slice(0, separator)), id: Model.ID.make(value.slice(separator + 1)) } + } + const id = Model.ID.make(value.slice(providerID.length + 1)) + if (findModel(models, { providerID, id })) return { providerID, id } + const separator = id.lastIndexOf("/") + const baseID = Model.ID.make(separator === -1 ? id : id.slice(0, separator)) + const variant = separator === -1 ? undefined : id.slice(separator + 1) + const model = findModel(models, { providerID, id: baseID }) + if (model && variant && model.variants.some((item) => item.id === variant)) + return { providerID, id: baseID, variant: Model.VariantID.make(variant) } + return { providerID, id } } -export function buildModelSelectOption(input: { - providers: readonly ConfigOptionProvider[] - currentModel: ModelSelection["model"] -}): SessionConfigOption { - return { - id: "model", - name: "Model", - category: "model", - type: "select", - currentValue: `${input.currentModel.providerID}/${input.currentModel.modelID}`, - options: input.providers.flatMap((provider) => - provider.models - .toSorted((a, b) => a.name.localeCompare(b.name)) - .map((model) => ({ value: `${provider.id}/${model.id}`, name: `${provider.name}/${model.name}` })), - ), - } -} - -export function buildEffortSelectOption(input: { - variants: readonly string[] - currentVariant?: string -}): SessionConfigOption { - return { - id: "effort", - name: "Effort", - description: "Available effort levels for this model", - category: "thought_level", - type: "select", - currentValue: selectVariant(input.currentVariant, input.variants), - options: [...new Set([...input.variants, DEFAULT_VARIANT_VALUE])].map((variant) => ({ - value: variant, - name: formatVariantName(variant), - })), - } -} - -export function buildModeSelectOption(input: { - modes: readonly ConfigOptionMode[] - currentModeId: string -}): SessionConfigOption { - return { - id: "mode", - name: "Session Mode", - category: "mode", - type: "select", - currentValue: input.currentModeId, - options: input.modes.map((mode) => ({ - value: mode.id, - name: mode.name, - ...(mode.description ? { description: mode.description } : {}), - })), - } -} - -export function parseModelSelection(modelId: string, providers: readonly ConfigOptionProvider[]): ModelSelection { - const provider = providers.find((item) => modelId.startsWith(`${item.id}/`)) - if (!provider) { - const separator = modelId.indexOf("/") - if (separator === -1) return { model: { providerID: modelId, modelID: "" } } - return { model: { providerID: modelId.slice(0, separator), modelID: modelId.slice(separator + 1) } } - } - const modelID = modelId.slice(provider.id.length + 1) - if (provider.models.some((model) => model.id === modelID)) return { model: { providerID: provider.id, modelID } } - const separator = modelID.lastIndexOf("/") - const baseModelID = separator === -1 ? modelID : modelID.slice(0, separator) - const variant = separator === -1 ? undefined : modelID.slice(separator + 1) - const model = provider.models.find((item) => item.id === baseModelID) - if (model && variant && model.variants?.includes(variant)) { - return { model: { providerID: provider.id, modelID: baseModelID }, variant } - } - return { model: { providerID: provider.id, modelID } } -} - -export function formatVariantName(variant: string) { - return variant - .split(/[_-]/) - .map((part) => (part ? part.charAt(0).toUpperCase() + part.slice(1) : part)) - .join(" ") -} +const requireModel = Effect.fnUntraced(function* (catalog: Catalog, value: string, current: Model.Ref) { + const selected = parseModelSelection(value, catalog.models) + const model = findModel(catalog.models, selected) + if (!model) return yield* new ACPError.InvalidModelError({ providerId: selected.providerID, modelId: value }) + const selectedVariant = model.variants.find((variant) => variant.id === selected.variant) + if (selected.variant && !selectedVariant) return yield* new ACPError.InvalidEffortError({ effort: selected.variant }) + const variant = + selectedVariant?.id ?? + (current.providerID === model.providerID && + current.id === model.id && + (current.variant === DEFAULT_VARIANT_VALUE || model.variants.some((variant) => variant.id === current.variant)) + ? current.variant + : undefined) + return { providerID: model.providerID, id: model.id, variant } satisfies Model.Ref +}) function selectVariant(variant: string | undefined, variants: readonly string[]) { if (!variant || variant === DEFAULT_VARIANT_VALUE) return DEFAULT_VARIANT_VALUE - if (variant && variants.includes(variant)) return variant + if (variants.includes(variant)) return variant if (variants.includes(DEFAULT_VARIANT_VALUE)) return DEFAULT_VARIANT_VALUE return variants[0] ?? DEFAULT_VARIANT_VALUE } diff --git a/packages/cli/src/acp/error.ts b/packages/cli/src/acp/error.ts index 2c22b4b75e2..ef26f0ef57c 100644 --- a/packages/cli/src/acp/error.ts +++ b/packages/cli/src/acp/error.ts @@ -1,6 +1,5 @@ import { RequestError } from "@agentclientprotocol/sdk" import { Schema } from "effect" -import type { ACPCatalog } from "./catalog" export class SessionNotFoundError extends Schema.TaggedError()("ACPSessionNotFoundError", { sessionId: Schema.String, @@ -56,6 +55,20 @@ export class ServerUnavailableError extends Schema.TaggedError()("ACPCatalogNotReadyError", { + reason: Schema.Literals(["models", "agents"]), +}) { + override get message() { + return this.reason === "models" ? "No models are available" : "No primary agents are available" + } +} + +export class CatalogLoadError extends Schema.TaggedError()("ACPCatalogLoadError", { + cause: Schema.Defect(), +}) {} + +export type CatalogError = CatalogNotReadyError | CatalogLoadError + export type Error = | SessionNotFoundError | SessionDirectoryMismatchError @@ -70,7 +83,7 @@ export type Error = | ServiceFailureError | ServerUnavailableError -export type Failure = Error | RequestError | ACPCatalog.Error +export type Failure = Error | RequestError | CatalogError export function toRequestError(error: Error): RequestError { switch (error._tag) { diff --git a/packages/cli/src/acp/service.ts b/packages/cli/src/acp/service.ts index 9c569980cc4..a001fdb1c44 100644 --- a/packages/cli/src/acp/service.ts +++ b/packages/cli/src/acp/service.ts @@ -1,6 +1,5 @@ import type { OpenCodeClient } from "@opencode/client/effect" import { SessionsCursor } from "@opencode/protocol/groups/session" -import { Model } from "@opencode/schema/model" import { AbsolutePath } from "@opencode/schema/schema" import { FSUtil } from "@opencode/util/fs-util" import { DateTime, Effect, Ref, Schema } from "effect" @@ -36,9 +35,9 @@ import type { } from "@agentclientprotocol/sdk" import { OPENCODE_VERSION } from "../version" import { ACPCapabilities, type Capabilities } from "./capabilities" -import type { ACPCatalog, Catalog } from "./catalog" +import type { ACPCatalog } from "./catalog" import { ACPClient } from "./client" -import { configOptions, currentModel, DEFAULT_VARIANT_VALUE, parseModelSelection } from "./config-option" +import { configOptions, resolveChange } from "./config-option" import type { ACPConnection } from "./connection" import { ACPDirectories } from "./directories" import { ACPError } from "./error" @@ -78,42 +77,21 @@ export function make(input: { return configOptions(yield* input.catalog.get(attached.cwd), yield* Ref.get(attached.selection)) }) - const withReload = (attached: Attached, select: Effect.Effect) => { - const retry = () => input.catalog.reload(attached.cwd).pipe(Effect.andThen(select)) - return select.pipe( + const withReload = (attached: Attached, attempt: Effect.Effect) => { + const retry = () => input.catalog.reload(attached.cwd).pipe(Effect.andThen(attempt)) + return attempt.pipe( Effect.catchTags({ ACPInvalidModelError: retry, ACPInvalidModeError: retry, ACPInvalidEffortError: retry }), ) } - const selectOption = Effect.fnUntraced(function* (attached: Attached, configId: string, value: string) { - const catalog = yield* input.catalog.get(attached.cwd) - const current = currentModel(catalog, yield* Ref.get(attached.selection)) - switch (configId) { - case "model": - return yield* selectModel(attached, yield* requireModel(catalog, value, current)) - case "effort": - return yield* selectModel(attached, yield* requireEffort(catalog, value, current)) - case "mode": - return yield* selectMode(attached, value) - default: - return yield* new ACPError.InvalidConfigOptionError({ configId }) - } - }) - - // Update selection before switching so the echoed event is a no-op. - const selectModel = Effect.fnUntraced(function* (attached: Attached, model: Model.Ref) { - yield* Ref.update(attached.selection, (selection) => ({ ...selection, model })) - yield* input.client.session.switchModel({ sessionID: attached.id, model }).pipe(Effect.catch(ACPClient.classify)) - }) - - const selectMode = Effect.fnUntraced(function* (attached: Attached, modeID: string) { - const catalog = yield* input.catalog.get(attached.cwd) - const mode = catalog.modes.find((item) => item.id === modeID) - if (!mode) return yield* new ACPError.InvalidModeError({ mode: modeID }) - yield* Ref.update(attached.selection, (selection) => ({ ...selection, modeID: mode.id })) - yield* input.client.session - .switchAgent({ sessionID: attached.id, agent: mode.id }) - .pipe(Effect.catch(ACPClient.classify)) + const select = Effect.fnUntraced(function* (attached: Attached, configId: string, value: string) { + const change = yield* resolveChange( + yield* input.catalog.get(attached.cwd), + yield* Ref.get(attached.selection), + configId, + value, + ) + yield* input.sessions.select(attached, change) }) const getSession = Effect.fnUntraced(function* (sessionId: string, cwd: string) { @@ -245,12 +223,12 @@ export function make(input: { const attached = yield* input.sessions.require(params.sessionId) const value = params.value if (typeof value !== "string") return yield* new ACPError.InvalidConfigOptionError({ configId: params.configId }) - yield* withReload(attached, selectOption(attached, params.configId, value)) + yield* withReload(attached, select(attached, params.configId, value)) return { configOptions: yield* currentOptions(attached) } }), setSessionMode: Effect.fnUntraced(function* (params) { const attached = yield* input.sessions.require(params.sessionId) - yield* withReload(attached, selectMode(attached, params.modeId)) + yield* withReload(attached, select(attached, "mode", params.modeId)) return {} }), prompt: input.turn.prompt, @@ -270,29 +248,4 @@ const supportedMcpServers = Effect.fnUntraced(function* (servers: readonly McpSe return supported }) -const requireModel = Effect.fnUntraced(function* (catalog: Catalog, modelID: string, current: Model.Ref) { - const selected = parseModelSelection(modelID, catalog.providers) - const model = catalog.models.find( - (item) => item.providerID === selected.model.providerID && item.id === selected.model.modelID, - ) - if (!model) return yield* new ACPError.InvalidModelError({ providerId: selected.model.providerID, modelId: modelID }) - const selectedVariant = model.variants.find((variant) => variant.id === selected.variant) - if (selected.variant && !selectedVariant) return yield* new ACPError.InvalidEffortError({ effort: selected.variant }) - const variant = - selectedVariant?.id ?? - (current.providerID === model.providerID && - current.id === model.id && - (current.variant === DEFAULT_VARIANT_VALUE || model.variants.some((variant) => variant.id === current.variant)) - ? current.variant - : undefined) - return { providerID: model.providerID, id: model.id, variant } satisfies Model.Ref -}) - -const requireEffort = Effect.fnUntraced(function* (catalog: Catalog, effort: string, current: Model.Ref) { - const model = catalog.models.find((item) => item.providerID === current.providerID && item.id === current.id) - if (!model || (effort !== DEFAULT_VARIANT_VALUE && !model.variants.some((variant) => variant.id === effort))) - return yield* new ACPError.InvalidEffortError({ effort }) - return { ...current, variant: Model.VariantID.make(effort) } satisfies Model.Ref -}) - export * as ACPService from "./service" diff --git a/packages/cli/src/acp/sessions.ts b/packages/cli/src/acp/sessions.ts index d488624f690..1384893e597 100644 --- a/packages/cli/src/acp/sessions.ts +++ b/packages/cli/src/acp/sessions.ts @@ -6,7 +6,7 @@ import type { Session } from "@opencode/schema/session" import { Cause, Deferred, Effect, Exit, Queue, Ref, Scope, Stream } from "effect" import type { ACPCatalog, Catalog } from "./catalog" import { ACPClient } from "./client" -import { availableCommands, configOptions, type Selection } from "./config-option" +import { availableCommands, configOptions, type Change, type Selection } from "./config-option" import { ACPConnection } from "./connection" import { ACPError } from "./error" @@ -28,12 +28,13 @@ export interface Interface { readonly release: (attached: Attached) => Effect.Effect readonly require: (sessionID: string) => Effect.Effect readonly fork: (attached: Attached, effect: Effect.Effect) => Effect.Effect + readonly select: (attached: Attached, change: Change) => Effect.Effect } type Entry = { readonly attached: Attached readonly scope: Scope.Closeable - readonly selected: Queue.Queue + readonly selected: Queue.Queue } type SelectedEvent = Extract @@ -130,7 +131,7 @@ export const make = Effect.fnUntraced(function* (input: { selection: yield* Ref.make({ model: session.model, modeID: session.agent }), }, scope: Scope.forkUnsafe(scope), - selected: yield* Queue.unbounded(), + selected: yield* Queue.unbounded(), } // Swap synchronously so concurrent attaches of one ID cannot both keep a scope. const replaced = sessions.get(session.id) @@ -179,6 +180,15 @@ export const make = Effect.fnUntraced(function* (input: { if (entry?.attached !== attached) return yield* new ACPError.SessionNotFoundError({ sessionId: attached.id }) yield* Effect.forkIn(effect, entry.scope, { startImmediately: true }) }), + // Update selection before switching so the echoed event is a no-op. + select: Effect.fnUntraced(function* (attached, change) { + yield* Ref.update(attached.selection, (selection) => ({ ...selection, ...change })) + yield* ( + "model" in change + ? input.client.session.switchModel({ sessionID: attached.id, model: change.model }) + : input.client.session.switchAgent({ sessionID: attached.id, agent: change.modeID }) + ).pipe(Effect.catch(ACPClient.classify)) + }), } satisfies Interface }) diff --git a/packages/cli/test/acp/config-option.test.ts b/packages/cli/test/acp/config-option.test.ts index 0cee7e049bb..fd8aef163b6 100644 --- a/packages/cli/test/acp/config-option.test.ts +++ b/packages/cli/test/acp/config-option.test.ts @@ -1,21 +1,41 @@ import { describe, expect, test } from "bun:test" -import { buildEffortSelectOption, parseModelSelection, type ConfigOptionProvider } from "../../src/acp/config-option" +import { Agent } from "@opencode/schema/agent" +import { Model } from "@opencode/schema/model" +import { Provider } from "@opencode/schema/provider" +import type { Catalog } from "../../src/acp/catalog" +import { configOptions, parseModelSelection } from "../../src/acp/config-option" -const providers: ConfigOptionProvider[] = [ - { - id: "anthropic", - name: "Anthropic", - models: [ - { id: "claude/sonnet-4", name: "Claude Sonnet 4", variants: ["default", "high", "very-high"] }, - { id: "claude-haiku", name: "Claude Haiku" }, - ], - }, - { id: "openai", name: "OpenAI", models: [{ id: "gpt-5", name: "GPT-5", variants: ["minimal", "low"] }] }, -] +const model = (providerID: string, id: string, name: string, variants: string[] = []) => ({ + ...Model.Info.default(Provider.ID.make(providerID), Model.ID.make(id)), + name, + variants: variants.map((variant) => ({ id: Model.VariantID.make(variant) })), +}) + +const catalog: Catalog = { + models: [ + model("anthropic", "claude/sonnet-4", "Claude Sonnet 4", ["default", "high", "very-high"]), + model("anthropic", "claude-haiku", "Claude Haiku"), + model("openai", "gpt-5", "GPT-5", ["minimal", "low"]), + model("test", "effort", "Effort", ["low", "default", "high"]), + ], + defaultModel: { providerID: Provider.ID.make("openai"), id: Model.ID.make("gpt-5") }, + modes: [{ id: Agent.ID.make("build"), name: "Build" }], + defaultModeID: Agent.ID.make("build"), + commands: [], +} + +const effortOption = (providerID: string, id: string) => + configOptions(catalog, { + model: { + providerID: Provider.ID.make(providerID), + id: Model.ID.make(id), + variant: Model.VariantID.make("missing"), + }, + }).find((option) => option.id === "effort") describe("acp config options", () => { test("builds effort option from variants and falls back to default when current variant is invalid", () => { - expect(buildEffortSelectOption({ variants: ["low", "default", "high"], currentVariant: "missing" })).toEqual({ + expect(effortOption("test", "effort")).toEqual({ id: "effort", name: "Effort", description: "Available effort levels for this model", @@ -28,21 +48,29 @@ describe("acp config options", () => { { value: "high", name: "High" }, ], }) - expect(buildEffortSelectOption({ variants: ["minimal", "low"], currentVariant: "missing" }).currentValue).toBe( - "minimal", - ) + expect(effortOption("openai", "gpt-5")?.currentValue).toBe("minimal") }) test.each([ - ["openai/gpt-5", { model: { providerID: "openai", modelID: "gpt-5" } }], - ["openai/gpt-5/low", { model: { providerID: "openai", modelID: "gpt-5" }, variant: "low" }], - ["anthropic/claude/sonnet-4", { model: { providerID: "anthropic", modelID: "claude/sonnet-4" } }], + ["openai/gpt-5", { providerID: Provider.ID.openai, id: Model.ID.make("gpt-5") }], + [ + "openai/gpt-5/low", + { providerID: Provider.ID.openai, id: Model.ID.make("gpt-5"), variant: Model.VariantID.make("low") }, + ], + ["anthropic/claude/sonnet-4", { providerID: Provider.ID.anthropic, id: Model.ID.make("claude/sonnet-4") }], [ "anthropic/claude/sonnet-4/high", - { model: { providerID: "anthropic", modelID: "claude/sonnet-4" }, variant: "high" }, + { + providerID: Provider.ID.anthropic, + id: Model.ID.make("claude/sonnet-4"), + variant: Model.VariantID.make("high"), + }, + ], + [ + "anthropic/claude/sonnet-4/missing", + { providerID: Provider.ID.anthropic, id: Model.ID.make("claude/sonnet-4/missing") }, ], - ["anthropic/claude/sonnet-4/missing", { model: { providerID: "anthropic", modelID: "claude/sonnet-4/missing" } }], ])("parses the model selection %s, preferring exact slash-containing model ids", (value, expected) => { - expect(parseModelSelection(value, providers)).toEqual(expected) + expect(parseModelSelection(value, catalog.models)).toEqual(expected) }) })