agy-delegate-mcp 1.4.0 → 1.6.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,21 +371,19 @@ 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();
386
+ if (up.toolCallId != null) state.toolLabels.set(up.toolCallId, state.lastToolLabel);
388
387
  try { onProgress?.(("running: " + state.lastToolLabel).slice(0, 200)); } catch {}
389
388
  } else {
390
389
  state.updateToolStatus(up.toolCallId, up.status);
@@ -399,23 +398,28 @@ export async function runDelegate({
399
398
  }
400
399
  });
401
400
 
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.
401
+ // agy backgrounds a shell command that outlasts WaitMsBeforeAsync and ends the turn; kept alive, it
402
+ // finishes the command and continues the turn unprompted, closing with a usage_update (measured,
403
+ // agy 1.5.14). Stopping agy at end_turn would kill the command. The hard cap still bounds the wait.
406
404
  let backgroundWaited;
405
+ // Set only when the wait ran its full length, which is what the warning blames.
406
+ let backgroundWaitRanOut = false;
407
+ // One clock per delegation, kept across steered turns.
408
+ let backgroundStartedAt;
407
409
  const waitForBackground = async () => {
408
- try { onProgress?.(`waiting for agy's background command: ${state.lastToolLabel ?? "tool"}`.slice(0, 200)); } catch {}
409
- const startedAt = Date.now();
410
+ const label = state.toolLabels.get(state.backgroundToolCalls()[0]) ?? state.lastToolLabel ?? "tool";
411
+ try { onProgress?.(`waiting for agy's background command: ${label}`.slice(0, 200)); } catch {}
412
+ const startedAt = (backgroundStartedAt ??= Date.now());
410
413
  for (;;) {
411
414
  await new Promise((r) => setTimeout(r, Math.min(250, backgroundSettleMs)));
412
415
  backgroundWaited = Date.now() - startedAt;
413
- if (backgroundWaited >= backgroundWaitMs) return;
414
416
  // The delegation already failed (agent exit, abort, hard cap): nobody reads this wait.
415
417
  if (supervisor.settled) return;
418
+ // Ahead of the deadline, so a cancel or steer in the last tick is not lost to it.
416
419
  if (client.cancelRequested) return "cancelled";
417
420
  // A steer redirects the turn; its own prompt reply is what ends it now.
418
421
  if (client.hasSteer?.()) return;
422
+ if (backgroundWaited >= backgroundWaitMs) { backgroundWaitRanOut = true; return; }
419
423
  if (state.backgroundToolCalls().length) continue;
420
424
  const quietMs = Date.now() - state.lastFrameAt;
421
425
  if (state.usageAfterActivity && quietMs >= backgroundSettleMs) return;
@@ -427,8 +431,11 @@ export async function runDelegate({
427
431
  let sessionId;
428
432
  let resumeError;
429
433
  let failed;
434
+ /** @type {any} */
435
+ let out;
430
436
  let servedModel;
431
437
  let effectiveEffort;
438
+ let noSettingsRecord = false;
432
439
  const contextWarnings = [];
433
440
  try {
434
441
  const res = await supervisor.supervise(async () => {
@@ -439,62 +446,95 @@ export async function runDelegate({
439
446
  resumeError = sess.resumeError;
440
447
  supervisor.setSessionId(sessionId);
441
448
  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.
449
+ // The options in force, replaced by each config reply. A resumed session opens at agy's
450
+ // defaults (agy #1460), so model, effort and mode are compared and re-sent every time.
446
451
  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));
452
+ if (client.cancelRequested) return cancelledInSetup;
453
+ // Only a resume that took inherits: a fallback to a fresh session is a different session.
454
+ const earlier = resumeSessionId && sessionId === resumeSessionId ? sessionSettings.get(sessionId) : undefined;
455
+ // The record lives in memory: a server restarted since the session ran has none to apply.
456
+ noSettingsRecord = !!resumeSessionId && sessionId === resumeSessionId && !earlier && model === undefined;
457
+ const targetModel = model ?? earlier?.model;
458
+ // A remembered effort holds only on the model it was set for: another model may not offer it.
459
+ const targetEffort = effort ?? (targetModel === earlier?.model ? earlier?.effort : undefined);
460
+ if (targetModel !== undefined) {
461
+ assertKnownModel(options, targetModel);
462
+ if (configOptionValue(options, "model") !== targetModel) {
463
+ options = optionsFrom(await client.setConfigOption(sessionId, "model", targetModel));
451
464
  }
452
465
  }
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));
466
+ if (client.cancelRequested) return cancelledInSetup;
467
+ // Kept across the effort reply, which may carry only the option it changed.
468
+ const modelBeforeEffort = configOptionValue(options, "model");
469
+ if (targetEffort !== undefined) {
470
+ const target = targetModel ?? modelBeforeEffort ?? "the session's model";
471
+ options = optionsFrom(await applyEffort(client, sessionId, target, targetEffort, options));
456
472
  }
457
- 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.
473
+ if (client.cancelRequested) return cancelledInSetup;
474
+ servedModel = configOptionValue(options, "model") ?? modelBeforeEffort;
475
+ // Saved once agy accepted them, with the model agy reports, so an effort set on agy's default
476
+ // is tied to that model. A session run on agy's defaults is recorded too, as having none, so
477
+ // its resume here does not read as a restart.
478
+ rememberSettings(sessionId, targetModel !== undefined || targetEffort !== undefined
479
+ ? { model: targetModel ?? servedModel, effort: targetEffort }
480
+ : {});
481
+ // What agy reported in force, never the requested value.
460
482
  effectiveEffort = effortSettings(options);
461
483
  await client.setMode(sessionId, agyMode);
484
+ if (client.cancelRequested) return cancelledInSetup;
462
485
  state.reset();
463
486
  supervisor.promptStarted();
464
487
  startHeartbeat();
465
- promptInFlight = true;
466
488
  try {
467
489
  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.
490
+ // A cancel that lands while attachments are read: the prompt is not sent.
491
+ if (client.cancelRequested) return cancelledInSetup;
492
+ // Raised with the prompt, so frames sent while attachments were read are not folded in.
493
+ promptInFlight = true;
494
+ promptSent = true;
495
+ const first = stampSettlement(client.prompt(sessionId, [{ type: "text", text: promptText }, ...blocks]));
496
+ // Opened once the prompt is on the wire (request writes synchronously): a steer sent first
497
+ // makes agy read the brief as a redirect of it.
471
498
  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.
499
+ const settled = await first;
500
+ let turn = settled.ok ? settled.value : undefined;
501
+ let turnError = "error" in settled ? settled.error : undefined;
502
+ let turnSeq = settled.seq;
503
+ const replies = settled.ok ? [turn] : [];
504
+ // A steer settles the prompt before it at once with end_turn, so the turn ends with the
505
+ // newest steer's reply. Each pass re-checks for a background command.
477
506
  for (;;) {
478
- if (!client.hasSteer?.() && state.backgroundToolCalls().length && await waitForBackground() === "cancelled") {
507
+ // Only end_turn leaves a backgrounded command (measured); a refusal or output cap is not
508
+ // waited on.
509
+ if (turn?.stopReason === "end_turn" && !client.hasSteer?.() && state.backgroundToolCalls().length
510
+ && await waitForBackground() === "cancelled") {
479
511
  return { ...turn, stopReason: "cancelled", replies };
480
512
  }
481
513
  const steer = client.takeSteer?.();
482
514
  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;
515
+ const reply = await steer;
516
+ if (reply.ok) {
517
+ turn = reply.value;
518
+ turnError = undefined;
519
+ turnSeq = reply.seq;
487
520
  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)}`);
521
+ } else if (reply.seq < turnSeq) {
522
+ // Refused before its target settled: that turn stands, and the warning tells the caller.
523
+ steerWarnings.push(`a steer was rejected by agy and did not redirect the turn: ${reply.error?.message || String(reply.error)}`);
524
+ } else {
525
+ // Failed after taking the turn over: the turn failed, unless a steer queued behind it
526
+ // succeeds.
527
+ turn = undefined;
528
+ turnError = reply.error;
529
+ turnSeq = reply.seq;
490
530
  }
491
531
  }
532
+ if (turnError) throw turnError;
492
533
  return { ...turn, replies };
493
534
  } finally {
494
535
  // Closed in the same tick as the last check above, so no steer lands unread.
495
536
  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.
537
+ // Cleared before the awaits below, so a frame trailing the settled turn is not folded in.
498
538
  promptInFlight = false;
499
539
  }
500
540
  });
@@ -507,17 +547,22 @@ export async function runDelegate({
507
547
  : "none";
508
548
  const protocolWarnings = [];
509
549
  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.
550
+ // Measured cases (agy 1.5.14): a background command still running when the wait ran out, or an
551
+ // ask_question waiting on the caller.
513
552
  result = state.unfinishedToolText;
514
553
  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.";
554
+ // The open command if there is one, else the question; not the newest tool.
555
+ const openId = state.backgroundToolCalls()[0] ?? [...state.activeToolCalls][0];
556
+ const openLabel = state.toolLabels.get(openId) ?? state.lastToolLabel;
557
+ // A refusal or output cap is not waited on, so a command can be open with no wait.
558
+ const cause = !state.backgroundToolCalls().length
559
+ ? " agy is asking a question (ask_question), which a resume answers."
560
+ : backgroundWaitRanOut
561
+ ? ` agy moved it to the background, and it was still running after the bridge waited ${fmtDuration(backgroundWaited)}`
562
+ + " (AGY_DELEGATE_BACKGROUND_WAIT_MS); it stops when the bridge stops agy."
563
+ : ` agy ended the turn (${res?.stopReason}) with it still running; it stops when the bridge stops agy.`;
519
564
  protocolWarnings.push(
520
- `the turn ended with a tool call still running (${state.lastToolLabel ?? "unnamed tool"}).`
565
+ `the turn ended with a tool call still running (${openLabel ?? "unnamed tool"}).`
521
566
  + cause
522
567
  + (result ? " result is agy's message from while it ran." : " agy sent no message while it ran.")
523
568
  );
@@ -528,7 +573,7 @@ export async function runDelegate({
528
573
  "the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
529
574
  + " result carries the last message before that tool call — it may be a preamble rather than the answer."
530
575
  );
531
- } else if (!finalMessageAvailable) {
576
+ } else if (!finalMessageAvailable && !res?.cancelledBeforePrompt) {
532
577
  protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
533
578
  }
534
579
  let stopReason;
@@ -536,34 +581,30 @@ export async function runDelegate({
536
581
  if (typeof res.stopReason !== "string") {
537
582
  protocolWarnings.push("stopReason dropped: ACP requires a string stop reason");
538
583
  } 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.
584
+ // end_turn is the normal case; only other stop reasons are surfaced.
541
585
  stopReason = res.stopReason;
542
586
  }
543
587
  }
544
- const out = {
588
+ out = {
545
589
  result,
546
590
  sessionId,
547
591
  };
548
- // Absence means "nothing reported", not "nothing changed" — a claim this field cannot make,
549
- // since shell-driven edits leave no diff event.
592
+ // Absent means nothing reported, not nothing changed: shell edits emit no diff.
550
593
  const filesReported = normalizeAgentReportedFiles([...state.touched], workspace);
551
594
  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.
595
+ // resultSource appears only as a caveat; resumed only when a resume took.
554
596
  if (resultSource !== "post-tool" && resultSource !== "tool-free-stream") out.resultSource = resultSource;
555
597
  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.
598
+ // Present when the served model differs from the requested one, so whenever model was omitted
599
+ // and agy reports one.
558
600
  if (servedModel !== undefined && servedModel !== model) out.effectiveModel = servedModel;
559
601
  if (effectiveEffort !== undefined) out.effectiveEffort = effectiveEffort;
560
602
  if (stopReason !== undefined) out.stopReason = stopReason;
561
603
  const usage = readUsage((res?.replies ?? [res]).map((r) => r?.usage));
562
604
  if (usage) out.usage = usage;
563
605
  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.
606
+ // In plan mode agy's message points at the plan; the artifact's content is the plan. Other
607
+ // artifacts are listed by path and summary.
567
608
  const artifacts = [...state.artifacts.values()];
568
609
  const planArtifact = mode === "plan" ? artifacts.at(-1) : undefined;
569
610
  if (planArtifact) {
@@ -578,26 +619,33 @@ export async function runDelegate({
578
619
  .map((a) => ({ path: a.path, ...(a.summary !== undefined ? { summary: a.summary } : {}) }));
579
620
  if (others.length) out.artifacts = others;
580
621
  if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
622
+ if (noSettingsRecord) {
623
+ protocolWarnings.push(`agy reopened the session at its default model${servedModel ? ` (${servedModel})` : ""}: this server has no record of the model set earlier, as it keeps none across restarts. Pass model to choose one.`);
624
+ }
581
625
  protocolWarnings.push(...contextWarnings);
582
626
  protocolWarnings.push(...frameWarnings);
583
627
  protocolWarnings.push(...steerWarnings);
584
628
  if (protocolWarnings.length) out.protocolWarnings = protocolWarnings;
585
629
  return out;
586
630
  } catch (err) {
631
+ // A caller's cancel before the prompt is a cancelled result, even if a config call then failed.
632
+ if (cancelledInSetupByCaller && sessionId) {
633
+ out = { result: "", sessionId, resultSource: "none", stopReason: "cancelled" };
634
+ if (resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
635
+ if (resumeError) out.protocolWarnings = [`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`];
636
+ return out;
637
+ }
587
638
  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.
639
+ // A JSON-RPC code means agy rejected something (fix the arguments), not that the bridge broke
640
+ // (retry). -32000 is ACP's auth_required, sent by agy from session/new when signed out.
591
641
  if (!err?.reason && err?.code === -32000) {
592
642
  err.reason = "not-signed-in";
593
643
  err.message += ". agy is not signed in: run agy once in a terminal and sign in, then retry.";
594
644
  }
595
645
  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.
646
+ // A bare duration cannot tell a wedged agent from a slow command, so name what was outstanding.
598
647
  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.
648
+ // A handshake timeout gets the forensics but not the long-command advice: no prompt was sent.
601
649
  const isStall = isTimeout || err?.reason === "handshake-timeout";
602
650
  if (isStall || err?.reason === "aborted" || err?.reason === "agent-exit") {
603
651
  const age = fmtDuration(supervisor.msSinceActivity());
@@ -606,24 +654,20 @@ export async function runDelegate({
606
654
  const files = normalizeAgentReportedFiles([...state.touched], workspace);
607
655
  if (files.length) err.message += ` Files reported edited: ${files.join(", ")}.`;
608
656
  }
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.
657
+ // Any failure after the session opens leaves a live session, unknown-model and effort included.
611
658
  if (resumeError) {
612
- // Without this the resume hint reads as "carry on from where you were", when the requested
613
- // session was never resumed.
659
+ // Otherwise the resume hint reads as continuing work that was never in context.
614
660
  err.message += ` Note: resuming ${resumeSessionId} had already failed (${resumeError}),`
615
661
  + ` so this ran as a fresh session and none of that earlier work was in context.`;
616
662
  }
617
663
  if (sessionId) err.message += ` Resume with resumeSessionId ${sessionId}.`;
618
664
  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.
665
+ // Name the knob that fired: the hard cap does not govern an idle-timeout.
621
666
  const knob = err.reason === "idle-timeout" ? "AGY_DELEGATE_IDLE_MS" : "AGY_DELEGATE_HARD_CAP_MS";
622
667
  err.message += " agy does not stream shell output over ACP, so a long-running command emits"
623
668
  + ` nothing until it exits. Split the command, run it in the background and poll, or raise ${knob}.`;
624
669
  }
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.
670
+ // Opt-in: raw frames help only when debugging the bridge, and cost the caller context.
627
671
  const frames = transcriptFrames();
628
672
  if (frames > 0) {
629
673
  try {
@@ -633,16 +677,35 @@ export async function runDelegate({
633
677
  }
634
678
  throw err;
635
679
  } finally {
680
+ // The turn is decided; what follows is teardown. The server stops treating a cancel as aimed
681
+ // at a running turn.
682
+ try { onTurnEnd?.(); } catch {}
636
683
  clearInterval(heartbeat);
637
684
  signal?.removeEventListener("abort", onAbort);
685
+ client.off?.("cancel", onCancel);
638
686
  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 {}
687
+ // Awaited, so agy has exited when the caller gets the result, or a warning says the exit was not
688
+ // seen; otherwise agy still holds the workspace as its cwd (deleting it fails with EBUSY on
689
+ // Windows). The handle stays registered meanwhile, so force cancel and shutdown can cut the grace
690
+ // short. Graceful after a completed turn, so agy closes its conversation database; a stall,
691
+ // abort or exit is killed at once.
692
+ const killNow = signal?.aborted || ["handshake-timeout", "hard-cap", "idle-timeout", "aborted", "agent-exit"].includes(failed?.reason);
693
+ // A host abort during the close is still an abort: a force stop ends the grace and kills.
694
+ const abortClose = () => { Promise.resolve(client.stop()).catch(() => {}); };
695
+ signal?.addEventListener("abort", abortClose, { once: true });
696
+ let exited = false;
697
+ try {
698
+ exited = await client.stop({ graceMs: killNow ? 0 : GRACEFUL_STOP_MS });
699
+ // A stop that did not see the exit is not memoized, so a second one dispatches a fresh kill.
700
+ if (exited === false) exited = await client.stop();
701
+ } catch {}
702
+ finally { signal?.removeEventListener("abort", abortClose); }
703
+ if (exited === false) {
704
+ const pid = client.child?.pid;
705
+ const note = `the bridge stopped agy${pid ? ` (pid ${pid})` : ""} but did not see agy exit; it may still be running.`;
706
+ // The result or the error is already decided; the note rides on whichever is going out.
707
+ if (failed) failed.message += ` Note: ${note}`;
708
+ else if (out) (out.protocolWarnings ??= []).push(note);
709
+ }
647
710
  }
648
711
  }