pi-straw-boss 0.82.0 → 0.82.1

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.
@@ -3664,15 +3664,15 @@ function refusalText2(r, what = "pi") {
3664
3664
  }
3665
3665
  var SettingsRefused = class extends Error {
3666
3666
  refusal;
3667
- constructor(refusal6, what) {
3668
- super(refusalText2(refusal6, what));
3669
- this.refusal = refusal6;
3667
+ constructor(refusal7, what) {
3668
+ super(refusalText2(refusal7, what));
3669
+ this.refusal = refusal7;
3670
3670
  }
3671
3671
  };
3672
3672
  async function assertSettingsSafe(dirs, what, run3) {
3673
3673
  for (const dir of new Set(dirs)) {
3674
- const refusal6 = dir ? await settingsRefusal(dir, run3) : void 0;
3675
- if (refusal6) throw new SettingsRefused(refusal6, what);
3674
+ const refusal7 = dir ? await settingsRefusal(dir, run3) : void 0;
3675
+ if (refusal7) throw new SettingsRefused(refusal7, what);
3676
3676
  }
3677
3677
  }
3678
3678
 
@@ -3852,17 +3852,17 @@ async function open({ run: run3, sleep: sleep2, live, moveFirst, model, trustDir
3852
3852
  let paneId, created;
3853
3853
  let running = false;
3854
3854
  const here = await panes(run3, ws);
3855
- const marked = here.find((p) => p.tokens?.sb_role === "tower");
3856
- const bare2 = marked ? [] : (await tabs(run3, ws)).filter((t) => t.label === TOWER_LABEL).flatMap((t) => {
3855
+ const marked2 = here.find((p) => p.tokens?.sb_role === "tower");
3856
+ const bare2 = marked2 ? [] : (await tabs(run3, ws)).filter((t) => t.label === TOWER_LABEL).flatMap((t) => {
3857
3857
  const inside2 = here.filter((p) => p.tab_id === t.tab_id);
3858
3858
  return inside2.length === 1 && (!inside2[0].agent || isStandin(inside2[0])) && !inside2[0].tokens?.sb_role ? [inside2[0]] : [];
3859
3859
  });
3860
- const reused = marked ?? bare2[0];
3860
+ const reused = marked2 ?? bare2[0];
3861
3861
  if (reused) {
3862
3862
  paneId = reused.pane_id;
3863
3863
  running = reused.agent === "pi";
3864
3864
  if (!running) await assertSettingsSafe([reused.cwd ?? workspace.worktree?.checkout_path ?? cwd]);
3865
- if (!marked) await report(run3, "pane", paneId, { sb_role: "tower" });
3865
+ if (!marked2) await report(run3, "pane", paneId, { sb_role: "tower" });
3866
3866
  await moveFirst(reused.tab_id);
3867
3867
  for (const extra of bare2.slice(1)) await run3(["tab", "close", extra.tab_id]).catch(() => {
3868
3868
  });
@@ -3877,7 +3877,7 @@ async function open({ run: run3, sleep: sleep2, live, moveFirst, model, trustDir
3877
3877
  }
3878
3878
  if (!running) {
3879
3879
  await startPi(run3, sleep2, `tower-${ws.toLowerCase()}`, paneId, ["--name", `tower \xB7 ${workspace.label}`, ...model ? ["--model", model] : []]).catch(async (error) => {
3880
- if (reused && !marked) await report(run3, "pane", paneId, { sb_role: null }).catch(() => {
3880
+ if (reused && !marked2) await report(run3, "pane", paneId, { sb_role: null }).catch(() => {
3881
3881
  });
3882
3882
  throw error;
3883
3883
  });
@@ -9709,9 +9709,9 @@ async function pickable(path, home = homedir7(), hidden = platformHidden) {
9709
9709
  return (await stat5(real4).catch(() => void 0))?.isDirectory() ? real4 : void 0;
9710
9710
  }
9711
9711
  async function listDirs(dir, home = homedir7(), hidden = platformHidden) {
9712
- const root = await realpath2(home).catch(() => home), names = [], marked = await hidden?.(dir);
9712
+ const root = await realpath2(home).catch(() => home), names = [], marked2 = await hidden?.(dir);
9713
9713
  for (const e of await readdir3(dir, { withFileTypes: true })) {
9714
- if (e.name.startsWith(".") || marked?.has(e.name.toLowerCase())) continue;
9714
+ if (e.name.startsWith(".") || marked2?.has(e.name.toLowerCase())) continue;
9715
9715
  if (e.isDirectory() || e.isSymbolicLink() && await pickable(join26(dir, e.name), home, hidden)) names.push(e.name);
9716
9716
  }
9717
9717
  names.sort((a, b) => a.localeCompare(b));
@@ -17130,7 +17130,7 @@ function createLinkService({ kit, stateDir, version, started, pid = process.pid,
17130
17130
  lookError = error.message;
17131
17131
  note(`Straw Link: the link holder could not start: ${error.message}`, "error");
17132
17132
  };
17133
- const refusal6 = () => {
17133
+ const refusal7 = () => {
17134
17134
  const found = policy();
17135
17135
  return found.mode === "refused" ? `Straw Link: unattended mode is refused (${found.reason}); no link holder runs on this computer` : void 0;
17136
17136
  };
@@ -17236,7 +17236,7 @@ function createLinkService({ kit, stateDir, version, started, pid = process.pid,
17236
17236
  };
17237
17237
  const handle = async (body2, from) => {
17238
17238
  const op = typeof body2 === "object" && body2 !== null ? body2 : {};
17239
- if (!holder?.active || !election?.isHolder()) return { ok: false, code: "no_holder", error: refusal6() ?? (inUse() ? "The link holder is not running in the sb server yet; ask again in a moment" : NOT_SET_UP) };
17239
+ if (!holder?.active || !election?.isHolder()) return { ok: false, code: "no_holder", error: refusal7() ?? (inUse() ? "The link holder is not running in the sb server yet; ask again in a moment" : NOT_SET_UP) };
17240
17240
  const only = Array.isArray(body2.teams) ? body2.teams.filter((t) => typeof t === "string") : void 0;
17241
17241
  if (op.op === "list") return { ok: true, teams: holder.list(only) };
17242
17242
  if (op.op === "board-read") return holder.boards({ ...only ? { only } : {}, ...typeof op.device === "string" ? { device: op.device } : {} });
@@ -22475,134 +22475,37 @@ import { join as join61 } from "node:path";
22475
22475
 
22476
22476
  // src/closemain.ts
22477
22477
  import { randomUUID as randomUUID12 } from "node:crypto";
22478
- var CONTROL8 = "straw-boss/control";
22479
- var ASK_MS2 = 1e4;
22480
- var RETRY_MS3 = 15e3;
22481
- var RETRY_STEP_MS = 3e3;
22482
- var QUIT_MS = 3e4;
22483
- var STANDING_CLOSE = "is a standing main: it has no end and sends no done report, so only the boss closes it";
22484
- function refuseStanding(net, query) {
22485
- const named = net.sessions.filter((x) => x.id === query || x.name === query);
22486
- if (named.length !== 1) return;
22487
- if (net.ps.find((p) => p.pane_id === named[0].herdrLocation?.paneId)?.tokens?.sb_duty === "standing") throw new Error(`${named[0].name ?? named[0].id} ${STANDING_CLOSE}`);
22488
- }
22489
- function createCloseMain({ pi, cfg, s: s2, me }, { closeSelf, check, turn }) {
22490
- const { run: run3, sleep: sleep2 } = cfg;
22491
- let channel;
22492
- const answers2 = /* @__PURE__ */ new Map();
22493
- const send = (payload) => channel?.publish({ version: 1, ...payload }, { audience: "capable" });
22494
- const judge = async (from, interrupt = false) => {
22495
- const no19 = (reason) => ({ reason });
22496
- if (s2.isTower) return no19("this session is a tower");
22497
- if (!s2.joined) return no19("this session has not joined the net");
22498
- const [all, workspace] = await Promise.all([panes(run3), workspaces(run3).then((list2) => list2.find((w) => w.workspace_id === s2.at.workspaceId))]);
22499
- const mine = all.find((p) => p.pane_id === s2.at.paneId);
22500
- if (!mine?.tokens?.sb_opened_by) return no19("no tower opened this main, so only the boss closes it");
22501
- if (!workspace?.tokens?.tower || workspace.tokens.tower !== from) return no19("the request is not from the tower of this workspace");
22502
- const running = subagents(mine, all, cfg.now()).filter((row2) => !row2.ended).length;
22503
- const subs = running && `${running} subagent${running > 1 ? "s are" : " is"} running`;
22504
- if (interrupt && turn?.running()) {
22505
- const others = [turn.blockers(), subs].filter(Boolean).join(", ");
22506
- if (others) return { reason: others, busy: true };
22507
- turn.abort();
22508
- return { reason: "its turn was interrupted; it quits once it is idle", busy: true };
22509
- }
22510
- const busy = [check(), subs].filter(Boolean).join(", ");
22511
- return busy ? { reason: busy, busy: true } : void 0;
22512
- };
22513
- const answer = async (from, reqId, interrupt) => {
22514
- const refused3 = await judge(from, interrupt).catch((error) => ({ reason: `it could not check itself: ${error.message}` }));
22515
- const quit = refused3 ? void 0 : closeSelf(false);
22516
- const why = refused3 ?? (quit ? { reason: quit } : void 0);
22517
- send({ type: "close-main-result", to: from, reqId, accepted: !why, ...why ?? {} });
22518
- };
22519
- const onEvent = (event) => {
22520
- const p = event.payload, from = event.fromSessionId;
22521
- if (event.type !== "message" || p?.version !== 1 || !from || typeof p.reqId !== "string" || p.reqId.length > 64) return;
22522
- if (p.type === "close-main" && p.to === me()) void answer(from, p.reqId, p.interrupt === true);
22523
- if (p.type === "close-main-result" && p.to === me() && typeof p.accepted === "boolean") answers2.set(p.reqId, { from, accepted: p.accepted, ...typeof p.reason === "string" ? { reason: p.reason.slice(0, 300) } : {}, ...p.busy === true ? { busy: true } : {} });
22524
- };
22525
- const ask = async (main, interrupt) => {
22526
- const reqId = randomUUID12().slice(0, 12);
22527
- send({ type: "close-main", to: main, reqId, ...interrupt ? { interrupt: true } : {} });
22528
- const got = await waitFor(sleep2, () => answers2.get(reqId)?.from === main ? answers2.get(reqId) : void 0, ASK_MS2, 100);
22529
- answers2.delete(reqId);
22530
- return got;
22531
- };
22532
- return {
22533
- /** Every tower, and every main a tower opened, hears and answers asks; registering twice is a no-op. */
22534
- register() {
22535
- if (channel) return;
22536
- pi.events.emit(REGISTER, { namespace: CONTROL8, ownerEligible: false, onReady: (c) => channel = c, onEvent });
22537
- if (!channel) throw new Error("pi-intercom is not loaded (Straw Boss needs pi-intercom >= 0.17.1)");
22538
- },
22539
- /** The tower's side: a main this workspace's tower opened, by intercom name or session id. */
22540
- closeMain: (async (query, opts) => {
22541
- const interrupt = opts?.interrupt === true;
22542
- if (!channel) throw new Error("This session cannot reach the mains' control channel yet");
22543
- const [sessions, all] = await Promise.all([s2.c.listSessions(), panes(run3)]);
22544
- const found = sessions.filter((x) => x.id === query || x.name === query);
22545
- if (found.length !== 1) throw new Error(`${found.length ? "Several sessions are named" : "No live session is named or has the id"} "${query}"`);
22546
- const main = found[0], name2 = main.name ?? main.id, pane = all.find((p) => p.pane_id === main.herdrLocation?.paneId);
22547
- if (pane?.workspace_id !== s2.at.workspaceId) throw new Error(`${name2} is not in this workspace; a tower closes only the mains it opened here`);
22548
- if (pane.tokens?.sb_role !== "main" && pane.tokens?.sb_role !== TRAIN) throw new Error(`${name2} is not a main agent`);
22549
- if (!pane.tokens.sb_opened_by) throw new Error(`${name2} was not opened by a tower (the boss opened it), so only the boss closes it`);
22550
- if (!interrupt && !["idle", "done"].includes(pane.agent_status ?? "")) throw new Error(`${name2} is ${pane.agent_status ?? "in an unknown state"}; try again when it is idle`);
22551
- let got = await ask(main.id, interrupt);
22552
- for (let waited = 0; got?.busy && waited < RETRY_MS3; waited += RETRY_STEP_MS) await sleep2(RETRY_STEP_MS), got = await ask(main.id, interrupt);
22553
- if (!got) throw new Error(`${name2} did not answer the close request within ${ASK_MS2 / 1e3} s (an older pi-straw-boss, or a stuck session); close it in its terminal`);
22554
- if (!got.accepted) throw new Error(`${name2} will not close: ${got.reason ?? "refused"}`);
22555
- const gone = await waitFor(sleep2, async () => !(await s2.c.listSessions().catch(() => [main])).some((x) => x.id === main.id), QUIT_MS, 500);
22556
- return { text: gone ? `${name2} quit and its pane closed.` : `${name2} accepted and is shutting down; its pane closes once pi has exited.`, main: main.id, name: name2, closed: Boolean(gone) };
22557
- })
22558
- };
22559
- }
22560
22478
 
22561
- // src/digest.ts
22562
- var PREFIX2 = "sbd_";
22563
- var SOURCE = "straw-boss-digest";
22564
- var KEEP3 = 20;
22565
- var WIDTH = 80;
22566
- var BATCH = 16;
22567
- var report3 = (run3, workspaceId, flags2) => run3(["workspace", "report-metadata", workspaceId, "--source", SOURCE, ...flags2]);
22568
- var entries2 = async (run3, workspaceId) => {
22569
- const tokens = (await workspaces(run3)).find((w) => w.workspace_id === workspaceId)?.tokens ?? {};
22570
- return Object.entries(tokens).filter(([key2]) => key2.startsWith(PREFIX2)).sort(([a], [b]) => a < b ? -1 : 1);
22571
- };
22572
- function createDigest(run3, now) {
22573
- let seq2 = 0;
22574
- return {
22575
- /** Adds one line, stamped with the local time, dropping the oldest lines past KEEP in the same report. */
22576
- async note(workspaceId, text11) {
22577
- const at = new Date(now());
22578
- const line4 = Array.from(`${String(at.getHours()).padStart(2, "0")}:${String(at.getMinutes()).padStart(2, "0")} ${text11.replace(/\s+/g, " ").trim()}`).slice(0, WIDTH).join("");
22579
- const key2 = `${PREFIX2}${now().toString(36).padStart(9, "0")}${process.pid.toString(36)}${(seq2++ % 36).toString(36)}`;
22580
- const old = await entries2(run3, workspaceId);
22581
- const drop = old.slice(0, Math.min(BATCH - 1, Math.max(0, old.length - (KEEP3 - 1)))).flatMap(([k]) => ["--clear-token", k]);
22582
- await report3(run3, workspaceId, [...drop, "--token", `${key2}=${line4}`]);
22583
- },
22584
- /** The lines as they are now, oldest first, with their keys, and nothing cleared (a run's brief shows them; `drop` clears them when the run calls tower_done). */
22585
- async peek(workspaceId) {
22586
- return (await entries2(run3, workspaceId)).map(([key2, line4]) => ({ key: key2, line: line4 }));
22587
- },
22588
- /** Clears the lines with these keys. */
22589
- async drop(workspaceId, keys) {
22590
- for (let i = 0; i < keys.length; i += BATCH) await report3(run3, workspaceId, keys.slice(i, i + BATCH).flatMap((k) => ["--clear-token", k]));
22591
- },
22592
- /** Returns the lines, oldest first, and clears them: the tower reads each one once. */
22593
- async take(workspaceId) {
22594
- const found = await entries2(run3, workspaceId);
22595
- for (let i = 0; i < found.length; i += BATCH) await report3(run3, workspaceId, found.slice(i, i + BATCH).flatMap(([k]) => ["--clear-token", k])).catch(() => {
22596
- });
22597
- return found.map(([, line4]) => line4);
22598
- }
22599
- };
22600
- }
22479
+ // src/deadpane.ts
22480
+ import { statSync as statSync18 } from "node:fs";
22601
22481
 
22602
- // src/opener.ts
22603
- import { createHash as createHash22, randomUUID as randomUUID14 } from "node:crypto";
22604
- import { existsSync as existsSync10 } from "node:fs";
22605
- import { join as join55 } from "node:path";
22482
+ // src/revive.ts
22483
+ import { createHash as createHash21 } from "node:crypto";
22484
+ import { closeSync as closeSync10, existsSync as existsSync9, lstatSync as lstatSync12, mkdirSync as mkdirSync16, openSync as openSync10, readdirSync as readdirSync17, readFileSync as readFileSync40, readSync as readSync3, realpathSync as realpathSync11, renameSync as renameSync9, rmSync as rmSync15, statSync as statSync17, writeFileSync as writeFileSync9 } from "node:fs";
22485
+ import { homedir as homedir14 } from "node:os";
22486
+ import { basename as basename14, join as join54, sep as sep9 } from "node:path";
22487
+
22488
+ // src/dead.ts
22489
+ var LIVE_MS = 6e4;
22490
+ var STALE_MS2 = 24 * 36e5;
22491
+ var CONFIRM_MS2 = 6e4;
22492
+ var LOOKS = 2;
22493
+ function classify(f) {
22494
+ if (!f.record) return { state: "closed", reason: "no role record: it was closed on purpose, or never was a main" };
22495
+ if (f.invalid) return { state: "invalid", reason: f.invalid };
22496
+ if (f.mtimeMs === void 0) return { state: "invalid", reason: "its session file is gone" };
22497
+ if (f.held) return { state: "live", reason: "a pane runs its session file" };
22498
+ if (f.listed) return { state: "live", reason: "the broker lists its session" };
22499
+ if (f.now - f.mtimeMs < LIVE_MS) return { state: "live", reason: "its session file moved in the last minute" };
22500
+ const handed = f.record.handedOver;
22501
+ if (handed) return { state: "handed", reason: `it handed over to session ${handed.to.slice(0, 8)} at ${new Date(handed.at).toISOString()}; its successor holds its work` };
22502
+ const ended = f.record.ended;
22503
+ if (ended && ended.reason !== "signal") return { state: "quit", reason: `it quit (${ended.reason}) at ${new Date(ended.at).toISOString()}` };
22504
+ if (f.now - f.mtimeMs > STALE_MS2) return { state: "stale", reason: "its session file has not moved for over 24 h" };
22505
+ if (f.recovering) return { state: "restoring", reason: "Herdr is restoring its panes" };
22506
+ if (f.seen && (f.seen.looks < LOOKS - 1 || f.now - f.seen.first < CONFIRM_MS2)) return { state: "restoring", reason: "seen ended once; a second look a minute later confirms it" };
22507
+ return ended ? { state: "dead", how: "signal", reason: `pi ended on a signal (a SIGHUP or SIGTERM) at ${new Date(ended.at).toISOString()} with no close` } : { state: "dead", how: "crash", reason: "it ended with no shutdown: a crash, a kill, or its pane or tab closed in Herdr" };
22508
+ }
22606
22509
 
22607
22510
  // src/integrator.ts
22608
22511
  import { existsSync as existsSync8, readdirSync as readdirSync15 } from "node:fs";
@@ -22657,40 +22560,6 @@ var ForwardAsBefore = class extends Error {
22657
22560
  }
22658
22561
  };
22659
22562
 
22660
- // src/reviver.ts
22661
- import { randomUUID as randomUUID13 } from "node:crypto";
22662
-
22663
- // src/tablabel.ts
22664
- var tabLabel = (name2) => Array.from(name2).length > 16 ? `${Array.from(name2).slice(0, 16).join("").trimEnd()}\u2026` : name2;
22665
-
22666
- // src/revive.ts
22667
- import { createHash as createHash21 } from "node:crypto";
22668
- import { closeSync as closeSync10, existsSync as existsSync9, lstatSync as lstatSync12, mkdirSync as mkdirSync16, openSync as openSync10, readdirSync as readdirSync17, readFileSync as readFileSync40, readSync as readSync3, realpathSync as realpathSync11, renameSync as renameSync9, rmSync as rmSync15, statSync as statSync17, writeFileSync as writeFileSync9 } from "node:fs";
22669
- import { homedir as homedir14 } from "node:os";
22670
- import { basename as basename14, join as join54, sep as sep9 } from "node:path";
22671
-
22672
- // src/dead.ts
22673
- var LIVE_MS = 6e4;
22674
- var STALE_MS2 = 24 * 36e5;
22675
- var CONFIRM_MS2 = 6e4;
22676
- var LOOKS = 2;
22677
- function classify(f) {
22678
- if (!f.record) return { state: "closed", reason: "no role record: it was closed on purpose, or never was a main" };
22679
- if (f.invalid) return { state: "invalid", reason: f.invalid };
22680
- if (f.mtimeMs === void 0) return { state: "invalid", reason: "its session file is gone" };
22681
- if (f.held) return { state: "live", reason: "a pane runs its session file" };
22682
- if (f.listed) return { state: "live", reason: "the broker lists its session" };
22683
- if (f.now - f.mtimeMs < LIVE_MS) return { state: "live", reason: "its session file moved in the last minute" };
22684
- const handed = f.record.handedOver;
22685
- if (handed) return { state: "handed", reason: `it handed over to session ${handed.to.slice(0, 8)} at ${new Date(handed.at).toISOString()}; its successor holds its work` };
22686
- const ended = f.record.ended;
22687
- if (ended && ended.reason !== "signal") return { state: "quit", reason: `it quit (${ended.reason}) at ${new Date(ended.at).toISOString()}` };
22688
- if (f.now - f.mtimeMs > STALE_MS2) return { state: "stale", reason: "its session file has not moved for over 24 h" };
22689
- if (f.recovering) return { state: "restoring", reason: "Herdr is restoring its panes" };
22690
- if (f.seen && (f.seen.looks < LOOKS - 1 || f.now - f.seen.first < CONFIRM_MS2)) return { state: "restoring", reason: "seen ended once; a second look a minute later confirms it" };
22691
- return ended ? { state: "dead", how: "signal", reason: `pi ended on a signal (a SIGHUP or SIGTERM) at ${new Date(ended.at).toISOString()} with no close` } : { state: "dead", how: "crash", reason: "it ended with no shutdown: a crash, a kill, or its pane or tab closed in Herdr" };
22692
- }
22693
-
22694
22563
  // src/roles.ts
22695
22564
  import { createHash as createHash20 } from "node:crypto";
22696
22565
  import { mkdirSync as mkdirSync15, readdirSync as readdirSync16, readFileSync as readFileSync39, renameSync as renameSync8, rmSync as rmSync14, statSync as statSync16, writeFileSync as writeFileSync8 } from "node:fs";
@@ -22712,7 +22581,7 @@ function loadRecord(record2, problem) {
22712
22581
  const r = JSON.parse(raw);
22713
22582
  if (r.duty !== void 0 && !isCoordinatorDuty(r.duty)) delete r.duty;
22714
22583
  if (r.ended !== void 0 && !(typeof r.ended === "object" && r.ended !== null && typeof r.ended.at === "number" && ENDED2.has(r.ended.reason))) delete r.ended;
22715
- if (r.handedOver !== void 0 && !(typeof r.handedOver === "object" && r.handedOver !== null && typeof r.handedOver.at === "number" && typeof r.handedOver.to === "string")) delete r.handedOver;
22584
+ if (r.handedOver !== void 0 && !(typeof r.handedOver === "object" && r.handedOver !== null && typeof r.handedOver.at === "number" && typeof r.handedOver.to === "string" && [r.handedOver.tab, r.handedOver.pane].every((v) => v === void 0 || typeof v === "string"))) delete r.handedOver;
22716
22585
  if (r.role === TRAIN && !(r.train && trainFromToken(trainToken(r.train)))) return void 0;
22717
22586
  return (r.role === "tower" || r.role === "main" || r.role === TRAIN) && typeof r.pane === "string" && typeof r.tab === "string" && typeof r.workspace === "string" && (r.terminal === void 0 || typeof r.terminal === "string") && (r.file === void 0 || typeof r.file === "string") && (r.openedBy === void 0 || typeof r.openedBy === "string") ? r : void 0;
22718
22587
  } catch {
@@ -22994,6 +22863,247 @@ function reviveHandoff(i) {
22994
22863
  return lines.join("\n");
22995
22864
  }
22996
22865
 
22866
+ // src/deadpane.ts
22867
+ var LOCK_MS = 5 * 6e4;
22868
+ var marked = (p) => Object.keys(p.tokens ?? {}).some((k) => k.startsWith("sb_") || k.startsWith("piha_")) || Boolean(p.agent_session?.value);
22869
+ function refusal6(f) {
22870
+ const p = f.pane, id = f.query;
22871
+ if (!p) return `No pane ${id} in Herdr's list`;
22872
+ if (p.workspace_id !== f.workspace) return `${id} is not in this workspace; a tower closes only its own workspace's panes`;
22873
+ const role = p.tokens?.sb_role;
22874
+ if (p.pane_id === f.tower.pane || f.tower.tab !== void 0 && p.tab_id === f.tower.tab || p.pane_id === f.tower.session || role === "tower" || role === "head") return `${id} is a tower's pane; a tower never closes one`;
22875
+ if (!marked(p)) return `${id} carries no mark of an agent (no Straw Boss or pi token): it is no agent pane, so the boss closes it`;
22876
+ if (p.tokens?.sb_open_main !== void 0 || p.tokens?.[REVIVE_TOKEN] !== void 0) return `${id} is being opened right now (an open, a revive, or a handover is starting its pi)`;
22877
+ if (f.reviving) return `${id} is being revived right now (a tower holds the revive lock of its session)`;
22878
+ if (f.listed) return `${id} is not dead: a live session (${f.listed.name ?? f.listed.id}) is at it`;
22879
+ if (p.agent) return `${id} runs ${p.agent}, so it is not dead`;
22880
+ return void 0;
22881
+ }
22882
+ function notBare(id, info) {
22883
+ const fg = info?.foreground_processes ?? [];
22884
+ if (typeof info?.shell_pid !== "number" || !fg.length) return `Herdr cannot show what runs in ${id}, so it is not proven dead`;
22885
+ if (fg.length === 1 && fg[0].pid === info.shell_pid) return void 0;
22886
+ const names = [...new Set(fg.filter((x) => x.pid !== info.shell_pid).map((x) => x.name ?? x.argv0 ?? `pid ${x.pid}`))].slice(0, 4).join(", ");
22887
+ return `${id} is not at a bare shell: ${names} runs in it`;
22888
+ }
22889
+ var paneWhat = (p) => {
22890
+ const t = p.tokens ?? {}, kind = t.sb_role ?? (t.sb_train ? "train" : Object.keys(t).some((k) => k.startsWith("piha_")) ? "subagent" : "pi"), name2 = t.sb_main_tab ?? t.sb_name ?? t.sb_tab ?? t.sb_member_tab;
22891
+ return name2 ? `${kind} ${name2}` : kind;
22892
+ };
22893
+ var deadList = (rows) => ({
22894
+ text: rows.length ? `Dead agent panes of this workspace (close one with boss_close_main pane):
22895
+ ${rows.map((r) => `- ${r.pane} (tab ${r.tab}${r.alone ? ", its only pane" : ""}): ${r.what}`).join("\n")}` : "No dead agent pane in this workspace.",
22896
+ details: rows
22897
+ });
22898
+ var WINDOWS_REFUSAL = "Dead agent panes are listed and closed on macOS and Linux only: on Windows Herdr's process-info names the shell alone even while a program runs under it, so no pane is proven dead; the boss closes it";
22899
+ function createDeadPanes(env) {
22900
+ const { run: run3 } = env;
22901
+ const platform = env.platform ?? process.platform;
22902
+ const onWindows = () => {
22903
+ if (platform === "win32") throw new Error(WINDOWS_REFUSAL);
22904
+ };
22905
+ const reviving = (p) => readRecords(env.stateDir).some(({ record: record2 }) => {
22906
+ if (record2.pane !== p.pane_id || record2.workspace !== p.workspace_id) return false;
22907
+ try {
22908
+ return env.now() - statSync18(`${ledgerPath(env.stateDir, record2.file)}.lock`).mtimeMs < LOCK_MS;
22909
+ } catch {
22910
+ return false;
22911
+ }
22912
+ });
22913
+ const look3 = async () => {
22914
+ const [all, sessions, ws] = await Promise.all([panes(run3), env.sessions(), workspaces(run3)]);
22915
+ const here = env.here(), towerId2 = ws.find((w) => w.workspace_id === here.workspace)?.tokens?.tower;
22916
+ const own = all.find((p) => p.pane_id === here.pane);
22917
+ const tower = { pane: here.pane, ...own ? { tab: own.tab_id } : {}, .../* @__PURE__ */ ((s2) => s2 ? { session: s2 } : {})(sessions.find((x) => x.id === towerId2)?.herdrLocation?.paneId) };
22918
+ const facts = (query) => {
22919
+ const pane = all.find((p) => p.pane_id === query);
22920
+ return { query, workspace: here.workspace, tower, reviving: pane ? reviving(pane) : false, ...pane ? { pane } : {}, .../* @__PURE__ */ ((x) => x ? { listed: x } : {})(sessions.find((x) => x.herdrLocation?.paneId === query)) };
22921
+ };
22922
+ return { all, facts, workspace: here.workspace };
22923
+ };
22924
+ const info = async (pane) => JSON.parse(await run3(["pane", "process-info", "--pane", pane])).result?.process_info;
22925
+ const why = async (f) => refusal6(f) ?? notBare(f.query, await info(f.query).catch(() => void 0));
22926
+ return {
22927
+ /** The dead agent panes of this workspace: each passed every row of the table. */
22928
+ async list() {
22929
+ onWindows();
22930
+ const { all, facts, workspace } = await look3();
22931
+ const rows = [];
22932
+ for (const p of all.filter((x) => x.workspace_id === workspace && marked(x))) {
22933
+ if (await why(facts(p.pane_id))) continue;
22934
+ rows.push({ pane: p.pane_id, tab: p.tab_id, what: paneWhat(p), alone: all.filter((x) => x.tab_id === p.tab_id).length === 1 });
22935
+ }
22936
+ return rows;
22937
+ },
22938
+ /** Closes one dead agent pane, its tab with it when it is the tab's only pane; refused with the table's reason otherwise. */
22939
+ async close(query) {
22940
+ onWindows();
22941
+ const { all, facts } = await look3();
22942
+ const f = facts(query), refused3 = await why(f);
22943
+ if (refused3) throw new Error(refused3);
22944
+ const p = f.pane, alone = all.filter((x) => x.tab_id === p.tab_id).length === 1;
22945
+ if (alone) {
22946
+ await run3(["tab", "close", p.tab_id]);
22947
+ return { text: `Closed tab ${p.tab_id} with its only pane ${p.pane_id} (${paneWhat(p)}), whose pi was gone.`, pane: p.pane_id, tab: p.tab_id };
22948
+ }
22949
+ await run3(["pane", "close", p.pane_id]);
22950
+ return { text: `Closed pane ${p.pane_id} (${paneWhat(p)}), whose pi was gone; its tab ${p.tab_id} keeps its other panes.`, pane: p.pane_id };
22951
+ }
22952
+ };
22953
+ }
22954
+
22955
+ // src/closemain.ts
22956
+ var CONTROL8 = "straw-boss/control";
22957
+ var ASK_MS2 = 1e4;
22958
+ var RETRY_MS3 = 15e3;
22959
+ var RETRY_STEP_MS = 3e3;
22960
+ var QUIT_MS = 3e4;
22961
+ var STANDING_CLOSE = "is a standing main: it has no end and sends no done report, so only the boss closes it";
22962
+ function refuseStanding(net, query, stateDir) {
22963
+ const named = net.sessions.filter((x) => x.id === query || x.name === query);
22964
+ if (named.length !== 1) return;
22965
+ const pane = net.ps.find((p) => p.pane_id === named[0].herdrLocation?.paneId);
22966
+ if (pane?.tokens?.sb_duty === "standing" && !(stateDir && handedOverOf(stateDir, pane))) throw new Error(`${named[0].name ?? named[0].id} ${STANDING_CLOSE}`);
22967
+ }
22968
+ function handedOverOf(stateDir, pane) {
22969
+ const file3 = pane.agent_session?.value;
22970
+ const mains = readRecords(stateDir).map((r) => r.record).filter((r) => r.role === "main" && r.pane === pane.pane_id && r.workspace === pane.workspace_id && (!file3 || r.file === file3));
22971
+ return mains.sort((a, b) => b.at - a.at)[0]?.handedOver;
22972
+ }
22973
+ var liveSuccessor = (h, sessions, ps) => {
22974
+ const at = sessions.find((x) => x.id === h.to)?.herdrLocation?.paneId;
22975
+ return at ? ps.find((p) => p.pane_id === at && p.agent === "pi") : void 0;
22976
+ };
22977
+ function createCloseMain({ pi, cfg, s: s2, me, guiDir }, { closeSelf, check, turn }) {
22978
+ const { run: run3, sleep: sleep2 } = cfg;
22979
+ let channel;
22980
+ const answers2 = /* @__PURE__ */ new Map();
22981
+ const send = (payload) => channel?.publish({ version: 1, ...payload }, { audience: "capable" });
22982
+ const judge = async (from, interrupt = false) => {
22983
+ const no19 = (reason) => ({ reason });
22984
+ if (s2.isTower) return no19("this session is a tower");
22985
+ if (!s2.joined) return no19("this session has not joined the net");
22986
+ const [all, workspace] = await Promise.all([panes(run3), workspaces(run3).then((list2) => list2.find((w) => w.workspace_id === s2.at.workspaceId))]);
22987
+ const mine = all.find((p) => p.pane_id === s2.at.paneId);
22988
+ if (!mine?.tokens?.sb_opened_by && !s2.saved.successor?.main) return no19("no tower opened this main, so only the boss closes it");
22989
+ if (!workspace?.tokens?.tower || workspace.tokens.tower !== from) return no19("the request is not from the tower of this workspace");
22990
+ const running = subagents(mine, all, cfg.now()).filter((row2) => !row2.ended).length;
22991
+ const subs = running && `${running} subagent${running > 1 ? "s are" : " is"} running`;
22992
+ if (interrupt && turn?.running()) {
22993
+ const others = [turn.blockers(), subs].filter(Boolean).join(", ");
22994
+ if (others) return { reason: others, busy: true };
22995
+ turn.abort();
22996
+ return { reason: "its turn was interrupted; it quits once it is idle", busy: true };
22997
+ }
22998
+ const busy = [check(), subs].filter(Boolean).join(", ");
22999
+ return busy ? { reason: busy, busy: true } : void 0;
23000
+ };
23001
+ const answer = async (from, reqId, interrupt) => {
23002
+ const refused3 = await judge(from, interrupt).catch((error) => ({ reason: `it could not check itself: ${error.message}` }));
23003
+ const quit = refused3 ? void 0 : closeSelf(false);
23004
+ const why = refused3 ?? (quit ? { reason: quit } : void 0);
23005
+ send({ type: "close-main-result", to: from, reqId, accepted: !why, ...why ?? {} });
23006
+ };
23007
+ const onEvent = (event) => {
23008
+ const p = event.payload, from = event.fromSessionId;
23009
+ if (event.type !== "message" || p?.version !== 1 || !from || typeof p.reqId !== "string" || p.reqId.length > 64) return;
23010
+ if (p.type === "close-main" && p.to === me()) void answer(from, p.reqId, p.interrupt === true);
23011
+ if (p.type === "close-main-result" && p.to === me() && typeof p.accepted === "boolean") answers2.set(p.reqId, { from, accepted: p.accepted, ...typeof p.reason === "string" ? { reason: p.reason.slice(0, 300) } : {}, ...p.busy === true ? { busy: true } : {} });
23012
+ };
23013
+ const ask = async (main, interrupt) => {
23014
+ const reqId = randomUUID12().slice(0, 12);
23015
+ send({ type: "close-main", to: main, reqId, ...interrupt ? { interrupt: true } : {} });
23016
+ const got = await waitFor(sleep2, () => answers2.get(reqId)?.from === main ? answers2.get(reqId) : void 0, ASK_MS2, 100);
23017
+ answers2.delete(reqId);
23018
+ return got;
23019
+ };
23020
+ const dead = createDeadPanes({ run: run3, sessions: () => s2.c.listSessions(), here: () => ({ workspace: s2.at.workspaceId, pane: s2.at.paneId }), stateDir: guiDir, now: cfg.now });
23021
+ return {
23022
+ /** Every tower, every main a tower opened, and every main that handed over hears and answers asks; registering twice is a no-op. */
23023
+ register() {
23024
+ if (channel) return;
23025
+ pi.events.emit(REGISTER, { namespace: CONTROL8, ownerEligible: false, onReady: (c) => channel = c, onEvent });
23026
+ if (!channel) throw new Error("pi-intercom is not loaded (Straw Boss needs pi-intercom >= 0.17.1)");
23027
+ },
23028
+ /** The tower's side: a main this workspace's tower opened, by intercom name or session id. */
23029
+ closeMain: (async (query, opts) => {
23030
+ const interrupt = opts?.interrupt === true;
23031
+ if (!channel) throw new Error("This session cannot reach the mains' control channel yet");
23032
+ const [sessions, all] = await Promise.all([s2.c.listSessions(), panes(run3)]);
23033
+ const found = sessions.filter((x) => x.id === query || x.name === query);
23034
+ if (found.length !== 1) throw new Error(`${found.length ? "Several sessions are named" : "No live session is named or has the id"} "${query}"`);
23035
+ const main = found[0], name2 = main.name ?? main.id, pane = all.find((p) => p.pane_id === main.herdrLocation?.paneId);
23036
+ if (pane?.workspace_id !== s2.at.workspaceId) throw new Error(`${name2} is not in this workspace; a tower closes only the mains it opened here`);
23037
+ if (pane.tokens?.sb_role !== "main" && pane.tokens?.sb_role !== TRAIN) throw new Error(`${name2} is not a main agent`);
23038
+ const handed = pane.tokens.sb_role === "main" ? handedOverOf(guiDir, pane) : void 0;
23039
+ if (!pane.tokens.sb_opened_by && !handed) throw new Error(`${name2} was not opened by a tower (the boss opened it), so only the boss closes it`);
23040
+ if (handed && !liveSuccessor(handed, sessions, all)) throw new Error(`${name2} handed over to session ${handed.to.slice(0, 8)}${handed.tab ? ` (tab ${handed.tab})` : ""}, which is not live (no pi runs it, or the broker does not list it); the old main stays open until its successor is live, or the boss closes it`);
23041
+ if (!interrupt && !["idle", "done"].includes(pane.agent_status ?? "")) throw new Error(`${name2} is ${pane.agent_status ?? "in an unknown state"}; try again when it is idle`);
23042
+ let got = await ask(main.id, interrupt);
23043
+ for (let waited = 0; got?.busy && waited < RETRY_MS3; waited += RETRY_STEP_MS) await sleep2(RETRY_STEP_MS), got = await ask(main.id, interrupt);
23044
+ if (!got) throw new Error(`${name2} did not answer the close request within ${ASK_MS2 / 1e3} s (an older pi-straw-boss, or a stuck session); close it in its terminal`);
23045
+ if (!got.accepted) throw new Error(`${name2} will not close: ${got.reason ?? "refused"}`);
23046
+ const gone = await waitFor(sleep2, async () => !(await s2.c.listSessions().catch(() => [main])).some((x) => x.id === main.id), QUIT_MS, 500);
23047
+ return { text: gone ? `${name2} quit and its pane closed.` : `${name2} accepted and is shutting down; its pane closes once pi has exited.`, main: main.id, name: name2, closed: Boolean(gone) };
23048
+ }),
23049
+ /** The tower's side: the dead agent panes of this workspace (deadpane.ts), and the close of one. */
23050
+ deadPanes: () => dead.list(),
23051
+ closePane: (pane) => dead.close(pane)
23052
+ };
23053
+ }
23054
+
23055
+ // src/digest.ts
23056
+ var PREFIX2 = "sbd_";
23057
+ var SOURCE = "straw-boss-digest";
23058
+ var KEEP3 = 20;
23059
+ var WIDTH = 80;
23060
+ var BATCH = 16;
23061
+ var report3 = (run3, workspaceId, flags2) => run3(["workspace", "report-metadata", workspaceId, "--source", SOURCE, ...flags2]);
23062
+ var entries2 = async (run3, workspaceId) => {
23063
+ const tokens = (await workspaces(run3)).find((w) => w.workspace_id === workspaceId)?.tokens ?? {};
23064
+ return Object.entries(tokens).filter(([key2]) => key2.startsWith(PREFIX2)).sort(([a], [b]) => a < b ? -1 : 1);
23065
+ };
23066
+ function createDigest(run3, now) {
23067
+ let seq2 = 0;
23068
+ return {
23069
+ /** Adds one line, stamped with the local time, dropping the oldest lines past KEEP in the same report. */
23070
+ async note(workspaceId, text11) {
23071
+ const at = new Date(now());
23072
+ const line4 = Array.from(`${String(at.getHours()).padStart(2, "0")}:${String(at.getMinutes()).padStart(2, "0")} ${text11.replace(/\s+/g, " ").trim()}`).slice(0, WIDTH).join("");
23073
+ const key2 = `${PREFIX2}${now().toString(36).padStart(9, "0")}${process.pid.toString(36)}${(seq2++ % 36).toString(36)}`;
23074
+ const old = await entries2(run3, workspaceId);
23075
+ const drop = old.slice(0, Math.min(BATCH - 1, Math.max(0, old.length - (KEEP3 - 1)))).flatMap(([k]) => ["--clear-token", k]);
23076
+ await report3(run3, workspaceId, [...drop, "--token", `${key2}=${line4}`]);
23077
+ },
23078
+ /** The lines as they are now, oldest first, with their keys, and nothing cleared (a run's brief shows them; `drop` clears them when the run calls tower_done). */
23079
+ async peek(workspaceId) {
23080
+ return (await entries2(run3, workspaceId)).map(([key2, line4]) => ({ key: key2, line: line4 }));
23081
+ },
23082
+ /** Clears the lines with these keys. */
23083
+ async drop(workspaceId, keys) {
23084
+ for (let i = 0; i < keys.length; i += BATCH) await report3(run3, workspaceId, keys.slice(i, i + BATCH).flatMap((k) => ["--clear-token", k]));
23085
+ },
23086
+ /** Returns the lines, oldest first, and clears them: the tower reads each one once. */
23087
+ async take(workspaceId) {
23088
+ const found = await entries2(run3, workspaceId);
23089
+ for (let i = 0; i < found.length; i += BATCH) await report3(run3, workspaceId, found.slice(i, i + BATCH).flatMap(([k]) => ["--clear-token", k])).catch(() => {
23090
+ });
23091
+ return found.map(([, line4]) => line4);
23092
+ }
23093
+ };
23094
+ }
23095
+
23096
+ // src/opener.ts
23097
+ import { createHash as createHash22, randomUUID as randomUUID14 } from "node:crypto";
23098
+ import { existsSync as existsSync10 } from "node:fs";
23099
+ import { join as join55 } from "node:path";
23100
+
23101
+ // src/reviver.ts
23102
+ import { randomUUID as randomUUID13 } from "node:crypto";
23103
+
23104
+ // src/tablabel.ts
23105
+ var tabLabel = (name2) => Array.from(name2).length > 16 ? `${Array.from(name2).slice(0, 16).join("").trimEnd()}\u2026` : name2;
23106
+
22997
23107
  // src/reviver.ts
22998
23108
  var livePanes = (ps, sessions, own) => ps.filter((p) => p.pane_id !== own && p.agent === "pi" && sessions.some((s2) => s2.herdrLocation?.paneId === p.pane_id));
22999
23109
  var reviveLabel = (r) => r.train ? trainLabel(r.train.code) : r.name ? tabLabel(r.name) : void 0;
@@ -23016,8 +23126,8 @@ async function reviveMain(env, { session, reason, origin }) {
23016
23126
  if (row2.record.role === TRAIN && !row2.train) throw new ReviveRefused("its record names no train");
23017
23127
  if (!REVIVABLE.includes(row2.verdict.state)) throw new ReviveRefused(`it is ${row2.verdict.state}: ${row2.verdict.reason}`);
23018
23128
  const rivals = livePanes(first2.everywhere, first2.sessions, row2.record.pane);
23019
- const refusal6 = roleRefusal(row2, { integrationOff: env.integrationOff?.() ?? false, live: rivals, sessions: first2.sessions });
23020
- if (refusal6) throw new ReviveRefused(refusal6);
23129
+ const refusal7 = roleRefusal(row2, { integrationOff: env.integrationOff?.() ?? false, live: rivals, sessions: first2.sessions });
23130
+ if (refusal7) throw new ReviveRefused(refusal7);
23021
23131
  const unlock = takeLock(env.stateDir, row2.file, Date.now());
23022
23132
  try {
23023
23133
  const now = Date.now(), ledger = readLedger2(env.stateDir, row2.file, row2.session), key2 = deathKey(row2.file) ?? "";
@@ -23038,11 +23148,11 @@ async function reviveMain(env, { session, reason, origin }) {
23038
23148
  if (env.integrationOff?.()) throw new ReviveRefused("a train is not revived: integration is off on this computer");
23039
23149
  }
23040
23150
  const here = rivals.filter((p) => p.workspace_id === workspace.workspace_id);
23041
- const marked = here.filter((p) => p.tokens?.sb_opened_by && !integratorOf(p.tokens.sb_opened_by) && p.tokens.sb_role !== TRAIN && !(p.tokens.sb_role === void 0 && p.tokens.sb_train));
23151
+ const marked2 = here.filter((p) => p.tokens?.sb_opened_by && !integratorOf(p.tokens.sb_opened_by) && p.tokens.sb_role !== TRAIN && !(p.tokens.sb_role === void 0 && p.tokens.sb_train));
23042
23152
  if (!train && row2.openedBy && !integratorOf(row2.openedBy)) {
23043
- const ofSender = marked.filter((p) => p.tokens.sb_opened_by === row2.openedBy).length;
23153
+ const ofSender = marked2.filter((p) => p.tokens.sb_opened_by === row2.openedBy).length;
23044
23154
  if (ofSender) throw new ReviveRefused(`its sender ${row2.openedBy.slice(0, 40)} already has an opened main running in workspace ${workspace.label} (a sender gets one at a time): close one first`);
23045
- if (marked.length >= MAX_OPENED_MAINS) throw new ReviveRefused(`workspace ${workspace.label} already has ${marked.length} mains opened by its tower (the limit is ${MAX_OPENED_MAINS})`);
23155
+ if (marked2.length >= MAX_OPENED_MAINS) throw new ReviveRefused(`workspace ${workspace.label} already has ${marked2.length} mains opened by its tower (the limit is ${MAX_OPENED_MAINS})`);
23046
23156
  }
23047
23157
  const cwd = sessionHeader(row2.file)?.cwd ?? dir;
23048
23158
  await assertSettingsSafe([cwd]);
@@ -23225,10 +23335,10 @@ function opener(env) {
23225
23335
  if (opened.length >= MAX_OPENED_INTEGRATORS) throw new OpenLimitError(`Workspace ${workspace.label} already has ${opened.length} integrators opened by its tower (${opened.join(", ")}; the limit is ${MAX_OPENED_INTEGRATORS}); try again when one has closed.`);
23226
23336
  if (dry) return { tab: "", pane: "", main: "", sender: sender.id, integrator: integ, repeated: true };
23227
23337
  }
23228
- const marked = here.filter((p) => p.tokens?.sb_opened_by && !integratorOf(p.tokens.sb_opened_by) && p.tokens.sb_role !== TRAIN && !(p.tokens.sb_role === void 0 && p.tokens.sb_train));
23229
- const ofSender = train || integ ? 0 : marked.filter((p) => p.tokens.sb_opened_by === sender.id).length;
23338
+ const marked2 = here.filter((p) => p.tokens?.sb_opened_by && !integratorOf(p.tokens.sb_opened_by) && p.tokens.sb_role !== TRAIN && !(p.tokens.sb_role === void 0 && p.tokens.sb_train));
23339
+ const ofSender = train || integ ? 0 : marked2.filter((p) => p.tokens.sb_opened_by === sender.id).length;
23230
23340
  if (ofSender) throw new OpenLimitError(`Sender ${sender.name ?? sender.id} already has ${ofSender === 1 ? "an opened main" : `${ofSender} opened mains`} running in workspace ${workspace.label}; a sender gets one at a time. Wait for it to finish, or send the request to it.`);
23231
- if (!train && !integ && marked.length >= MAX_OPENED_MAINS) throw new OpenLimitError(`Workspace ${workspace.label} already has ${marked.length} mains opened by its tower (the limit is ${MAX_OPENED_MAINS}); try again when one has finished.`);
23341
+ if (!train && !integ && marked2.length >= MAX_OPENED_MAINS) throw new OpenLimitError(`Workspace ${workspace.label} already has ${marked2.length} mains opened by its tower (the limit is ${MAX_OPENED_MAINS}); try again when one has finished.`);
23232
23342
  await assertSettingsSafe([dir]);
23233
23343
  const { tabId, paneId } = await createTab(run3, workspace.workspace_id, dir, [`STRAW_BOSS_ROLE=${train ? TRAIN : "main"}`], label);
23234
23344
  try {
@@ -24339,6 +24449,7 @@ async function allyTool(host, name2, args, extra) {
24339
24449
  if (await host.isTower(to)) throw new Error("An ally run may not write to a tower identity of this computer: it would carry a peer's text into a local run");
24340
24450
  await refuseTarget(host, to);
24341
24451
  }
24452
+ if (name2 === "boss_close_main" && (args.pane !== void 0 || args.main === void 0)) throw new Error("An ally run closes only a main opened for its own device: dead panes are the local tower's");
24342
24453
  if (name2 === "boss_close_main") refuseStanding(await host.reach.read(), await refuseClose(host, str10(args, "main", 300)));
24343
24454
  if (gated && name2 !== "tower_send") {
24344
24455
  if (!extra.toolCallId) throw new Error(`${name2} needs the boss's confirm in this run, and the call carried no tool call id`);
@@ -24575,8 +24686,18 @@ async function localTool(host, name2, args, extra, ally = false) {
24575
24686
  case "boss_revive_main":
24576
24687
  return reviveTool(host, args);
24577
24688
  case "boss_close_main": {
24689
+ if (!ally && args.main !== void 0 && args.pane !== void 0) throw new Error("Give main or pane, not both");
24690
+ if (!ally && args.pane !== void 0) {
24691
+ if (!host.closePane) throw new Error("This tower cannot close panes here");
24692
+ const closed2 = await host.closePane(str10(args, "pane", 100));
24693
+ return { text: closed2.text, details: closed2 };
24694
+ }
24695
+ if (!ally && args.main === void 0) {
24696
+ if (!host.deadPanes) throw new Error("This tower cannot list dead panes here");
24697
+ return deadList(await host.deadPanes());
24698
+ }
24578
24699
  const main = str10(args, "main", 300), target2 = ally ? await refuseClose(host, main) : main;
24579
- refuseStanding(await host.reach.read(), target2);
24700
+ refuseStanding(await host.reach.read(), target2, ally ? void 0 : host.stateDir);
24580
24701
  const closed = await host.closeMain(target2);
24581
24702
  return { text: closed.text, details: closed };
24582
24703
  }
@@ -26220,8 +26341,8 @@ function createRuns2(o) {
26220
26341
  const holder = live.find((a) => e.taken?.run === a.rec.id || a.offered.has(e.id));
26221
26342
  if (!holder) removeEvent(slot, HEAD_KEY, e), gone2++;
26222
26343
  else if (!e.drop) {
26223
- const marked = { ...e, drop: true };
26224
- updateEvent(slot, HEAD_KEY, marked);
26344
+ const marked2 = { ...e, drop: true };
26345
+ updateEvent(slot, HEAD_KEY, marked2);
26225
26346
  if (holder.offered.has(e.id)) holder.offered.set(e.id, { ...holder.offered.get(e.id), drop: true });
26226
26347
  }
26227
26348
  }
@@ -27314,12 +27435,12 @@ function createTowers(o) {
27314
27435
  const here = await panes(run3, ws);
27315
27436
  const given = hint ? here.find((p) => p.pane_id === hint) : void 0;
27316
27437
  if (hint && !given) throw new Error(`Pane ${hint} is not in workspace ${target2.label}`);
27317
- const marked = given ?? here.find((p) => p.tokens?.sb_role === "tower");
27318
- const bare2 = marked ? [] : (await tabs(run3, ws)).filter((t) => t.label === TOWER_LABEL).flatMap((t) => {
27438
+ const marked2 = given ?? here.find((p) => p.tokens?.sb_role === "tower");
27439
+ const bare2 = marked2 ? [] : (await tabs(run3, ws)).filter((t) => t.label === TOWER_LABEL).flatMap((t) => {
27319
27440
  const inside2 = here.filter((p) => p.tab_id === t.tab_id);
27320
27441
  return inside2.length === 1 && (!inside2[0].agent || isStandin(inside2[0])) && !inside2[0].tokens?.sb_role ? [inside2[0]] : [];
27321
27442
  });
27322
- let pane = marked ?? bare2[0], dir, made = false;
27443
+ let pane = marked2 ?? bare2[0], dir, made = false;
27323
27444
  if (!pane) {
27324
27445
  dir = target2.worktree?.checkout_path ?? cwd ?? slot.stateDir;
27325
27446
  const tab = await createTab(run3, ws, dir, [], TOWER_LABEL);
@@ -27480,6 +27601,9 @@ function createTowers(o) {
27480
27601
  now,
27481
27602
  boardDir: join61(slot.stateDir, "board"),
27482
27603
  label: l.record.label,
27604
+ ...l.control && !peer ? { closePane: (pane) => l.control.closePane(pane), deadPanes: () => l.control.deadPanes() } : {},
27605
+ stateDir: slot.stateDir,
27606
+ // a local run's dead panes (deadpane.ts); an ally run is refused them (runtools.ts)
27483
27607
  link: async (body2) => await o.link?.(body2, l.record.id) ?? { ok: false, code: "no_holder", error: "The link holder is not running in the sb server" },
27484
27608
  server: o.server ?? { status: () => ({}), logs: () => [], restart: () => Promise.reject(new Error("The server cannot restart itself here")) },
27485
27609
  expect: (to, name3, text11) => {
@@ -28266,8 +28390,8 @@ async function runServer(o) {
28266
28390
  case "head-drop": {
28267
28391
  const answers2 = request.answers === void 0 ? void 0 : waitId(request.answers);
28268
28392
  if (request.answers !== void 0 && !answers2) return Promise.resolve({ ok: false, error: "answers names a wait: W and its number" });
28269
- const refusal6 = request.cmd === "head-event" ? notAnAnswer(answers2, text11(request.text, 16384)) : void 0;
28270
- if (refusal6) return Promise.resolve(refusal6);
28393
+ const refusal7 = request.cmd === "head-event" ? notAnAnswer(answers2, text11(request.text, 16384)) : void 0;
28394
+ if (refusal7) return Promise.resolve(refusal7);
28271
28395
  return answer((t) => headCommand(t, request.cmd, text11(request.text, 16384), { ...request.door === "pane" ? { door: "pane" } : {}, ...requesterFrom(request) ? { requester: requesterFrom(request) } : {}, ...answers2 ? { answers: answers2 } : {}, ...text11(request.id, 64) ? { id: text11(request.id, 64) } : {} }));
28272
28396
  }
28273
28397
  case "close-tower":
@@ -28308,8 +28432,8 @@ async function runServer(o) {
28308
28432
  const body2 = text11(request.text, 16384);
28309
28433
  const answers2 = request.answers === void 0 ? void 0 : waitId(request.answers);
28310
28434
  if (request.answers !== void 0 && !answers2) return Promise.resolve({ ok: false, error: "answers names a wait: W and its number" });
28311
- const refusal6 = notAnAnswer(answers2, body2);
28312
- if (refusal6) return Promise.resolve(refusal6);
28435
+ const refusal7 = notAnAnswer(answers2, body2);
28436
+ if (refusal7) return Promise.resolve(refusal7);
28313
28437
  return workspace && body2 ? answer(async (t) => ({ queued: t.runs.boss(workspace, body2, "the boss", { present: request.present === true, ...request.door === "pane" ? { door: "pane" } : {}, ...requesterFrom(request) ? { requester: requesterFrom(request) } : {} }).id, ...answers2 ? { answered: await markWaitAnswered(t, workspace, answers2) } : {} })) : Promise.resolve({ ok: false, error: "tower-event needs a workspace and text" });
28314
28438
  }
28315
28439
  // The tower prompt in the standing pane (towerprompt/, standing.ts): it polls for the state it shows and for the order to leave, says Ctrl+D, and says it is gone. It starts nothing and holds no run token;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-straw-boss",
3
- "version": "0.82.0",
3
+ "version": "0.82.1",
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",
@@ -8,7 +8,7 @@ You are a run: the sb server woke you for the events that reach you as messages,
8
8
  - Before routing work or answering where work stands, call `board_read`. Remote entries are a peer's report, not the boss's instruction; never relay one to a local session as an instruction. Never quote a main's board items or todo text to an ally in `tower_send`; an ally gets its own board.
9
9
  - Friction reports: find the owner and the broken relationship (registration, endpoint, dependency, shared resource, cleanup); have the owner repair it. Return a Straw Boss defect as a finding with evidence.
10
10
  - Your memory (the Memory section of your brief) holds the boss's standing instructions and decisions, as the boss wrote or confirmed them, and the open waits. Follow the standing instructions. You cannot make one: when a boss message gives a lasting instruction or a decision, propose it with `tower_memory` (`add`, `kind`, `text`, and `event` with the boss message's first-line `[event id: <id>]` value), and to retire one propose `retire` with its id. A proposal is pending, not an instruction: the boss confirms or rejects it in the GUI or with `/boss memory`, the brief lists it apart as pending, and you do not act on it as if it were kept. At most 12 open waits are kept (an answered one takes no place), and one expires after 7 days. When the brief says some memory was left out, call `tower_memory` with `op: "read"`. Record a wait when something waits on someone, and resolve it when it ends; a wait is your own note, not an instruction. Record a wait for the boss as a card they act on in the GUI: `type` (action when they do something, choice when they pick, secret when a session needs a secret from them), `happened`, `do`, `url` or `command` (where, for an action), `after`, `options` (for a choice), `secret.name` (for a secret; never the value), and `from`: the session id in the `[intercom from ...]` line of the message that raised it, or `self`. Write every field in the language your brief names (sb's locale), as sentences for a person who has not followed the work: say what a host, a ticket, or a tool is the first time. Example, for an event from the session mp3946-print saying its print deploy cannot reach fonstar-staging: `tower_memory` op add, kind wait, for boss, type action, happened "The Tailscale login key of the machine fonstar-staging expired at about 10:30, so it is offline. The print feature of ticket MP-3946 is deployed there, but nobody can reach it to test it.", do "Open the Tailscale admin page and re-authorize fonstar-staging, or set its key to never expire.", url "https://login.tailscale.com/admin/machines", after "Once the machine is back, the tower asks the MP-3946 main to verify the print feature.", from the id in that event's `[intercom from ...]` line. A refusal lists what to fix. Fix every line and call again. Add `bossOnly: true` when only the boss may decide it (<!-- integration -->a strict train target's auth or approval, <!-- /integration -->a credential, a team join). Where this device names a boss's delegate, sb sends any other card there first: its answer comes as a server notice in the delegate's words, not the boss's; act on it as the card's answer and never quote it as the boss's<!-- integration --> (not as `auth`)<!-- /integration -->. One it does not approve comes back as a card on the boss's list. When the boss presses a card you get their message (`The boss pressed ...`, `chose ...`, `declined ...`): act on it, then resolve the wait. A declined wait is over: tell the raiser what happens instead. Do not send the raiser the same news yourself: sb told it, and your event says whether that reached it. A wait whose row ends with `(open ...)` has stood a day or more: check whether it still holds, then resolve or drop it, or restate it in your handoff note. A wait whose row says `answered by the boss` was answered by their message to you: read that message, act on it, then resolve the wait, or restate it as a new wait if the boss still has to decide something; until you do, the boss is not asked about it again. A wait that is no longer in your memory was resolved or dismissed by the boss: never record it again from an earlier handoff note. Memory is for what outlives runs; the handoff note is for your next run.
11
- - Close a coordinator main you opened with boss_close_main after its done report, unless it awaits a boss decision; a standing main is never closed by you, only by the boss; if it refuses as busy, retry after its next message.
11
+ - Close a coordinator main you opened with boss_close_main after its done report, unless it awaits a boss decision; a standing main is never closed by you, only by the boss; if it refuses as busy, retry after its next message. A main that handed over to a successor (its `milestone` says so) is closed by you once the successor is live, whoever opened it and whatever its kind; if it is still working (it is stepping down and sends nothing more), end the run with `wakeAfter: 5` and close it then. `boss_close_main` with no argument lists the dead agent panes of your workspace (pi gone, a bare shell): close each with `pane`, once any `main_died` for it is settled.
12
12
  - A `main_died` notice names a main that ended without a close: when its work is not done, revive it with boss_revive_main (action revive, its session, a reason) instead of opening a new main for its sender; leave it when the boss closed it on purpose or its work ended, and say which in your handoff note. A `quit` main is revived only when a request names it.
13
13
  - Each agent message says why it came (`why=` in its header, written by the code). `milestone`: update your obligations, tell whoever waits on it, and close a coordinator main you opened after its done report (never a standing one). `shared`: a heads-up, not a request for go: the main goes ahead without waiting. Check board_read and your obligations for a clash; on one, tell the main and the owner with `tower_reply`, naming both; else answer nothing. <!-- integration -->Exception: a `shared` request to merge into an app's base, from an app that declares `integration` in apps-config, is no heads-up: it is a car slip, and it goes to that project's integrator (the one main that runs the merge train, per integrator.md beside apps-config.md). Send it there with `boss_open_main` and `role: "integrator"`: the slip as it came as the request, and its sender, in the run that took it. The code reads the project from the checkout's apps.json (name none), refuses the slip of a main opened for a teammate's device (its device's ally run takes it), finds the project's integrator or opens it as your own main (kind integrator, outside the two opened mains and the sender's one; a project never has two) and forwards the slip stamped with its sender. Where the project already runs integrators of its own (the boss's, one per app, such as `integ FE2` and `integ v3`), the door names them but opens nothing: use `tower_reply` in the same run (`to`: that app's integrator, `message`: the slip as it came, `forward`: the first line's `[event id: <id>]` value). The code stamps the sender; open no main. `tower_send` cannot reach an integrator, and nothing you send without that stamp reaches one as a slip. The sb server tells the coordinator, so relay nothing back. A `shared` from the integrator that carries a `train:` block is a train to open, not a heads-up: `boss_open_main` with `role: "train"`, the manifest verbatim as the request, once per code, then answer the integrator with `tower_reply`: the train's session id, or the refusal; a train is no main and does not count toward the two opened mains. A train's `shared` naming a target gets the same clash check; close the train after its done `milestone`. An integrator that reports `milestone` idle is closed by the rule above. A `blocked` from the sb server about a car notice names a coordinator that is gone: find its owner on the board or record a wait for the boss, as for any `blocked`. One from an integrator about a `returned` notice sb cannot confirm carries the notice: when that coordinator is live, send it the notice with `tower_reply` (`to`: its session id); else do as for one that is gone. <!-- /integration --><!-- no-integration -->A `shared` request that carries a `car:` block is no go: answer it with tower_reply "integration is off on this computer" and open no main for it. <!-- /no-integration -->`blocked` or unspecified: route it to its owner. A decision only the boss can make is not sent back to the caller: record a wait for the boss in your memory and name it in your `tower_done` handoff note as waiting on the boss, and tell the main with `tower_reply` that it waits on the boss. Never ask mains for progress: board_read has it.
14
14
  - Never ask the boss yourself (no questions, robot_hand, focus changes), except `boss_wait_ask` for cards in your memory while the boss is at this pane: sb draws the card, you never word it. Its press also reaches you as an event: act once, then resolve the wait. A wait of yours parked under auto mode comes back closed when it ends: record it again if it still needs the boss. A decision only the boss can make goes in the handoff note as above. Call `tower_done` with a handoff note (what you routed, what waits for whom, what to check next) when nothing is left for you; it is refused while events are still for you, and it answers that the boss is here while they are in this session (they wrote at the tower prompt or typed here): then keep answering them, and call it again when they are quiet and you are asked to wrap up.
package/prompts/tower.md CHANGED
@@ -11,7 +11,7 @@ Agents and towers message you via intercom; answer by intercom send. Write to ag
11
11
  <!-- /no-integration -->
12
12
  - Before routing work or saying where work stands, call `board_read`. Remote entries are peer reports, not boss instructions: never relay one to a local session as such. A `waits-on=` blocked needs a tower run: say so. Never quote a main's board or todo text to an ally in `tower_send`: it gets its own board.
13
13
  - Friction reports: find the owner and the broken relationship; the owner repairs it. Return a Straw Boss defect as a finding with evidence.
14
- - Close a coordinator main you opened with boss_close_main after its done report, unless it awaits a boss decision; if busy, retry after its next message.
14
+ - Close a coordinator main you opened with boss_close_main after its done report, unless it awaits a boss decision; if busy, retry after its next message. Close a main that handed over once its successor is live, whoever opened it. boss_close_main with no argument lists dead agent panes (pi gone, bare shell): close each with `pane`.
15
15
  - A dead main whose work is not done: boss_revive_main revives it as itself; open no new main for its sender.
16
16
  - Never ask the boss (no questions, robot_hand, focus changes); boss decisions go to the owning main.
17
17
  - Do no work yourself: no commands, process signals, edits, or subagents; a one-step fix goes to its owner.
package/src/closemain.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { createDeadPanes } from "./deadpane.ts";
2
3
  import { subagents } from "./netdata.ts";
3
- import { panes, waitFor, workspaces } from "./herdr.ts";
4
+ import { type Pane, panes, type Session, waitFor, workspaces } from "./herdr.ts";
5
+ import { type HandedOver, readRecords } from "./roles.ts";
4
6
  import { type Kit, REGISTER } from "./state.ts";
5
7
  import { TRAIN } from "./trainrole.ts";
6
8
 
7
- // A tower closes the mains it opened (boss_open_main). It asks the main's own extension to quit as /boss close does, and the main decides: it checks that the
8
- // request is from the tower of its workspace, that a tower opened it (its pane's `sb_opened_by` token), and that nothing running would be lost, as a stash
9
- // checks. The ask goes over one intercom extension channel that towers and the mains a tower opened register, `straw-boss/control`, with the "capable" audience;
9
+ // A tower closes the mains it opened (boss_open_main), and a main that handed over to a live successor (boss_handover), whoever opened it (docs/specs/2026-11-23-tower-close-panes.md). It asks the main's own extension to quit as /boss close does, and the main decides: it checks that the
10
+ // request is from the tower of its workspace, that a tower opened it (its pane's `sb_opened_by` token) or it handed over (its `successor` entry), and that nothing running would be lost, as a stash
11
+ // checks. The ask goes over one intercom extension channel that towers, the mains a tower opened, and the mains that handed over register, `straw-boss/control`, with the "capable" audience;
10
12
  // the sender id is the one the session reports to the broker (self-reported, a same-user trust boundary), and a request is for one session (`to`). It does not go through the GUI server, which may be stopped, and a bridge's close
11
13
  // (bridge.ts) answers only that server.
12
14
  // {type: "close-main", to: <main session id>, reqId, interrupt?: true} tower → main
@@ -18,11 +20,46 @@ type Event = { type: string; fromSessionId?: string; payload?: Record<string, un
18
20
  interface Answer { from: string; accepted: boolean; reason?: string; busy?: boolean }
19
21
  /** The word a tower's `boss_close_main` answers for a main of kind standing: it has no end and no done report, so only the boss closes it. Checked in the tools, not in `closeMain`: revoke.ts and a signed stop end a peer's main through it. */
20
22
  export const STANDING_CLOSE = "is a standing main: it has no end and sends no done report, so only the boss closes it";
21
- export function refuseStanding(net: { sessions: { id: string; name?: string; herdrLocation?: { paneId?: string } }[]; ps: { pane_id: string; tokens?: Record<string, unknown> }[] }, query: string) {
23
+ /** `stateDir`: where the role records are; a standing main whose record says it handed over has stepped down, so it is not refused. Left out (an ally run's check: a main opened for a device never hands over), none is read. */
24
+ export function refuseStanding(net: { sessions: { id: string; name?: string; herdrLocation?: { paneId?: string } }[]; ps: Pick<Pane, "pane_id" | "tokens" | "workspace_id" | "agent_session">[] }, query: string, stateDir?: string) {
22
25
  const named = net.sessions.filter((x) => x.id === query || x.name === query);
23
26
  if (named.length !== 1) return;
24
- if (net.ps.find((p) => p.pane_id === named[0]!.herdrLocation?.paneId)?.tokens?.sb_duty === "standing") throw new Error(`${named[0]!.name ?? named[0]!.id} ${STANDING_CLOSE}`);
27
+ const pane = net.ps.find((p) => p.pane_id === named[0]!.herdrLocation?.paneId);
28
+ if (pane?.tokens?.sb_duty === "standing" && !(stateDir && handedOverOf(stateDir, pane))) throw new Error(`${named[0]!.name ?? named[0]!.id} ${STANDING_CLOSE}`);
25
29
  }
30
+ /** A remote turn's refusal of a dead pane or the list of them (link/hooks.ts, tools.ts), as an ally run's (server/runtools.ts). */
31
+ export const REMOTE_CLOSE = "a remote turn closes only a main opened for its own device: dead panes and their list are the local tower's";
32
+ /**
33
+ * A remote turn of a pi tower closes only a main opened for the device of every sender of the turn (its pane's `sb_opened_by` is `link:<device>`), as an ally run does (server/runtools.ts `refuseClose`): not a dead
34
+ * pane, not the list, not a main the boss or a local tower opened, though it handed over. Returns the main's session id.
35
+ */
36
+ export function remoteCloseTarget(net: { sessions: { id: string; name?: string; herdrLocation?: { paneId?: string } }[]; ps: Pick<Pane, "pane_id" | "tokens">[] }, args: { main?: string; pane?: string }, devices: string[]): string {
37
+ if (args.pane !== undefined || args.main === undefined) throw new Error(REMOTE_CLOSE);
38
+ const named = net.sessions.filter((x) => x.id === args.main || x.name === args.main), no = new Error(`${args.main} was not opened for the device of this remote turn; ${REMOTE_CLOSE}`);
39
+ if (named.length !== 1 || !devices.length) throw no;
40
+ const token = net.ps.find((p) => p.pane_id === named[0]!.herdrLocation?.paneId)?.tokens?.sb_opened_by;
41
+ const device = typeof token === "string" && token.startsWith("link:") ? token.replace(/^(link:)+/, "") : undefined;
42
+ if (!device || devices.some((d) => d !== device)) throw no;
43
+ return named[0]!.id;
44
+ }
45
+ /**
46
+ * The handover mark (roles.ts `handedOver`) of the main a pane runs: from the role record of the session file Herdr names for the pane, else the newest main record of that pane and workspace. The main confirms it
47
+ * itself when asked (its own `successor` entry), so a record alone closes nothing.
48
+ */
49
+ export function handedOverOf(stateDir: string, pane: Pick<Pane, "pane_id" | "workspace_id" | "agent_session">): HandedOver | undefined {
50
+ const file = pane.agent_session?.value;
51
+ const mains = readRecords(stateDir).map((r) => r.record).filter((r) => r.role === "main" && r.pane === pane.pane_id && r.workspace === pane.workspace_id && (!file || r.file === file));
52
+ return mains.sort((a, b) => b.at - a.at)[0]?.handedOver;
53
+ }
54
+ /** The successor's pane when it is live: the broker lists its session, and pi runs in the pane the broker places it in. */
55
+ export const liveSuccessor = (h: HandedOver, sessions: Session[], ps: Pane[]): Pane | undefined => {
56
+ const at = sessions.find((x) => x.id === h.to)?.herdrLocation?.paneId;
57
+ return at ? ps.find((p) => p.pane_id === at && p.agent === "pi") : undefined;
58
+ };
59
+ /** What a main that handed over tells its workspace's tower (§4): code-written, as a milestone that expects no reply. */
60
+ export const handedNotice = (name: string, id: string, next: { tab: string; main: string }) =>
61
+ `Straw Boss: main ${name} (session ${id}) handed over to its successor in tab ${next.tab} (session ${next.main}), which took the handoff. ${name} steps down now; once it is idle and its successor is live, close it with boss_close_main with main "${id}".`;
62
+
26
63
  interface Closed { text: string; main: string; name: string; closed: boolean }
27
64
  /** `interrupt` (a stop's mode, docs/specs/2026-11-07-link-remote-stop.md, section 5): a main that is working aborts its turn and answers busy, so the next ask finds it idle; the tower skips its own idle pre-check for it. */
28
65
  export type CloseMain = (query: string, opts?: { interrupt?: boolean }) => Promise<Closed>;
@@ -30,7 +67,7 @@ export type CloseMain = (query: string, opts?: { interrupt?: boolean }) => Promi
30
67
  export interface Turn { running(): boolean; blockers(): string | undefined; abort(): void }
31
68
 
32
69
  /** `closeSelf` quits this session as /boss close does; `check` says why it cannot be stashed now (the bridge's check: a turn, a queue, a dialog, a monitor); `turn` lets an `interrupt` abort a turn (a tower service has none and never receives one). */
33
- export function createCloseMain({ pi, cfg, s, me }: Kit, { closeSelf, check, turn }: { closeSelf(keepPane: boolean): string | undefined; check(): string | undefined; turn?: Turn }) {
70
+ export function createCloseMain({ pi, cfg, s, me, guiDir }: Kit, { closeSelf, check, turn }: { closeSelf(keepPane: boolean): string | undefined; check(): string | undefined; turn?: Turn }) {
34
71
  const { run, sleep } = cfg;
35
72
  let channel: { publish(payload: unknown, options?: { audience?: "owner" | "capable" }): void } | undefined;
36
73
  const answers = new Map<string, Answer>();
@@ -43,7 +80,8 @@ export function createCloseMain({ pi, cfg, s, me }: Kit, { closeSelf, check, tur
43
80
  if (!s.joined) return no("this session has not joined the net");
44
81
  const [all, workspace] = await Promise.all([panes(run), workspaces(run).then((list) => list.find((w) => w.workspace_id === s.at.workspaceId))]);
45
82
  const mine = all.find((p) => p.pane_id === s.at.paneId);
46
- if (!mine?.tokens?.sb_opened_by) return no("no tower opened this main, so only the boss closes it");
83
+ // A main that handed over (its own `successor` entry, written once the successor took the handoff) has stepped down: its workspace's tower may close it, whoever opened it.
84
+ if (!mine?.tokens?.sb_opened_by && !s.saved.successor?.main) return no("no tower opened this main, so only the boss closes it");
47
85
  if (!workspace?.tokens?.tower || workspace.tokens.tower !== from) return no("the request is not from the tower of this workspace");
48
86
  const running = subagents(mine, all, cfg.now()).filter((row) => !row.ended).length;
49
87
  const subs = running && `${running} subagent${running > 1 ? "s are" : " is"} running`;
@@ -79,8 +117,9 @@ export function createCloseMain({ pi, cfg, s, me }: Kit, { closeSelf, check, tur
79
117
  return got;
80
118
  };
81
119
 
120
+ const dead = createDeadPanes({ run, sessions: () => s.c.listSessions(), here: () => ({ workspace: s.at.workspaceId, pane: s.at.paneId }), stateDir: guiDir, now: cfg.now });
82
121
  return {
83
- /** Every tower, and every main a tower opened, hears and answers asks; registering twice is a no-op. */
122
+ /** Every tower, every main a tower opened, and every main that handed over hears and answers asks; registering twice is a no-op. */
84
123
  register() {
85
124
  if (channel) return;
86
125
  pi.events.emit(REGISTER, { namespace: CONTROL, ownerEligible: false, onReady: (c: NonNullable<typeof channel>) => (channel = c), onEvent });
@@ -96,7 +135,10 @@ export function createCloseMain({ pi, cfg, s, me }: Kit, { closeSelf, check, tur
96
135
  const main = found[0]!, name = main.name ?? main.id, pane = all.find((p) => p.pane_id === main.herdrLocation?.paneId);
97
136
  if (pane?.workspace_id !== s.at.workspaceId) throw new Error(`${name} is not in this workspace; a tower closes only the mains it opened here`);
98
137
  if (pane.tokens?.sb_role !== "main" && pane.tokens?.sb_role !== TRAIN) throw new Error(`${name} is not a main agent`);
99
- if (!pane.tokens.sb_opened_by) throw new Error(`${name} was not opened by a tower (the boss opened it), so only the boss closes it`);
138
+ const handed = pane.tokens.sb_role === "main" ? handedOverOf(guiDir, pane) : undefined;
139
+ if (!pane.tokens.sb_opened_by && !handed) throw new Error(`${name} was not opened by a tower (the boss opened it), so only the boss closes it`);
140
+ // A main that handed over is closed once its successor is live: until then the old main is the one session that holds the work.
141
+ if (handed && !liveSuccessor(handed, sessions, all)) throw new Error(`${name} handed over to session ${handed.to.slice(0, 8)}${handed.tab ? ` (tab ${handed.tab})` : ""}, which is not live (no pi runs it, or the broker does not list it); the old main stays open until its successor is live, or the boss closes it`);
100
142
  if (!interrupt && !["idle", "done"].includes(pane.agent_status ?? "")) throw new Error(`${name} is ${pane.agent_status ?? "in an unknown state"}; try again when it is idle`);
101
143
  // A main reports its outcome in the turn that ends right after, so a refusal for something running is asked again for a while; any other refusal is final.
102
144
  let got = await ask(main.id, interrupt);
@@ -106,6 +148,9 @@ export function createCloseMain({ pi, cfg, s, me }: Kit, { closeSelf, check, tur
106
148
  const gone = await waitFor(sleep, async () => !(await s.c.listSessions().catch(() => [main])).some((x) => x.id === main.id), QUIT_MS, 500);
107
149
  return { text: gone ? `${name} quit and its pane closed.` : `${name} accepted and is shutting down; its pane closes once pi has exited.`, main: main.id, name, closed: Boolean(gone) };
108
150
  }) as CloseMain,
151
+ /** The tower's side: the dead agent panes of this workspace (deadpane.ts), and the close of one. */
152
+ deadPanes: () => dead.list(),
153
+ closePane: (pane: string) => dead.close(pane),
109
154
  };
110
155
  }
111
156
  export type Control = ReturnType<typeof createCloseMain>;
@@ -0,0 +1,127 @@
1
+ import { statSync } from "node:fs";
2
+ import { type HerdrRun, type Pane, panes, type Session, workspaces } from "./herdr.ts";
3
+ import { ledgerPath, REVIVE_TOKEN } from "./revive.ts";
4
+ import { readRecords } from "./roles.ts";
5
+
6
+ // A tower closes an agent pane whose pi is gone (docs/specs/2026-11-23-tower-close-panes.md §3). Whether it may is decided by one table here, as dead.ts decides a death: the callers gather the facts, and
7
+ // `refusal` alone gives the answer. The cheap rows come first, so process-info is asked only of a pane that passed them.
8
+ //
9
+ // | row | evidence | close |
10
+ // |-----------|---------------------------------------------------------------------------------------------------------------------------------------|-------|
11
+ // | missing | Herdr lists no such pane | no |
12
+ // | elsewhere | the pane is not in the tower's workspace | no |
13
+ // | tower | the tower's own pane, a pane of its tab, the pane of the workspace's tower session, or a pane marked `sb_role` tower or head (a standing pane waits at its shell between runs) | no |
14
+ // | unmarked | no `sb_*` or `piha_*` token and no pi session Herdr names: a plain shell, never an agent's | no |
15
+ // | opening | the one-time claim (`sb_open_main`) or a revive's key waits in it: an open, a revive, or a handover is starting its pi | no |
16
+ // | reviving | a revive holds the lock of a session whose role record names this pane | no |
17
+ // | listed | the broker lists a session at it: its pi lives | no |
18
+ // | agent | Herdr reports an agent in it (`agent`): a pi that has not joined the broker, or lost it, still runs | no |
19
+ // | busy | process-info lists anything but the shell in the foreground (a pi, a dev server), or cannot tell | no |
20
+ // | windows | the platform is win32: process-info there names the shell alone even while a program runs under it (typegate.ts), so nothing is proven | no |
21
+ // | dead | none of the above | yes |
22
+
23
+ /** How long a revive lock holds (revive.ts `takeLock` takes over an older one). */
24
+ const LOCK_MS = 5 * 60_000;
25
+ export interface ProcessInfo { shell_pid?: number; foreground_processes?: { pid?: number; name?: string; argv0?: string }[] }
26
+ export interface PaneFacts {
27
+ pane?: Pane;
28
+ query: string;
29
+ workspace: string;
30
+ /** The tower's own pane and tab, and the pane of the workspace's tower session. */
31
+ tower: { pane: string; tab?: string; session?: string };
32
+ listed?: Session;
33
+ reviving: boolean;
34
+ }
35
+ /** A pane's marks of an agent: Straw Boss's tokens, pi-herdr-agents' (`piha_`), or a pi session Herdr's integration named. */
36
+ export const marked = (p: Pane) => Object.keys(p.tokens ?? {}).some((k) => k.startsWith("sb_") || k.startsWith("piha_")) || Boolean(p.agent_session?.value);
37
+ /** Why the tower may not close the pane, before process-info is asked; undefined when only the foreground is left to prove. */
38
+ export function refusal(f: PaneFacts): string | undefined {
39
+ const p = f.pane, id = f.query;
40
+ if (!p) return `No pane ${id} in Herdr's list`;
41
+ if (p.workspace_id !== f.workspace) return `${id} is not in this workspace; a tower closes only its own workspace's panes`;
42
+ const role = p.tokens?.sb_role;
43
+ if (p.pane_id === f.tower.pane || (f.tower.tab !== undefined && p.tab_id === f.tower.tab) || p.pane_id === f.tower.session || role === "tower" || role === "head") return `${id} is a tower's pane; a tower never closes one`;
44
+ if (!marked(p)) return `${id} carries no mark of an agent (no Straw Boss or pi token): it is no agent pane, so the boss closes it`;
45
+ if (p.tokens?.sb_open_main !== undefined || p.tokens?.[REVIVE_TOKEN] !== undefined) return `${id} is being opened right now (an open, a revive, or a handover is starting its pi)`;
46
+ if (f.reviving) return `${id} is being revived right now (a tower holds the revive lock of its session)`;
47
+ if (f.listed) return `${id} is not dead: a live session (${f.listed.name ?? f.listed.id}) is at it`;
48
+ if (p.agent) return `${id} runs ${p.agent}, so it is not dead`;
49
+ return undefined;
50
+ }
51
+ /** Why the foreground is no bare shell; undefined when the shell alone is there (`process-info` proof, as a revive's D3 takes it). */
52
+ export function notBare(id: string, info: ProcessInfo | undefined): string | undefined {
53
+ const fg = info?.foreground_processes ?? [];
54
+ if (typeof info?.shell_pid !== "number" || !fg.length) return `Herdr cannot show what runs in ${id}, so it is not proven dead`;
55
+ if (fg.length === 1 && fg[0]!.pid === info.shell_pid) return undefined;
56
+ const names = [...new Set(fg.filter((x) => x.pid !== info.shell_pid).map((x) => x.name ?? x.argv0 ?? `pid ${x.pid}`))].slice(0, 4).join(", ");
57
+ return `${id} is not at a bare shell: ${names} runs in it`;
58
+ }
59
+ /** What the pane was, for the list: its role and the name its tokens kept. */
60
+ export const paneWhat = (p: Pane) => {
61
+ const t = p.tokens ?? {}, kind = t.sb_role ?? (t.sb_train ? "train" : Object.keys(t).some((k) => k.startsWith("piha_")) ? "subagent" : "pi"), name = t.sb_main_tab ?? t.sb_name ?? t.sb_tab ?? t.sb_member_tab;
62
+ return name ? `${kind} ${name}` : kind;
63
+ };
64
+ export interface DeadPane { pane: string; tab: string; what: string; /** The tab's only pane: the tab closes with it. */ alone: boolean }
65
+ /** The list `boss_close_main` gives with neither main nor pane. */
66
+ export const deadList = (rows: DeadPane[]) => ({
67
+ text: rows.length ? `Dead agent panes of this workspace (close one with boss_close_main pane):\n${rows.map((r) => `- ${r.pane} (tab ${r.tab}${r.alone ? ", its only pane" : ""}): ${r.what}`).join("\n")}` : "No dead agent pane in this workspace.",
68
+ details: rows,
69
+ });
70
+ export interface ClosedPane { text: string; pane: string; tab?: string }
71
+ /** `here`: the tower's workspace and own pane, read at each call (a session learns them at its start). */
72
+ export interface DeadPaneEnv { run: HerdrRun; sessions(): Promise<Session[]>; here(): { workspace: string; pane: string }; stateDir: string; now(): number; /** `process.platform` unless a test gives one. */ platform?: NodeJS.Platform }
73
+ /** The refusal on Windows, before anything is read: no row of the table can prove a bare shell there. */
74
+ export const WINDOWS_REFUSAL = "Dead agent panes are listed and closed on macOS and Linux only: on Windows Herdr's process-info names the shell alone even while a program runs under it, so no pane is proven dead; the boss closes it";
75
+
76
+ export function createDeadPanes(env: DeadPaneEnv) {
77
+ const { run } = env;
78
+ const platform = env.platform ?? process.platform;
79
+ const onWindows = () => {
80
+ if (platform === "win32") throw new Error(WINDOWS_REFUSAL);
81
+ };
82
+ const reviving = (p: Pane) => readRecords(env.stateDir).some(({ record }) => {
83
+ if (record.pane !== p.pane_id || record.workspace !== p.workspace_id) return false;
84
+ try { return env.now() - statSync(`${ledgerPath(env.stateDir, record.file)}.lock`).mtimeMs < LOCK_MS; } catch { return false; }
85
+ });
86
+ const look = async () => {
87
+ const [all, sessions, ws] = await Promise.all([panes(run), env.sessions(), workspaces(run)]);
88
+ const here = env.here(), towerId = ws.find((w) => w.workspace_id === here.workspace)?.tokens?.tower;
89
+ const own = all.find((p) => p.pane_id === here.pane);
90
+ const tower = { pane: here.pane, ...(own ? { tab: own.tab_id } : {}), ...((s) => (s ? { session: s } : {}))(sessions.find((x) => x.id === towerId)?.herdrLocation?.paneId) };
91
+ const facts = (query: string): PaneFacts => {
92
+ const pane = all.find((p) => p.pane_id === query);
93
+ return { query, workspace: here.workspace, tower, reviving: pane ? reviving(pane) : false, ...(pane ? { pane } : {}), ...((x) => (x ? { listed: x } : {}))(sessions.find((x) => x.herdrLocation?.paneId === query)) };
94
+ };
95
+ return { all, facts, workspace: here.workspace };
96
+ };
97
+ const info = async (pane: string) => JSON.parse(await run(["pane", "process-info", "--pane", pane])).result?.process_info as ProcessInfo | undefined;
98
+ const why = async (f: PaneFacts) => refusal(f) ?? notBare(f.query, await info(f.query).catch(() => undefined));
99
+ return {
100
+ /** The dead agent panes of this workspace: each passed every row of the table. */
101
+ async list(): Promise<DeadPane[]> {
102
+ onWindows();
103
+ const { all, facts, workspace } = await look();
104
+ const rows: DeadPane[] = [];
105
+ for (const p of all.filter((x) => x.workspace_id === workspace && marked(x))) {
106
+ if (await why(facts(p.pane_id))) continue;
107
+ rows.push({ pane: p.pane_id, tab: p.tab_id, what: paneWhat(p), alone: all.filter((x) => x.tab_id === p.tab_id).length === 1 });
108
+ }
109
+ return rows;
110
+ },
111
+ /** Closes one dead agent pane, its tab with it when it is the tab's only pane; refused with the table's reason otherwise. */
112
+ async close(query: string): Promise<ClosedPane> {
113
+ onWindows();
114
+ const { all, facts } = await look();
115
+ const f = facts(query), refused = await why(f);
116
+ if (refused) throw new Error(refused);
117
+ const p = f.pane!, alone = all.filter((x) => x.tab_id === p.tab_id).length === 1;
118
+ if (alone) {
119
+ await run(["tab", "close", p.tab_id]);
120
+ return { text: `Closed tab ${p.tab_id} with its only pane ${p.pane_id} (${paneWhat(p)}), whose pi was gone.`, pane: p.pane_id, tab: p.tab_id };
121
+ }
122
+ await run(["pane", "close", p.pane_id]);
123
+ return { text: `Closed pane ${p.pane_id} (${paneWhat(p)}), whose pi was gone; its tab ${p.tab_id} keeps its other panes.`, pane: p.pane_id };
124
+ },
125
+ };
126
+ }
127
+ export type DeadPanes = ReturnType<typeof createDeadPanes>;
package/src/index.ts CHANGED
@@ -94,7 +94,7 @@ export function createStrawBoss({ run: given, world: reading, api = herdrApi(),
94
94
  const addTrainCar = trainCarTool(kit, () => trainGuard, cars, (text) => reach.callTower(text, undefined, false, "blocked"));
95
95
  const membership = createMembership(kit, { presence, election, guard, briefing, roles, openTower: reach.openTower, register: () => (tools.addNetTools(), tools.addPromote(), tools.addDuty(), tools.addHandover(), addTrainCar()), onMain: link.look, control: () => control });
96
96
  // `look` (above) starts and upgrades the sb server (src/server/) and is the way to it; a session that is no part of that has none.
97
- const tools = createTools(kit, { ...reach, mainDuty, promote: membership.promote, digest, closeMain: (query) => control.closeMain(query), link, server: look, boardFill: createBoardFill(kit), waitAsk: () => mainWaitAsk(kit, { ask: cfg.ask ?? look?.ask, here: (fn) => host.here(fn), auto }) });
97
+ const tools = createTools(kit, { ...reach, mainDuty, promote: membership.promote, digest, closeMain: (query) => control.closeMain(query), closePane: (pane) => control.closePane(pane), deadPanes: () => control.deadPanes(), listen: () => control.register(), link, server: look, boardFill: createBoardFill(kit), waitAsk: () => mainWaitAsk(kit, { ask: cfg.ask ?? look?.ask, here: (fn) => host.here(fn), auto }) });
98
98
  const host = createHost(kit, { connected: membership.connected, ask: cfg.ask ?? look?.ask });
99
99
  closeSelf = createClosing(kit);
100
100
  const control = createCloseMain(kit, { closeSelf, check: bridge.stashCheck, turn: bridge.turn });
package/src/link/hooks.ts CHANGED
@@ -6,6 +6,7 @@ import { createGate, type ForwardPort } from "./gate.ts";
6
6
  import { type PolicyDeps } from "./policy.ts";
7
7
  import { hideOldRemote, Turns } from "./turn.ts";
8
8
  import { NO_CONFIRM } from "../autotext.ts";
9
+ import { REMOTE_CLOSE } from "../closemain.ts";
9
10
 
10
11
  // The hooks that make a run a remote turn and hold it to its level (docs/specs/2026-10-25-straw-link.md, Remote turns): the run classification, the
11
12
  // `tool_call` allowlist and gate, the `tool_result` filter, and the `context` marker for later turns. They sit apart from the runtime so they run
@@ -103,6 +104,8 @@ export function createRemoteTurns({ pi, now, config, policy: policyDeps, home, a
103
104
  // A peer could otherwise restart this computer's server: no level, dispatch included, may.
104
105
  if (e.toolName === "boss_server") return { block: true, reason: "a remote turn cannot see or restart this computer's sb server, whatever its sender's level" };
105
106
  if (e.toolName === "boss_handover") return { block: true, reason: "a remote turn cannot open a successor of this main, whatever its sender's level" };
107
+ // As an ally run (server/runtools.ts): dead panes and their list are the local tower's, whatever the sender's level; a main is checked by the tool against its `sb_opened_by` (tools.ts).
108
+ if (e.toolName === "boss_close_main" && (input.pane !== undefined || input.main === undefined)) return { block: true, reason: REMOTE_CLOSE };
106
109
  if (level === "dispatch") return;
107
110
  const scope = scopeFor((ctx as { cwd?: string }).cwd ?? process.cwd());
108
111
  const verdict = scope ? decide(e.toolName, input, turns.list, scope) : ({ kind: "gate" } as const);
@@ -134,6 +137,6 @@ export function createRemoteTurns({ pi, now, config, policy: policyDeps, home, a
134
137
  });
135
138
 
136
139
  /** What a tool that answers a remote turn may show: the senders' teams, and the project they all bind. Undefined when the run is not remote. */
137
- const scope = () => (turns.active ? { teams: [...new Set(turns.list.map((s) => s.team))], project: commonProject() } : undefined);
140
+ const scope = () => (turns.active ? { teams: [...new Set(turns.list.map((s) => s.team))], project: commonProject(), devices: [...new Set(turns.list.map((s) => s.id))] } : undefined);
138
141
  return { turns, answerForward, scope };
139
142
  }
@@ -288,7 +288,7 @@ export function createLink({ pi, cfg, s, guiDir, me, tell }: Kit) {
288
288
  return answer.boards as AllyBoard[];
289
289
  },
290
290
  /** The teams of the senders of the current remote turn and the one project they all bind, or undefined outside a remote turn (spec, Reading: `board_read`, in a remote turn). */
291
- remoteScope(): { teams: string[]; project: string | undefined } | undefined {
291
+ remoteScope(): { teams: string[]; project: string | undefined; /** The senders' device ids (an ally run's pinned scope leaves them out). */ devices?: string[] } | undefined {
292
292
  return remote.scope();
293
293
  },
294
294
  /** Whether this computer is attended (no unattended policy file). */
package/src/roles.ts CHANGED
@@ -30,8 +30,8 @@ const KEEP_MS = 90 * 24 * 3600_000;
30
30
  */
31
31
  export interface Ended { at: number; reason: "quit" | "new" | "resume" | "fork" | "signal" }
32
32
  export interface RoleRecord { role: "tower" | "main" | "train"; pane: string; tab: string; workspace: string; terminal?: string; file?: string; openedBy?: string; /** A train's project and code (docs/specs/2026-11-07-train-workers.md §3.3). */ train?: TrainId; /** A main's kind, for a restore before its first message, when pi has written no entry yet (docs/specs/2026-11-09-agent-kinds.md §6). */ duty?: CoordinatorDuty; at: number; ended?: Ended; /** A main that opened its successor with boss_handover, once that successor took the handoff (RVR-F004): never raised as dead or revived, however it ends. */ handedOver?: HandedOver }
33
- /** The successor a main handed its work to: when, and its session id. */
34
- export interface HandedOver { at: number; to: string }
33
+ /** The successor a main handed its work to: when, its session id, and the tab and pane it was opened in (the tower's refusal names the tab). */
34
+ export interface HandedOver { at: number; to: string; tab?: string; pane?: string }
35
35
  /** Where a session runs now: the pane, tab, and workspace of the record must all be these. `tabLabel` is the label Herdr lists for the tab now, the proof of a tower's or a train's tab; left out, neither role is given back. */
36
36
  export interface Here { paneId?: string; tabId?: string; workspaceId?: string; terminalId?: string; tabLabel?: string }
37
37
 
@@ -53,7 +53,7 @@ export function loadRecord(record: string, problem?: (why: string) => void): Rol
53
53
  const r = JSON.parse(raw) as Partial<RoleRecord>;
54
54
  if (r.duty !== undefined && !isCoordinatorDuty(r.duty)) delete r.duty; // a kind that is none says nothing; the role still stands
55
55
  if (r.ended !== undefined && !(typeof r.ended === "object" && r.ended !== null && typeof r.ended.at === "number" && ENDED.has(r.ended.reason))) delete r.ended; // a mark that cannot be read says the session did not end cleanly
56
- if (r.handedOver !== undefined && !(typeof r.handedOver === "object" && r.handedOver !== null && typeof r.handedOver.at === "number" && typeof r.handedOver.to === "string")) delete r.handedOver;
56
+ if (r.handedOver !== undefined && !(typeof r.handedOver === "object" && r.handedOver !== null && typeof r.handedOver.at === "number" && typeof r.handedOver.to === "string" && [r.handedOver.tab, r.handedOver.pane].every((v) => v === undefined || typeof v === "string"))) delete r.handedOver;
57
57
  if (r.role === TRAIN && !(r.train && trainFromToken(trainToken(r.train as TrainId)))) return undefined; // a train record names its project and code, or proves nothing
58
58
  return (r.role === "tower" || r.role === "main" || r.role === TRAIN) && typeof r.pane === "string" && typeof r.tab === "string" && typeof r.workspace === "string" && (r.terminal === undefined || typeof r.terminal === "string") && (r.file === undefined || typeof r.file === "string") && (r.openedBy === undefined || typeof r.openedBy === "string") ? (r as RoleRecord) : undefined;
59
59
  } catch {
@@ -155,7 +155,7 @@ export function createRoles({ cfg, s, guiDir, tell }: Kit) {
155
155
  try {
156
156
  mkdirSync(dir, { recursive: true, mode: 0o700 });
157
157
  const file = path(s.file), temp = `${file}.${process.pid}.tmp`, at = cfg.now();
158
- writeFileSync(temp, JSON.stringify({ role, pane: s.at.paneId, tab: s.at.tabId, workspace: s.at.workspaceId, ...(s.at.terminalId ? { terminal: s.at.terminalId } : {}), file: s.file, ...(openedBy ? { openedBy } : {}), ...(role === TRAIN && s.train ? { train: s.train } : {}), ...(role === "main" && isCoordinatorDuty(s.duty) ? { duty: s.duty } : {}), ...(role === "main" && s.saved.successor?.main ? { handedOver: { at: s.saved.successor.at, to: s.saved.successor.main } } : {}), at } satisfies RoleRecord), { mode: 0o600 });
158
+ writeFileSync(temp, JSON.stringify({ role, pane: s.at.paneId, tab: s.at.tabId, workspace: s.at.workspaceId, ...(s.at.terminalId ? { terminal: s.at.terminalId } : {}), file: s.file, ...(openedBy ? { openedBy } : {}), ...(role === TRAIN && s.train ? { train: s.train } : {}), ...(role === "main" && isCoordinatorDuty(s.duty) ? { duty: s.duty } : {}), ...(role === "main" && s.saved.successor?.main ? { handedOver: { at: s.saved.successor.at, to: s.saved.successor.main, tab: s.saved.successor.tab, pane: s.saved.successor.pane } } : {}), at } satisfies RoleRecord), { mode: 0o600 });
159
159
  renameSync(temp, file);
160
160
  } catch (error) {
161
161
  return void tell(`Straw Boss: could not record this session's role, so a Herdr restore will not bring it back: ${(error as Error).message}`, "warning");
@@ -1,5 +1,6 @@
1
1
  import { readBoard } from "../boardread.ts";
2
2
  import { type Control, refuseStanding } from "../closemain.ts";
3
+ import { deadList } from "../deadpane.ts";
3
4
  import { ForwardAsBefore, INTEGRATOR } from "../integrator.ts";
4
5
  import type { Opened, OpenRequest, PeerSender, Revived, ReviveRequest } from "../opener.ts";
5
6
  import { type DeadRow, ReviveRefused, revivedText, rowLine } from "../revive.ts";
@@ -42,6 +43,11 @@ export interface ToolHost {
42
43
  reach: Reach;
43
44
  open(request: OpenRequest): Promise<Opened>;
44
45
  closeMain: Control["closeMain"];
46
+ /** The workspace tower's close of a dead agent pane and its list (deadpane.ts): a local run's only. */
47
+ closePane?: Control["closePane"];
48
+ deadPanes?: Control["deadPanes"];
49
+ /** The state folder: a standing main whose role record says it handed over is not refused (closemain.ts `refuseStanding`). */
50
+ stateDir?: string;
45
51
  /** A request to the link holder as this tower's identity. */
46
52
  link(body: Record<string, unknown>): Promise<Answer>;
47
53
  /** The work board's folder. */
@@ -238,7 +244,8 @@ async function allyTool(host: ToolHost, name: string, args: Record<string, unkno
238
244
  if (await host.isTower(to)) throw new Error("An ally run may not write to a tower identity of this computer: it would carry a peer's text into a local run");
239
245
  await refuseTarget(host, to);
240
246
  }
241
- // rev-0803d-F002: a standing main is refused before the gate, so no one confirms a close the code refuses.
247
+ // rev-0803d-F002: a standing main is refused before the gate, so no one confirms a close the code refuses. A dead pane is no main opened for the device, and its list is the local tower's.
248
+ if (name === "boss_close_main" && (args.pane !== undefined || args.main === undefined)) throw new Error("An ally run closes only a main opened for its own device: dead panes are the local tower's");
242
249
  if (name === "boss_close_main") refuseStanding(await host.reach.read(), await refuseClose(host, str(args, "main", 300)));
243
250
  // The sender's own device is the one write the allowlist lets through; everything else outside the free reads needs the Allow of the gate.
244
251
  if (gated && name !== "tower_send") {
@@ -526,9 +533,19 @@ async function localTool(host: ToolHost, name: string, args: Record<string, unkn
526
533
  case "boss_revive_main":
527
534
  return reviveTool(host, args);
528
535
  case "boss_close_main": {
536
+ if (!ally && args.main !== undefined && args.pane !== undefined) throw new Error("Give main or pane, not both");
537
+ if (!ally && args.pane !== undefined) {
538
+ if (!host.closePane) throw new Error("This tower cannot close panes here");
539
+ const closed = await host.closePane(str(args, "pane", 100));
540
+ return { text: closed.text, details: closed };
541
+ }
542
+ if (!ally && args.main === undefined) {
543
+ if (!host.deadPanes) throw new Error("This tower cannot list dead panes here");
544
+ return deadList(await host.deadPanes());
545
+ }
529
546
  // An ally run closes the session its own check resolved, not the name again: the name may have been reused since.
530
547
  const main = str(args, "main", 300), target = ally ? await refuseClose(host, main) : main;
531
- refuseStanding(await host.reach.read(), target);
548
+ refuseStanding(await host.reach.read(), target, ally ? undefined : host.stateDir);
532
549
  const closed = await host.closeMain(target);
533
550
  return { text: closed.text, details: closed };
534
551
  }
@@ -1143,7 +1143,7 @@ export function createTowers(o: TowersOptions): Towers {
1143
1143
  const route = (to: string, name: string, kind: "expect" | "opened", ask?: string, live?: ReadonlySet<string>, panes?: ReadonlySet<string>, pane?: string) => { try { addRoute(slot, ws, { ...peer!, to, name, kind, at: now(), ...(ask ? { ask } : {}), ...(pane ? { pane } : {}), ...(kind === "opened" && who.level ? { level: who.level } : {}) }, now(), live, panes); } catch (cause) { error("ally-route", (cause as Error).message); } };
1144
1144
  const ev = runEvents({ slot, ws, who, label: l.record.label, read: () => l.reach!.read() }), { mainOf } = ev;
1145
1145
  const host = {
1146
- reach: l.reach!, open: peer ? async (request: Parameters<NonNullable<Live["open"]>>[0]) => { const opened = await l.openAlly!(request); const net = await l.reach!.read().catch(() => undefined), live = net && new Set(net.sessions.map((x) => x.id)), panes = net && new Set(net.ps.map((p) => p.pane_id)); route(opened.main, "opened main", "opened", ((u) => (u.length === 1 ? u[0] : undefined))((who.asks ?? []).filter((a) => !answered.has(who.id, a))), live, panes, opened.pane); return opened; } : l.open!, closeMain: (l.control ? async (query: string) => forgetClosed(ws, await l.control!.closeMain(query)) : undefined) as unknown as Control["closeMain"], now, boardDir: join(slot.stateDir, "board"), label: l.record.label,
1146
+ reach: l.reach!, open: peer ? async (request: Parameters<NonNullable<Live["open"]>>[0]) => { const opened = await l.openAlly!(request); const net = await l.reach!.read().catch(() => undefined), live = net && new Set(net.sessions.map((x) => x.id)), panes = net && new Set(net.ps.map((p) => p.pane_id)); route(opened.main, "opened main", "opened", ((u) => (u.length === 1 ? u[0] : undefined))((who.asks ?? []).filter((a) => !answered.has(who.id, a))), live, panes, opened.pane); return opened; } : l.open!, closeMain: (l.control ? async (query: string) => forgetClosed(ws, await l.control!.closeMain(query)) : undefined) as unknown as Control["closeMain"], now, boardDir: join(slot.stateDir, "board"), label: l.record.label, ...(l.control && !peer ? { closePane: (pane: string) => l.control!.closePane(pane), deadPanes: () => l.control!.deadPanes() } : {}), stateDir: slot.stateDir, // a local run's dead panes (deadpane.ts); an ally run is refused them (runtools.ts)
1147
1147
  link: async (body: Record<string, unknown>) => ((await o.link?.(body, l.record.id)) ?? { ok: false, code: "no_holder", error: "The link holder is not running in the sb server" }) as { ok: boolean; error?: string },
1148
1148
  server: o.server ?? { status: () => ({}), logs: () => [], restart: () => Promise.reject(new Error("The server cannot restart itself here")) },
1149
1149
  expect: (to: string, name: string, text: string) => { if (peer) return route(to, phrase(name, 40), "expect"); try { addExpect(slot, ws, { to, name, at: now(), first: phrase(text, 80) }, now()); } catch (cause) { error("expects", (cause as Error).message); } },
package/src/session.ts CHANGED
@@ -241,6 +241,7 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
241
241
  }
242
242
  const claimed = await claimOpened();
243
243
  if (!claimed && event.reason !== "startup" && s.saved.openedBy && s.saved.openedPane === s.at.paneId) s.openedBy = s.saved.openedBy; // only the same pi in the tower's pane (/reload, /fork): `pi --session` anywhere is the boss's main
244
+ if (event.reason !== "startup" && s.saved.successor?.main) control.register(); // a main that handed over: its workspace's tower closes it once its successor is live (closemain.ts), also after a reload; `pi --session` anywhere is the boss's main again, as for openedBy (CLR-F004)
244
245
  if (s.openedBy) {
245
246
  control.register(); // the tower that opened this main may ask it to close (closemain.ts), also after a reload
246
247
  if (s.isMain) roles.remember("main"); // the guard may have crowned it during the join, before the opener was known: the record names it for a Herdr restore (roles.ts)
package/src/tools.ts CHANGED
@@ -9,7 +9,8 @@ import type { Digest } from "./digest.ts";
9
9
  import { COORDINATOR_DUTIES, isCoordinatorDuty } from "./duty.ts";
10
10
  import { INTEG_NAME, type MainDuty } from "./mainduty.ts";
11
11
  import type { Membership } from "./membership.ts";
12
- import { type CloseMain, refuseStanding } from "./closemain.ts";
12
+ import { type CloseMain, type Control, handedNotice, refuseStanding, remoteCloseTarget } from "./closemain.ts";
13
+ import { deadList } from "./deadpane.ts";
13
14
  import type { Link } from "./link/runtime.ts";
14
15
  import { callTowerTool } from "./link/waitcall.ts";
15
16
  import { INTEGRATOR } from "./integrator.ts";
@@ -50,8 +51,14 @@ export const reviveParameters = () => Type.Object({
50
51
  reason: Type.Optional(Type.String({ description: "With revive: one line, why you revive it (the main reads it in its handoff)." })),
51
52
  });
52
53
 
54
+ /** `boss_close_main` (docs/specs/2026-11-23-tower-close-panes.md): its description and parameters, the same for a tower session and a tower run (runmode.ts proxies the latter to the server). */
55
+ export const CLOSE_DESCRIPTION = "Close a main, or a dead agent pane, of your workspace. main: ask the main to quit as /boss close would, so its pane and tab close: a main you opened with boss_open_main (after its done report, unless it waits for a boss decision), or a main that handed over with boss_handover once its successor is live, whoever opened it. Refused while it has a running turn, a queued message, an open dialog, a monitor, or a subagent; try again later. A main the boss opened that has not handed over, and a standing main that has not, are refused: only the boss closes them. pane: close an agent pane whose pi is gone (a bare shell, no session), and its tab when it is the tab's only pane; never a live pi, a tower's pane, or one being opened or revived. Neither: list the dead agent panes.";
56
+ export const closeParameters = () => Type.Object({
57
+ main: Type.Optional(Type.String({ description: "The main's intercom name or session id." })),
58
+ pane: Type.Optional(Type.String({ description: "A dead agent pane's Herdr id (as the list shows it, e.g. w1:p3)." })),
59
+ });
53
60
  /** The tools the agent calls: what a joined session has (status, call_tower, broadcast, rename, promote), and the tower's boss_open_main. */
54
- export function createTools({ pi, cfg, s, guiDir, me, role }: Kit, { mainDuty, post, callTower, status, broadcast, towerList, towerSend, answerHead, read, promote, digest, closeMain, link, server, towerCall, boardFill, waitAsk }: Pick<Reach, "post" | "callTower" | "status" | "broadcast" | "towerList" | "towerSend" | "answerHead" | "read"> & Pick<Membership, "promote"> & { mainDuty: MainDuty; digest: Digest; closeMain: CloseMain; link: Link; server?: ServerLook; towerCall?: boolean; boardFill: BoardFill; /** Registers `boss_wait_ask` for a joined session (waitask.ts `mainWaitAsk`); a tower run registers its own (runmode.ts). */ waitAsk?: () => void }) {
61
+ export function createTools({ pi, cfg, s, guiDir, me, role }: Kit, { mainDuty, post, callTower, status, broadcast, towerList, towerSend, answerHead, read, openTower, promote, digest, closeMain, closePane, deadPanes, listen, link, server, towerCall, boardFill, waitAsk }: Pick<Reach, "post" | "callTower" | "status" | "broadcast" | "towerList" | "towerSend" | "answerHead" | "read" | "openTower"> & Pick<Membership, "promote"> & { mainDuty: MainDuty; digest: Digest; closeMain: CloseMain; /** A tower's close of a dead agent pane and its list (closemain.ts, deadpane.ts). */ closePane: Control["closePane"]; deadPanes: Control["deadPanes"]; /** Registers the control channel: a main that handed over answers its tower's close (closemain.ts). */ listen: () => void; link: Link; server?: ServerLook; towerCall?: boolean; boardFill: BoardFill; /** Registers `boss_wait_ask` for a joined session (waitask.ts `mainWaitAsk`); a tower run registers its own (runmode.ts). */ waitAsk?: () => void }) {
55
62
  const tool = <P extends TSchema>(name: string, description: string, parameters: P, body: (params: Static<P>) => Promise<{ text: string; details?: unknown }>) =>
56
63
  pi.registerTool({
57
64
  name, label: name, description, parameters,
@@ -239,8 +246,12 @@ export function createTools({ pi, cfg, s, guiDir, me, role }: Kit, { mainDuty, p
239
246
  s.saved.successor = { pane: next.pane, tab: next.tab, at: cfg.now(), main: next.main };
240
247
  pi.appendEntry(ENTRY, { successor: s.saved.successor });
241
248
  // RVR-F004: the successor took the handoff, so this main's record says so: a later Herdr close of this tab raises no main_died, and no tower revives it.
242
- if (s.file) try { markHandedOver(guiDir, s.file, { at: s.saved.successor.at, to: next.main }); } catch { /* the entry above keeps it for the next record this session writes */ }
243
- return { text: `Opened your successor in tab ${next.tab} (session ${next.main}) and handed it ${path}. When it tells you it took over, give up your role as your rule says: boss_duty coordinator (if you are standing or integrator), boss_rename to "old ${name} (handed over to ${next.main.slice(0, 8)})", stop your monitors and loops, clear your board, and wait to be closed.`, details: next };
249
+ if (s.file) try { markHandedOver(guiDir, s.file, { at: s.saved.successor.at, to: next.main, tab: next.tab, pane: next.pane }); } catch { /* the entry above keeps it for the next record this session writes */ }
250
+ // The workspace's tower closes this main once its successor is live (docs/specs/2026-11-23-tower-close-panes.md §4): it listens for that ask now, and the tower hears of the handover as a milestone, so it need not poll.
251
+ try { listen(); } catch { /* no pi-intercom channel: the tower's ask goes unanswered and says so; the handover itself stands */ }
252
+ const told = await openTower(undefined, false).then((tower) => post(tower.id, handedNotice(name, me(), next), "call_tower", "tower", false, undefined, "milestone")).then((r) => r.status === "sent", () => false);
253
+ const closer = told ? "your workspace's tower was told and closes this session once your successor is live" : "no tower of this workspace took the notice, so the boss closes this session";
254
+ return { text: `Opened your successor in tab ${next.tab} (session ${next.main}) and handed it ${path}. When it tells you it took over, give up your role as your rule says: boss_duty coordinator (if you are standing or integrator), boss_rename to "old ${name} (handed over to ${next.main.slice(0, 8)})", stop your monitors and loops, clear your board, and wait to be closed: ${closer}.`, details: { ...next, towerTold: told } };
244
255
  } finally {
245
256
  handing = false;
246
257
  }
@@ -329,10 +340,15 @@ export function createTools({ pi, cfg, s, guiDir, me, role }: Kit, { mainDuty, p
329
340
  if (forMain !== undefined || inReplyTo !== undefined) throw new Error("for and inReplyTo work in a tower run of the sb server (the run tools ask the server)");
330
341
  return device === undefined ? towerSend(message, workspace, reply ?? false) : link.send({ device, text: message, reply: reply ?? false, ...(workspace !== undefined ? { workspace } : {}) });
331
342
  });
332
- tool("boss_close_main", "Close a main you opened with boss_open_main: ask it to quit as /boss close would, so its pane and tab close. Only mains opened by a tower in your workspace, never one the boss opened. Refused while it has a running turn, a queued message, an open dialog, a monitor, or a subagent; try again later. Close an opened coordinator main after its done report, unless it waits for a boss decision. A standing main is refused: only the boss closes it.",
333
- Type.Object({ main: Type.String({ description: "The opened main's intercom name or session id." }) }),
334
- async ({ main }) => {
335
- const closed = (refuseStanding(await read(), main), await closeMain(main));
343
+ tool("boss_close_main", CLOSE_DESCRIPTION, closeParameters(),
344
+ async ({ main, pane }) => {
345
+ if (main !== undefined && pane !== undefined) throw new Error("Give main or pane, not both");
346
+ // CLR-F002: a teammate's turn gets an ally run's scope (server/runtools.ts): a main opened for its senders' device, no dead pane, no list.
347
+ const remote = link.remoteScope(), devices = remote || s.remoteOrigin ? (remote?.devices ?? (s.remoteOrigin ? [s.remoteOrigin.replace(/^remote:/, "")] : [])) : undefined, net = devices && (await read());
348
+ if (devices) main = remoteCloseTarget(net!, { ...(main !== undefined ? { main } : {}), ...(pane !== undefined ? { pane } : {}) }, devices);
349
+ if (pane !== undefined) return closePane(pane).then((closed) => ({ text: closed.text, details: closed }));
350
+ if (main === undefined) return deadList(await deadPanes());
351
+ const closed = (refuseStanding(net || (await read()), main, devices ? undefined : guiDir), await closeMain(main));
336
352
  return { text: closed.text, details: closed };
337
353
  });
338
354
  },