@gorlitzer-labs/seldon 0.17.1 β 0.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -76
- package/bin/seldon.js +156 -78
- package/lib/machines.mjs +14 -1
- package/lib/projects.mjs +0 -5
- package/lib/telegram.mjs +5 -6
- package/lib/workspace.mjs +175 -0
- package/package.json +1 -1
- package/lib/serve.mjs +0 -241
- package/lib/web/index.html +0 -351
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// The workspace: every agent in a list on the left, the selected agent's own terminal on the
|
|
2
|
+
// right, one key to switch. It is a tmux session on its own server (`tmux -L seldon-ws`), so
|
|
3
|
+
// its keys and options never touch the tmux you already use, and an agent that itself lives in
|
|
4
|
+
// tmux is simply attached inside the right-hand pane.
|
|
5
|
+
//
|
|
6
|
+
// Switching never stops an agent: the right-hand pane only holds a client (`claude attach`,
|
|
7
|
+
// `tmux attach`, or ssh to another machine's `seldon lane open`). Replacing the pane ends the
|
|
8
|
+
// client, not the agent.
|
|
9
|
+
//
|
|
10
|
+
// Everything here is pure: bin/seldon.js runs tmux and reads the lanes, and passes them in.
|
|
11
|
+
import { openCommand } from "./lanes.mjs";
|
|
12
|
+
import { sshArgs } from "./machines.mjs";
|
|
13
|
+
|
|
14
|
+
export const WS_SOCKET = "seldon-ws";
|
|
15
|
+
export const WS_SESSION = "ws";
|
|
16
|
+
export const SIDE_WIDTH = 38;
|
|
17
|
+
export const NARROW = 90; // below this many columns one pane fills the screen (a phone)
|
|
18
|
+
|
|
19
|
+
// ---- a face for every agent --------------------------------------------------------
|
|
20
|
+
// The same name always gets the same emoji (apiary does this for its agents), so an agent is
|
|
21
|
+
// recognisable in the list, in its pane title and across machines without reading its name.
|
|
22
|
+
export const AGENT_POOL = [
|
|
23
|
+
"π¦", "π", "π¦", "π’", "π¦", "π§", "π¦", "π³", "π¦", "π", "π¦", "πΊ", "π¦", "πΈ", "π¦", "πΌ",
|
|
24
|
+
"π¦", "π¬", "π¦©", "πΏοΈ", "π¦₯", "π¦¦", "π¨", "π¦", "π", "π¦", "π", "π¦", "π", "π¦¬", "π¦", "πͺΌ",
|
|
25
|
+
];
|
|
26
|
+
const hash = (s) => { let h = 7; for (const c of String(s)) h = (h * 31 + c.codePointAt(0)) >>> 0; return h; };
|
|
27
|
+
export const emojiFor = (name, pool = AGENT_POOL) => pool[hash(name) % pool.length];
|
|
28
|
+
|
|
29
|
+
// One emoji each for the agents on screen together. Each takes its own (hashed) one; when two
|
|
30
|
+
// would share, the later name alphabetically moves to the next free one, so the answer does
|
|
31
|
+
// not depend on the order the agents are listed in.
|
|
32
|
+
export function assignEmoji(names, pool = AGENT_POOL) {
|
|
33
|
+
const out = new Map(), used = new Set();
|
|
34
|
+
for (const name of [...new Set(names)].sort()) {
|
|
35
|
+
let i = hash(name) % pool.length;
|
|
36
|
+
for (let n = 0; used.has(pool[i]) && n < pool.length; n++) i = (i + 1) % pool.length;
|
|
37
|
+
used.add(pool[i]); out.set(name, pool[i]);
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// ---- the list ----------------------------------------------------------------------
|
|
43
|
+
// One numbered row per agent, in the order the panel shows them (the ones waiting first).
|
|
44
|
+
// `down` is the set of machines that did not answer: their agents stay listed, marked off.
|
|
45
|
+
export function wsRows(groups, down = new Set()) {
|
|
46
|
+
const rows = [];
|
|
47
|
+
for (const g of groups) {
|
|
48
|
+
for (const lane of g.lanes) {
|
|
49
|
+
rows.push({
|
|
50
|
+
n: rows.length + 1,
|
|
51
|
+
key: lane.key,
|
|
52
|
+
name: lane.name || lane.id || lane.key,
|
|
53
|
+
project: g.name,
|
|
54
|
+
harness: lane.harness,
|
|
55
|
+
state: lane.state,
|
|
56
|
+
waitingFor: lane.waitingFor || null,
|
|
57
|
+
startedAt: lane.startedAt || null,
|
|
58
|
+
machine: lane.machine || null,
|
|
59
|
+
off: !!lane.machine && down.has(lane.machine),
|
|
60
|
+
lane,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return rows;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// The next agent waiting on you after `currentKey`, wrapping round. null when nobody is.
|
|
68
|
+
export function nextNeeding(rows, currentKey) {
|
|
69
|
+
const live = rows.filter((r) => !r.off);
|
|
70
|
+
const at = live.findIndex((r) => r.key === currentKey);
|
|
71
|
+
for (let k = 1; k <= live.length; k++) {
|
|
72
|
+
const r = live[(at + k) % live.length];
|
|
73
|
+
if (r.state === "needs-you") return r;
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// A row by its number ("3") or its key.
|
|
79
|
+
export const findRow = (rows, ref) => rows.find((r) => String(r.n) === String(ref) || r.key === ref) || null;
|
|
80
|
+
|
|
81
|
+
// ---- what the right-hand pane runs ---------------------------------------------------
|
|
82
|
+
const sq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
83
|
+
const shJoin = (argv) => argv.map(sq).join(" ");
|
|
84
|
+
|
|
85
|
+
// The shell line that opens one agent. When its client exits (you detached, the agent ended,
|
|
86
|
+
// the machine dropped) the pane falls back to `home`, the full panel, instead of dying.
|
|
87
|
+
// A failure stays on screen long enough to read.
|
|
88
|
+
export function paneCommand(row, { machines = [], home }) {
|
|
89
|
+
const lane = row.lane;
|
|
90
|
+
let open;
|
|
91
|
+
if (row.off) return `printf '\\n %s is paused: %s is not reachable. It carries on when that machine is back.\\n' ${sq(row.name)} ${sq(row.machine)}; sleep 6; exec ${home}`;
|
|
92
|
+
if (lane.machine) {
|
|
93
|
+
const m = machines.find((x) => x.name === lane.machine);
|
|
94
|
+
if (!m) return `printf '\\n seldon does not know the machine %s\\n' ${sq(lane.machine)}; sleep 6; exec ${home}`;
|
|
95
|
+
open = shJoin(["ssh", ...sshArgs(m, ["seldon", "lane", "open", lane.remoteKey || lane.key], { tty: true })]);
|
|
96
|
+
} else {
|
|
97
|
+
const how = openCommand(lane);
|
|
98
|
+
if (how.why) return `printf '\\n cannot open %s here: %s\\n' ${sq(row.name)} ${sq(how.why)}; sleep 6; exec ${home}`;
|
|
99
|
+
// The lane's tmux lives on the default server; this pane's $TMUX points at the workspace's.
|
|
100
|
+
const argv = how.bin === "tmux" ? ["env", "-u", "TMUX", "tmux", ...how.args] : [how.bin, ...how.args];
|
|
101
|
+
open = (how.cwd ? `cd ${sq(how.cwd)} && ` : "") + shJoin(argv);
|
|
102
|
+
}
|
|
103
|
+
return `${open} || { printf '\\n seldon: %s closed with an error\\n' ${sq(row.name)}; sleep 5; }; exec ${home}`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ---- the tmux session ----------------------------------------------------------------
|
|
107
|
+
// `self` is the absolute `node seldon.js`, shell-quoted (tmux runs commands with its server's
|
|
108
|
+
// PATH, not yours); `home` is what the right-hand pane shows when no agent is open. Returned
|
|
109
|
+
// as argv lists, in order, for one `tmux -L seldon-ws` call.
|
|
110
|
+
export function setupCommands({ self, home = self, cols = 200, rows = 50 }) {
|
|
111
|
+
const argv = (...a) => ["run-shell", "-b", `${self} ws ${a.join(" ")}`];
|
|
112
|
+
const line = (...a) => `run-shell -b ${sq(`${self} ws ${a.join(" ")}`)}`; // a hook takes one string
|
|
113
|
+
const cmds = [
|
|
114
|
+
["start-server"],
|
|
115
|
+
["set", "-g", "default-terminal", "screen-256color"], ["set", "-as", "terminal-features", ",*:RGB"],
|
|
116
|
+
["set", "-g", "extended-keys", "on"], ["set", "-g", "history-limit", "20000"],
|
|
117
|
+
// No prefix key: every key goes to the agent, except the ones bound below.
|
|
118
|
+
["set", "-g", "prefix", "None"], ["set", "-g", "prefix2", "None"],
|
|
119
|
+
["set", "-g", "mouse", "on"], ["set", "-g", "escape-time", "10"], ["set", "-g", "focus-events", "on"],
|
|
120
|
+
["set", "-g", "status", "on"], ["set", "-g", "status-style", "bg=default,fg=colour244"],
|
|
121
|
+
["set", "-g", "status-left", "#[bold,fg=colour223] SELDON #[default]"], ["set", "-g", "status-left-length", "12"],
|
|
122
|
+
["set", "-g", "status-right", "Alt-1β¦9 agent Β· Alt-n next β Β· Alt-s list Β· Alt-h home Β· Alt-q leave "],
|
|
123
|
+
["set", "-g", "status-right-length", "90"], ["set", "-g", "window-status-format", ""], ["set", "-g", "window-status-current-format", ""],
|
|
124
|
+
["set", "-g", "pane-border-style", "fg=colour238"], ["set", "-g", "pane-active-border-style", "fg=colour238"],
|
|
125
|
+
["set-environment", "-g", "SELDON_WS", "1"],
|
|
126
|
+
// One pane fills a small screen; both show on a wide one. Re-checked whenever a screen attaches or resizes.
|
|
127
|
+
["set-hook", "-g", "client-attached", line("fit")], ["set-hook", "-g", "client-resized", line("fit")],
|
|
128
|
+
// Alt-<key> directly, and Ctrl-g then <key> for terminals that do not send Alt (macOS
|
|
129
|
+
// Terminal and iTerm2 need "Option as Meta" turned on).
|
|
130
|
+
["bind", "-n", "C-g", "switch-client", "-T", "seldon"],
|
|
131
|
+
];
|
|
132
|
+
const keys = { n: ["next"], s: ["list"], h: ["home"] };
|
|
133
|
+
for (let i = 1; i <= 9; i++) keys[i] = ["pick", i];
|
|
134
|
+
for (const [k, a] of Object.entries(keys)) {
|
|
135
|
+
cmds.push(["bind", "-n", `M-${k}`, ...argv(...a)], ["bind", "-T", "seldon", String(k), ...argv(...a)]);
|
|
136
|
+
}
|
|
137
|
+
cmds.push(["bind", "-n", "M-q", "detach-client"], ["bind", "-T", "seldon", "q", "detach-client"]);
|
|
138
|
+
// The session last, so both panes start with every option above already in force.
|
|
139
|
+
cmds.push(
|
|
140
|
+
["new-session", "-d", "-s", WS_SESSION, "-x", String(cols), "-y", String(rows), "-n", "seldon", "-e", "SELDON_WS=1", home],
|
|
141
|
+
["split-window", "-hb", "-t", `${WS_SESSION}:0`, "-l", String(SIDE_WIDTH), "-e", "SELDON_WS=1", `${self} ws sidebar`],
|
|
142
|
+
);
|
|
143
|
+
return cmds;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ---- drawing the list ------------------------------------------------------------------
|
|
147
|
+
const GLYPH = { "needs-you": "β", working: "β", running: "β", idle: "β", failed: "β", stopped: "Β·" };
|
|
148
|
+
const WORDS = { "needs-you": "needs you", working: "working", running: "running", idle: "idle", failed: "failed", stopped: "stopped" };
|
|
149
|
+
const cut = (s, w) => (s.length > w ? s.slice(0, Math.max(0, w - 1)) + "β¦" : s);
|
|
150
|
+
|
|
151
|
+
// The two lines of one agent, as plain cells the caller colours:
|
|
152
|
+
// { n, glyph, emoji, name, sub } β name and sub already cut to fit `width` columns.
|
|
153
|
+
// `emoji` comes from assignEmoji when several agents are drawn together.
|
|
154
|
+
export function rowCells(row, width = SIDE_WIDTH, ago = () => "", emoji = emojiFor(row.name)) {
|
|
155
|
+
const state = row.off ? "off" : row.state;
|
|
156
|
+
const where = row.machine ? ` @${row.machine}` : "";
|
|
157
|
+
const what = row.off ? `paused Β· ${row.machine} unreachable`
|
|
158
|
+
: row.state === "needs-you" ? `needs you Β· ${row.waitingFor || "input"}`
|
|
159
|
+
: [WORDS[row.state] || row.state, ago(row.startedAt)].filter(Boolean).join(" Β· ");
|
|
160
|
+
return {
|
|
161
|
+
n: row.n <= 9 ? String(row.n) : " ",
|
|
162
|
+
glyph: row.off ? "βΎ" : GLYPH[row.state] || "?",
|
|
163
|
+
emoji,
|
|
164
|
+
state,
|
|
165
|
+
name: cut(row.name, Math.max(6, width - 11)),
|
|
166
|
+
sub: cut(`${what} Β· ${row.harness}${where}`, Math.max(6, width - 8)),
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function wsHeadline(rows) {
|
|
171
|
+
const live = rows.filter((r) => !r.off);
|
|
172
|
+
const need = live.filter((r) => r.state === "needs-you").length;
|
|
173
|
+
const busy = live.filter((r) => r.state === "working" || r.state === "running").length;
|
|
174
|
+
return { need, busy, total: rows.length };
|
|
175
|
+
}
|
package/package.json
CHANGED
package/lib/serve.mjs
DELETED
|
@@ -1,241 +0,0 @@
|
|
|
1
|
-
// `seldon serve` β the panel as a phone app. Same lanes, same actions, a touch screen instead of
|
|
2
|
-
// a terminal. It owns nothing: it reads what the panel reads (readLanes, bifrost's machines) and
|
|
3
|
-
// acts through the same functions `seldon lane β¦` uses, locally or over `ssh <machine> seldon β¦`.
|
|
4
|
-
//
|
|
5
|
-
// Reach it from a phone with `tailscale serve`: HTTPS, the tailnet's identity on every request,
|
|
6
|
-
// no port on the internet. On its own it listens on loopback only.
|
|
7
|
-
//
|
|
8
|
-
// Pure rules first (tested without a server), then the I/O.
|
|
9
|
-
import { createServer } from "node:http";
|
|
10
|
-
import { readFileSync, writeFileSync, mkdirSync, chmodSync } from "node:fs";
|
|
11
|
-
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
12
|
-
import { execFile } from "node:child_process";
|
|
13
|
-
import { join, dirname } from "node:path";
|
|
14
|
-
import { fileURLToPath } from "node:url";
|
|
15
|
-
import { readLanes, readPlan, addToPlan, projectRoot, SELDON_HOME } from "./agents.mjs";
|
|
16
|
-
import { startLane, stopLane, resumeLane, removeLane, findLane, allLanes } from "./actions.mjs";
|
|
17
|
-
import { listMachines, fetchLanes, remoteGroups, sshArgs } from "./machines.mjs";
|
|
18
|
-
import { listHolds } from "./holds-store.mjs";
|
|
19
|
-
import { headline } from "./home.mjs";
|
|
20
|
-
import { HARNESSES, laneForItem, stopCommand, resumeCommands } from "./lanes.mjs";
|
|
21
|
-
|
|
22
|
-
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
23
|
-
|
|
24
|
-
// ---- pure ---------------------------------------------------------------------------
|
|
25
|
-
// "mini/claude:ab12" β { machine: "mini", key: "claude:ab12" }; local keys have no slash.
|
|
26
|
-
export function splitKey(key) {
|
|
27
|
-
const s = String(key || "");
|
|
28
|
-
const i = s.indexOf("/");
|
|
29
|
-
return i > 0 && !s.slice(0, i).includes(":") ? { machine: s.slice(0, i), key: s.slice(i + 1) } : { machine: null, key: s };
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
// Who may talk to it:
|
|
33
|
-
// - the Host is loopback or a tailnet name (a DNS-rebinding page can pose as neither), and a
|
|
34
|
-
// tailnet name only when it was started with --tailnet (`tailnet`): a `tailscale serve`
|
|
35
|
-
// mapping left over from an earlier run reaches nothing;
|
|
36
|
-
// - on the tailnet, the login tailscale serve stamps on the request must be the owner;
|
|
37
|
-
// - every /api call, reads too, carries the token. That also stops cross-site pages: they
|
|
38
|
-
// can't read it, and can't set a custom header without a CORS preflight nobody answers.
|
|
39
|
-
// The page itself (/) is static and holds no data, so it loads without one.
|
|
40
|
-
export function guard({ path, host, headers }, { token, owner = null, tailnet = false } = {}) {
|
|
41
|
-
const h = String(host || "").replace(/:\d+$/, "").toLowerCase();
|
|
42
|
-
const local = h === "localhost" || h === "127.0.0.1" || h === "[::1]";
|
|
43
|
-
if (!local && !h.endsWith(".ts.net")) return "host not allowed";
|
|
44
|
-
if (!local && !tailnet) return "not served on the tailnet (start with: seldon serve --tailnet)";
|
|
45
|
-
if (!local && (!owner || headers["tailscale-user-login"] !== owner)) return "not the owner";
|
|
46
|
-
if (String(path).startsWith("/api/") && !tokenOk(headers["x-seldon-token"], token)) return "bad or missing token";
|
|
47
|
-
return null;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export function tokenOk(given, token) {
|
|
51
|
-
if (!token || typeof given !== "string") return false;
|
|
52
|
-
const a = Buffer.from(given), b = Buffer.from(token);
|
|
53
|
-
return a.length === b.length && timingSafeEqual(a, b);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
// The tailnet login of this machine's user: who --tailnet lets in when --owner is not given.
|
|
57
|
-
export function ownerFromStatus(status) {
|
|
58
|
-
const id = status?.Self?.UserID;
|
|
59
|
-
return (id != null && status?.User?.[String(id)]?.LoginName) || null;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
// Keys a phone may press into an agent. A whitelist, so a reply can't smuggle tmux syntax.
|
|
63
|
-
export const REPLY_KEYS = { enter: "Enter", esc: "Escape", up: "Up", down: "Down", tab: "Tab", "ctrl-c": "C-c" };
|
|
64
|
-
// `submit: false` types without Enter: a menu key ("1") already chooses, and an Enter after it
|
|
65
|
-
// would answer whatever the agent asks next.
|
|
66
|
-
export function replyArgs(session, { key, text, submit = true } = {}) {
|
|
67
|
-
if (!session) return null;
|
|
68
|
-
if (key && REPLY_KEYS[key]) return [["send-keys", "-t", session, REPLY_KEYS[key]]];
|
|
69
|
-
if (typeof text === "string" && text.length && text.length <= 2000)
|
|
70
|
-
return [["send-keys", "-t", session, "-l", text], ...(submit ? [["send-keys", "-t", session, "Enter"]] : [])];
|
|
71
|
-
return null;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
// What a phone can do with a lane, so the UI never offers a button the server will refuse.
|
|
75
|
-
export function laneCaps(lane) {
|
|
76
|
-
const live = !["stopped", "failed"].includes(lane.state);
|
|
77
|
-
return {
|
|
78
|
-
peek: !!lane.tmuxSession && live,
|
|
79
|
-
reply: !!lane.tmuxSession && live,
|
|
80
|
-
stop: live && !stopCommand(lane).why,
|
|
81
|
-
resume: !live && !resumeCommands(lane).why,
|
|
82
|
-
rm: !live,
|
|
83
|
-
// Claude background lanes live under Claude's own supervisor: no tmux pane to read.
|
|
84
|
-
// Claude's Remote Control (claude.ai/code, the Claude app) is the way in for those.
|
|
85
|
-
hint: !lane.tmuxSession && lane.harness === "claude" && live
|
|
86
|
-
? (lane.id ? `claude attach ${lane.id}` : "open it in its terminal, or with Claude Remote Control") : null,
|
|
87
|
-
};
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
// ---- I/O ----------------------------------------------------------------------------
|
|
91
|
-
const sh = (bin, args, timeout = 10_000) => new Promise((res) =>
|
|
92
|
-
execFile(bin, args, { timeout, encoding: "utf8", maxBuffer: 4 << 20 }, (err, stdout, stderr) =>
|
|
93
|
-
res({ ok: !err, out: stdout || "", error: err ? (String(stderr).trim().split("\n").pop() || err.message) : null })));
|
|
94
|
-
|
|
95
|
-
// Machines are asked in the background, like the panel does, so a sleeping one never stalls a
|
|
96
|
-
// request. The cache is what the API answers from.
|
|
97
|
-
function remoteCache(intervalMs = 10_000) {
|
|
98
|
-
const state = new Map(); // name β { machine, lanes, error, at }
|
|
99
|
-
const poll = () => {
|
|
100
|
-
for (const m of listMachines()) fetchLanes(m, (r) => state.set(m.name, { machine: m, ...r, at: Date.now() }));
|
|
101
|
-
};
|
|
102
|
-
poll();
|
|
103
|
-
const t = setInterval(poll, intervalMs); t.unref();
|
|
104
|
-
return {
|
|
105
|
-
groups: () => [...state.values()].filter((s) => s.lanes).flatMap((s) => remoteGroups({ ...s.machine }, s.lanes)),
|
|
106
|
-
machines: () => listMachines().map((m) => {
|
|
107
|
-
const s = state.get(m.name);
|
|
108
|
-
return { name: m.name, host: m.host, ok: !!s?.lanes, error: s?.error || (s ? null : "askingβ¦"), count: s?.lanes?.length ?? 0, at: s?.at ?? null };
|
|
109
|
-
}),
|
|
110
|
-
get: (name) => state.get(name),
|
|
111
|
-
refresh: poll,
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
function snapshot(remote) {
|
|
116
|
-
const local = readLanes().map((g) => ({ ...g, machine: null }));
|
|
117
|
-
const groups = [...local, ...remote.groups()];
|
|
118
|
-
for (const g of groups) for (const l of g.lanes) l.caps = laneCaps(l);
|
|
119
|
-
return { headline: headline(groups), groups, machines: remote.machines(), holds: listHolds(), at: Date.now() };
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
function laneByKey(remote, fullKey) {
|
|
123
|
-
const { machine, key } = splitKey(fullKey);
|
|
124
|
-
if (!machine) { const lane = findLane(key); return lane ? { lane, machine: null } : null; }
|
|
125
|
-
const s = remote.get(machine);
|
|
126
|
-
const lane = s?.lanes?.find((l) => l.key === key);
|
|
127
|
-
return lane ? { lane, machine: s.machine } : null;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
// One verb, wherever the lane lives.
|
|
131
|
-
async function act(remote, verb, fullKey, opts = {}) {
|
|
132
|
-
const found = laneByKey(remote, fullKey);
|
|
133
|
-
if (!found) return { ok: false, error: "no such lane (it may have just ended)" };
|
|
134
|
-
const { lane, machine } = found;
|
|
135
|
-
if (machine) {
|
|
136
|
-
const r = await sh("ssh", sshArgs(machine, ["seldon", "lane", verb, lane.key, ...(opts.force ? ["--force"] : [])]), 30_000);
|
|
137
|
-
remote.refresh();
|
|
138
|
-
return r.ok ? { ok: true } : { ok: false, error: r.error };
|
|
139
|
-
}
|
|
140
|
-
const r = verb === "stop" ? stopLane(lane) : verb === "resume" ? resumeLane(lane) : removeLane(lane, { force: !!opts.force });
|
|
141
|
-
return r.why ? { ok: false, error: r.why } : r;
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
async function tmuxOn(machine, args) {
|
|
145
|
-
return machine ? sh("ssh", sshArgs(machine, ["tmux", ...args])) : sh("tmux", args);
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
async function peek(remote, fullKey, lines = 60) {
|
|
149
|
-
const found = laneByKey(remote, fullKey);
|
|
150
|
-
if (!found?.lane.tmuxSession) return { ok: false, error: "no screen to read for this lane" };
|
|
151
|
-
const r = await tmuxOn(found.machine, ["capture-pane", "-p", "-J", "-t", found.lane.tmuxSession, "-S", `-${Math.min(400, lines)}`]);
|
|
152
|
-
return r.ok ? { ok: true, screen: r.out.replace(/\s+$/, "") } : r;
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
async function reply(remote, fullKey, body) {
|
|
156
|
-
const found = laneByKey(remote, fullKey);
|
|
157
|
-
const steps = replyArgs(found?.lane.tmuxSession, body);
|
|
158
|
-
if (!steps) return { ok: false, error: "nothing to send, or no pane to send it to" };
|
|
159
|
-
for (const args of steps) { const r = await tmuxOn(found.machine, args); if (!r.ok) return r; }
|
|
160
|
-
return { ok: true };
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
async function start(remote, { root, machine, task, agent = "claude" }) {
|
|
164
|
-
if (!HARNESSES.includes(agent)) return { ok: false, error: `unknown agent ${agent}` };
|
|
165
|
-
if (machine) {
|
|
166
|
-
const m = remote.get(machine)?.machine;
|
|
167
|
-
if (!m) return { ok: false, error: `unknown machine ${machine}` };
|
|
168
|
-
const r = await sh("ssh", sshArgs(m, ["seldon", "lane", "start", root, "--task", task, "--agent", agent]), 30_000);
|
|
169
|
-
remote.refresh();
|
|
170
|
-
return r.ok ? { ok: true } : { ok: false, error: r.error };
|
|
171
|
-
}
|
|
172
|
-
const dir = projectRoot(root) || root;
|
|
173
|
-
return startLane({ root: dir, name: dir.split("/").pop(), task, harness: agent });
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
// The open plan, each item with the lane already on it (the panel's own matching rule).
|
|
177
|
-
async function plan(remote, { root, machine }) {
|
|
178
|
-
const withLanes = (items, lanes) => items && items.map((it) => ({ ...it, lane: laneForItem(it, lanes)?.name ?? null }));
|
|
179
|
-
if (!machine) return { ok: true, items: withLanes(readPlan(root), allLanes()) };
|
|
180
|
-
const s = remote.get(machine);
|
|
181
|
-
if (!s) return { ok: false, error: `unknown machine ${machine}` };
|
|
182
|
-
const r = await sh("ssh", sshArgs(s.machine, ["foundation", "queue", "--list", "--json", "--dir", root]));
|
|
183
|
-
const line = r.out.split("\n").reverse().find((l) => l.trim().startsWith("["));
|
|
184
|
-
try { return { ok: true, items: withLanes(line ? JSON.parse(line) : null, s.lanes || []) }; } catch { return { ok: true, items: null }; }
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
const readBody = (req) => new Promise((res) => {
|
|
188
|
-
let raw = ""; req.on("data", (c) => { raw += c; if (raw.length > 64_000) req.destroy(); });
|
|
189
|
-
req.on("end", () => { try { res(JSON.parse(raw || "{}")); } catch { res({}); } });
|
|
190
|
-
});
|
|
191
|
-
|
|
192
|
-
// The token, made once and kept owner-only (0600). Delete the file to change it.
|
|
193
|
-
export function serveToken(home = SELDON_HOME) {
|
|
194
|
-
const file = join(home, "serve-token");
|
|
195
|
-
try { const t = readFileSync(file, "utf8").trim(); if (t.length >= 32) return t; } catch { /* first run */ }
|
|
196
|
-
const t = randomBytes(24).toString("base64url");
|
|
197
|
-
mkdirSync(home, { recursive: true });
|
|
198
|
-
writeFileSync(file, t + "\n", { mode: 0o600 }); chmodSync(file, 0o600);
|
|
199
|
-
return t;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
export function serve({ port = 7930, token, owner = null, tailnet = false, allowReply = false } = {}) {
|
|
203
|
-
if (!token) throw new Error("seldon serve needs a token");
|
|
204
|
-
if (tailnet && !owner) throw new Error("seldon serve --tailnet needs an owner");
|
|
205
|
-
const remote = remoteCache();
|
|
206
|
-
const page = () => readFileSync(join(HERE, "web", "index.html"), "utf8"); // re-read: edit + reload
|
|
207
|
-
const send = (res, code, body, type = "application/json") => {
|
|
208
|
-
res.writeHead(code, { "content-type": type, "cache-control": "no-store", "x-content-type-options": "nosniff",
|
|
209
|
-
"referrer-policy": "no-referrer", "x-frame-options": "DENY" });
|
|
210
|
-
res.end(type === "application/json" ? JSON.stringify(body) : body);
|
|
211
|
-
};
|
|
212
|
-
const server = createServer(async (req, res) => {
|
|
213
|
-
const url = new URL(req.url, "http://x");
|
|
214
|
-
const denied = guard({ path: url.pathname, host: req.headers.host, headers: req.headers }, { token, owner, tailnet });
|
|
215
|
-
if (denied) return send(res, 403, { ok: false, error: denied });
|
|
216
|
-
try {
|
|
217
|
-
if (req.method === "GET" && url.pathname === "/") return send(res, 200, page(), "text/html; charset=utf-8");
|
|
218
|
-
if (req.method === "GET" && url.pathname === "/manifest.webmanifest")
|
|
219
|
-
return send(res, 200, JSON.stringify({ name: "seldon", short_name: "seldon", display: "standalone", start_url: "/", background_color: "#0e0f0c", theme_color: "#0e0f0c" }), "application/manifest+json");
|
|
220
|
-
if (req.method === "GET" && url.pathname === "/api/state") return send(res, 200, { ...snapshot(remote), allowReply });
|
|
221
|
-
if (req.method === "GET" && url.pathname === "/api/peek") return send(res, 200, await peek(remote, url.searchParams.get("key")));
|
|
222
|
-
if (req.method === "GET" && url.pathname === "/api/plan")
|
|
223
|
-
return send(res, 200, await plan(remote, { root: url.searchParams.get("root"), machine: url.searchParams.get("machine") || null }));
|
|
224
|
-
if (req.method === "POST") {
|
|
225
|
-
const body = await readBody(req);
|
|
226
|
-
const m = url.pathname.match(/^\/api\/lane\/(stop|resume|rm)$/);
|
|
227
|
-
if (m) return send(res, 200, await act(remote, m[1], body.key, body));
|
|
228
|
-
if (url.pathname === "/api/lane/start") return send(res, 200, await start(remote, body));
|
|
229
|
-
if (url.pathname === "/api/lane/reply") {
|
|
230
|
-
if (!allowReply) return send(res, 403, { ok: false, error: "replies are off β start with: seldon serve --allow-reply" });
|
|
231
|
-
return send(res, 200, await reply(remote, body.lane, body));
|
|
232
|
-
}
|
|
233
|
-
if (url.pathname === "/api/plan/add" && !body.machine && body.root && body.text)
|
|
234
|
-
return send(res, 200, addToPlan(body.root, String(body.text).slice(0, 500), body.priority || "P2"));
|
|
235
|
-
}
|
|
236
|
-
send(res, 404, { ok: false, error: "not found" });
|
|
237
|
-
} catch (e) { send(res, 500, { ok: false, error: e.message }); }
|
|
238
|
-
});
|
|
239
|
-
server.listen(port, "127.0.0.1");
|
|
240
|
-
return server;
|
|
241
|
-
}
|