From 7de3fdc405fa6407cdd2ab2f8d0e8182fda5a06c Mon Sep 17 00:00:00 2001 From: Junmo Kim Date: Mon, 9 Nov 2026 13:06:28 +0900 Subject: [PATCH] feat(acp): show OpenCode and Antigravity questions in HAPI and return the answer (#2309) * feat(acp): opt-in form elicitation capability advertisement * feat(acp): route elicitation/create forms to a registered handler * feat(opencode): map question forms to AskUserQuestion input and back * feat(opencode): queue question forms as AskUserQuestion requests without auto-answering * feat(opencode): advertise form elicitation for OpenCode v2 * feat(opencode): present the question tool call as AskUserQuestion * feat(opencode): cancel pending question forms on abort, turn end, archive and exit * test(opencode): cover the unshown question result surfacing * feat(acp): let a form elicitation be declined A form elicitation could only be accepted or cancelled. ACP also has decline, the user refusing to answer, and agents may record it differently from a cancel: Antigravity records a declined question as "User Skipped". FormElicitationResponse now includes it, and the backend passes it back to the agent unchanged. * feat(acp): let the ACP permission handler ask the user a question An agent's question (Antigravity's ask_question) is not a permission request: it needs the user's answers, and it must never be answered automatically. askUser() shows it as a pending request with the given tool name and input, whatever the permission mode, and resolves with the user's decision and answers. cancelAll() resolves an open question as aborted, and an open question counts as a pending request, so callers that wait for approvals also wait for it. onUserWait now covers these waits too and no longer takes the request. isUsed() tells whether an id is open or was already shown, since clients hide a pending request whose id was completed before. * feat(agy): answer agy's questions in the question card On agy acp, agy's ask_question used to arrive as a generic tool card and plain text. The turn ended, and whatever the user typed next became the answer. agy now gets form elicitation advertised, so it asks through elicitation/create and keeps the turn open. The launcher takes these forms through the backend's shared form elicitation handler, the same one OpenCode uses. - The question is shown as the AskUserQuestion card on agy's own tool call, with the options as choices, multi-select and an Other field. - The user's choice goes back as agy's answer: the chosen option values, plus free text under qN_other only when the user typed some, so agy records exactly the chosen label. - Denying declines the question, which agy records as "User Skipped". Stop and session end cancel it. - No permission mode answers a question, always-proceed included. - Steer is refused while a question is open. - An approval that carries no usable answer declines instead of sending an empty answer. - A question that arrives after Stop is cancelled. * fix(opencode): decline question forms that arrive after Stop cancelAll only swept requests that already existed, so a form delivered afterwards was queued as a card whose promise never settled. Close the gate synchronously in cancelAll and reopen it when the next prompt begins, matching the aborted-turn guard of the agy handler. * feat(web): let the question card be skipped Add a Skip button, also bound to Esc inside the card, that denies the pending question through the existing deny API and clears the draft like Submit does. A deny already becomes a decline for agy and a cancel for OpenCode, so the backend is unchanged. * fix(agy): decline questions that arrive after the turn has ended * fix(web): keep typed text when Esc is pressed in the question card's text field * fix(question): hide Other on question forms that do not allow free text Forms without qN_custom (OpenCode) or qN_other (agy) take no typed answer, yet the card always offered Other, and a typed answer was dropped so the result became a cancel. Carry an allowFreeText flag through the tool-call input and the synthesized question input, and hide Other on the card when it is false. Inputs without the flag keep showing Other. --- .../acp/AcpSdkBackend.elicitation.test.ts | 127 ++++++++ .../acp/AcpSdkBackend.initialize.test.ts | 12 + cli/src/agent/backends/acp/AcpSdkBackend.ts | 76 ++++- .../acp/__fixtures__/agy-question-turn.json | 304 ++++++++++++++++++ cli/src/agent/types.ts | 28 ++ ...yAcpRemoteLauncher.question.replay.test.ts | 142 ++++++++ cli/src/agy/agyAcpRemoteLauncher.test.ts | 204 +++++++++++- cli/src/agy/agyAcpRemoteLauncher.ts | 70 +++- cli/src/agy/agyQuestion.test.ts | 148 +++++++++ cli/src/agy/agyQuestion.ts | 158 +++++++++ cli/src/agy/utils/agyAcpBackend.ts | 4 +- .../permission/AcpPermissionHandler.test.ts | 68 +++- .../common/permission/AcpPermissionHandler.ts | 62 +++- .../opencode/opencodeRemoteLauncher.test.ts | 108 ++++++- cli/src/opencode/opencodeRemoteLauncher.ts | 9 +- cli/src/opencode/runOpencode.test.ts | 11 + cli/src/opencode/runOpencode.ts | 1 + .../opencode/utils/opencodeBackend.test.ts | 8 + cli/src/opencode/utils/opencodeBackend.ts | 3 + .../opencode/utils/opencodeQuestion.test.ts | 187 +++++++++++ cli/src/opencode/utils/opencodeQuestion.ts | 184 +++++++++++ .../utils/permissionHandler.question.test.ts | 281 ++++++++++++++++ cli/src/opencode/utils/permissionHandler.ts | 108 ++++++- docs/guide/agents.md | 4 + .../ToolCard/AskUserQuestionFooter.test.tsx | 79 ++++- .../ToolCard/AskUserQuestionFooter.tsx | 54 +++- .../components/ToolCard/askUserQuestion.ts | 5 +- .../components/ToolCard/cursorAskQuestion.ts | 3 +- web/src/lib/locales/en.ts | 1 + web/src/lib/locales/ru.ts | 1 + web/src/lib/locales/zh-CN.ts | 1 + 31 files changed, 2413 insertions(+), 38 deletions(-) create mode 100644 cli/src/agent/backends/acp/AcpSdkBackend.elicitation.test.ts create mode 100644 cli/src/agent/backends/acp/__fixtures__/agy-question-turn.json create mode 100644 cli/src/agy/agyAcpRemoteLauncher.question.replay.test.ts create mode 100644 cli/src/agy/agyQuestion.test.ts create mode 100644 cli/src/agy/agyQuestion.ts create mode 100644 cli/src/opencode/utils/opencodeQuestion.test.ts create mode 100644 cli/src/opencode/utils/opencodeQuestion.ts create mode 100644 cli/src/opencode/utils/permissionHandler.question.test.ts diff --git a/cli/src/agent/backends/acp/AcpSdkBackend.elicitation.test.ts b/cli/src/agent/backends/acp/AcpSdkBackend.elicitation.test.ts new file mode 100644 index 00000000..f32535b1 --- /dev/null +++ b/cli/src/agent/backends/acp/AcpSdkBackend.elicitation.test.ts @@ -0,0 +1,127 @@ +import { describe, expect, it, vi } from 'vitest'; +import { AcpSdkBackend } from './AcpSdkBackend'; + +type Internal = { + handleElicitationRequest: (params: unknown) => Promise; + transport: { sendNotification: (method: string, params: unknown) => void; close: () => Promise } | null; +}; + +const formParams = { + mode: 'form', + sessionId: 'session-1', + toolCallId: 'call-1', + message: 'Questions', + requestedSchema: { type: 'object', properties: { q0: { type: 'string' } }, required: [] } +}; + +function createBackend() { + const backend = new AcpSdkBackend({ command: 'opencode', elicitationForm: true }); + const internal = backend as unknown as Internal; + const notifications: Array<{ method: string; params: unknown }> = []; + internal.transport = { + sendNotification: (method, params) => notifications.push({ method, params }), + close: async () => {} + }; + return { backend, internal, notifications }; +} + +describe('AcpSdkBackend form elicitation', () => { + it('passes the form to the handler and returns its answer', async () => { + const { backend, internal } = createBackend(); + const handler = vi.fn(async () => ({ action: 'accept' as const, content: { q0: '승인' } })); + backend.onFormElicitation(handler); + + await expect(internal.handleElicitationRequest(formParams)).resolves.toEqual({ + action: 'accept', + content: { q0: '승인' } + }); + expect(handler).toHaveBeenCalledWith({ + sessionId: 'session-1', + toolCallId: 'call-1', + message: 'Questions', + requestedSchema: formParams.requestedSchema + }); + }); + + it('passes a decline back to the agent', async () => { + const { backend, internal } = createBackend(); + backend.onFormElicitation(async () => ({ action: 'decline' })); + + await expect(internal.handleElicitationRequest(formParams)).resolves.toEqual({ action: 'decline' }); + }); + + it('cancels when no handler is registered', async () => { + const { internal } = createBackend(); + + await expect(internal.handleElicitationRequest(formParams)).resolves.toEqual({ action: 'cancel' }); + }); + + it('cancels url mode and malformed requests without calling the handler', async () => { + const { backend, internal } = createBackend(); + const handler = vi.fn(async () => ({ action: 'accept' as const, content: {} })); + backend.onFormElicitation(handler); + + await expect(internal.handleElicitationRequest({ ...formParams, mode: 'url' })).resolves.toEqual({ action: 'cancel' }); + await expect(internal.handleElicitationRequest(null)).resolves.toEqual({ action: 'cancel' }); + await expect(internal.handleElicitationRequest({ mode: 'form', message: 'x' })).resolves.toEqual({ action: 'cancel' }); + expect(handler).not.toHaveBeenCalled(); + }); + + it('cancels when the handler throws', async () => { + const { backend, internal } = createBackend(); + backend.onFormElicitation(async () => { + throw new Error('boom'); + }); + + await expect(internal.handleElicitationRequest(formParams)).resolves.toEqual({ action: 'cancel' }); + }); + + it('settles a pending form with cancel when the prompt is cancelled', async () => { + const { backend, internal, notifications } = createBackend(); + backend.onFormElicitation(() => new Promise(() => {})); + + const pending = internal.handleElicitationRequest(formParams); + await backend.cancelPrompt('session-1'); + + await expect(pending).resolves.toEqual({ action: 'cancel' }); + expect(notifications).toEqual([{ method: 'session/cancel', params: { sessionId: 'session-1' } }]); + }); + + it('keeps forms of other sessions pending when one session is cancelled', async () => { + const { backend, internal } = createBackend(); + backend.onFormElicitation(() => new Promise(() => {})); + + let settled = false; + void internal.handleElicitationRequest({ ...formParams, sessionId: 'session-2' }).then(() => { + settled = true; + }); + await backend.cancelPrompt('session-1'); + await Promise.resolve(); + + expect(settled).toBe(false); + }); + + it('settles pending forms with cancel on disconnect', async () => { + const { backend, internal } = createBackend(); + backend.onFormElicitation(() => new Promise(() => {})); + + const pending = internal.handleElicitationRequest(formParams); + await backend.disconnect(); + + await expect(pending).resolves.toEqual({ action: 'cancel' }); + }); + + it('does not let a late handler answer overwrite the cancel', async () => { + const { backend, internal } = createBackend(); + let answer!: (value: { action: 'accept'; content: Record }) => void; + backend.onFormElicitation(() => new Promise((resolve) => { + answer = resolve; + })); + + const pending = internal.handleElicitationRequest(formParams); + await backend.cancelPrompt('session-1'); + answer({ action: 'accept', content: { q0: '승인' } }); + + await expect(pending).resolves.toEqual({ action: 'cancel' }); + }); +}); diff --git a/cli/src/agent/backends/acp/AcpSdkBackend.initialize.test.ts b/cli/src/agent/backends/acp/AcpSdkBackend.initialize.test.ts index 0603f085..787ddc85 100644 --- a/cli/src/agent/backends/acp/AcpSdkBackend.initialize.test.ts +++ b/cli/src/agent/backends/acp/AcpSdkBackend.initialize.test.ts @@ -56,4 +56,16 @@ describe('AcpSdkBackend.initialize', () => { expect(metas[0]).not.toHaveProperty(['opencode/child-session-updates']); expect(metas[1]).toMatchObject({ 'opencode/child-session-updates': true, parameterizedModelPicker: true }); }); + it('advertises form elicitation only when enabled', async () => { + transportState.calls.length = 0; + await new AcpSdkBackend({ command: 'opencode', args: ['acp'] }).initialize(); + await new AcpSdkBackend({ command: 'opencode', args: ['acp'], elicitationForm: true }).initialize(); + + const capabilities = transportState.calls + .filter((call) => call.method === 'initialize') + .map((call) => (call.params as { clientCapabilities: Record }).clientCapabilities); + expect(capabilities).toHaveLength(2); + expect(capabilities[0]).not.toHaveProperty('elicitation'); + expect(capabilities[1]).toMatchObject({ elicitation: { form: {} } }); + }); }); diff --git a/cli/src/agent/backends/acp/AcpSdkBackend.ts b/cli/src/agent/backends/acp/AcpSdkBackend.ts index a0aa8534..86f95ee2 100644 --- a/cli/src/agent/backends/acp/AcpSdkBackend.ts +++ b/cli/src/agent/backends/acp/AcpSdkBackend.ts @@ -1,5 +1,5 @@ import type { AgentFlavor } from '@hapi/protocol'; -import type { AgentBackend, AgentMessage, AgentSessionConfig, PermissionRequest, PermissionResponse, PromptContent } from '@/agent/types'; +import type { AgentBackend, AgentMessage, AgentSessionConfig, FormElicitationRequest, FormElicitationResponse, PermissionRequest, PermissionResponse, PromptContent } from '@/agent/types'; import { asString, isObject } from '@hapi/protocol'; import { AcpStdioTransport, type AcpStderrError } from './AcpStdioTransport'; import { AcpMessageHandler, type AcpTextChunkMode } from './AcpMessageHandler'; @@ -13,6 +13,11 @@ type PendingPermission = { resolve: (result: { outcome: { outcome: string; optionId?: string } }) => void; }; +type PendingElicitation = { + sessionId: string; + settle: (response: FormElicitationResponse) => void; +}; + type AcpPromptUsage = { inputTokens: number; outputTokens: number; @@ -99,6 +104,8 @@ export class AcpSdkBackend implements AgentBackend { private permissionHandler: ((request: PermissionRequest) => void) | null = null; private stderrErrorHandler: ((error: AcpStderrError) => void) | null = null; private readonly pendingPermissions = new Map(); + private formElicitationHandler: ((request: FormElicitationRequest) => Promise) | null = null; + private readonly pendingElicitations = new Set(); private readonly sessionModelsMetadata = new Map(); private readonly sessionConfigOptions = new Map(); private readonly sessionInfoRefreshTimers = new Map>(); @@ -193,6 +200,13 @@ export class AcpSdkBackend implements AgentBackend { * child in the background). */ childSessionUpdates?: boolean; + /** + * Advertise `elicitation.form` so the agent may ask the user structured + * questions through `elicitation/create`. Opt-in because the handler + * for that request is flavor specific; without a handler the agent + * would wait on a request nobody answers. + */ + elicitationForm?: boolean; textChunkMode?: AcpTextChunkMode; flavor?: AgentFlavor; }) {} @@ -241,12 +255,19 @@ export class AcpSdkBackend implements AgentBackend { return await this.handlePermissionRequest(params, requestId); }); + if (this.options.elicitationForm) { + this.transport.registerRequestHandler('elicitation/create', async (params) => { + return await this.handleElicitationRequest(params); + }); + } + const response = await withRetry( () => this.transport!.sendRequest('initialize', { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false, + ...(this.options.elicitationForm ? { elicitation: { form: {} } } : {}), _meta: { // Cursor ACP exposes Composer's non-fast/fast choice as separate // `model` + `fast` config options only when the client advertises @@ -829,6 +850,9 @@ export class AcpSdkBackend implements AgentBackend { } this.transport.sendNotification('session/cancel', { sessionId }); + // The agent keeps waiting on an unanswered form until its request is + // answered, so cancelling the prompt must settle the form too. + this.settlePendingElicitations(sessionId); } /** @@ -961,6 +985,55 @@ export class AcpSdkBackend implements AgentBackend { this.permissionHandler = handler; } + onFormElicitation(handler: (request: FormElicitationRequest) => Promise): void { + this.formElicitationHandler = handler; + } + + private settlePendingElicitations(sessionId?: string): void { + for (const pending of Array.from(this.pendingElicitations)) { + if (sessionId === undefined || pending.sessionId === sessionId) { + pending.settle({ action: 'cancel' }); + } + } + } + + private async handleElicitationRequest(params: unknown): Promise { + const cancel: FormElicitationResponse = { action: 'cancel' }; + if (!isObject(params) || params.mode !== 'form' || !this.formElicitationHandler) { + return cancel; + } + const sessionId = asString(params.sessionId); + if (!sessionId || !isObject(params.requestedSchema)) { + return cancel; + } + + const request: FormElicitationRequest = { + sessionId, + ...(asString(params.toolCallId) ? { toolCallId: asString(params.toolCallId) as string } : {}), + message: asString(params.message) ?? '', + requestedSchema: params.requestedSchema + }; + + return await new Promise((resolve) => { + const pending: PendingElicitation = { + sessionId, + settle: (response) => { + this.pendingElicitations.delete(pending); + resolve(response); + } + }; + this.pendingElicitations.add(pending); + this.agentActivityListener?.(true); + this.formElicitationHandler!(request).then( + (response) => pending.settle(response), + (error) => { + logger.warn('[ACP] form elicitation handler failed; cancelling', error); + pending.settle(cancel); + } + ); + }); + } + onStderrError(handler: (error: AcpStderrError) => void): void { this.stderrErrorHandler = handler; } @@ -1107,6 +1180,7 @@ export class AcpSdkBackend implements AgentBackend { this.sessionAvailableCommands.clear(); this.autoPermissionModeEnabled = null; this.notifyResponseComplete(); + this.settlePendingElicitations(); await this.transport.close(); this.transport = null; } diff --git a/cli/src/agent/backends/acp/__fixtures__/agy-question-turn.json b/cli/src/agent/backends/acp/__fixtures__/agy-question-turn.json new file mode 100644 index 00000000..1f5c0efe --- /dev/null +++ b/cli/src/agent/backends/acp/__fixtures__/agy-question-turn.json @@ -0,0 +1,304 @@ +{ + "source": "agy 1.5.3 `agy acp`, Gemini 3.8 Flash (Low), recorded 2026-11-09: ask_question with clientCapabilities.elicitation.form advertised; the probe accepted the second option and also sent free text", + "frames": [ + { + "t": 0.0, + "direction": "client->agy", + "message": { + "jsonrpc": "2.0", + "id": 104, + "method": "session/prompt", + "params": { + "sessionId": "agy-conv-1", + "prompt": [ + { + "type": "text", + "text": "Respond in English only. Use your ask_question tool to ask me one multiple-choice question: do I prefer RED or BLUE? Then reply with my answer in one word." + } + ] + } + } + }, + { + "t": 0.08, + "direction": "agy->client", + "message": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "agy-conv-1", + "update": { + "sessionUpdate": "user_message_chunk", + "content": { + "type": "text", + "text": "Respond in English only. Use your ask_question tool to ask me one multiple-choice question: do I prefer RED or BLUE? Then reply with my answer in one word." + } + } + } + } + }, + { + "t": 2.97, + "direction": "agy->client", + "message": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "agy-conv-1", + "update": { + "sessionUpdate": "tool_call", + "toolCallId": "call_q", + "name": "ask_question", + "args": { + "questions": [ + { + "is_multi_select": false, + "options": [ + "(Recommended) RED", + "BLUE" + ], + "question": "Do you prefer RED or BLUE?" + } + ] + }, + "status": "in_progress", + "kind": "other", + "title": "Run ask_question", + "rawInput": { + "questions": [ + { + "is_multi_select": false, + "options": [ + "(Recommended) RED", + "BLUE" + ], + "question": "Do you prefer RED or BLUE?" + } + ] + } + } + } + } + }, + { + "t": 3.12, + "direction": "agy->client", + "message": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "agy-conv-1", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "call_q", + "name": "ask_question", + "args": { + "questions": [ + { + "is_multi_select": false, + "options": [ + "(Recommended) RED", + "BLUE" + ], + "question": "Do you prefer RED or BLUE?" + } + ] + }, + "status": "pending", + "kind": "other", + "title": "Run ask_question", + "rawInput": { + "questions": [ + { + "is_multi_select": false, + "options": [ + "(Recommended) RED", + "BLUE" + ], + "question": "Do you prefer RED or BLUE?" + } + ] + } + } + } + } + }, + { + "t": 3.12, + "direction": "agy->client", + "message": { + "jsonrpc": "2.0", + "method": "elicitation/create", + "params": { + "sessionId": "agy-conv-1", + "toolCallId": "call_q", + "mode": "form", + "message": "The agent has a question.", + "requestedSchema": { + "type": "object", + "properties": { + "q1": { + "type": "string", + "title": "Do you prefer RED or BLUE?", + "oneOf": [ + { + "const": "1", + "title": "(Recommended) RED" + }, + { + "const": "2", + "title": "BLUE" + } + ] + }, + "q1_other": { + "type": "string", + "title": "Other", + "description": "Optional free-form answer to: Do you prefer RED or BLUE?" + } + } + } + }, + "id": "1" + } + }, + { + "t": 3.12, + "direction": "client->agy", + "message": { + "jsonrpc": "2.0", + "id": "1", + "result": { + "action": "accept", + "content": { + "q1": "2", + "q1_other": "BLUE" + } + } + } + }, + { + "t": 3.12, + "direction": "agy->client", + "message": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "agy-conv-1", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "call_q", + "name": "ask_question", + "args": { + "questions": [ + { + "is_multi_select": false, + "options": [ + "(Recommended) RED", + "BLUE" + ], + "question": "Do you prefer RED or BLUE?" + } + ] + }, + "status": "in_progress", + "kind": "other", + "title": "Run ask_question", + "rawInput": { + "questions": [ + { + "is_multi_select": false, + "options": [ + "(Recommended) RED", + "BLUE" + ], + "question": "Do you prefer RED or BLUE?" + } + ] + } + } + } + } + }, + { + "t": 3.15, + "direction": "agy->client", + "message": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "agy-conv-1", + "update": { + "sessionUpdate": "tool_call_update", + "toolCallId": "call_q", + "name": "ask_question", + "args": { + "questions": [ + { + "is_multi_select": false, + "options": [ + "(Recommended) RED", + "BLUE" + ], + "question": "Do you prefer RED or BLUE?" + } + ] + }, + "status": "completed", + "kind": "other", + "title": "Run ask_question", + "rawInput": { + "questions": [ + { + "is_multi_select": false, + "options": [ + "(Recommended) RED", + "BLUE" + ], + "question": "Do you prefer RED or BLUE?" + } + ] + } + } + } + } + }, + { + "t": 5.86, + "direction": "agy->client", + "message": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "agy-conv-1", + "update": { + "sessionUpdate": "agent_message_chunk", + "content": { + "type": "text", + "text": "BLUE" + } + } + } + } + }, + { + "t": 6.0, + "direction": "agy->client", + "message": { + "jsonrpc": "2.0", + "result": { + "stopReason": "end_turn", + "usage": { + "inputTokens": 30352, + "outputTokens": 47, + "cachedReadTokens": 0, + "cachedWriteTokens": 0, + "thoughtTokens": 0, + "totalTokens": 30399 + } + }, + "id": 104 + } + } + ] +} diff --git a/cli/src/agent/types.ts b/cli/src/agent/types.ts index 6c902ac4..c777b7f8 100644 --- a/cli/src/agent/types.ts +++ b/cli/src/agent/types.ts @@ -103,6 +103,28 @@ export type PermissionResponse = | { outcome: 'selected'; optionId: string } | { outcome: 'cancelled' }; +/** Agent-initiated `elicitation/create` in form mode (structured user input). */ +export type FormElicitationRequest = { + sessionId: string; + /** Tool call that triggered the form, when the agent links one. */ + toolCallId?: string; + message: string; + /** JSON-Schema-like object schema; shape is owned by the agent. */ + requestedSchema: unknown; +}; + +export type FormElicitationContent = Record; + +/** + * `decline` is the user refusing to answer; `cancel` covers every other + * non-answer: dismissed, aborted, or unavailable. Agents may record the two + * differently. + */ +export type FormElicitationResponse = + | { action: 'accept'; content: FormElicitationContent } + | { action: 'decline' } + | { action: 'cancel' }; + export type AgentSessionModelDescriptor = { modelId: string; name?: string; @@ -132,6 +154,12 @@ export interface AgentBackend { cancelPrompt(sessionId: string): Promise; respondToPermission(sessionId: string, request: PermissionRequest, response: PermissionResponse): Promise; onPermissionRequest(handler: (request: PermissionRequest) => void): void; + /** + * Register the handler for agent form elicitations. The returned promise + * stays pending until the user answers; backends settle it with `cancel` + * on abort and disconnect. + */ + onFormElicitation?(handler: (request: FormElicitationRequest) => Promise): void; disconnect(): Promise; } diff --git a/cli/src/agy/agyAcpRemoteLauncher.question.replay.test.ts b/cli/src/agy/agyAcpRemoteLauncher.question.replay.test.ts new file mode 100644 index 00000000..e765091e --- /dev/null +++ b/cli/src/agy/agyAcpRemoteLauncher.question.replay.test.ts @@ -0,0 +1,142 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { RPC_METHODS } from '@hapi/protocol/rpcMethods'; +import { MessageQueue2 } from '@/utils/MessageQueue2'; +import { hashObject } from '@/utils/deterministicJson'; +import type { ApiSessionClient } from '@/api/apiSession'; +import { AcpStdioTransport } from '@/agent/backends/acp/AcpStdioTransport'; +import agyQuestionTurn from '@/agent/backends/acp/__fixtures__/agy-question-turn.json'; +import { AgySession } from './session'; +import type { AgyMode } from './types'; +import { AgyAcpRemoteLauncher } from './agyAcpRemoteLauncher'; +import { createAgyAcpBackend } from './utils/agyAcpBackend'; + +vi.mock('@/ui/ink/RemoteModeDisplay', () => ({ RemoteModeDisplay: () => null })); +vi.mock('@/ui/logger', () => ({ logger: { debug: vi.fn(), warn: vi.fn(), info: vi.fn() } })); + +type Frame = { t: number; direction: string; message: Record }; +const frames = agyQuestionTurn.frames as Frame[]; +const prompt = frames[0]!; +const promptText = ((prompt.message.params as { prompt: Array<{ text: string }> }).prompt)[0]!.text; +const elicitationIndex = frames.findIndex((frame) => frame.message.method === 'elicitation/create'); +const result = frames.find((frame) => frame.direction === 'agy->client' && 'result' in frame.message)!; +const tick = () => new Promise((resolve) => setTimeout(resolve, 5)); + +/** Plays agy's side of the recorded question turn and records the client's answer. */ +class ReplayTransport { + private notify: (method: string, params: unknown) => void = () => {}; + private readonly requestHandlers = new Map Promise>(); + initializeParams: Record | null = null; + answer: unknown = undefined; + + onNotification(handler: (method: string, params: unknown) => void): void { + this.notify = handler; + } + onStderrError(): void {} + registerRequestHandler(method: string, handler: (params: unknown, id: string | number | null) => Promise): void { + this.requestHandlers.set(method, handler); + } + isAlive(): boolean { + return true; + } + sendNotification(): void {} + async close(): Promise {} + + async sendRequest(method: string, params?: unknown): Promise { + switch (method) { + case 'initialize': + this.initializeParams = params as Record; + return { protocolVersion: 1, agentCapabilities: { loadSession: true } }; + case 'session/new': + return { sessionId: 'agy-conv-1', models: { availableModels: [], currentModelId: 'gemini-3.8-flash-low' } }; + case 'session/prompt': + for (const [index, frame] of frames.entries()) { + if (frame.direction !== 'agy->client' || 'result' in frame.message) continue; + await tick(); + if (index === elicitationIndex) { + const handler = this.requestHandlers.get('elicitation/create')!; + this.answer = await handler(frame.message.params, frame.message.id as string); + continue; + } + this.notify('session/update', frame.message.params); + } + return (result.message as { result: unknown }).result; + default: + return {}; + } + } +} + +function makeClient() { + const handlers = new Map Promise>(); + return { + sessionId: 'hapi-session', + rpcHandlerManager: { + handlers, + registerHandler: vi.fn((method: string, handler: (payload?: unknown) => Promise) => { + handlers.set(method, handler); + }), + unregisterHandler: vi.fn() + }, + updateMetadata: vi.fn(), + updateAgentState: vi.fn(), + sendSessionEvent: vi.fn(), + sendAgentMessage: vi.fn(), + sendClaudeSessionMessage: vi.fn(), + emitMessagesConsumed: vi.fn(), + emitSteerIndeterminate: vi.fn(), + setSteerDeliveryState: vi.fn(async () => true), + getMetadata: vi.fn(() => null), + keepAlive: vi.fn(), + emitSessionReady: vi.fn() + }; +} + +function agentRequests(client: ReturnType): Record { + const state = client.updateAgentState.mock.calls + .reduce((current, [update]) => (update as (s: object) => object)(current), {} as object) as { requests?: Record }; + return state.requests ?? {}; +} + +describe('AgyAcpRemoteLauncher replaying a recorded agy 1.5.3 question', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('asks through the question card and answers agy with the chosen option', async () => { + const transport = new ReplayTransport(); + vi.spyOn(AcpStdioTransport, 'create').mockResolvedValue(transport as unknown as AcpStdioTransport); + const queue = new MessageQueue2((mode) => hashObject(mode)); + const client = makeClient(); + const session = new AgySession({ + api: {} as never, + client: client as unknown as ApiSessionClient, + path: '/tmp/agy-project', + logPath: '/tmp/agy.log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + // Even here a question waits for the user. + permissionMode: 'always-proceed' + }); + queue.push(promptText, { permissionMode: 'always-proceed' }, 'first'); + const launcher = new AgyAcpRemoteLauncher(session, { createBackend: createAgyAcpBackend }); + const run = launcher.launch(); + + await vi.waitFor(() => expect(agentRequests(client).call_q).toMatchObject({ + tool: 'AskUserQuestion', + arguments: { questions: [{ question: 'Do you prefer RED or BLUE?', multiSelect: false, options: [{ label: '(Recommended) RED' }, { label: 'BLUE' }] }] } + }), { timeout: 5000 }); + expect(transport.initializeParams).toMatchObject({ clientCapabilities: { elicitation: { form: {} } } }); + expect(client.sendAgentMessage).toHaveBeenCalledWith(expect.objectContaining({ type: 'tool-call', callId: 'call_q', name: 'AskUserQuestion' })); + + await client.rpcHandlerManager.handlers.get(RPC_METHODS.Permission)!({ id: 'call_q', approved: true, answers: { '0': ['BLUE'] } }); + await vi.waitFor(() => expect(client.sendSessionEvent).toHaveBeenCalledWith({ type: 'ready' }), { timeout: 10_000 }); + queue.close(); + await run; + + expect(transport.answer).toEqual({ action: 'accept', content: { q1: '2' } }); + expect(client.sendAgentMessage).toHaveBeenCalledWith(expect.objectContaining({ type: 'message', message: 'BLUE' })); + }, 20_000); +}); diff --git a/cli/src/agy/agyAcpRemoteLauncher.test.ts b/cli/src/agy/agyAcpRemoteLauncher.test.ts index 8b6585ba..ab68ce8f 100644 --- a/cli/src/agy/agyAcpRemoteLauncher.test.ts +++ b/cli/src/agy/agyAcpRemoteLauncher.test.ts @@ -3,7 +3,7 @@ import { RPC_METHODS } from '@hapi/protocol/rpcMethods'; import { MessageQueue2 } from '@/utils/MessageQueue2'; import { hashObject } from '@/utils/deterministicJson'; import type { ApiSessionClient } from '@/api/apiSession'; -import type { AgentMessage, PermissionRequest, PromptContent } from '@/agent/types'; +import type { AgentMessage, FormElicitationRequest, FormElicitationResponse, PermissionRequest, PromptContent } from '@/agent/types'; import type { AcpSdkBackend } from '@/agent/backends/acp'; import { ACP_INDETERMINATE_SYMBOL } from '@/agent/backends/acp/AcpStdioTransport'; import agySteeredTurn from '@/agent/backends/acp/__fixtures__/agy-steered-turn.json'; @@ -165,6 +165,15 @@ class FakeAgyBackend { this.echo = listener; } onStderrError(): void {} + formElicitationHandler: ((request: FormElicitationRequest) => Promise) | null = null; + onFormElicitation(handler: (request: FormElicitationRequest) => Promise): void { + this.formElicitationHandler = handler; + } + /** agy's `elicitation/create`, as the ACP backend hands it to the handler. */ + elicit(params: { sessionId: string; toolCallId?: string; message: string; requestedSchema: unknown }): Promise { + const { sessionId, toolCallId, message, requestedSchema } = params; + return this.formElicitationHandler!({ sessionId, ...(toolCallId ? { toolCallId } : {}), message, requestedSchema }); + } permissionHandler: ((request: PermissionRequest) => void) | null = null; readonly permissionResponses: unknown[] = []; onPermissionRequest(handler: (request: PermissionRequest) => void): void { @@ -1470,7 +1479,7 @@ describe('AgyAcpRemoteLauncher permissions', () => { // agy rejects a prompt while an approval is open (-32603). expect(await steer({ localId: 'steer-1' })).toEqual({ steered: false, - error: 'Antigravity is waiting for an approval; answer it, then steer' + error: 'Antigravity is waiting for your approval or answer; respond to it, then steer' }); expect(backend.steerPrompts).toEqual([]); expect(client.setSteerDeliveryState).not.toHaveBeenCalled(); @@ -2015,3 +2024,194 @@ describe('AgyAcpRemoteLauncher steer state matrix', () => { await run; }); }); + +describe('AgyAcpRemoteLauncher questions (agy ask_question)', () => { + type Handlers = Map Promise>; + // Recorded from agy 1.5.3 with form elicitation advertised. + const questionCall = { + type: 'tool_call' as const, id: 'call_q', name: 'Run ask_question', kind: 'other', status: 'pending' as const, title: 'Run ask_question', + input: { questions: [{ is_multi_select: false, options: ['(Recommended) RED', 'BLUE'], question: 'Do you prefer RED or BLUE?' }] } + }; + const elicitation = { + sessionId: 'agy-conv-new', toolCallId: 'call_q', mode: 'form', message: 'The agent has a question.', + requestedSchema: { type: 'object', properties: { + q1: { type: 'string', title: 'Do you prefer RED or BLUE?', oneOf: [{ const: '1', title: '(Recommended) RED' }, { const: '2', title: 'BLUE' }] }, + q1_other: { type: 'string', title: 'Other', description: 'Optional free-form answer to: Do you prefer RED or BLUE?' } + } } + }; + const card = { + questions: [{ + question: 'Do you prefer RED or BLUE?', header: null, multiSelect: false, + options: [{ label: '(Recommended) RED', description: null }, { label: 'BLUE', description: null }] + }] + }; + + async function askedTurn(permissionMode: AgyMode['permissionMode'] = 'request-review') { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + let answer!: Promise; + let finish!: () => void; + backend.promptScripts.push(async (onUpdate) => { + onUpdate(questionCall); + answer = backend.elicit(elicitation); + await new Promise((resolve) => { finish = resolve; }); + }); + queue.push('ask me', { permissionMode }, 'first'); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(Object.keys(agentState(client).requests ?? {})).toEqual(['call_q'])); + const rpc = (method: string) => (client.rpcHandlerManager.handlers as Handlers).get(method)!; + return { session, queue, client, backend, run, rpc, answer: () => answer, finish: () => finish() }; + } + + it('shows agy\'s question as the question card on its own tool call', async () => { + const { queue, client, run, finish } = await askedTurn(); + expect(agentState(client).requests).toMatchObject({ call_q: { tool: 'AskUserQuestion', arguments: card } }); + expect(client.sendAgentMessage).toHaveBeenCalledWith(expect.objectContaining({ + type: 'tool-call', callId: 'call_q', name: 'AskUserQuestion', input: card + })); + finish(); + queue.close(); + await run; + }); + + it('answers agy with the chosen option only', async () => { + const { queue, run, rpc, answer, finish } = await askedTurn(); + await rpc(RPC_METHODS.Permission)({ id: 'call_q', approved: true, answers: { '0': ['BLUE'] } }); + await expect(answer()).resolves.toEqual({ action: 'accept', content: { q1: '2' } }); + finish(); + queue.close(); + await run; + }); + + it('declines when the user denies the question', async () => { + const { queue, run, rpc, answer, finish } = await askedTurn(); + await rpc(RPC_METHODS.Permission)({ id: 'call_q', approved: false, decision: 'denied' }); + await expect(answer()).resolves.toEqual({ action: 'decline' }); + finish(); + queue.close(); + await run; + }); + + it.each(['always-proceed', 'acceptEdits', 'plan'] as const)('waits for the user even in %s', async (mode) => { + const { queue, run, answer, finish } = await askedTurn(mode); + let settled = false; + void answer().then(() => { settled = true; }); + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(settled).toBe(false); + finish(); + queue.close(); + await run; + }); + + it('refuses a steer while the question is open', async () => { + const { queue, run, rpc, finish } = await askedTurn(); + queue.push('also lint', REVIEW, 'steer-1'); + expect(await rpc(RPC_METHODS.SteerQueuedMessage)({ localId: 'steer-1' })).toEqual({ + steered: false, + error: 'Antigravity is waiting for your approval or answer; respond to it, then steer' + }); + expect(queue.size()).toBe(1); + finish(); + queue.close(); + await run; + }); + + it('cancels the question on Stop', async () => { + const { queue, run, rpc, answer, backend, finish } = await askedTurn(); + backend.onCancel = () => finish(); + await rpc(RPC_METHODS.Abort)(); + await expect(answer()).resolves.toEqual({ action: 'cancel' }); + queue.close(); + await run; + }); + + it('cancels the question when the session ends', async () => { + const { session, queue, client, run, answer, backend, finish } = await askedTurn(); + backend.onDisconnect = () => finish(); + await session.kill(); + await expect(answer()).resolves.toEqual({ action: 'cancel' }); + // A question the stopped process still sends is not shown. + await expect(backend.elicit({ ...elicitation, toolCallId: 'call_late' })).resolves.toEqual({ action: 'cancel' }); + expect(agentState(client).requests ?? {}).toEqual({}); + queue.close(); + await run; + }); + + it('declines rather than sending an empty answer when an approval carries none', async () => { + const { queue, run, rpc, answer, finish } = await askedTurn(); + await rpc(RPC_METHODS.Permission)({ id: 'call_q', approved: true }); + await expect(answer()).resolves.toEqual({ action: 'decline' }); + finish(); + queue.close(); + await run; + }); + + it('asks under a fresh id when agy\'s tool call id is already waiting for the user', async () => { + const { client, queue, run, rpc, backend, answer, finish } = await askedTurn(); + const second = backend.elicit(elicitation); + await vi.waitFor(() => expect(Object.keys(agentState(client).requests ?? {})).toHaveLength(2)); + const freshId = Object.keys(agentState(client).requests ?? {}).find((id) => id !== 'call_q')!; + await rpc(RPC_METHODS.Permission)({ id: freshId, approved: true, answers: { '0': ['BLUE'] } }); + await expect(second).resolves.toEqual({ action: 'accept', content: { q1: '2' } }); + await rpc(RPC_METHODS.Permission)({ id: 'call_q', approved: true, answers: { '0': ['(Recommended) RED'] } }); + await expect(answer()).resolves.toEqual({ action: 'accept', content: { q1: '1' } }); + finish(); + queue.close(); + await run; + }); + + it('asks under a fresh id when agy\'s tool call id was already answered', async () => { + const { client, queue, run, rpc, backend, answer, finish } = await askedTurn(); + await rpc(RPC_METHODS.Permission)({ id: 'call_q', approved: true, answers: { '0': ['BLUE'] } }); + await expect(answer()).resolves.toEqual({ action: 'accept', content: { q1: '2' } }); + + const again = backend.elicit(elicitation); + await vi.waitFor(() => expect(Object.keys(agentState(client).requests ?? {})).toHaveLength(1)); + const id = Object.keys(agentState(client).requests ?? {})[0]!; + // Clients hide a pending request whose id is already completed. + expect(id).not.toBe('call_q'); + await rpc(RPC_METHODS.Permission)({ id, approved: true, answers: { '0': ['(Recommended) RED'] } }); + await expect(again).resolves.toEqual({ action: 'accept', content: { q1: '1' } }); + finish(); + queue.close(); + await run; + }); + + it('cancels a question that arrives after Stop', async () => { + const { queue, run, rpc, answer, backend, finish } = await askedTurn(); + backend.onCancel = () => {}; + await rpc(RPC_METHODS.Abort)(); + await expect(answer()).resolves.toEqual({ action: 'cancel' }); + // At once, not when agy is restarted after the hard-stop timeout. + const late = backend.elicit({ ...elicitation, toolCallId: 'call_late' }); + await expect(Promise.race([late, new Promise((resolve) => setTimeout(() => resolve('still open'), 200))])) + .resolves.toEqual({ action: 'cancel' }); + finish(); + queue.close(); + await run; + }); + + it('cancels a question that arrives after the stopped turn has finished', async () => { + const { client, queue, run, rpc, answer, backend, finish } = await askedTurn(); + backend.onCancel = () => finish(); + await rpc(RPC_METHODS.Abort)(); + await expect(answer()).resolves.toEqual({ action: 'cancel' }); + await new Promise((resolve) => setTimeout(resolve, 100)); + const late = backend.elicit({ ...elicitation, toolCallId: 'call_late2' }); + await expect(Promise.race([late, new Promise((resolve) => setTimeout(() => resolve('still open'), 300))])) + .resolves.toEqual({ action: 'cancel' }); + expect(Object.keys(agentState(client).requests ?? {})).not.toContain('call_late2'); + queue.close(); + await run; + }); + + it('cancels a form that is not a question', async () => { + const { queue, run, backend, finish } = await askedTurn(); + await expect(backend.elicit({ + sessionId: 'agy-conv-new', message: 'Sign in', requestedSchema: { type: 'object', properties: { name: { type: 'string' } } } + })).resolves.toEqual({ action: 'cancel' }); + finish(); + queue.close(); + await run; + }); +}); diff --git a/cli/src/agy/agyAcpRemoteLauncher.ts b/cli/src/agy/agyAcpRemoteLauncher.ts index 59290ed8..a28363fe 100644 --- a/cli/src/agy/agyAcpRemoteLauncher.ts +++ b/cli/src/agy/agyAcpRemoteLauncher.ts @@ -1,10 +1,11 @@ import React from 'react'; +import { randomUUID } from 'node:crypto'; import { RPC_METHODS, splitAgyModelSelection } from '@hapi/protocol'; import { logger } from '@/ui/logger'; import { RemoteModeDisplay } from '@/ui/ink/RemoteModeDisplay'; import { convertAgentMessage } from '@/agent/messageConverter'; import { createAcpSessionTitleSync, registerAcpSessionTitleSync } from '@/agent/acpSessionTitle'; -import type { AgentMessage, PermissionRequest, PromptContent } from '@/agent/types'; +import type { AgentMessage, FormElicitationRequest, FormElicitationResponse, PermissionRequest, PromptContent } from '@/agent/types'; import type { AcpSdkBackend } from '@/agent/backends/acp'; import { isAcpIndeterminateError } from '@/agent/backends/acp/AcpStdioTransport'; import { AcpPermissionHandler } from '@/modules/common/permission/AcpPermissionHandler'; @@ -18,6 +19,13 @@ import type { AgySession } from './session'; import { AGY_BACKGROUND_COMMAND_RESULT, mapAgyToolCall, mapAgyToolResult } from './agyToolCards'; import type { AgyMode, PermissionMode } from './types'; import { createAgyAcpBackend } from './utils/agyAcpBackend'; +import { + QUESTION_TOOL_NAME, + agyQuestionContent, + parseAgyQuestionForm, + questionCardInput, + questionCardInputFromToolCall +} from './agyQuestion'; type UsageMessage = Extract; @@ -144,6 +152,17 @@ export function isAgyQuestionRequest(request: PermissionRequest): boolean { return Array.isArray(input?.questions) || /\bask_question\b/.test(request.title ?? ''); } +/** agy's ask_question tool call (titled "Run ask_question"), as the question card. */ +function asQuestionCard(message: AgentMessage): { message: AgentMessage; shownLabels: string[][] | null } { + if (message.type !== 'tool_call' || !/\bask_question\b/.test(message.name)) return { message, shownLabels: null }; + const input = questionCardInputFromToolCall(message.input); + if (!input) return { message, shownLabels: null }; + return { + message: { ...message, name: QUESTION_TOOL_NAME, input }, + shownLabels: input.questions.map((question) => question.options.map((option) => option.label)) + }; +} + /** agy acp did not come up; the caller may fall back to another transport. */ export class AgyAcpStartError extends Error {} @@ -191,6 +210,8 @@ export class AgyAcpRemoteLauncher extends RemoteLauncherBase { private readonly cancelHardStopMs: number; private readonly killSettleMs: number; private turnSettled: Promise | null = null; + // Option labels each question card showed, by agy tool call id. + private readonly questionLabels = new Map(); private backend: AcpSdkBackend | null = null; private permissionHandler: AcpPermissionHandler | null = null; // agy's own tool name by call id, to map results of the calls it started. @@ -349,6 +370,7 @@ export class AgyAcpRemoteLauncher extends RemoteLauncherBase { } } ); + backend.onFormElicitation((request) => this.handleQuestion(request)); void backend.refreshSessionInfo(acpSessionId, session.path); } catch (error) { // A half-started process must not serve later turns; the next turn @@ -372,6 +394,8 @@ export class AgyAcpRemoteLauncher extends RemoteLauncherBase { backend.onPermissionRequest((request) => { void backend.respondToPermission(request.sessionId, request, { outcome: 'cancelled' }); }); + // Its late questions must not open cards in the next process's session. + backend.onFormElicitation(async () => ({ action: 'cancel' })); const handler = this.permissionHandler; this.permissionHandler = null; await handler?.cancelAll('Antigravity stopped'); @@ -505,6 +529,7 @@ export class AgyAcpRemoteLauncher extends RemoteLauncherBase { await this.waitForSteers(turn); this.closeBackgroundCommands(turn); } finally { + this.questionLabels.clear(); // After a Stop or a lost agy process, agy may have dropped a steer // it had not echoed yet. const endedCleanly = !turn.aborted && !this.backendLost; @@ -584,9 +609,9 @@ export class AgyAcpRemoteLauncher extends RemoteLauncherBase { if (!turn || turn.aborted || !backend || !acpSessionId || this.shouldExit) { return { steered: false, error: 'No active steerable turn' }; } - // agy rejects a prompt while an approval is open. + // agy rejects a prompt while an approval or a question is open. if (this.permissionHandler?.hasPendingRequests()) { - return { steered: false, error: 'Antigravity is waiting for an approval; answer it, then steer' }; + return { steered: false, error: 'Antigravity is waiting for your approval or answer; respond to it, then steer' }; } const taken = session.queue.takeByLocalId(localId); if (!taken) return { steered: false, error: 'Message not in queue' }; @@ -644,6 +669,11 @@ export class AgyAcpRemoteLauncher extends RemoteLauncherBase { await restoreQueued(); return { steered: false, error: 'Active turn changed' }; } + // An approval or a question may have opened while the hub answered. + if (this.permissionHandler?.hasPendingRequests()) { + await restoreQueued(); + return { steered: false, error: 'Antigravity is waiting for your approval or answer; respond to it, then steer' }; + } let steer: ReturnType; try { @@ -778,10 +808,42 @@ export class AgyAcpRemoteLauncher extends RemoteLauncherBase { turn.sawActivity = true; turn.acknowledge(); this.trackToolWindow(turn, message); - this.forwardAgentMessage(message); + this.forwardAgentMessage(this.showQuestionCard(message)); } } + /** + * agy's ask_question, shown as the question card on its tool call. Never + * answered automatically: the user's choice goes back as agy's answer. + */ + private async handleQuestion(request: FormElicitationRequest): Promise { + const form = parseAgyQuestionForm(request); + const permissionHandler = this.permissionHandler; + // Not shown to the user, so not declined by them either. + if (!form || !permissionHandler) return { action: 'cancel' }; + // Only a live turn can be asked on: after Stop, or once that turn has + // ended, nothing would settle the card. + if (!this.turn || this.turn.aborted || this.shouldExit) return { action: 'cancel' }; + // Keyed by agy's tool call so the card shows on it, unless that id + // was already used for a request. + const id = form.toolCallId && !permissionHandler.isUsed(form.toolCallId) + ? form.toolCallId + : `agy-question-${randomUUID()}`; + const shownLabels = form.toolCallId ? this.questionLabels.get(form.toolCallId) : undefined; + const answer = await permissionHandler.askUser(id, QUESTION_TOOL_NAME, questionCardInput(form.questions)); + if (answer.decision === 'abort') return { action: 'cancel' }; + if (answer.decision === 'denied') return { action: 'decline' }; + const content = agyQuestionContent(form.questions, answer.answers, shownLabels); + // An approval without a usable answer must not become an empty answer. + return Object.keys(content).length > 0 ? { action: 'accept', content } : { action: 'decline' }; + } + + private showQuestionCard(message: AgentMessage): AgentMessage { + const shown = asQuestionCard(message); + if (shown.shownLabels && message.type === 'tool_call') this.questionLabels.set(message.id, shown.shownLabels); + return shown.message; + } + private trackToolWindow(turn: AgyTurn, message: AgentMessage): void { if (message.type !== 'tool_call' && message.type !== 'tool_result') return; // Only a command agy reports as running counts: one still waiting diff --git a/cli/src/agy/agyQuestion.test.ts b/cli/src/agy/agyQuestion.test.ts new file mode 100644 index 00000000..fc0abc27 --- /dev/null +++ b/cli/src/agy/agyQuestion.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, it } from 'vitest'; +import { + agyQuestionContent, + parseAgyQuestionForm, + questionCardInput, + questionCardInputFromToolCall +} from './agyQuestion'; + +// Recorded from agy 1.5.3 (`elicitation/create` after `ask_question`). +const singleChoice = { + sessionId: 'agy-conv-1', + toolCallId: 'call_1', + mode: 'form', + message: 'The agent has a question.', + requestedSchema: { + type: 'object', + properties: { + q1: { + type: 'string', + title: 'Do you prefer RED or BLUE?', + oneOf: [{ const: '1', title: '(Recommended) RED' }, { const: '2', title: 'BLUE' }] + }, + q1_other: { type: 'string', title: 'Other', description: 'Optional free-form answer to: Do you prefer RED or BLUE?' } + } + } +}; + +const twoQuestions = { + sessionId: 'agy-conv-1', + toolCallId: 'call_2', + mode: 'form', + message: 'The agent has 2 questions.', + requestedSchema: { + type: 'object', + properties: { + q1: { + type: 'array', + title: 'Which colors do you like?', + items: { anyOf: [{ const: '1', title: 'RED' }, { const: '2', title: 'GREEN' }, { const: '3', title: 'BLUE' }] } + }, + q1_other: { type: 'string', title: 'Other' }, + q2: { type: 'string', title: 'Light or dark theme?', oneOf: [{ const: '1', title: 'LIGHT' }, { const: '2', title: 'DARK' }] }, + q2_other: { type: 'string', title: 'Other' } + } + } +}; + +describe('agy question form', () => { + it('reads a single-choice question and shows it as the question card', () => { + const form = parseAgyQuestionForm(singleChoice)!; + expect(form).toEqual({ + toolCallId: 'call_1', + questions: [{ + key: 'q1', + otherKey: 'q1_other', + question: 'Do you prefer RED or BLUE?', + choices: [{ value: '1', label: '(Recommended) RED' }, { value: '2', label: 'BLUE' }], + multiSelect: false + }] + }); + expect(questionCardInput(form.questions)).toEqual({ + questions: [{ + question: 'Do you prefer RED or BLUE?', + header: null, + options: [{ label: '(Recommended) RED', description: null }, { label: 'BLUE', description: null }], + multiSelect: false, + allowFreeText: true + }] + }); + }); + + it('marks the card as not allowing free text when the form has no qN_other', () => { + const params = structuredClone(singleChoice) as any; + delete params.requestedSchema.properties.q1_other; + const form = parseAgyQuestionForm(params)!; + + expect(questionCardInput(form.questions).questions[0]?.allowFreeText).toBe(false); + }); + + it('reads several questions in order, with multi-select', () => { + const form = parseAgyQuestionForm(twoQuestions)!; + expect(form.questions.map((question) => [question.key, question.multiSelect, question.choices.length])) + .toEqual([['q1', true, 3], ['q2', false, 2]]); + }); + + it('ignores elicitations that are not agy questions', () => { + expect(parseAgyQuestionForm({ mode: 'url', url: 'https://example.com' })).toBeNull(); + expect(parseAgyQuestionForm({ mode: 'form', requestedSchema: { type: 'object', properties: { name: { type: 'string' } } } })).toBeNull(); + expect(parseAgyQuestionForm(null)).toBeNull(); + }); + + it('answers with the chosen option value only, so agy records the bare label', () => { + const form = parseAgyQuestionForm(singleChoice)!; + // An approval hook reads agy's "A1: