agy-delegate-mcp 1.4.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, GRACEFUL_STOP_MS } 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";
@@ -16,18 +15,27 @@ import { transcriptFrames } from "./jsonrpc.js";
16
15
 
17
16
  export const DEFAULT_HANDSHAKE_MS = 60000;
18
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
+
19
29
  export const DEFAULT_BACKGROUND_WAIT_MS = 10 * 60 * 1000;
20
30
 
21
- // The bridge's modes onto agy's. agy has no ask mode: ask runs in default with ASK_PREAMBLE
22
- // ahead of the spec. default asks before edits and commands, which the launch flag and the
23
- // 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.
24
33
  const AGY_MODE = { agent: "default", plan: "plan", ask: "default" };
25
34
  const ASK_PREAMBLE = "Answer the question below. Do not edit files or run commands that change state.";
26
35
  export const DEFAULT_HEARTBEAT_MS = 30000;
27
36
 
28
- // Malformed values fall back to the default rather than failing the call. Only a positive value
29
- // counts, so a blank var (Number("") is 0) cannot arm a zero-length deadline. The idle guard's
30
- // 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.
31
39
  function envMs(name, fallback) {
32
40
  const raw = process.env[name];
33
41
  if (raw === undefined) return fallback;
@@ -40,19 +48,16 @@ function fmtDuration(ms) {
40
48
  return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
41
49
  }
42
50
 
43
- // A blank spec spins up a live session that only replies "No prompt content provided" —
44
- // 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").
45
52
  function assertSpec(spec) {
46
53
  if (typeof spec === "string" && spec.trim() === "") {
47
54
  throw makeError("invalid-spec", "spec is empty. Provide a task brief.");
48
55
  }
49
56
  }
50
57
 
51
- // Named, never defaulted: under npx or a plugin launch the server's own cwd is a cache directory
52
- // or the user's home, so a defaulted workspace put an auto-approved agent to work on a tree
53
- // nobody asked about while every layer reported success. And without the existence check the
54
- // agent's first write creates the directory, so a typo spawns a parallel empty tree. Same check
55
- // 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.
56
61
  function assertWorkspace(workspace) {
57
62
  if (typeof workspace !== "string" || workspace.trim() === "") {
58
63
  throw makeError("invalid-workspace", "workspace is required. Name the directory the agent should work in.");
@@ -75,19 +80,15 @@ const IMAGE_MIME = {
75
80
  // Base64 inflates by a third and every byte lands in the prompt, unlike a link.
76
81
  const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
77
82
 
78
- // A resource_link hands the agent a path, not the file's bytes, so a large brief costs prompt
79
- // space only for what the agent opens. Images have no such form — they go inline. Both are
80
- // measured working on agy 1.5.13, including a link outside the workspace and both together.
81
- // - gate images on the advertised capability: an agent that takes an unsupported block
82
- // without error would drop the image silently;
83
- // - 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.
84
87
  async function buildContextBlocks(contextFiles, workspace, client, warnings) {
85
88
  const blocks = [];
86
89
  // A glob plus an explicit path can resolve to one file; sending it twice wastes prompt space.
87
90
  const seen = new Set();
88
- // Grouped, not one warning per file: a wrong workspace misses every attachment at once, and a
89
- // line each would repeat the same root N times for one root cause. The other skip reasons stay
90
- // 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.
91
92
  const notFound = [];
92
93
  const root = path.resolve(workspace || process.cwd());
93
94
  const identKey = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
@@ -146,11 +147,9 @@ async function buildContextBlocks(contextFiles, workspace, client, warnings) {
146
147
  return blocks;
147
148
  }
148
149
 
149
- // agy answers session/resume for an unknown id with -32603 "Failed to read session <id>; retry,
150
- // or load it with session/load", the same code and wording a failed read of a real session would
151
- // carry. session/list settles it: agy lists every session the account has, so an id missing from
152
- // it is one agy does not have. Only that justifies a fresh session; anything else runs the task
153
- // 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.
154
153
  async function sessionExists(client, sessionId) {
155
154
  try {
156
155
  const listed = await client.listSessions();
@@ -175,8 +174,7 @@ async function openSession(client, resumeSessionId, workspace) {
175
174
  + ` resumeSessionId to start fresh deliberately.`
176
175
  );
177
176
  }
178
- // Starting fresh is right, but silently doing so leaves the caller unable to tell a
179
- // 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.
180
178
  const fresh = await client.newSession(workspace);
181
179
  return { ...fresh, resumeError: `agy has no session ${resumeSessionId}` };
182
180
  }
@@ -184,18 +182,19 @@ async function openSession(client, resumeSessionId, workspace) {
184
182
 
185
183
  const isTokenCount = (v) => Number.isFinite(v) && v >= 0;
186
184
 
187
- // The token counts agy's session/prompt reply carries for that turn alone (measured, agy 1.5.14:
188
- // three one-line turns on one session reported 10273, 10406 and 10575 input tokens). Only the
189
- // fields ACP names, and only numbers, so an agent's extra keys stay out of the result. A steered
190
- // turn has one reply per prompt, each covering its own part, so they are summed.
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.
191
187
  const USAGE_FIELDS = ["inputTokens", "outputTokens", "cachedReadTokens", "cachedWriteTokens", "thoughtTokens", "totalTokens"];
188
+ const BREAKDOWN_FIELDS = new Set(["cachedReadTokens", "cachedWriteTokens", "thoughtTokens"]);
192
189
  export function readUsage(raws) {
193
190
  const reported = raws.filter((raw) => raw && typeof raw === "object" && USAGE_FIELDS.some((k) => isTokenCount(raw[k])));
194
- // A field counts only when every reply that reported usage carried it; summed from some of them
195
- // it would understate the turn.
196
- const fields = USAGE_FIELDS.filter((k) => reported.length && reported.every((raw) => 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]))));
197
196
  if (!fields.length) return undefined;
198
- return { scope: "turn", ...Object.fromEntries(fields.map((k) => [k, reported.reduce((sum, raw) => sum + raw[k], 0)])) };
197
+ return { scope: "turn", ...Object.fromEntries(fields.map((k) => [k, reported.reduce((sum, raw) => sum + (isTokenCount(raw[k]) ? raw[k] : 0), 0)])) };
199
198
  }
200
199
 
201
200
  function modelOption(configOptions) {
@@ -207,10 +206,8 @@ function configOptionValue(configOptions, id) {
207
206
  return typeof opt?.currentValue === "string" ? opt.currentValue : undefined;
208
207
  }
209
208
 
210
- // The model ids a session accepts are the values of its model config option: base ids such as
211
- // gemini-4-neon, with the thinking level set separately. Reject anything else here, where the
212
- // list can be named — agy's own -32602 "Unknown model ID" names none. An agent that reports no
213
- // 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.
214
211
  function assertKnownModel(configOptions, model) {
215
212
  const ids = allowedValues(modelOption(configOptions));
216
213
  if (ids.length === 0 || ids.includes(model)) return;
@@ -220,9 +217,8 @@ function assertKnownModel(configOptions, model) {
220
217
  );
221
218
  }
222
219
 
223
- // Sent only when the exact value appears under a thought-level option the selected model
224
- // advertised. Local validation keeps a bad token out of ACP and, more importantly, out of a
225
- // 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.
226
222
  async function applyEffort(client, sessionId, model, value, modelOptions) {
227
223
  const resolved = resolveEffort(modelOptions, value);
228
224
  if (resolved.status === "unavailable") {
@@ -258,6 +254,7 @@ async function applyEffort(client, sessionId, model, value, modelOptions) {
258
254
  * idleMs?: number, handshakeMs?: number, hardCapMs?: number, timeoutMs?: number,
259
255
  * onClientReady?: (client: any) => void,
260
256
  * onSessionReady?: (sessionId: string, client: any) => void,
257
+ * onTurnEnd?: () => void,
261
258
  * onProgress?: (message: string) => void,
262
259
  * progressThrottleMs?: number, heartbeatMs?: number, signal?: AbortSignal,
263
260
  * backgroundSettleMs?: number, backgroundContinueMs?: number, backgroundWaitMs?: number,
@@ -267,7 +264,7 @@ export async function runDelegate({
267
264
  spec, mode = "agent", resumeSessionId, workspace,
268
265
  model, effort, contextFiles, clientFactory,
269
266
  idleMs, handshakeMs, hardCapMs, timeoutMs,
270
- onClientReady, onSessionReady, onProgress, progressThrottleMs = 2000,
267
+ onClientReady, onSessionReady, onTurnEnd, onProgress, progressThrottleMs = 2000,
271
268
  heartbeatMs = DEFAULT_HEARTBEAT_MS,
272
269
  signal,
273
270
  // Quiet after agy's closing usage_update before its continuation counts as over, and how long
@@ -278,10 +275,8 @@ export async function runDelegate({
278
275
  // the hard cap.
279
276
  backgroundWaitMs = envMs("AGY_DELEGATE_BACKGROUND_WAIT_MS", DEFAULT_BACKGROUND_WAIT_MS),
280
277
  } = {}) {
281
- // Nothing between here and the abort listener below may await: addEventListener does not
282
- // replay an abort that already fired, so an abort landing in that window would be lost.
283
- // Throwing, not supervisor.abort(): tripping before supervise() installs its reject settles the
284
- // 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.
285
280
  if (signal?.aborted) {
286
281
  throw makeError("aborted", "delegation aborted by MCP host");
287
282
  }
@@ -298,15 +293,24 @@ export async function runDelegate({
298
293
 
299
294
  const make = clientFactory || ((opts) => new AcpClient(opts));
300
295
  const client = make({ cwd: workspace });
301
- // Handed over before the spawn, because from client.start() there is an agent process and the
302
- // caller needs something that can stop it.
296
+ // Handed over before the spawn, so the caller can stop the agent from client.start() on.
303
297
  onClientReady?.(client);
304
298
  const supervisor = new SessionSupervisor(client, { idleMs: turnIdleMs, handshakeMs: shakeMs, hardCapMs: capMs });
305
299
  const onAbort = () => supervisor.abort();
306
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 };
307
312
 
308
- // The bridge cannot see inside a running shell command, so a long silence is reported
309
- // 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.
310
314
  let promptInFlight = false;
311
315
  let heartbeat = null;
312
316
  const startHeartbeat = () => {
@@ -323,18 +327,15 @@ export async function runDelegate({
323
327
  heartbeat.unref?.();
324
328
  };
325
329
 
326
- // Malformed frames noticed as they arrive, where protocolWarnings does not exist yet. Merged
327
- // into it with the rest below.
330
+ // Collected as frames arrive; merged into protocolWarnings at the end.
328
331
  const frameWarnings = [];
329
332
  const steerWarnings = [];
330
333
 
331
- // Diff blocks name the files an edit tool changed. agy sends them on the finished
332
- // tool_call_update; tool_call is read too, since a frame that arrives already finished carries
333
- // 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.
334
336
  const recordDiffs = (content) => {
335
- // Array.isArray, not `|| []`: a non-array content is truthy and iterating it throws here, in
336
- // the readline callback, where nothing awaits it. That is an uncaught exception — the whole
337
- // 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.
338
339
  for (const c of Array.isArray(content) ? content : []) {
339
340
  if (!c || typeof c !== "object" || Array.isArray(c) || typeof c.type !== "string"
340
341
  || (c.type === "diff" && (typeof c.path !== "string" || !c.path))) {
@@ -350,18 +351,18 @@ export async function runDelegate({
350
351
  }
351
352
  };
352
353
 
353
- // Only frames inside the prompt are read, so nothing the session sends while it opens is
354
- // folded into this turn.
354
+ // Only frames inside the prompt count, not those sent while the session opens.
355
355
  client.on("update", (u) => {
356
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;
357
359
  const up = u?.update || {};
358
360
  state.lastFrameAt = Date.now();
359
361
  state.usageAfterActivity = up.sessionUpdate === "usage_update";
360
362
  if (up.sessionUpdate === "usage_update" && isTokenCount(up.used) && isTokenCount(up.size) && up.size > 0) {
361
363
  state.contextUsage = { used: up.used, size: up.size };
362
364
  }
363
- // The agent titles the turn a beat after the prompt lands — useful live, when several
364
- // delegations run, and in timeout forensics. Kept out of the result.
365
+ // agy titles the turn shortly after the prompt; shown live and in stall errors, not in the result.
365
366
  if (up.sessionUpdate === "session_info_update" && typeof up.title === "string" && up.title) {
366
367
  if (up.title !== state.sessionTitle) { try { onProgress?.(`turn titled: ${up.title}`.slice(0, 200)); } catch {} }
367
368
  state.sessionTitle = up.title;
@@ -370,18 +371,15 @@ export async function runDelegate({
370
371
  state.thoughts.push(up.content.text);
371
372
  }
372
373
  if (up.sessionUpdate === "tool_call" || up.sessionUpdate === "tool_call_update") {
373
- // An artifact is agy's own file (the plan, under its brain directory), reported as an
374
- // 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.
375
375
  const isArtifact = state.recordArtifact(up.rawInput ?? up.args);
376
376
  if (up.sessionUpdate === "tool_call") {
377
377
  state.startTool(up.toolCallId, up.status, up.name ?? up.title);
378
378
  const label = String(up.title || up.kind || "tool");
379
379
  const path = up.locations?.[0]?.path;
380
- // Collapsed onto one line the way both readers of this take it: a progress notification
381
- // and the "last tool call" line in a stall error. A command title arrives verbatim, so a
382
- // multi-line script arrives with its newlines.
383
- // agy's titles already name the file, with forward slashes where the location has
384
- // 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.
385
383
  const slashed = (s) => String(s).replace(/\\/g, "/");
386
384
  const named = path && slashed(label).includes(slashed(path));
387
385
  state.lastToolLabel = (label + (path && !named ? " — " + path : "")).replace(/\s+/g, " ").trim();
@@ -399,14 +397,15 @@ export async function runDelegate({
399
397
  }
400
398
  });
401
399
 
402
- // agy moves a shell command to the background once it outlasts the call's WaitMsBeforeAsync and
403
- // ends the turn; kept alive, it finishes the command, marks the call completed and continues the
404
- // turn unprompted, closing with a usage_update (measured, agy 1.5.14). Stopping agy at end_turn
405
- // 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.
406
403
  let backgroundWaited;
404
+ // One clock per delegation, kept across steered turns.
405
+ let backgroundStartedAt;
407
406
  const waitForBackground = async () => {
408
407
  try { onProgress?.(`waiting for agy's background command: ${state.lastToolLabel ?? "tool"}`.slice(0, 200)); } catch {}
409
- const startedAt = Date.now();
408
+ const startedAt = (backgroundStartedAt ??= Date.now());
410
409
  for (;;) {
411
410
  await new Promise((r) => setTimeout(r, Math.min(250, backgroundSettleMs)));
412
411
  backgroundWaited = Date.now() - startedAt;
@@ -427,6 +426,8 @@ export async function runDelegate({
427
426
  let sessionId;
428
427
  let resumeError;
429
428
  let failed;
429
+ /** @type {any} */
430
+ let out;
430
431
  let servedModel;
431
432
  let effectiveEffort;
432
433
  const contextWarnings = [];
@@ -439,62 +440,88 @@ export async function runDelegate({
439
440
  resumeError = sess.resumeError;
440
441
  supervisor.setSessionId(sessionId);
441
442
  onSessionReady?.(sessionId, client);
442
- // The options the session reports in force, replaced by each config reply. A resumed
443
- // session opens at agy's defaults rather than its saved settings (agy issue #1460,
444
- // reproduced on 1.5.13), so model, effort and mode are compared and re-sent every time
445
- // 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.
446
445
  let options = client.configOptions;
447
- if (model !== undefined) {
448
- assertKnownModel(options, model);
449
- if (configOptionValue(options, "model") !== model) {
450
- 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));
451
456
  }
452
457
  }
453
- if (effort !== undefined) {
454
- const target = model ?? configOptionValue(options, "model") ?? "the session's model";
455
- 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));
456
462
  }
463
+ if (client.cancelRequested) return cancelledInSetup;
457
464
  servedModel = configOptionValue(options, "model");
458
- // What the agent reported in force as the prompt goes out — never the requested value
459
- // 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.
460
469
  effectiveEffort = effortSettings(options);
461
470
  await client.setMode(sessionId, agyMode);
471
+ if (client.cancelRequested) return cancelledInSetup;
462
472
  state.reset();
463
473
  supervisor.promptStarted();
464
474
  startHeartbeat();
465
- promptInFlight = true;
466
475
  try {
467
476
  const blocks = await buildContextBlocks(contextFiles, workspace, client, contextWarnings);
468
- const first = client.prompt(sessionId, [{ type: "text", text: promptText }, ...blocks]);
469
- // Opened only once the prompt is on the wire (request writes synchronously): a steer
470
- // accepted earlier went out first, and agy took the brief as a redirect of it.
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.
471
485
  client.acceptSteers?.(true, mode === "ask" ? ASK_PREAMBLE : undefined);
472
- let turn = await first;
473
- const replies = [turn];
474
- // A steer settles the prompt before it at once with end_turn, so the turn ends only when
475
- // the newest steer's reply does. Each pass re-checks for a background command, which a
476
- // steered turn can leave running too.
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.
477
493
  for (;;) {
478
- if (!client.hasSteer?.() && state.backgroundToolCalls().length && await waitForBackground() === "cancelled") {
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") {
479
498
  return { ...turn, stopReason: "cancelled", replies };
480
499
  }
481
500
  const steer = client.takeSteer?.();
482
501
  if (!steer) break;
483
- // A rejected steer redirected nothing: the turn it was aimed at stands, and the caller,
484
- // told "steered", learns here that agy refused it.
485
- try {
486
- turn = await steer;
502
+ const reply = await steer;
503
+ if (reply.ok) {
504
+ turn = reply.value;
505
+ turnError = undefined;
506
+ turnSeq = reply.seq;
487
507
  replies.push(turn);
488
- } catch (err) {
489
- steerWarnings.push(`a steer was rejected by agy and did not redirect the turn: ${err?.message || String(err)}`);
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;
490
517
  }
491
518
  }
519
+ if (turnError) throw turnError;
492
520
  return { ...turn, replies };
493
521
  } finally {
494
522
  // Closed in the same tick as the last check above, so no steer lands unread.
495
523
  client.acceptSteers?.(false);
496
- // The result is assembled across awaits below, so without this a frame trailing the
497
- // settled turn is still folded into it.
524
+ // Cleared before the awaits below, so a frame trailing the settled turn is not folded in.
498
525
  promptInFlight = false;
499
526
  }
500
527
  });
@@ -507,15 +534,17 @@ export async function runDelegate({
507
534
  : "none";
508
535
  const protocolWarnings = [];
509
536
  if (!finalMessageAvailable && state.activeToolCalls.size > 0) {
510
- // Two measured cases (agy 1.5.14): a backgrounded command still running when the wait for it
511
- // ran out, or an ask_question, which waits on the caller. The bridge stops agy when the
512
- // 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.
513
539
  result = state.unfinishedToolText;
514
540
  resultSource = result ? "unfinished-tool" : "none";
515
- const cause = backgroundWaited !== undefined && state.backgroundToolCalls().length
516
- ? ` agy moved it to the background, and it was still running after the bridge waited ${fmtDuration(backgroundWaited)}`
517
- + " (AGY_DELEGATE_BACKGROUND_WAIT_MS); it stops when the bridge stops agy."
518
- : " 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.`;
519
548
  protocolWarnings.push(
520
549
  `the turn ended with a tool call still running (${state.lastToolLabel ?? "unnamed tool"}).`
521
550
  + cause
@@ -528,7 +557,7 @@ export async function runDelegate({
528
557
  "the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
529
558
  + " result carries the last message before that tool call — it may be a preamble rather than the answer."
530
559
  );
531
- } else if (!finalMessageAvailable) {
560
+ } else if (!finalMessageAvailable && !res?.cancelledBeforePrompt) {
532
561
  protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
533
562
  }
534
563
  let stopReason;
@@ -536,34 +565,29 @@ export async function runDelegate({
536
565
  if (typeof res.stopReason !== "string") {
537
566
  protocolWarnings.push("stopReason dropped: ACP requires a string stop reason");
538
567
  } else if (res.stopReason !== "end_turn") {
539
- // end_turn carries no signal. Surface a stop reason only when something happened: a
540
- // refusal, a cancel, an output cap.
568
+ // end_turn is the normal case; only other stop reasons are surfaced.
541
569
  stopReason = res.stopReason;
542
570
  }
543
571
  }
544
- const out = {
572
+ out = {
545
573
  result,
546
574
  sessionId,
547
575
  };
548
- // Absence means "nothing reported", not "nothing changed" — a claim this field cannot make,
549
- // since shell-driven edits leave no diff event.
576
+ // Absent means nothing reported, not nothing changed: shell edits emit no diff.
550
577
  const filesReported = normalizeAgentReportedFiles([...state.touched], workspace);
551
578
  if (filesReported.length) out.filesReportedByEditTools = filesReported;
552
- // resultSource is a caveat, not a fact: on the happy path result is just the answer. Emit it
553
- // 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.
554
580
  if (resultSource !== "post-tool" && resultSource !== "tool-free-stream") out.resultSource = resultSource;
555
581
  if (!!resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
556
- // Present when the session ran a different model than asked, and always when model was
557
- // 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.
558
583
  if (servedModel !== undefined && servedModel !== model) out.effectiveModel = servedModel;
559
584
  if (effectiveEffort !== undefined) out.effectiveEffort = effectiveEffort;
560
585
  if (stopReason !== undefined) out.stopReason = stopReason;
561
586
  const usage = readUsage((res?.replies ?? [res]).map((r) => r?.usage));
562
587
  if (usage) out.usage = usage;
563
588
  if (state.contextUsage) out.context = state.contextUsage;
564
- // In plan mode agy's message points at the plan rather than containing it, so the plan
565
- // artifact's content is the plan. Any other artifact is listed by path and summary; its
566
- // content stays in the file.
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.
567
591
  const artifacts = [...state.artifacts.values()];
568
592
  const planArtifact = mode === "plan" ? artifacts.at(-1) : undefined;
569
593
  if (planArtifact) {
@@ -584,20 +608,24 @@ export async function runDelegate({
584
608
  if (protocolWarnings.length) out.protocolWarnings = protocolWarnings;
585
609
  return out;
586
610
  } catch (err) {
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
+ }
587
618
  failed = err;
588
- // A JSON-RPC code means the agent rejected something rather than the bridge breaking — the
589
- // distinction a caller needs to tell "fix your arguments" from "retry".
590
- // -32000 is ACP's auth_required. agy sends it from session/new when no sign-in is stored.
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.
591
621
  if (!err?.reason && err?.code === -32000) {
592
622
  err.reason = "not-signed-in";
593
623
  err.message += ". agy is not signed in: run agy once in a terminal and sign in, then retry.";
594
624
  }
595
625
  if (!err?.reason && typeof err?.code === "number") err.reason = "agent-error";
596
- // A bare duration cannot distinguish a wedged agent from a slow command, so name what was
597
- // 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.
598
627
  const isTimeout = err?.reason === "hard-cap" || err?.reason === "idle-timeout";
599
- // A handshake timeout gets the forensics but not the long-command advice: no prompt was sent,
600
- // so no shell command explains the silence.
628
+ // A handshake timeout gets the forensics but not the long-command advice: no prompt was sent.
601
629
  const isStall = isTimeout || err?.reason === "handshake-timeout";
602
630
  if (isStall || err?.reason === "aborted" || err?.reason === "agent-exit") {
603
631
  const age = fmtDuration(supervisor.msSinceActivity());
@@ -606,24 +634,20 @@ export async function runDelegate({
606
634
  const files = normalizeAgentReportedFiles([...state.touched], workspace);
607
635
  if (files.length) err.message += ` Files reported edited: ${files.join(", ")}.`;
608
636
  }
609
- // Every failure after the session opens leaves a live session, not just the stalls: the id is
610
- // 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.
611
638
  if (resumeError) {
612
- // Without this the resume hint reads as "carry on from where you were", when the requested
613
- // session was never resumed.
639
+ // Otherwise the resume hint reads as continuing work that was never in context.
614
640
  err.message += ` Note: resuming ${resumeSessionId} had already failed (${resumeError}),`
615
641
  + ` so this ran as a fresh session and none of that earlier work was in context.`;
616
642
  }
617
643
  if (sessionId) err.message += ` Resume with resumeSessionId ${sessionId}.`;
618
644
  if (isTimeout) {
619
- // Name the knob that actually fired: raising the hard cap does nothing for an
620
- // idle-timeout, whose ceiling is AGY_DELEGATE_IDLE_MS.
645
+ // Name the knob that fired: the hard cap does not govern an idle-timeout.
621
646
  const knob = err.reason === "idle-timeout" ? "AGY_DELEGATE_IDLE_MS" : "AGY_DELEGATE_HARD_CAP_MS";
622
647
  err.message += " agy does not stream shell output over ACP, so a long-running command emits"
623
648
  + ` nothing until it exits. Split the command, run it in the background and poll, or raise ${knob}.`;
624
649
  }
625
- // Opt-in: the frames land in the caller's context and nothing there is actionable — the
626
- // 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.
627
651
  const frames = transcriptFrames();
628
652
  if (frames > 0) {
629
653
  try {
@@ -633,16 +657,34 @@ export async function runDelegate({
633
657
  }
634
658
  throw err;
635
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 {}
636
663
  clearInterval(heartbeat);
637
664
  signal?.removeEventListener("abort", onAbort);
665
+ client.off?.("cancel", onCancel);
638
666
  try { supervisor.finish(); } catch {}
639
- // Awaited, so agy is gone when the caller gets the result: returned during agy's ~400 ms close,
640
- // a delegation left a process with the workspace as its cwd, and deleting the workspace right
641
- // after failed with EBUSY on Windows. The handle stays registered until then, so a force
642
- // cancel or a shutdown in that window still reaches the agent and cuts the grace short.
643
- // Graceful when the turn ran its course: agy closes the session and its conversation database.
644
- // A stall, an abort or an exit gets the kill at once — a wedged agent would only burn the grace.
645
- const killNow = ["handshake-timeout", "hard-cap", "idle-timeout", "aborted", "agent-exit"].includes(failed?.reason);
646
- try { await client.stop({ graceMs: killNow ? 0 : GRACEFUL_STOP_MS }); } 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
+ }
647
689
  }
648
690
  }