@gorlitzer-labs/seldon 0.1.24 → 0.9.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.
package/bin/seldon.js CHANGED
@@ -7,17 +7,25 @@ import path from "node:path";
7
7
  import fs from "node:fs";
8
8
  import readline from "node:readline";
9
9
  import { MODULES, byId, DEPS, RAW, MONOREPO, withRequires, platformOk } from "../modules.mjs";
10
+ import { ensureSiblingPath, loadState, resolveProject, adopt as fAdopt, staff as fStaff, attach as fAttach, hiveOf, sameDir } from "../lib/projects.mjs";
11
+ import { readLanes, readPlan, addToPlan, projectRoot, writeReport } from "../lib/agents.mjs";
12
+ import { openCommand, stopCommand, transitions, laneForItem, slugify, HARNESSES } from "../lib/lanes.mjs";
13
+ import { startLane, stopLane, resumeLane, findLane } from "../lib/actions.mjs";
14
+ import { listMachines, addMachine, fetchLanes, remoteGroups, sshArgs, lastJsonLine } from "../lib/machines.mjs";
15
+ import { notify } from "../lib/notify.mjs";
16
+ import { reportFromEvent, mergeCodexHooks, removeCodexHooks, opencodePlugin } from "../lib/reports.mjs";
17
+ import { buildRows, headline, ago, laneDetail, unlistedAgents, GLYPH } from "../lib/home.mjs";
18
+ import { parseDuration, describe as describeHold, NAME_RE, DEFAULT_FOR_MS } from "../lib/holds.mjs";
19
+ import { tryHold, release as releaseHold, listHolds, findOwner } from "../lib/holds-store.mjs";
10
20
 
11
21
  const HERE = path.dirname(fileURLToPath(import.meta.url));
12
22
  // The monorepo root when running from a checkout (tools/seldon/bin -> ../../..)
13
23
  const REPO_ROOT = path.resolve(HERE, "..", "..", "..");
14
24
  const IN_CHECKOUT = fs.existsSync(path.join(REPO_ROOT, "modules", "apiary", "package.json"));
15
25
 
16
- const C = {
17
- dim: (s) => `\x1b[2m${s}\x1b[0m`, bold: (s) => `\x1b[1m${s}\x1b[0m`,
18
- gold: (s) => `\x1b[33m${s}\x1b[0m`, green: (s) => `\x1b[32m${s}\x1b[0m`,
19
- red: (s) => `\x1b[31m${s}\x1b[0m`, cyan: (s) => `\x1b[36m${s}\x1b[0m`,
20
- };
26
+ // NO_COLOR (https://no-color.org) turns every escape off — for logs, pipes and tests.
27
+ const paint = (code) => (s) => (process.env.NO_COLOR ? String(s) : `\x1b[${code}m${s}\x1b[0m`);
28
+ const C = { dim: paint(2), bold: paint(1), gold: paint(33), green: paint(32), red: paint(31), cyan: paint(36) };
21
29
 
22
30
  function have(dep) {
23
31
  const probe = DEPS[dep]?.probe;
@@ -372,7 +380,7 @@ function confirm(question) {
372
380
  return new Promise((resolve) => {
373
381
  if (!process.stdin.isTTY) return resolve(true); // non-interactive: assume yes (paired with an explicit ids/--all)
374
382
  process.stdout.write(question);
375
- readline.emitKeypressEvents(process.stdin);
383
+ readline.emitKeypressEvents(process.stdin, KEYS);
376
384
  process.stdin.setRawMode(true);
377
385
  process.stdin.resume();
378
386
  process.stdin.ref(); // a prior picker/prompt may have unref'd stdin; without
@@ -394,7 +402,7 @@ function readKey(question) {
394
402
  return new Promise((resolve) => {
395
403
  if (!process.stdin.isTTY) return resolve("");
396
404
  process.stdout.write(question);
397
- readline.emitKeypressEvents(process.stdin);
405
+ readline.emitKeypressEvents(process.stdin, KEYS);
398
406
  process.stdin.setRawMode(true);
399
407
  process.stdin.resume();
400
408
  process.stdin.ref();
@@ -720,11 +728,15 @@ async function up() {
720
728
  }
721
729
  }
722
730
 
723
- // Supervisor — factory watch (background daemon, the "let it work" loop)
724
- if (has("factory")) {
725
- const r = startDaemon("factory-watch", "factory", ["watch", "--all"]);
726
- go.push(`${C.bold("Supervisor")} ${C.dim(r.already ? "already running" : "running")} — heals agents, catches stalls ${C.dim("· live view: factory board")}`);
731
+ // The watcher — seldon's own supervisor: tells you when an agent needs you, fails or
732
+ // finishes. Plain code, no tokens, no rooms.
733
+ {
734
+ const r = startWatch();
735
+ go.push(`${C.bold("Watcher")} ${C.dim(r.already ? "already running" : "running")} — tells you when an agent needs you ${C.dim("· the panel: seldon")}`);
727
736
  }
737
+ // factory's supervisor only matters for projects that use rooms (heals room agents, files
738
+ // decisions from them). It no longer posts into rooms.
739
+ if (has("factory")) startDaemon("factory-watch", "factory", ["watch", "--all"]);
728
740
 
729
741
  // The rest are on-demand, not daemons — point at the command.
730
742
  if (has("factory")) go.push(`${C.bold("Put agents to work")} ${C.cyan('factory new "<your idea>"')} ${C.dim("→ repo · foundation · apiary hive")}`);
@@ -739,7 +751,7 @@ async function up() {
739
751
  }
740
752
 
741
753
  function down() {
742
- const tracked = ["demerzel", "bonsai", "factory-watch"].filter((n) => stopDaemon(n));
754
+ const tracked = ["demerzel", "bonsai", "factory-watch", "seldon-watch"].filter((n) => stopDaemon(n));
743
755
  // Belt-and-suspenders so nothing leaks: also reap by seldon's OWN ports and
744
756
  // process signatures. This catches a server started outside seldon (manual
745
757
  // launch) or a pidfile that drifted. Scoped tightly — only our ports and
@@ -751,6 +763,7 @@ function down() {
751
763
  `pgrep -f '${SELDON_HOME}/bonsai/bin/llama-server'`,
752
764
  "pgrep -f 'demerzel[.]server'",
753
765
  "pgrep -f 'factory.*watch --all'",
766
+ "pgrep -f 'seldon[.]js watch'",
754
767
  ];
755
768
  const collect = () => {
756
769
  const s = new Set();
@@ -859,6 +872,468 @@ function dockerState() {
859
872
  try { execSync("docker info", { stdio: "ignore", timeout: 8000 }); return "up"; } catch { return "down"; }
860
873
  }
861
874
 
875
+
876
+
877
+ // readline waits 500ms after Esc to tell a bare Esc from an Alt-sequence, so Esc then a quick
878
+ // key read as Alt+key and the screen ignored both. 50ms still catches real escape sequences,
879
+ // which a terminal sends in one write. Whichever emitKeypressEvents call runs first wins, so
880
+ // every caller passes this.
881
+ const KEYS = { escapeCodeTimeout: 50 };
882
+
883
+ // ---- raw-terminal plumbing, once ---------------------------------------------
884
+ // Both interactive screens (the install picker and the panel) need the same four-step dance,
885
+ // and the pause/unref at the end is load-bearing: emitKeypressEvents resumes stdin, and
886
+ // without releasing it the event loop stays alive and the process hangs after the screen
887
+ // closes. That bug was fixed once in the picker; sharing it means the panel cannot
888
+ // reintroduce it. `suspend` lets a screen hand the terminal to a child process and take it
889
+ // back — the panel does that every time it staffs an agent.
890
+ // `onError` gets anything a key handler throws — shown, never swallowed.
891
+ function rawSession({ draw, onKey, onError }) {
892
+ let done = null;
893
+ const listen = () => {
894
+ readline.emitKeypressEvents(process.stdin, KEYS);
895
+ if (process.stdin.isTTY) process.stdin.setRawMode(true);
896
+ process.stdin.resume();
897
+ process.stdin.on("keypress", handler);
898
+ };
899
+ const release = () => {
900
+ process.stdin.off("keypress", handler);
901
+ if (process.stdin.isTTY) process.stdin.setRawMode(false);
902
+ process.stdin.pause();
903
+ process.stdin.unref();
904
+ };
905
+ // Keys are handled one at a time, in order. A handler can take a while (it may spawn a CLI),
906
+ // and keys typed meanwhile used to run concurrently with it — Esc and the next prompt raced
907
+ // the first, leaving a stale screen and dropped characters.
908
+ let chain = Promise.resolve();
909
+ const handler = (str, key) => { chain = chain.then(() => onKey(str, key, api)).catch((e) => { onError?.(e); api.draw(); }); };
910
+ const api = {
911
+ draw: () => draw(api),
912
+ finish: (v) => { release(); readline.cursorTo(process.stdout, 0); readline.clearScreenDown(process.stdout); done(v); },
913
+ // run something that owns the terminal (a child process), then come back
914
+ suspend: async (fn) => { release(); try { return await fn(); } finally { listen(); api.draw(); } },
915
+ };
916
+ return new Promise((resolve) => { done = resolve; listen(); api.draw(); });
917
+ }
918
+
919
+ const clearScreen = () => { readline.cursorTo(process.stdout, 0, 0); readline.clearScreenDown(process.stdout); };
920
+
921
+ // Pad to a COLUMN width, then colour. Padding a string that already carries ANSI escapes
922
+ // counts those invisible bytes as width, which silently knocked every column after a coloured
923
+ // cell out of line.
924
+ const pad = (text, width, color = (x) => x) => color(String(text)) + " ".repeat(Math.max(0, width - String(text).length));
925
+
926
+ // ---- the panel: every agent, every project ------------------------------------
927
+ // Bare `seldon` is this screen: every coding agent on this machine (Claude, Codex, opencode),
928
+ // grouped by the project it works on, the ones waiting on you first. Lanes are read from the
929
+ // harnesses themselves (lib/agents.mjs), not from rooms, so the panel works with or without
930
+ // factory and apiary; when factory is there its projects and plans are shown too.
931
+ async function panel() {
932
+ ensureSiblingPath();
933
+ let groups = [], state = null, rows = [], cur = 0, note = "";
934
+ let lastState = 0;
935
+ // What the screen is doing: the home list, a project's plan, a line of text being typed, or
936
+ // picking which agent starts a lane. One at a time; esc always goes back to home.
937
+ let mode = { name: "home" };
938
+ let armedStop = null; // { key, at } — stop needs a second x within 3s
939
+ const here = projectRoot(process.cwd()); // the repo seldon was opened in is always listed
940
+ // Other machines (bifrost's realms). Their lanes arrive in the background every 10s, so a
941
+ // slow or sleeping machine never freezes this screen; `seen` says how each one answered.
942
+ const machines = listMachines();
943
+ const seen = new Map(); // name -> { groups, error, at, inflight }
944
+ const pollMachines = () => {
945
+ for (const m of machines) {
946
+ const was = seen.get(m.name) || {};
947
+ if (was.inflight || (was.at && Date.now() - was.at < 10_000)) continue;
948
+ seen.set(m.name, { ...was, inflight: true });
949
+ 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 }); });
950
+ }
951
+ };
952
+ const machineOf = (name) => machines.find((m) => m.name === name);
953
+ // Run seldon (or foundation) on a machine. `tty`: it may need a terminal (a trust dialog),
954
+ // so it inherits this one; otherwise its output is captured for the note line.
955
+ const onMachine = (name, argv, { tty = false } = {}) => {
956
+ const r = spawnSync("ssh", sshArgs(machineOf(name), argv, { tty }), tty ? { stdio: "inherit" } : { encoding: "utf8" });
957
+ seen.set(name, { ...(seen.get(name) || {}), at: 0 }); // it changed: ask it again on the next tick
958
+ const said = tty ? "" : `${r.stdout || ""}${r.stderr || ""}`.trim().split("\n").filter(Boolean).pop() || "";
959
+ return { ok: r.status === 0, out: r.stdout || "", error: r.status === 0 ? null : said || `ssh exited ${r.status}` };
960
+ };
961
+ const load = (force = false) => {
962
+ pollMachines();
963
+ groups = [...readLanes(), ...[...seen.values()].flatMap((v) => v.groups || [])];
964
+ if (force || Date.now() - lastState > 10_000) { state = has("factory") ? loadState() : null; lastState = Date.now(); }
965
+ const prev = rows[cur];
966
+ rows = buildRows(groups, state?.hives || [], sameDir, here);
967
+ // Keep the cursor on the same thing across a refresh, not the same row number.
968
+ const keep = prev && rows.findIndex((r) => r.type === prev.type && (r.type === "lane" ? r.lane.key === prev.lane.key : r.project.root === prev.project.root));
969
+ cur = keep >= 0 ? keep : Math.min(cur, Math.max(0, rows.length - 1));
970
+ };
971
+ const allLanes = () => groups.flatMap((g) => g.lanes);
972
+
973
+ const svc = (label, on) => (on ? C.green("●") : C.dim("○")) + " " + label;
974
+ const tint = { "needs-you": C.gold, working: C.green, running: C.green, idle: C.dim, failed: C.red, stopped: C.dim };
975
+ // Below 70 columns (a phone over ssh) a lane is one short line: glyph, name, the state in a
976
+ // word. The full detail is one ⏎ away.
977
+ const narrow = () => (process.stdout.columns || 100) < 70;
978
+ const laneCells = (l, sel) => {
979
+ const color = tint[l.state] || ((x) => x);
980
+ const name = (l.name || l.id || "?");
981
+ if (narrow()) {
982
+ const w = Math.max(10, (process.stdout.columns || 40) - 22);
983
+ return `${color(GLYPH[l.state] || "?")} ${pad(name.slice(0, w), w, sel ? C.bold : (x) => x)} ${color(l.state === "needs-you" ? "needs you" : l.state)}`;
984
+ }
985
+ return `${color(GLYPH[l.state] || "?")} ${pad(name.slice(0, 26), 26, sel ? C.bold : (x) => x)} ${pad(l.harness, 9, C.dim)} ${pad(laneDetail(l).slice(0, 40), 40, color)} ${C.dim(ago(l.startedAt))}`;
986
+ };
987
+
988
+ const drawHome = (out) => {
989
+ if (!rows.length) {
990
+ out.push(C.dim(" no agents running and no projects yet."));
991
+ out.push(" " + C.cyan("cd <repo> && seldon") + C.dim(", then ") + C.cyan("n") + C.dim(" starts an agent on a task"));
992
+ out.push(C.dim(" add-ons (rooms, voice, secrets, plans): ") + C.cyan("seldon install"));
993
+ }
994
+ rows.forEach((r, i) => {
995
+ const sel = i === cur;
996
+ const cursor = sel ? C.gold("❯") : " ";
997
+ if (r.type === "project") {
998
+ const p = r.project;
999
+ const plan = p.hive ? C.dim(`plan ${p.hive.queueOpen} · ${p.hive.done} done`) : "";
1000
+ const why = p.hive?.needsYou && p.hive.why ? C.gold(" ⚑ " + p.hive.why) : "";
1001
+ const others = unlistedAgents(p);
1002
+ out.push(` ${cursor} ${pad(p.name, 22, C.bold)} ${plan}${others.length ? C.green(" agents: " + others.join(", ")) : ""}${why}`);
1003
+ if (sel && !narrow()) out.push(` ${C.dim(p.root)}`);
1004
+ } else {
1005
+ out.push(` ${cursor} ${laneCells(r.lane, sel)}`);
1006
+ if (sel && r.lane.cwd !== r.project.root && !narrow()) out.push(` ${C.dim(r.lane.cwd)}`);
1007
+ }
1008
+ });
1009
+ const sel = rows[cur];
1010
+ out.push("");
1011
+ if (narrow()) out.push(" " + C.dim(sel?.type === "lane" ? "⏎ open · x stop · R resume · q" : "n lane · p plan · ⏎ go · q"));
1012
+ else {
1013
+ out.push(" " + C.dim(sel?.type === "lane"
1014
+ ? "↑↓ move · ⏎ open · x stop · R resume · n new lane · p plan · r refresh · q quit"
1015
+ : "↑↓ move · n new lane · p plan · ⏎ go (staff + room) · s staff · a room · b board · q quit"));
1016
+ out.push(" " + C.dim("U start stack · D stop stack · i install"));
1017
+ }
1018
+ };
1019
+
1020
+ const drawPlan = (out) => {
1021
+ const { project, items } = mode;
1022
+ out.push(` ${C.bold("PLAN")} ${C.dim("·")} ${C.bold(project.name)} ${C.dim(items ? `${items.length} open` : "")}`);
1023
+ out.push("");
1024
+ if (items === null) out.push(C.dim(" no plan here — needs foundation ≥ 0.3 and docs/QUEUE.md (") + C.cyan("foundation init") + C.dim(")"));
1025
+ else if (!items.length) out.push(C.dim(" the plan is empty — ") + C.cyan("a") + C.dim(" adds an item"));
1026
+ (items || []).forEach((it, i) => {
1027
+ const sel = i === mode.cur;
1028
+ const lane = laneForItem(it, allLanes());
1029
+ const tag = lane ? (tint[lane.state] || ((x) => x))(`${GLYPH[lane.state]} ${lane.harness} ${laneDetail(lane)}`) : C.dim("— no lane");
1030
+ out.push(` ${sel ? C.gold("❯") : " "} ${C.dim(`(${it.priority})`)} ${pad(it.text.slice(0, 60), 60, sel ? C.bold : (x) => x)} ${tag}`);
1031
+ });
1032
+ out.push("");
1033
+ out.push(" " + C.dim("↑↓ move · ⏎ start a lane on it · a add an item · esc back"));
1034
+ };
1035
+
1036
+ const drawInput = (out) => {
1037
+ out.push(` ${C.bold(mode.title)}`);
1038
+ out.push("");
1039
+ out.push(` ${mode.prompt} ${mode.buf}${C.gold("▏")}`);
1040
+ out.push("");
1041
+ out.push(" " + C.dim("⏎ ok · esc cancel"));
1042
+ };
1043
+
1044
+ const drawHarness = (out) => {
1045
+ out.push(` ${C.bold("NEW LANE")} ${C.dim("·")} ${C.bold(mode.project.name)}`);
1046
+ out.push("");
1047
+ out.push(` task ${mode.task}`);
1048
+ out.push(` agent ${HARNESSES.map((h, i) => `${C.cyan(String(i + 1))} ${h}`).join(" ")}`);
1049
+ out.push("");
1050
+ out.push(" " + C.dim("⏎ claude · 1/2/3 pick · esc cancel (each lane gets its own branch + worktree)"));
1051
+ };
1052
+
1053
+ const draw = () => {
1054
+ const out = [""];
1055
+ out.push(" " + C.gold(C.bold("SELDON")) + " " + headline(groups) + " " + C.dim([
1056
+ svc("watcher", !!daemonUp("seldon-watch")), svc("voice", !!daemonUp("demerzel")),
1057
+ ].join(" ")));
1058
+ if (machines.length) out.push(" " + C.dim("machines: ") + machines.map((m) => {
1059
+ const v = seen.get(m.name);
1060
+ return !v?.at ? C.dim(`${m.name} …`) : v.error ? C.red(`${m.name} ${v.error}`) : C.green(m.name);
1061
+ }).join(C.dim(" ")));
1062
+ const hs = listHolds();
1063
+ if (hs.length) out.push(" " + C.dim("held: ") + hs.map((h) => `${C.bold(h.resource)} ${C.dim("→ " + h.who + " " + ago(h.since))}`).join(C.dim(" ")));
1064
+ out.push("");
1065
+ ({ home: drawHome, plan: drawPlan, input: drawInput, harness: drawHarness })[mode.name](out);
1066
+ if (note) out.push("\n " + note);
1067
+ clearScreen();
1068
+ process.stdout.write(out.join("\n") + "\n");
1069
+ };
1070
+
1071
+ load(true);
1072
+ // Live: lanes change on their own, so redraw without a keypress. Cheap — one
1073
+ // `claude agents --json` and one `tmux list-panes` per tick.
1074
+ let timer = null;
1075
+ const tick = () => { try { load(); } catch { /* keep the last frame */ } draw(); };
1076
+ const startTimer = () => { timer = setInterval(tick, 2000); };
1077
+ const stopTimer = () => { clearInterval(timer); timer = null; };
1078
+ startTimer();
1079
+
1080
+ // Hand the terminal to something that needs it, then come back to a fresh frame.
1081
+ const runOwned = async (api, fn) => { stopTimer(); try { return await api.suspend(fn); } finally { load(true); startTimer(); } };
1082
+
1083
+ const planOf = (project) => (project.machine
1084
+ ? lastJsonLine(onMachine(project.machine, ["foundation", "queue", "--list", "--json", "--dir", project.remoteRoot]).out)
1085
+ : readPlan(project.root));
1086
+ const openPlan = (project) => { mode = { name: "plan", project, items: planOf(project), cur: 0 }; };
1087
+ const ask = (title, prompt, then) => { mode = { name: "input", title, prompt, buf: "", then }; };
1088
+ const pickHarness = (project, task) => { mode = { name: "harness", project, task }; };
1089
+
1090
+ // Bring stopped lanes back (after a reboot, a crash). Says plainly what it could not do.
1091
+ const resumeLanes = async (api, lanes) => {
1092
+ const said = [];
1093
+ for (const l of lanes) {
1094
+ const res = await runOwned(api, () => (l.machine ? onMachine(l.machine, ["seldon", "lane", "resume", l.remoteKey], { tty: true }) : resumeLane(l)));
1095
+ said.push(res.why ? C.gold(`${l.name}: `) + res.why
1096
+ : res.ok ? C.green(`resumed ${l.name}`) + (res.fresh ? C.dim(" (new conversation, same task + worktree)") : "")
1097
+ : C.red(`${l.name}: `) + res.error);
1098
+ }
1099
+ return said.join(C.dim(" · "));
1100
+ };
1101
+
1102
+ const startNewLane = async (api, project, task, harness) => {
1103
+ const r = await runOwned(api, () => (project.machine
1104
+ ? { ...onMachine(project.machine, ["seldon", "lane", "start", project.remoteRoot, "--task", task, "--agent", harness], { tty: true }), slug: slugify(task) }
1105
+ : startLane({ root: project.root, name: project.name, task, harness })));
1106
+ note = r.ok ? C.green(`started ${r.slug} (${harness})`) + C.dim(" — it shows up here in a moment") : C.red(`could not start ${r.slug || "the lane"}: `) + r.error;
1107
+ mode = { name: "home" };
1108
+ };
1109
+
1110
+ const keys = {
1111
+ input: async (str, key) => {
1112
+ if (key.name === "escape") mode = { name: "home" };
1113
+ else if (key.name === "return") { const t = mode.buf.trim(); const then = mode.then; mode = { name: "home" }; if (t) await then(t); }
1114
+ else if (key.name === "backspace") mode.buf = mode.buf.slice(0, -1);
1115
+ else if (str && !key.ctrl && !key.meta && str >= " ") mode.buf += str;
1116
+ },
1117
+ harness: async (str, key, api) => {
1118
+ if (key.name === "escape") { mode = { name: "home" }; return; }
1119
+ const i = key.name === "return" ? 0 : "123".indexOf(str);
1120
+ if (i >= 0) await startNewLane(api, mode.project, mode.task, HARNESSES[i]);
1121
+ },
1122
+ plan: async (str, key) => {
1123
+ const items = mode.items || [];
1124
+ if (key.name === "escape" || str === "q") mode = { name: "home" };
1125
+ else if (key.name === "up" || str === "k") mode.cur = Math.max(0, mode.cur - 1);
1126
+ else if (key.name === "down" || str === "j") mode.cur = Math.min(Math.max(0, items.length - 1), mode.cur + 1);
1127
+ else if (str === "a") {
1128
+ const project = mode.project;
1129
+ ask(`ADD TO PLAN · ${project.name}`, "(P2) ›", (text) => {
1130
+ const r = project.machine
1131
+ ? onMachine(project.machine, ["foundation", "queue", `(P2) ${text}`, "--dir", project.remoteRoot])
1132
+ : addToPlan(project.root, text);
1133
+ openPlan(project);
1134
+ note = r.ok ? C.green("added") : C.red("could not add: ") + r.error;
1135
+ });
1136
+ } else if (key.name === "return" && items[mode.cur]) {
1137
+ const it = items[mode.cur];
1138
+ const lane = laneForItem(it, allLanes());
1139
+ if (lane) note = C.dim(`already has a lane: ${lane.name} (${lane.harness}, ${laneDetail(lane)})`);
1140
+ else pickHarness(mode.project, it.text);
1141
+ }
1142
+ },
1143
+ home: async (str, key, api) => {
1144
+ const r = rows[cur];
1145
+ if (key.name === "up" || str === "k") cur = (cur - 1 + (rows.length || 1)) % (rows.length || 1);
1146
+ else if (key.name === "down" || str === "j") cur = (cur + 1) % (rows.length || 1);
1147
+ else if (str === "q" || key.name === "escape" || (key.ctrl && key.name === "c")) { stopTimer(); return api.finish(); }
1148
+ else if (str === "r") load(true);
1149
+ else if (str === "i") { stopTimer(); api.finish(); return install_picker(); }
1150
+ else if (str === "U") await runOwned(api, () => up());
1151
+ else if (str === "D") await runOwned(api, () => down());
1152
+ else if (!r) { /* nothing selected */ }
1153
+ else if (str === "n") { const p = r.project; ask(`NEW LANE · ${p.name}`, "task ›", (task) => pickHarness(p, task)); }
1154
+ else if (str === "p") openPlan(r.project);
1155
+ else if (str === "R") {
1156
+ const targets = (r.type === "lane" ? [r.lane] : r.project.lanes).filter((l) => l.state === "stopped" || l.state === "failed");
1157
+ if (!targets.length) note = C.dim("nothing stopped here to resume");
1158
+ else note = await resumeLanes(api, targets);
1159
+ }
1160
+ else if (r.type === "lane") {
1161
+ if (key.name === "return") {
1162
+ const how = openCommand(r.lane);
1163
+ if (how.why) note = C.gold(`can't open ${r.lane.name || "this agent"}: `) + how.why;
1164
+ else if (r.lane.machine) await runOwned(api, () => onMachine(r.lane.machine, ["seldon", "lane", "open", r.lane.remoteKey], { tty: true }));
1165
+ else await runOwned(api, () => spawnSync(how.bin, how.args, { stdio: "inherit", cwd: how.cwd }));
1166
+ } else if (str === "x") {
1167
+ const cannot = stopCommand(r.lane).why;
1168
+ if (cannot) note = C.gold(`can't stop ${r.lane.name || "this agent"}: `) + cannot;
1169
+ else if (armedStop?.key === r.lane.key && Date.now() - armedStop.at < 3000) {
1170
+ armedStop = null;
1171
+ const res = await runOwned(api, () => (r.lane.machine ? onMachine(r.lane.machine, ["seldon", "lane", "stop", r.lane.remoteKey]) : stopLane(r.lane)));
1172
+ note = res.why ? C.gold(`can't stop ${r.lane.name || "this agent"}: `) + res.why
1173
+ : res.ok ? C.dim(`stopped ${r.lane.name}`) : C.red(`could not stop: ${res.error}`);
1174
+ } else { armedStop = { key: r.lane.key, at: Date.now() }; note = C.gold(`press x again to stop ${r.lane.name}`); }
1175
+ }
1176
+ } else {
1177
+ const p = r.project;
1178
+ if (p.machine && key.name === "return") note = C.dim(`on ${p.machine} — n starts a lane there, p shows its plan; for the rest: ssh ${p.machine}, then seldon`);
1179
+ else if (key.name === "return") { stopTimer(); api.finish(); return go(p.hive ? p.hive.name : p.root); }
1180
+ if (!p.hive && "sab".includes(str)) note = C.dim("not adopted yet — ⏎ (seldon go) puts it on the line");
1181
+ else if (str === "a") { stopTimer(); api.finish(); return fAttach(p.hive.name); }
1182
+ else if (str === "b") await runOwned(api, () => spawnSync("factory", ["board"], { stdio: "inherit" }));
1183
+ else if (str === "s") await runOwned(api, () => { fStaff(p.root); });
1184
+ }
1185
+ },
1186
+ };
1187
+
1188
+ await rawSession({
1189
+ draw,
1190
+ onError: (e) => { note = C.red("error: ") + (e?.message || String(e)); mode = { name: "home" }; },
1191
+ onKey: async (str, key, api) => {
1192
+ if (mode.name === "home" && note && !note.includes("press x again")) note = "";
1193
+ if (key.ctrl && key.name === "c") { stopTimer(); return api.finish(); }
1194
+ const done = await keys[mode.name](str, key, api);
1195
+ if (done !== undefined) return done;
1196
+ api.draw();
1197
+ },
1198
+ });
1199
+ }
1200
+
1201
+ // ---- go: the one verb that gets you back to work ----------------------------
1202
+ // Every other command answered half of "I am in my repo, continue": `seldon up` started
1203
+ // daemons, `factory adopt` opened a room, `factory staff` put an agent in it, `apiary room
1204
+ // resume` got you a seat. Four commands across three tools, and none of them said which one
1205
+ // you needed — so an adopted repo with a stopped room looked identical to a broken install.
1206
+ //
1207
+ // `go` owns no decisions. It asks `factory state` what is missing and fills the gaps in order,
1208
+ // printing ✓ for a step it SKIPPED and → for one it DID, so the output doubles as the
1209
+ // explanation of how the pieces fit. Every step is idempotent: safe from a cold boot, safe
1210
+ // twice in a row, safe mid-session.
1211
+ const sDid = (t) => console.log(" " + C.gold("→") + " " + t);
1212
+ const sSkip = (t) => console.log(" " + C.green("✓") + " " + t);
1213
+ const sWarn = (t) => console.log(" " + C.gold("!") + " " + t);
1214
+
1215
+ function needFactory() {
1216
+ if (has("factory")) return true;
1217
+ console.log(C.red("\n this needs factory — install it: ") + C.cyan("seldon install factory") + "\n");
1218
+ process.exitCode = 1;
1219
+ return false;
1220
+ }
1221
+
1222
+ // `seldon go [name|dir] [--agent claude|codex] [--model X] [--effort E] [--no-staff] [--no-attach]`
1223
+ async function go(arg, flags = {}) {
1224
+ ensureSiblingPath();
1225
+ if (!needFactory()) return;
1226
+
1227
+ let state = loadState();
1228
+ if (!state) {
1229
+ console.log(C.red("\n could not read the hive registry (`factory state` failed).") +
1230
+ C.dim("\n try: factory state --compact\n"));
1231
+ process.exitCode = 1; return;
1232
+ }
1233
+ let t = resolveProject(arg, state);
1234
+
1235
+ if (t.kind === "unknown") {
1236
+ console.log(C.red(`\n no project or repo called "${t.arg}" `) + C.dim(`(${t.reason})`));
1237
+ if (state.hives.length) {
1238
+ console.log(C.dim(" on the line: ") + state.hives.map((h) => C.bold(h.name)).join(C.dim(" · ")));
1239
+ }
1240
+ console.log("");
1241
+ process.exitCode = 1; return;
1242
+ }
1243
+ // Not in a repo and no name given: the panel is the right answer to "where was I".
1244
+ if (t.kind === "nowhere") {
1245
+ if (!state.hives.length) {
1246
+ console.log(C.gold("\n nothing on the line yet.") +
1247
+ C.dim("\n a new idea: ") + C.cyan('factory new "<your idea>"') +
1248
+ C.dim("\n a repo you have: ") + C.cyan("cd <repo> && seldon go") + "\n");
1249
+ return;
1250
+ }
1251
+ if (process.stdin.isTTY) return panel();
1252
+ console.log(C.gold("\n not inside a git repo — name a project:"));
1253
+ for (const h of state.hives) console.log(` ${C.cyan("seldon go " + h.name)} ${C.dim(h.dir)}`);
1254
+ console.log("");
1255
+ process.exitCode = 1; return;
1256
+ }
1257
+
1258
+ const dir = t.dir;
1259
+ console.log("\n " + C.gold(C.bold(path.basename(dir))) + " " + C.dim(dir));
1260
+
1261
+ // 1. on the line? `factory adopt` is idempotent — it never overwrites docs and reuses a
1262
+ // reachable hive, so it is both "adopt me" and "reopen my room".
1263
+ let hive = t.kind === "hive" ? t.hive : null;
1264
+ if (!hive) {
1265
+ sDid("not on the line yet — adopting");
1266
+ if (!fAdopt(dir)) { process.exitCode = 1; return; }
1267
+ state = loadState(); hive = hiveOf(state, dir);
1268
+ if (!hive) { sWarn("adopted, but the hive did not register — run: factory adopt " + dir); process.exitCode = 1; return; }
1269
+ } else {
1270
+ sSkip("adopted" + C.dim(" (foundation docs in place)"));
1271
+ }
1272
+
1273
+ // 2. room up? A stopped room is the single most common state after a reboot, and the one
1274
+ // that used to look like a broken install.
1275
+ if (hive.up) {
1276
+ sSkip("hive up" + C.dim(hive.url ? " " + hive.url : ""));
1277
+ } else {
1278
+ sDid("hive is down — reopening" + C.dim(" (room history resumes)"));
1279
+ if (!fAdopt(dir)) { process.exitCode = 1; return; }
1280
+ state = loadState(); hive = hiveOf(state, dir) || hive;
1281
+ if (!hive.up) sWarn("the room still is not answering — check: apiary ps");
1282
+ }
1283
+
1284
+ // 3. the supervisor heals dead agents and catches stalls. `go` starts it rather than
1285
+ // telling you to go and run `seldon up` first.
1286
+ if (daemonUp("factory-watch")) sSkip("supervisor running");
1287
+ else { startDaemon("factory-watch", "factory", ["watch", "--all"]); sDid("supervisor started" + C.dim(" (heals agents, catches stalls)")); }
1288
+ if (!startWatch().already) sDid("watcher started" + C.dim(" (tells you when an agent needs you)"));
1289
+
1290
+ // 4. is anyone actually working here? This is the step that was missing: `factory adopt`
1291
+ // opens an EMPTY room, and nothing said so — you joined and sat there alone.
1292
+ // `agents` is absent from an older factory that cannot report it. Absent is NOT empty:
1293
+ // claiming "nobody is working here" when we simply do not know got printed over a running
1294
+ // Coordinator. Unknown falls through to `factory staff`, which is idempotent and says the
1295
+ // truth either way.
1296
+ const agents = hive.agents;
1297
+ const known = Array.isArray(agents);
1298
+ if (!known) sWarn("this factory is too old to report agents — " + C.cyan("seldon install factory"));
1299
+ if (known && agents.length) {
1300
+ sSkip("working here: " + C.bold(agents.join(", ")));
1301
+ } else if (flags["no-staff"]) {
1302
+ sSkip(C.dim("no agent (--no-staff)"));
1303
+ } else if (!has("apiary")) {
1304
+ sWarn("apiary is not installed — no agent can be staffed: " + C.cyan("seldon install apiary"));
1305
+ } else if (!has("tmux")) {
1306
+ sWarn("tmux is missing — apiary runs each agent in a tmux session: " + C.cyan("brew install tmux"));
1307
+ } else {
1308
+ sDid(known ? "nobody is working here — staffing" : "staffing (if nobody already is)");
1309
+ if (!fStaff(dir, flags)) sWarn("staffing failed — watch it try: factory board");
1310
+ state = loadState(); hive = hiveOf(state, dir) || hive;
1311
+ }
1312
+
1313
+ // 5. where the work stands, from the seam — the answer to "what was I doing".
1314
+ const bits = [`queue ${C.cyan(hive.queueOpen)}`, `${C.green(hive.done)} done`, `${hive.lanes.length} lanes`];
1315
+ if (hive.blockers) bits.push(C.red(`${hive.blockers} blocker`));
1316
+ if (hive.drift) bits.push(C.gold(`drift ${hive.drift}`));
1317
+ console.log(" " + C.dim(bits.join(" · ")));
1318
+ for (const n of (hive.next || []).slice(0, 2)) console.log(" " + C.dim("next: ") + n.slice(0, 96) + (n.length > 96 ? "…" : ""));
1319
+ const mine = (state.decisions || []).filter((d) => d.hive === hive.name);
1320
+ for (const d of mine) console.log(" " + C.gold("⚑ your call: ") + d.text.replace(/^\w+:\s*/, "").slice(0, 80) + C.dim(` (factory decide ${d.id} "…")`));
1321
+
1322
+ // 6. a seat in the room. `apiary room resume` restarts a stopped room, refreshes the share
1323
+ // tokens and shows the agent strip — the command nothing ever pointed at.
1324
+ if (flags["no-attach"]) { console.log("\n " + C.dim("attach when you want it: ") + C.cyan(`apiary room resume ${hive.name}`) + "\n"); return; }
1325
+ if (!has("apiary")) { console.log(""); return; }
1326
+ // Attaching takes over the terminal, so it is gated on having one. `--attach` forces it for
1327
+ // the cases where there IS a terminal we cannot see — a tmux pane, a wrapper script.
1328
+ if (!process.stdin.isTTY && !flags.attach) {
1329
+ console.log("\n " + C.dim("no TTY — attach from your terminal: ") + C.cyan(`apiary room resume ${hive.name}`) +
1330
+ C.dim(" (or: seldon go --attach)") + "\n");
1331
+ return;
1332
+ }
1333
+ sDid(`attaching to the ${C.bold(hive.name)} room` + C.dim(" (ctrl-c leaves the room; agents keep working)"));
1334
+ fAttach(hive.name);
1335
+ }
1336
+
862
1337
  // ---- adopt: bring an existing repo onto the line ----------------------------
863
1338
  // factory owns the registry + hive, so this is a front door onto `factory adopt`.
864
1339
  function adopt(target) {
@@ -882,23 +1357,23 @@ const BANNER = [
882
1357
  " ╚══════╝╚══════╝╚══════╝╚═════╝ ╚═════╝ ╚═╝ ╚═══╝",
883
1358
  ];
884
1359
  function tui() {
885
- return new Promise((resolve) => {
886
- // Pre-check what's already installed so the picker mirrors reality. On a
887
- // fresh machine (nothing installed) fall back to the recommended starter set.
888
- const anyInstalled = MODULES.some((m) => moduleInstalled(m));
889
- const rows = MODULES.map((m) => ({
890
- m,
891
- installed: moduleInstalled(m),
892
- on: platformOk(m) && (anyInstalled ? moduleInstalled(m) : ["apiary", "foundation", "factory"].includes(m.id)),
893
- }));
894
- let cur = 0;
895
- const methodTag = (m) => ({ npm: "npm", shell: "shell", python: "python" }[m.method]);
896
- const draw = () => {
897
- readline.cursorTo(process.stdout, 0, 0);
898
- readline.clearScreenDown(process.stdout);
1360
+ // Pre-check what's already installed so the picker mirrors reality. On a
1361
+ // fresh machine (nothing installed) fall back to the recommended starter set.
1362
+ const anyInstalled = MODULES.some((m) => moduleInstalled(m));
1363
+ const rows = MODULES.map((m) => ({
1364
+ m,
1365
+ installed: moduleInstalled(m),
1366
+ // seldon itself runs your agents; foundation adds the plan. Everything else is an add-on
1367
+ // you choose on purpose, so a fresh machine starts with just that.
1368
+ on: platformOk(m) && (anyInstalled ? moduleInstalled(m) : m.id === "foundation"),
1369
+ }));
1370
+ let cur = 0;
1371
+ const methodTag = (m) => ({ npm: "npm", shell: "shell", python: "python" }[m.method]);
1372
+ return rawSession({
1373
+ draw: () => {
899
1374
  const out = [];
900
1375
  BANNER.forEach((l) => out.push(C.gold(l)));
901
- out.push(C.dim(" the AI-agent-factory stack — pick your tools ") + C.green("✓ = installed"));
1376
+ out.push(C.dim(" seldon runs your agents on its own · foundation adds the plan · the rest are add-ons ") + C.green("✓ = installed"));
902
1377
  out.push(C.dim(" ↑↓ move · space toggle · a all · enter install · q quit\n"));
903
1378
  rows.forEach((r, i) => {
904
1379
  const sel = r.on ? C.green("[x]") : "[ ]";
@@ -911,32 +1386,30 @@ function tui() {
911
1386
  out.push(` ${cursor} ${sel} ${mark} ${name} ${C.dim(methodTag(r.m).padEnd(7))} ${C.dim(r.m.blurb)}${platNote}`);
912
1387
  if (i === cur) out.push(` ${C.dim("needs: " + (deps || "nothing"))}${r.m.requires.length ? C.dim(" · pulls in: " + r.m.requires.join(", ")) : ""}`);
913
1388
  });
1389
+ clearScreen();
914
1390
  process.stdout.write(out.join("\n") + "\n");
915
- };
916
- readline.emitKeypressEvents(process.stdin);
917
- if (process.stdin.isTTY) process.stdin.setRawMode(true);
918
- draw();
919
- const onKey = (str, key) => {
1391
+ },
1392
+ onKey: (str, key, api) => {
920
1393
  if (key.name === "up") cur = (cur - 1 + rows.length) % rows.length;
921
1394
  else if (key.name === "down") cur = (cur + 1) % rows.length;
922
1395
  else if (key.name === "space") { if (platformOk(rows[cur].m)) rows[cur].on = !rows[cur].on; }
923
1396
  else if (str === "a") { const all = rows.every((r) => r.on || !platformOk(r.m)); rows.forEach((r) => { if (platformOk(r.m)) r.on = !all; }); }
924
- else if (key.name === "return") return finish(rows.filter((r) => r.on).map((r) => r.m.id));
925
- else if (key.name === "q" || (key.ctrl && key.name === "c")) return finish(null);
926
- draw();
927
- };
928
- const finish = (ids) => {
929
- process.stdin.off("keypress", onKey);
930
- if (process.stdin.isTTY) process.stdin.setRawMode(false);
931
- process.stdin.pause(); // emitKeypressEvents resumed stdin; without this the
932
- process.stdin.unref(); // event loop stays alive and the process hangs after install
933
- readline.cursorTo(process.stdout, 0); readline.clearScreenDown(process.stdout);
934
- resolve(ids);
935
- };
936
- process.stdin.on("keypress", onKey);
1397
+ else if (key.name === "return") return api.finish(rows.filter((r) => r.on).map((r) => r.m.id));
1398
+ else if (key.name === "q" || (key.ctrl && key.name === "c")) return api.finish(null);
1399
+ api.draw();
1400
+ },
937
1401
  });
938
1402
  }
939
1403
 
1404
+ // The picker plus the install it leads to — `seldon install` with no ids, and `i` in the panel.
1405
+ async function install_picker({ dev = false } = {}) {
1406
+ if (!process.stdin.isTTY) { console.log(C.red("no TTY — use: seldon install <ids…>")); process.exitCode = 1; return; }
1407
+ const picked = await tui();
1408
+ if (!picked) { console.log(C.dim("nothing installed.")); return; }
1409
+ if (!picked.length) { console.log(C.dim("nothing selected.")); return; }
1410
+ await doInstall(picked, { dev });
1411
+ }
1412
+
940
1413
  // ---- cli --------------------------------------------------------------------
941
1414
  function list() {
942
1415
  console.log(C.bold("\nThe Seldon stack\n"));
@@ -948,16 +1421,23 @@ function list() {
948
1421
  }
949
1422
  function help() {
950
1423
  console.log(`
951
- ${C.bold("seldon")} — install the Seldon stack, pick what you use.
1424
+ ${C.bold("seldon")} — the agent factory: your projects, and the stack that runs them.
952
1425
 
953
- ${C.bold("seldon")} open the checklist (space to pick, enter to install)
1426
+ ${C.bold("seldon")} ${C.gold("the panel")} — every agent (claude · codex · opencode) by project; n new lane, p plan
1427
+ ${C.bold("seldon hold")} <thing> take a turn on a shared resource (emulator, unreal, gpu); waits if someone has it
1428
+ ${C.bold("seldon release")} <thing> give it back · ${C.bold("seldon holds")} who holds what
1429
+ ${C.bold("seldon go")} [name|dir] ${C.gold("get back to work")} — adopt if needed, reopen the room, staff an agent, attach.
1430
+ Idempotent, and it prints every step it skipped. Run it from inside a repo.
954
1431
  ${C.bold("seldon up")} start the stack (voice + supervisor) and print where to go
955
1432
  ${C.bold("seldon up --tailnet")} expose the voice over HTTPS (tailscale serve) so the mic works on your phone
956
1433
  ${C.bold("seldon up --brain=X")} pick the voice brain: qwen (in-process) | bonsai (local server); remembered
957
1434
  ${C.bold("seldon status")} what's running · ${C.bold("seldon down")} stop it
958
1435
  ${C.bold("seldon adopt")} [dir] put an existing repo on the line: foundation docs (never overwritten),
959
1436
  an apiary hive, supervised by factory — and print what's next. Safe to re-run.
960
- ${C.bold("seldon install")} [ids…] install everything picked, or the named modules
1437
+ ${C.dim("go takes --agent claude|codex, --model <id>, --effort <lvl>, --name <n>,")}
1438
+ ${C.dim(" --no-staff (do not start an agent), --no-attach (do not open the room) and")}
1439
+ ${C.dim(" --attach (open it even with no terminal detected — inside tmux, or from a script).")}
1440
+ ${C.bold("seldon install")} [ids…] install everything picked, or the named modules (no ids: the picker)
961
1441
  ${C.bold("seldon uninstall")} ids… remove the named modules (global CLI / isolated venv)
962
1442
  ${C.bold("seldon uninstall --all")} remove the whole stack (also drops ~/.seldon)
963
1443
  ${C.bold("seldon doctor")} [ids…] check external deps (tmux, sops, age, tailscale, python…)
@@ -974,9 +1454,211 @@ ${C.bold("seldon")} — install the Seldon stack, pick what you use.
974
1454
  `);
975
1455
  }
976
1456
 
977
- const argv = process.argv.slice(2);
978
- const dev = argv.includes("--dev");
979
- const args = argv.filter((a) => !a.startsWith("--"));
1457
+ // ---- the watcher: seldon's supervisor -----------------------------------------
1458
+ // Polls the lanes every 5s and tells you, once, when an agent starts waiting on you, fails
1459
+ // or finishes. Plain code: it costs no tokens and never types into an agent or a room.
1460
+ // `seldon up` runs it as a daemon; `seldon watch` runs it in the foreground.
1461
+ const SELF = fileURLToPath(import.meta.url);
1462
+ const startWatch = () => startDaemon("seldon-watch", process.execPath, [SELF, "watch"]);
1463
+
1464
+ async function watchCmd(flags) {
1465
+ ensureSiblingPath();
1466
+ const every = parseDuration(flags.interval, 5000) || 5000;
1467
+ let prev = new Map();
1468
+ const stamp = () => new Date().toTimeString().slice(0, 8);
1469
+ console.log(`${stamp()} seldon watch — every ${every / 1000}s`);
1470
+ for (;;) {
1471
+ let lanes = [];
1472
+ try { lanes = readLanes().flatMap((g) => g.lanes); } catch (e) { console.log(`${stamp()} read failed: ${e.message}`); }
1473
+ for (const e of transitions(prev, lanes)) {
1474
+ console.log(`${stamp()} ${e.text}`);
1475
+ notify(e.to === "needs-you" ? "Seldon · needs you" : "Seldon", `${e.text} — ${path.basename(e.lane.project || e.lane.cwd || "")}`);
1476
+ }
1477
+ prev = new Map(lanes.map((l) => [l.key, l.state]));
1478
+ if (flags.once) return;
1479
+ await new Promise((r) => setTimeout(r, every));
1480
+ }
1481
+ }
1482
+
1483
+ // ---- lanes from the command line ---------------------------------------------
1484
+ // The panel's actions, scriptable — and the protocol for other machines: the panel runs
1485
+ // `ssh <machine> seldon lanes --json` to read and `seldon lane <verb> <key>` to act.
1486
+ function lanesCmd(flags) {
1487
+ const groups = readLanes();
1488
+ if (flags.json) {
1489
+ process.stdout.write(JSON.stringify(groups.flatMap((g) => g.lanes.map((l) => ({ ...l, project: g.root, projectName: g.name })))) + "\n");
1490
+ return;
1491
+ }
1492
+ if (!groups.length) { console.log(C.dim("no agents running")); return; }
1493
+ for (const g of groups) {
1494
+ console.log(C.bold(g.name) + C.dim(" " + g.root));
1495
+ for (const l of g.lanes) console.log(` ${GLYPH[l.state] || "?"} ${(l.name || l.id || "?").padEnd(26)} ${l.harness.padEnd(9)} ${laneDetail(l).padEnd(36)} ${C.dim(l.key)}`);
1496
+ }
1497
+ }
1498
+
1499
+ function laneCmd(verb, arg, flags) {
1500
+ const fail = (msg) => { console.log(C.red(msg)); process.exitCode = 1; };
1501
+ if (verb === "start") {
1502
+ const root = projectRoot(path.resolve(arg || ".")) || path.resolve(arg || ".");
1503
+ const task = typeof flags.task === "string" ? flags.task : "";
1504
+ const r = startLane({ root, name: path.basename(root), task, harness: flags.agent || "claude" });
1505
+ return r.ok ? console.log(C.green(`✓ started ${r.slug}`) + C.dim(` (${flags.agent || "claude"}) in ${root}`)) : fail(`could not start: ${r.error}`);
1506
+ }
1507
+ if (!["stop", "resume", "open"].includes(verb)) return fail('usage: seldon lane start [dir] --task "…" [--agent claude|codex|opencode] · seldon lane stop|resume|open <key>');
1508
+ const lane = arg && findLane(arg);
1509
+ if (!lane) return fail(`no lane ${arg || ""} — see: seldon lanes`);
1510
+ if (verb === "open") {
1511
+ const how = openCommand(lane);
1512
+ if (how.why) return fail(`can't open ${lane.name}: ${how.why}`);
1513
+ process.exitCode = spawnSync(how.bin, how.args, { stdio: "inherit", cwd: how.cwd }).status ?? 1;
1514
+ return;
1515
+ }
1516
+ const r = verb === "stop" ? stopLane(lane) : resumeLane(lane);
1517
+ if (r.why) return fail(`can't ${verb} ${lane.name}: ${r.why}`);
1518
+ if (!r.ok) return fail(`${verb} failed: ${r.error}`);
1519
+ console.log(C.green(`✓ ${verb === "stop" ? "stopped" : "resumed"} ${lane.name}`) + (r.fresh ? C.dim(" (new conversation, same task + worktree)") : ""));
1520
+ }
1521
+
1522
+ // `seldon machines` — the other computers the panel shows (bifrost's realms, one list).
1523
+ function machinesCmd(verb, name, target) {
1524
+ if (verb === "add") {
1525
+ if (!name || !target) { console.log(C.red("usage: seldon machines add <name> <user@host>")); process.exitCode = 1; return; }
1526
+ addMachine(name, target);
1527
+ console.log(C.green(`✓ ${name} added`) + C.dim(` — the panel now asks it for its agents (it needs seldon there, and ssh keys: ssh ${target} works without a password)`));
1528
+ return;
1529
+ }
1530
+ const ms = listMachines();
1531
+ if (!ms.length) { console.log(C.dim("no other machines — add one: seldon machines add mini you@mini.tailnet.ts.net")); return; }
1532
+ let left = ms.length;
1533
+ for (const m of ms) fetchLanes(m, (r) => {
1534
+ console.log(` ${C.bold(m.name.padEnd(12))} ${C.dim((m.user ? m.user + "@" : "") + m.host)} ${r.error ? C.red(r.error) : C.green(`${r.lanes.length} agent(s)`)}`);
1535
+ if (--left === 0) process.exit(0);
1536
+ });
1537
+ }
1538
+
1539
+ // ---- harness reports: Codex and opencode say what they are doing ---------------
1540
+ // `seldon report <harness>` reads one hook/plugin event on stdin and records the session's
1541
+ // state. It must never slow down or break the agent that calls it: no output, exit 0 always.
1542
+ async function reportCmd(harness) {
1543
+ let raw = "";
1544
+ try { for await (const chunk of process.stdin) raw += chunk; writeReport(reportFromEvent(harness, JSON.parse(raw))); } catch { /* never fail the agent */ }
1545
+ }
1546
+
1547
+ // `seldon setup [codex|opencode] [--remove]` — install the reporter into each harness.
1548
+ const CODEX_HOOKS = path.join(process.env.HOME, ".codex", "hooks.json");
1549
+ const OPENCODE_PLUGIN = path.join(process.env.HOME, ".config", "opencode", "plugins", "seldon.js");
1550
+ function setupCmd(which, flags) {
1551
+ const targets = which ? [which] : ["codex", "opencode"].filter((h) => has(h) || flags.remove);
1552
+ if (!targets.length) { console.log(C.dim("neither codex nor opencode is installed — Claude needs no setup")); return; }
1553
+ // The command as you invoked it (the bin link), run through its own `#!/usr/bin/env node`:
1554
+ // the resolved file and the node binary both move on an upgrade (pnpm's store path, nvm's
1555
+ // version dir), and a hook pointing at a path that is gone fails on every event, silently.
1556
+ const bin = process.argv[1];
1557
+ const report = `SELDON_REPORT=1 ${JSON.stringify(bin)} report`;
1558
+ for (const h of targets) {
1559
+ if (h === "codex") {
1560
+ let cur = {};
1561
+ try { cur = JSON.parse(fs.readFileSync(CODEX_HOOKS, "utf8")); } catch (e) { if (fs.existsSync(CODEX_HOOKS)) { console.log(C.red(`~/.codex/hooks.json is not valid JSON — left alone: ${e.message}`)); continue; } }
1562
+ const next = flags.remove ? removeCodexHooks(cur) : mergeCodexHooks(cur, `${report} codex`);
1563
+ fs.mkdirSync(path.dirname(CODEX_HOOKS), { recursive: true });
1564
+ fs.writeFileSync(CODEX_HOOKS, JSON.stringify(next, null, 2) + "\n");
1565
+ if (flags.remove) console.log(C.green("✓ codex: seldon's hooks removed") + C.dim(" (yours kept)"));
1566
+ else {
1567
+ console.log(C.green("✓ codex: hooks added to ~/.codex/hooks.json") + C.dim(" (any of yours kept)"));
1568
+ console.log(" " + C.gold("one step left:") + " Codex runs a hook only after you trust it. Open " + C.cyan("codex") + ", run " + C.cyan("/hooks") + ", trust the seldon ones.");
1569
+ }
1570
+ } else if (h === "opencode") {
1571
+ if (flags.remove) { fs.rmSync(OPENCODE_PLUGIN, { force: true }); console.log(C.green("✓ opencode: plugin removed")); continue; }
1572
+ fs.mkdirSync(path.dirname(OPENCODE_PLUGIN), { recursive: true });
1573
+ fs.writeFileSync(OPENCODE_PLUGIN, opencodePlugin(bin));
1574
+ console.log(C.green("✓ opencode: plugin installed") + C.dim(" (~/.config/opencode/plugins/seldon.js — new opencode sessions report their state)"));
1575
+ } else { console.log(C.red(`unknown harness: ${h}`) + C.dim(" (codex or opencode)")); process.exitCode = 1; }
1576
+ }
1577
+ }
1578
+
1579
+ // ---- holds: turn-taking on shared machine resources ---------------------------
1580
+ // `seldon hold emulator` before using it, `seldon release emulator` after. If another agent
1581
+ // holds it, `hold` waits its turn (default 90s — under an agent's tool timeout) and then
1582
+ // exits 2 saying who has it, so the agent can do something else and come back.
1583
+ // `seldon hold emulator -- <command>` holds, runs, releases.
1584
+ function holder(flags) {
1585
+ const root = projectRoot(process.cwd());
1586
+ let branch = "";
1587
+ try { branch = execSync("git branch --show-current", { stdio: ["ignore", "pipe", "ignore"] }).toString().trim(); } catch { /* not a repo */ }
1588
+ const who = flags.as || [root ? path.basename(root) : path.basename(process.cwd()), branch].filter(Boolean).join("/");
1589
+ return { who, pid: findOwner(), cwd: process.cwd(), note: typeof flags.note === "string" ? flags.note : undefined };
1590
+ }
1591
+
1592
+ async function holdCmd(name, flags, command) {
1593
+ if (!name || !NAME_RE.test(name)) { console.log(C.red("usage: seldon hold <resource> [--for 30m] [--wait 90s] [-- command]") + C.dim(" resource: lowercase, e.g. emulator, unreal, gpu")); process.exitCode = 1; return; }
1594
+ const forMs = parseDuration(flags.for, DEFAULT_FOR_MS);
1595
+ const waitMs = parseDuration(flags.wait, 90_000);
1596
+ if (forMs === null || waitMs === null) { console.log(C.red("--for / --wait take a duration: 90s, 30m, 2h")); process.exitCode = 1; return; }
1597
+ const me = { ...holder(flags), forMs };
1598
+ const deadline = Date.now() + waitMs;
1599
+ let said = "";
1600
+ for (;;) {
1601
+ const r = tryHold(name, me);
1602
+ if (r.take) {
1603
+ console.log(C.green(`✓ ${name} is yours`) + C.dim(` (${me.who}, ${Math.round(forMs / 60_000)}m — release with: seldon release ${name})`));
1604
+ break;
1605
+ }
1606
+ const line = `${name} is held by ${describeHold(r.wait, Date.now())}`;
1607
+ if (Date.now() >= deadline) {
1608
+ console.log(C.gold(`… ${line}`) + C.dim(` — try again later, or wait longer: seldon hold ${name} --wait 10m`));
1609
+ process.exitCode = 2;
1610
+ return;
1611
+ }
1612
+ if (line.split(" · ")[0] !== said) { console.log(C.dim(`… ${line} — waiting your turn`)); said = line.split(" · ")[0]; }
1613
+ await new Promise((res) => setTimeout(res, 2000));
1614
+ }
1615
+ if (!command.length) return;
1616
+ const r = spawnSync(command[0], command.slice(1), { stdio: "inherit" });
1617
+ releaseHold(name, me);
1618
+ process.exitCode = r.status ?? 1;
1619
+ }
1620
+
1621
+ function releaseCmd(name, flags) {
1622
+ if (!name) { console.log(C.red("usage: seldon release <resource> [--force]")); process.exitCode = 1; return; }
1623
+ const r = releaseHold(name, holder(flags), !!flags.force);
1624
+ if (r.ok) console.log(C.green(`✓ released ${name}`) + (r.gone ? C.dim(" (it was not held)") : ""));
1625
+ else { console.log(C.gold(`${name} is held by ${describeHold(r.held, Date.now())} — not yours to release`) + C.dim(" (--force if it is truly stuck)")); process.exitCode = 1; }
1626
+ }
1627
+
1628
+ function holdsCmd() {
1629
+ const hs = listHolds();
1630
+ if (!hs.length) { console.log(C.dim("nothing is held")); return; }
1631
+ for (const h of hs) console.log(` ${C.bold(h.resource.padEnd(14))} ${describeHold(h, Date.now())}${h.note ? C.dim(" " + h.note) : ""}`);
1632
+ }
1633
+
1634
+ // ---- argv -------------------------------------------------------------------
1635
+ // A flag either carries a value (`--agent claude`, `--agent=claude`) or stands alone
1636
+ // (`--no-attach`). The value form has to be CONSUMED: filtering out everything starting with
1637
+ // `--` and keeping the rest as positionals read `seldon go --agent claude` as the project
1638
+ // named "claude".
1639
+ const VALUE_FLAGS = new Set(["agent", "model", "effort", "name", "port", "pm", "stall", "dir", "for", "wait", "as", "note", "interval", "task"]);
1640
+ function parseArgv(raw) {
1641
+ const flags = {}, positional = [];
1642
+ for (let i = 0; i < raw.length; i++) {
1643
+ const a = raw[i];
1644
+ if (!a.startsWith("--")) { positional.push(a); continue; }
1645
+ const body = a.slice(2);
1646
+ const eq = body.indexOf("=");
1647
+ if (eq !== -1) { flags[body.slice(0, eq)] = body.slice(eq + 1); continue; }
1648
+ if (VALUE_FLAGS.has(body) && raw[i + 1] && !raw[i + 1].startsWith("-")) { flags[body] = raw[++i]; continue; }
1649
+ flags[body] = true;
1650
+ }
1651
+ return { flags, positional };
1652
+ }
1653
+
1654
+ const rawArgv = process.argv.slice(2);
1655
+ // Everything after a bare `--` is a command to run (`seldon hold emulator -- ./gradlew test`),
1656
+ // never seldon's own flags.
1657
+ const dd = rawArgv.indexOf("--");
1658
+ const argv = dd === -1 ? rawArgv : rawArgv.slice(0, dd);
1659
+ const passthru = dd === -1 ? [] : rawArgv.slice(dd + 1);
1660
+ const { flags, positional: args } = parseArgv(argv);
1661
+ const dev = !!flags.dev;
980
1662
  const cmd = args[0];
981
1663
  const tokens = args.slice(1); // raw names after the command
982
1664
  const ids = tokens.filter((id) => byId[id]); // only the valid module ids
@@ -999,11 +1681,41 @@ const ids = tokens.filter((id) => byId[id]); // only the valid module
999
1681
  if (cmd === "down") return down();
1000
1682
  if (cmd === "status") return statusCmd();
1001
1683
  if (cmd === "adopt") return adopt(tokens[0]);
1684
+ if (cmd === "go") return go(tokens[0], flags);
1685
+ if (cmd === "hold") return holdCmd(tokens[0], flags, passthru);
1686
+ if (cmd === "release") return releaseCmd(tokens[0], flags);
1687
+ if (cmd === "holds") return holdsCmd();
1688
+ if (cmd === "watch") return watchCmd(flags);
1689
+ if (cmd === "report") return reportCmd(tokens[0]);
1690
+ if (cmd === "lanes") return lanesCmd(flags);
1691
+ if (cmd === "machines") return machinesCmd(tokens[0], tokens[1], tokens[2]);
1692
+ if (cmd === "lane") return laneCmd(tokens[0], tokens[1], flags);
1693
+ if (cmd === "setup") return setupCmd(tokens[0], flags);
1694
+ if (cmd === "panel" || cmd === "board") return panel();
1002
1695
  if (cmd && cmd !== "install") { help(); process.exitCode = 1; return; }
1003
- // interactive
1004
- if (!process.stdin.isTTY) { console.log(C.red("no TTY — use: seldon install <ids…>")); process.exitCode = 1; return; }
1005
- const picked = await tui();
1006
- if (!picked) { console.log(C.dim("nothing installed.")); return; }
1007
- if (!picked.length) { console.log(C.dim("nothing selected.")); return; }
1008
- await doInstall(picked, { dev });
1696
+ if (cmd === "install") return install_picker({ dev }); // `install` with no ids
1697
+
1698
+ // ---- bare `seldon` ----------------------------------------------------------
1699
+ // Always the panel. It needs nothing else installed — it reads Claude, Codex and opencode
1700
+ // directly — so a fresh machine is not sent to a checklist first; that made the add-ons look
1701
+ // required. `seldon install` is the checklist.
1702
+ if (!process.stdin.isTTY) {
1703
+ // No terminal to draw on (a script, a hook, an agent's shell) — answer the same question
1704
+ // in text: every agent and every project, the same rows the panel draws.
1705
+ ensureSiblingPath();
1706
+ const groups = readLanes();
1707
+ const st = has("factory") ? loadState() : null;
1708
+ const rows = buildRows(groups, st?.hives || [], sameDir);
1709
+ console.log(headline(groups));
1710
+ for (const r of rows) {
1711
+ if (r.type === "project") {
1712
+ const others = unlistedAgents(r.project);
1713
+ console.log(`${r.project.name}${r.project.hive ? ` (plan ${r.project.hive.queueOpen})` : ""}${others.length ? ` agents: ${others.join(", ")}` : ""}${r.project.hive?.why ? ` needs you: ${r.project.hive.why}` : ""}`);
1714
+ }
1715
+ else console.log(` ${GLYPH[r.lane.state] || "?"} ${(r.lane.name || r.lane.id || "?").padEnd(26)} ${r.lane.harness.padEnd(9)} ${laneDetail(r.lane)}`);
1716
+ }
1717
+ console.log(C.dim("\n in a terminal, `seldon` is the live panel · continue one: ") + C.cyan("seldon go <name>"));
1718
+ return;
1719
+ }
1720
+ return panel();
1009
1721
  })();