@gorlitzer-labs/seldon 0.15.0 → 0.16.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
@@ -175,11 +175,18 @@ watcher sends its news there too (needs you, failed, finished), so the phone hea
175
175
  with the app closed.
176
176
 
177
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
178
+ seldon tell --done "PR #19 merged" # 🟢 a card: kind · project · branch · machine
179
+ seldon tell --need "which domain should staging use?" # 🟠 (--fail 🔴 · --wip 🟡 · --info 🔵, the default)
180
+ pnpm test 2>&1 | seldon tell --fail "tests broke" # a piped log shows its tail as code
181
+ seldon tell --file out/pitch.mp4 --info "first cut" # a file, the card as its caption
182
+ seldon tell --plain "just text" # no card
181
183
  ```
182
184
 
185
+ Every message is a card that reads at a glance: a coloured dot for what kind of news it is,
186
+ then where it comes from (the repo, branch and machine it was sent from), then what happened.
187
+ The watcher's cards also name the agent, what it is waiting for, how long it has run, and link
188
+ to the phone app when `seldon serve --tailnet` is on.
189
+
183
190
  Images show inline, videos play, GIFs animate, audio plays, anything else is a document; a
184
191
  bot can send up to 50 MB per file.
185
192
 
package/bin/seldon.js CHANGED
@@ -5,6 +5,7 @@ import { execSync, spawnSync, spawn } from "node:child_process";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import path from "node:path";
7
7
  import fs from "node:fs";
8
+ import os from "node:os";
8
9
  import readline from "node:readline";
9
10
  import { MODULES, byId, DEPS, RAW, MONOREPO, withRequires, platformOk } from "../modules.mjs";
10
11
  import { ensureSiblingPath, loadState, resolveProject, adopt as fAdopt, staff as fStaff, attach as fAttach, hiveOf, sameDir } from "../lib/projects.mjs";
@@ -14,7 +15,7 @@ import { startLane, stopLane, resumeLane, removeLane, findLane } from "../lib/ac
14
15
  import { listMachines, addMachine, fetchLanes, remoteGroups, sshArgs, lastJsonLine } from "../lib/machines.mjs";
15
16
  import { notify } from "../lib/notify.mjs";
16
17
  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";
18
+ import { card, watchCard, KINDS, tokenName, readChat, writeChat, chatFromUpdates, getUpdates, sendText, sendFile, pollUpdates, fileFromMessage, inboxName, noteLine, downloadFile, react, MAX_DOWNLOAD } from "../lib/telegram.mjs";
18
19
  import { reportFromEvent, mergeCodexHooks, removeCodexHooks, opencodePlugin } from "../lib/reports.mjs";
19
20
  import { buildRows, headline, ago, laneDetail, unlistedAgents, GLYPH } from "../lib/home.mjs";
20
21
  import { parseDuration, describe as describeHold, NAME_RE, DEFAULT_FOR_MS } from "../lib/holds.mjs";
@@ -1469,18 +1470,28 @@ const startWatch = () => startDaemon("seldon-watch", process.execPath, [SELF, "w
1469
1470
 
1470
1471
  // The watcher's news on the phone too, once `seldon tell --setup` has been run. A child
1471
1472
  // `seldon tell` per event, so the token goes through comb exactly as it does for an agent.
1472
- function tellInBackground(text) {
1473
+ function tellInBackground(fields) {
1473
1474
  if (process.env.SELDON_NO_NOTIFY || !readChat()) return;
1474
- const child = spawn(process.execPath, [process.argv[1], "tell", text], { stdio: "ignore", detached: true });
1475
+ const child = spawn(process.execPath, [process.argv[1], "tell", "--card", JSON.stringify(fields)], { stdio: "ignore", detached: true });
1475
1476
  child.on("error", () => {}); child.unref();
1476
1477
  }
1477
1478
 
1479
+ function phoneAppUrl() {
1480
+ const ts = tailscaleBin(); if (!ts) return null;
1481
+ try {
1482
+ const out = execSync(`${ts} serve status`, { stdio: ["ignore", "pipe", "ignore"], timeout: 10000 }).toString();
1483
+ const m = out.match(new RegExp(`https://\\S+:${SERVE_TAILNET_PORT}`));
1484
+ return m ? m[0] + "/" : null;
1485
+ } catch { return null; }
1486
+ }
1487
+
1478
1488
  async function watchCmd(flags) {
1479
1489
  ensureSiblingPath();
1480
1490
  const every = parseDuration(flags.interval, 5000) || 5000;
1481
1491
  let prev = new Map();
1482
1492
  const stamp = () => new Date().toTimeString().slice(0, 8);
1483
1493
  console.log(`${stamp()} seldon watch — every ${every / 1000}s`);
1494
+ const phone = phoneAppUrl(); // once: the link the phone cards carry
1484
1495
  for (;;) {
1485
1496
  let lanes = [];
1486
1497
  try { lanes = readLanes().flatMap((g) => g.lanes); } catch (e) { console.log(`${stamp()} read failed: ${e.message}`); }
@@ -1488,7 +1499,7 @@ async function watchCmd(flags) {
1488
1499
  console.log(`${stamp()} ${e.text}`);
1489
1500
  const where = path.basename(e.lane.project || e.lane.cwd || "");
1490
1501
  notify(e.to === "needs-you" ? "Seldon · needs you" : "Seldon", `${e.text} — ${where}`);
1491
- tellInBackground(`${e.to === "needs-you" ? "⚑" : e.to === "failed" ? "✗" : "✓"} ${e.text} — ${where}`);
1502
+ tellInBackground(watchCard(e, { machine: os.hostname().split(".")[0], link: phone }));
1492
1503
  }
1493
1504
  prev = new Map(lanes.map((l) => [l.key, l.state]));
1494
1505
  if (flags.once) return;
@@ -1585,6 +1596,15 @@ function telegramToken(flags) {
1585
1596
  return null;
1586
1597
  }
1587
1598
 
1599
+ // Where a message comes from: the project (a worktree counts as its main repo), the branch,
1600
+ // and this machine's short name.
1601
+ function tellContext(cwd = process.cwd()) {
1602
+ const git = (...a) => { try { return execSync(`git ${a.join(" ")}`, { cwd, stdio: ["ignore", "pipe", "ignore"] }).toString().trim(); } catch { return null; } };
1603
+ const root = projectRoot(cwd);
1604
+ const branch = root ? git("rev-parse", "--abbrev-ref", "HEAD") : null;
1605
+ return { project: root ? path.basename(root) : null, branch: branch && branch !== "HEAD" ? branch : null, machine: os.hostname().split(".")[0] };
1606
+ }
1607
+
1588
1608
  async function tellCmd(words, flags) {
1589
1609
  const fail = (msg) => { console.error(C.red(msg)); process.exitCode = 1; };
1590
1610
  const t = telegramToken(flags);
@@ -1600,11 +1620,22 @@ async function tellCmd(words, flags) {
1600
1620
  }
1601
1621
  const chat = readChat();
1602
1622
  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');
1623
+ const text = words.join(" ");
1624
+ let log = "";
1625
+ if (!process.stdin.isTTY && !flags.card) { for await (const c of process.stdin) log += c; log = log.trim(); }
1626
+ const file = typeof flags.file === "string" ? flags.file : null;
1627
+ if (!text && !log && !file && !flags.card) return fail('usage: seldon tell [--done|--need|--fail|--wip|--info] "what happened" · … | seldon tell · --file shot.png · --plain · --setup');
1628
+ if (flags.plain) {
1629
+ const body = [text, log].filter(Boolean).join("\n");
1630
+ if (file) await sendFile(token, chat.id, file, body); else await sendText(token, chat.id, body);
1631
+ } else {
1632
+ // A card: the kind, then where it comes from — this repo, branch and machine — so the
1633
+ // phone says what is going on without the agent having to spell it out.
1634
+ const kind = Object.keys(KINDS).find((k) => flags[k]) || "info";
1635
+ const fields = typeof flags.card === "string" ? JSON.parse(flags.card) : { kind, text, log, ...tellContext() };
1636
+ if (file) await sendFile(token, chat.id, file, card({ ...fields, max: 1024 }), { html: true });
1637
+ else await sendText(token, chat.id, card(fields), { html: true });
1638
+ }
1608
1639
  console.log(C.green("✓ sent"));
1609
1640
  } catch (e) { fail(e.message); }
1610
1641
  }
@@ -1782,7 +1813,7 @@ function holdsCmd() {
1782
1813
  // (`--no-attach`). The value form has to be CONSUMED: filtering out everything starting with
1783
1814
  // `--` and keeping the rest as positionals read `seldon go --agent claude` as the project
1784
1815
  // named "claude".
1785
- const VALUE_FLAGS = new Set(["agent", "model", "effort", "name", "port", "pm", "stall", "dir", "for", "wait", "as", "note", "interval", "task", "owner", "file", "token-name"]);
1816
+ const VALUE_FLAGS = new Set(["agent", "model", "effort", "name", "port", "pm", "stall", "dir", "for", "wait", "as", "note", "interval", "task", "owner", "file", "token-name", "card"]);
1786
1817
  function parseArgv(raw) {
1787
1818
  const flags = {}, positional = [];
1788
1819
  for (let i = 0; i < raw.length; i++) {
package/lib/telegram.mjs CHANGED
@@ -11,6 +11,7 @@
11
11
  import { readFileSync, writeFileSync, mkdirSync, statSync } from "node:fs";
12
12
  import { join, basename } from "node:path";
13
13
  import { SELDON_HOME } from "./agents.mjs";
14
+ import { ago } from "./home.mjs";
14
15
 
15
16
  export const TOKEN_NAME = "TELEGRAM_BOT_TOKEN";
16
17
  // The comb name the token is stored under: TELEGRAM_BOT_TOKEN unless setup was told another.
@@ -65,10 +66,45 @@ export const getUpdates = (token) => call(token, "getUpdates", { allowed_updates
65
66
  export const pollUpdates = (token, offset, timeout = 50) =>
66
67
  call(token, "getUpdates", { offset, timeout, allowed_updates: ["message"] });
67
68
 
68
- export async function sendText(token, chatId, text) {
69
+ // Plain text is split to fit; a card (HTML) is built to fit already, so it goes as one.
70
+ export async function sendText(token, chatId, text, { html = false } = {}) {
71
+ if (html) return void await call(token, "sendMessage", { chat_id: chatId, text, parse_mode: "HTML", disable_web_page_preview: true });
69
72
  for (const part of chunks(text)) await call(token, "sendMessage", { chat_id: chatId, text: part, disable_web_page_preview: true });
70
73
  }
71
74
 
75
+ // ---- cards: what happened, where, and what to do — readable at a glance ---------------
76
+ // Telegram has no colours in text; a coloured dot carries it. One kind per message.
77
+ export const KINDS = {
78
+ done: { dot: "🟢", label: "DONE" },
79
+ need: { dot: "🟠", label: "NEEDS YOU" },
80
+ fail: { dot: "🔴", label: "FAILED" },
81
+ wip: { dot: "🟡", label: "WORKING" },
82
+ info: { dot: "🔵", label: "INFO" },
83
+ };
84
+ export const escHtml = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
85
+ const clip = (s, n) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
86
+
87
+ // Every part is optional but the kind. `log` is shown as code (its tail: the end of a log is
88
+ // what matters). `max` keeps the whole card under Telegram's limit — 1024 for a caption.
89
+ export function card({ kind = "info", text, log, project, branch, lane, harness, detail, age, machine, link, max = MAX } = {}) {
90
+ const k = KINDS[kind] || KINDS.info;
91
+ const e = escHtml;
92
+ const meta = [age && `⏱ ${e(age)}`, machine && `💻 ${e(machine)}`].filter(Boolean).join(" · ");
93
+ const top = [
94
+ `${k.dot} <b>${k.label}</b>` + (project ? ` · <b>${e(project)}</b>` : "") + (branch ? ` <i>(${e(branch)})</i>` : ""),
95
+ lane && `▸ <b>${e(lane)}</b>${harness ? ` · ${e(harness)}` : ""}`,
96
+ detail && `⏳ ${e(detail)}`,
97
+ ].filter(Boolean);
98
+ const bottom = [meta && `<i>${meta}</i>`, link && `👉 <a href="${e(link)}">open the app</a>`].filter(Boolean);
99
+ // The free text gets whatever room the frame leaves (escaping can grow it, hence the margin).
100
+ const room = Math.max(0, max - [...top, ...bottom].join("\n").length - 60);
101
+ const words = text && e(clip(String(text).trim(), Math.floor(room * (log ? 0.4 : 1) / 1.2)));
102
+ const tail = log && String(log).trimEnd();
103
+ const logRoom = Math.floor(room * 0.55 / 1.2);
104
+ const code = tail && `<pre>${e(tail.length > logRoom ? "…" + tail.slice(-logRoom) : tail)}</pre>`;
105
+ return [...top, words, code, ...bottom].filter(Boolean).join("\n");
106
+ }
107
+
72
108
  // How a file shows up in the chat: images inline, videos playable, GIFs animated, audio as a
73
109
  // track, anything else as a document.
74
110
  export function mediaKind(path) {
@@ -80,13 +116,14 @@ export function mediaKind(path) {
80
116
  return { method: "sendDocument", field: "document" };
81
117
  }
82
118
 
83
- export async function sendFile(token, chatId, path, caption = "") {
119
+ export async function sendFile(token, chatId, path, caption = "", { html = false } = {}) {
84
120
  const size = statSync(path).size;
85
121
  if (size > MAX_UPLOAD) throw new Error(`${basename(path)} is ${(size / 1048576).toFixed(0)} MB — Telegram bots can send up to 50 MB`);
86
122
  const { method, field } = mediaKind(path);
87
123
  const form = new FormData();
88
124
  form.set("chat_id", String(chatId));
89
- if (caption) form.set("caption", caption.slice(0, 1024));
125
+ if (caption) form.set("caption", html ? caption : caption.slice(0, 1024));
126
+ if (caption && html) form.set("parse_mode", "HTML");
90
127
  if (method === "sendVideo") form.set("supports_streaming", "true");
91
128
  form.set(field, new Blob([readFileSync(path)]), basename(path));
92
129
  await call(token, method, form);
@@ -129,3 +166,18 @@ export async function downloadFile(token, fileId, dest) {
129
166
  // A reaction on your message says it is saved, without a reply cluttering the chat.
130
167
  export const react = (token, chatId, messageId, emoji) =>
131
168
  call(token, "setMessageReaction", { chat_id: chatId, message_id: messageId, reaction: [{ type: "emoji", emoji }] }).catch(() => {});
169
+
170
+ // The watcher's news as a card: which agent, on what, what it is waiting for, for how long,
171
+ // and — when the phone app is on the tailnet — a link straight to it.
172
+ const WATCH_KIND = { "needs-you": "need", failed: "fail", idle: "done" };
173
+ const WATCH_DETAIL = { failed: "ended with an error", idle: "finished its turn — ready for the next task" };
174
+ export function watchCard(e, { machine = null, link = null, now = Date.now() } = {}) {
175
+ return {
176
+ kind: WATCH_KIND[e.to] || "info",
177
+ project: basename(e.lane.project || e.lane.cwd || "") || null,
178
+ lane: e.lane.name || e.lane.id, harness: e.lane.harness,
179
+ detail: e.to === "needs-you" ? (e.lane.waitingFor || "waiting for you") : WATCH_DETAIL[e.to] || e.to,
180
+ age: e.lane.startedAt ? `running ${ago(e.lane.startedAt, now)}` : null,
181
+ machine, link,
182
+ };
183
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gorlitzer-labs/seldon",
3
- "version": "0.15.0",
3
+ "version": "0.16.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": {