@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/README.md +191 -4
- package/bin/seldon.js +769 -57
- package/lib/actions.mjs +56 -0
- package/lib/agents.mjs +167 -0
- package/lib/holds-store.mjs +65 -0
- package/lib/holds.mjs +68 -0
- package/lib/home.mjs +64 -0
- package/lib/lanes.mjs +250 -0
- package/lib/machines.mjs +82 -0
- package/lib/notify.mjs +10 -0
- package/lib/projects.mjs +114 -0
- package/lib/reports.mjs +116 -0
- package/modules.mjs +6 -6
- package/package.json +2 -1
package/lib/lanes.mjs
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
// Lanes: every coding agent running on this machine, whatever harness it is, in one shape.
|
|
2
|
+
//
|
|
3
|
+
// A lane is one agent on one task. seldon does not launch or own them here — it reads them:
|
|
4
|
+
// - Claude Code reports its own sessions: `claude agents --json --all` is the documented,
|
|
5
|
+
// supported interface (https://code.claude.com/docs/en/agent-view). It covers interactive
|
|
6
|
+
// sessions (including the ones apiary runs in tmux) and background ones.
|
|
7
|
+
// - Codex and opencode have no equivalent list, so for now they are found as tmux panes
|
|
8
|
+
// running that CLI. Their state is "running" until a harness adapter reports more.
|
|
9
|
+
//
|
|
10
|
+
// Everything in this file is pure: the callers do the I/O (run the commands, read git) and
|
|
11
|
+
// pass the results in, so the mapping rules are testable with fixtures and no agents running.
|
|
12
|
+
|
|
13
|
+
// ---- the one shape -----------------------------------------------------------
|
|
14
|
+
// state is what a human needs to know, ordered by urgency:
|
|
15
|
+
// needs-you the agent is waiting on a person (question, permission, login, dialog)
|
|
16
|
+
// working it is getting on with it
|
|
17
|
+
// running alive, but its harness does not say more (Codex/opencode via tmux, for now)
|
|
18
|
+
// idle finished its turn, ready for the next prompt
|
|
19
|
+
// failed ended with an error
|
|
20
|
+
// stopped stopped by someone, or ended at shutdown
|
|
21
|
+
export const STATES = ["needs-you", "working", "running", "idle", "failed", "stopped"];
|
|
22
|
+
const RANK = Object.fromEntries(STATES.map((s, i) => [s, i]));
|
|
23
|
+
|
|
24
|
+
// ---- Claude Code ---------------------------------------------------------------
|
|
25
|
+
// Background sessions carry `state`; every live process carries `status` (+ `waitingFor`).
|
|
26
|
+
// `state` is the authority when present — `status` only says whether the process is busy
|
|
27
|
+
// this instant, and a background session between loop iterations is "working" while idle.
|
|
28
|
+
const CLAUDE_STATE = { working: "working", blocked: "needs-you", done: "idle", failed: "failed", stopped: "stopped" };
|
|
29
|
+
const CLAUDE_STATUS = { busy: "working", waiting: "needs-you", idle: "idle" };
|
|
30
|
+
|
|
31
|
+
export function claudeLanes(entries) {
|
|
32
|
+
if (!Array.isArray(entries)) return [];
|
|
33
|
+
return entries.filter((e) => e && typeof e.cwd === "string").map((e) => {
|
|
34
|
+
const state = CLAUDE_STATE[e.state] ?? CLAUDE_STATUS[e.status] ?? (e.pid ? "running" : "stopped");
|
|
35
|
+
return {
|
|
36
|
+
harness: "claude",
|
|
37
|
+
key: `claude:${e.id ?? e.sessionId ?? e.pid}`,
|
|
38
|
+
id: e.id ?? null, // background sessions: usable with `claude attach`
|
|
39
|
+
sessionId: e.sessionId ?? null, // usable with `claude --resume`
|
|
40
|
+
pid: e.pid ?? null,
|
|
41
|
+
name: e.name ?? null,
|
|
42
|
+
cwd: e.cwd,
|
|
43
|
+
kind: e.kind ?? null,
|
|
44
|
+
startedAt: e.startedAt ?? null,
|
|
45
|
+
state,
|
|
46
|
+
waitingFor: state === "needs-you" ? (e.waitingFor ?? "you") : null,
|
|
47
|
+
};
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// ---- tmux (Codex, opencode) ------------------------------------------------------
|
|
52
|
+
// `tmux list-panes -a -F '#{session_name}|#{pane_pid}|#{pane_current_command}|#{pane_current_path}'`
|
|
53
|
+
// Claude panes are skipped: Claude reports itself, and listing it twice would double-count.
|
|
54
|
+
export const TMUX_PANE_FORMAT = "#{session_name}|#{pane_pid}|#{pane_current_command}|#{pane_current_path}";
|
|
55
|
+
const TMUX_HARNESSES = new Set(["codex", "opencode"]);
|
|
56
|
+
|
|
57
|
+
export function parseTmuxPanes(text) {
|
|
58
|
+
return String(text || "").split("\n").filter(Boolean).map((line) => {
|
|
59
|
+
const [session, pid, command, cwd] = line.split("|");
|
|
60
|
+
return { session, panePid: Number(pid) || null, command: command || "", cwd: cwd || "" };
|
|
61
|
+
}).filter((p) => p.session);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// `known` maps a tmux session to what started it ({ harness, task, startedAt }) — seldon's own
|
|
65
|
+
// lanes registry and apiary's session files. That is the reliable signal: a pane's command
|
|
66
|
+
// name is often not the harness (codex installed from npm runs as a `node` wrapper), so the
|
|
67
|
+
// name match is only the fallback for agents started by hand.
|
|
68
|
+
export function tmuxLanes(panes, known = {}) {
|
|
69
|
+
return panes.filter((p) => known[p.session] || TMUX_HARNESSES.has(p.command)).map((p) => ({
|
|
70
|
+
harness: known[p.session]?.harness || p.command,
|
|
71
|
+
key: `tmux:${p.session}`,
|
|
72
|
+
id: null,
|
|
73
|
+
sessionId: null,
|
|
74
|
+
pid: p.panePid,
|
|
75
|
+
name: p.session.replace(/^(apiary|seldon)_/, ""),
|
|
76
|
+
cwd: p.cwd,
|
|
77
|
+
kind: "tmux",
|
|
78
|
+
startedAt: known[p.session]?.startedAt ?? null,
|
|
79
|
+
state: "running",
|
|
80
|
+
waitingFor: null,
|
|
81
|
+
tmuxSession: p.session,
|
|
82
|
+
}));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// The tmux session hosting a process: walk up its parents until one is a pane's shell.
|
|
86
|
+
// `parentOf(pid)` is injected (it shells out to `ps` in real use).
|
|
87
|
+
export function tmuxSessionFor(pid, panes, parentOf, maxDepth = 6) {
|
|
88
|
+
const byPanePid = new Map(panes.map((p) => [p.panePid, p.session]));
|
|
89
|
+
let cur = pid;
|
|
90
|
+
for (let i = 0; cur && i < maxDepth; i++) {
|
|
91
|
+
if (byPanePid.has(cur)) return byPanePid.get(cur);
|
|
92
|
+
cur = parentOf(cur);
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// ---- projects ------------------------------------------------------------------
|
|
98
|
+
// A lane belongs to the repo its cwd is in. A git worktree belongs to its MAIN repo, not to
|
|
99
|
+
// itself: an agent in .claude/worktrees/fix-x is working on the project, and reading its
|
|
100
|
+
// toplevel instead is how a working agent used to count as "nobody working here".
|
|
101
|
+
// `git rev-parse --path-format=absolute --git-common-dir` gives <main repo>/.git for both.
|
|
102
|
+
export function projectRootFromCommonDir(commonDir) {
|
|
103
|
+
if (!commonDir) return null;
|
|
104
|
+
const d = commonDir.replace(/\/+$/, "");
|
|
105
|
+
return d.endsWith("/.git") ? d.slice(0, -"/.git".length) : d;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function groupByProject(lanes, rootOf) {
|
|
109
|
+
const groups = new Map();
|
|
110
|
+
for (const lane of lanes) {
|
|
111
|
+
const root = rootOf(lane.cwd) || lane.cwd;
|
|
112
|
+
if (!groups.has(root)) groups.set(root, []);
|
|
113
|
+
groups.get(root).push({ ...lane, project: root });
|
|
114
|
+
}
|
|
115
|
+
return [...groups].map(([root, ls]) => ({ root, name: root.split("/").pop() || root, lanes: sortLanes(ls) }))
|
|
116
|
+
.sort((a, b) => urgency(a.lanes) - urgency(b.lanes) || a.name.localeCompare(b.name));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Most urgent first; within a state, newest first.
|
|
120
|
+
export function sortLanes(lanes) {
|
|
121
|
+
return [...lanes].sort((a, b) => (RANK[a.state] ?? 99) - (RANK[b.state] ?? 99) || (b.startedAt ?? 0) - (a.startedAt ?? 0));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const urgency = (lanes) => Math.min(...lanes.map((l) => RANK[l.state] ?? 99));
|
|
125
|
+
|
|
126
|
+
export function countByState(lanes) {
|
|
127
|
+
const c = Object.fromEntries(STATES.map((s) => [s, 0]));
|
|
128
|
+
for (const l of lanes) c[l.state] = (c[l.state] ?? 0) + 1;
|
|
129
|
+
return c;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// What one keypress should do to open a lane, or why it cannot. Decided here so the panel
|
|
133
|
+
// stays a dumb renderer and the rule is tested.
|
|
134
|
+
export function openCommand(lane) {
|
|
135
|
+
if (lane.harness === "claude" && lane.id) return { bin: "claude", args: ["attach", lane.id] };
|
|
136
|
+
if (lane.tmuxSession) return { bin: "tmux", args: ["attach", "-t", lane.tmuxSession] };
|
|
137
|
+
if (lane.harness === "claude" && lane.sessionId && (lane.state === "stopped" || lane.state === "failed"))
|
|
138
|
+
return { bin: "claude", args: ["--resume", lane.sessionId], cwd: lane.cwd };
|
|
139
|
+
return { why: "it runs in a terminal seldon cannot reach — switch to that window" };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ---- starting and stopping lanes -------------------------------------------------
|
|
143
|
+
// A lane's name is its task, slugged: it names the session, the branch and the worktree, so
|
|
144
|
+
// the plan item, the running agent and the branch on GitHub all read the same.
|
|
145
|
+
export function slugify(task, max = 40) {
|
|
146
|
+
const s = String(task).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
147
|
+
return (s.slice(0, max).replace(/-+$/, "") || "lane");
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export const HARNESSES = ["claude", "codex", "opencode"];
|
|
151
|
+
|
|
152
|
+
// A lane name nobody has used yet: "fix-it", else "fix-it-2", "fix-it-3"… Reusing a name
|
|
153
|
+
// collides with the branch or worktree an earlier lane of that name left behind.
|
|
154
|
+
export function uniqueSlug(base, isTaken) {
|
|
155
|
+
if (!isTaken(base)) return base;
|
|
156
|
+
for (let n = 2; ; n++) if (!isTaken(`${base}-${n}`)) return `${base}-${n}`;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// The commands that start a lane, in order. Claude makes and owns its worktree (`-w`) and runs
|
|
160
|
+
// under its own supervisor (`--bg`), so it survives the terminal and shows in `claude agents`.
|
|
161
|
+
// Codex and opencode have neither, so seldon makes the worktree (outside the repo, so it never
|
|
162
|
+
// shows up as untracked files) and hosts the agent in a tmux session named seldon_<slug>.
|
|
163
|
+
// claude: https://code.claude.com/docs/en/agent-view (`claude --bg`, `-w`, `-n`)
|
|
164
|
+
// codex: `codex -C <dir> "PROMPT"` opencode: `opencode <dir> --prompt "PROMPT"`
|
|
165
|
+
//
|
|
166
|
+
// tmux runs a session's command with the tmux SERVER's environment, not the caller's — so a
|
|
167
|
+
// bare `codex` resolves (or fails to) against whatever PATH the server started with, and the
|
|
168
|
+
// agent exits at once. `bins` maps harness -> absolute path and `env.PATH` is handed to the
|
|
169
|
+
// session, so the agent and everything it spawns see the PATH seldon saw.
|
|
170
|
+
export function startCommands({ harness, task, root, slug, worktreesDir, bins = {}, env = {} }) {
|
|
171
|
+
if (harness === "claude") return [{ bin: bins.claude || "claude", args: ["--bg", "-w", slug, "-n", slug, task], cwd: root }];
|
|
172
|
+
const wt = `${worktreesDir}/${slug}`;
|
|
173
|
+
const bin = bins[harness] || harness;
|
|
174
|
+
const agent = harness === "codex" ? [bin, "-C", wt, task] : [bin, wt, "--prompt", task];
|
|
175
|
+
const envArgs = env.PATH ? ["-e", `PATH=${env.PATH}`] : [];
|
|
176
|
+
return [
|
|
177
|
+
{ bin: "git", args: ["-C", root, "worktree", "add", "-b", `lane/${slug}`, wt], quiet: true },
|
|
178
|
+
{ bin: "tmux", args: ["new-session", "-d", "-s", `seldon_${slug}`, "-c", wt, ...envArgs, ...agent], session: `seldon_${slug}`, agent, cwd: wt },
|
|
179
|
+
];
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function stopCommand(lane) {
|
|
183
|
+
if (lane.harness === "claude" && lane.id) return { bin: "claude", args: ["stop", lane.id] };
|
|
184
|
+
if (lane.tmuxSession && lane.harness !== "claude") return { bin: "tmux", args: ["kill-session", "-t", lane.tmuxSession] };
|
|
185
|
+
return { why: "it is not a background session — stop it where it runs" };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Which running lane is working on a plan item: the one named after it (seldon starts lanes
|
|
189
|
+
// with the item's slug as name, session and worktree).
|
|
190
|
+
export function laneForItem(item, lanes) {
|
|
191
|
+
const slug = slugify(item.text);
|
|
192
|
+
return lanes.find((l) => l.name === slug || l.tmuxSession === `seldon_${slug}` || (l.cwd || "").split("/").pop() === slug) || null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ---- after a reboot ---------------------------------------------------------------
|
|
196
|
+
// A tmux lane seldon started, whose session is gone, and that nobody stopped on purpose,
|
|
197
|
+
// died with the machine (or crashed). It is listed as stopped so it can be resumed.
|
|
198
|
+
export function registryLanes(entries, liveSessions) {
|
|
199
|
+
const live = new Set(liveSessions);
|
|
200
|
+
return (entries || []).filter((e) => e.session && !e.stoppedAt && !live.has(e.session)).map((e) => ({
|
|
201
|
+
harness: e.harness,
|
|
202
|
+
key: `tmux:${e.session}`,
|
|
203
|
+
id: null,
|
|
204
|
+
sessionId: null,
|
|
205
|
+
pid: null,
|
|
206
|
+
name: e.slug || e.session.replace(/^seldon_/, ""),
|
|
207
|
+
cwd: e.worktree,
|
|
208
|
+
kind: "tmux",
|
|
209
|
+
startedAt: e.startedAt ?? null,
|
|
210
|
+
state: "stopped",
|
|
211
|
+
waitingFor: null,
|
|
212
|
+
tmuxSession: e.session,
|
|
213
|
+
task: e.task,
|
|
214
|
+
}));
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// How to bring a stopped lane back.
|
|
218
|
+
// claude: `claude respawn <id>` resumes its saved conversation.
|
|
219
|
+
// codex: `codex resume --last` is scoped to the current directory, and every lane has its
|
|
220
|
+
// own worktree, so it picks up exactly this lane's conversation.
|
|
221
|
+
// opencode: its "continue" is per project, and worktrees share one, so it could pick up a
|
|
222
|
+
// sibling lane's conversation. It is restarted on the same task in the same
|
|
223
|
+
// worktree instead (the work on disk is kept) — and says so.
|
|
224
|
+
export function resumeCommands(lane, { bins = {}, env = {} } = {}) {
|
|
225
|
+
if (lane.harness === "claude" && lane.id) return { cmds: [{ bin: bins.claude || "claude", args: ["respawn", lane.id] }] };
|
|
226
|
+
if (!lane.tmuxSession || !lane.cwd || !["codex", "opencode"].includes(lane.harness)) return { why: "seldon did not start it, so it cannot restart it" };
|
|
227
|
+
const bin = bins[lane.harness] || lane.harness;
|
|
228
|
+
const agent = lane.harness === "codex" ? [bin, "resume", "--last"] : [bin, lane.cwd, "--prompt", lane.task || "continue where you left off"];
|
|
229
|
+
const envArgs = env.PATH ? ["-e", `PATH=${env.PATH}`] : [];
|
|
230
|
+
return {
|
|
231
|
+
cmds: [{ bin: "tmux", args: ["new-session", "-d", "-s", lane.tmuxSession, "-c", lane.cwd, ...envArgs, ...agent], session: lane.tmuxSession, agent, cwd: lane.cwd }],
|
|
232
|
+
fresh: lane.harness === "opencode",
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// ---- telling the human ----------------------------------------------------------------
|
|
237
|
+
// What changed since the last look that a person should hear about: an agent that starts
|
|
238
|
+
// waiting on them, fails, or finishes. Only TRANSITIONS — a lane that stays blocked is not
|
|
239
|
+
// re-announced every tick, and a lane seen for the first time is not news.
|
|
240
|
+
const NEWS = { "needs-you": "needs you", failed: "failed", idle: "finished" };
|
|
241
|
+
export function transitions(prev, lanes) {
|
|
242
|
+
const events = [];
|
|
243
|
+
for (const l of lanes) {
|
|
244
|
+
const was = prev.get(l.key);
|
|
245
|
+
if (was === undefined || was === l.state || !NEWS[l.state]) continue;
|
|
246
|
+
if (l.state === "idle" && !["working", "running"].includes(was)) continue; // only work that just ended
|
|
247
|
+
events.push({ lane: l, from: was, to: l.state, text: `${l.name || l.id} ${NEWS[l.state]}${l.state === "needs-you" && l.waitingFor ? `: ${l.waitingFor}` : ""}` });
|
|
248
|
+
}
|
|
249
|
+
return events;
|
|
250
|
+
}
|
package/lib/machines.mjs
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Other machines. bifrost already owns "which machines exist" (~/.config/bifrost/realms/<name>,
|
|
2
|
+
// REALM_HOST / REALM_USER), so seldon reads that rather than keeping a second list; factory
|
|
3
|
+
// does the same (modules/factory/src/lib/realm.mjs). `seldon machines add` writes the same
|
|
4
|
+
// format, so the two tools always agree.
|
|
5
|
+
//
|
|
6
|
+
// The protocol is just seldon on the other end: `ssh <machine> seldon lanes --json` to read,
|
|
7
|
+
// `seldon lane <verb> <key>` to act. Pure helpers first, then the I/O.
|
|
8
|
+
import { readFileSync, readdirSync, writeFileSync, mkdirSync } from "node:fs";
|
|
9
|
+
import { execFile } from "node:child_process";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { homedir } from "node:os";
|
|
12
|
+
import { groupByProject } from "./lanes.mjs";
|
|
13
|
+
|
|
14
|
+
export const REALMS_DIR = join(homedir(), ".config", "bifrost", "realms");
|
|
15
|
+
|
|
16
|
+
// Read narrowly — two keys, quotes stripped, nothing executed. Sourcing a file to learn a
|
|
17
|
+
// hostname is not something to do.
|
|
18
|
+
export function parseRealmFile(text) {
|
|
19
|
+
const pick = (key) => {
|
|
20
|
+
for (const k of [`REALM_${key}`, `DEVICE_${key}`]) {
|
|
21
|
+
const m = String(text).match(new RegExp(`^\\s*${k}=["']?([^"'\\n]+)`, "m"));
|
|
22
|
+
if (m) return m[1].trim();
|
|
23
|
+
}
|
|
24
|
+
return null;
|
|
25
|
+
};
|
|
26
|
+
const host = pick("HOST");
|
|
27
|
+
return host ? { host, user: pick("USER") } : null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const sq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
31
|
+
|
|
32
|
+
// ssh argv that runs `argv` on the machine through its login shell — a non-interactive ssh
|
|
33
|
+
// often has no PATH to seldon (npm/pnpm/nvm set it in the shell's rc files).
|
|
34
|
+
export function sshArgs(machine, argv, { tty = false } = {}) {
|
|
35
|
+
const target = machine.user ? `${machine.user}@${machine.host}` : machine.host;
|
|
36
|
+
const inner = argv.map(sq).join(" ");
|
|
37
|
+
return ["-o", "BatchMode=yes", "-o", "ConnectTimeout=4", ...(tty ? ["-t"] : []), target, `exec "$SHELL" -lic ${sq(inner)}`];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// The JSON line in a remote reply. rc files can print before it (a motd, nvm notices).
|
|
41
|
+
export function lastJsonLine(text) {
|
|
42
|
+
const line = String(text).split("\n").reverse().find((l) => l.trim().startsWith("["));
|
|
43
|
+
try { return line ? JSON.parse(line) : null; } catch { return null; }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// A machine's lanes as project groups, named and keyed so they can never collide with this
|
|
47
|
+
// machine's: "stranded @mini", key "mini/claude:ab12".
|
|
48
|
+
export function remoteGroups(machine, lanes) {
|
|
49
|
+
const tagged = (lanes || []).map((l) => ({ ...l, machine: machine.name, remoteKey: l.key, key: `${machine.name}/${l.key}` }));
|
|
50
|
+
const projectOf = new Map(tagged.map((l) => [l.cwd, l.project])); // the remote already resolved it
|
|
51
|
+
return groupByProject(tagged, (cwd) => projectOf.get(cwd)).map((g) => ({
|
|
52
|
+
...g,
|
|
53
|
+
root: `${machine.name}:${g.root}`, // unique across machines
|
|
54
|
+
remoteRoot: g.root, // the path on that machine
|
|
55
|
+
name: `${g.lanes[0].projectName || g.name} @${machine.name}`,
|
|
56
|
+
machine: machine.name,
|
|
57
|
+
}));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ---- I/O -------------------------------------------------------------------------
|
|
61
|
+
export function listMachines() {
|
|
62
|
+
let names = [];
|
|
63
|
+
try { names = readdirSync(REALMS_DIR); } catch { return []; }
|
|
64
|
+
return names.map((name) => {
|
|
65
|
+
try { const r = parseRealmFile(readFileSync(join(REALMS_DIR, name), "utf8")); return r ? { name, ...r } : null; } catch { return null; }
|
|
66
|
+
}).filter(Boolean);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function addMachine(name, target) {
|
|
70
|
+
const [user, host] = target.includes("@") ? target.split("@") : [null, target];
|
|
71
|
+
mkdirSync(REALMS_DIR, { recursive: true });
|
|
72
|
+
writeFileSync(join(REALMS_DIR, name), `REALM_HOST="${host}"\n${user ? `REALM_USER="${user}"\n` : ""}`);
|
|
73
|
+
return { name, host, user };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Ask a machine for its lanes, in the background. Never throws; `error` says why it failed.
|
|
77
|
+
export function fetchLanes(machine, cb) {
|
|
78
|
+
execFile("ssh", sshArgs(machine, ["seldon", "lanes", "--json"]), { timeout: 10_000, encoding: "utf8" }, (err, stdout) => {
|
|
79
|
+
const lanes = lastJsonLine(stdout);
|
|
80
|
+
cb(lanes ? { lanes } : { error: err ? (err.killed ? "timed out" : "unreachable") : "no seldon there" });
|
|
81
|
+
});
|
|
82
|
+
}
|
package/lib/notify.mjs
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// A desktop notification, best-effort: macOS (osascript), Linux (notify-send), else nothing.
|
|
2
|
+
// SELDON_NO_NOTIFY silences it (tests, CI).
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
|
|
5
|
+
export function notify(title, message) {
|
|
6
|
+
if (process.env.SELDON_NO_NOTIFY) return;
|
|
7
|
+
const esc = (s) => String(s).replace(/["\\]/g, "\\$&").slice(0, 240);
|
|
8
|
+
if (process.platform === "darwin") execFile("osascript", ["-e", `display notification "${esc(message)}" with title "${esc(title)}"`], () => {});
|
|
9
|
+
else if (process.platform === "linux") execFile("notify-send", [String(title), String(message)], () => {});
|
|
10
|
+
}
|
package/lib/projects.mjs
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// "Where am I, and what is missing?" — asked once, used by `seldon go` and the panel.
|
|
2
|
+
//
|
|
3
|
+
// This owns NO state. factory owns the hive registry, foundation owns the docs seam, apiary
|
|
4
|
+
// owns the rooms. Everything here either reads `factory state --compact` or delegates to a
|
|
5
|
+
// sibling CLI. The moment seldon starts parsing docs/QUEUE.md itself there are two parsers of
|
|
6
|
+
// the seam and they drift — which is the mistake factory's own state.mjs header warns about.
|
|
7
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
8
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
|
|
12
|
+
// ---- sibling CLIs -----------------------------------------------------------
|
|
13
|
+
// seldon, factory, apiary and comb install side by side, but the install dir (pnpm's global
|
|
14
|
+
// bin) is often absent from PATH in a NON-interactive shell — a script, a hook, an agent's
|
|
15
|
+
// Bash tool. seldon itself was found, so its own directory is the one place guaranteed to
|
|
16
|
+
// hold its siblings. Prepending it turns "factory: command not found" into a non-event.
|
|
17
|
+
export function ensureSiblingPath(argv1 = process.argv[1]) {
|
|
18
|
+
try {
|
|
19
|
+
const dir = path.dirname(fs.realpathSync(argv1));
|
|
20
|
+
const parts = (process.env.PATH || "").split(path.delimiter);
|
|
21
|
+
for (const d of [dir, path.resolve(dir, "..")]) {
|
|
22
|
+
if (d && !parts.includes(d)) process.env.PATH = d + path.delimiter + process.env.PATH;
|
|
23
|
+
}
|
|
24
|
+
} catch { /* argv[1] unreadable — leave PATH alone */ }
|
|
25
|
+
return process.env.PATH;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const has = (bin) => {
|
|
29
|
+
try { execFileSync("sh", ["-c", `command -v ${bin}`], { stdio: "ignore" }); return true; } catch { return false; }
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// ---- state ------------------------------------------------------------------
|
|
33
|
+
// `factory state --compact` is read-only and already the machine-readable twin of the board.
|
|
34
|
+
// null means factory is missing or broke; an empty hive list is a valid, different answer.
|
|
35
|
+
export function loadState() {
|
|
36
|
+
try {
|
|
37
|
+
const out = execFileSync("factory", ["state", "--compact"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
|
|
38
|
+
const s = JSON.parse(out);
|
|
39
|
+
if (!Array.isArray(s.hives)) return null;
|
|
40
|
+
return s;
|
|
41
|
+
} catch { return null; }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// The git repo containing `dir`, or null. A project is always its repo root: running `seldon
|
|
45
|
+
// go` from src/world/ must mean the same thing as running it from the top.
|
|
46
|
+
export function gitRootOf(dir) {
|
|
47
|
+
try {
|
|
48
|
+
return execFileSync("git", ["-C", dir, "rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || null;
|
|
49
|
+
} catch { return null; }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const realish = (p) => { try { return fs.realpathSync(p); } catch { return p; } };
|
|
53
|
+
export const sameDir = (a, b) => !!a && !!b && realish(a) === realish(b);
|
|
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
|
+
|
|
61
|
+
/**
|
|
62
|
+
* What did the user mean, and what do we know about it?
|
|
63
|
+
* { kind: "hive" , hive } a registered project (by name, or we are standing in it)
|
|
64
|
+
* { kind: "repo" , dir } a git repo that is not on the line yet
|
|
65
|
+
* { kind: "unknown" , arg } a name that matches nothing
|
|
66
|
+
* { kind: "nowhere" } no argument and not inside a repo
|
|
67
|
+
*/
|
|
68
|
+
export function resolveProject(arg, state) {
|
|
69
|
+
const hives = state?.hives || [];
|
|
70
|
+
if (arg) {
|
|
71
|
+
const byName = hives.find((h) => h.name === arg);
|
|
72
|
+
if (byName) return { kind: "hive", hive: byName, dir: byName.dir };
|
|
73
|
+
const abs = path.resolve(arg);
|
|
74
|
+
if (existsSync(abs)) {
|
|
75
|
+
const root = gitRootOf(abs);
|
|
76
|
+
if (!root) return { kind: "unknown", arg, reason: "not a git repo" };
|
|
77
|
+
const byDir = hives.find((h) => sameDir(h.dir, root));
|
|
78
|
+
return byDir ? { kind: "hive", hive: byDir, dir: byDir.dir } : { kind: "repo", dir: root };
|
|
79
|
+
}
|
|
80
|
+
return { kind: "unknown", arg, reason: "no such project or directory" };
|
|
81
|
+
}
|
|
82
|
+
const root = gitRootOf(process.cwd());
|
|
83
|
+
if (!root) return { kind: "nowhere" };
|
|
84
|
+
const byDir = hives.find((h) => sameDir(h.dir, root));
|
|
85
|
+
return byDir ? { kind: "hive", hive: byDir, dir: byDir.dir } : { kind: "repo", dir: root };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ---- actions (all delegated, all idempotent) --------------------------------
|
|
89
|
+
const passthru = (bin, args, opts = {}) => spawnSync(bin, args, { stdio: "inherit", ...opts }).status === 0;
|
|
90
|
+
const quiet = (bin, args) => {
|
|
91
|
+
const r = spawnSync(bin, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
|
|
92
|
+
return { ok: r.status === 0, out: (r.stdout || "") + (r.stderr || "") };
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
// `factory adopt` is the one command that both puts a repo on the line AND reopens a hive that
|
|
96
|
+
// is down (it reuses a reachable one, else opens it with the room history intact).
|
|
97
|
+
export const adopt = (dir, { verbose = true } = {}) =>
|
|
98
|
+
verbose ? passthru("factory", ["adopt", dir]) : quiet("factory", ["adopt", dir]).ok;
|
|
99
|
+
|
|
100
|
+
export const staff = (dir, { agent, model, effort, name } = {}) => {
|
|
101
|
+
const a = [];
|
|
102
|
+
if (agent) a.push("--agent", agent);
|
|
103
|
+
if (model) a.push("--model", model);
|
|
104
|
+
if (effort) a.push("--effort", effort);
|
|
105
|
+
if (name) a.push("--name", name);
|
|
106
|
+
return passthru("factory", ["staff", dir, ...a]);
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
// `apiary room resume` is the human's seat: it restarts a stopped room, refreshes the share
|
|
110
|
+
// tokens and drops you into the TUI with the agent strip. It is also the thing nothing ever
|
|
111
|
+
// told you about.
|
|
112
|
+
export const attach = (name) => passthru("apiary", ["room", "resume", name]);
|
|
113
|
+
|
|
114
|
+
export const hiveOf = (state, dir) => (state?.hives || []).find((h) => sameDir(h.dir, dir)) || null;
|
package/lib/reports.mjs
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// Harness reports: Codex and opencode telling seldon what they are doing.
|
|
2
|
+
//
|
|
3
|
+
// Claude Code lists its own sessions (`claude agents --json`). Codex and opencode do not, but
|
|
4
|
+
// both run code on their own lifecycle events — Codex command hooks, opencode plugins — and
|
|
5
|
+
// both hand that code a JSON event. `seldon setup` installs a tiny hook/plugin that pipes the
|
|
6
|
+
// event to `seldon report <harness>`, which keeps one small state file per session. This file
|
|
7
|
+
// is the one place an event becomes a state, for both harnesses. Pure.
|
|
8
|
+
// Codex hooks: https://learn.chatgpt.com/docs/hooks
|
|
9
|
+
// opencode plugins: https://opencode.ai/docs/plugins/
|
|
10
|
+
|
|
11
|
+
// Codex hook event -> state. Interrupt and Stop both end the turn.
|
|
12
|
+
const CODEX = {
|
|
13
|
+
SessionStart: "idle", UserPromptSubmit: "working", PreToolUse: "working", PostToolUse: "working",
|
|
14
|
+
SubagentStart: "working", PermissionRequest: "needs-you", Stop: "idle", Interrupt: "idle",
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export function reportFromEvent(harness, ev, now = Date.now()) {
|
|
18
|
+
if (!ev || typeof ev !== "object") return null;
|
|
19
|
+
if (harness === "codex") {
|
|
20
|
+
const name = ev.hook_event_name;
|
|
21
|
+
if (name === "SessionEnd") return { harness, session: ev.session_id, cwd: ev.cwd, ended: true, at: now };
|
|
22
|
+
const state = CODEX[name];
|
|
23
|
+
if (!state || !ev.session_id) return null;
|
|
24
|
+
return { harness, session: ev.session_id, cwd: ev.cwd, state, waitingFor: state === "needs-you" ? `permission: ${ev.tool_name || "tool"}` : null, at: now };
|
|
25
|
+
}
|
|
26
|
+
if (harness === "opencode") {
|
|
27
|
+
// The plugin adds `cwd` (its directory); opencode events carry properties.sessionID.
|
|
28
|
+
const p = ev.properties || {};
|
|
29
|
+
const session = p.sessionID || p.info?.sessionID || p.info?.id;
|
|
30
|
+
if (!session) return null;
|
|
31
|
+
const base = { harness, session, cwd: ev.cwd, at: now };
|
|
32
|
+
switch (ev.type) {
|
|
33
|
+
case "session.status": {
|
|
34
|
+
const t = p.status?.type;
|
|
35
|
+
return t === "busy" || t === "retry" ? { ...base, state: "working" } : t === "idle" ? { ...base, state: "idle" } : null;
|
|
36
|
+
}
|
|
37
|
+
case "session.idle": return { ...base, state: "idle" };
|
|
38
|
+
case "permission.asked": return { ...base, state: "needs-you", waitingFor: `permission: ${p.permission || p.type || "tool"}` };
|
|
39
|
+
case "permission.replied": return { ...base, state: "working" };
|
|
40
|
+
case "session.error": return { ...base, state: "failed" };
|
|
41
|
+
case "session.deleted": return { ...base, ended: true };
|
|
42
|
+
default: return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// The opencode events worth a report — the plugin forwards only these, so the stream of
|
|
49
|
+
// message.part.updated events never spawns anything.
|
|
50
|
+
export const OPENCODE_EVENTS = ["session.status", "session.idle", "permission.asked", "permission.replied", "session.error", "session.deleted"];
|
|
51
|
+
|
|
52
|
+
// Give each tmux lane the newest report from its own worktree. A lane with no report keeps
|
|
53
|
+
// "running"; a report older than the lane (left by an earlier session there) is ignored.
|
|
54
|
+
export function applyReports(lanes, reports, sameDir = (a, b) => a === b) {
|
|
55
|
+
return lanes.map((l) => {
|
|
56
|
+
if (l.kind !== "tmux" || l.state === "stopped") return l;
|
|
57
|
+
const mine = reports.filter((r) => r.harness === l.harness && r.cwd && sameDir(r.cwd, l.cwd) && (!l.startedAt || r.at >= l.startedAt - 5000));
|
|
58
|
+
if (!mine.length) return l;
|
|
59
|
+
const r = mine.reduce((a, b) => (b.at > a.at ? b : a));
|
|
60
|
+
return { ...l, state: r.state, waitingFor: r.waitingFor ?? null };
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ---- setup: what seldon installs into each harness ---------------------------------------
|
|
65
|
+
const HOOK_EVENTS = ["SessionStart", "SessionEnd", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PermissionRequest", "Stop", "Interrupt"];
|
|
66
|
+
// Every command seldon installs starts with this, so it can find its own hooks again (and only
|
|
67
|
+
// its own) whatever path the seldon binary has.
|
|
68
|
+
export const SELDON_MARK = "SELDON_REPORT=1";
|
|
69
|
+
|
|
70
|
+
// A hook event's matcher groups with seldon's handlers taken out (and groups left empty dropped).
|
|
71
|
+
const withoutSeldon = (groups = []) => groups
|
|
72
|
+
.map((g) => ({ ...g, hooks: (g.hooks || []).filter((h) => !String(h.command || "").includes(SELDON_MARK)) }))
|
|
73
|
+
.filter((g) => g.hooks.length);
|
|
74
|
+
|
|
75
|
+
// Merge seldon's hooks into an existing Codex hooks.json, leaving everything else alone.
|
|
76
|
+
// Idempotent: an existing seldon handler is replaced, never duplicated.
|
|
77
|
+
export function mergeCodexHooks(existing, command) {
|
|
78
|
+
const cfg = existing && typeof existing === "object" ? structuredClone(existing) : {};
|
|
79
|
+
cfg.hooks = cfg.hooks || {};
|
|
80
|
+
for (const ev of HOOK_EVENTS) {
|
|
81
|
+
const groups = withoutSeldon(cfg.hooks[ev]);
|
|
82
|
+
groups.push({ hooks: [{ type: "command", command, timeout: 5 }] });
|
|
83
|
+
cfg.hooks[ev] = groups;
|
|
84
|
+
}
|
|
85
|
+
return cfg;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function removeCodexHooks(existing) {
|
|
89
|
+
if (!existing?.hooks) return existing;
|
|
90
|
+
const cfg = structuredClone(existing);
|
|
91
|
+
for (const ev of Object.keys(cfg.hooks)) {
|
|
92
|
+
cfg.hooks[ev] = withoutSeldon(cfg.hooks[ev]);
|
|
93
|
+
if (!cfg.hooks[ev].length) delete cfg.hooks[ev];
|
|
94
|
+
}
|
|
95
|
+
return cfg;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// The opencode plugin: forward the few events that change state to `seldon report opencode`,
|
|
99
|
+
// adding the directory (opencode events do not carry it). Never throws into opencode.
|
|
100
|
+
export function opencodePlugin(seldon) {
|
|
101
|
+
return `// Installed by \`seldon setup opencode\` — tells seldon what this opencode session is doing.
|
|
102
|
+
// Remove with \`seldon setup opencode --remove\`.
|
|
103
|
+
import { spawn } from "node:child_process";
|
|
104
|
+
const FORWARD = new Set(${JSON.stringify(OPENCODE_EVENTS)});
|
|
105
|
+
export const SeldonReport = async ({ directory }) => ({
|
|
106
|
+
event: async ({ event }) => {
|
|
107
|
+
if (!FORWARD.has(event?.type)) return;
|
|
108
|
+
try {
|
|
109
|
+
const p = spawn(${JSON.stringify(seldon)}, ["report", "opencode"], { stdio: ["pipe", "ignore", "ignore"], detached: true });
|
|
110
|
+
p.stdin.end(JSON.stringify({ ...event, cwd: directory }));
|
|
111
|
+
p.unref();
|
|
112
|
+
} catch {}
|
|
113
|
+
},
|
|
114
|
+
});
|
|
115
|
+
`;
|
|
116
|
+
}
|
package/modules.mjs
CHANGED
|
@@ -10,7 +10,7 @@ export const MODULES = [
|
|
|
10
10
|
{
|
|
11
11
|
id: "apiary",
|
|
12
12
|
title: "the conversation",
|
|
13
|
-
blurb: "
|
|
13
|
+
blurb: "add-on · rooms where agents talk to each other (MCP, tmux)",
|
|
14
14
|
method: "npm",
|
|
15
15
|
pkg: "@gorlitzer-labs/apiary",
|
|
16
16
|
dir: "modules/apiary",
|
|
@@ -22,7 +22,7 @@ export const MODULES = [
|
|
|
22
22
|
{
|
|
23
23
|
id: "foundation",
|
|
24
24
|
title: "the seam",
|
|
25
|
-
blurb: "the
|
|
25
|
+
blurb: "the plan · docs/QUEUE.md + a deterministic CLI · recommended",
|
|
26
26
|
method: "npm",
|
|
27
27
|
pkg: "@gorlitzer-labs/foundation",
|
|
28
28
|
dir: "modules/foundation",
|
|
@@ -34,7 +34,7 @@ export const MODULES = [
|
|
|
34
34
|
{
|
|
35
35
|
id: "comb",
|
|
36
36
|
title: "the vault",
|
|
37
|
-
blurb: "
|
|
37
|
+
blurb: "add-on · secrets by name; a leak audit; multi-machine (SOPS + age)",
|
|
38
38
|
method: "npm",
|
|
39
39
|
pkg: "@gorlitzer-labs/comb",
|
|
40
40
|
dir: "modules/comb",
|
|
@@ -46,7 +46,7 @@ export const MODULES = [
|
|
|
46
46
|
{
|
|
47
47
|
id: "factory",
|
|
48
48
|
title: "the floor",
|
|
49
|
-
blurb: "
|
|
49
|
+
blurb: "add-on · projects run through apiary rooms · new · board · box",
|
|
50
50
|
method: "npm",
|
|
51
51
|
pkg: "@gorlitzer-labs/factory",
|
|
52
52
|
dir: "modules/factory",
|
|
@@ -58,7 +58,7 @@ export const MODULES = [
|
|
|
58
58
|
{
|
|
59
59
|
id: "bifrost",
|
|
60
60
|
title: "the bridge",
|
|
61
|
-
blurb: "tmux + Tailscale
|
|
61
|
+
blurb: "add-on · tmux + Tailscale across machines; phone access",
|
|
62
62
|
method: "shell",
|
|
63
63
|
dir: "modules/bifrost",
|
|
64
64
|
installer: "modules/bifrost/install.sh",
|
|
@@ -70,7 +70,7 @@ export const MODULES = [
|
|
|
70
70
|
{
|
|
71
71
|
id: "demerzel",
|
|
72
72
|
title: "the voice",
|
|
73
|
-
blurb: "a fully-local voice you talk to (MLX, Apple silicon)",
|
|
73
|
+
blurb: "add-on · a fully-local voice you talk to (MLX, Apple silicon)",
|
|
74
74
|
method: "python",
|
|
75
75
|
dir: "modules/demerzel",
|
|
76
76
|
bin: "demerzel",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gorlitzer-labs/seldon",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Install the Seldon stack — pick your tools from a checklist; each installs via its native method.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
},
|
|
9
9
|
"files": [
|
|
10
10
|
"bin",
|
|
11
|
+
"lib",
|
|
11
12
|
"modules.mjs",
|
|
12
13
|
"README.md"
|
|
13
14
|
],
|