pi-straw-boss 0.113.2 → 0.114.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.113.2",
3
+ "version": "0.114.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",
@@ -49,10 +49,14 @@ A worker launched with `item` is drawn under its todo by pi-todo-ledger; one lau
49
49
 
50
50
  When a worker's pane closes or its pi dies before it reports, its failed result carries a line from Straw Boss with its name, session file and the `subagent_resume` call. Straw Boss does not revive or resume it: you decide, and resume it with a message saying what is left.
51
51
 
52
+ A child that sits idle after its turn without delivering a result is asked to finish by Straw Boss (10 minutes, at most twice). When it still has not reported, one `Subagent status` line tells you so: read its pane, then `subagent_cancel` it or answer what it waits for. Interactive children and persistent specialists are left alone. An auto-exit child is not asked (a fresh turn would close it as done); you get that line instead.
53
+
52
54
  ## Configuration
53
55
 
54
56
  The models live in `<agent dir>/herdr-agents/config.json` (default `~/.pi/agent/herdr-agents/config.json`), the same file pi-herdr-agents read: `models.default`, `models.agents`, `models.tasks` (ordered candidates per category), `models.tasksThinking`, plus `status`, `supervision`, `panes` and `spawning.maxDepth`. Edit it by hand and keep every other key; `/reload` after a change. Without the file the package's `config.json.example` supplies the non-model settings.
55
57
 
58
+ `subagentNudge` in `<agent dir>/straw-boss/config.json` (`{ "idleMinutes": 10, "max": 2 }`, `idleMinutes: 0` off) sets that nudge.
59
+
56
60
  `<agent dir>/straw-boss/host.json` with `{ "host": "off" }` turns the host off (`PI_STRAW_BOSS_HOST=off` for one process).
57
61
 
58
62
  ## When the tools are missing
package/src/host/child.ts CHANGED
@@ -1,8 +1,17 @@
1
1
  // Adapted from pi-herdr-agents f1590cb pi-extension/subagents/child.ts (MIT, Copyright (c) 2026 Giuseppe Rodriguez); see NOTICE.md.
2
2
  // The entry a child pi loads with `-e`. First, so a reload into another maestro build loads it fresh.
3
3
  import "./engine-build.ts";
4
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
5
  import { createChildExtension } from "@nubl/maestro/pi/child";
5
6
  import { renderChildWidget } from "./child-widget.ts";
7
+ import { nudgeInbox } from "./nudge-child.ts";
6
8
 
7
9
  export * from "@nubl/maestro/adapters/pi/child/protocol";
8
- export default createChildExtension(renderChildWidget);
10
+
11
+ const maestroChild = createChildExtension(renderChildWidget);
12
+
13
+ /** Maestro's child protocol, and the inbox of sb's done nudge (nudge-child.ts). */
14
+ export default function sbChild(pi: ExtensionAPI): void {
15
+ maestroChild(pi);
16
+ nudgeInbox(pi);
17
+ }
@@ -1,8 +1,10 @@
1
1
  // Adapted from pi-herdr-agents f1590cb pi-extension/subagents/index.ts, with the run rows of 2045e55 (MIT, Copyright (c) 2026 Giuseppe Rodriguez); see NOTICE.md.
2
2
  // First, so a reload into another maestro build loads it fresh.
3
3
  import "./engine-build.ts";
4
+ import { join } from "node:path";
4
5
  import { fileURLToPath } from "node:url";
5
6
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
7
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
8
  import { createPiExtension, maestroBuildInfo } from "@nubl/maestro/pi";
7
9
  import { loadAgentDefaults, resolveEffectivePersistent } from "@nubl/maestro/pi/subagents/catalog";
8
10
  import { hostSurfaceBinding } from "./host-surface.ts";
@@ -12,6 +14,8 @@ import { registerMessageRenderers } from "./renderers.ts";
12
14
  import { toolRenderers } from "./tool-renderers.ts";
13
15
  import { stampedLoad, stampedOnFailure, type StampSources } from "./load-stamp.ts";
14
16
  import { simpleApi } from "./surface.ts";
17
+ import { createNudger, readNudgeSettings, sharedNudgeStore } from "./nudge.ts";
18
+ import { localeOf } from "../locale.ts";
15
19
 
16
20
  /** The sb package root: the host stamps it as the wrapper, the way pi-herdr-agents stamps its own. */
17
21
  export const root = fileURLToPath(new URL("../../", import.meta.url)).replace(/[\\/]$/, "");
@@ -25,6 +29,8 @@ export const childEntryPath = fileURLToPath(new URL("./child.ts", import.meta.ur
25
29
  // and error-encoding APIs inherit from the one it was given), and a todo panel's claim on that presenter hides its rows from the Subagents box.
26
30
  const presenters = new WeakMap<ExtensionAPI, RunRows>();
27
31
  let registerRows: (pi: ExtensionAPI) => void = () => {};
32
+ /** The done nudge's notices a reload left unconfirmed go out at session start, with or without a run (widgets.ts, resumeNotices). */
33
+ let resumeNotices: (pi: ExtensionAPI) => void = () => {};
28
34
 
29
35
  // Invoked per load, not in the engine cache. Presentation never replaces a run owner.
30
36
  const extension = stampedOnFailure(
@@ -39,7 +45,12 @@ const extension = stampedOnFailure(
39
45
  presenters.set(pi, rows);
40
46
  rows.register(pi, deps.runtime.runningSubagents);
41
47
  };
42
- return createWidgetController(deps, presenters);
48
+ // sb's state folder, as the host entry reads it (index.ts): the done nudge's settings and the notice's language. Its store outlives a reload.
49
+ const stateDir = join(getAgentDir(), "straw-boss");
50
+ const nudger = createNudger({ settings: () => readNudgeSettings(stateDir), locale: () => localeOf(process.env, stateDir), store: sharedNudgeStore() });
51
+ const controller = createWidgetController(deps, presenters, nudger);
52
+ resumeNotices = controller.resumeNotices;
53
+ return controller;
43
54
  },
44
55
  registerMessageRenderers,
45
56
  toolRenderers,
@@ -63,5 +74,6 @@ export default function sbHost(pi: ExtensionAPI): void {
63
74
  stampedLoad(() => {
64
75
  extension(api);
65
76
  registerRows(api);
77
+ api.on("session_start", () => resumeNotices(api));
66
78
  }, stampSources);
67
79
  }
@@ -0,0 +1,177 @@
1
+ import { readdirSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { isChildBusy } from "@nubl/maestro/core/child-busy";
5
+ import { hasUndeliveredChildren } from "@nubl/maestro/core/undelivered-children";
6
+ import { ACK_MS, REQUEST_MS, ackFile, isRequestId, nudgeDir, nudgeText, readJson, requestFile, take, writeAtomic, type NudgeAck, type NudgeOutcome, type NudgeRequest } from "./nudge.ts";
7
+
8
+ // The child's half of the done nudge (docs/specs/2026-11-28-done-nudge.md): sb's child entry takes the parent's request from its run's folder beside its
9
+ // session file and sends the nudge into its own session with `pi.sendUserMessage` (the path Maestro's own done nudge and its persistent inbox use), only when
10
+ // it is idle, has no queued message, its input box holds no unsent text, and it waits on no subagent of its own. That call returns before pi takes the input,
11
+ // so `sent` is acked only once the nudge, marked with its request, enters the session as a user message within ACCEPT_MS. An auto-exit child sends
12
+ // nothing: a fresh turn there closes it as done. A request older than REQUEST_MS is `stale`, and no ack is written ACK_MS after its request, when the
13
+ // parent has stopped waiting for it (F007).
14
+
15
+ const POLL_MS = 2000;
16
+ /** A nudge sent that has not entered the session this long is acked `lost`. */
17
+ export const ACCEPT_MS = 30_000;
18
+
19
+ type Ctx = Pick<ExtensionContext, "isIdle" | "hasPendingMessages"> & {
20
+ ui?: { getEditorText?: () => string };
21
+ sessionManager?: { getSessionFile?: () => string | undefined };
22
+ };
23
+
24
+ export interface InboxCore {
25
+ /** The session file and the run id the child was launched with (`PI_SUBAGENT_SESSION`, `PI_SUBAGENT_ID`). */
26
+ file: string;
27
+ runId: string;
28
+ autoExit: boolean;
29
+ ctx: () => Ctx | undefined;
30
+ pi: Pick<ExtensionAPI, "sendUserMessage"> & { events?: ExtensionAPI["events"] };
31
+ undelivered?: () => boolean;
32
+ now?: () => number;
33
+ }
34
+
35
+ export interface Inbox {
36
+ /** Answers the open requests of this run, if any; returns the outcome of each answered. */
37
+ poll(): NudgeOutcome[];
38
+ /** A turn started: a request written before it is stale. */
39
+ turnStarted(): void;
40
+ /** A message entered the session: when it is the nudge in flight, `sent` is acked. */
41
+ messageStarted(message: unknown): void;
42
+ }
43
+
44
+ function textOf(message: unknown): string | undefined {
45
+ const m = message as { role?: unknown; content?: unknown } | undefined;
46
+ if (m?.role !== "user") return undefined;
47
+ if (typeof m.content === "string") return m.content;
48
+ if (!Array.isArray(m.content)) return undefined;
49
+ return m.content.filter((p: { type?: unknown }) => p?.type === "text").map((p: { text?: unknown }) => String(p.text ?? "")).join("\n");
50
+ }
51
+
52
+ /** The session the child is in now is the one it was launched with: after a `/resume` elsewhere, the inbox stands still. */
53
+ function onLaunchFile(ctx: Ctx | undefined, file: string): boolean {
54
+ try {
55
+ const current = ctx?.sessionManager?.getSessionFile?.();
56
+ return !!current && resolve(current) === resolve(file);
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+
62
+ export function createInbox(d: InboxCore): Inbox {
63
+ const dir = nudgeDir(d.file, d.runId);
64
+ const now = d.now ?? Date.now;
65
+ let lastTurnAt = -Infinity;
66
+ let inflight: { id: string; text: string; at: number; requested: number } | undefined;
67
+ /** `requested` is when the parent wrote the request: past ACK_MS the parent no longer waits, and an ack would only be left behind. */
68
+ const ack = (id: string, requested: number, outcome: NudgeOutcome) => {
69
+ if (now() - requested >= ACK_MS) return;
70
+ writeAtomic(ackFile(dir, id), { v: 2, id, runId: d.runId, outcome, at: now() } satisfies NudgeAck);
71
+ };
72
+
73
+ const outcomeOf = (ctx: Ctx): NudgeOutcome => {
74
+ try {
75
+ if (inflight || !ctx.isIdle() || ctx.hasPendingMessages()) return "busy";
76
+ if (ctx.ui?.getEditorText?.()?.trim()) return "draft";
77
+ if ((d.undelivered ?? hasUndeliveredChildren)() || isChildBusy(d.pi.events)) return "busy";
78
+ return "sent";
79
+ } catch {
80
+ // A context that cannot answer is not one to interrupt.
81
+ return "busy";
82
+ }
83
+ };
84
+
85
+ return {
86
+ poll() {
87
+ const ctx = d.ctx();
88
+ if (!ctx || !onLaunchFile(ctx, d.file)) return [];
89
+ if (inflight && now() - inflight.at >= ACCEPT_MS) {
90
+ const { id, requested } = inflight;
91
+ inflight = undefined;
92
+ ack(id, requested, "lost");
93
+ }
94
+ let names: string[];
95
+ try {
96
+ names = readdirSync(dir);
97
+ } catch {
98
+ return [];
99
+ }
100
+ const outcomes: NudgeOutcome[] = [];
101
+ for (const name of names.sort()) {
102
+ if (!name.endsWith(".req")) continue;
103
+ const id = name.slice(0, -4);
104
+ if (!isRequestId(id)) continue;
105
+ const req = readJson<NudgeRequest>(requestFile(dir, id));
106
+ // Consumed before it acts, so a slow send is never taken twice; one that is gone was revoked.
107
+ if (!req || !take(requestFile(dir, id))) continue;
108
+ // Another run's or another session's request is not this child's to answer.
109
+ if (req.v !== 2 || req.id !== id || req.runId !== d.runId || typeof req.sessionFile !== "string" || resolve(req.sessionFile) !== resolve(d.file)) continue;
110
+ const requested = typeof req.at === "number" && Number.isFinite(req.at) ? req.at : -Infinity;
111
+ let outcome: NudgeOutcome;
112
+ // One written before the latest turn, or long enough ago that its parent may have revoked it or gone.
113
+ if (requested <= lastTurnAt || now() - requested > REQUEST_MS) outcome = "stale";
114
+ else if (d.autoExit) outcome = "auto-exit";
115
+ else outcome = outcomeOf(ctx);
116
+ if (outcome === "sent") {
117
+ const text = nudgeText(typeof req.idleMs === "number" ? req.idleMs : 0, id);
118
+ inflight = { id, text, at: now(), requested };
119
+ try {
120
+ d.pi.sendUserMessage(text, { deliverAs: "followUp" });
121
+ } catch {
122
+ inflight = undefined;
123
+ ack(id, requested, "lost");
124
+ outcomes.push("lost");
125
+ continue;
126
+ }
127
+ // Acked when the nudge enters the session (messageStarted), or `lost` after ACCEPT_MS.
128
+ } else ack(id, requested, outcome);
129
+ outcomes.push(outcome);
130
+ }
131
+ return outcomes;
132
+ },
133
+ turnStarted() {
134
+ lastTurnAt = now();
135
+ },
136
+ messageStarted(message) {
137
+ // Only the nudge in flight carries its request's mark, so a message quoting an earlier reminder is not it. An input handler of another
138
+ // extension may wrap the text; one that rewrites it leaves the nudge `lost`, and so does one that enters after ACCEPT_MS (F008).
139
+ if (!inflight || !textOf(message)?.includes(inflight.text)) return;
140
+ const { id, at, requested } = inflight;
141
+ inflight = undefined;
142
+ ack(id, requested, now() - at >= ACCEPT_MS ? "lost" : "sent");
143
+ },
144
+ };
145
+ }
146
+
147
+ export interface InboxDeps { env?: NodeJS.ProcessEnv; pollMs?: number; undelivered?: () => boolean; now?: () => number }
148
+
149
+ /** Polls for the parent's request while the session runs. Not in a persistent specialist (idle between tasks is its normal state) or a session that is no subagent. */
150
+ export function nudgeInbox(pi: ExtensionAPI, deps: InboxDeps = {}): Inbox | undefined {
151
+ const env = deps.env ?? process.env;
152
+ const file = env.PI_SUBAGENT_SESSION, runId = env.PI_SUBAGENT_ID;
153
+ if (!file || !runId || env.PI_SUBAGENT_PERSISTENT === "1") return undefined;
154
+ let ctx: Ctx | undefined, timer: ReturnType<typeof setInterval> | undefined;
155
+ const inbox = createInbox({ file, runId, autoExit: env.PI_SUBAGENT_AUTO_EXIT === "1", ctx: () => ctx, pi, undelivered: deps.undelivered, now: deps.now });
156
+ const guard = (f: () => void) => {
157
+ try {
158
+ f();
159
+ } catch {
160
+ // A request that cannot be read or acked now is the parent's to time out.
161
+ }
162
+ };
163
+ pi.on("turn_start", () => guard(() => inbox.turnStarted()));
164
+ pi.on("message_start", (event) => guard(() => inbox.messageStarted((event as { message?: unknown }).message)));
165
+ pi.on("session_start", (_event, c) => {
166
+ ctx = c;
167
+ if (timer) return;
168
+ timer = setInterval(() => guard(() => void inbox.poll()), deps.pollMs ?? POLL_MS);
169
+ (timer as { unref?: () => void }).unref?.();
170
+ });
171
+ pi.on("session_shutdown", () => {
172
+ if (timer) clearInterval(timer);
173
+ timer = undefined;
174
+ ctx = undefined;
175
+ });
176
+ return inbox;
177
+ }
@@ -0,0 +1,328 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdirSync, readFileSync, renameSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import type { LifecycleProjection } from "@nubl/maestro/core/lifecycle";
5
+ import { encodeHostValue, HOST_PATH_CHARS } from "@nubl/maestro/core/host-text";
6
+ import { formatElapsedDuration, normalizeStatusName } from "@nubl/maestro/core/status";
7
+ import type { Locale } from "../locale.ts";
8
+
9
+ // The done nudge (docs/specs/2026-11-28-done-nudge.md; boss 2026-11-28 「subagent idle/finished 太久,也要提醒他們做 subagent done」): a child of sb's host whose turn has ended
10
+ // (Maestro's `waiting` projection) and that has sat `idleMs` without a result is asked to finish, once per idle stretch and `max` times in all; then the parent is told once.
11
+ // This is the parent's half, called from the status loop that already looks at every child each second (widgets.ts). The child's own pi delivers the nudge
12
+ // (nudge-child.ts), since only the extension that owns the input box can tell a draft is there: the parent writes a request into the run's folder beside the
13
+ // child's session file and reads its ack. An auto-exit child is never nudged: a fresh turn there makes Maestro deliver it as done, finished or not.
14
+
15
+ /** The folder beside a child's session file that holds the requests of all its runs, one subfolder per run. */
16
+ export const NUDGE_SUFFIX = ".sb-nudge";
17
+ /** A request with no ack this long gets none: the parent says so and stops asking. */
18
+ export const ACK_MS = 60_000;
19
+ /** After an ack that sent nothing (`draft`, `busy`, `stale`), the next request waits this long. */
20
+ export const RETRY_MS = 60_000;
21
+ /** A request older than this when the child reads it is `stale`: its parent may have revoked it, or gone (F007). */
22
+ export const REQUEST_MS = 20_000;
23
+ /** A parent's notice that pi has not confirmed is sent again this long after, doubling each time up to 10 minutes, and only while the parent is idle (F009). */
24
+ export const RESEND_MS = 30_000;
25
+ const CONFIG_MS = 15_000;
26
+ const MIN = 60_000;
27
+
28
+ export interface NudgeSettings { idleMs: number; max: number }
29
+ export const DEFAULT_NUDGE: NudgeSettings = { idleMs: 10 * MIN, max: 2 };
30
+
31
+ /** `subagentNudge` of `<stateDir>/config.json`: `idleMinutes` 0 to 1440 (0 is off), `max` a whole number 1 to 10; anything else, or no readable file, is the default. */
32
+ export function readNudgeSettings(stateDir: string): NudgeSettings {
33
+ let raw: { idleMinutes?: unknown; max?: unknown } | undefined;
34
+ try {
35
+ raw = (JSON.parse(readFileSync(join(stateDir, "config.json"), "utf8").replace(/^\uFEFF/, "")) as { subagentNudge?: typeof raw } | null)?.subagentNudge;
36
+ } catch {
37
+ return { ...DEFAULT_NUDGE };
38
+ }
39
+ const idle = raw?.idleMinutes, max = raw?.max;
40
+ return {
41
+ idleMs: typeof idle === "number" && Number.isFinite(idle) && idle >= 0 && idle <= 1440 ? Math.round(idle * MIN) : DEFAULT_NUDGE.idleMs,
42
+ max: typeof max === "number" && Number.isInteger(max) && max >= 1 && max <= 10 ? max : DEFAULT_NUDGE.max,
43
+ };
44
+ }
45
+
46
+ const minutes = (ms: number) => {
47
+ const n = Math.max(1, Math.round(ms / MIN));
48
+ return `${n} minute${n === 1 ? "" : "s"}`;
49
+ };
50
+
51
+ /** The mark of a request in its nudge's text: the child acks `sent` only for a message that carries the mark of the request in flight (F008). */
52
+ export const nudgeMark = (id: string) => `reminder ${id.slice(-8)}`;
53
+
54
+ /** What the child is told, marked with its request. Only a child with subagent_done gets it: an auto-exit child is never nudged. */
55
+ export function nudgeText(idleMs: number, id: string): string {
56
+ return `Straw Boss (${nudgeMark(id)}): you have been idle for ${minutes(idleMs)}, and your caller still has no result from you. If your task is done, write your final report now and call subagent_done. If you truly wait on your caller (a decision, an access, or an answer only it can give), say so with caller_ping. If you wait on work of your own that will wake you (a monitor, a loop, your own subagents), reply in one line with what it is and when it ends.`;
57
+ }
58
+
59
+ /** The run's folder: `<session>.sb-nudge/<run id>`, so a resumed run on the same session file never sees another run's request. */
60
+ export function nudgeDir(sessionFile: string, runId: string): string {
61
+ return join(sessionFile + NUDGE_SUFFIX, encodeURIComponent(runId).replace(/\./g, "%2E"));
62
+ }
63
+ export const requestFile = (dir: string, id: string) => join(dir, `${id}.req`);
64
+ export const ackFile = (dir: string, id: string) => join(dir, `${id}.ack`);
65
+ /** A request id: unique across parent reloads, and safe as a file name. */
66
+ export const isRequestId = (id: unknown): id is string => typeof id === "string" && /^[A-Za-z0-9-]{8,64}$/.test(id);
67
+
68
+ /** `at` is when the parent wrote it, on the clock child and parent share: the child refuses it when a turn started since. */
69
+ export interface NudgeRequest { v: 2; id: string; runId: string; sessionFile: string; at: number; idleMs: number }
70
+ /**
71
+ * `sent`: the child saw the nudge enter its session as a user message. `draft`, `busy`: it sent nothing. `stale`: a turn started after the request was written.
72
+ * `lost`: it sent the nudge but never saw it enter. `auto-exit`: it closes when a turn ends, so it sent nothing and never will.
73
+ */
74
+ export type NudgeOutcome = "sent" | "draft" | "busy" | "stale" | "lost" | "auto-exit";
75
+ export interface NudgeAck { v: 2; id: string; runId: string; outcome: NudgeOutcome; at: number }
76
+ const OUTCOMES: readonly string[] = ["sent", "draft", "busy", "stale", "lost", "auto-exit"] satisfies NudgeOutcome[];
77
+
78
+ /** Writes `value` as `file` by rename, so a reader never sees half of it. */
79
+ export function writeAtomic(file: string, value: unknown): void {
80
+ const temp = `${file}.${process.pid}.tmp`;
81
+ try {
82
+ writeFileSync(temp, JSON.stringify(value), { mode: 0o600 });
83
+ renameSync(temp, file);
84
+ } catch (error) {
85
+ rmSync(temp, { force: true });
86
+ throw error;
87
+ }
88
+ }
89
+
90
+ export function readJson<T>(file: string): T | undefined {
91
+ try {
92
+ return JSON.parse(readFileSync(file, "utf8")) as T;
93
+ } catch {
94
+ return undefined;
95
+ }
96
+ }
97
+
98
+ /** Removes `file`; true when it was there and is gone, false when it was already gone (or cannot be removed now). */
99
+ export function take(file: string): boolean {
100
+ try {
101
+ rmSync(file);
102
+ return true;
103
+ } catch {
104
+ return false;
105
+ }
106
+ }
107
+
108
+ /** Removes the run's folder and the session's once empty; a folder another request still uses stays. */
109
+ export function tidy(dir: string): void {
110
+ for (const d of [dir, dirname(dir)]) {
111
+ try {
112
+ rmdirSync(d);
113
+ } catch {
114
+ return;
115
+ }
116
+ }
117
+ }
118
+
119
+ /** What the nudger reads of a running child (Maestro's RunningSubagent). */
120
+ export interface NudgeRun { id: string; name: string; sessionFile: string; interactive: boolean; persistent?: boolean; cancelState?: string }
121
+
122
+ interface RunState {
123
+ /** Nudges the child saw enter its session. */
124
+ sent: number;
125
+ /** Nudges the child sent but never saw enter: no delivery, yet one of the `max` tries, since one may have gone in. */
126
+ lost: number;
127
+ /** When the last one was sent: it starts a stretch of its own. */
128
+ lastSentAt?: number;
129
+ /** When the idleness the notice reports began: the stretch of the first request. */
130
+ idleFrom?: number;
131
+ /** The open request: its id, when it was written, and the idle stretch it was written for. */
132
+ pending?: { id: string; at: number; since: number | undefined };
133
+ retryAt?: number;
134
+ done?: true;
135
+ }
136
+
137
+ /** A notice for the parent: it leaves the queue only once pi confirms the message that carries it started in the parent's session. */
138
+ interface Notice { id: string; text: string; sentAt?: number; tries: number }
139
+
140
+ /**
141
+ * What the nudger keeps, in a process-wide slot (sharedNudgeStore), so a reload's new nudger takes over the counts, the notices not yet confirmed, and
142
+ * the requests the old one revoked (F007, F009).
143
+ */
144
+ export interface NudgeStore {
145
+ runs: Map<string, { dir: string; run: NudgeRun; state: RunState }>;
146
+ queue: Notice[];
147
+ /** Requests revoked after the child took them: an ack that still comes is removed, until no child may write one. */
148
+ revoked: { dir: string; id: string; until: number }[];
149
+ }
150
+
151
+ export const newNudgeStore = (): NudgeStore => ({ runs: new Map(), queue: [], revoked: [] });
152
+
153
+ const STORE_KEY = Symbol.for("pi-straw-boss/done-nudge/v1");
154
+ /** The store of this process: it outlives a reload, not a restart. A new shape takes a new key. */
155
+ export function sharedNudgeStore(): NudgeStore {
156
+ const slot = globalThis as { [STORE_KEY]?: NudgeStore };
157
+ return (slot[STORE_KEY] ??= newNudgeStore());
158
+ }
159
+
160
+ export interface Nudger {
161
+ /** One look at a running child: may write or revoke a request, and may queue a notice for the parent. */
162
+ look(run: NudgeRun, projection: LifecycleProjection, now: number): void;
163
+ /** The notices to send now, oldest first: those not sent, and those sent that pi has not confirmed when they are due again and `idle` says pi holds no turn that could still take them. Each returned counts as sent at `now`. */
164
+ outbox(now: number, idle: boolean): readonly { id: string; text: string }[];
165
+ /** The send of these threw: they go at the next tick. */
166
+ unsent(ids: readonly string[]): void;
167
+ /** A message started in the parent's session: the notices it carries (`details.nudgeNotices` of a `subagent_status`) leave the queue. */
168
+ accepted(message: unknown): void;
169
+ /** Notices pi has not confirmed yet. */
170
+ undelivered(): number;
171
+ /** Forgets the runs not in `live`, removing their open requests, and removes the late acks of revoked requests. */
172
+ prune(live: Iterable<string>, now: number): void;
173
+ /** The parent stops looking (a reload, a quit): every open request is revoked, an ack already there counted. */
174
+ stop(now: number): void;
175
+ }
176
+
177
+ export interface NudgerDeps { settings(): NudgeSettings; locale(): Locale; newId?: () => string; store?: NudgeStore }
178
+
179
+ type NoticeKind = "gave-up" | "no-ack" | "auto-exit";
180
+ /** No child writes an ack this long after its request was written (nudge-child.ts), so a revoked request's late ack is watched for this long. */
181
+ const LATE_MS = 2 * ACK_MS;
182
+ const RESEND_MAX_MS = 10 * MIN;
183
+
184
+ export function createNudger(deps: NudgerDeps): Nudger {
185
+ const store = deps.store ?? newNudgeStore();
186
+ const { runs, queue, revoked } = store;
187
+ const newId = deps.newId ?? randomUUID;
188
+ let cached: { at: number; value: NudgeSettings } | undefined;
189
+ const settings = (now: number) => {
190
+ if (!cached || now - cached.at >= CONFIG_MS || now < cached.at) cached = { at: now, value: deps.settings() };
191
+ return cached.value;
192
+ };
193
+ const notice = (run: NudgeRun, s: RunState, now: number, kind: NoticeKind) => {
194
+ const name = encodeHostValue(normalizeStatusName(run.name)), file = encodeHostValue(run.sessionFile, HOST_PATH_CHARS);
195
+ const idle = formatElapsedDuration(Math.max(0, now - (s.idleFrom ?? now)));
196
+ if (deps.locale() === "zh-TW") {
197
+ const next = `請看它的窗格;要停掉它用 subagent_cancel,之後要接著做,用 subagent_resume 帶它的 session 檔(${file})。`;
198
+ const lost = s.lost ? `(其中 ${s.lost} 次它的 pi 無法確認已送進它的 session)` : "";
199
+ if (kind === "gave-up") return `${name} 已閒置 ${idle},還沒交回結果;Straw Boss 已提醒它收尾 ${s.sent + s.lost} 次${lost},不會再提醒。${next}`;
200
+ if (kind === "auto-exit") return `${name} 已閒置 ${idle},還沒交回結果。Straw Boss 沒有提醒它:它一輪結束就會關閉,提醒會讓它把沒做完的工作當成結果交回。${next}`;
201
+ return `${name} 還沒交回結果;Straw Boss 要提醒它收尾,但它的 pi 一分鐘內沒有回應這個請求,所以不會再提醒。${next}`;
202
+ }
203
+ const next = `Read its pane; subagent_cancel stops it, and subagent_resume with its session file (${file}) continues it later.`;
204
+ const tries = s.sent + s.lost;
205
+ const lost = s.lost ? ` (its pi could not confirm that ${s.lost === tries ? (tries === 1 ? "it" : "they") : `${s.lost} of them`} entered its session)` : "";
206
+ if (kind === "gave-up")
207
+ return `${name} has been idle ${idle} and has not delivered its result, after ${tries} reminder${tries === 1 ? "" : "s"} to finish${lost}. Straw Boss will not remind it again. ${next}`;
208
+ if (kind === "auto-exit")
209
+ return `${name} has been idle ${idle} and has not delivered its result. Straw Boss did not remind it: it closes when a turn ends, so a reminder would close it and deliver its unfinished work as done. ${next}`;
210
+ return `${name} has not delivered its result, and its pi sent no acknowledgement of Straw Boss's reminder request within a minute, so Straw Boss will not remind it. ${next}`;
211
+ };
212
+ const tell = (run: NudgeRun, s: RunState, now: number, kind: NoticeKind) => {
213
+ s.done = true;
214
+ queue.push({ id: randomUUID(), text: notice(run, s, now, kind), tries: 0 });
215
+ };
216
+ /** Removes the files of the open request, never another's, and forgets it. One the child took and has not acked yet is watched for its late ack (F007). */
217
+ const close = (dir: string, s: RunState): boolean => {
218
+ const p = s.pending;
219
+ if (!p) return false;
220
+ const tookRequest = take(requestFile(dir, p.id));
221
+ const awaited = !take(ackFile(dir, p.id)) && !tookRequest;
222
+ if (awaited) revoked.push({ dir, id: p.id, until: p.at + LATE_MS });
223
+ tidy(dir);
224
+ s.pending = undefined;
225
+ return awaited;
226
+ };
227
+ /** Takes in the open request's ack when it is there; false when there is none to read. */
228
+ const settle = (dir: string, run: NudgeRun, s: RunState, now: number): boolean => {
229
+ const p = s.pending;
230
+ if (!p) return false;
231
+ const ack = readJson<NudgeAck>(ackFile(dir, p.id));
232
+ if (!(ack?.v === 2 && ack.id === p.id && ack.runId === run.id && OUTCOMES.includes(ack.outcome))) return false;
233
+ close(dir, s);
234
+ if (ack.outcome === "auto-exit") tell(run, s, now, "auto-exit");
235
+ else if (ack.outcome === "sent" || ack.outcome === "lost") {
236
+ if (ack.outcome === "sent") s.sent++;
237
+ else s.lost++;
238
+ s.lastSentAt = typeof ack.at === "number" && Number.isFinite(ack.at) ? Math.min(ack.at, now) : now;
239
+ } else s.retryAt = now + RETRY_MS;
240
+ return true;
241
+ };
242
+
243
+ return {
244
+ look(run, projection, now) {
245
+ if (run.interactive || run.persistent) return;
246
+ let entry = runs.get(run.id);
247
+ if (!entry) runs.set(run.id, (entry = { dir: nudgeDir(run.sessionFile, run.id), run, state: { sent: 0, lost: 0 } }));
248
+ entry.run = run;
249
+ const s = entry.state, dir = entry.dir;
250
+ // A cancel revokes the open request, so a child that outlives it takes nothing.
251
+ if (run.cancelState) return void close(dir, s);
252
+ if (s.done) return;
253
+ if (s.pending) {
254
+ const p = s.pending;
255
+ if (settle(dir, run, s, now)) {
256
+ if (s.done) return;
257
+ } else if (now - p.at >= ACK_MS) {
258
+ close(dir, s);
259
+ return tell(run, s, now, "no-ack");
260
+ } else if (projection.kind !== "waiting" || projection.stateDurationSince !== p.since) {
261
+ // The idle stretch it was written for ended. Still there: revoked. Gone: the child took it, and its ack is still to come.
262
+ if (!take(requestFile(dir, p.id))) return;
263
+ take(ackFile(dir, p.id));
264
+ tidy(dir);
265
+ s.pending = undefined;
266
+ } else return;
267
+ }
268
+ if (projection.kind !== "waiting") return;
269
+ const cfg = settings(now);
270
+ if (!cfg.idleMs) return;
271
+ const since = projection.stateDurationSince ?? now;
272
+ const quietSince = Math.max(since, s.lastSentAt ?? -Infinity);
273
+ if (now - quietSince < cfg.idleMs) return;
274
+ if (s.sent + s.lost >= cfg.max) return tell(run, s, now, "gave-up");
275
+ if (s.retryAt !== undefined && now < s.retryAt) return;
276
+ s.idleFrom ??= since;
277
+ const id = newId();
278
+ try {
279
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
280
+ writeAtomic(requestFile(dir, id), { v: 2, id, runId: run.id, sessionFile: run.sessionFile, at: now, idleMs: now - quietSince } satisfies NudgeRequest);
281
+ } catch {
282
+ // A request that cannot be written is tried again a minute later.
283
+ s.retryAt = now + RETRY_MS;
284
+ return;
285
+ }
286
+ s.pending = { id, at: now, since: projection.stateDurationSince };
287
+ s.retryAt = undefined;
288
+ },
289
+ outbox(now, idle) {
290
+ const due = queue.filter((n) => n.sentAt === undefined || (idle && now - n.sentAt >= Math.min(RESEND_MS * 2 ** Math.max(0, n.tries - 1), RESEND_MAX_MS)));
291
+ for (const n of due) {
292
+ n.sentAt = now;
293
+ n.tries++;
294
+ }
295
+ return due.map(({ id, text }) => ({ id, text }));
296
+ },
297
+ unsent(ids) {
298
+ for (const n of queue) if (ids.includes(n.id)) n.sentAt = undefined;
299
+ },
300
+ accepted(message) {
301
+ const m = message as { role?: unknown; customType?: unknown; details?: { nudgeNotices?: unknown } } | undefined;
302
+ if (m?.role !== "custom" || m.customType !== "subagent_status" || !Array.isArray(m.details?.nudgeNotices)) return;
303
+ const ids: unknown[] = m.details.nudgeNotices;
304
+ for (let i = queue.length - 1; i >= 0; i--) if (ids.includes(queue[i].id)) queue.splice(i, 1);
305
+ },
306
+ undelivered: () => queue.length,
307
+ prune(live, now) {
308
+ const keep = new Set(live);
309
+ for (const [id, entry] of runs) {
310
+ if (keep.has(id)) continue;
311
+ close(entry.dir, entry.state);
312
+ runs.delete(id);
313
+ }
314
+ for (let i = revoked.length - 1; i >= 0; i--) {
315
+ const r = revoked[i];
316
+ if (take(ackFile(r.dir, r.id))) tidy(r.dir);
317
+ if (now >= r.until) revoked.splice(i, 1);
318
+ }
319
+ },
320
+ stop(now) {
321
+ for (const { dir, run, state: s } of runs.values()) {
322
+ if (!s.pending || settle(dir, run, s, now)) continue;
323
+ // Taken but not acked: the nudge may be in. The next request waits, so a reload does not ask twice in a row.
324
+ if (close(dir, s)) s.retryAt = now + RETRY_MS;
325
+ }
326
+ },
327
+ };
328
+ }
@@ -1,5 +1,6 @@
1
1
  // Copied from pi-herdr-agents f1590cb, with the run-row changes of 2045e55 (branch feat/run-rows-probe; MIT, Copyright (c) 2026 Giuseppe Rodriguez); see NOTICE.md. sb: one row per worker, name · model · state · time.
2
2
  import type { RunRows } from "./run-rows.ts";
3
+ import type { Nudger } from "./nudge.ts";
3
4
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
5
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
5
6
  import type { SupervisionConfig } from "@nubl/maestro/core/config/supervision-config";
@@ -159,6 +160,8 @@ export function createWidgetController(
159
160
  evaluateNoProgressAdvisory,
160
161
  }: WidgetDeps,
161
162
  presenters = new WeakMap<ExtensionAPI, RunRows>(),
163
+ /** sb's done nudge (nudge.ts): asked about each child at each look; its queued notices ride in the same status message. */
164
+ nudger?: Nudger,
162
165
  ) {
163
166
  const runningSubagents = runtime.runningSubagents;
164
167
 
@@ -276,24 +279,74 @@ export function createWidgetController(
276
279
  );
277
280
  }
278
281
 
282
+ /** The APIs whose `message_start` confirms the done nudge's notices (F009). */
283
+ const watched = new WeakSet<object>();
284
+
285
+ function stopStatusRefresh() {
286
+ if (!statusInterval) return;
287
+ clearInterval(statusInterval);
288
+ statusInterval = null;
289
+ writeGlobalSlot<ReturnType<typeof setInterval> | null>(
290
+ STATUS_INTERVAL_KEY,
291
+ null,
292
+ );
293
+ }
294
+
279
295
  function startStatusRefresh(pi: ExtensionAPI) {
280
296
  if (!statusConfig.enabled || statusInterval) return;
281
297
 
282
- statusInterval = setInterval(() => {
298
+ // sb: pi's sendMessage returns before pi takes the message and reports a failure only to its own UI, so a notice leaves the nudger's queue
299
+ // when the message that carries it starts in this session (docs/specs/2026-11-28-done-nudge.md).
300
+ if (nudger && !watched.has(pi)) {
301
+ try {
302
+ pi.on("message_start", (event) => nudger.accepted((event as { message?: unknown }).message));
303
+ watched.add(pi);
304
+ } catch {
305
+ // An API pi already retired: the next start, from a live one, listens.
306
+ }
307
+ }
308
+
309
+ // sb: the done nudge's notices go first and outside the line cap; a notice pi has not confirmed goes again while this session is idle.
310
+ const send = (lines: string[], now: number) => {
311
+ let idle = false;
312
+ try {
313
+ idle = runtime.latestCtx?.isIdle() === true;
314
+ } catch {
315
+ // A context gone stale holds no turn we know of: wait for the next one.
316
+ }
317
+ const notices = nudger ? nudger.outbox(now, idle) : [];
318
+ const all = [...notices.map((n) => n.text), ...lines];
319
+ if (all.length === 0) return;
320
+ const limit = statusConfig.lineLimit + notices.length;
321
+ const capped = capStatusLines(all, limit);
322
+ const ids = notices.map((n) => n.id);
323
+ try {
324
+ pi.sendMessage(
325
+ {
326
+ customType: "subagent_status",
327
+ content: formatStatusAggregate(all, limit),
328
+ display: true,
329
+ details: { lines: capped.visibleLines, overflow: capped.overflow, ...(ids.length ? { nudgeNotices: ids } : {}) },
330
+ },
331
+ { triggerTurn: true, deliverAs: "steer" },
332
+ );
333
+ } catch (error) {
334
+ nudger?.unsent(ids);
335
+ throw error;
336
+ }
337
+ };
338
+
339
+ const tick = () => {
340
+ const now = Date.now();
341
+ nudger?.prune(runningSubagents.keys(), now);
283
342
  if (runningSubagents.size === 0) {
284
- if (statusInterval) {
285
- clearInterval(statusInterval);
286
- statusInterval = null;
287
- writeGlobalSlot<ReturnType<typeof setInterval> | null>(
288
- STATUS_INTERVAL_KEY,
289
- null,
290
- );
291
- }
343
+ send([], now);
344
+ // sb: the loop stays while a notice waits for pi's confirmation.
345
+ if (!nudger?.undelivered()) stopStatusRefresh();
292
346
  return;
293
347
  }
294
348
 
295
349
  const transitionLines: string[] = [];
296
- const now = Date.now();
297
350
  let shouldRefreshWidget = false;
298
351
 
299
352
  for (const running of runningSubagents.values()) {
@@ -337,30 +390,33 @@ export function createWidgetController(
337
390
  formatNoProgressAdvisoryLine(running, noProgress),
338
391
  );
339
392
  }
393
+
394
+ // sb: a child idle too long without a result is asked to finish (docs/specs/2026-11-28-done-nudge.md).
395
+ nudger?.look(running, projection, now);
340
396
  }
341
397
 
342
398
  if (shouldRefreshWidget) updateWidget();
343
399
 
344
- if (transitionLines.length > 0) {
345
- const capped = capStatusLines(transitionLines, statusConfig.lineLimit);
346
- pi.sendMessage(
347
- {
348
- customType: "subagent_status",
349
- content: formatStatusAggregate(
350
- transitionLines,
351
- statusConfig.lineLimit,
352
- ),
353
- display: true,
354
- details: { lines: capped.visibleLines, overflow: capped.overflow },
355
- },
356
- { triggerTurn: true, deliverAs: "steer" },
357
- );
400
+ send(transitionLines, now);
401
+ };
402
+
403
+ statusInterval = setInterval(() => {
404
+ // sb: a throw here would escape the timer; what it left undone is done at the next tick.
405
+ try {
406
+ tick();
407
+ } catch {
408
+ // Nothing to report to: the next tick tries again, and the nudger kept what was not sent.
358
409
  }
359
410
  }, 1000);
360
411
 
361
412
  writeGlobalSlot(STATUS_INTERVAL_KEY, statusInterval);
362
413
  }
363
414
 
415
+ /** sb: after a reload, the notices the last load left unconfirmed go out even when no run is left to start the loop. */
416
+ function resumeNotices(pi: ExtensionAPI) {
417
+ if (nudger?.undelivered()) startStatusRefresh(pi);
418
+ }
419
+
364
420
  function startWidgetRefresh() {
365
421
  if (widgetInterval) return;
366
422
  updateWidget(); // immediate first render
@@ -379,14 +435,9 @@ export function createWidgetController(
379
435
  null,
380
436
  );
381
437
  }
382
- if (statusInterval) {
383
- clearInterval(statusInterval);
384
- statusInterval = null;
385
- writeGlobalSlot<ReturnType<typeof setInterval> | null>(
386
- STATUS_INTERVAL_KEY,
387
- null,
388
- );
389
- }
438
+ stopStatusRefresh();
439
+ // sb: a reload or a quit revokes the done nudge's open requests (F007); its notices stay in the process-wide store for the next load.
440
+ nudger?.stop(Date.now());
390
441
  }
391
442
 
392
443
  return {
@@ -395,5 +446,6 @@ export function createWidgetController(
395
446
  startStatusRefresh,
396
447
  startWidgetRefresh,
397
448
  stopRefresh,
449
+ resumeNotices,
398
450
  };
399
451
  }