agy-delegate-mcp 1.5.0 → 1.6.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,34 @@ All notable changes to this project are documented here. The format follows
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [1.6.0] - 2026-11-22
10
+
11
+ ### Changed
12
+
13
+ - On Windows the launcher is found first and started by file type. agy.exe runs directly rather
14
+ than through cmd.exe, so its arguments arrive exactly; a `.ps1` runs through Windows PowerShell; a
15
+ `.cmd` or `.bat` runs through cmd.exe with its arguments quoted. A Store app alias counts as
16
+ found, a file with no extension never matches, and a bare name is no longer run from the
17
+ workspace.
18
+ - In `ACP_AGENT_ARGS` a quoted section after `=` belongs to its argument, so
19
+ `--log-file="C:\a b\x.log"` is one argument. A quote inside a word stays a character.
20
+ - A resume that omits `model` on a server with no record of the session says so in
21
+ `protocolWarnings`.
22
+
23
+ ### Fixed
24
+
25
+ - A launcher path or argument with spaces reaches a `.cmd` launcher whole.
26
+ - `force` cancel kills unsettled turns alongside the other turns' closes, not after them.
27
+ - A delegation cancelled during setup carries `resultSource: "none"`.
28
+ - The unfinished-tool warning and the background wait's progress line name the command still
29
+ running. The wait's limit is named only when it ran out, and a cancel or steer in its last check
30
+ is honoured.
31
+ - An effort reply that omits the model keeps the model recorded for the session.
32
+ - An aborted `doctor` spawns no version probe, and an aborted probe returns only once it has
33
+ closed, also when the abort falls just before its timeout.
34
+ - A signal after stdin closes sets the exit code. A second signal kills every agent shutdown
35
+ stopped, except one whose exit was already confirmed.
36
+
9
37
  ## [1.5.0] - 2026-11-22
10
38
 
11
39
  ### Changed
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-delegate-mcp",
3
- "version": "1.5.0",
3
+ "version": "1.6.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.",
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) => {
@@ -185,9 +190,9 @@ export class AcpClient extends EventEmitter {
185
190
  }
186
191
  hasSteer() { return this._steers.length > 0; }
187
192
  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.
193
+ // Read by the background wait: after a cancel agy closes the call without the usage_update that
194
+ // ends a continuation. Closes the steer window: a later steer would restart the cancelled turn.
195
+ // delegate listens for the event to end its setup when no prompt has gone out.
191
196
  cancel(sessionId) {
192
197
  this.cancelRequested = true;
193
198
  this._steerWindow = "closed";
package/src/delegate.js CHANGED
@@ -383,6 +383,7 @@ export async function runDelegate({
383
383
  const slashed = (s) => String(s).replace(/\\/g, "/");
384
384
  const named = path && slashed(label).includes(slashed(path));
385
385
  state.lastToolLabel = (label + (path && !named ? " — " + path : "")).replace(/\s+/g, " ").trim();
386
+ if (up.toolCallId != null) state.toolLabels.set(up.toolCallId, state.lastToolLabel);
386
387
  try { onProgress?.(("running: " + state.lastToolLabel).slice(0, 200)); } catch {}
387
388
  } else {
388
389
  state.updateToolStatus(up.toolCallId, up.status);
@@ -401,20 +402,24 @@ export async function runDelegate({
401
402
  // finishes the command and continues the turn unprompted, closing with a usage_update (measured,
402
403
  // agy 1.5.14). Stopping agy at end_turn would kill the command. The hard cap still bounds the wait.
403
404
  let backgroundWaited;
405
+ // Set only when the wait ran its full length, which is what the warning blames.
406
+ let backgroundWaitRanOut = false;
404
407
  // One clock per delegation, kept across steered turns.
405
408
  let backgroundStartedAt;
406
409
  const waitForBackground = async () => {
407
- try { onProgress?.(`waiting for agy's background command: ${state.lastToolLabel ?? "tool"}`.slice(0, 200)); } catch {}
410
+ const label = state.toolLabels.get(state.backgroundToolCalls()[0]) ?? state.lastToolLabel ?? "tool";
411
+ try { onProgress?.(`waiting for agy's background command: ${label}`.slice(0, 200)); } catch {}
408
412
  const startedAt = (backgroundStartedAt ??= Date.now());
409
413
  for (;;) {
410
414
  await new Promise((r) => setTimeout(r, Math.min(250, backgroundSettleMs)));
411
415
  backgroundWaited = Date.now() - startedAt;
412
- if (backgroundWaited >= backgroundWaitMs) return;
413
416
  // The delegation already failed (agent exit, abort, hard cap): nobody reads this wait.
414
417
  if (supervisor.settled) return;
418
+ // Ahead of the deadline, so a cancel or steer in the last tick is not lost to it.
415
419
  if (client.cancelRequested) return "cancelled";
416
420
  // A steer redirects the turn; its own prompt reply is what ends it now.
417
421
  if (client.hasSteer?.()) return;
422
+ if (backgroundWaited >= backgroundWaitMs) { backgroundWaitRanOut = true; return; }
418
423
  if (state.backgroundToolCalls().length) continue;
419
424
  const quietMs = Date.now() - state.lastFrameAt;
420
425
  if (state.usageAfterActivity && quietMs >= backgroundSettleMs) return;
@@ -430,6 +435,7 @@ export async function runDelegate({
430
435
  let out;
431
436
  let servedModel;
432
437
  let effectiveEffort;
438
+ let noSettingsRecord = false;
433
439
  const contextWarnings = [];
434
440
  try {
435
441
  const res = await supervisor.supervise(async () => {
@@ -446,6 +452,8 @@ export async function runDelegate({
446
452
  if (client.cancelRequested) return cancelledInSetup;
447
453
  // Only a resume that took inherits: a fallback to a fresh session is a different session.
448
454
  const earlier = resumeSessionId && sessionId === resumeSessionId ? sessionSettings.get(sessionId) : undefined;
455
+ // The record lives in memory: a server restarted since the session ran has none to apply.
456
+ noSettingsRecord = !!resumeSessionId && sessionId === resumeSessionId && !earlier && model === undefined;
449
457
  const targetModel = model ?? earlier?.model;
450
458
  // A remembered effort holds only on the model it was set for: another model may not offer it.
451
459
  const targetEffort = effort ?? (targetModel === earlier?.model ? earlier?.effort : undefined);
@@ -456,15 +464,20 @@ export async function runDelegate({
456
464
  }
457
465
  }
458
466
  if (client.cancelRequested) return cancelledInSetup;
467
+ // Kept across the effort reply, which may carry only the option it changed.
468
+ const modelBeforeEffort = configOptionValue(options, "model");
459
469
  if (targetEffort !== undefined) {
460
- const target = targetModel ?? configOptionValue(options, "model") ?? "the session's model";
470
+ const target = targetModel ?? modelBeforeEffort ?? "the session's model";
461
471
  options = optionsFrom(await applyEffort(client, sessionId, target, targetEffort, options));
462
472
  }
463
473
  if (client.cancelRequested) return cancelledInSetup;
464
- servedModel = configOptionValue(options, "model");
474
+ servedModel = configOptionValue(options, "model") ?? modelBeforeEffort;
465
475
  // 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 });
476
+ // is tied to that model. A session run on agy's defaults is recorded too, as having none, so
477
+ // its resume here does not read as a restart.
478
+ rememberSettings(sessionId, targetModel !== undefined || targetEffort !== undefined
479
+ ? { model: targetModel ?? servedModel, effort: targetEffort }
480
+ : {});
468
481
  // What agy reported in force, never the requested value.
469
482
  effectiveEffort = effortSettings(options);
470
483
  await client.setMode(sessionId, agyMode);
@@ -538,15 +551,18 @@ export async function runDelegate({
538
551
  // ask_question waiting on the caller.
539
552
  result = state.unfinishedToolText;
540
553
  resultSource = result ? "unfinished-tool" : "none";
554
+ // The open command if there is one, else the question; not the newest tool.
555
+ const openId = state.backgroundToolCalls()[0] ?? [...state.activeToolCalls][0];
556
+ const openLabel = state.toolLabels.get(openId) ?? state.lastToolLabel;
541
557
  // A refusal or output cap is not waited on, so a command can be open with no wait.
542
558
  const cause = !state.backgroundToolCalls().length
543
559
  ? " agy is asking a question (ask_question), which a resume answers."
544
- : backgroundWaited !== undefined
560
+ : backgroundWaitRanOut
545
561
  ? ` agy moved it to the background, and it was still running after the bridge waited ${fmtDuration(backgroundWaited)}`
546
562
  + " (AGY_DELEGATE_BACKGROUND_WAIT_MS); it stops when the bridge stops agy."
547
563
  : ` agy ended the turn (${res?.stopReason}) with it still running; it stops when the bridge stops agy.`;
548
564
  protocolWarnings.push(
549
- `the turn ended with a tool call still running (${state.lastToolLabel ?? "unnamed tool"}).`
565
+ `the turn ended with a tool call still running (${openLabel ?? "unnamed tool"}).`
550
566
  + cause
551
567
  + (result ? " result is agy's message from while it ran." : " agy sent no message while it ran.")
552
568
  );
@@ -579,7 +595,8 @@ export async function runDelegate({
579
595
  // resultSource appears only as a caveat; resumed only when a resume took.
580
596
  if (resultSource !== "post-tool" && resultSource !== "tool-free-stream") out.resultSource = resultSource;
581
597
  if (!!resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
582
- // Present when the served model differs from the requested one, so always when model was omitted.
598
+ // Present when the served model differs from the requested one, so whenever model was omitted
599
+ // and agy reports one.
583
600
  if (servedModel !== undefined && servedModel !== model) out.effectiveModel = servedModel;
584
601
  if (effectiveEffort !== undefined) out.effectiveEffort = effectiveEffort;
585
602
  if (stopReason !== undefined) out.stopReason = stopReason;
@@ -602,6 +619,9 @@ export async function runDelegate({
602
619
  .map((a) => ({ path: a.path, ...(a.summary !== undefined ? { summary: a.summary } : {}) }));
603
620
  if (others.length) out.artifacts = others;
604
621
  if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
622
+ if (noSettingsRecord) {
623
+ 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.`);
624
+ }
605
625
  protocolWarnings.push(...contextWarnings);
606
626
  protocolWarnings.push(...frameWarnings);
607
627
  protocolWarnings.push(...steerWarnings);
@@ -610,7 +630,7 @@ export async function runDelegate({
610
630
  } catch (err) {
611
631
  // A caller's cancel before the prompt is a cancelled result, even if a config call then failed.
612
632
  if (cancelledInSetupByCaller && sessionId) {
613
- out = { result: "", sessionId, stopReason: "cancelled" };
633
+ out = { result: "", sessionId, resultSource: "none", stopReason: "cancelled" };
614
634
  if (resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
615
635
  if (resumeError) out.protocolWarnings = [`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`];
616
636
  return out;
@@ -664,10 +684,11 @@ export async function runDelegate({
664
684
  signal?.removeEventListener("abort", onAbort);
665
685
  client.off?.("cancel", onCancel);
666
686
  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.
687
+ // Awaited, so agy has exited when the caller gets the result, or a warning says the exit was not
688
+ // seen; otherwise agy still holds the workspace as its cwd (deleting it fails with EBUSY on
689
+ // Windows). The handle stays registered meanwhile, so force cancel and shutdown can cut the grace
690
+ // short. Graceful after a completed turn, so agy closes its conversation database; a stall,
691
+ // abort or exit is killed at once.
671
692
  const killNow = signal?.aborted || ["handshake-timeout", "hard-cap", "idle-timeout", "aborted", "agent-exit"].includes(failed?.reason);
672
693
  // A host abort during the close is still an abort: a force stop ends the grace and kills.
673
694
  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
  }
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
@@ -337,13 +337,12 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
337
337
  if (cut.size === live.length || Date.now() >= graceEnds) break;
338
338
  await new Promise((r) => setTimeout(r, Math.min(50, Math.max(1, graceEnds - Date.now()))));
339
339
  }
340
- await Promise.all(closing);
341
- // A snapshot, so a resume registering during teardown is not swept from the map.
340
+ // Classified the moment the grace ends and killed alongside the closes, not after them: a slow
341
+ // close would delay the kill, and a turn ending meanwhile would be reported killed. A snapshot,
342
+ // so a resume registering during teardown is not swept from the map.
342
343
  const toKill = live.filter((handle) => !cut.has(handle));
344
+ const [observed] = await Promise.all([Promise.all(toKill.map(stopQuietly)), Promise.all(closing)]);
343
345
  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
346
  // "killed" needs an observed exit; without one the handles stay and force can be retried.
348
347
  if (!observed.every(Boolean)) return statusResult("cancelled", sessionId);
349
348
  for (const handle of toKill) unregisterInFlight(inFlight, sessionId, handle);
@@ -433,26 +432,39 @@ export function installSignalCleanup(map, {
433
432
  } = {}) {
434
433
  let shuttingDown = false;
435
434
  let signalsSeen = 0;
435
+ // The code shutdown exits with: a signal's, even when it follows the stdin EOF.
436
+ let exitCode = 0;
437
+ // Every handle a stop went to, so a second signal still reaches one that has since unregistered.
438
+ const dispatched = new Set();
436
439
  const shutdown = (code, fromSignal = false) => {
437
440
  // Only a second signal skips the wait for the kills: a hangup closes stdin and sends SIGHUP,
438
441
  // in either order. The first stops may still be in their ps walk, so the groups are killed
439
442
  // synchronously before leaving.
440
443
  if (fromSignal) signalsSeen++;
441
444
  if (shuttingDown) {
445
+ if (fromSignal && signalsSeen === 1) { exitCode = code; setExitCode(code); }
442
446
  if (signalsSeen < 2) return undefined;
443
- for (const handles of [...map.values(), pending]) {
444
- for (const handle of handles) { try { handle.client.killNow?.(); } catch {} }
447
+ for (const handle of new Set([...dispatched, ...[...map.values()].flatMap((h) => [...h]), ...pending])) {
448
+ try { handle.client.killNow?.(); } catch {}
445
449
  }
446
450
  return exit(code);
447
451
  }
448
452
  shuttingDown = true;
453
+ exitCode = code;
449
454
  // Set now: if the loop runs dry before the scheduled exit, the process still exits with it.
450
455
  setExitCode(code);
451
456
  const stops = [];
452
457
  // A stop that did not see the exit is retried once, as the delegation does.
453
458
  const stopOnce = (handle) => Promise.resolve(handle.client.stop()).catch(() => false);
454
459
  const dispatch = (handle) => {
455
- try { stops.push(stopOnce(handle).then((exited) => (exited === false ? stopOnce(handle) : exited))); } catch {}
460
+ dispatched.add(handle);
461
+ try {
462
+ stops.push(stopOnce(handle).then((exited) => (exited === false ? stopOnce(handle) : exited)).then((exited) => {
463
+ // Its group is killed and its id may be reused: a second signal must not kill it again.
464
+ if (exited !== false) dispatched.delete(handle);
465
+ return exited;
466
+ }));
467
+ } catch {}
456
468
  };
457
469
  for (const handles of map.values()) for (const handle of handles) dispatch(handle);
458
470
  // Delegations still in their handshake, with no session id yet.
@@ -460,7 +472,7 @@ export function installSignalCleanup(map, {
460
472
  // Exit waits for the kills: on Windows taskkill is a separate process, and exiting first left
461
473
  // the launcher and agent running (measured). stop() bounds itself. The exit is scheduled onto
462
474
  // a clean loop turn, off the settlement stack.
463
- const leave = () => schedule(() => exit(code));
475
+ const leave = () => schedule(() => exit(exitCode));
464
476
  Promise.all(stops).then(leave, leave);
465
477
  };
466
478
  // On POSIX each agent has its own process group, so a signal to this process does not reach it.
package/src/spawn.js CHANGED
@@ -1,14 +1,26 @@
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
@@ -16,9 +28,10 @@ export function splitArgs(raw) {
16
28
  // which only the flag covers.
17
29
  export const DEFAULT_AGENT_ARGS = Object.freeze(["acp", "--dangerously-skip-permissions"]);
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
@@ -55,7 +55,10 @@ function freshFields() {
55
55
  // Tool name per call id, to tell an ask_question (waits on the caller) from a backgrounded
56
56
  // command (finishes by itself).
57
57
  toolNames: new Map(),
58
- // Set by a usage_update, cleared by any other frame: agy closes every turn with one.
58
+ // The one-line label per call id, so a warning names the call still open, not the newest one.
59
+ toolLabels: new Map(),
60
+ // Set by a usage_update, cleared by any other frame: agy closes a completed turn, prompted or
61
+ // not, with one.
59
62
  usageAfterActivity: false,
60
63
  // The newest usage_update's { used, size }; unlike the reply's usage it covers a continuation.
61
64
  contextUsage: undefined,
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();