pi-straw-boss 0.81.7 → 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.
@@ -220,8 +220,8 @@ import {
220
220
  } from "./chunk-OODCU4LU.mjs";
221
221
 
222
222
  // src/server/main.ts
223
- import { homedir as homedir15 } from "node:os";
224
- import { join as join59 } from "node:path";
223
+ import { homedir as homedir16 } from "node:os";
224
+ import { join as join62 } from "node:path";
225
225
 
226
226
  // src/boardauto.ts
227
227
  import { posix, win32 } from "node:path";
@@ -2868,7 +2868,7 @@ var decoders = {
2868
2868
  }
2869
2869
  }
2870
2870
  };
2871
- var encodePlaintext = (kind, plain3) => encoders[kind](plain3);
2871
+ var encodePlaintext = (kind, plain4) => encoders[kind](plain4);
2872
2872
  function decodePlaintext(kind, bytes) {
2873
2873
  try {
2874
2874
  return decoders[kind](bytes);
@@ -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
  });
@@ -3974,15 +3974,15 @@ function createReach({ pi, cfg, s: s2, guiDir, me, role, tell: tell2 }, server =
3974
3974
  const moveFirst = (tabId) => api2("tab.move", { tab_id: tabId, insert_index: 0 }).catch((error) => tell2(`Straw Boss: could not move the tower tab first: ${error.message}`, "warning"));
3975
3975
  return { target: target2, routed: target2 !== asked3 ? asked3 : void 0, ...await ensureTower({ run: run3, sleep: sleep2, live: live2, moveFirst, model: towerModel(guiDir), trustDir: trustDir(guiDir) }, target2, process.cwd()) };
3976
3976
  };
3977
- const scopeOf = (within2, ps) => ({
3978
- bound: (workspaceId) => !within2 || within2.project !== void 0 && ps.some((p) => p.workspace_id === workspaceId && p.cwd && inside(p.cwd, within2.project)),
3979
- here: (x) => !within2 || within2.project !== void 0 && ps.some((p) => p.pane_id === x?.herdrLocation?.paneId && p.cwd && inside(p.cwd, within2.project))
3977
+ const scopeOf = (within3, ps) => ({
3978
+ bound: (workspaceId) => !within3 || within3.project !== void 0 && ps.some((p) => p.workspace_id === workspaceId && p.cwd && inside(p.cwd, within3.project)),
3979
+ here: (x) => !within3 || within3.project !== void 0 && ps.some((p) => p.pane_id === x?.herdrLocation?.paneId && p.cwd && inside(p.cwd, within3.project))
3980
3980
  });
3981
- const status = async (within2) => {
3982
- const L = (t) => within2 ? allyLabel(t) : t;
3981
+ const status = async (within3) => {
3982
+ const L = (t) => within3 ? allyLabel(t) : t;
3983
3983
  const sessions = await s2.c.listSessions();
3984
3984
  const [ps, all] = [await panes(run3), await workspaces(run3)];
3985
- const { bound: bound2, here } = scopeOf(within2, ps);
3985
+ const { bound: bound2, here } = scopeOf(within3, ps);
3986
3986
  const mine = all.find((w) => w.workspace_id === s2.at.workspaceId);
3987
3987
  const towerOf = (w) => {
3988
3988
  const x = sessions.find((y) => y.id === w?.tokens?.tower);
@@ -4000,8 +4000,8 @@ function createReach({ pi, cfg, s: s2, guiDir, me, role, tell: tell2 }, server =
4000
4000
  return {
4001
4001
  me: { id: me(), role: role() },
4002
4002
  workspace: { id: s2.at.workspaceId, label: L(mine?.label) },
4003
- head: within2 ? null : headInfo(sessions, ps, all),
4004
- ...within2 ? {} : { auto: autoSummary(guiDir) },
4003
+ head: within3 ? null : headInfo(sessions, ps, all),
4004
+ ...within3 ? {} : { auto: autoSummary(guiDir) },
4005
4005
  tower: towerOf(mine) ?? null,
4006
4006
  tabs: tabs2,
4007
4007
  towers: all.filter((w) => w !== mine && !isHead(w) && bound2(w.workspace_id)).flatMap((w) => towerOf(w) ?? [])
@@ -4046,8 +4046,8 @@ function createReach({ pi, cfg, s: s2, guiDir, me, role, tell: tell2 }, server =
4046
4046
  return net.all.filter((w) => !isSub(w) && !isHead(w)).map((workspace) => {
4047
4047
  const tower = net.sessions.find((x) => x.id === workspace.tokens?.tower);
4048
4048
  const here = members.filter((m) => m.workspace.id === workspace.workspace_id && m.role !== "tower");
4049
- const [mains, plain3] = [here.filter((m) => m.role === "main").map((m) => m.s), here.filter((m) => m.role === "member").map((m) => m.s)];
4050
- const [via, sessions] = tower ? ["tower", [tower]] : mains.length ? ["main", mains] : plain3.length ? ["member", plain3] : ["none", []];
4049
+ const [mains, plain4] = [here.filter((m) => m.role === "main").map((m) => m.s), here.filter((m) => m.role === "member").map((m) => m.s)];
4050
+ const [via, sessions] = tower ? ["tower", [tower]] : mains.length ? ["main", mains] : plain4.length ? ["member", plain4] : ["none", []];
4051
4051
  return { workspace, self: workspace.workspace_id === s2.at.workspaceId, via, sessions, members: here };
4052
4052
  });
4053
4053
  };
@@ -4074,16 +4074,16 @@ ${summary}`, details: { scope, results } };
4074
4074
  }
4075
4075
  return report4(await deliver(targets, message, "broadcast", scope, reply3, net), notes, scope);
4076
4076
  };
4077
- const towerList = async (within2) => {
4078
- const L = (t) => within2 ? allyLabel(t) : t;
4077
+ const towerList = async (within3) => {
4078
+ const L = (t) => within3 ? allyLabel(t) : t;
4079
4079
  const net = await read4(), mark2 = (x) => ({ id: x.id, name: L(nameOf2(x)), state: sessionMark(x, net.ps.find((p) => p.pane_id === x.herdrLocation?.paneId)) });
4080
4080
  const mine = net.all.find((w) => w.workspace_id === s2.at.workspaceId);
4081
- const { bound: bound2, here } = scopeOf(within2, net.ps);
4081
+ const { bound: bound2, here } = scopeOf(within3, net.ps);
4082
4082
  const towers = stationsOf(net).filter((st) => bound2(st.workspace.workspace_id)).map((st) => {
4083
4083
  const tabs2 = Object.values(Object.groupBy(st.members.filter((m) => here(m.s)), (m) => m.tab.id)).map((group2 = []) => ({ label: L(group2[0].tab.label), main: L(nameOf2(group2.find((m) => m.role === "main")?.s)) || null, kind: group2.find((m) => m.role === "main")?.duty ?? null, ...group2.some((m) => m.role === "train") ? { train: L(nameOf2(group2.find((m) => m.role === "train").s)) } : {}, members: group2.filter((m) => m.role === "member").map((m) => L(nameOf2(m.s))) }));
4084
4084
  return { workspace: { id: st.workspace.workspace_id, label: L(st.workspace.label) }, self: st.self, reach: st.via, sessions: st.sessions.filter(here).map(mark2), tabs: tabs2 };
4085
4085
  });
4086
- const result2 = { me: { id: me(), role: role(), workspace: { id: s2.at.workspaceId, label: L(mine?.label) } }, head: within2 ? null : headInfo(net.sessions, net.ps, net.all), towers };
4086
+ const result2 = { me: { id: me(), role: role(), workspace: { id: s2.at.workspaceId, label: L(mine?.label) } }, head: within3 ? null : headInfo(net.sessions, net.ps, net.all), towers };
4087
4087
  return { text: JSON.stringify(result2, null, 2), details: result2 };
4088
4088
  };
4089
4089
  const towerSend = async (message, workspace, reply3 = false, stamped = {}) => {
@@ -4149,7 +4149,8 @@ ${i.auto}` : "");
4149
4149
  const lead = leadOf(m);
4150
4150
  return lead ? `${m.tab}: ${lead.word} ${lead.row.name} (${lead.row.id.slice(0, 8)}) ${lead.row.state}${lead.row.openedBy ? `, opened by ${lead.row.openedBy}` : ""}${lead.row.stale ? " [stale: idle, not updated for over 2 hours]" : ""}${lead.row.now ? `; now: ${lead.row.now}` : ""}${lead.row.open ? ` (${lead.row.open} open)` : ""}${m.members ? `; ${m.members} members` : ""}` : `${m.tab}: no main${m.members ? `; ${m.members} members` : ""}`;
4151
4151
  });
4152
- const mains = ["Mains you supervise:", ...mainLines.length ? rowsOf(mainLines, CAPS.mains, CAPS.mainRow, 2400) : ["- none: no tab of this workspace has joined"]].join("\n");
4152
+ const mains = ["Mains you supervise:", ...mainLines.length ? rowsOf(mainLines, CAPS.mains, CAPS.mainRow, 2400) : ["- none: no tab of this workspace has joined"]].join("\n") + (i.dead?.length ? `
4153
+ ${["Mains that ended without a close (boss_revive_main revives a dead one):", ...rowsOf(i.dead, 6, 400, 1600)].join("\n")}` : "");
4153
4154
  const talk = cut([i.conversation ?? "", ...i.since?.length ? ["Since you last talked with the boss:", ...i.since.slice(0, 3)] : []].filter(Boolean).join("\n"), CAPS.talk);
4154
4155
  const parts = { talk, mains, obligations, memory: i.memory ?? "", digest, note };
4155
4156
  const size2 = () => [who2, ...Object.values(parts), tools, flags2].filter(Boolean).join("\n\n").length;
@@ -5467,10 +5468,10 @@ function createMusic(dir) {
5467
5468
  async function track(name2) {
5468
5469
  if (!dir) return void 0;
5469
5470
  try {
5470
- const [root, real3] = await Promise.all([realpath(dir), realpath(join18(dir, name2))]);
5471
- if (!real3.startsWith(root + sep2)) return void 0;
5472
- const s2 = await stat(real3);
5473
- return s2.isFile() && s2.size > 0 ? { real: real3, size: s2.size } : void 0;
5471
+ const [root, real4] = await Promise.all([realpath(dir), realpath(join18(dir, name2))]);
5472
+ if (!real4.startsWith(root + sep2)) return void 0;
5473
+ const s2 = await stat(real4);
5474
+ return s2.isFile() && s2.size > 0 ? { real: real4, size: s2.size } : void 0;
5474
5475
  } catch {
5475
5476
  return void 0;
5476
5477
  }
@@ -6048,8 +6049,8 @@ function toolLine(name2, a) {
6048
6049
  return first(a.description ?? a.command);
6049
6050
  // Another tool shows its first plain argument by name; one with only structured arguments shows their names, never "[object Object]".
6050
6051
  default: {
6051
- const plain3 = Object.entries(a).find(([, v]) => ["string", "number", "boolean"].includes(typeof v));
6052
- return `(${first(plain3 ? `${plain3[0]}: ${plain3[1]}` : Object.keys(a).join(", "), 100)})`;
6052
+ const plain4 = Object.entries(a).find(([, v]) => ["string", "number", "boolean"].includes(typeof v));
6053
+ return `(${first(plain4 ? `${plain4[0]}: ${plain4[1]}` : Object.keys(a).join(", "), 100)})`;
6053
6054
  }
6054
6055
  }
6055
6056
  }
@@ -6207,9 +6208,9 @@ async function withPending(net, fileOf4, relayed) {
6207
6208
  if (dialogs?.length) [u.mark, b.mark] = ["waiting", "waiting"];
6208
6209
  if (dialogs?.length && u !== b.tower) u.note = "waiting on a question";
6209
6210
  const file3 = u.mark === "waiting" ? fileOf4(u.key) : void 0;
6210
- const join60 = (p, calls) => dialogs?.length ? relayed.merge(u.key, p, dialogs, Boolean(file3), calls) : p;
6211
- if (file3) jobs.push(pendingWith(file3).then(({ pending, calls }) => u.pending = join60(pending, calls)));
6212
- else if (dialogs?.length) u.pending = join60();
6211
+ const join63 = (p, calls) => dialogs?.length ? relayed.merge(u.key, p, dialogs, Boolean(file3), calls) : p;
6212
+ if (file3) jobs.push(pendingWith(file3).then(({ pending, calls }) => u.pending = join63(pending, calls)));
6213
+ else if (dialogs?.length) u.pending = join63();
6213
6214
  }
6214
6215
  for (const b of net.bases) for (const u of unitsOf(b)) u.mark = commanding(u.mark, u.subs.map((c) => c.mark));
6215
6216
  await Promise.all(jobs);
@@ -6794,12 +6795,12 @@ var TODO_TEXT = 120;
6794
6795
  var todoOk = (v) => {
6795
6796
  const t = v;
6796
6797
  const count4 = (n) => Number.isSafeInteger(n) && n >= 0 && n <= 200;
6797
- const plain3 = (s2, max) => typeof s2 === "string" && s2.length > 0 && s2.length <= max && !/[\p{Cc}\p{Cf}]/u.test(s2);
6798
+ const plain4 = (s2, max) => typeof s2 === "string" && s2.length > 0 && s2.length <= max && !/[\p{Cc}\p{Cf}]/u.test(s2);
6798
6799
  const step = (r) => {
6799
6800
  const x = r;
6800
- return x !== null && typeof x === "object" && Object.keys(x).every((k) => ["id", "kind", "status", "name", "round", "outcome"].includes(k)) && Number.isSafeInteger(x.id) && x.id >= 1 && plain3(x.kind, 32) && ["pending", "in_progress", "completed"].includes(x.status) && (x.name === void 0 || plain3(x.name, 64)) && (x.round === void 0 || Number.isSafeInteger(x.round) && x.round >= 1) && (x.outcome === void 0 || ["passed", "failed", "void"].includes(x.outcome));
6801
+ return x !== null && typeof x === "object" && Object.keys(x).every((k) => ["id", "kind", "status", "name", "round", "outcome"].includes(k)) && Number.isSafeInteger(x.id) && x.id >= 1 && plain4(x.kind, 32) && ["pending", "in_progress", "completed"].includes(x.status) && (x.name === void 0 || plain4(x.name, 64)) && (x.round === void 0 || Number.isSafeInteger(x.round) && x.round >= 1) && (x.outcome === void 0 || ["passed", "failed", "void"].includes(x.outcome));
6801
6802
  };
6802
- return t !== null && typeof t === "object" && count4(t.done) && count4(t.total) && t.done <= t.total && t.total > 0 && (t.now === void 0 || plain3(t.now, TODO_TEXT)) && (t.steps === void 0 || Array.isArray(t.steps) && t.steps.length <= 200 && t.steps.every(step)) && (t.graph === void 0 || GRAPHS.includes(t.graph));
6803
+ return t !== null && typeof t === "object" && count4(t.done) && count4(t.total) && t.done <= t.total && t.total > 0 && (t.now === void 0 || plain4(t.now, TODO_TEXT)) && (t.steps === void 0 || Array.isArray(t.steps) && t.steps.length <= 200 && t.steps.every(step)) && (t.graph === void 0 || GRAPHS.includes(t.graph));
6803
6804
  };
6804
6805
 
6805
6806
  // src/dialogs.ts
@@ -6894,7 +6895,7 @@ function createHub(pi, me, local, onAllow) {
6894
6895
  } catch {
6895
6896
  }
6896
6897
  };
6897
- const join60 = () => {
6898
+ const join63 = () => {
6898
6899
  try {
6899
6900
  if (!channel && me) pi.events.emit(REGISTER2, { namespace: guiNamespace(me), ownerEligible: true, onReady: (c) => channel = c, onEvent });
6900
6901
  } catch {
@@ -6988,12 +6989,12 @@ function createHub(pi, me, local, onAllow) {
6988
6989
  /** The channel is registered at the first start, before gui.json names this session; later starts in this process reuse it. */
6989
6990
  start(onChange) {
6990
6991
  [change, active] = [onChange, true];
6991
- join60();
6992
+ join63();
6992
6993
  },
6993
6994
  /** The server keeps the channel and the gates' tracking up with no page listening, and through a page's stop; bridges relay to it as soon as it owns the channel. */
6994
6995
  track() {
6995
6996
  tracking = true;
6996
- join60();
6997
+ join63();
6997
6998
  },
6998
6999
  stop() {
6999
7000
  active = false;
@@ -7379,13 +7380,18 @@ var refusalReply = (no19) => no19.why === "bad-request" ? { status: 400, body: {
7379
7380
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
7380
7381
  var mark = new AsyncLocalStorage2();
7381
7382
 
7383
+ // src/safetext.ts
7384
+ var UNSAFE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u180e\u200b-\u200f\u2028-\u202e\u2060-\u206f\ufeff\ufff9-\ufffb]/g;
7385
+ var plain3 = (text11) => text11.replace(/\r\n/g, "\n").replace(/\t/g, " ").replace(UNSAFE, (c) => c.charCodeAt(0) < 256 ? `\\x${c.charCodeAt(0).toString(16).padStart(2, "0")}` : `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
7386
+ var line = (text11) => plain3(text11).replace(/\n/g, "\\n");
7387
+
7382
7388
  // src/bossopen.ts
7383
7389
  var OPEN_MS = 12 * 6e4;
7384
7390
  function firstWord(text11) {
7385
7391
  const quoted2 = /^(["'])(.*?)\1(?:\s+|$)([\s\S]*)$/.exec(text11);
7386
7392
  if (quoted2) return { word: quoted2[2], rest: quoted2[3].trim() };
7387
- const plain3 = /^(\S+)(?:\s+([\s\S]*))?$/.exec(text11);
7388
- return { word: plain3?.[1] ?? "", rest: (plain3?.[2] ?? "").trim() };
7393
+ const plain4 = /^(\S+)(?:\s+([\s\S]*))?$/.exec(text11);
7394
+ return { word: plain4?.[1] ?? "", rest: (plain4?.[2] ?? "").trim() };
7389
7395
  }
7390
7396
  function parseOpen(rest) {
7391
7397
  const kind = firstWord((rest ?? "").trim());
@@ -8022,13 +8028,13 @@ function createDocs(hub, name2, { answered = createAnswered({ load: () => void 0
8022
8028
  };
8023
8029
  const body2 = async (doc2) => {
8024
8030
  if (doc2.v === 2) return (await pull(doc2.capability, MAX_DOC))?.toString("utf8");
8025
- const real3 = file3(doc2.path, MAX_DOC);
8026
- return real3 ? readFileSync15(real3, "utf8") : void 0;
8031
+ const real4 = file3(doc2.path, MAX_DOC);
8032
+ return real4 ? readFileSync15(real4, "utf8") : void 0;
8027
8033
  };
8028
8034
  const file3 = (path, max, under2) => {
8029
8035
  try {
8030
- const real3 = realpathSync6(path), root = under2 && realpathSync6(under2);
8031
- return (root ? real3.startsWith(root + sep3) : real3 === path) && statSync7(real3).isFile() && statSync7(real3).size <= max ? real3 : void 0;
8036
+ const real4 = realpathSync6(path), root = under2 && realpathSync6(under2);
8037
+ return (root ? real4.startsWith(root + sep3) : real4 === path) && statSync7(real4).isFile() && statSync7(real4).size <= max ? real4 : void 0;
8032
8038
  } catch {
8033
8039
  return void 0;
8034
8040
  }
@@ -8060,8 +8066,8 @@ function createDocs(hub, name2, { answered = createAnswered({ load: () => void 0
8060
8066
  const { doc: doc2, key: key2 } = found, dest = h["sec-fetch-dest"], site = h["sec-fetch-site"];
8061
8067
  if (!rest.length) return void res.writeHead(308, { ...base, location: `${cap}/` }).end();
8062
8068
  if (rest.length === 1 && rest[0] === "") {
8063
- const real4 = doc2.kind === "html" ? await body2(doc2) : void 0;
8064
- if (real4 === void 0 || dest && dest !== "iframe" && dest !== "document") return void page2(404, "Not found", "This document cannot be shown here.");
8069
+ const real5 = doc2.kind === "html" ? await body2(doc2) : void 0;
8070
+ if (real5 === void 0 || dest && dest !== "iframe" && dest !== "document") return void page2(404, "Not found", "This document cannot be shown here.");
8065
8071
  if (site && site !== "same-origin" && site !== "none") return void page2(409, "Reload the document", "Use Reload on its tile, or open it again, to see it and send its form again.");
8066
8072
  const nonce = randomBytes9(16).toString("hex"), now = Date.now();
8067
8073
  for (const [n, v] of nonces) if (v.until < now || nonces.size >= MAX_NONCES) nonces.delete(n);
@@ -8073,7 +8079,7 @@ function createDocs(hub, name2, { answered = createAnswered({ load: () => void 0
8073
8079
  tickets.set(ticket, { cap, until: now + TICKET_MS, lan: true, ...lan.device && { device: lan.device } });
8074
8080
  ticketBase = `${root}r/${ticket}/`;
8075
8081
  }
8076
- return void res.writeHead(200, { ...base, "cache-control": "private, no-cache", "content-type": "text/html; charset=utf-8" }).end(rewrite(doc2.v === 2 ? real4.replace(HOOK, "") : real4, nonce, ticketBase));
8082
+ return void res.writeHead(200, { ...base, "cache-control": "private, no-cache", "content-type": "text/html; charset=utf-8" }).end(rewrite(doc2.v === 2 ? real5.replace(HOOK, "") : real5, nonce, ticketBase));
8077
8083
  }
8078
8084
  if (rest[0] === "answer" && rest.length === 2) {
8079
8085
  const n = nonces.get(rest[1]), url = req.url ?? "", query = url.includes("?") ? url.slice(url.indexOf("?") + 1) : "";
@@ -8100,10 +8106,10 @@ function createDocs(hub, name2, { answered = createAnswered({ load: () => void 0
8100
8106
  if (!bytes) return void page2(404, "Not found", "No such file beside the document.");
8101
8107
  return void res.writeHead(200, heads).end(bytes);
8102
8108
  }
8103
- const real3 = allowed ? file3(resolve4(dirname7(doc2.path), rel), MAX_FILE2, dirname7(doc2.path)) : void 0;
8104
- if (!real3) return void page2(404, "Not found", "No such file beside the document.");
8109
+ const real4 = allowed ? file3(resolve4(dirname7(doc2.path), rel), MAX_FILE2, dirname7(doc2.path)) : void 0;
8110
+ if (!real4) return void page2(404, "Not found", "No such file beside the document.");
8105
8111
  res.writeHead(200, heads);
8106
- pipeline(createReadStream(real3), res, () => {
8112
+ pipeline(createReadStream(real4), res, () => {
8107
8113
  });
8108
8114
  },
8109
8115
  /** POST /<t>/api/doc/<cap>/answer {answerId, answer, rev}: a Markdown document's block answers, in the Answer of pi-better-show whose `ref.block` is the block. Only a v2 owner (pi-better-show) takes a block's Answer; a v1 Markdown document draws its blocks but its owner (pi-herdr-doc-review) has no way to take one, so the answer is refused up front. The text is read from its owner first: `rev` must be the hash of the text served now, and the block one the text has
@@ -9463,7 +9469,7 @@ var joinedRole = (token) => token === "main" || token === "member" || token ===
9463
9469
  var RECENT_MS2 = 10 * 6e4;
9464
9470
  var raiserView = ({ id, ...rest }, keys) => ({ ...rest, ...id && keys.get(id) ? { key: keys.get(id) } : {} });
9465
9471
  function buildNet({ sessions, panes: ps, workspaces: all, children: children2, services, head, sessionDir = join24(process.env.PI_CODING_AGENT_DIR ?? join24(homedir6(), ".pi", "agent"), "sessions") }, refs = /* @__PURE__ */ new Map()) {
9466
- const root = canonical2(sessionDir), readable2 = (file3, id, real3 = file3?.endsWith(".jsonl") ? canonical2(file3) : void 0) => real3 && real3.startsWith(root + sep4) && (!id || basename6(real3).endsWith(`_${id}.jsonl`)) ? real3 : void 0;
9472
+ const root = canonical2(sessionDir), readable2 = (file3, id, real4 = file3?.endsWith(".jsonl") ? canonical2(file3) : void 0) => real4 && real4.startsWith(root + sep4) && (!id || basename6(real4).endsWith(`_${id}.jsonl`)) ? real4 : void 0;
9467
9473
  const piFile = (pane, id) => readable2(pane?.agent === "pi" ? pane.agent_session?.value : void 0, id);
9468
9474
  const paneOf2 = (s2) => ps.find((p) => p.pane_id === s2.herdrLocation?.paneId);
9469
9475
  const note = (mark2, status) => ({ working: status, waiting: "waiting on a question" })[mark2];
@@ -9687,9 +9693,9 @@ var no10 = (status, error, reason) => ({ status, body: { error, reason } });
9687
9693
  var OUTSIDE2 = no10(400, "not_allowed", "Only folders in your home folder, outside hidden folders, can be picked.");
9688
9694
  async function pickable(path, home = homedir7(), hidden = platformHidden) {
9689
9695
  if (typeof path !== "string" || !isAbsolute4(path) || path.length > 4096) return;
9690
- const [real3, root] = await Promise.all([realpath2(path).catch(() => void 0), realpath2(home).catch(() => home)]);
9691
- if (!real3) return;
9692
- const rel = relative3(root, real3);
9696
+ const [real4, root] = await Promise.all([realpath2(path).catch(() => void 0), realpath2(home).catch(() => home)]);
9697
+ if (!real4) return;
9698
+ const rel = relative3(root, real4);
9693
9699
  if (rel.startsWith("..") || isAbsolute4(rel) || rel.split(sep5).some((part3) => part3.startsWith("."))) return;
9694
9700
  if (hidden) {
9695
9701
  for (const base of [root, resolve5(home)]) {
@@ -9700,12 +9706,12 @@ async function pickable(path, home = homedir7(), hidden = platformHidden) {
9700
9706
  }
9701
9707
  if (rel && await hasHidden(root, rel.split(sep5), hidden)) return;
9702
9708
  }
9703
- return (await stat5(real3).catch(() => void 0))?.isDirectory() ? real3 : void 0;
9709
+ return (await stat5(real4).catch(() => void 0))?.isDirectory() ? real4 : void 0;
9704
9710
  }
9705
9711
  async function listDirs(dir, home = homedir7(), hidden = platformHidden) {
9706
- 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);
9707
9713
  for (const e of await readdir3(dir, { withFileTypes: true })) {
9708
- if (e.name.startsWith(".") || marked?.has(e.name.toLowerCase())) continue;
9714
+ if (e.name.startsWith(".") || marked2?.has(e.name.toLowerCase())) continue;
9709
9715
  if (e.isDirectory() || e.isSymbolicLink() && await pickable(join26(dir, e.name), home, hidden)) names.push(e.name);
9710
9716
  }
9711
9717
  names.sort((a, b) => a.localeCompare(b));
@@ -9721,13 +9727,13 @@ async function makeDir(parent, name2, home = homedir7(), hidden = platformHidden
9721
9727
  if (!clean6 || Buffer.byteLength(clean6) > 255 || RESERVED.test(clean6) || clean6.startsWith(".") || /[. ]$/.test(clean6) || BAD_NAME.test(clean6)) return BAD();
9722
9728
  const path = join26(dir, clean6), made = await mkdir2(path).then(() => true, (error) => error.code === "EEXIST" ? false : error);
9723
9729
  if (made instanceof Error) return made.code === "ENAMETOOLONG" ? BAD() : no10(403, "unwritable", `The folder could not be made: ${made.message}`);
9724
- const real3 = await pickable(path, home, hidden);
9725
- if (!real3 && made) await rmdir(path).catch(() => {
9730
+ const real4 = await pickable(path, home, hidden);
9731
+ if (!real4 && made) await rmdir(path).catch(() => {
9726
9732
  });
9727
- return real3 ? { status: 200, body: { path: real3, created: made } } : no10(409, "not_a_folder", `${clean6} exists here and is not a folder you can pick.`);
9733
+ return real4 ? { status: 200, body: { path: real4, created: made } } : no10(409, "not_a_folder", `${clean6} exists here and is not a folder you can pick.`);
9728
9734
  }
9729
9735
  function createSpawn({ run: run3, sleep: sleep2, call, live, sessionAt, home = homedir7(), hidden = platformHidden, deploys = createDeploys(), trustDir: trustDir2, openings = createOpenings(), intents, note, lock = { busy: false } }) {
9730
- const pick2 = (path) => pickable(path, home, hidden);
9736
+ const pick3 = (path) => pickable(path, home, hidden);
9731
9737
  const keep2 = (id, opening3) => {
9732
9738
  try {
9733
9739
  openings.set(id, opening3);
@@ -9747,12 +9753,12 @@ function createSpawn({ run: run3, sleep: sleep2, call, live, sessionAt, home = h
9747
9753
  if (!ws) return home;
9748
9754
  const here = await panes(run3, ws.workspace_id);
9749
9755
  const own = ws.worktree?.checkout_path ?? here.find((p) => p.tokens?.sb_role === "tower")?.cwd ?? here[0]?.cwd;
9750
- return await pick2(own) ?? await realpath2(home).catch(() => home);
9756
+ return await pick3(own) ?? await realpath2(home).catch(() => home);
9751
9757
  };
9752
9758
  const places = async () => {
9753
9759
  const root = await realpath2(home).catch(() => home), seen = /* @__PURE__ */ new Set(), recent = [];
9754
9760
  const keep3 = async (path) => {
9755
- const dir = await pick2(path);
9761
+ const dir = await pick3(path);
9756
9762
  if (dir && dir !== root && !seen.has(dir)) seen.add(dir), recent.push(dir);
9757
9763
  };
9758
9764
  for (const ws of await workspaces(run3).catch(() => [])) {
@@ -9760,7 +9766,7 @@ function createSpawn({ run: run3, sleep: sleep2, call, live, sessionAt, home = h
9760
9766
  await keep3(ws.worktree?.checkout_path);
9761
9767
  for (const pane of await panes(run3, ws.workspace_id).catch(() => [])) await keep3(pane.cwd);
9762
9768
  }
9763
- const named = await Promise.all(["Desktop", "Documents"].map(async (name2) => [name2, await pick2(join26(root, name2))]));
9769
+ const named = await Promise.all(["Desktop", "Documents"].map(async (name2) => [name2, await pick3(join26(root, name2))]));
9764
9770
  return { home: root, sep: sep5, places: named.flatMap(([name2, path]) => path ? [{ name: name2, path }] : []), recent: recent.slice(0, 10) };
9765
9771
  };
9766
9772
  const leadOf2 = async (workspaceId, tabId) => {
@@ -9841,7 +9847,7 @@ function createSpawn({ run: run3, sleep: sleep2, call, live, sessionAt, home = h
9841
9847
  } else {
9842
9848
  const lead = await leadOf2(ws.workspace_id, tabId);
9843
9849
  if (!lead) return no10(404, "not_found", "That tab is not open any more.");
9844
- const cwd = dir ?? await pick2(lead.cwd) ?? await baseDir(ws.workspace_id);
9850
+ const cwd = dir ?? await pick3(lead.cwd) ?? await baseDir(ws.workspace_id);
9845
9851
  await assertSettingsSafe([cwd]);
9846
9852
  const split = await result(run3, ["pane", "split", lead.pane_id, "--direction", "right", "--cwd", cwd, "--no-focus", "--env", "STRAW_BOSS_ROLE=member"]);
9847
9853
  const paneId = split.pane.pane_id;
@@ -9857,7 +9863,7 @@ function createSpawn({ run: run3, sleep: sleep2, call, live, sessionAt, home = h
9857
9863
  const had = openings.get(id);
9858
9864
  if (!had) return;
9859
9865
  const pane = had.dir === dir ? (await panes(run3, had.workspace)).find((p) => p.pane_id === had.pane) : void 0;
9860
- const same5 = pane && (pane.cwd ? await pick2(pane.cwd) === had.dir : open8.find((w) => w.workspace_id === had.workspace)?.label === had.label);
9866
+ const same5 = pane && (pane.cwd ? await pick3(pane.cwd) === had.dir : open8.find((w) => w.workspace_id === had.workspace)?.label === had.label);
9861
9867
  if (!pane || !same5) return void openings.drop(id);
9862
9868
  d.go("start");
9863
9869
  d.pane = pane.pane_id;
@@ -9901,7 +9907,7 @@ function createSpawn({ run: run3, sleep: sleep2, call, live, sessionAt, home = h
9901
9907
  const route = async ([scope, kind = ""], json3) => {
9902
9908
  if (scope === "dirs" && !kind) {
9903
9909
  const lead = json3.path === void 0 && typeof json3.workspace === "string" && json3.tab !== void 0 ? await leadOf2(json3.workspace, json3.tab) : void 0;
9904
- const dir2 = json3.path !== void 0 ? await pick2(json3.path) : (lead && await pick2(lead.cwd)) ?? await baseDir(json3.workspace);
9910
+ const dir2 = json3.path !== void 0 ? await pick3(json3.path) : (lead && await pick3(lead.cwd)) ?? await baseDir(json3.workspace);
9905
9911
  if (!dir2) return OUTSIDE2;
9906
9912
  return listDirs(dir2, home, hidden).then((body2) => ({ status: 200, body: body2 }), (error) => error instanceof HiddenError ? Promise.reject(error) : no10(403, "unreadable", "This folder cannot be read."));
9907
9913
  }
@@ -9915,7 +9921,7 @@ function createSpawn({ run: run3, sleep: sleep2, call, live, sessionAt, home = h
9915
9921
  if (json3.deploy !== void 0 && !deploys.valid(json3.deploy)) return no10(400, "bad_request", "The opening's id is 8 to 64 letters, digits, - or _.");
9916
9922
  const split = kind === "member" && json3.tab !== void 0;
9917
9923
  if (split && typeof json3.tab !== "string") return no10(400, "bad_request", "A tab is named by its id.");
9918
- const dir = split && json3.dir === void 0 ? void 0 : await pick2(json3.dir);
9924
+ const dir = split && json3.dir === void 0 ? void 0 : await pick3(json3.dir);
9919
9925
  if (!dir && !(split && json3.dir === void 0)) return OUTSIDE2;
9920
9926
  let prompt, label = "";
9921
9927
  if (typeof json3.prompt === "string" && json3.prompt.trim()) {
@@ -10738,14 +10744,14 @@ function windowsCoded(read4, input, execPath, realPath) {
10738
10744
  var windowsUnknown = (port2, why) => `Windows Firewall could not be read (${why}). If a phone cannot connect, in an elevated PowerShell allow the port with \`${allowCommand(port2)}\`, and list rules that block node.exe with \`${listCommand}\`; disable one by its InstanceID with \`Disable-NetFirewallRule -Name '<InstanceID>'\`.`;
10739
10745
  async function readWindows(input, execPath, exec, env, realpath3) {
10740
10746
  if (!Number.isInteger(input.port) || input.port < 1 || input.port > 65535) throw new Error(`not a port: ${input.port}`);
10741
- let real3;
10747
+ let real4;
10742
10748
  try {
10743
- real3 = realpath3(execPath);
10749
+ real4 = realpath3(execPath);
10744
10750
  } catch {
10745
10751
  }
10746
- const { file: file3, args, options } = windowsCommand(env, real3 ? [execPath, real3] : [execPath]);
10752
+ const { file: file3, args, options } = windowsCommand(env, real4 ? [execPath, real4] : [execPath]);
10747
10753
  try {
10748
- const read4 = parseWindows(await exec(file3, args, options)), coded2 = windowsCoded(read4, input, execPath, real3), notes = texts(coded2);
10754
+ const read4 = parseWindows(await exec(file3, args, options)), coded2 = windowsCoded(read4, input, execPath, real4), notes = texts(coded2);
10749
10755
  return { notes, coded: coded2, summary: `Windows Firewall: ${read4.rules.length} inbound rules read, ${notes.length} note${notes.length === 1 ? "" : "s"}` };
10750
10756
  } catch (error) {
10751
10757
  const e = error;
@@ -11987,7 +11993,7 @@ function nodsOf(folder, clean6, budget) {
11987
11993
  return out;
11988
11994
  }
11989
11995
  function noticeLookup(stateDir, project, budget, clean6, book) {
11990
- const real3 = carsFolderOk(stateDir, project), seen = /* @__PURE__ */ new Map();
11996
+ const real4 = carsFolderOk(stateDir, project), seen = /* @__PURE__ */ new Map();
11991
11997
  const lineOf = (view) => {
11992
11998
  const latest = view.file.states.at(-1);
11993
11999
  if (!latest) return void 0;
@@ -12004,7 +12010,7 @@ ${head}`;
12004
12010
  seen.set(key2, told2);
12005
12011
  return told2;
12006
12012
  }
12007
- if (!real3) return void 0;
12013
+ if (!real4) return void 0;
12008
12014
  const found = (() => {
12009
12015
  try {
12010
12016
  let name2;
@@ -12033,8 +12039,8 @@ function cleanWait(wait2, clean6) {
12033
12039
  if ("lane" in wait2) return { lane: { app: clean6(wait2.lane.app, 64), holder: clean6(wait2.lane.holder, 32), ...wait2.lane.why ? { why: wait2.lane.why } : {} } };
12034
12040
  return { target: { target: clean6(wait2.target.target, 128), holder: clean6(wait2.target.holder, 32), ...wait2.target.why ? { why: wait2.target.why } : {} } };
12035
12041
  }
12036
- function unitOf(join60, project, code, writer) {
12037
- const claims = join60.trains.filter((u) => u.project === project && u.code === code);
12042
+ function unitOf(join63, project, code, writer) {
12043
+ const claims = join63.trains.filter((u) => u.project === project && u.code === code);
12038
12044
  return claims.length === 1 ? claims[0].key : claims.find((u) => u.key === writer)?.key;
12039
12045
  }
12040
12046
  function readYards(deps, join_) {
@@ -13747,16 +13753,16 @@ function readLabels(state, team) {
13747
13753
  const hasTable = entry.op === "create" || entry.op === "remove" || entry.op === "rotate", hasLabel = entry.op === "add";
13748
13754
  if (!hasTable && !hasLabel) continue;
13749
13755
  const blob = entry.op === "add" ? dec(entry.payload, 2)[0] : entry.op === "create" ? entry.payload : sealedList(entry.payload).table;
13750
- const plain3 = openUnderTeamKey({ team, epoch: entry.epoch, key: key2, sealed: blob });
13751
- if (!plain3) return fail("fork-label", entry.seq);
13756
+ const plain4 = openUnderTeamKey({ team, epoch: entry.epoch, key: key2, sealed: blob });
13757
+ if (!plain4) return fail("fork-label", entry.seq);
13752
13758
  try {
13753
13759
  if (hasLabel) {
13754
- const label = readStr(dec(plain3, 1)[0]);
13760
+ const label = readStr(dec(plain4, 1)[0]);
13755
13761
  if (!labelOk(label)) return fail("fork-label", entry.seq);
13756
13762
  labels.set(entry.subject.record.id, label);
13757
13763
  } else {
13758
13764
  const table = /* @__PURE__ */ new Map();
13759
- for (const item of readList(plain3)) {
13765
+ for (const item of readList(plain4)) {
13760
13766
  const [id, label] = dec(item, 2).map(readStr);
13761
13767
  if (!labelOk(label) || table.has(id)) return fail("fork-label", entry.seq);
13762
13768
  table.set(id, label);
@@ -13892,11 +13898,11 @@ function buildJoinRequest(o) {
13892
13898
  function openJoinRequest(o) {
13893
13899
  const no19 = (reason) => ({ ok: false, reason });
13894
13900
  if (o.blob.length < NONCE_BYTES) return no19("bad-ciphertext");
13895
- const plain3 = aeadOpen(joinKey(o.secret, o.team), o.blob.subarray(0, NONCE_BYTES), o.blob.subarray(NONCE_BYTES));
13896
- if (!plain3) return no19("bad-ciphertext");
13901
+ const plain4 = aeadOpen(joinKey(o.secret, o.team), o.blob.subarray(0, NONCE_BYTES), o.blob.subarray(NONCE_BYTES));
13902
+ if (!plain4) return no19("bad-ciphertext");
13897
13903
  let rec, label, mac;
13898
13904
  try {
13899
- [rec, label, mac] = dec(plain3, 3);
13905
+ [rec, label, mac] = dec(plain4, 3);
13900
13906
  } catch {
13901
13907
  return no19("bad-request");
13902
13908
  }
@@ -15543,7 +15549,7 @@ var LinkHolder = class {
15543
15549
  const live = !!main && mainPane?.tokens?.sb_role === "main", was2 = this.offered.get(id), first3 = live && was2?.tower === main.id ? was2.first ?? was2.at : this.now();
15544
15550
  const over = live && !this.o.waits && this.now() - first3 >= REPLY_OFFER_MS, expired2 = this.now() - item.received >= REPLY_HOLD_MS;
15545
15551
  if (!live || over || expired2) {
15546
- const { reply: reply3, ...plain3 } = item, why = !main ? "gone" : !live ? "not-main" : expired2 ? "expired" : "not-taken";
15552
+ const { reply: reply3, ...plain4 } = item, why = !main ? "gone" : !live ? "not-main" : expired2 ? "expired" : "not-taken";
15547
15553
  this.offered.delete(id);
15548
15554
  const routed = this.o.waits?.orphan ? await this.o.waits.orphan(item, reply3.mainName, pickedWs()).catch((error) => (store2.log({ event: "wait-take-failed", id, error: error.message }), false)) : false;
15549
15555
  if (routed === "held") continue;
@@ -15553,7 +15559,7 @@ var LinkHolder = class {
15553
15559
  await store2.withLock(() => store2.removeInbox(id));
15554
15560
  continue;
15555
15561
  }
15556
- await store2.withLock(() => store2.putInbox({ ...plain3, askedBy: reply3.mainName }));
15562
+ await store2.withLock(() => store2.putInbox({ ...plain4, askedBy: reply3.mainName }));
15557
15563
  if (main) this.noteReplyFallback(id, main.id);
15558
15564
  store2.log({ event: "reply-fallback", id, why });
15559
15565
  this.again = true;
@@ -15587,11 +15593,11 @@ var LinkHolder = class {
15587
15593
  servedNow.add(first2.session.id);
15588
15594
  continue;
15589
15595
  }
15590
- const was = this.offered.get(id), pick2 = was && picks.find((p) => p.session.id === was.tower) || first2;
15591
- if (was && was.tower === pick2.session.id && this.now() - was.at < (this.o.offerAgainMs ?? 3e4)) continue;
15592
- this.offered.set(id, { tower: pick2.session.id, at: this.now() });
15596
+ const was = this.offered.get(id), pick3 = was && picks.find((p) => p.session.id === was.tower) || first2;
15597
+ if (was && was.tower === pick3.session.id && this.now() - was.at < (this.o.offerAgainMs ?? 3e4)) continue;
15598
+ this.offered.set(id, { tower: pick3.session.id, at: this.now() });
15593
15599
  this.waiting.get(id).offered = true;
15594
- await this.o.offer(pick2.session, id);
15600
+ await this.o.offer(pick3.session, id);
15595
15601
  }
15596
15602
  for (const identity2 of servedNow) {
15597
15603
  try {
@@ -17124,7 +17130,7 @@ function createLinkService({ kit, stateDir, version, started, pid = process.pid,
17124
17130
  lookError = error.message;
17125
17131
  note(`Straw Link: the link holder could not start: ${error.message}`, "error");
17126
17132
  };
17127
- const refusal6 = () => {
17133
+ const refusal7 = () => {
17128
17134
  const found = policy();
17129
17135
  return found.mode === "refused" ? `Straw Link: unattended mode is refused (${found.reason}); no link holder runs on this computer` : void 0;
17130
17136
  };
@@ -17230,7 +17236,7 @@ function createLinkService({ kit, stateDir, version, started, pid = process.pid,
17230
17236
  };
17231
17237
  const handle = async (body2, from) => {
17232
17238
  const op = typeof body2 === "object" && body2 !== null ? body2 : {};
17233
- 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) };
17234
17240
  const only = Array.isArray(body2.teams) ? body2.teams.filter((t) => typeof t === "string") : void 0;
17235
17241
  if (op.op === "list") return { ok: true, teams: holder.list(only) };
17236
17242
  if (op.op === "board-read") return holder.boards({ ...only ? { only } : {}, ...typeof op.device === "string" ? { device: op.device } : {} });
@@ -17563,11 +17569,11 @@ var OperateSession = class _OperateSession {
17563
17569
  onFrame(m) {
17564
17570
  if (m.ctr <= this.recvCtr) return this.drop("replay", "frame");
17565
17571
  const keys = this.keys, mine = this.role === "box";
17566
- const plain3 = operateOpen({ key: mine ? keys.subarray(0, 32) : keys.subarray(32), dir: mine ? "toBox" : "toOperator", session: this.id, ctr: m.ctr, ct: m.ct });
17567
- if (!plain3) return this.drop("unsealed", "frame");
17572
+ const plain4 = operateOpen({ key: mine ? keys.subarray(0, 32) : keys.subarray(32), dir: mine ? "toBox" : "toOperator", session: this.id, ctr: m.ctr, ct: m.ct });
17573
+ if (!plain4) return this.drop("unsealed", "frame");
17568
17574
  this.recvCtr = m.ctr;
17569
17575
  this.lastRecv = this.clock();
17570
- this.take(plain3, false);
17576
+ this.take(plain4, false);
17571
17577
  }
17572
17578
  /** An inflated, parsed inner message, from a frame (`plain` is its deflated bytes) or from reassembled parts. */
17573
17579
  take(z, assembled) {
@@ -19164,13 +19170,13 @@ function fold3(source) {
19164
19170
  }
19165
19171
  var order = (a, b) => b.last - a.last || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
19166
19172
  function readable(file3, root) {
19167
- const real3 = canonical2(file3), top2 = canonical2(root);
19168
- if (!real3 || !top2 || !real3.endsWith(".jsonl") || !real3.startsWith(top2 + sep6)) return void 0;
19173
+ const real4 = canonical2(file3), top2 = canonical2(root);
19174
+ if (!real4 || !top2 || !real4.endsWith(".jsonl") || !real4.startsWith(top2 + sep6)) return void 0;
19169
19175
  let fd;
19170
19176
  try {
19171
- fd = openSync8(real3, constants7.O_RDONLY | constants7.O_NONBLOCK | (constants7.O_NOFOLLOW ?? 0));
19172
- const s2 = fstatSync5(fd), at = statSync11(real3);
19173
- return s2.isFile() && s2.nlink === 1 && s2.dev === at.dev && s2.ino === at.ino ? { real: real3, size: s2.size } : void 0;
19177
+ fd = openSync8(real4, constants7.O_RDONLY | constants7.O_NONBLOCK | (constants7.O_NOFOLLOW ?? 0));
19178
+ const s2 = fstatSync5(fd), at = statSync11(real4);
19179
+ return s2.isFile() && s2.nlink === 1 && s2.dev === at.dev && s2.ino === at.ino ? { real: real4, size: s2.size } : void 0;
19174
19180
  } catch {
19175
19181
  return void 0;
19176
19182
  } finally {
@@ -19700,9 +19706,9 @@ var CarBook = class {
19700
19706
  if (!look3) throw refusal4(`sb: session ${session} is not live on the net, so it cannot register`);
19701
19707
  if (look3.pane !== pane) throw refusal4(`sb: session ${session} does not run in pane ${pane}`);
19702
19708
  if (!look3.foreground.includes(pid)) throw refusal4(`sb: pid ${pid} is not a foreground process of pane ${pane}; only the pi of the pane registers`);
19703
- const real3 = this.d.startOf(pid);
19704
- if (real3 === void 0) throw refusal4(`sb: the start time of pid ${pid} cannot be read, so it cannot register`);
19705
- if (real3 !== started) throw refusal4(`sb: pid ${pid} started at ${real3}, not ${started}`);
19709
+ const real4 = this.d.startOf(pid);
19710
+ if (real4 === void 0) throw refusal4(`sb: the start time of pid ${pid} cannot be read, so it cannot register`);
19711
+ if (real4 !== started) throw refusal4(`sb: pid ${pid} started at ${real4}, not ${started}`);
19706
19712
  const known2 = this.bySession.get(session), old = known2 ? this.regs.get(known2) : void 0;
19707
19713
  if (old && look3.foreground.includes(old.pid) && this.d.startOf(old.pid) === old.started) throw refusal4(`sb: session ${session} is already registered to a live process (pid ${old.pid}); a registration is not replaced while that process runs`);
19708
19714
  if (known2) this.regs.delete(known2);
@@ -20447,15 +20453,15 @@ function physical(path) {
20447
20453
  }
20448
20454
  }
20449
20455
  }
20450
- function checkoutOf(cwd, disk = realDisk, real3 = physical) {
20451
- for (let dir = real3(cwd); ; dir = dirname15(dir)) {
20456
+ function checkoutOf(cwd, disk = realDisk, real4 = physical) {
20457
+ for (let dir = real4(cwd); ; dir = dirname15(dir)) {
20452
20458
  const git = join43(dir, ".git"), kind = disk.kind(git);
20453
20459
  if (kind === "dir") return { kind: "main", root: dir };
20454
20460
  if (kind === "file") {
20455
20461
  const gitdir = /^gitdir:\s*(.+?)\s*$/m.exec(disk.read(git) ?? "")?.[1];
20456
20462
  if (gitdir && /[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitdir)) {
20457
20463
  const admin = resolve7(dir, gitdir), back = disk.read(join43(admin, "gitdir"))?.trim();
20458
- if (disk.kind(admin) === "dir" && back && real3(resolve7(admin, back)) === join43(dir, ".git")) return { kind: "linked", root: dir, gitdir };
20464
+ if (disk.kind(admin) === "dir" && back && real4(resolve7(admin, back)) === join43(dir, ".git")) return { kind: "linked", root: dir, gitdir };
20459
20465
  return { kind: "none" };
20460
20466
  }
20461
20467
  if (gitdir && /[\\/]modules[\\/]/.test(gitdir)) return { kind: "submodule", root: dir };
@@ -20608,7 +20614,7 @@ function createProcs(d) {
20608
20614
  const folder = join44(d.dir, "procs"), file3 = join44(folder, OWNERS_FILE);
20609
20615
  const read4 = d.read ?? (() => readTable()), cwdsOf = d.cwds ?? ((pids) => readCwds(pids)), markersOf = d.markers ?? ((pids) => readOwners(pids));
20610
20616
  const inode = d.inode ?? inodeOnDisk, checkout = d.checkout ?? checkoutOf, probe = d.startOf ?? startOf, reap2 = d.reap ?? ((refs) => reap(refs));
20611
- const platform = d.platform ?? process.platform, self = d.self ?? [process.pid], real3 = d.real ?? physical, exists = d.exists ?? existsSync7;
20617
+ const platform = d.platform ?? process.platform, self = d.self ?? [process.pid], real4 = d.real ?? physical, exists = d.exists ?? existsSync7;
20612
20618
  const owners = /* @__PURE__ */ new Map();
20613
20619
  const pending = /* @__PURE__ */ new Set();
20614
20620
  const linked = /* @__PURE__ */ new Map();
@@ -20896,7 +20902,7 @@ function createProcs(d) {
20896
20902
  return result2;
20897
20903
  },
20898
20904
  async reapCheckout(path) {
20899
- const physicalPath = real3(path), table = await read4();
20905
+ const physicalPath = real4(path), table = await read4();
20900
20906
  const holders2 = (where) => [...owners.values()].filter((r) => !r.ended && table && alive2(table, r) && r.roots.some((root2) => overlap(where, root2)));
20901
20907
  let root;
20902
20908
  if (exists(physicalPath)) {
@@ -22463,24 +22469,512 @@ function runNotice(s2) {
22463
22469
  }
22464
22470
 
22465
22471
  // src/server/towers.ts
22466
- import { createHash as createHash23 } from "node:crypto";
22467
- import { mkdirSync as mkdirSync17, readdirSync as readdirSync16, readFileSync as readFileSync41, rmSync as rmSync14 } from "node:fs";
22468
- import { join as join58 } from "node:path";
22472
+ import { createHash as createHash25 } from "node:crypto";
22473
+ import { mkdirSync as mkdirSync19, readdirSync as readdirSync18, readFileSync as readFileSync43, rmSync as rmSync16 } from "node:fs";
22474
+ import { join as join61 } from "node:path";
22469
22475
 
22470
22476
  // src/closemain.ts
22471
22477
  import { randomUUID as randomUUID12 } from "node:crypto";
22478
+
22479
+ // src/deadpane.ts
22480
+ import { statSync as statSync18 } from "node:fs";
22481
+
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
+ }
22509
+
22510
+ // src/integrator.ts
22511
+ import { existsSync as existsSync8, readdirSync as readdirSync15 } from "node:fs";
22512
+ import { join as join52 } from "node:path";
22513
+ var INTEGRATOR = "integrator";
22514
+ var MAX_OPENED_INTEGRATORS = 2;
22515
+ var MARK2 = "integ:";
22516
+ var integMark = (project) => `${MARK2}${project}`;
22517
+ var integratorOf = (token) => {
22518
+ const project = typeof token === "string" && token.startsWith(MARK2) ? token.slice(MARK2.length) : void 0;
22519
+ return isName(project) ? project : void 0;
22520
+ };
22521
+ function ledgerProjects(stateDir, app) {
22522
+ try {
22523
+ return readdirSync15(join52(stateDir, "trains")).filter((project) => isName(project) && existsSync8(join52(stateDir, "trains", project, `${app}.json`)));
22524
+ } catch {
22525
+ return [];
22526
+ }
22527
+ }
22528
+ var integratorHandoff = (workspace, project, tower) => [
22529
+ `Straw Boss: the tower of workspace ${workspace} opened this tab for you: you are the integrator of project ${project}, the tower's own main, of kind integrator and named integ ${project}.`,
22530
+ "Car slips reach you as the tower's forwards, the first right after this message; each names its sender (fwd-from). Report to the tower that opened this tab with call_tower as your prompt describes; when your queue is empty and no train waits to be opened, report idle (why: milestone, reply: false) and the tower closes this tab.",
22531
+ `Tower: ${tower.name} (session id ${tower.id})`
22532
+ ].join("\n");
22533
+ function liveIntegrator(everywhere, sessions, project) {
22534
+ const isIntegrator = (p) => p.tokens?.sb_role === "main" && p.tokens.sb_duty === INTEGRATOR, live = /* @__PURE__ */ new Map();
22535
+ for (const pane of everywhere.filter((p) => integratorOf(p.tokens?.sb_opened_by) === project)) {
22536
+ const session = sessions.find((s2) => s2.herdrLocation?.paneId === pane.pane_id);
22537
+ if (!session || pane.tokens?.sb_role !== "main") return { refusal: `The integrator of project ${project} (pane ${pane.pane_id}) has not joined yet or no longer answers; a project has one, so nothing opens. Try again when it has joined, or when its tab has closed.` };
22538
+ if (!isIntegrator(pane)) return { refusal: `The main opened as the integrator of project ${project} (${session.name ?? session.id}, session ${session.id}) is of kind ${pane.tokens.sb_duty ?? "none"} now; a project has one, so nothing opens and no slip goes to it. It calls boss_duty with integrator, or the boss closes it.` };
22539
+ live.set(session.id, { session, pane });
22540
+ }
22541
+ for (const session of sessions) {
22542
+ const pane = session.name === `integ ${project}` ? everywhere.find((p) => p.pane_id === session.herdrLocation?.paneId) : void 0;
22543
+ if (pane && isIntegrator(pane) && !pane.tokens?.sb_opened_by?.startsWith("link:")) live.set(session.id, { session, pane });
22544
+ }
22545
+ if (live.size > 1) return { refusal: `Project ${project} has ${live.size} integrators (${[...live.keys()].map((id) => `session ${id}`).join(", ")}); a project has one, so the slip goes to neither. The boss closes one.` };
22546
+ return [...live.values()][0];
22547
+ }
22548
+ function keptIntegrators(everywhere, sessions, mine) {
22549
+ return sessions.flatMap((session) => {
22550
+ const pane = everywhere.find((p) => p.pane_id === session.herdrLocation?.paneId), by = pane?.tokens?.sb_opened_by;
22551
+ return pane && pane.tokens?.sb_role === "main" && pane.tokens.sb_duty === INTEGRATOR && !by?.startsWith("link:") && !by?.startsWith(MARK2) && mine(pane) ? [{ session, pane }] : [];
22552
+ });
22553
+ }
22554
+ var ForwardAsBefore = class extends Error {
22555
+ mains;
22556
+ constructor(project, apps, mains) {
22557
+ const one4 = mains.length === 1;
22558
+ super(`Project ${project} already runs ${one4 ? "an integrator" : `${mains.length} integrators`} of its own, opened before this door and not by it: ${mains.map((m) => `${m.name} (session ${m.id})`).join(", ")}. Nothing opens beside ${one4 ? "it" : "them"} and the door picks none: the slip of app${apps.length === 1 ? "" : "s"} ${apps.join(", ")} goes to the one that runs ${apps.length === 1 ? "that app's" : "those apps'"} trains, forwarded as before.`);
22559
+ this.mains = mains;
22560
+ }
22561
+ };
22562
+
22563
+ // src/roles.ts
22564
+ import { createHash as createHash20 } from "node:crypto";
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";
22566
+ import { join as join53 } from "node:path";
22567
+ var KEEP_MS10 = 90 * 24 * 36e5;
22568
+ var keyOf3 = (file3) => createHash20("sha256").update(file3).digest("hex").slice(0, 32);
22569
+ var ENDED2 = /* @__PURE__ */ new Set(["quit", "new", "resume", "fork", "signal"]);
22570
+ var rolesDir = (stateDir) => join53(stateDir, "roles");
22571
+ var recordPath = (stateDir, file3) => join53(rolesDir(stateDir), `${keyOf3(file3)}.json`);
22572
+ function loadRecord(record2, problem) {
22573
+ let raw;
22574
+ try {
22575
+ raw = readFileSync39(record2, "utf8");
22576
+ } catch (error) {
22577
+ if (error.code !== "ENOENT") problem?.(error.message);
22578
+ return void 0;
22579
+ }
22580
+ try {
22581
+ const r = JSON.parse(raw);
22582
+ if (r.duty !== void 0 && !isCoordinatorDuty(r.duty)) delete r.duty;
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;
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;
22585
+ if (r.role === TRAIN && !(r.train && trainFromToken(trainToken(r.train)))) return void 0;
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;
22587
+ } catch {
22588
+ return void 0;
22589
+ }
22590
+ }
22591
+ function readRecords(stateDir) {
22592
+ let names = [];
22593
+ try {
22594
+ names = readdirSync16(rolesDir(stateDir)).filter((name2) => /^[0-9a-f]{32}\.json$/.test(name2));
22595
+ } catch {
22596
+ }
22597
+ return names.flatMap((name2) => {
22598
+ const path = join53(rolesDir(stateDir), name2), record2 = loadRecord(path);
22599
+ return record2?.file && path === recordPath(stateDir, record2.file) ? [{ path, record: record2 }] : [];
22600
+ });
22601
+ }
22602
+
22603
+ // src/revive.ts
22604
+ var REVIVE_TOKEN = "sb_revive";
22605
+ var MAX_REVIVES = 2;
22606
+ var LOOP_MS = 10 * 6e4;
22607
+ var DAY_MS = 24 * 36e5;
22608
+ var KEEP_MS11 = 7 * DAY_MS;
22609
+ var HEADER_MAX = 64 * 1024;
22610
+ var SCAN_MAX = 32 * 1024 * 1024;
22611
+ var POLICY = ".pi-herdr-subagent-policy.json";
22612
+ var ReviveRefused = class extends Error {
22613
+ };
22614
+ var sessionsDir = (env = process.env) => join54(env.PI_CODING_AGENT_DIR || join54(homedir14(), ".pi", "agent"), "sessions");
22615
+ var keyOf4 = (file3) => createHash21("sha256").update(file3).digest("hex").slice(0, 32);
22616
+ var reviveDir = (stateDir) => join54(stateDir, "revive");
22617
+ var ledgerPath = (stateDir, file3) => join54(reviveDir(stateDir), `${keyOf4(file3)}.json`);
22618
+ function sessionHeader(file3) {
22619
+ try {
22620
+ const fd = openSync10(file3, "r");
22621
+ try {
22622
+ const buffer = Buffer.alloc(HEADER_MAX), n = readSync3(fd, buffer, 0, HEADER_MAX, 0), first2 = buffer.subarray(0, n).toString("utf8").split("\n")[0];
22623
+ const h = JSON.parse(first2);
22624
+ return h.type === "session" && typeof h.id === "string" ? { id: h.id, ...typeof h.cwd === "string" ? { cwd: h.cwd } : {}, ...typeof h.parentSession === "string" ? { parentSession: h.parentSession } : {} } : void 0;
22625
+ } finally {
22626
+ closeSync10(fd);
22627
+ }
22628
+ } catch {
22629
+ return void 0;
22630
+ }
22631
+ }
22632
+ var idOfName = (file3) => /_([0-9a-f][0-9a-f-]{7,63})\.jsonl$/.exec(basename14(file3))?.[1];
22633
+ var real3 = (path) => {
22634
+ try {
22635
+ return realpathSync11(path);
22636
+ } catch {
22637
+ return void 0;
22638
+ }
22639
+ };
22640
+ var within2 = (path, root) => path === root || path.startsWith(root.endsWith(sep9) ? root : root + sep9);
22641
+ function fileRefusal(file3, o) {
22642
+ let stat6;
22643
+ try {
22644
+ stat6 = lstatSync12(file3);
22645
+ } catch {
22646
+ return "its session file is gone";
22647
+ }
22648
+ if (!stat6.isFile()) return "its session file is no regular file (a link or a folder)";
22649
+ const root = real3(o.root), path = real3(file3);
22650
+ if (!root || !path || !within2(path, root)) return "its session file is outside pi's sessions folder";
22651
+ if (existsSync9(`${file3}${POLICY}`)) return "its session file is a subagent's (it has pi-herdr-agents' policy sidecar): a subagent is resumed by its parent, not revived";
22652
+ const header2 = sessionHeader(file3), named = idOfName(file3);
22653
+ if (!header2) return "its session file has no pi session header";
22654
+ if (!named || header2.id !== named) return `its session file's header id (${header2.id.slice(0, 13)}) is not the id in its name: the intercom id would differ (PI_INTERCOM_STABLE_ID or a renamed file), so nothing it held would find it`;
22655
+ if (o.checkout && !(header2.cwd && real3(header2.cwd) && within2(real3(header2.cwd), real3(o.checkout) ?? o.checkout))) return `its working folder (${header2.cwd ?? "none"}) is outside the workspace's checkout`;
22656
+ if (header2.cwd && !real3(header2.cwd)) return `its working folder ${header2.cwd} is gone`;
22657
+ return void 0;
22658
+ }
22659
+ function sessionNotes(file3) {
22660
+ let text11;
22661
+ try {
22662
+ const size2 = statSync17(file3).size, fd = openSync10(file3, "r");
22663
+ try {
22664
+ const from = Math.max(0, size2 - SCAN_MAX), buffer = Buffer.alloc(size2 - from), n = readSync3(fd, buffer, 0, buffer.length, from);
22665
+ text11 = buffer.subarray(0, n).toString("utf8");
22666
+ } finally {
22667
+ closeSync10(fd);
22668
+ }
22669
+ } catch {
22670
+ return {};
22671
+ }
22672
+ let name2, duty, openedBy, train;
22673
+ for (const row2 of text11.split("\n")) {
22674
+ if (!row2.includes('"session_info"') && !row2.includes('"straw-boss"')) continue;
22675
+ try {
22676
+ const e = JSON.parse(row2);
22677
+ if (e.type === "session_info") name2 = typeof e.name === "string" && e.name.trim() ? e.name.trim() : void 0;
22678
+ else if (e.type === "custom" && e.customType === "straw-boss" && e.data) {
22679
+ if ("duty" in e.data) duty = isCoordinatorDuty(e.data.duty) ? e.data.duty : duty;
22680
+ if ("openedBy" in e.data) openedBy = typeof e.data.openedBy === "string" ? e.data.openedBy : void 0;
22681
+ if (e.data.train && typeof e.data.train === "object") train = trainFromToken(trainToken(e.data.train)) ?? train;
22682
+ }
22683
+ } catch {
22684
+ }
22685
+ }
22686
+ return { ...name2 ? { name: name2 } : {}, ...duty ? { duty } : {}, ...openedBy ? { openedBy } : {}, ...train ? { train } : {} };
22687
+ }
22688
+ var deathKey = (file3) => {
22689
+ try {
22690
+ const st = statSync17(file3);
22691
+ return createHash21("sha256").update(`${file3}
22692
+ ${st.size}
22693
+ ${Math.trunc(st.mtimeMs)}`).digest("hex").slice(0, 16);
22694
+ } catch {
22695
+ return void 0;
22696
+ }
22697
+ };
22698
+ function readLedger2(stateDir, file3, session = idOfName(file3) ?? "") {
22699
+ try {
22700
+ const l = JSON.parse(readFileSync40(ledgerPath(stateDir, file3), "utf8"));
22701
+ if (l.v === 1 && l.file === file3) return { v: 1, file: file3, session: typeof l.session === "string" ? l.session : session, detections: Array.isArray(l.detections) ? l.detections : [], attempts: Array.isArray(l.attempts) ? l.attempts : [], missed: Array.isArray(l.missed) ? l.missed : [] };
22702
+ } catch {
22703
+ }
22704
+ return { v: 1, file: file3, session, detections: [], attempts: [], missed: [] };
22705
+ }
22706
+ function updateLedger(stateDir, file3, now, change) {
22707
+ const l = readLedger2(stateDir, file3);
22708
+ change(l);
22709
+ l.detections = l.detections.filter((d) => now - d.at < KEEP_MS11).slice(-32);
22710
+ l.attempts = l.attempts.filter((a) => now - a.at < KEEP_MS11).slice(-32);
22711
+ l.missed = l.missed.filter((m) => now - m.at < DAY_MS).slice(-16);
22712
+ mkdirSync16(reviveDir(stateDir), { recursive: true, mode: 448 });
22713
+ const path = ledgerPath(stateDir, file3), temp = `${path}.${process.pid}.tmp`;
22714
+ writeFileSync9(temp, JSON.stringify(l), { mode: 384 });
22715
+ renameSync9(temp, path);
22716
+ return l;
22717
+ }
22718
+ var revivedIn = (l, now) => l.attempts.filter((a) => a.outcome === "revived" && now - a.at < DAY_MS);
22719
+ var failedIn = (l, now) => l.attempts.filter((a) => a.outcome === "failed" && now - a.at < DAY_MS);
22720
+ function noteMissed(stateDir, file3, now, from, text11) {
22721
+ updateLedger(stateDir, file3, now, (l) => void l.missed.push({ at: now, from: from.slice(0, 80), text: text11.slice(0, 2e3) }));
22722
+ }
22723
+ function takeLock(stateDir, file3, now) {
22724
+ mkdirSync16(reviveDir(stateDir), { recursive: true, mode: 448 });
22725
+ const path = `${ledgerPath(stateDir, file3)}.lock`;
22726
+ for (let attempt = 0; attempt < 2; attempt++) {
22727
+ try {
22728
+ writeFileSync9(path, String(process.pid), { flag: "wx", mode: 384 });
22729
+ return () => rmSync15(path, { force: true });
22730
+ } catch (error) {
22731
+ if (error.code !== "EEXIST") throw error;
22732
+ let age2 = 0;
22733
+ try {
22734
+ age2 = now - statSync17(path).mtimeMs;
22735
+ } catch {
22736
+ continue;
22737
+ }
22738
+ if (age2 < 5 * 6e4) break;
22739
+ rmSync15(path, { force: true });
22740
+ }
22741
+ }
22742
+ throw new ReviveRefused("another tower is reviving this session right now");
22743
+ }
22744
+ function countOrphans(file3) {
22745
+ const count4 = { finished: 0, pings: 0, open: 0, worktree: 0, persistent: 0 }, base = artifacts(file3);
22746
+ let ids = [];
22747
+ try {
22748
+ ids = readdirSync17(join54(base, "subagent-activity")).filter((n) => n.endsWith(".json")).map((n) => n.slice(0, -5));
22749
+ } catch {
22750
+ return count4;
22751
+ }
22752
+ let scripts = [];
22753
+ try {
22754
+ scripts = readdirSync17(join54(base, "subagent-scripts"));
22755
+ } catch {
22756
+ }
22757
+ for (const id of ids) {
22758
+ const script = scripts.find((n) => n.endsWith(`-${id}.sh`) && !n.includes("-resume-"));
22759
+ let text11 = "";
22760
+ try {
22761
+ text11 = script ? readFileSync40(join54(base, "subagent-scripts", script), "utf8") : "";
22762
+ } catch {
22763
+ }
22764
+ const session = /^# Session: (.+)$/m.exec(text11)?.[1]?.trim();
22765
+ if (/\bPI_SUBAGENT_PERSISTENT=1\b/.test(text11)) count4.persistent++;
22766
+ else if (existsSync9(join54(base, "worktree-runs", `${id}.json`))) count4.worktree++;
22767
+ else if (session && existsSync9(`${session}.exit`)) {
22768
+ try {
22769
+ JSON.parse(readFileSync40(`${session}.exit`, "utf8")).type === "ping" ? count4.pings++ : count4.finished++;
22770
+ } catch {
22771
+ count4.finished++;
22772
+ }
22773
+ } else count4.open++;
22774
+ }
22775
+ return count4;
22776
+ }
22777
+ var countText = (c) => {
22778
+ const parts = [c.finished && `${c.finished} finished`, c.pings && `${c.pings} asking for help`, c.open && `${c.open} open (running, idle, or cut)`, c.worktree && `${c.worktree} worktree`, c.persistent && `${c.persistent} persistent`].filter(Boolean);
22779
+ return parts.length ? parts.join(", ") : "none";
22780
+ };
22781
+ async function gatherDead(d) {
22782
+ const records = readRecords(d.stateDir).filter((r) => r.record.role !== "tower" && (!d.workspace || r.record.workspace === d.workspace));
22783
+ if (!records.length) return [];
22784
+ const [ps, sessions] = await Promise.all([d.panes ?? panes(d.run), d.sessionList ?? d.sessions()]);
22785
+ return records.map(({ record: record2 }) => {
22786
+ const file3 = record2.file, session = idOfName(file3) ?? sessionHeader(file3)?.id ?? keyOf4(file3);
22787
+ let mtimeMs;
22788
+ try {
22789
+ mtimeMs = statSync17(file3).mtimeMs;
22790
+ } catch {
22791
+ }
22792
+ const invalid = mtimeMs === void 0 ? void 0 : fileRefusal(file3, { root: d.root, ...d.checkout ? { checkout: d.checkout } : {} });
22793
+ const held2 = ps.some((p) => p.agent_session?.value === file3), listed2 = sessions.some((s2) => s2.id === session);
22794
+ const seen = d.seen?.(file3);
22795
+ const verdict = classify({ now: d.now, record: record2, ...invalid ? { invalid } : {}, ...mtimeMs !== void 0 ? { mtimeMs } : {}, held: held2, listed: listed2, recovering: Boolean(d.recovering), ...seen ? { seen } : {} });
22796
+ const notes = d.allNotes || verdict.state === "dead" || verdict.state === "quit" || verdict.state === "restoring" ? sessionNotes(file3) : {};
22797
+ let board;
22798
+ try {
22799
+ board = JSON.parse(readFileSync40(join54(d.stateDir, "board", `${session}.json`), "utf8")).now;
22800
+ } catch {
22801
+ }
22802
+ const kind = notes.duty ?? record2.duty, train = record2.role === "train" ? record2.train : void 0;
22803
+ return {
22804
+ session,
22805
+ file: file3,
22806
+ record: record2,
22807
+ verdict,
22808
+ ...notes.name ? { name: notes.name } : {},
22809
+ ...kind ? { kind } : {},
22810
+ ...record2.openedBy ? { openedBy: record2.openedBy } : {},
22811
+ ...train ? { train } : {},
22812
+ ...typeof board === "string" ? { board: line(board).slice(0, 120) } : {},
22813
+ ...mtimeMs !== void 0 ? { ageMs: d.now - mtimeMs } : {},
22814
+ ...verdict.state === "dead" || verdict.state === "quit" ? { key: deathKey(file3), orphans: countOrphans(file3) } : {}
22815
+ };
22816
+ });
22817
+ }
22818
+ function pick2(rows, query) {
22819
+ const q = query.trim();
22820
+ const found = rows.filter((r) => r.session === q || q.length >= 8 && r.session.startsWith(q) || r.name === q);
22821
+ if (found.length === 1) return found[0];
22822
+ if (found.length > 1) throw new ReviveRefused(`${found.length} sessions match ${JSON.stringify(q.slice(0, 40))} (${found.map((r) => `${r.name ?? "unnamed"} ${r.session.slice(0, 8)}`).join(", ")}): name one by its id`);
22823
+ throw new ReviveRefused(`No main or train of this workspace with a role record matches ${JSON.stringify(q.slice(0, 40))}. A member has no role record and holds nothing a tower restores: resume it with pi --session. A main closed on purpose (/boss close, boss_close_main) has none either.`);
22824
+ }
22825
+ function rowLine(r, now) {
22826
+ const what = r.record.role === "train" && r.train ? trainLabel(r.train.code) : `main ${r.name ? JSON.stringify(line(r.name).slice(0, 40)) : "(unnamed)"}`;
22827
+ const age2 = r.ageMs === void 0 ? "" : `, its file last moved ${ago(r.ageMs)} ago`;
22828
+ return `${what} (session ${r.session.slice(0, 8)}, kind ${r.kind ?? "none"}, tab ${r.record.tab}${r.openedBy ? `, opened by ${line(r.openedBy).slice(0, 60)}` : ", opened by the boss"}): ${r.verdict.state}: ${r.verdict.reason}${age2}${r.board ? `; board: ${r.board}` : ""}${r.orphans ? `; subagents: ${countText(r.orphans)}` : ""}${now ? "" : ""}`;
22829
+ }
22830
+ var ago = (ms3) => {
22831
+ const m = Math.max(0, Math.round(ms3 / 6e4));
22832
+ return m < 60 ? `${m}m` : m < 1440 ? `${Math.floor(m / 60)}h ${m % 60}m` : `${Math.floor(m / 1440)}d ${Math.floor(m % 1440 / 60)}h`;
22833
+ };
22834
+ var revivedText = (d) => `Revived ${d.train ? trainLabel(d.train.code) : `main ${d.name ?? d.main.slice(0, 8)}`} (session ${d.main}) in tab ${d.tab} as the same session, kind ${d.train ? "train" : d.kind ?? "none"}, and handed it what it held.${d.closedOld ? ` Its old tab ${d.closedOld} held only its dead pane at a shell and was closed.` : ""} It picks up its subagents itself.`;
22835
+ var diedText = (r, now) => `main_died: ${rowLine(r, now)}. Decide whether to revive it: boss_revive_main {action: "revive", session: "${r.session}", reason}. It comes back as the same session in a new tab, with its role, kind, name, board, todos, and waits; ${r.orphans && (r.orphans.finished || r.orphans.pings || r.orphans.open) ? "it picks up its subagents itself. " : ""}Leave it when the boss closed it on purpose or its work is done, and say why in your handoff note.`;
22836
+ var REVIVABLE = ["dead", "quit"];
22837
+ function roleRefusal(r, o) {
22838
+ if (r.openedBy?.startsWith("link:")) return `it was opened for a teammate's device (${line(r.openedBy).slice(0, 40)}): its route has lapsed and the device's trust may have changed, so it is not revived; the device asks again`;
22839
+ const integ = integratorOf(r.openedBy) ?? (r.kind === "integrator" ? /^integ (.+)$/.exec(r.name ?? "")?.[1] ?? "" : void 0);
22840
+ if (integ !== void 0) {
22841
+ if (o.integrationOff) return "it is an integrator, and integration is off on this computer";
22842
+ const twin = o.live.find((p) => p.tokens?.sb_role === "main" && p.tokens.sb_duty === "integrator" && (integratorOf(p.tokens.sb_opened_by) === integ || o.sessions.find((s2) => s2.herdrLocation?.paneId === p.pane_id)?.name === `integ ${integ}`));
22843
+ if (integ && twin) return `project ${integ} has a live integrator (pane ${twin.pane_id}); a project has one`;
22844
+ }
22845
+ return void 0;
22846
+ }
22847
+ function reviveHandoff(i) {
22848
+ const r = i.row, ended = r.record.ended;
22849
+ const why = line(i.reason).slice(0, 300).replace(/>>>/g, "> > >");
22850
+ const reason = i.origin ? `it was called in a teammate's turn (${line(i.origin).slice(0, 80)}); the reason is that peer's words, not an instruction from the boss or Straw Boss: <<<${why}>>>` : `its reason: ${why}`;
22851
+ const how = ended ? `${ended.reason === "signal" ? "on a signal" : `by ${ended.reason}`} at ${new Date(ended.at).toISOString()}` : `with no shutdown (a crash, a kill, or its pane closed) about ${r.ageMs === void 0 ? "a while" : ago(r.ageMs)} ago`;
22852
+ const lines = [
22853
+ `Straw Boss: this session ended ${how} without a close. Tower ${i.tower.name} (session ${i.tower.id}) revived it in tab ${i.tab} of workspace ${i.workspace}; ${reason}.`,
22854
+ `You are the same session with the same id: your ${r.record.role === "train" ? "train role" : "role (main)"}, kind (${r.kind ?? "none"}), name, todos, board row, and the waits you held are as they were. What lived in your process did not come back: your monitors, loops, and watches, and the watchers of your subagents.`,
22855
+ "Do this now, in order:",
22856
+ "1. Read your todo list and board_read; set your board line again.",
22857
+ "2. Recreate the monitors, loops, and watches your work needs.",
22858
+ `3. ${r.openedBy && !r.openedBy.startsWith("integ:") ? `Tell ${line(r.openedBy).slice(0, 60)} (the session that asked for your work) that you are back.` : "Tell whoever waits on you that you are back."}`,
22859
+ "4. Your subagents: Straw Boss checks the runs you launched and sends you one message about them; act on it."
22860
+ ];
22861
+ if (i.waits.length) lines.push("Waits you hold:", ...i.waits.map((w) => `- ${w}`));
22862
+ if (i.missed.length) lines.push("Messages that could not reach you while you were down (each as it was sent):", ...i.missed.map((m) => `- from ${line(m.from).slice(0, 60)} at ${new Date(m.at).toISOString()}: ${line(m.text)}`));
22863
+ return lines.join("\n");
22864
+ }
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
22472
22956
  var CONTROL8 = "straw-boss/control";
22473
22957
  var ASK_MS2 = 1e4;
22474
22958
  var RETRY_MS3 = 15e3;
22475
22959
  var RETRY_STEP_MS = 3e3;
22476
22960
  var QUIT_MS = 3e4;
22477
22961
  var STANDING_CLOSE = "is a standing main: it has no end and sends no done report, so only the boss closes it";
22478
- function refuseStanding(net, query) {
22962
+ function refuseStanding(net, query, stateDir) {
22479
22963
  const named = net.sessions.filter((x) => x.id === query || x.name === query);
22480
22964
  if (named.length !== 1) return;
22481
- 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}`);
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}`);
22482
22967
  }
22483
- function createCloseMain({ pi, cfg, s: s2, me }, { closeSelf, check, turn }) {
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 }) {
22484
22978
  const { run: run3, sleep: sleep2 } = cfg;
22485
22979
  let channel;
22486
22980
  const answers2 = /* @__PURE__ */ new Map();
@@ -22491,7 +22985,7 @@ function createCloseMain({ pi, cfg, s: s2, me }, { closeSelf, check, turn }) {
22491
22985
  if (!s2.joined) return no19("this session has not joined the net");
22492
22986
  const [all, workspace] = await Promise.all([panes(run3), workspaces(run3).then((list2) => list2.find((w) => w.workspace_id === s2.at.workspaceId))]);
22493
22987
  const mine = all.find((p) => p.pane_id === s2.at.paneId);
22494
- if (!mine?.tokens?.sb_opened_by) return no19("no tower opened this main, so only the boss closes it");
22988
+ if (!mine?.tokens?.sb_opened_by && !s2.saved.successor?.main) return no19("no tower opened this main, so only the boss closes it");
22495
22989
  if (!workspace?.tokens?.tower || workspace.tokens.tower !== from) return no19("the request is not from the tower of this workspace");
22496
22990
  const running = subagents(mine, all, cfg.now()).filter((row2) => !row2.ended).length;
22497
22991
  const subs = running && `${running} subagent${running > 1 ? "s are" : " is"} running`;
@@ -22523,8 +23017,9 @@ function createCloseMain({ pi, cfg, s: s2, me }, { closeSelf, check, turn }) {
22523
23017
  answers2.delete(reqId);
22524
23018
  return got;
22525
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 });
22526
23021
  return {
22527
- /** Every tower, and every main a tower opened, hears and answers asks; registering twice is a no-op. */
23022
+ /** Every tower, every main a tower opened, and every main that handed over hears and answers asks; registering twice is a no-op. */
22528
23023
  register() {
22529
23024
  if (channel) return;
22530
23025
  pi.events.emit(REGISTER, { namespace: CONTROL8, ownerEligible: false, onReady: (c) => channel = c, onEvent });
@@ -22540,7 +23035,9 @@ function createCloseMain({ pi, cfg, s: s2, me }, { closeSelf, check, turn }) {
22540
23035
  const main = found[0], name2 = main.name ?? main.id, pane = all.find((p) => p.pane_id === main.herdrLocation?.paneId);
22541
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`);
22542
23037
  if (pane.tokens?.sb_role !== "main" && pane.tokens?.sb_role !== TRAIN) throw new Error(`${name2} is not a main agent`);
22543
- 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`);
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`);
22544
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`);
22545
23042
  let got = await ask(main.id, interrupt);
22546
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);
@@ -22548,7 +23045,10 @@ function createCloseMain({ pi, cfg, s: s2, me }, { closeSelf, check, turn }) {
22548
23045
  if (!got.accepted) throw new Error(`${name2} will not close: ${got.reason ?? "refused"}`);
22549
23046
  const gone = await waitFor(sleep2, async () => !(await s2.c.listSessions().catch(() => [main])).some((x) => x.id === main.id), QUIT_MS, 500);
22550
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) };
22551
- })
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)
22552
23052
  };
22553
23053
  }
22554
23054
 
@@ -22594,62 +23094,113 @@ function createDigest(run3, now) {
22594
23094
  }
22595
23095
 
22596
23096
  // src/opener.ts
22597
- import { createHash as createHash20, randomUUID as randomUUID13 } from "node:crypto";
22598
- import { existsSync as existsSync9 } from "node:fs";
22599
- import { join as join53 } from "node:path";
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";
22600
23100
 
22601
- // src/integrator.ts
22602
- import { existsSync as existsSync8, readdirSync as readdirSync15 } from "node:fs";
22603
- import { join as join52 } from "node:path";
22604
- var INTEGRATOR = "integrator";
22605
- var MAX_OPENED_INTEGRATORS = 2;
22606
- var MARK2 = "integ:";
22607
- var integMark = (project) => `${MARK2}${project}`;
22608
- var integratorOf = (token) => {
22609
- const project = typeof token === "string" && token.startsWith(MARK2) ? token.slice(MARK2.length) : void 0;
22610
- return isName(project) ? project : void 0;
22611
- };
22612
- function ledgerProjects(stateDir, app) {
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
+
23107
+ // src/reviver.ts
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));
23109
+ var reviveLabel = (r) => r.train ? trainLabel(r.train.code) : r.name ? tabLabel(r.name) : void 0;
23110
+ async function reviveMain(env, { session, reason, origin }) {
23111
+ const { run: run3, sleep: sleep2 } = env;
23112
+ if (!env.stateDir) throw new ReviveRefused("this tower keeps no state folder, so it reads no role record");
23113
+ const why = reason.trim();
23114
+ if (!why || why.length > 300 || /[\r\n]/.test(why)) throw new ReviveRefused("reason is one line of 1 to 300 characters: why this session is revived");
23115
+ const workspace = (await workspaces(run3)).find((w) => w.workspace_id === env.workspaceId);
23116
+ if (!workspace) throw new Error(`Workspace ${env.workspaceId} is not open any more`);
23117
+ const dir = workspace.worktree?.checkout_path ?? env.cwd, root = env.sessionsRoot ?? sessionsDir();
23118
+ const look3 = async () => {
23119
+ const [everywhere, sessions] = await Promise.all([panes(run3), env.sessions()]);
23120
+ const rows = await gatherDead({ stateDir: env.stateDir, run: run3, now: Date.now(), sessions: async () => sessions, root, checkout: dir, recovering: env.recovering?.() ?? false, panes: everywhere, sessionList: sessions, allNotes: true });
23121
+ return { everywhere, sessions, rows };
23122
+ };
23123
+ const first2 = await look3();
23124
+ const row2 = pick2(first2.rows, session);
23125
+ if (row2.record.workspace !== workspace.workspace_id) throw new ReviveRefused(`it is a session of workspace ${row2.record.workspace}; that workspace's tower revives it`);
23126
+ if (row2.record.role === TRAIN && !row2.train) throw new ReviveRefused("its record names no train");
23127
+ if (!REVIVABLE.includes(row2.verdict.state)) throw new ReviveRefused(`it is ${row2.verdict.state}: ${row2.verdict.reason}`);
23128
+ const rivals = livePanes(first2.everywhere, first2.sessions, row2.record.pane);
23129
+ const refusal7 = roleRefusal(row2, { integrationOff: env.integrationOff?.() ?? false, live: rivals, sessions: first2.sessions });
23130
+ if (refusal7) throw new ReviveRefused(refusal7);
23131
+ const unlock = takeLock(env.stateDir, row2.file, Date.now());
22613
23132
  try {
22614
- return readdirSync15(join52(stateDir, "trains")).filter((project) => isName(project) && existsSync8(join52(stateDir, "trains", project, `${app}.json`)));
22615
- } catch {
22616
- return [];
22617
- }
22618
- }
22619
- var integratorHandoff = (workspace, project, tower) => [
22620
- `Straw Boss: the tower of workspace ${workspace} opened this tab for you: you are the integrator of project ${project}, the tower's own main, of kind integrator and named integ ${project}.`,
22621
- "Car slips reach you as the tower's forwards, the first right after this message; each names its sender (fwd-from). Report to the tower that opened this tab with call_tower as your prompt describes; when your queue is empty and no train waits to be opened, report idle (why: milestone, reply: false) and the tower closes this tab.",
22622
- `Tower: ${tower.name} (session id ${tower.id})`
22623
- ].join("\n");
22624
- function liveIntegrator(everywhere, sessions, project) {
22625
- const isIntegrator = (p) => p.tokens?.sb_role === "main" && p.tokens.sb_duty === INTEGRATOR, live = /* @__PURE__ */ new Map();
22626
- for (const pane of everywhere.filter((p) => integratorOf(p.tokens?.sb_opened_by) === project)) {
22627
- const session = sessions.find((s2) => s2.herdrLocation?.paneId === pane.pane_id);
22628
- if (!session || pane.tokens?.sb_role !== "main") return { refusal: `The integrator of project ${project} (pane ${pane.pane_id}) has not joined yet or no longer answers; a project has one, so nothing opens. Try again when it has joined, or when its tab has closed.` };
22629
- if (!isIntegrator(pane)) return { refusal: `The main opened as the integrator of project ${project} (${session.name ?? session.id}, session ${session.id}) is of kind ${pane.tokens.sb_duty ?? "none"} now; a project has one, so nothing opens and no slip goes to it. It calls boss_duty with integrator, or the boss closes it.` };
22630
- live.set(session.id, { session, pane });
22631
- }
22632
- for (const session of sessions) {
22633
- const pane = session.name === `integ ${project}` ? everywhere.find((p) => p.pane_id === session.herdrLocation?.paneId) : void 0;
22634
- if (pane && isIntegrator(pane) && !pane.tokens?.sb_opened_by?.startsWith("link:")) live.set(session.id, { session, pane });
23133
+ const now = Date.now(), ledger = readLedger2(env.stateDir, row2.file, row2.session), key2 = deathKey(row2.file) ?? "";
23134
+ const tried = ledger.attempts.find((a) => a.key === key2 && a.outcome !== "refused");
23135
+ if (tried) throw new ReviveRefused(`this death was already tried at ${new Date(tried.at).toISOString()} (${tried.outcome}${tried.error ? `: ${tried.error}` : ""}); a tower tries each death once, and the boss decides a retry`);
23136
+ const failed = failedIn(ledger, now).at(-1);
23137
+ if (failed) throw new ReviveRefused(`a revive of it failed at ${new Date(failed.at).toISOString()} (${failed.error ?? "no reason kept"}); a tower does not try it again for 24 h, and the boss decides a retry`);
23138
+ const recent = revivedIn(ledger, now);
23139
+ if (recent.length >= MAX_REVIVES) throw new ReviveRefused(`it was revived ${recent.length} times in the last 24 h (the limit is ${MAX_REVIVES}): it keeps dying, so the boss looks at it first`);
23140
+ const train = row2.train;
23141
+ if (train) {
23142
+ const read4 = readTrainboards(env.stateDir, { project: train.project }).trains.find((b) => b.code === train.code);
23143
+ if (!read4?.ok) throw new ReviveRefused(`the trainboard of ${trainLabel(train.code)} of project ${train.project} cannot be read${read4 && !read4.ok ? `: ${read4.reason}` : ""}`);
23144
+ if (read4.end || boardState(read4.board, { now, alive: false, ...read4.end ? { end: read4.end } : {} }) === "ended") throw new ReviveRefused(`${trainLabel(train.code)} of project ${train.project} has ended (its board says so); a new train takes a new code`);
23145
+ if (read4.board.writer.session !== row2.session) throw new ReviveRefused(`the trainboard of ${trainLabel(train.code)} was written by session ${read4.board.writer.session.slice(0, 8)}, not this one`);
23146
+ if (alive(read4.board.writer.pid)) throw new ReviveRefused(`the writer of ${trainLabel(train.code)}'s board (pid ${read4.board.writer.pid}) is still running`);
23147
+ if (rivals.some((p) => trainFromToken(p.tokens?.sb_train)?.code === train.code && trainFromToken(p.tokens?.sb_train)?.project === train.project)) throw new ReviveRefused(`a live pane carries ${trainLabel(train.code)} of project ${train.project}`);
23148
+ if (env.integrationOff?.()) throw new ReviveRefused("a train is not revived: integration is off on this computer");
23149
+ }
23150
+ const here = rivals.filter((p) => p.workspace_id === workspace.workspace_id);
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));
23152
+ if (!train && row2.openedBy && !integratorOf(row2.openedBy)) {
23153
+ const ofSender = marked2.filter((p) => p.tokens.sb_opened_by === row2.openedBy).length;
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`);
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})`);
23156
+ }
23157
+ const cwd = sessionHeader(row2.file)?.cwd ?? dir;
23158
+ await assertSettingsSafe([cwd]);
23159
+ const again = (await look3()).rows.find((r) => r.file === row2.file);
23160
+ if (!again || !REVIVABLE.includes(again.verdict.state)) throw new ReviveRefused(`it is ${again?.verdict.state ?? "gone"} now${again ? `: ${again.verdict.reason}` : ""}`);
23161
+ const { tabId, paneId } = await createTab(run3, workspace.workspace_id, cwd, [`STRAW_BOSS_ROLE=${train ? TRAIN : "main"}`], reviveLabel(row2));
23162
+ const attempt = (outcome, more = {}) => updateLedger(env.stateDir, row2.file, Date.now(), (l) => void l.attempts.push({ at: Date.now(), key: key2, by: env.tower().id, outcome, reason: why, ...more }));
23163
+ try {
23164
+ await report(run3, "pane", paneId, { sb_open_main: "1", [REVIVE_TOKEN]: keyOf4(row2.file), ...row2.openedBy ? { sb_opened_by: row2.openedBy } : {}, ...train ? { sb_train: trainToken(train) } : {}, ...!train && row2.record.duty && !sessionNotes(row2.file).duty ? { sb_open_duty: row2.record.duty } : {} });
23165
+ await startPi(run3, sleep2, `revive-${randomUUID13().slice(0, 8)}`, paneId, ["--session", row2.file]);
23166
+ const wanted = train ? TRAIN : "main";
23167
+ const main = await waitPastTrust(sleep2, async () => {
23168
+ const tokens = (await panes(run3, workspace.workspace_id)).find((p) => p.pane_id === paneId)?.tokens;
23169
+ if (tokens?.sb_role !== wanted) return void 0;
23170
+ const mine = (await env.sessions()).find((s2) => s2.herdrLocation?.paneId === paneId);
23171
+ if (mine && mine.id !== row2.session) throw new Error(`the pi in pane ${paneId} joined as session ${mine.id.slice(0, 8)}, not ${row2.session.slice(0, 8)}: it is no revive of that session`);
23172
+ return mine;
23173
+ }, MAIN_WAIT_MS, 500, env.trustDir ? { dir: env.trustDir, pane: paneId } : void 0);
23174
+ if (!main) throw new Error(`The pi in pane ${paneId} did not come back as the ${wanted} of session ${row2.session.slice(0, 8)} within ${MAIN_WAIT_MS / 1e3} s`);
23175
+ const twins = (await panes(run3)).filter((p) => p.pane_id !== paneId && p.agent_session?.value === row2.file);
23176
+ if (twins.length) throw new ReviveRefused(`another pane (${twins.map((p) => p.pane_id).join(", ")}) runs this session file now; the revived pi was closed, and that one keeps it`);
23177
+ const missed = readLedger2(env.stateDir, row2.file, row2.session).missed;
23178
+ const sent = await env.send(main.id, reviveHandoff({ row: row2, tower: env.tower(), tab: tabId, workspace: workspace.label, reason: why, waits: env.waitsOf?.(row2.session) ?? [], missed, now: Date.now(), ...origin ? { origin } : {} }));
23179
+ if (sent.status !== "sent") throw new Error(`The revived ${wanted} ${main.name ?? main.id} did not take the handoff: ${sent.status} ${sent.code ?? ""} ${sent.detail ?? ""}`.trim());
23180
+ updateLedger(env.stateDir, row2.file, Date.now(), (l) => void (l.missed = []));
23181
+ attempt("revived", { tab: tabId, pane: paneId });
23182
+ const closedOld = await closeOldTab(env, row2, paneId).catch(() => void 0);
23183
+ return { tab: tabId, pane: paneId, main: main.id, file: row2.file, ...row2.name ? { name: row2.name } : {}, ...row2.kind ? { kind: row2.kind } : {}, ...train ? { train } : {}, ...row2.openedBy ? { openedBy: row2.openedBy } : {}, ...closedOld ? { closedOld } : {} };
23184
+ } catch (error) {
23185
+ await run3(["tab", "close", tabId]).catch(() => {
23186
+ });
23187
+ if (!(error instanceof ReviveRefused)) attempt("failed", { error: error.message.slice(0, 300) });
23188
+ throw error;
23189
+ }
23190
+ } finally {
23191
+ unlock();
22635
23192
  }
22636
- if (live.size > 1) return { refusal: `Project ${project} has ${live.size} integrators (${[...live.keys()].map((id) => `session ${id}`).join(", ")}); a project has one, so the slip goes to neither. The boss closes one.` };
22637
- return [...live.values()][0];
22638
23193
  }
22639
- function keptIntegrators(everywhere, sessions, mine) {
22640
- return sessions.flatMap((session) => {
22641
- const pane = everywhere.find((p) => p.pane_id === session.herdrLocation?.paneId), by = pane?.tokens?.sb_opened_by;
22642
- return pane && pane.tokens?.sb_role === "main" && pane.tokens.sb_duty === INTEGRATOR && !by?.startsWith("link:") && !by?.startsWith(MARK2) && mine(pane) ? [{ session, pane }] : [];
22643
- });
23194
+ async function closeOldTab(env, row2, newPane) {
23195
+ if (!row2.openedBy || row2.record.tab === void 0) return void 0;
23196
+ const inTab = (await panes(env.run, row2.record.workspace)).filter((p) => p.tab_id === row2.record.tab);
23197
+ if (inTab.length !== 1 || inTab[0].pane_id !== row2.record.pane || inTab[0].pane_id === newPane) return void 0;
23198
+ const info = JSON.parse(await env.run(["pane", "process-info", "--pane", row2.record.pane])).result?.process_info;
23199
+ const fg = info?.foreground_processes ?? [];
23200
+ if (!(fg.length === 1 && typeof info?.shell_pid === "number" && fg[0].pid === info.shell_pid)) return void 0;
23201
+ await env.run(["tab", "close", row2.record.tab]);
23202
+ return row2.record.tab;
22644
23203
  }
22645
- var ForwardAsBefore = class extends Error {
22646
- mains;
22647
- constructor(project, apps, mains) {
22648
- const one4 = mains.length === 1;
22649
- super(`Project ${project} already runs ${one4 ? "an integrator" : `${mains.length} integrators`} of its own, opened before this door and not by it: ${mains.map((m) => `${m.name} (session ${m.id})`).join(", ")}. Nothing opens beside ${one4 ? "it" : "them"} and the door picks none: the slip of app${apps.length === 1 ? "" : "s"} ${apps.join(", ")} goes to the one that runs ${apps.length === 1 ? "that app's" : "those apps'"} trains, forwarded as before.`);
22650
- this.mains = mains;
22651
- }
22652
- };
22653
23204
 
22654
23205
  // src/opener.ts
22655
23206
  var MAIN_WAIT_MS = 6e4;
@@ -22701,7 +23252,7 @@ function opener(env) {
22701
23252
  turn.end?.();
22702
23253
  }
22703
23254
  };
22704
- const openHeld = async ({ request, sender: asked3, label: asked_label, peer, role, project, within: within2, dry, duty }, turn) => {
23255
+ const openHeld = async ({ request, sender: asked3, label: asked_label, peer, role, project, within: within3, dry, duty }, turn) => {
22705
23256
  const { run: run3, sleep: sleep2 } = env;
22706
23257
  if (role !== void 0 && role !== TRAIN && role !== INTEGRATOR) throw new OpenLimitError(`role must be "train" or "integrator" when given, not ${JSON.stringify(role).slice(0, 40)}`);
22707
23258
  if (duty !== void 0 && !isCoordinatorDuty(duty)) throw new OpenLimitError(`duty must be "coordinator" or "standing" when given, not ${JSON.stringify(duty).slice(0, 40)}`);
@@ -22744,7 +23295,7 @@ function opener(env) {
22744
23295
  const own = checkoutProject(dir);
22745
23296
  if (!own.ok) throw new OpenLimitError(own.refusal);
22746
23297
  if (project !== void 0 && project !== own.project) throw new OpenLimitError(`The project of this workspace's checkout is ${own.project} (${own.from}), not ${JSON.stringify(project).slice(0, 80)}: the slip of its app${apps.length === 1 ? "" : "s"} ${apps.join(", ")} goes to integ ${own.project} and to no other project's integrator.`);
22747
- if (within2 !== void 0 && !inside(dir, within2)) throw new OpenLimitError("An ally run's slip goes to the integrator of the project its team binds on this computer, and this workspace's checkout is outside that project: nothing opens and nothing is forwarded.");
23298
+ if (within3 !== void 0 && !inside(dir, within3)) throw new OpenLimitError("An ally run's slip goes to the integrator of the project its team binds on this computer, and this workspace's checkout is outside that project: nothing opens and nothing is forwarded.");
22748
23299
  integ = own.project, label = `integ ${integ}`, found = { from: own.from, file: own.file, apps };
22749
23300
  turn.end = await projectTurn(integ);
22750
23301
  }
@@ -22753,7 +23304,7 @@ function opener(env) {
22753
23304
  const everywhere = await panes(run3);
22754
23305
  const codes = new Set(everywhere.flatMap((p) => ((t) => t && t.project === train.project ? [t.code] : [])(trainFromToken(p.tokens?.sb_train))));
22755
23306
  if (codes.has(train.code)) throw new OpenLimitError(`The ${trainLabel(train.code)} of project ${train.project} is already open; a code is used once`);
22756
- if (env.stateDir && existsSync9(join53(trainboardDir(env.stateDir), train.project, train.code))) throw new OpenLimitError(`The ${trainLabel(train.code)} of project ${train.project} was already used (its trainboard is kept); a code is used once, so the next train takes a new code`);
23307
+ if (env.stateDir && existsSync10(join55(trainboardDir(env.stateDir), train.project, train.code))) throw new OpenLimitError(`The ${trainLabel(train.code)} of project ${train.project} was already used (its trainboard is kept); a code is used once, so the next train takes a new code`);
22757
23308
  const max = (env.maxTrains ?? readMaxTrains)(dir);
22758
23309
  if (typeof max !== "number") throw new OpenLimitError(max.refusal);
22759
23310
  const config = (env.appsRefusal ?? openRefusal)(dir, appFromRequest(request));
@@ -22784,15 +23335,15 @@ function opener(env) {
22784
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.`);
22785
23336
  if (dry) return { tab: "", pane: "", main: "", sender: sender.id, integrator: integ, repeated: true };
22786
23337
  }
22787
- 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));
22788
- 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;
22789
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.`);
22790
- 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.`);
22791
23342
  await assertSettingsSafe([dir]);
22792
23343
  const { tabId, paneId } = await createTab(run3, workspace.workspace_id, dir, [`STRAW_BOSS_ROLE=${train ? TRAIN : "main"}`], label);
22793
23344
  try {
22794
23345
  await report(run3, "pane", paneId, { sb_opened_by: integ ? integMark(integ) : sender.id, sb_open_main: "1", ...train ? { sb_train: trainToken(train) } : {}, ...openDuty ? { sb_open_duty: openDuty } : {} });
22795
- await startPi(run3, sleep2, `${train ? TRAIN : integ ? "integ" : "main"}-${randomUUID13().slice(0, 8)}`, paneId, ["--name", train || integ ? label : `main \xB7 ${label ?? workspace.label}`]);
23346
+ await startPi(run3, sleep2, `${train ? TRAIN : integ ? "integ" : "main"}-${randomUUID14().slice(0, 8)}`, paneId, ["--name", train || integ ? label : `main \xB7 ${label ?? workspace.label}`]);
22796
23347
  const wanted = train ? TRAIN : "main";
22797
23348
  const main = await waitPastTrust(sleep2, async () => {
22798
23349
  const tokens = (await panes(run3, workspace.workspace_id)).find((p) => p.pane_id === paneId)?.tokens;
@@ -22809,14 +23360,20 @@ function opener(env) {
22809
23360
  }
22810
23361
  };
22811
23362
  let queue = Promise.resolve();
22812
- return (input) => {
23363
+ const revive = (input) => {
23364
+ const pending = queue.then(() => reviveMain(env, input), () => reviveMain(env, input));
23365
+ queue = pending.catch(() => {
23366
+ });
23367
+ return pending;
23368
+ };
23369
+ const openOne = (input) => {
22813
23370
  if (input.role === INTEGRATOR) {
22814
23371
  const pending2 = queue.then(() => open8(input), () => open8(input));
22815
23372
  queue = pending2.catch(() => {
22816
23373
  });
22817
23374
  return pending2;
22818
23375
  }
22819
- const key2 = createHash20("sha256").update(JSON.stringify(input.role === TRAIN ? [input.sender, input.request, TRAIN] : [input.sender, input.request])).digest("hex");
23376
+ const key2 = createHash22("sha256").update(JSON.stringify(input.role === TRAIN ? [input.sender, input.request, TRAIN] : [input.sender, input.request])).digest("hex");
22820
23377
  const prior = seen.get(key2);
22821
23378
  if (prior) return prior.then((opened) => ({ ...opened, repeated: true }), (error) => Promise.reject(new Error(`A main was already tried for this request and is not opened again: ${error.message}`)));
22822
23379
  const pending = queue.then(() => open8(input), () => open8(input));
@@ -22831,10 +23388,11 @@ function opener(env) {
22831
23388
  });
22832
23389
  return pending;
22833
23390
  };
23391
+ return Object.assign(openOne, { revive });
22834
23392
  }
22835
23393
 
22836
23394
  // src/order.ts
22837
- import { createHash as createHash21 } from "node:crypto";
23395
+ import { createHash as createHash23 } from "node:crypto";
22838
23396
  var INDENT = { more: "\u251C\u2500", last: "\u2514\u2500" };
22839
23397
  var MAX_KIDS = 999;
22840
23398
  var NAME_MAX = 24;
@@ -22844,7 +23402,7 @@ function orderKey(role, pane, ps, all, tabList, who2 = {}) {
22844
23402
  const index2 = all.filter((w) => !isSub(w) && !isHead(w)).findIndex((w) => w.workspace_id === pane.workspace_id), base = index2 + (all.some(isHead) ? 1 : 0);
22845
23403
  if (index2 < 0) return void 0;
22846
23404
  if (role === "tower") return `${part2(base)}.0`;
22847
- if (role === "train") return who2.code !== void 0 && isCode(who2.code) && isName(who2.project) ? `${part2(base)}.06.${who2.code.slice(2, 4)}${who2.code.slice(5, 7)}${who2.code.slice(8, 10)}${shortCode(who2.code).slice(4).padStart(2, "0")}.${createHash21("sha256").update(who2.project).digest("hex").slice(0, 8)}` : void 0;
23405
+ if (role === "train") return who2.code !== void 0 && isCode(who2.code) && isName(who2.project) ? `${part2(base)}.06.${who2.code.slice(2, 4)}${who2.code.slice(5, 7)}${who2.code.slice(8, 10)}${shortCode(who2.code).slice(4).padStart(2, "0")}.${createHash23("sha256").update(who2.project).digest("hex").slice(0, 8)}` : void 0;
22848
23406
  const tab = tabList.findIndex((t) => t.tab_id === pane.tab_id), slot = ps.filter((p) => p.tab_id === pane.tab_id).findIndex((p) => p.pane_id === pane.pane_id);
22849
23407
  if (tab < 0 || slot < 0) return void 0;
22850
23408
  return who2.integrator ? `${part2(base)}.05.${part2(tab)}.${role === "main" ? 0 : 1}.${part2(slot)}` : `${part2(base)}.1.${part2(tab)}.${role === "main" ? 0 : 1}.${part2(slot)}`;
@@ -22887,9 +23445,9 @@ var clearOrder = (run3, paneIds) => Promise.all(paneIds.map((id) => report(run3,
22887
23445
  })));
22888
23446
 
22889
23447
  // src/server/head.ts
22890
- import { chmodSync as chmodSync7, mkdirSync as mkdirSync15 } from "node:fs";
22891
- import { homedir as homedir14 } from "node:os";
22892
- import { join as join54 } from "node:path";
23448
+ import { chmodSync as chmodSync7, mkdirSync as mkdirSync17 } from "node:fs";
23449
+ import { homedir as homedir15 } from "node:os";
23450
+ import { join as join56 } from "node:path";
22893
23451
  var HEAD_REFUSAL = "The head tower takes only the boss's words and answers to its own asks.";
22894
23452
  var HEAD_TOKEN = "sb_head";
22895
23453
  var HEAD_ORDER = "000.0";
@@ -22898,10 +23456,10 @@ function refuseHead(client, from, message, log, now) {
22898
23456
  client.sendMessageReceipt?.({ messageId: message.id, status: "expired", timestamp: now(), detail: HEAD_REFUSAL });
22899
23457
  }
22900
23458
  var headLabel = (env, stateDir) => localeOf(env, stateDir) === "zh-TW" ? "\u4E3B\u5854\u53F0" : "Head tower";
22901
- var headFolder = (env) => join54(env.PI_CODING_AGENT_DIR || join54(homedir14(), ".pi", "agent"), "straw-boss-head");
23459
+ var headFolder = (env) => join56(env.PI_CODING_AGENT_DIR || join56(homedir15(), ".pi", "agent"), "straw-boss-head");
22902
23460
  async function makeHead(d) {
22903
23461
  const cwd = headFolder(d.env), label = headLabel(d.env, d.slot?.stateDir);
22904
- mkdirSync15(cwd, { recursive: true, mode: 448 });
23462
+ mkdirSync17(cwd, { recursive: true, mode: 448 });
22905
23463
  chmodSync7(cwd, 448);
22906
23464
  const made = await result(d.run, ["workspace", "create", "--cwd", cwd, "--label", label, "--no-focus"]);
22907
23465
  const workspace = made.workspace.workspace_id, tab = made.tab.tab_id, pane = made.root_pane.pane_id;
@@ -22956,7 +23514,7 @@ function createHead(d) {
22956
23514
  }
22957
23515
 
22958
23516
  // src/server/headside.ts
22959
- import { join as join55 } from "node:path";
23517
+ import { join as join57 } from "node:path";
22960
23518
 
22961
23519
  // src/server/headbrief.ts
22962
23520
  var CAPS2 = { workspaces: 2400, asks: 1200, row: 200, note: 1200, recap: 2e3 };
@@ -23084,7 +23642,7 @@ async function headBrief(d, input) {
23084
23642
  const ws = d.record().workspace, all = await workspaces(d.run), at = new Date(input.woken);
23085
23643
  const rows = [];
23086
23644
  for (const w of all.filter((x) => !isSub(x) && !isHead(x)).slice(0, 20)) {
23087
- const { rows: mains } = await gatherMains({ run: d.run, now: d.now, sessions: d.sessions, boardDir: join55(d.slot.stateDir, "board"), workspace: w, ledger: [] }).catch(() => ({ rows: [] }));
23645
+ const { rows: mains } = await gatherMains({ run: d.run, now: d.now, sessions: d.sessions, boardDir: join57(d.slot.stateDir, "board"), workspace: w, ledger: [] }).catch(() => ({ rows: [] }));
23088
23646
  rows.push({ label: phrase5(w.label, 60), id: w.workspace_id, ...w.worktree?.checkout_path ? { folder: w.worktree.checkout_path } : {}, tower: d.towerState(w.workspace_id, w.tokens), rows: mains });
23089
23647
  }
23090
23648
  const kept = readMemory(d.slot, ws, d.now()), section = memorySection(kept.memory, d.now(), kept.problem), note = lastNote(d.slot, ws, "local");
@@ -23221,8 +23779,8 @@ function reportText(r) {
23221
23779
 
23222
23780
  // src/server/automode.ts
23223
23781
  import { randomBytes as randomBytes22 } from "node:crypto";
23224
- import { mkdirSync as mkdirSync16, readFileSync as readFileSync39, renameSync as renameSync8, writeFileSync as writeFileSync8 } from "node:fs";
23225
- import { join as join56 } from "node:path";
23782
+ import { mkdirSync as mkdirSync18, readFileSync as readFileSync41, renameSync as renameSync10, writeFileSync as writeFileSync10 } from "node:fs";
23783
+ import { join as join58 } from "node:path";
23226
23784
  var PENDING_MS2 = 10 * 6e4;
23227
23785
  var USED_MAX = 500;
23228
23786
  var STALE = "This request expired or was replaced: ask again";
@@ -23238,7 +23796,7 @@ var gistOf = (v) => {
23238
23796
  };
23239
23797
  function readReportFile(dir) {
23240
23798
  try {
23241
- const j = JSON.parse(readFileSync39(join56(dir, REPORT_FILE), "utf8"));
23799
+ const j = JSON.parse(readFileSync41(join58(dir, REPORT_FILE), "utf8"));
23242
23800
  return j.v === 1 && typeof j.since === "string" && Array.isArray(j.parked) && Array.isArray(j.lines) ? j : void 0;
23243
23801
  } catch {
23244
23802
  return void 0;
@@ -23253,7 +23811,7 @@ function createAutoMode(d) {
23253
23811
  const listeners = /* @__PURE__ */ new Set();
23254
23812
  const readPeriod = () => {
23255
23813
  try {
23256
- const j = JSON.parse(readFileSync39(join56(d.dir, PERIOD_FILE), "utf8"));
23814
+ const j = JSON.parse(readFileSync41(join58(d.dir, PERIOD_FILE), "utf8"));
23257
23815
  return typeof j.since === "string" && Array.isArray(j.notes) ? { since: j.since, notes: j.notes.slice(-NOTES_MAX), foreign: Array.isArray(j.foreign) ? j.foreign : [], decided: Array.isArray(j.decided) ? j.decided : [], .../* @__PURE__ */ ((w) => w ? { watch: w } : {})(watchOf(j.watch)) } : void 0;
23258
23816
  } catch {
23259
23817
  return void 0;
@@ -23264,11 +23822,11 @@ function createAutoMode(d) {
23264
23822
  if (period) write2(PERIOD_FILE, period);
23265
23823
  };
23266
23824
  const write2 = (name2, value) => {
23267
- const file3 = join56(d.dir, name2), tmp = `${file3}.${process.pid}.tmp`;
23268
- mkdirSync16(d.dir, { recursive: true });
23269
- writeFileSync8(tmp, `${JSON.stringify(value)}
23825
+ const file3 = join58(d.dir, name2), tmp = `${file3}.${process.pid}.tmp`;
23826
+ mkdirSync18(d.dir, { recursive: true });
23827
+ writeFileSync10(tmp, `${JSON.stringify(value)}
23270
23828
  `, { mode: 384 });
23271
- renameSync8(tmp, file3);
23829
+ renameSync10(tmp, file3);
23272
23830
  };
23273
23831
  const commit = (next2, publish) => {
23274
23832
  own = next2;
@@ -23673,18 +24231,18 @@ async function tell(reach, to, text11, wait2, ms3) {
23673
24231
  }
23674
24232
  }
23675
24233
  function returnAll(d) {
23676
- const at = d.now(), until = iso(at), toHead = /* @__PURE__ */ new Set(), keyOf3 = (target2, id) => `${target2.workspace}:${id}`;
24234
+ const at = d.now(), until = iso(at), toHead = /* @__PURE__ */ new Set(), keyOf5 = (target2, id) => `${target2.workspace}:${id}`;
23677
24235
  const back = returnParked(d.slot, at, d.targets, (target2, entry) => {
23678
24236
  const from = entry.card?.from, what = entry.card?.do ?? entry.text, head = from && !from.gone ? d.head?.(from.id) : void 0;
23679
- if (head) return d.notice(head, returnedText(entry.id, what, until, "tower"), `wait-returned:${keyOf3(target2, entry.id)}:${until}`) ? (toHead.add(keyOf3(target2, entry.id)), "raiser") : "gone";
24237
+ if (head) return d.notice(head, returnedText(entry.id, what, until, "tower"), `wait-returned:${keyOf5(target2, entry.id)}:${until}`) ? (toHead.add(keyOf5(target2, entry.id)), "raiser") : "gone";
23680
24238
  if (from) return from.gone || !d.reach(target2.workspace) ? "gone" : "raiser";
23681
24239
  return d.notice(target2.workspace, ownReturnedText(entry.id, what, until), `wait-returned:${entry.id}:${until}`) ? "tower" : "gone";
23682
24240
  });
23683
24241
  const rows = backRows(back);
23684
24242
  const settled = Promise.all(back.map(async (b, i) => {
23685
24243
  const row2 = rows[i], from = b.entry.card?.from, reach = d.reach(b.target.workspace);
23686
- if (toHead.has(keyOf3(b.target, b.entry.id))) d.log.line("wait-returned", { workspace: b.target.workspace, id: b.entry.id, delivery: "head" });
23687
- if (b.to !== "raiser" || !from || toHead.has(keyOf3(b.target, b.entry.id))) return row2;
24244
+ if (toHead.has(keyOf5(b.target, b.entry.id))) d.log.line("wait-returned", { workspace: b.target.workspace, id: b.entry.id, delivery: "head" });
24245
+ if (b.to !== "raiser" || !from || toHead.has(keyOf5(b.target, b.entry.id))) return row2;
23688
24246
  const status = reach ? await tell(reach, from.id, returnedText(b.entry.id, b.entry.card?.do ?? b.entry.text, until, from.role), b.entry.id, d.waitMs ?? NOTICE_WAIT_MS) : "gone";
23689
24247
  d.log.line("wait-returned", { workspace: b.target.workspace, id: b.entry.id, delivery: status });
23690
24248
  if (status === "delivered" || status === "queued") return row2;
@@ -23828,7 +24386,7 @@ async function refuseClose(host, query) {
23828
24386
  return named[0].id;
23829
24387
  }
23830
24388
  var ALLY = /* @__PURE__ */ new Set(["boss_status", "tower_list", "board_read", "tower_send", "tower_reply", "boss_open_main", "boss_close_main", "ally_escalate"]);
23831
- var TOOLS = ["boss_status", "tower_list", "board_read", "call_tower", "tower_send", "tower_reply", "boss_open_main", "boss_close_main", "boss_server", "link_request", "tower_memory", "ally_escalate"];
24389
+ var TOOLS = ["boss_status", "tower_list", "board_read", "call_tower", "tower_send", "tower_reply", "boss_open_main", "boss_close_main", "boss_revive_main", "boss_server", "link_request", "tower_memory", "ally_escalate"];
23832
24390
  var FREE = /* @__PURE__ */ new Set(["boss_status", "tower_list", "board_read", "ally_escalate"]);
23833
24391
  var str10 = (args, name2, max = 1e5) => {
23834
24392
  const v = args[name2];
@@ -23891,6 +24449,7 @@ async function allyTool(host, name2, args, extra) {
23891
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");
23892
24450
  await refuseTarget(host, to);
23893
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");
23894
24453
  if (name2 === "boss_close_main") refuseStanding(await host.reach.read(), await refuseClose(host, str10(args, "main", 300)));
23895
24454
  if (gated && name2 !== "tower_send") {
23896
24455
  if (!extra.toolCallId) throw new Error(`${name2} needs the boss's confirm in this run, and the call carried no tool call id`);
@@ -24101,6 +24660,8 @@ async function localTool(host, name2, args, extra, ally = false) {
24101
24660
  if (ally) await refuseTarget(host, to);
24102
24661
  const net = await reach.read();
24103
24662
  const named = net.sessions.filter((s2) => s2.id === to || s2.name === to);
24663
+ const kept = named.length === 0 && !ally ? await host.missed?.(to, message) : void 0;
24664
+ if (kept) throw new Error(kept);
24104
24665
  if (named.length !== 1) throw new Error(`${named.length ? "Several sessions are named" : "No live session is named or has the id"} "${to}"`);
24105
24666
  const target2 = named[0], shown3 = clean(target2.name ?? target2.id, 40);
24106
24667
  if (!ally && target2.id === headIdOf(net.all)) throw new Error('Not delivered: the head tower takes no tower_reply. Answer it with tower_send {head: true, inReplyTo: "H<n>", message} (H<n> is the ask id in the header of its message).');
@@ -24117,12 +24678,26 @@ async function localTool(host, name2, args, extra, ally = false) {
24117
24678
  const sender = str10(args, "sender", 300), peer = ally ? peerSender(host.who, sender) : void 0;
24118
24679
  const opened = await host.open({ request: str10(args, "request"), sender: peer?.id ?? sender, ...peer ? { peer } : {}, ...opt2(args, "label") ? { label: opt2(args, "label") } : {}, ...opt2(args, "role") ? { role: opt2(args, "role") } : {}, ...opt2(args, "duty") ? { duty: opt2(args, "duty") } : {} });
24119
24680
  if (opened.train) return { text: opened.repeated ? `A train was already opened for this request (tab ${opened.tab}); nothing new opened.` : `Opened tab ${opened.tab} with ${trainLabel(opened.train.code)} (session ${opened.main}) and handed it the manifest. It reports to you; close it with boss_close_main after its milestone report.`, details: opened };
24120
- const text11 = opened.repeated ? `A main was already opened for this request (tab ${opened.tab}); nothing new opened.` : opt2(args, "duty") === "standing" ? `Opened tab ${opened.tab} with a standing main (session ${opened.main}) and handed it the request. It tells ${peer ? "the tower" : sender} once and sends no done report; do not close it, only the boss does.` : `Opened tab ${opened.tab} with a main agent (session ${opened.main}) and handed it the request. ${peer ? `It reports to the tower only; each report wakes a run for ${peer.label} that sends it to the sender.` : `It reports to ${opened.sender} and to you.`}`;
24681
+ const died = !ally && !opened.repeated && host.dead ? (await host.dead().catch(() => [])).filter((r) => r.openedBy === opened.sender && r.verdict.state === "dead") : [];
24682
+ const hint = died.map((r) => ` Note: ${clean(sender, 40)}'s main ${clean(r.name ?? r.session.slice(0, 8), 40)} (session ${r.session.slice(0, 8)}) died ${r.ageMs === void 0 ? "earlier" : `${Math.round(r.ageMs / 6e4)} min ago`}; boss_revive_main revives it, once this main is closed (a sender gets one at a time).`).join("");
24683
+ const text11 = (opened.repeated ? `A main was already opened for this request (tab ${opened.tab}); nothing new opened.` : opt2(args, "duty") === "standing" ? `Opened tab ${opened.tab} with a standing main (session ${opened.main}) and handed it the request. It tells ${peer ? "the tower" : sender} once and sends no done report; do not close it, only the boss does.` : `Opened tab ${opened.tab} with a main agent (session ${opened.main}) and handed it the request. ${peer ? `It reports to the tower only; each report wakes a run for ${peer.label} that sends it to the sender.` : `It reports to ${opened.sender} and to you.`}`) + hint;
24121
24684
  return { text: text11, details: opened };
24122
24685
  }
24686
+ case "boss_revive_main":
24687
+ return reviveTool(host, args);
24123
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
+ }
24124
24699
  const main = str10(args, "main", 300), target2 = ally ? await refuseClose(host, main) : main;
24125
- refuseStanding(await host.reach.read(), target2);
24700
+ refuseStanding(await host.reach.read(), target2, ally ? void 0 : host.stateDir);
24126
24701
  const closed = await host.closeMain(target2);
24127
24702
  return { text: closed.text, details: closed };
24128
24703
  }
@@ -24145,6 +24720,24 @@ async function localTool(host, name2, args, extra, ally = false) {
24145
24720
  }
24146
24721
  }
24147
24722
  }
24723
+ async function reviveTool(host, args) {
24724
+ if (!host.dead || !host.revive) throw new Error("This tower revives no mains (the head tower opens none)");
24725
+ const action = args.action ?? "list";
24726
+ if (action === "list") {
24727
+ const rows = await host.dead(), now = host.now();
24728
+ const shown3 = rows.filter((r) => r.verdict.state !== "closed");
24729
+ return { text: shown3.length ? ["The mains and trains of this workspace with a role record:", ...shown3.map((r) => `- ${rowLine(r, now)}`), "Revive a dead one with action revive; a quit one only when a request names it."].join("\n") : "No main or train of this workspace has a role record.", details: shown3.map((r) => ({ session: r.session, name: r.name ?? null, role: r.record.role, kind: r.kind ?? null, state: r.verdict.state, reason: r.verdict.reason, tab: r.record.tab, openedBy: r.openedBy ?? null, ...r.train ? { train: r.train } : {}, ...r.orphans ? { orphans: r.orphans } : {} })) };
24730
+ }
24731
+ if (action !== "revive") throw new Error("action is list or revive");
24732
+ const session = str10(args, "session", 200), reason = str10(args, "reason", 300);
24733
+ try {
24734
+ const done2 = await host.revive({ session, reason });
24735
+ return { text: revivedText(done2), details: done2 };
24736
+ } catch (error) {
24737
+ if (error instanceof ReviveRefused) throw new Error(`Not revived: ${error.message}`);
24738
+ throw error;
24739
+ }
24740
+ }
24148
24741
  async function answerHead(host, args) {
24149
24742
  const id = opt2(args, "inReplyTo"), message = str10(args, "message", 12e3);
24150
24743
  if (!id || !/^H\d{1,6}$/.test(id)) throw new Error("head needs inReplyTo, the ask id (H12) of the head tower's message you answer");
@@ -24378,10 +24971,64 @@ function createRevoker(d) {
24378
24971
  };
24379
24972
  }
24380
24973
 
24974
+ // src/server/deadwatch.ts
24975
+ import { join as join59 } from "node:path";
24976
+ function createDeadWatch(d) {
24977
+ const seen = /* @__PURE__ */ new Map();
24978
+ const last = /* @__PURE__ */ new Map();
24979
+ let busy = false;
24980
+ async function sweep3() {
24981
+ if (busy) return;
24982
+ busy = true;
24983
+ try {
24984
+ const served = await d.workspaces();
24985
+ const rows = /* @__PURE__ */ new Map();
24986
+ const sessions = await d.sessions();
24987
+ for (const { workspace, checkout } of served) {
24988
+ const found = await gatherDead({ stateDir: d.stateDir, run: d.run, now: d.now(), sessions: async () => sessions, sessionList: sessions, root: d.root, workspace, ...checkout ? { checkout } : {}, recovering: d.recovering(), seen: (file3) => seen.get(file3) ?? { first: d.now(), looks: 0 } });
24989
+ rows.set(workspace, found);
24990
+ }
24991
+ const now = d.now(), dying = /* @__PURE__ */ new Set();
24992
+ for (const [workspace, found] of rows) {
24993
+ last.set(workspace, found.filter((r) => r.verdict.state !== "closed" && r.verdict.state !== "live" && r.verdict.state !== "handed"));
24994
+ for (const r of found) {
24995
+ if (r.verdict.state === "restoring" && !d.recovering()) {
24996
+ const was = seen.get(r.file);
24997
+ seen.set(r.file, was ? { first: was.first, looks: was.looks + 1 } : { first: now, looks: 1 });
24998
+ dying.add(r.file);
24999
+ continue;
25000
+ }
25001
+ if (r.verdict.state !== "dead") continue;
25002
+ dying.add(r.file);
25003
+ if (!r.key) continue;
25004
+ const ledger = readLedger2(d.stateDir, r.file, r.session);
25005
+ if (ledger.detections.some((x) => x.key === r.key)) continue;
25006
+ const revived = ledger.attempts.filter((a) => a.outcome === "revived").at(-1);
25007
+ const loop = revived !== void 0 && r.ageMs !== void 0 && now - r.ageMs - revived.at < LOOP_MS;
25008
+ const failed = failedIn(ledger, now).length > 0;
25009
+ updateLedger(d.stateDir, r.file, now, (l) => void l.detections.push({ key: r.key, at: now }));
25010
+ if (loop || failed) {
25011
+ d.log(failed ? "main-died-failed" : "main-died-loop", { workspace, session: r.session });
25012
+ continue;
25013
+ }
25014
+ const queued = d.notice(workspace, diedText(r, now), `main_died:${r.key}`);
25015
+ d.log("main-died", { workspace, session: r.session, queued });
25016
+ }
25017
+ }
25018
+ for (const file3 of [...seen.keys()]) if (!dying.has(file3)) seen.delete(file3);
25019
+ } catch (cause) {
25020
+ d.log("dead-sweep-failed", { why: cause.message.slice(0, 200) });
25021
+ } finally {
25022
+ busy = false;
25023
+ }
25024
+ }
25025
+ return { sweep: sweep3, rows: (workspace) => last.get(workspace) ?? [], ledgerDir: join59(d.stateDir, "revive") };
25026
+ }
25027
+
24381
25028
  // src/server/runs.ts
24382
25029
  import { randomBytes as randomBytes24 } from "node:crypto";
24383
- import { lstatSync as lstatSync12, realpathSync as realpathSync11 } from "node:fs";
24384
- import { basename as basename14, resolve as resolve9, sep as sep9 } from "node:path";
25030
+ import { lstatSync as lstatSync13, realpathSync as realpathSync12 } from "node:fs";
25031
+ import { basename as basename15, resolve as resolve9, sep as sep10 } from "node:path";
24385
25032
 
24386
25033
  // src/server/herdrcode.ts
24387
25034
  function herdrCode(cause) {
@@ -24484,7 +25131,7 @@ var readProcs = (platform = process.platform) => (runId) => {
24484
25131
 
24485
25132
  // src/runallow.ts
24486
25133
  var RUN_FILE_TOOLS = ["read", "grep", "find", "ls"];
24487
- var RUN_TOWER_TOOLS = ["boss_status", "call_tower", "boss_server", "tower_list", "board_read", "tower_send", "boss_open_main", "boss_close_main", "tower_memory", "tower_reply", "tower_done", "link_request", "boss_wait_ask"];
25134
+ var RUN_TOWER_TOOLS = ["boss_status", "call_tower", "boss_server", "tower_list", "board_read", "tower_send", "boss_open_main", "boss_close_main", "boss_revive_main", "tower_memory", "tower_reply", "tower_done", "link_request", "boss_wait_ask"];
24488
25135
  var LOCAL_RUN_TOOLS = [...RUN_FILE_TOOLS, ...RUN_TOWER_TOOLS];
24489
25136
  var HEAD_TOWER_TOOLS = ["tower_list", "board_read", "tower_send", "tower_memory", "tower_done", "boss_server", "boss_auto", "boss_wait_ask"];
24490
25137
  var HEAD_RUN_TOOLS = [...RUN_FILE_TOOLS, ...HEAD_TOWER_TOOLS];
@@ -24507,7 +25154,7 @@ var PROMPT_WAKE_MS = 5 * 6e4;
24507
25154
  var RUNS_SHOWN = 6;
24508
25155
  var onDisk = (file3) => {
24509
25156
  try {
24510
- lstatSync12(file3);
25157
+ lstatSync13(file3);
24511
25158
  return true;
24512
25159
  } catch {
24513
25160
  return false;
@@ -24517,10 +25164,10 @@ var mayAppear = (file3, root) => {
24517
25164
  if (!file3.endsWith(".jsonl")) return false;
24518
25165
  const abs = resolve9(file3), bases = [resolve9(root)];
24519
25166
  try {
24520
- bases.push(realpathSync11(root));
25167
+ bases.push(realpathSync12(root));
24521
25168
  } catch {
24522
25169
  }
24523
- return bases.some((b) => abs.startsWith(b + sep9));
25170
+ return bases.some((b) => abs.startsWith(b + sep10));
24524
25171
  };
24525
25172
  var phrase8 = (value, max) => typeof value === "string" ? value.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max) : "";
24526
25173
  var iso5 = (ms3) => new Date(ms3).toISOString();
@@ -24874,8 +25521,8 @@ function createRuns2(o) {
24874
25521
  const procOf = async (pane, runId) => {
24875
25522
  const all = await paneInfo(pane), info = all?.foreground_processes ?? [];
24876
25523
  const named = piByName(all);
24877
- const pick2 = info.find((p) => runId && p.cmdline?.includes(runId)) ?? info.find((p) => p.argv0 === "pi") ?? named.by ?? (named.all.length > 1 ? void 0 : info.filter((p) => p.name === "node")[0]);
24878
- return typeof pick2?.pid === "number" ? pick2.pid : void 0;
25524
+ const pick3 = info.find((p) => runId && p.cmdline?.includes(runId)) ?? info.find((p) => p.argv0 === "pi") ?? named.by ?? (named.all.length > 1 ? void 0 : info.filter((p) => p.name === "node")[0]);
25525
+ return typeof pick3?.pid === "number" ? pick3.pid : void 0;
24879
25526
  };
24880
25527
  const piByName = (all) => {
24881
25528
  const named = (all?.foreground_processes ?? []).filter((p) => p.name === "pi");
@@ -25694,8 +26341,8 @@ function createRuns2(o) {
25694
26341
  const holder = live.find((a) => e.taken?.run === a.rec.id || a.offered.has(e.id));
25695
26342
  if (!holder) removeEvent(slot, HEAD_KEY, e), gone2++;
25696
26343
  else if (!e.drop) {
25697
- const marked = { ...e, drop: true };
25698
- updateEvent(slot, HEAD_KEY, marked);
26344
+ const marked2 = { ...e, drop: true };
26345
+ updateEvent(slot, HEAD_KEY, marked2);
25699
26346
  if (holder.offered.has(e.id)) holder.offered.set(e.id, { ...holder.offered.get(e.id), drop: true });
25700
26347
  }
25701
26348
  }
@@ -25836,7 +26483,7 @@ function createRuns2(o) {
25836
26483
  setFile(token, file3, session) {
25837
26484
  const a = of(token);
25838
26485
  if (!a || typeof file3 !== "string" || file3.length > 4096) return;
25839
- if (a.rec.kind === "ally" && !(typeof session === "string" && /^[\w-]{1,128}$/.test(session) && basename14(file3).endsWith(`_${session}.jsonl`))) return;
26486
+ if (a.rec.kind === "ally" && !(typeof session === "string" && /^[\w-]{1,128}$/.test(session) && basename15(file3).endsWith(`_${session}.jsonl`))) return;
25840
26487
  a.rec.file = file3;
25841
26488
  if ((a.rec.conversation || headRun(a)) && a.rec.kind === "local") {
25842
26489
  a.pendingFile = onDisk(file3) || !mayAppear(file3, o.sessions ?? sessionsRoot()) ? void 0 : file3;
@@ -25927,15 +26574,15 @@ function allyReceipts(d) {
25927
26574
  }
25928
26575
 
25929
26576
  // src/server/towerseen.ts
25930
- import { createHash as createHash22 } from "node:crypto";
25931
- import { appendFileSync as appendFileSync4, readFileSync as readFileSync40 } from "node:fs";
25932
- import { join as join57 } from "node:path";
26577
+ import { createHash as createHash24 } from "node:crypto";
26578
+ import { appendFileSync as appendFileSync4, readFileSync as readFileSync42 } from "node:fs";
26579
+ import { join as join60 } from "node:path";
25933
26580
  var SEEN_KEEP_MS = 48 * 36e5;
25934
26581
  var SEEN_MAX = 5e3;
25935
26582
  var SLACK = 500;
25936
26583
  var FILE = "seen.jsonl";
25937
26584
  var baseId = (messageId) => messageId.replace(/~r\d+$/, "");
25938
- var hashOf3 = (text11) => createHash22("sha256").update(text11).digest("hex");
26585
+ var hashOf3 = (text11) => createHash24("sha256").update(text11).digest("hex");
25939
26586
  var key = (from, base) => `${from}
25940
26587
  ${base}`;
25941
26588
  var parse5 = (line4) => {
@@ -25947,11 +26594,11 @@ var parse5 = (line4) => {
25947
26594
  }
25948
26595
  };
25949
26596
  function openSeen(slot, workspace, now) {
25950
- const file3 = join57(towerDir(slot, workspace), FILE);
26597
+ const file3 = join60(towerDir(slot, workspace), FILE);
25951
26598
  const rows = /* @__PURE__ */ new Map();
25952
26599
  let text11 = "", lines = 0;
25953
26600
  try {
25954
- text11 = readFileSync40(file3, "utf8");
26601
+ text11 = readFileSync42(file3, "utf8");
25955
26602
  } catch {
25956
26603
  }
25957
26604
  for (const line4 of text11.split("\n")) {
@@ -26032,6 +26679,7 @@ function noteTrains(open8, d) {
26032
26679
  var UNKNOWN = "(unknown)";
26033
26680
  var RUN_SEND_CAP_MS = 2e4;
26034
26681
  var RETRY_MS4 = [1e3, 2e3, 5e3, 1e4, 3e4];
26682
+ var DEAD_MS = 6e4;
26035
26683
  var REPUBLISH_MS = 300;
26036
26684
  var REVOKE_MS = 15e3;
26037
26685
  var REFRESH_MS3 = 4 * 6e4;
@@ -26056,6 +26704,36 @@ function createTowers(o) {
26056
26704
  let republishSoon = () => {
26057
26705
  };
26058
26706
  const digest = createDigest(run3, now);
26707
+ const deadWatch = createDeadWatch({
26708
+ stateDir: slot.stateDir,
26709
+ run: run3,
26710
+ now,
26711
+ root: sessionsDir(o.env),
26712
+ recovering: () => now() < recoverUntil,
26713
+ sessions: () => o.sessions(),
26714
+ workspaces: async () => {
26715
+ const all = await workspaces(run3);
26716
+ return [...services.values()].filter((l) => !isHeadL(l) && l.state === "live" && !l.stopped).map((l) => ({ workspace: l.record.workspace, .../* @__PURE__ */ ((c) => c ? { checkout: c } : {})(all.find((w) => w.workspace_id === l.record.workspace)?.worktree?.checkout_path) }));
26717
+ },
26718
+ notice: (workspace, text11, key2) => runs2.notice(workspace, text11, key2),
26719
+ log: (event, facts) => log.line(event, facts)
26720
+ });
26721
+ const waitsHeld = (workspace, session) => {
26722
+ const lines = [];
26723
+ try {
26724
+ for (const w of readWaits(slot, workspace).entries) if (isOpen2(w) && (w.claimedBy?.id === session || w.toldTo?.some((m) => m.id === session) || w.raiser?.id === session)) lines.push(`link wait L${w.n} (${w.dir === "in" ? "a teammate's device waits on you" : "you wait on a teammate's device"}): ${phrase9(w.what, 160)}; state ${w.state}`);
26725
+ } catch {
26726
+ }
26727
+ try {
26728
+ for (const e of readMemory(slot, workspace, now()).memory.entries) {
26729
+ if (e.kind !== "wait" || e.state === "resolved" || e.state === "expired" || e.card?.from?.id !== session) continue;
26730
+ const press = e.press, missed = press && press.main && !["delivered", "queued", "asked"].includes(press.main.status);
26731
+ lines.push(`wait card ${e.id}: ${phrase9(e.card?.do ?? e.text, 160)}; ${press ? `the boss pressed ${press.act}${press.option !== void 0 ? ` (option ${press.option})` : ""}${press.reason ? `: ${phrase9(press.reason, 200)}` : ""} at ${press.at}${missed ? "; that notice did not reach you" : ""}` : "still open"}`);
26732
+ }
26733
+ } catch {
26734
+ }
26735
+ return lines;
26736
+ };
26059
26737
  const isHeadL = (l) => l.record.kind === "head";
26060
26738
  const kindOf3 = (l) => isHeadL(l) ? "head" : "tower";
26061
26739
  const headLive = () => [...services.values()].find((l) => isHeadL(l) && !l.stopped);
@@ -26103,7 +26781,7 @@ function createTowers(o) {
26103
26781
  const ws = l.record.workspace, all = await workspaces(run3), target2 = all.find((w) => w.workspace_id === ws);
26104
26782
  if (!target2 || !l.client) throw new Error("the tower's workspace or its intercom connection is gone");
26105
26783
  const first2 = items[0], device = rec.device ?? "";
26106
- const mains2 = await gatherMains({ run: run3, now, sessions: () => l.client.listSessions(), boardDir: join58(slot.stateDir, "board"), workspace: target2, ledger: [], within: { project: rec.team ? o.ally?.project(rec.team) : void 0 } });
26784
+ const mains2 = await gatherMains({ run: run3, now, sessions: () => l.client.listSessions(), boardDir: join61(slot.stateDir, "board"), workspace: target2, ledger: [], within: { project: rec.team ? o.ally?.project(rec.team) : void 0 } });
26107
26785
  const note = lastNote(slot, ws, "ally", device), at = new Date(woken);
26108
26786
  const line4 = (text11) => text11.split("\n").find((x) => x.trim()) ?? "";
26109
26787
  return {
@@ -26125,7 +26803,7 @@ function createTowers(o) {
26125
26803
  const ws = l.record.workspace, all = await workspaces(run3), target2 = all.find((w) => w.workspace_id === ws);
26126
26804
  if (!target2 || !l.client) throw new Error("the tower's workspace or its intercom connection is gone");
26127
26805
  if (isHeadL(l)) return headBrief({ slot, run: run3, now, auto: autoLine, record: () => l.record, sessions: () => l.client.listSessions(), towerState, locale: localeOf(o.env, slot.stateDir) }, { woken, run: rec, ...split ? { split } : {} });
26128
- const mains2 = await gatherMains({ run: run3, now, sessions: () => l.client.listSessions(), boardDir: join58(slot.stateDir, "board"), workspace: target2, ledger: readLedger(slot, ws, now()) });
26806
+ const mains2 = await gatherMains({ run: run3, now, sessions: () => l.client.listSessions(), boardDir: join61(slot.stateDir, "board"), workspace: target2, ledger: readLedger(slot, ws, now()) });
26129
26807
  const lines = await digest.peek(ws).catch(() => []), note = lastNote(slot, ws, "local"), timer = readTimer(slot, ws);
26130
26808
  const counts = {};
26131
26809
  for (const e of events2) counts[e.kind] = (counts[e.kind] ?? 0) + 1;
@@ -26148,6 +26826,7 @@ function createTowers(o) {
26148
26826
  ...talk ? { conversation: talk.line, since: talk.since } : {},
26149
26827
  memory: section.text,
26150
26828
  mains: mains2.rows,
26829
+ dead: deadWatch.rows(ws).map((r) => rowLine(r, now())),
26151
26830
  obligations: [...mains2.opened, ...(o.asks?.openOf(ws) ?? []).map((a) => `an ask for the main ${a.forName} is open (sent ${ageOf(now() - a.at)} ago): its answer goes to that main, not to you`), ...readExpects(slot, ws, now()).map((e) => `waiting for a reply from ${e.name} (asked ${ageOf(now() - e.at)} ago): ${e.first}`), ...timer && timer.at <= now() ? ["your wakeAfter follow-up is due"] : []],
26152
26831
  digest: lines.map((x) => x.line),
26153
26832
  ...note ? { note: { text: note.note, age: ageOf(now() - Date.parse(note.at)) } } : {},
@@ -26211,7 +26890,7 @@ function createTowers(o) {
26211
26890
  });
26212
26891
  const standing2 = createStanding({ run: run3, api: cfg.api, world: cfg.world, sleep: sleep2, now, log, command: o.promptCommand ?? (() => void 0), timers: o.standing, ...o.standingWait ? { wait: o.standingWait } : {}, ...o.runs?.platform ? { platform: o.runs.platform } : {}, ...o.runs?.alive ? { alive: o.runs.alive } : {}, locale: () => localeOf(o.env, slot.stateDir), attended: () => !o.unattended?.() });
26213
26892
  const place = (l) => ({ paneId: l.record.pane, tabId: l.record.tab, workspaceId: l.record.workspace });
26214
- const dirOf2 = (workspace) => join58(towerDir(slot, workspace));
26893
+ const dirOf2 = (workspace) => join61(towerDir(slot, workspace));
26215
26894
  const error = (code, text11) => log.line("error", { code, text: phrase9(text11, 300) });
26216
26895
  const markAnswered2 = async (l, session) => {
26217
26896
  try {
@@ -26287,6 +26966,9 @@ function createTowers(o) {
26287
26966
  trustDir: trustDir(slot.stateDir),
26288
26967
  integrationOff: () => integrationOff(o.env, slot.stateDir),
26289
26968
  stateDir: slot.stateDir,
26969
+ sessionsRoot: sessionsDir(o.env),
26970
+ recovering: () => now() < recoverUntil,
26971
+ waitsOf: (session) => waitsHeld(l.record.workspace, session),
26290
26972
  ledger: { entries: () => readLedger(slot, l.record.workspace, now(), file3), put: (row3) => {
26291
26973
  try {
26292
26974
  putLedger(slot, l.record.workspace, row3, now(), file3);
@@ -26295,12 +26977,17 @@ function createTowers(o) {
26295
26977
  }
26296
26978
  } }
26297
26979
  });
26298
- if (!isHeadL(l)) l.open = noteTrains(openerFor(), { cars: o.cars, checkout: async () => (await workspaces(run3)).find((w) => w.workspace_id === l.record.workspace)?.worktree?.checkout_path ?? l.record.cwd, error }), l.openAlly = openerFor(ALLY_LEDGER);
26980
+ if (!isHeadL(l)) {
26981
+ const local = openerFor();
26982
+ l.open = noteTrains(local, { cars: o.cars, checkout: async () => (await workspaces(run3)).find((w) => w.workspace_id === l.record.workspace)?.worktree?.checkout_path ?? l.record.cwd, error });
26983
+ l.revive = local.revive;
26984
+ l.openAlly = openerFor(ALLY_LEDGER);
26985
+ }
26299
26986
  }
26300
26987
  l.kit.attach(client);
26301
26988
  l.client = client;
26302
26989
  wire(l, client);
26303
- mkdirSync17(dirOf2(l.record.workspace), { recursive: true, mode: 448 });
26990
+ mkdirSync19(dirOf2(l.record.workspace), { recursive: true, mode: 448 });
26304
26991
  await client.connect(registration(l), l.record.id);
26305
26992
  log.line("tower-registered", { workspace: l.record.workspace, id: l.record.id, pane: l.record.pane });
26306
26993
  return true;
@@ -26581,10 +27268,10 @@ function createTowers(o) {
26581
27268
  return l;
26582
27269
  };
26583
27270
  const convertRoles = async () => {
26584
- const dir = join58(slot.stateDir, "roles");
27271
+ const dir = join61(slot.stateDir, "roles");
26585
27272
  let names = [];
26586
27273
  try {
26587
- names = readdirSync16(dir).filter((name2) => name2.endsWith(".json"));
27274
+ names = readdirSync18(dir).filter((name2) => name2.endsWith(".json"));
26588
27275
  } catch {
26589
27276
  return;
26590
27277
  }
@@ -26592,7 +27279,7 @@ function createTowers(o) {
26592
27279
  for (const name2 of names) {
26593
27280
  let record2;
26594
27281
  try {
26595
- record2 = JSON.parse(readFileSync41(join58(dir, name2), "utf8"));
27282
+ record2 = JSON.parse(readFileSync43(join61(dir, name2), "utf8"));
26596
27283
  } catch {
26597
27284
  continue;
26598
27285
  }
@@ -26608,12 +27295,12 @@ function createTowers(o) {
26608
27295
  writeService(slot, made);
26609
27296
  log.line("tower-converted", { workspace: made.workspace, pane: made.pane });
26610
27297
  }
26611
- rmSync14(join58(dir, name2), { force: true });
27298
+ rmSync16(join61(dir, name2), { force: true });
26612
27299
  }
26613
27300
  };
26614
27301
  const begin = async () => {
26615
27302
  recoverUntil = now() + (o.recoverMs ?? RECOVER_MS);
26616
- secretDir(join58(slot.dir, "tower"));
27303
+ secretDir(join61(slot.dir, "tower"));
26617
27304
  try {
26618
27305
  await convertRoles();
26619
27306
  } catch (cause) {
@@ -26668,6 +27355,7 @@ function createTowers(o) {
26668
27355
  }
26669
27356
  }, o.refreshMs ?? REFRESH_MS3));
26670
27357
  timers.push(setInterval(() => void revoker.sweep(), o.revokeMs ?? REVOKE_MS));
27358
+ timers.push(setInterval(() => void deadWatch.sweep(), o.deadMs ?? DEAD_MS));
26671
27359
  const poll = o.recoverPollMs ?? RECOVER_POLL_MS;
26672
27360
  timers.push(setInterval(() => {
26673
27361
  if (now() < recoverUntil + poll) look3();
@@ -26747,12 +27435,12 @@ function createTowers(o) {
26747
27435
  const here = await panes(run3, ws);
26748
27436
  const given = hint ? here.find((p) => p.pane_id === hint) : void 0;
26749
27437
  if (hint && !given) throw new Error(`Pane ${hint} is not in workspace ${target2.label}`);
26750
- const marked = given ?? here.find((p) => p.tokens?.sb_role === "tower");
26751
- 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) => {
26752
27440
  const inside2 = here.filter((p) => p.tab_id === t.tab_id);
26753
27441
  return inside2.length === 1 && (!inside2[0].agent || isStandin(inside2[0])) && !inside2[0].tokens?.sb_role ? [inside2[0]] : [];
26754
27442
  });
26755
- let pane = marked ?? bare2[0], dir, made = false;
27443
+ let pane = marked2 ?? bare2[0], dir, made = false;
26756
27444
  if (!pane) {
26757
27445
  dir = target2.worktree?.checkout_path ?? cwd ?? slot.stateDir;
26758
27446
  const tab = await createTab(run3, ws, dir, [], TOWER_LABEL);
@@ -26911,8 +27599,11 @@ function createTowers(o) {
26911
27599
  } : l.open,
26912
27600
  closeMain: l.control ? async (query) => forgetClosed(ws, await l.control.closeMain(query)) : void 0,
26913
27601
  now,
26914
- boardDir: join58(slot.stateDir, "board"),
27602
+ boardDir: join61(slot.stateDir, "board"),
26915
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)
26916
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" },
26917
27608
  server: o.server ?? { status: () => ({}), logs: () => [], restart: () => Promise.reject(new Error("The server cannot restart itself here")) },
26918
27609
  expect: (to, name3, text11) => {
@@ -26946,7 +27637,7 @@ function createTowers(o) {
26946
27637
  // said to the tower. The sender is the broker's, the text the sender's own; an ally answer has no event id, so its forward is named by a digest of the answer's id.
26947
27638
  slipEvents: () => {
26948
27639
  const shared = (text11) => ((f) => f?.kind === "call_tower" && f.why === "shared")(fieldsOf(text11));
26949
- if (peer) return runs2.allyAnswers(request.token).filter((x) => shared(x.text)).map((x) => ({ fwd: createHash23("sha256").update(x.id).digest("hex").slice(0, 16), from: x.from, text: x.text }));
27640
+ if (peer) return runs2.allyAnswers(request.token).filter((x) => shared(x.text)).map((x) => ({ fwd: createHash25("sha256").update(x.id).digest("hex").slice(0, 16), from: x.from, text: x.text }));
26950
27641
  return readQueue(slot, ws).flatMap((e) => e.taken?.run === who2.id && e.kind === "intercom" && e.from && shared(e.text) ? [{ fwd: e.id, from: e.from, text: e.text }] : []);
26951
27642
  },
26952
27643
  // An integrator is the tower's own main whichever run's slip opened it: one opener (and so one queue) for both kinds of run, and no ally route, so its reports reach the local runs.
@@ -26993,7 +27684,18 @@ function createTowers(o) {
26993
27684
  }
26994
27685
  }, margs),
26995
27686
  mainOf,
26996
- requester: ev.requester
27687
+ requester: ev.requester,
27688
+ // The revive (docs/specs/2026-11-23-tower-revive.md §4): a local run's, never an ally run's (runtools.ts refuses the tool by its kind as well).
27689
+ ...!peer && l.revive ? {
27690
+ revive: l.revive,
27691
+ dead: async () => gatherDead({ stateDir: slot.stateDir, run: run3, now: now(), sessions: () => l.client.listSessions(), root: sessionsDir(o.env), workspace: ws, .../* @__PURE__ */ ((c) => c ? { checkout: c } : {})((await workspaces(run3)).find((w) => w.workspace_id === ws)?.worktree?.checkout_path), recovering: now() < recoverUntil, allNotes: true }),
27692
+ missed: async (to, text11) => {
27693
+ const row3 = (await gatherDead({ stateDir: slot.stateDir, run: run3, now: now(), sessions: () => l.client.listSessions(), root: sessionsDir(o.env), workspace: ws, allNotes: true })).find((r) => (r.session === to || r.name === to) && (r.verdict.state === "dead" || r.verdict.state === "quit" || r.verdict.state === "restoring"));
27694
+ if (!row3) return void 0;
27695
+ noteMissed(slot.stateDir, row3.file, now(), l.record.name, text11);
27696
+ return `Not delivered: ${row3.name ?? row3.session.slice(0, 8)} (session ${row3.session.slice(0, 8)}) is ${row3.verdict.state}: ${row3.verdict.reason}. The message is kept, and its revive handoff carries it; revive it with boss_revive_main {action: "revive", session: "${row3.session}", reason} if its work is not done.`;
27697
+ }
27698
+ } : {}
26997
27699
  };
26998
27700
  try {
26999
27701
  if (who2.kind === "head") {
@@ -27271,7 +27973,7 @@ function createAutoFollower(d) {
27271
27973
  }
27272
27974
 
27273
27975
  // src/server/autoback.ts
27274
- import { randomUUID as randomUUID14 } from "node:crypto";
27976
+ import { randomUUID as randomUUID15 } from "node:crypto";
27275
27977
 
27276
27978
  // src/autotext.ts
27277
27979
  var KIND2 = {
@@ -27318,7 +28020,7 @@ function createBackstop(d) {
27318
28020
  }
27319
28021
  done2.add(id);
27320
28022
  keys.add(o.key);
27321
- await d.send(o.key, o.target, { id, answerId: `auto-${randomUUID14()}`, digest: o.target.answer.digest, cancel: true });
28023
+ await d.send(o.key, o.target, { id, answerId: `auto-${randomUUID15()}`, digest: o.target.answer.digest, cancel: true });
27322
28024
  note("backstop");
27323
28025
  await d.tell(o.key, cancelledText(view.since, o.owner, d.kindOf?.(o.key) ?? "main")).catch(() => void 0);
27324
28026
  }
@@ -27539,7 +28241,7 @@ async function runServer(o) {
27539
28241
  let reporter;
27540
28242
  let operateBox;
27541
28243
  let operateHost;
27542
- const operateSwitch = operateOff(join59(slot.stateDir, "link", "operate-off.json"), now);
28244
+ const operateSwitch = operateOff(join62(slot.stateDir, "link", "operate-off.json"), now);
27543
28245
  const makeOperateHost = () => operateHost = createOperateHost({
27544
28246
  now,
27545
28247
  device: () => link?.holder?.deviceId,
@@ -27688,8 +28390,8 @@ async function runServer(o) {
27688
28390
  case "head-drop": {
27689
28391
  const answers2 = request.answers === void 0 ? void 0 : waitId(request.answers);
27690
28392
  if (request.answers !== void 0 && !answers2) return Promise.resolve({ ok: false, error: "answers names a wait: W and its number" });
27691
- const refusal6 = request.cmd === "head-event" ? notAnAnswer(answers2, text11(request.text, 16384)) : void 0;
27692
- 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);
27693
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) } : {} }));
27694
28396
  }
27695
28397
  case "close-tower":
@@ -27730,8 +28432,8 @@ async function runServer(o) {
27730
28432
  const body2 = text11(request.text, 16384);
27731
28433
  const answers2 = request.answers === void 0 ? void 0 : waitId(request.answers);
27732
28434
  if (request.answers !== void 0 && !answers2) return Promise.resolve({ ok: false, error: "answers names a wait: W and its number" });
27733
- const refusal6 = notAnAnswer(answers2, body2);
27734
- if (refusal6) return Promise.resolve(refusal6);
28435
+ const refusal7 = notAnAnswer(answers2, body2);
28436
+ if (refusal7) return Promise.resolve(refusal7);
27735
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" });
27736
28438
  }
27737
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;
@@ -27843,7 +28545,7 @@ async function runServer(o) {
27843
28545
  // The work board's Clear tells a live writer once (boardpanel.ts): one intercom message from the server, under a `board_clear` header.
27844
28546
  tell: tellVia(() => client, serverId(slot)),
27845
28547
  // The primary server holds the link itself (B3), so the GUI asks the holder in this process as the server, which the holder takes GUI requests from; before it runs, the channel reaches the holder's session. A secondary server holds none and its GUI says so (`no_link`, as its `link` request does): the channel would ask the primary's holder as a session that is not the GUI's host.
27846
- link: gui.link ?? (!slot.primary ? elsewhereLink() : inProcessLink(createGuiLink({ events: kit.pi.events, id: () => serverId(slot), stateDir: slot.stateDir, agentDir: env.PI_CODING_AGENT_DIR ?? join59(homedir15(), ".pi", "agent"), log: (text11) => log.line("link", { text: text11 }) }), () => link, () => serverId(slot))),
28548
+ link: gui.link ?? (!slot.primary ? elsewhereLink() : inProcessLink(createGuiLink({ events: kit.pi.events, id: () => serverId(slot), stateDir: slot.stateDir, agentDir: env.PI_CODING_AGENT_DIR ?? join62(homedir16(), ".pi", "agent"), log: (text11) => log.line("link", { text: text11 }) }), () => link, () => serverId(slot))),
27847
28549
  status: () => ({ state: phase === "ready" ? "live" : phase, version, pid, mode, desk, uptimeMs: now() - startedAt, log: fileOf(slot, "log"), ...own.lastError ? { lastError: own.lastError } : {} }),
27848
28550
  restart: gui.restart ?? ((reason) => spawnRestart(cliBeside(), reason, "the GUI", serverEnv(env), slot.dir, void 0, true)),
27849
28551
  failed: (code, text11) => recordError(code, text11),
@@ -28031,8 +28733,8 @@ ${unit}`), note = ws ? readNotes(slot, ws).at(-1) : void 0, sent = ws ? link?.ho
28031
28733
  run: cfg.run,
28032
28734
  towers: () => towers,
28033
28735
  now,
28034
- home: o.link?.home ?? homedir15(),
28035
- agentDir: env.PI_CODING_AGENT_DIR ?? join59(o.link?.home ?? homedir15(), ".pi", "agent"),
28736
+ home: o.link?.home ?? homedir16(),
28737
+ agentDir: env.PI_CODING_AGENT_DIR ?? join62(o.link?.home ?? homedir16(), ".pi", "agent"),
28036
28738
  failed: (from, project, error) => void unitsOut().notify(`tower-open/${from}/${project}/${Math.floor(now() / 6e5)}`, { kind: "tower-open-failed", unit: allyLabel(project), text: `Could not open a tower for ${project}: ${error.message}` }, { device: from })
28037
28739
  })
28038
28740
  }