agy-delegate-mcp 1.3.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);
@@ -34,7 +32,7 @@ function registerInFlight(map, sessionId, handle) {
34
32
  else map.set(sessionId, new Set([handle]));
35
33
  }
36
34
  /** @returns {import("@modelcontextprotocol/sdk/types.js").CallToolResult} */
37
- function cancelResult(status, sessionId) {
35
+ function statusResult(status, sessionId) {
38
36
  return { content: [{ type: "text", text: JSON.stringify({ status, sessionId }) }] };
39
37
  }
40
38
  function unregisterInFlight(map, sessionId, handle) {
@@ -43,43 +41,45 @@ 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 status lives on
76
- // its tool description.
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(),
80
70
  effectiveModel: z.string().optional(),
81
71
  effectiveEffort: z.record(z.string(), z.string()).optional(),
82
72
  stopReason: z.string().optional(),
73
+ usage: z.object({
74
+ scope: z.literal("turn"),
75
+ inputTokens: z.number().optional(),
76
+ outputTokens: z.number().optional(),
77
+ cachedReadTokens: z.number().optional(),
78
+ cachedWriteTokens: z.number().optional(),
79
+ thoughtTokens: z.number().optional(),
80
+ totalTokens: z.number().optional(),
81
+ }).strict().optional(),
82
+ context: z.object({ used: z.number(), size: z.number() }).strict().optional(),
83
83
  sessionId: z.string(),
84
84
  filesReportedByEditTools: z.array(z.string()).optional(),
85
85
  resumed: z.boolean().optional(),
@@ -96,9 +96,9 @@ export const delegateOutputShape = {
96
96
  })).optional(),
97
97
  };
98
98
 
99
- // Same in-repo contract as delegateOutputShape. Relayed agent fields stay unknown so a
100
- // weird protocolVersion is a diagnostic, not a failed call. doctor.test.js holds the
101
- // 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.
102
102
  export const doctorHandshakeShape = {
103
103
  ok: z.boolean(),
104
104
  error: z.string().optional(),
@@ -108,7 +108,7 @@ export const doctorHandshakeShape = {
108
108
  currentModel: z.unknown().optional(),
109
109
  modes: z.array(z.unknown()).optional(),
110
110
  tier: z.unknown().optional(),
111
- // 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.
112
112
  currentModelOptions: z.array(z.object({
113
113
  id: z.string(),
114
114
  name: z.string().optional(),
@@ -148,15 +148,28 @@ export const doctorOutputShape = {
148
148
  export const delegateInputSchema = z.object({
149
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."),
150
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."),
151
- resumeSessionId: z.string().optional().describe("Continue an existing agy session."),
151
+ resumeSessionId: z.string().trim().optional().describe("Continue an existing agy session."),
152
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."),
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 and effectiveModel names it. doctor deep:true lists every id."),
154
- // Which values a model offers is only knowable after selecting it, so this stays an open
155
- // 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.
156
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."),
157
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."),
158
157
  });
159
158
 
159
+ // Steers every turn running on the id, as cancel does: the caller named a session.
160
+ export function steerSession(map, seen, sessionId, message) {
161
+ const handles = map.get(sessionId);
162
+ if (!handles || handles.size === 0) return seen.has(sessionId) ? "not-running" : "not-found";
163
+ const statuses = new Set();
164
+ for (const handle of handles) {
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"); }
168
+ }
169
+ for (const status of ["steered", "not-ready"]) if (statuses.has(status)) return status;
170
+ return "not-running";
171
+ }
172
+
160
173
  /**
161
174
  * @param {{
162
175
  * args: any, extra?: any,
@@ -176,8 +189,7 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
176
189
  if (progressToken != null) {
177
190
  let progress = 0;
178
191
  onProgress = (message) => {
179
- // sendNotification is async: its rejection settles outside this try and would exit the
180
- // 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.
181
193
  try {
182
194
  Promise.resolve(extra.sendNotification({
183
195
  method: "notifications/progress",
@@ -193,7 +205,8 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
193
205
  const out = await runDelegate({
194
206
  spec,
195
207
  mode,
196
- resumeSessionId,
208
+ // Blank is no resume: hosts fill optional fields with "".
209
+ resumeSessionId: resumeSessionId || undefined,
197
210
  workspace,
198
211
  model,
199
212
  effort,
@@ -206,45 +219,44 @@ export async function runDelegateTool({ args, extra, runDelegate, inFlight, pend
206
219
  },
207
220
  onSessionReady: (sessionId, client) => {
208
221
  capturedSessionId = sessionId;
209
- // The same handle moves across, so a shutdown racing this boundary finds it on exactly
210
- // one side of it rather than on neither.
222
+ // The same handle moves across, so a racing shutdown finds it on one side.
211
223
  handle ??= { client, cancelRequested: false };
212
224
  pending.delete(handle);
213
225
  registerInFlight(inFlight, sessionId, handle);
214
226
  rememberSession(seenSessions, sessionId);
215
- // Emit the id the moment the session opens, before the turn finishes, so a host that
216
- // can call tools concurrently has something to pass to cancel mid-run — otherwise the
217
- // id only arrives when delegate returns, by which point there is nothing to cancel.
218
- // (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.
219
229
  onProgress(`session ready: ${sessionId}`);
220
230
  },
231
+ onTurnEnd: () => { if (handle) handle.ended = true; },
221
232
  });
222
233
  if (handle?.cancelRequested) out.cancelRequested = true;
223
234
  return { content: [{ type: "text", text: JSON.stringify(out) }] };
224
235
  } catch (err) {
225
236
  return {
226
- // The reason is already decided upstream; naming it here saves the caller parsing
227
- // prose to tell a timeout from a rejected argument.
237
+ // The reason in brackets spares the caller parsing prose.
228
238
  content: [{ type: "text", text: `delegate failed${err?.reason ? ` [${err.reason}]` : ""}: ` + (err?.message || String(err)) }],
229
239
  isError: true,
230
240
  };
231
241
  } finally {
232
- // Drops only this delegation's own handle; the id stays registered while another turn
233
- // is still running on it. A delegation that failed before its session opened is only ever
234
- // 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.
235
243
  if (handle) pending.delete(handle);
236
244
  if (capturedSessionId) unregisterInFlight(inFlight, capturedSessionId, handle);
237
245
  }
238
246
  }
239
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
+
240
251
  /**
241
252
  * @param {{
242
253
  * runDelegate?: (opts: any) => Promise<any>,
243
254
  * runDoctor?: (opts: any) => Promise<any>,
244
255
  * forceGraceMs?: number,
256
+ * pending?: Set<any>,
245
257
  * }} [opts]
246
258
  */
247
- export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000 } = {}) {
259
+ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000, pending = pendingDelegations } = {}) {
248
260
  const runDelegate = runDelegateInjected || runDelegateDefault;
249
261
  const runDoctor = runDoctorInjected || runDoctorDefault;
250
262
  const server = new McpServer(
@@ -266,7 +278,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
266
278
  openWorldHint: true,
267
279
  },
268
280
  },
269
- async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, pending: pendingDelegations, seenSessions })
281
+ async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, pending, seenSessions })
270
282
  );
271
283
 
272
284
  server.registerTool(
@@ -275,7 +287,7 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
275
287
  description:
276
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).",
277
289
  inputSchema: {
278
- sessionId: z.string(),
290
+ sessionId: sessionIdInput,
279
291
  force: z.boolean().default(false).describe("Kill the agent process if the turn is still running after a short grace period."),
280
292
  },
281
293
  annotations: {
@@ -289,45 +301,76 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
289
301
  async ({ sessionId, force }) => {
290
302
  const handles = inFlight.get(sessionId);
291
303
  if (!handles || handles.size === 0) {
292
- // A finished session and a garbage id are both "not in flight". Reporting them alike
293
- // 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.
294
305
  const known = seenSessions.has(sessionId);
295
- return cancelResult(known ? "not-running" : "not-found", sessionId);
306
+ return statusResult(known ? "not-running" : "not-found", sessionId);
307
+ }
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);
296
316
  }
297
- // Cancel every turn running on the id: the caller named a session, not one of the
298
- // turns that happen to share it.
299
- for (const handle of handles) handle.cancelRequested = true;
300
- await Promise.all([...handles].map((handle) => handle.client.cancel(sessionId).catch(() => {})));
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(() => {})));
301
320
  if (!force) {
302
- // The handles stay registered: session/cancel is best-effort, so the turn may still
303
- // be running. Dropping them here made the natural escalation — cancel, wait, cancel
304
- // with force — report not-found while the agent was alive. Each delegation's own
305
- // finally removes its handle when the turn actually settles.
306
- return cancelResult("cancelled", sessionId);
321
+ // The handles stay registered: session/cancel is best-effort, and a follow-up force must
322
+ // still find a turn that kept running.
323
+ return statusResult("cancelled", sessionId);
307
324
  }
308
- // Watched rather than slept through: agy stops a cancelled turn in milliseconds, and the
309
- // 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();
310
329
  const graceEnds = Date.now() + forceGraceMs;
311
- 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;
312
338
  await new Promise((r) => setTimeout(r, Math.min(50, Math.max(1, graceEnds - Date.now()))));
313
339
  }
314
- const stillRunning = inFlight.get(sessionId);
315
- if (!stillRunning || stillRunning.size === 0) return cancelResult("cancelled", sessionId);
316
- // Snapshot before awaiting stop. A resume that registers during teardown must not be
317
- // swept out of the map — it was never killed, and inFlight.delete(sessionId) would
318
- // hide it from cancel and shutdown.
319
- 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);
320
344
  const observed = await Promise.all(
321
345
  toKill.map((handle) => Promise.resolve(handle.client.stop()).catch(() => false))
322
346
  );
323
- // "killed" claims the process is gone, so it needs the exit, not just a dispatched signal.
324
- // When one does not follow, the handles stay registered and force can be tried again.
325
- if (!observed.every(Boolean)) return cancelResult("cancelled", sessionId);
347
+ // "killed" needs an observed exit; without one the handles stay and force can be retried.
348
+ if (!observed.every(Boolean)) return statusResult("cancelled", sessionId);
326
349
  for (const handle of toKill) unregisterInFlight(inFlight, sessionId, handle);
327
- return cancelResult("killed", sessionId);
350
+ return statusResult("killed", sessionId);
328
351
  }
329
352
  );
330
353
 
354
+ server.registerTool(
355
+ "steer",
356
+ {
357
+ description:
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).",
359
+ inputSchema: {
360
+ sessionId: sessionIdInput,
361
+ message: z.string().trim().min(1, "message must not be blank").describe("The new instruction for agy."),
362
+ },
363
+ annotations: {
364
+ title: "Steer Antigravity delegation",
365
+ readOnlyHint: false,
366
+ destructiveHint: true,
367
+ idempotentHint: false,
368
+ openWorldHint: true,
369
+ },
370
+ },
371
+ async ({ sessionId, message }) => statusResult(steerSession(inFlight, seenSessions, sessionId, message), sessionId)
372
+ );
373
+
331
374
  server.registerTool(
332
375
  "doctor",
333
376
  {
@@ -347,15 +390,23 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
347
390
  openWorldHint: false,
348
391
  },
349
392
  },
350
- async ({ deep }) => {
351
- const out = await runDoctor({
352
- deep,
353
- getClientInfo: () => ({
354
- capabilities: server.server.getClientCapabilities(),
355
- version: server.server.getClientVersion(),
356
- }),
357
- });
358
- 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
+ }
359
410
  }
360
411
  );
361
412
 
@@ -381,51 +432,51 @@ export function installSignalCleanup(map, {
381
432
  stdin = process.stdin,
382
433
  } = {}) {
383
434
  let shuttingDown = false;
384
- const shutdown = (code) => {
385
- // A second trigger skips the wait below: the kills are already dispatched, and a caller
386
- // that has asked twice wants out now.
387
- 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
+ }
388
448
  shuttingDown = true;
389
- // Set in the handler, not left to the exit below: a loop that runs dry on its own still
390
- // has to die with the code the signal asked for, and the scheduled exit may never get a
391
- // turn to run.
449
+ // Set now: if the loop runs dry before the scheduled exit, the process still exits with it.
392
450
  setExitCode(code);
393
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);
394
454
  const dispatch = (handle) => {
395
- try { stops.push(Promise.resolve(handle.client.stop()).catch(() => {})); } catch {}
455
+ try { stops.push(stopOnce(handle).then((exited) => (exited === false ? stopOnce(handle) : exited))); } catch {}
396
456
  };
397
457
  for (const handles of map.values()) for (const handle of handles) dispatch(handle);
398
- // Delegations still inside their handshake. The agent is already running for these, and this
399
- // 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.
400
459
  for (const handle of pending) dispatch(handle);
401
- // On Windows the kill is a separate taskkill process: exiting before it walks the tree
402
- // orphans everything below the shell wrapper — the ps1 launcher and the versioned agent
403
- // were measured surviving the server's exit. stop() bounds itself (observed exit or its
404
- // own deadline), so this wait is short and finite on every platform.
405
- // Scheduled rather than called from the kill's own continuation, so the exit runs on a
406
- // 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.
407
463
  const leave = () => schedule(() => exit(code));
408
464
  Promise.all(stops).then(leave, leave);
409
465
  };
410
- // Each agent runs in its own process group on POSIX, so a signal aimed at this process no
411
- // longer reaches it. Installing a handler replaces Node's default; swallowing Ctrl-C would
412
- // 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.
413
468
  if (DETACHED) {
414
- const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143]]);
415
- 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));
416
472
  }
417
- // Closing the server's stdin is how a stdio host shuts the transport down, and it is what a
418
- // host reaches for before it resorts to a signal. The SDK transport does not listen for it —
419
- // it subscribes to `data` and `error` only — so EOF leaves this process up with a delegation
420
- // 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.
421
474
  stdin.on("end", () => shutdown(0));
422
475
  }
423
476
 
424
477
  if (isMain) {
425
- // Without this the flag falls through to the transport, which owns stdout and waits on stdin —
426
- // so confirming an install meant wiring the server into a host first. Reads the package.json
427
- // beside this file, so it reports the code that is actually running rather than what a
428
- // 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.
429
480
  const argv = process.argv.slice(2);
430
481
  if (argv.includes("--version") || argv.includes("-v")) {
431
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,6 +40,11 @@ export class SessionSupervisor {
41
40
  this.sessionId = sessionId;
42
41
  }
43
42
 
43
+ // True once decided (a trip or the work's end); work still running after a trip reads it to stop.
44
+ get settled() {
45
+ return this._settled;
46
+ }
47
+
44
48
  msSinceActivity() {
45
49
  return Date.now() - this.lastActivityAt;
46
50
  }
@@ -58,9 +62,7 @@ export class SessionSupervisor {
58
62
  }, this.handshakeMs);
59
63
  }
60
64
 
61
- // The handshake is strict request/response, so silence there is real evidence of a
62
- // wedged agent. Once the prompt is in flight that stops being true, and the deadline
63
- // must come off.
65
+ // Silence in the request/response handshake means a wedged agent; during the prompt it does not.
64
66
  promptStarted() {
65
67
  if (this._promptStarted) return;
66
68
  this._promptStarted = true;
@@ -95,6 +97,11 @@ export class SessionSupervisor {
95
97
  this._trip("aborted", "delegation aborted by MCP host");
96
98
  }
97
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
+
98
105
  _trip(reason, message) {
99
106
  if (this._settled) return;
100
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;