pi-straw-boss 0.26.2 → 0.27.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.
Files changed (44) hide show
  1. package/README.md +37 -0
  2. package/README.zh-TW.md +37 -0
  3. package/dist/gui/assets/ask-C1mvQKbG.js +1 -0
  4. package/dist/gui/assets/chat-BECfofMv.js +2 -0
  5. package/dist/gui/assets/index-DI9km3B9.css +1 -0
  6. package/dist/gui/assets/index-gWx1_-3G.js +1 -0
  7. package/dist/gui/assets/layer-D1jSjgZJ.js +3 -0
  8. package/dist/gui/assets/lightbox-BfLxcOSU.js +1 -0
  9. package/dist/gui/assets/pair-CHVcdx5H.js +1 -0
  10. package/dist/gui/assets/spawn-DbHqsZJv.js +1 -0
  11. package/dist/gui/assets/views-JgP8ffyr.js +7 -0
  12. package/dist/gui/index.html +3 -2
  13. package/package.json +1 -1
  14. package/src/boss.ts +36 -0
  15. package/src/briefing.ts +33 -0
  16. package/src/closing.ts +23 -0
  17. package/src/dashboard.ts +108 -29
  18. package/src/election.ts +24 -0
  19. package/src/guard.ts +83 -0
  20. package/src/gui.ts +2 -91
  21. package/src/handover.ts +93 -0
  22. package/src/herdr.ts +39 -62
  23. package/src/host.ts +82 -0
  24. package/src/index.ts +37 -685
  25. package/src/membership.ts +115 -0
  26. package/src/net.ts +4 -4
  27. package/src/order.ts +3 -3
  28. package/src/presence.ts +57 -0
  29. package/src/reach.ts +96 -0
  30. package/src/session.ts +133 -0
  31. package/src/state.ts +106 -0
  32. package/src/tools.ts +77 -0
  33. package/src/tower.ts +44 -0
  34. package/src/towertab.ts +65 -0
  35. package/dist/gui/assets/ask-D1_QuXvf.js +0 -1
  36. package/dist/gui/assets/chat-DKFo83Ey.js +0 -2
  37. package/dist/gui/assets/dom-BaTXH9WU.js +0 -1
  38. package/dist/gui/assets/index-BQP3YgWb.js +0 -1
  39. package/dist/gui/assets/index-D4oTe33x.css +0 -1
  40. package/dist/gui/assets/layer-DS7hZlBy.js +0 -3
  41. package/dist/gui/assets/lightbox-BPldIRyA.js +0 -1
  42. package/dist/gui/assets/pair-F2FcMHbJ.js +0 -1
  43. package/dist/gui/assets/spawn-Bso_wUYV.js +0 -1
  44. package/dist/gui/assets/views-D7Y4KGK_.js +0 -8
package/src/boss.ts ADDED
@@ -0,0 +1,36 @@
1
+ import type { createHost } from "./host.ts";
2
+ import type { Membership } from "./membership.ts";
3
+ import type { Reach } from "./reach.ts";
4
+ import type { Kit } from "./state.ts";
5
+
6
+ /** What Tab completes after /boss; a bare /boss (take over as the main agent) has nothing to complete. */
7
+ const BOSS_ARGUMENTS = Object.entries({ status: "Show the coordinators", close: "Quit this session and close its pane", tower: "Open and focus the workspace tower", gui: "Open the net in the browser", "gui stop": "Close the browser GUI", "gui remote": "Open the GUI to your phone over Tailscale", "gui remote off": "Close the Tailscale entry" }).map(([value, description]) => ({ value, label: value, description }));
8
+
9
+ /** The /boss command. */
10
+ export function registerBoss({ pi, cfg, s, tell }: Kit, { host, membership, reach, closeSelf }: { host: ReturnType<typeof createHost>; membership: Membership; reach: Reach; closeSelf(keepPane: boolean): string | undefined }) {
11
+ pi.registerCommand("boss", {
12
+ description: "Take over as this tab's main agent (every session already joins as a member). /boss status shows the coordinators; /boss tower focuses the workspace tower (a main opens it when there is none); /boss close quits this session and closes its pane; /boss gui opens the net in the browser (/boss gui stop closes it; /boss gui remote opens it to your phone over Tailscale, /boss gui remote off closes that).",
13
+ // pi passes the whole argument text and replaces it with the chosen value, so each value is a full argument line.
14
+ getArgumentCompletions: (prefix) => {
15
+ const items = BOSS_ARGUMENTS.filter((item) => item.value.startsWith(prefix.trimStart()));
16
+ return items.length ? items : null;
17
+ },
18
+ handler: async (args, ctx) => {
19
+ s.ui = ctx.ui;
20
+ try {
21
+ if (/^gui( stop| remote( off)?)?$/.test(args.trim())) return await host.command(args.trim().slice(4));
22
+ const why = args.trim() === "close" ? (closeSelf(false) ?? "") : undefined;
23
+ if (why !== undefined) return void (why && tell(why, "error"));
24
+ if (args.trim() === "status") return tell(s.joined || s.isTower ? JSON.stringify(await reach.status(), null, 2) : "Not in the net: still joining, or this session cannot join.");
25
+ if (s.isTower) throw new Error("This session is the tower, not a main agent");
26
+ if (args.trim() !== "tower") return tell((await membership.promote(true)).text);
27
+ await membership.joinNet();
28
+ const tower = await reach.openTower(undefined, true); // anyone may open the tower by hand
29
+ const where = (await s.c.listSessions()).find((x) => x.id === tower.id)?.herdrLocation;
30
+ if (where?.tab) await cfg.run(["tab", "focus", where.tab.id]);
31
+ } catch (error) {
32
+ tell((error as Error).message, "error");
33
+ }
34
+ },
35
+ });
36
+ }
@@ -0,0 +1,33 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { ENTRY, type Kit, type Role } from "./state.ts";
4
+
5
+ const PROMPTS = ["main", "tower", "member", "member-no-main"];
6
+
7
+ /** The role prompt: a system prompt section, set when a run starts, and a steer when the role changes during one. */
8
+ export function createBriefing({ pi, cfg, s, role }: Kit) {
9
+ let prompts: Record<string, string> = {};
10
+ const promptOf = (current = role()) => (current === "member" && !s.mainId ? "member-no-main" : current);
11
+ // The role's prompt is a system prompt section, set when a run starts. A role that changes during a run (a member promoted as it
12
+ // dispatches a subagent, mains demoted as their tower quits) reaches the agent at its next step as a steer; an idle session gets it with its next run.
13
+ let briefed: Role | undefined, running = false;
14
+ const render = (text = "") => text.replace(/\{\{(\w+)\}\}/g, (_, key: string) => ({ dir: cfg.promptDir, ...s.info })[key] || "none yet");
15
+ return {
16
+ load: () => void (prompts = Object.fromEntries(PROMPTS.map((name) => [name, readFileSync(join(cfg.promptDir, `${name}.md`), "utf8").trim()]))),
17
+ rebrief() {
18
+ const current = role(), name = promptOf(current);
19
+ if (!running || current === briefed || !name) return;
20
+ briefed = current;
21
+ pi.sendMessage({ customType: ENTRY, content: `<straw-boss>\nYour Straw Boss role changed during this run. This replaces the role instructions in your system prompt:\n\n${render(prompts[name])}\n</straw-boss>`, display: true }, { deliverAs: "steer" });
22
+ },
23
+ /** A run starts: the role's prompt becomes the session's section. */
24
+ begin(sections: Record<string, string>) {
25
+ const current = role(), name = promptOf(current);
26
+ if (name) sections[ENTRY] = render(prompts[name]);
27
+ else delete sections[ENTRY];
28
+ [briefed, running] = [current, true];
29
+ },
30
+ settled: () => void (running = false),
31
+ };
32
+ }
33
+ export type Briefing = ReturnType<typeof createBriefing>;
package/src/closing.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { spawn } from "node:child_process";
2
+ import type { Kit } from "./state.ts";
3
+
4
+ /** Closes a pane once the pi process `pid` has exited, from a process of its own, so pi's shutdown runs to the end first. */
5
+ export const afterExit = (pid: number, args: string[]) => {
6
+ const herdr = process.env.HERDR_BIN_PATH || "herdr";
7
+ const script = `i=0; while kill -0 ${pid} 2>/dev/null && [ $i -lt 120 ]; do sleep 0.5; i=$((i+1)); done; exec "$0" "$@"`;
8
+ spawn("sh", ["-c", script, herdr, ...args], { detached: true, stdio: "ignore" }).unref();
9
+ };
10
+
11
+ /**
12
+ * Closing: pi quits as /quit would (its shutdown clears this session's tokens; a tower's quit clears the mains), then its pane closes, which
13
+ * closes an emptied tab and an emptied base with it. `keepPane` leaves the pane to a caller that closes the whole tab or base.
14
+ * Closing is this session's own: the GUI asks its bridge, /boss close asks here, and only a session that runs this extension can (not a subagent).
15
+ */
16
+ export function createClosing({ s }: Kit) {
17
+ return (keepPane: boolean): string | undefined => {
18
+ if (!s.quit) return "This session has not started yet.";
19
+ s.closing ??= { keepPane };
20
+ setTimeout(() => s.quit?.(), 50); // after the answer has gone out
21
+ return undefined;
22
+ };
23
+ }
package/src/dashboard.ts CHANGED
@@ -2,7 +2,7 @@ import { readdirSync, readFileSync, statSync } from "node:fs";
2
2
  import { basename, dirname, join } from "node:path";
3
3
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
4
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
5
- import { ARROW, headOf, type HerdrRun, isSub, MARK, type Pane, panes, parentOf, type Session, TOWER_LABEL, workspaces, type Workspace } from "./herdr.ts";
5
+ import { ARROW, headOf, type HerdrRun, type HerdrWorld, isSub, MARK, type Pane, parentOf, type Session, TOWER_LABEL, type Workspace, worldOf } from "./herdr.ts";
6
6
 
7
7
  // The tower's monitoring screen: a widget above the editor, never focused, redrawn only while something is working.
8
8
  //
@@ -22,7 +22,8 @@ export interface Row { group: "net" | "towers"; depth: number; mark: Mark; text:
22
22
  export interface Snapshot { title: string; mark: Mark; head: boolean; rows: Row[]; gui?: string }
23
23
  export type Tone = "accent" | "warning" | "muted" | "success" | "dim" | "error" | "border" | "title" | "tower" | "main" | "member";
24
24
  export type Paint = (tone: Tone, text: string) => string;
25
- export interface Sources { run: HerdrRun; sessions(): Promise<Session[]>; workspaceId: string; now?: number; gui?(): Promise<string | undefined> }
25
+ /** `world` reads the panes and workspaces; without it they are listed through `run`. */
26
+ export interface Sources { run: HerdrRun; world?: HerdrWorld; sessions(): Promise<Session[]>; workspaceId: string; now?: number; gui?(): Promise<string | undefined> }
26
27
 
27
28
  const KEY = "straw-boss-dashboard";
28
29
  const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
@@ -85,32 +86,88 @@ export function readJson(path: string): Record<string, unknown> {
85
86
  }
86
87
  }
87
88
 
89
+ // What a tick re-reads for every child is cached: the pane that runs each child (indexed once per pane list), the names in the two
90
+ // directories pi-herdr-agents keeps per session (until the directory changes), and a launch script's session file (until the script does).
91
+ const RACY_MS = 2000;
92
+ const childPanes = new WeakMap<Pane[], { size: number; index: Map<string, Pane> }>();
93
+ const listings = new Map<string, { mtime: bigint; readAt: number; names: string[] }>();
94
+ const scripts = new Map<string, { mtimeMs: number; session?: string }>();
95
+ const SUFFIX = /^(.*)-[0-9a-f]{1,8}-[0-9a-f]{1,8}-[0-9a-f]{1,4}$/;
96
+
97
+ /** The child ids a pane's session file can belong to: `ownFile` read from the file's side, so one pass over the panes replaces a match per child and pane. */
98
+ function childIds(file: string | undefined): string[] {
99
+ if (!file?.endsWith(".jsonl")) return [];
100
+ const name = file.slice(Math.max(file.lastIndexOf("/"), file.lastIndexOf("\\")) + 1, -".jsonl".length), ids: string[] = [];
101
+ for (let at = name.indexOf("_"); at >= 0; at = name.indexOf("_", at + 1)) {
102
+ const tail = name.slice(at + 1), stripped = SUFFIX.exec(tail)?.[1];
103
+ ids.push(tail, ...(stripped === undefined ? [] : [stripped]));
104
+ }
105
+ return ids;
106
+ }
107
+
108
+ /** The first pane in list order that runs each child. The index belongs to the list it was built from, which is a reading of Herdr and not changed after (one that grew or shrank is indexed again). */
109
+ function paneOfChild(all: Pane[], id: string): Pane | undefined {
110
+ let cached = childPanes.get(all);
111
+ if (cached?.size !== all.length) {
112
+ const index = new Map<string, Pane>();
113
+ for (const pane of all) for (const child of childIds(pane.agent_session?.value)) if (!index.has(child)) index.set(child, pane);
114
+ childPanes.set(all, (cached = { size: all.length, index }));
115
+ }
116
+ return cached.index.get(id);
117
+ }
118
+
119
+ /** The file names in `dir`, read again only once the directory has changed (a directory changed in the last two seconds is always read, as its timestamp may not tell two changes apart). */
120
+ function listed(dir: string): string[] {
121
+ try {
122
+ const stat = statSync(dir, { bigint: true }), cached = listings.get(dir);
123
+ // A listing read within RACY_MS of the directory's timestamp may have missed a change in the same tick (git's racy-index rule).
124
+ if (cached?.mtime === stat.mtimeNs && cached.readAt - Number(stat.mtimeNs / 1_000_000n) > RACY_MS) return cached.names;
125
+ const readAt = Date.now(), names = readdirSync(dir);
126
+ if (listings.size > 200) listings.clear();
127
+ listings.set(dir, { mtime: stat.mtimeNs, readAt, names });
128
+ return names;
129
+ } catch {
130
+ listings.delete(dir);
131
+ return []; // the directory is not there: nothing was ever launched from this session
132
+ }
133
+ }
134
+
135
+ /** The session file a launch script names, read again only when the script changed. */
136
+ function scriptSession(path: string): string | undefined {
137
+ try {
138
+ const { mtimeMs } = statSync(path), cached = scripts.get(path);
139
+ if (cached?.mtimeMs === mtimeMs) return cached.session;
140
+ const session = readFileSync(path, "utf8").match(/PI_SUBAGENT_SESSION='([^']+)'/)?.[1];
141
+ if (scripts.size > 500) scripts.clear();
142
+ scripts.set(path, { mtimeMs, session });
143
+ return session;
144
+ } catch {
145
+ return undefined; // the launch script is only a fallback source for the name and the session file
146
+ }
147
+ }
148
+
88
149
  /** The subagents a pi session launched: live ones, plus those that finished in the last 10 minutes. The dashboard shows the first `limit`. */
89
150
  export function subagents(parent: Pane | undefined, all: Pane[], now: number, limit = MAX_CHILDREN): Row[] {
90
151
  const file = parent?.agent_session?.value;
91
152
  if (!file) return [];
92
- const dir = artifacts(file);
93
- let files: string[] = [];
94
- try {
95
- files = readdirSync(join(dir, "subagent-activity"));
96
- } catch {} // no subagents were ever launched from this session
97
- return files
98
- .map((name) => {
99
- const id = name.replace(/\.json$/, "");
100
- const path = join(dir, "subagent-activity", name);
101
- return { id, path, pane: all.find((p) => ownFile(p.agent_session?.value, id)), age: now - statSync(path).mtimeMs };
153
+ const dir = artifacts(file), launched = listed(join(dir, "subagent-scripts"));
154
+ return listed(join(dir, "subagent-activity"))
155
+ .flatMap((name) => {
156
+ const id = name.replace(/\.json$/, ""), path = join(dir, "subagent-activity", name);
157
+ try {
158
+ const child = { id, path, pane: paneOfChild(all, id), age: now - statSync(path).mtimeMs };
159
+ return child.pane || child.age < RECENT_MS ? [child] : [];
160
+ } catch {
161
+ return []; // the activity file went away since the directory was listed
162
+ }
102
163
  })
103
- .filter((c) => c.pane || c.age < RECENT_MS)
104
164
  .map(({ id, path, pane }) => {
105
165
  const activity = readJson(path);
106
166
  // A child whose pane is gone, or back at a shell prompt, has finished.
107
167
  const mark: Mark = pane?.agent === "pi" ? markOf(pane.agent_status) : "done";
108
168
  // Only a pi pane's session file is the child's transcript; a reused pane running another agent is not read.
109
- let script: string | undefined, file = pane?.agent === "pi" ? pane.agent_session?.value : undefined;
110
- try {
111
- script = readdirSync(join(dir, "subagent-scripts")).find((f) => f.endsWith(`-${id}.sh`));
112
- file ??= readFileSync(join(dir, "subagent-scripts", script!), "utf8").match(/PI_SUBAGENT_SESSION='([^']+)'/)?.[1];
113
- } catch {} // the launch script is only a fallback source for the name and the session file
169
+ const script = launched.find((f) => f.endsWith(`-${id}.sh`));
170
+ const file = (pane?.agent === "pi" ? pane.agent_session?.value : undefined) ?? (script && scriptSession(join(dir, "subagent-scripts", script)));
114
171
  const name = pane?.label || (script?.slice(0, -`-${id}.sh`.length) ?? id.slice(0, 8));
115
172
  const doing = activity.toolActive ? String(activity.toolName) : String(activity.phase ?? "");
116
173
  const ended = pane?.agent !== "pi" || activity.phase === "done";
@@ -124,8 +181,8 @@ export function subagents(parent: Pane | undefined, all: Pane[], now: number, li
124
181
  * One reading of the world as rows: this tower's own net in detail (each tab's joined sessions with their subagents, then its
125
182
  * sub workspaces), and one summary line for every other tower. Other workspaces' sessions, and sessions that did not join, are not listed.
126
183
  */
127
- export async function collect({ run, sessions, workspaceId, now = Date.now(), gui }: Sources): Promise<Snapshot> {
128
- const [live, ps, all] = [await sessions(), await panes(run), await workspaces(run)];
184
+ export async function collect({ run, world = worldOf(run), sessions, workspaceId, now = Date.now(), gui }: Sources): Promise<Snapshot> {
185
+ const [live, { panes: ps, workspaces: all }] = await Promise.all([sessions(), world()]);
129
186
  const head = headOf(all);
130
187
  const mine = all.find((w) => w.workspace_id === workspaceId);
131
188
  const sessionRow = (s: Session, role: string): Row => {
@@ -153,19 +210,36 @@ export async function collect({ run, sessions, workspaceId, now = Date.now(), gu
153
210
  }
154
211
 
155
212
  export interface Dashboard { poke(): void; stop(): void }
156
- export interface Timing { frameMs?: number; pollMs?: number; minGapMs?: number }
213
+ /** `watch` subscribes to what changes the screen and calls `refresh` for each; it returns the unsubscribe. */
214
+ export interface Timing { frameMs?: number; pollMs?: number; minGapMs?: number; debounceMs?: number; watch?(refresh: () => void): () => void }
215
+
216
+ /** The dashboard re-reads when Herdr reports a change; this poll only catches what no event told (a missed one, a subagent's activity file). */
217
+ export const SAFETY_MS = 30_000;
218
+ const DEBOUNCE_MS = 500;
157
219
 
158
220
  /**
159
- * Shows the dashboard in a tower's TUI. The spinner timer (8 fps) runs only while a row is working; the data poll (3 s)
160
- * runs while the widget exists. stop() clears both timers and the widget, and pi disposing the widget does the same.
221
+ * Shows the dashboard in a tower's TUI. The spinner timer (8 fps) runs only while a row is working. Data is re-read when `watch` reports
222
+ * a change (collected for `debounceMs`, so a burst is one read), when poke() says intercom changed (at once), and every `pollMs` as a safety net;
223
+ * two reads are never closer than `minGapMs`, and a request that comes inside the gap or while a read runs is read when it ends, not dropped.
224
+ * stop() clears the timers and the subscription and removes the widget, and pi disposing the widget does the same.
161
225
  */
162
- export function startDashboard({ ui, collect: read, frameMs = 125, pollMs = 3000, minGapMs = 500 }: { ui: ExtensionContext["ui"]; collect(): Promise<Snapshot> } & Timing): Dashboard {
226
+ export function startDashboard({ ui, collect: read, watch, frameMs = 125, pollMs = SAFETY_MS, minGapMs = 500, debounceMs = DEBOUNCE_MS }: { ui: ExtensionContext["ui"]; collect(): Promise<Snapshot> } & Timing): Dashboard {
163
227
  let live: Dashboard | undefined;
164
228
  ui.setWidget(KEY, (tui, theme) => {
165
- let snap: Snapshot = { title: "", mark: "unknown", head: false, rows: [] }, frame = 0, busy = false, stopped = false, last = 0;
166
- let spinner: ReturnType<typeof setInterval> | undefined;
229
+ let snap: Snapshot = { title: "", mark: "unknown", head: false, rows: [] }, frame = 0, busy = false, again = false, stopped = false, last = 0, due = Infinity;
230
+ let spinner: ReturnType<typeof setInterval> | undefined, wake: ReturnType<typeof setTimeout> | undefined;
231
+ // One pending read at a time, at the earliest time anyone asked for (and not inside the gap after the last read).
232
+ const schedule = (delay: number) => {
233
+ const at = Math.max(Date.now() + delay, last + minGapMs);
234
+ if (stopped || at >= due) return;
235
+ clearTimeout(wake);
236
+ due = at;
237
+ // A read that ran meanwhile moved `last`, so the gap is checked again when the timer fires.
238
+ wake = setTimeout(() => ((due = Infinity), Date.now() < last + minGapMs ? schedule(0) : void refresh()), Math.max(0, at - Date.now())).unref();
239
+ };
167
240
  const refresh = async () => {
168
- if (busy || stopped) return;
241
+ if (stopped) return;
242
+ if (busy) return void (again = true);
169
243
  busy = true;
170
244
  try {
171
245
  snap = await read();
@@ -179,15 +253,20 @@ export function startDashboard({ ui, collect: read, frameMs = 125, pollMs = 3000
179
253
  if (working && !spinner) spinner = setInterval(() => (frame++, tui.requestRender()), frameMs).unref();
180
254
  if (!working && spinner) spinner = void clearInterval(spinner);
181
255
  tui.requestRender();
256
+ if (again) (again = false, schedule(0));
182
257
  };
183
- const poll = setInterval(() => void refresh(), pollMs).unref();
258
+ const poll = setInterval(() => schedule(0), pollMs).unref();
259
+ const unwatch = watch?.(() => schedule(debounceMs));
184
260
  const stop = () => {
261
+ if (stopped) return;
185
262
  stopped = true;
186
263
  clearInterval(poll);
264
+ clearTimeout(wake);
187
265
  clearInterval(spinner);
188
266
  spinner = undefined;
267
+ unwatch?.();
189
268
  };
190
- live = { poke: () => void (Date.now() - last >= minGapMs && refresh()), stop };
269
+ live = { poke: () => schedule(0), stop };
191
270
  void refresh();
192
271
  // Every color is a theme role. The title and the role marks are bold: the tower in warning, a main agent in accent, a member in success.
193
272
  const strong: Partial<Record<Tone, "accent" | "warning" | "success">> = { title: "accent", tower: "warning", main: "accent", member: "success" };
@@ -0,0 +1,24 @@
1
+ import type { Channel, Kit } from "./state.ts";
2
+
3
+ /** Who is the tab's main: the owner of the tab channel records it, and decides the claims members send. */
4
+ export function createElection({ cfg, s, me, tell }: Kit) {
5
+ // The owner records who is main. Promotion is first come, first served, and the main stays until it leaves: a later owner change never swaps it.
6
+ const pin = (channel: Channel, main?: string) => {
7
+ if (channel.snapshot().owner?.sessionId !== me()) return;
8
+ channel.commitState({ v: 1, ...(main ? { main } : {}), since: cfg.now() });
9
+ if (channel === s.c) s.pinned = main;
10
+ };
11
+ // The owner decides a claim: a tab has one main, so a claim is dropped while a live main exists, unless the user forced it with /boss.
12
+ const claim = async (channel: Channel, from: string, force: boolean) => {
13
+ try {
14
+ if (channel.snapshot().owner?.sessionId !== me()) return;
15
+ const current = (channel === s.c ? s.pinned : undefined) ?? (channel.snapshot().state?.payload as { main?: string } | undefined)?.main;
16
+ if (!force && current && current !== from && (await channel.listSessions()).some((x) => x.id === current)) return;
17
+ pin(channel, from);
18
+ } catch (error) {
19
+ tell(`Straw Boss: ${(error as Error).message}`, "warning");
20
+ }
21
+ };
22
+ return { pin, claim };
23
+ }
24
+ export type Election = ReturnType<typeof createElection>;
package/src/guard.ts ADDED
@@ -0,0 +1,83 @@
1
+ import { panes, workspaces } from "./herdr.ts";
2
+ import type { Election } from "./election.ts";
3
+ import type { Reach } from "./reach.ts";
4
+ import type { Kit } from "./state.ts";
5
+
6
+ // The tower and the mains go together (guard below): Herdr's events start each check, and a sweep every GUARD_MS catches what no event tells; how
7
+ // long a tower may be gone (a /reload) before the mains are cleared, and how long a fresh main's tower may take to open.
8
+ export const GUARD_MS = 4 * 60_000;
9
+ const TOWER_GRACE_MS = 15_000, TOWER_OPEN_MS = 60_000;
10
+
11
+ /** The tab channel owner's check that a base has mains only while it has a tower. */
12
+ export function createGuard({ cfg, s, me }: Kit, { claim, pin, openTower }: Election & Pick<Reach, "openTower">) {
13
+ const { run, autoTower, couple, guardMs, events, now } = cfg;
14
+ // A base has mains only while it has a tower. The owner of each tab channel, its earliest member, checks when Herdr says a workspace's tokens
15
+ // or this workspace's panes changed, and every guardMs: with a live tower and no live main it promotes itself; with no tower for
16
+ // TOWER_GRACE_MS (at once when the tower quit) it clears the tab's main, unless that main is younger than TOWER_OPEN_MS and its tower may
17
+ // still be opening. A check that has to wait for either sets one timer for it. A demoted main keeps its subagents.
18
+ let missing: number | undefined, guardTimer: ReturnType<typeof setInterval> | undefined, unlisten: (() => void) | undefined;
19
+ let soon: ReturnType<typeof setTimeout> | undefined, soonAt = Infinity, checking = false, again: boolean | undefined;
20
+ const guard = async (joining = false) => {
21
+ const owner = s.c.snapshot().owner?.sessionId === me();
22
+ if (!s.joined || s.isTower || s.stopped || (!owner && !joining)) return void (missing = undefined);
23
+ const sessions = await s.c.listSessions(), all = await workspaces(run), ws = all.find((w) => w.workspace_id === s.at.workspaceId);
24
+ const live = (id?: string) => Boolean(id && sessions.some((x) => x.id === id));
25
+ const state = s.c.snapshot().state?.payload as { main?: string; since?: number } | undefined, main = s.pinned ?? state?.main;
26
+ if (live(ws?.tokens?.tower)) {
27
+ missing = undefined;
28
+ if (owner && !live(main)) await claim(s.c, me(), false);
29
+ return;
30
+ }
31
+ // A tower opens by itself when this base has two members while another base already has one: they start to collide (the other rule, a
32
+ // member dispatching a subagent, promotes it in tool_call, and a promotion opens the tower). A member that joins checks it too.
33
+ // A tower closed on purpose stays closed until the base grows past the members it had then (a subagent or /boss tower opens it any time).
34
+ if (autoTower && all.some((w) => w.workspace_id !== s.at.workspaceId && live(w.tokens?.tower))) {
35
+ const members = (await panes(run, s.at.workspaceId)).filter((p) => ["member", "main"].includes(p.tokens?.sb_role ?? "")).length;
36
+ if (members >= 2 && members > Number(ws?.tokens?.sb_tower_quit ?? -1)) return void (await openTower(undefined, true));
37
+ }
38
+ if (!owner) return;
39
+ missing ??= now();
40
+ if (!live(main) || (s.pinned && s.pinned !== state?.main)) return;
41
+ if (now() - (state?.since ?? 0) < TOWER_OPEN_MS) return wake((state?.since ?? 0) + TOWER_OPEN_MS);
42
+ if (ws?.tokens?.sb_tower_quit !== undefined || now() - missing >= TOWER_GRACE_MS) pin(s.c);
43
+ else wake(missing + TOWER_GRACE_MS);
44
+ };
45
+ /** One check at a time, queued with the claims; a request during a check runs once more after it. */
46
+ const check = (joining = false) => {
47
+ if (!couple) return;
48
+ if (checking) return void (again = Boolean(again) || joining);
49
+ checking = true;
50
+ s.queue = s.queue.then(() => guard(joining).catch(() => {})).finally(() => {
51
+ checking = false;
52
+ const next = again;
53
+ again = undefined;
54
+ if (next !== undefined) check(next);
55
+ });
56
+ };
57
+ /** A check at `when` (on the clock `now`), keeping only the earliest one asked for. */
58
+ const wake = (when: number) => {
59
+ if (when >= soonAt) return;
60
+ clearTimeout(soon);
61
+ soonAt = when;
62
+ (soon = setTimeout(() => ((soonAt = Infinity), check()), Math.max(0, when - now()) + 50)).unref();
63
+ };
64
+ return {
65
+ check,
66
+ keep() {
67
+ if (!couple) return;
68
+ if (guardMs && !guardTimer) (guardTimer = setInterval(() => check(), guardMs)).unref();
69
+ unlisten ??= events(["workspace.metadata_updated", "pane.closed", "pane.agent_detected"], (e) => {
70
+ const ws = e && (e.event === "workspace_metadata_updated" ? undefined : String(e.data.workspace_id ?? (e.data.pane as { workspace_id?: string } | undefined)?.workspace_id ?? ""));
71
+ if (!e || ws === undefined || ws === s.at.workspaceId) check(); // any workspace's tokens (its tower), this one's panes, or a reconnection
72
+ });
73
+ check(true);
74
+ },
75
+ stop() {
76
+ clearInterval(guardTimer);
77
+ clearTimeout(soon);
78
+ unlisten?.();
79
+ [guardTimer, unlisten, soonAt] = [undefined, undefined, Infinity];
80
+ },
81
+ };
82
+ }
83
+ export type Guard = ReturnType<typeof createGuard>;
package/src/gui.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { createHash, randomBytes } from "node:crypto";
3
- import { mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
4
- import { createServer, type IncomingMessage, request, type ServerResponse } from "node:http";
3
+ import { readdirSync, readFileSync, statSync } from "node:fs";
4
+ import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
5
5
  import type { AddressInfo } from "node:net";
6
6
  import { extname, join } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
@@ -176,95 +176,6 @@ export async function startGui({ read, net, call, hub, dir = BUNDLE, port = 0, t
176
176
  };
177
177
  }
178
178
 
179
- // One server per machine. gui.json in the state directory records the running server (pid, port, token, owner session), and
180
- // gui.lock makes the check-and-start atomic, so a second /boss gui, from this session or another, opens the running server
181
- // instead of starting one. A dead server's port and token are reused, so a page left open reconnects to its successor. Any session reaches
182
- // the running one: it asks it to stop (requestStop), or takes it over, stopping it and starting its own on the same URL. A session whose
183
- // pi-straw-boss is newer takes it over unasked, so an update reaches every open page once one session has reloaded.
184
- /** `ownerSession` is the owner's intercom session id: bridges follow it to the server's dialog channel. `reload` marks a server its owner's /reload stopped. */
185
- export interface GuiRecord { pid: number; port: number; token: string; csrf?: string; owner: string; ownerSession?: string; version?: string; reload?: boolean }
186
- /** `stale`: the running server is older and could not be taken over. */
187
- export interface Shared { url: string; owner: string; mine?: Gui; stale?: boolean }
188
-
189
- /** Whether version `a` is newer than `b`; a server that recorded none predates the handover. */
190
- export function newer(a: string, b?: string) {
191
- const [x, y] = [a, b ?? "0"].map((v) => [...v.split(/[.-]/).slice(0, 3).map(Number), 0, 0].slice(0, 3)) as [number[], number[]];
192
- const i = x.findIndex((n, j) => n !== y[j]);
193
- return i >= 0 && x[i]! > y[i]!;
194
- }
195
- export const urlOf = (r: GuiRecord) => `http://127.0.0.1:${r.port}/${r.token}/`;
196
-
197
- export function readRecord(dir: string): GuiRecord | undefined {
198
- try {
199
- return JSON.parse(readFileSync(join(dir, "gui.json"), "utf8")) as GuiRecord;
200
- } catch {
201
- return undefined;
202
- }
203
- }
204
-
205
- /**
206
- * Marks the record of the server this process runs, so the extension that loads after its /reload starts it again on the same URL.
207
- * Matched by pid, not by session id: pi-intercom, loaded first, has already cleared PI_INTERCOM_SESSION_ID when this runs at shutdown.
208
- */
209
- export function markReload(dir: string, pid = process.pid) {
210
- const record = readRecord(dir);
211
- if (record?.pid === pid) writeFileSync(join(dir, "gui.json"), JSON.stringify({ ...record, reload: true }), { mode: 0o600 });
212
- }
213
-
214
- /** Asks a recorded server to stop, as its own page would, and waits until it is gone; false when it refused (a server from before 0.11.0) or stayed up. */
215
- export async function requestStop(r: GuiRecord, asked: Asked, sleep: (ms: number) => Promise<void>) {
216
- const body = JSON.stringify(asked), origin = `http://127.0.0.1:${r.port}`;
217
- const status = await new Promise<number>((done) => {
218
- const headers = { host: `127.0.0.1:${r.port}`, origin, "content-type": "application/json", "x-sb-csrf": r.csrf ?? "", "content-length": Buffer.byteLength(body) };
219
- const req = request({ host: "127.0.0.1", port: r.port, path: `/${r.token}/api/server/stop`, method: "POST", headers, agent: false, timeout: 2000 }, (res) => (res.resume(), done(res.statusCode ?? 0)));
220
- req.on("error", () => done(0)).on("timeout", () => (req.destroy(), done(0)));
221
- req.end(body);
222
- });
223
- for (const end = Date.now() + 5000; status === 202 && Date.now() < end; await sleep(100)) if (!(await answers(r))) return true;
224
- return false;
225
- }
226
-
227
- /** Whether a recorded server answers its own page. */
228
- export const answers = (r: GuiRecord) =>
229
- new Promise<boolean>((done) => {
230
- const req = request({ host: "127.0.0.1", port: r.port, path: `/${r.token}/`, headers: { host: `127.0.0.1:${r.port}` }, agent: false, timeout: 1000 }, (res) => {
231
- res.resume();
232
- done(res.statusCode === 200);
233
- });
234
- req.on("error", () => done(false)).on("timeout", () => (req.destroy(), done(false)));
235
- req.end();
236
- });
237
-
238
- /** `take` takes the running server over whatever its version; a newer `version` takes it over anyway. */
239
- export async function sharedGui(dir: string, [owner, ownerSession]: [string, string], start: (prefer: { port?: number; token?: string; csrf?: string }) => Promise<Gui>, sleep: (ms: number) => Promise<void>, { version = VERSION, take = false } = {}): Promise<Shared> {
240
- mkdirSync(dir, { recursive: true, mode: 0o700 });
241
- const lock = join(dir, "gui.lock");
242
- for (let tries = 0; ; tries++) {
243
- try {
244
- writeFileSync(lock, String(process.pid), { flag: "wx" });
245
- break;
246
- } catch (error) {
247
- if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
248
- // A lock older than 10 s was left by a session that died while starting the server.
249
- const age = Date.now() - (statSync(lock, { throwIfNoEntry: false })?.mtimeMs ?? Date.now());
250
- if (age > 10_000) rmSync(lock, { force: true });
251
- else if (tries >= 50) throw new Error("Another session is starting the straw net GUI; try again");
252
- else await sleep(200);
253
- }
254
- }
255
- try {
256
- const record = readRecord(dir);
257
- const theirs = record && (await answers(record)) && { url: urlOf(record), owner: record.owner };
258
- if (theirs && !(take || newer(version, record.version))) return theirs;
259
- if (theirs && !(await requestStop(record, { by: owner, take: true }, sleep))) return { ...theirs, stale: true };
260
- const gui = await start(record ? { port: record.port, token: record.token, csrf: record.csrf } : {});
261
- writeFileSync(join(dir, "gui.json"), JSON.stringify({ pid: process.pid, port: gui.port, token: gui.token, csrf: gui.csrf, owner, ownerSession, version }), { mode: 0o600 });
262
- return { url: gui.url, owner, mine: gui };
263
- } finally {
264
- rmSync(lock, { force: true });
265
- }
266
- }
267
-
268
179
  /** Opens the default browser; rejects when the platform command fails, so the caller can show the URL instead. */
269
180
  export const openBrowser = (url: string) =>
270
181
  new Promise<void>((done, fail) => {
@@ -0,0 +1,93 @@
1
+ import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { request } from "node:http";
3
+ import { join } from "node:path";
4
+ import { type Asked, type Gui, VERSION } from "./gui.ts";
5
+
6
+ // One server per machine. gui.json in the state directory records the running server (pid, port, token, owner session), and
7
+ // gui.lock makes the check-and-start atomic, so a second /boss gui, from this session or another, opens the running server
8
+ // instead of starting one. A dead server's port and token are reused, so a page left open reconnects to its successor. Any session reaches
9
+ // the running one: it asks it to stop (requestStop), or takes it over, stopping it and starting its own on the same URL. A session whose
10
+ // pi-straw-boss is newer takes it over unasked, so an update reaches every open page once one session has reloaded.
11
+ /** `ownerSession` is the owner's intercom session id: bridges follow it to the server's dialog channel. `reload` marks a server its owner's /reload stopped. */
12
+ export interface GuiRecord { pid: number; port: number; token: string; csrf?: string; owner: string; ownerSession?: string; version?: string; reload?: boolean }
13
+ /** `stale`: the running server is older and could not be taken over. */
14
+ export interface Shared { url: string; owner: string; mine?: Gui; stale?: boolean }
15
+
16
+ /** Whether version `a` is newer than `b`; a server that recorded none predates the handover. */
17
+ export function newer(a: string, b?: string) {
18
+ const [x, y] = [a, b ?? "0"].map((v) => [...v.split(/[.-]/).slice(0, 3).map(Number), 0, 0].slice(0, 3)) as [number[], number[]];
19
+ const i = x.findIndex((n, j) => n !== y[j]);
20
+ return i >= 0 && x[i]! > y[i]!;
21
+ }
22
+ export const urlOf = (r: GuiRecord) => `http://127.0.0.1:${r.port}/${r.token}/`;
23
+
24
+ export function readRecord(dir: string): GuiRecord | undefined {
25
+ try {
26
+ return JSON.parse(readFileSync(join(dir, "gui.json"), "utf8")) as GuiRecord;
27
+ } catch {
28
+ return undefined;
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Marks the record of the server this process runs, so the extension that loads after its /reload starts it again on the same URL.
34
+ * Matched by pid, not by session id: pi-intercom, loaded first, has already cleared PI_INTERCOM_SESSION_ID when this runs at shutdown.
35
+ */
36
+ export function markReload(dir: string, pid = process.pid) {
37
+ const record = readRecord(dir);
38
+ if (record?.pid === pid) writeFileSync(join(dir, "gui.json"), JSON.stringify({ ...record, reload: true }), { mode: 0o600 });
39
+ }
40
+
41
+ /** Asks a recorded server to stop, as its own page would, and waits until it is gone; false when it refused (a server from before 0.11.0) or stayed up. */
42
+ export async function requestStop(r: GuiRecord, asked: Asked, sleep: (ms: number) => Promise<void>) {
43
+ const body = JSON.stringify(asked), origin = `http://127.0.0.1:${r.port}`;
44
+ const status = await new Promise<number>((done) => {
45
+ const headers = { host: `127.0.0.1:${r.port}`, origin, "content-type": "application/json", "x-sb-csrf": r.csrf ?? "", "content-length": Buffer.byteLength(body) };
46
+ const req = request({ host: "127.0.0.1", port: r.port, path: `/${r.token}/api/server/stop`, method: "POST", headers, agent: false, timeout: 2000 }, (res) => (res.resume(), done(res.statusCode ?? 0)));
47
+ req.on("error", () => done(0)).on("timeout", () => (req.destroy(), done(0)));
48
+ req.end(body);
49
+ });
50
+ for (const end = Date.now() + 5000; status === 202 && Date.now() < end; await sleep(100)) if (!(await answers(r))) return true;
51
+ return false;
52
+ }
53
+
54
+ /** Whether a recorded server answers its own page. */
55
+ export const answers = (r: GuiRecord) =>
56
+ new Promise<boolean>((done) => {
57
+ const req = request({ host: "127.0.0.1", port: r.port, path: `/${r.token}/`, headers: { host: `127.0.0.1:${r.port}` }, agent: false, timeout: 1000 }, (res) => {
58
+ res.resume();
59
+ done(res.statusCode === 200);
60
+ });
61
+ req.on("error", () => done(false)).on("timeout", () => (req.destroy(), done(false)));
62
+ req.end();
63
+ });
64
+
65
+ /** `take` takes the running server over whatever its version; a newer `version` takes it over anyway. */
66
+ export async function sharedGui(dir: string, [owner, ownerSession]: [string, string], start: (prefer: { port?: number; token?: string; csrf?: string }) => Promise<Gui>, sleep: (ms: number) => Promise<void>, { version = VERSION, take = false } = {}): Promise<Shared> {
67
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
68
+ const lock = join(dir, "gui.lock");
69
+ for (let tries = 0; ; tries++) {
70
+ try {
71
+ writeFileSync(lock, String(process.pid), { flag: "wx" });
72
+ break;
73
+ } catch (error) {
74
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
75
+ // A lock older than 10 s was left by a session that died while starting the server.
76
+ const age = Date.now() - (statSync(lock, { throwIfNoEntry: false })?.mtimeMs ?? Date.now());
77
+ if (age > 10_000) rmSync(lock, { force: true });
78
+ else if (tries >= 50) throw new Error("Another session is starting the straw net GUI; try again");
79
+ else await sleep(200);
80
+ }
81
+ }
82
+ try {
83
+ const record = readRecord(dir);
84
+ const theirs = record && (await answers(record)) && { url: urlOf(record), owner: record.owner };
85
+ if (theirs && !(take || newer(version, record.version))) return theirs;
86
+ if (theirs && !(await requestStop(record, { by: owner, take: true }, sleep))) return { ...theirs, stale: true };
87
+ const gui = await start(record ? { port: record.port, token: record.token, csrf: record.csrf } : {});
88
+ writeFileSync(join(dir, "gui.json"), JSON.stringify({ pid: process.pid, port: gui.port, token: gui.token, csrf: gui.csrf, owner, ownerSession, version }), { mode: 0o600 });
89
+ return { url: gui.url, owner, mine: gui };
90
+ } finally {
91
+ rmSync(lock, { force: true });
92
+ }
93
+ }