agy-delegate-mcp 1.5.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,55 @@ 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
+
30
+ ## [1.6.0] - 2026-11-22
31
+
32
+ ### Changed
33
+
34
+ - On Windows the launcher is found first and started by file type. agy.exe runs directly rather
35
+ than through cmd.exe, so its arguments arrive exactly; a `.ps1` runs through Windows PowerShell; a
36
+ `.cmd` or `.bat` runs through cmd.exe with its arguments quoted. A Store app alias counts as
37
+ found, a file with no extension never matches, and a bare name is no longer run from the
38
+ workspace.
39
+ - In `ACP_AGENT_ARGS` a quoted section after `=` belongs to its argument, so
40
+ `--log-file="C:\a b\x.log"` is one argument. A quote inside a word stays a character.
41
+ - A resume that omits `model` on a server with no record of the session says so in
42
+ `protocolWarnings`.
43
+
44
+ ### Fixed
45
+
46
+ - A launcher path or argument with spaces reaches a `.cmd` launcher whole.
47
+ - `force` cancel kills unsettled turns alongside the other turns' closes, not after them.
48
+ - A delegation cancelled during setup carries `resultSource: "none"`.
49
+ - The unfinished-tool warning and the background wait's progress line name the command still
50
+ running. The wait's limit is named only when it ran out, and a cancel or steer in its last check
51
+ is honoured.
52
+ - An effort reply that omits the model keeps the model recorded for the session.
53
+ - An aborted `doctor` spawns no version probe, and an aborted probe returns only once it has
54
+ closed, also when the abort falls just before its timeout.
55
+ - A signal after stdin closes sets the exit code. A second signal kills every agent shutdown
56
+ stopped, except one whose exit was already confirmed.
57
+
9
58
  ## [1.5.0] - 2026-11-22
10
59
 
11
60
  ### 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.5.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
@@ -4,13 +4,14 @@ import { EventEmitter } from "node:events";
4
4
  import { StringDecoder } from "node:string_decoder";
5
5
  import { JsonRpcPeer } from "./jsonrpc.js";
6
6
  import { createRequestRouter } from "./request-router.js";
7
- import { commandExists, resolveAcpSpawn, spawnCommandLine } from "./spawn.js";
7
+ import { resolveAcpSpawn, spawnArgv, spawnCommandLine } from "./spawn.js";
8
8
  import { DETACHED, isChildAlive, treeKill } from "./proc.js";
9
9
  import { VERSION } from "./version.js";
10
10
  import { makeError } from "./errors.js";
11
11
 
12
12
  const STDERR_CAP = 64 * 1024;
13
- // How long stop() waits for the exit after the kill; it elapses only when the kill failed.
13
+ // How long stop() waits for the exit and the tree kill; it elapses when the kill failed or the
14
+ // tree walk is slow.
14
15
  const STOP_EXIT_TIMEOUT_MS = 2000;
15
16
  // How long a graceful stop gives agy to exit by itself before the kill. agy took 200–400 ms.
16
17
  export const GRACEFUL_STOP_MS = 2000;
@@ -54,15 +55,18 @@ export class AcpClient extends EventEmitter {
54
55
 
55
56
  start() {
56
57
  const { command, args, options } = this.spawnSpec;
57
- if (/** @type {{ shell?: boolean }} */ (options)?.shell && !commandExists(command)) {
58
+ // Found before the spawn: through cmd.exe a missing launcher still spawns, and would read as an
59
+ // agent crash.
60
+ const launch = spawnArgv(command, args, options);
61
+ if (!launch) {
58
62
  return Promise.reject(makeError("spawn-failed", `Failed to spawn agent (${command}): not found on PATH. Install the Antigravity CLI (agy) and sign in by running agy once.`));
59
63
  }
60
64
  this._stderrChunks = [];
61
65
  this._stderrLength = 0;
62
66
  const stderrDecoder = new StringDecoder("utf8");
63
67
  this._exitEmitted = false;
64
- const [file, argv] = spawnCommandLine(command, args, options);
65
- this.child = spawn(file, argv, { ...options, ...(this.cwd ? { cwd: this.cwd } : {}), detached: DETACHED, stdio: ["pipe", "pipe", "pipe"] });
68
+ const [file, argv] = spawnCommandLine(launch.command, launch.args, launch.options);
69
+ this.child = spawn(file, argv, { ...launch.options, ...(this.cwd ? { cwd: this.cwd } : {}), detached: DETACHED, stdio: ["pipe", "pipe", "pipe"] });
66
70
  this.child.stderr.on("data", (chunk) => {
67
71
  const text = stderrDecoder.write(chunk);
68
72
  if (text) {
@@ -81,7 +85,8 @@ export class AcpClient extends EventEmitter {
81
85
  }
82
86
  });
83
87
  this.child.stderr.on("error", () => {});
84
- // A write after the agent is gone raises 'error'; unhandled, it takes down the server.
88
+ // A write after the agent is gone raises 'error' on stdin. readline forwards stdout's errors only
89
+ // until it closes. Unhandled, either takes down the server.
85
90
  this.child.stdin.on("error", () => {});
86
91
  this.child.stdout.on("error", () => {});
87
92
  const emitExit = (code, signal) => {
@@ -181,13 +186,14 @@ export class AcpClient extends EventEmitter {
181
186
  const body = this._steerPrefix ? `${this._steerPrefix}\n\n${text}` : text;
182
187
  // Stamped, so it never rejects unobserved.
183
188
  this._steers.push(stampSettlement(this.peer.request("session/prompt", { sessionId, prompt: [{ type: "text", text: body }] })));
189
+ this.emit("steer");
184
190
  return "steered";
185
191
  }
186
192
  hasSteer() { return this._steers.length > 0; }
187
193
  takeSteer() { return this._steers.shift(); }
188
- // Read by the background wait, which a cancelled turn's usage_update would not end, and closes
189
- // the steer window: a later steer would restart the cancelled turn. delegate listens for the
190
- // event to end its setup when no prompt has gone out.
194
+ // Read by the background wait: after a cancel agy closes the call without the usage_update that
195
+ // ends a continuation. Closes the steer window: a later steer would restart the cancelled turn.
196
+ // delegate listens for the event to end its setup when no prompt has gone out.
191
197
  cancel(sessionId) {
192
198
  this.cancelRequested = true;
193
199
  this._steerWindow = "closed";
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");
@@ -383,10 +436,15 @@ export async function runDelegate({
383
436
  const slashed = (s) => String(s).replace(/\\/g, "/");
384
437
  const named = path && slashed(label).includes(slashed(path));
385
438
  state.lastToolLabel = (label + (path && !named ? " — " + path : "")).replace(/\s+/g, " ").trim();
439
+ if (up.toolCallId != null) state.toolLabels.set(up.toolCallId, state.lastToolLabel);
386
440
  try { onProgress?.(("running: " + state.lastToolLabel).slice(0, 200)); } catch {}
387
441
  } else {
388
442
  state.updateToolStatus(up.toolCallId, up.status);
389
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
+ }
390
448
  if (!isArtifact) recordDiffs(up.content);
391
449
  }
392
450
  if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
@@ -401,20 +459,24 @@ export async function runDelegate({
401
459
  // finishes the command and continues the turn unprompted, closing with a usage_update (measured,
402
460
  // agy 1.5.14). Stopping agy at end_turn would kill the command. The hard cap still bounds the wait.
403
461
  let backgroundWaited;
462
+ // Set only when the wait ran its full length, which is what the warning blames.
463
+ let backgroundWaitRanOut = false;
404
464
  // One clock per delegation, kept across steered turns.
405
465
  let backgroundStartedAt;
406
466
  const waitForBackground = async () => {
407
- try { onProgress?.(`waiting for agy's background command: ${state.lastToolLabel ?? "tool"}`.slice(0, 200)); } catch {}
467
+ const label = state.toolLabels.get(state.backgroundToolCalls()[0]) ?? state.lastToolLabel ?? "tool";
468
+ try { onProgress?.(`waiting for agy's background command: ${label}`.slice(0, 200)); } catch {}
408
469
  const startedAt = (backgroundStartedAt ??= Date.now());
409
470
  for (;;) {
410
471
  await new Promise((r) => setTimeout(r, Math.min(250, backgroundSettleMs)));
411
472
  backgroundWaited = Date.now() - startedAt;
412
- if (backgroundWaited >= backgroundWaitMs) return;
413
473
  // The delegation already failed (agent exit, abort, hard cap): nobody reads this wait.
414
474
  if (supervisor.settled) return;
475
+ // Ahead of the deadline, so a cancel or steer in the last tick is not lost to it.
415
476
  if (client.cancelRequested) return "cancelled";
416
477
  // A steer redirects the turn; its own prompt reply is what ends it now.
417
478
  if (client.hasSteer?.()) return;
479
+ if (backgroundWaited >= backgroundWaitMs) { backgroundWaitRanOut = true; return; }
418
480
  if (state.backgroundToolCalls().length) continue;
419
481
  const quietMs = Date.now() - state.lastFrameAt;
420
482
  if (state.usageAfterActivity && quietMs >= backgroundSettleMs) return;
@@ -430,6 +492,7 @@ export async function runDelegate({
430
492
  let out;
431
493
  let servedModel;
432
494
  let effectiveEffort;
495
+ let noSettingsRecord = false;
433
496
  const contextWarnings = [];
434
497
  try {
435
498
  const res = await supervisor.supervise(async () => {
@@ -446,6 +509,8 @@ export async function runDelegate({
446
509
  if (client.cancelRequested) return cancelledInSetup;
447
510
  // Only a resume that took inherits: a fallback to a fresh session is a different session.
448
511
  const earlier = resumeSessionId && sessionId === resumeSessionId ? sessionSettings.get(sessionId) : undefined;
512
+ // The record lives in memory: a server restarted since the session ran has none to apply.
513
+ noSettingsRecord = !!resumeSessionId && sessionId === resumeSessionId && !earlier && model === undefined;
449
514
  const targetModel = model ?? earlier?.model;
450
515
  // A remembered effort holds only on the model it was set for: another model may not offer it.
451
516
  const targetEffort = effort ?? (targetModel === earlier?.model ? earlier?.effort : undefined);
@@ -456,15 +521,20 @@ export async function runDelegate({
456
521
  }
457
522
  }
458
523
  if (client.cancelRequested) return cancelledInSetup;
524
+ // Kept across the effort reply, which may carry only the option it changed.
525
+ const modelBeforeEffort = configOptionValue(options, "model");
459
526
  if (targetEffort !== undefined) {
460
- const target = targetModel ?? configOptionValue(options, "model") ?? "the session's model";
527
+ const target = targetModel ?? modelBeforeEffort ?? "the session's model";
461
528
  options = optionsFrom(await applyEffort(client, sessionId, target, targetEffort, options));
462
529
  }
463
530
  if (client.cancelRequested) return cancelledInSetup;
464
- servedModel = configOptionValue(options, "model");
531
+ servedModel = configOptionValue(options, "model") ?? modelBeforeEffort;
465
532
  // Saved once agy accepted them, with the model agy reports, so an effort set on agy's default
466
- // is tied to that model.
467
- if (targetModel !== undefined || targetEffort !== undefined) rememberSettings(sessionId, { model: targetModel ?? servedModel, effort: targetEffort });
533
+ // is tied to that model. A session run on agy's defaults is recorded too, as having none, so
534
+ // its resume here does not read as a restart.
535
+ rememberSettings(sessionId, targetModel !== undefined || targetEffort !== undefined
536
+ ? { model: targetModel ?? servedModel, effort: targetEffort }
537
+ : {});
468
538
  // What agy reported in force, never the requested value.
469
539
  effectiveEffort = effortSettings(options);
470
540
  await client.setMode(sessionId, agyMode);
@@ -499,6 +569,7 @@ export async function runDelegate({
499
569
  }
500
570
  const steer = client.takeSteer?.();
501
571
  if (!steer) break;
572
+ const closed = closedBySteer.shift() ?? [];
502
573
  const reply = await steer;
503
574
  if (reply.ok) {
504
575
  turn = reply.value;
@@ -508,6 +579,9 @@ export async function runDelegate({
508
579
  } else if (reply.seq < turnSeq) {
509
580
  // Refused before its target settled: that turn stands, and the warning tells the caller.
510
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);
511
585
  } else {
512
586
  // Failed after taking the turn over: the turn failed, unless a steer queued behind it
513
587
  // succeeds.
@@ -533,23 +607,31 @@ export async function runDelegate({
533
607
  ? (state.sawToolCall ? "post-tool" : "tool-free-stream")
534
608
  : "none";
535
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;
536
613
  if (!finalMessageAvailable && state.activeToolCalls.size > 0) {
537
614
  // Measured cases (agy 1.5.14): a background command still running when the wait ran out, or an
538
615
  // ask_question waiting on the caller.
539
616
  result = state.unfinishedToolText;
540
617
  resultSource = result ? "unfinished-tool" : "none";
618
+ // The open command if there is one, else the question; not the newest tool.
619
+ const openId = state.backgroundToolCalls()[0] ?? [...state.activeToolCalls][0];
620
+ const openLabel = state.toolLabels.get(openId) ?? state.lastToolLabel;
541
621
  // A refusal or output cap is not waited on, so a command can be open with no wait.
542
622
  const cause = !state.backgroundToolCalls().length
543
623
  ? " agy is asking a question (ask_question), which a resume answers."
544
- : backgroundWaited !== undefined
624
+ : backgroundWaitRanOut
545
625
  ? ` agy moved it to the background, and it was still running after the bridge waited ${fmtDuration(backgroundWaited)}`
546
626
  + " (AGY_DELEGATE_BACKGROUND_WAIT_MS); it stops when the bridge stops agy."
547
627
  : ` agy ended the turn (${res?.stopReason}) with it still running; it stops when the bridge stops agy.`;
548
- protocolWarnings.push(
549
- `the turn ended with a tool call still running (${state.lastToolLabel ?? "unnamed tool"}).`
550
- + cause
551
- + (result ? " result is agy's message from while it ran." : " agy sent no message while it ran.")
552
- );
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
+ }
553
635
  } else if (!finalMessageAvailable && state.discardedResult) {
554
636
  result = state.discardedResult;
555
637
  resultSource = "pre-tool-fallback";
@@ -576,10 +658,14 @@ export async function runDelegate({
576
658
  // Absent means nothing reported, not nothing changed: shell edits emit no diff.
577
659
  const filesReported = normalizeAgentReportedFiles([...state.touched], workspace);
578
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;
579
664
  // resultSource appears only as a caveat; resumed only when a resume took.
580
665
  if (resultSource !== "post-tool" && resultSource !== "tool-free-stream") out.resultSource = resultSource;
581
666
  if (!!resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
582
- // Present when the served model differs from the requested one, so always when model was omitted.
667
+ // Present when the served model differs from the requested one, so whenever model was omitted
668
+ // and agy reports one.
583
669
  if (servedModel !== undefined && servedModel !== model) out.effectiveModel = servedModel;
584
670
  if (effectiveEffort !== undefined) out.effectiveEffort = effectiveEffort;
585
671
  if (stopReason !== undefined) out.stopReason = stopReason;
@@ -602,6 +688,9 @@ export async function runDelegate({
602
688
  .map((a) => ({ path: a.path, ...(a.summary !== undefined ? { summary: a.summary } : {}) }));
603
689
  if (others.length) out.artifacts = others;
604
690
  if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
691
+ if (noSettingsRecord) {
692
+ protocolWarnings.push(`agy reopened the session at its default model${servedModel ? ` (${servedModel})` : ""}: this server has no record of the model set earlier, as it keeps none across restarts. Pass model to choose one.`);
693
+ }
605
694
  protocolWarnings.push(...contextWarnings);
606
695
  protocolWarnings.push(...frameWarnings);
607
696
  protocolWarnings.push(...steerWarnings);
@@ -610,7 +699,7 @@ export async function runDelegate({
610
699
  } catch (err) {
611
700
  // A caller's cancel before the prompt is a cancelled result, even if a config call then failed.
612
701
  if (cancelledInSetupByCaller && sessionId) {
613
- out = { result: "", sessionId, stopReason: "cancelled" };
702
+ out = { result: "", sessionId, resultSource: "none", stopReason: "cancelled" };
614
703
  if (resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
615
704
  if (resumeError) out.protocolWarnings = [`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`];
616
705
  return out;
@@ -663,11 +752,13 @@ export async function runDelegate({
663
752
  clearInterval(heartbeat);
664
753
  signal?.removeEventListener("abort", onAbort);
665
754
  client.off?.("cancel", onCancel);
755
+ client.off?.("steer", onSteer);
666
756
  try { supervisor.finish(); } catch {}
667
- // Awaited, so agy has exited when the caller gets the result; otherwise agy still holds the
668
- // workspace as its cwd (deleting it fails with EBUSY on Windows). The handle stays registered
669
- // meanwhile, so force cancel and shutdown can cut the grace short. Graceful after a completed
670
- // turn, so agy closes its conversation database; a stall, abort or exit is killed at once.
757
+ // Awaited, so agy has exited when the caller gets the result, or a warning says the exit was not
758
+ // seen; otherwise agy still holds the workspace as its cwd (deleting it fails with EBUSY on
759
+ // Windows). The handle stays registered meanwhile, so force cancel and shutdown can cut the grace
760
+ // short. Graceful after a completed turn, so agy closes its conversation database; a stall,
761
+ // abort or exit is killed at once.
671
762
  const killNow = signal?.aborted || ["handshake-timeout", "hard-cap", "idle-timeout", "aborted", "agent-exit"].includes(failed?.reason);
672
763
  // A host abort during the close is still an abort: a force stop ends the grace and kills.
673
764
  const abortClose = () => { Promise.resolve(client.stop()).catch(() => {}); };
package/src/doctor.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import process from "node:process";
2
2
  import { spawn } from "node:child_process";
3
+ import { existsSync } from "node:fs";
3
4
  import { AcpClient, GRACEFUL_STOP_MS } from "./acp-client.js";
4
- import { commandExists, resolveAcpSpawn, spawnCommandLine } from "./spawn.js";
5
+ import { commandExists, resolveAcpSpawn, spawnArgv, spawnCommandLine } from "./spawn.js";
5
6
  import { DETACHED, treeKill } from "./proc.js";
6
7
  import { readPackageVersion } from "./version.js";
7
8
  import { allowedValues, describeOptions } from "./model-options.js";
@@ -9,6 +10,7 @@ import { allowedValues, describeOptions } from "./model-options.js";
9
10
  const HANDSHAKE_TIMEOUT_MS = 15_000;
10
11
  const VERSION_PROBE_TIMEOUT_MS = 10_000;
11
12
  const PROBE_STDOUT_CAP = 64 * 1024;
13
+ const PROBE_KILL_WAIT_MS = 2000;
12
14
  const DEFAULT_LOG_SIZE = "2000";
13
15
 
14
16
  function formatArg(value) {
@@ -38,13 +40,20 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
38
40
  const isJsScript = isJsLauncher(launcher);
39
41
  const execCommand = isJsScript ? process.execPath : command;
40
42
  const execArgs = isJsScript ? [launcher, "--version"] : ["--version"];
41
- // Through a shell, a missing launcher still spawns (the shell does) and would read as found.
42
- if (options?.shell && !isJsScript && !commandExists(launcher)) return Promise.resolve({ found: false, version: null });
43
+ // Found before the spawn: through cmd.exe a missing launcher still spawns and would read as found.
44
+ const launch = spawnArgv(execCommand, execArgs, options);
45
+ if (!launch) return Promise.resolve({ found: false, version: null });
46
+ const aborted = { version: null, error: "version probe aborted by MCP host" };
47
+ // Interrupted already: nothing is spawned, and found comes from the lookup alone.
48
+ if (signal?.aborted) {
49
+ return Promise.resolve({ found: isJsScript ? existsSync(launcher) : commandExists(launcher, options?.env), ...aborted });
50
+ }
43
51
  return new Promise((resolve) => {
44
52
  let settled = false;
45
53
  let stdout = "";
46
54
  let timer;
47
55
  let onAbort;
56
+ let abortRequested = false;
48
57
  const finish = (result) => {
49
58
  if (settled) return;
50
59
  settled = true;
@@ -52,8 +61,8 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
52
61
  if (onAbort) signal?.removeEventListener("abort", onAbort);
53
62
  resolve(result);
54
63
  };
55
- const [file, argv] = spawnCommandLine(execCommand, execArgs, options);
56
- const child = spawn(file, argv, { ...options, detached: DETACHED, stdio: ["ignore", "pipe", "pipe"] });
64
+ const [file, argv] = spawnCommandLine(launch.command, launch.args, launch.options);
65
+ const child = spawn(file, argv, { ...launch.options, detached: DETACHED, stdio: ["ignore", "pipe", "pipe"] });
57
66
  // Capped: a version is one line.
58
67
  child.stdout?.on("data", (chunk) => {
59
68
  if (stdout.length < PROBE_STDOUT_CAP) stdout += chunk.toString();
@@ -62,7 +71,9 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
62
71
  child.stderr?.on("data", () => {});
63
72
  child.stderr?.on("error", () => {});
64
73
  child.on("error", () => finish({ found: false, version: null }));
74
+ const closed = new Promise((r) => child.once("close", r));
65
75
  child.on("close", (code) => {
76
+ if (abortRequested) return;
66
77
  const version = code === 0 ? stdout.trim() || null : null;
67
78
  finish({
68
79
  found: true,
@@ -71,19 +82,23 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
71
82
  });
72
83
  });
73
84
  timer = setTimeout(() => {
74
- // treeKill: on win32 a plain kill reaches only the shell wrapper.
85
+ // treeKill: on win32 a plain kill reaches only the launcher, not what a .cmd or .ps1 started.
75
86
  if (child.pid) treeKill(child.pid).catch(() => {});
76
87
  // It spawned, so it is installed; it did not answer.
77
88
  finish({ found: true, version: null, error: `version probe timed out after ${timeoutMs}ms` });
78
89
  }, timeoutMs);
79
90
  timer.unref?.();
80
91
  // A host interrupt ends the probe at once rather than at its timeout.
92
+ // Returns once the probe has closed, so doctor does not leave it running; bounded like stop().
81
93
  onAbort = () => {
82
- if (child.pid) treeKill(child.pid).catch(() => {});
83
- finish({ found: true, version: null, error: "version probe aborted by MCP host" });
94
+ // The timeout would otherwise still fire during the kill and return first.
95
+ clearTimeout(timer);
96
+ abortRequested = true;
97
+ const killed = child.pid ? treeKill(child.pid).catch(() => {}) : Promise.resolve();
98
+ const bound = new Promise((r) => setTimeout(r, PROBE_KILL_WAIT_MS).unref?.());
99
+ Promise.race([Promise.all([killed, closed]), bound]).then(() => finish({ found: true, ...aborted }));
84
100
  };
85
- if (signal?.aborted) onAbort();
86
- else signal?.addEventListener("abort", onAbort, { once: true });
101
+ signal?.addEventListener("abort", onAbort, { once: true });
87
102
  });
88
103
  }
89
104
 
@@ -138,9 +153,9 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
138
153
  return { ok: false, error: err?.message || String(err) };
139
154
  } finally {
140
155
  clearTimeout(timer);
141
- // Awaited, so doctor returns after its agent has exited. Graceful, closing the handshake's
142
- // session; after a timeout or abort it joins the kill already started. The abort listener stays
143
- // on through the close, so an abort there forces the kill.
156
+ // Awaited, so doctor returns once its agent is stopped or the stop's deadline passed. Graceful,
157
+ // closing the handshake's session; after a timeout or abort it joins the kill already started.
158
+ // The abort listener stays on through the close, so an abort there forces the kill.
144
159
  try { await Promise.resolve(client.stop({ graceMs: signal?.aborted ? 0 : GRACEFUL_STOP_MS })); } catch {}
145
160
  if (onAbort) signal?.removeEventListener("abort", onAbort);
146
161
  }
@@ -148,7 +163,7 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
148
163
 
149
164
  /**
150
165
  * @param {{
151
- * getClientInfo?: () => { capabilities?: any, version?: any },
166
+ * getClientInfo?: () => { capabilities?: any, version?: any, protocolVersion?: string },
152
167
  * deep?: boolean,
153
168
  * spawnSpec?: { command: string, args: string[], options?: object },
154
169
  * clientFactory?: (opts: any) => any,
@@ -172,7 +187,7 @@ export async function runDoctor({
172
187
  signal,
173
188
  onClientReady,
174
189
  } = {}) {
175
- const { capabilities, version } = getClientInfo();
190
+ const { capabilities, version, protocolVersion } = getClientInfo();
176
191
  const agentProbe = await probeAgentVersion(spawnSpec, versionTimeoutMs, signal);
177
192
 
178
193
  /** @type {{ plugin: any, client: any, agent: any & { handshake?: any }, runtime: any, env: any }} */
@@ -182,6 +197,8 @@ export async function runDoctor({
182
197
  name: version?.name ?? null,
183
198
  version: version?.version ?? null,
184
199
  capabilities: capabilities ?? {},
200
+ // The MCP revision the host speaks: 2026-07-28 or a 2025-era one.
201
+ ...(typeof protocolVersion === "string" ? { protocolVersion } : {}),
185
202
  },
186
203
  agent: {
187
204
  found: agentProbe.found,
package/src/proc.js CHANGED
@@ -35,7 +35,8 @@ function descendantPids(pid) {
35
35
  }));
36
36
  }
37
37
 
38
- // On win32 a plain kill reaches only the shell wrapper; taskkill /T takes the tree.
38
+ // On win32 a plain kill reaches only the launched process (agy.exe, or the cmd.exe or PowerShell
39
+ // running a script); taskkill /T takes the tree, agy's commands included.
39
40
  export async function treeKill(pid, { childAlive = true } = {}) {
40
41
  if (!pid) return;
41
42
  if (process.platform === "win32") {
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,
@@ -337,13 +354,12 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
337
354
  if (cut.size === live.length || Date.now() >= graceEnds) break;
338
355
  await new Promise((r) => setTimeout(r, Math.min(50, Math.max(1, graceEnds - Date.now()))));
339
356
  }
340
- await Promise.all(closing);
341
- // A snapshot, so a resume registering during teardown is not swept from the map.
357
+ // Classified the moment the grace ends and killed alongside the closes, not after them: a slow
358
+ // close would delay the kill, and a turn ending meanwhile would be reported killed. A snapshot,
359
+ // so a resume registering during teardown is not swept from the map.
342
360
  const toKill = live.filter((handle) => !cut.has(handle));
361
+ const [observed] = await Promise.all([Promise.all(toKill.map(stopQuietly)), Promise.all(closing)]);
343
362
  if (toKill.length === 0) return statusResult("cancelled", sessionId);
344
- const observed = await Promise.all(
345
- toKill.map((handle) => Promise.resolve(handle.client.stop()).catch(() => false))
346
- );
347
363
  // "killed" needs an observed exit; without one the handles stay and force can be retried.
348
364
  if (!observed.every(Boolean)) return statusResult("cancelled", sessionId);
349
365
  for (const handle of toKill) unregisterInFlight(inFlight, sessionId, handle);
@@ -356,10 +372,10 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
356
372
  {
357
373
  description:
358
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).",
359
- inputSchema: {
375
+ inputSchema: z.object({
360
376
  sessionId: sessionIdInput,
361
377
  message: z.string().trim().min(1, "message must not be blank").describe("The new instruction for agy."),
362
- },
378
+ }),
363
379
  annotations: {
364
380
  title: "Steer Antigravity delegation",
365
381
  readOnlyHint: false,
@@ -376,12 +392,12 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
376
392
  {
377
393
  description:
378
394
  "Setup diagnostics: plugin version, MCP client capabilities, agy launcher resolution. Run when delegation fails or agent.found is false.",
379
- inputSchema: {
395
+ inputSchema: z.object({
380
396
  deep: z
381
397
  .boolean()
382
398
  .default(false)
383
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."),
384
- },
400
+ }),
385
401
  annotations: {
386
402
  title: "Diagnose Antigravity delegation setup",
387
403
  readOnlyHint: true,
@@ -390,18 +406,15 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
390
406
  openWorldHint: false,
391
407
  },
392
408
  },
393
- async ({ deep }, extra) => {
409
+ async ({ deep }, ctx) => {
394
410
  // In pending while it runs, so shutdown stops doctor's agent too.
395
411
  let handle;
396
412
  try {
397
413
  const out = await runDoctor({
398
414
  deep,
399
- signal: extra?.signal,
415
+ signal: ctx?.mcpReq?.signal,
400
416
  onClientReady: (client) => { handle = { client }; pending.add(handle); },
401
- getClientInfo: () => ({
402
- capabilities: server.server.getClientCapabilities(),
403
- version: server.server.getClientVersion(),
404
- }),
417
+ getClientInfo: () => clientInfoOf(server, ctx),
405
418
  });
406
419
  return { content: [{ type: "text", text: JSON.stringify(out) }] };
407
420
  } finally {
@@ -413,6 +426,17 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
413
426
  return server;
414
427
  }
415
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
+
416
440
  const __filename = fileURLToPath(import.meta.url);
417
441
  let isMain = false;
418
442
  if (process.argv[1]) {
@@ -433,26 +457,39 @@ export function installSignalCleanup(map, {
433
457
  } = {}) {
434
458
  let shuttingDown = false;
435
459
  let signalsSeen = 0;
460
+ // The code shutdown exits with: a signal's, even when it follows the stdin EOF.
461
+ let exitCode = 0;
462
+ // Every handle a stop went to, so a second signal still reaches one that has since unregistered.
463
+ const dispatched = new Set();
436
464
  const shutdown = (code, fromSignal = false) => {
437
465
  // Only a second signal skips the wait for the kills: a hangup closes stdin and sends SIGHUP,
438
466
  // in either order. The first stops may still be in their ps walk, so the groups are killed
439
467
  // synchronously before leaving.
440
468
  if (fromSignal) signalsSeen++;
441
469
  if (shuttingDown) {
470
+ if (fromSignal && signalsSeen === 1) { exitCode = code; setExitCode(code); }
442
471
  if (signalsSeen < 2) return undefined;
443
- for (const handles of [...map.values(), pending]) {
444
- for (const handle of handles) { try { handle.client.killNow?.(); } catch {} }
472
+ for (const handle of new Set([...dispatched, ...[...map.values()].flatMap((h) => [...h]), ...pending])) {
473
+ try { handle.client.killNow?.(); } catch {}
445
474
  }
446
475
  return exit(code);
447
476
  }
448
477
  shuttingDown = true;
478
+ exitCode = code;
449
479
  // Set now: if the loop runs dry before the scheduled exit, the process still exits with it.
450
480
  setExitCode(code);
451
481
  const stops = [];
452
482
  // A stop that did not see the exit is retried once, as the delegation does.
453
483
  const stopOnce = (handle) => Promise.resolve(handle.client.stop()).catch(() => false);
454
484
  const dispatch = (handle) => {
455
- try { stops.push(stopOnce(handle).then((exited) => (exited === false ? stopOnce(handle) : exited))); } catch {}
485
+ dispatched.add(handle);
486
+ try {
487
+ stops.push(stopOnce(handle).then((exited) => (exited === false ? stopOnce(handle) : exited)).then((exited) => {
488
+ // Its group is killed and its id may be reused: a second signal must not kill it again.
489
+ if (exited !== false) dispatched.delete(handle);
490
+ return exited;
491
+ }));
492
+ } catch {}
456
493
  };
457
494
  for (const handles of map.values()) for (const handle of handles) dispatch(handle);
458
495
  // Delegations still in their handshake, with no session id yet.
@@ -460,7 +497,7 @@ export function installSignalCleanup(map, {
460
497
  // Exit waits for the kills: on Windows taskkill is a separate process, and exiting first left
461
498
  // the launcher and agent running (measured). stop() bounds itself. The exit is scheduled onto
462
499
  // a clean loop turn, off the settlement stack.
463
- const leave = () => schedule(() => exit(code));
500
+ const leave = () => schedule(() => exit(exitCode));
464
501
  Promise.all(stops).then(leave, leave);
465
502
  };
466
503
  // On POSIX each agent has its own process group, so a signal to this process does not reach it.
@@ -470,7 +507,7 @@ export function installSignalCleanup(map, {
470
507
  const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]]);
471
508
  for (const [signal, code] of signals) process.on(signal, () => shutdown(code, true));
472
509
  }
473
- // 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.
474
511
  stdin.on("end", () => shutdown(0));
475
512
  }
476
513
 
@@ -481,8 +518,8 @@ if (isMain) {
481
518
  if (argv.includes("--version") || argv.includes("-v")) {
482
519
  console.log(readPackageVersion());
483
520
  } else {
484
- const server = buildServer();
485
521
  installSignalCleanup(inFlight, { pending: pendingDelegations });
486
- await server.connect(new StdioServerTransport());
522
+ // One factory serves both protocol eras: a 2025-era initialize pins a legacy instance.
523
+ serveStdio(() => buildServer());
487
524
  }
488
525
  }
package/src/spawn.js CHANGED
@@ -1,24 +1,37 @@
1
1
  import process from "node:process";
2
- import { existsSync, statSync } from "node:fs";
2
+ import { lstatSync, statSync } from "node:fs";
3
3
  import path from "node:path";
4
4
 
5
+ // Splits on whitespace outside quotes. A quote opens a section only at the start of an argument or
6
+ // right after "=", and only when it closes: --log-file="C:\a b\x.log" is one argument, quotes
7
+ // removed, while the apostrophe in O'Brien stays a character. Backslashes are literal.
5
8
  export function splitArgs(raw) {
9
+ const s = String(raw || "");
6
10
  const args = [];
7
- const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
8
- for (const m of String(raw || "").matchAll(re)) {
9
- args.push(m[1] ?? m[2] ?? m[3]);
11
+ let i = 0;
12
+ for (;;) {
13
+ while (i < s.length && /\s/.test(s[i])) i++;
14
+ if (i >= s.length) return args;
15
+ let arg = "";
16
+ while (i < s.length && !/\s/.test(s[i])) {
17
+ const end = (s[i] === '"' || s[i] === "'") && (arg === "" || arg.endsWith("=")) ? s.indexOf(s[i], i + 1) : -1;
18
+ if (end === -1) { arg += s[i++]; continue; }
19
+ arg += s.slice(i + 1, end);
20
+ i = end + 1;
21
+ }
22
+ args.push(arg);
10
23
  }
11
- return args;
12
24
  }
13
25
 
14
26
  // --dangerously-skip-permissions makes agy approve its own tool calls. The request router approves
15
27
  // any permission request too, but a subagent's command can wait without raising one (agy #1658),
16
28
  // which only the flag covers.
17
- 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"]);
18
30
 
19
- // shell:true on win32 lets a .cmd/.ps1 launcher resolve, and cmd.exe parses the line. Safe because
20
- // both values come from the environment, as trusted as this process. Never route host or caller
21
- // input into them: that would be command injection.
31
+ // shell:true on win32 marks the spec for the Windows launch at each spawn site (spawnArgv): the
32
+ // command is found first and started by file type, and only a .cmd or .bat reaches cmd.exe, which
33
+ // parses its line. Safe because both values come from the environment, as trusted as this process.
34
+ // Never route host or caller input into them: that would be command injection.
22
35
  export function resolveAcpSpawn() {
23
36
  const command = process.env.ACP_AGENT_COMMAND || "agy";
24
37
  const args = process.env.ACP_AGENT_ARGS
@@ -27,26 +40,99 @@ export function resolveAcpSpawn() {
27
40
  return { command, args, options: { shell: process.platform === "win32" } };
28
41
  }
29
42
 
30
- // Node 24 warns (DEP0190) on args passed with shell: true. Node joins them with spaces anyway, so
31
- // joining here sends cmd.exe the same line without the warning.
43
+ // Under shell: true Node hands cmd.exe one joined line and quotes nothing, so a launcher path or an
44
+ // argument with a space or a cmd metacharacter split there. A value already holding a quote passes
45
+ // as given: cmd cannot nest them, and a pre-quoted path is how one with a space had to be written.
46
+ // %VAR% still expands, inside quotes too.
47
+ function cmdQuote(value) {
48
+ const s = String(value);
49
+ if (s.includes('"') || (s !== "" && !/[\s&|<>^(),;=]/.test(s))) return s;
50
+ // Doubled so the child's argv parser does not read a trailing backslash as escaping the quote.
51
+ return `"${s.replace(/(\\+)$/, "$1$1")}"`;
52
+ }
53
+
54
+ // The line is built here, quoted for cmd.exe, and passed alone: Node 24 warns (DEP0190) on args
55
+ // passed with shell: true.
32
56
  /** @returns {[string, string[]]} */
33
57
  export function spawnCommandLine(command, args, options) {
34
58
  const argv = args ?? [];
35
- return options?.shell ? [[command, ...argv].join(" "), []] : [command, argv];
59
+ if (!options?.shell) return [command, argv];
60
+ const quote = process.platform === "win32" ? cmdQuote : String;
61
+ return [[command, ...argv].map(quote).join(" "), []];
62
+ }
63
+
64
+ /**
65
+ * What to hand spawn() for a spec, or null when the launcher is not found. Applied at each spawn
66
+ * site, after doctor has built its --version args from the spec as configured. On win32 the command
67
+ * is looked up on every spawn (an update can move it) and started by the type of the file found:
68
+ * an .exe or .com directly, a .ps1 through PowerShell, anything else through cmd.exe.
69
+ * @param {string} command @param {string[] | undefined} args
70
+ * @param {{ shell?: boolean, env?: NodeJS.ProcessEnv } | undefined} options
71
+ * @returns {{ command: string, args: string[], options: any } | null}
72
+ */
73
+ export function spawnArgv(command, args, options) {
74
+ const argv = args ?? [];
75
+ if (!options?.shell) return { command, args: argv, options };
76
+ const env = options.env || process.env;
77
+ if (process.platform !== "win32") return commandExists(command, env) ? { command, args: argv, options } : null;
78
+ const file = findCommand(command, env);
79
+ if (!file) return null;
80
+ const ext = path.extname(file).toLowerCase();
81
+ // Exact arguments: cmd.exe would expand %VAR% and strip quotes and carets.
82
+ if (ext === ".exe" || ext === ".com") return { command: file, args: argv, options: { ...options, shell: false } };
83
+ // cmd.exe hands a .ps1 to its file association (an editor or an "open with" dialog) instead of
84
+ // running it.
85
+ if (ext === ".ps1") {
86
+ const rootKey = Object.keys(env).find((k) => k.toUpperCase() === "SYSTEMROOT");
87
+ const powershell = rootKey && env[rootKey]
88
+ ? path.win32.join(env[rootKey], "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
89
+ : "powershell.exe";
90
+ return {
91
+ command: powershell,
92
+ args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", file, ...argv],
93
+ options: { ...options, shell: false },
94
+ };
95
+ }
96
+ return { command: file, args: argv, options };
36
97
  }
37
98
 
38
- // Through a shell the spawn always succeeds (cmd.exe starts, then fails to find the launcher), so a
39
- // missing agy would read as an agent crash. Mirrors cmd's lookup: a path as given, a bare name in
40
- // each PATH entry, each with and without every PATHEXT extension.
41
99
  export function commandExists(command, env = process.env) {
100
+ return findCommand(command, env) !== null;
101
+ }
102
+
103
+ // The file cmd's lookup lands on, as an absolute path (the spawn may run in another directory), or
104
+ // null: a path as given, a bare name in each PATH entry, each with and without every PATHEXT
105
+ // extension. On win32 a file with no extension never matches: cmd reports it "not recognized"
106
+ // (measured), and npm installs an sh script of that name beside the .cmd.
107
+ function findCommand(command, env) {
42
108
  const name = String(command || "").replace(/^["']|["']$/g, "");
43
- if (!name) return false;
109
+ if (!name) return null;
44
110
  const pathKey = Object.keys(env).find((k) => k.toUpperCase() === "PATH");
45
111
  const extKey = Object.keys(env).find((k) => k.toUpperCase() === "PATHEXT");
46
112
  const exts = ["", ...String((extKey && env[extKey]) || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)];
47
- const isFile = (p) => { try { return existsSync(p) && statSync(p).isFile(); } catch { return false; } };
48
- const hit = (base) => exts.some((ext) => isFile(base + ext) || isFile(base + ext.toLowerCase()));
113
+ const win32 = process.platform === "win32";
114
+ const isFile = (p) => {
115
+ if (win32 && !path.extname(p)) return false;
116
+ try {
117
+ return statSync(p).isFile();
118
+ } catch (e) {
119
+ // A Store app's alias (WindowsApps\pwsh.exe) is a link into a folder this user cannot stat,
120
+ // so stat fails with EACCES, yet cmd runs it. A link to a missing file fails with ENOENT.
121
+ if (!win32 || (e.code !== "EACCES" && e.code !== "EPERM")) return false;
122
+ try { return lstatSync(p).isSymbolicLink(); } catch { return false; }
123
+ }
124
+ };
125
+ const hit = (base) => {
126
+ for (const ext of exts) {
127
+ for (const p of [base + ext.toLowerCase(), base + ext]) if (isFile(p)) return path.resolve(p);
128
+ }
129
+ return null;
130
+ };
49
131
  if (/[\\/]/.test(name)) return hit(name);
50
132
  const dirs = String((pathKey && env[pathKey]) || "").split(path.delimiter).filter(Boolean);
51
- return dirs.some((dir) => hit(path.join(dir.replace(/^"|"$/g, ""), name)));
133
+ for (const dir of dirs) {
134
+ const found = hit(path.join(dir.replace(/^"|"$/g, ""), name));
135
+ if (found) return found;
136
+ }
137
+ return null;
52
138
  }
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
 
@@ -55,7 +57,10 @@ function freshFields() {
55
57
  // Tool name per call id, to tell an ask_question (waits on the caller) from a backgrounded
56
58
  // command (finishes by itself).
57
59
  toolNames: new Map(),
58
- // Set by a usage_update, cleared by any other frame: agy closes every turn with one.
60
+ // The one-line label per call id, so a warning names the call still open, not the newest one.
61
+ toolLabels: new Map(),
62
+ // Set by a usage_update, cleared by any other frame: agy closes a completed turn, prompted or
63
+ // not, with one.
59
64
  usageAfterActivity: false,
60
65
  // The newest usage_update's { used, size }; unlike the reply's usage it covers a continuation.
61
66
  contextUsage: undefined,
@@ -66,6 +71,11 @@ function freshFields() {
66
71
  // ~/.gemini/antigravity-cli/brain/<sessionId>/. Keyed by path, so a rewrite replaces.
67
72
  artifacts: new Map(),
68
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(),
69
79
  lastToolLabel: null,
70
80
  sessionTitle: undefined,
71
81
  };
@@ -109,7 +119,7 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
109
119
  if (toolCallId != null && !isTerminalToolStatus(status)) {
110
120
  state.activeToolCalls.add(toolCallId);
111
121
  // A fresh tool_call frame for a finished id is the agent reusing it, not history.
112
- state.finishedToolCalls.delete(toolCallId);
122
+ if (state.finishedToolCalls.delete(toolCallId)) state.questions.delete(toolCallId);
113
123
  }
114
124
  if (toolCallId != null && isTerminalToolStatus(status)) state.finishedToolCalls.add(toolCallId);
115
125
  if (isTerminalToolStatus(status) && state.activeToolCalls.size === 0) state.collectingPostToolResult = true;
@@ -140,10 +150,50 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
140
150
  }
141
151
  },
142
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
+
143
161
  // Unfinished calls that end on their own: a backgrounded command or a scheduled wake-up. An
144
162
  // ask_question waits on the caller instead, so it is never waited for.
145
163
  backgroundToolCalls() {
146
- 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) ?? []);
147
197
  },
148
198
 
149
199
  // True while a message chunk still belongs in the result: before any tool ran, or after
@@ -152,6 +202,29 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
152
202
  return !state.sawToolCall || (state.collectingPostToolResult && state.activeToolCalls.size === 0);
153
203
  },
154
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
+
155
228
  // The artifact's content arrives whole in rawInput.Content; Path is where agy saved it.
156
229
  recordArtifact(input) {
157
230
  const meta = input?.ArtifactMetadata;
package/src/version.js CHANGED
@@ -11,8 +11,9 @@ function readVersion() {
11
11
  // Captured once, for the ACP and MCP identity sent at connect.
12
12
  export const VERSION = readVersion();
13
13
 
14
- // Read fresh for doctor: /reload-plugins does not restart the server, so the constant goes stale
15
- // after an in-place upgrade.
14
+ // Read fresh for doctor: /reload-plugins does not restart the server, so after an in-place upgrade
15
+ // the constant is stale. doctor then reports the installed version; the running server still runs
16
+ // the old code until restarted.
16
17
  export function readPackageVersion() {
17
18
  try {
18
19
  return readVersion();