agy-delegate-mcp 1.1.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,45 @@ 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
+
27
+ ## [1.2.0] - 2026-11-22
28
+
29
+ ### Added
30
+
31
+ - `resultSource: "unfinished-tool"`: a turn that ends with a tool call still running returns agy's
32
+ message from while it ran, and `protocolWarnings` names the tool. agy ends a turn this way when
33
+ it moves a shell command to the background after the wait it set for it (`WaitMsBeforeAsync`),
34
+ which stops with agy when the delegation returns, and when it asks a question through
35
+ `ask_question`, which a resume answers. The result was empty, with a warning that agy sent no
36
+ message.
37
+
38
+ ### Fixed
39
+
40
+ - agy starts in the workspace. Started in the MCP server's directory, it listed that directory and
41
+ ran `git status` and `git diff` there during a delegation to another workspace.
42
+ - A missing agy on Windows is reported as `spawn-failed` with the install hint, and `doctor`
43
+ reports `found: false`. Launched through cmd.exe it read as `agent-exit` quoting cmd's
44
+ "is not recognized" line, and `doctor` reported `found: true`.
45
+ - `cancel` with `force` returns as soon as the turn settles, in about 60 ms, instead of waiting out
46
+ its 5 s grace.
47
+
9
48
  ## [1.1.0] - 2026-11-22
10
49
 
11
50
  ### Changed
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-delegate-mcp",
3
- "version": "1.1.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
@@ -3,7 +3,7 @@ import { EventEmitter } from "node:events";
3
3
  import { StringDecoder } from "node:string_decoder";
4
4
  import { JsonRpcPeer } from "./jsonrpc.js";
5
5
  import { createRequestRouter } from "./request-router.js";
6
- import { resolveAcpSpawn } from "./spawn.js";
6
+ import { commandExists, resolveAcpSpawn } from "./spawn.js";
7
7
  import { DETACHED, isChildAlive, treeKill } from "./proc.js";
8
8
  import { VERSION } from "./version.js";
9
9
  import { makeError } from "./errors.js";
@@ -19,9 +19,14 @@ export class AcpClient extends EventEmitter {
19
19
  * spawnSpec?: { command: string, args: string[], options?: object },
20
20
  * }} [opts]
21
21
  */
22
- constructor({ spawnSpec } = {}) {
22
+ /** @param {{ spawnSpec?: any, cwd?: string }} [opts] */
23
+ constructor({ spawnSpec, cwd } = {}) {
23
24
  super();
24
25
  this.spawnSpec = spawnSpec || resolveAcpSpawn();
26
+ // agy treats its process directory as part of the workspace, not only the session's cwd:
27
+ // started from the MCP server's directory it listed that directory and ran git status and
28
+ // git diff there (measured, agy 1.5.14). Started in the workspace, there is nothing else to see.
29
+ this.cwd = cwd;
25
30
  this._stderrChunks = [];
26
31
  this._stderrLength = 0;
27
32
  /** @type {Promise<boolean> | null} */
@@ -41,11 +46,14 @@ export class AcpClient extends EventEmitter {
41
46
 
42
47
  start() {
43
48
  const { command, args, options } = this.spawnSpec;
49
+ if (/** @type {{ shell?: boolean }} */ (options)?.shell && !commandExists(command)) {
50
+ return Promise.reject(makeError("spawn-failed", `Failed to spawn agent (${command}): not found on PATH. Install the Antigravity CLI (agy) and sign in by running agy once.`));
51
+ }
44
52
  this._stderrChunks = [];
45
53
  this._stderrLength = 0;
46
54
  const stderrDecoder = new StringDecoder("utf8");
47
55
  this._exitEmitted = false;
48
- this.child = spawn(command, args, { ...options, detached: DETACHED, stdio: ["pipe", "pipe", "pipe"] });
56
+ this.child = spawn(command, args, { ...options, ...(this.cwd ? { cwd: this.cwd } : {}), detached: DETACHED, stdio: ["pipe", "pipe", "pipe"] });
49
57
  this.child.stderr.on("data", (chunk) => {
50
58
  const text = stderrDecoder.write(chunk);
51
59
  if (text) {
@@ -142,7 +150,9 @@ export class AcpClient extends EventEmitter {
142
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
143
151
  setMode(sessionId, modeId) { return this.peer.request("session/set_mode", { sessionId, modeId }); }
144
152
  prompt(sessionId, blocks) { return this.peer.request("session/prompt", { sessionId, prompt: blocks }); }
145
- 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(); }
146
156
 
147
157
  getTranscript(n) { return this.peer ? this.peer.formatLog(n) : ""; }
148
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.
@@ -271,7 +280,7 @@ export async function runDelegate({
271
280
  const state = makeTurnState({ onProgress, progressThrottleMs });
272
281
 
273
282
  const make = clientFactory || ((opts) => new AcpClient(opts));
274
- const client = make({});
283
+ const client = make({ cwd: workspace });
275
284
  // Handed over before the spawn, because from client.start() there is an agent process and the
276
285
  // caller needs something that can stop it.
277
286
  onClientReady?.(client);
@@ -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
@@ -362,10 +373,32 @@ export async function runDelegate({
362
373
  if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
363
374
  const text = up.content.text;
364
375
  if (state.collectingResult()) state.appendResult(text);
376
+ else if (state.activeToolCalls.size > 0) state.unfinishedToolText += text;
365
377
  state.messages.push(text);
366
378
  }
367
379
  });
368
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
+
369
402
  let sessionId;
370
403
  let resumeError;
371
404
  let servedModel;
@@ -406,7 +439,11 @@ export async function runDelegate({
406
439
  promptInFlight = true;
407
440
  try {
408
441
  const blocks = await buildContextBlocks(contextFiles, workspace, client, contextWarnings);
409
- 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;
410
447
  } finally {
411
448
  // The result is assembled across awaits below, so without this a frame trailing the
412
449
  // settled turn is still folded into it.
@@ -421,7 +458,22 @@ export async function runDelegate({
421
458
  ? (state.sawToolCall ? "post-tool" : "tool-free-stream")
422
459
  : "none";
423
460
  const protocolWarnings = [];
424
- if (!finalMessageAvailable && state.discardedResult) {
461
+ if (!finalMessageAvailable && state.activeToolCalls.size > 0) {
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.
465
+ result = state.unfinishedToolText;
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.";
471
+ protocolWarnings.push(
472
+ `the turn ended with a tool call still running (${state.lastToolLabel ?? "unnamed tool"}).`
473
+ + cause
474
+ + (result ? " result is agy's message from while it ran." : " agy sent no message while it ran.")
475
+ );
476
+ } else if (!finalMessageAvailable && state.discardedResult) {
425
477
  result = state.discardedResult;
426
478
  resultSource = "pre-tool-fallback";
427
479
  protocolWarnings.push(
@@ -482,6 +534,11 @@ export async function runDelegate({
482
534
  } catch (err) {
483
535
  // A JSON-RPC code means the agent rejected something rather than the bridge breaking — the
484
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
+ }
485
542
  if (!err?.reason && typeof err?.code === "number") err.reason = "agent-error";
486
543
  // A bare duration cannot distinguish a wedged agent from a slow command, so name what was
487
544
  // outstanding — it also lets a retry resume the work already done.
package/src/doctor.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import process from "node:process";
2
2
  import { spawn } from "node:child_process";
3
3
  import { AcpClient } from "./acp-client.js";
4
- import { resolveAcpSpawn } from "./spawn.js";
4
+ import { commandExists, resolveAcpSpawn } from "./spawn.js";
5
5
  import { DETACHED, treeKill } from "./proc.js";
6
6
  import { readPackageVersion } from "./version.js";
7
7
  import { allowedValues, describeOptions } from "./model-options.js";
@@ -40,6 +40,8 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
40
40
  const isJsScript = isJsLauncher(launcher);
41
41
  const execCommand = isJsScript ? process.execPath : command;
42
42
  const execArgs = isJsScript ? [launcher, "--version"] : ["--version"];
43
+ // Through a shell, a missing launcher still spawns (the shell does) and would read as found.
44
+ if (options?.shell && !isJsScript && !commandExists(launcher)) return Promise.resolve({ found: false, version: null });
43
45
  return new Promise((resolve) => {
44
46
  let settled = false;
45
47
  let stdout = "";
@@ -83,8 +85,8 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
83
85
  }
84
86
 
85
87
  async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs }) {
86
- const client = clientFactory({ spawnSpec });
87
88
  const workspaceDir = workspace || process.cwd();
89
+ const client = clientFactory({ spawnSpec, cwd: workspaceDir });
88
90
  let timer;
89
91
  try {
90
92
  const details = {};
@@ -186,6 +188,7 @@ export async function runDoctor({
186
188
  AGY_DELEGATE_HANDSHAKE_MS: envReport("AGY_DELEGATE_HANDSHAKE_MS"),
187
189
  AGY_DELEGATE_HARD_CAP_MS: envReport("AGY_DELEGATE_HARD_CAP_MS"),
188
190
  AGY_DELEGATE_IDLE_MS: envReport("AGY_DELEGATE_IDLE_MS"),
191
+ AGY_DELEGATE_BACKGROUND_WAIT_MS: envReport("AGY_DELEGATE_BACKGROUND_WAIT_MS"),
189
192
  },
190
193
  };
191
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/server.js CHANGED
@@ -76,7 +76,7 @@ export const SERVER_INSTRUCTIONS = `Delegate coding work to Antigravity (agy) th
76
76
  // its tool description.
77
77
  export const delegateOutputShape = {
78
78
  result: z.string(),
79
- resultSource: z.enum(["pre-tool-fallback", "none"]).optional(),
79
+ resultSource: z.enum(["pre-tool-fallback", "unfinished-tool", "none"]).optional(),
80
80
  effectiveModel: z.string().optional(),
81
81
  effectiveEffort: z.record(z.string(), z.string()).optional(),
82
82
  stopReason: z.string().optional(),
@@ -305,7 +305,12 @@ export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDo
305
305
  // finally removes its handle when the turn actually settles.
306
306
  return cancelResult("cancelled", sessionId);
307
307
  }
308
- await new Promise((r) => setTimeout(r, forceGraceMs));
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.
310
+ const graceEnds = Date.now() + forceGraceMs;
311
+ while (Date.now() < graceEnds && inFlight.get(sessionId)?.size) {
312
+ await new Promise((r) => setTimeout(r, Math.min(50, Math.max(1, graceEnds - Date.now()))));
313
+ }
309
314
  const stillRunning = inFlight.get(sessionId);
310
315
  if (!stillRunning || stillRunning.size === 0) return cancelResult("cancelled", sessionId);
311
316
  // Snapshot before awaiting stop. A resume that registers during teardown must not be
package/src/spawn.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import process from "node:process";
2
+ import { existsSync, statSync } from "node:fs";
3
+ import path from "node:path";
2
4
 
3
5
  export function splitArgs(raw) {
4
6
  const args = [];
@@ -27,3 +29,21 @@ export function resolveAcpSpawn() {
27
29
  : [...DEFAULT_AGENT_ARGS];
28
30
  return { command, args, options: { shell: process.platform === "win32" } };
29
31
  }
32
+
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.
38
+ export function commandExists(command, env = process.env) {
39
+ const name = String(command || "").replace(/^["']|["']$/g, "");
40
+ if (!name) return false;
41
+ const pathKey = Object.keys(env).find((k) => k.toUpperCase() === "PATH");
42
+ const extKey = Object.keys(env).find((k) => k.toUpperCase() === "PATHEXT");
43
+ const exts = ["", ...String((extKey && env[extKey]) || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)];
44
+ const isFile = (p) => { try { return existsSync(p) && statSync(p).isFile(); } catch { return false; } };
45
+ const hit = (base) => exts.some((ext) => isFile(base + ext) || isFile(base + ext.toLowerCase()));
46
+ if (/[\\/]/.test(name)) return hit(name);
47
+ const dirs = String((pathKey && env[pathKey]) || "").split(path.delimiter).filter(Boolean);
48
+ return dirs.some((dir) => hit(path.join(dir.replace(/^"|"$/g, ""), name)));
49
+ }
package/src/turn-state.js CHANGED
@@ -52,9 +52,20 @@ function freshFields() {
52
52
  // caller "" with stopReason end_turn and no error. Kept so it can be handed back when
53
53
  // nothing survived — labelled, never blended with a real final message.
54
54
  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.
58
+ unfinishedToolText: "",
55
59
  sawToolCall: false,
56
60
  collectingPostToolResult: false,
57
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,
58
69
  // Ids observed terminal, so a stale non-terminal re-send for one is recognized and dropped
59
70
  // instead of restarting collection — which would demote an already-collected final message
60
71
  // to discardedResult and mislabel it pre-tool-fallback.
@@ -99,7 +110,9 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
99
110
  state.resultChunks.push(text);
100
111
  },
101
112
 
102
- startTool(toolCallId, status) {
113
+ startTool(toolCallId, status, name) {
114
+ if (toolCallId != null && name) state.toolNames.set(toolCallId, String(name));
115
+ state.unfinishedToolText = "";
103
116
  state.sawToolCall = true;
104
117
  state.collectingPostToolResult = false;
105
118
  state.resetResult();
@@ -137,6 +150,12 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
137
150
  }
138
151
  },
139
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
+
140
159
  // True while a message chunk still belongs in the result: before any tool ran, or after
141
160
  // the last one finished.
142
161
  collectingResult() {