feat(acp): answer V2 forms through ACP elicitation (#52511)

This commit is contained in:
Shoubhit Dash
2026-10-01 22:17:50 +05:30
committed by GitHub
Unverified
parent b03d760f43
commit 96339544bf
9 changed files with 829 additions and 20 deletions
+1 -1
View File
@@ -115,7 +115,7 @@ export const connect = Effect.fnUntraced(function* (client: OpenCodeClient, stre
const acp = ACPConnection.make(app, stream)
const connection = acp.connection
const sessions = yield* ACPSessions.make({ client, connection, catalog })
const capabilities = yield* Ref.make({ childSessionUpdates: false })
const capabilities = yield* Ref.make({ childSessionUpdates: false, formElicitation: false })
const turn = yield* ACPTurn.make({ client, connection, sessions, catalog, capabilities })
yield* Deferred.succeed(ready, ACPService.make({ client, connection, catalog, sessions, capabilities, turn }))
return acp.agent
+10
View File
@@ -2,6 +2,8 @@ import {
methods,
type AgentApp,
type AnyMessage,
type CreateElicitationRequest,
type CreateElicitationResponse,
type JsonRpcId,
type RequestError,
type RequestPermissionRequest,
@@ -31,6 +33,10 @@ export interface Interface {
method: string,
params: Record<string, unknown>,
) => Effect.Effect<void, ACPError.Error | RequestError>
/** Interruption cancels the client's request. */
readonly createElicitation: (
params: CreateElicitationRequest,
) => Effect.Effect<CreateElicitationResponse, ACPError.Error | RequestError>
/** Tracks an incoming request from now on and returns its `Responded`. */
readonly responded: (requestId: JsonRpcId) => Effect.Effect<void>
}
@@ -65,6 +71,10 @@ export function make(app: AgentApp, stream: Stream) {
agent.client.request(methods.client.session.requestPermission, params, { cancellationSignal: signal }),
),
extNotification: (method, params) => ACPPromise.promise(() => agent.client.notify(method, params)),
createElicitation: (params) =>
ACPPromise.promise((signal) =>
agent.client.request(methods.client.elicitation.create, params, { cancellationSignal: signal }),
),
responded: (requestId) => {
const responded = Deferred.makeUnsafe<void>()
responses.set(requestId, responded)
+238
View File
@@ -0,0 +1,238 @@
import type {
CreateElicitationResponse,
ElicitationPropertySchema,
ElicitationSchema,
EnumOption,
} from "@agentclientprotocol/sdk"
import { isFormAlreadySettledError, isFormNotFoundError, type OpenCodeClient } from "@opencode/client/promise"
import { Form } from "@opencode/schema/form"
import { Cause, Effect, Option, Schema } from "effect"
import type { ACPConnection } from "./connection"
import type { ACPService } from "./service"
/** A form as the event stream carries it, with an unbranded ID. */
export type AskedForm = Omit<Form.Info, "id"> & { readonly id: string }
type InputField = Exclude<Form.Field, Form.ExternalField>
type SelectField = Form.StringField | Form.MultiselectField
// Form mode must not collect secrets, so only forms from flows known not to ask for credentials are elicited.
const ElicitedKind = Schema.Struct({ kind: Schema.Literals(["question", "websearch.provider"]) })
const Credential = /password|passphrase|secret|token|api[_-]?key|credential|private[_-]?key/i
const ToolSource = Schema.Struct({ tool: Schema.Struct({ id: Schema.String }) })
type Input = {
readonly client: OpenCodeClient
readonly connection: ACPConnection.Interface
readonly form: AskedForm
readonly requestedSchema: ElicitationSchema
readonly clientSessionID: string
readonly child?: { readonly id: string; readonly title?: string }
/** Whether the asking tool call reached the client as a `session/update` tool call. */
readonly toolCallSent: boolean
/** Completes once the form is answered or cancelled elsewhere. */
readonly settled: Effect.Effect<void>
}
type Outcome = Form.Answer | "cancel" | "settled"
/**
* Asks the client, then resolves the form on the server. Once `cancelled` completes, the client's request is
* cancelled or never sent, and the form is cancelled. Once `settled` completes, the client's request is cancelled and
* the server is left alone. Resolving on the server is uninterruptible.
*/
export const reply = Effect.fn("cli.acp.elicitation.reply")(function* (input: Input, cancelled: Effect.Effect<void>) {
yield* Effect.uninterruptibleMask((restore) =>
// The race starts racers in order and stops once one is done, so an earlier cancel never starts the ask.
restore(
cancelled.pipe(
Effect.as("cancel" as const),
Effect.raceFirst(input.settled.pipe(Effect.as("settled" as const))),
Effect.raceFirst(ask(input)),
),
).pipe(
Effect.tapCauseIf(Cause.hasDies, (cause) => Effect.logWarning("ACP elicitation failed", cause)),
Effect.catchCause(() => Effect.succeed("cancel" as const)),
Effect.flatMap((outcome) => respond(input, outcome)),
),
)
})
/** Cancels a form, interrupting its session when the server can't cancel it. */
export function cancel(client: OpenCodeClient, form: AskedForm) {
return settle(() => client.session.form.cancel({ sessionID: form.sessionID, formID: form.id })).pipe(
Effect.catch(() =>
Effect.tryPromise(() => client.session.interrupt({ sessionID: form.sessionID })).pipe(Effect.ignore),
),
)
}
/**
* The form-mode schema for a form, or undefined when the form is cancelled instead: the client lacks form
* elicitation, the form is not from an allowed flow or has a field that looks like a credential, or ACP can't
* represent it faithfully. Unrepresentable forms have `external` fields, `when` conditions, a hidden required field
* without a default, a default outside a field's options, or a free-text answer alongside options that must also
* satisfy `required` or item bounds across both inputs. Hidden fields are not asked and answer with their default.
*/
export function requestedSchema(form: AskedForm, capabilities: ACPService.Capabilities): ElicitationSchema | undefined {
if (!capabilities.formElicitation) return undefined
if (Option.isNone(Schema.decodeUnknownOption(ElicitedKind)(form.metadata))) return undefined
if (form.fields.some((field) => Credential.test(field.key) || Credential.test(field.title ?? ""))) return undefined
const fields = form.fields.filter((field): field is InputField => field.type !== "external")
if (fields.length !== form.fields.length || fields.some((field) => field.when?.length)) return undefined
if (fields.some((field) => field.hidden && field.required && field.default === undefined)) return undefined
const keys = new Set(fields.map((field) => field.key))
const visible = fields.filter((field) => !field.hidden)
if (!visible.every((field) => representable(field, keys))) return undefined
return {
type: "object",
properties: Object.fromEntries(visible.flatMap(properties)),
required: visible.filter((field) => field.required).map((field) => field.key),
}
}
/** The answer for an accepted response, or undefined when the user declined, cancelled, or sent invalid content. */
export function answer(form: AskedForm, response: CreateElicitationResponse): Form.Answer | undefined {
if (response.action !== "accept") return undefined
const content = Schema.decodeUnknownOption(Form.Answer)(response.content ?? {})
if (Option.isNone(content)) return undefined
return Object.fromEntries(
form.fields.flatMap((field) => {
const value = fieldAnswer(field, content.value)
return value === undefined ? [] : [[field.key, value]]
}),
)
}
const ask = Effect.fnUntraced(function* (input: Input) {
const source = input.toolCallSent ? Schema.decodeUnknownOption(ToolSource)(input.form.metadata) : Option.none()
const toolCallID = Option.getOrUndefined(Option.map(source, (metadata) => metadata.tool.id))
const response = yield* input.connection.createElicitation({
mode: "form",
sessionId: input.clientSessionID,
...(toolCallID ? { toolCallId: input.child ? `${input.child.id}:${toolCallID}` : toolCallID } : {}),
message: input.child?.title ? `${input.child.title}: ${input.form.title}` : input.form.title,
requestedSchema: input.requestedSchema,
})
return answer(input.form, response) ?? "cancel"
})
function respond(input: Input, outcome: Outcome) {
if (outcome === "settled") return Effect.void
if (outcome === "cancel") return cancel(input.client, input.form)
return settle(() =>
input.client.session.form.reply({ sessionID: input.form.sessionID, formID: input.form.id, answer: outcome }),
).pipe(
Effect.catch((cause) =>
Effect.logWarning("ACP form reply failed", cause).pipe(Effect.andThen(cancel(input.client, input.form))),
),
)
}
// A form already answered or cancelled elsewhere needs nothing more.
function settle(evaluate: () => Promise<void>) {
return Effect.tryPromise({ try: evaluate, catch: (cause) => cause }).pipe(
Effect.catch((cause) =>
isFormAlreadySettledError(cause) || isFormNotFoundError(cause) ? Effect.void : Effect.fail(cause),
),
)
}
function representable(field: InputField, keys: ReadonlySet<string>) {
if (field.type !== "string" && field.type !== "multiselect") return true
if (!hasOptions(field)) return true
const values = new Set(field.options?.map((option) => option.value))
const defaults =
field.default === undefined ? [] : typeof field.default === "string" ? [field.default] : field.default
if (defaults.some((value) => !values.has(value))) return false
if (!field.custom) return true
if (field.required || keys.has(customKey(field))) return false
return field.type === "string" || (field.minItems === undefined && field.maxItems === undefined)
}
function properties(field: InputField): Array<[string, ElicitationPropertySchema]> {
const base = { title: field.title, description: field.description }
switch (field.type) {
case "string": {
if (!hasOptions(field)) return [[field.key, { type: "string", ...base, ...text(field), default: field.default }]]
const select: ElicitationPropertySchema = {
type: "string",
...base,
oneOf: options(field),
default: field.default,
}
return field.custom ? [[field.key, select], other(field, "Type your own answer")] : [[field.key, select]]
}
case "multiselect": {
const select: ElicitationPropertySchema = {
type: "array",
...base,
items: { anyOf: options(field) },
minItems: field.required ? Math.max(field.minItems ?? 0, 1) : field.minItems,
maxItems: field.maxItems,
default: field.default,
}
return field.custom ? [[field.key, select], other(field, "Add your own answer")] : [[field.key, select]]
}
case "number":
case "integer":
return [
[
field.key,
{ type: field.type, ...base, minimum: field.minimum, maximum: field.maximum, default: field.default },
],
]
case "boolean":
return [[field.key, { type: "boolean", ...base, default: field.default }]]
}
}
// A free-text answer next to a field's options is a separate optional property that wins over the selection.
function other(field: SelectField, description: string): [string, ElicitationPropertySchema] {
return [
customKey(field),
{
type: "string",
title: `${field.title ?? field.key} (other)`,
description,
...(field.type === "string" ? text(field) : {}),
},
]
}
// Core rejects an empty string for a required field, so the client is told it needs at least one character.
function text(field: Form.StringField) {
return {
format: field.format,
minLength: field.required ? Math.max(field.minLength ?? 0, 1) : field.minLength,
maxLength: field.maxLength,
pattern: field.pattern,
}
}
function options(field: SelectField): EnumOption[] {
return (field.options ?? []).map((option) => ({
const: option.value,
title: option.label,
description: option.description,
}))
}
function fieldAnswer(field: Form.Field, content: Form.Answer) {
if (field.type !== "external" && field.hidden) return field.default
const value = content[field.key]
if ((field.type !== "string" && field.type !== "multiselect") || !field.custom || !hasOptions(field)) return value
const custom = content[customKey(field)]
if (typeof custom !== "string" || custom.trim() === "") return value
if (field.type === "string") return custom
return Array.isArray(value) ? [...value, custom] : [custom]
}
function hasOptions(field: SelectField) {
return field.type === "multiselect" || field.options !== undefined
}
function customKey(field: SelectField) {
return `${field.key}_custom`
}
export * as ACPElicitation from "./elicitation"
+6 -1
View File
@@ -51,6 +51,9 @@ export const AuthMethodID = "opencode-login"
export type Failure = ACPError.Error | RequestError | ACPCatalog.Error
/** What the client advertised in `initialize`. */
export type Capabilities = { readonly childSessionUpdates: boolean; readonly formElicitation: boolean }
export interface Interface {
readonly initialize: (input: InitializeRequest) => Effect.Effect<InitializeResponse>
readonly authenticate: (input: AuthenticateRequest) => Effect.Effect<AuthenticateResponse, Failure>
@@ -74,7 +77,7 @@ export function make(input: {
readonly connection: ACPConnection.Interface
readonly catalog: ACPCatalog.Interface
readonly sessions: ACPSessions.Interface
readonly capabilities: Ref.Ref<{ readonly childSessionUpdates: boolean }>
readonly capabilities: Ref.Ref<Capabilities>
readonly turn: ACPTurn.Interface
}): Interface {
const currentOptions = Effect.fnUntraced(function* (attached: Attached) {
@@ -147,8 +150,10 @@ export function make(input: {
return {
initialize: Effect.fnUntraced(function* (params) {
const elicitation = params.clientCapabilities?.elicitation
yield* Ref.set(input.capabilities, {
childSessionUpdates: params.clientCapabilities?._meta?.[ACPTranslate.ChildSessionUpdatesCapability] === true,
formElicitation: elicitation?.form !== undefined && elicitation.form !== null,
})
const authMethod: AuthMethod = {
description: "Run `opencode auth login` in the terminal",
+26 -3
View File
@@ -75,6 +75,8 @@ export type TurnState = {
readonly compactions: ReadonlyMap<string, string>
readonly children: ReadonlyMap<string, ChildSession>
readonly openChildren: ReadonlySet<string>
/** Forms asked of the client that the server has not yet answered or cancelled. */
readonly forms: ReadonlySet<string>
readonly finish?: SessionMessageAssistant["finish"]
readonly usage?: { readonly turn: TokenUsageInfo; readonly last: TokenUsageInfo }
readonly stepError?: SessionStructuredError
@@ -82,6 +84,7 @@ export type TurnState = {
}
type PermissionEvent = Extract<EventSubscribeOutput, { type: "permission.asked" }>
type FormEvent = Extract<EventSubscribeOutput, { type: "form.created" }>
export type Output =
| { readonly _tag: "SessionUpdate"; readonly update: SessionUpdate }
@@ -92,7 +95,14 @@ export type Output =
readonly tool?: Tool
readonly child?: ChildSession
}
| { readonly _tag: "FormCancel"; readonly sessionID: string; readonly formID: string }
| {
readonly _tag: "FormAsk"
readonly form: FormEvent["data"]["form"]
readonly child?: ChildSession
/** Whether the form's session sends its tool calls to the client as `session/update` tool calls. */
readonly toolCallSent: boolean
}
| { readonly _tag: "FormSettled"; readonly formID: string }
export type Step = {
readonly state: TurnState
@@ -119,6 +129,7 @@ export const initial: TurnState = {
compactions: new Map(),
children: new Map(),
openChildren: new Set(),
forms: new Set(),
}
export function step(state: TurnState, event: EventSubscribeOutput, ctx: Context): Step {
@@ -151,10 +162,22 @@ export function step(state: TurnState, event: EventSubscribeOutput, ctx: Context
}
if (event.type === "form.created" && (event.data.form.sessionID === ctx.sessionID || child)) {
return {
state,
outputs: [{ _tag: "FormCancel", sessionID: event.data.form.sessionID, formID: event.data.form.id }],
state: { ...state, forms: new Set(state.forms).add(event.data.form.id) },
outputs: [
{
_tag: "FormAsk",
form: event.data.form,
child,
toolCallSent: ctx.mode === "turn" && (!child || !ctx.childUpdates),
},
],
}
}
if ((event.type === "form.replied" || event.type === "form.cancelled") && state.forms.has(event.data.id)) {
const forms = new Set(state.forms)
forms.delete(event.data.id)
return { state: { ...state, forms }, outputs: [{ _tag: "FormSettled", formID: event.data.id }] }
}
if (!eventSessionID || (eventSessionID !== ctx.sessionID && !child)) return { state, outputs: [] }
if (matchesStart(event, ctx.start)) return { state: { ...state, started: true }, outputs: [] }
if (!state.started) return { state, outputs: [] }
+46 -15
View File
@@ -26,9 +26,11 @@ import { builtinCommands, type ACPCatalog, type Catalog } from "./catalog"
import { currentModel } from "./config-option"
import type { ACPConnection } from "./connection"
import { promptContentToParts } from "./content"
import { ACPElicitation } from "./elicitation"
import { ACPError } from "./error"
import { ACPPermission } from "./permission"
import { ACPPromise } from "./promise"
import type { ACPService } from "./service"
import type { ACPSessions, Attached } from "./sessions"
import { ACPTranslate } from "./translate"
@@ -71,10 +73,12 @@ type PermissionAsk = Extract<ACPTranslate.Output, { readonly _tag: "PermissionAs
type Subscription = {
readonly scope: Scope.Closeable
readonly events: Queue.Dequeue<OpenCodeEvent, unknown>
/** Runs permission replies one at a time in ask order, without holding back the rest of the stream. */
readonly permissions: Queue.Queue<Effect.Effect<void, ACPError.Error | RequestError>>
/** Completed when the turn is cancelled; pending and later asks are then rejected. */
/** Runs permission and form asks one at a time in ask order, without holding back the rest of the stream. */
readonly asks: Queue.Queue<Effect.Effect<void, ACPError.Error | RequestError>>
/** Completed when the turn is cancelled; pending and later asks then resolve without the client. */
readonly cancelled: Deferred.Deferred<void>
/** Completed per asked form once the server reports it answered or cancelled. */
readonly forms: Map<string, Deferred.Deferred<void>>
}
export const make = Effect.fnUntraced(function* (input: {
@@ -82,7 +86,7 @@ export const make = Effect.fnUntraced(function* (input: {
readonly connection: ACPConnection.Interface
readonly sessions: ACPSessions.Interface
readonly catalog: ACPCatalog.Interface
readonly capabilities: Ref.Ref<{ readonly childSessionUpdates: boolean }>
readonly capabilities: Ref.Ref<ACPService.Capabilities>
}) {
const scope = yield* Effect.scope
const drainTimeout = yield* CancelDrainTimeout
@@ -97,10 +101,11 @@ export const make = Effect.fnUntraced(function* (input: {
Stream.toQueue({ capacity: "unbounded" }),
Scope.provide(subscriptionScope),
),
permissions: yield* Queue.unbounded<Effect.Effect<void, ACPError.Error | RequestError>>(),
asks: yield* Queue.unbounded<Effect.Effect<void, ACPError.Error | RequestError>>(),
cancelled: yield* Deferred.make<void>(),
forms: new Map(),
}
yield* Queue.take(subscription.permissions).pipe(
yield* Queue.take(subscription.asks).pipe(
Effect.flatten,
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause) ? Effect.void : Effect.logWarning("ACP permission reply failed", cause),
@@ -118,10 +123,10 @@ export const make = Effect.fnUntraced(function* (input: {
),
)
// A turn settles only after the permission asks it saw have been answered.
const permissionsSettled = Effect.fnUntraced(function* (subscription: Subscription) {
// A turn settles only after the asks it saw have been resolved.
const asksSettled = Effect.fnUntraced(function* (subscription: Subscription) {
const settled = yield* Deferred.make<void>()
yield* Queue.offer(subscription.permissions, Deferred.succeed(settled, undefined).pipe(Effect.asVoid))
yield* Queue.offer(subscription.asks, Deferred.succeed(settled, undefined).pipe(Effect.asVoid))
yield* Deferred.await(settled)
})
@@ -149,11 +154,37 @@ export const make = Effect.fnUntraced(function* (input: {
.extNotification(ACPTranslate.ChildSessionUpdateMethod, output.update)
.pipe(Effect.ignoreCause)
case "PermissionAsk":
return Queue.offer(subscription.permissions, reply(subscription, ctx, output)).pipe(Effect.asVoid)
case "FormCancel":
return Effect.tryPromise(() =>
input.client.session.form.cancel({ sessionID: output.sessionID, formID: output.formID }),
).pipe(Effect.catch(() => interruptServer(output.sessionID)))
return Queue.offer(subscription.asks, reply(subscription, ctx, output)).pipe(Effect.asVoid)
case "FormAsk":
return Effect.gen(function* () {
const capabilities = yield* Ref.get(input.capabilities)
const requestedSchema = ACPElicitation.requestedSchema(output.form, capabilities)
if (!requestedSchema) return yield* ACPElicitation.cancel(input.client, output.form)
const settled = yield* Deferred.make<void>()
subscription.forms.set(output.form.id, settled)
yield* Queue.offer(
subscription.asks,
ACPElicitation.reply(
{
client: input.client,
connection: input.connection,
form: output.form,
requestedSchema,
clientSessionID: ctx.sessionID,
child: output.child,
toolCallSent: output.toolCallSent,
settled: Deferred.await(settled),
},
Deferred.await(subscription.cancelled),
),
)
})
case "FormSettled":
return Effect.suspend(() => {
const settled = subscription.forms.get(output.formID)
subscription.forms.delete(output.formID)
return settled ? Deferred.succeed(settled, undefined) : Effect.void
})
}
}
@@ -168,7 +199,7 @@ export const make = Effect.fnUntraced(function* (input: {
yield* Ref.set(state, next.state)
yield* Effect.forEach(next.outputs, (output) => interpret(subscription, ctx, output), { discard: true })
if (next.terminal) {
yield* permissionsSettled(subscription)
yield* asksSettled(subscription)
return next.terminal
}
}
+468
View File
@@ -0,0 +1,468 @@
import { describe, expect, test } from "bun:test"
import type { AnyMessage, AnyRequest, CreateElicitationResponse } from "@agentclientprotocol/sdk"
import { ACPElicitation } from "../../src/acp/elicitation"
import {
childCreated,
delivered,
durableEvent,
ephemeralEvent,
interrupted,
startSession,
succeeded,
textDelta,
toolStarted,
toolSucceeded,
} from "./wire-fixture"
const questions = (sessionID: string, id = "frm_question", tool = "call_question") =>
ephemeralEvent("form.created", {
form: {
id,
sessionID,
title: "Questions",
metadata: { kind: "question", tool: { messageID: "msg_tools", id: tool } },
fields: [
{
key: "q0",
title: "Runtime",
description: "Which runtime?",
type: "string",
options: [
{ value: "Bun", label: "Bun", description: "Fast" },
{ value: "Node", label: "Node", description: "Stable" },
],
custom: true,
},
{
key: "q1",
title: "Goals",
description: "What matters?",
type: "multiselect",
options: [{ value: "Fast", label: "Fast", description: "Speed" }],
custom: true,
},
],
},
})
const capable = { childSessionUpdates: false, formElicitation: true }
const form = (
fields: ACPElicitation.AskedForm["fields"],
metadata: ACPElicitation.AskedForm["metadata"] = { kind: "question" },
) => ({ id: "frm_test", sessionID: "ses_test", title: "Test", metadata, fields })
const accept = (content: Record<string, string | number | boolean | string[]>): CreateElicitationResponse => ({
action: "accept",
content,
})
const pendingUntilAborted = (_request: unknown, signal: AbortSignal) =>
new Promise<CreateElicitationResponse>((resolve) => {
signal.addEventListener("abort", () => resolve({ action: "cancel" }), { once: true })
})
const firstElicitationCancel = (received: readonly AnyMessage[]): AnyMessage => {
const asked = received.find(
(message): message is AnyRequest =>
"method" in message && "id" in message && message.method === "elicitation/create",
)
return { jsonrpc: "2.0", method: "$/cancel_request", params: { requestId: asked?.id } }
}
describe("acp elicitation mapping", () => {
test("maps every representable field type", () => {
expect(
ACPElicitation.requestedSchema(
form([
{
key: "email",
title: "Email",
description: "Work address",
type: "string",
format: "email",
maxLength: 80,
pattern: ".+@.+",
placeholder: "you@example.com",
default: "a@b.co",
required: true,
},
{ key: "name", type: "string", minLength: 2 },
{
key: "plan",
type: "string",
options: [
{ value: "pro", label: "Pro", description: "Paid" },
{ value: "free", label: "Free" },
],
default: "free",
},
{ key: "ratio", type: "number", minimum: 0, maximum: 1, default: 0.5 },
{ key: "count", type: "integer", minimum: 1, required: true },
{ key: "confirm", type: "boolean", default: false },
{
key: "tags",
type: "multiselect",
options: [
{ value: "a", label: "A" },
{ value: "b", label: "B" },
],
maxItems: 2,
default: ["a"],
required: true,
},
{ key: "server", type: "string", format: "uri", hidden: true, default: "https://example.com" },
]),
capable,
),
).toEqual({
type: "object",
properties: {
email: {
type: "string",
title: "Email",
description: "Work address",
format: "email",
minLength: 1,
maxLength: 80,
pattern: ".+@.+",
default: "a@b.co",
},
name: { type: "string", minLength: 2 },
plan: {
type: "string",
oneOf: [
{ const: "pro", title: "Pro", description: "Paid" },
{ const: "free", title: "Free" },
],
default: "free",
},
ratio: { type: "number", minimum: 0, maximum: 1, default: 0.5 },
count: { type: "integer", minimum: 1 },
confirm: { type: "boolean", default: false },
tags: {
type: "array",
items: {
anyOf: [
{ const: "a", title: "A" },
{ const: "b", title: "B" },
],
},
minItems: 1,
maxItems: 2,
default: ["a"],
},
},
required: ["email", "count", "tags"],
})
})
test("adds a free-text property next to options that accept a custom answer", () => {
expect(
ACPElicitation.requestedSchema(
form([
{
key: "q0",
title: "Runtime",
type: "string",
options: [{ value: "Bun", label: "Bun" }],
custom: true,
maxLength: 20,
},
{ key: "q1", type: "multiselect", options: [{ value: "Fast", label: "Fast" }], custom: true },
]),
capable,
)?.properties,
).toEqual({
q0: { type: "string", title: "Runtime", oneOf: [{ const: "Bun", title: "Bun" }] },
q0_custom: { type: "string", title: "Runtime (other)", description: "Type your own answer", maxLength: 20 },
q1: { type: "array", items: { anyOf: [{ const: "Fast", title: "Fast" }] } },
q1_custom: { type: "string", title: "q1 (other)", description: "Add your own answer" },
})
})
test("cancels forms from unsupported clients, unknown flows, and credential-looking fields", () => {
const fields: ACPElicitation.AskedForm["fields"] = [{ key: "name", type: "string" }]
expect(ACPElicitation.requestedSchema(form(fields), { ...capable, formElicitation: false })).toBeUndefined()
expect(ACPElicitation.requestedSchema(form(fields, { kind: "mcp-elicitation" }), capable)).toBeUndefined()
expect(ACPElicitation.requestedSchema(form(fields, {}), capable)).toBeUndefined()
expect(ACPElicitation.requestedSchema(form(fields, { kind: "websearch.provider" }), capable)).toBeDefined()
const credentials: Array<ACPElicitation.AskedForm["fields"]> = [
[{ key: "api_key", type: "string" }],
[{ key: "q0", title: "GitHub token", type: "string" }],
[{ key: "q0", title: "Password", type: "string", hidden: true, default: "" }],
]
expect(credentials.map((fields) => ACPElicitation.requestedSchema(form(fields), capable))).toEqual(
credentials.map(() => undefined),
)
})
test("cancels forms it cannot represent faithfully", () => {
const options = [{ value: "a", label: "A" }]
const unrepresentable: Array<ACPElicitation.AskedForm["fields"]> = [
[
{ key: "mode", type: "boolean" },
{ key: "detail", type: "string", when: [{ key: "mode", op: "eq", value: true }] },
],
[
{ key: "mode", type: "boolean" },
{ key: "detail", type: "string", hidden: true, default: "x", when: [{ key: "mode", op: "eq", value: true }] },
],
[{ key: "login", type: "external", url: "https://example.com/login" }],
[{ key: "server", type: "string", hidden: true, required: true }],
[{ key: "pick", type: "string", options, custom: true, required: true }],
[{ key: "pick", type: "multiselect", options, custom: true, maxItems: 1 }],
[{ key: "pick", type: "string", options, default: "b" }],
[{ key: "pick", type: "multiselect", options, default: ["a", "b"] }],
[
{ key: "pick", type: "string", options, custom: true },
{ key: "pick_custom", type: "string" },
],
]
expect(unrepresentable.map((fields) => ACPElicitation.requestedSchema(form(fields), capable))).toEqual(
unrepresentable.map(() => undefined),
)
expect(
ACPElicitation.requestedSchema(
form([
{ key: "name", type: "string" },
{ key: "pick", type: "string", options, default: "b", hidden: true },
]),
capable,
)?.properties,
).toEqual({ name: { type: "string" } })
})
test("maps an accepted response back to answers", () => {
const options = [{ value: "a", label: "A" }]
const fields: ACPElicitation.AskedForm["fields"] = [
{ key: "single", type: "string", options, custom: true },
{ key: "multi", type: "multiselect", options, custom: true },
{ key: "blank", type: "string", options, custom: true },
{ key: "count", type: "integer" },
{ key: "server", type: "string", hidden: true, default: "https://example.com" },
{ key: "region", type: "string", hidden: true },
]
expect(
ACPElicitation.answer(
form(fields),
accept({
single: "a",
single_custom: "typed",
multi: ["a"],
multi_custom: "extra",
blank: "a",
blank_custom: " ",
count: 3,
server: "https://other.example.com",
unknown: true,
}),
),
).toEqual({
single: "typed",
multi: ["a", "extra"],
blank: "a",
count: 3,
server: "https://example.com",
})
expect(ACPElicitation.answer(form(fields), accept({ multi_custom: "only" }))).toEqual({
multi: ["only"],
server: "https://example.com",
})
expect(ACPElicitation.answer(form(fields), { action: "accept" })).toEqual({ server: "https://example.com" })
})
test("has no answer unless the user accepted valid content", () => {
const fields: ACPElicitation.AskedForm["fields"] = [{ key: "name", type: "string" }]
expect(ACPElicitation.answer(form(fields), { action: "decline" })).toBeUndefined()
expect(ACPElicitation.answer(form(fields), { action: "cancel" })).toBeUndefined()
expect(ACPElicitation.answer(form(fields), { action: "_custom" })).toBeUndefined()
expect(
ACPElicitation.answer(form(fields), { action: "accept", content: { name: { nested: true } } }),
).toBeUndefined()
})
})
describe("acp elicitation over the wire", () => {
test("answers a question form through elicitation and continues the turn", async () => {
await using acp = await startSession({
capabilities: { elicitation: true },
onPrompt: ({ sessionID, id }) => [
delivered(sessionID, id),
toolStarted(sessionID, "call_question", "question"),
questions(sessionID),
],
elicitation: () => accept({ q0: "Bun", q1: ["Fast"], q1_custom: "Small" }),
onFormReply: ({ sessionID, formID }) => [
ephemeralEvent("form.replied", { sessionID, id: formID, answer: {} }),
toolSucceeded(sessionID, "call_question", {}, "answered"),
textDelta(sessionID, "msg_after", "thanks"),
succeeded(sessionID),
],
})
expect((await acp.prompt(acp.sessionId, "hello")).stopReason).toBe("end_turn")
expect(acp.elicitations).toMatchObject([
{ mode: "form", sessionId: acp.sessionId, toolCallId: "call_question", message: "Questions" },
])
expect(acp.server.repliedForms).toEqual([
{ sessionID: acp.sessionId, formID: "frm_question", answer: { q0: "Bun", q1: ["Fast", "Small"] } },
])
expect(acp.server.cancelledForms).toEqual([])
expect(acp.updates.some((item) => item.update.sessionUpdate === "agent_message_chunk")).toBe(true)
})
test("cancels the form when the client declines, cancels, fails, or sends a wrong value type", async () => {
const responses: Array<() => CreateElicitationResponse> = [
() => ({ action: "decline" }),
() => ({ action: "cancel" }),
() => {
throw new Error("elicitation UI failed")
},
() => ({ action: "accept", content: { q0: { nested: true } } }),
]
const ids = ["frm_decline", "frm_cancel", "frm_fail", "frm_invalid"]
await using acp = await startSession({
capabilities: { elicitation: true },
onPrompt: ({ sessionID, id }) => [delivered(sessionID, id), ...ids.map((form) => questions(sessionID, form))],
elicitation: () => responses[acp.elicitations.length - 1](),
onFormCancel: ({ sessionID }) => (acp.server.cancelledForms.length === ids.length ? [succeeded(sessionID)] : []),
})
expect((await acp.prompt(acp.sessionId, "hello")).stopReason).toBe("end_turn")
expect(acp.elicitations).toHaveLength(ids.length)
expect(acp.server.cancelledForms.map((item) => item.formID)).toEqual(ids)
expect(acp.server.repliedForms).toEqual([])
expect(acp.server.interrupts).toEqual([])
})
test("cancels forms outside the allowed flows without asking", async () => {
await using acp = await startSession({
capabilities: { elicitation: true },
onPrompt: ({ sessionID, id }) => [
delivered(sessionID, id),
ephemeralEvent("form.created", {
form: {
id: "frm_plugin",
sessionID,
title: "Plugin",
metadata: { kind: "plugin" },
fields: [{ key: "name", type: "string" }],
},
}),
],
onFormCancel: ({ sessionID }) => [succeeded(sessionID)],
})
expect((await acp.prompt(acp.sessionId, "hello")).stopReason).toBe("end_turn")
expect(acp.elicitations).toEqual([])
expect(acp.server.cancelledForms).toEqual([{ sessionID: acp.sessionId, formID: "frm_plugin" }])
})
test("cancelling the turn cancels its pending elicitation and the form, and never sends queued ones", async () => {
await using acp = await startSession({
capabilities: { elicitation: true },
onPrompt: ({ sessionID, id }) => [
delivered(sessionID, id),
questions(sessionID, "frm_pending"),
questions(sessionID, "frm_queued"),
],
onInterrupt: ({ sessionID }) => [interrupted(sessionID)],
elicitation: pendingUntilAborted,
})
const prompt = acp.prompt(acp.sessionId, "hello")
await acp.until(() => acp.elicitations.length === 1, "elicitation request")
await acp.notify("session/cancel", { sessionId: acp.sessionId })
expect(await prompt).toMatchObject({ stopReason: "cancelled" })
await acp.until(() => acp.server.cancelledForms.length === 2, "form cancellation")
expect(acp.elicitations).toHaveLength(1)
expect(acp.server.cancelledForms.map((item) => item.formID)).toEqual(["frm_pending", "frm_queued"])
expect(acp.server.repliedForms).toEqual([])
expect(acp.received).toContainEqual(firstElicitationCancel(acp.received))
})
test("withdraws an elicitation for a form settled elsewhere and moves on to the next ask", async () => {
await using acp = await startSession({
capabilities: { elicitation: true },
onPrompt: ({ sessionID, id }) => [delivered(sessionID, id), questions(sessionID, "frm_elsewhere")],
elicitation: (request, signal) =>
acp.elicitations.length === 1 ? pendingUntilAborted(request, signal) : accept({ q0: "Node" }),
onFormReply: ({ sessionID }) => [succeeded(sessionID)],
})
const prompt = acp.prompt(acp.sessionId, "hello")
await acp.until(() => acp.elicitations.length === 1, "elicitation request")
acp.server.send(
ephemeralEvent("form.replied", { sessionID: acp.sessionId, id: "frm_elsewhere", answer: { q0: "Bun" } }),
questions(acp.sessionId, "frm_next"),
)
expect((await prompt).stopReason).toBe("end_turn")
expect(acp.received).toContainEqual(firstElicitationCancel(acp.received))
expect(acp.elicitations).toHaveLength(2)
expect(acp.server.repliedForms).toEqual([{ sessionID: acp.sessionId, formID: "frm_next", answer: { q0: "Node" } }])
expect(acp.server.cancelledForms).toEqual([])
expect(acp.server.interrupts).toEqual([])
})
test("leaves the session alone when the user's answer arrives after the form settled", async () => {
await using acp = await startSession({
capabilities: { elicitation: true },
onPrompt: ({ sessionID, id }) => [delivered(sessionID, id), questions(sessionID)],
elicitation: () => accept({ q0: "Bun" }),
fetch: (request) => {
if (!request.path.endsWith("/form/frm_question/reply")) return undefined
acp.server.send(succeeded(acp.sessionId))
return Response.json(
{ _tag: "FormAlreadySettledError", id: "frm_question", message: "Form already settled: frm_question" },
{ status: 409 },
)
},
})
expect((await acp.prompt(acp.sessionId, "hello")).stopReason).toBe("end_turn")
expect(acp.server.requests.filter((request) => request.path.endsWith("/reply"))).toHaveLength(1)
expect(acp.server.cancelledForms).toEqual([])
expect(acp.server.interrupts).toEqual([])
})
test("prefixes a foreground child form's tool call and message with the child", async () => {
await using acp = await startSession({
capabilities: { elicitation: true },
onPrompt: ({ sessionID, id }) => [
delivered(sessionID, id),
childCreated("ses_child", sessionID, "Review code"),
durableEvent("session.execution.started", { sessionID: "ses_child" }),
questions("ses_child", "frm_child", "call_child"),
],
elicitation: () => accept({ q0: "Node" }),
onFormReply: ({ sessionID }) => [succeeded(sessionID), succeeded(acp.sessionId)],
})
expect((await acp.prompt(acp.sessionId, "hello")).stopReason).toBe("end_turn")
expect(acp.elicitations).toMatchObject([
{ sessionId: acp.sessionId, toolCallId: "ses_child:call_child", message: "Review code: Questions" },
])
expect(acp.server.repliedForms).toEqual([{ sessionID: "ses_child", formID: "frm_child", answer: { q0: "Node" } }])
})
test("omits the tool call when the child's tool calls only reach the client as child updates", async () => {
await using acp = await startSession({
capabilities: { elicitation: true, childSessionUpdates: true },
onPrompt: ({ sessionID, id }) => [
delivered(sessionID, id),
childCreated("ses_child", sessionID, "Review code"),
questions("ses_child", "frm_child", "call_child"),
],
elicitation: () => accept({ q0: "Node" }),
onFormReply: ({ sessionID }) => [succeeded(sessionID), succeeded(acp.sessionId)],
})
expect((await acp.prompt(acp.sessionId, "hello")).stopReason).toBe("end_turn")
expect(acp.elicitations).toHaveLength(1)
expect(acp.elicitations[0]).toMatchObject({ sessionId: acp.sessionId, message: "Review code: Questions" })
expect(acp.elicitations[0]).not.toHaveProperty("toolCallId")
})
})
+1
View File
@@ -364,6 +364,7 @@ describe("acp turn events over the wire", () => {
expect((await acp.prompt(acp.sessionId, "hello")).stopReason).toBe("end_turn")
expect(acp.server.cancelledForms).toEqual([{ sessionID: acp.sessionId, formID: "frm_question" }])
expect(acp.elicitations).toEqual([])
})
test("reports locations for native edit, write, and patch tools (https://github.com/anomalyco/opencode/issues/49591)", async () => {
+33
View File
@@ -9,6 +9,8 @@ import {
type AgentRequestResponsesByMethod,
type AnyMessage,
type ContentBlock,
type CreateElicitationRequest,
type CreateElicitationResponse,
type McpServer,
type RequestPermissionRequest,
type RequestPermissionResponse,
@@ -27,6 +29,7 @@ import {
type SessionMessageInfo,
type TokenUsageInfo,
} from "@opencode/client/promise"
import { Form } from "@opencode/schema/form"
import type { BunRequest } from "bun"
import { Duration, Effect, Exit, Logger, Option, Schema, Scope } from "effect"
import { ACP } from "../../src/acp/agent"
@@ -64,6 +67,7 @@ const ModelBody = Schema.Struct({
})
const AgentBody = Schema.Struct({ agent: Schema.String })
const ReplyBody = Schema.Struct({ decision: Schema.Literals(["once", "always", "reject"]) })
const FormReplyBody = Schema.Struct({ answer: Form.Answer })
const McpBody = Schema.Struct({ config: Schema.Unknown })
const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown))
@@ -118,13 +122,24 @@ export type WireOptions = {
readonly decision: string
}>
readonly onFormCancel?: Hook<{ readonly sessionID: string; readonly formID: string }>
readonly onFormReply?: Hook<FormReply>
readonly permission?: (
request: RequestPermissionRequest,
signal: AbortSignal,
) => RequestPermissionResponse | Promise<RequestPermissionResponse>
readonly elicitation?: (
request: CreateElicitationRequest,
signal: AbortSignal,
) => CreateElicitationResponse | Promise<CreateElicitationResponse>
readonly cancelDrainTimeout?: Duration.Input
}
type FormReply = {
readonly sessionID: string
readonly formID: string
readonly answer: typeof FormReplyBody.Type.answer
}
type CatalogKind = "model" | "default" | "agent" | "command"
export type Catalog = {
@@ -139,6 +154,7 @@ export type InitializeOptions = {
readonly writeTextFile?: boolean
readonly childSessionUpdates?: boolean
readonly terminalAuth?: boolean
readonly elicitation?: boolean
}
export const testModel = {
@@ -369,6 +385,7 @@ export async function startWire(options: WireOptions = {}) {
const permissions: RequestPermissionRequest[] = []
const writes: WriteTextFileRequest[] = []
const childUpdates: ChildUpdate[] = []
const elicitations: CreateElicitationRequest[] = []
// Client handlers record SDK-validated params; responses wait until they have seen every earlier agent message.
const counts = { sent: 0, handled: 0 }
const handled = <Value>(list: Value[], value: Value) => {
@@ -404,6 +421,10 @@ export async function startWire(options: WireOptions = {}) {
handled(permissions, ctx.params)
return options.permission?.(ctx.params, ctx.signal) ?? { outcome: { outcome: "cancelled" } }
})
.onRequest("elicitation/create", (ctx) => {
handled(elicitations, ctx.params)
return options.elicitation?.(ctx.params, ctx.signal) ?? { action: "cancel" }
})
.onRequest("fs/write_text_file", (ctx) => {
handled(writes, ctx.params)
return {}
@@ -459,6 +480,7 @@ export async function startWire(options: WireOptions = {}) {
protocolVersion: 1,
clientCapabilities: {
...(capabilities.writeTextFile ? { fs: { writeTextFile: true, readTextFile: false } } : {}),
...(capabilities.elicitation ? { elicitation: { form: {} } } : {}),
_meta: {
...(capabilities.childSessionUpdates ? { "opencode/child-session-updates": true } : {}),
...(capabilities.terminalAuth ? { "terminal-auth": true } : {}),
@@ -475,6 +497,7 @@ export async function startWire(options: WireOptions = {}) {
permissions,
writes,
childUpdates,
elicitations,
request,
until,
initialize,
@@ -534,6 +557,7 @@ function startServer(options: WireOptions, changed: () => void) {
const interrupts: string[] = []
const replies: Array<{ readonly sessionID: string; readonly requestID: string; readonly decision: string }> = []
const cancelledForms: Array<{ readonly sessionID: string; readonly formID: string }> = []
const repliedForms: FormReply[] = []
const mcp: Array<{ readonly name: string; readonly directory?: string; readonly config: unknown }> = []
const fake = {
requests,
@@ -549,6 +573,7 @@ function startServer(options: WireOptions, changed: () => void) {
interrupts,
replies,
cancelledForms,
repliedForms,
mcp,
send(...events: ReadonlyArray<OpenCodeEvent>) {
events.forEach((event) => {
@@ -787,6 +812,14 @@ function startServer(options: WireOptions, changed: () => void) {
return noContent()
}),
},
"/api/session/:sessionID/form/:formID/reply": {
POST: body(FormReplyBody, async (req, input) => {
const reply = { sessionID: req.params.sessionID, formID: req.params.formID, answer: input.answer }
fake.repliedForms.push(reply)
await emit(options.onFormReply?.(reply))
return noContent()
}),
},
"/api/experimental/mcp/:name": {
PUT: body(McpBody, (req, input, query) => {
fake.mcp.push({ name: req.params.name, directory: query["location[directory]"], config: input.config })