telecoder 0.0.0-stage → 1.3.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.
Files changed (235) hide show
  1. package/.env.example +375 -0
  2. package/CHANGELOG.md +1867 -0
  3. package/LICENSE +22 -0
  4. package/README.md +130 -2
  5. package/dist/audio/transcribe.js +41 -0
  6. package/dist/bin/mcp-server.js +363 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +573 -0
  10. package/dist/bot/command-catalog.js +263 -0
  11. package/dist/bot/deleted-threads.js +103 -0
  12. package/dist/bot/file-access.js +150 -0
  13. package/dist/bot/handlers/album.handler.js +128 -0
  14. package/dist/bot/handlers/branch.handler.js +1096 -0
  15. package/dist/bot/handlers/command/access.js +407 -0
  16. package/dist/bot/handlers/command/admin.js +803 -0
  17. package/dist/bot/handlers/command/all-view.js +33 -0
  18. package/dist/bot/handlers/command/auto-approve.js +138 -0
  19. package/dist/bot/handlers/command/background.js +37 -0
  20. package/dist/bot/handlers/command/botname.js +76 -0
  21. package/dist/bot/handlers/command/btw.js +175 -0
  22. package/dist/bot/handlers/command/cleanup.js +329 -0
  23. package/dist/bot/handlers/command/model.js +226 -0
  24. package/dist/bot/handlers/command/prefs-scope.js +362 -0
  25. package/dist/bot/handlers/command/project.js +458 -0
  26. package/dist/bot/handlers/command/resume.js +325 -0
  27. package/dist/bot/handlers/command/session.js +299 -0
  28. package/dist/bot/handlers/command/settings.js +657 -0
  29. package/dist/bot/handlers/command/shared.js +207 -0
  30. package/dist/bot/handlers/command/tasks.js +681 -0
  31. package/dist/bot/handlers/command/thread.js +128 -0
  32. package/dist/bot/handlers/command/topic-store.js +74 -0
  33. package/dist/bot/handlers/command/topic.js +27 -0
  34. package/dist/bot/handlers/command/usage.js +382 -0
  35. package/dist/bot/handlers/command-fallback.js +179 -0
  36. package/dist/bot/handlers/command.handler.js +446 -0
  37. package/dist/bot/handlers/loop.handler.js +389 -0
  38. package/dist/bot/handlers/media-fallback.js +126 -0
  39. package/dist/bot/handlers/message/replies.js +56 -0
  40. package/dist/bot/handlers/message/shared.js +95 -0
  41. package/dist/bot/handlers/message/turn-notify.js +135 -0
  42. package/dist/bot/handlers/message/turn-runner.js +56 -0
  43. package/dist/bot/handlers/message.handler.js +114 -0
  44. package/dist/bot/handlers/newbot.handler.js +230 -0
  45. package/dist/bot/handlers/photo.handler.js +286 -0
  46. package/dist/bot/handlers/prompts.handler.js +343 -0
  47. package/dist/bot/handlers/running-note.js +44 -0
  48. package/dist/bot/handlers/session-guard.js +78 -0
  49. package/dist/bot/handlers/suggestion.handler.js +84 -0
  50. package/dist/bot/handlers/tree.handler.js +480 -0
  51. package/dist/bot/handlers/view.js +41 -0
  52. package/dist/bot/handlers/voice.handler.js +147 -0
  53. package/dist/bot/kept-threads.js +51 -0
  54. package/dist/bot/middleware/admin-only.js +49 -0
  55. package/dist/bot/middleware/album-collector.js +69 -0
  56. package/dist/bot/middleware/auth.middleware.js +122 -0
  57. package/dist/bot/middleware/group-mention.middleware.js +145 -0
  58. package/dist/bot/middleware/group-role.middleware.js +75 -0
  59. package/dist/bot/middleware/message-batcher.js +87 -0
  60. package/dist/bot/middleware/queued-messages.js +1082 -0
  61. package/dist/bot/middleware/stale-filter.js +9 -0
  62. package/dist/build-info.json +8 -0
  63. package/dist/claude/ask-user-form.js +517 -0
  64. package/dist/claude/ask-user.js +363 -0
  65. package/dist/claude/auto-approve.js +225 -0
  66. package/dist/claude/auto-topic-haiku.js +143 -0
  67. package/dist/claude/available-commands.js +156 -0
  68. package/dist/claude/background-hint.js +91 -0
  69. package/dist/claude/branch-tree.js +393 -0
  70. package/dist/claude/carry-over.js +25 -0
  71. package/dist/claude/ccr-shim.js +48 -0
  72. package/dist/claude/charter-judge.js +214 -0
  73. package/dist/claude/claude-auth.js +117 -0
  74. package/dist/claude/command-parser.js +206 -0
  75. package/dist/claude/cost-overlay-scraper.js +134 -0
  76. package/dist/claude/effort-level.js +5 -0
  77. package/dist/claude/enabled-plugins.js +52 -0
  78. package/dist/claude/in-flight-tracker.js +82 -0
  79. package/dist/claude/ipc-server.js +192 -0
  80. package/dist/claude/mcp-bridge.js +481 -0
  81. package/dist/claude/memory-guard.js +400 -0
  82. package/dist/claude/message-offsets.js +88 -0
  83. package/dist/claude/modal-relay.js +817 -0
  84. package/dist/claude/model-catalog.js +102 -0
  85. package/dist/claude/monitor-relay.js +712 -0
  86. package/dist/claude/native-commands.js +40 -0
  87. package/dist/claude/pending-branches.js +93 -0
  88. package/dist/claude/pending-suggestions.js +50 -0
  89. package/dist/claude/permission-gate.js +338 -0
  90. package/dist/claude/permission-mode.js +152 -0
  91. package/dist/claude/poll-user.js +51 -0
  92. package/dist/claude/prewarm.js +70 -0
  93. package/dist/claude/project-commands.js +69 -0
  94. package/dist/claude/prompt-hold.js +124 -0
  95. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  96. package/dist/claude/pty-idle-reaper.js +96 -0
  97. package/dist/claude/pty-provider.js +2499 -0
  98. package/dist/claude/pty-spawn-config.js +343 -0
  99. package/dist/claude/pty-stream.js +363 -0
  100. package/dist/claude/pty-watch.js +201 -0
  101. package/dist/claude/request-queue.js +107 -0
  102. package/dist/claude/rewind.js +111 -0
  103. package/dist/claude/scheduled-runner.js +89 -0
  104. package/dist/claude/scheduler.js +241 -0
  105. package/dist/claude/scope-guard.js +279 -0
  106. package/dist/claude/screen-marks.js +83 -0
  107. package/dist/claude/screen-render.js +96 -0
  108. package/dist/claude/secret-request.js +576 -0
  109. package/dist/claude/session-history.js +288 -0
  110. package/dist/claude/session-jsonl.js +1067 -0
  111. package/dist/claude/session-manager.js +216 -0
  112. package/dist/claude/session-move.js +70 -0
  113. package/dist/claude/session-scan.js +270 -0
  114. package/dist/claude/setup-token.js +285 -0
  115. package/dist/claude/shell-mode-gate.js +60 -0
  116. package/dist/claude/side-call-options.js +45 -0
  117. package/dist/claude/side-question.js +252 -0
  118. package/dist/claude/stage-images.js +62 -0
  119. package/dist/claude/subagent-tools.js +12 -0
  120. package/dist/claude/synthetic-ctx.js +51 -0
  121. package/dist/claude/tasks-overlay-scraper.js +217 -0
  122. package/dist/claude/thread-judge-haiku.js +88 -0
  123. package/dist/claude/tip-scraper.js +77 -0
  124. package/dist/claude/tui-modal.js +746 -0
  125. package/dist/claude/tui-state.js +456 -0
  126. package/dist/claude/turn-end.js +105 -0
  127. package/dist/claude/turn-prose.js +64 -0
  128. package/dist/claude/typed-answer.js +104 -0
  129. package/dist/claude/update-banner-relay.js +70 -0
  130. package/dist/cli/commands/doctor.js +338 -0
  131. package/dist/cli/commands/help.js +34 -0
  132. package/dist/cli/commands/init.js +126 -0
  133. package/dist/cli/commands/service.js +710 -0
  134. package/dist/cli/commands/start.js +63 -0
  135. package/dist/cli/commands/version.js +11 -0
  136. package/dist/cli/commands/watch.js +322 -0
  137. package/dist/cli/dispatch.js +84 -0
  138. package/dist/cli/init/env-file.js +99 -0
  139. package/dist/cli/init/flow.js +705 -0
  140. package/dist/cli/init/prompter.js +124 -0
  141. package/dist/cli/init/telegram.js +120 -0
  142. package/dist/cli/service/render.js +212 -0
  143. package/dist/cli.js +18 -0
  144. package/dist/config-report.js +107 -0
  145. package/dist/config.js +525 -0
  146. package/dist/index.js +443 -0
  147. package/dist/launcher.js +960 -0
  148. package/dist/node-version-check.js +27 -0
  149. package/dist/providers/ccr-health.js +119 -0
  150. package/dist/providers/ccr-introspect.js +142 -0
  151. package/dist/providers/ccr-provider.js +59 -0
  152. package/dist/providers/claude-provider.js +10 -0
  153. package/dist/providers/prefs-sync.js +121 -0
  154. package/dist/providers/project-favorites.js +74 -0
  155. package/dist/providers/provider-router.js +128 -0
  156. package/dist/providers/provider-switch.js +91 -0
  157. package/dist/providers/spawn-settings.js +45 -0
  158. package/dist/providers/types.js +8 -0
  159. package/dist/providers/user-preferences.js +322 -0
  160. package/dist/restart-when-idle.js +173 -0
  161. package/dist/startup/auto-continue.js +67 -0
  162. package/dist/startup/auto-resume.js +161 -0
  163. package/dist/startup/notices.js +120 -0
  164. package/dist/startup/shared.js +44 -0
  165. package/dist/startup/verify-token.js +31 -0
  166. package/dist/telegram/access-request.js +153 -0
  167. package/dist/telegram/action-logger.js +522 -0
  168. package/dist/telegram/admin-mention.js +107 -0
  169. package/dist/telegram/background-activity-card.js +502 -0
  170. package/dist/telegram/botname-settings.js +282 -0
  171. package/dist/telegram/button-text.js +26 -0
  172. package/dist/telegram/client-options.js +26 -0
  173. package/dist/telegram/deduplication.js +33 -0
  174. package/dist/telegram/entities.js +295 -0
  175. package/dist/telegram/force-reply-tracker.js +96 -0
  176. package/dist/telegram/lettered-options.js +87 -0
  177. package/dist/telegram/markdown.js +362 -0
  178. package/dist/telegram/message-sender.js +1019 -0
  179. package/dist/telegram/prompt-label.js +148 -0
  180. package/dist/telegram/prompt-suggestion.js +54 -0
  181. package/dist/telegram/send.js +123 -0
  182. package/dist/telegram/streaming-turn.js +103 -0
  183. package/dist/telegram/suggestions-settings.js +30 -0
  184. package/dist/telegram/table-lists.js +56 -0
  185. package/dist/telegram/task-list.js +367 -0
  186. package/dist/telegram/task-tracker.js +128 -0
  187. package/dist/telegram/terminal-renderer.js +667 -0
  188. package/dist/telegram/thread-titles.js +262 -0
  189. package/dist/telegram/threads-setup.js +117 -0
  190. package/dist/utils/admins.js +143 -0
  191. package/dist/utils/agent-timer.js +55 -0
  192. package/dist/utils/atomic-write.js +24 -0
  193. package/dist/utils/bot-icon.js +248 -0
  194. package/dist/utils/bot-token.js +77 -0
  195. package/dist/utils/bounded-map.js +55 -0
  196. package/dist/utils/build-info.js +57 -0
  197. package/dist/utils/caffeinate.js +53 -0
  198. package/dist/utils/claude-env.js +53 -0
  199. package/dist/utils/claude-version.js +48 -0
  200. package/dist/utils/config-home.js +62 -0
  201. package/dist/utils/download.js +137 -0
  202. package/dist/utils/exit-codes.js +59 -0
  203. package/dist/utils/file-type.js +149 -0
  204. package/dist/utils/format.js +78 -0
  205. package/dist/utils/home-project.js +30 -0
  206. package/dist/utils/host-stall.js +51 -0
  207. package/dist/utils/id-list.js +44 -0
  208. package/dist/utils/idle-restart.js +92 -0
  209. package/dist/utils/install-mode.js +63 -0
  210. package/dist/utils/instance-config.js +148 -0
  211. package/dist/utils/instances.js +95 -0
  212. package/dist/utils/json-store.js +140 -0
  213. package/dist/utils/keyed-settings.js +62 -0
  214. package/dist/utils/legacy-env.js +35 -0
  215. package/dist/utils/memory-pressure.js +60 -0
  216. package/dist/utils/npm-version.js +134 -0
  217. package/dist/utils/prefs-relay.js +107 -0
  218. package/dist/utils/proc-children.js +102 -0
  219. package/dist/utils/resolve-bin.js +86 -0
  220. package/dist/utils/resolve-claude-bin.js +52 -0
  221. package/dist/utils/respawn-backoff.js +28 -0
  222. package/dist/utils/sanitize.js +91 -0
  223. package/dist/utils/session-key.js +37 -0
  224. package/dist/utils/stale-launcher.js +109 -0
  225. package/dist/utils/state-dir-migration.js +92 -0
  226. package/dist/utils/systemd.js +126 -0
  227. package/dist/utils/telegram-proxy.js +72 -0
  228. package/dist/utils/uploads-dir.js +27 -0
  229. package/dist/utils/user-roster.js +275 -0
  230. package/dist/utils/verbosity.js +118 -0
  231. package/dist/utils/version-check.js +166 -0
  232. package/dist/utils/workspace-guard.js +44 -0
  233. package/dist/worker-restart.js +141 -0
  234. package/instances.json.example +41 -0
  235. package/package.json +75 -4
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Remembers which of the bot's own messages were ForceReply prompts, and which
3
+ * flow each one opened.
4
+ *
5
+ * A ForceReply flow (`/dir`) posts a question and
6
+ * takes the user's reply to it as the answer: Telegram pops the composer open
7
+ * with the reply already attached. Two things need to know a reply answers a
8
+ * prompt:
9
+ *
10
+ * - the message handlers, to route the answer to the flow that asked, which
11
+ * {@link forceReplyFlow} tells them from the prompt's id rather than from
12
+ * its wording — a list of phrases that would drift from the handlers;
13
+ * - the group mention gate, since in a group the bot only answers when it is
14
+ * @mentioned and a reply to a prompt has nowhere to put a mention. A
15
+ * transformer watches outgoing sendMessage calls and records every message
16
+ * sent with a force_reply keyboard, so that gate holds for a prompt sent
17
+ * any other way too.
18
+ *
19
+ * The ids live in memory only: these prompts are answered within seconds, and
20
+ * a prompt left hanging across a restart is better re-opened than resurrected.
21
+ */
22
+ import { replyFormatted } from './send.js';
23
+ /** Plenty for any realistic number of prompts open at once; bounds the map. */
24
+ const MAX_TRACKED = 200;
25
+ /** Prompt → the flow it opened, or undefined for one sent outside {@link sendForceReplyPrompt}. */
26
+ const prompts = new Map();
27
+ const key = (chatId, messageId) => `${chatId}:${messageId}`;
28
+ export function rememberForceReplyPrompt(chatId, messageId, flow) {
29
+ const k = key(chatId, messageId);
30
+ // Re-inserting moves it to the end, so the oldest entry is always first out.
31
+ // The transformer records a prompt first, without its flow; the sender then
32
+ // names the flow, which must not be lost to a later nameless record.
33
+ const known = prompts.get(k);
34
+ prompts.delete(k);
35
+ prompts.set(k, flow ?? known);
36
+ while (prompts.size > MAX_TRACKED) {
37
+ const oldest = prompts.keys().next();
38
+ if (oldest.done)
39
+ break;
40
+ prompts.delete(oldest.value);
41
+ }
42
+ }
43
+ export function isForceReplyPrompt(chatId, messageId) {
44
+ return prompts.has(key(chatId, messageId));
45
+ }
46
+ /** The flow a reply to `messageId` answers, or undefined when it answers no open prompt. */
47
+ export function forceReplyFlow(chatId, messageId) {
48
+ return prompts.get(key(chatId, messageId));
49
+ }
50
+ /**
51
+ * The flow the message being replied to opened, if it is one of this bot's
52
+ * prompts. Undefined for a message that isn't a reply, replies to a user, or
53
+ * replies to a bot message that was no prompt (or one from before a restart).
54
+ */
55
+ export function repliedForceReplyFlow(ctx) {
56
+ const replyTo = ctx.message?.reply_to_message;
57
+ const chatId = ctx.chat?.id;
58
+ if (!replyTo?.from?.is_bot || chatId === undefined)
59
+ return undefined;
60
+ return forceReplyFlow(chatId, replyTo.message_id);
61
+ }
62
+ /**
63
+ * Post a ForceReply prompt for `flow` and remember which flow it opened.
64
+ * `selective` keeps the composer from opening for everyone else in a group.
65
+ */
66
+ export async function sendForceReplyPrompt(ctx, flow, text, placeholder) {
67
+ const sent = await replyFormatted(ctx, text, {
68
+ reply_markup: {
69
+ force_reply: true,
70
+ input_field_placeholder: placeholder,
71
+ selective: true,
72
+ },
73
+ });
74
+ rememberForceReplyPrompt(sent.chat.id, sent.message_id, flow);
75
+ }
76
+ /** Test seam — the map is module state that would otherwise leak between cases. */
77
+ export function clearForceReplyPrompts() {
78
+ prompts.clear();
79
+ }
80
+ /** Record every ForceReply prompt this bot sends. Call once, at startup. */
81
+ export function trackForceReplyPrompts(bot) {
82
+ bot.api.config.use(async (prev, method, payload, signal) => {
83
+ const res = await prev(method, payload, signal);
84
+ if (method !== 'sendMessage' || !res.ok)
85
+ return res;
86
+ const markup = payload.reply_markup;
87
+ if (!markup?.force_reply)
88
+ return res;
89
+ const sent = res.result;
90
+ if (typeof sent?.message_id === 'number' && typeof sent.chat?.id === 'number') {
91
+ rememberForceReplyPrompt(sent.chat.id, sent.message_id);
92
+ }
93
+ return res;
94
+ });
95
+ }
96
+ //# sourceMappingURL=force-reply-tracker.js.map
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Lettered options — the A/B/C rendering any picker uses once its choices are
3
+ * too long to survive on an inline button.
4
+ *
5
+ * A Telegram inline button is a single line the client ellipsises, with no way
6
+ * for the reader to expand it, so text past the clip is not buried, it is gone
7
+ * ({@link MAX_BUTTON_TEXT_LEN}). The rule that fixes that is the same wherever
8
+ * a keyboard offers a choice: write every option out in the message body keyed
9
+ * `A`, `B`, `C`, and let the same letter prefix its button. The body is then
10
+ * the one place the full text is guaranteed to reach the user, and the button
11
+ * only has to point back at it.
12
+ *
13
+ * `telecoder_ask_user` established the rule and `/resume` follows it; both
14
+ * build their keyboard here so a question and a session list clip at the same
15
+ * place instead of each keeping their own copy of the threshold.
16
+ */
17
+ import { fitsOnButton } from './button-text.js';
18
+ /** Separator between an option's letter and its label on a button. */
19
+ const BUTTON_SEP = ' · ';
20
+ /** Bare-letter buttons per row, once a keyboard has gone compact. */
21
+ const LETTERS_PER_ROW = 4;
22
+ /**
23
+ * A label is one line by construction: a newline in it would break the A/B/C
24
+ * listing apart, and a button renders a single line regardless. Model- and
25
+ * user-written text reaches here unflattened, so flatten it once, here, rather
26
+ * than at every call site.
27
+ */
28
+ function oneLine(text) {
29
+ return text.replace(/\s+/g, ' ').trim();
30
+ }
31
+ /**
32
+ * The key an option is known by: `A`, `B`, `C`, … It prefixes the option both
33
+ * in the message body and on its button, so a letter-only button still points
34
+ * at the full text above it. Past `Z` it falls back to the 1-based index;
35
+ * callers offer nowhere near 26 options, so that is defensive only.
36
+ */
37
+ export function optionLetter(index) {
38
+ return index < 26 ? String.fromCharCode(65 + index) : String(index + 1);
39
+ }
40
+ /**
41
+ * One body line per option — `A. Label — description` — for the caller to put
42
+ * under whatever heading it is asking beneath. Returned as plain text, to go
43
+ * out verbatim (or into an `EntityText`).
44
+ */
45
+ export function letteredOptionLines(options) {
46
+ return options.map((o, idx) => {
47
+ const desc = o.description ? oneLine(o.description) : '';
48
+ return `${optionLetter(idx)}. ${oneLine(o.label)}${desc ? ` — ${desc}` : ''}`;
49
+ });
50
+ }
51
+ /**
52
+ * The inline keyboard for a lettered list.
53
+ *
54
+ * A label rides on its own button while it fits ({@link MAX_BUTTON_TEXT_LEN})
55
+ * — `A · Patch the regex` reads fine and saves a glance at the body. The
56
+ * moment one option is too wide, every button in that keyboard falls back to
57
+ * its bare letter and they pack four to a row: a keyboard that is half labels
58
+ * and half mystery letters is harder to read than one that is uniformly keyed,
59
+ * and the body above it already spells out what each letter stands for.
60
+ *
61
+ * `label` is what the button would carry, which is not always the whole of
62
+ * what the body says — a caller free to park detail in `description` keeps
63
+ * more of its buttons readable.
64
+ */
65
+ export function buildLetteredKeyboard(options) {
66
+ const labelled = options.map((o, idx) => `${optionLetter(idx)}${BUTTON_SEP}${oneLine(o.label)}`);
67
+ if (labelled.every(fitsOnButton)) {
68
+ return labelled.map((text, idx) => [{ text, callback_data: options[idx].callbackData }]);
69
+ }
70
+ return buildLetterKeyboard(options.map((o) => o.callbackData));
71
+ }
72
+ /**
73
+ * A keyboard of bare letters, four to a row: `A` for the first callback, `B`
74
+ * for the next. For a message whose body is already the full list — a tree
75
+ * drawn line by line, say — where a label on the button would only repeat it.
76
+ */
77
+ export function buildLetterKeyboard(callbackData) {
78
+ const rows = [];
79
+ for (let i = 0; i < callbackData.length; i += LETTERS_PER_ROW) {
80
+ rows.push(callbackData.slice(i, i + LETTERS_PER_ROW).map((data, j) => ({
81
+ text: optionLetter(i + j),
82
+ callback_data: data,
83
+ })));
84
+ }
85
+ return rows;
86
+ }
87
+ //# sourceMappingURL=lettered-options.js.map
@@ -0,0 +1,362 @@
1
+ /**
2
+ * Markdown, as Claude writes it, turned into a Telegram message: plain text
3
+ * with the formatting carried as entities. See ./entities.ts for why nothing
4
+ * goes out with a parse mode.
5
+ *
6
+ * The markdown is parsed into a syntax tree (CommonMark plus GitHub's tables,
7
+ * strikethrough and bare-URL links) and the tree is walked into an
8
+ * {@link EntityText}. Markdown that doesn't parse as formatting — an unclosed
9
+ * `**`, a half-written link while a reply is still streaming — comes out as the
10
+ * literal characters, never as an error.
11
+ *
12
+ * What it renders, kept as the earlier MarkdownV2 conversion showed it:
13
+ * headings in bold, `•` and `1.` list markers, `———` for a thematic break, and
14
+ * a table as one block of `**Header**: cell` lines per row, since Telegram has
15
+ * no tables. `<expandable>…</expandable>` becomes a quote collapsed to its
16
+ * first lines.
17
+ */
18
+ import { fromMarkdown } from 'mdast-util-from-markdown';
19
+ import { gfmFromMarkdown } from 'mdast-util-gfm';
20
+ import { gfm } from 'micromark-extension-gfm';
21
+ import { EntityText, indentMessage, isHighSurrogate, isLinkableUrl, sliceMessage, trimMessage, } from './entities.js';
22
+ /** Telegram's cap on a message's text, in UTF-16 code units. */
23
+ export const MAX_MESSAGE_LENGTH = 4096;
24
+ /** Telegram applies at most this many entities to a message. */
25
+ export const MAX_ENTITIES = 100;
26
+ /** Room kept free in every part of a split message for its `[2/3]` marker. */
27
+ const PART_MARKER_RESERVE = 16;
28
+ // ---------------------------------------------------------------------------
29
+ // Markdown → entities
30
+ // ---------------------------------------------------------------------------
31
+ const EXPANDABLE_TAG_RE = /<expandable>([\s\S]*?)<\/expandable>/g;
32
+ const expandablePlaceholder = (i) => `XCGEXPANDABLEBLOCK${i}ENDX`;
33
+ const EXPANDABLE_PLACEHOLDER_RE = /^XCGEXPANDABLEBLOCK(\d+)ENDX$/;
34
+ /**
35
+ * Pull `<expandable>` regions out before parsing, outside fenced code, so a
36
+ * markdown parser that reads them as raw HTML can't split them across nodes.
37
+ * Each leaves a placeholder paragraph of its own.
38
+ */
39
+ function extractExpandableBlocks(text) {
40
+ const blocks = [];
41
+ const parts = text.split(/(```[\s\S]*?```)/g);
42
+ const processed = parts.map((segment, i) => {
43
+ if (i % 2 === 1)
44
+ return segment;
45
+ return segment.replace(EXPANDABLE_TAG_RE, (_, body) => {
46
+ blocks.push(body.replace(/^\n+|\n+$/g, ''));
47
+ return `\n\n${expandablePlaceholder(blocks.length - 1)}\n\n`;
48
+ });
49
+ });
50
+ return { text: processed.join(''), blocks };
51
+ }
52
+ /** Convert markdown to a Telegram message: plain text plus entities. */
53
+ export function markdownToEntities(markdown) {
54
+ const { text, blocks } = extractExpandableBlocks(markdown);
55
+ return trimMessage(renderMarkdown(text, { inQuote: false, expandables: blocks }));
56
+ }
57
+ function renderMarkdown(markdown, ctx) {
58
+ let tree;
59
+ try {
60
+ tree = fromMarkdown(markdown, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] });
61
+ }
62
+ catch (error) {
63
+ // The parser accepts any string; this is belt and braces. Plain text is
64
+ // the one rendering that can't be refused.
65
+ console.error('[Markdown] Parse failed, sending as plain text:', error);
66
+ return { text: markdown, entities: [] };
67
+ }
68
+ return renderBlocks(tree.children, ctx, '\n\n');
69
+ }
70
+ function renderBlocks(nodes, ctx, separator) {
71
+ const b = new EntityText();
72
+ let first = true;
73
+ for (const node of nodes) {
74
+ const rendered = renderBlock(node, ctx);
75
+ if (rendered === null)
76
+ continue;
77
+ if (!first)
78
+ b.add(separator);
79
+ b.append(rendered);
80
+ first = false;
81
+ }
82
+ return b.build();
83
+ }
84
+ /** One block-level node, or null for one that renders nothing (a link definition). */
85
+ function renderBlock(node, ctx) {
86
+ const b = new EntityText();
87
+ switch (node.type) {
88
+ case 'paragraph': {
89
+ const placeholder = paragraphPlaceholder(node.children);
90
+ if (placeholder !== null)
91
+ return renderExpandable(ctx.expandables[placeholder] ?? '', ctx);
92
+ renderInline(b, node.children);
93
+ return b.build();
94
+ }
95
+ case 'heading':
96
+ b.wrap('bold', (inner) => renderInline(inner, node.children));
97
+ return b.build();
98
+ case 'thematicBreak':
99
+ return b.add('———').build();
100
+ case 'code':
101
+ // An empty block has nothing to show, and a `pre` over nothing is refused.
102
+ if (!node.value)
103
+ return null;
104
+ return b.pre(node.value, node.lang ?? undefined).build();
105
+ case 'blockquote': {
106
+ const inner = renderBlocks(node.children, { ...ctx, inQuote: true }, '\n');
107
+ if (ctx.inQuote)
108
+ return inner;
109
+ return b.quote(inner).build();
110
+ }
111
+ case 'list':
112
+ return renderList(node, ctx);
113
+ case 'table':
114
+ return renderTable(node);
115
+ case 'html':
116
+ return b.add(node.value).build();
117
+ case 'definition':
118
+ return null;
119
+ case 'footnoteDefinition': {
120
+ b.add(`[^${node.identifier}]: `);
121
+ b.append(indentMessage(renderBlocks(node.children, ctx, '\n'), ' ', true));
122
+ return b.build();
123
+ }
124
+ default:
125
+ // Anything phrasing-level that turns up at block level.
126
+ renderInline(b, [node]);
127
+ return b.build();
128
+ }
129
+ }
130
+ function paragraphPlaceholder(children) {
131
+ if (children.length !== 1 || children[0].type !== 'text')
132
+ return null;
133
+ const match = EXPANDABLE_PLACEHOLDER_RE.exec(children[0].value.trim());
134
+ return match ? Number(match[1]) : null;
135
+ }
136
+ function renderExpandable(body, ctx) {
137
+ const inner = trimMessage(renderMarkdown(body, { ...ctx, inQuote: true }));
138
+ if (!inner.text)
139
+ return null;
140
+ if (ctx.inQuote)
141
+ return inner;
142
+ return new EntityText().quote(inner, true).build();
143
+ }
144
+ function renderList(list, ctx) {
145
+ const b = new EntityText();
146
+ const start = list.start ?? 1;
147
+ list.children.forEach((item, i) => {
148
+ if (i > 0)
149
+ b.newline();
150
+ b.append(renderListItem(item, list.ordered ? `${start + i}. ` : '• ', ctx));
151
+ });
152
+ return b.build();
153
+ }
154
+ function renderListItem(item, marker, ctx) {
155
+ const b = new EntityText().add(marker);
156
+ if (item.checked === true)
157
+ b.add('☑ ');
158
+ else if (item.checked === false)
159
+ b.add('☐ ');
160
+ const body = renderBlocks(item.children, ctx, '\n');
161
+ // Continuation lines — a second paragraph, a nested list — sit indented
162
+ // under the item rather than flush with the margin.
163
+ return b.append(indentMessage(body, ' ', true)).build();
164
+ }
165
+ /**
166
+ * A table as one block per data row, each cell on a line of its own under its
167
+ * column's header in bold. A table with a header row only lists the headers.
168
+ */
169
+ function renderTable(table) {
170
+ const [headerRow, ...rows] = table.children;
171
+ const headers = headerRow?.children ?? [];
172
+ const b = new EntityText();
173
+ if (rows.length === 0) {
174
+ headers.forEach((cell, i) => {
175
+ if (i > 0)
176
+ b.newline();
177
+ b.add('- ');
178
+ renderInline(b, cell.children);
179
+ });
180
+ return b.build();
181
+ }
182
+ rows.forEach((row, r) => {
183
+ if (r > 0)
184
+ b.newline(2);
185
+ let firstLine = true;
186
+ row.children.forEach((cell, c) => {
187
+ if (cell.children.length === 0)
188
+ return;
189
+ if (!firstLine)
190
+ b.newline();
191
+ firstLine = false;
192
+ const header = headers[c];
193
+ if (header && header.children.length > 0) {
194
+ // The label is bold already, so a header that is bold in the markdown
195
+ // too doesn't need a second bold inside the first.
196
+ b.wrap('bold', (inner) => renderInline(inner, withoutStrong(header.children)));
197
+ b.add(': ');
198
+ }
199
+ renderInline(b, cell.children);
200
+ });
201
+ });
202
+ return b.build();
203
+ }
204
+ function withoutStrong(nodes) {
205
+ return nodes.flatMap((n) => (n.type === 'strong' ? withoutStrong(n.children) : [n]));
206
+ }
207
+ function renderInline(b, nodes) {
208
+ for (const node of nodes) {
209
+ switch (node.type) {
210
+ case 'text':
211
+ b.add(node.value);
212
+ break;
213
+ case 'strong':
214
+ b.wrap('bold', (inner) => renderInline(inner, node.children));
215
+ break;
216
+ case 'emphasis':
217
+ b.wrap('italic', (inner) => renderInline(inner, node.children));
218
+ break;
219
+ case 'delete':
220
+ b.wrap('strikethrough', (inner) => renderInline(inner, node.children));
221
+ break;
222
+ case 'inlineCode':
223
+ b.code(node.value);
224
+ break;
225
+ case 'break':
226
+ b.newline();
227
+ break;
228
+ case 'link':
229
+ renderLink(b, node.url, node.children);
230
+ break;
231
+ case 'image':
232
+ b.link(node.alt || node.url, node.url);
233
+ break;
234
+ case 'linkReference':
235
+ case 'imageReference':
236
+ // An unresolved reference: what the model typed, minus the brackets.
237
+ if ('children' in node)
238
+ renderInline(b, node.children);
239
+ else
240
+ b.add(node.alt ?? '');
241
+ break;
242
+ case 'footnoteReference':
243
+ b.add(`[^${node.identifier}]`);
244
+ break;
245
+ case 'html':
246
+ b.add(node.value);
247
+ break;
248
+ default:
249
+ b.add(textOf(node));
250
+ }
251
+ }
252
+ }
253
+ /**
254
+ * A link keeps the formatting inside its label. One Telegram won't take (see
255
+ * {@link EntityText.link}) is written out as its label and address instead.
256
+ */
257
+ function renderLink(b, url, children) {
258
+ const label = children.map(textOf).join('');
259
+ if (!isLinkableUrl(url)) {
260
+ b.link(label, url);
261
+ return;
262
+ }
263
+ if (!label) {
264
+ b.link(url, url);
265
+ return;
266
+ }
267
+ b.wrap('text_link', (inner) => renderInline(inner, children), { url });
268
+ }
269
+ function textOf(node) {
270
+ if ('value' in node && typeof node.value === 'string')
271
+ return node.value;
272
+ if ('children' in node)
273
+ return node.children.map((c) => textOf(c)).join('');
274
+ if (node.type === 'image')
275
+ return node.alt ?? '';
276
+ return '';
277
+ }
278
+ // ---------------------------------------------------------------------------
279
+ // Splitting
280
+ // ---------------------------------------------------------------------------
281
+ /**
282
+ * Split a message into parts Telegram will take: at most `maxLength` code
283
+ * units and {@link MAX_ENTITIES} entities each. Parts break at a paragraph, a
284
+ * line or a word where one is near enough to the limit, and anywhere at all
285
+ * otherwise — formatting that runs across a break continues on the other side,
286
+ * a code block included. With more than one part, each ends in `[n/total]`.
287
+ */
288
+ export function splitEntityMessage(message, maxLength = MAX_MESSAGE_LENGTH, { markers = true } = {}) {
289
+ let rest = trimMessage(message);
290
+ if (fits(rest, maxLength))
291
+ return [rest];
292
+ const budget = Math.max(1, maxLength - (markers ? PART_MARKER_RESERVE : 0));
293
+ // The marker is an entity too.
294
+ const entityBudget = markers ? MAX_ENTITIES - 1 : MAX_ENTITIES;
295
+ const parts = [];
296
+ while (!fits(rest, budget, entityBudget)) {
297
+ const cut = findCut(rest, budget, entityBudget);
298
+ const part = trimMessage(sliceMessage(rest, 0, cut));
299
+ if (part.text)
300
+ parts.push(part);
301
+ rest = trimLeading(sliceMessage(rest, cut));
302
+ }
303
+ rest = trimMessage(rest);
304
+ if (rest.text)
305
+ parts.push(rest);
306
+ if (parts.length <= 1 || !markers)
307
+ return parts;
308
+ return parts.map((part, i) => {
309
+ const b = new EntityText().append(part).newline(2).italic(`[${i + 1}/${parts.length}]`);
310
+ return b.length <= maxLength ? b.build() : part;
311
+ });
312
+ }
313
+ function fits(message, maxLength, maxEntities = MAX_ENTITIES) {
314
+ return message.text.length <= maxLength && message.entities.length <= maxEntities;
315
+ }
316
+ /**
317
+ * Where to end the next part. Prefers the last paragraph break, then line
318
+ * break, then space, in the back half of the window; inside a code block only
319
+ * a line break, so no line of code is cut in two unless it has to be.
320
+ */
321
+ function findCut(message, budget, entityBudget) {
322
+ const { text, entities } = message;
323
+ let limit = Math.min(budget, text.length);
324
+ if (entities.length > entityBudget) {
325
+ // End the part before the first entity it has no room for.
326
+ const starts = entities.map((e) => e.offset).sort((a, b) => a - b);
327
+ const overflowAt = starts[entityBudget];
328
+ if (overflowAt > 0)
329
+ limit = Math.min(limit, overflowAt);
330
+ }
331
+ if (limit >= text.length)
332
+ return text.length;
333
+ const window = text.slice(0, limit);
334
+ const half = limit / 2;
335
+ const inPre = entities.some((e) => e.type === 'pre' && e.offset < limit && e.offset + e.length > limit);
336
+ let cut = limit;
337
+ const breaks = inPre ? ['\n'] : ['\n\n', '\n', ' '];
338
+ for (const sep of breaks) {
339
+ const at = window.lastIndexOf(sep);
340
+ if (at > half) {
341
+ cut = at + sep.length;
342
+ break;
343
+ }
344
+ }
345
+ if (cut > 1 && cut < text.length && isHighSurrogate(text.charCodeAt(cut - 1)))
346
+ cut--;
347
+ return Math.max(1, cut);
348
+ }
349
+ /**
350
+ * Drop whitespace from the front of the next part — but inside a code block
351
+ * only newlines, since the spaces there are the code's indentation.
352
+ */
353
+ function trimLeading(message) {
354
+ const startsInPre = message.entities.some((e) => e.type === 'pre' && e.offset === 0);
355
+ const match = (startsInPre ? /^\n+/ : /^\s+/).exec(message.text);
356
+ return match ? sliceMessage(message, match[0].length) : message;
357
+ }
358
+ /** Markdown to the message parts it is sent as. */
359
+ export function formatMarkdown(markdown, maxLength = MAX_MESSAGE_LENGTH) {
360
+ return splitEntityMessage(markdownToEntities(markdown), maxLength);
361
+ }
362
+ //# sourceMappingURL=markdown.js.map