@gorlitzer-labs/seldon 0.16.0 → 0.17.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
@@ -182,6 +182,12 @@ seldon tell --file out/pitch.mp4 --info "first cut" # a file, the card as i
182
182
  seldon tell --plain "just text" # no card
183
183
  ```
184
184
 
185
+ **Write Markdown — it renders.** `**bold**` `*italic*` `~~strike~~` `||spoiler||` `` `code` ``,
186
+ fenced blocks with a language, `[links](https://…)`, `#` headings, `-` lists, `>` quotes, `---`.
187
+ Anything else is shown exactly as written (`snake_case`, `2*3`, `<tags>` stay literal), and if
188
+ Telegram ever rejects the formatting the card is resent as plain text, so nothing is lost. A
189
+ piped log over a few lines folds away — tap it to open.
190
+
185
191
  Every message is a card that reads at a glance: a coloured dot for what kind of news it is,
186
192
  then where it comes from (the repo, branch and machine it was sent from), then what happened.
187
193
  The watcher's cards also name the agent, what it is waiting for, how long it has run, and link
package/bin/seldon.js CHANGED
@@ -15,7 +15,7 @@ import { startLane, stopLane, resumeLane, removeLane, findLane } from "../lib/ac
15
15
  import { listMachines, addMachine, fetchLanes, remoteGroups, sshArgs, lastJsonLine } from "../lib/machines.mjs";
16
16
  import { notify } from "../lib/notify.mjs";
17
17
  import { serve, serveToken, ownerFromStatus } from "../lib/serve.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
+ import { sendCard, watchCard, KINDS, tokenName, readChat, writeChat, chatFromUpdates, getUpdates, sendText, sendFile, pollUpdates, fileFromMessage, inboxName, noteLine, downloadFile, react, MAX_DOWNLOAD } from "../lib/telegram.mjs";
19
19
  import { reportFromEvent, mergeCodexHooks, removeCodexHooks, opencodePlugin } from "../lib/reports.mjs";
20
20
  import { buildRows, headline, ago, laneDetail, unlistedAgents, GLYPH } from "../lib/home.mjs";
21
21
  import { parseDuration, describe as describeHold, NAME_RE, DEFAULT_FOR_MS } from "../lib/holds.mjs";
@@ -1605,6 +1605,13 @@ function tellContext(cwd = process.cwd()) {
1605
1605
  return { project: root ? path.basename(root) : null, branch: branch && branch !== "HEAD" ? branch : null, machine: os.hostname().split(".")[0] };
1606
1606
  }
1607
1607
 
1608
+ // Something was piped or redirected in (`cmd | seldon tell`, `< file`). Not "stdin is not a
1609
+ // terminal": an agent's shell hands its commands an open socket that never sends or closes,
1610
+ // and reading that would hang the agent forever.
1611
+ function pipedIn() {
1612
+ try { const s = fs.fstatSync(0); return s.isFIFO() || s.isFile(); } catch { return false; }
1613
+ }
1614
+
1608
1615
  async function tellCmd(words, flags) {
1609
1616
  const fail = (msg) => { console.error(C.red(msg)); process.exitCode = 1; };
1610
1617
  const t = telegramToken(flags);
@@ -1612,17 +1619,21 @@ async function tellCmd(words, flags) {
1612
1619
  const { token, name } = t;
1613
1620
  try {
1614
1621
  if (flags.setup) {
1615
- const chat = chatFromUpdates(await getUpdates(token));
1622
+ const updates = await getUpdates(token).catch((e) => {
1623
+ if (/conflict|terminated by other getUpdates/i.test(e.message)) throw new Error("something else is reading this bot (seldon inbox?) — stop it, run --setup, then start it again");
1624
+ throw e;
1625
+ });
1626
+ const chat = chatFromUpdates(updates);
1616
1627
  if (!chat) return fail("no message to the bot yet — open your bot in Telegram, send it /start, then run this again");
1617
1628
  writeChat({ ...chat, ...(name !== "TELEGRAM_BOT_TOKEN" ? { tokenName: name } : {}) });
1618
- await sendText(token, chat.id, "✓ seldon is connected. Agents can reach you here with: seldon tell \"…\"");
1629
+ await sendCard(token, chat.id, { kind: "done", text: "**seldon is connected.**\nAgents reach you here with `seldon tell --done \"…\"`; send this chat a photo, file or note and `seldon inbox` saves it on your machine.", machine: os.hostname().split(".")[0] });
1619
1630
  return console.log(C.green(`✓ connected to ${chat.name || "your chat"}`) + C.dim(" — try: seldon tell \"hello\""));
1620
1631
  }
1621
1632
  const chat = readChat();
1622
1633
  if (!chat) return fail("not set up yet — send your bot /start in Telegram, then: seldon tell --setup");
1623
1634
  const text = words.join(" ");
1624
1635
  let log = "";
1625
- if (!process.stdin.isTTY && !flags.card) { for await (const c of process.stdin) log += c; log = log.trim(); }
1636
+ if (pipedIn() && !flags.card) { for await (const c of process.stdin) log += c; log = log.trim(); }
1626
1637
  const file = typeof flags.file === "string" ? flags.file : null;
1627
1638
  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
1639
  if (flags.plain) {
@@ -1633,8 +1644,7 @@ async function tellCmd(words, flags) {
1633
1644
  // phone says what is going on without the agent having to spell it out.
1634
1645
  const kind = Object.keys(KINDS).find((k) => flags[k]) || "info";
1635
1646
  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 });
1647
+ await sendCard(token, chat.id, fields, file);
1638
1648
  }
1639
1649
  console.log(C.green("✓ sent"));
1640
1650
  } catch (e) { fail(e.message); }
@@ -1681,7 +1691,7 @@ async function inboxCmd(flags) {
1681
1691
  await react(t.token, chat.id, m.message_id, "👍");
1682
1692
  } catch (e) {
1683
1693
  console.log(`${stamp()} ${e.message}`);
1684
- await sendText(t.token, chat.id, `✗ not saved: ${e.message}`).catch(() => {});
1694
+ await sendCard(t.token, chat.id, { kind: "fail", text: `**Not saved:** ${e.message}`, machine: os.hostname().split(".")[0] }).catch(() => {});
1685
1695
  }
1686
1696
  }
1687
1697
  }
package/lib/telegram.mjs CHANGED
@@ -84,6 +84,64 @@ export const KINDS = {
84
84
  export const escHtml = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
85
85
  const clip = (s, n) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
86
86
 
87
+ // ---- Markdown → Telegram HTML -----------------------------------------------------
88
+ // Agents write Markdown; Telegram renders a small HTML set. This turns the common subset into
89
+ // it: **bold** *italic* _italic_ ~~strike~~ ||spoiler|| `code`, ```lang fenced blocks```,
90
+ // [text](https://…), # headings, - lists, 1. lists, > quotes, ---. Everything is escaped
91
+ // first, so text can never inject a tag; what isn't Markdown is shown as written.
92
+ // Telegram rejects badly nested tags — sendCard falls back to plain text when it does.
93
+ const SAFE_URL = /^(https?:\/\/|tg:\/\/|mailto:)/i;
94
+
95
+ function inline(line) {
96
+ const keep = [];
97
+ const hold = (html) => `\u0000${keep.push(html) - 1}\u0000`;
98
+ let s = escHtml(line)
99
+ .replace(/`([^`\n]+)`/g, (_, c) => hold(`<code>${c}</code>`))
100
+ .replace(/\[([^\]\n]+)\]\(([^)\s]+)\)/g, (m, label, url) => SAFE_URL.test(url) ? hold(`<a href="${url}">${label}</a>`) : m)
101
+ .replace(/\*\*(?=\S)([^*\n]+?)\*\*/g, "<b>$1</b>")
102
+ .replace(/__(?=\S)([^_\n]+?)__/g, "<b>$1</b>")
103
+ .replace(/~~(?=\S)([^~\n]+?)~~/g, "<s>$1</s>")
104
+ .replace(/\|\|(?=\S)([^|\n]+?)\|\|/g, "<tg-spoiler>$1</tg-spoiler>")
105
+ .replace(/(^|[\s(])\*(?=\S)([^*\n]+?)\*(?=$|[\s).,:;!?])/g, "$1<i>$2</i>")
106
+ .replace(/(^|[\s(])_(?=\S)([^_\n]+?)_(?=$|[\s).,:;!?])/g, "$1<i>$2</i>"); // not snake_case
107
+ return s.replace(/\u0000(\d+)\u0000/g, (_, i) => keep[i]);
108
+ }
109
+
110
+ export function mdToHtml(text) {
111
+ const out = [];
112
+ const lines = String(text ?? "").replace(/\r\n?/g, "\n").split("\n");
113
+ let quote = [];
114
+ const flush = () => { if (quote.length) { out.push(`<blockquote>${quote.join("\n")}</blockquote>`); quote = []; } };
115
+ for (let i = 0; i < lines.length; i++) {
116
+ const line = lines[i];
117
+ const fence = line.match(/^\s*```\s*([\w+#.-]*)\s*$/);
118
+ if (fence) { // a fenced block, to its closing fence (or the end)
119
+ flush();
120
+ const body = [];
121
+ while (++i < lines.length && !/^\s*```\s*$/.test(lines[i])) body.push(lines[i]);
122
+ const lang = fence[1] ? ` class="language-${escHtml(fence[1])}"` : "";
123
+ out.push(`<pre><code${lang}>${escHtml(body.join("\n"))}</code></pre>`);
124
+ continue;
125
+ }
126
+ const q = line.match(/^\s*>\s?(.*)$/);
127
+ if (q) { quote.push(inline(q[1])); continue; }
128
+ flush();
129
+ let m;
130
+ if ((m = line.match(/^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$/))) out.push(`<b>${inline(m[1])}</b>`);
131
+ else if ((m = line.match(/^(\s*)[-*+]\s+(.*)$/))) out.push(`${m[1].replace(/\t/g, " ")}• ${inline(m[2])}`);
132
+ else if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) out.push("──────────");
133
+ else out.push(inline(line));
134
+ }
135
+ flush();
136
+ return out.join("\n");
137
+ }
138
+
139
+ // The same card without tags: what is sent when Telegram rejects the HTML.
140
+ export const htmlToPlain = (html) => String(html)
141
+ .replace(/<a href="([^"]*)">([^<]*)<\/a>/g, (_, url, label) => (label === url ? label : `${label} (${url})`))
142
+ .replace(/<[^>]+>/g, "")
143
+ .replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&amp;/g, "&");
144
+
87
145
  // Every part is optional but the kind. `log` is shown as code (its tail: the end of a log is
88
146
  // what matters). `max` keeps the whole card under Telegram's limit — 1024 for a caption.
89
147
  export function card({ kind = "info", text, log, project, branch, lane, harness, detail, age, machine, link, max = MAX } = {}) {
@@ -98,10 +156,13 @@ export function card({ kind = "info", text, log, project, branch, lane, harness,
98
156
  const bottom = [meta && `<i>${meta}</i>`, link && `👉 <a href="${e(link)}">open the app</a>`].filter(Boolean);
99
157
  // The free text gets whatever room the frame leaves (escaping can grow it, hence the margin).
100
158
  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)));
159
+ const words = text && mdToHtml(clip(String(text).trim(), Math.floor(room * (log ? 0.4 : 1) / 1.2)));
102
160
  const tail = log && String(log).trimEnd();
103
161
  const logRoom = Math.floor(room * 0.55 / 1.2);
104
- const code = tail && `<pre>${e(tail.length > logRoom ? "…" + tail.slice(-logRoom) : tail)}</pre>`;
162
+ const shown = tail && (tail.length > logRoom ? "…" + tail.slice(-logRoom) : tail);
163
+ // A short log shows as is; a long one folds away (tap to open), so the card stays readable.
164
+ const folds = shown && (shown.split("\n").length > 8 || shown.length > 500);
165
+ const code = shown && (folds ? `<blockquote expandable><pre>${e(shown)}</pre></blockquote>` : `<pre>${e(shown)}</pre>`);
105
166
  return [...top, words, code, ...bottom].filter(Boolean).join("\n");
106
167
  }
107
168
 
@@ -181,3 +242,16 @@ export function watchCard(e, { machine = null, link = null, now = Date.now() } =
181
242
  machine, link,
182
243
  };
183
244
  }
245
+
246
+ // Send a card — as a message, or as a file's caption. If Telegram rejects the formatting (badly
247
+ // nested Markdown), the same card goes out as plain text: a message is never lost to styling.
248
+ export async function sendCard(token, chatId, fields, file = null) {
249
+ const html = card({ ...fields, max: file ? 1024 : MAX });
250
+ try {
251
+ return file ? await sendFile(token, chatId, file, html, { html: true }) : await sendText(token, chatId, html, { html: true });
252
+ } catch (e) {
253
+ if (!/can't parse entities/i.test(e.message)) throw e;
254
+ const plain = htmlToPlain(html);
255
+ return file ? await sendFile(token, chatId, file, plain) : await sendText(token, chatId, plain);
256
+ }
257
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gorlitzer-labs/seldon",
3
- "version": "0.16.0",
3
+ "version": "0.17.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": {