pi-straw-boss 0.79.2 → 0.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -200,6 +200,7 @@ import {
200
200
  updateRecord,
201
201
  validateStateFields,
202
202
  waitFor,
203
+ waitMessage,
203
204
  waitingTrains,
204
205
  wireId,
205
206
  workspaces,
@@ -211,11 +212,11 @@ import {
211
212
  writeStartError,
212
213
  writerAlive,
213
214
  yardPath
214
- } from "./chunk-VOBPJZPJ.mjs";
215
+ } from "./chunk-GEBLT4XW.mjs";
215
216
 
216
217
  // src/server/main.ts
217
- import { homedir as homedir14 } from "node:os";
218
- import { join as join57 } from "node:path";
218
+ import { homedir as homedir15 } from "node:os";
219
+ import { join as join58 } from "node:path";
219
220
 
220
221
  // src/boardauto.ts
221
222
  import { posix, win32 } from "node:path";
@@ -3408,6 +3409,7 @@ function scriptRead(folder, path) {
3408
3409
  return void 0;
3409
3410
  }
3410
3411
  }
3412
+ var launchScripts = (dir, scriptDir = join14(dir, "subagent-scripts"), names = listed(scriptDir).filter((f) => f.endsWith(".sh")), folder = scriptsOf(scriptDir, names)) => names.flatMap((script) => ((l) => l ? [{ script, id: l.id, session: l.session, agent: l.agent }] : [])(scriptRead(folder, join14(scriptDir, script))));
3411
3413
  var ROLE_BYTES = 64 * 1024;
3412
3414
  var roles = /* @__PURE__ */ new Map();
3413
3415
  var roleless = /* @__PURE__ */ new Map();
@@ -3765,9 +3767,9 @@ async function withPending(net, fileOf4, relayed) {
3765
3767
  if (dialogs?.length) [u.mark, b.mark] = ["waiting", "waiting"];
3766
3768
  if (dialogs?.length && u !== b.tower) u.note = "waiting on a question";
3767
3769
  const file2 = u.mark === "waiting" ? fileOf4(u.key) : void 0;
3768
- const join58 = (p, calls) => dialogs?.length ? relayed.merge(u.key, p, dialogs, Boolean(file2), calls) : p;
3769
- if (file2) jobs.push(pendingWith(file2).then(({ pending, calls }) => u.pending = join58(pending, calls)));
3770
- else if (dialogs?.length) u.pending = join58();
3770
+ const join59 = (p, calls) => dialogs?.length ? relayed.merge(u.key, p, dialogs, Boolean(file2), calls) : p;
3771
+ if (file2) jobs.push(pendingWith(file2).then(({ pending, calls }) => u.pending = join59(pending, calls)));
3772
+ else if (dialogs?.length) u.pending = join59();
3771
3773
  }
3772
3774
  for (const b of net.bases) for (const u of unitsOf(b)) u.mark = commanding(u.mark, u.subs.map((c) => c.mark));
3773
3775
  await Promise.all(jobs);
@@ -4448,7 +4450,7 @@ function createHub(pi, me, local, onAllow) {
4448
4450
  } catch {
4449
4451
  }
4450
4452
  };
4451
- const join58 = () => {
4453
+ const join59 = () => {
4452
4454
  try {
4453
4455
  if (!channel && me) pi.events.emit(REGISTER2, { namespace: guiNamespace(me), ownerEligible: true, onReady: (c) => channel = c, onEvent });
4454
4456
  } catch {
@@ -4537,12 +4539,12 @@ function createHub(pi, me, local, onAllow) {
4537
4539
  /** The channel is registered at the first start, before gui.json names this session; later starts in this process reuse it. */
4538
4540
  start(onChange) {
4539
4541
  [change, active] = [onChange, true];
4540
- join58();
4542
+ join59();
4541
4543
  },
4542
4544
  /** 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. */
4543
4545
  track() {
4544
4546
  tracking = true;
4545
- join58();
4547
+ join59();
4546
4548
  },
4547
4549
  stop() {
4548
4550
  active = false;
@@ -4921,7 +4923,7 @@ function unitsOfTab(net, workspace, tab) {
4921
4923
  return found?.units.length ? found.units.flatMap((u) => [u.key, ...u.subs.map((s2) => s2.key)]) : void 0;
4922
4924
  }
4923
4925
  var OPERATE_REFUSED = "operate_refused";
4924
- var refusalReply = (no17) => no17.why === "bad-request" ? { status: 400, body: { error: "bad_request", reason: no17.reason } } : { status: 403, body: { error: OPERATE_REFUSED, why: no17.why, reason: no17.reason } };
4926
+ var refusalReply = (no19) => no19.why === "bad-request" ? { status: 400, body: { error: "bad_request", reason: no19.reason } } : { status: 403, body: { error: OPERATE_REFUSED, why: no19.why, reason: no19.reason } };
4925
4927
 
4926
4928
  // src/autoscope.ts
4927
4929
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
@@ -5931,38 +5933,38 @@ function createDocs(hub, name2, { answered = createAnswered({ load: () => void 0
5931
5933
  * (blockcount.ts), else the page drew another text and the answer is refused (409 `stale`, `no_block`) before anything is recorded or sent. The block is begun in the record then (answered.ts), so a block that is answered or on its way is not sent again from any device. One answer id is sent once: its outcome is the reply to the same id again for as long as the window lasts (30 minutes, whatever else is answered),
5932
5934
  * but a send that failed outright (no outcome at all) is forgotten, so the same id may try again. */
5933
5935
  async answer(cap, json3) {
5934
- const no17 = (status, error, reason, extra = {}) => ({ status, body: { error, reason, ...extra } }), { answerId, answer, rev } = json3;
5936
+ const no19 = (status, error, reason, extra = {}) => ({ status, body: { error, reason, ...extra } }), { answerId, answer, rev } = json3;
5935
5937
  const found = CAP.test(cap) ? hub.doc(cap) : void 0;
5936
- if (!found) return no17(404, "closed", "The document is no longer open in its session.");
5937
- if (!isBlocksDoc(found.doc)) return no17(409, "refused", "This document takes no answers from its blocks.");
5938
- if (typeof answerId !== "string" || !ANSWER_ID2.test(answerId) || !answerOk(answer) || answer.ref === void 0 || typeof rev !== "string" || !REV.test(rev)) return no17(400, "bad_request", "The answer is not a block's answer: at most 65 text fields, under 12 KB, with no control characters, the block's index, and the hash of the text it was drawn from.");
5939
- if (found.doc.v !== 2) return no17(409, "refused", "This document comes from pi-herdr-doc-review, which takes no answers from its blocks: they need the document package pi-better-show (contract v2). Answer in the session instead.");
5938
+ if (!found) return no19(404, "closed", "The document is no longer open in its session.");
5939
+ if (!isBlocksDoc(found.doc)) return no19(409, "refused", "This document takes no answers from its blocks.");
5940
+ if (typeof answerId !== "string" || !ANSWER_ID2.test(answerId) || !answerOk(answer) || answer.ref === void 0 || typeof rev !== "string" || !REV.test(rev)) return no19(400, "bad_request", "The answer is not a block's answer: at most 65 text fields, under 12 KB, with no control characters, the block's index, and the hash of the text it was drawn from.");
5941
+ if (found.doc.v !== 2) return no19(409, "refused", "This document comes from pi-herdr-doc-review, which takes no answers from its blocks: they need the document package pi-better-show (contract v2). Answer in the session instead.");
5940
5942
  const now = Date.now(), k = `${cap}
5941
5943
  ${answerId}`, { block } = answer.ref, doc2 = found.doc;
5942
5944
  for (const [id, v] of answers2) if (v.until < now) answers2.delete(id);
5943
5945
  else break;
5944
5946
  const had = answers2.get(k);
5945
5947
  if (had) return had.reply;
5946
- const unspent = (status, error, reason) => (answers2.delete(k), no17(status, error, reason));
5948
+ const unspent = (status, error, reason) => (answers2.delete(k), no19(status, error, reason));
5947
5949
  const reply3 = (async () => {
5948
5950
  const text11 = await body2(doc2);
5949
5951
  if (text11 === void 0) return unspent(404, "closed", "The document could not be read from its owner: it is no longer open in its session.");
5950
5952
  if (revOf(text11) !== rev) return unspent(409, "stale", "The document changed since this page drew it. Reload it to see the text, then answer.");
5951
5953
  if (block >= blockCount(text11)) return unspent(409, "no_block", "The document has no such block. Reload it to see the text, then answer.");
5952
5954
  const key2 = docKey(found.key, doc2.path ?? doc2.display, rev, block), begun = answered.begin(key2);
5953
- if (begun === "answered") return no17(409, "answered", "This block was answered already.", { fields: answered.get(key2)?.fields ?? [] });
5954
- if (begun === "pending") return no17(409, "pending", "This block's answer is on its way.");
5955
- if (begun === "unsaved") return no17(500, "unsaved", "This server could not write down the answer, so nothing was sent.");
5955
+ if (begun === "answered") return no19(409, "answered", "This block was answered already.", { fields: answered.get(key2)?.fields ?? [] });
5956
+ if (begun === "pending") return no19(409, "pending", "This block's answer is on its way.");
5957
+ if (begun === "unsaved") return no19(500, "unsaved", "This server could not write down the answer, so nothing was sent.");
5956
5958
  try {
5957
5959
  const r = await hub.form(cap, answerId, answer.fields, { ...answer, ref: { doc: doc2.display, block } });
5958
- if (!r) return no17(504, "not_confirmed", "Check the terminal: the session did not confirm the answer, so it may or may not have arrived.");
5960
+ if (!r) return no19(504, "not_confirmed", "Check the terminal: the session did not confirm the answer, so it may or may not have arrived.");
5959
5961
  if (r.accepted) return { status: 200, body: answered.done(key2, answer.fields) ? { accepted: true } : { accepted: true, unsaved: true } };
5960
5962
  answered.cancel(key2);
5961
- return no17(409, "refused", r.reason === "closed" ? "The document is no longer open in its session." : r.reason === "empty" ? "The form has no fields to send." : `The session refused it (${r.reason ?? "no reason"}).`);
5963
+ return no19(409, "refused", r.reason === "closed" ? "The document is no longer open in its session." : r.reason === "empty" ? "The form has no fields to send." : `The session refused it (${r.reason ?? "no reason"}).`);
5962
5964
  } catch {
5963
5965
  answers2.delete(k);
5964
5966
  answered.cancel(key2);
5965
- return no17(500, "internal", "The answer could not be sent.");
5967
+ return no19(500, "internal", "The answer could not be sent.");
5966
5968
  }
5967
5969
  })();
5968
5970
  answers2.set(k, { until: now + NONCE_MS, reply: reply3 });
@@ -6008,31 +6010,31 @@ async function claimGate(f) {
6008
6010
  return { claimed: true, fresh: f.bare && !f.typed() };
6009
6011
  }
6010
6012
  async function typeGate(f) {
6011
- const no17 = (reason) => ({ type: false, reason });
6012
- if (!f.attached) return no17("absent");
6013
- if (!f.seated()) return no17("unseated");
6014
- if (f.busy) return no17("busy");
6015
- if (f.run) return no17("run");
6016
- if (f.agent === "other") return no17("agent");
6017
- if (f.prompt()) return no17("prompt");
6013
+ const no19 = (reason) => ({ type: false, reason });
6014
+ if (!f.attached) return no19("absent");
6015
+ if (!f.seated()) return no19("unseated");
6016
+ if (f.busy) return no19("busy");
6017
+ if (f.run) return no19("run");
6018
+ if (f.agent === "other") return no19("agent");
6019
+ if (f.prompt()) return no19("prompt");
6018
6020
  await f.gone();
6019
- if (!f.seated()) return no17("unseated");
6020
- if (f.prompt()) return no17("prompt");
6021
- if (f.parked()) return no17("parked");
6022
- if (f.runSoon()) return no17("run-soon");
6023
- if (f.launchWait()) return no17("launch-wait");
6024
- if (f.agent !== "none") return no17("stand-in");
6025
- if (!f.command()) return no17("no-command");
6021
+ if (!f.seated()) return no19("unseated");
6022
+ if (f.prompt()) return no19("prompt");
6023
+ if (f.parked()) return no19("parked");
6024
+ if (f.runSoon()) return no19("run-soon");
6025
+ if (f.launchWait()) return no19("launch-wait");
6026
+ if (f.agent !== "none") return no19("stand-in");
6027
+ if (!f.command()) return no19("no-command");
6026
6028
  const settled = f.settle();
6027
- if (settled.hand) return no17("hand");
6028
- if (settled.giveUp) return no17("gave-up");
6029
- if (!f.groups && f.typedHere()) return no17("typed");
6030
- if (!f.groups && f.held) return no17("held");
6031
- if (!f.groups && !f.fresh()) return no17("unproven");
6029
+ if (settled.hand) return no19("hand");
6030
+ if (settled.giveUp) return no19("gave-up");
6031
+ if (!f.groups && f.typedHere()) return no19("typed");
6032
+ if (!f.groups && f.held) return no19("held");
6033
+ if (!f.groups && !f.fresh()) return no19("unproven");
6032
6034
  const info = await f.read();
6033
- if (!f.seated()) return no17("unseated");
6034
- if (f.prompt()) return no17("prompt");
6035
- if (!idleShell(info, f.fresh(), f.groups)) return no17("not-idle");
6035
+ if (!f.seated()) return no19("unseated");
6036
+ if (f.prompt()) return no19("prompt");
6037
+ if (!idleShell(info, f.fresh(), f.groups)) return no19("not-idle");
6036
6038
  return { type: true };
6037
6039
  }
6038
6040
  function holdGate(f) {
@@ -9376,7 +9378,7 @@ function createLanHost(o) {
9376
9378
  if ("lost" in read4) return read4;
9377
9379
  return caStatus(read4.ca, now()).state === "ended" ? (ca = read4.ca, { ended: true }) : (ca = read4.ca, { ca: read4.ca });
9378
9380
  }
9379
- const factsOf3 = () => {
9381
+ const factsOf4 = () => {
9380
9382
  const addresses = served().map((a) => ({ address: a.address, interface: a.iface })), g = gui;
9381
9383
  return {
9382
9384
  wanted: g ? lan().wanted : false,
@@ -9389,7 +9391,7 @@ function createLanHost(o) {
9389
9391
  };
9390
9392
  };
9391
9393
  const pendingBody = () => ({
9392
- ...factsOf3(),
9394
+ ...factsOf4(),
9393
9395
  pending: lan().pending().map(({ id, label, peer, iface, since }) => ({ id, label, peer, iface, since, age: age(now() - since), ageMs: now() - since })),
9394
9396
  events: events.map((e) => e.text),
9395
9397
  // The same, with the codes the page words in its own language (gui/lan.ts); `events` and `note` stay the English the overlay shows.
@@ -9418,7 +9420,7 @@ function createLanHost(o) {
9418
9420
  held = void 0;
9419
9421
  if (listener && lan().on && status && !hasTaken(status)) {
9420
9422
  watchFirewall();
9421
- return reply(200, { ...factsOf3(), text: `Wi-Fi access is on: ${urlOf() ?? "no address is served yet"}` });
9423
+ return reply(200, { ...factsOf4(), text: `Wi-Fi access is on: ${urlOf() ?? "no address is served yet"}` });
9422
9424
  }
9423
9425
  await down(false, "restart").catch(() => {
9424
9426
  });
@@ -9431,14 +9433,14 @@ function createLanHost(o) {
9431
9433
  return bad("lan_start_failed", error.message, 500);
9432
9434
  }
9433
9435
  if (!serving) return bad("lan_taken", lanNote() ?? "Wi-Fi access could not be turned on.", 409);
9434
- return reply(200, { ...factsOf3(), text: `Wi-Fi access is on: ${urlOf() ?? "no address is served yet"}` });
9436
+ return reply(200, { ...factsOf4(), text: `Wi-Fi access is on: ${urlOf() ?? "no address is served yet"}` });
9435
9437
  }
9436
9438
  async function turnOff() {
9437
9439
  if (!gui) return bad("stopped", "The GUI is not running.", 409);
9438
9440
  if (!o.primary) return bad("secondary", SECONDARY.text, 409);
9439
9441
  held = moved = void 0;
9440
9442
  await down(true);
9441
- return reply(200, { ...factsOf3(), text: "Wi-Fi access is off; the devices you allowed stay paired" });
9443
+ return reply(200, { ...factsOf4(), text: "Wi-Fi access is off; the devices you allowed stay paired" });
9442
9444
  }
9443
9445
  const faceOk = (face) => {
9444
9446
  const v = faces.accepts(face);
@@ -9606,7 +9608,7 @@ function createLanHost(o) {
9606
9608
  }
9607
9609
  if (!serving) return bad("lan_taken", lanNote() ?? "Wi-Fi access could not be turned on.", 409);
9608
9610
  }
9609
- return reply(200, { ...factsOf3(), text: `A new Wi-Fi certificate was made${unpair ? "; every device paired over Wi-Fi is unpaired" : "; the devices stay paired"}` });
9611
+ return reply(200, { ...factsOf4(), text: `A new Wi-Fi certificate was made${unpair ? "; every device paired over Wi-Fi is unpaired" : "; the devices stay paired"}` });
9610
9612
  }
9611
9613
  return {
9612
9614
  faces,
@@ -9618,7 +9620,7 @@ function createLanHost(o) {
9618
9620
  attach(running) {
9619
9621
  gui = running;
9620
9622
  },
9621
- facts: factsOf3,
9623
+ facts: factsOf4,
9622
9624
  /** Why Wi-Fi access is off or limited, for `up` and the page's notice row. */
9623
9625
  get note() {
9624
9626
  return lanNote();
@@ -9849,8 +9851,8 @@ function cleanWait(wait2, clean6) {
9849
9851
  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 } : {} } };
9850
9852
  return { target: { target: clean6(wait2.target.target, 128), holder: clean6(wait2.target.holder, 32), ...wait2.target.why ? { why: wait2.target.why } : {} } };
9851
9853
  }
9852
- function unitOf(join58, project, code, writer) {
9853
- const claims = join58.trains.filter((u) => u.project === project && u.code === code);
9854
+ function unitOf(join59, project, code, writer) {
9855
+ const claims = join59.trains.filter((u) => u.project === project && u.code === code);
9854
9856
  return claims.length === 1 ? claims[0].key : claims.find((u) => u.key === writer)?.key;
9855
9857
  }
9856
9858
  function readYards(deps, join_) {
@@ -10140,9 +10142,9 @@ function createGuiHost(o) {
10140
10142
  const seen = readRecord2(dir);
10141
10143
  if (!seen || seen.pid === pid && (!seen.started || !o.started() || seen.started === o.started())) return false;
10142
10144
  if (!(o.runs ?? ((r) => alive(r.pid)))(seen)) return false;
10143
- const told2 = seen.started ? await startOfLater(seen.pid) : void 0;
10144
- if (!seen.started || told2 !== seen.started) {
10145
- log.line("gui-reclaim-skipped", { pid: seen.pid, why: !seen.started ? "no-start-recorded" : told2 === void 0 ? "start-unknown" : "start-differs" });
10145
+ const told3 = seen.started ? await startOfLater(seen.pid) : void 0;
10146
+ if (!seen.started || told3 !== seen.started) {
10147
+ log.line("gui-reclaim-skipped", { pid: seen.pid, why: !seen.started ? "no-start-recorded" : told3 === void 0 ? "start-unknown" : "start-differs" });
10146
10148
  return false;
10147
10149
  }
10148
10150
  if (!await answers(seen)) return false;
@@ -10151,15 +10153,27 @@ function createGuiHost(o) {
10151
10153
  for (const end = Date.now() + RECLAIM_WAIT_MS; Date.now() < end; await new Promise((r) => setTimeout(r, 100))) if (!await listening(seen.port)) return true;
10152
10154
  return false;
10153
10155
  };
10156
+ const boardDir = join29(slot.stateDir, "board");
10157
+ const newNet = () => current = netSource({ ...o.auto ? { auto: () => o.auto.snap(), autoable: () => o.auto.available() } : {}, ...o.tower ? { services: (workspace) => o.tower.view(workspace) } : {}, ...o.head ? { head: o.head } : {}, run: cfg.run, world: cfg.world, sessions, stashed: () => stashedList(slot.stateDir), trust, hub: theHub(), board: boardSeam({ dir: boardDir, now: () => cfg.now() }), trainyard: trainyardSeam({ env: cfg.env, stateDir: slot.stateDir, ...o.trainCars ? { book: o.trainCars } : {}, ...o.trainyard }) });
10158
+ const watchers = /* @__PURE__ */ new Set();
10159
+ let lastNet;
10160
+ const told2 = (net) => {
10161
+ lastNet = net;
10162
+ for (const cb of watchers) try {
10163
+ cb(net);
10164
+ } catch (error) {
10165
+ log.line("error", { code: "watch", text: phrase(error.message, 200) });
10166
+ }
10167
+ return net;
10168
+ };
10154
10169
  const begin = async (prefer, wait2) => {
10155
10170
  theHub();
10156
- const boardDir = join29(slot.stateDir, "board");
10157
- const net = current = netSource({ ...o.auto ? { auto: () => o.auto.snap(), autoable: () => o.auto.available() } : {}, ...o.tower ? { services: (workspace) => o.tower.view(workspace) } : {}, ...o.head ? { head: o.head } : {}, run: cfg.run, world: cfg.world, sessions, stashed: () => stashedList(slot.stateDir), trust, hub, board: boardSeam({ dir: boardDir, now: () => cfg.now() }), trainyard: trainyardSeam({ env: cfg.env, stateDir: slot.stateDir, ...o.trainCars ? { book: o.trainCars } : {}, ...o.trainyard }) });
10171
+ const net = newNet();
10158
10172
  let running;
10159
10173
  const host = createLanHost({ dir, primary: slot.primary, log, ...o.lan ? { seams: o.lan } : {}, notice: (waiting) => void updateRecord(slot, (r) => r.pid === pid ? (({ lanNotice: _gone, ...rest }) => ({ ...rest, ...waiting.length ? { lanNotice: waiting } : {} }))(r) : void 0) });
10160
10174
  running = await startGui({
10161
10175
  read: async () => {
10162
- const next2 = await net.read(), summary = await o.link.summary();
10176
+ const next2 = told2(await net.read()), summary = await o.link.summary();
10163
10177
  return summary && (summary.allies.length || summary.alerts.length || summary.confirms.length) ? { ...next2, link: summary } : next2;
10164
10178
  },
10165
10179
  ...o.auto ? { auto: o.auto } : {},
@@ -10317,6 +10331,8 @@ function createGuiHost(o) {
10317
10331
  /** The unit the hub files dialogs under `key` (known after a `read`): its pane for the dispatcher, its name and role for the label a controller is told. */
10318
10332
  lookup: (key2) => forwardNet?.lookup(key2)
10319
10333
  }),
10334
+ /** The readings of the net for the watchdog routes (watchread.ts): every reading a GUI makes, the last one, the registry of the last reading, and a reading made now, which a stopped GUI's source (or a new one) gives. */
10335
+ watchNet: () => ({ onRead: (cb) => (watchers.add(cb), () => void watchers.delete(cb)), last: () => lastNet, lookup: (key2) => current?.lookup(key2), read: async () => told2(await (current ?? newNet()).read()) }),
10320
10336
  /** The operate bridge's way in while a GUI runs (src/server/operatebox.ts): the GUI's in-process operate entry, and the registry's units and keys as the last net reading knows them. */
10321
10337
  operate: () => gui && current ? { api: gui.operate, refs: () => current.refs(), lookup: (key2) => current.lookup(key2) } : void 0,
10322
10338
  /** At the server's start: the GUI on the recorded ports unless it was stopped on purpose (which only the boss's own command undoes). */
@@ -11692,30 +11708,30 @@ function buildJoinRequest(o) {
11692
11708
  return Buffer.concat([nonce, aeadSeal(joinKey(o.secret, o.team), nonce, enc(encodeKeyRecord(o.record), str(o.label), mac))]);
11693
11709
  }
11694
11710
  function openJoinRequest(o) {
11695
- const no17 = (reason) => ({ ok: false, reason });
11696
- if (o.blob.length < NONCE_BYTES) return no17("bad-ciphertext");
11711
+ const no19 = (reason) => ({ ok: false, reason });
11712
+ if (o.blob.length < NONCE_BYTES) return no19("bad-ciphertext");
11697
11713
  const plain3 = aeadOpen(joinKey(o.secret, o.team), o.blob.subarray(0, NONCE_BYTES), o.blob.subarray(NONCE_BYTES));
11698
- if (!plain3) return no17("bad-ciphertext");
11714
+ if (!plain3) return no19("bad-ciphertext");
11699
11715
  let rec, label, mac;
11700
11716
  try {
11701
11717
  [rec, label, mac] = dec(plain3, 3);
11702
11718
  } catch {
11703
- return no17("bad-request");
11719
+ return no19("bad-request");
11704
11720
  }
11705
11721
  let record2;
11706
11722
  try {
11707
11723
  record2 = decodeKeyRecord(rec);
11708
11724
  } catch {
11709
- return no17("bad-record");
11725
+ return no19("bad-record");
11710
11726
  }
11711
11727
  const text11 = readStr(label);
11712
- if (!equalBytes(mac, joinMac(o.secret, o.team, requestFields(record2, text11)))) return no17("bad-mac");
11713
- if (!labelOk(text11)) return no17("bad-label");
11714
- if (o.forDevice !== "" && record2.id !== o.forDevice) return no17("wrong-device");
11728
+ if (!equalBytes(mac, joinMac(o.secret, o.team, requestFields(record2, text11)))) return no19("bad-mac");
11729
+ if (!labelOk(text11)) return no19("bad-label");
11730
+ if (o.forDevice !== "" && record2.id !== o.forDevice) return no19("wrong-device");
11715
11731
  if (o.roster) {
11716
- if (o.roster.banned.has(record2.id)) return no17("banned");
11717
- if (o.roster.members.has(record2.id)) return no17("already-member");
11718
- if ([...o.roster.members.values()].some((m) => m.label === text11)) return no17("label-taken");
11732
+ if (o.roster.banned.has(record2.id)) return no19("banned");
11733
+ if (o.roster.members.has(record2.id)) return no19("already-member");
11734
+ if ([...o.roster.members.values()].some((m) => m.label === text11)) return no19("label-taken");
11719
11735
  }
11720
11736
  return { ok: true, record: record2, label: text11 };
11721
11737
  }
@@ -17258,8 +17274,8 @@ function localHost(host) {
17258
17274
  const quad = labels.length === 4 && labels.every((l) => /^(?:0|[1-9][0-9]{0,2})$/.test(l) && Number(l) <= 255);
17259
17275
  return !quad || labels[0] === "127" || labels[0] === "0";
17260
17276
  }
17261
- const mine = hostname3().toLowerCase().replace(/\.+$/, ""), short4 = mine.split(".")[0];
17262
- return [mine, short4, `${short4}.local`, `${mine}.local`].includes(h);
17277
+ const mine = hostname3().toLowerCase().replace(/\.+$/, ""), short5 = mine.split(".")[0];
17278
+ return [mine, short5, `${short5}.local`, `${mine}.local`].includes(h);
17263
17279
  }
17264
17280
  var safeUrl = (url) => {
17265
17281
  if (url.length > 500 || url.startsWith("-") || /\/\/[^/@]*@-/.test(url)) return void 0;
@@ -18378,18 +18394,18 @@ function createProcs(d) {
18378
18394
  async function refuseProtected(pid, table, pane) {
18379
18395
  const proc = table.find((p) => p.pid === pid && !p.zombie);
18380
18396
  if (!proc) return;
18381
- const no17 = (what) => new ProcsRefusal(`procs-hello: pid ${pid} is ${what}, not a pi`);
18382
- if (SHELLS3.has(baseName(proc.comm).replace(/^-/, ""))) throw no17("a shell");
18383
- if (self.includes(pid)) throw no17("this server");
18397
+ const no19 = (what) => new ProcsRefusal(`procs-hello: pid ${pid} is ${what}, not a pi`);
18398
+ if (SHELLS3.has(baseName(proc.comm).replace(/^-/, ""))) throw no19("a shell");
18399
+ if (self.includes(pid)) throw no19("this server");
18384
18400
  const all = await d.protect?.(table) ?? [];
18385
18401
  const named = all.filter((p) => p.why !== "pane-foreground");
18386
18402
  const hit = named.find((p) => p.pid === pid && (p.started === void 0 || p.started === proc.started));
18387
- if (hit) throw no17(`protected (${hit.why})`);
18388
- if (pane && all.some((p) => p.why === "pane-foreground" && p.pid === pid && p.pane !== void 0 && p.pane !== pane)) throw no17("the foreground of another pane");
18403
+ if (hit) throw no19(`protected (${hit.why})`);
18404
+ if (pane && all.some((p) => p.why === "pane-foreground" && p.pid === pid && p.pane !== void 0 && p.pane !== pane)) throw no19("the foreground of another pane");
18389
18405
  const below = new Set(descendants(table, [pid]).map((p) => p.pid));
18390
18406
  const shells = new Set(named.filter((p) => p.why === "pane").map((p) => p.pid));
18391
18407
  const server = (p) => p.why === "herdr" && (shells.size === 0 || descendants(table, [p.pid]).some((c) => shells.has(c.pid)));
18392
- if (named.some((p) => (server(p) || p.why === "pane") && below.has(p.pid))) throw no17("above Herdr or a pane's shell");
18408
+ if (named.some((p) => (server(p) || p.why === "pane") && below.has(p.pid))) throw no19("above Herdr or a pane's shell");
18393
18409
  }
18394
18410
  async function reapSet(subject, reason, explicit = false) {
18395
18411
  const table = await read4();
@@ -18715,12 +18731,264 @@ function startProcs(o) {
18715
18731
  return procs;
18716
18732
  }
18717
18733
 
18734
+ // src/server/watchdogops.ts
18735
+ import { homedir as homedir12 } from "node:os";
18736
+ import { join as join43 } from "node:path";
18737
+
18738
+ // src/server/watchread.ts
18739
+ import { createHash as createHash15, randomBytes as randomBytes18 } from "node:crypto";
18740
+ var HOLD_MS = 45e3;
18741
+ var READ_MS2 = 1e4;
18742
+ var FORGET_MS = 10 * 6e4;
18743
+ var MAX_TOLD = 12;
18744
+ var short3 = (text11, n = 8) => createHash15("sha256").update(text11).digest("hex").slice(0, n);
18745
+ var holdersOf = (b) => [...b.tower ? [b.tower, ...b.tower.subs] : [], ...[...b.tabs.flatMap((t) => t.units), ...b.outside].flatMap((u) => [u, ...u.subs])];
18746
+ var trainOf = (net, key2) => net.yards?.projects.flatMap((p) => p.trains).find((t) => t.key === key2 && t.state !== "unreadable");
18747
+ var stepOf = (train) => train.steps.find((s2) => s2.status === "in_progress") ?? train.steps.findLast((s2) => s2.status !== "pending");
18748
+ var waitFact = (w) => "load" in w ? "load" : JSON.stringify(w);
18749
+ function factsOf2({ unit, train }) {
18750
+ return short3(JSON.stringify([
18751
+ unit.mark,
18752
+ (unit.monitors ?? []).map((m) => [m.id, m.status, m.exit ?? null]),
18753
+ unit.todo ? [unit.todo.done, unit.todo.total, unit.todo.now ?? null] : null,
18754
+ train ? [train.state, train.round ?? null, train.steps.map((s2) => [s2.id, s2.status, s2.round, s2.outcome ?? null, s2.status === "in_progress" ? s2.waits.map(waitFact) : null])] : null,
18755
+ (unit.subs ?? []).map((s2) => [s2.key, s2.mark])
18756
+ ]), 16);
18757
+ }
18758
+ function viewOf({ unit, train }, now) {
18759
+ const monitor = (m) => ({ id: m.id, status: m.status, ...m.exit !== void 0 ? { exit: m.exit } : {}, ...m.last !== void 0 ? { last: m.last } : {}, ...m.load ? { load: { max: m.load.max, now: m.load.now } } : {}, ageMs: Math.max(0, now - m.at) });
18760
+ const step = train && stepOf(train);
18761
+ return {
18762
+ mark: unit.mark,
18763
+ ...unit.note ? { note: unit.note } : {},
18764
+ ...unit.duty ? { duty: unit.duty } : {},
18765
+ ...unit.todo ? { todo: { done: unit.todo.done, total: unit.todo.total, ...unit.todo.now ? { now: unit.todo.now } : {} } } : {},
18766
+ ...unit.monitors?.length ? { monitors: unit.monitors.map(monitor) } : {},
18767
+ ...train ? { train: { status: train.state, ...step ? { step: `${step.id} ${step.kind} ${step.name} ${step.status}${step.outcome ? ` ${step.outcome}` : ""}` } : {}, ...step?.status === "in_progress" && step.waits.length ? { waits: waitMessage(step.waits) } : {} } } : {},
18768
+ ...unit.subs?.length ? { subs: unit.subs.map((s2) => ({ name: s2.name, mark: s2.mark })) } : {}
18769
+ };
18770
+ }
18771
+ function createWatchRead(d) {
18772
+ const instance = randomBytes18(4).toString("hex"), holdMs = d.holdMs ?? HOLD_MS, readMs = d.readMs ?? READ_MS2;
18773
+ const timer = d.timer ?? ((ms3, fn) => {
18774
+ const t = setTimeout(fn, ms3);
18775
+ t.unref?.();
18776
+ return () => clearTimeout(t);
18777
+ });
18778
+ const holds = /* @__PURE__ */ new Set(), quiets = /* @__PURE__ */ new Map();
18779
+ let net, units = /* @__PURE__ */ new Map(), fed = -Infinity, reading, poll;
18780
+ const stampOf = (t) => Buffer.from(JSON.stringify([instance, t.hash, t.stalled, t.load])).toString("base64url");
18781
+ const toldOf = (since) => {
18782
+ if (!since || since.length > 512) return void 0;
18783
+ try {
18784
+ const [of, hash, stalled, load2] = JSON.parse(Buffer.from(since, "base64url").toString("utf8"));
18785
+ return of === instance && typeof hash === "string" && typeof stalled === "number" && Array.isArray(load2) && load2.every((x) => typeof x === "string") ? { hash, stalled, load: load2.slice(0, MAX_TOLD) } : void 0;
18786
+ } catch {
18787
+ return void 0;
18788
+ }
18789
+ };
18790
+ const follow = (key2, unit, at, asked3) => {
18791
+ const lines = new Map((unit.monitors ?? []).map((m) => [m.id, m.lines])), tick = unit.ticks?.at(-1)?.at, was = quiets.get(key2);
18792
+ if (!was) return void (asked3 !== void 0 && quiets.set(key2, { at, from: at, move: at, mark: unit.mark, note: unit.note, tick, lines, asked: asked3 }));
18793
+ const moved = was.mark !== unit.mark || was.note !== unit.note || was.tick !== tick || [...lines].some(([id, n]) => (was.lines.get(id) ?? -1) < n);
18794
+ if (moved) was.from = was.move = at;
18795
+ else if (at - was.at > GAP_MS) was.from = at;
18796
+ Object.assign(was, { at, mark: unit.mark, note: unit.note, tick, lines }, asked3 !== void 0 ? { asked: asked3 } : {});
18797
+ };
18798
+ const take = (next2) => {
18799
+ const at = d.now();
18800
+ [net, fed, units] = [next2, at, /* @__PURE__ */ new Map()];
18801
+ if (!holds.size && !quiets.size) return;
18802
+ for (const b of next2.bases) for (const unit of holdersOf(b)) if (!units.has(unit.key)) units.set(unit.key, { unit, .../* @__PURE__ */ ((train) => train ? { train } : {})(trainOf(next2, unit.key)) });
18803
+ for (const [key2, q] of quiets) {
18804
+ const seen = units.get(key2);
18805
+ if (at - q.asked > FORGET_MS) quiets.delete(key2);
18806
+ else if (seen) follow(key2, seen.unit, at);
18807
+ }
18808
+ for (const hold of [...holds]) {
18809
+ const reply3 = judge(hold, at, false);
18810
+ if (reply3) hold.done(reply3);
18811
+ }
18812
+ };
18813
+ const seenOf = (key2) => {
18814
+ if (net && !units.size) {
18815
+ for (const b of net.bases) for (const unit of holdersOf(b)) if (!units.has(unit.key)) units.set(unit.key, { unit, .../* @__PURE__ */ ((train) => train ? { train } : {})(trainOf(net, unit.key)) });
18816
+ }
18817
+ return units.get(key2);
18818
+ };
18819
+ const answer = (state, hold, at, seen, more = {}) => ({ ok: true, state, since: stampOf(hold.told), now: at, ...seen ? { unit: viewOf(seen, at) } : {}, ...more });
18820
+ const judge = (hold, at, arrival) => {
18821
+ const { q, told: told2 } = hold, seen = seenOf(q.key);
18822
+ if (!seen) {
18823
+ const found = d.net.lookup(q.key);
18824
+ if (found?.live) return void 0;
18825
+ if (!found && arrival) return { ok: false, error: `unknown key ${q.key}` };
18826
+ return answer("gone", hold, at, void 0, found?.successor ? { successor: found.successor } : {});
18827
+ }
18828
+ if (arrival) follow(q.key, seen.unit, fed, at);
18829
+ if (q.deadline !== void 0 && at >= q.deadline) return answer("expired", hold, at, seen);
18830
+ const over = (seen.unit.monitors ?? []).filter((m) => m.load && m.load.now > (q.loadMax ?? m.load.max)).map((m) => short3(m.id)).slice(0, MAX_TOLD);
18831
+ const fresh = over.filter((id) => !told2.load.includes(id)), hash = factsOf2(seen);
18832
+ told2.load = told2.load.filter((id) => over.includes(id));
18833
+ if (hash !== told2.hash) return told2.hash = hash, answer("changed", hold, at, seen);
18834
+ if (fresh.length) return told2.load = over, answer("load", hold, at, seen);
18835
+ const quiet = quiets.get(q.key);
18836
+ if (q.quietMs !== void 0 && quiet && quiet.at - quiet.from >= q.quietMs && told2.stalled !== quiet.move) return told2.stalled = quiet.move, answer("stalled", hold, at, seen);
18837
+ return void 0;
18838
+ };
18839
+ const readNow = () => reading ??= d.net.read().then((next2) => void (next2 !== net && take(next2)), () => {
18840
+ }).finally(() => reading = void 0);
18841
+ const beat = () => {
18842
+ poll = void 0;
18843
+ if (!holds.size) return;
18844
+ if (d.now() - fed >= readMs) void readNow();
18845
+ poll = timer(readMs, beat);
18846
+ };
18847
+ const stopRead = d.net.onRead((next2) => take(next2));
18848
+ return {
18849
+ /** One hold: answered at once when the stamp does not match the last reading, else by a reading, the deadline, or the hold's timer. */
18850
+ async read(q) {
18851
+ const last = net ? void 0 : d.net.last();
18852
+ if (last) take(last);
18853
+ else if (d.now() - fed >= 2 * readMs) await readNow();
18854
+ if (!net) return { ok: false, error: "the net could not be read; ask again" };
18855
+ const was = toldOf(q.since), hold = { q, told: was ?? { hash: "", stalled: 0, load: [] }, done() {
18856
+ }, cancel() {
18857
+ } };
18858
+ if (!seenOf(q.key) && d.net.lookup(q.key)?.live) await readNow();
18859
+ if (!seenOf(q.key) && d.net.lookup(q.key)?.live) return { ok: false, error: `unknown key ${q.key}` };
18860
+ const first2 = judge(hold, d.now(), true);
18861
+ if (first2) return first2;
18862
+ return new Promise((resolve10) => {
18863
+ const left = q.deadline !== void 0 ? q.deadline - d.now() : Infinity;
18864
+ const cancel = timer(Math.min(holdMs, left), () => hold.done(answer(left <= holdMs ? "expired" : "unchanged", hold, d.now(), seenOf(q.key))));
18865
+ hold.cancel = cancel;
18866
+ hold.done = (reply3) => {
18867
+ if (holds.delete(hold)) cancel(), resolve10(reply3);
18868
+ };
18869
+ holds.add(hold);
18870
+ poll ??= timer(readMs, beat);
18871
+ });
18872
+ },
18873
+ /** How many holds are open. */
18874
+ holds: () => holds.size,
18875
+ /** The server leaves: the timers stop and the open holds are left to their connections, which close with the socket. */
18876
+ stop() {
18877
+ stopRead();
18878
+ poll?.();
18879
+ poll = void 0;
18880
+ for (const hold of holds) hold.cancel();
18881
+ holds.clear();
18882
+ }
18883
+ };
18884
+ }
18885
+
18886
+ // src/server/watchreport.ts
18887
+ import { createHash as createHash16, randomUUID as randomUUID10 } from "node:crypto";
18888
+ import { readFileSync as readFileSync31, statSync as statSync13 } from "node:fs";
18889
+ import { basename as basename12, dirname as dirname16, sep as sep7 } from "node:path";
18890
+ var RATE_MS2 = 3e4;
18891
+ var MAX_TEXT4 = 2e3;
18892
+ var ID5 = /^[A-Za-z0-9_.:@-]{1,128}$/;
18893
+ var CONTROL7 = /[\p{Cc}\p{Cf}\u2028\u2029]/u;
18894
+ var no16 = (error) => ({ ok: false, error });
18895
+ var isFile = (path) => {
18896
+ try {
18897
+ return statSync13(path).isFile();
18898
+ } catch {
18899
+ return false;
18900
+ }
18901
+ };
18902
+ var hashOf = (text11) => createHash16("sha256").update(text11).digest("hex");
18903
+ function createWatchReport(d) {
18904
+ const last = /* @__PURE__ */ new Map();
18905
+ return {
18906
+ async report(q) {
18907
+ if (typeof q.text !== "string" || !q.text.trim() || q.text.length > MAX_TEXT4 || CONTROL7.test(q.text.replace(/[\n\t]/g, " "))) return no16(`text is 1 to ${MAX_TEXT4} plain characters`);
18908
+ const root = canonical2(d.sessionsDir), under2 = (path) => path !== void 0 && path.startsWith(root + sep7);
18909
+ const activity = canonical2(q.activityFile), session = canonical2(q.session), activityDir = activity && dirname16(activity), art = activityDir && dirname16(activityDir);
18910
+ if (!under2(activity) || !under2(session) || !art || basename12(activity) !== `${q.child}.json` || basename12(activityDir) !== "subagent-activity" || basename12(dirname16(art)) !== "artifacts" || !isFile(activity)) return no16("outside the sessions folder");
18911
+ const parent = basename12(art);
18912
+ const scripts = launchScripts(art).map((s2) => ({ ...s2, session: canonical2(s2.session) })), tie = scripts.find((s2) => s2.id === q.child && s2.session === session);
18913
+ if (!tie) return no16(`no launch script ties ${q.child} to that session`);
18914
+ let phase;
18915
+ try {
18916
+ phase = JSON.parse(readFileSync31(activity, "utf8"))?.phase;
18917
+ } catch {
18918
+ }
18919
+ if (phase === "done") return no16("that child is done");
18920
+ const written = isFile(session), agent = written ? agentOfSession(session) : void 0;
18921
+ const watchdog = agent !== void 0 ? agent === "watchdog" : written ? scripts.some((s2) => s2.session === session && s2.agent === "watchdog") : tie.agent === "watchdog";
18922
+ if (!watchdog) return no16("not a watchdog's session");
18923
+ const was = last.get(session), now = d.now(), text11 = hashOf(q.text);
18924
+ if (was && now - was.at < RATE_MS2) return no16(`rate: one report every ${RATE_MS2 / 1e3} s`);
18925
+ if (was?.text === text11) return no16("same text as the last report");
18926
+ const intercom = d.intercom();
18927
+ if (!intercom) return no16("pi-intercom is not connected");
18928
+ const mine = { at: now, text: text11 };
18929
+ if (last.size > 2e3) last.clear();
18930
+ last.set(session, mine);
18931
+ const back = (reply3) => {
18932
+ if (last.get(session) === mine) was ? last.set(session, was) : last.delete(session);
18933
+ return reply3;
18934
+ };
18935
+ let to;
18936
+ try {
18937
+ to = (await intercom.listSessions()).find((s2) => s2.id === parent);
18938
+ } catch (error) {
18939
+ return back(no16(`pi-intercom cannot list its sessions: ${error.message}`));
18940
+ }
18941
+ if (!to) return back({ ok: true, delivery: "gone" });
18942
+ const name2 = tie.script.endsWith(`-${q.child}.sh`) ? tie.script.slice(0, -`-${q.child}.sh`.length) : tie.script.replace(/-resume-[^-]*\.sh$/, "").replace(/\.sh$/, "");
18943
+ const message = stamp({ from: { name: `watchdog ${name2}`, id: q.child, role: "session" }, kind: "watch_report", scope: "session", to: [{ name: to.name ?? to.id, id: to.id, role: "session" }], reply: false }, q.text);
18944
+ let sent;
18945
+ try {
18946
+ sent = await intercom.send(to.id, { text: message, messageId: `watch-report-${randomUUID10()}` });
18947
+ } catch (error) {
18948
+ return back(no16(`not delivered: ${error.message}`));
18949
+ }
18950
+ const delivery = !sent.delivered ? void 0 : sent.delivery === "queued" ? "queued" : sent.delivery === void 0 || sent.delivery === "socket_delivered" ? "delivered" : void 0;
18951
+ d.log?.("watch-report", { child: q.child, parent, delivery: delivery ?? "failed" });
18952
+ if (!delivery) return back(no16(`not delivered: ${sent.reason ?? String(sent.delivery ?? "the broker did not take it")}`));
18953
+ return { ok: true, delivery };
18954
+ }
18955
+ };
18956
+ }
18957
+ function reportQuery(request) {
18958
+ const path = (v) => typeof v === "string" && v.length > 0 && v.length <= 4096 ? v : void 0;
18959
+ const session = path(request.session), activityFile = path(request.activityFile), child = typeof request.child === "string" && ID5.test(request.child) ? request.child : void 0;
18960
+ return session && activityFile && child ? { session, child, activityFile, text: request.text } : void 0;
18961
+ }
18962
+
18963
+ // src/server/watchdogops.ts
18964
+ var no17 = (error) => Promise.resolve({ ok: false, error });
18965
+ var number = (v) => typeof v === "number" && Number.isFinite(v);
18966
+ function watchdogReply(dog, request) {
18967
+ if (request.cmd !== "watch-read" && request.cmd !== "watch-report") return void 0;
18968
+ if (!dog) return no17("the server is still starting");
18969
+ if (request.cmd === "watch-report") {
18970
+ const q = reportQuery(request);
18971
+ return q ? dog.report.report(q) : no17("watch-report needs session, child, and activityFile");
18972
+ }
18973
+ const { key: key2, since, deadline, quietMs, loadMax } = request;
18974
+ if (typeof key2 !== "string" || key2.length < 1 || key2.length > 200) return no17("key is 1 to 200 characters");
18975
+ if (deadline !== void 0 && !(number(deadline) && deadline > 0)) return no17("deadline is a time in epoch ms");
18976
+ if (quietMs !== void 0 && !(number(quietMs) && quietMs >= 6e4)) return no17("quietMs is at least 60000");
18977
+ if (loadMax !== void 0 && !(number(loadMax) && loadMax > 0)) return no17("loadMax is a number over 0");
18978
+ return dog.read.read({ key: key2, ...typeof since === "string" ? { since } : {}, ...deadline !== void 0 ? { deadline } : {}, ...quietMs !== void 0 ? { quietMs } : {}, ...loadMax !== void 0 ? { loadMax } : {} });
18979
+ }
18980
+ function startWatchdog(o) {
18981
+ const read4 = createWatchRead({ net: o.net, now: o.now, ...o.over });
18982
+ o.stops.push(() => read4.stop());
18983
+ return { read: read4, report: createWatchReport({ sessionsDir: join43(o.env.PI_CODING_AGENT_DIR ?? join43(homedir12(), ".pi", "agent"), "sessions"), now: o.now, intercom: o.client, log: o.log }) };
18984
+ }
18985
+
18718
18986
  // src/server/stallops.ts
18719
- import { statSync as statSync13 } from "node:fs";
18987
+ import { statSync as statSync14 } from "node:fs";
18720
18988
 
18721
18989
  // src/server/stallwatch.ts
18722
- import { mkdirSync as mkdirSync14, readFileSync as readFileSync31 } from "node:fs";
18723
- import { basename as basename12, join as join43 } from "node:path";
18990
+ import { mkdirSync as mkdirSync14, readFileSync as readFileSync32 } from "node:fs";
18991
+ import { basename as basename13, join as join44 } from "node:path";
18724
18992
  var STALL_FILE = "stallwatch.json";
18725
18993
  var SAMPLE_MS = 6e4;
18726
18994
  var PAUSE_MS = 18e4;
@@ -18734,7 +19002,7 @@ var STALL_DEFAULTS = { enabled: true, cpuPercent: 75, cpuMinutes: 5, silentMinut
18734
19002
  function readStallWatch(stateDir) {
18735
19003
  let section;
18736
19004
  try {
18737
- section = JSON.parse(readFileSync31(join43(stateDir, "config.json"), "utf8")).stallWatch;
19005
+ section = JSON.parse(readFileSync32(join44(stateDir, "config.json"), "utf8")).stallWatch;
18738
19006
  } catch {
18739
19007
  }
18740
19008
  const found = typeof section === "object" && section !== null ? section : {};
@@ -18784,7 +19052,7 @@ var paneKey = (p) => `${p.pane}
18784
19052
  ${p.terminal ?? ""}`;
18785
19053
  var text8 = (v, max) => typeof v === "string" && v.length > 0 && v.length <= max ? v : void 0;
18786
19054
  function createStallWatch(d) {
18787
- const folder = join43(d.dir, "procs"), file2 = join43(folder, STALL_FILE), self = d.self ?? [process.pid];
19055
+ const folder = join44(d.dir, "procs"), file2 = join44(folder, STALL_FILE), self = d.self ?? [process.pid];
18788
19056
  const watched = /* @__PURE__ */ new Map();
18789
19057
  const unresolved = /* @__PURE__ */ new Map();
18790
19058
  let lastAt, on = false, busy = false, saved = "", loaded = false, samples = 0, askedLast;
@@ -18803,7 +19071,7 @@ function createStallWatch(d) {
18803
19071
  const load2 = () => {
18804
19072
  loaded = true;
18805
19073
  try {
18806
- const parsed = JSON.parse(readFileSync31(file2, "utf8"));
19074
+ const parsed = JSON.parse(readFileSync32(file2, "utf8"));
18807
19075
  for (const r of Array.isArray(parsed.watched) ? parsed.watched : []) {
18808
19076
  const o = r, i = o?.incident;
18809
19077
  if (!Number.isSafeInteger(o?.pid) || typeof o.started !== "string" || typeof o.pane !== "string") continue;
@@ -18820,7 +19088,7 @@ function createStallWatch(d) {
18820
19088
  kind,
18821
19089
  pid: w.pid,
18822
19090
  started: w.started,
18823
- session: w.session ?? (w.file ? basename12(w.file).replace(/\.jsonl$/, "") : "(unknown)"),
19091
+ session: w.session ?? (w.file ? basename13(w.file).replace(/\.jsonl$/, "") : "(unknown)"),
18824
19092
  ...w.name ? { name: w.name } : {},
18825
19093
  pane: w.pane,
18826
19094
  ...w.workspace ? { workspace: w.workspace } : {},
@@ -18974,7 +19242,7 @@ function startStall(o) {
18974
19242
  },
18975
19243
  mtime: (file2) => {
18976
19244
  try {
18977
- return statSync13(file2).mtimeMs;
19245
+ return statSync14(file2).mtimeMs;
18978
19246
  } catch {
18979
19247
  return void 0;
18980
19248
  }
@@ -18994,21 +19262,21 @@ function startStall(o) {
18994
19262
  }
18995
19263
 
18996
19264
  // src/server/watchops.ts
18997
- import { join as join49 } from "node:path";
19265
+ import { join as join50 } from "node:path";
18998
19266
 
18999
19267
  // src/reach.ts
19000
- import { randomUUID as randomUUID10 } from "node:crypto";
19268
+ import { randomUUID as randomUUID11 } from "node:crypto";
19001
19269
 
19002
19270
  // src/autostate.ts
19003
- import { createHash as createHash15 } from "node:crypto";
19004
- import { readFileSync as readFileSync32 } from "node:fs";
19005
- import { join as join44 } from "node:path";
19271
+ import { createHash as createHash17 } from "node:crypto";
19272
+ import { readFileSync as readFileSync33 } from "node:fs";
19273
+ import { join as join45 } from "node:path";
19006
19274
  var AUTO_FILE = "auto.json";
19007
19275
  var OWN_FILE = "auto-own.json";
19008
19276
  var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
19009
19277
  var text9 = (v, max) => typeof v === "string" ? v.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max) : "";
19010
- var hashOf = (s2) => createHash15("sha256").update(JSON.stringify([s2.v, s2.rev, s2.on, s2.since ?? null, s2.by])).digest("hex");
19011
- var seal = (s2) => ({ ...s2, hash: hashOf(s2) });
19278
+ var hashOf2 = (s2) => createHash17("sha256").update(JSON.stringify([s2.v, s2.rev, s2.on, s2.since ?? null, s2.by])).digest("hex");
19279
+ var seal = (s2) => ({ ...s2, hash: hashOf2(s2) });
19012
19280
  function requesterOf(v) {
19013
19281
  if (!isRecord(v)) return void 0;
19014
19282
  const out = { ...text9(v.session, 80) ? { session: text9(v.session, 80) } : {}, ...text9(v.pane, 80) ? { pane: text9(v.pane, 80) } : {}, ...Number.isInteger(v.pid) && v.pid > 0 ? { pid: v.pid } : {} };
@@ -19031,7 +19299,7 @@ function parseAuto(raw) {
19031
19299
  const by = byOf(j.by);
19032
19300
  if (!by || j.since !== void 0 && (typeof j.since !== "string" || Number.isNaN(Date.parse(j.since)))) return void 0;
19033
19301
  const state = { v: 1, rev: j.rev, on: j.on, ...j.since ? { since: j.since } : {}, by, hash: j.hash };
19034
- return hashOf(state) === state.hash ? state : void 0;
19302
+ return hashOf2(state) === state.hash ? state : void 0;
19035
19303
  }
19036
19304
  function pendingOf2(v) {
19037
19305
  if (!isRecord(v) || typeof v.id !== "string" || !Number.isFinite(v.at) || !Number.isFinite(v.expires)) return void 0;
@@ -19055,7 +19323,7 @@ function parseOwn(raw) {
19055
19323
  }
19056
19324
  var read3 = (dir, name2) => {
19057
19325
  try {
19058
- return readFileSync32(join44(dir, name2), "utf8");
19326
+ return readFileSync33(join45(dir, name2), "utf8");
19059
19327
  } catch {
19060
19328
  return void 0;
19061
19329
  }
@@ -19108,7 +19376,7 @@ var clock = (iso6) => {
19108
19376
  var REPORT_FILE = "auto-report.json";
19109
19377
  function reportSummary(dir) {
19110
19378
  try {
19111
- const r = JSON.parse(readFileSync32(join44(dir, REPORT_FILE), "utf8"));
19379
+ const r = JSON.parse(readFileSync33(join45(dir, REPORT_FILE), "utf8"));
19112
19380
  if (r.v !== 1 || typeof r.since !== "string" || typeof r.until !== "string" || !Array.isArray(r.parked) || !Array.isArray(r.lines)) return void 0;
19113
19381
  return { since: r.since, until: r.until, off: String(r.off ?? ""), parked: r.parked.length, towers: new Set(r.parked.map((p) => p.workspace)).size, cancels: r.lines.filter((l) => l.kind !== "re-asked").reduce((n, l) => n + (l.count ?? 1), 0), decided: r.decided?.length ?? 0, stillWaiting: r.stillWaiting?.length ?? 0 };
19114
19382
  } catch {
@@ -19225,7 +19493,7 @@ function createReach({ pi, cfg, s: s2, guiDir, me, role, tell }, server = {
19225
19493
  ctx: () => makeCtx({ slot: slotOf(cfg.stateDir ?? guiDir, cfg.env), version: VERSION, cli: serverCli(), by: `session "${(s2.ownName || me() || "unnamed").replace(/["\n]/g, " ")}" (${me().slice(0, 8) || "no id"})`, env: cfg.env, now: cfg.now })
19226
19494
  }, limits = {}) {
19227
19495
  const { run: run3, api: api2, sleep: sleep2 } = cfg;
19228
- const nonce = randomUUID10().slice(0, 8);
19496
+ const nonce = randomUUID11().slice(0, 8);
19229
19497
  let requests = 0, toldStopped = false;
19230
19498
  const sendOnce = (to, message, requestId) => new Promise((resolve10) => {
19231
19499
  const done2 = (result2) => {
@@ -19552,8 +19820,8 @@ function allyTools(level) {
19552
19820
  }
19553
19821
 
19554
19822
  // src/server/towermemory.ts
19555
- import { readFileSync as readFileSync33 } from "node:fs";
19556
- import { join as join45 } from "node:path";
19823
+ import { readFileSync as readFileSync34 } from "node:fs";
19824
+ import { join as join46 } from "node:path";
19557
19825
 
19558
19826
  // src/server/waitcard.ts
19559
19827
  var CARD = { happened: 160, do: 160, url: 300, command: 300, commandLines: 4, after: 160, label: 24, then: 120, name: 60, from: 200, optionsMin: 2, optionsMax: 4, reason: 120, dueMin: 5, dueMax: 7 * 24 * 60 };
@@ -19743,7 +20011,7 @@ function tidy2(what, text11, max) {
19743
20011
  if (chars2(out) > max) throw new Error(`${what} is too long: at most ${max} characters`);
19744
20012
  return out;
19745
20013
  }
19746
- var fileOf2 = (slot, workspace) => join45(towerDir(slot, workspace), "memory.json");
20014
+ var fileOf2 = (slot, workspace) => join46(towerDir(slot, workspace), "memory.json");
19747
20015
  var isEntry = (e) => {
19748
20016
  const v = e;
19749
20017
  return typeof v === "object" && v !== null && typeof v.id === "string" && /^[SDW]\d+$/.test(v.id) && v.id[0] === LETTER[v.kind] && typeof v.text === "string" && (v.by === "boss" || v.by === "run") && typeof v.at === "string" && (v.kind !== "wait" || ["open", "answered", "resolved", "expired"].includes(String(v.state)));
@@ -19755,7 +20023,7 @@ var isProposal = (e) => {
19755
20023
  function loadMemory(slot, workspace) {
19756
20024
  let text11;
19757
20025
  try {
19758
- text11 = readFileSync33(fileOf2(slot, workspace), "utf8");
20026
+ text11 = readFileSync34(fileOf2(slot, workspace), "utf8");
19759
20027
  } catch (cause) {
19760
20028
  return cause.code === "ENOENT" ? { memory: emptyMemory() } : { memory: emptyMemory(), problem: `memory.json cannot be read (${cause.code ?? "unknown"})` };
19761
20029
  }
@@ -20037,10 +20305,10 @@ var memoryView = (m) => ({
20037
20305
  entries: m.entries.map((e) => ({ id: e.id, kind: e.kind, text: e.text, by: e.by, via: e.via, at: e.at, ...e.for ? { for: e.for } : {}, ...e.on ? { on: e.on.name } : {}, ...e.state ? { state: e.state } : {}, ...e.due ? { due: e.due } : {}, ...e.answered ? { answered: e.answered } : {}, ...e.outcome ? { outcome: e.outcome } : {}, ...e.ended ? { ended: e.ended } : {}, ...e.card ? { card: e.card } : {}, ...e.press ? { press: e.press } : {}, ...e.parked ? { parked: true } : {}, ...e.listed ? { listed: true } : {} }))
20038
20306
  });
20039
20307
  function memoryRequest(slot, workspace, now, json3, log) {
20040
- const op = json3.op, no17 = (status, error, reason, extra = {}) => ({ status, body: { error, reason, ...extra } });
20308
+ const op = json3.op, no19 = (status, error, reason, extra = {}) => ({ status, body: { error, reason, ...extra } });
20041
20309
  if (op === "read") {
20042
20310
  const { memory, problem } = readMemory(slot, workspace, now);
20043
- return problem ? no17(409, "unreadable", problem) : { status: 200, body: memoryView(memory) };
20311
+ return problem ? no19(409, "unreadable", problem) : { status: 200, body: memoryView(memory) };
20044
20312
  }
20045
20313
  const change = {
20046
20314
  add: (m) => {
@@ -20055,17 +20323,17 @@ function memoryRequest(slot, workspace, now, json3, log) {
20055
20323
  confirm: (m) => confirmProposal(m, now, json3.proposal),
20056
20324
  reject: (m) => rejectProposal(m, json3.proposal)
20057
20325
  };
20058
- if (typeof op !== "string" || !Object.hasOwn(change, op)) return no17(400, "bad_request", "op is read, add, edit, delete, resolve, drop, answer, confirm, or reject");
20326
+ if (typeof op !== "string" || !Object.hasOwn(change, op)) return no19(400, "bad_request", "op is read, add, edit, delete, resolve, drop, answer, confirm, or reject");
20059
20327
  const byId = op === "reject" || op === "drop" || op === "answer";
20060
- if (!byId && (typeof json3.rev !== "number" || !Number.isInteger(json3.rev))) return no17(400, "bad_request", "A change names the rev it read");
20328
+ if (!byId && (typeof json3.rev !== "number" || !Number.isInteger(json3.rev))) return no19(400, "bad_request", "A change names the rev it read");
20061
20329
  try {
20062
20330
  const done2 = updateMemory(slot, workspace, now, change[op], byId ? void 0 : json3.rev);
20063
20331
  log?.line("tower-memory", { workspace, op, by: "boss", ...done2.value ? { id: done2.value.id } : {}, ...op === "confirm" ? { proposal: String(json3.proposal) } : {} });
20064
20332
  return { status: 200, body: { ...memoryView(done2.memory), ...done2.value ? { id: done2.value.id } : {} } };
20065
20333
  } catch (cause) {
20066
20334
  const error = cause;
20067
- if (error.code === "rev") return no17(409, "rev", "The memory changed since you read it; it is shown again.", memoryView(error.memory));
20068
- return error instanceof Refused ? no17(409, "refused", error.message) : no17(/memory\.json/.test(error.message) ? 409 : 400, /memory\.json/.test(error.message) ? "unreadable" : "bad_request", error.message);
20335
+ if (error.code === "rev") return no19(409, "rev", "The memory changed since you read it; it is shown again.", memoryView(error.memory));
20336
+ return error instanceof Refused ? no19(409, "refused", error.message) : no19(/memory\.json/.test(error.message) ? 409 : 400, /memory\.json/.test(error.message) ? "unreadable" : "bad_request", error.message);
20069
20337
  }
20070
20338
  }
20071
20339
  var str9 = (args, name2) => {
@@ -20178,7 +20446,7 @@ var plural = (n, one4, many = `${one4}s`) => `${n} ${n === 1 ? one4 : many}`;
20178
20446
  var openWait = (w) => !w.state && !w.answered;
20179
20447
  var movedAt = (t) => Math.max(Date.parse(t.updated ?? "") || 0, ...t.steps.map((s2) => s2.status === "in_progress" && s2.gate ? Date.parse(s2.gate.updated) || 0 : 0));
20180
20448
  var told = (n, since) => n !== void 0 && n.status === "delivered" && n.at !== void 0 && Date.parse(n.at) > since;
20181
- function factsOf2(net, x) {
20449
+ function factsOf3(net, x) {
20182
20450
  const bases = net.bases.filter((b) => !b.box), where = /* @__PURE__ */ new Map(), names = /* @__PURE__ */ new Map();
20183
20451
  const place = (u, base) => (where.set(u.key, base), names.set(u.key, u.name), u.subs.forEach((c) => place(c, base)));
20184
20452
  for (const b of bases) b.tabs.forEach((t) => t.units.forEach((u) => place(u, b.id))), b.outside.forEach((u) => place(u, b.id)), b.tower && (where.set(b.tower.key, b.id), b.tower.subs.forEach((c) => place(c, b.id)));
@@ -20491,15 +20759,15 @@ ${why}`, d.log("watch-skipped", { why });
20491
20759
  }
20492
20760
 
20493
20761
  // src/server/headasks.ts
20494
- import { readFileSync as readFileSync34 } from "node:fs";
20495
- import { join as join46 } from "node:path";
20762
+ import { readFileSync as readFileSync35 } from "node:fs";
20763
+ import { join as join47 } from "node:path";
20496
20764
  var ASK_OPEN_MS = 24 * 36e5;
20497
20765
  var ASK_CAP = 40;
20498
20766
  var ASK_KEEP = 100;
20499
20767
  var FIRST = 120;
20500
20768
  var TEXT_KEEP = 1500;
20501
20769
  var GROUP_MS = 6e4;
20502
- var fileOf3 = (slot) => join46(towerDir(slot, HEAD_KEY), "asks.json");
20770
+ var fileOf3 = (slot) => join47(towerDir(slot, HEAD_KEY), "asks.json");
20503
20771
  var cut4 = (text11) => {
20504
20772
  const t = (text11 ?? "").trim();
20505
20773
  return t ? Array.from(t).slice(0, TEXT_KEEP).join("") : void 0;
@@ -20515,7 +20783,7 @@ function clean4(a) {
20515
20783
  }
20516
20784
  function load(slot) {
20517
20785
  try {
20518
- const f = JSON.parse(readFileSync34(fileOf3(slot), "utf8"));
20786
+ const f = JSON.parse(readFileSync35(fileOf3(slot), "utf8"));
20519
20787
  const asks = Array.isArray(f.asks) ? f.asks.filter(valid2).map(clean4) : [];
20520
20788
  return { next: Number.isInteger(f.next) && f.next >= 1 ? f.next : 1 + Math.max(0, ...asks.map((a) => Number(a.id.slice(1)))), asks };
20521
20789
  } catch {
@@ -20603,23 +20871,23 @@ function closeAsk(slot, id) {
20603
20871
  var asked2 = (slot, now, workspace, id) => openAsks(slot, now).some((a) => a.id === id && a.workspace === workspace);
20604
20872
 
20605
20873
  // src/server/headnet.ts
20606
- import { closeSync as closeSync9, openSync as openSync9, readSync as readSync2, statSync as statSync14 } from "node:fs";
20874
+ import { closeSync as closeSync9, openSync as openSync9, readSync as readSync2, statSync as statSync15 } from "node:fs";
20607
20875
 
20608
20876
  // src/server/headchapters.ts
20609
20877
  import { open as open7 } from "node:fs/promises";
20610
- import { readFileSync as readFileSync36 } from "node:fs";
20611
- import { join as join48 } from "node:path";
20878
+ import { readFileSync as readFileSync37 } from "node:fs";
20879
+ import { join as join49 } from "node:path";
20612
20880
 
20613
20881
  // src/server/bossconv.ts
20614
- import { lstatSync as lstatSync11, readFileSync as readFileSync35, realpathSync as realpathSync10, rmSync as rmSync13 } from "node:fs";
20615
- import { homedir as homedir12 } from "node:os";
20616
- import { isAbsolute as isAbsolute9, join as join47, relative as relative5, resolve as resolve8, sep as sep7 } from "node:path";
20882
+ import { lstatSync as lstatSync11, readFileSync as readFileSync36, realpathSync as realpathSync10, rmSync as rmSync13 } from "node:fs";
20883
+ import { homedir as homedir13 } from "node:os";
20884
+ import { isAbsolute as isAbsolute9, join as join48, relative as relative5, resolve as resolve8, sep as sep8 } from "node:path";
20617
20885
  var BOSS_FILE_MAX = 4 * 1024 * 1024;
20618
20886
  var BOSS_FILE_DAYS = 7;
20619
- var pointerFile = (slot, workspace) => join47(towerDir(slot, workspace), "boss-session.json");
20887
+ var pointerFile = (slot, workspace) => join48(towerDir(slot, workspace), "boss-session.json");
20620
20888
  function readPointer(slot, workspace) {
20621
20889
  try {
20622
- const p = JSON.parse(readFileSync35(pointerFile(slot, workspace), "utf8"));
20890
+ const p = JSON.parse(readFileSync36(pointerFile(slot, workspace), "utf8"));
20623
20891
  return typeof p.file === "string" && typeof p.run === "string" && typeof p.startedAt === "string" && typeof p.lastAt === "string" && Number.isFinite(Date.parse(p.lastAt)) && Number.isInteger(p.turns) && p.turns >= 0 ? { file: p.file, run: p.run, startedAt: p.startedAt, lastAt: p.lastAt, turns: p.turns, ...p.fresh === true ? { fresh: true } : {} } : void 0;
20624
20892
  } catch {
20625
20893
  return void 0;
@@ -20629,7 +20897,7 @@ function writePointer(slot, workspace, pointer) {
20629
20897
  ensureDir(towerDir(slot, workspace));
20630
20898
  writeDurable(pointerFile(slot, workspace), pointer);
20631
20899
  }
20632
- var sessionsRoot = (env = process.env) => join47(env.PI_CODING_AGENT_DIR || join47(homedir12(), ".pi", "agent"), "sessions");
20900
+ var sessionsRoot = (env = process.env) => join48(env.PI_CODING_AGENT_DIR || join48(homedir13(), ".pi", "agent"), "sessions");
20633
20901
  var real2 = (path) => {
20634
20902
  try {
20635
20903
  return realpathSync10(path);
@@ -20640,7 +20908,7 @@ var real2 = (path) => {
20640
20908
  function underRoot(file2, root) {
20641
20909
  if (!file2.endsWith(".jsonl")) return void 0;
20642
20910
  const base = real2(root), path = real2(file2);
20643
- return base && path && path.startsWith(base + sep7) ? path : void 0;
20911
+ return base && path && path.startsWith(base + sep8) ? path : void 0;
20644
20912
  }
20645
20913
  function linkIn(file2, root) {
20646
20914
  const abs = resolve8(file2);
@@ -20649,8 +20917,8 @@ function linkIn(file2, root) {
20649
20917
  const rel = relative5(base, abs);
20650
20918
  if (rel.startsWith("..") || isAbsolute9(rel)) continue;
20651
20919
  let at = base;
20652
- for (const part3 of rel.split(sep7)) {
20653
- at = join47(at, part3);
20920
+ for (const part3 of rel.split(sep8)) {
20921
+ at = join48(at, part3);
20654
20922
  try {
20655
20923
  if (lstatSync11(at).isSymbolicLink()) return true;
20656
20924
  } catch {
@@ -20688,10 +20956,10 @@ var KEEP2 = 50;
20688
20956
  var RECAP_LINES = 8;
20689
20957
  var RECAP_CHARS = 2e3;
20690
20958
  var TAIL_BYTES = 262144;
20691
- var chaptersFile = (slot) => join48(towerDir(slot, HEAD_KEY), "chapters.json");
20959
+ var chaptersFile = (slot) => join49(towerDir(slot, HEAD_KEY), "chapters.json");
20692
20960
  function readChapters(slot) {
20693
20961
  try {
20694
- const list2 = JSON.parse(readFileSync36(chaptersFile(slot), "utf8"));
20962
+ const list2 = JSON.parse(readFileSync37(chaptersFile(slot), "utf8"));
20695
20963
  return Array.isArray(list2) ? list2.filter((c) => Number.isInteger(c?.n) && typeof c.file === "string" && typeof c.from === "string" && typeof c.why === "string") : [];
20696
20964
  } catch {
20697
20965
  return [];
@@ -20746,7 +21014,7 @@ function lastWords(file2) {
20746
21014
  let fd;
20747
21015
  try {
20748
21016
  fd = openSync9(file2, "r");
20749
- const { size: size2 } = statSync14(file2), start = Math.max(0, size2 - TAIL4), buf = Buffer.alloc(size2 - start);
21017
+ const { size: size2 } = statSync15(file2), start = Math.max(0, size2 - TAIL4), buf = Buffer.alloc(size2 - start);
20750
21018
  readSync2(fd, buf, 0, buf.length, start);
20751
21019
  const rows = buf.toString("utf8").split("\n");
20752
21020
  if (start) rows.shift();
@@ -20768,7 +21036,7 @@ function headSeam(slot, now) {
20768
21036
  const words2 = (file2) => {
20769
21037
  if (!file2) return {};
20770
21038
  try {
20771
- const s2 = statSync14(file2), sig = `${s2.size}:${s2.mtimeMs}`, kept = seen.get(file2);
21039
+ const s2 = statSync15(file2), sig = `${s2.size}:${s2.mtimeMs}`, kept = seen.get(file2);
20772
21040
  if (kept?.sig === sig) return kept.words;
20773
21041
  const read4 = lastWords(file2);
20774
21042
  seen.set(file2, { sig, words: read4 });
@@ -20879,7 +21147,7 @@ function startAutoWatch(o) {
20879
21147
  run: o.run,
20880
21148
  ...o.world ? { world: o.world } : {},
20881
21149
  sessions: o.sessions,
20882
- board: boardSeam({ dir: join49(o.slot.stateDir, "board"), now: o.now }),
21150
+ board: boardSeam({ dir: join50(o.slot.stateDir, "board"), now: o.now }),
20883
21151
  trainyard: trainyardSeam({ env: o.env, stateDir: o.slot.stateDir, now: o.now, ...o.book ? { book: o.book } : {} })
20884
21152
  });
20885
21153
  let stopped = false;
@@ -20890,7 +21158,7 @@ function startAutoWatch(o) {
20890
21158
  auto: o.auto,
20891
21159
  // The head tower is woken where the server stands in for it; a service that is held starts no run, so its notices would only pile up.
20892
21160
  head: () => ((row2) => row2 ? { workspace: row2.workspace, ...row2.service?.state === "held" ? { held: true } : {} } : void 0)(o.towers()?.head.status()),
20893
- facts: async (input) => factsOf2(await net.read(), { ...input, stalls: o.stalls() }),
21161
+ facts: async (input) => factsOf3(await net.read(), { ...input, stalls: o.stalls() }),
20894
21162
  asks: () => asksOf(o.slot, o.now),
20895
21163
  waiting: (workspace) => o.towers()?.runs.noticeWaits(workspace, WATCH_KEY) ?? false,
20896
21164
  noticeState: (_workspace, key2) => noticeState(o.towers, { key: key2 }),
@@ -20907,27 +21175,27 @@ var ALLY_LINK_OPS = ["confirm-request", "forget-confirm"];
20907
21175
  var OWN_TOKEN = /* @__PURE__ */ new Set(["run-poll", "run-taken", "run-done", "run-boss", "run-release", "run-file", "run-tool"]);
20908
21176
  var LOCAL_ONLY_OWN_WORKSPACE = /* @__PURE__ */ new Set(["open-main", "close-main"]);
20909
21177
  var LOCAL_READS = /* @__PURE__ */ new Set(["status"]);
20910
- var no16 = (error) => ({ ok: false, error });
21178
+ var no18 = (error) => ({ ok: false, error });
20911
21179
  var opOf = (body2) => typeof body2 === "object" && body2 !== null ? body2.op : void 0;
20912
21180
  function gateRun(request, run3) {
20913
21181
  const { cmd } = request;
20914
21182
  if (OWN_TOKEN.has(cmd)) return { ok: true };
20915
21183
  if (run3.kind === "ally") {
20916
21184
  if (cmd === "link" && ALLY_LINK_OPS.includes(opOf(request.body))) return { ok: true };
20917
- return no16(`an ally run's token may not ask for ${cmd}`);
21185
+ return no18(`an ally run's token may not ask for ${cmd}`);
20918
21186
  }
20919
21187
  if (LOCAL_READS.has(cmd)) return { ok: true };
20920
- if (run3.kind === "head") return no16(`the head tower's token may not ask for ${cmd}: it forwards to the towers, which open and close mains`);
20921
- if (LOCAL_ONLY_OWN_WORKSPACE.has(cmd)) return request.workspace === run3.workspace ? { ok: true } : no16(`a run token may ${cmd} only for its own workspace (${run3.workspace})`);
21188
+ if (run3.kind === "head") return no18(`the head tower's token may not ask for ${cmd}: it forwards to the towers, which open and close mains`);
21189
+ if (LOCAL_ONLY_OWN_WORKSPACE.has(cmd)) return request.workspace === run3.workspace ? { ok: true } : no18(`a run token may ${cmd} only for its own workspace (${run3.workspace})`);
20922
21190
  if (cmd === "link") {
20923
21191
  const op = opOf(request.body);
20924
- return LOCAL_LINK_OPS.includes(op) ? { ok: true } : no16(`a run token may not send the link request ${String(op)}: the team is the boss's to administer`);
21192
+ return LOCAL_LINK_OPS.includes(op) ? { ok: true } : no18(`a run token may not send the link request ${String(op)}: the team is the boss's to administer`);
20925
21193
  }
20926
- return no16(`a run token may not ask for ${cmd}`);
21194
+ return no18(`a run token may not ask for ${cmd}`);
20927
21195
  }
20928
21196
 
20929
21197
  // src/link/unitstatus.ts
20930
- import { createHash as createHash16 } from "node:crypto";
21198
+ import { createHash as createHash18 } from "node:crypto";
20931
21199
  var STATUS_EVERY_MS = 6e4;
20932
21200
  var TOLD_MAX = 512;
20933
21201
  var UnitReporter = class {
@@ -20987,7 +21255,7 @@ function runNotice(s2) {
20987
21255
  const who2 = s2.ally ? "An ally run" : "A run";
20988
21256
  if (s2.kind === "revoked") return { key: `revoked/${s2.main}/${s2.ended ? "ended" : s2.manual ? "manual" : "pending"}`, notice: { kind: s2.ended ? "main-revoked" : "main-revoke-pending", unit: allyLabel(s2.label), text: s2.text }, scope };
20989
21257
  if (s2.kind === "main-stop") return { key: s2.outcome === "refused" ? `stop-refused/${s2.stopId}` : `stop/${s2.main}/${s2.outcome}`, notice: { kind: { pending: "main-stop-pending", stopped: "main-stopped", manual: "main-stop-manual", refused: "unit-stop-refused" }[s2.outcome], unit: allyLabel(s2.label), text: s2.text }, scope };
20990
- if (s2.kind === "refused") return { key: `refused/${s2.workspace}/${createHash16("sha256").update(s2.text).digest("hex").slice(0, 16)}`, notice: { kind: "run-refused", unit: allyLabel(s2.label), text: s2.text }, scope };
21258
+ if (s2.kind === "refused") return { key: `refused/${s2.workspace}/${createHash18("sha256").update(s2.text).digest("hex").slice(0, 16)}`, notice: { kind: "run-refused", unit: allyLabel(s2.label), text: s2.text }, scope };
20991
21259
  const trust = s2.detail?.startsWith("No trust decision");
20992
21260
  const kind = trust ? "trust-unanswered" : s2.outcome === "quit" ? "run-quit" : s2.outcome === "timeout" ? "run-timeout" : "run-crashed";
20993
21261
  return { key: `run/${s2.run}`, notice: { kind, unit: allyLabel(s2.label), text: `${who2} ${s2.outcome === "quit" ? "was quit" : s2.outcome === "timeout" ? "timed out" : "crashed"}${s2.detail ? `: ${s2.detail}` : ""}` }, scope };
@@ -21039,13 +21307,13 @@ function createUnitStop(d) {
21039
21307
  }
21040
21308
 
21041
21309
  // src/server/towers.ts
21042
- import { createHash as createHash20 } from "node:crypto";
21043
- import { mkdirSync as mkdirSync16, readdirSync as readdirSync16, readFileSync as readFileSync38, rmSync as rmSync14 } from "node:fs";
21044
- import { join as join55 } from "node:path";
21310
+ import { createHash as createHash22 } from "node:crypto";
21311
+ import { mkdirSync as mkdirSync16, readdirSync as readdirSync16, readFileSync as readFileSync39, rmSync as rmSync14 } from "node:fs";
21312
+ import { join as join56 } from "node:path";
21045
21313
 
21046
21314
  // src/closemain.ts
21047
- import { randomUUID as randomUUID11 } from "node:crypto";
21048
- var CONTROL7 = "straw-boss/control";
21315
+ import { randomUUID as randomUUID12 } from "node:crypto";
21316
+ var CONTROL8 = "straw-boss/control";
21049
21317
  var ASK_MS2 = 1e4;
21050
21318
  var RETRY_MS3 = 15e3;
21051
21319
  var RETRY_STEP_MS = 3e3;
@@ -21056,13 +21324,13 @@ function createCloseMain({ pi, cfg, s: s2, me }, { closeSelf, check, turn }) {
21056
21324
  const answers2 = /* @__PURE__ */ new Map();
21057
21325
  const send = (payload) => channel?.publish({ version: 1, ...payload }, { audience: "capable" });
21058
21326
  const judge = async (from, interrupt = false) => {
21059
- const no17 = (reason) => ({ reason });
21060
- if (s2.isTower) return no17("this session is a tower");
21061
- if (!s2.joined) return no17("this session has not joined the net");
21327
+ const no19 = (reason) => ({ reason });
21328
+ if (s2.isTower) return no19("this session is a tower");
21329
+ if (!s2.joined) return no19("this session has not joined the net");
21062
21330
  const [all, workspace] = await Promise.all([panes(run3), workspaces(run3).then((list2) => list2.find((w) => w.workspace_id === s2.at.workspaceId))]);
21063
21331
  const mine = all.find((p) => p.pane_id === s2.at.paneId);
21064
- if (!mine?.tokens?.sb_opened_by) return no17("no tower opened this main, so only the boss closes it");
21065
- if (!workspace?.tokens?.tower || workspace.tokens.tower !== from) return no17("the request is not from the tower of this workspace");
21332
+ if (!mine?.tokens?.sb_opened_by) return no19("no tower opened this main, so only the boss closes it");
21333
+ if (!workspace?.tokens?.tower || workspace.tokens.tower !== from) return no19("the request is not from the tower of this workspace");
21066
21334
  const running = subagents(mine, all, cfg.now()).filter((row2) => !row2.ended).length;
21067
21335
  const subs = running && `${running} subagent${running > 1 ? "s are" : " is"} running`;
21068
21336
  if (interrupt && turn?.running()) {
@@ -21087,7 +21355,7 @@ function createCloseMain({ pi, cfg, s: s2, me }, { closeSelf, check, turn }) {
21087
21355
  if (p.type === "close-main-result" && p.to === me() && typeof p.accepted === "boolean") answers2.set(p.reqId, { from, accepted: p.accepted, ...typeof p.reason === "string" ? { reason: p.reason.slice(0, 300) } : {}, ...p.busy === true ? { busy: true } : {} });
21088
21356
  };
21089
21357
  const ask = async (main, interrupt) => {
21090
- const reqId = randomUUID11().slice(0, 12);
21358
+ const reqId = randomUUID12().slice(0, 12);
21091
21359
  send({ type: "close-main", to: main, reqId, ...interrupt ? { interrupt: true } : {} });
21092
21360
  const got = await waitFor(sleep2, () => answers2.get(reqId)?.from === main ? answers2.get(reqId) : void 0, ASK_MS2, 100);
21093
21361
  answers2.delete(reqId);
@@ -21097,7 +21365,7 @@ function createCloseMain({ pi, cfg, s: s2, me }, { closeSelf, check, turn }) {
21097
21365
  /** Every tower, and every main a tower opened, hears and answers asks; registering twice is a no-op. */
21098
21366
  register() {
21099
21367
  if (channel) return;
21100
- pi.events.emit(REGISTER, { namespace: CONTROL7, ownerEligible: false, onReady: (c) => channel = c, onEvent });
21368
+ pi.events.emit(REGISTER, { namespace: CONTROL8, ownerEligible: false, onReady: (c) => channel = c, onEvent });
21101
21369
  if (!channel) throw new Error("pi-intercom is not loaded (Straw Boss needs pi-intercom >= 0.17.1)");
21102
21370
  },
21103
21371
  /** The tower's side: a main this workspace's tower opened, by intercom name or session id. */
@@ -21164,13 +21432,13 @@ function createDigest(run3, now) {
21164
21432
  }
21165
21433
 
21166
21434
  // src/opener.ts
21167
- import { createHash as createHash17, randomUUID as randomUUID12 } from "node:crypto";
21435
+ import { createHash as createHash19, randomUUID as randomUUID13 } from "node:crypto";
21168
21436
  import { existsSync as existsSync9 } from "node:fs";
21169
- import { join as join51 } from "node:path";
21437
+ import { join as join52 } from "node:path";
21170
21438
 
21171
21439
  // src/integrator.ts
21172
21440
  import { existsSync as existsSync8, readdirSync as readdirSync15 } from "node:fs";
21173
- import { join as join50 } from "node:path";
21441
+ import { join as join51 } from "node:path";
21174
21442
  var INTEGRATOR = "integrator";
21175
21443
  var MAX_OPENED_INTEGRATORS = 2;
21176
21444
  var MARK2 = "integ:";
@@ -21181,7 +21449,7 @@ var integratorOf = (token) => {
21181
21449
  };
21182
21450
  function ledgerProjects(stateDir, app) {
21183
21451
  try {
21184
- return readdirSync15(join50(stateDir, "trains")).filter((project) => isName(project) && existsSync8(join50(stateDir, "trains", project, `${app}.json`)));
21452
+ return readdirSync15(join51(stateDir, "trains")).filter((project) => isName(project) && existsSync8(join51(stateDir, "trains", project, `${app}.json`)));
21185
21453
  } catch {
21186
21454
  return [];
21187
21455
  }
@@ -21320,7 +21588,7 @@ function opener(env) {
21320
21588
  const everywhere = await panes(run3);
21321
21589
  const codes = new Set(everywhere.flatMap((p) => ((t) => t && t.project === train.project ? [t.code] : [])(trainFromToken(p.tokens?.sb_train))));
21322
21590
  if (codes.has(train.code)) throw new OpenLimitError(`The ${trainLabel(train.code)} of project ${train.project} is already open; a code is used once`);
21323
- if (env.stateDir && existsSync9(join51(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`);
21591
+ if (env.stateDir && existsSync9(join52(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`);
21324
21592
  const max = (env.maxTrains ?? readMaxTrains)(dir);
21325
21593
  if (typeof max !== "number") throw new OpenLimitError(max.refusal);
21326
21594
  const config = (env.appsRefusal ?? openRefusal)(dir, appFromRequest(request));
@@ -21359,7 +21627,7 @@ function opener(env) {
21359
21627
  const { tabId, paneId } = await createTab(run3, workspace.workspace_id, dir, [`STRAW_BOSS_ROLE=${train ? TRAIN : "main"}`], label);
21360
21628
  try {
21361
21629
  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 } : {} });
21362
- await startPi(run3, sleep2, `${train ? TRAIN : integ ? "integ" : "main"}-${randomUUID12().slice(0, 8)}`, paneId, ["--name", train || integ ? label : `main \xB7 ${label ?? workspace.label}`]);
21630
+ await startPi(run3, sleep2, `${train ? TRAIN : integ ? "integ" : "main"}-${randomUUID13().slice(0, 8)}`, paneId, ["--name", train || integ ? label : `main \xB7 ${label ?? workspace.label}`]);
21363
21631
  const wanted = train ? TRAIN : "main";
21364
21632
  const main = await waitPastTrust(sleep2, async () => {
21365
21633
  const tokens = (await panes(run3, workspace.workspace_id)).find((p) => p.pane_id === paneId)?.tokens;
@@ -21383,7 +21651,7 @@ function opener(env) {
21383
21651
  });
21384
21652
  return pending2;
21385
21653
  }
21386
- const key2 = createHash17("sha256").update(JSON.stringify(input.role === TRAIN ? [input.sender, input.request, TRAIN] : [input.sender, input.request])).digest("hex");
21654
+ const key2 = createHash19("sha256").update(JSON.stringify(input.role === TRAIN ? [input.sender, input.request, TRAIN] : [input.sender, input.request])).digest("hex");
21387
21655
  const prior = seen.get(key2);
21388
21656
  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}`)));
21389
21657
  const pending = queue.then(() => open8(input), () => open8(input));
@@ -21401,17 +21669,17 @@ function opener(env) {
21401
21669
  }
21402
21670
 
21403
21671
  // src/order.ts
21404
- import { createHash as createHash18 } from "node:crypto";
21672
+ import { createHash as createHash20 } from "node:crypto";
21405
21673
  var INDENT = { more: "\u251C\u2500", last: "\u2514\u2500" };
21406
21674
  var MAX_KIDS = 999;
21407
21675
  var NAME_MAX = 24;
21408
21676
  var part2 = (n, width = 3) => String(n).padStart(width, "0");
21409
- var short3 = (name2) => name2.length > NAME_MAX ? `${name2.slice(0, NAME_MAX - 1)}\u2026` : name2;
21677
+ var short4 = (name2) => name2.length > NAME_MAX ? `${name2.slice(0, NAME_MAX - 1)}\u2026` : name2;
21410
21678
  function orderKey(role, pane, ps, all, tabList, who2 = {}) {
21411
21679
  const index2 = all.filter((w) => !isSub(w) && !isHead(w)).findIndex((w) => w.workspace_id === pane.workspace_id), base = index2 + (all.some(isHead) ? 1 : 0);
21412
21680
  if (index2 < 0) return void 0;
21413
21681
  if (role === "tower") return `${part2(base)}.0`;
21414
- 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")}.${createHash18("sha256").update(who2.project).digest("hex").slice(0, 8)}` : void 0;
21682
+ 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")}.${createHash20("sha256").update(who2.project).digest("hex").slice(0, 8)}` : void 0;
21415
21683
  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);
21416
21684
  if (tab < 0 || slot < 0) return void 0;
21417
21685
  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)}`;
@@ -21424,7 +21692,7 @@ function descendants2(parent, key2, name2, ps, now, seen = new Set(parent ? [par
21424
21692
  if (!row2.pane || seen.has(row2.pane)) return [];
21425
21693
  seen.add(row2.pane);
21426
21694
  const order2 = `${key2}.${part2(i)}`, indent = rows.slice(i + 1).some((r) => r.pane && !seen.has(r.pane)) ? INDENT.more : INDENT.last;
21427
- return [{ pane: row2.pane, order: order2, mark: row2.duty ? KIND_MARK[row2.duty] : `${ARROW} ${short3(name2)}`, indent, name: short3(row2.text) }, ...descendants2(ps.find((p) => p.pane_id === row2.pane), order2, row2.text, ps, now, seen)];
21695
+ return [{ pane: row2.pane, order: order2, mark: row2.duty ? KIND_MARK[row2.duty] : `${ARROW} ${short4(name2)}`, indent, name: short4(row2.text) }, ...descendants2(ps.find((p) => p.pane_id === row2.pane), order2, row2.text, ps, now, seen)];
21428
21696
  });
21429
21697
  }
21430
21698
  function unplaced(parent, ps, now, seen = new Set(parent ? [parent.pane_id] : [])) {
@@ -21437,7 +21705,7 @@ function unplaced(parent, ps, now, seen = new Set(parent ? [parent.pane_id] : []
21437
21705
  });
21438
21706
  }
21439
21707
  function allyKids(towerKey, allies) {
21440
- return allies.map((ally, i) => ({ pane: ally.pane, order: `${towerKey}.${part2(i)}`, mark: `${ALLY_MARK} ${short3(ally.label)}`, indent: i < allies.length - 1 ? INDENT.more : INDENT.last, name: "ally run" }));
21708
+ return allies.map((ally, i) => ({ pane: ally.pane, order: `${towerKey}.${part2(i)}`, mark: `${ALLY_MARK} ${short4(ally.label)}`, indent: i < allies.length - 1 ? INDENT.more : INDENT.last, name: "ally run" }));
21441
21709
  }
21442
21710
  var markOf2 = (role, who2) => role === "tower" ? null : role === "train" ? who2.code ? `${MARK.train} ${shortCode(who2.code)}` : null : role === "main" ? isCoordinatorDuty(who2.duty) ? KIND_MARK[who2.duty] : who2.integrator ? MARK.integrator : MARK.main : MARK[role];
21443
21711
  async function netTokens(run3, place, role, name2, now = Date.now(), world = worldOf(run3), who2 = {}) {
@@ -21455,8 +21723,8 @@ var clearOrder = (run3, paneIds) => Promise.all(paneIds.map((id) => report(run3,
21455
21723
 
21456
21724
  // src/server/head.ts
21457
21725
  import { chmodSync as chmodSync7, mkdirSync as mkdirSync15 } from "node:fs";
21458
- import { homedir as homedir13 } from "node:os";
21459
- import { join as join52 } from "node:path";
21726
+ import { homedir as homedir14 } from "node:os";
21727
+ import { join as join53 } from "node:path";
21460
21728
  var HEAD_REFUSAL = "The head tower takes only the boss's words and answers to its own asks.";
21461
21729
  var HEAD_TOKEN = "sb_head";
21462
21730
  var HEAD_ORDER = "000.0";
@@ -21465,7 +21733,7 @@ function refuseHead(client, from, message, log, now) {
21465
21733
  client.sendMessageReceipt?.({ messageId: message.id, status: "expired", timestamp: now(), detail: HEAD_REFUSAL });
21466
21734
  }
21467
21735
  var headLabel = (env) => localeOf(env) === "zh-TW" ? "\u4E3B\u5854\u53F0" : "Head tower";
21468
- var headFolder = (env) => join52(env.PI_CODING_AGENT_DIR || join52(homedir13(), ".pi", "agent"), "straw-boss-head");
21736
+ var headFolder = (env) => join53(env.PI_CODING_AGENT_DIR || join53(homedir14(), ".pi", "agent"), "straw-boss-head");
21469
21737
  async function makeHead(d) {
21470
21738
  const cwd = headFolder(d.env), label = headLabel(d.env);
21471
21739
  mkdirSync15(cwd, { recursive: true, mode: 448 });
@@ -21523,7 +21791,7 @@ function createHead(d) {
21523
21791
  }
21524
21792
 
21525
21793
  // src/server/headside.ts
21526
- import { join as join53 } from "node:path";
21794
+ import { join as join54 } from "node:path";
21527
21795
 
21528
21796
  // src/server/headbrief.ts
21529
21797
  var CAPS2 = { workspaces: 2400, asks: 1200, row: 200, note: 1200, recap: 2e3 };
@@ -21637,7 +21905,7 @@ async function headBrief(d, input) {
21637
21905
  const ws = d.record().workspace, all = await workspaces(d.run), at = new Date(input.woken);
21638
21906
  const rows = [];
21639
21907
  for (const w of all.filter((x) => !isSub(x) && !isHead(x)).slice(0, 20)) {
21640
- const { rows: mains } = await gatherMains({ run: d.run, now: d.now, sessions: d.sessions, boardDir: join53(d.slot.stateDir, "board"), workspace: w, ledger: [] }).catch(() => ({ rows: [] }));
21908
+ const { rows: mains } = await gatherMains({ run: d.run, now: d.now, sessions: d.sessions, boardDir: join54(d.slot.stateDir, "board"), workspace: w, ledger: [] }).catch(() => ({ rows: [] }));
21641
21909
  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 });
21642
21910
  }
21643
21911
  const kept = readMemory(d.slot, ws, d.now()), section = memorySection(kept.memory, d.now(), kept.problem), note = lastNote(d.slot, ws, "local");
@@ -21784,7 +22052,7 @@ function remoteTowers(teams) {
21784
22052
  }
21785
22053
 
21786
22054
  // src/server/runtools.ts
21787
- import { randomBytes as randomBytes18 } from "node:crypto";
22055
+ import { randomBytes as randomBytes19 } from "node:crypto";
21788
22056
  var NO_TARGET = "tower_reply has no such target: no session of this computer that an ally run may write to has that name or id";
21789
22057
  async function refuseTarget(host, query) {
21790
22058
  const net = await host.reach.read(), named = net.sessions.filter((s2) => s2.id === query || s2.name === query);
@@ -21957,7 +22225,7 @@ async function towerSendDevice(host, args, forced, ally = false) {
21957
22225
  const requester = forWho === void 0 && !ally && reply3 ? await host.requester() : void 0;
21958
22226
  if (forWho !== void 0) main = await host.mainOf(forWho);
21959
22227
  else if (requester) main = requester;
21960
- if (main) ask = randomBytes18(16).toString("hex");
22228
+ if (main) ask = randomBytes19(16).toString("hex");
21961
22229
  const answer = await host.link({ op: "send", device, text: message, reply: reply3, ...opt2(args, "workspace") ? { workspace: opt2(args, "workspace") } : {}, ...ask ? { awaitsReply: ask } : {}, ...inReplyTo ? { inReplyTo } : {} });
21962
22230
  if (!answer.ok) throw new Error(String(answer.error));
21963
22231
  const details = answer.details ?? {};
@@ -22102,8 +22370,8 @@ function autoAnswer(out) {
22102
22370
  return { text: out.changed === false ? "Auto mode is already in that state." : "Auto mode is off.", details: { changed: out.changed !== false } };
22103
22371
  }
22104
22372
  var headHost = (host, head) => {
22105
- const no17 = () => Promise.reject(new Error("The head tower opens and closes no mains: forward to the tower that owns the work"));
22106
- return { ...host, open: no17, closeMain: no17, head };
22373
+ const no19 = () => Promise.reject(new Error("The head tower opens and closes no mains: forward to the tower that owns the work"));
22374
+ return { ...host, open: no19, closeMain: no19, head };
22107
22375
  };
22108
22376
  var str11 = (args, name2, max) => {
22109
22377
  const v = args[name2];
@@ -22294,9 +22562,9 @@ function createRevoker(d) {
22294
22562
  }
22295
22563
 
22296
22564
  // src/server/runs.ts
22297
- import { randomBytes as randomBytes19 } from "node:crypto";
22565
+ import { randomBytes as randomBytes20 } from "node:crypto";
22298
22566
  import { lstatSync as lstatSync12, realpathSync as realpathSync11 } from "node:fs";
22299
- import { basename as basename13, resolve as resolve9, sep as sep8 } from "node:path";
22567
+ import { basename as basename14, resolve as resolve9, sep as sep9 } from "node:path";
22300
22568
 
22301
22569
  // src/server/herdrcode.ts
22302
22570
  function herdrCode(cause) {
@@ -22315,7 +22583,7 @@ function herdrCode(cause) {
22315
22583
  import { execFile as execFile2 } from "node:child_process";
22316
22584
  var PROMPT_WORDS = " prompt --workspace ";
22317
22585
  var RUN_ID2 = /^[0-9a-f]{1,64}$/i;
22318
- var READ_MS2 = 15e3;
22586
+ var READ_MS3 = 15e3;
22319
22587
  var MAX_DEPTH = 8;
22320
22588
  var WRAPPER = /^(cmd|sh|bash|dash|zsh|fish|env|npm|npx|pnpm|yarn|volta|powershell|pwsh)(\.exe)?$/i;
22321
22589
  var isWrapper = (name2) => WRAPPER.test(name2);
@@ -22362,7 +22630,7 @@ var ISO_START = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/;
22362
22630
  var cimCommand = (runId, env = process.env) => ({
22363
22631
  file: powershellPath(env),
22364
22632
  args: [...POWERSHELL_FLAGS, "-Command", `${PROGRESS_OFF}; $ErrorActionPreference='Stop'; $id='${runId}'; $inv=[cultureinfo]::InvariantCulture; $rows = foreach ($o in ([wmisearcher]'SELECT ProcessId,ParentProcessId,CreationDate,Name,CommandLine FROM Win32_Process').Get()) { $d=''; $cd=[string]$o['CreationDate']; if ($cd) { $d=${dmtfUtcPs("$cd")}.ToString('${START_FORMAT}',$inv) }; $cl=[string]$o['CommandLine']; $c='0'; if ($cl.Contains('--sb-run ' + $id)) { $c='1' }; $q='0'; if ($cl.Contains('${PROMPT_WORDS}')) { $q='1' }; (@($o['ProcessId'],$o['ParentProcessId'],$d,$o['Name'],$c,$q) -join [char]9) }; $rows`],
22365
- options: { encoding: "utf8", timeout: READ_MS2, windowsHide: true, cwd: system32(env), env: powershellEnv(env), maxBuffer: 16 * 1024 * 1024 }
22633
+ options: { encoding: "utf8", timeout: READ_MS3, windowsHide: true, cwd: system32(env), env: powershellEnv(env), maxBuffer: 16 * 1024 * 1024 }
22366
22634
  });
22367
22635
  function parseCim(text11) {
22368
22636
  return text11.split(/\r?\n/).flatMap((line3) => {
@@ -22435,7 +22703,7 @@ var mayAppear = (file2, root) => {
22435
22703
  bases.push(realpathSync11(root));
22436
22704
  } catch {
22437
22705
  }
22438
- return bases.some((b) => abs.startsWith(b + sep8));
22706
+ return bases.some((b) => abs.startsWith(b + sep9));
22439
22707
  };
22440
22708
  var phrase6 = (value, max) => typeof value === "string" ? value.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max) : "";
22441
22709
  var iso5 = (ms3) => new Date(ms3).toISOString();
@@ -22448,7 +22716,7 @@ function createRuns2(o) {
22448
22716
  const start = o.startPi ?? startPi, settings = o.settings ?? ((dirs) => assertSettingsSafe(dirs)), append = o.append ?? appendEvent;
22449
22717
  const startedLater2 = o.startedLater ?? (o.startOf ? (pid) => Promise.resolve(startOf2(pid)) : startedLater);
22450
22718
  const procs = o.procs ?? readProcs();
22451
- const newId = o.newId ?? (() => randomBytes19(8).toString("hex"));
22719
+ const newId = o.newId ?? (() => randomBytes20(8).toString("hex"));
22452
22720
  const services = /* @__PURE__ */ new Map(), byToken = /* @__PURE__ */ new Map(), byRun = /* @__PURE__ */ new Map(), blocked = /* @__PURE__ */ new Set();
22453
22721
  const confirms = /* @__PURE__ */ new Map();
22454
22722
  let slots = 0, pendingTakeovers = 0, herdrLostAt, watcher, stopped = false;
@@ -23129,7 +23397,7 @@ function createRuns2(o) {
23129
23397
  a.digestKeys = built.digestKeys;
23130
23398
  a.expired = built.expired?.length ? built.expired : void 0;
23131
23399
  a.briefV = ally ? void 0 : svc.ref.briefVersion?.();
23132
- a.token = randomBytes19(24).toString("hex");
23400
+ a.token = randomBytes20(24).toString("hex");
23133
23401
  a.lastPoll = now();
23134
23402
  a.recovering = void 0;
23135
23403
  if (a.left) {
@@ -23723,7 +23991,7 @@ function createRuns2(o) {
23723
23991
  setFile(token, file2, session) {
23724
23992
  const a = of(token);
23725
23993
  if (!a || typeof file2 !== "string" || file2.length > 4096) return;
23726
- if (a.rec.kind === "ally" && !(typeof session === "string" && /^[\w-]{1,128}$/.test(session) && basename13(file2).endsWith(`_${session}.jsonl`))) return;
23994
+ if (a.rec.kind === "ally" && !(typeof session === "string" && /^[\w-]{1,128}$/.test(session) && basename14(file2).endsWith(`_${session}.jsonl`))) return;
23727
23995
  a.rec.file = file2;
23728
23996
  if ((a.rec.conversation || headRun(a)) && a.rec.kind === "local") {
23729
23997
  a.pendingFile = onDisk(file2) || !mayAppear(file2, o.sessions ?? sessionsRoot()) ? void 0 : file2;
@@ -23740,7 +24008,7 @@ function createRuns2(o) {
23740
24008
  const svc = services.get(workspace);
23741
24009
  if (!svc) throw new Error(`The sb server stands in for no tower of workspace ${workspace}`);
23742
24010
  const rec = { id: newId(), workspace, kind: who2.kind, ...who2.device ? { device: who2.device } : {}, ...who2.level ? { level: who2.level } : {}, ...who2.team ? { team: who2.team } : {}, pane: svc.ref.record().pane, agent: "minted", startedAt: iso5(now()), events: [] };
23743
- const a = { rec, svc, commands: [], lastPoll: now(), started: now(), digestKeys: [], offered: /* @__PURE__ */ new Map(), token: randomBytes19(24).toString("hex") };
24011
+ const a = { rec, svc, commands: [], lastPoll: now(), started: now(), digestKeys: [], offered: /* @__PURE__ */ new Map(), token: randomBytes20(24).toString("hex") };
23744
24012
  byToken.set(a.token, a);
23745
24013
  return a.token;
23746
24014
  },
@@ -23943,15 +24211,15 @@ async function pressRequest(d, workspace, json3, via = "pi") {
23943
24211
  }
23944
24212
 
23945
24213
  // src/server/towerseen.ts
23946
- import { createHash as createHash19 } from "node:crypto";
23947
- import { appendFileSync as appendFileSync4, readFileSync as readFileSync37 } from "node:fs";
23948
- import { join as join54 } from "node:path";
24214
+ import { createHash as createHash21 } from "node:crypto";
24215
+ import { appendFileSync as appendFileSync4, readFileSync as readFileSync38 } from "node:fs";
24216
+ import { join as join55 } from "node:path";
23949
24217
  var SEEN_KEEP_MS = 48 * 36e5;
23950
24218
  var SEEN_MAX = 5e3;
23951
24219
  var SLACK = 500;
23952
24220
  var FILE = "seen.jsonl";
23953
24221
  var baseId = (messageId) => messageId.replace(/~r\d+$/, "");
23954
- var hashOf2 = (text11) => createHash19("sha256").update(text11).digest("hex");
24222
+ var hashOf3 = (text11) => createHash21("sha256").update(text11).digest("hex");
23955
24223
  var key = (from, base) => `${from}
23956
24224
  ${base}`;
23957
24225
  var parse5 = (line3) => {
@@ -23963,11 +24231,11 @@ var parse5 = (line3) => {
23963
24231
  }
23964
24232
  };
23965
24233
  function openSeen(slot, workspace, now) {
23966
- const file2 = join54(towerDir(slot, workspace), FILE);
24234
+ const file2 = join55(towerDir(slot, workspace), FILE);
23967
24235
  const rows = /* @__PURE__ */ new Map();
23968
24236
  let text11 = "", lines = 0;
23969
24237
  try {
23970
- text11 = readFileSync37(file2, "utf8");
24238
+ text11 = readFileSync38(file2, "utf8");
23971
24239
  } catch {
23972
24240
  }
23973
24241
  for (const line3 of text11.split("\n")) {
@@ -23979,7 +24247,7 @@ function openSeen(slot, workspace, now) {
23979
24247
  if (event.kind !== "intercom" || !event.messageId || !event.from) continue;
23980
24248
  const base = baseId(event.messageId), k = key(event.from.id, base);
23981
24249
  if (rows.has(k)) continue;
23982
- rows.set(k, { from: event.from.id, base, hash: hashOf2(event.text), at: Date.parse(event.at) || now() });
24250
+ rows.set(k, { from: event.from.id, base, hash: hashOf3(event.text), at: Date.parse(event.at) || now() });
23983
24251
  added = true;
23984
24252
  }
23985
24253
  const trim = () => {
@@ -24002,10 +24270,10 @@ function openSeen(slot, workspace, now) {
24002
24270
  return {
24003
24271
  check(from, messageId, body2) {
24004
24272
  const found = rows.get(key(from, baseId(messageId)));
24005
- return !found ? "new" : found.hash === hashOf2(body2) ? "seen" : "conflict";
24273
+ return !found ? "new" : found.hash === hashOf3(body2) ? "seen" : "conflict";
24006
24274
  },
24007
24275
  add(from, messageId, body2, at = now()) {
24008
- const row2 = { from, base: baseId(messageId), hash: hashOf2(body2), at };
24276
+ const row2 = { from, base: baseId(messageId), hash: hashOf3(body2), at };
24009
24277
  rows.delete(key(from, row2.base));
24010
24278
  rows.set(key(from, row2.base), row2);
24011
24279
  trim();
@@ -24118,7 +24386,7 @@ function createTowers(o) {
24118
24386
  const ws = l.record.workspace, all = await workspaces(run3), target2 = all.find((w) => w.workspace_id === ws);
24119
24387
  if (!target2 || !l.client) throw new Error("the tower's workspace or its intercom connection is gone");
24120
24388
  const first2 = items[0], device = rec.device ?? "";
24121
- const mains2 = await gatherMains({ run: run3, now, sessions: () => l.client.listSessions(), boardDir: join55(slot.stateDir, "board"), workspace: target2, ledger: [], within: { project: rec.team ? o.ally?.project(rec.team) : void 0 } });
24389
+ const mains2 = await gatherMains({ run: run3, now, sessions: () => l.client.listSessions(), boardDir: join56(slot.stateDir, "board"), workspace: target2, ledger: [], within: { project: rec.team ? o.ally?.project(rec.team) : void 0 } });
24122
24390
  const note = lastNote(slot, ws, "ally", device), at = new Date(woken);
24123
24391
  const line3 = (text11) => text11.split("\n").find((x) => x.trim()) ?? "";
24124
24392
  return {
@@ -24139,7 +24407,7 @@ function createTowers(o) {
24139
24407
  const ws = l.record.workspace, all = await workspaces(run3), target2 = all.find((w) => w.workspace_id === ws);
24140
24408
  if (!target2 || !l.client) throw new Error("the tower's workspace or its intercom connection is gone");
24141
24409
  if (isHeadL(l)) return headBrief({ slot, run: run3, now, auto: autoLine, record: () => l.record, sessions: () => l.client.listSessions(), towerState, locale: localeOf(o.env) }, { woken, run: rec });
24142
- const mains2 = await gatherMains({ run: run3, now, sessions: () => l.client.listSessions(), boardDir: join55(slot.stateDir, "board"), workspace: target2, ledger: readLedger(slot, ws, now()) });
24410
+ const mains2 = await gatherMains({ run: run3, now, sessions: () => l.client.listSessions(), boardDir: join56(slot.stateDir, "board"), workspace: target2, ledger: readLedger(slot, ws, now()) });
24143
24411
  const lines = await digest.peek(ws).catch(() => []), note = lastNote(slot, ws, "local"), timer = readTimer(slot, ws);
24144
24412
  const counts = {};
24145
24413
  for (const e of events2) counts[e.kind] = (counts[e.kind] ?? 0) + 1;
@@ -24209,7 +24477,7 @@ function createTowers(o) {
24209
24477
  const runs2 = createRuns2({ slot, run: run3, sleep: sleep2, now, log, sessions: sessionsRoot(o.env), enabled: o.enabled, max: () => readTowerRuns(slot.stateDir).max, trustDir: trustDir(slot.stateDir), model: () => towerModel(slot.stateDir), headModel: () => headModel(slot.stateDir), ...allyPort2 ? { ally: allyPort2 } : {}, ...o.runs });
24210
24478
  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 } : {} });
24211
24479
  const place = (l) => ({ paneId: l.record.pane, tabId: l.record.tab, workspaceId: l.record.workspace });
24212
- const dirOf2 = (workspace) => join55(towerDir(slot, workspace));
24480
+ const dirOf2 = (workspace) => join56(towerDir(slot, workspace));
24213
24481
  const error = (code, text11) => log.line("error", { code, text: phrase7(text11, 300) });
24214
24482
  const markAnswered2 = async (l, session) => {
24215
24483
  try {
@@ -24575,7 +24843,7 @@ function createTowers(o) {
24575
24843
  return l;
24576
24844
  };
24577
24845
  const convertRoles = async () => {
24578
- const dir = join55(slot.stateDir, "roles");
24846
+ const dir = join56(slot.stateDir, "roles");
24579
24847
  let names = [];
24580
24848
  try {
24581
24849
  names = readdirSync16(dir).filter((name2) => name2.endsWith(".json"));
@@ -24586,7 +24854,7 @@ function createTowers(o) {
24586
24854
  for (const name2 of names) {
24587
24855
  let record2;
24588
24856
  try {
24589
- record2 = JSON.parse(readFileSync38(join55(dir, name2), "utf8"));
24857
+ record2 = JSON.parse(readFileSync39(join56(dir, name2), "utf8"));
24590
24858
  } catch {
24591
24859
  continue;
24592
24860
  }
@@ -24602,12 +24870,12 @@ function createTowers(o) {
24602
24870
  writeService(slot, made);
24603
24871
  log.line("tower-converted", { workspace: made.workspace, pane: made.pane });
24604
24872
  }
24605
- rmSync14(join55(dir, name2), { force: true });
24873
+ rmSync14(join56(dir, name2), { force: true });
24606
24874
  }
24607
24875
  };
24608
24876
  const begin = async () => {
24609
24877
  recoverUntil = now() + (o.recoverMs ?? RECOVER_MS);
24610
- secretDir(join55(slot.dir, "tower"));
24878
+ secretDir(join56(slot.dir, "tower"));
24611
24879
  try {
24612
24880
  await convertRoles();
24613
24881
  } catch (cause) {
@@ -24921,7 +25189,7 @@ function createTowers(o) {
24921
25189
  } : l.open,
24922
25190
  closeMain: l.control ? async (query) => forgetClosed(ws, await l.control.closeMain(query)) : void 0,
24923
25191
  now,
24924
- boardDir: join55(slot.stateDir, "board"),
25192
+ boardDir: join56(slot.stateDir, "board"),
24925
25193
  label: l.record.label,
24926
25194
  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" },
24927
25195
  server: o.server ?? { status: () => ({}), logs: () => [], restart: () => Promise.reject(new Error("The server cannot restart itself here")) },
@@ -24958,7 +25226,7 @@ function createTowers(o) {
24958
25226
  // 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.
24959
25227
  slipEvents: () => {
24960
25228
  const shared = (text11) => ((f) => f?.kind === "call_tower" && f.why === "shared")(fieldsOf(text11));
24961
- if (peer) return runs2.allyAnswers(request.token).filter((x) => shared(x.text)).map((x) => ({ fwd: createHash20("sha256").update(x.id).digest("hex").slice(0, 16), from: x.from, text: x.text }));
25229
+ if (peer) return runs2.allyAnswers(request.token).filter((x) => shared(x.text)).map((x) => ({ fwd: createHash22("sha256").update(x.id).digest("hex").slice(0, 16), from: x.from, text: x.text }));
24962
25230
  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 }] : []);
24963
25231
  },
24964
25232
  // 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.
@@ -25207,9 +25475,9 @@ async function headCommand(t, cmd, text11, extra = {}) {
25207
25475
  }
25208
25476
 
25209
25477
  // src/server/automode.ts
25210
- import { randomBytes as randomBytes20 } from "node:crypto";
25211
- import { mkdirSync as mkdirSync17, readFileSync as readFileSync39, renameSync as renameSync8, writeFileSync as writeFileSync8 } from "node:fs";
25212
- import { join as join56 } from "node:path";
25478
+ import { randomBytes as randomBytes21 } from "node:crypto";
25479
+ import { mkdirSync as mkdirSync17, readFileSync as readFileSync40, renameSync as renameSync8, writeFileSync as writeFileSync8 } from "node:fs";
25480
+ import { join as join57 } from "node:path";
25213
25481
  var PENDING_MS2 = 10 * 6e4;
25214
25482
  var USED_MAX = 500;
25215
25483
  var STALE = "This request expired or was replaced: ask again";
@@ -25225,7 +25493,7 @@ var gistOf = (v) => {
25225
25493
  };
25226
25494
  function readReportFile(dir) {
25227
25495
  try {
25228
- const j = JSON.parse(readFileSync39(join56(dir, REPORT_FILE), "utf8"));
25496
+ const j = JSON.parse(readFileSync40(join57(dir, REPORT_FILE), "utf8"));
25229
25497
  return j.v === 1 && typeof j.since === "string" && Array.isArray(j.parked) && Array.isArray(j.lines) ? j : void 0;
25230
25498
  } catch {
25231
25499
  return void 0;
@@ -25240,7 +25508,7 @@ function createAutoMode(d) {
25240
25508
  const listeners = /* @__PURE__ */ new Set();
25241
25509
  const readPeriod = () => {
25242
25510
  try {
25243
- const j = JSON.parse(readFileSync39(join56(d.dir, PERIOD_FILE), "utf8"));
25511
+ const j = JSON.parse(readFileSync40(join57(d.dir, PERIOD_FILE), "utf8"));
25244
25512
  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;
25245
25513
  } catch {
25246
25514
  return void 0;
@@ -25251,7 +25519,7 @@ function createAutoMode(d) {
25251
25519
  if (period) write2(PERIOD_FILE, period);
25252
25520
  };
25253
25521
  const write2 = (name2, value) => {
25254
- const file2 = join56(d.dir, name2), tmp = `${file2}.${process.pid}.tmp`;
25522
+ const file2 = join57(d.dir, name2), tmp = `${file2}.${process.pid}.tmp`;
25255
25523
  mkdirSync17(d.dir, { recursive: true });
25256
25524
  writeFileSync8(tmp, `${JSON.stringify(value)}
25257
25525
  `, { mode: 384 });
@@ -25328,7 +25596,7 @@ function createAutoMode(d) {
25328
25596
  });
25329
25597
  function stage(said2, from) {
25330
25598
  if (own.state.on) return { ok: false, error: "Auto mode is on already." };
25331
- const at = d.now(), pending = { id: d.id?.() ?? randomBytes20(6).toString("hex"), said: phrase8(said2, 200), from: { ...from, name: phrase8(from.name, 80) }, at, expires: at + PENDING_MS2 };
25599
+ const at = d.now(), pending = { id: d.id?.() ?? randomBytes21(6).toString("hex"), said: phrase8(said2, 200), from: { ...from, name: phrase8(from.name, 80) }, at, expires: at + PENDING_MS2 };
25332
25600
  commit({ ...own, pending }, false);
25333
25601
  d.log("auto-staged", { id: pending.id, ...whoFacts(from) });
25334
25602
  return { ok: true, pending: { id: pending.id, said: pending.said, expires: pending.expires } };
@@ -25530,7 +25798,7 @@ function autoReply(auto, request, unattended = () => false) {
25530
25798
  }
25531
25799
 
25532
25800
  // src/server/autoback.ts
25533
- import { randomUUID as randomUUID13 } from "node:crypto";
25801
+ import { randomUUID as randomUUID14 } from "node:crypto";
25534
25802
 
25535
25803
  // src/autotext.ts
25536
25804
  var KIND2 = {
@@ -25577,7 +25845,7 @@ function createBackstop(d) {
25577
25845
  }
25578
25846
  done2.add(id);
25579
25847
  keys.add(o.key);
25580
- await d.send(o.key, o.target, { id, answerId: `auto-${randomUUID13()}`, digest: o.target.answer.digest, cancel: true });
25848
+ await d.send(o.key, o.target, { id, answerId: `auto-${randomUUID14()}`, digest: o.target.answer.digest, cancel: true });
25581
25849
  note("backstop");
25582
25850
  await d.tell(o.key, cancelledText(view.since, o.owner, d.kindOf?.(o.key) ?? "main")).catch(() => void 0);
25583
25851
  }
@@ -25670,7 +25938,7 @@ async function runServer(o) {
25670
25938
  if (workspace) towers.runs.notice(workspace, text11, `auto:${now()}`);
25671
25939
  } });
25672
25940
  const unattended = () => Boolean(link?.holder) && !link.attended();
25673
- let cars;
25941
+ let dog, cars;
25674
25942
  const allows = createAllows({ now }), asks = createAsks(slot, now);
25675
25943
  const abort = (code, text11, sddl) => {
25676
25944
  timers.forEach(clearInterval);
@@ -25798,7 +26066,7 @@ async function runServer(o) {
25798
26066
  let reporter;
25799
26067
  let operateBox;
25800
26068
  let operateHost;
25801
- const operateSwitch = operateOff(join57(slot.stateDir, "link", "operate-off.json"), now);
26069
+ const operateSwitch = operateOff(join58(slot.stateDir, "link", "operate-off.json"), now);
25802
26070
  const makeOperateHost = () => operateHost = createOperateHost({
25803
26071
  now,
25804
26072
  device: () => link?.holder?.deviceId,
@@ -25906,7 +26174,7 @@ async function runServer(o) {
25906
26174
  if (followed) return followed;
25907
26175
  const autoAnswer2 = autoReply(auto, request, unattended);
25908
26176
  if (autoAnswer2) return autoAnswer2;
25909
- const owners = procsReply(procs, request);
26177
+ const owners = procsReply(procs, request) ?? watchdogReply(dog, request);
25910
26178
  if (owners) return owners;
25911
26179
  const carsAnswer = carsReply(cars, request);
25912
26180
  if (carsAnswer) return carsAnswer;
@@ -26098,7 +26366,7 @@ async function runServer(o) {
26098
26366
  // The work board's Clear tells a live writer once (boardpanel.ts): one intercom message from the server, under a `board_clear` header.
26099
26367
  tell: tellVia(() => client, serverId(slot)),
26100
26368
  // 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.
26101
- link: gui.link ?? (!slot.primary ? elsewhereLink() : inProcessLink(createGuiLink({ events: kit.pi.events, id: () => serverId(slot), stateDir: slot.stateDir, agentDir: env.PI_CODING_AGENT_DIR ?? join57(homedir14(), ".pi", "agent"), log: (text11) => log.line("link", { text: text11 }) }), () => link, () => serverId(slot))),
26369
+ link: gui.link ?? (!slot.primary ? elsewhereLink() : inProcessLink(createGuiLink({ events: kit.pi.events, id: () => serverId(slot), stateDir: slot.stateDir, agentDir: env.PI_CODING_AGENT_DIR ?? join58(homedir15(), ".pi", "agent"), log: (text11) => log.line("link", { text: text11 }) }), () => link, () => serverId(slot))),
26102
26370
  status: () => ({ state: phase === "ready" ? "live" : phase, version, pid, mode, desk, uptimeMs: now() - startedAt, log: fileOf(slot, "log"), ...own.lastError ? { lastError: own.lastError } : {} }),
26103
26371
  restart: gui.restart ?? ((reason) => spawnRestart(cliBeside(), reason, "the GUI", serverEnv(env), slot.dir)),
26104
26372
  failed: (code, text11) => recordError(code, text11),
@@ -26131,6 +26399,7 @@ async function runServer(o) {
26131
26399
  if (read4.problem !== toldConfig) toldConfig = read4.problem ?? "", read4.problem && recordError("config", read4.problem);
26132
26400
  return read4;
26133
26401
  };
26402
+ dog = startWatchdog({ net: guiHost.watchNet(), env, now, client: () => client?.isConnected() ? client : void 0, log: (event, facts2) => log.line(event, facts2), stops, ...o.watchdog ? { over: o.watchdog } : {} });
26134
26403
  cars = startCars({ slot, run: cfg.run, now, startedAt, client: () => client?.isConnected() ? client : void 0, startOf: startOf2, log: (event, facts2) => log.line(event, facts2), stops });
26135
26404
  towers = createTowers({
26136
26405
  ally: allyPort(() => link),
@@ -26278,8 +26547,8 @@ ${unit}`), note = ws ? readNotes(slot, ws).at(-1) : void 0, sent = ws ? link?.ho
26278
26547
  run: cfg.run,
26279
26548
  towers: () => towers,
26280
26549
  now,
26281
- home: o.link?.home ?? homedir14(),
26282
- agentDir: env.PI_CODING_AGENT_DIR ?? join57(o.link?.home ?? homedir14(), ".pi", "agent"),
26550
+ home: o.link?.home ?? homedir15(),
26551
+ agentDir: env.PI_CODING_AGENT_DIR ?? join58(o.link?.home ?? homedir15(), ".pi", "agent"),
26283
26552
  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 })
26284
26553
  })
26285
26554
  }