@gorlitzer-labs/seldon 0.13.1 → 0.15.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 CHANGED
@@ -168,6 +168,50 @@ seldon serve --allow-reply # let the phone type into agents (off by default
168
168
  - **Alerts:** while the page is open, the phone buzzes and notifies when an agent starts
169
169
  needing you.
170
170
 
171
+ ## On Telegram — `seldon tell`
172
+
173
+ Any agent, on any machine, can message you — text, screenshots, videos, files — and the
174
+ watcher sends its news there too (needs you, failed, finished), so the phone hears about it
175
+ with the app closed.
176
+
177
+ ```bash
178
+ seldon tell "the build is green" # text (long text is split)
179
+ pnpm test 2>&1 | tail -20 | seldon tell # or from stdin
180
+ seldon tell --file out/pitch.mp4 "first cut" # a file, with a caption
181
+ ```
182
+
183
+ Images show inline, videos play, GIFs animate, audio plays, anything else is a document; a
184
+ bot can send up to 50 MB per file.
185
+
186
+ **Once:** make a bot with [@BotFather](https://t.me/BotFather), store its token in comb —
187
+ `comb set TELEGRAM_BOT_TOKEN` — send your bot `/start`, then `seldon tell --setup` (it finds
188
+ your chat and keeps its id in `~/.seldon/telegram.json`). Stored it under another name?
189
+ `seldon tell --setup --token-name MY_NAME` — seldon remembers it.
190
+
191
+ - **The token never shows.** seldon does not store it: without it in the environment,
192
+ `seldon tell` re-runs itself under `comb run --with TELEGRAM_BOT_TOKEN`, so an agent can send
193
+ without ever seeing it. Every machine with comb synced can send.
194
+ - **Your phone → this machine: `seldon inbox`.** Send the bot a screenshot, video, file, voice
195
+ note or a line of text and it lands in `~/Downloads/seldon-inbox/` (`--dir` for another),
196
+ with a 👍 on your message once it is saved and one line per item in `notes.md`. Plain code,
197
+ no agent in between, no tokens; only your chat is listened to. A bot can fetch up to 20 MB,
198
+ and Telegram compresses photos — *Send as File* for the original. Telegram itself still
199
+ carries everything (a bot chat is not end-to-end encrypted).
200
+ - **Sending only.** Any number of sessions can send through one bot. Writing *to* an agent from
201
+ Telegram (text, or a screenshot from your phone) is Claude Code's own Telegram channel
202
+ (`claude --channels plugin:telegram@claude-plugins-official`), and the same bot works for
203
+ both: sending never competes with its one reader. Run `seldon tell --setup` before starting
204
+ that channel — setup reads the bot's messages once to find your chat.
205
+
206
+ Tell your agents once, in `~/.claude/CLAUDE.md` / `AGENTS.md`:
207
+
208
+ ```markdown
209
+ ## Telegram
210
+ Send the operator what they'd want to see on their phone with `seldon tell "…"` /
211
+ `seldon tell --file <path> "caption"`: a finished piece of work, a screenshot or video of it,
212
+ a link, a blocker. Short. Never a secret.
213
+ ```
214
+
171
215
  ## Holds — taking turns on shared things
172
216
 
173
217
  Agents on different projects share one machine: one boots the Android emulator, another
package/bin/seldon.js CHANGED
@@ -14,6 +14,7 @@ import { startLane, stopLane, resumeLane, removeLane, findLane } from "../lib/ac
14
14
  import { listMachines, addMachine, fetchLanes, remoteGroups, sshArgs, lastJsonLine } from "../lib/machines.mjs";
15
15
  import { notify } from "../lib/notify.mjs";
16
16
  import { serve, serveToken, ownerFromStatus } from "../lib/serve.mjs";
17
+ import { tokenName, readChat, writeChat, chatFromUpdates, getUpdates, sendText, sendFile, pollUpdates, fileFromMessage, inboxName, noteLine, downloadFile, react, MAX_DOWNLOAD } from "../lib/telegram.mjs";
17
18
  import { reportFromEvent, mergeCodexHooks, removeCodexHooks, opencodePlugin } from "../lib/reports.mjs";
18
19
  import { buildRows, headline, ago, laneDetail, unlistedAgents, GLYPH } from "../lib/home.mjs";
19
20
  import { parseDuration, describe as describeHold, NAME_RE, DEFAULT_FOR_MS } from "../lib/holds.mjs";
@@ -1433,6 +1434,8 @@ ${C.bold("seldon")} — the agent factory: your projects, and the stack that run
1433
1434
  ${C.bold("seldon up")} start the stack (voice + supervisor) and print where to go
1434
1435
  ${C.bold("seldon up --tailnet")} expose the voice over HTTPS (tailscale serve) so the mic works on your phone
1435
1436
  ${C.bold("seldon serve")} [--tailnet] the panel as a phone web app (--allow-reply to answer agents)
1437
+ ${C.bold("seldon tell")} "…" message yourself on Telegram (--file to send one; --setup once)
1438
+ ${C.bold("seldon inbox")} [--dir d] save what you send the bot to a folder here (no agent, no tokens)
1436
1439
  ${C.bold("seldon up --brain=X")} pick the voice brain: qwen (in-process) | bonsai (local server); remembered
1437
1440
  ${C.bold("seldon status")} what's running · ${C.bold("seldon down")} stop it
1438
1441
  ${C.bold("seldon adopt")} [dir] put an existing repo on the line: foundation docs (never overwritten),
@@ -1464,6 +1467,14 @@ ${C.bold("seldon")} — the agent factory: your projects, and the stack that run
1464
1467
  const SELF = fileURLToPath(import.meta.url);
1465
1468
  const startWatch = () => startDaemon("seldon-watch", process.execPath, [SELF, "watch"]);
1466
1469
 
1470
+ // The watcher's news on the phone too, once `seldon tell --setup` has been run. A child
1471
+ // `seldon tell` per event, so the token goes through comb exactly as it does for an agent.
1472
+ function tellInBackground(text) {
1473
+ if (process.env.SELDON_NO_NOTIFY || !readChat()) return;
1474
+ const child = spawn(process.execPath, [process.argv[1], "tell", text], { stdio: "ignore", detached: true });
1475
+ child.on("error", () => {}); child.unref();
1476
+ }
1477
+
1467
1478
  async function watchCmd(flags) {
1468
1479
  ensureSiblingPath();
1469
1480
  const every = parseDuration(flags.interval, 5000) || 5000;
@@ -1475,7 +1486,9 @@ async function watchCmd(flags) {
1475
1486
  try { lanes = readLanes().flatMap((g) => g.lanes); } catch (e) { console.log(`${stamp()} read failed: ${e.message}`); }
1476
1487
  for (const e of transitions(prev, lanes)) {
1477
1488
  console.log(`${stamp()} ${e.text}`);
1478
- notify(e.to === "needs-you" ? "Seldon · needs you" : "Seldon", `${e.text} — ${path.basename(e.lane.project || e.lane.cwd || "")}`);
1489
+ const where = path.basename(e.lane.project || e.lane.cwd || "");
1490
+ notify(e.to === "needs-you" ? "Seldon · needs you" : "Seldon", `${e.text} — ${where}`);
1491
+ tellInBackground(`${e.to === "needs-you" ? "⚑" : e.to === "failed" ? "✗" : "✓"} ${e.text} — ${where}`);
1479
1492
  }
1480
1493
  prev = new Map(lanes.map((l) => [l.key, l.state]));
1481
1494
  if (flags.once) return;
@@ -1554,6 +1567,95 @@ function serveCmd(flags) {
1554
1567
  } catch (e) { console.log(C.red(" tailscale serve failed: " + ((e.stderr || e.message || "").toString().split("\n")[0]))); }
1555
1568
  }
1556
1569
 
1570
+ // `seldon tell "…"` — message the operator on Telegram, from any agent. The token comes from
1571
+ // comb in the environment: without it, seldon re-runs itself under `comb run`, so the value
1572
+ // is never in an argument, a file seldon writes, or the agent's transcript.
1573
+ // The bot token, from the environment. Without it, re-run this same command under
1574
+ // `comb run` (which puts it there) and return null: the child does the work.
1575
+ function telegramToken(flags) {
1576
+ const fail = (msg) => { console.error(C.red(msg)); process.exitCode = 1; return null; };
1577
+ const name = typeof flags["token-name"] === "string" ? flags["token-name"] : tokenName();
1578
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) return fail(`not a secret name: ${name}`);
1579
+ if (process.env[name]) return { token: process.env[name], name };
1580
+ if (process.env.SELDON_TELL_VIA_COMB) return fail(`comb has no ${name} — store it once: comb set ${name}`);
1581
+ if (!has("comb")) return fail(`no ${name} in the environment, and comb is not installed (seldon install comb)`);
1582
+ const r = spawnSync("comb", ["run", "--with", name, "--", process.execPath, process.argv[1], ...process.argv.slice(2)],
1583
+ { stdio: "inherit", env: { ...process.env, SELDON_TELL_VIA_COMB: "1" } });
1584
+ process.exitCode = r.status ?? 1;
1585
+ return null;
1586
+ }
1587
+
1588
+ async function tellCmd(words, flags) {
1589
+ const fail = (msg) => { console.error(C.red(msg)); process.exitCode = 1; };
1590
+ const t = telegramToken(flags);
1591
+ if (!t) return;
1592
+ const { token, name } = t;
1593
+ try {
1594
+ if (flags.setup) {
1595
+ const chat = chatFromUpdates(await getUpdates(token));
1596
+ if (!chat) return fail("no message to the bot yet — open your bot in Telegram, send it /start, then run this again");
1597
+ writeChat({ ...chat, ...(name !== "TELEGRAM_BOT_TOKEN" ? { tokenName: name } : {}) });
1598
+ await sendText(token, chat.id, "✓ seldon is connected. Agents can reach you here with: seldon tell \"…\"");
1599
+ return console.log(C.green(`✓ connected to ${chat.name || "your chat"}`) + C.dim(" — try: seldon tell \"hello\""));
1600
+ }
1601
+ const chat = readChat();
1602
+ if (!chat) return fail("not set up yet — send your bot /start in Telegram, then: seldon tell --setup");
1603
+ let text = words.join(" ");
1604
+ if (!text && !process.stdin.isTTY) { for await (const c of process.stdin) text += c; text = text.trim(); }
1605
+ if (typeof flags.file === "string") await sendFile(token, chat.id, flags.file, text);
1606
+ else if (text) await sendText(token, chat.id, text);
1607
+ else return fail('usage: seldon tell "message" · … | seldon tell · seldon tell --file shot.png "caption" · seldon tell --setup');
1608
+ console.log(C.green("✓ sent"));
1609
+ } catch (e) { fail(e.message); }
1610
+ }
1611
+
1612
+ // `seldon inbox` — what you send the bot from your phone lands in a folder here: photos,
1613
+ // videos, files, voice notes, and text into notes.md. Plain code, no agent in between, no
1614
+ // tokens. Only your chat (from `seldon tell --setup`) is listened to; anyone else is ignored.
1615
+ async function inboxCmd(flags) {
1616
+ const fail = (msg) => { console.error(C.red(msg)); process.exitCode = 1; };
1617
+ const chat = readChat();
1618
+ if (!chat) return fail("not set up yet — send your bot /start in Telegram, then: seldon tell --setup");
1619
+ const t = telegramToken(flags);
1620
+ if (!t) return;
1621
+ const dir = path.resolve(typeof flags.dir === "string" ? flags.dir : path.join(process.env.HOME, "Downloads", "seldon-inbox"));
1622
+ fs.mkdirSync(dir, { recursive: true });
1623
+ const stamp = () => new Date().toTimeString().slice(0, 8);
1624
+ console.log(`${stamp()} seldon inbox → ${dir}`);
1625
+ let offset;
1626
+ for (;;) {
1627
+ let updates;
1628
+ try { updates = (await pollUpdates(t.token, offset)).result; }
1629
+ catch (e) {
1630
+ console.log(`${stamp()} ${e.message}`);
1631
+ if (/terminated by other getUpdates/i.test(e.message)) return fail("another reader has this bot (a second inbox, or Claude's Telegram channel) — stop it first");
1632
+ await new Promise((r) => setTimeout(r, 5000)); continue;
1633
+ }
1634
+ for (const u of updates) {
1635
+ offset = u.update_id + 1;
1636
+ const m = u.message;
1637
+ if (!m || m.chat?.id !== chat.id) continue;
1638
+ const when = m.date * 1000, f = fileFromMessage(m), text = m.caption || m.text || "";
1639
+ try {
1640
+ if (f) {
1641
+ if (f.size && f.size > MAX_DOWNLOAD) throw new Error(`${f.name} is over 20 MB — a bot can't fetch it; share it another way`);
1642
+ const name = inboxName(f.name, when);
1643
+ await downloadFile(t.token, f.fileId, path.join(dir, name));
1644
+ fs.appendFileSync(path.join(dir, "notes.md"), noteLine(when, { file: name, text }), { mode: 0o600 });
1645
+ console.log(`${stamp()} saved ${name}`);
1646
+ } else if (text && !text.startsWith("/")) {
1647
+ fs.appendFileSync(path.join(dir, "notes.md"), noteLine(when, { text }), { mode: 0o600 });
1648
+ console.log(`${stamp()} noted`);
1649
+ } else continue;
1650
+ await react(t.token, chat.id, m.message_id, "👍");
1651
+ } catch (e) {
1652
+ console.log(`${stamp()} ${e.message}`);
1653
+ await sendText(t.token, chat.id, `✗ not saved: ${e.message}`).catch(() => {});
1654
+ }
1655
+ }
1656
+ }
1657
+ }
1658
+
1557
1659
  // `seldon machines` — the other computers the panel shows (bifrost's realms, one list).
1558
1660
  function machinesCmd(verb, name, target) {
1559
1661
  if (verb === "add") {
@@ -1680,7 +1782,7 @@ function holdsCmd() {
1680
1782
  // (`--no-attach`). The value form has to be CONSUMED: filtering out everything starting with
1681
1783
  // `--` and keeping the rest as positionals read `seldon go --agent claude` as the project
1682
1784
  // named "claude".
1683
- const VALUE_FLAGS = new Set(["agent", "model", "effort", "name", "port", "pm", "stall", "dir", "for", "wait", "as", "note", "interval", "task", "owner"]);
1785
+ const VALUE_FLAGS = new Set(["agent", "model", "effort", "name", "port", "pm", "stall", "dir", "for", "wait", "as", "note", "interval", "task", "owner", "file", "token-name"]);
1684
1786
  function parseArgv(raw) {
1685
1787
  const flags = {}, positional = [];
1686
1788
  for (let i = 0; i < raw.length; i++) {
@@ -1735,6 +1837,8 @@ const ids = tokens.filter((id) => byId[id]); // only the valid module
1735
1837
  if (cmd === "machines") return machinesCmd(tokens[0], tokens[1], tokens[2]);
1736
1838
  if (cmd === "lane") return laneCmd(tokens[0], tokens[1], flags);
1737
1839
  if (cmd === "serve") return serveCmd(flags);
1840
+ if (cmd === "tell") return tellCmd(tokens, flags);
1841
+ if (cmd === "inbox") return inboxCmd(flags);
1738
1842
  if (cmd === "setup") return setupCmd(tokens[0], flags);
1739
1843
  if (cmd === "panel" || cmd === "board") return panel();
1740
1844
  if (cmd && cmd !== "install") { help(); process.exitCode = 1; return; }
@@ -0,0 +1,131 @@
1
+ // `seldon tell` — any agent can message you on Telegram: `seldon tell "the build is green"`.
2
+ //
3
+ // The bot token is a secret and lives in comb (TELEGRAM_BOT_TOKEN): seldon never stores it,
4
+ // prints it or puts it on a command line — `comb run` hands it over in the environment. The
5
+ // chat id is not a secret (it is useless without the token), so `seldon tell --setup` finds it
6
+ // once and keeps it in ~/.seldon/telegram.json.
7
+ //
8
+ // Sending is open to any number of sessions at once. Reading a bot's messages is one reader
9
+ // only: `seldon inbox` (what you send the bot lands in a folder on this machine — no agent in
10
+ // between), or Claude Code's own Telegram channel, never both. --setup reads once.
11
+ import { readFileSync, writeFileSync, mkdirSync, statSync } from "node:fs";
12
+ import { join, basename } from "node:path";
13
+ import { SELDON_HOME } from "./agents.mjs";
14
+
15
+ export const TOKEN_NAME = "TELEGRAM_BOT_TOKEN";
16
+ // The comb name the token is stored under: TELEGRAM_BOT_TOKEN unless setup was told another.
17
+ export const tokenName = (chat = readChat()) => chat?.tokenName || TOKEN_NAME;
18
+ export const MAX = 4096; // Telegram's limit per message
19
+ export const MAX_UPLOAD = 50 * 1024 * 1024; // a bot may upload up to 50 MB
20
+ const CONFIG = () => join(SELDON_HOME, "telegram.json");
21
+
22
+ // ---- pure -------------------------------------------------------------------------
23
+ // Long text goes out in pieces, split at a line break when there is one near the limit.
24
+ export function chunks(text, max = MAX) {
25
+ const out = [];
26
+ let s = String(text);
27
+ while (s.length > max) {
28
+ const cut = s.lastIndexOf("\n", max);
29
+ const at = cut > max * 0.5 ? cut : max;
30
+ out.push(s.slice(0, at));
31
+ s = s.slice(at).replace(/^\n/, "");
32
+ }
33
+ if (s.length) out.push(s);
34
+ return out;
35
+ }
36
+
37
+ // The private chat that last wrote to the bot: whoever just sent it /start during --setup.
38
+ export function chatFromUpdates(updates) {
39
+ const msgs = (updates?.result || []).map((u) => u.message || u.edited_message).filter((m) => m?.chat?.type === "private");
40
+ const m = msgs.at(-1);
41
+ return m ? { id: m.chat.id, name: m.chat.username || m.chat.first_name || null } : null;
42
+ }
43
+
44
+ // ---- I/O --------------------------------------------------------------------------
45
+ export function readChat() {
46
+ try { return JSON.parse(readFileSync(CONFIG(), "utf8")); } catch { return null; }
47
+ }
48
+ export function writeChat(chat) {
49
+ mkdirSync(SELDON_HOME, { recursive: true });
50
+ writeFileSync(CONFIG(), JSON.stringify(chat) + "\n", { mode: 0o600 });
51
+ }
52
+
53
+ // Errors name the method and Telegram's description, never the URL (it carries the token).
54
+ async function call(token, method, body) {
55
+ const r = await fetch(`https://api.telegram.org/bot${token}/${method}`, body instanceof FormData
56
+ ? { method: "POST", body } : { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body || {}) });
57
+ const j = await r.json().catch(() => ({}));
58
+ if (!j.ok) throw new Error(`telegram ${method}: ${j.description || r.status}`);
59
+ return j;
60
+ }
61
+
62
+ export const getUpdates = (token) => call(token, "getUpdates", { allowed_updates: ["message"] });
63
+ // Long polling: Telegram holds the request until something arrives (or `timeout` seconds pass).
64
+ // Asking with `offset` = last update_id + 1 also tells Telegram the earlier ones are handled.
65
+ export const pollUpdates = (token, offset, timeout = 50) =>
66
+ call(token, "getUpdates", { offset, timeout, allowed_updates: ["message"] });
67
+
68
+ export async function sendText(token, chatId, text) {
69
+ for (const part of chunks(text)) await call(token, "sendMessage", { chat_id: chatId, text: part, disable_web_page_preview: true });
70
+ }
71
+
72
+ // How a file shows up in the chat: images inline, videos playable, GIFs animated, audio as a
73
+ // track, anything else as a document.
74
+ export function mediaKind(path) {
75
+ const ext = String(path).toLowerCase().split(".").pop();
76
+ if (["png", "jpg", "jpeg", "webp"].includes(ext)) return { method: "sendPhoto", field: "photo" };
77
+ if (["mp4", "mov", "m4v", "webm"].includes(ext)) return { method: "sendVideo", field: "video" };
78
+ if (ext === "gif") return { method: "sendAnimation", field: "animation" };
79
+ if (["mp3", "m4a", "ogg", "wav", "flac"].includes(ext)) return { method: "sendAudio", field: "audio" };
80
+ return { method: "sendDocument", field: "document" };
81
+ }
82
+
83
+ export async function sendFile(token, chatId, path, caption = "") {
84
+ const size = statSync(path).size;
85
+ if (size > MAX_UPLOAD) throw new Error(`${basename(path)} is ${(size / 1048576).toFixed(0)} MB — Telegram bots can send up to 50 MB`);
86
+ const { method, field } = mediaKind(path);
87
+ const form = new FormData();
88
+ form.set("chat_id", String(chatId));
89
+ if (caption) form.set("caption", caption.slice(0, 1024));
90
+ if (method === "sendVideo") form.set("supports_streaming", "true");
91
+ form.set(field, new Blob([readFileSync(path)]), basename(path));
92
+ await call(token, method, form);
93
+ }
94
+
95
+ // ---- the inbox: what you send the bot, saved on this machine ------------------------
96
+ export const MAX_DOWNLOAD = 20 * 1024 * 1024; // a bot may download up to 20 MB
97
+
98
+ // The one file in a message, if it carries one. A photo comes in several sizes: the largest.
99
+ export function fileFromMessage(m) {
100
+ if (!m) return null;
101
+ const pick = (f, fallback) => f && { fileId: f.file_id, size: f.file_size ?? null, name: f.file_name || fallback };
102
+ if (m.photo?.length) return pick(m.photo.at(-1), "photo.jpg");
103
+ return pick(m.document, "file") || pick(m.video, "video.mp4") || pick(m.animation, "animation.mp4")
104
+ || pick(m.audio, "audio.mp3") || pick(m.voice, "voice.ogg") || pick(m.video_note, "video-note.mp4") || null;
105
+ }
106
+
107
+ // A name that is safe on disk and sorts by time: 20261031-091502-screenshot.png
108
+ export function inboxName(name, date) {
109
+ const base = String(name).split(/[\\/]/).pop().replace(/[^\w.-]+/g, "_").replace(/^\.+/, "").slice(-120) || "file";
110
+ const d = new Date(date), p = (n) => String(n).padStart(2, "0");
111
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}-${base}`;
112
+ }
113
+
114
+ // One line in notes.md per thing received, so the folder reads as a log.
115
+ export function noteLine(date, { file, text }) {
116
+ const d = new Date(date), p = (n) => String(n).padStart(2, "0");
117
+ const when = `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
118
+ const body = String(text || "").replace(/\s*\n\s*/g, " ⏎ ").trim();
119
+ return `- ${when} · ${file ? `[${file}](${encodeURI(file)})${body ? ` — ${body}` : ""}` : body}\n`;
120
+ }
121
+
122
+ export async function downloadFile(token, fileId, dest) {
123
+ const { result } = await call(token, "getFile", { file_id: fileId });
124
+ const r = await fetch(`https://api.telegram.org/file/bot${token}/${result.file_path}`);
125
+ if (!r.ok) throw new Error(`telegram download: ${r.status}`);
126
+ writeFileSync(dest, Buffer.from(await r.arrayBuffer()), { mode: 0o600 });
127
+ }
128
+
129
+ // A reaction on your message says it is saved, without a reply cluttering the chat.
130
+ export const react = (token, chatId, messageId, emoji) =>
131
+ call(token, "setMessageReaction", { chat_id: chatId, message_id: messageId, reaction: [{ type: "emoji", emoji }] }).catch(() => {});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gorlitzer-labs/seldon",
3
- "version": "0.13.1",
3
+ "version": "0.15.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": {