@gorlitzer-labs/seldon 0.17.1 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,64 +9,73 @@
9
9
  ╚══════╝╚══════╝╚══════╝╚═════╝ ╚═════╝ ╚═╝ ╚═══╝
10
10
  ```
11
11
 
12
- **One screen for every coding agent** — Claude Code, Codex, opencode — on every project and
13
- machine: what is working, what needs you, what is next on the plan.
14
-
15
- `seldon` is the panel. `seldon install` adds the optional add-ons (rooms, voice, secrets, the
16
- plan), each via its native method (npm for the Node tools, a shell installer for bifrost, a
17
- venv for demerzel).
12
+ **Every coding agent you run — Claude Code, Codex, opencode — on every project, every machine,
13
+ one screen.** See who needs you. Jump there. Answer. Move on.
18
14
 
19
15
  ## Install
20
16
 
21
17
  ```bash
22
- pnpm add -g @gorlitzer-labs/seldon # or: bun add -g … · npm i -g …
18
+ pnpm add -g @gorlitzer-labs/seldon # or bun / npm
19
+ seldon ws # the workspace
23
20
  seldon # the panel
24
- seldon install # the add-on checklist — ↑↓ move · space pick · a all · enter
21
+ seldon install # add-ons: ↑↓ move · space pick · enter
25
22
  ```
26
23
 
27
- Or name the modules directly:
24
+ ## The workspace — `seldon ws`
28
25
 
29
- ```bash
30
- seldon install foundation comb # install just these
31
- seldon doctor # check external deps (tmux, sops, age, tailscale, python)
32
- seldon list # everything available
26
+ Every agent, on every machine, beside the one you're talking to. One key to switch.
27
+
28
+ ```text
29
+ SELDON ⚑ 2 ● 3 │ ── fix-save-crash ──────────────────────────
30
+ │ ❯ fix the save crash on resume
31
+ stranded │ Read src/save/slot.ts
32
+ ❯1 ⚑ 🦊 fix-save-crash │ Allow this command? ./gradlew test
33
+ needs you · permission │ 1 Yes 2 Always 3 No
34
+ 2 ● 🐙 smoke-harness │
35
+ working · 40m · codex │
36
+ weather │
37
+ 3 ⚑ 🦉 add-cache │
38
+ needs you · @mini │
39
+ 4 ○ 🐢 docs-pass │
40
+ SELDON Alt-1…9 agent · Alt-n next ⚑ · Alt-s list · Alt-h home · Alt-q leave
33
41
  ```
34
42
 
43
+ | key | does |
44
+ |---|---|
45
+ | `Alt-1`…`9` | open that agent |
46
+ | `Alt-n` | next agent that needs you |
47
+ | `Alt-s` | the list (on a phone it's behind this key) |
48
+ | `Alt-h` | home: the full panel on the right |
49
+ | `Alt-q` | leave. Agents keep running |
50
+
51
+ - **Real terminals.** The right side is the agent itself, not a copy.
52
+ - **Switching never stops anything.** Leave, reconnect from anywhere, it's all still there.
53
+ - **Both laptops, one list.** Agents on `seldon machines` open over ssh in the same pane. A sleeping one shows ☾ and waits.
54
+ - **Phone.** `ssh` in, run `seldon ws`. Under 90 columns one pane fills the screen.
55
+ - **Emoji per agent.** Same name, same face, everywhere.
56
+ - **No Alt key?** `Ctrl-g` then the key. macOS: turn on *Option as Meta*.
57
+ - **Your tmux is untouched.** It runs on its own server. `seldon ws stop` closes it.
58
+
35
59
  ## The panel — `seldon`
36
60
 
37
61
  ```text
38
- SELDON 1 need you · 2 working · 1 idle ● watcher ○ voice
62
+ SELDON 1 need you · 2 working · 1 idle ● watcher
39
63
 
40
64
  ❯ stranded plan 5 · 2 done
41
- ⚑ fix-save-crash claude needs you: permission prompt 2m
42
- ● smoke-harness codex working 40m
43
- weather plan 2 · 0 done
44
- ● add-cache claude working 12m
45
- ○ docs-pass claude idle 1h
46
-
47
- ↑↓ move · ⏎ open · x stop · R resume · n new lane · p plan · r refresh · q quit
48
- U start stack · D stop stack · i install
65
+ ⚑ fix-save-crash claude needs you: permission prompt 2m
66
+ ● smoke-harness codex working 40m
49
67
  ```
50
68
 
51
- Every coding agent on this machine — Claude Code, Codex, opencode — grouped by project (a
52
- worktree counts for its main repo), most urgent first, refreshed every two seconds. `⏎` on an
53
- agent opens it; `⏎` on a project runs `go`. Claude agents report their own state via
54
- `claude agents --json`; Codex and opencode do after `seldon setup` (until then they read
55
- *running*). Without a terminal
56
- (a script, a hook, an agent's shell) the same rows are printed as plain text.
57
-
58
69
  | key | does |
59
70
  |---|---|
60
- | `n` | new lane: type the task, pick `1` claude · `2` codex · `3` opencode (⏎ = claude) |
61
- | `p` | the project's plan (`docs/QUEUE.md`); `⏎` on an item starts a lane on it, `a` adds one |
62
- | `⏎` | on an agent: open it · on a project: `seldon go` |
63
- | `x` `x` | stop the agent (asks twice) |
64
- | `R` | resume what a reboot stopped; on a project, all of its stopped lanes |
71
+ | `n` | new lane: task, then `1` claude · `2` codex · `3` opencode |
72
+ | `p` | the plan (`docs/QUEUE.md`); `⏎` starts a lane on an item |
73
+ | `⏎` | open the agent |
74
+ | `x` `x` | stop it |
75
+ | `R` | resume what a reboot stopped |
65
76
 
66
- Every lane gets its own branch and worktree. Claude lanes run as `claude --bg -w <slug>`, so
67
- they live under Claude's own supervisor and show in `claude agents` too. Codex and opencode
68
- lanes run in tmux (`seldon_<slug>`), in a worktree under `~/.seldon/worktrees/`, and are
69
- recorded in `~/.seldon/lanes.json`. A plan item shows the lane working on it.
77
+ Each lane gets its own branch and worktree. Claude lanes run under Claude's supervisor
78
+ (`claude --bg -w`); Codex and opencode run in tmux (`seldon_<slug>`).
70
79
 
71
80
  ## Lanes from the command line
72
81
 
@@ -131,42 +140,7 @@ seldon machines # each one, and whether it an
131
140
  - **How it reaches them:** the panel runs `ssh <machine> seldon lanes --json` in the background
132
141
  every 10 seconds, so a sleeping machine never freezes it, and it acts with
133
142
  `ssh <machine> seldon lane <verb> <key>`.
134
- - **From a phone:** `ssh` to any one machine and run `seldon`. Below 70 columns it switches to
135
- one line per lane.
136
-
137
- ## On your phone — `seldon serve`
138
-
139
- The panel as a web app, for a phone (or any browser). Same lanes, same actions, a touch screen
140
- instead of a terminal: what needs you first, the agent's screen, quick replies, stop / resume /
141
- remove, new lanes and the plan, for this machine and every machine in `seldon machines`.
142
-
143
- ```bash
144
- seldon serve # http://localhost:7930/#t=<token> on this machine only
145
- seldon serve --tailnet # + HTTPS on your tailnet, for your tailscale login only
146
- seldon serve --tailnet --owner you@example.com # a different login than this machine's
147
- seldon serve --allow-reply # let the phone type into agents (off by default)
148
- ```
149
-
150
- - **Nothing is open by default.** It listens on loopback only. `--tailnet` puts it behind
151
- `tailscale serve` (HTTPS, tailnet-only, never the internet, on its own port 8443 so it never
152
- takes `/` from the voice) and lets in exactly one login: `--owner`, or this machine's
153
- tailscale user. If it can't tell whose it is, it does not go on the tailnet. Undo with
154
- `tailscale serve --https=8443 off`.
155
- - **A token on every call.** The first run makes one in `~/.seldon/serve-token` (0600). Every
156
- API call, reads included, needs it; the phone gets it once from the link `serve` prints,
157
- keeps it, and takes it out of the address bar. `rm ~/.seldon/serve-token` for a new one —
158
- every device has to open the new link.
159
- - **A leftover tailnet mapping reaches nothing.** Started without `--tailnet`, it refuses every
160
- request that comes in by a `*.ts.net` name.
161
- - **Replies are off unless `--allow-reply`,** and are a whitelist of keys or literal text. A
162
- menu key ("1") is sent without Enter.
163
- - **What it can read:** lanes in tmux (Codex, opencode, and Claude lanes seldon started) show
164
- their screen and take replies. An interactive Claude session in a plain terminal has no pane
165
- to read: open it with `claude attach`, or from the Claude app with Remote Control.
166
- - **It acts with this machine's ssh keys:** a lane on another machine is stopped or started by
167
- `ssh <machine> seldon lane …`, so whoever gets in reaches those machines' lanes too.
168
- - **Alerts:** while the page is open, the phone buzzes and notifies when an agent starts
169
- needing you.
143
+ - **From a phone:** `ssh` to any one machine and run `seldon ws`.
170
144
 
171
145
  ## On Telegram — `seldon tell`
172
146
 
@@ -190,8 +164,7 @@ piped log over a few lines folds away — tap it to open.
190
164
 
191
165
  Every message is a card that reads at a glance: a coloured dot for what kind of news it is,
192
166
  then where it comes from (the repo, branch and machine it was sent from), then what happened.
193
- The watcher's cards also name the agent, what it is waiting for, how long it has run, and link
194
- to the phone app when `seldon serve --tailnet` is on.
167
+ The watcher's cards also name the agent, what it is waiting for and how long it has run.
195
168
 
196
169
  Images show inline, videos play, GIFs animate, audio plays, anything else is a document; a
197
170
  bot can send up to 50 MB per file.
package/bin/seldon.js CHANGED
@@ -8,16 +8,16 @@ import fs from "node:fs";
8
8
  import os from "node:os";
9
9
  import readline from "node:readline";
10
10
  import { MODULES, byId, DEPS, RAW, MONOREPO, withRequires, platformOk } from "../modules.mjs";
11
- import { ensureSiblingPath, loadState, resolveProject, adopt as fAdopt, staff as fStaff, attach as fAttach, hiveOf, sameDir } from "../lib/projects.mjs";
11
+ import { ensureSiblingPath, has, loadState, resolveProject, adopt as fAdopt, staff as fStaff, attach as fAttach, hiveOf, sameDir } from "../lib/projects.mjs";
12
12
  import { readLanes, readPlan, addToPlan, projectRoot, writeReport } from "../lib/agents.mjs";
13
13
  import { openCommand, stopCommand, transitions, laneForItem, slugify, HARNESSES } from "../lib/lanes.mjs";
14
14
  import { startLane, stopLane, resumeLane, removeLane, findLane } from "../lib/actions.mjs";
15
- import { listMachines, addMachine, fetchLanes, remoteGroups, sshArgs, lastJsonLine } from "../lib/machines.mjs";
15
+ import { listMachines, addMachine, fetchLanes, machinePoller, sshArgs, lastJsonLine } from "../lib/machines.mjs";
16
16
  import { notify } from "../lib/notify.mjs";
17
- import { serve, serveToken, ownerFromStatus } from "../lib/serve.mjs";
18
17
  import { sendCard, watchCard, KINDS, tokenName, readChat, writeChat, chatFromUpdates, getUpdates, sendText, sendFile, pollUpdates, fileFromMessage, inboxName, freeName, noteLine, downloadFile, react, MAX_DOWNLOAD } from "../lib/telegram.mjs";
19
18
  import { reportFromEvent, mergeCodexHooks, removeCodexHooks, opencodePlugin } from "../lib/reports.mjs";
20
19
  import { buildRows, headline, ago, laneDetail, unlistedAgents, GLYPH } from "../lib/home.mjs";
20
+ import { WS_SOCKET, WS_SESSION, NARROW, SIDE_WIDTH, assignEmoji, wsRows, nextNeeding, findRow, paneCommand, setupCommands, rowCells, wsHeadline } from "../lib/workspace.mjs";
21
21
  import { parseDuration, describe as describeHold, NAME_RE, DEFAULT_FOR_MS } from "../lib/holds.mjs";
22
22
  import { tryHold, release as releaseHold, listHolds, findOwner } from "../lib/holds-store.mjs";
23
23
 
@@ -63,8 +63,8 @@ function run(cmd, args, opts = {}) {
63
63
  return r.status === 0;
64
64
  }
65
65
 
66
- // Is a command on PATH? (used to pick the fastest package manager)
67
- const has = (bin) => { try { execSync(`command -v ${bin}`, { stdio: "ignore" }); return true; } catch { return false; } };
66
+ // Colour per lane state, shared by the panel and the workspace list.
67
+ const TINT = { "needs-you": C.gold, working: C.green, running: C.green, idle: C.dim, failed: C.red, stopped: C.dim, off: C.dim };
68
68
 
69
69
  // A usable uv, for Python modules. Prefer one on PATH; else a prior isolated
70
70
  // copy; else bootstrap uv into ~/.seldon/bin with NO shell/profile changes.
@@ -326,7 +326,7 @@ async function doInstall(ids, { dev } = {}) {
326
326
  const bad = results.filter(([, r]) => !r).map(([i]) => i);
327
327
  console.log("\n" + C.bold("Done. ") + C.green(good.join(", ") || "—") + (bad.length ? " " + C.red("failed: " + bad.join(", ")) : ""));
328
328
  // demerzel's models are the heavy part — offer to pull them now, at install time.
329
- if (good.includes("demerzel")) await ensureDemerzelModels({ ask: true });
329
+ if (good.includes("demerzel")) await ensureDemerzelModels();
330
330
  }
331
331
 
332
332
  // ---- uninstall --------------------------------------------------------------
@@ -495,30 +495,6 @@ function demerzelModelsMissing() {
495
495
  const demerzelModelsReady = () => demerzelModelsMissing().length === 0;
496
496
  const demerzelInstalled = () => fs.existsSync(path.join(SELDON_HOME, "demerzel", ".venv", "bin", "python"));
497
497
 
498
- // This machine's Tailscale IPv4 (100.64.0.0/10), or null. Tries PATH then the
499
- // macOS app location. Used to expose the voice to your phone over the tailnet.
500
- function tailnetIp() {
501
- for (const bin of ["tailscale", "/Applications/Tailscale.app/Contents/MacOS/tailscale"]) {
502
- try {
503
- const ip = execSync(`${bin} ip -4`, { stdio: ["ignore", "pipe", "ignore"] }).toString().trim().split(/\s+/)[0];
504
- if (/^100\./.test(ip)) return ip;
505
- } catch {}
506
- }
507
- // CLI missing/moved? The tailnet address is still on a utun interface —
508
- // read it straight from the OS (Tailscale's CGNAT range is 100.64.0.0/10).
509
- try {
510
- const out = execSync("ifconfig", { stdio: ["ignore", "pipe", "ignore"] }).toString();
511
- const m = out.match(/inet (100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d+\.\d+)/);
512
- if (m) return m[1];
513
- } catch {}
514
- try { // linux `ip addr`
515
- const out = execSync("ip -4 addr", { stdio: ["ignore", "pipe", "ignore"] }).toString();
516
- const m = out.match(/inet (100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d+\.\d+)/);
517
- if (m) return m[1];
518
- } catch {}
519
- return null;
520
- }
521
-
522
498
  // Find the Tailscale CLI (PATH, homebrew, or the macOS app bundle).
523
499
  function tailscaleBin() {
524
500
  for (const b of ["tailscale", "/opt/homebrew/bin/tailscale", "/usr/local/bin/tailscale", "/Applications/Tailscale.app/Contents/MacOS/tailscale", "/usr/bin/tailscale"]) {
@@ -571,7 +547,7 @@ function tailscaleServeSetup() {
571
547
  // Fetch demerzel's model set (~25 GB) — offered, never silent. Respects the
572
548
  // chosen LLM (DEMERZEL_LLM) so `seldon install demerzel` / `seldon up` pull the
573
549
  // model you'll actually run. --models forces yes, --no-models forces skip.
574
- async function ensureDemerzelModels({ ask = true } = {}) {
550
+ async function ensureDemerzelModels() {
575
551
  if (!demerzelInstalled() || !platformOk(byId.demerzel)) return false;
576
552
  if (demerzelModelsReady()) return true;
577
553
  const home = path.join(SELDON_HOME, "demerzel");
@@ -691,7 +667,7 @@ async function up() {
691
667
  const home = path.join(SELDON_HOME, "demerzel");
692
668
  if (!platformOk(dem)) later.push("Voice (demerzel) needs macOS on Apple silicon — skipped here.");
693
669
  else {
694
- if (!demerzelModelsReady()) await ensureDemerzelModels({ ask: true }); // offer the fetch inline
670
+ if (!demerzelModelsReady()) await ensureDemerzelModels(); // offer the fetch inline
695
671
  if (demerzelModelsReady()) {
696
672
  const env = { ...process.env };
697
673
  // --- choose the brain (remembered) ---
@@ -945,14 +921,7 @@ async function panel() {
945
921
  // slow or sleeping machine never freezes this screen; `seen` says how each one answered.
946
922
  const machines = listMachines();
947
923
  const seen = new Map(); // name -> { groups, error, at, inflight }
948
- const pollMachines = () => {
949
- for (const m of machines) {
950
- const was = seen.get(m.name) || {};
951
- if (was.inflight || (was.at && Date.now() - was.at < 10_000)) continue;
952
- seen.set(m.name, { ...was, inflight: true });
953
- fetchLanes(m, (r) => { seen.set(m.name, { groups: r.lanes ? remoteGroups(m, r.lanes) : was.groups || [], error: r.error || null, at: Date.now(), inflight: false }); });
954
- }
955
- };
924
+ const pollMachines = machinePoller(machines, seen);
956
925
  const machineOf = (name) => machines.find((m) => m.name === name);
957
926
  // Run seldon (or foundation) on a machine. `tty`: it may need a terminal (a trust dialog),
958
927
  // so it inherits this one; otherwise its output is captured for the note line.
@@ -975,7 +944,7 @@ async function panel() {
975
944
  const allLanes = () => groups.flatMap((g) => g.lanes);
976
945
 
977
946
  const svc = (label, on) => (on ? C.green("●") : C.dim("○")) + " " + label;
978
- const tint = { "needs-you": C.gold, working: C.green, running: C.green, idle: C.dim, failed: C.red, stopped: C.dim };
947
+ const tint = TINT;
979
948
  // Below 70 columns (a phone over ssh) a lane is one short line: glyph, name, the state in a
980
949
  // word. The full detail is one ⏎ away.
981
950
  const narrow = () => (process.stdout.columns || 100) < 70;
@@ -1428,13 +1397,13 @@ function help() {
1428
1397
  ${C.bold("seldon")} — the agent factory: your projects, and the stack that runs them.
1429
1398
 
1430
1399
  ${C.bold("seldon")} ${C.gold("the panel")} — every agent (claude · codex · opencode) by project; n new lane, p plan
1400
+ ${C.bold("seldon ws")} ${C.gold("the workspace")} — the agent list beside the agent's own terminal; Alt-1…9 switches
1431
1401
  ${C.bold("seldon hold")} <thing> take a turn on a shared resource (emulator, unreal, gpu); waits if someone has it
1432
1402
  ${C.bold("seldon release")} <thing> give it back · ${C.bold("seldon holds")} who holds what
1433
1403
  ${C.bold("seldon go")} [name|dir] ${C.gold("get back to work")} — adopt if needed, reopen the room, staff an agent, attach.
1434
1404
  Idempotent, and it prints every step it skipped. Run it from inside a repo.
1435
1405
  ${C.bold("seldon up")} start the stack (voice + supervisor) and print where to go
1436
1406
  ${C.bold("seldon up --tailnet")} expose the voice over HTTPS (tailscale serve) so the mic works on your phone
1437
- ${C.bold("seldon serve")} [--tailnet] the panel as a phone web app (--allow-reply to answer agents)
1438
1407
  ${C.bold("seldon tell")} "…" message yourself on Telegram (--file to send one; --setup once)
1439
1408
  ${C.bold("seldon inbox")} [--dir d] save what you send the bot to a folder here (no agent, no tokens)
1440
1409
  ${C.bold("seldon up --brain=X")} pick the voice brain: qwen (in-process) | bonsai (local server); remembered
@@ -1476,22 +1445,12 @@ function tellInBackground(fields) {
1476
1445
  child.on("error", () => {}); child.unref();
1477
1446
  }
1478
1447
 
1479
- function phoneAppUrl() {
1480
- const ts = tailscaleBin(); if (!ts) return null;
1481
- try {
1482
- const out = execSync(`${ts} serve status`, { stdio: ["ignore", "pipe", "ignore"], timeout: 10000 }).toString();
1483
- const m = out.match(new RegExp(`https://\\S+:${SERVE_TAILNET_PORT}`));
1484
- return m ? m[0] + "/" : null;
1485
- } catch { return null; }
1486
- }
1487
-
1488
1448
  async function watchCmd(flags) {
1489
1449
  ensureSiblingPath();
1490
1450
  const every = parseDuration(flags.interval, 5000) || 5000;
1491
1451
  let prev = new Map();
1492
1452
  const stamp = () => new Date().toTimeString().slice(0, 8);
1493
1453
  console.log(`${stamp()} seldon watch — every ${every / 1000}s`);
1494
- const phone = phoneAppUrl(); // once: the link the phone cards carry
1495
1454
  for (;;) {
1496
1455
  let lanes = [];
1497
1456
  try { lanes = readLanes().flatMap((g) => g.lanes); } catch (e) { console.log(`${stamp()} read failed: ${e.message}`); }
@@ -1499,7 +1458,7 @@ async function watchCmd(flags) {
1499
1458
  console.log(`${stamp()} ${e.text}`);
1500
1459
  const where = path.basename(e.lane.project || e.lane.cwd || "");
1501
1460
  notify(e.to === "needs-you" ? "Seldon · needs you" : "Seldon", `${e.text} — ${where}`);
1502
- tellInBackground(watchCard(e, { machine: os.hostname().split(".")[0], link: phone }));
1461
+ tellInBackground(watchCard(e, { machine: os.hostname().split(".")[0] }));
1503
1462
  }
1504
1463
  prev = new Map(lanes.map((l) => [l.key, l.state]));
1505
1464
  if (flags.once) return;
@@ -1553,29 +1512,143 @@ function laneCmd(verb, arg, flags) {
1553
1512
  console.log(C.green(`✓ ${verb === "stop" ? "stopped" : "resumed"} ${lane.name}`) + (r.fresh ? C.dim(" (new conversation, same task + worktree)") : ""));
1554
1513
  }
1555
1514
 
1556
- // `seldon serve` — the panel for a phone. Loopback only, and every call needs the token.
1557
- // `--tailnet` puts it behind `tailscale serve` (HTTPS, its own port so it never takes the
1558
- // voice's /) and only ever for one login: --owner, or this machine's tailscale user.
1559
- const SERVE_TAILNET_PORT = 8443;
1560
- function serveCmd(flags) {
1561
- const port = Number(flags.port) || 7930;
1562
- const allowReply = !!flags["allow-reply"];
1563
- const token = serveToken();
1564
- let owner = null, dns = null, ts = null;
1565
- if (flags.tailnet) {
1566
- ts = tailscaleBin(); const status = ts && tailscaleStatus(ts);
1567
- dns = tailnetDnsName(ts, status);
1568
- owner = typeof flags.owner === "string" ? flags.owner : ownerFromStatus(status);
1569
- if (!dns || !owner) { console.log(C.red(" not serving on the tailnet: " + (!dns ? "tailscale not found or not connected" : "can't tell whose it is — pass --owner you@example.com"))); process.exitCode = 1; return; }
1515
+ // ---- the workspace: `seldon ws` -------------------------------------------------------
1516
+ // The agent list on the left, the selected agent's own terminal on the right, one key to
1517
+ // switch (lib/workspace.mjs has the rules; this is the tmux and the drawing). It runs on its
1518
+ // own tmux server, so nothing here touches the user's tmux or its config.
1519
+ const WS_ROWS = path.join(SELDON_HOME, "ws.json"); // the list, as the sidebar last drew it
1520
+ const WS_CURRENT = path.join(SELDON_HOME, "ws-current"); // the key of the agent on the right
1521
+ const shq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
1522
+ const wsSelf = () => `${shq(process.execPath)} ${shq(fs.realpathSync(process.argv[1]))}`;
1523
+ // The right-hand pane with no agent open is the full panel; when it exits, it comes back.
1524
+ const wsHome = () => `sh -c ${shq(`while :; do ${wsSelf()}; sleep 0.3; done`)}`;
1525
+ const wsTmux = (args, opts = {}) => spawnSync("tmux", ["-L", WS_SOCKET, "-f", "/dev/null", ...args], { encoding: "utf8", ...opts });
1526
+ const wsOpt = (name) => (wsTmux(["show-options", "-v", "-t", WS_SESSION, name]).stdout || "").trim();
1527
+ const wsReadRows = () => { try { return JSON.parse(fs.readFileSync(WS_ROWS, "utf8")); } catch { return []; } };
1528
+ const wsCurrent = () => { try { return fs.readFileSync(WS_CURRENT, "utf8").trim() || null; } catch { return null; } };
1529
+ function wsSave(file, text) {
1530
+ fs.mkdirSync(SELDON_HOME, { recursive: true });
1531
+ const tmp = `${file}.${process.pid}`;
1532
+ fs.writeFileSync(tmp, text); fs.renameSync(tmp, file); // a reader never sees half a file
1533
+ }
1534
+ // Show `pane`. On a small screen it fills it; on a wide one both panes show.
1535
+ function wsFocus(pane, width = null) {
1536
+ const [w0, zoomed] = (wsTmux(["display-message", "-p", "-t", `${WS_SESSION}:0`, "#{window_width} #{window_zoomed_flag}"]).stdout || "").trim().split(" ");
1537
+ const narrow = (width ?? Number(w0)) < NARROW; // `width`: the screen about to attach
1538
+ if (!pane && narrow && !wsCurrent()) pane = wsOpt("@side"); // a phone with no agent open starts on the list
1539
+ if (pane) wsTmux(["select-pane", ...(narrow ? ["-Z"] : []), "-t", pane]);
1540
+ if (narrow !== (zoomed === "1")) wsTmux(["resize-pane", "-Z", "-t", `${WS_SESSION}:0`]);
1541
+ if (!narrow) wsTmux(["resize-pane", "-t", wsOpt("@side"), "-x", String(SIDE_WIDTH)]); // a resize stretches it otherwise
1542
+ }
1543
+ function wsOpen(row) {
1544
+ const main = wsOpt("@main");
1545
+ wsTmux(["respawn-pane", "-k", "-t", main, row.cmd]);
1546
+ wsSave(WS_CURRENT, row.off ? "" : row.key);
1547
+ wsFocus(main);
1548
+ }
1549
+ function wsGoHome() {
1550
+ const main = wsOpt("@main");
1551
+ wsTmux(["respawn-pane", "-k", "-t", main, wsHome()]);
1552
+ wsSave(WS_CURRENT, "");
1553
+ wsFocus(main);
1554
+ }
1555
+
1556
+ // The left-hand pane: the list. It also writes the list to disk, which is how a key pressed
1557
+ // anywhere in the workspace (`seldon ws pick 3`, run by tmux) knows what "3" is.
1558
+ async function wsSidebar() {
1559
+ ensureSiblingPath();
1560
+ const machines = listMachines();
1561
+ const seen = new Map();
1562
+ const poll = machinePoller(machines, seen);
1563
+ let rows = [], cur = 0, note = "";
1564
+ const home = wsHome();
1565
+ const load = () => {
1566
+ poll();
1567
+ let groups = [];
1568
+ try { groups = [...readLanes(), ...[...seen.values()].flatMap((v) => v.groups || [])]; } catch (e) { note = C.red(e.message); }
1569
+ const down = new Set([...seen].filter(([, v]) => v.error).map(([name]) => name));
1570
+ const prev = rows[cur]?.key;
1571
+ rows = wsRows(groups, down);
1572
+ const keep = rows.findIndex((r) => r.key === prev);
1573
+ cur = keep >= 0 ? keep : Math.min(cur, Math.max(0, rows.length - 1));
1574
+ wsSave(WS_ROWS, JSON.stringify(rows.map((r) => ({ n: r.n, key: r.key, name: r.name, state: r.state, off: r.off, cmd: paneCommand(r, { machines, home }) }))));
1575
+ };
1576
+ const tint = TINT;
1577
+ const draw = () => {
1578
+ const width = process.stdout.columns || 38, height = process.stdout.rows || 40;
1579
+ const open = wsCurrent(), h = wsHeadline(rows);
1580
+ const head = [` ${C.bold("SELDON")} ${h.need ? C.gold(`⚑ ${h.need}`) : C.dim("⚑ 0")} ${C.green(`● ${h.busy}`)}`, ""];
1581
+ const foot = ["", C.dim(" ⏎ open · n next ⚑ · h home"), C.dim(" Alt-1…9 from any pane · q leave"), ...(note ? [" " + note] : [])];
1582
+ const body = []; let curLine = 0, last = null;
1583
+ if (!rows.length) body.push(C.dim(" no agents running"), C.dim(" h, then n starts one"));
1584
+ const faces = assignEmoji(rows.map((r) => r.name));
1585
+ rows.forEach((r, i) => {
1586
+ if (r.project !== last) { if (last !== null) body.push(""); body.push(" " + C.dim(r.project.slice(0, width - 2))); last = r.project; }
1587
+ const c = rowCells(r, width, ago, faces.get(r.name)), color = tint[c.state] || ((x) => x);
1588
+ const mark = i === cur ? C.gold("❯") : r.key === open ? C.cyan("▸") : " ";
1589
+ if (i === cur) curLine = body.length;
1590
+ body.push(`${mark}${C.dim(c.n)} ${color(c.glyph)} ${c.emoji} ${i === cur ? C.bold(c.name) : c.name}`);
1591
+ body.push(` ${color(c.sub)}`);
1592
+ });
1593
+ const room = Math.max(2, height - head.length - foot.length);
1594
+ const from = Math.max(0, Math.min(curLine - Math.floor(room / 2), body.length - room));
1595
+ clearScreen();
1596
+ process.stdout.write([...head, ...body.slice(from, from + room), ...foot].join("\n"));
1597
+ };
1598
+ const openRow = (r) => { if (r) { wsOpen(wsReadRows().find((x) => x.key === r.key) || r); note = ""; } };
1599
+ load();
1600
+ setInterval(() => { load(); draw(); }, 2000);
1601
+ process.stdout.on("resize", draw);
1602
+ await rawSession({
1603
+ draw,
1604
+ onError: (e) => { note = C.red(e.message); },
1605
+ onKey: (str, key, api) => {
1606
+ if (key?.name === "up" || str === "k") cur = Math.max(0, cur - 1);
1607
+ else if (key?.name === "down" || str === "j") cur = Math.min(rows.length - 1, cur + 1);
1608
+ else if (key?.name === "return") openRow(rows[cur]);
1609
+ else if (/^[1-9]$/.test(str || "")) openRow(findRow(rows, str));
1610
+ else if (str === "n") { const r = nextNeeding(rows, wsCurrent()); if (r) openRow(r); else note = C.dim("nobody is waiting on you"); }
1611
+ else if (str === "h") wsGoHome();
1612
+ else if (str === "r") load();
1613
+ else if (str === "q" || (key?.ctrl && key.name === "c")) wsTmux(["detach-client"]);
1614
+ api.draw();
1615
+ },
1616
+ });
1617
+ }
1618
+
1619
+ function wsCmd(sub, arg) {
1620
+ const fail = (msg) => { console.log(C.red(msg)); process.exitCode = 1; };
1621
+ if (!has("tmux")) return fail("the workspace needs tmux — install it (brew install tmux / apt install tmux), then: seldon ws");
1622
+ if (sub === "sidebar") return wsSidebar();
1623
+ if (sub === "fit") return wsFocus(null);
1624
+ if (sub === "list") return wsFocus(wsOpt("@side"));
1625
+ if (sub === "home") return wsGoHome();
1626
+ if (sub === "pick" || sub === "next") {
1627
+ const rows = wsReadRows();
1628
+ const row = sub === "pick" ? findRow(rows, arg) : nextNeeding(rows, wsCurrent());
1629
+ if (row) wsOpen(row);
1630
+ else wsTmux(["display-message", sub === "pick" ? `no agent ${arg ?? ""}` : "nobody is waiting on you"]);
1631
+ return;
1570
1632
  }
1571
- serve({ port, token, owner, tailnet: !!flags.tailnet, allowReply });
1572
- console.log(C.green(`✓ seldon serve`) + C.dim(` on http://localhost:${port}/#t=${token}`) + (allowReply ? C.gold(" · replies ON (the phone can type into agents)") : ""));
1573
- if (!flags.tailnet) { console.log(C.dim(` for your phone: seldon serve --tailnet (HTTPS on your tailnet, only for your login)`)); return; }
1574
- try {
1575
- execSync(`${ts} serve --bg --https=${SERVE_TAILNET_PORT} http://127.0.0.1:${port}`, { stdio: "ignore", timeout: 30000 });
1576
- console.log(C.green(` phone → https://${dns}:${SERVE_TAILNET_PORT}/#t=${token}`) + C.dim(` only for ${owner} · open it once, then add to home screen`));
1577
- console.log(C.dim(` undo: tailscale serve --https=${SERVE_TAILNET_PORT} off · new token: rm ~/.seldon/serve-token`));
1578
- } catch (e) { console.log(C.red(" tailscale serve failed: " + ((e.stderr || e.message || "").toString().split("\n")[0]))); }
1633
+ if (sub === "stop") {
1634
+ wsTmux(["kill-server"]);
1635
+ return console.log(C.green("✓ workspace closed") + C.dim(" — your agents keep running"));
1636
+ }
1637
+ if (sub) return fail("usage: seldon ws (open the workspace) · seldon ws stop (close it; agents keep running)");
1638
+ if (process.env.SELDON_WS) return console.log(C.dim("you are already in the workspace — Alt-s for the list, Alt-q to leave"));
1639
+ if (wsTmux(["has-session", "-t", WS_SESSION]).status !== 0) {
1640
+ const cmds = setupCommands({ self: wsSelf(), home: wsHome(), cols: process.stdout.columns || 200, rows: process.stdout.rows || 50 });
1641
+ const made = wsTmux(cmds.flatMap((c, i) => (i ? [";", ...c] : c)));
1642
+ if (made.status !== 0) return fail(`could not start the workspace: ${(made.stderr || "").trim() || "tmux failed"} (it needs tmux 3.2 or newer)`);
1643
+ const panes = (wsTmux(["list-panes", "-t", `${WS_SESSION}:0`, "-F", "#{pane_left} #{pane_id}"]).stdout || "").trim().split("\n")
1644
+ .map((l) => l.split(" ")).sort((a, b) => Number(a[0]) - Number(b[0]));
1645
+ wsTmux(["set-option", "-t", WS_SESSION, "@side", panes[0][1]]);
1646
+ wsTmux(["set-option", "-t", WS_SESSION, "@main", panes[panes.length - 1][1]]);
1647
+ wsSave(WS_CURRENT, "");
1648
+ }
1649
+ wsFocus(null, process.stdout.columns || null); // fit this screen before it shows
1650
+ const env = { ...process.env }; delete env.TMUX;
1651
+ process.exitCode = spawnSync("tmux", ["-L", WS_SOCKET, "attach", "-t", WS_SESSION], { stdio: "inherit", env }).status ?? 1;
1579
1652
  }
1580
1653
 
1581
1654
  // `seldon tell "…"` — message the operator on Telegram, from any agent. The token comes from
@@ -1823,7 +1896,7 @@ function holdsCmd() {
1823
1896
  // (`--no-attach`). The value form has to be CONSUMED: filtering out everything starting with
1824
1897
  // `--` and keeping the rest as positionals read `seldon go --agent claude` as the project
1825
1898
  // named "claude".
1826
- const VALUE_FLAGS = new Set(["agent", "model", "effort", "name", "port", "pm", "stall", "dir", "for", "wait", "as", "note", "interval", "task", "owner", "file", "token-name", "card"]);
1899
+ const VALUE_FLAGS = new Set(["agent", "model", "effort", "name", "pm", "dir", "for", "wait", "as", "note", "interval", "task", "file", "token-name", "card"]);
1827
1900
  function parseArgv(raw) {
1828
1901
  const flags = {}, positional = [];
1829
1902
  for (let i = 0; i < raw.length; i++) {
@@ -1838,6 +1911,11 @@ function parseArgv(raw) {
1838
1911
  return { flags, positional };
1839
1912
  }
1840
1913
 
1914
+ // Inside the workspace $TMUX points at the workspace's own tmux server. Lanes live on the
1915
+ // default one, so every tmux call seldon makes from here (listing panes, attaching) must not
1916
+ // follow it; the workspace's own calls name their server explicitly.
1917
+ if (process.env.SELDON_WS) delete process.env.TMUX;
1918
+
1841
1919
  const rawArgv = process.argv.slice(2);
1842
1920
  // Everything after a bare `--` is a command to run (`seldon hold emulator -- ./gradlew test`),
1843
1921
  // never seldon's own flags.
@@ -1877,11 +1955,11 @@ const ids = tokens.filter((id) => byId[id]); // only the valid module
1877
1955
  if (cmd === "lanes") return lanesCmd(flags);
1878
1956
  if (cmd === "machines") return machinesCmd(tokens[0], tokens[1], tokens[2]);
1879
1957
  if (cmd === "lane") return laneCmd(tokens[0], tokens[1], flags);
1880
- if (cmd === "serve") return serveCmd(flags);
1958
+ if (cmd === "ws") return wsCmd(tokens[0], tokens[1]);
1881
1959
  if (cmd === "tell") return tellCmd(tokens, flags);
1882
1960
  if (cmd === "inbox") return inboxCmd(flags);
1883
1961
  if (cmd === "setup") return setupCmd(tokens[0], flags);
1884
- if (cmd === "panel" || cmd === "board") return panel();
1962
+ if (cmd === "panel") return panel();
1885
1963
  if (cmd && cmd !== "install") { help(); process.exitCode = 1; return; }
1886
1964
  if (cmd === "install") return install_picker({ dev }); // `install` with no ids
1887
1965
 
package/lib/machines.mjs CHANGED
@@ -11,7 +11,7 @@ import { join } from "node:path";
11
11
  import { homedir } from "node:os";
12
12
  import { groupByProject } from "./lanes.mjs";
13
13
 
14
- export const REALMS_DIR = join(homedir(), ".config", "bifrost", "realms");
14
+ const REALMS_DIR = join(homedir(), ".config", "bifrost", "realms");
15
15
 
16
16
  // Read narrowly — two keys, quotes stripped, nothing executed. Sourcing a file to learn a
17
17
  // hostname is not something to do.
@@ -80,3 +80,16 @@ export function fetchLanes(machine, cb) {
80
80
  cb(lanes ? { lanes } : { error: err ? (err.killed ? "timed out" : "unreachable") : "no seldon there" });
81
81
  });
82
82
  }
83
+
84
+ // Poll every machine's lanes in the background, at most every 10s each, so a slow or sleeping
85
+ // machine never blocks a redraw. `seen` maps name -> { groups, error, at, inflight }.
86
+ export function machinePoller(machines, seen, fetch = fetchLanes) {
87
+ return () => {
88
+ for (const m of machines) {
89
+ const was = seen.get(m.name) || {};
90
+ if (was.inflight || (was.at && Date.now() - was.at < 10_000)) continue;
91
+ seen.set(m.name, { ...was, inflight: true });
92
+ fetch(m, (r) => { seen.set(m.name, { groups: r.lanes ? remoteGroups(m, r.lanes) : was.groups || [], error: r.error || null, at: Date.now(), inflight: false }); });
93
+ }
94
+ };
95
+ }
package/lib/projects.mjs CHANGED
@@ -52,11 +52,6 @@ export function gitRootOf(dir) {
52
52
  const realish = (p) => { try { return fs.realpathSync(p); } catch { return p; } };
53
53
  export const sameDir = (a, b) => !!a && !!b && realish(a) === realish(b);
54
54
 
55
- // A repo carries its hive in .factory.json — the local truth, which survives a pruned or
56
- // hand-edited registry.
57
- export function localHive(dir) {
58
- try { return JSON.parse(readFileSync(path.join(dir, ".factory.json"), "utf8")); } catch { return null; }
59
- }
60
55
 
61
56
  /**
62
57
  * What did the user mean, and what do we know about it?
package/lib/telegram.mjs CHANGED
@@ -144,7 +144,7 @@ export const htmlToPlain = (html) => String(html)
144
144
 
145
145
  // Every part is optional but the kind. `log` is shown as code (its tail: the end of a log is
146
146
  // what matters). `max` keeps the whole card under Telegram's limit — 1024 for a caption.
147
- export function card({ kind = "info", text, log, project, branch, lane, harness, detail, age, machine, link, max = MAX } = {}) {
147
+ export function card({ kind = "info", text, log, project, branch, lane, harness, detail, age, machine, max = MAX } = {}) {
148
148
  const k = KINDS[kind] || KINDS.info;
149
149
  const e = escHtml;
150
150
  const meta = [age && `⏱ ${e(age)}`, machine && `💻 ${e(machine)}`].filter(Boolean).join(" · ");
@@ -153,7 +153,7 @@ export function card({ kind = "info", text, log, project, branch, lane, harness,
153
153
  lane && `▸ <b>${e(lane)}</b>${harness ? ` · ${e(harness)}` : ""}`,
154
154
  detail && `⏳ ${e(detail)}`,
155
155
  ].filter(Boolean);
156
- const bottom = [meta && `<i>${meta}</i>`, link && `👉 <a href="${e(link)}">open the app</a>`].filter(Boolean);
156
+ const bottom = [meta && `<i>${meta}</i>`].filter(Boolean);
157
157
  // The free text gets whatever room the frame leaves (escaping can grow it, hence the margin).
158
158
  const room = Math.max(0, max - [...top, ...bottom].join("\n").length - 60);
159
159
  const words = text && mdToHtml(clip(String(text).trim(), Math.floor(room * (log ? 0.4 : 1) / 1.2)));
@@ -236,18 +236,17 @@ export async function downloadFile(token, fileId, dest) {
236
236
  export const react = (token, chatId, messageId, emoji) =>
237
237
  call(token, "setMessageReaction", { chat_id: chatId, message_id: messageId, reaction: [{ type: "emoji", emoji }] }).catch(() => {});
238
238
 
239
- // The watcher's news as a card: which agent, on what, what it is waiting for, for how long,
240
- // and — when the phone app is on the tailnet — a link straight to it.
239
+ // The watcher's news as a card: which agent, on what, what it is waiting for, for how long.
241
240
  const WATCH_KIND = { "needs-you": "need", failed: "fail", idle: "done" };
242
241
  const WATCH_DETAIL = { failed: "ended with an error", idle: "finished its turn — ready for the next task" };
243
- export function watchCard(e, { machine = null, link = null, now = Date.now() } = {}) {
242
+ export function watchCard(e, { machine = null, now = Date.now() } = {}) {
244
243
  return {
245
244
  kind: WATCH_KIND[e.to] || "info",
246
245
  project: basename(e.lane.project || e.lane.cwd || "") || null,
247
246
  lane: e.lane.name || e.lane.id, harness: e.lane.harness,
248
247
  detail: e.to === "needs-you" ? (e.lane.waitingFor || "waiting for you") : WATCH_DETAIL[e.to] || e.to,
249
248
  age: e.lane.startedAt ? `running ${ago(e.lane.startedAt, now)}` : null,
250
- machine, link,
249
+ machine,
251
250
  };
252
251
  }
253
252