agy-delegate-mcp 1.4.0 → 1.5.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/src/server.js CHANGED
@@ -23,10 +23,8 @@ if (nodeMajor < 20) {
23
23
  process.exit(1);
24
24
  }
25
25
 
26
- // sessionId -> the set of delegations currently running on it. A set, not a single handle,
27
- // because a resume can race the turn it resumes: both are live, both are cancellable, and
28
- // keying one handle per id let whichever finished first deregister the other — after which
29
- // cancel reported a running session as already ended.
26
+ // sessionId -> the delegations running on it. A set: a resume can race the turn it resumes, and
27
+ // with one handle per id the first to finish would deregister the other.
30
28
  const inFlight = new Map();
31
29
  function registerInFlight(map, sessionId, handle) {
32
30
  const handles = map.get(sessionId);
@@ -43,37 +41,29 @@ function unregisterInFlight(map, sessionId, handle) {
43
41
  handles.delete(handle);
44
42
  if (handles.size === 0) map.delete(sessionId);
45
43
  }
46
- // Delegations whose session has not opened yet. inFlight is keyed by session id, and that id
47
- // arrives about 3.4s after the agent process does — so between client.start() and session/new
48
- // there is a live, auto-approved agent that the map cannot name. Shutdown walks this too.
49
- // cancel deliberately does not: an id the caller has never been given is not one it can pass.
44
+ // Delegations whose session has not opened yet (about 3.4 s after the spawn): a live agent that
45
+ // inFlight cannot name. Shutdown walks this; cancel cannot, having no id to pass.
50
46
  const pendingDelegations = new Set();
51
47
 
52
- // Session ids seen this process, kept after the turn ends so cancel can tell a finished
53
- // session (resumable, only the turn is over) from an id that never existed. Bounded so a
54
- // long-lived server does not grow without limit.
48
+ // Session ids seen by this process, kept after the turn so cancel can tell a finished session
49
+ // (still resumable) from an unknown id. Bounded.
55
50
  const seenSessions = new Set();
56
51
  const SEEN_SESSIONS_CAP = 500;
57
52
  function rememberSession(set, id) {
58
53
  if (id == null) return;
59
- // Set iteration order makes the delete-then-add a small LRU: a session that is still being
60
- // resumed moves back to the recent end, so it outlives an equally old id that was seen once
61
- // and never again. Without it the id a caller is actually working with ages out on insertion
62
- // order alone, and cancel then calls a live, resumable session one that never existed.
54
+ // Delete-then-add makes the Set an LRU, so a session still being resumed does not age out.
63
55
  if (set.has(id)) set.delete(id);
64
56
  set.add(id);
65
57
  if (set.size > SEEN_SESSIONS_CAP) set.delete(set.values().next().value);
66
58
  }
67
59
 
68
- // Loaded at connect, before any tool schema is, so this carries only pre-call facts: what a
69
- // caller needs to decide whether to delegate at all. Call-time facts belong on the parameter
70
- // descriptions, read while the call is being written.
60
+ // Loaded at connect: only what a caller needs to decide whether to delegate. Call-time facts go on
61
+ // the parameter descriptions.
71
62
  export const SERVER_INSTRUCTIONS = `Delegate coding work to Antigravity (agy) through the delegate tool. Every permission the agent requests is auto-approved, in every mode: agent/plan/ask reach any file the user account can, and mode instructs the agent rather than limiting it. Scope workspace tightly and review the git diff after every run — filesReportedByEditTools carries only what the agent's edit tools reported; the diff is authoritative.`;
72
63
 
73
- // No outputSchema: that also requires structuredContent, and a host that reads both (Codex)
74
- // puts the payload in context twice. One JSON text block; the .strict() copy is in
75
- // delegate.test.js. Field meanings: skills/delegate/reference.md. cancel and steer statuses
76
- // live on their tool descriptions.
64
+ // No outputSchema: it requires structuredContent too, and a host that reads both (Codex) puts the
65
+ // payload in context twice. The .strict() copy is in delegate.test.js; field meanings are in
66
+ // skills/delegate/reference.md.
77
67
  export const delegateOutputShape = {
78
68
  result: z.string(),
79
69
  resultSource: z.enum(["pre-tool-fallback", "unfinished-tool", "none"]).optional(),
@@ -106,9 +96,9 @@ export const delegateOutputShape = {
106
96
  })).optional(),
107
97
  };
108
98
 
109
- // Same in-repo contract as delegateOutputShape. Relayed agent fields stay unknown so a
110
- // weird protocolVersion is a diagnostic, not a failed call. doctor.test.js holds the
111
- // strict copy. Handshake is its own shape: a .strict() on agent does not look inside it.
99
+ // Same in-repo contract; the strict copy is in doctor.test.js. Relayed agent fields stay unknown,
100
+ // so an odd value is a diagnostic, not a failed call. Its own shape because .strict() on agent
101
+ // does not look inside it.
112
102
  export const doctorHandshakeShape = {
113
103
  ok: z.boolean(),
114
104
  error: z.string().optional(),
@@ -118,7 +108,7 @@ export const doctorHandshakeShape = {
118
108
  currentModel: z.unknown().optional(),
119
109
  modes: z.array(z.unknown()).optional(),
120
110
  tier: z.unknown().optional(),
121
- // Built here rather than relayed, so it gets a real type where its neighbours get z.unknown().
111
+ // Built here, not relayed, so it gets a real type.
122
112
  currentModelOptions: z.array(z.object({
123
113
  id: z.string(),
124
114
  name: z.string().optional(),
@@ -158,25 +148,26 @@ export const doctorOutputShape = {
158
148
  export const delegateInputSchema = z.object({
159
149
  spec: z.string().trim().min(1, "spec must not be blank").describe("Task brief: goal, scope, fixed decisions quoted exactly, acceptance criteria. Sent as written. Point at files to read rather than pasting code, or attach them with contextFiles."),
160
150
  mode: z.enum(["agent", "plan", "ask"]).default("agent").describe("agent implements; plan writes a plan, returned as plan; ask answers. plan and ask are instructions to the agent, not limits."),
161
- resumeSessionId: z.string().optional().describe("Continue an existing agy session."),
151
+ resumeSessionId: z.string().trim().optional().describe("Continue an existing agy session."),
162
152
  workspace: z.string().trim().min(1, "workspace must not be blank").describe("The agent's working directory, not a limit. Smallest directory holding the task's files; with no such directory the project root is the floor. Must already exist; never create one for the call."),
163
- model: z.string().trim().min(1, "model must be a non-empty string").optional().describe("agy base model id, no level suffix: gemini-4-neon, gemini-3.8-flash. Omitted, agy's default runs and effectiveModel names it. doctor deep:true lists every id."),
164
- // Which values a model offers is only knowable after selecting it, so this stays an open
165
- // string and the bridge validates the exact token against the live option list.
153
+ model: z.string().trim().min(1, "model must be a non-empty string").optional().describe("agy base model id, no level suffix: gemini-4-neon, gemini-3.8-flash. Omitted, agy's default runs (a resume keeps the model last set on the session) and effectiveModel names it. doctor deep:true lists every id."),
154
+ // Open string: a model's levels are known only once it is selected, and are validated then.
166
155
  effort: z.string().trim().min(1).optional().describe("agy thinking level for the selected model (low, medium, high, xhigh). Levels differ per model; invalid values fail before the prompt and name the accepted set. Pass only when the user asks for agy effort — the host's own reasoning setting is unrelated."),
167
156
  contextFiles: z.array(z.string()).optional().describe("Paths to attach instead of pasting contents into spec. Text becomes references the agent may open; images (png/jpg/gif/webp, <5MB) are sent inline. Relative paths resolve against workspace but are not limited to it. Skips are reported in protocolWarnings, never fatal."),
168
157
  });
169
158
 
170
- // Every turn running on the id is steered, as cancel cancels every one: the caller named a
171
- // session. A delegation still setting up its session takes no steer until its prompt is out.
159
+ // Steers every turn running on the id, as cancel does: the caller named a session.
172
160
  export function steerSession(map, seen, sessionId, message) {
173
161
  const handles = map.get(sessionId);
174
162
  if (!handles || handles.size === 0) return seen.has(sessionId) ? "not-running" : "not-found";
175
- let sent = false;
163
+ const statuses = new Set();
176
164
  for (const handle of handles) {
177
- try { if (handle.client.steer?.(sessionId, message)) sent = true; } catch {}
165
+ // A turn that has ended is only tearing down, whatever state its window was left in.
166
+ if (handle.ended) { statuses.add("not-running"); continue; }
167
+ try { statuses.add(handle.client.steer?.(sessionId, message) ?? "not-running"); } catch { statuses.add("not-running"); }
178
168
  }
179
- return sent ? "steered" : "not-ready";
169
+ for (const status of ["steered", "not-ready"]) if (statuses.has(status)) return status;
170
+ return "not-running";
180
171
  }
181
172
 
182
173
  /**
@@ -198,8 +189,7 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
198
189
  if (progressToken != null) {
199
190
  let progress = 0;
200
191
  onProgress = (message) => {
201
- // sendNotification is async: its rejection settles outside this try and would exit the
202
- // server. The try stays for a sync throw, which lands before Promise.resolve can wrap it.
192
+ // An unhandled rejection would exit the server; the try catches a sync throw.
203
193
  try {
204
194
  Promise.resolve(extra.sendNotification({
205
195
  method: "notifications/progress",
@@ -215,7 +205,8 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
215
205
  const out = await runDelegate({
216
206
  spec,
217
207
  mode,
218
- resumeSessionId,
208
+ // Blank is no resume: hosts fill optional fields with "".
209
+ resumeSessionId: resumeSessionId || undefined,
219
210
  workspace,
220
211
  model,
221
212
  effort,
@@ -228,45 +219,44 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
228
219
  },
229
220
  onSessionReady: (sessionId, client) => {
230
221
  capturedSessionId = sessionId;
231
- // The same handle moves across, so a shutdown racing this boundary finds it on exactly
232
- // one side of it rather than on neither.
222
+ // The same handle moves across, so a racing shutdown finds it on one side.
233
223
  handle ??= { client, cancelRequested: false };
234
224
  pending.delete(handle);
235
225
  registerInFlight(inFlight, sessionId, handle);
236
226
  rememberSession(seenSessions, sessionId);
237
- // Emit the id the moment the session opens, before the turn finishes, so a host that
238
- // can call tools concurrently has something to pass to cancel mid-run — otherwise the
239
- // id only arrives when delegate returns, by which point there is nothing to cancel.
240
- // (Hosts that serialize tool calls still cannot cancel in flight; that is a host limit.)
227
+ // Sent as the session opens, so a host that calls tools concurrently can cancel or steer
228
+ // mid-run.
241
229
  onProgress(`session ready: ${sessionId}`);
242
230
  },
231
+ onTurnEnd: () => { if (handle) handle.ended = true; },
243
232
  });
244
233
  if (handle?.cancelRequested) out.cancelRequested = true;
245
234
  return { content: [{ type: "text", text: JSON.stringify(out) }] };
246
235
  } catch (err) {
247
236
  return {
248
- // The reason is already decided upstream; naming it here saves the caller parsing
249
- // prose to tell a timeout from a rejected argument.
237
+ // The reason in brackets spares the caller parsing prose.
250
238
  content: [{ type: "text", text: `delegate failed${err?.reason ? ` [${err.reason}]` : ""}: ` + (err?.message || String(err)) }],
251
239
  isError: true,
252
240
  };
253
241
  } finally {
254
- // Drops only this delegation's own handle; the id stays registered while another turn
255
- // is still running on it. A delegation that failed before its session opened is only ever
256
- // in pending, and one that opened is only ever in the map — the delete covers both.
242
+ // Only this delegation's handle; the id stays registered while another turn runs on it.
257
243
  if (handle) pending.delete(handle);
258
244
  if (capturedSessionId) unregisterInFlight(inFlight, capturedSessionId, handle);
259
245
  }
260
246
  }
261
247
 
248
+ // cancel and steer take the id delegate announces; a blank one is a malformed call, not a stale id.
249
+ const sessionIdInput = z.string().trim().min(1).describe("From delegate's \"session ready: <id>\" progress notification or its result.");
250
+
262
251
  /**
263
252
  * @param {{
264
253
  * runDelegate?: (opts: any) => Promise<any>,
265
254
  * runDoctor?: (opts: any) => Promise<any>,
266
255
  * forceGraceMs?: number,
256
+ * pending?: Set<any>,
267
257
  * }} [opts]
268
258
  */
269
- export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000 } = {}) {
259
+ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000, pending = pendingDelegations } = {}) {
270
260
  const runDelegate = runDelegateInjected || runDelegateDefault;
271
261
  const runDoctor = runDoctorInjected || runDoctorDefault;
272
262
  const server = new McpServer(
@@ -288,7 +278,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
288
278
  openWorldHint: true,
289
279
  },
290
280
  },
291
- async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, pending: pendingDelegations, seenSessions })
281
+ async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, pending, seenSessions })
292
282
  );
293
283
 
294
284
  server.registerTool(
@@ -297,7 +287,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
297
287
  description:
298
288
  "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).",
299
289
  inputSchema: {
300
- sessionId: z.string(),
290
+ sessionId: sessionIdInput,
301
291
  force: z.boolean().default(false).describe("Kill the agent process if the turn is still running after a short grace period."),
302
292
  },
303
293
  annotations: {
@@ -311,39 +301,50 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
311
301
  async ({ sessionId, force }) => {
312
302
  const handles = inFlight.get(sessionId);
313
303
  if (!handles || handles.size === 0) {
314
- // A finished session and a garbage id are both "not in flight". Reporting them alike
315
- // would read as "bad id" for a session that ran and is still resumable.
304
+ // A finished session is still resumable, unlike an unknown id.
316
305
  const known = seenSessions.has(sessionId);
317
306
  return statusResult(known ? "not-running" : "not-found", sessionId);
318
307
  }
319
- // Cancel every turn running on the id: the caller named a session, not one of the
320
- // turns that happen to share it.
321
- for (const handle of handles) handle.cancelRequested = true;
322
- await Promise.all([...handles].map((handle) => handle.client.cancel(sessionId).catch(() => {})));
308
+ // A handle whose turn ended stays registered while agy closes. A cancel leaves its result
309
+ // alone; force only cuts the close short.
310
+ const ending = [...handles].filter((handle) => handle.ended);
311
+ const live = [...handles].filter((handle) => !handle.ended);
312
+ const stopQuietly = (handle) => Promise.resolve(handle.client.stop()).catch(() => false);
313
+ if (live.length === 0) {
314
+ if (force) await Promise.all(ending.map(stopQuietly));
315
+ return statusResult("not-running", sessionId);
316
+ }
317
+ // Every turn running on the id: the caller named a session.
318
+ for (const handle of live) handle.cancelRequested = true;
319
+ await Promise.all(live.map((handle) => handle.client.cancel(sessionId).catch(() => {})));
323
320
  if (!force) {
324
- // The handles stay registered: session/cancel is best-effort, so the turn may still
325
- // be running. Dropping them here made the natural escalation — cancel, wait, cancel
326
- // with force — report not-found while the agent was alive. Each delegation's own
327
- // finally removes its handle when the turn actually settles.
321
+ // The handles stay registered: session/cancel is best-effort, and a follow-up force must
322
+ // still find a turn that kept running.
328
323
  return statusResult("cancelled", sessionId);
329
324
  }
330
- // Watched rather than slept through: agy stops a cancelled turn in milliseconds, and the
331
- // delegation's finally drops its handle the moment the turn settles.
325
+ // Each turn's close is cut as soon as it settles (agy stops a cancelled turn in milliseconds);
326
+ // what still runs when the grace ends is killed.
327
+ const closing = ending.map(stopQuietly);
328
+ const cut = new Set();
332
329
  const graceEnds = Date.now() + forceGraceMs;
333
- while (Date.now() < graceEnds && inFlight.get(sessionId)?.size) {
330
+ for (;;) {
331
+ for (const handle of live) {
332
+ if (!cut.has(handle) && (handle.ended || !inFlight.get(sessionId)?.has(handle))) {
333
+ cut.add(handle);
334
+ closing.push(stopQuietly(handle));
335
+ }
336
+ }
337
+ if (cut.size === live.length || Date.now() >= graceEnds) break;
334
338
  await new Promise((r) => setTimeout(r, Math.min(50, Math.max(1, graceEnds - Date.now()))));
335
339
  }
336
- const stillRunning = inFlight.get(sessionId);
337
- if (!stillRunning || stillRunning.size === 0) return statusResult("cancelled", sessionId);
338
- // Snapshot before awaiting stop. A resume that registers during teardown must not be
339
- // swept out of the map — it was never killed, and inFlight.delete(sessionId) would
340
- // hide it from cancel and shutdown.
341
- const toKill = [...stillRunning];
340
+ await Promise.all(closing);
341
+ // A snapshot, so a resume registering during teardown is not swept from the map.
342
+ const toKill = live.filter((handle) => !cut.has(handle));
343
+ if (toKill.length === 0) return statusResult("cancelled", sessionId);
342
344
  const observed = await Promise.all(
343
345
  toKill.map((handle) => Promise.resolve(handle.client.stop()).catch(() => false))
344
346
  );
345
- // "killed" claims the process is gone, so it needs the exit, not just a dispatched signal.
346
- // When one does not follow, the handles stay registered and force can be tried again.
347
+ // "killed" needs an observed exit; without one the handles stay and force can be retried.
347
348
  if (!observed.every(Boolean)) return statusResult("cancelled", sessionId);
348
349
  for (const handle of toKill) unregisterInFlight(inFlight, sessionId, handle);
349
350
  return statusResult("killed", sessionId);
@@ -356,7 +357,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
356
357
  description:
357
358
  "Redirect an in-flight delegation by sessionId: message goes to agy as a new instruction for the running turn, and the delegate call returns the redirected turn's result. Status: steered (sent), not-ready (prompt not sent yet; retry), not-running (turn already ended — resume instead), not-found (id not in this process's recent session history).",
358
359
  inputSchema: {
359
- sessionId: z.string(),
360
+ sessionId: sessionIdInput,
360
361
  message: z.string().trim().min(1, "message must not be blank").describe("The new instruction for agy."),
361
362
  },
362
363
  annotations: {
@@ -389,15 +390,23 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
389
390
  openWorldHint: false,
390
391
  },
391
392
  },
392
- async ({ deep }) => {
393
- const out = await runDoctor({
394
- deep,
395
- getClientInfo: () => ({
396
- capabilities: server.server.getClientCapabilities(),
397
- version: server.server.getClientVersion(),
398
- }),
399
- });
400
- return { content: [{ type: "text", text: JSON.stringify(out) }] };
393
+ async ({ deep }, extra) => {
394
+ // In pending while it runs, so shutdown stops doctor's agent too.
395
+ let handle;
396
+ try {
397
+ const out = await runDoctor({
398
+ deep,
399
+ signal: extra?.signal,
400
+ onClientReady: (client) => { handle = { client }; pending.add(handle); },
401
+ getClientInfo: () => ({
402
+ capabilities: server.server.getClientCapabilities(),
403
+ version: server.server.getClientVersion(),
404
+ }),
405
+ });
406
+ return { content: [{ type: "text", text: JSON.stringify(out) }] };
407
+ } finally {
408
+ if (handle) pending.delete(handle);
409
+ }
401
410
  }
402
411
  );
403
412
 
@@ -423,51 +432,51 @@ export function installSignalCleanup(map, {
423
432
  stdin = process.stdin,
424
433
  } = {}) {
425
434
  let shuttingDown = false;
426
- const shutdown = (code) => {
427
- // A second trigger skips the wait below: the kills are already dispatched, and a caller
428
- // that has asked twice wants out now.
429
- if (shuttingDown) return exit(code);
435
+ let signalsSeen = 0;
436
+ const shutdown = (code, fromSignal = false) => {
437
+ // Only a second signal skips the wait for the kills: a hangup closes stdin and sends SIGHUP,
438
+ // in either order. The first stops may still be in their ps walk, so the groups are killed
439
+ // synchronously before leaving.
440
+ if (fromSignal) signalsSeen++;
441
+ if (shuttingDown) {
442
+ if (signalsSeen < 2) return undefined;
443
+ for (const handles of [...map.values(), pending]) {
444
+ for (const handle of handles) { try { handle.client.killNow?.(); } catch {} }
445
+ }
446
+ return exit(code);
447
+ }
430
448
  shuttingDown = true;
431
- // Set in the handler, not left to the exit below: a loop that runs dry on its own still
432
- // has to die with the code the signal asked for, and the scheduled exit may never get a
433
- // turn to run.
449
+ // Set now: if the loop runs dry before the scheduled exit, the process still exits with it.
434
450
  setExitCode(code);
435
451
  const stops = [];
452
+ // A stop that did not see the exit is retried once, as the delegation does.
453
+ const stopOnce = (handle) => Promise.resolve(handle.client.stop()).catch(() => false);
436
454
  const dispatch = (handle) => {
437
- try { stops.push(Promise.resolve(handle.client.stop()).catch(() => {})); } catch {}
455
+ try { stops.push(stopOnce(handle).then((exited) => (exited === false ? stopOnce(handle) : exited))); } catch {}
438
456
  };
439
457
  for (const handles of map.values()) for (const handle of handles) dispatch(handle);
440
- // Delegations still inside their handshake. The agent is already running for these, and this
441
- // is the only place it is reachable from — they have no session id to be keyed under yet.
458
+ // Delegations still in their handshake, with no session id yet.
442
459
  for (const handle of pending) dispatch(handle);
443
- // On Windows the kill is a separate taskkill process: exiting before it walks the tree
444
- // orphans everything below the shell wrapper — the ps1 launcher and the versioned agent
445
- // were measured surviving the server's exit. stop() bounds itself (observed exit or its
446
- // own deadline), so this wait is short and finite on every platform.
447
- // Scheduled rather than called from the kill's own continuation, so the exit runs on a
448
- // clean loop turn instead of on the settlement stack.
460
+ // Exit waits for the kills: on Windows taskkill is a separate process, and exiting first left
461
+ // the launcher and agent running (measured). stop() bounds itself. The exit is scheduled onto
462
+ // a clean loop turn, off the settlement stack.
449
463
  const leave = () => schedule(() => exit(code));
450
464
  Promise.all(stops).then(leave, leave);
451
465
  };
452
- // Each agent runs in its own process group on POSIX, so a signal aimed at this process no
453
- // longer reaches it. Installing a handler replaces Node's default; swallowing Ctrl-C would
454
- // leak the agent. shutdown() already walks pending, so this covers spawn through session/new.
466
+ // On POSIX each agent has its own process group, so a signal to this process does not reach it.
467
+ // The handler replaces Node's default and must exit, not swallow the signal.
455
468
  if (DETACHED) {
456
- const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143]]);
457
- for (const [signal, code] of signals) process.on(signal, () => shutdown(code));
469
+ // SIGHUP is a closed terminal; its default would end the server without stopping the agents.
470
+ const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]]);
471
+ for (const [signal, code] of signals) process.on(signal, () => shutdown(code, true));
458
472
  }
459
- // Closing the server's stdin is how a stdio host shuts the transport down, and it is what a
460
- // host reaches for before it resorts to a signal. The SDK transport does not listen for it —
461
- // it subscribes to `data` and `error` only — so EOF leaves this process up with a delegation
462
- // still running and nobody left to hand it to.
473
+ // A stdio host shuts down by closing stdin, which the SDK transport does not watch.
463
474
  stdin.on("end", () => shutdown(0));
464
475
  }
465
476
 
466
477
  if (isMain) {
467
- // Without this the flag falls through to the transport, which owns stdout and waits on stdin —
468
- // so confirming an install meant wiring the server into a host first. Reads the package.json
469
- // beside this file, so it reports the code that is actually running rather than what a
470
- // manifest pinned. stdout is free here because the transport never starts.
478
+ // Confirms an install without a host. Reads the package.json beside this file, so it reports the
479
+ // code that runs, not a manifest pin.
471
480
  const argv = process.argv.slice(2);
472
481
  if (argv.includes("--version") || argv.includes("-v")) {
473
482
  console.log(readPackageVersion());
@@ -11,9 +11,8 @@ export class SessionSupervisor {
11
11
  this.client = client;
12
12
  this.handshakeMs = handshakeMs;
13
13
  this.hardCapMs = hardCapMs;
14
- // Mid-turn idle detection is opt-in and off by default. agy emits no ACP frames while a
15
- // shell command runs, so silence during a prompt turn says nothing about liveness: a
16
- // running `ping -n 60` produced no frame between its tool_call and the cancel 7s later.
14
+ // Opt-in: agy sends no frames while a shell command runs, so mid-turn silence says nothing
15
+ // about liveness.
17
16
  this.idleMs = idleMs > 0 ? idleMs : 0;
18
17
  this.sessionId = null;
19
18
  this.lastActivityAt = Date.now();
@@ -31,7 +30,7 @@ export class SessionSupervisor {
31
30
  this._onExit = (info) => {
32
31
  this._trip(
33
32
  "agent-exit",
34
- // Kept whole, for the reason acp-client.js states where it builds the same message.
33
+ // stderr kept whole, as in acp-client.js.
35
34
  `agent exited (code=${info.code}${info.signal ? ", signal=" + info.signal : ""})${info.stderr ? ": " + String(info.stderr) : ""}`
36
35
  );
37
36
  };
@@ -41,8 +40,7 @@ export class SessionSupervisor {
41
40
  this.sessionId = sessionId;
42
41
  }
43
42
 
44
- // True once the delegation is decided: a trip (exit, abort, a deadline) or the work's own end.
45
- // Work still running after a trip reads this to stop, since the race no longer awaits it.
43
+ // True once decided (a trip or the work's end); work still running after a trip reads it to stop.
46
44
  get settled() {
47
45
  return this._settled;
48
46
  }
@@ -64,9 +62,7 @@ export class SessionSupervisor {
64
62
  }, this.handshakeMs);
65
63
  }
66
64
 
67
- // The handshake is strict request/response, so silence there is real evidence of a
68
- // wedged agent. Once the prompt is in flight that stops being true, and the deadline
69
- // must come off.
65
+ // Silence in the request/response handshake means a wedged agent; during the prompt it does not.
70
66
  promptStarted() {
71
67
  if (this._promptStarted) return;
72
68
  this._promptStarted = true;
@@ -101,6 +97,11 @@ export class SessionSupervisor {
101
97
  this._trip("aborted", "delegation aborted by MCP host");
102
98
  }
103
99
 
100
+ // A cancel before the prompt: nothing is running to wait for, so setup stops at once.
101
+ cancelSetup() {
102
+ this._trip("cancelled-in-setup", "cancelled before the prompt was sent");
103
+ }
104
+
104
105
  _trip(reason, message) {
105
106
  if (this._settled) return;
106
107
  this._settled = true;
package/src/spawn.js CHANGED
@@ -11,17 +11,14 @@ export function splitArgs(raw) {
11
11
  return args;
12
12
  }
13
13
 
14
- // --dangerously-skip-permissions makes agy approve its own tool calls instead of asking. The
15
- // request router still approves any session/request_permission that arrives, but agy issue
16
- // #1658 reports a subagent's command raising none and waiting for an approval that cannot come,
17
- // which only the flag reaches. With the flag, a probe turn raised no permission request at all.
14
+ // --dangerously-skip-permissions makes agy approve its own tool calls. The request router approves
15
+ // any permission request too, but a subagent's command can wait without raising one (agy #1658),
16
+ // which only the flag covers.
18
17
  export const DEFAULT_AGENT_ARGS = Object.freeze(["acp", "--dangerously-skip-permissions"]);
19
18
 
20
- // shell:true on win32 is what lets a .cmd/.ps1 launcher resolve at all, and it means the
21
- // command and args are parsed by cmd.exe. Safe only because both come from the environment,
22
- // which is already as trusted as this process: anything that can set them can run code here
23
- // anyway. Routing host- or caller-supplied values into either variable would turn this into a
24
- // command-injection path, so don't.
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.
25
22
  export function resolveAcpSpawn() {
26
23
  const command = process.env.ACP_AGENT_COMMAND || "agy";
27
24
  const args = process.env.ACP_AGENT_ARGS
@@ -30,11 +27,17 @@ export function resolveAcpSpawn() {
30
27
  return { command, args, options: { shell: process.platform === "win32" } };
31
28
  }
32
29
 
33
- // Through a shell the spawn itself always succeeds: cmd.exe starts, fails to find the launcher and
34
- // exits 1 with a localized "is not recognized" line, so Node's spawn 'error' event never fires and
35
- // a missing agy reads as an agent crash. Resolving the launcher first is what lets that case be
36
- // reported as not installed. Mirrors cmd's lookup: a path is checked as given, a bare name against
37
- // each PATH entry, both with and without each PATHEXT extension.
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.
32
+ /** @returns {[string, string[]]} */
33
+ export function spawnCommandLine(command, args, options) {
34
+ const argv = args ?? [];
35
+ return options?.shell ? [[command, ...argv].join(" "), []] : [command, argv];
36
+ }
37
+
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.
38
41
  export function commandExists(command, env = process.env) {
39
42
  const name = String(command || "").replace(/^["']|["']$/g, "");
40
43
  if (!name) return false;
package/src/turn-state.js CHANGED
@@ -1,8 +1,5 @@
1
- // Everything describing the turn in progress, in one object because it has to be wiped as one:
2
- // session/load replays the previous turn as ordinary update frames, so anything left behind
3
- // leaks into the next result. Fields are declared in exactly one place, freshFields(), which is
4
- // also what reset() applies — a field added there is reset for free, and one that is missed is a
5
- // silent stale-data bug on resume.
1
+ // Everything describing the turn in progress, reset as one before the prompt. freshFields() is the
2
+ // single declaration reset() applies, so a field added there is reset too.
6
3
 
7
4
  const isTerminalToolStatus = (status) =>
8
5
  status === "completed" || status === "failed" || status === "cancelled";
@@ -46,36 +43,27 @@ function progressStream(prefix, onProgress, throttleMs) {
46
43
  function freshFields() {
47
44
  return {
48
45
  resultChunks: [],
49
- // Text superseded by a later tool call is normally a preamble ("Inspecting the
50
- // implementation."), but the rule cannot tell a preamble from the whole answer: an agent
51
- // that replies and then runs one more command has its entire reply discarded, leaving the
52
- // caller "" with stopReason end_turn and no error. Kept so it can be handed back when
53
- // nothing survived — labelled, never blended with a real final message.
46
+ // Text a later tool call superseded: usually a preamble, but it can be the whole answer when
47
+ // agy replies and then runs one more command. Handed back, labelled, only when nothing else is.
54
48
  discardedResult: "",
55
- // Message text sent while a tool call was still running, since that call started. Not part of
56
- // the result: it is handed back only when the turn ends with the call still unfinished, which
57
- // is how agy reports moving a long shell command to the background.
49
+ // Message text sent since a still-running tool call started; handed back only when the turn
50
+ // ends with the call unfinished (a backgrounded command or ask_question).
58
51
  unfinishedToolText: "",
59
52
  sawToolCall: false,
60
53
  collectingPostToolResult: false,
61
54
  activeToolCalls: new Set(),
62
- // Tool name per call id (agy's `name`, else its title), so an unfinished ask_question, which
63
- // waits on the caller, can be told from a backgrounded command, which finishes by itself.
55
+ // Tool name per call id, to tell an ask_question (waits on the caller) from a backgrounded
56
+ // command (finishes by itself).
64
57
  toolNames: new Map(),
65
- // Set by a usage_update and cleared by any other frame: agy closes a turn, prompted or not,
66
- // with a usage_update after its last message.
58
+ // Set by a usage_update, cleared by any other frame: agy closes every turn with one.
67
59
  usageAfterActivity: false,
68
- // The newest usage_update's { used, size }: the conversation's context in tokens and the
69
- // model's window. Unlike the prompt reply's usage it covers a background continuation too.
60
+ // The newest usage_update's { used, size }; unlike the reply's usage it covers a continuation.
70
61
  contextUsage: undefined,
71
62
  lastFrameAt: 0,
72
- // Ids observed terminal, so a stale non-terminal re-send for one is recognized and dropped
73
- // instead of restarting collection — which would demote an already-collected final message
74
- // to discardedResult and mislabel it pre-tool-fallback.
63
+ // Ids seen terminal, so a stale non-terminal re-send cannot discard a collected final message.
75
64
  finishedToolCalls: new Set(),
76
- // agy writes its plan as an artifact: a write_file call carrying ArtifactMetadata, saved
77
- // under ~/.gemini/antigravity-cli/brain/<sessionId>/. Keyed by path, so a rewrite of the
78
- // same artifact replaces the earlier entry.
65
+ // agy's artifacts (the plan): write_file calls carrying ArtifactMetadata, under
66
+ // ~/.gemini/antigravity-cli/brain/<sessionId>/. Keyed by path, so a rewrite replaces.
79
67
  artifacts: new Map(),
80
68
  touched: new Set(),
81
69
  lastToolLabel: null,
@@ -107,8 +95,7 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
107
95
  state.resultChunks.length = 0;
108
96
  },
109
97
 
110
- // The stream is the model's own message, bounded by its output limit; a byte cap
111
- // here would hand back a partial answer as if it were the whole one.
98
+ // Uncapped: a cap would return a partial answer as the whole one.
112
99
  appendResult(text) {
113
100
  state.resultChunks.push(text);
114
101
  },
@@ -141,8 +128,8 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
141
128
  state.finishedToolCalls.add(toolCallId);
142
129
  }
143
130
  if (state.activeToolCalls.size === 0 && !state.collectingPostToolResult) {
144
- // Discard any message text emitted while tools were still running.
145
- // A duplicate or late terminal update must not wipe an already-collected final message.
131
+ // Drop text sent while tools ran; the guard above keeps a late duplicate from wiping a
132
+ // collected final message.
146
133
  state.resetResult();
147
134
  state.collectingPostToolResult = true;
148
135
  }
package/src/version.js CHANGED
@@ -8,13 +8,11 @@ function readVersion() {
8
8
  return JSON.parse(readFileSync(PKG_PATH, "utf8")).version;
9
9
  }
10
10
 
11
- // Captured once, for the ACP/MCP identity handshake that is sent at connect and never re-read.
11
+ // Captured once, for the ACP and MCP identity sent at connect.
12
12
  export const VERSION = readVersion();
13
13
 
14
- // doctor reads fresh rather than using the constant: the MCP child is long-lived and
15
- // /reload-plugins does not restart it, so a version captured at process start goes stale after
16
- // an in-place upgrade — exactly when doctor is run to confirm the new version shipped. An
17
- // un-restarted child running old code stays a gap, but no in-process value can close that.
14
+ // Read fresh for doctor: /reload-plugins does not restart the server, so the constant goes stale
15
+ // after an in-place upgrade.
18
16
  export function readPackageVersion() {
19
17
  try {
20
18
  return readVersion();