@ouro.bot/cli 0.1.0-alpha.1350 → 0.1.0-alpha.1352

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/changelog.json CHANGED
@@ -1,6 +1,12 @@
1
1
  {
2
2
  "_note": "This changelog is maintained as part of the PR/version-bump workflow. Agent-curated, not auto-generated. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1352",
6
+ "changes": [
7
+ "Every agent's Telegram replies render Markdown (bold, italic, headings, lists, quotes, links, code, and tables as aligned monospace), split by block and measured after rendering; a refused chunk is resent with only code and links, then as plain text."
8
+ ]
9
+ },
4
10
  {
5
11
  "version": "0.1.0-alpha.1350",
6
12
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1350",
2
+ "runtimeVersion": "0.1.0-alpha.1352",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -1,7 +1,7 @@
1
1
  <?xml version="1.0"?>
2
2
  <Container version="2">
3
3
  <Name>ouro-butler</Name>
4
- <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1350</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1352</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -1,16 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TELEGRAM_APPROVAL_TOMBSTONE_TTL_MS = exports.TELEGRAM_APPROVAL_TERMINAL_EDIT_TIMEOUT_MS = exports.TELEGRAM_APPROVAL_EXPIRED_TEXT = exports.TELEGRAM_APPROVAL_TTL_MS = exports.FileTelegramPendingApprovalStore = exports.FileTelegramUpdateInboxStore = exports.TELEGRAM_TEST_ID_FLOOR = exports.TELEGRAM_ALLOWED_UPDATES = exports.FileTelegramOffsetStore = exports.MAX_TELEGRAM_UPLOAD_BYTES = exports.TelegramApiError = void 0;
3
+ exports.splitTelegramText = exports.escapeTelegramHtml = exports.TELEGRAM_APPROVAL_TOMBSTONE_TTL_MS = exports.TELEGRAM_APPROVAL_TERMINAL_EDIT_TIMEOUT_MS = exports.TELEGRAM_APPROVAL_EXPIRED_TEXT = exports.TELEGRAM_APPROVAL_TTL_MS = exports.FileTelegramPendingApprovalStore = exports.FileTelegramUpdateInboxStore = exports.TELEGRAM_TEST_ID_FLOOR = exports.TELEGRAM_ALLOWED_UPDATES = exports.FileTelegramOffsetStore = exports.MAX_TELEGRAM_UPLOAD_BYTES = exports.TelegramApiError = void 0;
4
4
  exports.isTelegramInputFile = isTelegramInputFile;
5
5
  exports.isTelegramTestId = isTelegramTestId;
6
6
  exports.telegramUpdateMessageCoordinates = telegramUpdateMessageCoordinates;
7
7
  exports.createTelegramLongPoll = createTelegramLongPoll;
8
8
  exports.classifyTelegramPersistedApprovalState = classifyTelegramPersistedApprovalState;
9
9
  exports.createTelegramApprovalTransport = createTelegramApprovalTransport;
10
- exports.escapeTelegramHtml = escapeTelegramHtml;
11
- exports.splitTelegramText = splitTelegramText;
12
10
  exports.sendTelegramText = sendTelegramText;
13
11
  exports.createTelegramBotApi = createTelegramBotApi;
12
+ const telegram_markdown_1 = require("./telegram-markdown");
13
+ Object.defineProperty(exports, "escapeTelegramHtml", { enumerable: true, get: function () { return telegram_markdown_1.escapeTelegramHtml; } });
14
+ Object.defineProperty(exports, "splitTelegramText", { enumerable: true, get: function () { return telegram_markdown_1.splitTelegramText; } });
14
15
  const runtime_1 = require("../nerves/runtime");
15
16
  const node_fs_1 = require("node:fs");
16
17
  const node_crypto_1 = require("node:crypto");
@@ -1607,59 +1608,8 @@ function createTelegramApprovalTransport(options) {
1607
1608
  return { handled: true, accepted: outcome.accepted, reason };
1608
1609
  }
1609
1610
  }
1610
- function escapeTelegramHtml(value) {
1611
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
1612
- }
1613
- function sourceIndexForRenderedLimit(value, limit) {
1614
- let renderedUnits = 0;
1615
- let sourceIndex = 0;
1616
- for (const character of value) {
1617
- const escaped = escapeTelegramHtml(character);
1618
- if (renderedUnits + escaped.length > limit)
1619
- break;
1620
- renderedUnits += escaped.length;
1621
- sourceIndex += character.length;
1622
- }
1623
- return sourceIndex;
1624
- }
1625
- function preferredBoundary(value, limit, minimum) {
1626
- const paragraph = value.lastIndexOf("\n\n", limit - 1);
1627
- if (paragraph >= minimum)
1628
- return paragraph + 2;
1629
- const newline = value.lastIndexOf("\n", limit - 1);
1630
- if (newline >= minimum)
1631
- return newline + 1;
1632
- for (let index = limit - 1; index >= minimum; index -= 1) {
1633
- if (/\s/u.test(value[index]))
1634
- return index + 1;
1635
- }
1636
- return limit;
1637
- }
1638
- function splitTelegramText(value, options = {}) {
1639
- const targetUnits = options.targetUnits ?? 1_200;
1640
- const maxUnits = options.maxUnits ?? 4_000;
1641
- if (!Number.isInteger(targetUnits) || !Number.isInteger(maxUnits) || targetUnits < 1 || maxUnits < targetUnits) {
1642
- throw new Error("Telegram chunk limits must be positive integers with targetUnits <= maxUnits");
1643
- }
1644
- if (!value)
1645
- return [""];
1646
- const chunks = [];
1647
- let remaining = value;
1648
- while (escapeTelegramHtml(remaining).length > maxUnits || escapeTelegramHtml(remaining).length > targetUnits) {
1649
- const targetIndex = sourceIndexForRenderedLimit(remaining, targetUnits);
1650
- const maxIndex = sourceIndexForRenderedLimit(remaining, maxUnits);
1651
- const candidate = targetIndex > 0 ? targetIndex : maxIndex;
1652
- if (candidate <= 0)
1653
- throw new Error("Telegram chunk limit cannot fit one character");
1654
- const splitAt = preferredBoundary(remaining, candidate, Math.floor(candidate / 2));
1655
- chunks.push(remaining.slice(0, splitAt));
1656
- remaining = remaining.slice(splitAt);
1657
- }
1658
- chunks.push(remaining);
1659
- return chunks;
1660
- }
1661
1611
  async function sendTelegramText(api, chatId, text, options = {}) {
1662
- const renderHtml = options.renderHtml ?? escapeTelegramHtml;
1612
+ const renderHtml = options.renderHtml ?? telegram_markdown_1.escapeTelegramHtml;
1663
1613
  const results = [];
1664
1614
  const recordMessageId = (value, chunk) => {
1665
1615
  const messageId = value && typeof value === "object" && !Array.isArray(value)
@@ -1670,7 +1620,7 @@ async function sendTelegramText(api, chatId, text, options = {}) {
1670
1620
  results.push(messageId);
1671
1621
  options.onMessageDelivered?.(messageId, chunk);
1672
1622
  };
1673
- for (const [index, chunk] of splitTelegramText(text).entries()) {
1623
+ for (const [index, chunk] of (options.split ?? telegram_markdown_1.splitTelegramText)(text).entries()) {
1674
1624
  const replyTo = index === 0 && options.replyToMessageId ? { reply_parameters: { message_id: options.replyToMessageId } } : {};
1675
1625
  try {
1676
1626
  recordMessageId(await api.request("sendMessage", {
@@ -1683,6 +1633,17 @@ async function sendTelegramText(api, chatId, text, options = {}) {
1683
1633
  catch (error) {
1684
1634
  if (!(error instanceof TelegramApiError) || error.status !== 400)
1685
1635
  throw error;
1636
+ if (options.fallbackHtml) {
1637
+ try {
1638
+ recordMessageId(await api.request("sendMessage", { chat_id: chatId, text: options.fallbackHtml(chunk), parse_mode: "HTML", ...replyTo }, options.signal), chunk);
1639
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "telegram.text_fallback_sent", message: "Telegram refused a chunk's HTML; it went out with only code and links kept", meta: { fallback: "safe_html" } });
1640
+ continue;
1641
+ }
1642
+ catch (retry) {
1643
+ if (!(retry instanceof TelegramApiError) || retry.status !== 400)
1644
+ throw retry;
1645
+ }
1646
+ }
1686
1647
  recordMessageId(await api.request("sendMessage", { chat_id: chatId, text: chunk }, options.signal), chunk);
1687
1648
  }
1688
1649
  }
@@ -55,6 +55,7 @@ const router_1 = require("../heart/external-events/router");
55
55
  const session_events_1 = require("../heart/session-events");
56
56
  const session_transaction_1 = require("../mind/session-transaction");
57
57
  const telegram_client_1 = require("./telegram-client");
58
+ const telegram_markdown_1 = require("./telegram-markdown");
58
59
  exports.FIXED_ADMISSION_ACKNOWLEDGEMENT = "Thanks — I’ve asked the person I work for. Your message is still unread and unprocessed; I’ll only read it if they welcome you in.";
59
60
  exports.FIXED_USENET_SYSTEM_FAILSAFE = "Quick heads-up: I paused downloads because the server was discarding most of what it fetched. Nothing needs doing this second — I’ll investigate and follow up when I’m back online.";
60
61
  const SYSTEM_FAILSAFE_UNAVAILABLE_MS = 2 * 60_000;
@@ -69,62 +70,14 @@ function requireText(value, label) {
69
70
  throw new Error(`${label} must be nonempty`);
70
71
  return value;
71
72
  }
73
+ const sameTexts = (parts, texts) => Array.isArray(parts) && parts.length === texts.length && parts.every((part, index) => part?.text === texts[index]);
72
74
  function preparedTexts(effect) {
73
75
  if (effect.kind === "text" || effect.kind === "admission_ack")
74
- return (0, telegram_client_1.splitTelegramText)(requireText(effect.text, "Telegram text"));
76
+ return (0, telegram_markdown_1.splitTelegramMarkdown)(requireText(effect.text, "Telegram text"));
75
77
  if (effect.kind === "card" || effect.kind === "edit")
76
78
  return [requireText(effect.text, "Telegram text")];
77
79
  return [effect.text?.trim() || null];
78
80
  }
79
- // Bold spans may carry one level of emphasis inside them, because `**bold with
80
- // *italic* inside**` is ordinary model prose. The inner span is rendered by the
81
- // same conservative scan, so a bold run that does not resolve cleanly still
82
- // degrades the whole message to literal text rather than emitting partial
83
- // markup. Everything else stays as strict as before: a span must open on a
84
- // letter or digit and close on a non-space, which is what keeps `**/src/**`,
85
- // `2 ** 3` and `a_b_c` literal.
86
- const TELEGRAM_BOLD_WITH_NESTING = /`([^`\n]+)`|\*\*([\p{L}\p{N}](?:[^*_`\n]|\*(?!\*)|_)*\S|[\p{L}\p{N}])\*\*|\*([\p{L}\p{N}](?:[^*_`\n]*\S)?)\*|_([\p{L}\p{N}](?:[^*_`\n]*\S)?)_/gu;
87
- const TELEGRAM_EMPHASIS_ONLY = /`([^`\n]+)`|\*([\p{L}\p{N}](?:[^*_`\n]*\S)?)\*|_([\p{L}\p{N}](?:[^*_`\n]*\S)?)_/gu;
88
- function renderTelegramButlerHtml(text) {
89
- return renderTelegramStyledSpan(text, true) ?? (0, telegram_client_1.escapeTelegramHtml)(text);
90
- }
91
- // Returns null when the span cannot be rendered cleanly, so every caller falls
92
- // back to escaping rather than emitting half-applied markup.
93
- function renderTelegramStyledSpan(text, allowBold) {
94
- let html = "";
95
- let cursor = 0;
96
- const pattern = allowBold ? TELEGRAM_BOLD_WITH_NESTING : TELEGRAM_EMPHASIS_ONLY;
97
- pattern.lastIndex = 0;
98
- for (const match of text.matchAll(pattern)) {
99
- const gap = text.slice(cursor, match.index);
100
- if (/[*_`]/u.test(gap))
101
- return null;
102
- html += (0, telegram_client_1.escapeTelegramHtml)(gap);
103
- const code = match[1];
104
- const bold = allowBold ? match[2] : undefined;
105
- const italic = allowBold ? match[3] : match[2];
106
- const underscored = allowBold ? match[4] : match[3];
107
- if (code !== undefined)
108
- html += `<code>${(0, telegram_client_1.escapeTelegramHtml)(code)}</code>`;
109
- else if (bold !== undefined) {
110
- const inner = renderTelegramStyledSpan(bold, false);
111
- if (inner === null)
112
- return null;
113
- html += `<b>${inner}</b>`;
114
- // A single-marker span is bold at the top level, which is the long-standing
115
- // convention here, but inside a bold run it is the nested emphasis the
116
- // author meant - and nesting <b> in <b> would be markup Telegram has no
117
- // reason to accept.
118
- }
119
- else if (italic !== undefined)
120
- html += allowBold ? `<b>${(0, telegram_client_1.escapeTelegramHtml)(italic)}</b>` : `<i>${(0, telegram_client_1.escapeTelegramHtml)(italic)}</i>`;
121
- else
122
- html += `<i>${(0, telegram_client_1.escapeTelegramHtml)(underscored)}</i>`;
123
- cursor = match.index + match[0].length;
124
- }
125
- const tail = text.slice(cursor);
126
- return /[*_`]/u.test(tail) ? null : html + (0, telegram_client_1.escapeTelegramHtml)(tail);
127
- }
128
81
  function assertEffectTarget(target, effect, idempotencyKey) {
129
82
  if (target.kind === "admission_gate") {
130
83
  if (effect.kind !== "admission_ack" || effect.text !== exports.FIXED_ADMISSION_ACKNOWLEDGEMENT || idempotencyKey !== `ack:${target.admissionId}`) {
@@ -178,6 +131,14 @@ function validateArtifact(artifact, expectedId) {
178
131
  if (targetValid && effectValid) {
179
132
  assertEffectTarget(target, effect, artifact.idempotencyKey);
180
133
  expectedTexts = preparedTexts(effect);
134
+ // A text prepared before Markdown splitting was cut by length; it stays valid so an upgrade never strands it.
135
+ if ((effect.kind === "text" || effect.kind === "admission_ack") && !sameTexts(artifact.parts, expectedTexts)) {
136
+ const legacy = (0, telegram_client_1.splitTelegramText)(effect.text);
137
+ if (sameTexts(artifact.parts, legacy)) {
138
+ expectedTexts = legacy;
139
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "telegram.legacy_split_accepted", message: "a Telegram text prepared under the earlier length split was accepted", meta: { parts: legacy.length } });
140
+ }
141
+ }
181
142
  }
182
143
  }
183
144
  catch {
@@ -416,9 +377,15 @@ function canonicalMessageId(result) {
416
377
  async function executePart(api, artifact, part, chatId, signal) {
417
378
  const effect = artifact.effect;
418
379
  if (effect.kind === "text" || effect.kind === "admission_ack") {
419
- const renderHtml = effect.kind === "text" && artifact.authorClass === "butler" ? renderTelegramButlerHtml : undefined;
380
+ // The agent's own words render as Markdown; fixed control texts go out escaped, as written.
381
+ const markdown = effect.kind === "text" && artifact.authorClass === "butler";
420
382
  const replyToMessageId = effect.kind === "text" && part.index === 0 ? effect.replyToMessageId : undefined;
421
- const ids = await (0, telegram_client_1.sendTelegramText)(api, chatId, part.text, { ...(signal ? { signal } : {}), ...(renderHtml ? { renderHtml } : {}), ...(replyToMessageId ? { replyToMessageId } : {}) });
383
+ const ids = await (0, telegram_client_1.sendTelegramText)(api, chatId, part.text, {
384
+ split: (text) => [text],
385
+ ...(signal ? { signal } : {}),
386
+ ...(markdown ? { renderHtml: telegram_markdown_1.renderTelegramMarkdown, fallbackHtml: telegram_markdown_1.renderTelegramMarkdownSafe } : {}),
387
+ ...(replyToMessageId ? { replyToMessageId } : {}),
388
+ });
422
389
  if (ids.length !== 1)
423
390
  throw new Error("Telegram effect chunk renderer returned an unexpected message count");
424
391
  return ids[0];
@@ -0,0 +1,331 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TELEGRAM_MESSAGE_LIMIT = void 0;
4
+ exports.escapeTelegramHtml = escapeTelegramHtml;
5
+ exports.splitTelegramText = splitTelegramText;
6
+ exports.renderTelegramMarkdown = renderTelegramMarkdown;
7
+ exports.renderTelegramMarkdownSafe = renderTelegramMarkdownSafe;
8
+ exports.splitTelegramMarkdown = splitTelegramMarkdown;
9
+ /**
10
+ * Ordinary Markdown to Telegram HTML, for every agent's Telegram replies (spec R11.1).
11
+ *
12
+ * - Inline: `**x**` and `*x*` are bold (the long-standing meaning of `*x*` here), `_x_` is italic, `` `x` `` is code,
13
+ * `[text](https://…)` is a link. A span that doesn't resolve cleanly stays literal text, never half-applied markup.
14
+ * - Blocks: a heading is a bold line, list items keep their marker (bullets become •), `>` lines are a quote, fenced code
15
+ * is a code block, and a table is a monospace block with its columns aligned.
16
+ * - Splitting goes by Markdown block and never inside a code block or table unless that block alone is too long; each
17
+ * chunk is measured after rendering.
18
+ * - `renderTelegramMarkdownSafe` is the first fallback when Telegram rejects a chunk: inline markup is escaped and only
19
+ * code blocks, tables, code spans and links are kept.
20
+ */
21
+ const runtime_1 = require("../nerves/runtime");
22
+ /** Telegram's limit on one message's text. */
23
+ exports.TELEGRAM_MESSAGE_LIMIT = 4096;
24
+ function escapeTelegramHtml(value) {
25
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
26
+ }
27
+ function sourceIndexForRenderedLimit(value, limit) {
28
+ let renderedUnits = 0;
29
+ let sourceIndex = 0;
30
+ for (const character of value) {
31
+ const escaped = escapeTelegramHtml(character);
32
+ if (renderedUnits + escaped.length > limit)
33
+ break;
34
+ renderedUnits += escaped.length;
35
+ sourceIndex += character.length;
36
+ }
37
+ return sourceIndex;
38
+ }
39
+ function preferredBoundary(value, limit, minimum) {
40
+ const paragraph = value.lastIndexOf("\n\n", limit - 1);
41
+ if (paragraph >= minimum)
42
+ return paragraph + 2;
43
+ const newline = value.lastIndexOf("\n", limit - 1);
44
+ if (newline >= minimum)
45
+ return newline + 1;
46
+ for (let index = limit - 1; index >= minimum; index -= 1) {
47
+ if (/\s/u.test(value[index]))
48
+ return index + 1;
49
+ }
50
+ return limit;
51
+ }
52
+ function splitTelegramText(value, options = {}) {
53
+ const targetUnits = options.targetUnits ?? 1_200;
54
+ const maxUnits = options.maxUnits ?? 4_000;
55
+ if (!Number.isInteger(targetUnits) || !Number.isInteger(maxUnits) || targetUnits < 1 || maxUnits < targetUnits) {
56
+ throw new Error("Telegram chunk limits must be positive integers with targetUnits <= maxUnits");
57
+ }
58
+ if (!value)
59
+ return [""];
60
+ const chunks = [];
61
+ let remaining = value;
62
+ while (escapeTelegramHtml(remaining).length > maxUnits || escapeTelegramHtml(remaining).length > targetUnits) {
63
+ const targetIndex = sourceIndexForRenderedLimit(remaining, targetUnits);
64
+ const maxIndex = sourceIndexForRenderedLimit(remaining, maxUnits);
65
+ const candidate = targetIndex > 0 ? targetIndex : maxIndex;
66
+ if (candidate <= 0)
67
+ throw new Error("Telegram chunk limit cannot fit one character");
68
+ const splitAt = preferredBoundary(remaining, candidate, Math.floor(candidate / 2));
69
+ chunks.push(remaining.slice(0, splitAt));
70
+ remaining = remaining.slice(splitAt);
71
+ }
72
+ chunks.push(remaining);
73
+ return chunks;
74
+ }
75
+ const escapeAttribute = (value) => escapeTelegramHtml(value).replaceAll("\"", "&quot;");
76
+ // Bold spans may carry one level of emphasis inside them, because `**bold with *italic* inside**` is ordinary model prose.
77
+ // A span must open on a letter or digit and close on a non-space, which keeps `**/src/**`, `2 ** 3` and `a_b_c` literal.
78
+ const BOLD_WITH_NESTING = /`([^`\n]+)`|\*\*([\p{L}\p{N}](?:[^*_`\n]|\*(?!\*)|_)*\S|[\p{L}\p{N}])\*\*|\*([\p{L}\p{N}](?:[^*_`\n]*\S)?)\*|_([\p{L}\p{N}](?:[^*_`\n]*\S)?)_/gu;
79
+ const EMPHASIS_ONLY = /`([^`\n]+)`|\*([\p{L}\p{N}](?:[^*_`\n]*\S)?)\*|_([\p{L}\p{N}](?:[^*_`\n]*\S)?)_/gu;
80
+ // A code span, or a link to a web or Telegram address.
81
+ const ATOM = /`([^`\n]+)`|\[([^\]\n]+)\]\(((?:https?|tg):\/\/[^\s)]+)\)/gu;
82
+ // Null when the span can't be rendered cleanly, so the caller escapes it instead of emitting partial markup.
83
+ function styledSpan(text, allowBold) {
84
+ let html = "";
85
+ let cursor = 0;
86
+ const pattern = allowBold ? BOLD_WITH_NESTING : EMPHASIS_ONLY;
87
+ for (const match of text.matchAll(pattern)) {
88
+ const gap = text.slice(cursor, match.index);
89
+ if (/[*_`]/u.test(gap))
90
+ return null;
91
+ html += escapeTelegramHtml(gap);
92
+ const code = match[1];
93
+ const bold = allowBold ? match[2] : undefined;
94
+ const italic = allowBold ? match[3] : match[2];
95
+ const underscored = allowBold ? match[4] : match[3];
96
+ if (code !== undefined)
97
+ html += `<code>${escapeTelegramHtml(code)}</code>`;
98
+ else if (bold !== undefined) {
99
+ const inner = styledSpan(bold, false);
100
+ if (inner === null)
101
+ return null;
102
+ html += `<b>${inner}</b>`;
103
+ // A single-marker span is bold at the top level, but inside a bold run it is the nested emphasis the author meant.
104
+ }
105
+ else if (italic !== undefined)
106
+ html += allowBold ? `<b>${escapeTelegramHtml(italic)}</b>` : `<i>${escapeTelegramHtml(italic)}</i>`;
107
+ else
108
+ html += `<i>${escapeTelegramHtml(underscored)}</i>`;
109
+ cursor = match.index + match[0].length;
110
+ }
111
+ const tail = text.slice(cursor);
112
+ return /[*_`]/u.test(tail) ? null : html + escapeTelegramHtml(tail);
113
+ }
114
+ /** One line's inline markup: code spans and links are kept whole first, then the styled spans between them. */
115
+ function inline(line, safe) {
116
+ let html = "";
117
+ let cursor = 0;
118
+ const rest = (text) => (safe ? escapeTelegramHtml(text) : styledSpan(text, true) ?? escapeTelegramHtml(text));
119
+ for (const match of line.matchAll(ATOM)) {
120
+ html += rest(line.slice(cursor, match.index));
121
+ if (match[1] !== undefined)
122
+ html += `<code>${escapeTelegramHtml(match[1])}</code>`;
123
+ else {
124
+ const label = safe ? escapeTelegramHtml(match[2]) : styledSpan(match[2], true) ?? escapeTelegramHtml(match[2]);
125
+ html += `<a href="${escapeAttribute(match[3])}">${label}</a>`;
126
+ }
127
+ cursor = match.index + match[0].length;
128
+ }
129
+ return html + rest(line.slice(cursor));
130
+ }
131
+ const FENCE = /^\s*(```+|~~~+)\s*([\w+#.-]*)\s*$/u;
132
+ const TABLE_SEPARATOR = /^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$/u;
133
+ const HEADING = /^\s{0,3}#{1,6}\s+(.*?)\s*#*\s*$/u;
134
+ const LIST_ITEM = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/u;
135
+ const QUOTE = /^\s{0,3}>\s?(.*)$/u;
136
+ const isTableRow = (line) => /^\s*\|.*\|\s*$/u.test(line);
137
+ const cells = (line) => line.trim().replace(/^\|/u, "").replace(/\|$/u, "").split("|").map((cell) => cell.trim());
138
+ /**
139
+ * The text as blocks whose sources concatenate back to it exactly. A text block runs to the next blank line, so a
140
+ * paragraph, list or quote is one block; code fences and tables are their own blocks.
141
+ */
142
+ function parseBlocks(text) {
143
+ const lines = text.split(/(?<=\n)/u);
144
+ const blocks = [];
145
+ let index = 0;
146
+ while (index < lines.length) {
147
+ const line = lines[index];
148
+ const bare = line.replace(/\r?\n$/u, "");
149
+ const fence = FENCE.exec(bare);
150
+ if (fence) {
151
+ const marker = fence[1];
152
+ let end = index + 1;
153
+ while (end < lines.length && !lines[end].trim().startsWith(marker.slice(0, 3)))
154
+ end += 1;
155
+ const closed = end < lines.length;
156
+ const body = lines.slice(index + 1, end);
157
+ const source = lines.slice(index, closed ? end + 1 : end).join("");
158
+ blocks.push({ kind: "code", source, language: fence[2], lines: body.map((entry) => entry.replace(/\r?\n$/u, "")), open: line, close: closed ? lines[end] : null });
159
+ index = closed ? end + 1 : end;
160
+ continue;
161
+ }
162
+ if (isTableRow(bare) && index + 1 < lines.length && TABLE_SEPARATOR.test(lines[index + 1].replace(/\r?\n$/u, ""))) {
163
+ let end = index + 2;
164
+ while (end < lines.length && isTableRow(lines[end].replace(/\r?\n$/u, "")))
165
+ end += 1;
166
+ const body = lines.slice(index + 2, end).map((entry) => cells(entry));
167
+ blocks.push({ kind: "table", source: lines.slice(index, end).join(""), header: cells(bare), separator: lines[index + 1], rows: body });
168
+ index = end;
169
+ continue;
170
+ }
171
+ // A text block: up to and including the blank lines that end it, stopping before a fence or a table.
172
+ let end = index + 1;
173
+ let sawBlank = bare.trim() === "";
174
+ while (end < lines.length) {
175
+ const next = lines[end].replace(/\r?\n$/u, "");
176
+ const blank = next.trim() === "";
177
+ if (FENCE.test(next) || (isTableRow(next) && end + 1 < lines.length && TABLE_SEPARATOR.test(lines[end + 1].replace(/\r?\n$/u, ""))))
178
+ break;
179
+ if (sawBlank && !blank)
180
+ break;
181
+ sawBlank = sawBlank || blank;
182
+ end += 1;
183
+ }
184
+ const previous = blocks.at(-1);
185
+ const source = lines.slice(index, end).join("");
186
+ // Blank lines after a code block or table belong with it, so every block keeps its own separator.
187
+ if (bare.trim() === "" && previous && previous.kind !== "text" && source.trim() === "")
188
+ previous.source += source;
189
+ else
190
+ blocks.push({ kind: "text", source });
191
+ index = end;
192
+ }
193
+ return blocks;
194
+ }
195
+ function renderTable(header, rows) {
196
+ const width = Math.max(header.length, ...rows.map((row) => row.length));
197
+ const all = [header, ...rows].map((row) => Array.from({ length: width }, (_, column) => row[column] ?? ""));
198
+ const widths = Array.from({ length: width }, (_, column) => Math.max(...all.map((row) => [...row[column]].length)));
199
+ const line = (row) => row.map((cell, column) => cell + " ".repeat(widths[column] - [...cell].length)).join(" | ").replace(/[ |]+$/u, "");
200
+ const rule = widths.map((size) => "-".repeat(size)).join("-+-");
201
+ return `<pre>${escapeTelegramHtml([line(all[0]), rule, ...all.slice(1).map(line)].join("\n"))}</pre>`;
202
+ }
203
+ function renderCode(language, lines) {
204
+ const code = escapeTelegramHtml(lines.join("\n"));
205
+ return language ? `<pre><code class="language-${escapeAttribute(language)}">${code}</code></pre>` : `<pre>${code}</pre>`;
206
+ }
207
+ function renderTextBlock(source, safe) {
208
+ const trailing = /\s*$/u.exec(source)[0];
209
+ const body = source.slice(0, source.length - trailing.length);
210
+ const out = [];
211
+ let quote = [];
212
+ const flushQuote = () => {
213
+ if (quote.length)
214
+ out.push(`<blockquote>${quote.join("\n")}</blockquote>`);
215
+ quote = [];
216
+ };
217
+ for (const raw of body.split("\n")) {
218
+ const line = raw.replace(/\r$/u, "");
219
+ if (safe) {
220
+ out.push(inline(line, true));
221
+ continue;
222
+ }
223
+ const quoted = QUOTE.exec(line);
224
+ if (quoted) {
225
+ quote.push(inline(quoted[1], false));
226
+ continue;
227
+ }
228
+ flushQuote();
229
+ const heading = HEADING.exec(line);
230
+ const item = LIST_ITEM.exec(line);
231
+ if (heading)
232
+ out.push(`<b>${inline(heading[1], false)}</b>`);
233
+ else if (item)
234
+ out.push(`${item[1]}${/^[-*+]$/u.test(item[2]) ? "•" : item[2]} ${inline(item[3], false)}`);
235
+ else
236
+ out.push(inline(line, false));
237
+ }
238
+ flushQuote();
239
+ return out.join("\n") + trailing.replace(/\r/gu, "");
240
+ }
241
+ function renderBlocks(blocks, safe) {
242
+ return blocks.map((block) => {
243
+ if (block.kind === "code")
244
+ return renderCode(block.language, block.lines) + trailingOf(block);
245
+ if (block.kind === "table")
246
+ return renderTable(block.header, block.rows) + trailingOf(block);
247
+ return renderTextBlock(block.source, safe);
248
+ }).join("");
249
+ }
250
+ // What follows a code block's closing fence or a table's last row: the blank lines that separate it from the next block.
251
+ function trailingOf(block) {
252
+ return /\n*$/u.exec(block.source.replace(/[^\S\n]+$/u, ""))[0].slice(1) ? "\n\n" : "";
253
+ }
254
+ /** Markdown as Telegram HTML. */
255
+ function renderTelegramMarkdown(text) {
256
+ return renderBlocks(parseBlocks(text), false).trimEnd();
257
+ }
258
+ /** The first fallback for a chunk Telegram refused: inline markup escaped; code blocks, tables, code spans and links kept. */
259
+ function renderTelegramMarkdownSafe(text) {
260
+ return renderBlocks(parseBlocks(text), true).trimEnd();
261
+ }
262
+ /** Pieces of one block that alone renders longer than the limit: code and tables by line, each piece still a whole block. */
263
+ function cutBlock(block, maxUnits) {
264
+ const fits = (source) => renderTelegramMarkdown(source).length <= maxUnits;
265
+ const pack = (items, wrap) => {
266
+ const pieces = [];
267
+ let current = "";
268
+ for (const item of items) {
269
+ if (current && !fits(wrap(current + item))) {
270
+ pieces.push(wrap(current));
271
+ current = "";
272
+ }
273
+ current += item;
274
+ }
275
+ if (current)
276
+ pieces.push(wrap(current));
277
+ return pieces;
278
+ };
279
+ // A piece is a whole block only if every piece fits; a single line or header too long for one message is cut as text.
280
+ const whole = (pieces) => (pieces.length && pieces.every(fits) ? pieces : null);
281
+ if (block.kind === "code") {
282
+ const close = block.close ?? "```\n";
283
+ const pieces = whole(pack(block.lines.map((line) => `${line}\n`), (body) => `${block.open}${body}${close.endsWith("\n") ? close : `${close}\n`}`));
284
+ if (pieces)
285
+ return pieces;
286
+ }
287
+ if (block.kind === "table") {
288
+ const head = block.source.split(/(?<=\n)/u).slice(0, 2).join("");
289
+ const pieces = whole(pack(block.source.split(/(?<=\n)/u).slice(2), (body) => `${head}${body}`));
290
+ if (pieces)
291
+ return pieces;
292
+ }
293
+ // A long paragraph, or a block that can't be cut whole: cut at paragraph, line or word boundaries by escaped length, then checked after rendering; markup only
294
+ // adds tags, so a piece still too long is cut again with a smaller budget.
295
+ for (let budget = maxUnits;; budget = Math.floor(budget * 0.8)) {
296
+ const pieces = splitTelegramText(block.source, { targetUnits: budget, maxUnits: budget });
297
+ if (budget < 64 || pieces.every(fits))
298
+ return pieces;
299
+ }
300
+ }
301
+ /**
302
+ * The text cut into Telegram messages by Markdown block; each chunk is measured after rendering. Chunks join back to the
303
+ * text, except where one code block or table is longer than a message: each of its pieces is re-fenced or repeats the header.
304
+ */
305
+ function splitTelegramMarkdown(text, options = {}) {
306
+ const targetUnits = options.targetUnits ?? 1_200;
307
+ const maxUnits = options.maxUnits ?? exports.TELEGRAM_MESSAGE_LIMIT;
308
+ if (!Number.isInteger(targetUnits) || !Number.isInteger(maxUnits) || targetUnits < 1 || maxUnits < targetUnits) {
309
+ throw new Error("Telegram chunk limits must be positive integers with targetUnits <= maxUnits");
310
+ }
311
+ if (!text)
312
+ return [""];
313
+ const chunks = [];
314
+ let current = "";
315
+ for (const block of parseBlocks(text)) {
316
+ if (current && renderTelegramMarkdown(current + block.source).length > targetUnits) {
317
+ chunks.push(current);
318
+ current = "";
319
+ }
320
+ if (renderTelegramMarkdown(block.source).length > maxUnits) {
321
+ const pieces = cutBlock(block, maxUnits);
322
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "telegram.block_cut", message: "a Markdown block longer than one Telegram message was cut", meta: { kind: block.kind, pieces: pieces.length } });
323
+ chunks.push(...pieces);
324
+ continue;
325
+ }
326
+ current += block.source;
327
+ }
328
+ if (current)
329
+ chunks.push(current);
330
+ return chunks;
331
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1350",
3
+ "version": "0.1.0-alpha.1352",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@ouro.bot/cli",
9
- "version": "0.1.0-alpha.1350",
9
+ "version": "0.1.0-alpha.1352",
10
10
  "bundleDependencies": [
11
11
  "@ouro.bot/friends"
12
12
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1350",
3
+ "version": "0.1.0-alpha.1352",
4
4
  "description": "Ouroboros, the agent harness: agents with durable memory that live where you talk (terminal, Teams, iMessage, mail, voice) and use real tools. Start with npx ouro.bot@latest.",
5
5
  "homepage": "https://ouroboros.bot/",
6
6
  "engines": {