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/delegate.js CHANGED
@@ -2,11 +2,10 @@ import process from "node:process";
2
2
  import path from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import { statSync, realpathSync } from "node:fs";
5
- // Async: a sync read on the server's only thread stalls every other in-flight delegation and
6
- // its progress stream. The statSync calls below stay sync — they are argument validation and
7
- // run before the spawn.
5
+ // Async: a sync read on the server's one thread stalls every other delegation. The statSync calls
6
+ // below are pre-spawn argument validation and stay sync.
8
7
  import { readFile } from "node:fs/promises";
9
- import { AcpClient } from "./acp-client.js";
8
+ import { AcpClient, GRACEFUL_STOP_MS, stampSettlement } from "./acp-client.js";
10
9
  import { DEFAULT_HARD_CAP_MS, SessionSupervisor } from "./session-supervisor.js";
11
10
  import { normalizeAgentReportedFiles } from "./agent-reported-files.js";
12
11
  import { makeTurnState } from "./turn-state.js";
@@ -15,18 +14,28 @@ import { effortSettings, optionsFrom, resolveEffort, allowedValues } from "./mod
15
14
  import { transcriptFrames } from "./jsonrpc.js";
16
15
 
17
16
  export const DEFAULT_HANDSHAKE_MS = 60000;
17
+
18
+ // Model and effort last set on each session by this process. agy reopens a resumed session at its
19
+ // defaults (agy #1460, measured on 1.5.14), so a resume that omits them re-applies these. LRU,
20
+ // bounded like seenSessions in server.js; a restarted server starts empty.
21
+ const sessionSettings = new Map();
22
+ const SESSION_SETTINGS_CAP = 500;
23
+ function rememberSettings(id, settings) {
24
+ sessionSettings.delete(id);
25
+ sessionSettings.set(id, settings);
26
+ if (sessionSettings.size > SESSION_SETTINGS_CAP) sessionSettings.delete(sessionSettings.keys().next().value);
27
+ }
28
+
18
29
  export const DEFAULT_BACKGROUND_WAIT_MS = 10 * 60 * 1000;
19
30
 
20
- // The bridge's modes onto agy's. agy has no ask mode: ask runs in default with ASK_PREAMBLE
21
- // ahead of the spec. default asks before edits and commands, which the launch flag and the
22
- // request router both approve.
31
+ // agy has no ask mode: ask runs in default with ASK_PREAMBLE ahead of the spec. default asks before
32
+ // edits and commands; the launch flag and the request router approve them.
23
33
  const AGY_MODE = { agent: "default", plan: "plan", ask: "default" };
24
34
  const ASK_PREAMBLE = "Answer the question below. Do not edit files or run commands that change state.";
25
35
  export const DEFAULT_HEARTBEAT_MS = 30000;
26
36
 
27
- // Malformed values fall back to the default rather than failing the call. Only a positive value
28
- // counts, so a blank var (Number("") is 0) cannot arm a zero-length deadline. The idle guard's
29
- // documented 0 comes from its own fallback being 0, not from an env value.
37
+ // A malformed or non-positive value falls back to the default, so a blank var (Number("") is 0)
38
+ // cannot arm a zero-length deadline. The idle guard's 0 is its fallback, not an env value.
30
39
  function envMs(name, fallback) {
31
40
  const raw = process.env[name];
32
41
  if (raw === undefined) return fallback;
@@ -39,19 +48,16 @@ function fmtDuration(ms) {
39
48
  return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
40
49
  }
41
50
 
42
- // A blank spec spins up a live session that only replies "No prompt content provided" —
43
- // a billed turn for nothing. Reject it before the spawn, like a bad workspace.
51
+ // A blank spec still costs a billed turn (agy replies "No prompt content provided").
44
52
  function assertSpec(spec) {
45
53
  if (typeof spec === "string" && spec.trim() === "") {
46
54
  throw makeError("invalid-spec", "spec is empty. Provide a task brief.");
47
55
  }
48
56
  }
49
57
 
50
- // Named, never defaulted: under npx or a plugin launch the server's own cwd is a cache directory
51
- // or the user's home, so a defaulted workspace put an auto-approved agent to work on a tree
52
- // nobody asked about while every layer reported success. And without the existence check the
53
- // agent's first write creates the directory, so a typo spawns a parallel empty tree. Same check
54
- // contextFiles applies.
58
+ // Required: under npx or a plugin the server's cwd is a cache directory or the user's home, the
59
+ // wrong tree for an auto-approved agent. Must exist: the agent's first write would create it, so a
60
+ // typo would start a parallel empty tree.
55
61
  function assertWorkspace(workspace) {
56
62
  if (typeof workspace !== "string" || workspace.trim() === "") {
57
63
  throw makeError("invalid-workspace", "workspace is required. Name the directory the agent should work in.");
@@ -74,19 +80,15 @@ const IMAGE_MIME = {
74
80
  // Base64 inflates by a third and every byte lands in the prompt, unlike a link.
75
81
  const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
76
82
 
77
- // A resource_link hands the agent a path, not the file's bytes, so a large brief costs prompt
78
- // space only for what the agent opens. Images have no such form — they go inline. Both are
79
- // measured working on agy 1.5.13, including a link outside the workspace and both together.
80
- // - gate images on the advertised capability: an agent that takes an unsupported block
81
- // without error would drop the image silently;
82
- // - report anything skipped — a dropped attachment is otherwise invisible.
83
+ // A resource_link passes a path, so the agent spends prompt space only on what it opens; images
84
+ // have no link form and go inline (both measured on agy 1.5.13, links outside the workspace too).
85
+ // Images are gated on the advertised capability, since an agent may drop an unsupported block
86
+ // silently, and every skip is reported.
83
87
  async function buildContextBlocks(contextFiles, workspace, client, warnings) {
84
88
  const blocks = [];
85
89
  // A glob plus an explicit path can resolve to one file; sending it twice wastes prompt space.
86
90
  const seen = new Set();
87
- // Grouped, not one warning per file: a wrong workspace misses every attachment at once, and a
88
- // line each would repeat the same root N times for one root cause. The other skip reasons stay
89
- // per-entry — they are individually distinct and never arrive in bulk.
91
+ // Grouped: a wrong workspace misses every attachment at once. Other skips are reported per entry.
90
92
  const notFound = [];
91
93
  const root = path.resolve(workspace || process.cwd());
92
94
  const identKey = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
@@ -145,11 +147,9 @@ async function buildContextBlocks(contextFiles, workspace, client, warnings) {
145
147
  return blocks;
146
148
  }
147
149
 
148
- // agy answers session/resume for an unknown id with -32603 "Failed to read session <id>; retry,
149
- // or load it with session/load", the same code and wording a failed read of a real session would
150
- // carry. session/list settles it: agy lists every session the account has, so an id missing from
151
- // it is one agy does not have. Only that justifies a fresh session; anything else runs the task
152
- // without the context the caller asked for.
150
+ // agy answers a resume of an unknown id and a failed read of a real one with the same -32603.
151
+ // session/list settles it: agy lists every session the account has, and only an id missing from it
152
+ // justifies a fresh session.
153
153
  async function sessionExists(client, sessionId) {
154
154
  try {
155
155
  const listed = await client.listSessions();
@@ -174,13 +174,29 @@ async function openSession(client, resumeSessionId, workspace) {
174
174
  + ` resumeSessionId to start fresh deliberately.`
175
175
  );
176
176
  }
177
- // Starting fresh is right, but silently doing so leaves the caller unable to tell a
178
- // stale id from a typo'd one — keep why the resume failed.
177
+ // Kept, so the caller can tell a stale id from a mistyped one.
179
178
  const fresh = await client.newSession(workspace);
180
179
  return { ...fresh, resumeError: `agy has no session ${resumeSessionId}` };
181
180
  }
182
181
  }
183
182
 
183
+ const isTokenCount = (v) => Number.isFinite(v) && v >= 0;
184
+
185
+ // The session/prompt reply's token counts cover that turn alone (measured, agy 1.5.14). Only ACP's
186
+ // numeric fields are kept. A steered turn has one reply per prompt; they are summed.
187
+ const USAGE_FIELDS = ["inputTokens", "outputTokens", "cachedReadTokens", "cachedWriteTokens", "thoughtTokens", "totalTokens"];
188
+ const BREAKDOWN_FIELDS = new Set(["cachedReadTokens", "cachedWriteTokens", "thoughtTokens"]);
189
+ export function readUsage(raws) {
190
+ const reported = raws.filter((raw) => raw && typeof raw === "object" && USAGE_FIELDS.some((k) => isTokenCount(raw[k])));
191
+ // The totals count only when every reply that reported usage carried them; summed from some of
192
+ // them they would understate the turn. A breakdown field a reply left out is zero for it.
193
+ const fields = USAGE_FIELDS.filter((k) => reported.length && (BREAKDOWN_FIELDS.has(k)
194
+ ? reported.some((raw) => isTokenCount(raw[k]))
195
+ : reported.every((raw) => isTokenCount(raw[k]))));
196
+ if (!fields.length) return undefined;
197
+ return { scope: "turn", ...Object.fromEntries(fields.map((k) => [k, reported.reduce((sum, raw) => sum + (isTokenCount(raw[k]) ? raw[k] : 0), 0)])) };
198
+ }
199
+
184
200
  function modelOption(configOptions) {
185
201
  return (Array.isArray(configOptions) ? configOptions : []).find((o) => o?.id === "model");
186
202
  }
@@ -190,10 +206,8 @@ function configOptionValue(configOptions, id) {
190
206
  return typeof opt?.currentValue === "string" ? opt.currentValue : undefined;
191
207
  }
192
208
 
193
- // The model ids a session accepts are the values of its model config option: base ids such as
194
- // gemini-4-neon, with the thinking level set separately. Reject anything else here, where the
195
- // list can be named — agy's own -32602 "Unknown model ID" names none. An agent that reports no
196
- // list is left alone.
209
+ // The model option's values are the accepted base ids (the thinking level is set separately).
210
+ // Checked here because agy's -32602 "Unknown model ID" names none. No list, no check.
197
211
  function assertKnownModel(configOptions, model) {
198
212
  const ids = allowedValues(modelOption(configOptions));
199
213
  if (ids.length === 0 || ids.includes(model)) return;
@@ -203,9 +217,8 @@ function assertKnownModel(configOptions, model) {
203
217
  );
204
218
  }
205
219
 
206
- // Sent only when the exact value appears under a thought-level option the selected model
207
- // advertised. Local validation keeps a bad token out of ACP and, more importantly, out of a
208
- // billed prompt. Missing capability data is not mislabeled as a caller mistake.
220
+ // Sent only when the selected model advertises the exact value, so a bad one never reaches a billed
221
+ // prompt. Missing capability data is reported as such, not as a caller error.
209
222
  async function applyEffort(client, sessionId, model, value, modelOptions) {
210
223
  const resolved = resolveEffort(modelOptions, value);
211
224
  if (resolved.status === "unavailable") {
@@ -241,6 +254,7 @@ async function applyEffort(client, sessionId, model, value, modelOptions) {
241
254
  * idleMs?: number, handshakeMs?: number, hardCapMs?: number, timeoutMs?: number,
242
255
  * onClientReady?: (client: any) => void,
243
256
  * onSessionReady?: (sessionId: string, client: any) => void,
257
+ * onTurnEnd?: () => void,
244
258
  * onProgress?: (message: string) => void,
245
259
  * progressThrottleMs?: number, heartbeatMs?: number, signal?: AbortSignal,
246
260
  * backgroundSettleMs?: number, backgroundContinueMs?: number, backgroundWaitMs?: number,
@@ -250,7 +264,7 @@ export async function runDelegate({
250
264
  spec, mode = "agent", resumeSessionId, workspace,
251
265
  model, effort, contextFiles, clientFactory,
252
266
  idleMs, handshakeMs, hardCapMs, timeoutMs,
253
- onClientReady, onSessionReady, onProgress, progressThrottleMs = 2000,
267
+ onClientReady, onSessionReady, onTurnEnd, onProgress, progressThrottleMs = 2000,
254
268
  heartbeatMs = DEFAULT_HEARTBEAT_MS,
255
269
  signal,
256
270
  // Quiet after agy's closing usage_update before its continuation counts as over, and how long
@@ -261,10 +275,8 @@ export async function runDelegate({
261
275
  // the hard cap.
262
276
  backgroundWaitMs = envMs("AGY_DELEGATE_BACKGROUND_WAIT_MS", DEFAULT_BACKGROUND_WAIT_MS),
263
277
  } = {}) {
264
- // Nothing between here and the abort listener below may await: addEventListener does not
265
- // replay an abort that already fired, so an abort landing in that window would be lost.
266
- // Throwing, not supervisor.abort(): tripping before supervise() installs its reject settles the
267
- // supervisor with nothing listening.
278
+ // No await between here and the abort listener: addEventListener does not replay a past abort.
279
+ // Thrown rather than supervisor.abort(), which before supervise() settles with nothing listening.
268
280
  if (signal?.aborted) {
269
281
  throw makeError("aborted", "delegation aborted by MCP host");
270
282
  }
@@ -281,15 +293,24 @@ export async function runDelegate({
281
293
 
282
294
  const make = clientFactory || ((opts) => new AcpClient(opts));
283
295
  const client = make({ cwd: workspace });
284
- // Handed over before the spawn, because from client.start() there is an agent process and the
285
- // caller needs something that can stop it.
296
+ // Handed over before the spawn, so the caller can stop the agent from client.start() on.
286
297
  onClientReady?.(client);
287
298
  const supervisor = new SessionSupervisor(client, { idleMs: turnIdleMs, handshakeMs: shakeMs, hardCapMs: capMs });
288
299
  const onAbort = () => supervisor.abort();
289
300
  signal?.addEventListener("abort", onAbort, { once: true });
301
+ // A cancel before the prompt ends setup at once; setup checks cancelRequested between its calls.
302
+ let promptSent = false;
303
+ // The caller's cancel only: a supervisor trip (a deadline, an abort) cancels after settling.
304
+ let cancelledInSetupByCaller = false;
305
+ const onCancel = () => {
306
+ if (promptSent || supervisor.settled) return;
307
+ cancelledInSetupByCaller = true;
308
+ supervisor.cancelSetup();
309
+ };
310
+ client.on?.("cancel", onCancel);
311
+ const cancelledInSetup = { stopReason: "cancelled", replies: [], cancelledBeforePrompt: true };
290
312
 
291
- // The bridge cannot see inside a running shell command, so a long silence is reported
292
- // rather than acted on: the caller gets elapsed time and frame age and can decide.
313
+ // The bridge cannot see inside a shell command, so silence is reported, not acted on.
293
314
  let promptInFlight = false;
294
315
  let heartbeat = null;
295
316
  const startHeartbeat = () => {
@@ -306,17 +327,15 @@ export async function runDelegate({
306
327
  heartbeat.unref?.();
307
328
  };
308
329
 
309
- // Malformed frames noticed as they arrive, where protocolWarnings does not exist yet. Merged
310
- // into it with the rest below.
330
+ // Collected as frames arrive; merged into protocolWarnings at the end.
311
331
  const frameWarnings = [];
332
+ const steerWarnings = [];
312
333
 
313
- // Diff blocks name the files an edit tool changed. agy sends them on the finished
314
- // tool_call_update; tool_call is read too, since a frame that arrives already finished carries
315
- // its content there.
334
+ // Diff blocks name the files an edit tool changed: agy sends them on the finished
335
+ // tool_call_update, or on tool_call when the call arrives already finished.
316
336
  const recordDiffs = (content) => {
317
- // Array.isArray, not `|| []`: a non-array content is truthy and iterating it throws here, in
318
- // the readline callback, where nothing awaits it. That is an uncaught exception — the whole
319
- // server, not this one turn — and it also stops the reply after it from being read.
337
+ // Array.isArray, not `|| []`: iterating a truthy non-array throws in the readline callback, an
338
+ // uncaught exception that takes down the server.
320
339
  for (const c of Array.isArray(content) ? content : []) {
321
340
  if (!c || typeof c !== "object" || Array.isArray(c) || typeof c.type !== "string"
322
341
  || (c.type === "diff" && (typeof c.path !== "string" || !c.path))) {
@@ -332,15 +351,18 @@ export async function runDelegate({
332
351
  }
333
352
  };
334
353
 
335
- // Only frames inside the prompt are read, so nothing the session sends while it opens is
336
- // folded into this turn.
354
+ // Only frames inside the prompt count, not those sent while the session opens.
337
355
  client.on("update", (u) => {
338
356
  if (!promptInFlight) return;
357
+ // One session per agy process today; the check keeps another session's frames out regardless.
358
+ if (sessionId && typeof u?.sessionId === "string" && u.sessionId !== sessionId) return;
339
359
  const up = u?.update || {};
340
360
  state.lastFrameAt = Date.now();
341
361
  state.usageAfterActivity = up.sessionUpdate === "usage_update";
342
- // The agent titles the turn a beat after the prompt lands — useful live, when several
343
- // delegations run, and in timeout forensics. Kept out of the result.
362
+ if (up.sessionUpdate === "usage_update" && isTokenCount(up.used) && isTokenCount(up.size) && up.size > 0) {
363
+ state.contextUsage = { used: up.used, size: up.size };
364
+ }
365
+ // agy titles the turn shortly after the prompt; shown live and in stall errors, not in the result.
344
366
  if (up.sessionUpdate === "session_info_update" && typeof up.title === "string" && up.title) {
345
367
  if (up.title !== state.sessionTitle) { try { onProgress?.(`turn titled: ${up.title}`.slice(0, 200)); } catch {} }
346
368
  state.sessionTitle = up.title;
@@ -349,18 +371,15 @@ export async function runDelegate({
349
371
  state.thoughts.push(up.content.text);
350
372
  }
351
373
  if (up.sessionUpdate === "tool_call" || up.sessionUpdate === "tool_call_update") {
352
- // An artifact is agy's own file (the plan, under its brain directory), reported as an
353
- // artifact rather than as a workspace edit.
374
+ // An artifact is agy's own file (the plan, in its brain directory), not a workspace edit.
354
375
  const isArtifact = state.recordArtifact(up.rawInput ?? up.args);
355
376
  if (up.sessionUpdate === "tool_call") {
356
377
  state.startTool(up.toolCallId, up.status, up.name ?? up.title);
357
378
  const label = String(up.title || up.kind || "tool");
358
379
  const path = up.locations?.[0]?.path;
359
- // Collapsed onto one line the way both readers of this take it: a progress notification
360
- // and the "last tool call" line in a stall error. A command title arrives verbatim, so a
361
- // multi-line script arrives with its newlines.
362
- // agy's titles already name the file, with forward slashes where the location has
363
- // backslashes, so the path is appended only when the title does not carry it.
380
+ // One line, for the progress note and the stall error (a command title keeps its newlines).
381
+ // agy's titles usually name the file, with forward slashes, so the path is appended only
382
+ // when the title lacks it.
364
383
  const slashed = (s) => String(s).replace(/\\/g, "/");
365
384
  const named = path && slashed(label).includes(slashed(path));
366
385
  state.lastToolLabel = (label + (path && !named ? " — " + path : "")).replace(/\s+/g, " ").trim();
@@ -378,19 +397,24 @@ export async function runDelegate({
378
397
  }
379
398
  });
380
399
 
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.
400
+ // agy backgrounds a shell command that outlasts WaitMsBeforeAsync and ends the turn; kept alive, it
401
+ // finishes the command and continues the turn unprompted, closing with a usage_update (measured,
402
+ // agy 1.5.14). Stopping agy at end_turn would kill the command. The hard cap still bounds the wait.
385
403
  let backgroundWaited;
404
+ // One clock per delegation, kept across steered turns.
405
+ let backgroundStartedAt;
386
406
  const waitForBackground = async () => {
387
407
  try { onProgress?.(`waiting for agy's background command: ${state.lastToolLabel ?? "tool"}`.slice(0, 200)); } catch {}
388
- const startedAt = Date.now();
408
+ const startedAt = (backgroundStartedAt ??= Date.now());
389
409
  for (;;) {
390
410
  await new Promise((r) => setTimeout(r, Math.min(250, backgroundSettleMs)));
391
411
  backgroundWaited = Date.now() - startedAt;
392
412
  if (backgroundWaited >= backgroundWaitMs) return;
413
+ // The delegation already failed (agent exit, abort, hard cap): nobody reads this wait.
414
+ if (supervisor.settled) return;
393
415
  if (client.cancelRequested) return "cancelled";
416
+ // A steer redirects the turn; its own prompt reply is what ends it now.
417
+ if (client.hasSteer?.()) return;
394
418
  if (state.backgroundToolCalls().length) continue;
395
419
  const quietMs = Date.now() - state.lastFrameAt;
396
420
  if (state.usageAfterActivity && quietMs >= backgroundSettleMs) return;
@@ -401,6 +425,9 @@ export async function runDelegate({
401
425
 
402
426
  let sessionId;
403
427
  let resumeError;
428
+ let failed;
429
+ /** @type {any} */
430
+ let out;
404
431
  let servedModel;
405
432
  let effectiveEffort;
406
433
  const contextWarnings = [];
@@ -413,40 +440,88 @@ export async function runDelegate({
413
440
  resumeError = sess.resumeError;
414
441
  supervisor.setSessionId(sessionId);
415
442
  onSessionReady?.(sessionId, client);
416
- // The options the session reports in force, replaced by each config reply. A resumed
417
- // session opens at agy's defaults rather than its saved settings (agy issue #1460,
418
- // reproduced on 1.5.13), so model, effort and mode are compared and re-sent every time
419
- // rather than assumed to have carried over.
443
+ // The options in force, replaced by each config reply. A resumed session opens at agy's
444
+ // defaults (agy #1460), so model, effort and mode are compared and re-sent every time.
420
445
  let options = client.configOptions;
421
- if (model !== undefined) {
422
- assertKnownModel(options, model);
423
- if (configOptionValue(options, "model") !== model) {
424
- options = optionsFrom(await client.setConfigOption(sessionId, "model", model));
446
+ if (client.cancelRequested) return cancelledInSetup;
447
+ // Only a resume that took inherits: a fallback to a fresh session is a different session.
448
+ const earlier = resumeSessionId && sessionId === resumeSessionId ? sessionSettings.get(sessionId) : undefined;
449
+ const targetModel = model ?? earlier?.model;
450
+ // A remembered effort holds only on the model it was set for: another model may not offer it.
451
+ const targetEffort = effort ?? (targetModel === earlier?.model ? earlier?.effort : undefined);
452
+ if (targetModel !== undefined) {
453
+ assertKnownModel(options, targetModel);
454
+ if (configOptionValue(options, "model") !== targetModel) {
455
+ options = optionsFrom(await client.setConfigOption(sessionId, "model", targetModel));
425
456
  }
426
457
  }
427
- if (effort !== undefined) {
428
- const target = model ?? configOptionValue(options, "model") ?? "the session's model";
429
- options = optionsFrom(await applyEffort(client, sessionId, target, effort, options));
458
+ if (client.cancelRequested) return cancelledInSetup;
459
+ if (targetEffort !== undefined) {
460
+ const target = targetModel ?? configOptionValue(options, "model") ?? "the session's model";
461
+ options = optionsFrom(await applyEffort(client, sessionId, target, targetEffort, options));
430
462
  }
463
+ if (client.cancelRequested) return cancelledInSetup;
431
464
  servedModel = configOptionValue(options, "model");
432
- // What the agent reported in force as the prompt goes out — never the requested value
433
- // standing in for a reply that did not confirm it.
465
+ // Saved once agy accepted them, with the model agy reports, so an effort set on agy's default
466
+ // is tied to that model.
467
+ if (targetModel !== undefined || targetEffort !== undefined) rememberSettings(sessionId, { model: targetModel ?? servedModel, effort: targetEffort });
468
+ // What agy reported in force, never the requested value.
434
469
  effectiveEffort = effortSettings(options);
435
470
  await client.setMode(sessionId, agyMode);
471
+ if (client.cancelRequested) return cancelledInSetup;
436
472
  state.reset();
437
473
  supervisor.promptStarted();
438
474
  startHeartbeat();
439
- promptInFlight = true;
440
475
  try {
441
476
  const blocks = await buildContextBlocks(contextFiles, workspace, client, contextWarnings);
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" };
477
+ // A cancel that lands while attachments are read: the prompt is not sent.
478
+ if (client.cancelRequested) return cancelledInSetup;
479
+ // Raised with the prompt, so frames sent while attachments were read are not folded in.
480
+ promptInFlight = true;
481
+ promptSent = true;
482
+ const first = stampSettlement(client.prompt(sessionId, [{ type: "text", text: promptText }, ...blocks]));
483
+ // Opened once the prompt is on the wire (request writes synchronously): a steer sent first
484
+ // makes agy read the brief as a redirect of it.
485
+ client.acceptSteers?.(true, mode === "ask" ? ASK_PREAMBLE : undefined);
486
+ const settled = await first;
487
+ let turn = settled.ok ? settled.value : undefined;
488
+ let turnError = "error" in settled ? settled.error : undefined;
489
+ let turnSeq = settled.seq;
490
+ const replies = settled.ok ? [turn] : [];
491
+ // A steer settles the prompt before it at once with end_turn, so the turn ends with the
492
+ // newest steer's reply. Each pass re-checks for a background command.
493
+ for (;;) {
494
+ // Only end_turn leaves a backgrounded command (measured); a refusal or output cap is not
495
+ // waited on.
496
+ if (turn?.stopReason === "end_turn" && !client.hasSteer?.() && state.backgroundToolCalls().length
497
+ && await waitForBackground() === "cancelled") {
498
+ return { ...turn, stopReason: "cancelled", replies };
499
+ }
500
+ const steer = client.takeSteer?.();
501
+ if (!steer) break;
502
+ const reply = await steer;
503
+ if (reply.ok) {
504
+ turn = reply.value;
505
+ turnError = undefined;
506
+ turnSeq = reply.seq;
507
+ replies.push(turn);
508
+ } else if (reply.seq < turnSeq) {
509
+ // Refused before its target settled: that turn stands, and the warning tells the caller.
510
+ steerWarnings.push(`a steer was rejected by agy and did not redirect the turn: ${reply.error?.message || String(reply.error)}`);
511
+ } else {
512
+ // Failed after taking the turn over: the turn failed, unless a steer queued behind it
513
+ // succeeds.
514
+ turn = undefined;
515
+ turnError = reply.error;
516
+ turnSeq = reply.seq;
517
+ }
445
518
  }
446
- return turn;
519
+ if (turnError) throw turnError;
520
+ return { ...turn, replies };
447
521
  } finally {
448
- // The result is assembled across awaits below, so without this a frame trailing the
449
- // settled turn is still folded into it.
522
+ // Closed in the same tick as the last check above, so no steer lands unread.
523
+ client.acceptSteers?.(false);
524
+ // Cleared before the awaits below, so a frame trailing the settled turn is not folded in.
450
525
  promptInFlight = false;
451
526
  }
452
527
  });
@@ -459,15 +534,17 @@ export async function runDelegate({
459
534
  : "none";
460
535
  const protocolWarnings = [];
461
536
  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.
537
+ // Measured cases (agy 1.5.14): a background command still running when the wait ran out, or an
538
+ // ask_question waiting on the caller.
465
539
  result = state.unfinishedToolText;
466
540
  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.";
541
+ // A refusal or output cap is not waited on, so a command can be open with no wait.
542
+ const cause = !state.backgroundToolCalls().length
543
+ ? " agy is asking a question (ask_question), which a resume answers."
544
+ : backgroundWaited !== undefined
545
+ ? ` agy moved it to the background, and it was still running after the bridge waited ${fmtDuration(backgroundWaited)}`
546
+ + " (AGY_DELEGATE_BACKGROUND_WAIT_MS); it stops when the bridge stops agy."
547
+ : ` agy ended the turn (${res?.stopReason}) with it still running; it stops when the bridge stops agy.`;
471
548
  protocolWarnings.push(
472
549
  `the turn ended with a tool call still running (${state.lastToolLabel ?? "unnamed tool"}).`
473
550
  + cause
@@ -480,7 +557,7 @@ export async function runDelegate({
480
557
  "the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
481
558
  + " result carries the last message before that tool call — it may be a preamble rather than the answer."
482
559
  );
483
- } else if (!finalMessageAvailable) {
560
+ } else if (!finalMessageAvailable && !res?.cancelledBeforePrompt) {
484
561
  protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
485
562
  }
486
563
  let stopReason;
@@ -488,31 +565,29 @@ export async function runDelegate({
488
565
  if (typeof res.stopReason !== "string") {
489
566
  protocolWarnings.push("stopReason dropped: ACP requires a string stop reason");
490
567
  } else if (res.stopReason !== "end_turn") {
491
- // end_turn carries no signal. Surface a stop reason only when something happened: a
492
- // refusal, a cancel, an output cap.
568
+ // end_turn is the normal case; only other stop reasons are surfaced.
493
569
  stopReason = res.stopReason;
494
570
  }
495
571
  }
496
- const out = {
572
+ out = {
497
573
  result,
498
574
  sessionId,
499
575
  };
500
- // Absence means "nothing reported", not "nothing changed" — a claim this field cannot make,
501
- // since shell-driven edits leave no diff event.
576
+ // Absent means nothing reported, not nothing changed: shell edits emit no diff.
502
577
  const filesReported = normalizeAgentReportedFiles([...state.touched], workspace);
503
578
  if (filesReported.length) out.filesReportedByEditTools = filesReported;
504
- // resultSource is a caveat, not a fact: on the happy path result is just the answer. Emit it
505
- // only when it warns. resumed likewise appears only when a resume took.
579
+ // resultSource appears only as a caveat; resumed only when a resume took.
506
580
  if (resultSource !== "post-tool" && resultSource !== "tool-free-stream") out.resultSource = resultSource;
507
581
  if (!!resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
508
- // Present when the session ran a different model than asked, and always when model was
509
- // omitted: then it is the only place the caller sees which model agy used.
582
+ // Present when the served model differs from the requested one, so always when model was omitted.
510
583
  if (servedModel !== undefined && servedModel !== model) out.effectiveModel = servedModel;
511
584
  if (effectiveEffort !== undefined) out.effectiveEffort = effectiveEffort;
512
585
  if (stopReason !== undefined) out.stopReason = stopReason;
513
- // In plan mode agy's message points at the plan rather than containing it, so the plan
514
- // artifact's content is the plan. Any other artifact is listed by path and summary; its
515
- // content stays in the file.
586
+ const usage = readUsage((res?.replies ?? [res]).map((r) => r?.usage));
587
+ if (usage) out.usage = usage;
588
+ if (state.contextUsage) out.context = state.contextUsage;
589
+ // In plan mode agy's message points at the plan; the artifact's content is the plan. Other
590
+ // artifacts are listed by path and summary.
516
591
  const artifacts = [...state.artifacts.values()];
517
592
  const planArtifact = mode === "plan" ? artifacts.at(-1) : undefined;
518
593
  if (planArtifact) {
@@ -529,22 +604,28 @@ export async function runDelegate({
529
604
  if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
530
605
  protocolWarnings.push(...contextWarnings);
531
606
  protocolWarnings.push(...frameWarnings);
607
+ protocolWarnings.push(...steerWarnings);
532
608
  if (protocolWarnings.length) out.protocolWarnings = protocolWarnings;
533
609
  return out;
534
610
  } catch (err) {
535
- // A JSON-RPC code means the agent rejected something rather than the bridge breaking — the
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.
611
+ // A caller's cancel before the prompt is a cancelled result, even if a config call then failed.
612
+ if (cancelledInSetupByCaller && sessionId) {
613
+ out = { result: "", sessionId, stopReason: "cancelled" };
614
+ if (resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
615
+ if (resumeError) out.protocolWarnings = [`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`];
616
+ return out;
617
+ }
618
+ failed = err;
619
+ // A JSON-RPC code means agy rejected something (fix the arguments), not that the bridge broke
620
+ // (retry). -32000 is ACP's auth_required, sent by agy from session/new when signed out.
538
621
  if (!err?.reason && err?.code === -32000) {
539
622
  err.reason = "not-signed-in";
540
623
  err.message += ". agy is not signed in: run agy once in a terminal and sign in, then retry.";
541
624
  }
542
625
  if (!err?.reason && typeof err?.code === "number") err.reason = "agent-error";
543
- // A bare duration cannot distinguish a wedged agent from a slow command, so name what was
544
- // outstanding — it also lets a retry resume the work already done.
626
+ // A bare duration cannot tell a wedged agent from a slow command, so name what was outstanding.
545
627
  const isTimeout = err?.reason === "hard-cap" || err?.reason === "idle-timeout";
546
- // A handshake timeout gets the forensics but not the long-command advice: no prompt was sent,
547
- // so no shell command explains the silence.
628
+ // A handshake timeout gets the forensics but not the long-command advice: no prompt was sent.
548
629
  const isStall = isTimeout || err?.reason === "handshake-timeout";
549
630
  if (isStall || err?.reason === "aborted" || err?.reason === "agent-exit") {
550
631
  const age = fmtDuration(supervisor.msSinceActivity());
@@ -553,24 +634,20 @@ export async function runDelegate({
553
634
  const files = normalizeAgentReportedFiles([...state.touched], workspace);
554
635
  if (files.length) err.message += ` Files reported edited: ${files.join(", ")}.`;
555
636
  }
556
- // Every failure after the session opens leaves a live session, not just the stalls: the id is
557
- // set before the config calls, so unknown-model and a rejected effort land here too.
637
+ // Any failure after the session opens leaves a live session, unknown-model and effort included.
558
638
  if (resumeError) {
559
- // Without this the resume hint reads as "carry on from where you were", when the requested
560
- // session was never resumed.
639
+ // Otherwise the resume hint reads as continuing work that was never in context.
561
640
  err.message += ` Note: resuming ${resumeSessionId} had already failed (${resumeError}),`
562
641
  + ` so this ran as a fresh session and none of that earlier work was in context.`;
563
642
  }
564
643
  if (sessionId) err.message += ` Resume with resumeSessionId ${sessionId}.`;
565
644
  if (isTimeout) {
566
- // Name the knob that actually fired: raising the hard cap does nothing for an
567
- // idle-timeout, whose ceiling is AGY_DELEGATE_IDLE_MS.
645
+ // Name the knob that fired: the hard cap does not govern an idle-timeout.
568
646
  const knob = err.reason === "idle-timeout" ? "AGY_DELEGATE_IDLE_MS" : "AGY_DELEGATE_HARD_CAP_MS";
569
647
  err.message += " agy does not stream shell output over ACP, so a long-running command emits"
570
648
  + ` nothing until it exits. Split the command, run it in the background and poll, or raise ${knob}.`;
571
649
  }
572
- // Opt-in: the frames land in the caller's context and nothing there is actionable — the
573
- // forensics above already carry that. Raw frames only help someone debugging the bridge.
650
+ // Opt-in: raw frames help only when debugging the bridge, and cost the caller context.
574
651
  const frames = transcriptFrames();
575
652
  if (frames > 0) {
576
653
  try {
@@ -580,11 +657,34 @@ export async function runDelegate({
580
657
  }
581
658
  throw err;
582
659
  } finally {
660
+ // The turn is decided; what follows is teardown. The server stops treating a cancel as aimed
661
+ // at a running turn.
662
+ try { onTurnEnd?.(); } catch {}
583
663
  clearInterval(heartbeat);
584
664
  signal?.removeEventListener("abort", onAbort);
665
+ client.off?.("cancel", onCancel);
585
666
  try { supervisor.finish(); } catch {}
586
- // Deliberately not awaited: stop() waits for the child to exit, and every turn — success as
587
- // much as failure — would pay that before returning. Nothing here reads whether it landed.
588
- Promise.resolve(client.stop()).catch(() => {});
667
+ // Awaited, so agy has exited when the caller gets the result; otherwise agy still holds the
668
+ // workspace as its cwd (deleting it fails with EBUSY on Windows). The handle stays registered
669
+ // meanwhile, so force cancel and shutdown can cut the grace short. Graceful after a completed
670
+ // turn, so agy closes its conversation database; a stall, abort or exit is killed at once.
671
+ const killNow = signal?.aborted || ["handshake-timeout", "hard-cap", "idle-timeout", "aborted", "agent-exit"].includes(failed?.reason);
672
+ // A host abort during the close is still an abort: a force stop ends the grace and kills.
673
+ const abortClose = () => { Promise.resolve(client.stop()).catch(() => {}); };
674
+ signal?.addEventListener("abort", abortClose, { once: true });
675
+ let exited = false;
676
+ try {
677
+ exited = await client.stop({ graceMs: killNow ? 0 : GRACEFUL_STOP_MS });
678
+ // A stop that did not see the exit is not memoized, so a second one dispatches a fresh kill.
679
+ if (exited === false) exited = await client.stop();
680
+ } catch {}
681
+ finally { signal?.removeEventListener("abort", abortClose); }
682
+ if (exited === false) {
683
+ const pid = client.child?.pid;
684
+ const note = `the bridge stopped agy${pid ? ` (pid ${pid})` : ""} but did not see agy exit; it may still be running.`;
685
+ // The result or the error is already decided; the note rides on whichever is going out.
686
+ if (failed) failed.message += ` Note: ${note}`;
687
+ else if (out) (out.protocolWarnings ??= []).push(note);
688
+ }
589
689
  }
590
690
  }