@gorlitzer-labs/seldon 0.14.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 +16 -3
- package/bin/seldon.js +108 -21
- package/lib/telegram.mjs +100 -6
- package/package.json +1 -1
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 "
|
|
179
|
-
|
|
180
|
-
seldon tell --
|
|
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
|
|
|
@@ -191,6 +198,12 @@ your chat and keeps its id in `~/.seldon/telegram.json`). Stored it under anothe
|
|
|
191
198
|
- **The token never shows.** seldon does not store it: without it in the environment,
|
|
192
199
|
`seldon tell` re-runs itself under `comb run --with TELEGRAM_BOT_TOKEN`, so an agent can send
|
|
193
200
|
without ever seeing it. Every machine with comb synced can send.
|
|
201
|
+
- **Your phone โ this machine: `seldon inbox`.** Send the bot a screenshot, video, file, voice
|
|
202
|
+
note or a line of text and it lands in `~/Downloads/seldon-inbox/` (`--dir` for another),
|
|
203
|
+
with a ๐ on your message once it is saved and one line per item in `notes.md`. Plain code,
|
|
204
|
+
no agent in between, no tokens; only your chat is listened to. A bot can fetch up to 20 MB,
|
|
205
|
+
and Telegram compresses photos โ *Send as File* for the original. Telegram itself still
|
|
206
|
+
carries everything (a bot chat is not end-to-end encrypted).
|
|
194
207
|
- **Sending only.** Any number of sessions can send through one bot. Writing *to* an agent from
|
|
195
208
|
Telegram (text, or a screenshot from your phone) is Claude Code's own Telegram channel
|
|
196
209
|
(`claude --channels plugin:telegram@claude-plugins-official`), and the same bot works for
|
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 } 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";
|
|
@@ -1435,6 +1436,7 @@ ${C.bold("seldon")} โ the agent factory: your projects, and the stack that run
|
|
|
1435
1436
|
${C.bold("seldon up --tailnet")} expose the voice over HTTPS (tailscale serve) so the mic works on your phone
|
|
1436
1437
|
${C.bold("seldon serve")} [--tailnet] the panel as a phone web app (--allow-reply to answer agents)
|
|
1437
1438
|
${C.bold("seldon tell")} "โฆ" message yourself on Telegram (--file to send one; --setup once)
|
|
1439
|
+
${C.bold("seldon inbox")} [--dir d] save what you send the bot to a folder here (no agent, no tokens)
|
|
1438
1440
|
${C.bold("seldon up --brain=X")} pick the voice brain: qwen (in-process) | bonsai (local server); remembered
|
|
1439
1441
|
${C.bold("seldon status")} what's running ยท ${C.bold("seldon down")} stop it
|
|
1440
1442
|
${C.bold("seldon adopt")} [dir] put an existing repo on the line: foundation docs (never overwritten),
|
|
@@ -1468,18 +1470,28 @@ const startWatch = () => startDaemon("seldon-watch", process.execPath, [SELF, "w
|
|
|
1468
1470
|
|
|
1469
1471
|
// The watcher's news on the phone too, once `seldon tell --setup` has been run. A child
|
|
1470
1472
|
// `seldon tell` per event, so the token goes through comb exactly as it does for an agent.
|
|
1471
|
-
function tellInBackground(
|
|
1473
|
+
function tellInBackground(fields) {
|
|
1472
1474
|
if (process.env.SELDON_NO_NOTIFY || !readChat()) return;
|
|
1473
|
-
const child = spawn(process.execPath, [process.argv[1], "tell",
|
|
1475
|
+
const child = spawn(process.execPath, [process.argv[1], "tell", "--card", JSON.stringify(fields)], { stdio: "ignore", detached: true });
|
|
1474
1476
|
child.on("error", () => {}); child.unref();
|
|
1475
1477
|
}
|
|
1476
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
|
+
|
|
1477
1488
|
async function watchCmd(flags) {
|
|
1478
1489
|
ensureSiblingPath();
|
|
1479
1490
|
const every = parseDuration(flags.interval, 5000) || 5000;
|
|
1480
1491
|
let prev = new Map();
|
|
1481
1492
|
const stamp = () => new Date().toTimeString().slice(0, 8);
|
|
1482
1493
|
console.log(`${stamp()} seldon watch โ every ${every / 1000}s`);
|
|
1494
|
+
const phone = phoneAppUrl(); // once: the link the phone cards carry
|
|
1483
1495
|
for (;;) {
|
|
1484
1496
|
let lanes = [];
|
|
1485
1497
|
try { lanes = readLanes().flatMap((g) => g.lanes); } catch (e) { console.log(`${stamp()} read failed: ${e.message}`); }
|
|
@@ -1487,7 +1499,7 @@ async function watchCmd(flags) {
|
|
|
1487
1499
|
console.log(`${stamp()} ${e.text}`);
|
|
1488
1500
|
const where = path.basename(e.lane.project || e.lane.cwd || "");
|
|
1489
1501
|
notify(e.to === "needs-you" ? "Seldon ยท needs you" : "Seldon", `${e.text} โ ${where}`);
|
|
1490
|
-
tellInBackground(
|
|
1502
|
+
tellInBackground(watchCard(e, { machine: os.hostname().split(".")[0], link: phone }));
|
|
1491
1503
|
}
|
|
1492
1504
|
prev = new Map(lanes.map((l) => [l.key, l.state]));
|
|
1493
1505
|
if (flags.once) return;
|
|
@@ -1569,19 +1581,35 @@ function serveCmd(flags) {
|
|
|
1569
1581
|
// `seldon tell "โฆ"` โ message the operator on Telegram, from any agent. The token comes from
|
|
1570
1582
|
// comb in the environment: without it, seldon re-runs itself under `comb run`, so the value
|
|
1571
1583
|
// is never in an argument, a file seldon writes, or the agent's transcript.
|
|
1572
|
-
|
|
1573
|
-
|
|
1584
|
+
// The bot token, from the environment. Without it, re-run this same command under
|
|
1585
|
+
// `comb run` (which puts it there) and return null: the child does the work.
|
|
1586
|
+
function telegramToken(flags) {
|
|
1587
|
+
const fail = (msg) => { console.error(C.red(msg)); process.exitCode = 1; return null; };
|
|
1574
1588
|
const name = typeof flags["token-name"] === "string" ? flags["token-name"] : tokenName();
|
|
1575
1589
|
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) return fail(`not a secret name: ${name}`);
|
|
1576
|
-
|
|
1577
|
-
if (
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1590
|
+
if (process.env[name]) return { token: process.env[name], name };
|
|
1591
|
+
if (process.env.SELDON_TELL_VIA_COMB) return fail(`comb has no ${name} โ store it once: comb set ${name}`);
|
|
1592
|
+
if (!has("comb")) return fail(`no ${name} in the environment, and comb is not installed (seldon install comb)`);
|
|
1593
|
+
const r = spawnSync("comb", ["run", "--with", name, "--", process.execPath, process.argv[1], ...process.argv.slice(2)],
|
|
1594
|
+
{ stdio: "inherit", env: { ...process.env, SELDON_TELL_VIA_COMB: "1" } });
|
|
1595
|
+
process.exitCode = r.status ?? 1;
|
|
1596
|
+
return null;
|
|
1597
|
+
}
|
|
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
|
+
|
|
1608
|
+
async function tellCmd(words, flags) {
|
|
1609
|
+
const fail = (msg) => { console.error(C.red(msg)); process.exitCode = 1; };
|
|
1610
|
+
const t = telegramToken(flags);
|
|
1611
|
+
if (!t) return;
|
|
1612
|
+
const { token, name } = t;
|
|
1585
1613
|
try {
|
|
1586
1614
|
if (flags.setup) {
|
|
1587
1615
|
const chat = chatFromUpdates(await getUpdates(token));
|
|
@@ -1592,15 +1620,73 @@ async function tellCmd(words, flags) {
|
|
|
1592
1620
|
}
|
|
1593
1621
|
const chat = readChat();
|
|
1594
1622
|
if (!chat) return fail("not set up yet โ send your bot /start in Telegram, then: seldon tell --setup");
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
if (
|
|
1598
|
-
|
|
1599
|
-
|
|
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
|
+
}
|
|
1600
1639
|
console.log(C.green("โ sent"));
|
|
1601
1640
|
} catch (e) { fail(e.message); }
|
|
1602
1641
|
}
|
|
1603
1642
|
|
|
1643
|
+
// `seldon inbox` โ what you send the bot from your phone lands in a folder here: photos,
|
|
1644
|
+
// videos, files, voice notes, and text into notes.md. Plain code, no agent in between, no
|
|
1645
|
+
// tokens. Only your chat (from `seldon tell --setup`) is listened to; anyone else is ignored.
|
|
1646
|
+
async function inboxCmd(flags) {
|
|
1647
|
+
const fail = (msg) => { console.error(C.red(msg)); process.exitCode = 1; };
|
|
1648
|
+
const chat = readChat();
|
|
1649
|
+
if (!chat) return fail("not set up yet โ send your bot /start in Telegram, then: seldon tell --setup");
|
|
1650
|
+
const t = telegramToken(flags);
|
|
1651
|
+
if (!t) return;
|
|
1652
|
+
const dir = path.resolve(typeof flags.dir === "string" ? flags.dir : path.join(process.env.HOME, "Downloads", "seldon-inbox"));
|
|
1653
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
1654
|
+
const stamp = () => new Date().toTimeString().slice(0, 8);
|
|
1655
|
+
console.log(`${stamp()} seldon inbox โ ${dir}`);
|
|
1656
|
+
let offset;
|
|
1657
|
+
for (;;) {
|
|
1658
|
+
let updates;
|
|
1659
|
+
try { updates = (await pollUpdates(t.token, offset)).result; }
|
|
1660
|
+
catch (e) {
|
|
1661
|
+
console.log(`${stamp()} ${e.message}`);
|
|
1662
|
+
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");
|
|
1663
|
+
await new Promise((r) => setTimeout(r, 5000)); continue;
|
|
1664
|
+
}
|
|
1665
|
+
for (const u of updates) {
|
|
1666
|
+
offset = u.update_id + 1;
|
|
1667
|
+
const m = u.message;
|
|
1668
|
+
if (!m || m.chat?.id !== chat.id) continue;
|
|
1669
|
+
const when = m.date * 1000, f = fileFromMessage(m), text = m.caption || m.text || "";
|
|
1670
|
+
try {
|
|
1671
|
+
if (f) {
|
|
1672
|
+
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`);
|
|
1673
|
+
const name = inboxName(f.name, when);
|
|
1674
|
+
await downloadFile(t.token, f.fileId, path.join(dir, name));
|
|
1675
|
+
fs.appendFileSync(path.join(dir, "notes.md"), noteLine(when, { file: name, text }), { mode: 0o600 });
|
|
1676
|
+
console.log(`${stamp()} saved ${name}`);
|
|
1677
|
+
} else if (text && !text.startsWith("/")) {
|
|
1678
|
+
fs.appendFileSync(path.join(dir, "notes.md"), noteLine(when, { text }), { mode: 0o600 });
|
|
1679
|
+
console.log(`${stamp()} noted`);
|
|
1680
|
+
} else continue;
|
|
1681
|
+
await react(t.token, chat.id, m.message_id, "๐");
|
|
1682
|
+
} catch (e) {
|
|
1683
|
+
console.log(`${stamp()} ${e.message}`);
|
|
1684
|
+
await sendText(t.token, chat.id, `โ not saved: ${e.message}`).catch(() => {});
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1604
1690
|
// `seldon machines` โ the other computers the panel shows (bifrost's realms, one list).
|
|
1605
1691
|
function machinesCmd(verb, name, target) {
|
|
1606
1692
|
if (verb === "add") {
|
|
@@ -1727,7 +1813,7 @@ function holdsCmd() {
|
|
|
1727
1813
|
// (`--no-attach`). The value form has to be CONSUMED: filtering out everything starting with
|
|
1728
1814
|
// `--` and keeping the rest as positionals read `seldon go --agent claude` as the project
|
|
1729
1815
|
// named "claude".
|
|
1730
|
-
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"]);
|
|
1731
1817
|
function parseArgv(raw) {
|
|
1732
1818
|
const flags = {}, positional = [];
|
|
1733
1819
|
for (let i = 0; i < raw.length; i++) {
|
|
@@ -1783,6 +1869,7 @@ const ids = tokens.filter((id) => byId[id]); // only the valid module
|
|
|
1783
1869
|
if (cmd === "lane") return laneCmd(tokens[0], tokens[1], flags);
|
|
1784
1870
|
if (cmd === "serve") return serveCmd(flags);
|
|
1785
1871
|
if (cmd === "tell") return tellCmd(tokens, flags);
|
|
1872
|
+
if (cmd === "inbox") return inboxCmd(flags);
|
|
1786
1873
|
if (cmd === "setup") return setupCmd(tokens[0], flags);
|
|
1787
1874
|
if (cmd === "panel" || cmd === "board") return panel();
|
|
1788
1875
|
if (cmd && cmd !== "install") { help(); process.exitCode = 1; return; }
|
package/lib/telegram.mjs
CHANGED
|
@@ -5,12 +5,13 @@
|
|
|
5
5
|
// chat id is not a secret (it is useless without the token), so `seldon tell --setup` finds it
|
|
6
6
|
// once and keeps it in ~/.seldon/telegram.json.
|
|
7
7
|
//
|
|
8
|
-
// Sending
|
|
9
|
-
//
|
|
10
|
-
//
|
|
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
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.
|
|
@@ -60,11 +61,50 @@ async function call(token, method, body) {
|
|
|
60
61
|
}
|
|
61
62
|
|
|
62
63
|
export const getUpdates = (token) => call(token, "getUpdates", { allowed_updates: ["message"] });
|
|
64
|
+
// Long polling: Telegram holds the request until something arrives (or `timeout` seconds pass).
|
|
65
|
+
// Asking with `offset` = last update_id + 1 also tells Telegram the earlier ones are handled.
|
|
66
|
+
export const pollUpdates = (token, offset, timeout = 50) =>
|
|
67
|
+
call(token, "getUpdates", { offset, timeout, allowed_updates: ["message"] });
|
|
63
68
|
|
|
64
|
-
|
|
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 });
|
|
65
72
|
for (const part of chunks(text)) await call(token, "sendMessage", { chat_id: chatId, text: part, disable_web_page_preview: true });
|
|
66
73
|
}
|
|
67
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) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[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
|
+
|
|
68
108
|
// How a file shows up in the chat: images inline, videos playable, GIFs animated, audio as a
|
|
69
109
|
// track, anything else as a document.
|
|
70
110
|
export function mediaKind(path) {
|
|
@@ -76,14 +116,68 @@ export function mediaKind(path) {
|
|
|
76
116
|
return { method: "sendDocument", field: "document" };
|
|
77
117
|
}
|
|
78
118
|
|
|
79
|
-
export async function sendFile(token, chatId, path, caption = "") {
|
|
119
|
+
export async function sendFile(token, chatId, path, caption = "", { html = false } = {}) {
|
|
80
120
|
const size = statSync(path).size;
|
|
81
121
|
if (size > MAX_UPLOAD) throw new Error(`${basename(path)} is ${(size / 1048576).toFixed(0)} MB โ Telegram bots can send up to 50 MB`);
|
|
82
122
|
const { method, field } = mediaKind(path);
|
|
83
123
|
const form = new FormData();
|
|
84
124
|
form.set("chat_id", String(chatId));
|
|
85
|
-
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");
|
|
86
127
|
if (method === "sendVideo") form.set("supports_streaming", "true");
|
|
87
128
|
form.set(field, new Blob([readFileSync(path)]), basename(path));
|
|
88
129
|
await call(token, method, form);
|
|
89
130
|
}
|
|
131
|
+
|
|
132
|
+
// ---- the inbox: what you send the bot, saved on this machine ------------------------
|
|
133
|
+
export const MAX_DOWNLOAD = 20 * 1024 * 1024; // a bot may download up to 20 MB
|
|
134
|
+
|
|
135
|
+
// The one file in a message, if it carries one. A photo comes in several sizes: the largest.
|
|
136
|
+
export function fileFromMessage(m) {
|
|
137
|
+
if (!m) return null;
|
|
138
|
+
const pick = (f, fallback) => f && { fileId: f.file_id, size: f.file_size ?? null, name: f.file_name || fallback };
|
|
139
|
+
if (m.photo?.length) return pick(m.photo.at(-1), "photo.jpg");
|
|
140
|
+
return pick(m.document, "file") || pick(m.video, "video.mp4") || pick(m.animation, "animation.mp4")
|
|
141
|
+
|| pick(m.audio, "audio.mp3") || pick(m.voice, "voice.ogg") || pick(m.video_note, "video-note.mp4") || null;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// A name that is safe on disk and sorts by time: 20261031-091502-screenshot.png
|
|
145
|
+
export function inboxName(name, date) {
|
|
146
|
+
const base = String(name).split(/[\\/]/).pop().replace(/[^\w.-]+/g, "_").replace(/^\.+/, "").slice(-120) || "file";
|
|
147
|
+
const d = new Date(date), p = (n) => String(n).padStart(2, "0");
|
|
148
|
+
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}-${base}`;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// One line in notes.md per thing received, so the folder reads as a log.
|
|
152
|
+
export function noteLine(date, { file, text }) {
|
|
153
|
+
const d = new Date(date), p = (n) => String(n).padStart(2, "0");
|
|
154
|
+
const when = `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
|
155
|
+
const body = String(text || "").replace(/\s*\n\s*/g, " โ ").trim();
|
|
156
|
+
return `- ${when} ยท ${file ? `[${file}](${encodeURI(file)})${body ? ` โ ${body}` : ""}` : body}\n`;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export async function downloadFile(token, fileId, dest) {
|
|
160
|
+
const { result } = await call(token, "getFile", { file_id: fileId });
|
|
161
|
+
const r = await fetch(`https://api.telegram.org/file/bot${token}/${result.file_path}`);
|
|
162
|
+
if (!r.ok) throw new Error(`telegram download: ${r.status}`);
|
|
163
|
+
writeFileSync(dest, Buffer.from(await r.arrayBuffer()), { mode: 0o600 });
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// A reaction on your message says it is saved, without a reply cluttering the chat.
|
|
167
|
+
export const react = (token, chatId, messageId, emoji) =>
|
|
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
|
+
}
|