pi-straw-boss 0.117.0 → 0.117.2

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.
@@ -5186,7 +5186,7 @@ async function serverFor(ctx, boss) {
5186
5186
  async function ensureTowerVia(ctx, ask2) {
5187
5187
  const record = await serverFor(ctx, ask2.boss === true);
5188
5188
  try {
5189
- const { reply } = await callControl(record.socket, record.secret, { cmd: "ensure-tower", workspace: ask2.workspace, ...ask2.cwd ? { cwd: ask2.cwd } : {}, ...ask2.pane ? { pane: ask2.pane } : {}, ...ask2.pid !== void 0 ? { pid: ask2.pid } : {}, ...ask2.made ? { made: ask2.made } : {} }, ask2.ms ?? 3e4);
5189
+ const { reply } = await callControl(record.socket, record.secret, { cmd: "ensure-tower", workspace: ask2.workspace, ...ask2.view ? { view: true } : {}, ...ask2.cwd ? { cwd: ask2.cwd } : {}, ...ask2.pane ? { pane: ask2.pane } : {}, ...ask2.pid !== void 0 ? { pid: ask2.pid } : {}, ...ask2.made ? { made: ask2.made } : {} }, ask2.ms ?? 3e4);
5190
5190
  if (!reply?.ok) throw new Error(`the sb server did not give the tower of ${ask2.workspace}: ${String(reply?.error ?? "no answer")}`);
5191
5191
  const { ok: _ok, ...answer } = reply;
5192
5192
  return answer;
@@ -120,7 +120,7 @@ import {
120
120
  writeEnd,
121
121
  writeJson,
122
122
  writerAlive
123
- } from "./chunk-X3FZH4LO.mjs";
123
+ } from "./chunk-CV2TPJUE.mjs";
124
124
 
125
125
  // src/server/cli.ts
126
126
  import { existsSync as existsSync3, realpathSync as realpathSync4 } from "node:fs";
@@ -308,7 +308,7 @@ import {
308
308
  writeStartError,
309
309
  writerAlive,
310
310
  yardPath
311
- } from "./chunk-X3FZH4LO.mjs";
311
+ } from "./chunk-CV2TPJUE.mjs";
312
312
 
313
313
  // src/server/main.ts
314
314
  import { homedir as homedir18 } from "node:os";
@@ -1560,6 +1560,13 @@ var LinkStore = class {
1560
1560
  }
1561
1561
  async acquire(waitMs) {
1562
1562
  this.ensure();
1563
+ try {
1564
+ for (const name2 of readdirSync(this.dir)) {
1565
+ const match = /^holder\.lock\.([1-9]\d*)\.[a-f0-9]{8}\.tmp$/.exec(name2);
1566
+ if (match && Number(match[1]) <= 2147483647 && !this.alive(Number(match[1]))) rmSync(this.path(name2), { force: true });
1567
+ }
1568
+ } catch {
1569
+ }
1563
1570
  const token = randomUUID(), end = Date.now() + waitMs;
1564
1571
  for (; ; ) {
1565
1572
  if (this.create(JSON.stringify({ pid: process.pid, ...this.started() ? { started: this.started() } : {}, token, t: this.now() }), token)) return token;
@@ -1584,10 +1591,21 @@ var LinkStore = class {
1584
1591
  linkSync(temp, this.lock);
1585
1592
  return true;
1586
1593
  } catch (error) {
1587
- if (error.code !== "EEXIST") throw error;
1588
- return false;
1594
+ const code = error.code;
1595
+ if (code === "EEXIST") return false;
1596
+ if (!code || !["EPERM", "ENOTSUP", "EOPNOTSUPP", "EXDEV", "ENOSYS"].includes(code)) throw error;
1597
+ try {
1598
+ writeFileSync2(this.lock, text14, { flag: "wx", mode: 384 });
1599
+ return true;
1600
+ } catch (fallback) {
1601
+ if (fallback.code === "EEXIST") return false;
1602
+ throw fallback;
1603
+ }
1589
1604
  } finally {
1590
- rmSync(temp, { force: true });
1605
+ try {
1606
+ rmSync(temp, { force: true });
1607
+ } catch {
1608
+ }
1591
1609
  }
1592
1610
  }
1593
1611
  started() {
@@ -3794,7 +3812,7 @@ function createReach({ pi, cfg, s: s2, guiDir, me, role, tell: tell2 }, server =
3794
3812
  }
3795
3813
  return result2;
3796
3814
  };
3797
- const openTower2 = async (query, create = s2.isMain, boss = false) => {
3815
+ const openTower2 = async (query, create = s2.isMain, boss = false, view = false) => {
3798
3816
  const all = await workspaces(run2);
3799
3817
  const found = all.filter((w) => query ? w.workspace_id === query || w.label === query : w.workspace_id === s2.at.workspaceId);
3800
3818
  if (found.length !== 1) {
@@ -3811,12 +3829,12 @@ function createReach({ pi, cfg, s: s2, guiDir, me, role, tell: tell2 }, server =
3811
3829
  throw new Error(`${target2.label} has no tower yet: it opens when a member there promotes itself to main`);
3812
3830
  }
3813
3831
  if (towerRunsEnabled(cfg.stateDir ?? guiDir)) {
3814
- if (held2 && await live2(held2)) return { target: target2, routed: target2 !== asked3 ? asked3 : void 0, id: held2, opened: false };
3815
- const got = await ensureTowerVia(server.ctx(), { workspace: target2.workspace_id, cwd: process.cwd(), boss }).catch((error) => {
3832
+ if (held2 && (!view || held2 !== towerId(server.ctx().slot, target2.workspace_id)) && await live2(held2)) return { target: target2, routed: target2 !== asked3 ? asked3 : void 0, id: held2, opened: false };
3833
+ const got = await ensureTowerVia(server.ctx(), { workspace: target2.workspace_id, cwd: process.cwd(), boss, view }).catch((error) => {
3816
3834
  if (error.message === STOPPED && !toldStopped) tell2(`Straw Boss: ${STOPPED}`, "warning"), toldStopped = true;
3817
3835
  throw error;
3818
3836
  });
3819
- return { target: target2, routed: target2 !== asked3 ? asked3 : void 0, id: got.id, opened: got.opened };
3837
+ return { target: target2, routed: target2 !== asked3 ? asked3 : void 0, id: got.id, opened: got.opened, tab: got.tab };
3820
3838
  }
3821
3839
  const moveFirst = (tabId) => api2("tab.move", { tab_id: tabId, insert_index: 0 }).catch((error) => tell2(`Straw Boss: could not move the tower tab first: ${error.message}`, "warning"));
3822
3840
  return { target: target2, routed: target2 !== asked3 ? asked3 : void 0, ...await ensureTower({ run: run2, sleep: sleep2, live: live2, moveFirst, model: towerModel(guiDir), trustDir: trustDir(guiDir) }, target2, process.cwd()) };
@@ -30547,6 +30565,7 @@ function createTowers(o) {
30547
30565
  const target2 = isSub(asked3) ? parentOf(all, asked3) : asked3;
30548
30566
  if (!target2) throw new Error(`${asked3.label} is a sub workspace with no open parent workspace, so it has no tower; open the parent workspace first`);
30549
30567
  if (isHead(target2) || headLive()?.record.workspace === target2.workspace_id) throw new Error(`${target2.label} is the head tower's workspace: it has no workspace tower, the head tower is its own`);
30568
+ if (view === true) while (opening3.has(target2.workspace_id)) await opening3.get(target2.workspace_id);
30550
30569
  const pending = opening3.get(target2.workspace_id) ?? openFor(target2, target2 === asked3 ? pane : void 0, cwd, pid, target2 === asked3 ? made : void 0, view ?? false).finally(() => opening3.delete(target2.workspace_id));
30551
30570
  opening3.set(target2.workspace_id, pending);
30552
30571
  return pending;
@@ -30931,6 +30950,24 @@ ${d.message}`, at: new Date(now()).toISOString(), messageId: `quiet:${createHash
30931
30950
  },
30932
30951
  owns: (id2) => [...services.values()].some((l) => l.record.id === id2),
30933
30952
  watchSend: async (workspace, session, text14, facts) => ((l) => l && l.state === "live" && !l.stopped && !isHeadL(l) && l.control ? l.control.notify(session, { text: text14, ...facts }) : Promise.resolve(false))(services.get(workspace)),
30953
+ async viewExisting(ws, holder) {
30954
+ await activate();
30955
+ const target2 = (await workspaces(run2)).find((w) => w.workspace_id === ws);
30956
+ if (!target2 || isSub(target2) || isHead(target2) || target2.tokens?.tower !== holder) throw new Error("The parent workspace has no live tower");
30957
+ if (holder === towerId(slot, ws)) {
30958
+ while (opening3.has(ws)) await opening3.get(ws);
30959
+ const l = services.get(ws);
30960
+ if (l && !l.stopped && l.state === "live" && l.record.id === holder) {
30961
+ if (l.record.tab) return l.record.tab;
30962
+ if (headless()) {
30963
+ const pending = openHeadless(target2, l, void 0, true).finally(() => opening3.delete(ws));
30964
+ opening3.set(ws, pending);
30965
+ return (await pending).tab;
30966
+ }
30967
+ }
30968
+ }
30969
+ throw new Error("The parent workspace has no live tower viewer");
30970
+ },
30934
30971
  identityOf: (workspace) => ((l) => l && l.state === "live" && !l.stopped && !isHeadL(l) ? l.record.id : void 0)(services.get(workspace)),
30935
30972
  post: async (workspace, to, text14, kind, extra) => ((l) => l?.reach && !l.stopped ? Promise.all(to.map((id2) => l.reach.post(id2, text14, kind, "session", false, void 0, void 0, extra))).then((r) => r.every((x) => x.status === "sent")) : false)(services.get(workspace)),
30936
30973
  status: () => [...services.values()].filter((l) => !isHeadL(l)).map(row2),
@@ -31488,6 +31525,10 @@ async function runServer(o) {
31488
31525
  const noAsk = askRefused(request, unattended);
31489
31526
  if (noAsk) return Promise.resolve({ ok: false, error: noAsk });
31490
31527
  switch (request.cmd) {
31528
+ case "view-existing-tower": {
31529
+ const workspace2 = text14(request.workspace), holder = text14(request.holder);
31530
+ return workspace2 && holder && request.view === true ? answer(async (t) => ({ tab: await t.viewExisting(workspace2, holder) })) : Promise.resolve({ ok: false, error: "Missing parent tower identity" });
31531
+ }
31491
31532
  case "ensure-tower": {
31492
31533
  const claim = typeof request.made === "object" && request.made !== null ? request.made : void 0;
31493
31534
  const made = text14(claim?.pane) && typeof claim?.at === "number" && Number.isFinite(claim.at) ? { pane: text14(claim.pane), at: claim.at } : void 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-straw-boss",
3
- "version": "0.117.0",
3
+ "version": "0.117.2",
4
4
  "description": "Straw Boss coordination for pi in Herdr: sessions join a tab's net by choice, the first joiner is its main agent, a workspace tower opens on demand with a live monitoring dashboard, and boss_broadcast reaches the rest",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -78,7 +78,7 @@
78
78
  "vite": "8.3.4"
79
79
  },
80
80
  "dependencies": {
81
- "@nubl/maestro": "git+https://github.com/wayne930242/maestro.git#a5a9c439b94244348997ec9445c1fd9f321f86cc",
81
+ "@nubl/maestro": "git+https://github.com/wayne930242/maestro.git#5c0164e4c41038c8995ab6972e3efeff67c91e97",
82
82
  "tsx": "^4.23.15"
83
83
  }
84
84
  }
package/src/boss.ts CHANGED
@@ -2,6 +2,7 @@ import { join } from "node:path";
2
2
  import { boardCommand } from "./boardcmd.ts";
3
3
  import { bookText } from "./server/logbook.ts";
4
4
  import { runHeadCommand, parseHeadArgs } from "./headcmd.ts";
5
+ import { focusTower } from "./towerview.ts";
5
6
  import { tabs, workspaces } from "./herdr.ts";
6
7
  import { localeCommand, localeOf } from "./locale.ts";
7
8
  import { runMemoryCommand } from "./memorycmd.ts";
@@ -157,10 +158,7 @@ export function registerBoss(kit: Kit, { runMode, host, membership, reach, close
157
158
  }
158
159
  if (s.isTower) throw new Error("This session is the tower, not a main agent");
159
160
  if (args.trim() !== "tower") return tell((await membership.promote(true)).text);
160
- await membership.joinNet();
161
- const tower = await reach.openTower(undefined, true, true); // anyone may open the tower by hand; the boss's own command also starts a server that was stopped on purpose
162
- const where = (await s.c.listSessions()).find((x) => x.id === tower.id)?.herdrLocation;
163
- if (where?.tab) await cfg.run(["tab", "focus", where.tab.id]);
161
+ await focusTower(kit, membership.joinNet, reach, req => { if (!server) throw new Error("No tower server"); return server.ask(req, { start: "never" }); });
164
162
  } catch (error) {
165
163
  tell((error as Error).message, "error");
166
164
  }
package/src/link/store.ts CHANGED
@@ -296,6 +296,12 @@ export class LinkStore {
296
296
  }
297
297
  private async acquire(waitMs: number): Promise<string> {
298
298
  this.ensure();
299
+ try {
300
+ for (const name of readdirSync(this.dir)) {
301
+ const match = /^holder\.lock\.([1-9]\d*)\.[a-f0-9]{8}\.tmp$/.exec(name);
302
+ if (match && Number(match[1]) <= 0x7fffffff && !this.alive(Number(match[1]))) rmSync(this.path(name), { force: true });
303
+ }
304
+ } catch { /* orphan cleanup is best effort */ }
299
305
  const token = randomUUID(), end = Date.now() + waitMs;
300
306
  for (;;) {
301
307
  if (this.create(JSON.stringify({ pid: process.pid, ...(this.started() ? { started: this.started() } : {}), token, t: this.now() }), token)) return token;
@@ -320,10 +326,18 @@ export class LinkStore {
320
326
  linkSync(temp, this.lock);
321
327
  return true;
322
328
  } catch (error) {
323
- if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
324
- return false;
329
+ const code = (error as NodeJS.ErrnoException).code;
330
+ if (code === "EEXIST") return false;
331
+ if (!code || !["EPERM", "ENOTSUP", "EOPNOTSUPP", "EXDEV", "ENOSYS"].includes(code)) throw error;
332
+ try {
333
+ writeFileSync(this.lock, text, { flag: "wx", mode: 0o600 });
334
+ return true;
335
+ } catch (fallback) {
336
+ if ((fallback as NodeJS.ErrnoException).code === "EEXIST") return false;
337
+ throw fallback;
338
+ }
325
339
  } finally {
326
- rmSync(temp, { force: true });
340
+ try { rmSync(temp, { force: true }); } catch { /* not part of lock acquisition */ }
327
341
  }
328
342
  }
329
343
  private started(): string | undefined {
package/src/reach.ts CHANGED
@@ -9,7 +9,7 @@ import { isHead, isSub, type Pane, panes, parentOf, type Session, towerModel, wo
9
9
  import type { Kit, Scope, SendResult } from "./state.ts";
10
10
  import { inside } from "./link/routing.ts";
11
11
  import { type Ctx, makeCtx } from "./server/client.ts";
12
- import { slotOf } from "./server/record.ts";
12
+ import { slotOf, towerId } from "./server/record.ts";
13
13
  import { noteLedger } from "./server/ledger.ts";
14
14
  import { ensureTowerVia, STOPPED, type TowerAnswer } from "./server/towerclient.ts";
15
15
 
@@ -90,7 +90,7 @@ export function createReach({ pi, cfg, s, guiDir, me, role, tell }: Kit, server:
90
90
  * The tower of this workspace, or of another by id or label. A missing tower is opened only in this workspace: by /boss tower, by a main, or by the guard's rule. With
91
91
  * `towerRuns.enabled` the sb server makes it (it starts no pi); `boss` is the boss's own command, which may start a server that was stopped on purpose.
92
92
  */
93
- const openTower = async (query?: string, create = s.isMain, boss = false) => {
93
+ const openTower = async (query?: string, create = s.isMain, boss = false, view = false) => {
94
94
  const all = await workspaces(run);
95
95
  const found = all.filter((w) => (query ? w.workspace_id === query || w.label === query : w.workspace_id === s.at.workspaceId));
96
96
  if (found.length !== 1) {
@@ -108,14 +108,14 @@ export function createReach({ pi, cfg, s, guiDir, me, role, tell }: Kit, server:
108
108
  throw new Error(`${target.label} has no tower yet: it opens when a member there promotes itself to main`);
109
109
  }
110
110
  if (towerRunsEnabled(cfg.stateDir ?? guiDir)) {
111
- // A live tower is the tower, whoever runs it; otherwise the server stands in for it.
112
- if (held && (await live(held))) return { target, routed: target !== asked ? asked : undefined, id: held, opened: false };
113
- const got = await ensureTowerVia(server.ctx(), { workspace: target.workspace_id, cwd: process.cwd(), boss }).catch((error: Error) => {
111
+ // A legacy resident already has a tab. A managed identity may be live without a viewer.
112
+ if (held && (!view || held !== towerId(server.ctx().slot, target.workspace_id)) && (await live(held))) return { target, routed: target !== asked ? asked : undefined, id: held, opened: false };
113
+ const got = await ensureTowerVia(server.ctx(), { workspace: target.workspace_id, cwd: process.cwd(), boss, view }).catch((error: Error) => {
114
114
  // A server stopped on purpose is told once per session, whichever automatic path (a promotion, the guard) hit it first; the error still goes to the caller.
115
115
  if (error.message === STOPPED && !toldStopped) tell(`Straw Boss: ${STOPPED}`, "warning"), toldStopped = true;
116
116
  throw error;
117
117
  });
118
- return { target, routed: target !== asked ? asked : undefined, id: got.id, opened: got.opened };
118
+ return { target, routed: target !== asked ? asked : undefined, id: got.id, opened: got.opened, tab: got.tab };
119
119
  }
120
120
  const moveFirst = (tabId: string) => api("tab.move", { tab_id: tabId, insert_index: 0 }).catch((error: Error) => tell(`Straw Boss: could not move the tower tab first: ${error.message}`, "warning"));
121
121
  return { target, routed: target !== asked ? asked : undefined, ...(await ensureTower({ run, sleep, live, moveFirst, model: towerModel(guiDir), trustDir: trustDir(guiDir) }, target, process.cwd())) };
@@ -482,6 +482,10 @@ export async function runServer(o: ServerOptions): Promise<ServerHandle> {
482
482
  const noAsk = askRefused(request, unattended);
483
483
  if (noAsk) return Promise.resolve({ ok: false, error: noAsk });
484
484
  switch (request.cmd) {
485
+ case "view-existing-tower": {
486
+ const workspace = text(request.workspace), holder = text(request.holder);
487
+ return workspace && holder && request.view === true ? answer(async t => ({ tab: await t.viewExisting(workspace, holder) })) : Promise.resolve({ ok: false, error: "Missing parent tower identity" });
488
+ }
485
489
  case "ensure-tower": {
486
490
  const claim = typeof request.made === "object" && request.made !== null ? (request.made as Record<string, unknown>) : undefined;
487
491
  const made = text(claim?.pane) && typeof claim?.at === "number" && Number.isFinite(claim.at) ? { pane: text(claim.pane)!, at: claim.at } : undefined;
@@ -19,7 +19,7 @@ export interface TowerAsk {
19
19
  /** The root pane of a base this run made a moment ago (desk mode): a bare shell nobody has used, which the server may type the prompt into where Herdr cannot tell an idle shell from a busy one. The server checks it before it believes it. */
20
20
  made?: { pane: string; at: number };
21
21
  /** The boss's own command (`/boss tower`): it clears a stop on purpose and starts the server. Anything else fails against a stopped server. */
22
- boss?: boolean;
22
+ boss?: boolean; view?: boolean;
23
23
  /** How long the ask waits for the server's answer (30 s by default). */
24
24
  ms?: number;
25
25
  }
@@ -68,7 +68,7 @@ async function serverFor(ctx: Ctx, boss: boolean) {
68
68
  export async function ensureTowerVia(ctx: Ctx, ask: TowerAsk): Promise<TowerAnswer> {
69
69
  const record = await serverFor(ctx, ask.boss === true);
70
70
  try {
71
- const { reply } = await callControl(record.socket, record.secret, { cmd: "ensure-tower", workspace: ask.workspace, ...(ask.cwd ? { cwd: ask.cwd } : {}), ...(ask.pane ? { pane: ask.pane } : {}), ...(ask.pid !== undefined ? { pid: ask.pid } : {}), ...(ask.made ? { made: ask.made } : {}) }, ask.ms ?? 30_000);
71
+ const { reply } = await callControl(record.socket, record.secret, { cmd: "ensure-tower", workspace: ask.workspace, ...(ask.view ? { view: true } : {}), ...(ask.cwd ? { cwd: ask.cwd } : {}), ...(ask.pane ? { pane: ask.pane } : {}), ...(ask.pid !== undefined ? { pid: ask.pid } : {}), ...(ask.made ? { made: ask.made } : {}) }, ask.ms ?? 30_000);
72
72
  if (!reply?.ok) throw new Error(`the sb server did not give the tower of ${ask.workspace}: ${String(reply?.error ?? "no answer")}`);
73
73
  const { ok: _ok, ...answer } = reply;
74
74
  // SAFETY: the server's `ensure-tower` reply carries exactly these fields (src/server/towers.ts, Ensured).
@@ -156,6 +156,7 @@ export interface Towers extends Returns {
156
156
  recovering(): boolean;
157
157
  /** Gives a workspace its tower (a promotion, `/boss tower`, a handover from a resident tower of this build). */
158
158
  /** `view`: headless runs only (towerRuns.headless): a viewer tab is made when none runs; without it the service has no tab (docs/specs/2026-11-23-f-entry.md §2.2). */
159
+ viewExisting(workspace: string, holder: string): Promise<string>;
159
160
  ensure(request: { workspace: string; pane?: string; cwd?: string; pid?: number; made?: { pane: string; at: number }; view?: boolean | "attended" }): Promise<Ensured>;
160
161
  /** The boss closed the tower: its tab goes, and the service with it. */
161
162
  close(workspace: string): Promise<{ workspace: string; id: string }>;
@@ -1160,6 +1161,7 @@ export function createTowers(o: TowersOptions): Towers {
1160
1161
  const target = isSub(asked) ? parentOf(all, asked) : asked;
1161
1162
  if (!target) throw new Error(`${asked.label} is a sub workspace with no open parent workspace, so it has no tower; open the parent workspace first`);
1162
1163
  if (isHead(target) || headLive()?.record.workspace === target.workspace_id) throw new Error(`${target.label} is the head tower's workspace: it has no workspace tower, the head tower is its own`);
1164
+ if (view === true) while (opening.has(target.workspace_id)) await opening.get(target.workspace_id); // an ordinary ensure in flight may return without a viewer
1163
1165
  const pending = opening.get(target.workspace_id) ?? openFor(target, target === asked ? pane : undefined, cwd, pid, target === asked ? made : undefined, view ?? false).finally(() => opening.delete(target.workspace_id));
1164
1166
  opening.set(target.workspace_id, pending);
1165
1167
  return pending;
@@ -1459,6 +1461,23 @@ export function createTowers(o: TowersOptions): Towers {
1459
1461
  },
1460
1462
  owns: (id) => [...services.values()].some((l) => l.record.id === id),
1461
1463
  watchSend: async (workspace, session, text, facts) => ((l) => (l && l.state === "live" && !l.stopped && !isHeadL(l) && l.control ? l.control.notify(session, { text, ...facts }) : Promise.resolve(false)))(services.get(workspace)),
1464
+ async viewExisting(ws, holder) {
1465
+ await activate();
1466
+ const target = (await workspaces(run)).find(w => w.workspace_id === ws);
1467
+ if (!target || isSub(target) || isHead(target) || target.tokens?.tower !== holder) throw new Error("The parent workspace has no live tower");
1468
+ if (holder === towerId(slot, ws)) {
1469
+ while (opening.has(ws)) await opening.get(ws);
1470
+ const l = services.get(ws);
1471
+ if (l && !l.stopped && l.state === "live" && l.record.id === holder) {
1472
+ if (l.record.tab) return l.record.tab;
1473
+ if (headless()) {
1474
+ const pending = openHeadless(target, l, undefined, true).finally(() => opening.delete(ws));
1475
+ opening.set(ws, pending); return (await pending).tab!;
1476
+ }
1477
+ }
1478
+ }
1479
+ throw new Error("The parent workspace has no live tower viewer");
1480
+ },
1462
1481
  identityOf: (workspace) => ((l) => (l && l.state === "live" && !l.stopped && !isHeadL(l) ? l.record.id : undefined))(services.get(workspace)),
1463
1482
  post: async (workspace, to, text, kind, extra) => ((l) => (l?.reach && !l.stopped ? Promise.all(to.map((id) => l.reach!.post(id, text, kind, "session", false, undefined, undefined, extra))).then((r) => r.every((x) => x.status === "sent")) : false))(services.get(workspace)),
1464
1483
  status: () => [...services.values()].filter((l) => !isHeadL(l)).map(row),
@@ -0,0 +1,33 @@
1
+ import { isSub, panes, parentOf, place, workspaces } from "./herdr.ts";
2
+ import type { Kit } from "./state.ts";
3
+ import type { createReach } from "./reach.ts";
4
+ import { ownFile } from "./netdata.ts";
5
+ import { slotOf, towerId } from "./server/record.ts";
6
+ import { towerRunsEnabled } from "./server/towerruns.ts";
7
+ import type { Request, Reply } from "./server/socket.ts";
8
+
9
+ /** A human's open-and-focus command. A linked checkout never joins and can only view an existing parent tower. */
10
+ export async function focusTower({ cfg, s, guiDir }: Kit, join: () => Promise<void>, reach: ReturnType<typeof createReach>, existing: (req: Request) => Promise<Reply>) {
11
+ const here = await place(cfg.run), all = await workspaces(cfg.run), own = all.find(w => w.workspace_id === here.workspaceId);
12
+ let tab: string | undefined;
13
+ if (own && isSub(own)) {
14
+ const parent = parentOf(all, own);
15
+ if (!parent?.tokens?.tower) throw new Error("The parent workspace has no live tower");
16
+ const dir = cfg.stateDir ?? guiDir, holder = parent.tokens.tower;
17
+ if (holder !== towerId(slotOf(dir, cfg.env), parent.workspace_id)) {
18
+ const resident = (await panes(cfg.run, parent.workspace_id)).find(p => p.agent === "pi" && ownFile(p.agent_session?.value, holder) && p.tokens?.sb_role === "tower");
19
+ if (!resident) throw new Error("The parent workspace has no live resident tower");
20
+ await cfg.run(["tab", "focus", resident.tab_id]); return;
21
+ }
22
+ if (!towerRunsEnabled(dir)) throw new Error("The tower service is off");
23
+ const reply = await existing({ cmd: "view-existing-tower", workspace: parent.workspace_id, holder: parent.tokens.tower, view: true });
24
+ if (!reply.ok || typeof reply.tab !== "string" || !reply.tab) throw new Error(String(reply.error ?? "The parent tower has no viewer"));
25
+ tab = reply.tab;
26
+ } else {
27
+ await join();
28
+ const tower = await reach.openTower(undefined, true, true, true);
29
+ tab = ("tab" in tower && tower.tab) || (await s.c.listSessions()).find(x => x.id === tower.id)?.herdrLocation?.tab?.id;
30
+ }
31
+ if (!tab) throw new Error("The tower has no viewer tab to focus");
32
+ await cfg.run(["tab", "focus", tab]);
33
+ }