From 38b6540bedee00a1e9e79d12af15a8a9b73f0f80 Mon Sep 17 00:00:00 2001 From: Junmo Kim Date: Mon, 9 Nov 2026 13:05:15 +0900 Subject: [PATCH] feat(agy): show Antigravity's tool calls as the canonical tool cards (#2330) * docs(agy): say request-review follows agy's toolPermission setting On agy acp, HAPI's request-review is agy's default mode, which asks only as agy's own toolPermission setting says. With toolPermission set to always-proceed, agy runs commands and edits without asking, so HAPI shows no approval prompts, and HAPI cannot override that per session. The guide now says so, and says what acceptEdits and plan do on agy. It also notes that always-proceed approves a request a PreToolUse hook marks force_ask: agy sends it as an ordinary approval request, with nothing that says it came from a hook. * feat(acp): carry the agent's own tool name and args on tool calls Some ACP agents send their own tool name and args next to the standard title, kind and rawInput (agy: name, args). Pass them through as nativeName and nativeArgs so a launcher can pick a card by the real tool instead of a free-text title. Agents that send no name are unaffected. * feat(agy): show agy ACP tool calls as the canonical tool cards Map agy's own tool names to the cards the other flavors use: run_command to Bash (with a clean stdout result), read_file to Read, edit_file to an Edit diff, write_file to Write, search_web to WebSearch, invoke_subagent to Task and call_mcp_tool to the mcp card. A write_file artifact (plan or task list) is shown as a plan instead of a hidden brain-directory path. A command agy moves to the background gets no further update after end_turn, so its card spun until the next message. Show it as running in the background at end_turn; the real result replaces that when agy reports it in a later prompt's stream. --- .../backends/acp/AcpMessageHandler.test.ts | 48 +++++++ .../agent/backends/acp/AcpMessageHandler.ts | 20 ++- cli/src/agent/types.ts | 4 + cli/src/agy/agyAcpRemoteLauncher.test.ts | 114 +++++++++++++++ cli/src/agy/agyAcpRemoteLauncher.ts | 49 ++++++- cli/src/agy/agyToolCards.test.ts | 132 +++++++++++++++++ cli/src/agy/agyToolCards.ts | 134 ++++++++++++++++++ docs/guide/agents.md | 17 ++- 8 files changed, 510 insertions(+), 8 deletions(-) create mode 100644 cli/src/agy/agyToolCards.test.ts create mode 100644 cli/src/agy/agyToolCards.ts diff --git a/cli/src/agent/backends/acp/AcpMessageHandler.test.ts b/cli/src/agent/backends/acp/AcpMessageHandler.test.ts index a099e416..6a48cc64 100644 --- a/cli/src/agent/backends/acp/AcpMessageHandler.test.ts +++ b/cli/src/agent/backends/acp/AcpMessageHandler.test.ts @@ -25,6 +25,54 @@ describe('AcpMessageHandler', () => { vi.restoreAllMocks(); }); + it('carries the agent\'s own tool name and args on tool calls and their updates', () => { + const messages: AgentMessage[] = []; + const handler = new AcpMessageHandler((message) => messages.push(message)); + const args = { CommandLine: 'ls -la', toolSummary: 'List files' }; + + handler.handleUpdate({ + sessionUpdate: ACP_SESSION_UPDATE_TYPES.toolCall, + toolCallId: 'tool-n', + name: 'run_command', + args, + title: 'ls -la', + kind: 'execute', + rawInput: args, + status: 'in_progress' + }); + // A later update that omits the name keeps the stored one. + handler.handleUpdate({ + sessionUpdate: ACP_SESSION_UPDATE_TYPES.toolCallUpdate, + toolCallId: 'tool-n', + title: 'ls -la', + kind: 'execute', + rawInput: args, + status: 'in_progress' + }); + + const calls = messages.filter((m): m is Extract => m.type === 'tool_call'); + expect(calls).toHaveLength(2); + for (const call of calls) { + expect(call).toMatchObject({ nativeName: 'run_command', nativeArgs: args }); + } + }); + + it('leaves nativeName off tool calls from agents that do not send a name', () => { + const messages: AgentMessage[] = []; + const handler = new AcpMessageHandler((message) => messages.push(message)); + + handler.handleUpdate({ + sessionUpdate: ACP_SESSION_UPDATE_TYPES.toolCall, + toolCallId: 'tool-o', + title: 'Read', + rawInput: { path: 'README.md' }, + status: 'in_progress' + }); + + expect(messages[0]).not.toHaveProperty('nativeName'); + expect(messages[0]).not.toHaveProperty('nativeArgs'); + }); + it('does not synthesize {status} output when tool completes without payload', () => { const messages: AgentMessage[] = []; const handler = new AcpMessageHandler((message) => messages.push(message)); diff --git a/cli/src/agent/backends/acp/AcpMessageHandler.ts b/cli/src/agent/backends/acp/AcpMessageHandler.ts index 72851fc5..23815643 100644 --- a/cli/src/agent/backends/acp/AcpMessageHandler.ts +++ b/cli/src/agent/backends/acp/AcpMessageHandler.ts @@ -496,6 +496,9 @@ function mayBeUnfinishedControlEnvelope(text: string): boolean { export class AcpMessageHandler { private readonly toolCalls = new Map(); + // The agent's own tool name and args by call id (agy sends `name`/`args` + // on every tool_call and tool_call_update). + private readonly nativeTools = new Map(); private acceptingUpdates = true; private bufferedText = ''; // Stable stream id for a text segment that has already been emitted by an @@ -943,6 +946,17 @@ export class AcpMessageHandler { return source; } + private nativeToolFields(toolCallId: string, update: Record): { nativeName?: string; nativeArgs?: unknown } { + const nativeName = asString(update.name); + if (nativeName) { + this.nativeTools.set(toolCallId, { + nativeName, + nativeArgs: update.args !== undefined ? update.args : update.rawInput + }); + } + return this.nativeTools.get(toolCallId) ?? {}; + } + private handleToolCall(update: Record): void { const toolCallId = asString(update.toolCallId); if (!toolCallId) return; @@ -993,7 +1007,8 @@ export class AcpMessageHandler { input, status, ...(asString(update.title) ? { title: asString(update.title)! } : {}), - ...(asString(update.kind) ? { kind: asString(update.kind)! } : {}) + ...(asString(update.kind) ? { kind: asString(update.kind)! } : {}), + ...this.nativeToolFields(toolCallId, update) }); } @@ -1005,7 +1020,8 @@ export class AcpMessageHandler { const existing = this.toolCalls.get(toolCallId); const presentation = { ...(asString(update.title) ? { title: asString(update.title)! } : {}), - ...(asString(update.kind) ? { kind: asString(update.kind)! } : {}) + ...(asString(update.kind) ? { kind: asString(update.kind)! } : {}), + ...this.nativeToolFields(toolCallId, update) }; if (isUsableRawInput(update.rawInput)) { diff --git a/cli/src/agent/types.ts b/cli/src/agent/types.ts index 9cff3e6c..6c902ac4 100644 --- a/cli/src/agent/types.ts +++ b/cli/src/agent/types.ts @@ -59,6 +59,10 @@ export type AgentMessage = title?: string; kind?: string; progress?: unknown; + // The agent's own tool name and args, when it sends them next to the + // standard fields (agy does: `name`, `args`). + nativeName?: string; + nativeArgs?: unknown; } | { type: 'tool_result'; id: string; output: unknown; status: 'completed' | 'failed' } | { diff --git a/cli/src/agy/agyAcpRemoteLauncher.test.ts b/cli/src/agy/agyAcpRemoteLauncher.test.ts index 640bb6aa..8b6585ba 100644 --- a/cli/src/agy/agyAcpRemoteLauncher.test.ts +++ b/cli/src/agy/agyAcpRemoteLauncher.test.ts @@ -1511,6 +1511,120 @@ describe('AgyAcpRemoteLauncher questions', () => { }); }); +describe('AgyAcpRemoteLauncher tool cards', () => { + const toolMessages = (client: ReturnType) => client.sendAgentMessage.mock.calls + .map(([message]) => message as Record) + .filter((message) => message.type === 'tool-call' || message.type === 'tool-call-result'); + + it('shows agy tools as their canonical cards and cleans the command result', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + backend.promptScripts.push(async (onUpdate) => { + const args = { CommandLine: 'ls', WaitMsBeforeAsync: 5000, toolSummary: 'List files' }; + onUpdate({ + type: 'tool_call', id: 'c1', name: 'ls', input: args, status: 'in_progress', + title: 'ls', kind: 'execute', nativeName: 'run_command', nativeArgs: args + }); + onUpdate({ + type: 'tool_result', id: 'c1', status: 'completed', + output: { output: 'Command exited with code 0.\n\nCommand output:\na\r\nb\r\n', exit_code: 0 } + }); + onUpdate({ type: 'turn_complete', stopReason: 'end_turn' }); + }); + queue.push('go', REVIEW, 'a'); + queue.close(); + + await launch(session, [backend]).run; + + expect(toolMessages(client)).toMatchObject([ + { type: 'tool-call', callId: 'c1', name: 'Bash', input: { command: 'ls', description: 'List files' } }, + { type: 'tool-call-result', callId: 'c1', output: { stdout: 'a\nb', exit_code: 0 } } + ]); + }); + + it('closes a command agy moved to the background at the end of the turn, and the real result replaces it', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + const args = { CommandLine: 'sleep 30', WaitMsBeforeAsync: 5000 }; + backend.promptScripts.push(async (onUpdate) => { + onUpdate({ + type: 'tool_call', id: 'bg', name: 'sleep 30', input: args, status: 'in_progress', + kind: 'execute', nativeName: 'run_command', nativeArgs: args + }); + onUpdate({ type: 'turn_complete', stopReason: 'end_turn' }); + }); + backend.promptScripts.push(async (onUpdate) => { + // agy reports the completion inside the next prompt's stream. + onUpdate({ + type: 'tool_call', id: 'bg', name: 'sleep 30', input: args, status: 'in_progress', + kind: 'execute', nativeName: 'run_command', nativeArgs: args + }); + onUpdate({ + type: 'tool_result', id: 'bg', status: 'completed', + output: { output: 'Command exited with code 0.\n\nCommand output:\ndone', exit_code: 0 } + }); + onUpdate({ type: 'turn_complete', stopReason: 'end_turn' }); + }); + queue.push('start it', REVIEW, 'a'); + const { run } = launch(session, [backend]); + await vi.waitFor(() => expect(sessionEvents(client)).toContainEqual({ type: 'ready' })); + expect(toolMessages(client).filter((m) => m.type === 'tool-call-result')).toMatchObject([ + { callId: 'bg', output: { stdout: expect.stringContaining('background') }, is_error: false } + ]); + + queue.push('next', REVIEW, 'b'); + await vi.waitFor(() => expect(backend.prompts).toHaveLength(2)); + queue.close(); + await run; + + const results = toolMessages(client).filter((m) => m.type === 'tool-call-result'); + expect(results).toHaveLength(2); + expect(results[1]).toMatchObject({ callId: 'bg', output: { stdout: 'done', exit_code: 0 } }); + }); + + it('does not call a command that never started a background command', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + backend.promptScripts.push(async (onUpdate) => { + const args = { CommandLine: 'rm -rf x' }; + onUpdate({ + type: 'tool_call', id: 'd', name: 'rm -rf x', input: args, status: 'in_progress', + kind: 'execute', nativeName: 'run_command', nativeArgs: args + }); + // Waiting for approval; the user denies and agy ends the turn. + onUpdate({ + type: 'tool_call', id: 'd', name: 'rm -rf x', input: args, status: 'pending', + kind: 'execute', nativeName: 'run_command', nativeArgs: args + }); + onUpdate({ type: 'turn_complete', stopReason: 'end_turn' }); + }); + queue.push('go', REVIEW, 'a'); + queue.close(); + + await launch(session, [backend]).run; + + expect(toolMessages(client).filter((m) => m.type === 'tool-call-result')).toEqual([]); + }); + + it('does not close a command that finished or a turn that was cancelled', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + backend.promptScripts.push(async (onUpdate) => { + onUpdate({ + type: 'tool_call', id: 'x', name: 'x', input: {}, status: 'in_progress', + kind: 'execute', nativeName: 'run_command', nativeArgs: { CommandLine: 'x' } + }); + onUpdate({ type: 'turn_complete', stopReason: 'cancelled' }); + }); + queue.push('go', REVIEW, 'a'); + queue.close(); + + await launch(session, [backend]).run; + + expect(toolMessages(client).filter((m) => m.type === 'tool-call-result')).toEqual([]); + }); +}); + describe('agy ACP helpers', () => { it('maps HAPI permission modes to agy ACP modes', () => { expect(agyAcpModeForPermission('request-review')).toBe('default'); diff --git a/cli/src/agy/agyAcpRemoteLauncher.ts b/cli/src/agy/agyAcpRemoteLauncher.ts index 53f0c01a..59290ed8 100644 --- a/cli/src/agy/agyAcpRemoteLauncher.ts +++ b/cli/src/agy/agyAcpRemoteLauncher.ts @@ -15,6 +15,7 @@ import { } from '@/modules/common/remote/RemoteLauncherBase'; import type { SessionEffort, SessionModel } from '@/api/types'; 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'; @@ -155,6 +156,9 @@ type AgyTurn = { // Tool runs and waits for the user, which are not generation time. idleWindows: TimeWindow[]; toolWindows: Map; + // Commands agy has not reported an end for; one still open at end_turn was + // moved to the background. + openCommands: Set; usage: UsageMessage | null; // Any agent output proves agy accepted the prompt. sawActivity: boolean; @@ -189,6 +193,8 @@ export class AgyAcpRemoteLauncher extends RemoteLauncherBase { private turnSettled: Promise | null = null; 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. + private readonly nativeToolNames = new Map(); private acpSessionId: string | null = null; private abortController = new AbortController(); /** agy's own model at session start; the target of the "Default" selection. */ @@ -419,6 +425,7 @@ export class AgyAcpRemoteLauncher extends RemoteLauncherBase { answeredAt: null, idleWindows: [], toolWindows: new Map(), + openCommands: new Set(), usage: null, sawActivity: false, // AgySession does not acknowledge on dequeue: a message counts as @@ -496,6 +503,7 @@ export class AgyAcpRemoteLauncher extends RemoteLauncherBase { // ends only when every open request has settled. Steers sent // during this wait extend it. await this.waitForSteers(turn); + this.closeBackgroundCommands(turn); } finally { // After a Stop or a lost agy process, agy may have dropped a steer // it had not echoed yet. @@ -530,6 +538,24 @@ export class AgyAcpRemoteLauncher extends RemoteLauncherBase { } } + /** + * agy sends nothing more for a command it moved to the background: its + * completion arrives inside a later prompt's stream. Until then the card + * would spin, so it shows the command as running in the background; the + * real result replaces this one when it comes. + */ + private closeBackgroundCommands(turn: AgyTurn): void { + if (turn.aborted || this.backendLost || turn.stopReason !== 'end_turn') return; + for (const id of turn.openCommands) { + const placeholder = convertAgentMessage( + { type: 'tool_result', id, output: AGY_BACKGROUND_COMMAND_RESULT, status: 'completed' }, + this.currentModelId + ); + if (placeholder) this.session.sendAgentMessage(placeholder); + } + turn.openCommands.clear(); + } + private async waitForSteers(turn: AgyTurn): Promise { while (turn.steers.length > 0) { const pending = [...turn.steers]; @@ -758,6 +784,13 @@ export class AgyAcpRemoteLauncher extends RemoteLauncherBase { 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 + // for approval (pending) did not start, whatever happens to the turn. + if (message.type === 'tool_call' && message.nativeName === 'run_command' && message.status === 'in_progress') { + turn.openCommands.add(message.id); + } else if (message.status !== 'in_progress') { + turn.openCommands.delete(message.id); + } const now = Date.now(); let window = turn.toolWindows.get(message.id); if (!window) { @@ -769,7 +802,7 @@ export class AgyAcpRemoteLauncher extends RemoteLauncherBase { } private forwardAgentMessage(message: AgentMessage): void { - const converted = convertAgentMessage(message, this.currentModelId); + const converted = convertAgentMessage(this.toCanonicalToolMessage(message), this.currentModelId); if (converted) this.session.sendAgentMessage(converted); switch (message.type) { @@ -800,6 +833,20 @@ export class AgyAcpRemoteLauncher extends RemoteLauncherBase { } } + /** agy's own tool name picks the card; the open-command bookkeeping rides along. */ + private toCanonicalToolMessage(message: AgentMessage): AgentMessage { + if (message.type === 'tool_call') { + if (message.nativeName) this.nativeToolNames.set(message.id, message.nativeName); + return mapAgyToolCall(message); + } + if (message.type === 'tool_result') { + const nativeName = this.nativeToolNames.get(message.id); + this.nativeToolNames.delete(message.id); + return mapAgyToolResult(message, nativeName); + } + return message; + } + private reportTurnError(message: string): void { this.session.sendSessionEvent({ type: 'error', message }); this.messageBuffer.addMessage(message, 'status'); diff --git a/cli/src/agy/agyToolCards.test.ts b/cli/src/agy/agyToolCards.test.ts new file mode 100644 index 00000000..46b96087 --- /dev/null +++ b/cli/src/agy/agyToolCards.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, it } from 'vitest'; +import type { AgentMessage } from '@/agent/types'; +import { mapAgyToolCall, mapAgyToolResult, AGY_BACKGROUND_COMMAND_RESULT } from './agyToolCards'; + +type ToolCall = Extract; + +function call(nativeName: string, args: Record, extra: Partial = {}): ToolCall { + return { + type: 'tool_call', + id: 'call_1', + name: 'some title', + input: args, + status: 'in_progress', + title: 'some title', + kind: 'other', + nativeName, + nativeArgs: args, + ...extra + }; +} + +describe('mapAgyToolCall', () => { + it('maps run_command to Bash and drops the bookkeeping args', () => { + const mapped = mapAgyToolCall(call('run_command', { + CommandLine: 'ls -la', Cwd: '/tmp/x', WaitMsBeforeAsync: 5000, toolSummary: 'List files' + })); + expect(mapped).toMatchObject({ + name: 'Bash', + input: { command: 'ls -la', cwd: '/tmp/x', description: 'List files' } + }); + expect(mapped.input).not.toHaveProperty('WaitMsBeforeAsync'); + }); + + it('maps read_file to Read', () => { + expect(mapAgyToolCall(call('read_file', { Path: '/a/b.md' }))).toMatchObject({ + name: 'Read', input: { file_path: '/a/b.md' } + }); + }); + + it('maps edit_file to an Edit diff input', () => { + expect(mapAgyToolCall(call('edit_file', { Path: '/a/b.md', Target: 'two', Replacement: 'TWO' }))).toMatchObject({ + name: 'Edit', input: { file_path: '/a/b.md', old_string: 'two', new_string: 'TWO' } + }); + }); + + it('maps write_file to Write', () => { + expect(mapAgyToolCall(call('write_file', { Path: '/a/c.md', Content: 'hello\n' }))).toMatchObject({ + name: 'Write', input: { file_path: '/a/c.md', content: 'hello\n' } + }); + }); + + it('shows an artifact write as a plan without the brain path', () => { + const mapped = mapAgyToolCall(call('write_file', { + Path: '/home/u/.gemini/antigravity-cli/brain/abc/plan.md', + Content: '- [ ] step 1\n', + ArtifactMetadata: { Summary: 'Haiku Plan', UserFacing: true, RequestFeedback: false } + }, { title: 'File ../../../.gemini/antigravity-cli/brain/abc/plan.md' })); + expect(mapped.name).toBe('ExitPlanMode'); + expect(mapped.input).toEqual({ plan: '# Haiku Plan\n\n- [ ] step 1\n' }); + expect(JSON.stringify({ title: mapped.title, input: mapped.input })).not.toContain('brain'); + }); + + it('keeps an artifact that starts with its own heading as is', () => { + const mapped = mapAgyToolCall(call('write_file', { + Path: '/x/brain/p.md', Content: '# Own title\n\nbody', + ArtifactMetadata: { Summary: 'Other' } + })); + expect(mapped.input).toEqual({ plan: '# Own title\n\nbody' }); + }); + + it('maps search_web to WebSearch', () => { + expect(mapAgyToolCall(call('search_web', { query: 'acp elicitation' }))).toMatchObject({ + name: 'WebSearch', input: { query: 'acp elicitation' } + }); + }); + + it('maps invoke_subagent to Task', () => { + expect(mapAgyToolCall(call('invoke_subagent', { + Prompt: 'Draw it', Role: 'Image Generator', TypeName: 'image-generator', Model: 'inherit' + }))).toMatchObject({ + name: 'Task', + input: { description: 'Image Generator', prompt: 'Draw it', subagent_type: 'image-generator' } + }); + }); + + it('maps call_mcp_tool to the mcp card, parsing string arguments', () => { + expect(mapAgyToolCall(call('call_mcp_tool', { + ServerName: 'hapi', ToolName: 'change_title', Arguments: { title: 'T' } + }))).toMatchObject({ name: 'mcp__hapi__change_title', input: { title: 'T' } }); + expect(mapAgyToolCall(call('call_mcp_tool', { + ServerName: 'hapi', ToolName: 'change_title', Arguments: '{"title":"S"}' + }))).toMatchObject({ name: 'mcp__hapi__change_title', input: { title: 'S' } }); + }); + + it('leaves unknown agy tools, ask_question and calls without a native name alone', () => { + const unknown = call('manage_task', { a: 1 }); + expect(mapAgyToolCall(unknown)).toBe(unknown); + const question = call('ask_question', { questions: [] }); + expect(mapAgyToolCall(question)).toBe(question); + const plain: ToolCall = { type: 'tool_call', id: 'x', name: 'Read', input: {}, status: 'pending' }; + expect(mapAgyToolCall(plain)).toBe(plain); + }); + + it('keeps id, status, title and kind of the mapped call', () => { + const mapped = mapAgyToolCall(call('read_file', { Path: '/a' }, { status: 'pending', kind: 'read' })); + expect(mapped).toMatchObject({ type: 'tool_call', id: 'call_1', status: 'pending', title: 'some title', kind: 'read' }); + }); +}); + +describe('mapAgyToolResult', () => { + it('strips run_command framing into stdout', () => { + const result: Extract = { + type: 'tool_result', id: 'c', status: 'completed', + output: { output: 'Command exited with code 0.\n\nCommand output:\nhello\r\nworld\r\n', exit_code: 0 } + }; + expect(mapAgyToolResult(result, 'run_command')).toMatchObject({ + output: { stdout: 'hello\nworld', exit_code: 0 } + }); + }); + + it('leaves other results alone', () => { + const result: Extract = { + type: 'tool_result', id: 'c', status: 'completed', output: { a: 1 } + }; + expect(mapAgyToolResult(result, 'read_file')).toBe(result); + expect(mapAgyToolResult(result, undefined)).toBe(result); + }); + + it('exposes the background placeholder as Bash stdout', () => { + expect(AGY_BACKGROUND_COMMAND_RESULT).toMatchObject({ stdout: expect.stringContaining('background') }); + }); +}); diff --git a/cli/src/agy/agyToolCards.ts b/cli/src/agy/agyToolCards.ts new file mode 100644 index 00000000..8aaf9a44 --- /dev/null +++ b/cli/src/agy/agyToolCards.ts @@ -0,0 +1,134 @@ +import type { AgentMessage } from '@/agent/types'; + +type ToolCall = Extract; +type ToolResult = Extract; + +/** + * agy's `agy acp` titles its tool calls with free text (the command line, + * `File notes.md`, `Run invoke_subagent`), so no web card matches them. It + * also sends its own tool name and args, which identify the tool; this maps + * them to the canonical cards the other flavors use. Names differ from agy's + * stream-json tools (read_file / edit_file / write_file there are view_file / + * replace_file_content / write_to_file). + */ + +/** Shown for a command agy moved to the background until its real result arrives. */ +export const AGY_BACKGROUND_COMMAND_RESULT = { + stdout: 'Running in the background. The result appears when agy reports it.' +} as const; + +function asRecord(value: unknown): Record | null { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? value as Record + : null; +} + +function asText(value: unknown): string | undefined { + return typeof value === 'string' && value !== '' ? value : undefined; +} + +function compact(input: Record): Record { + return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined && value !== null && value !== '')); +} + +function parseArguments(value: unknown): Record { + if (typeof value === 'string') { + try { + return asRecord(JSON.parse(value)) ?? {}; + } catch { + return {}; + } + } + return asRecord(value) ?? {}; +} + +/** An artifact write (plan, task list) lives in agy's private brain directory. */ +function artifactPlan(args: Record): string | null { + const metadata = asRecord(args.ArtifactMetadata); + if (!metadata) return null; + const content = asText(args.Content) ?? ''; + const summary = asText(metadata.Summary); + if (!summary || /^\s*#/.test(content)) return content; + return `# ${summary}\n\n${content}`; +} + +export function mapAgyToolCall(message: ToolCall): ToolCall { + const args = asRecord(message.nativeArgs); + if (!message.nativeName || !args) return message; + + let name: string; + let input: Record; + switch (message.nativeName) { + case 'run_command': + name = 'Bash'; + input = compact({ + command: args.CommandLine, + cwd: args.Cwd, + description: args.toolSummary + }); + break; + case 'read_file': + name = 'Read'; + input = compact({ file_path: args.Path }); + break; + case 'edit_file': + name = 'Edit'; + input = compact({ file_path: args.Path, old_string: args.Target, new_string: args.Replacement }); + break; + case 'write_file': { + const plan = artifactPlan(args); + if (plan !== null) { + name = 'ExitPlanMode'; + input = { plan }; + } else { + name = 'Write'; + input = compact({ file_path: args.Path, content: args.Content }); + } + break; + } + case 'search_web': + name = 'WebSearch'; + input = compact({ query: args.query }); + break; + case 'invoke_subagent': + name = 'Task'; + input = compact({ description: args.Role, prompt: args.Prompt, subagent_type: args.TypeName }); + break; + case 'call_mcp_tool': { + const server = asText(args.ServerName); + const tool = asText(args.ToolName); + if (!server || !tool) return message; + name = `mcp__${server}__${tool}`; + input = parseArguments(args.Arguments); + break; + } + default: + return message; + } + + // An artifact plan must not leak the brain path through the title. + if (name === 'ExitPlanMode') { + const { title: _title, ...rest } = message; + return { ...rest, name, input }; + } + return { ...message, name, input }; +} + +/** agy frames a command result as "Command exited with code N.\n\nCommand output:\n". */ +export function mapAgyToolResult(message: ToolResult, nativeName: string | undefined): ToolResult { + if (nativeName !== 'run_command') return message; + const output = asRecord(message.output); + const text = asText(output?.output); + if (!output || text === undefined) return message; + const body = text + .replace(/\r\n/g, '\n') + .replace(/^Command exited with code -?\d+\.\s*\n\s*Command output:\n?/, '') + .trimEnd(); + return { + ...message, + output: { + stdout: body, + ...(typeof output.exit_code === 'number' ? { exit_code: output.exit_code } : {}) + } + }; +} diff --git a/docs/guide/agents.md b/docs/guide/agents.md index 1285e018..3f764877 100644 --- a/docs/guide/agents.md +++ b/docs/guide/agents.md @@ -335,11 +335,18 @@ the prompt is loaded by DSH through its own `skill` tool and catalog. finishes any tool call already running, then continues the same turn with the new message. The turn's usage includes the steered part. - Permission modes map to agy's session modes: `request-review` is agy's - `default` mode, which follows agy's own permission settings and, on ACP, - shows its approval requests in HAPI; `acceptEdits` and `plan` are agy's - `accept-edits` and `plan` modes; `always-proceed` approves every request - automatically. On ACP, mode changes apply to the next message without + Permission modes map to agy's session modes. `request-review` is agy's + `default` mode, which asks only as agy's own `toolPermission` setting + (`~/.gemini/antigravity-cli/settings.json`) says; on ACP its approval + requests show in HAPI. With `toolPermission: always-proceed`, agy runs + commands and edits without asking, so HAPI shows no approval prompts; set + it to `request-review` in agy to approve each command and edit from HAPI. + HAPI cannot override this per session. `acceptEdits` is agy's + `accept-edits` mode, which also runs edits without asking, and `plan` is + agy's `plan` mode, which writes a plan instead of running commands or + edits. `always-proceed` approves every request automatically, including + one a PreToolUse hook marks `force_ask` (agy does not tell HAPI a request + came from a hook). On ACP, mode changes apply to the next message without restarting agy. Conversation titles come from agy; on ACP each response's details show the turn's token usage.