pi-straw-boss 0.87.2 → 0.88.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-straw-boss",
3
- "version": "0.87.2",
3
+ "version": "0.88.0",
4
4
  "description": "Straw Boss coordination for pi in Herdr: sessions join a tab's net by choice, the first joiner is its main agent, a workspace tower opens on demand with a live monitoring dashboard, and boss_broadcast reaches the rest",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,76 @@
1
+ // Whether a subagent run died under its live launcher, from one table (docs/specs/2026-11-24-worker-revive.md §1 and §2), the way dead.ts decides a main: the callers gather the facts, and this module
2
+ // alone gives the answer. It reads no file and asks nobody.
3
+ //
4
+ // pi-herdr-agents ends a run on the child's `.exit` sidecar (done, error, ping), on its launch script's `__SUBAGENT_DONE_<code>__` sentinel, or on its pane's disappearance, and hands the launcher one
5
+ // `subagent_result`. The child writes `.exit` before it exits, so a report always comes through the sidecar; a result with neither a sidecar's error nor a zero exit is a pi that ended without one.
6
+ //
7
+ // | details | death |
8
+ // |-----------------------------------------------------------|----------------------------------------------------|
9
+ // | `error: "cancelled"` or a `cancellation` | no: the launcher cancelled it |
10
+ // | `error: "persistent-crash"` | no: a persistent specialist, which cannot come back |
11
+ // | `exitCode: 0` | no: it completed |
12
+ // | an `errorMessage` other than the host's three below | no: the child reported an error (a provider error) |
13
+ // | the host's "pane disappeared" | no: its pane was closed (the boss, an agent, a tab); a crash leaves the shell and its sentinel |
14
+ // | the host's "native execution ended", "process exited" | yes: its process went first |
15
+ // | no `errorMessage`, exit 130 (SIGINT) | no: a Ctrl-C in its pane |
16
+ // | no `errorMessage`, any other exit | yes: a crash (1), a kill (137), another signal |
17
+ //
18
+ // | state | evidence | the launcher |
19
+ // |------------|-------------------------------------------------------------------------------------------------------|-------------------|
20
+ // | refused | no launch script, a command that cannot be read, a persistent run, a session that never started, a revive of the file that failed in 24 h or came in the last 10 minutes | tells, never revives |
21
+ // | live | a pane runs the file, the broker lists its session, or the file moved in the last 60 s | waits |
22
+ // | confirming | seen dead in fewer than 2 looks 60 s apart | waits |
23
+ // | dead | none of the above | revives |
24
+
25
+ import { CONFIRM_MS, LIVE_MS, LOOKS } from "./dead.ts";
26
+
27
+ /** What maestro writes as the error of a run whose pane or process went away before any evidence of its own (adapters/pi/completion.ts). */
28
+ export const HOST_DEATHS = [
29
+ "Subagent pane disappeared before completion evidence was recorded.",
30
+ "Subagent native execution ended before completion evidence was recorded.",
31
+ "Subagent process exited before completion evidence was recorded.",
32
+ ];
33
+ const SIGNALS: Record<number, string> = { 1: "SIGHUP", 2: "SIGINT", 6: "SIGABRT", 9: "SIGKILL", 10: "SIGBUS", 11: "SIGSEGV", 15: "SIGTERM" };
34
+
35
+ export interface Death { file: string; name: string; /** How it ended, as a clause. */ why: string }
36
+
37
+ /** The death a `subagent_result`'s details describe, or undefined when the run ended any other way. */
38
+ export function deathOf(details: unknown): Death | undefined {
39
+ if (!details || typeof details !== "object") return undefined;
40
+ const d = details as { sessionFile?: unknown; exitCode?: unknown; errorMessage?: unknown; error?: unknown; cancellation?: unknown; name?: unknown };
41
+ if (typeof d.sessionFile !== "string" || !d.sessionFile || d.error !== undefined || d.cancellation !== undefined) return undefined;
42
+ const code = typeof d.exitCode === "number" ? d.exitCode : undefined, name = typeof d.name === "string" && d.name ? d.name : "subagent";
43
+ if (code === 0) return undefined;
44
+ if (d.errorMessage !== undefined) {
45
+ const host = HOST_DEATHS.indexOf(String(d.errorMessage));
46
+ // A closed pane is never revived (review RV-F003): maestro types the script into the pane's own shell, so a pi that crashes or is killed leaves the shell and its sentinel's exit code.
47
+ return host < 1 ? undefined : { file: d.sessionFile, name, why: "its process ended" };
48
+ }
49
+ if (code === undefined || code === 130) return undefined;
50
+ const signal = code > 128 ? SIGNALS[code - 128] : undefined;
51
+ return { file: d.sessionFile, name, why: signal ? `its pi was ended by ${signal} (exit ${code})` : `its pi exited with code ${code} and no report` };
52
+ }
53
+
54
+ export type ChildDeadState = "refused" | "live" | "confirming" | "dead";
55
+ export interface ChildFacts {
56
+ now: number;
57
+ /** Why the run may not be revived (childrevive.ts `refusal`), or undefined when it may. */
58
+ refusal?: string;
59
+ /** A pane of Herdr runs the session file. */
60
+ held: boolean;
61
+ /** The broker lists the session's id. */
62
+ listed: boolean;
63
+ /** The session file's mtime; undefined when the file is gone (that is a refusal). */
64
+ mtimeMs?: number;
65
+ /** The looks that found it dead before this one, the first one's time. */
66
+ seen: { first: number; looks: number };
67
+ }
68
+
69
+ export function classify(f: ChildFacts): { state: ChildDeadState; reason: string } {
70
+ if (f.refusal) return { state: "refused", reason: f.refusal };
71
+ if (f.held) return { state: "live", reason: "a pane runs its session file" };
72
+ if (f.listed) return { state: "live", reason: "the broker lists its session" };
73
+ if (f.mtimeMs !== undefined && f.now - f.mtimeMs < LIVE_MS) return { state: "live", reason: "its session file moved in the last minute" };
74
+ if (f.seen.looks < LOOKS - 1 || f.now - f.seen.first < CONFIRM_MS) return { state: "confirming", reason: "seen dead once; a second look a minute later confirms it" };
75
+ return { state: "dead", reason: "its pi is gone, no pane runs its session, and nothing else holds it" };
76
+ }
@@ -0,0 +1,354 @@
1
+ import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+ import { classify, type Death, deathOf } from "./childdead.ts";
4
+ import { cutOf, describe } from "./cut.ts";
5
+ import { CONFIRM_MS, LOOKS } from "./dead.ts";
6
+ import { type HerdrRun, type Pane, panes, result, type Session, type Sleep } from "./herdr.ts";
7
+ import { encoded, lastText, RESULT } from "./inherit.ts";
8
+ import { artifacts, readJson } from "./netdata.ts";
9
+ import { tracked } from "./orphan.ts";
10
+ import { DAY_MS, LOOP_MS, sessionHeader } from "./revive.ts";
11
+ import { line } from "./safetext.ts";
12
+
13
+ // A subagent whose own pi dies while its launcher lives is revived by the launcher's Straw Boss (docs/specs/2026-11-24-worker-revive.md). pi-herdr-agents delivers the death as a failed
14
+ // `subagent_result` and lets the run go; childdead.ts tells a death from any other ending. This look, on the launcher's 15 s timer, confirms it in two looks a minute apart, starts the run's own launch
15
+ // command again in a new pane of the launcher's tab with a revive notice as its first message, and then watches the revived pi in pi-herdr-agents' place: its `.exit` is delivered as inherit.ts
16
+ // delivers an inherited run's. Every step is an entry in the launcher's session (`{workerRevive}`), written before it acts, keyed by the failure's own entry: a death is acted on once, across a reload.
17
+
18
+ export const REVIVED = "straw-boss-child-revived";
19
+ const KEY = "workerRevive", RESULT_TYPE = "subagent_result", FINALS = new Set([RESULT_TYPE, "subagent_ping"]), NOTE = "Straw Boss: this is no report of ", START_MS = 60_000, CLOSE_LOOKS = 8, HEAD = 1024 * 1024;
20
+ const TAIL = "; echo '__SUBAGENT_DONE_'$?'__'";
21
+ /** The run id in a subagent session file's name (`<time>_<run id>[-<suffix>].jsonl`, netdata.ts `ownFile`). */
22
+ const RUN = /_([^_]+?)(?:-[0-9a-f]{1,8}-[0-9a-f]{1,8}-[0-9a-f]{1,4})?\.jsonl$/;
23
+ const FOLLOW = "Your pi died while you were working and was not revived. Read your session so far, check the current state before re-running anything that changes state, finish the task you were given, and report your result.";
24
+
25
+ export interface Entry { type: string; id?: string; timestamp?: string; customType?: string; data?: unknown; details?: unknown; content?: unknown }
26
+ type Step = "reviving" | "revived" | "delivered" | "failed" | "skipped";
27
+ interface Mark { death: string; file: string; step: Step; at: number; name: string; pane?: string; why?: string }
28
+ interface Open { id: string; at: number; death: Death; index: number }
29
+ /** A run as its newest launch or resume script says: the folder and the command a revive runs again. */
30
+ export interface Launch { name: string; id?: string; /** When its script was generated. */ at: number; folder: string; command: string; worktree?: { path?: string; branch?: string } }
31
+
32
+ export interface ChildRevive {
33
+ run: HerdrRun;
34
+ sleep: Sleep;
35
+ now(): number;
36
+ /** The launcher's session file, and every entry of its transcript. */
37
+ file(): string | undefined;
38
+ entries(): Entry[];
39
+ /** The launcher's own pane, beside which a revived run opens. */
40
+ pane(): string | undefined;
41
+ sessions(): Promise<Session[]>;
42
+ /** A tower launches no subagents and revives none. */
43
+ active(): boolean;
44
+ type: string;
45
+ remember(data: Record<string, unknown>): void;
46
+ /** Hands the launcher's model a message; `wake` starts a turn. Throws when the session cannot take it. */
47
+ deliver(customType: string, text: string, details: Record<string, unknown>, wake: boolean): void;
48
+ tell(text: string, level?: "info" | "warning"): void;
49
+ note?(text: string): void;
50
+ /** How long the revived pi has to show in its pane (60 s). */
51
+ startMs?: number;
52
+ }
53
+
54
+ const q = (value: string) => `'${value.replace(/'/g, "'\\''")}'`;
55
+ const unq = (value: string) => value.replace(/'\\''/g, "'");
56
+ const isDir = (path: string) => { try { return statSync(path).isDirectory(); } catch { return false; } };
57
+ const safeName = (name: string) => name.replace(/[^\w.-]+/g, "-").slice(0, 48) || "subagent";
58
+ const said = (name: string) => JSON.stringify(line(name).slice(0, 60));
59
+
60
+ /** The newest launch or resume script of `launcher` whose header names `file`, read for a revive; a string is why it cannot be. */
61
+ export function launchOf(launcher: string, file: string): Launch | string {
62
+ // Only the run's own first launch and the resumes can name its file: a launcher with a thousand scripts reads a few headers, not every script.
63
+ const dir = join(artifacts(launcher), "subagent-scripts"), run = RUN.exec(basename(file))?.[1];
64
+ let found: { path: string; at: number } | undefined;
65
+ try {
66
+ for (const name of readdirSync(dir)) {
67
+ if (!name.endsWith(".sh") || (run && !name.endsWith(`-${run}.sh`) && !name.includes("-resume-"))) continue;
68
+ const top = head(join(dir, name), 4096);
69
+ if (/^# Session: (.+)$/m.exec(top)?.[1]?.trim() !== file) continue;
70
+ const at = Date.parse(/^# Generated: (.+)$/m.exec(top)?.[1] ?? "") || 0;
71
+ if (!found || at >= found.at) found = { path: join(dir, name), at };
72
+ }
73
+ } catch { /* no script folder */ }
74
+ if (!found) return "no launch script of this session names its session file";
75
+ let text: string;
76
+ try { text = readFileSync(found.path, "utf8"); } catch { return "its launch script cannot be read"; }
77
+ const name = /^# Subagent (?:launch|resume) script for (.+)$/m.exec(text)?.[1]?.trim() ?? "subagent";
78
+ if (/\bPI_SUBAGENT_PERSISTENT=1\b/.test(text)) return "it is a persistent specialist, which pi-herdr-agents cannot take back: launch a new one";
79
+ const command = text.split("\n").filter((l) => l.trim() && !l.startsWith("#")).at(-1) ?? "";
80
+ // A fork run carries its task inline (maestro taskDelivery "direct"): kept, the revived pi would start the task over (review RV-F004). Only a resume may take the notice appended.
81
+ if (/^# Subagent launch script/m.test(text) && command.endsWith(TAIL) && !/ '@(?:[^']|'\\'')*'$/.test(command.slice(0, -TAIL.length))) return "its task is inline in its launch command (a fork run), which a revive would start over";
82
+ // maestro's own shape (buildPiCommand, launch-resume): anything else would be edited on a guess.
83
+ if (!command.endsWith(TAIL) || !/(?:^|\s)pi --session /.test(command)) return "its launch command is not one Straw Boss knows how to start again";
84
+ const cd = /^cd '((?:[^']|'\\'')*)' && /.exec(command), folder = cd ? unq(cd[1]!) : sessionHeader(file)?.cwd;
85
+ if (!folder || !isDir(folder)) return `its folder ${folder ?? "(none)"} is gone`;
86
+ const policy = readJson(`${file}.pi-herdr-subagent-policy.json`) as { worktree?: { path?: unknown; branch?: unknown } };
87
+ const worktree = policy.worktree && typeof policy.worktree === "object" ? { ...(typeof policy.worktree.path === "string" ? { path: policy.worktree.path } : {}), ...(typeof policy.worktree.branch === "string" ? { branch: policy.worktree.branch } : {}) } : undefined;
88
+ const id = /\bPI_SUBAGENT_ID='([^']*)'/.exec(command)?.[1];
89
+ return { name, at: found.at, folder, command: cd ? command : `cd ${q(folder)} && ${command}`, ...(id ? { id } : {}), ...(worktree ? { worktree } : {}) };
90
+ }
91
+
92
+ /** The launch command with the revive notice as its first message instead of the task, and the pane it runs in. */
93
+ export function reviveCommand(launch: Launch, notice: string, pane: string): string {
94
+ let body = launch.command.slice(0, -TAIL.length);
95
+ const last = / '((?:[^']|'\\'')*)'$/.exec(body), arg = q(`@${notice}`);
96
+ body = last && last[1]!.startsWith("@") ? `${body.slice(0, last.index)} ${arg}` : `${body} ${arg}`;
97
+ return body.replace(/\bPI_SUBAGENT_SURFACE='(?:[^']|'\\'')*'/, `PI_SUBAGENT_SURFACE=${q(pane)}`) + TAIL;
98
+ }
99
+
100
+ /** The first `bytes` of a file, or nothing when it cannot be read. */
101
+ function head(file: string, bytes: number): string {
102
+ try {
103
+ const fd = openSync(file, "r");
104
+ try {
105
+ const buffer = Buffer.alloc(bytes), n = readSync(fd, buffer, 0, bytes, 0);
106
+ return buffer.subarray(0, n).toString("utf8");
107
+ } finally {
108
+ closeSync(fd);
109
+ }
110
+ } catch {
111
+ return "";
112
+ }
113
+ }
114
+ /** Whether pi wrote any message into the session: one that never started failed to launch, and would fail again. */
115
+ const started = (file: string) => head(file, HEAD).includes('"type":"message"');
116
+
117
+ const worktreeWords = (l: Launch) => (l.worktree ? ` It is a managed worktree run (worktree ${l.worktree.path ?? "unknown"}, branch ${l.worktree.branch ?? "unknown"}), which subagent_resume refuses: launch a new run there instead.` : "");
118
+ const resumeWords = (name: string, file: string, l?: Launch) => (l?.worktree ? worktreeWords(l) : ` Resume it with subagent_resume {sessionPath: ${JSON.stringify(file)}, name: ${said(name)}, message: ${JSON.stringify(FOLLOW)}}, or launch a new run.`);
119
+ /** The paragraph a death's failure gets before the launcher's model reads it. */
120
+ export const noteText = (death: Death) =>
121
+ `${NOTE}${said(death.name)}'s own: ${death.why}. Straw Boss revives it from its session file in about a minute, once a second look shows nothing else runs it, in a new pane of your tab, and brings its report here. Do not resume, respawn, or cancel it meanwhile, and launch no replacement; go on with other work. If it cannot be revived, Straw Boss says so here.`;
122
+
123
+ type Looks = Map<string, { first: number; looks: number }>;
124
+ const counted = (looks: Looks, key: string, now: number) => looks.get(key) ?? { first: now, looks: 0 };
125
+ const count = (looks: Looks, key: string, now: number) => void looks.set(key, ((was) => ({ first: was.first, looks: was.looks + 1 }))(counted(looks, key, now)));
126
+ /** What Herdr, the broker, and the disk say of a session file now: the facts childdead.ts `classify` weighs. */
127
+ function factsOf(file: string, ps: Pane[], list: Session[] | undefined) {
128
+ const id = sessionHeader(file)?.id, holder = ps.find((p) => p.agent_session?.value === file);
129
+ let mtimeMs: number | undefined;
130
+ try { mtimeMs = statSync(file).mtimeMs; } catch { /* gone */ }
131
+ return { holder, held: Boolean(holder), listed: Boolean(id && list?.some((s) => s.id === id)), ...(mtimeMs !== undefined ? { mtimeMs } : {}) };
132
+ }
133
+
134
+ export function childRevive(d: ChildRevive) {
135
+ // The looks that found a death dead (`seen`), held by someone else (`taken`), and a revived pi gone (`gone`); a reload starts them again.
136
+ const seen: Looks = new Map(), gone: Looks = new Map();
137
+ const closing = new Map<string, { pane: string; looks: number }>();
138
+ let busy = false, stopped = false;
139
+
140
+ /** The last mark of each death, as the session's entries say. */
141
+ const marksOf = (): Map<string, Mark> => {
142
+ const out = new Map<string, Mark>();
143
+ for (const e of d.entries()) {
144
+ const m = e.type === "custom" && e.customType === d.type ? (e.data as Record<string, unknown> | undefined)?.[KEY] as Mark | undefined : undefined;
145
+ if (m && typeof m.death === "string" && typeof m.file === "string") out.set(m.death, m);
146
+ }
147
+ return out;
148
+ };
149
+ /** The deaths the transcript holds: failures that childdead.ts reads as a pi that ended without a report. */
150
+ const deaths = (all: Entry[]): Open[] => all.flatMap((e, index) => {
151
+ const death = e.type === "custom_message" && e.customType === RESULT_TYPE && e.id ? deathOf(e.details) : undefined;
152
+ return death ? [{ id: e.id!, at: Date.parse(e.timestamp ?? "") || d.now(), death, index }] : [];
153
+ });
154
+ /** Why a death is no longer the run's last word (review RV-F001, RV-F002): a later result, ping, or script names its file. Someone else has it: no word to the model (RV2-F001). */
155
+ const superseded = (o: Open, all: Entry[], launch: Launch | string): string | undefined => {
156
+ if (all.slice(o.index + 1).some((e) => e.type === "custom_message" && FINALS.has(e.customType ?? "") && (e.details as { sessionFile?: unknown } | undefined)?.sessionFile === o.death.file)) return "a later result or ping names its session file";
157
+ if (typeof launch !== "string" && launch.at > o.at) return "a launch or resume script newer than its death names its session file";
158
+ return undefined;
159
+ };
160
+ /** Whether the failure carried the paragraph that promised a revive (`annotate`). */
161
+ const noted = (e: Entry | undefined) => JSON.stringify(e?.content ?? "").includes(NOTE.slice(0, -1));
162
+ /** Why a death may not be revived, from the files and the marks alone; undefined when it may. */
163
+ const refusal = (death: Death, at: number, marks: Map<string, Mark>, launch: Launch | string): string | undefined => {
164
+ if (typeof launch === "string") return launch;
165
+ if (!started(death.file)) return "its session never started: that is a launch failure, which a revive would repeat";
166
+ const mine = [...marks.values()].filter((m) => m.file === death.file);
167
+ if (mine.some((m) => m.step === "failed" && at - m.at < DAY_MS)) return "a revive of it failed in the last 24 hours";
168
+ if (mine.some((m) => (m.step === "revived" || m.step === "delivered") && at - m.at < LOOP_MS)) return "it died again within 10 minutes of a revive";
169
+ return undefined;
170
+ };
171
+ const mark = (m: Mark) => d.remember({ [KEY]: m });
172
+ const send = (customType: string, text: string, details: Record<string, unknown>, wake: boolean) => {
173
+ try {
174
+ d.deliver(customType, text, details, wake);
175
+ } catch (error) {
176
+ d.tell(`Straw Boss: could not tell this session: ${(error as Error).message}`, "warning");
177
+ }
178
+ };
179
+
180
+ async function revive(o: Open, launcher: string, launch: Launch): Promise<void> {
181
+ const { death } = o, base = { death: o.id, file: death.file, name: launch.name };
182
+ mark({ ...base, step: "reviving", at: d.now() });
183
+ let pane: string | undefined;
184
+ const close = async () => void (pane && (await d.run(["pane", "close", pane]).catch(() => {})));
185
+ const fail = async (why: string) => {
186
+ await close();
187
+ mark({ ...base, step: "failed", at: d.now(), why });
188
+ send(REVIVED, `Straw Boss: could not revive subagent ${said(launch.name)} (sessionPath ${death.file}), whose pi died (${death.why}): ${why}. Straw Boss does not try again.${resumeWords(launch.name, death.file, launch)}`, { name: launch.name, sessionFile: death.file }, true);
189
+ d.tell(`Straw Boss: could not revive subagent ${launch.name}: ${why}`, "warning");
190
+ };
191
+ const holder = async () => {
192
+ const p = (await panes(d.run)).find((x) => x.agent_session?.value === death.file && x.pane_id !== pane);
193
+ const id = sessionHeader(death.file)?.id, fresh = launchOf(launcher, death.file);
194
+ // A resume pi-herdr-agents started since the look is in its registry before its pane shows the file (review RV-F006).
195
+ if (typeof fresh !== "string" && fresh.at > launch.at) return "a newer launch or resume script names its session file";
196
+ const ids = [launch.id, typeof fresh === "string" ? undefined : fresh.id].filter((x): x is string => Boolean(x));
197
+ if (ids.some((x) => tracked()?.has(x))) return "pi-herdr-agents runs it again";
198
+ return p ? `pane ${p.pane_id} runs its session now` : id && (await d.sessions().catch(() => [])).some((s) => s.id === id) ? "the broker lists its session now" : undefined;
199
+ };
200
+ try {
201
+ const lead = d.pane();
202
+ if (!lead || !(await panes(d.run)).some((p) => p.pane_id === lead)) return await fail("Herdr does not list this session's own pane, so there is no tab to open it in");
203
+ pane = (await result(d.run, ["pane", "split", lead, "--direction", "right", "--cwd", launch.folder, "--no-focus"])).pane.pane_id as string;
204
+ await d.run(["pane", "rename", pane, launch.name]).catch(() => {});
205
+ mark({ ...base, step: "reviving", at: d.now(), pane }); // a reload can close it (review RV-F005)
206
+ // Once more, just before pi starts: two pis on one session file corrupt it.
207
+ const other = await holder();
208
+ if (other) {
209
+ await close();
210
+ mark({ ...base, step: "skipped", at: d.now(), why: other });
211
+ return send(REVIVED, `Straw Boss: did not revive subagent ${said(launch.name)} (sessionPath ${death.file}): ${other}. Its result goes to whoever runs it.`, { name: launch.name, sessionFile: death.file }, false);
212
+ }
213
+ const dir = join(artifacts(launcher), "straw-boss-revive"), stamp = new Date(d.now()).toISOString().replace(/[:.]/g, "-");
214
+ mkdirSync(dir, { recursive: true });
215
+ const notice = join(dir, `${safeName(launch.name)}-${stamp}.md`), script = join(dir, `${safeName(launch.name)}-${launch.id ?? "run"}-${stamp}.sh`);
216
+ const cut = cutOf(death.file);
217
+ writeFileSync(notice, `Straw Boss: your pi died (${death.why}) while you were working on the task your launcher gave you, and Straw Boss revived you from your session file, in a new pane, with the same model and folder. Your launcher waits for your report.${cut ? ` Your last turn was cut: ${describe(cut)} (your last recorded step was at ${cut.at}).` : ""} Read your session so far, check the current state before re-running anything that changes state (a command may have run halfway), then finish the task you were given and report your result.`);
218
+ writeFileSync(script, `#!/bin/bash\n# Straw Boss revive script for ${launch.name}\n# Generated: ${new Date(d.now()).toISOString()}\n# Session: ${death.file}\n# Surface: ${pane}\n${reviveCommand(launch, notice, pane)}\n`, { mode: 0o755 });
219
+ if (stopped) return await close(); // a reload: the next start gives it up from its `reviving` step
220
+ await d.run(["pane", "run", pane, `bash ${q(script)}`]);
221
+ const limit = d.now() + (d.startMs ?? START_MS);
222
+ let up = false;
223
+ while (!up && !stopped && d.now() <= limit) {
224
+ up = (await panes(d.run).catch(() => [] as Pane[])).some((p) => p.pane_id === pane && p.agent_session?.value === death.file);
225
+ if (!up) await d.sleep(1000);
226
+ }
227
+ if (stopped && !up) return; // the next start reads the `reviving` step
228
+ if (!up) return await fail(`pi did not start on its session in pane ${pane} within ${Math.round((d.startMs ?? START_MS) / 1000)} s`);
229
+ } catch (error) {
230
+ return await fail((error as Error).message.slice(0, 300));
231
+ }
232
+ // From here the run is back: what tells of it may fail, and never undoes it (a live check closed a revived pane over a notice that threw).
233
+ mark({ ...base, step: "revived", at: d.now(), pane });
234
+ const where = launch.worktree ? `, in its worktree ${launch.worktree.path ?? launch.folder}${launch.worktree.branch ? ` (branch ${launch.worktree.branch})` : ""}` : "";
235
+ send(REVIVED, `Straw Boss: subagent ${said(launch.name)} died (${death.why}) and was revived from its session file in pane ${pane} of this tab, with its own model, folder${where}, and tools. It goes on with its task, and its report comes here when it ends. Do not resume or respawn it.`, { name: launch.name, sessionFile: death.file, pane }, false);
236
+ for (const tell of [() => d.tell(`Straw Boss: revived subagent ${launch.name} in pane ${pane} after its pi died (${death.why})`), () => d.note?.(`subagent ${line(launch.name).slice(0, 60)} died (${death.why}) and was revived in pane ${pane}`)]) try { tell(); } catch { /* a notice only */ }
237
+ }
238
+
239
+ /** A revived run: its `.exit` delivered, or its second death told. */
240
+ function watch(m: Mark, ps: Pane[], list: Session[] | undefined, now: number): void {
241
+ const exit = `${m.file}.exit`;
242
+ if (existsSync(exit)) {
243
+ const x = readJson(exit) as { type?: unknown; message?: unknown; errorMessage?: unknown };
244
+ if (typeof x.type !== "string") return; // read mid-write: the next look reads it whole (review RV-F007)
245
+ const type = x.type === "ping" || x.type === "error" ? x.type : "done";
246
+ mark({ ...m, step: "delivered", at: now });
247
+ const launch = launchOf(d.file() ?? "", m.file);
248
+ const head = `Straw Boss: subagent ${said(m.name)}, which Straw Boss revived after its pi died, `;
249
+ const text = type === "ping"
250
+ ? `${head}asked for help (sessionPath ${m.file}). pi-herdr-agents no longer watches it, so Straw Boss brings this. Its question:\n${encoded(m.name, typeof x.message === "string" ? x.message : "")}\n${typeof launch !== "string" && launch.worktree ? worktreeWords(launch).trim() : `Answer it with subagent_resume {sessionPath: ${JSON.stringify(m.file)}, name: ${said(m.name)}, message: <your answer>}.`}`
251
+ : `${head}finished${type === "error" ? " with an error" : ""} (sessionPath ${m.file}). pi-herdr-agents no longer watches it, so Straw Boss brings its result.${type === "error" && typeof x.errorMessage === "string" ? ` Its error: ${line(x.errorMessage).slice(0, 400)}.` : ""} Its last message, which is its report:\n${encoded(m.name, lastText(m.file))}`;
252
+ send(RESULT, text, { name: m.name, sessionFile: m.file, kind: type === "ping" ? "ping" : "finished", revived: true }, true);
253
+ rmSync(exit, { force: true }); // pi-herdr-agents' watcher consumes it too
254
+ if (m.pane) closing.set(m.file, { pane: m.pane, looks: 0 });
255
+ return void gone.delete(m.death);
256
+ }
257
+ const verdict = classify({ now, ...factsOf(m.file, ps, list), seen: counted(gone, m.death, now) });
258
+ if (verdict.state === "live") return void gone.delete(m.death);
259
+ if (verdict.state === "confirming") return count(gone, m.death, now);
260
+ gone.delete(m.death);
261
+ mark({ ...m, step: "failed", at: now, why: "it ended again without a report" });
262
+ const launch = launchOf(d.file() ?? "", m.file);
263
+ send(REVIVED, `Straw Boss: subagent ${said(m.name)}, which Straw Boss revived after its pi died, ended again without a report: its pi is gone and left no .exit. Straw Boss revives a run once and does not try again. Its last message:\n${encoded(m.name, lastText(m.file))}\n${resumeWords(m.name, m.file, typeof launch === "string" ? undefined : launch).trim()}`, { name: m.name, sessionFile: m.file }, true);
264
+ d.tell(`Straw Boss: subagent ${m.name} ended again after its revive, without a report`, "warning");
265
+ if (m.pane) closing.set(m.file, { pane: m.pane, looks: 0 });
266
+ }
267
+
268
+ async function poll(): Promise<void> {
269
+ const launcher = d.file();
270
+ if (busy || stopped || !launcher || !d.active()) return;
271
+ busy = true;
272
+ try {
273
+ const marks = marksOf(), now = d.now(), all = d.entries();
274
+ const open = deaths(all).filter((o) => !marks.has(o.id));
275
+ // A revive a reload cut off: back when a pane runs the file, given up when none does.
276
+ const cutOff = [...marks.values()].filter((m) => m.step === "reviving");
277
+ const revived = [...marks.values()].filter((m) => m.step === "revived");
278
+ if (!open.length && !cutOff.length && !revived.length && !closing.size) return;
279
+ const ps = await panes(d.run);
280
+ const list = open.length || revived.length ? await d.sessions().catch(() => undefined) : undefined;
281
+ for (const [file, c] of closing) {
282
+ const p = ps.find((x) => x.pane_id === c.pane);
283
+ if (!p || ++c.looks > CLOSE_LOOKS) closing.delete(file);
284
+ else if (!p.agent) (closing.delete(file), await d.run(["pane", "close", c.pane]).catch(() => {}));
285
+ }
286
+ for (const m of cutOff) {
287
+ const p = ps.find((x) => x.agent_session?.value === m.file);
288
+ if (p) mark({ ...m, step: "revived", at: now, pane: p.pane_id });
289
+ else if (now - m.at < (d.startMs ?? START_MS)) continue; // its pi may still be starting
290
+ else {
291
+ if (m.pane) await d.run(["pane", "close", m.pane]).catch(() => {});
292
+ mark({ ...m, step: "failed", at: now, why: "the revive was cut off before its pi started" });
293
+ send(REVIVED, `Straw Boss: the revive of subagent ${said(m.name)} (sessionPath ${m.file}) was cut off before its pi started (this session reloaded). Straw Boss does not try again.${resumeWords(m.name, m.file)}`, { name: m.name, sessionFile: m.file }, true);
294
+ }
295
+ }
296
+ for (const m of revived) watch(m, ps, list, now);
297
+ const live = tracked();
298
+ for (const o of open) {
299
+ if (stopped) return;
300
+ const launch = launchOf(launcher, o.death.file), facts = factsOf(o.death.file, ps, list);
301
+ const later = superseded(o, all, launch);
302
+ if (later) {
303
+ seen.delete(o.id);
304
+ mark({ death: o.id, file: o.death.file, name: o.death.name, step: "skipped", at: now, why: later });
305
+ d.tell(`Straw Boss: does not revive subagent ${o.death.name}: ${later}`);
306
+ continue;
307
+ }
308
+ // Old when first seen: a transcript from before this version (review RV-F001).
309
+ const old = counted(seen, o.id, now).first - o.at > LOOP_MS ? "its death is older than 10 minutes, from before Straw Boss looked" : undefined;
310
+ const why = old ?? refusal(o.death, o.at, marks, launch) ?? (facts.mtimeMs === undefined ? "its session file is gone" : undefined);
311
+ // pi-herdr-agents tracking the run's id again (a resume of its own) holds it as a pane does.
312
+ const owned = typeof launch !== "string" && launch.id !== undefined && live?.has(launch.id) === true;
313
+ const verdict = classify({ now, ...facts, ...(why ? { refusal: why } : {}), held: facts.held || owned, seen: counted(seen, o.id, now) });
314
+ if (verdict.state === "refused") {
315
+ seen.delete(o.id);
316
+ mark({ death: o.id, file: o.death.file, name: o.death.name, step: "skipped", at: now, why: verdict.reason });
317
+ d.tell(`Straw Boss: does not revive subagent ${o.death.name}: ${verdict.reason}`);
318
+ // The paragraph said Straw Boss would say so here (review RV-F008).
319
+ if (noted(all[o.index])) send(REVIVED, `Straw Boss: will not revive subagent ${said(o.death.name)} (sessionPath ${o.death.file}) after all: ${verdict.reason}.${resumeWords(o.death.name, o.death.file, typeof launch === "string" ? undefined : launch)}`, { name: o.death.name, sessionFile: o.death.file }, true);
320
+ continue;
321
+ }
322
+ if (verdict.state === "live") {
323
+ seen.delete(o.id);
324
+ // Held by a pane, listed by the broker, or tracked again: someone runs it (the launcher's own resume, a restore, the boss), and that run, not this death, ends it (review RV-F002).
325
+ if (!facts.held && !facts.listed && !owned) continue;
326
+ mark({ death: o.id, file: o.death.file, name: o.death.name, step: "skipped", at: now, why: verdict.reason });
327
+ send(REVIVED, `Straw Boss: did not revive subagent ${said(o.death.name)} (sessionPath ${o.death.file}): ${facts.holder ? `pane ${facts.holder.pane_id} runs its session again` : verdict.reason}. Its result goes to whoever runs it.`, { name: o.death.name, sessionFile: o.death.file }, false);
328
+ continue;
329
+ }
330
+ if (verdict.state === "confirming") {
331
+ count(seen, o.id, now);
332
+ continue;
333
+ }
334
+ seen.delete(o.id);
335
+ await revive(o, launcher, launch as Launch);
336
+ }
337
+ } catch { /* a Herdr that cannot answer is asked again at the next look */ } finally {
338
+ busy = false;
339
+ }
340
+ }
341
+
342
+ /** The failure of a death, with the paragraph that tells the launcher's model Straw Boss revives it (pi's `message_end`); undefined leaves the message as it is. */
343
+ function annotate<M extends { role?: string; customType?: string; content?: unknown; details?: unknown }>(message: M): M | undefined {
344
+ const launcher = d.file();
345
+ if (!launcher || !d.active() || message.role !== "custom" || message.customType !== RESULT_TYPE) return undefined;
346
+ const death = deathOf(message.details);
347
+ if (!death || refusal(death, d.now(), marksOf(), launchOf(launcher, death.file))) return undefined;
348
+ const note = noteText(death);
349
+ const content = typeof message.content === "string" ? `${message.content}\n\n${note}` : Array.isArray(message.content) ? [...message.content, { type: "text", text: note }] : note;
350
+ return { ...message, content };
351
+ }
352
+
353
+ return { poll, annotate, stop: () => void (stopped = true) };
354
+ }
package/src/session.ts CHANGED
@@ -14,6 +14,7 @@ import type { MainDuty } from "./mainduty.ts";
14
14
  import { orphans } from "./orphan.ts";
15
15
  import { createWorkerCap, deviceRoom } from "./workercap.ts";
16
16
  import { inherited, RESULT } from "./inherit.ts";
17
+ import { childRevive } from "./childrevive.ts";
17
18
  import { keyOf, REVIVE_TOKEN } from "./revive.ts";
18
19
  import { armSignals, signalSeen } from "./signalseen.ts";
19
20
  import { restored } from "./restored.ts";
@@ -48,12 +49,13 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
48
49
  pi.appendEntry(ENTRY, { revived: cfg.now() });
49
50
  return true;
50
51
  };
51
- let nudges: ReturnType<typeof orphans> | undefined, restores: ReturnType<typeof restored> | undefined, inherits: ReturnType<typeof inherited> | undefined, nudgeTimer: ReturnType<typeof setInterval> | undefined, unwatch: (() => void) | undefined, retryTimer: ReturnType<typeof setTimeout> | undefined;
52
+ let nudges: ReturnType<typeof orphans> | undefined, restores: ReturnType<typeof restored> | undefined, revives: ReturnType<typeof childRevive> | undefined, inherits: ReturnType<typeof inherited> | undefined, nudgeTimer: ReturnType<typeof setInterval> | undefined, unwatch: (() => void) | undefined, retryTimer: ReturnType<typeof setTimeout> | undefined;
52
53
  const stopWatching = () => {
53
54
  clearInterval(nudgeTimer);
54
55
  clearTimeout(retryTimer);
55
56
  nudges?.stop();
56
57
  restores?.stop();
58
+ revives?.stop();
57
59
  inherits?.stop();
58
60
  inherits = undefined;
59
61
  unwatch?.();
@@ -145,6 +147,8 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
145
147
  nudges = orphans({ run, file: () => log.getSessionFile(), entries: () => log.getEntries(), sessions: host.sessions, send: reach.send, type: ENTRY, remember: (key) => pi.appendEntry(ENTRY, { nudged: key }), me, tell });
146
148
  // Subagents a Herdr restart brought back as plain pi sessions are closed, and this session is asked to resume them (restored.ts).
147
149
  restores = restored({ run, sleep: cfg.sleep, file: () => log.getSessionFile(), entries: () => log.getEntries(), active: () => !s.isTower, launcher: () => (me() ? { id: me(), name: who() } : undefined), sessions: host.sessions, send: reach.send, type: ENTRY, remember: (data) => pi.appendEntry(ENTRY, data), resume: (text, details) => pi.sendMessage({ customType: RESUME, content: text, display: true, details }, { triggerTurn: true, deliverAs: "steer" }), tell });
150
+ // A subagent whose own pi died while this session lives is revived from its session file, and its result brought here (childrevive.ts).
151
+ revives = childRevive({ run, sleep: cfg.sleep, now: cfg.now, file: () => log.getSessionFile(), entries: () => log.getEntries(), pane: () => env.HERDR_PANE_ID, sessions: host.sessions, active: () => !s.isTower, type: ENTRY, remember: (data) => pi.appendEntry(ENTRY, data), deliver: (customType, text, details, wake) => pi.sendMessage({ customType, content: text, display: true, details }, wake ? { triggerTurn: true, deliverAs: "steer" } : { triggerTurn: false }), tell, note: (text) => void (s.at && note(text)) }); // a session that never joined has no workspace to note in
148
152
  // A session a tower revived picks up the subagents it launched before it died (inherit.ts), at its claim and at every start after (a /reload), until none is left to watch.
149
153
  startInherit = () => {
150
154
  if (inherits || s.isTower) return;
@@ -152,7 +156,7 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
152
156
  void inherits.poll();
153
157
  };
154
158
  if (typeof s.saved.revived === "number") startInherit();
155
- nudgeTimer = setInterval(() => void Promise.allSettled([nudges?.poll(), restores?.poll(), inherits?.poll()]), cfg.nudgeMs).unref();
159
+ nudgeTimer = setInterval(() => void Promise.allSettled([nudges?.poll(), restores?.poll(), revives?.poll(), inherits?.poll()]), cfg.nudgeMs).unref();
156
160
  // Starting runs in the background: pi awaits session_start handlers in turn, and pi-intercom connects in its own, after this one.
157
161
  const asTower = () => {
158
162
  s.trainSettled = true; // a tower is no train
@@ -319,6 +323,7 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
319
323
  pi.on("session_info_changed", (event) => void (!runMode.active() && mainDuty.migrate((event as { name?: string }).name)));
320
324
  pi.on("agent_settled", () => void (!runMode.active() && briefing.settled()));
321
325
  pi.on("message_end", (event) => void (!runMode.active() && briefing.delivered(event.message))); // a role steer counts as told once pi delivers it (briefing.ts `told`)
326
+ pi.on("message_end", (event) => ((message) => (message ? { message } : undefined))(revives?.annotate(event.message))); // a subagent's death says, before the model reads it, that it comes back
322
327
  // Compaction and tree navigation can remove earlier steers. Resend current guidance without touching the role section.
323
328
  pi.on("session_compact", (event) => void (!runMode.active() && briefing.fresh(event.willRetry)));
324
329
  pi.on("session_tree", () => void (!runMode.active() && briefing.fresh()));