agy-delegate-mcp 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,24 @@ All notable changes to this project are documented here. The format follows
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [1.3.0] - 2026-11-22
10
+
11
+ ### Added
12
+
13
+ - A command agy moves to the background is waited for. agy ends the turn when a shell command
14
+ outlasts the wait it set for it (`WaitMsBeforeAsync`); kept running, it finishes the command and
15
+ reports on it, and that report is the result. Stopping agy at the end of the turn stopped the
16
+ command: a 25 s `npm test` came back unfinished. `AGY_DELEGATE_BACKGROUND_WAIT_MS` bounds the wait
17
+ (default 10 min); a command still running then comes back as `unfinished-tool`. A cancel ends the
18
+ wait at once with `stopReason: "cancelled"`.
19
+ - `not-signed-in` failure reason: a signed-out agy is reported with the step to sign in. It read as
20
+ `agent-error: Authentication required`.
21
+
22
+ ### Fixed
23
+
24
+ - On Linux, stopping agy also stops the commands it runs in their own session. A command outlived a
25
+ hard-cap teardown.
26
+
9
27
  ## [1.2.0] - 2026-11-22
10
28
 
11
29
  ### Added
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-delegate-mcp",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "mcpName": "io.github.andreilungeanu/agy-delegate-mcp",
5
5
  "type": "module",
6
6
  "description": "Delegate multi-file coding work from Claude Code, Codex, Copilot, or any MCP client to Google's Antigravity CLI (agy) — structured results, plan mode, and changed files.",
package/src/acp-client.js CHANGED
@@ -150,7 +150,9 @@ export class AcpClient extends EventEmitter {
150
150
  setConfigOption(sessionId, configId, value) { return this.peer.request("session/set_config_option", { sessionId, configId, value: String(value) }); } // configId, not optionId; ACP wants a string value
151
151
  setMode(sessionId, modeId) { return this.peer.request("session/set_mode", { sessionId, modeId }); }
152
152
  prompt(sessionId, blocks) { return this.peer.request("session/prompt", { sessionId, prompt: blocks }); }
153
- cancel(sessionId) { this.peer.notify("session/cancel", { sessionId }); return Promise.resolve(); }
153
+ // Recorded so a delegation waiting on a backgrounded command can stop waiting: after a cancel
154
+ // agy closes the call without the usage_update that ends a continuation.
155
+ cancel(sessionId) { this.cancelRequested = true; this.peer.notify("session/cancel", { sessionId }); return Promise.resolve(); }
154
156
 
155
157
  getTranscript(n) { return this.peer ? this.peer.formatLog(n) : ""; }
156
158
 
package/src/delegate.js CHANGED
@@ -15,6 +15,7 @@ import { effortSettings, optionsFrom, resolveEffort, allowedValues } from "./mod
15
15
  import { transcriptFrames } from "./jsonrpc.js";
16
16
 
17
17
  export const DEFAULT_HANDSHAKE_MS = 60000;
18
+ export const DEFAULT_BACKGROUND_WAIT_MS = 10 * 60 * 1000;
18
19
 
19
20
  // The bridge's modes onto agy's. agy has no ask mode: ask runs in default with ASK_PREAMBLE
20
21
  // ahead of the spec. default asks before edits and commands, which the launch flag and the
@@ -242,6 +243,7 @@ async function applyEffort(client, sessionId, model, value, modelOptions) {
242
243
  * onSessionReady?: (sessionId: string, client: any) => void,
243
244
  * onProgress?: (message: string) => void,
244
245
  * progressThrottleMs?: number, heartbeatMs?: number, signal?: AbortSignal,
246
+ * backgroundSettleMs?: number, backgroundContinueMs?: number, backgroundWaitMs?: number,
245
247
  * }} [opts]
246
248
  */
247
249
  export async function runDelegate({
@@ -251,6 +253,13 @@ export async function runDelegate({
251
253
  onClientReady, onSessionReady, onProgress, progressThrottleMs = 2000,
252
254
  heartbeatMs = DEFAULT_HEARTBEAT_MS,
253
255
  signal,
256
+ // Quiet after agy's closing usage_update before its continuation counts as over, and how long
257
+ // to wait for a continuation that never starts once every background call has finished.
258
+ backgroundSettleMs = 2000,
259
+ backgroundContinueMs = 60000,
260
+ // A backgrounded command that never ends (a dev server) would otherwise hold the delegation to
261
+ // the hard cap.
262
+ backgroundWaitMs = envMs("AGY_DELEGATE_BACKGROUND_WAIT_MS", DEFAULT_BACKGROUND_WAIT_MS),
254
263
  } = {}) {
255
264
  // Nothing between here and the abort listener below may await: addEventListener does not
256
265
  // replay an abort that already fired, so an abort landing in that window would be lost.
@@ -328,6 +337,8 @@ export async function runDelegate({
328
337
  client.on("update", (u) => {
329
338
  if (!promptInFlight) return;
330
339
  const up = u?.update || {};
340
+ state.lastFrameAt = Date.now();
341
+ state.usageAfterActivity = up.sessionUpdate === "usage_update";
331
342
  // The agent titles the turn a beat after the prompt lands — useful live, when several
332
343
  // delegations run, and in timeout forensics. Kept out of the result.
333
344
  if (up.sessionUpdate === "session_info_update" && typeof up.title === "string" && up.title) {
@@ -342,7 +353,7 @@ export async function runDelegate({
342
353
  // artifact rather than as a workspace edit.
343
354
  const isArtifact = state.recordArtifact(up.rawInput ?? up.args);
344
355
  if (up.sessionUpdate === "tool_call") {
345
- state.startTool(up.toolCallId, up.status);
356
+ state.startTool(up.toolCallId, up.status, up.name ?? up.title);
346
357
  const label = String(up.title || up.kind || "tool");
347
358
  const path = up.locations?.[0]?.path;
348
359
  // Collapsed onto one line the way both readers of this take it: a progress notification
@@ -367,6 +378,27 @@ export async function runDelegate({
367
378
  }
368
379
  });
369
380
 
381
+ // agy moves a shell command to the background once it outlasts the call's WaitMsBeforeAsync and
382
+ // ends the turn; kept alive, it finishes the command, marks the call completed and continues the
383
+ // turn unprompted, closing with a usage_update (measured, agy 1.5.14). Stopping agy at end_turn
384
+ // killed the command, so wait for that continuation instead. The hard cap still bounds it.
385
+ let backgroundWaited;
386
+ const waitForBackground = async () => {
387
+ try { onProgress?.(`waiting for agy's background command: ${state.lastToolLabel ?? "tool"}`.slice(0, 200)); } catch {}
388
+ const startedAt = Date.now();
389
+ for (;;) {
390
+ await new Promise((r) => setTimeout(r, Math.min(250, backgroundSettleMs)));
391
+ backgroundWaited = Date.now() - startedAt;
392
+ if (backgroundWaited >= backgroundWaitMs) return;
393
+ if (client.cancelRequested) return "cancelled";
394
+ if (state.backgroundToolCalls().length) continue;
395
+ const quietMs = Date.now() - state.lastFrameAt;
396
+ if (state.usageAfterActivity && quietMs >= backgroundSettleMs) return;
397
+ // Everything finished but agy never closed a continuation: stop waiting for one.
398
+ if (quietMs >= backgroundContinueMs) return;
399
+ }
400
+ };
401
+
370
402
  let sessionId;
371
403
  let resumeError;
372
404
  let servedModel;
@@ -407,7 +439,11 @@ export async function runDelegate({
407
439
  promptInFlight = true;
408
440
  try {
409
441
  const blocks = await buildContextBlocks(contextFiles, workspace, client, contextWarnings);
410
- return await client.prompt(sessionId, [{ type: "text", text: promptText }, ...blocks]);
442
+ const turn = await client.prompt(sessionId, [{ type: "text", text: promptText }, ...blocks]);
443
+ if (state.backgroundToolCalls().length && await waitForBackground() === "cancelled") {
444
+ return { ...turn, stopReason: "cancelled" };
445
+ }
446
+ return turn;
411
447
  } finally {
412
448
  // The result is assembled across awaits below, so without this a frame trailing the
413
449
  // settled turn is still folded into it.
@@ -423,17 +459,18 @@ export async function runDelegate({
423
459
  : "none";
424
460
  const protocolWarnings = [];
425
461
  if (!finalMessageAvailable && state.activeToolCalls.size > 0) {
426
- // agy ends a turn with a call unfinished in two measured cases (agy 1.5.14): it moves a
427
- // shell command to the background once it outlasts the call's WaitMsBeforeAsync, a wait agy
428
- // picks per command, or it waits on ask_question.
429
- // The bridge stops agy when the delegation returns, so a backgrounded command stops with it.
462
+ // Two measured cases (agy 1.5.14): a backgrounded command still running when the wait for it
463
+ // ran out, or an ask_question, which waits on the caller. The bridge stops agy when the
464
+ // delegation returns, so a backgrounded command stops with it.
430
465
  result = state.unfinishedToolText;
431
466
  resultSource = result ? "unfinished-tool" : "none";
467
+ const cause = backgroundWaited !== undefined && state.backgroundToolCalls().length
468
+ ? ` agy moved it to the background, and it was still running after the bridge waited ${fmtDuration(backgroundWaited)}`
469
+ + " (AGY_DELEGATE_BACKGROUND_WAIT_MS); it stops when the bridge stops agy."
470
+ : " agy is asking a question (ask_question), which a resume answers.";
432
471
  protocolWarnings.push(
433
472
  `the turn ended with a tool call still running (${state.lastToolLabel ?? "unnamed tool"}).`
434
- + " agy does this when it moves a shell command to the background after the wait it set for it (WaitMsBeforeAsync) —"
435
- + " the command stops when the bridge stops agy — and when it asks a question (ask_question),"
436
- + " which a resume answers."
473
+ + cause
437
474
  + (result ? " result is agy's message from while it ran." : " agy sent no message while it ran.")
438
475
  );
439
476
  } else if (!finalMessageAvailable && state.discardedResult) {
@@ -497,6 +534,11 @@ export async function runDelegate({
497
534
  } catch (err) {
498
535
  // A JSON-RPC code means the agent rejected something rather than the bridge breaking — the
499
536
  // distinction a caller needs to tell "fix your arguments" from "retry".
537
+ // -32000 is ACP's auth_required. agy sends it from session/new when no sign-in is stored.
538
+ if (!err?.reason && err?.code === -32000) {
539
+ err.reason = "not-signed-in";
540
+ err.message += ". agy is not signed in: run agy once in a terminal and sign in, then retry.";
541
+ }
500
542
  if (!err?.reason && typeof err?.code === "number") err.reason = "agent-error";
501
543
  // A bare duration cannot distinguish a wedged agent from a slow command, so name what was
502
544
  // outstanding — it also lets a retry resume the work already done.
package/src/doctor.js CHANGED
@@ -188,6 +188,7 @@ export async function runDoctor({
188
188
  AGY_DELEGATE_HANDSHAKE_MS: envReport("AGY_DELEGATE_HANDSHAKE_MS"),
189
189
  AGY_DELEGATE_HARD_CAP_MS: envReport("AGY_DELEGATE_HARD_CAP_MS"),
190
190
  AGY_DELEGATE_IDLE_MS: envReport("AGY_DELEGATE_IDLE_MS"),
191
+ AGY_DELEGATE_BACKGROUND_WAIT_MS: envReport("AGY_DELEGATE_BACKGROUND_WAIT_MS"),
191
192
  },
192
193
  };
193
194
 
package/src/proc.js CHANGED
@@ -11,6 +11,31 @@ export function isChildAlive(child) {
11
11
  // an injected spawnSpec has to become a group leader too or the group kill finds nothing.
12
12
  export const DETACHED = process.platform !== "win32";
13
13
 
14
+ // Every process below pid, from one `ps` snapshot (Linux and macOS both have -A -o pid=,ppid=).
15
+ // Empty when ps is unavailable or fails: the group kill still runs.
16
+ function descendantPids(pid) {
17
+ return /** @type {Promise<number[]>} */ (new Promise((resolve) => {
18
+ execFile("ps", ["-A", "-o", "pid=,ppid="], { timeout: 3000 }, (err, stdout) => {
19
+ if (err) return resolve([]);
20
+ const children = new Map();
21
+ for (const line of String(stdout).split("\n")) {
22
+ const [p, pp] = line.trim().split(/\s+/).map(Number);
23
+ if (!p || !Number.isFinite(pp)) continue;
24
+ if (!children.has(pp)) children.set(pp, []);
25
+ children.get(pp).push(p);
26
+ }
27
+ const out = [];
28
+ const queue = [pid];
29
+ while (queue.length) {
30
+ for (const c of children.get(queue.shift()) ?? []) {
31
+ if (!out.includes(c)) { out.push(c); queue.push(c); }
32
+ }
33
+ }
34
+ resolve(out);
35
+ });
36
+ }));
37
+ }
38
+
14
39
  // On win32 a plain child.kill() only reaches the shell wrapper (spawn uses shell: true);
15
40
  // taskkill /T takes the whole tree so the agent itself dies too.
16
41
  export async function treeKill(pid, { childAlive = true } = {}) {
@@ -26,10 +51,19 @@ export async function treeKill(pid, { childAlive = true } = {}) {
26
51
  }));
27
52
  return;
28
53
  }
54
+ // agy runs each shell command in its own session, outside the agent's group, so the group kill
55
+ // alone left a command running (a sleep outlived a hard-cap teardown in WSL). Walk the parent
56
+ // links first, while the agent is still there to hold them, and kill each descendant and its
57
+ // group too. Only while the child is alive: after a reap its pid can belong to someone else.
58
+ const descendants = childAlive ? await descendantPids(pid) : [];
29
59
  // Negative pid signals the whole group, so the agent's descendants go with it. A group outlives
30
60
  // its leader while any member is left, which is why this runs even for an exited child: that is
31
61
  // the case where descendants are the only thing still running.
32
62
  try { process.kill(-pid, "SIGKILL"); } catch {}
63
+ for (const d of descendants) {
64
+ try { process.kill(-d, "SIGKILL"); } catch {}
65
+ try { process.kill(d, "SIGKILL"); } catch {}
66
+ }
33
67
  // Reaches a child that is not a group leader, where the group kill raised ESRCH. Skipped once
34
68
  // the child is gone, since a reaped pid can already belong to something else.
35
69
  if (childAlive) { try { process.kill(pid, "SIGKILL"); } catch {} }
package/src/turn-state.js CHANGED
@@ -59,6 +59,13 @@ function freshFields() {
59
59
  sawToolCall: false,
60
60
  collectingPostToolResult: false,
61
61
  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.
64
+ 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.
67
+ usageAfterActivity: false,
68
+ lastFrameAt: 0,
62
69
  // Ids observed terminal, so a stale non-terminal re-send for one is recognized and dropped
63
70
  // instead of restarting collection — which would demote an already-collected final message
64
71
  // to discardedResult and mislabel it pre-tool-fallback.
@@ -103,7 +110,8 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
103
110
  state.resultChunks.push(text);
104
111
  },
105
112
 
106
- startTool(toolCallId, status) {
113
+ startTool(toolCallId, status, name) {
114
+ if (toolCallId != null && name) state.toolNames.set(toolCallId, String(name));
107
115
  state.unfinishedToolText = "";
108
116
  state.sawToolCall = true;
109
117
  state.collectingPostToolResult = false;
@@ -142,6 +150,12 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
142
150
  }
143
151
  },
144
152
 
153
+ // Unfinished calls that end on their own: a backgrounded command or a scheduled wake-up. An
154
+ // ask_question waits on the caller instead, so it is never waited for.
155
+ backgroundToolCalls() {
156
+ return [...state.activeToolCalls].filter((id) => !/ask_question/.test(state.toolNames.get(id) ?? ""));
157
+ },
158
+
145
159
  // True while a message chunk still belongs in the result: before any tool ran, or after
146
160
  // the last one finished.
147
161
  collectingResult() {