@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.
@@ -0,0 +1,56 @@
1
+ // What you can do to a lane, in one place: start, stop, resume. The panel calls these, and so
2
+ // does `seldon lane …` — which is also how the panel acts on another machine (it runs
3
+ // `ssh <machine> seldon lane …`). One implementation, so the two can never disagree.
4
+ import { join } from "node:path";
5
+ import { existsSync } from "node:fs";
6
+ import { execFileSync } from "node:child_process";
7
+ import {
8
+ readLanes, runSteps, run, harnessBins, recordLane, markLane, SELDON_HOME,
9
+ } from "./agents.mjs";
10
+ import { startCommands, resumeCommands, stopCommand, slugify, uniqueSlug, HARNESSES } from "./lanes.mjs";
11
+
12
+ const branchExists = (root, ref) => {
13
+ try { execFileSync("git", ["-C", root, "rev-parse", "--verify", "--quiet", `refs/heads/${ref}`], { stdio: "ignore" }); return true; } catch { return false; }
14
+ };
15
+
16
+ export function startLane({ root, name, task, harness = "claude" }) {
17
+ if (!HARNESSES.includes(harness)) return { ok: false, error: `unknown agent "${harness}" (${HARNESSES.join(", ")})` };
18
+ if (!task || !String(task).trim()) return { ok: false, error: "a lane needs a task" };
19
+ const bins = harnessBins();
20
+ if (!bins[harness]) return { ok: false, slug: slugify(task), error: `${harness} is not installed (not on PATH)` };
21
+ const worktreesDir = join(SELDON_HOME, "worktrees", name || root.split("/").pop());
22
+ const names = new Set(allLanes().map((l) => l.name));
23
+ const slug = uniqueSlug(slugify(task), (s) => names.has(s) || existsSync(join(worktreesDir, s)) || existsSync(join(root, ".claude", "worktrees", s)) || branchExists(root, `lane/${s}`));
24
+ const cmds = startCommands({ harness, task, root, slug, worktreesDir, bins, env: { PATH: process.env.PATH } });
25
+ const r = runSteps(cmds);
26
+ const tmux = cmds.find((c) => c.session);
27
+ if (r.ok && tmux) recordLane({ session: tmux.session, harness, task, slug, root, worktree: tmux.cwd, startedAt: Date.now() });
28
+ return { ...r, slug };
29
+ }
30
+
31
+ export function stopLane(lane) {
32
+ const how = stopCommand(lane);
33
+ if (how.why) return { ok: false, why: how.why };
34
+ const r = run(how, { quiet: true });
35
+ // Stopped on purpose: not offered for resume after a reboot.
36
+ if (r.ok && lane.tmuxSession) markLane(lane.tmuxSession, { stoppedAt: Date.now() });
37
+ return r;
38
+ }
39
+
40
+ export function resumeLane(lane) {
41
+ const how = resumeCommands(lane, { bins: harnessBins(), env: { PATH: process.env.PATH } });
42
+ if (how.why) return { ok: false, why: how.why };
43
+ const r = runSteps(how.cmds);
44
+ if (r.ok && lane.tmuxSession) markLane(lane.tmuxSession, { stoppedAt: undefined, startedAt: Date.now() });
45
+ return { ...r, fresh: !!how.fresh };
46
+ }
47
+
48
+ export const allLanes = () => readLanes().flatMap((g) => g.lanes);
49
+ // By key, or by name when exactly one lane has it (keys are long; names are what you see).
50
+ export function findLane(ref) {
51
+ const lanes = allLanes();
52
+ const byKey = lanes.find((l) => l.key === ref);
53
+ if (byKey) return byKey;
54
+ const named = lanes.filter((l) => l.name === ref);
55
+ return named.length === 1 ? named[0] : null;
56
+ }
package/lib/agents.mjs ADDED
@@ -0,0 +1,167 @@
1
+ // The I/O half of lanes.mjs: run the harness commands, resolve projects, hand back lanes.
2
+ // Every source is best-effort — a missing `claude` or no tmux server is an empty list, not
3
+ // an error, because a machine running only Codex (or nothing yet) is a normal machine.
4
+ import { execFileSync, spawnSync } from "node:child_process";
5
+ import { readFileSync, writeFileSync, renameSync, mkdirSync, readdirSync, rmSync, statSync } from "node:fs";
6
+ import { applyReports } from "./reports.mjs";
7
+ import { sameDir } from "./projects.mjs";
8
+ import { join } from "node:path";
9
+ import { homedir } from "node:os";
10
+ import {
11
+ claudeLanes, parseTmuxPanes, tmuxLanes, tmuxSessionFor, groupByProject,
12
+ projectRootFromCommonDir, registryLanes, TMUX_PANE_FORMAT,
13
+ } from "./lanes.mjs";
14
+
15
+ export const SELDON_HOME = process.env.SELDON_HOME || join(homedir(), ".seldon");
16
+ const LANES_FILE = join(SELDON_HOME, "lanes.json");
17
+ const STATE_DIR = join(SELDON_HOME, "state");
18
+
19
+ const out = (bin, args, timeout = 5000) => {
20
+ try { return execFileSync(bin, args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout }); }
21
+ catch { return null; }
22
+ };
23
+
24
+ export function readClaude() {
25
+ const raw = out("claude", ["agents", "--json", "--all"]);
26
+ try { return raw ? JSON.parse(raw) : []; } catch { return []; }
27
+ }
28
+
29
+ export const readTmuxPanes = () => parseTmuxPanes(out("tmux", ["list-panes", "-a", "-F", TMUX_PANE_FORMAT]) || "");
30
+
31
+ // A process's parent never changes, so `ps` is asked once per pid, not once per refresh.
32
+ const parents = new Map();
33
+ const parentOf = (pid) => {
34
+ if (!parents.has(pid)) parents.set(pid, Number(out("ps", ["-o", "ppid=", "-p", String(pid)])?.trim()) || null);
35
+ return parents.get(pid);
36
+ };
37
+
38
+ // cwd -> project root. A lane's cwd does not move between refreshes, so ask git once.
39
+ const rootCache = new Map();
40
+ export function projectRoot(cwd) {
41
+ if (!cwd) return null;
42
+ if (!rootCache.has(cwd)) {
43
+ const common = out("git", ["-C", cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"])?.trim();
44
+ rootCache.set(cwd, projectRootFromCommonDir(common));
45
+ }
46
+ return rootCache.get(cwd);
47
+ }
48
+
49
+ // ---- what seldon started -----------------------------------------------------
50
+ // One record per lane seldon starts in tmux: which harness, which task, where. It is how a
51
+ // lane is recognised whatever its pane happens to run, and (later) how it is resumed.
52
+ const readJson = (p, fallback) => { try { return JSON.parse(readFileSync(p, "utf8")); } catch { return fallback; } };
53
+
54
+ const writeLanes = (all) => {
55
+ mkdirSync(SELDON_HOME, { recursive: true });
56
+ const tmp = `${LANES_FILE}.${process.pid}.tmp`;
57
+ writeFileSync(tmp, JSON.stringify(all, null, 2));
58
+ renameSync(tmp, LANES_FILE);
59
+ };
60
+
61
+ export function recordLane(entry) {
62
+ writeLanes([...readJson(LANES_FILE, []).filter((e) => e.session !== entry.session), entry]);
63
+ }
64
+
65
+ // Stopped on purpose (x x): not offered for resume after a reboot. Resuming clears it.
66
+ export function markLane(session, patch) {
67
+ writeLanes(readJson(LANES_FILE, []).map((e) => (e.session === session ? { ...e, ...patch } : e)));
68
+ }
69
+
70
+ // tmux session -> { harness, task, startedAt }: seldon's lanes plus apiary's Codex agents.
71
+ export function knownSessions() {
72
+ const known = {};
73
+ for (const e of readJson(LANES_FILE, [])) if (e.session) known[e.session] = e;
74
+ const dir = join(homedir(), ".apiary", "sessions");
75
+ let files = [];
76
+ try { files = readdirSync(dir); } catch { /* no apiary */ }
77
+ for (const f of files.filter((f) => f.startsWith("codex_") && f.endsWith(".json"))) {
78
+ const s = readJson(join(dir, f), null);
79
+ if (s?.tmuxSession) known[s.tmuxSession] = { harness: "codex" };
80
+ }
81
+ return known;
82
+ }
83
+
84
+ // All lanes, grouped by project, most urgent first. Claude lanes that live in a tmux pane
85
+ // (apiary's agents, or a claude you started inside tmux) learn which session, so ⏎ can open it.
86
+ export function readLanes() {
87
+ const panes = readTmuxPanes();
88
+ const claude = claudeLanes(readClaude()).map((l) =>
89
+ l.id || !l.pid || !panes.length ? l : { ...l, tmuxSession: tmuxSessionFor(l.pid, panes, parentOf) });
90
+ const stopped = registryLanes(readJson(LANES_FILE, []), panes.map((p) => p.session));
91
+ const tmux = applyReports(tmuxLanes(panes, knownSessions()), readReports(), sameDir);
92
+ return groupByProject([...claude, ...tmux, ...stopped], projectRoot);
93
+ }
94
+
95
+ // The project's open plan, via foundation (the one parser of QUEUE.md). null = no foundation
96
+ // or no plan here; [] = an empty plan.
97
+ export function readPlan(root) {
98
+ const raw = out("foundation", ["queue", "--list", "--json", "--dir", root]);
99
+ try { return raw ? JSON.parse(raw) : null; } catch { return null; }
100
+ }
101
+
102
+ export function addToPlan(root, text, priority = "P2") {
103
+ return run({ bin: "foundation", args: ["queue", `(${priority}) ${text}`, "--dir", root] }, { quiet: true });
104
+ }
105
+
106
+ // Run a command with the terminal attached (a trust dialog may need answering), and say how
107
+ // it went. Steps run in order and stop at the first failure.
108
+ // `quiet` captures the output instead (for a command that would print over the panel), and
109
+ // its last line becomes the error.
110
+ export function run(cmd, { quiet = false } = {}) {
111
+ const r = spawnSync(cmd.bin, cmd.args, { stdio: quiet ? ["ignore", "pipe", "pipe"] : "inherit", cwd: cmd.cwd, encoding: "utf8" });
112
+ const said = quiet ? `${r.stderr || ""}${r.stdout || ""}`.trim().split("\n").pop() : "";
113
+ return { ok: r.status === 0, error: r.error ? r.error.message : r.status !== 0 ? (said || `${cmd.bin} exited ${r.status}`) : null };
114
+ }
115
+ export function runSteps(cmds) {
116
+ for (const c of cmds) {
117
+ const r = run(c, { quiet: !!c.quiet });
118
+ if (!r.ok) return r;
119
+ // A tmux session that is gone a moment later means the agent exited at once (bad flag,
120
+ // no login, not installed). Say so — "started" for something that is not running is the
121
+ // one answer worse than an error.
122
+ if (c.session) {
123
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1500);
124
+ if (out("tmux", ["has-session", "-t", c.session]) === null)
125
+ return { ok: false, error: `the agent exited right after starting — run it by hand to see why: cd ${c.cwd} && ${c.agent.join(" ")}` };
126
+ }
127
+ }
128
+ return { ok: true };
129
+ }
130
+
131
+ // Absolute paths of the agent CLIs, resolved with seldon's own PATH.
132
+ export function harnessBins() {
133
+ const bins = {};
134
+ for (const h of ["claude", "codex", "opencode"]) {
135
+ const p = out("sh", ["-c", `command -v ${h}`])?.trim();
136
+ if (p) bins[h] = p;
137
+ }
138
+ return bins;
139
+ }
140
+
141
+ // ---- harness reports (see reports.mjs) -------------------------------------------
142
+ const reportFile = (r) => join(STATE_DIR, `${r.harness}-${String(r.session).replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
143
+
144
+ export function writeReport(r) {
145
+ if (!r) return;
146
+ if (r.ended) { rmSync(reportFile(r), { force: true }); return; }
147
+ mkdirSync(STATE_DIR, { recursive: true });
148
+ const f = reportFile(r), tmp = `${f}.${process.pid}.tmp`;
149
+ writeFileSync(tmp, JSON.stringify(r));
150
+ renameSync(tmp, f);
151
+ }
152
+
153
+ // Every report, newest state per session. Files untouched for 3 days are sessions that died
154
+ // without saying so; they are cleared as they are read.
155
+ export function readReports(now = Date.now()) {
156
+ let files = [];
157
+ try { files = readdirSync(STATE_DIR).filter((f) => f.endsWith(".json")); } catch { return []; }
158
+ const out = [];
159
+ for (const f of files) {
160
+ const p = join(STATE_DIR, f);
161
+ try {
162
+ if (now - statSync(p).mtimeMs > 3 * 86_400_000) { rmSync(p, { force: true }); continue; }
163
+ out.push(JSON.parse(readFileSync(p, "utf8")));
164
+ } catch { /* half-written or gone */ }
165
+ }
166
+ return out;
167
+ }
@@ -0,0 +1,65 @@
1
+ // The files behind holds.mjs: ~/.seldon/holds/<resource>.json, one per held resource.
2
+ //
3
+ // Every read-decide-write runs inside a mutex (an atomic `mkdir`), so two agents asking at
4
+ // the same instant can never both win. A mutex left behind by a process that died inside the
5
+ // critical section — milliseconds long — is cleared after 10s.
6
+ import { mkdirSync, rmdirSync, readFileSync, writeFileSync, renameSync, rmSync, readdirSync, statSync } from "node:fs";
7
+ import { execFileSync } from "node:child_process";
8
+ import { join } from "node:path";
9
+ import { homedir } from "node:os";
10
+ import { decide, mayRelease, isLive, ownerPid } from "./holds.mjs";
11
+
12
+ const HOME = process.env.SELDON_HOME || join(homedir(), ".seldon");
13
+ export const HOLDS_DIR = join(HOME, "holds");
14
+
15
+ export const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === "EPERM"; } };
16
+ const ps = (field, pid) => { try { return execFileSync("ps", ["-o", `${field}=`, "-p", String(pid)], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); } catch { return ""; } };
17
+ export const findOwner = () => ownerPid(process.ppid, (p) => Number(ps("ppid", p)) || null, (p) => ps("comm", p));
18
+
19
+ const file = (name) => join(HOLDS_DIR, `${name}.json`);
20
+ const read = (name) => { try { return JSON.parse(readFileSync(file(name), "utf8")); } catch { return null; } };
21
+
22
+ function withMutex(name, fn) {
23
+ mkdirSync(HOLDS_DIR, { recursive: true });
24
+ const m = join(HOLDS_DIR, `${name}.mutex`);
25
+ for (let i = 0; ; i++) {
26
+ try { mkdirSync(m); break; }
27
+ catch (e) {
28
+ if (e.code !== "EEXIST") throw e;
29
+ try { if (Date.now() - statSync(m).mtimeMs > 10_000) rmdirSync(m); } catch { /* raced */ }
30
+ if (i > 500) throw new Error(`hold ${name}: could not get the lock file`);
31
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
32
+ }
33
+ }
34
+ try { return fn(); } finally { try { rmdirSync(m); } catch { /* already gone */ } }
35
+ }
36
+
37
+ const write = (name, hold) => {
38
+ const tmp = `${file(name)}.${process.pid}.tmp`;
39
+ writeFileSync(tmp, JSON.stringify(hold, null, 2));
40
+ renameSync(tmp, file(name));
41
+ };
42
+
43
+ // One attempt. { take } = it is ours now; { wait } = someone else has it.
44
+ export function tryHold(name, me, now = Date.now()) {
45
+ return withMutex(name, () => {
46
+ const r = decide(read(name), me, now, alive);
47
+ if (r.take) write(name, { resource: name, ...r.take });
48
+ return r;
49
+ });
50
+ }
51
+
52
+ export function release(name, me, force = false, now = Date.now()) {
53
+ return withMutex(name, () => {
54
+ const r = mayRelease(read(name), me, now, alive, force);
55
+ if (r.ok && !r.gone) rmSync(file(name), { force: true });
56
+ return r;
57
+ });
58
+ }
59
+
60
+ // Every hold in force right now (dead ones are left for the next taker to clear).
61
+ export function listHolds(now = Date.now()) {
62
+ let names = [];
63
+ try { names = readdirSync(HOLDS_DIR).filter((f) => f.endsWith(".json")).map((f) => f.slice(0, -5)); } catch { return []; }
64
+ return names.map(read).filter((h) => isLive(h, now, alive));
65
+ }
package/lib/holds.mjs ADDED
@@ -0,0 +1,68 @@
1
+ // Holds: turn-taking on things one machine has only one of.
2
+ //
3
+ // Agents on different projects share the machine: one boots the Android emulator, another
4
+ // opens Unreal, a third runs the GPU benchmark, and they trip over each other. Rooms do not
5
+ // help — they are per project, and agents on different repos never meet. A hold is the
6
+ // smallest thing that does: before using a shared resource an agent runs `seldon hold
7
+ // emulator`; if someone else holds it, the command waits its turn; `seldon release emulator`
8
+ // when done.
9
+ //
10
+ // A hold can never wedge the machine: it expires when its time is up, or as soon as the agent
11
+ // that took it has exited. This file is the rules, pure; holds-store.mjs does the files.
12
+
13
+ export const DEFAULT_FOR_MS = 30 * 60_000; // a hold lasts 30 min unless renewed
14
+ export const NAME_RE = /^[a-z0-9][a-z0-9._-]{0,39}$/;
15
+
16
+ export function parseDuration(s, fallback) {
17
+ if (s === undefined || s === true) return fallback;
18
+ const m = String(s).match(/^(\d+)(s|m|h)?$/);
19
+ if (!m) return null;
20
+ return Number(m[1]) * ({ s: 1000, m: 60_000, h: 3_600_000 }[m[2] || "m"]);
21
+ }
22
+
23
+ // Is this hold still in force? `alive(pid)` is injected.
24
+ export function isLive(hold, now, alive) {
25
+ if (!hold) return false;
26
+ if (hold.until <= now) return false;
27
+ if (hold.pid && !alive(hold.pid)) return false;
28
+ return true;
29
+ }
30
+
31
+ const sameHolder = (a, b) => (a.pid && b.pid ? a.pid === b.pid : a.who === b.who);
32
+
33
+ // What happens when `me` asks for a resource currently `held` (or null).
34
+ // { take: hold } it is free, expired, abandoned, or already mine (renewed)
35
+ // { wait: held } someone else has it
36
+ export function decide(held, me, now, alive) {
37
+ if (!isLive(held, now, alive) || sameHolder(held, me)) {
38
+ return { take: { ...me, since: held && sameHolder(held, me) && isLive(held, now, alive) ? held.since : now, until: now + me.forMs } };
39
+ }
40
+ return { wait: held };
41
+ }
42
+
43
+ // May `me` release `held`? Only its holder, unless forced; a dead hold is anyone's to clear.
44
+ export function mayRelease(held, me, now, alive, force = false) {
45
+ if (!held) return { ok: true, gone: true };
46
+ if (force || !isLive(held, now, alive) || sameHolder(held, me)) return { ok: true };
47
+ return { ok: false, held };
48
+ }
49
+
50
+ // The agent a `seldon hold` belongs to: the nearest ancestor that is an agent CLI. `seldon`
51
+ // itself exits right after taking the hold, so its own pid would make every hold look
52
+ // abandoned. Falls back to null (the hold then lives by its timer alone).
53
+ const AGENTS = new Set(["claude", "codex", "opencode"]);
54
+ export function ownerPid(startPid, parentOf, nameOf, maxDepth = 8) {
55
+ let pid = startPid;
56
+ for (let i = 0; pid && pid > 1 && i < maxDepth; i++) {
57
+ const name = (nameOf(pid) || "").split("/").pop();
58
+ if (AGENTS.has(name)) return pid;
59
+ pid = parentOf(pid);
60
+ }
61
+ return null;
62
+ }
63
+
64
+ export function describe(hold, now) {
65
+ const mins = Math.max(0, Math.round((now - hold.since) / 60_000));
66
+ const left = Math.max(0, Math.round((hold.until - now) / 60_000));
67
+ return `${hold.who} · ${mins}m · ${left}m left`;
68
+ }
package/lib/home.mjs ADDED
@@ -0,0 +1,64 @@
1
+ // The home screen as data: projects, each with its lanes, most urgent first. Pure — the
2
+ // panel in bin/seldon.js only draws these rows and maps keys to them.
3
+ //
4
+ // A project shows up if it has a running lane OR is registered with factory (it has a plan
5
+ // even when nobody is working on it). The two sources are matched by directory.
6
+ import { countByState } from "./lanes.mjs";
7
+
8
+ const URGENT = ["needs-you", "working", "running"];
9
+
10
+ // `here` is the repo seldon was opened in: always listed, first among the quiet ones, so a
11
+ // fresh repo with no agents yet can still get its first lane.
12
+ export function buildRows(groups, hives = [], sameDir = (a, b) => a === b, here = null) {
13
+ const projects = groups.map((g) => ({ ...g, hive: hives.find((h) => sameDir(h.dir, g.root)) || null }));
14
+ for (const h of hives) {
15
+ if (!projects.some((p) => sameDir(p.root, h.dir))) projects.push({ root: h.dir, name: h.name, lanes: [], hive: h });
16
+ }
17
+ if (here && !projects.some((p) => sameDir(p.root, here))) projects.push({ root: here, name: here.split("/").pop() || here, lanes: [], hive: null });
18
+ // Active projects keep the urgency order groupByProject gave them; idle registered ones follow.
19
+ const active = projects.filter((p) => p.lanes.some((l) => URGENT.includes(l.state)));
20
+ const isHere = (p) => !!here && sameDir(p.root, here);
21
+ const rest = projects.filter((p) => !active.includes(p)).sort((a, b) => isHere(b) - isHere(a) || a.name.localeCompare(b.name));
22
+ const rows = [];
23
+ for (const p of [...active, ...rest]) {
24
+ rows.push({ type: "project", project: p });
25
+ for (const lane of p.lanes) rows.push({ type: "lane", lane, project: p });
26
+ }
27
+ return rows;
28
+ }
29
+
30
+ export function headline(groups) {
31
+ const c = countByState(groups.flatMap((g) => g.lanes));
32
+ const parts = [];
33
+ if (c["needs-you"]) parts.push(`${c["needs-you"]} need you`);
34
+ const busy = c.working + c.running;
35
+ if (busy) parts.push(`${busy} working`);
36
+ if (c.idle) parts.push(`${c.idle} idle`);
37
+ if (c.failed) parts.push(`${c.failed} failed`);
38
+ return parts.join(" · ") || "no agents running";
39
+ }
40
+
41
+ export function ago(ms, now = Date.now()) {
42
+ if (!ms) return "";
43
+ const s = Math.max(0, Math.round((now - ms) / 1000));
44
+ if (s < 60) return `${s}s`;
45
+ if (s < 3600) return `${Math.floor(s / 60)}m`;
46
+ if (s < 86400) return `${Math.floor(s / 3600)}h`;
47
+ return `${Math.floor(s / 86400)}d`;
48
+ }
49
+
50
+ // The words after a lane's name: what it is doing, as far as its harness says.
51
+ export function laneDetail(lane) {
52
+ if (lane.state === "needs-you") return `needs you: ${lane.waitingFor || "input"}`;
53
+ if (lane.state === "running") return "running (no state reported)";
54
+ return lane.state;
55
+ }
56
+
57
+ // Agents factory knows about that no lane accounts for — e.g. one on another machine, which
58
+ // `claude agents` here cannot see. An apiary agent named X runs in tmux session apiary_X.
59
+ export function unlistedAgents(project) {
60
+ const names = project.hive?.agents || [];
61
+ return names.filter((n) => !project.lanes.some((l) => l.tmuxSession === `apiary_${n}` || l.name === n));
62
+ }
63
+
64
+ export const GLYPH = { "needs-you": "⚑", working: "●", running: "●", idle: "○", failed: "✗", stopped: "·" };