pi-straw-boss 0.113.1 → 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.
@@ -26750,7 +26750,6 @@ var STOW = { intervalMs: 3e3, idleMs: 3e4 };
26750
26750
  var keep2 = (why2) => ({ stow: false, why: why2 });
26751
26751
  function idleGate(f) {
26752
26752
  if (f.head) return keep2("head");
26753
- if (f.headless) return keep2("headless");
26754
26753
  if (!f.ready) return keep2("unready");
26755
26754
  if (f.cards > 0) return keep2("cards");
26756
26755
  if (f.run || f.state === "waking" || f.state === "running" || f.state === "closing") return keep2("run");
@@ -26777,6 +26776,9 @@ function foregroundOf(info, workspace, promptPid) {
26777
26776
  const shell2 = typeof info?.shell_pid === "number" ? info.shell_pid : void 0, prompt = new RegExp(`\\bprompt --workspace ${workspace.replace(/[^\w.:-]/g, "")}(\\s|$)`);
26778
26777
  return list2.every((p) => (shell2 !== void 0 ? p.pid === shell2 : list2.length === 1 && SHELLS2.has(nameOf2(p))) || promptPid !== void 0 && p.pid === promptPid || prompt.test(p.cmdline ?? "")) ? "clean" : "program";
26779
26778
  }
26779
+ function reopenGate(f) {
26780
+ return !f.headless || f.stowed && f.attended;
26781
+ }
26780
26782
  function seatOpen(f) {
26781
26783
  if (f.label === void 0) return "gone";
26782
26784
  return f.seated || f.label === f.record ? "open" : "stranger";
@@ -26791,8 +26793,9 @@ function createStow(o) {
26791
26793
  const processInfo = (pane) => run2(["pane", "process-info", "--pane", pane]).then((x) => JSON.parse(x).result?.process_info, () => void 0);
26792
26794
  const idleOf = (l, at) => {
26793
26795
  const ws = o.record(l).workspace, status = o.status(ws), from = since.get(ws);
26794
- return idleGate({ head: o.head(l), headless: o.headless(), ready: o.ready(l), cards: o.cards(l), state: status?.state, run: Boolean(status?.run) || (status?.allyRuns.length ?? 0) > 0, queued: o.queued(ws), soon: o.soon(ws, t.idleMs), idleFor: from ? at - from.at : 0, idleMs: t.idleMs });
26796
+ return idleGate({ head: o.head(l), ready: o.ready(l), cards: o.cards(l), state: status?.state, run: Boolean(status?.run) || (status?.allyRuns.length ?? 0) > 0, queued: o.queued(ws), soon: o.soon(ws, t.idleMs), idleFor: from ? at - from.at : 0, idleMs: t.idleMs });
26795
26797
  };
26798
+ const wants = (l) => reopenGate({ headless: o.headless(), stowed: o.record(l).stowed === true, attended: o.attended() });
26796
26799
  const said1 = (ws, why2) => {
26797
26800
  if (said2.get(ws) === why2) return;
26798
26801
  said2.set(ws, why2);
@@ -26800,7 +26803,7 @@ function createStow(o) {
26800
26803
  };
26801
26804
  const close = async (l, record2) => {
26802
26805
  const ws = record2.workspace, undo = o.hold(l);
26803
- const bare2 = { ...record2, pane: "", tab: "" };
26806
+ const bare2 = { ...record2, pane: "", tab: "", stowed: true };
26804
26807
  o.place(l, bare2);
26805
26808
  try {
26806
26809
  await run2(["pane", "close", record2.pane]);
@@ -26816,8 +26819,9 @@ function createStow(o) {
26816
26819
  };
26817
26820
  const lookAt = async (l) => {
26818
26821
  const record2 = o.record(l), ws = record2.workspace;
26819
- if (o.head(l) || o.headless() || opening3.has(ws)) return;
26822
+ if (o.head(l) || opening3.has(ws)) return;
26820
26823
  if (!record2.pane) {
26824
+ if (!wants(l)) return;
26821
26825
  if (!o.seated(l)) {
26822
26826
  const listed = await workspaces(run2).catch(() => void 0), seat = listed && seatOpen({ seated: false, label: listed.find((w) => w.workspace_id === ws)?.label, record: record2.label });
26823
26827
  if (seat === "open") await o.seat(l);
@@ -26867,7 +26871,8 @@ function createStow(o) {
26867
26871
  await report(run2, "pane", made.paneId, { sb_role: "tower" });
26868
26872
  await o.api("tab.move", { tab_id: made.tabId, insert_index: 0 }).catch((cause) => error("tab-move", cause.message));
26869
26873
  log.line("tower-unstowed", { workspace, pane: made.paneId, why: why2 });
26870
- return await o.reseat(l, { ...record2, pane: made.paneId, tab: made.tabId, cwd: dir }, true);
26874
+ const { stowed: _, ...kept } = record2;
26875
+ return await o.reseat(l, { ...kept, pane: made.paneId, tab: made.tabId, cwd: dir }, true);
26871
26876
  } catch (cause) {
26872
26877
  undo();
26873
26878
  if (made) await run2(["pane", "close", made.paneId]).catch(() => {
@@ -26881,6 +26886,8 @@ function createStow(o) {
26881
26886
  return {
26882
26887
  look: look2,
26883
26888
  open: open9,
26889
+ /** Whether the tower with no pane gets its tab again before a run starts (`reopenGate`). */
26890
+ wants,
26884
26891
  start() {
26885
26892
  timer ??= setInterval(() => void look2(), t.intervalMs);
26886
26893
  timer.unref();
@@ -27669,7 +27676,7 @@ function createRuns2(o) {
27669
27676
  const begin = async (svc) => {
27670
27677
  if (stopped || svc.run || svc.state !== "standing" || !o.enabled() || !waitingOf(svc).some((e) => !e.quiet)) return;
27671
27678
  if (!svc.ref.live()) return;
27672
- if (!headlessOn() && !svc.ref.record().pane) return void svc.ref.seat?.("run");
27679
+ if (!svc.ref.record().pane && (!headlessOn() || svc.ref.viewer?.())) return void svc.ref.seat?.("run");
27673
27680
  if (slots >= o.max()) return void blocked.add(svc);
27674
27681
  slots++;
27675
27682
  svc.state = "waking";
@@ -27877,7 +27884,7 @@ function createRuns2(o) {
27877
27884
  for (const { device, items } of devicesWaiting(svc)) {
27878
27885
  if (stopped || !o.enabled() || svc.refusedAt !== void 0 && now() - svc.refusedAt < t.refuse) return;
27879
27886
  if (!svc.ref.live()) return;
27880
- if (!headlessOn() && !svc.ref.record().pane) return void svc.ref.seat?.("ally");
27887
+ if (!svc.ref.record().pane && (!headlessOn() || svc.ref.viewer?.())) return void svc.ref.seat?.("ally");
27881
27888
  if (slots >= o.max()) return void blocked.add(svc);
27882
27889
  await beginAlly(svc, device, items).catch((cause) => error("ally-begin", cause.message));
27883
27890
  }
@@ -29480,7 +29487,8 @@ function createTowers(o) {
29480
29487
  },
29481
29488
  renewPane: (runId) => renew(l, runId),
29482
29489
  renewing: () => l.renewing === true,
29483
- seat: (why2) => void stow.open(l.record.workspace, why2).catch((cause) => error("tower-seat", cause.message)),
29490
+ seat: (why2) => void stow.open(l.record.workspace, why2).catch((cause) => (error("tower-seat", cause.message), unstow(l))),
29491
+ viewer: () => headless() && tabless(l) && stow.wants(l),
29484
29492
  // The run that was shown an expired wait has polled: it will not be shown again (towermemory.ts).
29485
29493
  shown: (ids) => {
29486
29494
  try {
@@ -29972,6 +29980,14 @@ function createTowers(o) {
29972
29980
  else if (l.state === "live") await publish(l);
29973
29981
  }
29974
29982
  };
29983
+ const unstow = (l) => {
29984
+ if (!headless() || l.stopped || services.get(l.record.workspace) !== l || !l.record.stowed) return;
29985
+ const { stowed: _, ...kept } = l.record;
29986
+ l.record = kept;
29987
+ writeService(slot, kept);
29988
+ log.line("tower-unstow-failed", { workspace: kept.workspace });
29989
+ runs2.poke(kept.workspace);
29990
+ };
29975
29991
  const untab = async (l) => {
29976
29992
  if (l.stopped || services.get(l.record.workspace) !== l) return;
29977
29993
  l.record = { ...l.record, pane: "", tab: "" };
@@ -30006,6 +30022,7 @@ function createTowers(o) {
30006
30022
  seat: async (l) => void (l.seated = true, await publish(l)),
30007
30023
  hold: (l) => ((was) => (l.state = "registering", l.renewing = true, () => void (l.state = was, l.renewing = false)))(l.state),
30008
30024
  headless,
30025
+ attended: () => !o.unattended?.(),
30009
30026
  status: (ws) => runs2.status(ws),
30010
30027
  queued: (ws) => runs2.queue(ws).filter((e) => !e.quiet).length,
30011
30028
  soon: (ws, ms4) => runs2.startsWithin(ws, ms4),
@@ -30267,7 +30284,8 @@ function createTowers(o) {
30267
30284
  await report(run2, "pane", tab.paneId, { sb_role: "tower" }).catch(() => {
30268
30285
  });
30269
30286
  await cfg.api("tab.move", { tab_id: tab.tabId, insert_index: 0 }).catch((cause) => error("tab-move", cause.message));
30270
- record2 = { ...record2, pane: tab.paneId, tab: tab.tabId };
30287
+ const { stowed: _, ...kept } = record2;
30288
+ record2 = { ...kept, pane: tab.paneId, tab: tab.tabId };
30271
30289
  }
30272
30290
  const l = existing ? await reseat(existing, record2, view) : (writeService(slot, record2), adopt(record2, view, true));
30273
30291
  log.line(existing ? "tower-viewer" : "tower-opened", { workspace: ws, id: record2.id, ...view ? { pane: record2.pane, tab: record2.tab } : { tab: "none" } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-straw-boss",
3
- "version": "0.113.1",
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
  }
@@ -203,6 +203,8 @@ export interface ServiceRef {
203
203
  renewing?(): boolean;
204
204
  /** A service whose pane closed between runs (towerstow.ts) gets it made again before a run starts: once its identity has registered with the new pane, it pokes again. */
205
205
  seat?(why: "run" | "ally"): void;
206
+ /** Under headless runs: whether a run waits for the service's viewer to be made again first (a viewer the idle close took, on an attended device; towerstow.ts `reopenGate`). */
207
+ viewer?(): boolean;
206
208
  /** The tower's memory in counts for the GUI's snapshot (towermemory.ts). */
207
209
  memory?(): MemorySummary;
208
210
  }
@@ -479,7 +481,7 @@ export function createRuns(o: RunsOptions) {
479
481
  const begin = async (svc: Svc) => {
480
482
  if (stopped || svc.run || svc.state !== "standing" || !o.enabled() || !waitingOf(svc).some((e) => !e.quiet)) return;
481
483
  if (!svc.ref.live()) return; // the identity registers first: runs reply under it. The service pokes again when it is live.
482
- if (!headlessOn() && !svc.ref.record().pane) return void svc.ref.seat?.("run"); // its pane closed between runs: made first
484
+ if (!svc.ref.record().pane && (!headlessOn() || svc.ref.viewer?.())) return void svc.ref.seat?.("run"); // its pane (a headless viewer) closed between runs: made first
483
485
  if (slots >= o.max()) return void blocked.add(svc);
484
486
  slots++;
485
487
  svc.state = "waking";
@@ -729,7 +731,7 @@ export function createRuns(o: RunsOptions) {
729
731
  for (const { device, items } of devicesWaiting(svc)) {
730
732
  if (stopped || !o.enabled() || svc.refusedAt !== undefined && now() - svc.refusedAt < t.refuse) return;
731
733
  if (!svc.ref.live()) return; // the identity registers first; the service pokes again when it is live
732
- if (!headlessOn() && !svc.ref.record().pane) return void svc.ref.seat?.("ally"); // the ally pane is split off the standing pane, which is made first
734
+ if (!svc.ref.record().pane && (!headlessOn() || svc.ref.viewer?.())) return void svc.ref.seat?.("ally"); // the ally pane is split off the standing pane (or the headless viewer comes back), which is made first
733
735
  if (slots >= o.max()) return void blocked.add(svc);
734
736
  await beginAlly(svc, device, items).catch((cause: Error) => error("ally-begin", cause.message));
735
737
  }
@@ -309,7 +309,8 @@ export function createTowers(o: TowersOptions): Towers {
309
309
  // The logbook's read mark rides on the digest's keys (`book:<seq>`, this slot's book): a run that ended well read the rows its brief carried.
310
310
  clearDigest: async (keys) => { for (const k of keys) if (k.startsWith(BOOK_KEY)) markRead(slot.dir, l.record.workspace, Number(k.slice(BOOK_KEY.length)), now()); await digest.drop(l.record.workspace, keys.filter((k) => !k.startsWith(BOOK_KEY))); },
311
311
  renewPane: (runId) => renew(l, runId),
312
- renewing: () => l.renewing === true, seat: (why) => void stow.open(l.record.workspace, why).catch((cause: Error) => error("tower-seat", cause.message)),
312
+ renewing: () => l.renewing === true, seat: (why) => void stow.open(l.record.workspace, why).catch((cause: Error) => (error("tower-seat", cause.message), unstow(l))),
313
+ viewer: () => headless() && tabless(l) && stow.wants(l),
313
314
  // The run that was shown an expired wait has polled: it will not be shown again (towermemory.ts).
314
315
  shown: (ids) => { try { markShown(slot, l.record.workspace, now(), ids); } catch (cause) { error("memory", (cause as Error).message); } },
315
316
  memory: () => {
@@ -820,6 +821,15 @@ export function createTowers(o: TowersOptions): Towers {
820
821
  else if (l.state === "live") await publish(l);
821
822
  }
822
823
  };
824
+ /** Headless runs: a viewer the idle close took could not be made again; the service stops waiting for one, so its runs start with no tab, and the next look pokes them. */
825
+ const unstow = (l: Live) => {
826
+ if (!headless() || l.stopped || services.get(l.record.workspace) !== l || !l.record.stowed) return;
827
+ const { stowed: _, ...kept } = l.record;
828
+ l.record = kept;
829
+ writeService(slot, kept);
830
+ log.line("tower-unstow-failed", { workspace: kept.workspace });
831
+ runs.poke(kept.workspace);
832
+ };
823
833
  /** Headless runs: the service's viewer pane is gone, and the service goes on with no tab. The identity registers again with no pane, as after a move (`tower-found`). */
824
834
  const untab = async (l: Live) => {
825
835
  if (l.stopped || services.get(l.record.workspace) !== l) return;
@@ -833,7 +843,7 @@ export function createTowers(o: TowersOptions): Towers {
833
843
  const reseat = async (l: Live, record: ServiceRecord, fresh: boolean): Promise<Live> => { l.record = record; writeService(slot, record); await release(l); await standing.detach(record.workspace); if (services.get(record.workspace) === l) services.delete(record.workspace); return adopt(record, fresh, true); };
834
844
  const stow = createStow<Live>({ run, api: cfg.api, log, now, stateDir: slot.stateDir, ...(o.stow ? { timers: o.stow } : {}), list: () => [...services.values()].filter((l) => !l.stopped), current: (ws) => ((l) => (l && !l.stopped ? l : undefined))(services.get(ws)), record: (l) => l.record, place: (l, record) => void (l.record = record), head: isHeadL, seated: (l) => l.seated, recovering: () => now() < recoverUntil,
835
845
  ready: (l) => l.state === "live" && l.seated && !l.stopped && !l.renewing && Boolean(l.client?.isConnected()), seat: async (l) => void ((l.seated = true), await publish(l)), hold: (l) => ((was) => ((l.state = "registering"), (l.renewing = true), () => void ((l.state = was), (l.renewing = false))))(l.state),
836
- headless, status: (ws) => runs.status(ws), queued: (ws) => runs.queue(ws).filter((e) => !e.quiet).length, soon: (ws, ms) => runs.startsWithin(ws, ms), cards: (l) => cardsFor(l), prompt: (ws) => standing.here(ws), reseat, lose });
846
+ headless, attended: () => !o.unattended?.(), status: (ws) => runs.status(ws), queued: (ws) => runs.queue(ws).filter((e) => !e.quiet).length, soon: (ws, ms) => runs.startsWithin(ws, ms), cards: (l) => cardsFor(l), prompt: (ws) => standing.here(ws), reseat, lose });
837
847
 
838
848
  // --- the start ------------------------------------------------------------------------------------------------------------------------------------------------------------
839
849
 
@@ -1130,7 +1140,8 @@ export function createTowers(o: TowersOptions): Towers {
1130
1140
  const tab = await createTab(run, ws, record.cwd ?? slot.stateDir, [], TOWER_LABEL);
1131
1141
  await report(run, "pane", tab.paneId, { sb_role: "tower" }).catch(() => {});
1132
1142
  await cfg.api("tab.move", { tab_id: tab.tabId, insert_index: 0 }).catch((cause: Error) => error("tab-move", cause.message));
1133
- record = { ...record, pane: tab.paneId, tab: tab.tabId };
1143
+ const { stowed: _, ...kept } = record;
1144
+ record = { ...kept, pane: tab.paneId, tab: tab.tabId };
1134
1145
  }
1135
1146
  const l = existing ? await reseat(existing, record, view) : (writeService(slot, record), adopt(record, view, true));
1136
1147
  log.line(existing ? "tower-viewer" : "tower-opened", { workspace: ws, id: record.id, ...(view ? { pane: record.pane, tab: record.tab } : { tab: "none" }) });
@@ -34,6 +34,8 @@ export interface ServiceRecord {
34
34
  waiting?: true;
35
35
  /** `head` for the head tower's service (its workspace is the head workspace, its folder `head/`); absent for a workspace tower. */
36
36
  kind?: "head";
37
+ /** The idle close took the pane (towerstow.ts): under headless runs only such a viewer comes back, as a fresh one. Dropped when a pane is made again. */
38
+ stowed?: true;
37
39
  }
38
40
  /** What wakes a run (the spec, Wake triggers): an intercom message, the boss typing into the tower, a notice the server raises, a follow-up the last run asked for. */
39
41
  /** `link` is a teammate's message an ally run was given: it lives in the link inbox, never in this queue. */
@@ -8,6 +8,8 @@ import { nameOf, SHELLS } from "./typegate.ts";
8
8
  // is live, nothing waits to wake one, no card of the tower waits, and that has held for `idleMs`, the pane closes (only the pane: Herdr drops the emptied tab itself) and the service goes on with no pane, as a headless
9
9
  // service does: its identity stays registered and its token written, so mains still reach it. The next run, ally run, card, or ensure-tower makes the tab again, as the first open made it.
10
10
  // What keeps the pane is decided here alone (`idleGate`, `paneGate`, `seatOpen`; their table test is tests/towerstow.test.ts); the look gathers the facts and acts on the answer.
11
+ // Under headless runs (`towerRuns.headless`) the pane is the service's viewer and the same rules close it; it comes back as a fresh viewer only when the idle close took it (`stowed` on the record), and only on an attended
12
+ // device (`reopenGate`): a service of headless runs needs no tab, and a viewer the boss ended himself stays ended.
11
13
  // The head tower's pane is never closed: it is its workspace's only pane, so closing it would close the head workspace and take the head's record with it (`lose`). A pane that is the last of its workspace is kept for the
12
14
  // same reason: the queue, the memory, and the ledgers are kept under the workspace's id, which a workspace made again does not get.
13
15
 
@@ -20,14 +22,12 @@ export interface StowTimers {
20
22
  export const STOW: StowTimers = { intervalMs: 3000, idleMs: 30_000 };
21
23
 
22
24
  /** Why a standing pane stays. */
23
- export type Keep = "head" | "headless" | "unready" | "cards" | "run" | "held" | "queued" | "soon" | "recent" | "gone" | "agent" | "tab" | "last" | "parked" | "prompt" | "draft" | "program" | "unknown";
25
+ export type Keep = "head" | "unready" | "cards" | "run" | "held" | "queued" | "soon" | "recent" | "gone" | "agent" | "tab" | "last" | "parked" | "prompt" | "draft" | "program" | "unknown";
24
26
  export type StowVerdict = { stow: true } | { stow: false; why: Keep };
25
27
  const keep = (why: Keep): StowVerdict => ({ stow: false, why });
26
28
 
27
29
  export interface IdleFacts {
28
30
  head: boolean;
29
- /** `towerRuns.headless`: a viewer has its own life (it ends by itself). */
30
- headless: boolean;
31
31
  /** The identity is registered, the seat proven, and no pane change is under way. */
32
32
  ready: boolean;
33
33
  /** The tower's own wait cards that wait for the boss. */
@@ -45,7 +45,6 @@ export interface IdleFacts {
45
45
  /** The facts of the service, cheap to read: asked before the pane's facts, which cost Herdr calls. */
46
46
  export function idleGate(f: IdleFacts): StowVerdict {
47
47
  if (f.head) return keep("head");
48
- if (f.headless) return keep("headless");
49
48
  if (!f.ready) return keep("unready");
50
49
  if (f.cards > 0) return keep("cards");
51
50
  if (f.run || f.state === "waking" || f.state === "running" || f.state === "closing") return keep("run");
@@ -89,6 +88,11 @@ export function foregroundOf(info: { shell_pid?: unknown; foreground_processes?:
89
88
  return list.every((p) => (shell !== undefined ? p.pid === shell : list.length === 1 && SHELLS.has(nameOf(p))) || (promptPid !== undefined && p.pid === promptPid) || prompt.test(p.cmdline ?? "")) ? "clean" : "program";
90
89
  }
91
90
 
91
+ /** Whether a tower with no pane gets its tab again (before a run or an ally run, for a card): a standing pane always does; under headless runs only a viewer the idle close took (`stowed`), and only where the boss is. */
92
+ export function reopenGate(f: { headless: boolean; stowed: boolean; attended: boolean }): boolean {
93
+ return !f.headless || (f.stowed && f.attended);
94
+ }
95
+
92
96
  /** Whether a tower with no pane may make its tab in the workspace under its id: after a Herdr restart (`seated` false) only one that still carries the label it had is its own (ids repeat across Herdr servers). */
93
97
  export function seatOpen(f: { seated: boolean; label: string | undefined; record: string }): "open" | "stranger" | "gone" {
94
98
  if (f.label === undefined) return "gone";
@@ -118,6 +122,8 @@ export interface StowPort<L> {
118
122
  /** The service is not live while its pane changes (no run begins, no pi is admitted); returns the undo. */
119
123
  hold(l: L): () => void;
120
124
  headless(): boolean;
125
+ /** A boss is at this device (no `unattended` box): only there does a headless viewer come back. */
126
+ attended(): boolean;
121
127
  status(workspace: string): ServiceStatus | undefined;
122
128
  queued(workspace: string): number;
123
129
  soon(workspace: string, ms: number): boolean;
@@ -139,8 +145,9 @@ export function createStow<L>(o: StowPort<L>) {
139
145
  const processInfo = (pane: string) => run(["pane", "process-info", "--pane", pane]).then((x) => JSON.parse(x).result?.process_info, () => undefined);
140
146
  const idleOf = (l: L, at: number) => {
141
147
  const ws = o.record(l).workspace, status = o.status(ws), from = since.get(ws);
142
- return idleGate({ head: o.head(l), headless: o.headless(), ready: o.ready(l), cards: o.cards(l), state: status?.state, run: Boolean(status?.run) || (status?.allyRuns.length ?? 0) > 0, queued: o.queued(ws), soon: o.soon(ws, t.idleMs), idleFor: from ? at - from.at : 0, idleMs: t.idleMs });
148
+ return idleGate({ head: o.head(l), ready: o.ready(l), cards: o.cards(l), state: status?.state, run: Boolean(status?.run) || (status?.allyRuns.length ?? 0) > 0, queued: o.queued(ws), soon: o.soon(ws, t.idleMs), idleFor: from ? at - from.at : 0, idleMs: t.idleMs });
143
149
  };
150
+ const wants = (l: L) => reopenGate({ headless: o.headless(), stowed: o.record(l).stowed === true, attended: o.attended() });
144
151
  const said1 = (ws: string, why: Keep) => {
145
152
  if (said.get(ws) === why) return;
146
153
  said.set(ws, why);
@@ -150,7 +157,7 @@ export function createStow<L>(o: StowPort<L>) {
150
157
  /** The pane closes and the service goes on with no pane. Every fact is asked again after the last await; a close Herdr refuses leaves everything as it was. */
151
158
  const close = async (l: L, record: ServiceRecord) => {
152
159
  const ws = record.workspace, undo = o.hold(l);
153
- const bare: ServiceRecord = { ...record, pane: "", tab: "" };
160
+ const bare: ServiceRecord = { ...record, pane: "", tab: "", stowed: true };
154
161
  o.place(l, bare);
155
162
  try {
156
163
  await run(["pane", "close", record.pane]);
@@ -166,8 +173,9 @@ export function createStow<L>(o: StowPort<L>) {
166
173
  };
167
174
  const lookAt = async (l: L) => {
168
175
  const record = o.record(l), ws = record.workspace;
169
- if (o.head(l) || o.headless() || opening.has(ws)) return;
176
+ if (o.head(l) || opening.has(ws)) return;
170
177
  if (!record.pane) {
178
+ if (!wants(l)) return; // a service of headless runs with no viewer, or one the boss ended: nothing to bring back
171
179
  // A service seated before a Herdr restart is seated again by its workspace's label: its token is written again, and a card or a run makes its tab. A workspace under its id with another label is a stranger's, once the minute is over.
172
180
  if (!o.seated(l)) {
173
181
  const listed = await workspaces(run).catch(() => undefined), seat = listed && seatOpen({ seated: false, label: listed.find((w) => w.workspace_id === ws)?.label, record: record.label });
@@ -221,7 +229,8 @@ export function createStow<L>(o: StowPort<L>) {
221
229
  await report(run, "pane", made.paneId, { sb_role: "tower" });
222
230
  await o.api("tab.move", { tab_id: made.tabId, insert_index: 0 }).catch((cause: Error) => error("tab-move", cause.message));
223
231
  log.line("tower-unstowed", { workspace, pane: made.paneId, why });
224
- return await o.reseat(l, { ...record, pane: made.paneId, tab: made.tabId, cwd: dir }, true);
232
+ const { stowed: _, ...kept } = record;
233
+ return await o.reseat(l, { ...kept, pane: made.paneId, tab: made.tabId, cwd: dir }, true);
225
234
  } catch (cause) {
226
235
  undo();
227
236
  if (made) await run(["pane", "close", made.paneId]).catch(() => {}); // the pane it made, never the tab
@@ -235,6 +244,8 @@ export function createStow<L>(o: StowPort<L>) {
235
244
  return {
236
245
  look,
237
246
  open,
247
+ /** Whether the tower with no pane gets its tab again before a run starts (`reopenGate`). */
248
+ wants,
238
249
  start() {
239
250
  timer ??= setInterval(() => void look(), t.intervalMs);
240
251
  timer.unref();