agy-delegate-mcp 1.4.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/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,49 @@ 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];
342
- const observed = await Promise.all(
343
- toKill.map((handle) => Promise.resolve(handle.client.stop()).catch(() => false))
344
- );
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.
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.
343
+ const toKill = live.filter((handle) => !cut.has(handle));
344
+ const [observed] = await Promise.all([Promise.all(toKill.map(stopQuietly)), Promise.all(closing)]);
345
+ if (toKill.length === 0) return statusResult("cancelled", sessionId);
346
+ // "killed" needs an observed exit; without one the handles stay and force can be retried.
347
347
  if (!observed.every(Boolean)) return statusResult("cancelled", sessionId);
348
348
  for (const handle of toKill) unregisterInFlight(inFlight, sessionId, handle);
349
349
  return statusResult("killed", sessionId);
@@ -356,7 +356,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
356
356
  description:
357
357
  "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
358
  inputSchema: {
359
- sessionId: z.string(),
359
+ sessionId: sessionIdInput,
360
360
  message: z.string().trim().min(1, "message must not be blank").describe("The new instruction for agy."),
361
361
  },
362
362
  annotations: {
@@ -389,15 +389,23 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
389
389
  openWorldHint: false,
390
390
  },
391
391
  },
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) }] };
392
+ async ({ deep }, extra) => {
393
+ // In pending while it runs, so shutdown stops doctor's agent too.
394
+ let handle;
395
+ try {
396
+ const out = await runDoctor({
397
+ deep,
398
+ signal: extra?.signal,
399
+ onClientReady: (client) => { handle = { client }; pending.add(handle); },
400
+ getClientInfo: () => ({
401
+ capabilities: server.server.getClientCapabilities(),
402
+ version: server.server.getClientVersion(),
403
+ }),
404
+ });
405
+ return { content: [{ type: "text", text: JSON.stringify(out) }] };
406
+ } finally {
407
+ if (handle) pending.delete(handle);
408
+ }
401
409
  }
402
410
  );
403
411
 
@@ -423,51 +431,64 @@ export function installSignalCleanup(map, {
423
431
  stdin = process.stdin,
424
432
  } = {}) {
425
433
  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);
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();
439
+ const shutdown = (code, fromSignal = false) => {
440
+ // Only a second signal skips the wait for the kills: a hangup closes stdin and sends SIGHUP,
441
+ // in either order. The first stops may still be in their ps walk, so the groups are killed
442
+ // synchronously before leaving.
443
+ if (fromSignal) signalsSeen++;
444
+ if (shuttingDown) {
445
+ if (fromSignal && signalsSeen === 1) { exitCode = code; setExitCode(code); }
446
+ if (signalsSeen < 2) return undefined;
447
+ for (const handle of new Set([...dispatched, ...[...map.values()].flatMap((h) => [...h]), ...pending])) {
448
+ try { handle.client.killNow?.(); } catch {}
449
+ }
450
+ return exit(code);
451
+ }
430
452
  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.
453
+ exitCode = code;
454
+ // Set now: if the loop runs dry before the scheduled exit, the process still exits with it.
434
455
  setExitCode(code);
435
456
  const stops = [];
457
+ // A stop that did not see the exit is retried once, as the delegation does.
458
+ const stopOnce = (handle) => Promise.resolve(handle.client.stop()).catch(() => false);
436
459
  const dispatch = (handle) => {
437
- try { stops.push(Promise.resolve(handle.client.stop()).catch(() => {})); } 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 {}
438
468
  };
439
469
  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.
470
+ // Delegations still in their handshake, with no session id yet.
442
471
  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.
449
- const leave = () => schedule(() => exit(code));
472
+ // Exit waits for the kills: on Windows taskkill is a separate process, and exiting first left
473
+ // the launcher and agent running (measured). stop() bounds itself. The exit is scheduled onto
474
+ // a clean loop turn, off the settlement stack.
475
+ const leave = () => schedule(() => exit(exitCode));
450
476
  Promise.all(stops).then(leave, leave);
451
477
  };
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.
478
+ // On POSIX each agent has its own process group, so a signal to this process does not reach it.
479
+ // The handler replaces Node's default and must exit, not swallow the signal.
455
480
  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));
481
+ // SIGHUP is a closed terminal; its default would end the server without stopping the agents.
482
+ const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]]);
483
+ for (const [signal, code] of signals) process.on(signal, () => shutdown(code, true));
458
484
  }
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.
485
+ // A stdio host shuts down by closing stdin, which the SDK transport does not watch.
463
486
  stdin.on("end", () => shutdown(0));
464
487
  }
465
488
 
466
489
  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.
490
+ // Confirms an install without a host. Reads the package.json beside this file, so it reports the
491
+ // code that runs, not a manifest pin.
471
492
  const argv = process.argv.slice(2);
472
493
  if (argv.includes("--version") || argv.includes("-v")) {
473
494
  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;