viewable-one 0.12.2 → 0.12.4

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.
Files changed (61) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +2 -2
  3. package/SPAWN.md +107 -53
  4. package/glytch.mjs +49 -12
  5. package/lib/acp.mjs +110 -148
  6. package/lib/admission.mjs +25 -5
  7. package/lib/agents.mjs +59 -16
  8. package/lib/answerTag.mjs +47 -0
  9. package/lib/atomic.mjs +1 -16
  10. package/lib/auth.mjs +25 -9
  11. package/lib/boardside.mjs +28 -12
  12. package/lib/child.mjs +89 -116
  13. package/lib/claudeModels.mjs +168 -0
  14. package/lib/codex-rpc.mjs +2 -2
  15. package/lib/codex.mjs +43 -63
  16. package/lib/codexApps.mjs +5 -3
  17. package/lib/codexToolInputs.mjs +98 -22
  18. package/lib/codingChecks.mjs +8 -4
  19. package/lib/conversationRules.mjs +46 -6
  20. package/lib/detect.mjs +14 -23
  21. package/lib/devserver.mjs +6 -6
  22. package/lib/doctor.mjs +4 -2
  23. package/lib/folderReads.mjs +96 -0
  24. package/lib/followUps.mjs +170 -0
  25. package/lib/hosted.mjs +13 -4
  26. package/lib/init-connect.mjs +29 -10
  27. package/lib/lateResume.mjs +135 -0
  28. package/lib/logindaemon.mjs +113 -33
  29. package/lib/mcpjson.mjs +35 -2
  30. package/lib/multiwatch.mjs +80 -45
  31. package/lib/pagePictures.mjs +14 -11
  32. package/lib/paths.mjs +0 -1
  33. package/lib/permissionAsk.mjs +341 -58
  34. package/lib/procs.mjs +73 -2
  35. package/lib/refusal.mjs +0 -2
  36. package/lib/restartPass.mjs +52 -11
  37. package/lib/rowsAnswers.mjs +18 -34
  38. package/lib/rowsEvents.mjs +20 -2
  39. package/lib/runner-health.mjs +26 -2
  40. package/lib/runner.mjs +106 -1363
  41. package/lib/runnerAdmission.mjs +33 -12
  42. package/lib/runnerApi.mjs +28 -12
  43. package/lib/runnerBeat.mjs +398 -0
  44. package/lib/runnerCompletion.mjs +5 -2
  45. package/lib/runnerExecute.mjs +227 -0
  46. package/lib/runnerGates.mjs +338 -0
  47. package/lib/runnerLaunch.mjs +351 -0
  48. package/lib/runnerLease.mjs +31 -9
  49. package/lib/runnerOps.mjs +226 -0
  50. package/lib/runnerPace.mjs +10 -6
  51. package/lib/runnerRecovery.mjs +457 -0
  52. package/lib/runnerRegister.mjs +29 -8
  53. package/lib/runnerSettlement.mjs +29 -9
  54. package/lib/selfUninstall.mjs +239 -0
  55. package/lib/spawn.mjs +0 -5
  56. package/lib/sync.mjs +26 -14
  57. package/lib/update.mjs +184 -0
  58. package/lib/viewableFolder.mjs +8 -2
  59. package/lib/worktree.mjs +66 -13
  60. package/lib/writePolicy.mjs +90 -10
  61. package/package.json +1 -1
@@ -0,0 +1,47 @@
1
+ // THE LEAD'S EXPLICIT ANSWER, read event by event (#3611, #3634).
2
+ //
3
+ // One reader for two places: boardside.mjs reads it out of a finished run's
4
+ // log, and child.mjs reads it as the events stream, so an answer still
5
+ // counts when later tool output pushes it out of the capped log.
6
+
7
+ const ANSWER_TAG = /<viewable-answer>\s*([\s\S]*?)\s*<\/viewable-answer>/g;
8
+
9
+ /** The last non-empty tagged answer in `text`, or "". */
10
+ export function lastAnswerIn(text) {
11
+ let answer = "";
12
+ for (const match of String(text ?? "").matchAll(ANSWER_TAG)) {
13
+ if (match[1].trim()) answer = match[1].trim();
14
+ }
15
+ return answer;
16
+ }
17
+
18
+ /** Fed parsed events in order; `answer()` is the last tagged answer so far.
19
+ * Engines share assistant events (Claude stream-json, normalised Codex/ACP).
20
+ * ACP sends one assistant event per message chunk, so a tag can split across
21
+ * events: consecutive lead text joins into one turn, and any other event
22
+ * (user, tool call, result) ends it. Subagent events are skipped, and a
23
+ * content-less assistant event (ACP usage_update) is neutral. */
24
+ export function makeAnswerTracker() {
25
+ let turn = "";
26
+ let answer = "";
27
+ const endTurn = () => {
28
+ if (turn) answer = lastAnswerIn(turn) || answer;
29
+ turn = "";
30
+ };
31
+ return {
32
+ push(event) {
33
+ if (event?.parent_tool_use_id) return;
34
+ if (event?.type === "assistant" && !Array.isArray(event.message?.content)) return;
35
+ const blocks = event?.type === "assistant" ? event.message.content : null;
36
+ if (!blocks) { endTurn(); return; }
37
+ // Reasoning is neither answer text nor a turn break: an ACP thought
38
+ // can arrive between two chunks of one message (#3644).
39
+ if (blocks.length > 0 && blocks.every(block => block?.type === "thinking")) return;
40
+ turn += blocks.filter(block => block?.type === "text" && typeof block.text === "string").map(block => block.text).join("");
41
+ if (blocks.some(block => block?.type !== "text")) endTurn();
42
+ },
43
+ answer() {
44
+ return lastAnswerIn(turn) || answer;
45
+ },
46
+ };
47
+ }
package/lib/atomic.mjs CHANGED
@@ -24,7 +24,7 @@
24
24
  // filesystem) and carries the pid plus a counter, so two processes writing
25
25
  // the same destination never share a scratch name.
26
26
 
27
- import { link, rename, writeFile, rm } from "node:fs/promises";
27
+ import { rename, writeFile, rm } from "node:fs/promises";
28
28
  import { dirname, join, basename } from "node:path";
29
29
 
30
30
  let seq = 0;
@@ -79,18 +79,3 @@ export async function writeFileAtomic(
79
79
  throw error;
80
80
  }
81
81
  }
82
-
83
- /** Publish a complete file only if the destination does not exist. The link
84
- * reserves the destination atomically across processes; a crash before it
85
- * leaves only an ignored temp file, and a crash after it leaves the full file.
86
- * EEXIST means another publisher already committed this identity. */
87
- export async function writeFileAtomicExclusive(path, data, encoding = "utf8") {
88
- seq += 1;
89
- const tmp = join(dirname(path), `.${basename(path)}.tmp-${process.pid}-${seq}`);
90
- try {
91
- await writeFile(tmp, data, encoding);
92
- await link(tmp, path);
93
- } finally {
94
- await rm(tmp, { force: true }).catch(() => {});
95
- }
96
- }
package/lib/auth.mjs CHANGED
@@ -1035,19 +1035,35 @@ async function discoverResource(fetchImpl, base, log) {
1035
1035
  return { resource: `${base}/mcp`, authorizationServerBase: base };
1036
1036
  }
1037
1037
 
1038
+ /** The program and argument list that open `url` in the default browser, or
1039
+ * null when `url` is not a plain http(s) link. Never goes through a shell:
1040
+ * on Windows `cmd /c start` read each `&` in the link as a command separator
1041
+ * (the browser got a cut link, and anything after the `&` ran as a command),
1042
+ * so Windows uses rundll32, which gets the link as one argument. The link
1043
+ * comes from the app's discovery metadata, so a `file:` or other scheme is
1044
+ * refused too: the handler would run it. */
1045
+ export function browserCommand(url, platform = process.platform) {
1046
+ let parsed;
1047
+ try {
1048
+ parsed = new URL(String(url));
1049
+ } catch {
1050
+ return null;
1051
+ }
1052
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
1053
+ const link = String(url);
1054
+ if (platform === "darwin") return { file: "open", args: [link] };
1055
+ if (platform === "win32") return { file: "rundll32", args: ["url.dll,FileProtocolHandler", link] };
1056
+ return { file: "xdg-open", args: [link] };
1057
+ }
1058
+
1038
1059
  /** Open a URL in the person's default browser. Best-effort and silent on
1039
1060
  * failure - the caller always prints the URL too, which is the fallback that
1040
1061
  * matters on a headless box or an unfamiliar platform. */
1041
- export function openInBrowser(url) {
1062
+ export function openInBrowser(url, { platform = process.platform, spawnFn = spawn } = {}) {
1042
1063
  try {
1043
- const platform = process.platform;
1044
- const [cmd, args] =
1045
- platform === "darwin"
1046
- ? ["open", [url]]
1047
- : platform === "win32"
1048
- ? ["cmd", ["/c", "start", "", url]]
1049
- : ["xdg-open", [url]];
1050
- const child = spawn(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
1064
+ const command = browserCommand(url, platform);
1065
+ if (!command) return false;
1066
+ const child = spawnFn(command.file, command.args, { stdio: "ignore", detached: true, windowsHide: true, shell: false });
1051
1067
  child.on("error", () => {});
1052
1068
  child.unref();
1053
1069
  return true;
package/lib/boardside.mjs CHANGED
@@ -20,6 +20,7 @@
20
20
  // its own op (e.g. a `session_asks` view) and is not in this contract.
21
21
 
22
22
  import { classifyExit } from "./exitClass.mjs";
23
+ import { lastAnswerIn, makeAnswerTracker } from "./answerTag.mjs";
23
24
  import { callTool as hostedCallTool } from "./hosted.mjs";
24
25
 
25
26
  /** The verdict, in words. The default set is the receipt's own (`finished` /
@@ -106,13 +107,12 @@ async function proposeOnBoard(session, ops, label, { callTool = hostedCallTool,
106
107
  export async function commentOnAnchor(session, frameId, text, options = {}) {
107
108
  if (!frameId) return null;
108
109
  const { fields, ...rest } = options;
109
- const result = await proposeOnBoard(
110
+ return proposeOnBoard(
110
111
  session,
111
112
  [{ call: "addComment", args: { id: frameId, text, ...(fields ?? {}) } }],
112
113
  `Session ${session.key} outcome`,
113
114
  rest,
114
115
  );
115
- return result.ok ? result.detail : null;
116
116
  }
117
117
 
118
118
  /** A question through `ask_user`, under the run's own session key. It lands as
@@ -120,14 +120,15 @@ export async function commentOnAnchor(session, frameId, text, options = {}) {
120
120
  * circle of its own. Used for the one case the runner itself ever asks
121
121
  * anything: a failed merge. Returns the question NOTE id parsed out of
122
122
  * `ask_user`'s reply text (`pending (question_id: <noteId>)`), or null when the call failed or the id could not
123
- * be found in the reply. */
124
- export async function askUserOnBoard(session, question, { why, fromId, options: choices, recommendation, images, purpose } = {}, options = {}) {
123
+ * be found in the reply. `askKey` makes the ask idempotent: the same key from
124
+ * the same session returns the note already asked (#5106). */
125
+ export async function askUserOnBoard(session, question, { why, fromId, options: choices, recommendation, images, purpose, askKey } = {}, options = {}) {
125
126
  const outcome = await (options.callTool ?? hostedCallTool)(
126
127
  "ask_user",
127
- { question, why, ...(fromId ? { from_id: fromId } : {}), ...(choices ? { options: choices } : {}), ...(recommendation ? { recommendation } : {}), ...(images?.length > 0 ? { images } : {}), ...(purpose ? { purpose } : {}) },
128
+ { question, why, ...(fromId ? { from_id: fromId } : {}), ...(choices ? { options: choices } : {}), ...(recommendation ? { recommendation } : {}), ...(images?.length > 0 ? { images } : {}), ...(purpose ? { purpose } : {}), ...(askKey ? { ask_key: askKey } : {}) },
128
129
  { sessionKey: session.key, env: options.env },
129
130
  );
130
- if (outcome.isError) return { ok: false, detail: outcome.text };
131
+ if (outcome.isError) return { ok: false, detail: outcome.text, ...(outcome.refused === true ? { refused: true } : {}) };
131
132
  const match = /question_id:\s*(\S+)\)/.exec(outcome.text ?? "");
132
133
  return { ok: true, questionId: match?.[1] ?? null, detail: outcome.text };
133
134
  }
@@ -138,12 +139,26 @@ export async function askUserOnBoard(session, question, { why, fromId, options:
138
139
  // one line of figures. The hosted `addComment` on an idea lands it as a
139
140
  // `reply` note carrying the agent, the run, a caption and the links.
140
141
 
141
- /** The closing words, capped at 2,000 characters with the END kept: the part
142
- * of a long answer a person needs is the part that says where it landed. */
143
- export const CLOSING_TEXT_CAP = 2000;
142
+ /** An explicitly delimited answer is the deliverable, not a coding handoff:
143
+ * preserve its whole shape. Other closing words are kept whole too; the hosted
144
+ * writer splits overflow into ideas (#3583), so nothing is cut here. */
144
145
  export function closingTextOf(outcome) {
145
146
  const raw = typeof outcome.envelope?.result === "string" ? outcome.envelope.result.trim() : "";
146
- return raw.length > CLOSING_TEXT_CAP ? `…${raw.slice(raw.length - (CLOSING_TEXT_CAP - 1)).trimStart()}` : raw;
147
+ // A repo may require another message after the answer (#3611). Only the
148
+ // lead's explicit answer counts, never tool output or a subagent's reply.
149
+ // The envelope's own result wins; then the answer the child read as events
150
+ // streamed, which survives a log cut down by later tool output (#3634);
151
+ // then the log itself, for engines that do not stream one.
152
+ let answer = lastAnswerIn(raw) || (typeof outcome.answer === "string" ? outcome.answer : "");
153
+ if (!answer) {
154
+ const tracker = makeAnswerTracker();
155
+ for (const line of (outcome.log ?? "").split("\n")) {
156
+ try { tracker.push(JSON.parse(line)); } catch { /* A capped log can begin with a partial event. */ }
157
+ }
158
+ answer = tracker.answer();
159
+ }
160
+ if (answer) return answer;
161
+ return raw;
147
162
  }
148
163
 
149
164
  /** The first sentence of the closing words, for the circle's caption. */
@@ -171,7 +186,7 @@ export const IN_PLACE_NOTICE = "This ran in your folder itself, so Throw away ca
171
186
 
172
187
  /** The reply's text and caption for a run that finished. Pure.
173
188
  *
174
- * The closing words first (capped, the end kept), then ONE line led by
189
+ * The explicit answer (or the closing words, kept whole for the hosted splitter), then ONE line led by
175
190
  * "Finished" that carries only how long it took: "Finished; 4m". The card
176
191
  * footer reads "Took 4 minutes" (#470, #735); turns, the branch and the file
177
192
  * count are developer words and stay on the session screen.
@@ -221,5 +236,6 @@ export async function reportOutcomeOnBoard(session, outcome, frameId, options =
221
236
  // The plain line when a screen changed but no pictures could be taken (#2194).
222
237
  const lines = [text, outcome.result?.fixAttempted && "Coding tried one fix.", outcome.picturesNote].filter(Boolean);
223
238
  const closing = lines.join("\n\n");
224
- return commentOnAnchor(session, frameId, closing, { ...rest, fields });
239
+ const receipt = await commentOnAnchor(session, frameId, closing, { ...rest, fields });
240
+ return { landed: receipt?.ok === true && Boolean(closingTextOf(outcome)) };
225
241
  }
package/lib/child.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { observeClaudeModel } from "./claudeModels.mjs";
1
2
  import { imageAttachments } from "./imageAttachments.mjs";
2
3
  // RUNNING A CHILD PROCESS, and nothing about the board.
3
4
  //
@@ -13,13 +14,14 @@ import { imageAttachments } from "./imageAttachments.mjs";
13
14
  // runaway and stall paths testable against a fake binary.
14
15
 
15
16
  import { spawn } from "node:child_process";
16
- import { readFile, readdir, unlink } from "node:fs/promises";
17
17
  import { createWriteStream } from "node:fs";
18
18
  import { createGzip, constants as zlibConstants } from "node:zlib";
19
19
  import { join } from "node:path";
20
20
 
21
21
  import { killTree } from "./kill.mjs";
22
+ import { makeAnswerTracker } from "./answerTag.mjs";
22
23
  import { RUNNER_BEAT_MS } from "./spawn.mjs";
24
+ import { DELIVERED, SKIP, STOP, watchAnswers, watchReplyFiles } from "./followUps.mjs";
23
25
  import { runnableCommand } from "./windows-command.mjs";
24
26
 
25
27
  // Defaults, all overridable by env and all bounds rather than preferences.
@@ -44,6 +46,11 @@ export const DEFAULTS = {
44
46
  beatMs: RUNNER_BEAT_MS,
45
47
  // How long a SIGTERM'd child gets to exit before SIGKILL.
46
48
  killGraceMs: 5_000,
49
+ // Automatic tests, build and pictures after the agent finishes get their own
50
+ // cap, so they cannot hold the result and Keep changes for the rest of a
51
+ // 90-minute coding session. A check that hits it is "not finished", never
52
+ // failed. The one repair run stays on the session budget.
53
+ checkMaxMs: 300_000,
47
54
  // Stall watchdog: no stdout for this long with a turn open (no result envelope
48
55
  // since the last user message AND no tool_use waiting for its tool_result) kills
49
56
  // the child. Default 15 minutes. Armed only when the MODEL should be producing
@@ -311,6 +318,8 @@ export function costOf(envelope) {
311
318
  * settled() whether the promise has already been resolved
312
319
  */
313
320
  export function attachChild(child, {
321
+ onProcess,
322
+ onSession,
314
323
  resolve,
315
324
  maxMs,
316
325
  maxLogBytes = DEFAULTS.maxLogBytes,
@@ -331,6 +340,7 @@ export function attachChild(child, {
331
340
  // 2026-09-06 ruling and the whole of "a finished session exits". Called
332
341
  // once per envelope, never after the promise has settled.
333
342
  onResult = () => {},
343
+ onEvent = () => {},
334
344
  // Close protocol admission before signalling a child that may linger.
335
345
  onKill = () => {},
336
346
  // A `control_request` or `control_cancel_request` line arrived on stdout:
@@ -353,7 +363,11 @@ export function attachChild(child, {
353
363
  // unaffected, byte for byte.
354
364
  transcriptDir,
355
365
  }) {
366
+ onProcess?.(child.pid);
367
+ let reportedSession;
356
368
  const ring = makeLogRing(maxLogBytes);
369
+ // The answer as events stream, kept apart from the capped ring (#3634).
370
+ const answers = makeAnswerTracker();
357
371
  const timers = new Set();
358
372
  /** An interval that cannot outlive the child: settle clears every one. */
359
373
  const every = (fn, ms) => {
@@ -458,6 +472,14 @@ export function attachChild(child, {
458
472
  try {
459
473
  const parsed = JSON.parse(line);
460
474
  if (parsed === null || typeof parsed !== "object") continue;
475
+ if (!state.settled) {
476
+ onEvent(parsed);
477
+ if (typeof parsed.session_id === "string" && parsed.session_id && parsed.session_id !== reportedSession) {
478
+ reportedSession = parsed.session_id;
479
+ void Promise.resolve(onSession?.(reportedSession)).catch(() => {});
480
+ }
481
+ }
482
+ answers.push(parsed);
461
483
  if (parsed.type === "assistant") state.sawAssistant = true;
462
484
  if ((parsed.type === "control_request" || parsed.type === "control_cancel_request") && !state.settled) {
463
485
  try { onControl(parsed); } catch { /* a listener must not take the child down */ }
@@ -546,8 +568,9 @@ export function attachChild(child, {
546
568
  * IT IS THE CHILD'S PID AND NOT ITS PROCESS GROUP, and since 2026-09-06
547
569
  * that is load-bearing rather than incidental. `child.kill(sig)` signals
548
570
  * one pid; `process.kill(-pgid, sig)` would signal everything the child
549
- * started, and the child is spawned WITHOUT `detached`, so it shares the
550
- * runner's group and a group kill here would reach the runner itself.
571
+ * started. Recovery-tracked agents now have a private group, but ordinary
572
+ * callers can still share the runner's group. Normal agent shutdown
573
+ * remains a single-PID signal; orphan recovery verifies members separately.
551
574
  *
552
575
  * Ruling A that day is what makes the distinction matter: a session
553
576
  * with the Browser switch on starts its dev server detached so the browser
@@ -631,6 +654,7 @@ export function attachChild(child, {
631
654
  // The running total - see the note on `state.totalTokens`.
632
655
  totalTokens: state.totalTokens,
633
656
  sawAssistant: state.sawAssistant,
657
+ answer: answers.answer(),
634
658
  ...extraFields(state),
635
659
  });
636
660
  const closed = transcriptSink?.close();
@@ -665,7 +689,7 @@ export function attachChild(child, {
665
689
  * The wall clock is not a progress protocol and does not put a third state on
666
690
  * the board. It is the one bound between "a session hung" and "a session
667
691
  * billed all night". */
668
- export function runChild({ bin, args, cwd, env, input, maxMs, maxLogBytes = DEFAULTS.maxLogBytes, killGraceMs = DEFAULTS.killGraceMs, onChunk, onStdout, stopCheck, stopPollMs = 2000, onSpend, platform = process.platform, transcriptDir, killProcessGroup = false, claudeResult = false }) {
692
+ export function runChild({ bin, args, cwd, env, input, recoveryGroup = false, onProcess, onSession, maxMs, maxLogBytes = DEFAULTS.maxLogBytes, killGraceMs = DEFAULTS.killGraceMs, onChunk, onStdout, stopCheck, stopPollMs = 2000, onSpend, platform = process.platform, transcriptDir, killProcessGroup = false, claudeResult = false }) {
669
693
  return new Promise((resolve) => {
670
694
  let child;
671
695
  try {
@@ -678,7 +702,7 @@ export function runChild({ bin, args, cwd, env, input, maxMs, maxLogBytes = DEFA
678
702
  // `windowsHide: true` is harmless on POSIX (detect.mjs's execProbe has
679
703
  // carried it unconditionally since before this brief) and stops a
680
704
  // console window flashing per session on Windows.
681
- child = spawn(resolved.file, resolved.args, { cwd, env, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], shell: resolved.shell, windowsHide: true, detached: killProcessGroup && platform !== "win32" });
705
+ child = spawn(resolved.file, resolved.args, { cwd, env, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], shell: resolved.shell, windowsHide: true, detached: (killProcessGroup || recoveryGroup) && platform !== "win32" });
682
706
  } catch (error) {
683
707
  resolve({ ok: false, spawnError: error instanceof Error ? error.message : String(error), log: "" });
684
708
  return;
@@ -692,6 +716,8 @@ export function runChild({ bin, args, cwd, env, input, maxMs, maxLogBytes = DEFA
692
716
  // the envelope scan, the wall clock, the stop watcher and the settle. A
693
717
  // Claude error envelope vetoes success; ordinary command output does not.
694
718
  attachChild(child, {
719
+ onProcess,
720
+ onSession,
695
721
  resolve,
696
722
  maxMs,
697
723
  maxLogBytes,
@@ -702,6 +728,7 @@ export function runChild({ bin, args, cwd, env, input, maxMs, maxLogBytes = DEFA
702
728
  killProcessGroup: killProcessGroup && platform !== "win32",
703
729
  transcriptDir,
704
730
  flushFinalLine: claudeResult,
731
+ ...(claudeResult ? { onEvent: observeClaudeModel(args, { ...process.env, ...env }) } : {}),
705
732
  ...(onSpend ? { onSpend } : {}),
706
733
  okOf: (state, code) => !state.timedOut && !state.stoppedByUser && !(claudeResult && state.resultWasError) && code === 0,
707
734
  extraFields: (state) => claudeResult ? { finishedWithError: state.resultWasError && !state.timedOut && !state.stoppedByUser } : {},
@@ -782,7 +809,7 @@ export function runChild({ bin, args, cwd, env, input, maxMs, maxLogBytes = DEFA
782
809
  * whole new resume request - the watch loop's 5s poll, the app's receipt, the
783
810
  * worktree, and a cold `claude --resume`. That is tens of seconds and it is a
784
811
  * design decision, not a constant. */
785
- export function runStreamingChild({ bin, args, cwd, env, onSpawn, maxMs, maxLogBytes = DEFAULTS.maxLogBytes, killGraceMs = DEFAULTS.killGraceMs, stallMs = DEFAULTS.stallMs, onChunk, prompt, images, replyDir, replyPrefix, replyPollMs = 500, onUndeliveredReply, answerPoll, answerPollMs = 4000, askPermission, stopCheck, stopPollMs = 2000, onSpend, platform = process.platform, transcriptDir }) {
812
+ export function runStreamingChild({ bin, args, cwd, env, recoveryGroup = false, onSpawn, onProcess, onSession, maxMs, maxLogBytes = DEFAULTS.maxLogBytes, killGraceMs = DEFAULTS.killGraceMs, stallMs = DEFAULTS.stallMs, onChunk, prompt, images, replyDir, replyPrefix, replyPollMs = 500, onUndeliveredReply, answerPoll, answerPollMs = 4000, askPermission, stopCheck, stopPollMs = 2000, onSpend, platform = process.platform, transcriptDir }) {
786
813
  return new Promise((resolve) => {
787
814
  try { imageAttachments(images); } catch (error) { resolve({ ok: false, log: "", spawnError: error.message }); return; }
788
815
  let child;
@@ -791,7 +818,7 @@ export function runStreamingChild({ bin, args, cwd, env, onSpawn, maxMs, maxLogB
791
818
  // AND opencode per ruling 5B) - streaming is the path a persistent
792
819
  // Claude Code session takes.
793
820
  const resolved = runnableCommand(bin, args, { platform, env });
794
- child = spawn(resolved.file, resolved.args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], shell: resolved.shell, windowsHide: true });
821
+ child = spawn(resolved.file, resolved.args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], shell: resolved.shell, windowsHide: true, detached: recoveryGroup && platform !== "win32" });
795
822
  } catch (error) {
796
823
  resolve({ ok: false, spawnError: error instanceof Error ? error.message : String(error), log: "" });
797
824
  return;
@@ -804,6 +831,9 @@ export function runStreamingChild({ bin, args, cwd, env, onSpawn, maxMs, maxLogB
804
831
  // uses. What is left in this function is the half a one-shot child does
805
832
  // not have: stdin.
806
833
  const handle = attachChild(child, {
834
+ onProcess,
835
+ onSession,
836
+ onEvent: observeClaudeModel(args, { ...process.env, ...env }),
807
837
  resolve,
808
838
  maxMs,
809
839
  maxLogBytes,
@@ -971,122 +1001,65 @@ export function runStreamingChild({ bin, args, cwd, env, onSpawn, maxMs, maxLogB
971
1001
 
972
1002
  sendToChild(userMessage(prompt, images));
973
1003
 
974
- // Watch for reply files. Each file is a JSON object with a `message` string.
975
- // Files are sorted by name (timestamp-based) and consumed in order.
976
- const watchReplies = () => {
977
- if (handle.settled() || !replyDir || !replyPrefix) return;
978
- const replyWatcher = handle.every(async () => {
979
- if (handle.settled()) { clearInterval(replyWatcher); return; }
980
- try {
981
- const files = (await readdir(replyDir))
982
- .filter((f) => f.startsWith(replyPrefix) && f.endsWith(".json"))
983
- .sort();
984
- for (const file of files) {
985
- if (handle.settled()) break;
986
- const full = join(replyDir, file);
987
- let text = null;
988
- let replyImages;
989
- let fromField = null;
990
- try {
991
- const data = JSON.parse(await readFile(full, "utf8"));
992
- text = typeof data.message === "string" ? data.message : null;
993
- // Reply files may carry images alongside text, same data URL
994
- // format as the spawn request. The runner sends them as image
995
- // content blocks on stdin.
996
- replyImages = data.images;
997
- // Brief 12: agent-to-agent messaging. A `from` field in the
998
- // reply file labels the sender (another session's id, the human's
999
- // name, anything) so the receiver never mistakes a peer's words
1000
- // for the user's. The runner wraps it: injection is prompt
1001
- // injection by design; label it.
1002
- fromField = typeof data.from === "string" && data.from.trim() !== "" ? data.from.trim() : null;
1003
- } catch { continue; /* skip malformed reply files */ }
1004
- try { imageAttachments(replyImages); } catch (error) {
1005
- const detail = `Reference image reply was not delivered: ${error.message}`;
1006
- const failure = JSON.stringify({ type: "result", subtype: "error_during_execution", is_error: true, errors: [detail] }) + "\n";
1007
- child.stdout.emit("data", Buffer.from(failure));
1008
- handle.kill();
1009
- return;
1010
- }
1011
- // CONSUME BEFORE SENDING. The write used to come first, and an
1012
- // unlink that then failed (permission, or the app rewriting the
1013
- // file) left the reply on disk for the next 2s poll to send
1014
- // again - the human's message arrived at the session twice, with
1015
- // the failure swallowed. Deleting first means the worst case is a
1016
- // reply that is not delivered because the child is already gone,
1017
- // which is not a delivery this could have made anyway.
1018
- try {
1019
- await unlink(full);
1020
- } catch {
1021
- continue;
1022
- }
1023
- if (text) {
1024
- const attributed = fromField ? `[message from ${fromField}] ${text}` : text;
1025
- // A REPLY THAT CANNOT BE SPOKEN IS NOT A LOST REPLY (2026-09-06).
1026
- // Since the envelope closes stdin, this is the ordinary ending
1027
- // of a finished session rather than a rare race: the human typed
1028
- // into a session whose turn was already over. The file has been
1029
- // consumed above, so the words exist only here - hand them
1030
- // straight back to whoever passed this callback (runner.mjs
1031
- // turns them into a resume request) rather than dropping them on
1032
- // the floor the way a `false` from sendToChild used to.
1033
- if (!sendToChild(userMessage(attributed, replyImages)) && onUndeliveredReply) {
1034
- try {
1035
- await onUndeliveredReply({ text, from: fromField, images: replyImages, attributed });
1036
- } catch { /* the caller's problem to log; never take the child down */ }
1037
- }
1038
- }
1039
- }
1040
- } catch { /* replyDir may not exist yet */ }
1041
- }, replyPollMs);
1042
- };
1043
- watchReplies();
1004
+ // Reply files and board answers: the steps are shared by all three engines
1005
+ // (followUps.mjs, #4625); this engine says only how a message reaches the
1006
+ // child. Each reply file is a JSON object with a `message` string and may
1007
+ // carry images in the same data URL format as the spawn request, which the
1008
+ // runner sends as image content blocks on stdin.
1009
+ watchReplyFiles({
1010
+ handle, replyDir, replyPrefix, pollMs: replyPollMs,
1011
+ validate: (_text, images) => { imageAttachments(images); },
1012
+ onInvalid: (error) => {
1013
+ const detail = `Reference image reply was not delivered: ${error.message}`;
1014
+ const failure = JSON.stringify({ type: "result", subtype: "error_during_execution", is_error: true, errors: [detail] }) + "\n";
1015
+ child.stdout.emit("data", Buffer.from(failure));
1016
+ handle.kill();
1017
+ },
1018
+ send: async ({ text, from, images, attributed }) => {
1019
+ // A REPLY THAT CANNOT BE SPOKEN IS NOT A LOST REPLY (2026-09-06).
1020
+ // Since the envelope closes stdin, this is the ordinary ending
1021
+ // of a finished session rather than a rare race: the human typed
1022
+ // into a session whose turn was already over. The file has been
1023
+ // consumed, so the words exist only here - hand them straight back to
1024
+ // whoever passed this callback (runner.mjs turns them into a resume
1025
+ // request) rather than dropping them on the floor the way a `false`
1026
+ // from sendToChild used to.
1027
+ if (!sendToChild(userMessage(attributed, images)) && onUndeliveredReply) {
1028
+ try {
1029
+ await onUndeliveredReply({ text, from, images, attributed });
1030
+ } catch { /* the caller's problem to log; never take the child down */ }
1031
+ }
1032
+ },
1033
+ });
1044
1034
 
1045
1035
  // THE SAME DOOR, for answers the human gave on the canvas after ask_user
1046
1036
  // had already returned pending. `answerPoll` hands back ready-made
1047
- // messages so this function stays free of board vocabulary; it knows only
1048
- // that something upstream may have words for the child.
1037
+ // messages so this function stays free of board vocabulary.
1049
1038
  //
1050
1039
  // Delivery is confirmed AFTER the write, not before: onDelivered is what
1051
1040
  // records that the session has been told, and marking first would lose a
1052
1041
  // ruling for good if the child settled in between.
1053
- let answerBusy = false;
1054
- const watchAnswers = () => {
1055
- if (handle.settled() || !answerPoll) return;
1056
- const collect = async () => {
1057
- if (handle.settled()) return;
1058
- // setInterval does not wait for an async callback, and a slow mirror
1059
- // read would otherwise let two passes see the same unmarked answer.
1060
- if (answerBusy) return;
1061
- answerBusy = true;
1062
- try {
1063
- for (const answer of await answerPoll()) {
1064
- if (handle.settled()) break;
1065
- // Only record delivery if the pipe actually took it, or a ruling
1066
- // would be marked delivered to a child that never heard it.
1067
- // `answer.images` (item 6, brief 30 Move 2b): a message's
1068
- // images, delivered through the SAME content-block channel a
1069
- // reply file's images already use (`userMessage`, above).
1070
- let payload;
1071
- try { payload = userMessage(answer.text, answer.images); }
1072
- catch (error) {
1073
- // Omit only this invalid reply, leaving it unacknowledged for
1074
- // late recovery. Other rows in this batch still need delivery.
1075
- const failure = JSON.stringify({ type: "system", subtype: "error",
1076
- message: `Reference image reply was not delivered: ${error.message}` }) + "\n";
1077
- child.stdout.emit("data", Buffer.from(failure));
1078
- continue;
1079
- }
1080
- if (!sendToChild(payload)) break;
1081
- if (answer.onDelivered) await answer.onDelivered();
1082
- }
1083
- } catch { /* a poll that throws is not an answer either way */ }
1084
- answerBusy = false;
1085
- };
1086
- handle.every(collect, answerPollMs);
1087
- answerPoll.subscribe?.(collect);
1088
- };
1089
- watchAnswers();
1042
+ watchAnswers({
1043
+ handle, answerPoll, pollMs: answerPollMs,
1044
+ send: async (answer) => {
1045
+ // `answer.images` (item 6, brief 30 Move 2b): a message's images,
1046
+ // delivered through the SAME content-block channel a reply file's
1047
+ // images already use (`userMessage`).
1048
+ let payload;
1049
+ try { payload = userMessage(answer.text, answer.images); }
1050
+ catch (error) {
1051
+ // Omit only this invalid reply, leaving it unacknowledged for
1052
+ // late recovery. Other rows in this batch still need delivery.
1053
+ const failure = JSON.stringify({ type: "system", subtype: "error",
1054
+ message: `Reference image reply was not delivered: ${error.message}` }) + "\n";
1055
+ child.stdout.emit("data", Buffer.from(failure));
1056
+ return SKIP;
1057
+ }
1058
+ // Only record delivery if the pipe actually took it, or a ruling
1059
+ // would be marked delivered to a child that never heard it.
1060
+ return sendToChild(payload) ? DELIVERED : STOP;
1061
+ },
1062
+ });
1090
1063
 
1091
1064
  // STALL WATCHDOG: no stdout for stallMs while the MODEL should be producing
1092
1065
  // output. Armed when a turn is open (no result envelope since the last user