agy-delegate-mcp 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,27 @@ All notable changes to this project are documented here. The format follows
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [1.7.0] - 2026-11-23
10
+
11
+ ### Added
12
+
13
+ - `execution` in the delegate result: tool calls per kind, and the commands agy ran with exit codes
14
+ (the last 8 plus older failures, repeats folded into `runs`).
15
+ - `questions`: agy's open questions as `{question, options, multiSelect?, recommended?}[]`. Answer
16
+ by resuming with the answers in `spec`.
17
+ - `doctor` reports `client.protocolVersion`.
18
+
19
+ ### Changed
20
+
21
+ - agy is launched with `--disable-telemetry`; `ACP_AGENT_ARGS` replaces the arguments.
22
+ - MCP SDK v2 (`@modelcontextprotocol/server` 2.4.0): the server takes 2025-era and 2026-07-28
23
+ hosts.
24
+
25
+ ### Fixed
26
+
27
+ - A steer sent while agy's question is open is taken as its answer: the result is agy's reply, not
28
+ the question. A steer agy rejects leaves the question open.
29
+
9
30
  ## [1.6.0] - 2026-11-22
10
31
 
11
32
  ### Changed
package/SECURITY.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## What this plugin does
4
4
 
5
- `agy-delegate-mcp` spawns **agy** (`agy acp --dangerously-skip-permissions`) in your workspace,
5
+ `agy-delegate-mcp` spawns **agy** (`agy acp --dangerously-skip-permissions --disable-telemetry`) in your workspace,
6
6
  so agy approves its own tool calls, and the bridge **auto-approves every permission request**
7
7
  that still arrives over ACP, in every mode — `agent`, `plan` and `ask`. Each request is answered
8
8
  with the broadest allow option agy offered (`allow_always`, else `allow_once`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-delegate-mcp",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "mcpName": "io.github.andreilungeanu/agy-delegate-mcp",
5
5
  "type": "module",
6
6
  "description": "Delegate multi-file coding work from Claude Code, Codex, Copilot, or any MCP client to Google's Antigravity CLI (agy) — structured results, plan mode, and changed files.",
@@ -53,10 +53,11 @@
53
53
  "typecheck": "tsc -p tsconfig.json"
54
54
  },
55
55
  "dependencies": {
56
- "@modelcontextprotocol/sdk": "^1.23.0",
56
+ "@modelcontextprotocol/server": "^2.4.0",
57
57
  "zod": "^4.6.5"
58
58
  },
59
59
  "devDependencies": {
60
+ "@modelcontextprotocol/client": "^2.4.0",
60
61
  "@types/node": "^26.1.1",
61
62
  "typescript": "^7.0.2"
62
63
  }
package/src/acp-client.js CHANGED
@@ -186,6 +186,7 @@ export class AcpClient extends EventEmitter {
186
186
  const body = this._steerPrefix ? `${this._steerPrefix}\n\n${text}` : text;
187
187
  // Stamped, so it never rejects unobserved.
188
188
  this._steers.push(stampSettlement(this.peer.request("session/prompt", { sessionId, prompt: [{ type: "text", text: body }] })));
189
+ this.emit("steer");
189
190
  return "steered";
190
191
  }
191
192
  hasSteer() { return this._steers.length > 0; }
package/src/delegate.js CHANGED
@@ -197,6 +197,48 @@ export function readUsage(raws) {
197
197
  return { scope: "turn", ...Object.fromEntries(fields.map((k) => [k, reported.reduce((sum, raw) => sum + (isTokenCount(raw[k]) ? raw[k] : 0), 0)])) };
198
198
  }
199
199
 
200
+ // The newest commands, where a test run usually lands, plus older ones that failed.
201
+ export const RECENT_COMMANDS = 8;
202
+ export const OLDER_FAILED_COMMANDS = 5;
203
+ const MAX_COMMAND_CHARS = 150;
204
+
205
+ const commandFailed = (c) => (c.exitCode !== undefined && c.exitCode !== 0) || (c.status !== undefined && c.status !== "completed");
206
+
207
+ // agy reports a non-zero exit as completed, so exitCode is the outcome. agy's own files (the plan)
208
+ // are reported as plan and artifacts instead.
209
+ export function executionSummary(records) {
210
+ const calls = [...records.values()].filter((r) => !r.artifact);
211
+ if (!calls.length) return undefined;
212
+ // A Map, so a kind such as "constructor" or "__proto__" is counted, not read off Object.
213
+ const kinds = new Map();
214
+ for (const r of calls) kinds.set(r.kind || "other", (kinds.get(r.kind || "other") ?? 0) + 1);
215
+ // Keyed by the full text, so two commands sharing a truncated prefix stay apart. Re-inserting
216
+ // moves a command to its last run.
217
+ /** @type {Map<string, { runs: number, exitCode?: number, status?: string }>} */
218
+ const byText = new Map();
219
+ for (const r of calls) {
220
+ if (r.kind !== "execute") continue;
221
+ const text = String(r.command ?? r.title ?? "");
222
+ const runs = (byText.get(text)?.runs ?? 0) + 1;
223
+ byText.delete(text);
224
+ byText.set(text, { runs, exitCode: r.exitCode, status: r.status });
225
+ }
226
+ const all = [...byText].map(([text, c]) => ({ text, ...c }));
227
+ const recent = all.slice(-RECENT_COMMANDS);
228
+ const olderFailed = all.slice(0, -RECENT_COMMANDS).filter(commandFailed).slice(-OLDER_FAILED_COMMANDS);
229
+ const listed = [...olderFailed, ...recent].map((c) => ({
230
+ command: c.text.length > MAX_COMMAND_CHARS ? c.text.slice(0, MAX_COMMAND_CHARS) + "…" : c.text,
231
+ ...(c.exitCode !== undefined ? { exitCode: c.exitCode } : {}),
232
+ ...(c.status !== undefined && c.status !== "completed" ? { status: c.status } : {}),
233
+ ...(c.runs > 1 ? { runs: c.runs } : {}),
234
+ }));
235
+ /** @type {{ toolCalls: Record<string, number>, commands?: any[], commandsOmitted?: number }} */
236
+ const out = { toolCalls: Object.fromEntries(kinds) };
237
+ if (listed.length) out.commands = listed;
238
+ if (all.length > listed.length) out.commandsOmitted = all.length - listed.length;
239
+ return out;
240
+ }
241
+
200
242
  function modelOption(configOptions) {
201
243
  return (Array.isArray(configOptions) ? configOptions : []).find((o) => o?.id === "model");
202
244
  }
@@ -308,6 +350,16 @@ export async function runDelegate({
308
350
  supervisor.cancelSetup();
309
351
  };
310
352
  client.on?.("cancel", onCancel);
353
+ // agy takes the next prompt as its open question's answer, and can leave the call open. Closed as
354
+ // the steer goes out, so its reply is the result, and kept per steer to reopen if agy rejects it.
355
+ /** @type {any[][]} */
356
+ const closedBySteer = [];
357
+ const onSteer = () => {
358
+ const ids = state.openQuestionCalls();
359
+ for (const id of ids) state.updateToolStatus(id, "completed");
360
+ closedBySteer.push(ids);
361
+ };
362
+ client.on?.("steer", onSteer);
311
363
  const cancelledInSetup = { stopReason: "cancelled", replies: [], cancelledBeforePrompt: true };
312
364
 
313
365
  // The bridge cannot see inside a shell command, so silence is reported, not acted on.
@@ -373,6 +425,7 @@ export async function runDelegate({
373
425
  if (up.sessionUpdate === "tool_call" || up.sessionUpdate === "tool_call_update") {
374
426
  // An artifact is agy's own file (the plan, in its brain directory), not a workspace edit.
375
427
  const isArtifact = state.recordArtifact(up.rawInput ?? up.args);
428
+ state.recordToolCall(up, isArtifact);
376
429
  if (up.sessionUpdate === "tool_call") {
377
430
  state.startTool(up.toolCallId, up.status, up.name ?? up.title);
378
431
  const label = String(up.title || up.kind || "tool");
@@ -388,6 +441,10 @@ export async function runDelegate({
388
441
  } else {
389
442
  state.updateToolStatus(up.toolCallId, up.status);
390
443
  }
444
+ // The opening frame's questions win; an update fills them in when it had none.
445
+ if (state.isQuestion(up.toolCallId) && (up.sessionUpdate === "tool_call" || !state.questions.has(up.toolCallId))) {
446
+ state.recordQuestions(up.toolCallId, (up.rawInput ?? up.args)?.questions);
447
+ }
391
448
  if (!isArtifact) recordDiffs(up.content);
392
449
  }
393
450
  if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
@@ -512,6 +569,7 @@ export async function runDelegate({
512
569
  }
513
570
  const steer = client.takeSteer?.();
514
571
  if (!steer) break;
572
+ const closed = closedBySteer.shift() ?? [];
515
573
  const reply = await steer;
516
574
  if (reply.ok) {
517
575
  turn = reply.value;
@@ -521,6 +579,9 @@ export async function runDelegate({
521
579
  } else if (reply.seq < turnSeq) {
522
580
  // Refused before its target settled: that turn stands, and the warning tells the caller.
523
581
  steerWarnings.push(`a steer was rejected by agy and did not redirect the turn: ${reply.error?.message || String(reply.error)}`);
582
+ // Its questions stay closed if a steer queued behind it reaches agy.
583
+ if (closedBySteer.length) closedBySteer[0].push(...closed);
584
+ else for (const id of closed) state.reopenTool(id);
524
585
  } else {
525
586
  // Failed after taking the turn over: the turn failed, unless a steer queued behind it
526
587
  // succeeds.
@@ -546,6 +607,9 @@ export async function runDelegate({
546
607
  ? (state.sawToolCall ? "post-tool" : "tool-free-stream")
547
608
  : "none";
548
609
  const protocolWarnings = [];
610
+ // An open ask_question whose questions were read is reported in questions, not as a warning.
611
+ const questions = state.openQuestions();
612
+ const askedOnly = questions.length > 0 && state.backgroundToolCalls().length === 0;
549
613
  if (!finalMessageAvailable && state.activeToolCalls.size > 0) {
550
614
  // Measured cases (agy 1.5.14): a background command still running when the wait ran out, or an
551
615
  // ask_question waiting on the caller.
@@ -561,11 +625,13 @@ export async function runDelegate({
561
625
  ? ` agy moved it to the background, and it was still running after the bridge waited ${fmtDuration(backgroundWaited)}`
562
626
  + " (AGY_DELEGATE_BACKGROUND_WAIT_MS); it stops when the bridge stops agy."
563
627
  : ` agy ended the turn (${res?.stopReason}) with it still running; it stops when the bridge stops agy.`;
564
- protocolWarnings.push(
565
- `the turn ended with a tool call still running (${openLabel ?? "unnamed tool"}).`
566
- + cause
567
- + (result ? " result is agy's message from while it ran." : " agy sent no message while it ran.")
568
- );
628
+ if (!askedOnly) {
629
+ protocolWarnings.push(
630
+ `the turn ended with a tool call still running (${openLabel ?? "unnamed tool"}).`
631
+ + cause
632
+ + (result ? " result is agy's message from while it ran." : " agy sent no message while it ran.")
633
+ );
634
+ }
569
635
  } else if (!finalMessageAvailable && state.discardedResult) {
570
636
  result = state.discardedResult;
571
637
  resultSource = "pre-tool-fallback";
@@ -592,6 +658,9 @@ export async function runDelegate({
592
658
  // Absent means nothing reported, not nothing changed: shell edits emit no diff.
593
659
  const filesReported = normalizeAgentReportedFiles([...state.touched], workspace);
594
660
  if (filesReported.length) out.filesReportedByEditTools = filesReported;
661
+ if (questions.length) out.questions = questions;
662
+ const execution = executionSummary(state.toolCallRecords);
663
+ if (execution) out.execution = execution;
595
664
  // resultSource appears only as a caveat; resumed only when a resume took.
596
665
  if (resultSource !== "post-tool" && resultSource !== "tool-free-stream") out.resultSource = resultSource;
597
666
  if (!!resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
@@ -683,6 +752,7 @@ export async function runDelegate({
683
752
  clearInterval(heartbeat);
684
753
  signal?.removeEventListener("abort", onAbort);
685
754
  client.off?.("cancel", onCancel);
755
+ client.off?.("steer", onSteer);
686
756
  try { supervisor.finish(); } catch {}
687
757
  // Awaited, so agy has exited when the caller gets the result, or a warning says the exit was not
688
758
  // seen; otherwise agy still holds the workspace as its cwd (deleting it fails with EBUSY on
package/src/doctor.js CHANGED
@@ -163,7 +163,7 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
163
163
 
164
164
  /**
165
165
  * @param {{
166
- * getClientInfo?: () => { capabilities?: any, version?: any },
166
+ * getClientInfo?: () => { capabilities?: any, version?: any, protocolVersion?: string },
167
167
  * deep?: boolean,
168
168
  * spawnSpec?: { command: string, args: string[], options?: object },
169
169
  * clientFactory?: (opts: any) => any,
@@ -187,7 +187,7 @@ export async function runDoctor({
187
187
  signal,
188
188
  onClientReady,
189
189
  } = {}) {
190
- const { capabilities, version } = getClientInfo();
190
+ const { capabilities, version, protocolVersion } = getClientInfo();
191
191
  const agentProbe = await probeAgentVersion(spawnSpec, versionTimeoutMs, signal);
192
192
 
193
193
  /** @type {{ plugin: any, client: any, agent: any & { handshake?: any }, runtime: any, env: any }} */
@@ -197,6 +197,8 @@ export async function runDoctor({
197
197
  name: version?.name ?? null,
198
198
  version: version?.version ?? null,
199
199
  capabilities: capabilities ?? {},
200
+ // The MCP revision the host speaks: 2026-07-28 or a 2025-era one.
201
+ ...(typeof protocolVersion === "string" ? { protocolVersion } : {}),
200
202
  },
201
203
  agent: {
202
204
  found: agentProbe.found,
package/src/server.js CHANGED
@@ -2,8 +2,8 @@
2
2
  import process from "node:process";
3
3
  import { realpathSync } from "node:fs";
4
4
  import { fileURLToPath } from "node:url";
5
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+ import { McpServer, CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, PROTOCOL_VERSION_META_KEY } from "@modelcontextprotocol/server";
6
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
7
7
  import { z } from "zod";
8
8
  import { runDelegate as runDelegateDefault } from "./delegate.js";
9
9
  import { runDoctor as runDoctorDefault } from "./doctor.js";
@@ -31,7 +31,7 @@ function registerInFlight(map, sessionId, handle) {
31
31
  if (handles) handles.add(handle);
32
32
  else map.set(sessionId, new Set([handle]));
33
33
  }
34
- /** @returns {import("@modelcontextprotocol/sdk/types.js").CallToolResult} */
34
+ /** @returns {import("@modelcontextprotocol/server").CallToolResult} */
35
35
  function statusResult(status, sessionId) {
36
36
  return { content: [{ type: "text", text: JSON.stringify({ status, sessionId }) }] };
37
37
  }
@@ -82,6 +82,22 @@ export const delegateOutputShape = {
82
82
  context: z.object({ used: z.number(), size: z.number() }).strict().optional(),
83
83
  sessionId: z.string(),
84
84
  filesReportedByEditTools: z.array(z.string()).optional(),
85
+ questions: z.array(z.object({
86
+ question: z.string(),
87
+ options: z.array(z.string()),
88
+ multiSelect: z.boolean().optional(),
89
+ recommended: z.string().optional(),
90
+ }).strict()).optional(),
91
+ execution: z.object({
92
+ toolCalls: z.record(z.string(), z.number()),
93
+ commands: z.array(z.object({
94
+ command: z.string(),
95
+ exitCode: z.number().optional(),
96
+ status: z.string().optional(),
97
+ runs: z.number().optional(),
98
+ }).strict()).optional(),
99
+ commandsOmitted: z.number().optional(),
100
+ }).strict().optional(),
85
101
  resumed: z.boolean().optional(),
86
102
  cancelRequested: z.boolean().optional(),
87
103
  protocolWarnings: z.array(z.string()).optional(),
@@ -133,6 +149,7 @@ export const doctorOutputShape = {
133
149
  name: z.string().nullable(),
134
150
  version: z.string().nullable(),
135
151
  capabilities: z.record(z.string(), z.unknown()),
152
+ protocolVersion: z.string().optional(),
136
153
  }).passthrough(),
137
154
  agent: z.object(doctorAgentShape).passthrough(),
138
155
  runtime: z.object({
@@ -172,18 +189,18 @@ export function steerSession(map, seen, sessionId, message) {
172
189
 
173
190
  /**
174
191
  * @param {{
175
- * args: any, extra?: any,
192
+ * args: any, ctx?: any,
176
193
  * runDelegate: (opts: any) => Promise<any>,
177
194
  * inFlight: Map<string, Set<any>>,
178
195
  * pending?: Set<any>,
179
196
  * seenSessions?: Set<string>,
180
197
  * }} deps
181
- * @returns {Promise<import("@modelcontextprotocol/sdk/types.js").CallToolResult>}
198
+ * @returns {Promise<import("@modelcontextprotocol/server").CallToolResult>}
182
199
  */
183
- export async function runDelegateTool({ args, extra, runDelegate, inFlight, pending = new Set(), seenSessions = new Set() }) {
200
+ export async function runDelegateTool({ args, ctx, runDelegate, inFlight, pending = new Set(), seenSessions = new Set() }) {
184
201
  const { spec, mode, resumeSessionId, workspace, model, effort, contextFiles } = args;
185
202
 
186
- const progressToken = extra?._meta?.progressToken;
203
+ const progressToken = ctx?.mcpReq?._meta?.progressToken;
187
204
  /** @type {(message: string) => void} */
188
205
  let onProgress = () => {};
189
206
  if (progressToken != null) {
@@ -191,7 +208,7 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
191
208
  onProgress = (message) => {
192
209
  // An unhandled rejection would exit the server; the try catches a sync throw.
193
210
  try {
194
- Promise.resolve(extra.sendNotification({
211
+ Promise.resolve(ctx.mcpReq.notify({
195
212
  method: "notifications/progress",
196
213
  params: { progressToken, progress: ++progress, message },
197
214
  })).catch(() => {});
@@ -212,7 +229,7 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
212
229
  effort,
213
230
  contextFiles,
214
231
  onProgress,
215
- signal: extra?.signal,
232
+ signal: ctx?.mcpReq?.signal,
216
233
  onClientReady: (client) => {
217
234
  handle = { client, cancelRequested: false };
218
235
  pending.add(handle);
@@ -268,7 +285,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
268
285
  "delegate",
269
286
  {
270
287
  description:
271
- "Delegate a coding task to Antigravity's agy over ACP. Never shell out to agy — use this tool only. Auto-approves every permission the agent requests, in any mode and anywhere on disk. Clarifying questions arrive as prose in result — resume with resumeSessionId to answer. Leave model and effort unset unless the user explicitly asks. See the delegate skill.",
288
+ "Delegate a coding task to Antigravity's agy over ACP. Never shell out to agy — use this tool only. Auto-approves every permission the agent requests, in any mode and anywhere on disk. agy's clarifying questions arrive in questions — resume with resumeSessionId and the answers in spec. Leave model and effort unset unless the user explicitly asks. See the delegate skill.",
272
289
  inputSchema: delegateInputSchema,
273
290
  annotations: {
274
291
  title: "Delegate coding task to Antigravity",
@@ -278,7 +295,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
278
295
  openWorldHint: true,
279
296
  },
280
297
  },
281
- async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, pending, seenSessions })
298
+ async (args, ctx) => runDelegateTool({ args, ctx, runDelegate, inFlight, pending, seenSessions })
282
299
  );
283
300
 
284
301
  server.registerTool(
@@ -286,10 +303,10 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
286
303
  {
287
304
  description:
288
305
  "Best-effort cancel of an in-flight delegation by sessionId. session/cancel is advisory — the agent may finish the turn anyway, and the delegate result then carries cancelRequested. Status: cancelled, killed (agent process observed to exit), not-running (turn already ended, still resumable), not-found (id not in this process's recent session history).",
289
- inputSchema: {
306
+ inputSchema: z.object({
290
307
  sessionId: sessionIdInput,
291
308
  force: z.boolean().default(false).describe("Kill the agent process if the turn is still running after a short grace period."),
292
- },
309
+ }),
293
310
  annotations: {
294
311
  title: "Cancel Antigravity delegation",
295
312
  readOnlyHint: false,
@@ -355,10 +372,10 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
355
372
  {
356
373
  description:
357
374
  "Redirect an in-flight delegation by sessionId: message goes to agy as a new instruction for the running turn, and the delegate call returns the redirected turn's result. Status: steered (sent), not-ready (prompt not sent yet; retry), not-running (turn already ended — resume instead), not-found (id not in this process's recent session history).",
358
- inputSchema: {
375
+ inputSchema: z.object({
359
376
  sessionId: sessionIdInput,
360
377
  message: z.string().trim().min(1, "message must not be blank").describe("The new instruction for agy."),
361
- },
378
+ }),
362
379
  annotations: {
363
380
  title: "Steer Antigravity delegation",
364
381
  readOnlyHint: false,
@@ -375,12 +392,12 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
375
392
  {
376
393
  description:
377
394
  "Setup diagnostics: plugin version, MCP client capabilities, agy launcher resolution. Run when delegation fails or agent.found is false.",
378
- inputSchema: {
395
+ inputSchema: z.object({
379
396
  deep: z
380
397
  .boolean()
381
398
  .default(false)
382
399
  .describe("Run an ACP handshake (start → initialize → newSession) to verify the agent is usable and signed in; adds models, modes, the current model's options and the account tier."),
383
- },
400
+ }),
384
401
  annotations: {
385
402
  title: "Diagnose Antigravity delegation setup",
386
403
  readOnlyHint: true,
@@ -389,18 +406,15 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
389
406
  openWorldHint: false,
390
407
  },
391
408
  },
392
- async ({ deep }, extra) => {
409
+ async ({ deep }, ctx) => {
393
410
  // In pending while it runs, so shutdown stops doctor's agent too.
394
411
  let handle;
395
412
  try {
396
413
  const out = await runDoctor({
397
414
  deep,
398
- signal: extra?.signal,
415
+ signal: ctx?.mcpReq?.signal,
399
416
  onClientReady: (client) => { handle = { client }; pending.add(handle); },
400
- getClientInfo: () => ({
401
- capabilities: server.server.getClientCapabilities(),
402
- version: server.server.getClientVersion(),
403
- }),
417
+ getClientInfo: () => clientInfoOf(server, ctx),
404
418
  });
405
419
  return { content: [{ type: "text", text: JSON.stringify(out) }] };
406
420
  } finally {
@@ -412,6 +426,17 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
412
426
  return server;
413
427
  }
414
428
 
429
+ // A 2026-07-28 client sends its identity with each request; a 2025-era one sends it once, in
430
+ // initialize, which the server's getters return.
431
+ export function clientInfoOf(server, ctx) {
432
+ const envelope = ctx?.mcpReq?.envelope;
433
+ return {
434
+ capabilities: envelope?.[CLIENT_CAPABILITIES_META_KEY] ?? server.server.getClientCapabilities(),
435
+ version: envelope?.[CLIENT_INFO_META_KEY] ?? server.server.getClientVersion(),
436
+ protocolVersion: envelope?.[PROTOCOL_VERSION_META_KEY] ?? server.server.getNegotiatedProtocolVersion(),
437
+ };
438
+ }
439
+
415
440
  const __filename = fileURLToPath(import.meta.url);
416
441
  let isMain = false;
417
442
  if (process.argv[1]) {
@@ -482,7 +507,7 @@ export function installSignalCleanup(map, {
482
507
  const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]]);
483
508
  for (const [signal, code] of signals) process.on(signal, () => shutdown(code, true));
484
509
  }
485
- // A stdio host shuts down by closing stdin, which the SDK transport does not watch.
510
+ // A stdio host shuts down by closing stdin; the SDK closes its transport but does not stop agy.
486
511
  stdin.on("end", () => shutdown(0));
487
512
  }
488
513
 
@@ -493,8 +518,8 @@ if (isMain) {
493
518
  if (argv.includes("--version") || argv.includes("-v")) {
494
519
  console.log(readPackageVersion());
495
520
  } else {
496
- const server = buildServer();
497
521
  installSignalCleanup(inFlight, { pending: pendingDelegations });
498
- await server.connect(new StdioServerTransport());
522
+ // One factory serves both protocol eras: a 2025-era initialize pins a legacy instance.
523
+ serveStdio(() => buildServer());
499
524
  }
500
525
  }
package/src/spawn.js CHANGED
@@ -26,7 +26,7 @@ export function splitArgs(raw) {
26
26
  // --dangerously-skip-permissions makes agy approve its own tool calls. The request router approves
27
27
  // any permission request too, but a subagent's command can wait without raising one (agy #1658),
28
28
  // which only the flag covers.
29
- export const DEFAULT_AGENT_ARGS = Object.freeze(["acp", "--dangerously-skip-permissions"]);
29
+ export const DEFAULT_AGENT_ARGS = Object.freeze(["acp", "--dangerously-skip-permissions", "--disable-telemetry"]);
30
30
 
31
31
  // shell:true on win32 marks the spec for the Windows launch at each spawn site (spawnArgv): the
32
32
  // command is found first and started by file type, and only a .cmd or .bat reaches cmd.exe, which
package/src/turn-state.js CHANGED
@@ -1,6 +1,8 @@
1
1
  // Everything describing the turn in progress, reset as one before the prompt. freshFields() is the
2
2
  // single declaration reset() applies, so a field added there is reset too.
3
3
 
4
+ const RECOMMENDED = /^\(Recommended\)\s*/;
5
+
4
6
  const isTerminalToolStatus = (status) =>
5
7
  status === "completed" || status === "failed" || status === "cancelled";
6
8
 
@@ -69,6 +71,11 @@ function freshFields() {
69
71
  // ~/.gemini/antigravity-cli/brain/<sessionId>/. Keyed by path, so a rewrite replaces.
70
72
  artifacts: new Map(),
71
73
  touched: new Set(),
74
+ // One record per tool call, in first-seen order, for the execution summary: agy re-sends
75
+ // finished calls, so their frames merge.
76
+ toolCallRecords: new Map(),
77
+ // The questions of each ask_question call, normalized, by call id.
78
+ questions: new Map(),
72
79
  lastToolLabel: null,
73
80
  sessionTitle: undefined,
74
81
  };
@@ -112,7 +119,7 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
112
119
  if (toolCallId != null && !isTerminalToolStatus(status)) {
113
120
  state.activeToolCalls.add(toolCallId);
114
121
  // A fresh tool_call frame for a finished id is the agent reusing it, not history.
115
- state.finishedToolCalls.delete(toolCallId);
122
+ if (state.finishedToolCalls.delete(toolCallId)) state.questions.delete(toolCallId);
116
123
  }
117
124
  if (toolCallId != null && isTerminalToolStatus(status)) state.finishedToolCalls.add(toolCallId);
118
125
  if (isTerminalToolStatus(status) && state.activeToolCalls.size === 0) state.collectingPostToolResult = true;
@@ -143,10 +150,50 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
143
150
  }
144
151
  },
145
152
 
153
+ // Reopens a call the bridge closed itself, for a steer agy then rejected. Text collected since
154
+ // goes with the open call, as it would have had the call stayed open.
155
+ reopenTool(toolCallId) {
156
+ state.finishedToolCalls.delete(toolCallId);
157
+ state.unfinishedToolText += state.text();
158
+ state.updateToolStatus(toolCallId, "pending");
159
+ },
160
+
146
161
  // Unfinished calls that end on their own: a backgrounded command or a scheduled wake-up. An
147
162
  // ask_question waits on the caller instead, so it is never waited for.
148
163
  backgroundToolCalls() {
149
- return [...state.activeToolCalls].filter((id) => !/ask_question/.test(state.toolNames.get(id) ?? ""));
164
+ return [...state.activeToolCalls].filter((id) => !state.isQuestion(id));
165
+ },
166
+
167
+ isQuestion(id) {
168
+ return /ask_question/.test(state.toolNames.get(id) ?? "");
169
+ },
170
+
171
+ // agy sends rawInput.questions as [{question, options[], is_multi_select}], marking one option
172
+ // "(Recommended) ". Entries without a question string are dropped; false when none is left.
173
+ recordQuestions(id, raw) {
174
+ if (id == null || !Array.isArray(raw)) return false;
175
+ const questions = raw.filter((q) => q && typeof q.question === "string" && q.question).map((q) => {
176
+ const options = (Array.isArray(q.options) ? q.options : []).filter((o) => typeof o === "string");
177
+ const marked = options.find((o) => RECOMMENDED.test(o));
178
+ return {
179
+ question: q.question,
180
+ options: options.map((o) => o.replace(RECOMMENDED, "")),
181
+ ...(q.is_multi_select === true ? { multiSelect: true } : {}),
182
+ ...(marked !== undefined ? { recommended: marked.replace(RECOMMENDED, "") } : {}),
183
+ };
184
+ });
185
+ if (!questions.length) return false;
186
+ state.questions.set(id, questions);
187
+ return true;
188
+ },
189
+
190
+ // The ask_question calls still open, in the order agy asked them.
191
+ openQuestionCalls() {
192
+ return [...state.activeToolCalls].filter((id) => state.isQuestion(id));
193
+ },
194
+
195
+ openQuestions() {
196
+ return state.openQuestionCalls().flatMap((id) => state.questions.get(id) ?? []);
150
197
  },
151
198
 
152
199
  // True while a message chunk still belongs in the result: before any tool ran, or after
@@ -155,6 +202,29 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
155
202
  return !state.sawToolCall || (state.collectingPostToolResult && state.activeToolCalls.size === 0);
156
203
  },
157
204
 
205
+ // Merges a frame into its call's record. A fresh tool_call for a finished id is a new call (agy
206
+ // reusing the id); the finished record keeps its place under a key of its own.
207
+ recordToolCall(up, isArtifact) {
208
+ const id = up?.toolCallId;
209
+ if (id == null) return;
210
+ let rec = state.toolCallRecords.get(id);
211
+ if (rec && up.sessionUpdate === "tool_call" && isTerminalToolStatus(rec.status) && !isTerminalToolStatus(up.status)) {
212
+ state.toolCallRecords = new Map([...state.toolCallRecords].map(([k, v]) => [k === id ? Symbol() : k, v]));
213
+ rec = undefined;
214
+ }
215
+ rec ??= {};
216
+ if (isArtifact) rec.artifact = true;
217
+ if (typeof up.kind === "string" && up.kind) rec.kind = up.kind;
218
+ if (typeof up.title === "string" && up.title) rec.title = up.title;
219
+ if (typeof up.rawInput?.CommandLine === "string") rec.command = up.rawInput.CommandLine;
220
+ if (Number.isInteger(up.rawOutput?.exit_code)) rec.exitCode = up.rawOutput.exit_code;
221
+ if (typeof up.status === "string"
222
+ && (up.sessionUpdate === "tool_call" || isTerminalToolStatus(up.status) || !isTerminalToolStatus(rec.status))) {
223
+ rec.status = up.status;
224
+ }
225
+ state.toolCallRecords.set(id, rec);
226
+ },
227
+
158
228
  // The artifact's content arrives whole in rawInput.Content; Path is where agy saved it.
159
229
  recordArtifact(input) {
160
230
  const meta = input?.ArtifactMetadata;