@gorlitzer-labs/seldon 0.11.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -74,6 +74,8 @@ recorded in `~/.seldon/lanes.json`. A plan item shows the lane working on it.
74
74
  seldon lanes [--json] # every agent here
75
75
  seldon lane start [dir] --task "fix the save crash" [--agent codex]
76
76
  seldon lane stop|resume|open <name or key>
77
+ seldon lane rm <name or key> [--force] # a stopped lane: its worktree goes,
78
+ # its branch too if git sees it merged
77
79
  ```
78
80
 
79
81
  ## Codex and opencode: let them report their state
@@ -132,6 +134,40 @@ seldon machines # each one, and whether it an
132
134
  - **From a phone:** `ssh` to any one machine and run `seldon`. Below 70 columns it switches to
133
135
  one line per lane.
134
136
 
137
+ ## On your phone — `seldon serve`
138
+
139
+ The panel as a web app, for a phone (or any browser). Same lanes, same actions, a touch screen
140
+ instead of a terminal: what needs you first, the agent's screen, quick replies, stop / resume /
141
+ remove, new lanes and the plan, for this machine and every machine in `seldon machines`.
142
+
143
+ ```bash
144
+ seldon serve # http://localhost:7930/#t=<token> on this machine only
145
+ seldon serve --tailnet # + HTTPS on your tailnet, for your tailscale login only
146
+ seldon serve --tailnet --owner you@example.com # a different login than this machine's
147
+ seldon serve --allow-reply # let the phone type into agents (off by default)
148
+ ```
149
+
150
+ - **Nothing is open by default.** It listens on loopback only. `--tailnet` puts it behind
151
+ `tailscale serve` (HTTPS, tailnet-only, never the internet, on its own port 8443 so it never
152
+ takes `/` from the voice) and lets in exactly one login: `--owner`, or this machine's
153
+ tailscale user. If it can't tell whose it is, it does not go on the tailnet. Undo with
154
+ `tailscale serve --https=8443 off`.
155
+ - **A token on every call.** The first run makes one in `~/.seldon/serve-token` (0600). Every
156
+ API call, reads included, needs it; the phone gets it once from the link `serve` prints,
157
+ keeps it, and takes it out of the address bar. `rm ~/.seldon/serve-token` for a new one —
158
+ every device has to open the new link.
159
+ - **A leftover tailnet mapping reaches nothing.** Started without `--tailnet`, it refuses every
160
+ request that comes in by a `*.ts.net` name.
161
+ - **Replies are off unless `--allow-reply`,** and are a whitelist of keys or literal text. A
162
+ menu key ("1") is sent without Enter.
163
+ - **What it can read:** lanes in tmux (Codex, opencode, and Claude lanes seldon started) show
164
+ their screen and take replies. An interactive Claude session in a plain terminal has no pane
165
+ to read: open it with `claude attach`, or from the Claude app with Remote Control.
166
+ - **It acts with this machine's ssh keys:** a lane on another machine is stopped or started by
167
+ `ssh <machine> seldon lane …`, so whoever gets in reaches those machines' lanes too.
168
+ - **Alerts:** while the page is open, the phone buzzes and notifies when an agent starts
169
+ needing you.
170
+
135
171
  ## Holds — taking turns on shared things
136
172
 
137
173
  Agents on different projects share one machine: one boots the Android emulator, another
package/bin/seldon.js CHANGED
@@ -10,9 +10,10 @@ import { MODULES, byId, DEPS, RAW, MONOREPO, withRequires, platformOk } from "..
10
10
  import { ensureSiblingPath, loadState, resolveProject, adopt as fAdopt, staff as fStaff, attach as fAttach, hiveOf, sameDir } from "../lib/projects.mjs";
11
11
  import { readLanes, readPlan, addToPlan, projectRoot, writeReport } from "../lib/agents.mjs";
12
12
  import { openCommand, stopCommand, transitions, laneForItem, slugify, HARNESSES } from "../lib/lanes.mjs";
13
- import { startLane, stopLane, resumeLane, findLane } from "../lib/actions.mjs";
13
+ import { startLane, stopLane, resumeLane, removeLane, findLane } from "../lib/actions.mjs";
14
14
  import { listMachines, addMachine, fetchLanes, remoteGroups, sshArgs, lastJsonLine } from "../lib/machines.mjs";
15
15
  import { notify } from "../lib/notify.mjs";
16
+ import { serve, serveToken, ownerFromStatus } from "../lib/serve.mjs";
16
17
  import { reportFromEvent, mergeCodexHooks, removeCodexHooks, opencodePlugin } from "../lib/reports.mjs";
17
18
  import { buildRows, headline, ago, laneDetail, unlistedAgents, GLYPH } from "../lib/home.mjs";
18
19
  import { parseDuration, describe as describeHold, NAME_RE, DEFAULT_FOR_MS } from "../lib/holds.mjs";
@@ -523,11 +524,11 @@ function tailscaleBin() {
523
524
  }
524
525
  return null;
525
526
  }
526
- function tailnetDnsName(ts) {
527
- try {
528
- const d = JSON.parse(execSync(`${ts} status --json`, { stdio: ["ignore", "pipe", "ignore"], timeout: 15000 }).toString());
529
- return ((d.Self && d.Self.DNSName) || "").replace(/\.$/, "");
530
- } catch { return null; }
527
+ function tailscaleStatus(ts) {
528
+ try { return JSON.parse(execSync(`${ts} status --json`, { stdio: ["ignore", "pipe", "ignore"], timeout: 15000 }).toString()); } catch { return null; }
529
+ }
530
+ function tailnetDnsName(ts, status = tailscaleStatus(ts)) {
531
+ return status ? ((status.Self && status.Self.DNSName) || "").replace(/\.$/, "") : null;
531
532
  }
532
533
  function tailscaleServeUrl() {
533
534
  const ts = tailscaleBin(); if (!ts) return null;
@@ -1431,6 +1432,7 @@ ${C.bold("seldon")} — the agent factory: your projects, and the stack that run
1431
1432
  Idempotent, and it prints every step it skipped. Run it from inside a repo.
1432
1433
  ${C.bold("seldon up")} start the stack (voice + supervisor) and print where to go
1433
1434
  ${C.bold("seldon up --tailnet")} expose the voice over HTTPS (tailscale serve) so the mic works on your phone
1435
+ ${C.bold("seldon serve")} [--tailnet] the panel as a phone web app (--allow-reply to answer agents)
1434
1436
  ${C.bold("seldon up --brain=X")} pick the voice brain: qwen (in-process) | bonsai (local server); remembered
1435
1437
  ${C.bold("seldon status")} what's running · ${C.bold("seldon down")} stop it
1436
1438
  ${C.bold("seldon adopt")} [dir] put an existing repo on the line: foundation docs (never overwritten),
@@ -1505,7 +1507,7 @@ function laneCmd(verb, arg, flags) {
1505
1507
  const r = startLane({ root, name: path.basename(root), task, harness: flags.agent || "claude" });
1506
1508
  return r.ok ? console.log(C.green(`✓ started ${r.slug}`) + C.dim(` (${flags.agent || "claude"}) in ${root}`)) : fail(`could not start: ${r.error}`);
1507
1509
  }
1508
- if (!["stop", "resume", "open"].includes(verb)) return fail('usage: seldon lane start [dir] --task "…" [--agent claude|codex|opencode] · seldon lane stop|resume|open <key>');
1510
+ if (!["stop", "resume", "open", "rm"].includes(verb)) return fail('usage: seldon lane start [dir] --task "…" [--agent claude|codex|opencode] · seldon lane stop|resume|open|rm <key>');
1509
1511
  const lane = arg && findLane(arg);
1510
1512
  if (!lane) return fail(`no lane ${arg || ""} — see: seldon lanes`);
1511
1513
  if (verb === "open") {
@@ -1514,12 +1516,44 @@ function laneCmd(verb, arg, flags) {
1514
1516
  process.exitCode = spawnSync(how.bin, how.args, { stdio: "inherit", cwd: how.cwd }).status ?? 1;
1515
1517
  return;
1516
1518
  }
1519
+ if (verb === "rm") {
1520
+ const r = removeLane(lane, { force: !!flags.force });
1521
+ if (r.why) return fail(`can't remove ${lane.name}: ${r.why}`);
1522
+ if (!r.ok) return fail(`rm failed: ${r.error}`);
1523
+ return console.log(C.green(`✓ removed ${lane.name}`) + C.dim(!r.branch ? "" : r.branchDeleted ? ` (merged branch ${r.branch} deleted too)`
1524
+ : ` (kept branch ${r.branch}: git does not see it merged; if it was squash-merged: git branch -D ${r.branch})`));
1525
+ }
1517
1526
  const r = verb === "stop" ? stopLane(lane) : resumeLane(lane);
1518
1527
  if (r.why) return fail(`can't ${verb} ${lane.name}: ${r.why}`);
1519
1528
  if (!r.ok) return fail(`${verb} failed: ${r.error}`);
1520
1529
  console.log(C.green(`✓ ${verb === "stop" ? "stopped" : "resumed"} ${lane.name}`) + (r.fresh ? C.dim(" (new conversation, same task + worktree)") : ""));
1521
1530
  }
1522
1531
 
1532
+ // `seldon serve` — the panel for a phone. Loopback only, and every call needs the token.
1533
+ // `--tailnet` puts it behind `tailscale serve` (HTTPS, its own port so it never takes the
1534
+ // voice's /) and only ever for one login: --owner, or this machine's tailscale user.
1535
+ const SERVE_TAILNET_PORT = 8443;
1536
+ function serveCmd(flags) {
1537
+ const port = Number(flags.port) || 7930;
1538
+ const allowReply = !!flags["allow-reply"];
1539
+ const token = serveToken();
1540
+ let owner = null, dns = null, ts = null;
1541
+ if (flags.tailnet) {
1542
+ ts = tailscaleBin(); const status = ts && tailscaleStatus(ts);
1543
+ dns = tailnetDnsName(ts, status);
1544
+ owner = typeof flags.owner === "string" ? flags.owner : ownerFromStatus(status);
1545
+ if (!dns || !owner) { console.log(C.red(" not serving on the tailnet: " + (!dns ? "tailscale not found or not connected" : "can't tell whose it is — pass --owner you@example.com"))); process.exitCode = 1; return; }
1546
+ }
1547
+ serve({ port, token, owner, tailnet: !!flags.tailnet, allowReply });
1548
+ console.log(C.green(`✓ seldon serve`) + C.dim(` on http://localhost:${port}/#t=${token}`) + (allowReply ? C.gold(" · replies ON (the phone can type into agents)") : ""));
1549
+ if (!flags.tailnet) { console.log(C.dim(` for your phone: seldon serve --tailnet (HTTPS on your tailnet, only for your login)`)); return; }
1550
+ try {
1551
+ execSync(`${ts} serve --bg --https=${SERVE_TAILNET_PORT} http://127.0.0.1:${port}`, { stdio: "ignore", timeout: 30000 });
1552
+ console.log(C.green(` phone → https://${dns}:${SERVE_TAILNET_PORT}/#t=${token}`) + C.dim(` only for ${owner} · open it once, then add to home screen`));
1553
+ console.log(C.dim(` undo: tailscale serve --https=${SERVE_TAILNET_PORT} off · new token: rm ~/.seldon/serve-token`));
1554
+ } catch (e) { console.log(C.red(" tailscale serve failed: " + ((e.stderr || e.message || "").toString().split("\n")[0]))); }
1555
+ }
1556
+
1523
1557
  // `seldon machines` — the other computers the panel shows (bifrost's realms, one list).
1524
1558
  function machinesCmd(verb, name, target) {
1525
1559
  if (verb === "add") {
@@ -1646,7 +1680,7 @@ function holdsCmd() {
1646
1680
  // (`--no-attach`). The value form has to be CONSUMED: filtering out everything starting with
1647
1681
  // `--` and keeping the rest as positionals read `seldon go --agent claude` as the project
1648
1682
  // named "claude".
1649
- const VALUE_FLAGS = new Set(["agent", "model", "effort", "name", "port", "pm", "stall", "dir", "for", "wait", "as", "note", "interval", "task"]);
1683
+ const VALUE_FLAGS = new Set(["agent", "model", "effort", "name", "port", "pm", "stall", "dir", "for", "wait", "as", "note", "interval", "task", "owner"]);
1650
1684
  function parseArgv(raw) {
1651
1685
  const flags = {}, positional = [];
1652
1686
  for (let i = 0; i < raw.length; i++) {
@@ -1700,6 +1734,7 @@ const ids = tokens.filter((id) => byId[id]); // only the valid module
1700
1734
  if (cmd === "lanes") return lanesCmd(flags);
1701
1735
  if (cmd === "machines") return machinesCmd(tokens[0], tokens[1], tokens[2]);
1702
1736
  if (cmd === "lane") return laneCmd(tokens[0], tokens[1], flags);
1737
+ if (cmd === "serve") return serveCmd(flags);
1703
1738
  if (cmd === "setup") return setupCmd(tokens[0], flags);
1704
1739
  if (cmd === "panel" || cmd === "board") return panel();
1705
1740
  if (cmd && cmd !== "install") { help(); process.exitCode = 1; return; }
package/lib/actions.mjs CHANGED
@@ -1,13 +1,13 @@
1
- // What you can do to a lane, in one place: start, stop, resume. The panel calls these, and so
1
+ // What you can do to a lane, in one place: start, stop, resume, remove. The panel calls these, and so
2
2
  // does `seldon lane …` — which is also how the panel acts on another machine (it runs
3
3
  // `ssh <machine> seldon lane …`). One implementation, so the two can never disagree.
4
4
  import { join } from "node:path";
5
5
  import { existsSync } from "node:fs";
6
6
  import { execFileSync } from "node:child_process";
7
7
  import {
8
- readLanes, runSteps, run, harnessBins, recordLane, markLane, SELDON_HOME,
8
+ readLanes, runSteps, run, harnessBins, recordLane, markLane, forgetLane, projectRoot, SELDON_HOME,
9
9
  } from "./agents.mjs";
10
- import { startCommands, resumeCommands, stopCommand, slugify, uniqueSlug, HARNESSES } from "./lanes.mjs";
10
+ import { startCommands, resumeCommands, stopCommand, removeCommands, slugify, uniqueSlug, HARNESSES } from "./lanes.mjs";
11
11
 
12
12
  const branchExists = (root, ref) => {
13
13
  try { execFileSync("git", ["-C", root, "rev-parse", "--verify", "--quiet", `refs/heads/${ref}`], { stdio: "ignore" }); return true; } catch { return false; }
@@ -45,6 +45,18 @@ export function resumeLane(lane) {
45
45
  return { ...r, fresh: !!how.fresh };
46
46
  }
47
47
 
48
+ // Worktree gone, branch deleted only if merged. Says which branch it kept, and why.
49
+ export function removeLane(lane, { force = false } = {}) {
50
+ const git = (...args) => { try { return execFileSync("git", ["-C", lane.cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); } catch { return null; } };
51
+ const how = removeCommands(lane, { root: projectRoot(lane.cwd), branch: git("rev-parse", "--abbrev-ref", "HEAD"), dirty: !!git("status", "--porcelain"), force });
52
+ if (how.why) return { ok: false, why: how.why };
53
+ const r = runSteps(how.cmds);
54
+ if (!r.ok) return r;
55
+ if (lane.tmuxSession && lane.harness !== "claude") forgetLane(lane.tmuxSession);
56
+ const branch = how.branch?.args.at(-1) ?? null;
57
+ return { ok: true, branch, branchDeleted: !!how.branch && run(how.branch, { quiet: true }).ok };
58
+ }
59
+
48
60
  export const allLanes = () => readLanes().flatMap((g) => g.lanes);
49
61
  // By key, or by name when exactly one lane has it (keys are long; names are what you see).
50
62
  export function findLane(ref) {
package/lib/agents.mjs CHANGED
@@ -67,6 +67,11 @@ export function markLane(session, patch) {
67
67
  writeLanes(readJson(LANES_FILE, []).map((e) => (e.session === session ? { ...e, ...patch } : e)));
68
68
  }
69
69
 
70
+ // Removed: the lane is gone for good, so it is not listed as stopped either.
71
+ export function forgetLane(session) {
72
+ writeLanes(readJson(LANES_FILE, []).filter((e) => e.session !== session));
73
+ }
74
+
70
75
  // tmux session -> { harness, task, startedAt }: seldon's lanes plus apiary's Codex agents.
71
76
  export function knownSessions() {
72
77
  const known = {};
package/lib/lanes.mjs CHANGED
@@ -233,6 +233,20 @@ export function resumeCommands(lane, { bins = {}, env = {} } = {}) {
233
233
  };
234
234
  }
235
235
 
236
+ // ---- removing a finished lane ------------------------------------------------------
237
+ // What a done lane leaves behind is a worktree and a branch. rm takes the worktree, and the
238
+ // branch only when git can see it is merged (`git branch -d` refuses otherwise). A squash-merged
239
+ // branch looks unmerged to git, so it is kept and named, never force-deleted.
240
+ export function removeCommands(lane, { root, branch, dirty = false, force = false } = {}) {
241
+ if (!["stopped", "failed"].includes(lane.state)) return { why: `it is ${lane.state}, stop it first` };
242
+ if (!root || !lane.cwd || lane.cwd.replace(/\/+$/, "") === root.replace(/\/+$/, "")) return { why: "it works in the repo itself, not in a worktree of its own" };
243
+ if (dirty && !force) return { why: "its worktree has uncommitted changes: commit them, or --force to throw them away" };
244
+ return {
245
+ cmds: [{ bin: "git", args: ["-C", root, "worktree", "remove", ...(force ? ["--force"] : []), lane.cwd], quiet: true }],
246
+ branch: branch && branch !== "HEAD" ? { bin: "git", args: ["-C", root, "branch", "-d", branch], quiet: true } : null,
247
+ };
248
+ }
249
+
236
250
  // ---- telling the human ----------------------------------------------------------------
237
251
  // What changed since the last look that a person should hear about: an agent that starts
238
252
  // waiting on them, fails, or finishes. Only TRANSITIONS — a lane that stays blocked is not
package/lib/serve.mjs ADDED
@@ -0,0 +1,241 @@
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
+ }
@@ -0,0 +1,351 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
6
+ <meta name="theme-color" content="#0e0f0c">
7
+ <meta name="apple-mobile-web-app-capable" content="yes">
8
+ <link rel="manifest" href="/manifest.webmanifest">
9
+ <title>seldon</title>
10
+ <style>
11
+ :root {
12
+ --bg: #f4f2ec; --card: #fffdf8; --ink: #1b1c18; --mute: #6d6c64; --line: #e2dfd5;
13
+ --need: #c2410c; --need-bg: #fdecdf; --work: #2f7d4f; --idle: #8b8a80; --fail: #b42318; --accent: #1b1c18;
14
+ --mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;
15
+ --sans: -apple-system, system-ui, "Segoe UI", Roboto, sans-serif;
16
+ --r: 14px; --safe-b: env(safe-area-inset-bottom, 0px);
17
+ }
18
+ @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) {
19
+ --bg: #0e0f0c; --card: #171814; --ink: #ecebe4; --mute: #8f8e85; --line: #2a2b25;
20
+ --need: #fb923c; --need-bg: #2a1a0e; --work: #5fbf86; --idle: #77766d; --fail: #f87171; --accent: #ecebe4;
21
+ } }
22
+ :root[data-theme="dark"] {
23
+ --bg: #0e0f0c; --card: #171814; --ink: #ecebe4; --mute: #8f8e85; --line: #2a2b25;
24
+ --need: #fb923c; --need-bg: #2a1a0e; --work: #5fbf86; --idle: #77766d; --fail: #f87171; --accent: #ecebe4;
25
+ }
26
+ * { box-sizing: border-box; }
27
+ html, body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.4 var(--sans); -webkit-text-size-adjust: 100%; }
28
+ button, input, textarea, select { font: inherit; color: inherit; }
29
+ button { cursor: pointer; }
30
+ .wrap { max-width: 640px; margin: 0 auto; padding: 0 16px calc(96px + var(--safe-b)); }
31
+
32
+ /* top */
33
+ header { position: sticky; top: 0; z-index: 5; background: color-mix(in srgb, var(--bg) 92%, transparent); backdrop-filter: blur(10px);
34
+ padding: calc(10px + env(safe-area-inset-top, 0px)) 0 10px; border-bottom: 1px solid var(--line); }
35
+ .top { display: flex; align-items: baseline; gap: 10px; }
36
+ .mark { font: 700 13px/1 var(--mono); letter-spacing: .28em; }
37
+ .head { flex: 1; min-width: 0; color: var(--mute); font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
38
+ .live { width: 8px; height: 8px; border-radius: 50%; background: var(--work); align-self: center; transition: opacity .3s; }
39
+ .live.stale { background: var(--fail); }
40
+ .chips { display: flex; gap: 8px; overflow-x: auto; margin-top: 10px; scrollbar-width: none; }
41
+ .chips::-webkit-scrollbar { display: none; }
42
+ .chip { flex: none; min-height: 44px; padding: 0 14px; border-radius: 999px; border: 1px solid var(--line); background: var(--card);
43
+ display: inline-flex; align-items: center; gap: 6px; font-size: 13px; }
44
+ .chip[aria-pressed="true"] { background: var(--accent); color: var(--bg); border-color: var(--accent); }
45
+ .chip .n { font: 600 12px var(--mono); }
46
+ .chip.need .n { color: var(--need); }
47
+ .chip[aria-pressed="true"].need .n { color: inherit; }
48
+ .chip .dot { width: 7px; height: 7px; }
49
+
50
+ .holds { margin: 12px 0 0; font: 12px var(--mono); color: var(--mute); }
51
+ .holds b { color: var(--ink); font-weight: 600; }
52
+
53
+ /* projects + lanes */
54
+ section.proj { margin-top: 18px; }
55
+ .ph { display: flex; align-items: center; gap: 8px; min-height: 44px; }
56
+ .ph h2 { margin: 0; font-size: 15px; font-weight: 650; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
57
+ .ph .at { font: 12px var(--mono); color: var(--mute); flex: none; }
58
+ .ph .sp { flex: 1; }
59
+ .ghost { min-height: 44px; min-width: 44px; padding: 0 12px; border: 0; background: none; color: var(--mute); font-size: 13px; border-radius: 10px; }
60
+ .ghost:active { background: var(--line); }
61
+ .card { background: var(--card); border: 1px solid var(--line); border-radius: var(--r); overflow: hidden; }
62
+ .lane { display: grid; grid-template-columns: 22px 1fr auto; gap: 2px 10px; align-items: center; width: 100%; text-align: left;
63
+ padding: 12px 14px; min-height: 60px; border: 0; background: none; border-top: 1px solid var(--line); }
64
+ .lane:first-child { border-top: 0; }
65
+ .lane:active { background: var(--line); }
66
+ .lane.needs-you { background: var(--need-bg); }
67
+ .lane .g { grid-row: span 2; display: grid; place-items: center; }
68
+ .lane .nm { min-width: 0; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
69
+ .lane .ag { font: 12px var(--mono); color: var(--mute); }
70
+ .lane .dt { grid-column: 2 / 4; min-width: 0; font-size: 13px; color: var(--mute); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
71
+ .lane.needs-you .dt { color: var(--need); font-weight: 600; }
72
+ .dot { width: 10px; height: 10px; border-radius: 50%; background: var(--idle); display: inline-block; flex: none; }
73
+ .dot.needs-you { background: var(--need); box-shadow: 0 0 0 4px color-mix(in srgb, var(--need) 25%, transparent); animation: pulse 1.6s infinite; }
74
+ .dot.working, .dot.running { background: var(--work); }
75
+ .dot.failed { background: var(--fail); }
76
+ .dot.stopped { background: transparent; border: 2px solid var(--idle); }
77
+ @keyframes pulse { 50% { box-shadow: 0 0 0 7px transparent; } }
78
+ @media (prefers-reduced-motion: reduce) { .dot.needs-you { animation: none; } }
79
+ .empty { padding: 40px 8px; text-align: center; color: var(--mute); }
80
+ .empty p { margin: 6px 0; }
81
+
82
+ /* fab */
83
+ .fab { position: fixed; right: max(16px, calc(50% - 304px)); bottom: calc(18px + var(--safe-b)); z-index: 6; min-height: 52px; padding: 0 20px;
84
+ border-radius: 999px; border: 0; background: var(--accent); color: var(--bg); font-weight: 650; box-shadow: 0 6px 24px rgb(0 0 0 / .25); }
85
+
86
+ /* sheet */
87
+ .scrim { position: fixed; inset: 0; background: rgb(0 0 0 / .45); z-index: 10; opacity: 0; pointer-events: none; transition: opacity .2s; }
88
+ .scrim.on { opacity: 1; pointer-events: auto; }
89
+ .sheet { position: fixed; left: 0; right: 0; bottom: 0; z-index: 11; max-width: 640px; margin: 0 auto; max-height: 92dvh; overflow-y: auto;
90
+ background: var(--card); border-radius: 18px 18px 0 0; padding: 8px 16px calc(20px + var(--safe-b)); transform: translateY(105%); transition: transform .22s ease-out; }
91
+ .sheet.on { transform: none; }
92
+ .grab { width: 40px; height: 5px; border-radius: 3px; background: var(--line); margin: 4px auto 12px; }
93
+ .sheet h3 { margin: 0; font-size: 18px; overflow-wrap: anywhere; }
94
+ .meta { display: flex; flex-wrap: wrap; gap: 6px 12px; margin: 6px 0 14px; font: 12px var(--mono); color: var(--mute); }
95
+ .meta .st { display: inline-flex; gap: 6px; align-items: center; color: var(--ink); }
96
+ .screen { background: #0b0c0a; color: #d8d6cc; font: 11.5px/1.45 var(--mono); border-radius: 10px; padding: 10px 12px; max-height: 42dvh;
97
+ overflow: auto; white-space: pre; margin: 0 0 12px; }
98
+ .note { font-size: 13px; color: var(--mute); background: var(--bg); border-radius: 10px; padding: 10px 12px; margin: 0 0 12px; }
99
+ .note code { font: 12px var(--mono); color: var(--ink); overflow-wrap: anywhere; }
100
+ .keys { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin-bottom: 8px; }
101
+ .k { min-height: 44px; border-radius: 10px; border: 1px solid var(--line); background: var(--bg); font: 600 14px var(--mono); }
102
+ .k:active { background: var(--line); }
103
+ .row { display: flex; gap: 8px; }
104
+ .row > * { min-width: 0; }
105
+ .in { flex: 1; min-height: 44px; border-radius: 10px; border: 1px solid var(--line); background: var(--bg); padding: 10px 12px; }
106
+ textarea.in { min-height: 96px; resize: vertical; width: 100%; }
107
+ select.in { width: 100%; }
108
+ .btn { min-height: 44px; padding: 0 16px; border-radius: 10px; border: 1px solid var(--line); background: var(--bg); font-weight: 600; }
109
+ .btn.primary { background: var(--accent); color: var(--bg); border-color: var(--accent); }
110
+ .btn.danger { color: var(--fail); }
111
+ .btn.danger.armed { background: var(--fail); color: #fff; border-color: var(--fail); }
112
+ .btn:disabled { opacity: .5; }
113
+ .actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; }
114
+ .actions .btn { flex: 1 1 30%; }
115
+ label.f { display: block; font-size: 12px; color: var(--mute); margin: 12px 0 6px; font-weight: 600; letter-spacing: .02em; }
116
+ .seg { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; }
117
+ .seg button { min-height: 44px; border-radius: 10px; border: 1px solid var(--line); background: var(--bg); font: 13px var(--mono); }
118
+ .seg button[aria-pressed="true"] { background: var(--accent); color: var(--bg); border-color: var(--accent); }
119
+ .plan { list-style: none; margin: 0; padding: 0; }
120
+ .plan li { display: flex; gap: 10px; align-items: center; padding: 10px 0; border-top: 1px solid var(--line); }
121
+ .plan li:first-child { border-top: 0; }
122
+ .plan .pr { font: 600 11px var(--mono); color: var(--mute); flex: none; width: 22px; }
123
+ .plan .tx { flex: 1; min-width: 0; font-size: 14px; }
124
+ .plan .on { font: 11px var(--mono); color: var(--work); }
125
+ .toast { position: fixed; left: 16px; right: 16px; bottom: calc(84px + var(--safe-b)); z-index: 20; max-width: 560px; margin: 0 auto;
126
+ background: var(--ink); color: var(--bg); padding: 12px 14px; border-radius: 12px; font-size: 14px; opacity: 0; transform: translateY(8px);
127
+ transition: .2s; pointer-events: none; }
128
+ .toast.on { opacity: 1; transform: none; }
129
+ .toast.err { background: var(--fail); color: #fff; }
130
+ </style>
131
+ </head>
132
+ <body>
133
+ <header><div class="wrap" style="padding-bottom:0">
134
+ <div class="top"><span class="mark">SELDON</span><span class="head" id="head">…</span><span class="live" id="live" title="live"></span></div>
135
+ <div class="chips" id="chips" role="toolbar" aria-label="filter"></div>
136
+ <div class="holds" id="holds"></div>
137
+ </div></header>
138
+ <main class="wrap" id="main"></main>
139
+ <button class="fab" data-act="new">+ lane</button>
140
+ <div class="scrim" id="scrim" data-act="close"></div>
141
+ <div class="sheet" id="sheet" role="dialog" aria-modal="true"><div class="grab"></div><div id="sheetBody"></div></div>
142
+ <div class="toast" id="toast" role="status"></div>
143
+ <script>
144
+ "use strict";
145
+ const $ = (id) => document.getElementById(id);
146
+ const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
147
+ const ago = (ms) => { if (!ms) return ""; const s = Math.max(0, (Date.now() - ms) / 1000 | 0);
148
+ return s < 60 ? s + "s" : s < 3600 ? (s / 60 | 0) + "m" : s < 86400 ? (s / 3600 | 0) + "h" : (s / 86400 | 0) + "d"; };
149
+ const detail = (l) => l.state === "needs-you" ? "needs you: " + (l.waitingFor || "input") : l.state === "running" ? "running (no state reported)" : l.state;
150
+
151
+ let S = null, filter = "all", sheet = null, peekTimer = null, lastNeed = -1;
152
+ // The token arrives once in the link seldon serve prints (#t=…), is kept on this device, and
153
+ // is taken out of the address bar so it never ends up in a screenshot or a shared URL.
154
+ const TOKEN = (() => {
155
+ const m = location.hash.match(/[#&]t=([A-Za-z0-9_-]+)/);
156
+ try { if (m) localStorage.setItem("seldon-token", m[1]); } catch {}
157
+ if (m) history.replaceState(null, "", location.pathname);
158
+ try { return m?.[1] || localStorage.getItem("seldon-token") || ""; } catch { return m?.[1] || ""; }
159
+ })();
160
+ const api = async (path, body) => {
161
+ const headers = { "x-seldon-token": TOKEN, ...(body ? { "content-type": "application/json" } : {}) };
162
+ const r = await fetch(path, body ? { method: "POST", headers, body: JSON.stringify(body) } : { headers });
163
+ const j = await r.json().catch(() => ({ ok: false, error: "bad reply (" + r.status + ")" }));
164
+ if (r.status === 403) locked(j.error);
165
+ return j;
166
+ };
167
+ function locked(why) {
168
+ $("head").textContent = "locked";
169
+ $("main").innerHTML = `<div class="empty"><p><b>This device isn't let in.</b></p><p>${esc(why)}</p>
170
+ <p>Open the link <code>seldon serve</code> printed in your terminal (it carries the token).</p></div>`;
171
+ throw new Error(why);
172
+ }
173
+ const toast = (msg, err) => { const t = $("toast"); t.textContent = msg; t.className = "toast on" + (err ? " err" : ""); clearTimeout(toast.t); toast.t = setTimeout(() => t.className = "toast", 2600); };
174
+ const allLanes = () => S ? S.groups.flatMap((g) => g.lanes.map((l) => ({ ...l, group: g }))) : [];
175
+ const laneBy = (key) => allLanes().find((l) => l.key === key);
176
+
177
+ // ---- poll -------------------------------------------------------------------------
178
+ async function refresh() {
179
+ try {
180
+ S = await api("/api/state");
181
+ $("live").classList.remove("stale");
182
+ render();
183
+ const need = allLanes().filter((l) => l.state === "needs-you").length;
184
+ if (lastNeed >= 0 && need > lastNeed) alertNeed(need);
185
+ lastNeed = need;
186
+ document.title = need ? `(${need}) seldon` : "seldon";
187
+ if (sheet?.type === "lane") renderLaneSheet(false);
188
+ } catch { $("live").classList.add("stale"); }
189
+ }
190
+ function alertNeed(n) {
191
+ navigator.vibrate?.(120);
192
+ if (document.hidden && "Notification" in window && Notification.permission === "granted")
193
+ new Notification("seldon", { body: n === 1 ? "an agent needs you" : n + " agents need you", tag: "seldon-need" });
194
+ }
195
+
196
+ // ---- render -----------------------------------------------------------------------
197
+ function render() {
198
+ $("head").textContent = S.headline;
199
+ const lanes = allLanes(), need = lanes.filter((l) => l.state === "needs-you").length;
200
+ const chips = [["all", "All", lanes.length, ""], ["need", "Needs you", need, "need"], ["here", "this mac", S.groups.filter((g) => !g.machine).reduce((a, g) => a + g.lanes.length, 0), ""],
201
+ ...S.machines.map((m) => ["m:" + m.name, m.name, m.ok ? m.count : "—", m.ok ? "" : "off"])];
202
+ $("chips").innerHTML = chips.map(([id, label, n, cls]) =>
203
+ `<button class="chip ${cls}" data-act="filter" data-id="${esc(id)}" aria-pressed="${filter === id}">${cls === "off" ? '<span class="dot failed"></span>' : ""}${esc(label)} <span class="n">${esc(n)}</span></button>`).join("");
204
+ $("holds").innerHTML = S.holds?.length ? "held: " + S.holds.map((h) => `<b>${esc(h.name)}</b> → ${esc(h.who)}`).join(" · ") : "";
205
+
206
+ const groups = S.groups.map((g) => ({ ...g, lanes: g.lanes.filter((l) =>
207
+ filter === "need" ? l.state === "needs-you" : filter === "here" ? !g.machine : filter.startsWith("m:") ? g.machine === filter.slice(2) : true) }))
208
+ .filter((g) => g.lanes.length);
209
+ $("main").innerHTML = groups.length ? groups.map((g) => `
210
+ <section class="proj">
211
+ <div class="ph"><h2>${esc(g.lanes[0].projectName || g.name.replace(/ @.*/, ""))}</h2>${g.machine ? `<span class="at">@${esc(g.machine)}</span>` : ""}<span class="sp"></span>
212
+ <button class="ghost" data-act="plan" data-root="${esc(g.remoteRoot || g.root)}" data-machine="${esc(g.machine || "")}">plan</button>
213
+ <button class="ghost" data-act="new" data-root="${esc(g.remoteRoot || g.root)}" data-machine="${esc(g.machine || "")}" aria-label="new lane here">+</button></div>
214
+ <div class="card">${g.lanes.map((l) => `
215
+ <button class="lane ${esc(l.state)}" data-act="lane" data-key="${esc(l.key)}">
216
+ <span class="g"><span class="dot ${esc(l.state)}"></span></span>
217
+ <span class="nm">${esc(l.name || l.id || "?")}</span><span class="ag">${esc(l.harness)} ${esc(ago(l.startedAt))}</span>
218
+ <span class="dt">${esc(detail(l))}</span>
219
+ </button>`).join("")}</div>
220
+ </section>`).join("")
221
+ : `<div class="empty"><p><b>${filter === "need" ? "Nobody needs you." : "No agents here."}</b></p><p>${filter === "need" ? "You'll get a buzz when one does." : "Start one with + lane."}</p></div>`;
222
+ }
223
+
224
+ // ---- sheets -----------------------------------------------------------------------
225
+ function open(type, data) { sheet = { type, ...data }; $("scrim").classList.add("on"); $("sheet").classList.add("on"); }
226
+ function close() { sheet = null; clearInterval(peekTimer); $("scrim").classList.remove("on"); $("sheet").classList.remove("on"); }
227
+
228
+ function renderLaneSheet(full = true) {
229
+ const l = laneBy(sheet.key);
230
+ if (!l) { $("sheetBody").innerHTML = `<h3>Lane ended</h3><p class="note">It is no longer listed.</p>`; return; }
231
+ const c = l.caps || {};
232
+ const head = `<h3>${esc(l.name || l.id)}</h3>
233
+ <div class="meta"><span class="st"><span class="dot ${esc(l.state)}"></span>${esc(detail(l))}</span><span>${esc(l.harness)}</span>
234
+ <span>${esc(l.group.lanes[0].projectName || l.group.name)}${l.group.machine ? " @" + esc(l.group.machine) : ""}</span><span>${esc(ago(l.startedAt))}</span></div>`;
235
+ if (!full) { $("sheetBody").querySelector(".lanehead").innerHTML = head; return; }
236
+ $("sheetBody").innerHTML = `<div class="lanehead">${head}</div>
237
+ ${c.peek ? `<pre class="screen" id="screen">reading the screen…</pre>` : ""}
238
+ ${c.hint ? `<p class="note">No terminal pane to read for this lane. Open it with <code>${esc(c.hint)}</code>, or from the Claude app via Remote Control.</p>` : ""}
239
+ ${c.reply && S.allowReply ? `
240
+ <div class="keys">${["1", "2", "3", "y"].map((k) => `<button class="k" data-act="text" data-v="${k}">${k}</button>`).join("")}
241
+ ${[["enter", "⏎"], ["esc", "esc"], ["up", "↑"], ["down", "↓"]].map(([k, v]) => `<button class="k" data-act="key" data-v="${k}">${v}</button>`).join("")}</div>
242
+ <form class="row" data-form="reply"><input class="in" name="t" placeholder="reply to the agent…" autocomplete="off" enterkeyhint="send"><button class="btn primary">Send</button></form>`
243
+ : c.reply ? `<p class="note">Read-only. To answer from here, start it with <code>seldon serve --allow-reply</code>.</p>` : ""}
244
+ <div class="actions">
245
+ ${c.stop ? `<button class="btn danger" data-act="stop">Stop</button>` : ""}
246
+ ${c.resume ? `<button class="btn primary" data-act="resume">Resume</button>` : ""}
247
+ ${c.rm ? `<button class="btn danger" data-act="rm">Remove</button>` : ""}
248
+ <button class="btn" data-act="close">Close</button>
249
+ </div>`;
250
+ clearInterval(peekTimer);
251
+ if (c.peek) { peek(); peekTimer = setInterval(peek, 2000); }
252
+ }
253
+ async function peek() {
254
+ const el = $("screen"); if (!el || !sheet) return;
255
+ const r = await api("/api/peek?key=" + encodeURIComponent(sheet.key));
256
+ const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 8;
257
+ el.textContent = r.ok ? (r.screen || "(empty)") : r.error;
258
+ if (atBottom) el.scrollTop = el.scrollHeight;
259
+ }
260
+
261
+ function projects() {
262
+ return S.groups.map((g) => ({ root: g.remoteRoot || g.root, machine: g.machine || "", label: (g.lanes[0]?.projectName || g.name.replace(/ @.*/, "")) + (g.machine ? " @" + g.machine : "") }));
263
+ }
264
+ function renderNew(d) {
265
+ const ps = projects(); const pick = ps.find((p) => p.root === d.root && p.machine === (d.machine || "")) || ps[0];
266
+ sheet.agent = sheet.agent || "claude";
267
+ $("sheetBody").innerHTML = `<h3>New lane</h3>
268
+ <form data-form="start">
269
+ <label class="f">Project</label>
270
+ <select class="in" name="p">${ps.map((p, i) => `<option value="${i}" ${p === pick ? "selected" : ""}>${esc(p.label)}</option>`).join("")}</select>
271
+ <label class="f">Task</label>
272
+ <textarea class="in" name="task" placeholder="fix the save crash">${esc(d.task || "")}</textarea>
273
+ <label class="f">Agent</label>
274
+ <div class="seg">${["claude", "codex", "opencode"].map((a) => `<button type="button" data-act="agent" data-v="${a}" aria-pressed="${sheet.agent === a}">${a}</button>`).join("")}</div>
275
+ <div class="actions"><button class="btn primary">Start lane</button><button type="button" class="btn" data-act="close">Cancel</button></div>
276
+ </form>`;
277
+ sheet.projects = ps;
278
+ }
279
+ async function renderPlan() {
280
+ $("sheetBody").innerHTML = `<h3>Plan</h3><p class="note">reading docs/QUEUE.md…</p>`;
281
+ const r = await api(`/api/plan?root=${encodeURIComponent(sheet.root)}&machine=${encodeURIComponent(sheet.machine || "")}`);
282
+ if (sheet?.type !== "plan") return;
283
+ const items = r.items;
284
+ $("sheetBody").innerHTML = `<h3>Plan</h3><div class="meta"><span>${esc(sheet.root)}${sheet.machine ? " @" + esc(sheet.machine) : ""}</span></div>
285
+ ${!r.ok ? `<p class="note">${esc(r.error)}</p>` : items == null ? `<p class="note">No plan here (foundation not installed, or no docs/QUEUE.md).</p>`
286
+ : !items.length ? `<p class="note">The plan is empty.</p>`
287
+ : `<ul class="plan">${items.map((it, i) => `<li><span class="pr">${esc(it.priority || "")}</span><span class="tx">${esc(it.text)}</span>
288
+ ${it.lane ? `<span class="on">● ${esc(it.lane)}</span>` : `<button class="btn" data-act="item" data-i="${i}">Start</button>`}</li>`).join("")}</ul>`}
289
+ ${!sheet.machine && items ? `<form class="row" data-form="add" style="margin-top:12px"><input class="in" name="t" placeholder="add to the plan…" autocomplete="off"><button class="btn">Add</button></form>` : ""}
290
+ <div class="actions"><button class="btn" data-act="close">Close</button></div>`;
291
+ sheet.items = items;
292
+ }
293
+
294
+ // ---- one listener for everything ----------------------------------------------------
295
+ async function doLane(verb, btn) {
296
+ if (verb !== "resume" && !btn.classList.contains("armed")) { btn.classList.add("armed"); btn.textContent = "Tap again to " + verb.replace("rm", "remove"); setTimeout(() => { btn.classList.remove("armed"); btn.textContent = verb === "rm" ? "Remove" : "Stop"; }, 3000); return; }
297
+ btn.disabled = true;
298
+ const r = await api("/api/lane/" + verb, { key: sheet.key });
299
+ toast(r.ok ? ({ stop: "Stopped", resume: "Resumed", rm: "Removed" }[verb]) : r.error, !r.ok);
300
+ if (r.ok && verb !== "resume") close();
301
+ refresh();
302
+ }
303
+ document.addEventListener("click", async (e) => {
304
+ const b = e.target.closest("[data-act]"); if (!b) return;
305
+ const a = b.dataset.act;
306
+ if (a === "filter") { filter = b.dataset.id; render(); }
307
+ else if (a === "lane") { open("lane", { key: b.dataset.key }); renderLaneSheet(); maybeAskNotify(); }
308
+ else if (a === "new") { open("new", {}); renderNew({ root: b.dataset.root, machine: b.dataset.machine }); }
309
+ else if (a === "plan") { open("plan", { root: b.dataset.root, machine: b.dataset.machine }); renderPlan(); }
310
+ else if (a === "close") close();
311
+ else if (a === "agent") { sheet.agent = b.dataset.v; b.parentElement.querySelectorAll("button").forEach((x) => x.setAttribute("aria-pressed", x === b)); }
312
+ else if (["stop", "resume", "rm"].includes(a)) doLane(a, b);
313
+ else if (a === "key") reply({ key: b.dataset.v });
314
+ else if (a === "text") reply({ text: b.dataset.v, submit: false });
315
+ else if (a === "item") { const it = sheet.items[b.dataset.i]; const { root, machine } = sheet; open("new", {}); renderNew({ root, machine, task: it.text }); }
316
+ });
317
+ async function reply(what) {
318
+ const r = await api("/api/lane/reply", { lane: sheet.key, ...what });
319
+ if (!r.ok) toast(r.error, true); else { navigator.vibrate?.(15); setTimeout(peek, 250); }
320
+ }
321
+ document.addEventListener("submit", async (e) => {
322
+ const f = e.target.closest("[data-form]"); if (!f) return;
323
+ e.preventDefault();
324
+ const kind = f.dataset.form, btn = f.querySelector("button:not([type=button])");
325
+ if (kind === "reply") { const t = f.t.value; if (!t) return; f.t.value = ""; return reply({ text: t }); }
326
+ if (kind === "add") {
327
+ const t = f.t.value.trim(); if (!t) return;
328
+ const r = await api("/api/plan/add", { root: sheet.root, text: t });
329
+ toast(r.ok ? "Added to the plan" : r.error, !r.ok); if (r.ok) renderPlan(); return;
330
+ }
331
+ if (kind === "start") {
332
+ const p = sheet.projects[f.p.value], task = f.task.value.trim();
333
+ if (!p || !task) return toast("pick a project and write a task", true);
334
+ btn.disabled = true; btn.textContent = "Starting…";
335
+ const r = await api("/api/lane/start", { root: p.root, machine: p.machine || null, task, agent: sheet.agent });
336
+ toast(r.ok ? "Started " + (r.slug || "lane") : r.error, !r.ok);
337
+ if (r.ok) close(); else { btn.disabled = false; btn.textContent = "Start lane"; }
338
+ refresh();
339
+ }
340
+ });
341
+ // Notifications need a secure context (tailscale serve gives one) and a tap to ask.
342
+ function maybeAskNotify() {
343
+ if ("Notification" in window && Notification.permission === "default" && window.isSecureContext) Notification.requestPermission();
344
+ }
345
+ document.addEventListener("keydown", (e) => { if (e.key === "Escape" && sheet) close(); });
346
+ document.addEventListener("visibilitychange", () => { if (!document.hidden) refresh(); });
347
+ refresh();
348
+ setInterval(refresh, 3000);
349
+ </script>
350
+ </body>
351
+ </html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gorlitzer-labs/seldon",
3
- "version": "0.11.0",
3
+ "version": "0.13.1",
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": {