pi-straw-boss 0.87.1 → 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.
@@ -11941,6 +11941,15 @@ var JOBS = 50;
11941
11941
  var DETAIL = 120;
11942
11942
  var num2 = (v, lo, hi) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi ? v : void 0;
11943
11943
  var capDir = (boardDir) => join30(dirname10(boardDir), "capacity");
11944
+ function readBudget(stateDir) {
11945
+ let b;
11946
+ try {
11947
+ b = JSON.parse(readFileSync19(join30(stateDir, "config.json"), "utf8")).capacity?.budget;
11948
+ } catch {
11949
+ return void 0;
11950
+ }
11951
+ return typeof b === "number" && Number.isFinite(b) && b > 0 && b <= 1e3 ? b : void 0;
11952
+ }
11944
11953
  var DEVICE = "_device.json";
11945
11954
  var SENT = "_sent.json";
11946
11955
  function writeJson2(dir, name2, value) {
@@ -22163,14 +22172,6 @@ function createCapWatch(d) {
22163
22172
  }
22164
22173
 
22165
22174
  // src/server/capops.ts
22166
- function readBudget(stateDir) {
22167
- try {
22168
- const b = JSON.parse(readFileSync36(join47(stateDir, "config.json"), "utf8")).capacity?.budget;
22169
- return typeof b === "number" && Number.isFinite(b) && b > 0 && b <= 1e3 ? b : void 0;
22170
- } catch {
22171
- return void 0;
22172
- }
22173
- }
22174
22175
  function armedLoop(dir, session, now) {
22175
22176
  if (!safeSession(session)) return false;
22176
22177
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-straw-boss",
3
- "version": "0.87.1",
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",
package/prompts/main.md CHANGED
@@ -1,6 +1,6 @@
1
1
  You are the main agent of Herdr tab {{tab}}, of kind {{duty}}: the boss works with you here.
2
2
 
3
- - Dispatch: split work by owning app ({{dir}}/apps-config.md); a task is one worker's end-to-end work in one app, a todo before its worker starts ({{dir}}/planning.md: plan, anchors). Dependent tasks wait (`blockedBy`); parallel writers get worktrees under `~/.herdr/worktrees/<repo>/<branch>` (elsewhere a child hangs on pi's trust prompt); work independent of your chain goes to subagents in parallel, up to the device's capacity budget (`board_read` `capacity`; none set: at most 4 workers at once). Idle with ready todos: dispatch them; none ready: take your next eligible work or report idle (`milestone`). A capacity notice on your work: dispatch its ready work now, or say why not (blocked, shared files, the boss): reply to whoever asked; sb's: board it.
3
+ - Dispatch: split work by owning app ({{dir}}/apps-config.md); a task is one worker's end-to-end work in one app, a todo before its worker starts ({{dir}}/planning.md: plan, anchors). Dependent tasks wait (`blockedBy`); parallel writers get worktrees under `~/.herdr/worktrees/<repo>/<branch>` (elsewhere pi's trust prompt hangs it); work independent of your chain goes to subagents in parallel, on an unattended device within its capacity budget (`board_read` `capacity`; an API-bound worker's todo may set `metadata.points` 0.25). Idle with ready todos: dispatch them; none ready: take your next eligible work or report idle (`milestone`). A capacity notice on your work: dispatch its ready work now, or say why not (blocked, shared files, the boss): reply to whoever asked; sb's: board it.
4
4
  - A result passing brief and anchor: todo `completed`, dispatch what it unblocked. A failed or cancelled task blocks its dependents: report them; settle the next step with the boss.
5
5
  - Write to agents terse, caveman-style: point first; keep negations, numbers, paths, IDs, and quoted decisions verbatim; full sentences where a fragment could mislead; a brief still carries its goal, context, reasons with their cause, scope, what others own, and acceptance check, or workers redo work; a reader unsure restates it or asks.
6
6
  - Brief workers in English: required behavior, the Reality anchor, the boss's authorizations quoted; cause and location are the worker's. End with: "When you need a decision these authorizations do not cover, or a rule you follow says to ask first, call `caller_ping` and stop." Answer pings via the boss; `subagent_resume`. Reviewed change: `boss_pair` worker and reviewer, brief both, dispatch both with `Thread: T<n>`; both results come when the thread closes; relay nothing.
@@ -19,8 +19,8 @@ For fan-out and orchestrator-worker, one todo per task:
19
19
  - `subject`: the required outcome.
20
20
  - `owner`: the subagent's name, or `self`.
21
21
  - `description`: the app, the worktree branch for a parallel writer, the anchor and who exercises it, and the exact artifact path a dependent will read.
22
- - `blockedBy`: the tasks whose output or landed change this one needs; the rest run in parallel up to the capacity budget (`board_read` `capacity`; else 4). Serialize only on a real dependency or shared files.
23
- - `metadata`: `{ "graph": "<a graph name from section 1, exactly>", "anchor": "...", "checkpoint": "own" | "<checkpoint todo id>", "points": <n> }`: its weight against the budget, as the boss or project weighs it (default 1).
22
+ - `blockedBy`: the tasks whose output or landed change this one needs; the rest run in parallel, on an unattended device within its capacity budget. Serialize only on a real dependency or shared files.
23
+ - `metadata`: `{ "graph": "<a graph name from section 1, exactly>", "anchor": "...", "checkpoint": "own" | "<checkpoint todo id>", "points": <n> }`: its weight against the budget, as the boss or project weighs it (default 1; 0.25 for a light, API-bound worker).
24
24
  - Defer: `metadata.until` (ISO) or `metadata.waitsOn` (person). Your monitor, loop or `boss_watch` prevents stale notices.
25
25
 
26
26
  ## 3. Name the anchors
package/src/capacity.ts CHANGED
@@ -54,6 +54,12 @@ export function pauseOf(data: unknown, now: number): { state: "paused"; pause: P
54
54
 
55
55
  /** `<state dir>/capacity`, beside the board folder (whose listing the board's readers and purge own). */
56
56
  export const capDir = (boardDir: string) => join(dirname(boardDir), "capacity");
57
+ /** `capacity.budget` of `<state dir>/config.json`: a number of points over 0 (at most 1000); none when it is unset or not such a number. Read at each call, so a change applies at once. */
58
+ export function readBudget(stateDir: string): number | undefined {
59
+ let b: unknown;
60
+ try { b = (JSON.parse(readFileSync(join(stateDir, "config.json"), "utf8")) as { capacity?: { budget?: unknown } }).capacity?.budget; } catch { return undefined; }
61
+ return typeof b === "number" && Number.isFinite(b) && b > 0 && b <= 1000 ? b : undefined;
62
+ }
57
63
  const DEVICE = "_device.json", SENT = "_sent.json";
58
64
  function writeJson(dir: string, name: string, value: unknown): void {
59
65
  mkdirSync(dir, { recursive: true, mode: 0o700 });
@@ -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/index.ts CHANGED
@@ -108,7 +108,7 @@ export function createStrawBoss({ run: given, world: reading, api = herdrApi(),
108
108
  closeSelf = createClosing(kit);
109
109
  const control = createCloseMain(kit, { closeSelf, check: bridge.stashCheck, turn: bridge.turn });
110
110
  const watch = createBossWatch(kit, { ask: cfg.ask ?? look?.ask, control, openTower: reach.openTower, remote: () => Boolean(link.remoteScope()) });
111
- registerSession(kit, { mainDuty, integration: createIntegrationWatch(kit), runMode, briefing, roles, presence, membership, guard, host, reach, digest, control, startTower: createTower(kit, { membership, presence, tools, control, digest, roles, reach }) });
111
+ registerSession(kit, { mainDuty, attended: () => link.attended(), integration: createIntegrationWatch(kit), runMode, briefing, roles, presence, membership, guard, host, reach, digest, control, startTower: createTower(kit, { membership, presence, tools, control, digest, roles, reach }) });
112
112
  trainGuard = registerTrainGuard(kit, cars.client, mainDuty);
113
113
  mainDuty.trainOn(() => Boolean(trainGuard)); // a train's todo and MonitorCreate calls, and the integrator's train todos (nothing loads with the merge train off)
114
114
  registerBoss(kit, { runMode, host, membership, reach, closeSelf, stashing: createStashing(kit, { host }), server: look, paths: createBossPaths(kit, { host, server: look, closeSelf, here: host.here }) });
@@ -2,7 +2,7 @@ import { readFileSync, statSync } from "node:fs";
2
2
  import { availableParallelism, homedir, loadavg } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { readEntries, safeSession } from "../board.ts";
5
- import { capDir, type MainFacts } from "../capacity.ts";
5
+ import { capDir, type MainFacts, readBudget } from "../capacity.ts";
6
6
  import { type HerdrRun, panes as herdrPanes, type Session, workspaces as herdrWorkspaces } from "../herdr.ts";
7
7
  import { commanding, sessionMark, subagentsOfAll } from "../netdata.ts";
8
8
  import { nameOf, netMembers } from "../reach.ts";
@@ -14,16 +14,6 @@ import type { Towers } from "./towers.ts";
14
14
  // The server's side of the capacity watch (capwatch.ts): what it reads of this machine (pi-intercom's list, Herdr's panes, the board and capacity files, the load, `capacity.budget`), and whom it tells:
15
15
  // the tower of the main's workspace (as the stall watch finds it), this device's standing main, and for `under` and `stale` the main itself. Kept out of main.ts, which carries a line budget.
16
16
 
17
- /** `capacity.budget` of `<state dir>/config.json`: a number of points over 0 (at most 1000); none when it is unset or not such a number. */
18
- export function readBudget(stateDir: string): number | undefined {
19
- try {
20
- const b = (JSON.parse(readFileSync(join(stateDir, "config.json"), "utf8")) as { capacity?: { budget?: unknown } }).capacity?.budget;
21
- return typeof b === "number" && Number.isFinite(b) && b > 0 && b <= 1000 ? b : undefined;
22
- } catch {
23
- return undefined;
24
- }
25
- }
26
-
27
17
  /** pi-loop-monitor persists loops-<pi-session-id>.json. No mutating store import; consume only the active flag and expiry. */
28
18
  export function armedLoop(dir: string, session: string, now: number): boolean {
29
19
  if (!safeSession(session)) return false;
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";
@@ -33,7 +34,7 @@ const CHECKING = "Straw Boss is still asking Herdr whether this is a sub workspa
33
34
  const UNPLACED = (why: string) => `Straw Boss could not tell whether this is a sub workspace: ${why}; it asks again`;
34
35
 
35
36
  /** What the session does at its start, around each run, and at its end. */
36
- export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles, presence, membership, guard, host, reach, digest, control, integration, startTower }: { mainDuty: MainDuty; runMode: RunMode; briefing: Briefing; roles: Roles; presence: Presence; membership: Membership; guard: Guard; host: ReturnType<typeof createHost>; reach: Reach; digest: Digest; control: Control; integration: IntegrationWatch; startTower(): Promise<void> }) {
37
+ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles, presence, membership, guard, host, reach, digest, control, integration, startTower, attended }: { mainDuty: MainDuty; runMode: RunMode; briefing: Briefing; roles: Roles; presence: Presence; membership: Membership; guard: Guard; host: ReturnType<typeof createHost>; reach: Reach; digest: Digest; control: Control; integration: IntegrationWatch; startTower(): Promise<void>; /** Whether a person is at this device (the link's policy): the worker cap holds only on an unattended one. */ attended(): boolean }) {
37
38
  const { pi, cfg, s, guiDir, me, role, tell } = kit;
38
39
  const { run, env, version } = cfg;
39
40
  const who = () => pi.getSessionName() || s.ownName || me().slice(0, 8);
@@ -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,13 +323,14 @@ 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()));
325
330
 
326
331
  // A member that dispatches or resumes a subagent without promoting is promoted here, before the subagent starts, unless the tab already has a main.
327
332
  // A tower only coordinates: it dispatches no subagent (one would outlive it with no one to take its result), and opens a main for the work instead.
328
- const cap = createWorkerCap(undefined, deviceRoom(guiDir, me));
333
+ const cap = createWorkerCap(deviceRoom(guiDir, me, attended));
329
334
  pi.on("turn_end", () => cap.settle());
330
335
  pi.on("tool_call", async (event, ctx) => {
331
336
  if (!SUBAGENT_TOOLS.includes(event.toolName) || runMode.active()) return;
@@ -346,7 +351,7 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
346
351
  tell(`Straw Boss: ${(error as Error).message}`, "warning");
347
352
  }
348
353
  mainDuty.migrate(pi.getSessionName()); // the promotion above may have just made this an `integ <project>` main whose migration had not run
349
- // No plan gates a worker (docs/specs/2026-11-23-lite-main.md §1); the cap does (§3): at most 4 workers of this session run at once, or, with a capacity budget, as many as the device's points allow (docs/specs/2026-11-24-capacity.md, The cap).
354
+ // No plan gates a worker (docs/specs/2026-11-23-lite-main.md §1) and no count does: only an unattended device with a capacity budget holds one back, by its points (docs/specs/2026-11-24-capacity.md, The cap).
350
355
  if (event.toolName === "subagent") return cap.admit(event.toolCallId, event.input, () => ctx.sessionManager.getBranch()); // the todo its `name` owns weighs it
351
356
  });
352
357
 
package/src/workercap.ts CHANGED
@@ -1,46 +1,43 @@
1
1
  import { join } from "node:path";
2
- import { capDir, DEFAULT_POINTS, nameKey, readDevice } from "./capacity.ts";
2
+ import { capDir, DEFAULT_POINTS, nameKey, readBudget, readDevice } from "./capacity.ts";
3
3
  import { createReservations, type Holder, type Reservations } from "./capres.ts";
4
4
  import { dutyOfAgent } from "./duty.ts";
5
5
  import { todosOf } from "./items.ts";
6
6
  import { snapshotScan } from "./todo.ts";
7
7
 
8
- // The cap on a session's concurrent workers (docs/specs/2026-11-23-lite-main.md §3): at most 4 `worker` subagents run at once, counted from pi-herdr-agents' registry of the children this process
9
- // launched and is still waiting on (orphan.ts `tracked` reads the same slot), plus the worker calls admitted in the message being prepared: pi prepares every tool call of an assistant message before any
10
- // runs, so the registry holds none of them yet. Scouts, planners, reviewers, and resumes are not workers and are never held. A registry that cannot be read holds nothing back.
8
+ // Worker admission (docs/specs/2026-11-24-capacity.md, The cap). sb holds back no worker by count: on an attended device (the boss's own, who watches it) nothing gates a worker, and its
9
+ // `capacity.budget` only feeds the board and the capacity notices. On an unattended device the device's points gate `worker` subagents against `capacity.budget`, read from config.json at
10
+ // each admission (a change applies at once; none set: no cap, and no built-in figure). Scouts, planners, reviewers, and resumes are not workers and are never held.
11
11
 
12
- export const WORKER_CAP = 4;
13
12
  const REGISTRY = Symbol.for("pi-subagents/runtime");
14
13
 
15
- /** The workers pi-herdr-agents runs for this process, or undefined when its registry cannot be read. */
16
- function runningWorkers(): number | undefined {
14
+ /** The names of the workers pi-herdr-agents runs for this process (its registry of the children it still waits on), or undefined when the registry cannot be read. */
15
+ function runningWorkers(): string[] | undefined {
17
16
  const map = (globalThis as Record<symbol, { runningSubagents?: unknown } | undefined>)[REGISTRY]?.runningSubagents;
18
17
  if (!(map instanceof Map)) return undefined;
19
- let n = 0;
20
- for (const run of map.values()) if (dutyOfAgent((run as { agent?: unknown } | null)?.agent as string | undefined) === "worker") n++;
21
- return n;
18
+ return [...map.values()].flatMap((run) => (dutyOfAgent((run as { agent?: string } | null)?.agent) === "worker" ? [String((run as { name?: unknown }).name ?? "")] : []));
22
19
  }
23
20
 
24
- /** The device's capacity as the sb server last wrote it (capacity.ts `readDevice`): points in use, the budget when one is set, when the row was sampled, and the mains it sampled with their running workers. */
25
- export interface Room { points: number; budget?: number | undefined; at?: number; mains?: readonly { session: string; workers?: readonly string[] }[] }
26
- /** What the cap reads of the device: its row, the reservations every main of it shares (capres.ts), and this main's session id. */
27
- export interface DeviceSide { room(): Room | undefined; store: Reservations; session(): string | undefined }
21
+ /** The device's capacity as the sb server last wrote it (capacity.ts `readDevice`): points in use, when the row was sampled, and the mains it sampled with their running workers. */
22
+ export interface Room { points: number; at?: number; mains?: readonly { session: string; workers?: readonly string[] }[] }
23
+ /** What the cap reads of the device: its fresh row, the reservations every main of it shares (capres.ts), this main's session id, the budget now, and whether a person is at it. */
24
+ export interface DeviceSide { room(): Room | undefined; store: Reservations; session(): string | undefined; budget(): number | undefined; attended(): boolean }
28
25
 
29
- // With a capacity budget (docs/specs/2026-11-24-capacity.md, The cap) the device's points decide instead of the count of 4: a worker starts while the points in use, the points the device's
30
- // reservations hold (launches of any main that no row shows yet), and its own fit the budget. Its reservation is written before the row and the sum are read, so two mains that launch at once
31
- // see each other. Only a main the row lists takes this path: the server samples the mains of its own Herdr slot, so a main of another slot, or one not sampled yet, keeps the count of 4 and
32
- // holds nothing device-wide. A device row that is missing or stale falls back to the count.
33
- /** The device row and reservations beside the board folder under `guiDir`, for the main whose session id `me` gives. */
34
- export const deviceRoom = (guiDir: string, me: () => string | undefined): DeviceSide => {
35
- const dir = capDir(join(guiDir, "board"));
36
- return { room: () => readDevice(dir, Date.now()), store: createReservations(dir, Date.now), session: me };
26
+ // A worker starts while the points in use, the points the device's reservations hold (launches of any main that no row shows yet), and its own fit the budget. Its reservation is written
27
+ // before the row and the sum are read, so two mains that launch at once see each other. The server samples only the mains of its own Herdr slot: a main the row does not list (another slot,
28
+ // not sampled yet) or any main while no fresh row exists still reserves device-wide, and adds its own running workers from its registry, which no row counts, in place of its own launched reservations.
29
+ /** The device row, reservations, and budget of the state folder `stateDir`, for the main whose session id `me` gives; `attended` says whether a person is at the device (the link's policy). */
30
+ export const deviceRoom = (stateDir: string, me: () => string | undefined, attended: () => boolean): DeviceSide => {
31
+ const dir = capDir(join(stateDir, "board"));
32
+ return { room: () => readDevice(dir, Date.now()), store: createReservations(dir, Date.now), session: me, budget: () => readBudget(stateDir), attended };
37
33
  };
38
34
  /** The row shows a launch: it lists the main's session with a running worker of the launch's (folded) name. */
39
35
  const shows = (r: Room, h: Holder) => h.worker !== "" && (r.mains?.find((m) => m.session === h.session)?.workers ?? []).some((w) => nameKey(w) === h.worker);
36
+ const sum = (xs: readonly number[]) => xs.reduce((n, x) => n + x, 0);
40
37
 
41
- export function createWorkerCap(cap = WORKER_CAP, device?: DeviceSide) {
42
- /** Worker calls admitted whose tool has not returned yet: the registry may not hold them. With a budget, each holds a reservation (its id). */
43
- const admitted = new Map<string, string | undefined>();
38
+ export function createWorkerCap(device?: DeviceSide) {
39
+ /** Worker calls admitted whose tool has not returned yet, each with its reservation's id. */
40
+ const admitted = new Map<string, string>();
44
41
  const snapshotOf = snapshotScan();
45
42
  /** The `metadata.points` of the main's own open todo whose `owner` is the subagent's `name` (read as capfill.ts reads the list), as the board's headroom weighs a ready todo; 1 without one. */
46
43
  const weight = (name: unknown, branch?: () => readonly unknown[]): number => {
@@ -51,32 +48,30 @@ export function createWorkerCap(cap = WORKER_CAP, device?: DeviceSide) {
51
48
  return (mine.find((t) => t.status === "in_progress") ?? mine[0])?.points ?? DEFAULT_POINTS;
52
49
  };
53
50
  return {
54
- /** pi's `tool_call` for `subagent`: a refusal when `input.agent` is a worker and the budget, or `cap` workers already run or are admitted, leave no room. `branch`: the main's session entries, for the todo's weight. */
51
+ /** pi's `tool_call` for `subagent`: on an unattended device with a budget, a refusal when `input.agent` is a worker the device's points leave no room for. `branch`: the main's session entries, for the todo's weight. */
55
52
  admit(toolCallId: string, input: unknown, branch?: () => readonly unknown[]): { block: true; reason: string } | undefined {
56
53
  const { agent, name } = (input ?? {}) as { agent?: unknown; name?: unknown };
57
- if (typeof agent !== "string" || dutyOfAgent(agent) !== "worker") return undefined;
58
- const me = device?.session(), listed = (r: Room | undefined): r is Room & { budget: number } => r?.budget !== undefined && me !== undefined && (r.mains ?? []).some((m) => m.session === me);
59
- if (device && listed(device.room())) {
60
- const need = weight(name, branch);
61
- let id: string | undefined, r: Room | undefined, held = 0;
62
- try {
63
- id = device.store.add(need, { session: me!, worker: typeof name === "string" ? nameKey(name) : "" });
64
- r = device.room(); // read after the reservation is published
65
- if (listed(r)) held = device.store.live(r.at ?? -Infinity, (h) => shows(r!, h)).filter((x) => x.id !== id).reduce((n, x) => n + x.points, 0);
66
- } catch (error) {
67
- try { if (id !== undefined) device.store.drop(id); } catch { /* it expires */ }
68
- return { block: true, reason: `sb: the device's capacity reservation could not be written (${(error as Error).message}): no worker starts until it can.` };
69
- }
70
- if (!listed(r)) device.store.drop(id); // the row went stale or no longer lists this main: the count of 4 below
71
- else if (r.points + held + need > r.budget) {
72
- device.store.drop(id);
73
- return { block: true, reason: `sb: the device runs ${r.points} of its ${r.budget} capacity points, ${Math.round(held * 100) / 100} more held by launches it does not count yet: this worker needs ${need}. Wait for a result, then dispatch the next; a scout, a planner, or a reviewer may run now.` };
74
- } else return void admitted.set(toolCallId, id);
54
+ if (typeof agent !== "string" || dutyOfAgent(agent) !== "worker" || !device || device.attended()) return undefined;
55
+ const budget = device.budget();
56
+ if (budget === undefined) return undefined;
57
+ const me = device.session() ?? "", need = weight(name, branch);
58
+ let id: string | undefined, used = 0, held = 0;
59
+ try {
60
+ id = device.store.add(need, { session: me, worker: typeof name === "string" ? nameKey(name) : "" });
61
+ const r = device.room(); // read after the reservation is published
62
+ const own = r?.mains?.some((m) => m.session === me) ? undefined : runningWorkers(); // no row counts this main's workers: its registry does
63
+ used = (r?.points ?? 0) + sum((own ?? []).map((w) => weight(w, branch)));
64
+ held = sum(device.store.live(r?.at ?? -Infinity, (h) => r !== undefined && shows(r, h)).filter((x) => x.id !== id && !(own && x.session === me && x.launched)).map((x) => x.points));
65
+ } catch (error) {
66
+ try { if (id !== undefined) device.store.drop(id); } catch { /* it expires */ }
67
+ return { block: true, reason: `sb: the device's capacity reservation could not be written (${(error as Error).message}): no worker starts until it can.` };
75
68
  }
76
- const running = runningWorkers();
77
- if (running === undefined) return undefined;
78
- if (running + admitted.size >= cap) return { block: true, reason: `sb: ${cap} workers run for this main already (${running} running, ${admitted.size} starting in this message): wait for a result, then dispatch the next; a scout, a planner, or a reviewer may run now.` };
79
- admitted.set(toolCallId, undefined);
69
+ if (used + held + need > budget) {
70
+ device.store.drop(id);
71
+ const pts = (n: number) => Math.round(n * 100) / 100;
72
+ return { block: true, reason: `sb: the device runs ${pts(used)} of its ${budget} capacity points, ${pts(held)} more held by launches it does not count yet: this worker needs ${need}. Wait for a result, then dispatch the next; a scout, a planner, or a reviewer may run now.` };
73
+ }
74
+ admitted.set(toolCallId, id);
80
75
  return undefined;
81
76
  },
82
77
  /** pi's `tool_result` for `subagent`: the launch ended, and the registry holds the worker if it started. A reservation stays for a launch that returned, and goes for one that failed. */
@@ -87,7 +82,7 @@ export function createWorkerCap(cap = WORKER_CAP, device?: DeviceSide) {
87
82
  },
88
83
  /** The turn ended: every call of it has run, or was blocked by another extension, which leaves no result: its reservation goes. */
89
84
  settle(): void {
90
- for (const id of admitted.values()) if (id !== undefined && device) try { device.store.drop(id); } catch { /* it expires */ }
85
+ for (const id of admitted.values()) if (device) try { device.store.drop(id); } catch { /* it expires */ }
91
86
  admitted.clear();
92
87
  },
93
88
  };