agy-delegate-mcp 0.0.0 → 1.0.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.
@@ -0,0 +1,533 @@
1
+ import process from "node:process";
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
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.
8
+ import { readFile } from "node:fs/promises";
9
+ import { AcpClient } from "./acp-client.js";
10
+ import { DEFAULT_HARD_CAP_MS, SessionSupervisor } from "./session-supervisor.js";
11
+ import { normalizeAgentReportedFiles } from "./agent-reported-files.js";
12
+ import { makeTurnState } from "./turn-state.js";
13
+ import { makeError } from "./errors.js";
14
+ import { effortSettings, optionsFrom, resolveEffort, allowedValues } from "./model-options.js";
15
+ import { transcriptFrames } from "./jsonrpc.js";
16
+
17
+ export const DEFAULT_HANDSHAKE_MS = 60000;
18
+
19
+ // The bridge's modes onto agy's. agy has no ask mode: ask runs in default with ASK_PREAMBLE
20
+ // ahead of the spec. default asks before edits and commands, which the launch flag and the
21
+ // request router both approve.
22
+ const AGY_MODE = { agent: "default", plan: "plan", ask: "default" };
23
+ const ASK_PREAMBLE = "Answer the question below. Do not edit files or run commands that change state.";
24
+ export const DEFAULT_HEARTBEAT_MS = 30000;
25
+
26
+ // Malformed values fall back to the default rather than failing the call. Only a positive value
27
+ // counts, so a blank var (Number("") is 0) cannot arm a zero-length deadline. The idle guard's
28
+ // documented 0 comes from its own fallback being 0, not from an env value.
29
+ function envMs(name, fallback) {
30
+ const raw = process.env[name];
31
+ if (raw === undefined) return fallback;
32
+ const n = Number(raw);
33
+ return Number.isFinite(n) && n > 0 ? n : fallback;
34
+ }
35
+
36
+ function fmtDuration(ms) {
37
+ const s = Math.round(ms / 1000);
38
+ return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
39
+ }
40
+
41
+ // A blank spec spins up a live session that only replies "No prompt content provided" —
42
+ // a billed turn for nothing. Reject it before the spawn, like a bad workspace.
43
+ function assertSpec(spec) {
44
+ if (typeof spec === "string" && spec.trim() === "") {
45
+ throw makeError("invalid-spec", "spec is empty. Provide a task brief.");
46
+ }
47
+ }
48
+
49
+ // Named, never defaulted: under npx or a plugin launch the server's own cwd is a cache directory
50
+ // or the user's home, so a defaulted workspace put an auto-approved agent to work on a tree
51
+ // nobody asked about while every layer reported success. And without the existence check the
52
+ // agent's first write creates the directory, so a typo spawns a parallel empty tree. Same check
53
+ // contextFiles applies.
54
+ function assertWorkspace(workspace) {
55
+ if (typeof workspace !== "string" || workspace.trim() === "") {
56
+ throw makeError("invalid-workspace", "workspace is required. Name the directory the agent should work in.");
57
+ }
58
+ let stat;
59
+ try {
60
+ stat = statSync(workspace);
61
+ } catch {
62
+ throw makeError("invalid-workspace", `workspace ${workspace} does not exist. Create it first, or point at an existing directory.`);
63
+ }
64
+ if (!stat.isDirectory()) {
65
+ throw makeError("invalid-workspace", `workspace ${workspace} is not a directory.`);
66
+ }
67
+ }
68
+
69
+ const IMAGE_MIME = {
70
+ ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
71
+ ".gif": "image/gif", ".webp": "image/webp",
72
+ };
73
+ // Base64 inflates by a third and every byte lands in the prompt, unlike a link.
74
+ const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
75
+
76
+ // A resource_link hands the agent a path, not the file's bytes, so a large brief costs prompt
77
+ // space only for what the agent opens. Images have no such form — they go inline. Both are
78
+ // measured working on agy 1.5.13, including a link outside the workspace and both together.
79
+ // - gate images on the advertised capability: an agent that takes an unsupported block
80
+ // without error would drop the image silently;
81
+ // - report anything skipped — a dropped attachment is otherwise invisible.
82
+ async function buildContextBlocks(contextFiles, workspace, client, warnings) {
83
+ const blocks = [];
84
+ // A glob plus an explicit path can resolve to one file; sending it twice wastes prompt space.
85
+ const seen = new Set();
86
+ // Grouped, not one warning per file: a wrong workspace misses every attachment at once, and a
87
+ // line each would repeat the same root N times for one root cause. The other skip reasons stay
88
+ // per-entry — they are individually distinct and never arrive in bulk.
89
+ const notFound = [];
90
+ const root = path.resolve(workspace || process.cwd());
91
+ const identKey = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
92
+ for (const entry of contextFiles || []) {
93
+ if (typeof entry !== "string" || !entry.trim()) continue;
94
+ const abs = path.resolve(workspace || process.cwd(), entry);
95
+ let canonical;
96
+ try {
97
+ canonical = realpathSync(abs);
98
+ } catch {
99
+ const missKey = identKey(abs);
100
+ if (seen.has(missKey)) continue;
101
+ seen.add(missKey);
102
+ notFound.push(entry);
103
+ continue;
104
+ }
105
+ const key = identKey(canonical);
106
+ if (seen.has(key)) continue;
107
+ seen.add(key);
108
+ let stat;
109
+ try {
110
+ stat = statSync(canonical);
111
+ } catch {
112
+ notFound.push(entry);
113
+ continue;
114
+ }
115
+ if (!stat.isFile()) {
116
+ warnings.push(`contextFile ${entry} skipped: not a file`);
117
+ continue;
118
+ }
119
+ const mimeType = IMAGE_MIME[path.extname(canonical).toLowerCase()];
120
+ if (mimeType) {
121
+ if (!client?.agentCapabilities?.promptCapabilities?.image) {
122
+ warnings.push(`contextFile ${entry} skipped: this agent does not accept image prompts`);
123
+ continue;
124
+ }
125
+ if (stat.size > MAX_IMAGE_BYTES) {
126
+ warnings.push(`contextFile ${entry} skipped: ${Math.round(stat.size / 1024)}KB exceeds the ${MAX_IMAGE_BYTES / 1024 / 1024}MB image limit`);
127
+ continue;
128
+ }
129
+ try {
130
+ blocks.push({ type: "image", mimeType, data: (await readFile(canonical)).toString("base64") });
131
+ } catch (err) {
132
+ warnings.push(`contextFile ${entry} skipped: could not read image (${err?.code || "read failed"})`);
133
+ }
134
+ continue;
135
+ }
136
+ blocks.push({ type: "resource_link", uri: pathToFileURL(canonical).href, name: path.basename(canonical) });
137
+ }
138
+ if (notFound.length) {
139
+ warnings.push(
140
+ `contextFile${notFound.length > 1 ? "s" : ""} skipped: ${notFound.length} not found under ${root}`
141
+ + ` — ${notFound.join(", ")}`
142
+ );
143
+ }
144
+ return blocks;
145
+ }
146
+
147
+ // agy answers session/resume for an unknown id with -32603 "Failed to read session <id>; retry,
148
+ // or load it with session/load", the same code and wording a failed read of a real session would
149
+ // carry. session/list settles it: agy lists every session the account has, so an id missing from
150
+ // it is one agy does not have. Only that justifies a fresh session; anything else runs the task
151
+ // without the context the caller asked for.
152
+ async function sessionExists(client, sessionId) {
153
+ try {
154
+ const listed = await client.listSessions();
155
+ if (!Array.isArray(listed?.sessions)) return undefined;
156
+ return listed.sessions.some((s) => s?.sessionId === sessionId);
157
+ } catch {
158
+ return undefined;
159
+ }
160
+ }
161
+
162
+ async function openSession(client, resumeSessionId, workspace) {
163
+ if (!resumeSessionId) return client.newSession(workspace);
164
+ try {
165
+ await client.resumeSession(resumeSessionId, workspace);
166
+ return { sessionId: resumeSessionId };
167
+ } catch (err) {
168
+ if ((await sessionExists(client, resumeSessionId)) !== false) {
169
+ throw makeError(
170
+ "resume-failed",
171
+ `session ${resumeSessionId} could not be resumed: ${err?.message || String(err)}.`
172
+ + ` The session was not resumed and no fresh session was started — retry, or omit`
173
+ + ` resumeSessionId to start fresh deliberately.`
174
+ );
175
+ }
176
+ // Starting fresh is right, but silently doing so leaves the caller unable to tell a
177
+ // stale id from a typo'd one — keep why the resume failed.
178
+ const fresh = await client.newSession(workspace);
179
+ return { ...fresh, resumeError: `agy has no session ${resumeSessionId}` };
180
+ }
181
+ }
182
+
183
+ function modelOption(configOptions) {
184
+ return (Array.isArray(configOptions) ? configOptions : []).find((o) => o?.id === "model");
185
+ }
186
+
187
+ function configOptionValue(configOptions, id) {
188
+ const opt = (Array.isArray(configOptions) ? configOptions : []).find((o) => o?.id === id);
189
+ return typeof opt?.currentValue === "string" ? opt.currentValue : undefined;
190
+ }
191
+
192
+ // The model ids a session accepts are the values of its model config option: base ids such as
193
+ // gemini-4-neon, with the thinking level set separately. Reject anything else here, where the
194
+ // list can be named — agy's own -32602 "Unknown model ID" names none. An agent that reports no
195
+ // list is left alone.
196
+ function assertKnownModel(configOptions, model) {
197
+ const ids = allowedValues(modelOption(configOptions));
198
+ if (ids.length === 0 || ids.includes(model)) return;
199
+ throw makeError(
200
+ "unknown-model",
201
+ `Unknown model ${JSON.stringify(model)}. agy offers: ${ids.join(", ")}. Set the thinking level with effort, not a model id suffix.`
202
+ );
203
+ }
204
+
205
+ // Sent only when the exact value appears under a thought-level option the selected model
206
+ // advertised. Local validation keeps a bad token out of ACP and, more importantly, out of a
207
+ // billed prompt. Missing capability data is not mislabeled as a caller mistake.
208
+ async function applyEffort(client, sessionId, model, value, modelOptions) {
209
+ const resolved = resolveEffort(modelOptions, value);
210
+ if (resolved.status === "unavailable") {
211
+ throw makeError(
212
+ "effort-options-unavailable",
213
+ `Cannot validate effort ${JSON.stringify(value)} for ${JSON.stringify(model)}:`
214
+ + " the selected model did not report a usable effort option list."
215
+ );
216
+ }
217
+ if (resolved.status === "unrecognized") {
218
+ throw makeError(
219
+ "invalid-effort",
220
+ `Model ${JSON.stringify(model)} advertised no option the bridge recognizes as effort.`
221
+ + ` Advertised: ${JSON.stringify(resolved.advertised)}.`
222
+ + " If one of these is an effort setting, the bridge failed to recognize it — report that rather than retrying."
223
+ );
224
+ }
225
+ if (resolved.status === "invalid") {
226
+ throw makeError(
227
+ "invalid-effort",
228
+ `Invalid effort ${JSON.stringify(value)} for ${JSON.stringify(model)}.`
229
+ + ` Accepted: ${JSON.stringify(resolved.accepted)}.`
230
+ );
231
+ }
232
+ return client.setConfigOption(sessionId, resolved.id, resolved.value);
233
+ }
234
+
235
+ /**
236
+ * @param {{
237
+ * spec?: string, mode?: string, resumeSessionId?: string, workspace?: string,
238
+ * model?: string, effort?: string,
239
+ * contextFiles?: string[], clientFactory?: (opts: any) => any,
240
+ * idleMs?: number, handshakeMs?: number, hardCapMs?: number, timeoutMs?: number,
241
+ * onClientReady?: (client: any) => void,
242
+ * onSessionReady?: (sessionId: string, client: any) => void,
243
+ * onProgress?: (message: string) => void,
244
+ * progressThrottleMs?: number, heartbeatMs?: number, signal?: AbortSignal,
245
+ * }} [opts]
246
+ */
247
+ export async function runDelegate({
248
+ spec, mode = "agent", resumeSessionId, workspace,
249
+ model, effort, contextFiles, clientFactory,
250
+ idleMs, handshakeMs, hardCapMs, timeoutMs,
251
+ onClientReady, onSessionReady, onProgress, progressThrottleMs = 2000,
252
+ heartbeatMs = DEFAULT_HEARTBEAT_MS,
253
+ signal,
254
+ } = {}) {
255
+ // Nothing between here and the abort listener below may await: addEventListener does not
256
+ // replay an abort that already fired, so an abort landing in that window would be lost.
257
+ // Throwing, not supervisor.abort(): tripping before supervise() installs its reject settles the
258
+ // supervisor with nothing listening.
259
+ if (signal?.aborted) {
260
+ throw makeError("aborted", "delegation aborted by MCP host");
261
+ }
262
+ // Before the spawn: validating later costs a process, a handshake and a billed turn.
263
+ assertWorkspace(workspace);
264
+ assertSpec(spec);
265
+ const agyMode = AGY_MODE[mode];
266
+ if (!agyMode) throw makeError("invalid-mode", `mode must be agent, plan or ask; got ${JSON.stringify(mode)}.`);
267
+ const promptText = mode === "ask" ? `${ASK_PREAMBLE}\n\n${spec}` : spec;
268
+ const capMs = hardCapMs ?? timeoutMs ?? envMs("AGY_DELEGATE_HARD_CAP_MS", DEFAULT_HARD_CAP_MS);
269
+ const shakeMs = handshakeMs ?? envMs("AGY_DELEGATE_HANDSHAKE_MS", DEFAULT_HANDSHAKE_MS);
270
+ const turnIdleMs = idleMs ?? envMs("AGY_DELEGATE_IDLE_MS", 0);
271
+ const state = makeTurnState({ onProgress, progressThrottleMs });
272
+
273
+ const make = clientFactory || ((opts) => new AcpClient(opts));
274
+ const client = make({});
275
+ // Handed over before the spawn, because from client.start() there is an agent process and the
276
+ // caller needs something that can stop it.
277
+ onClientReady?.(client);
278
+ const supervisor = new SessionSupervisor(client, { idleMs: turnIdleMs, handshakeMs: shakeMs, hardCapMs: capMs });
279
+ const onAbort = () => supervisor.abort();
280
+ signal?.addEventListener("abort", onAbort, { once: true });
281
+
282
+ // The bridge cannot see inside a running shell command, so a long silence is reported
283
+ // rather than acted on: the caller gets elapsed time and frame age and can decide.
284
+ let promptInFlight = false;
285
+ let heartbeat = null;
286
+ const startHeartbeat = () => {
287
+ if (!(heartbeatMs > 0)) return;
288
+ const startedAt = Date.now();
289
+ heartbeat = setInterval(() => {
290
+ const parts = [
291
+ `still working — ${fmtDuration(Date.now() - startedAt)} elapsed`,
292
+ `last agent frame ${fmtDuration(supervisor.msSinceActivity())} ago`,
293
+ ];
294
+ if (state.lastToolLabel) parts.push(`running: ${state.lastToolLabel}`);
295
+ try { onProgress?.(parts.join(", ").slice(0, 200)); } catch {}
296
+ }, heartbeatMs);
297
+ heartbeat.unref?.();
298
+ };
299
+
300
+ // Malformed frames noticed as they arrive, where protocolWarnings does not exist yet. Merged
301
+ // into it with the rest below.
302
+ const frameWarnings = [];
303
+
304
+ // Diff blocks name the files an edit tool changed. agy sends them on the finished
305
+ // tool_call_update; tool_call is read too, since a frame that arrives already finished carries
306
+ // its content there.
307
+ const recordDiffs = (content) => {
308
+ // Array.isArray, not `|| []`: a non-array content is truthy and iterating it throws here, in
309
+ // the readline callback, where nothing awaits it. That is an uncaught exception — the whole
310
+ // server, not this one turn — and it also stops the reply after it from being read.
311
+ for (const c of Array.isArray(content) ? content : []) {
312
+ if (!c || typeof c !== "object" || Array.isArray(c) || typeof c.type !== "string"
313
+ || (c.type === "diff" && (typeof c.path !== "string" || !c.path))) {
314
+ const warning = "malformed tool content dropped: expected content blocks with string diff paths";
315
+ if (!frameWarnings.includes(warning)) frameWarnings.push(warning);
316
+ continue;
317
+ }
318
+ if (c.type === "diff") {
319
+ state.touched.add(c.path);
320
+ // Named as the result names it: agy's /C:/… spelling, resolved against the workspace.
321
+ try { onProgress?.("editing " + normalizeAgentReportedFiles([c.path], workspace)[0]); } catch {}
322
+ }
323
+ }
324
+ };
325
+
326
+ // Only frames inside the prompt are read, so nothing the session sends while it opens is
327
+ // folded into this turn.
328
+ client.on("update", (u) => {
329
+ if (!promptInFlight) return;
330
+ const up = u?.update || {};
331
+ // The agent titles the turn a beat after the prompt lands — useful live, when several
332
+ // delegations run, and in timeout forensics. Kept out of the result.
333
+ if (up.sessionUpdate === "session_info_update" && typeof up.title === "string" && up.title) {
334
+ if (up.title !== state.sessionTitle) { try { onProgress?.(`turn titled: ${up.title}`.slice(0, 200)); } catch {} }
335
+ state.sessionTitle = up.title;
336
+ }
337
+ if (up.sessionUpdate === "agent_thought_chunk" && up.content?.text) {
338
+ state.thoughts.push(up.content.text);
339
+ }
340
+ if (up.sessionUpdate === "tool_call" || up.sessionUpdate === "tool_call_update") {
341
+ // An artifact is agy's own file (the plan, under its brain directory), reported as an
342
+ // artifact rather than as a workspace edit.
343
+ const isArtifact = state.recordArtifact(up.rawInput ?? up.args);
344
+ if (up.sessionUpdate === "tool_call") {
345
+ state.startTool(up.toolCallId, up.status);
346
+ const label = String(up.title || up.kind || "tool");
347
+ const path = up.locations?.[0]?.path;
348
+ // Collapsed onto one line the way both readers of this take it: a progress notification
349
+ // and the "last tool call" line in a stall error. A command title arrives verbatim, so a
350
+ // multi-line script arrives with its newlines.
351
+ // agy's titles already name the file, with forward slashes where the location has
352
+ // backslashes, so the path is appended only when the title does not carry it.
353
+ const slashed = (s) => String(s).replace(/\\/g, "/");
354
+ const named = path && slashed(label).includes(slashed(path));
355
+ state.lastToolLabel = (label + (path && !named ? " — " + path : "")).replace(/\s+/g, " ").trim();
356
+ try { onProgress?.(("running: " + state.lastToolLabel).slice(0, 200)); } catch {}
357
+ } else {
358
+ state.updateToolStatus(up.toolCallId, up.status);
359
+ }
360
+ if (!isArtifact) recordDiffs(up.content);
361
+ }
362
+ if (up.sessionUpdate === "agent_message_chunk" && up.content?.text) {
363
+ const text = up.content.text;
364
+ if (state.collectingResult()) state.appendResult(text);
365
+ state.messages.push(text);
366
+ }
367
+ });
368
+
369
+ let sessionId;
370
+ let resumeError;
371
+ let servedModel;
372
+ let effectiveEffort;
373
+ const contextWarnings = [];
374
+ try {
375
+ const res = await supervisor.supervise(async () => {
376
+ await client.start();
377
+ await client.initialize();
378
+ const sess = await openSession(client, resumeSessionId, workspace);
379
+ sessionId = sess.sessionId;
380
+ resumeError = sess.resumeError;
381
+ supervisor.setSessionId(sessionId);
382
+ onSessionReady?.(sessionId, client);
383
+ // The options the session reports in force, replaced by each config reply. A resumed
384
+ // session opens at agy's defaults rather than its saved settings (agy issue #1460,
385
+ // reproduced on 1.5.13), so model, effort and mode are compared and re-sent every time
386
+ // rather than assumed to have carried over.
387
+ let options = client.configOptions;
388
+ if (model !== undefined) {
389
+ assertKnownModel(options, model);
390
+ if (configOptionValue(options, "model") !== model) {
391
+ options = optionsFrom(await client.setConfigOption(sessionId, "model", model));
392
+ }
393
+ }
394
+ if (effort !== undefined) {
395
+ const target = model ?? configOptionValue(options, "model") ?? "the session's model";
396
+ options = optionsFrom(await applyEffort(client, sessionId, target, effort, options));
397
+ }
398
+ servedModel = configOptionValue(options, "model");
399
+ // What the agent reported in force as the prompt goes out — never the requested value
400
+ // standing in for a reply that did not confirm it.
401
+ effectiveEffort = effortSettings(options);
402
+ await client.setMode(sessionId, agyMode);
403
+ state.reset();
404
+ supervisor.promptStarted();
405
+ startHeartbeat();
406
+ promptInFlight = true;
407
+ try {
408
+ const blocks = await buildContextBlocks(contextFiles, workspace, client, contextWarnings);
409
+ return await client.prompt(sessionId, [{ type: "text", text: promptText }, ...blocks]);
410
+ } finally {
411
+ // The result is assembled across awaits below, so without this a frame trailing the
412
+ // settled turn is still folded into it.
413
+ promptInFlight = false;
414
+ }
415
+ });
416
+ state.thoughts.end();
417
+ state.messages.end();
418
+ let result = state.text();
419
+ const finalMessageAvailable = result.length > 0;
420
+ let resultSource = finalMessageAvailable
421
+ ? (state.sawToolCall ? "post-tool" : "tool-free-stream")
422
+ : "none";
423
+ const protocolWarnings = [];
424
+ if (!finalMessageAvailable && state.discardedResult) {
425
+ result = state.discardedResult;
426
+ resultSource = "pre-tool-fallback";
427
+ protocolWarnings.push(
428
+ "the agent ran a tool after its last message and never spoke again, so no final message closed the turn."
429
+ + " result carries the last message before that tool call — it may be a preamble rather than the answer."
430
+ );
431
+ } else if (!finalMessageAvailable) {
432
+ protocolWarnings.push("the agent ended the turn without emitting any message; result is empty.");
433
+ }
434
+ let stopReason;
435
+ if (res?.stopReason !== undefined) {
436
+ if (typeof res.stopReason !== "string") {
437
+ protocolWarnings.push("stopReason dropped: ACP requires a string stop reason");
438
+ } else if (res.stopReason !== "end_turn") {
439
+ // end_turn carries no signal. Surface a stop reason only when something happened: a
440
+ // refusal, a cancel, an output cap.
441
+ stopReason = res.stopReason;
442
+ }
443
+ }
444
+ const out = {
445
+ result,
446
+ sessionId,
447
+ };
448
+ // Absence means "nothing reported", not "nothing changed" — a claim this field cannot make,
449
+ // since shell-driven edits leave no diff event.
450
+ const filesReported = normalizeAgentReportedFiles([...state.touched], workspace);
451
+ if (filesReported.length) out.filesReportedByEditTools = filesReported;
452
+ // resultSource is a caveat, not a fact: on the happy path result is just the answer. Emit it
453
+ // only when it warns. resumed likewise appears only when a resume took.
454
+ if (resultSource !== "post-tool" && resultSource !== "tool-free-stream") out.resultSource = resultSource;
455
+ if (!!resumeSessionId && sessionId === resumeSessionId) out.resumed = true;
456
+ // Present when the session ran a different model than asked, and always when model was
457
+ // omitted: then it is the only place the caller sees which model agy used.
458
+ if (servedModel !== undefined && servedModel !== model) out.effectiveModel = servedModel;
459
+ if (effectiveEffort !== undefined) out.effectiveEffort = effectiveEffort;
460
+ if (stopReason !== undefined) out.stopReason = stopReason;
461
+ // In plan mode agy's message points at the plan rather than containing it, so the plan
462
+ // artifact's content is the plan. Any other artifact is listed by path and summary; its
463
+ // content stays in the file.
464
+ const artifacts = [...state.artifacts.values()];
465
+ const planArtifact = mode === "plan" ? artifacts.at(-1) : undefined;
466
+ if (planArtifact) {
467
+ out.plan = {
468
+ path: planArtifact.path,
469
+ ...(planArtifact.summary !== undefined ? { overview: planArtifact.summary } : {}),
470
+ ...(planArtifact.content !== undefined ? { detail: planArtifact.content } : {}),
471
+ };
472
+ }
473
+ const others = artifacts
474
+ .filter((a) => a !== planArtifact)
475
+ .map((a) => ({ path: a.path, ...(a.summary !== undefined ? { summary: a.summary } : {}) }));
476
+ if (others.length) out.artifacts = others;
477
+ if (resumeError) protocolWarnings.push(`resuming ${resumeSessionId} failed, started a fresh session: ${resumeError}`);
478
+ protocolWarnings.push(...contextWarnings);
479
+ protocolWarnings.push(...frameWarnings);
480
+ if (protocolWarnings.length) out.protocolWarnings = protocolWarnings;
481
+ return out;
482
+ } catch (err) {
483
+ // A JSON-RPC code means the agent rejected something rather than the bridge breaking — the
484
+ // distinction a caller needs to tell "fix your arguments" from "retry".
485
+ if (!err?.reason && typeof err?.code === "number") err.reason = "agent-error";
486
+ // A bare duration cannot distinguish a wedged agent from a slow command, so name what was
487
+ // outstanding — it also lets a retry resume the work already done.
488
+ const isTimeout = err?.reason === "hard-cap" || err?.reason === "idle-timeout";
489
+ // A handshake timeout gets the forensics but not the long-command advice: no prompt was sent,
490
+ // so no shell command explains the silence.
491
+ const isStall = isTimeout || err?.reason === "handshake-timeout";
492
+ if (isStall || err?.reason === "aborted" || err?.reason === "agent-exit") {
493
+ const age = fmtDuration(supervisor.msSinceActivity());
494
+ err.message += `\n\nLast ACP frame ${age} ago${state.lastToolLabel ? `; last tool call: ${state.lastToolLabel}` : ""}.`;
495
+ if (state.sessionTitle) err.message += ` The agent titled this turn ${JSON.stringify(state.sessionTitle)}.`;
496
+ const files = normalizeAgentReportedFiles([...state.touched], workspace);
497
+ if (files.length) err.message += ` Files reported edited: ${files.join(", ")}.`;
498
+ }
499
+ // Every failure after the session opens leaves a live session, not just the stalls: the id is
500
+ // set before the config calls, so unknown-model and a rejected effort land here too.
501
+ if (resumeError) {
502
+ // Without this the resume hint reads as "carry on from where you were", when the requested
503
+ // session was never resumed.
504
+ err.message += ` Note: resuming ${resumeSessionId} had already failed (${resumeError}),`
505
+ + ` so this ran as a fresh session and none of that earlier work was in context.`;
506
+ }
507
+ if (sessionId) err.message += ` Resume with resumeSessionId ${sessionId}.`;
508
+ if (isTimeout) {
509
+ // Name the knob that actually fired: raising the hard cap does nothing for an
510
+ // idle-timeout, whose ceiling is AGY_DELEGATE_IDLE_MS.
511
+ const knob = err.reason === "idle-timeout" ? "AGY_DELEGATE_IDLE_MS" : "AGY_DELEGATE_HARD_CAP_MS";
512
+ err.message += " agy does not stream shell output over ACP, so a long-running command emits"
513
+ + ` nothing until it exits. Split the command, run it in the background and poll, or raise ${knob}.`;
514
+ }
515
+ // Opt-in: the frames land in the caller's context and nothing there is actionable — the
516
+ // forensics above already carry that. Raw frames only help someone debugging the bridge.
517
+ const frames = transcriptFrames();
518
+ if (frames > 0) {
519
+ try {
520
+ const transcript = client.getTranscript?.(frames);
521
+ if (transcript) err.message += `\n\n--- recent ACP transcript (last ${frames} frames) ---\n` + transcript;
522
+ } catch {}
523
+ }
524
+ throw err;
525
+ } finally {
526
+ clearInterval(heartbeat);
527
+ signal?.removeEventListener("abort", onAbort);
528
+ try { supervisor.finish(); } catch {}
529
+ // Deliberately not awaited: stop() waits for the child to exit, and every turn — success as
530
+ // much as failure — would pay that before returning. Nothing here reads whether it landed.
531
+ Promise.resolve(client.stop()).catch(() => {});
532
+ }
533
+ }