telecoder 0.0.0-stage → 1.2.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 (223) hide show
  1. package/.env.example +363 -0
  2. package/CHANGELOG.md +1186 -0
  3. package/LICENSE +22 -0
  4. package/README.md +126 -2
  5. package/dist/audio/transcribe.js +50 -0
  6. package/dist/bin/mcp-server.js +378 -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 +592 -0
  10. package/dist/bot/file-access.js +141 -0
  11. package/dist/bot/handlers/command/access.js +407 -0
  12. package/dist/bot/handlers/command/admin.js +827 -0
  13. package/dist/bot/handlers/command/auto-approve.js +138 -0
  14. package/dist/bot/handlers/command/btw.js +224 -0
  15. package/dist/bot/handlers/command/cost.js +409 -0
  16. package/dist/bot/handlers/command/media.js +197 -0
  17. package/dist/bot/handlers/command/model.js +305 -0
  18. package/dist/bot/handlers/command/prefs-scope.js +197 -0
  19. package/dist/bot/handlers/command/project.js +536 -0
  20. package/dist/bot/handlers/command/resume.js +321 -0
  21. package/dist/bot/handlers/command/session.js +438 -0
  22. package/dist/bot/handlers/command/settings.js +1012 -0
  23. package/dist/bot/handlers/command/shared.js +210 -0
  24. package/dist/bot/handlers/command/streaming-mode.js +16 -0
  25. package/dist/bot/handlers/command/tasks.js +513 -0
  26. package/dist/bot/handlers/command/topic-store.js +113 -0
  27. package/dist/bot/handlers/command/topic.js +80 -0
  28. package/dist/bot/handlers/command.handler.js +772 -0
  29. package/dist/bot/handlers/fork.handler.js +1109 -0
  30. package/dist/bot/handlers/media-fallback.js +121 -0
  31. package/dist/bot/handlers/message/replies.js +133 -0
  32. package/dist/bot/handlers/message/shared.js +117 -0
  33. package/dist/bot/handlers/message/throttle.js +49 -0
  34. package/dist/bot/handlers/message/turn-notify.js +169 -0
  35. package/dist/bot/handlers/message/turn-runner.js +141 -0
  36. package/dist/bot/handlers/message.handler.js +107 -0
  37. package/dist/bot/handlers/newbot.handler.js +221 -0
  38. package/dist/bot/handlers/photo.handler.js +327 -0
  39. package/dist/bot/handlers/prompts.handler.js +343 -0
  40. package/dist/bot/handlers/running-note.js +44 -0
  41. package/dist/bot/handlers/schedule.handler.js +303 -0
  42. package/dist/bot/handlers/session-guard.js +78 -0
  43. package/dist/bot/handlers/suggestion.handler.js +84 -0
  44. package/dist/bot/handlers/tree.handler.js +480 -0
  45. package/dist/bot/handlers/view.js +41 -0
  46. package/dist/bot/handlers/voice.handler.js +209 -0
  47. package/dist/bot/middleware/admin-only.js +49 -0
  48. package/dist/bot/middleware/auth.middleware.js +122 -0
  49. package/dist/bot/middleware/group-mention.middleware.js +139 -0
  50. package/dist/bot/middleware/group-role.middleware.js +75 -0
  51. package/dist/bot/middleware/message-batcher.js +87 -0
  52. package/dist/bot/middleware/queued-messages.js +971 -0
  53. package/dist/bot/middleware/stale-filter.js +31 -0
  54. package/dist/build-info.json +8 -0
  55. package/dist/claude/agent-watchdog.js +162 -0
  56. package/dist/claude/agent.js +1458 -0
  57. package/dist/claude/ask-user.js +295 -0
  58. package/dist/claude/auto-approve.js +225 -0
  59. package/dist/claude/auto-topic-haiku.js +126 -0
  60. package/dist/claude/available-commands.js +153 -0
  61. package/dist/claude/carry-over.js +27 -0
  62. package/dist/claude/ccr-shim.js +46 -0
  63. package/dist/claude/charter-judge.js +214 -0
  64. package/dist/claude/claude-auth.js +121 -0
  65. package/dist/claude/command-parser.js +200 -0
  66. package/dist/claude/cost-overlay-scraper.js +129 -0
  67. package/dist/claude/enabled-plugins.js +56 -0
  68. package/dist/claude/fork-tree.js +393 -0
  69. package/dist/claude/held-query.js +190 -0
  70. package/dist/claude/in-flight-tracker.js +61 -0
  71. package/dist/claude/ipc-server.js +192 -0
  72. package/dist/claude/mcp-bridge.js +453 -0
  73. package/dist/claude/mcp-tools.js +354 -0
  74. package/dist/claude/message-offsets.js +88 -0
  75. package/dist/claude/modal-relay.js +450 -0
  76. package/dist/claude/model-catalog.js +85 -0
  77. package/dist/claude/monitor-relay.js +597 -0
  78. package/dist/claude/pending-forks.js +93 -0
  79. package/dist/claude/pending-suggestions.js +50 -0
  80. package/dist/claude/permission-gate.js +337 -0
  81. package/dist/claude/permission-mode.js +178 -0
  82. package/dist/claude/poll-user.js +51 -0
  83. package/dist/claude/project-commands.js +69 -0
  84. package/dist/claude/prompt-hold.js +124 -0
  85. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  86. package/dist/claude/pty-provider.js +2214 -0
  87. package/dist/claude/pty-spawn-config.js +296 -0
  88. package/dist/claude/pty-stream.js +363 -0
  89. package/dist/claude/request-queue.js +135 -0
  90. package/dist/claude/scheduled-runner.js +91 -0
  91. package/dist/claude/scheduler.js +237 -0
  92. package/dist/claude/scope-guard.js +274 -0
  93. package/dist/claude/sdk-permission-gate.js +77 -0
  94. package/dist/claude/secret-request.js +576 -0
  95. package/dist/claude/session-cost.js +41 -0
  96. package/dist/claude/session-history.js +286 -0
  97. package/dist/claude/session-jsonl.js +920 -0
  98. package/dist/claude/session-manager.js +195 -0
  99. package/dist/claude/session-scan.js +270 -0
  100. package/dist/claude/setup-token.js +285 -0
  101. package/dist/claude/side-call-options.js +45 -0
  102. package/dist/claude/side-question.js +249 -0
  103. package/dist/claude/stage-images.js +62 -0
  104. package/dist/claude/subagent-tools.js +12 -0
  105. package/dist/claude/synthetic-ctx.js +51 -0
  106. package/dist/claude/system-prompt.js +162 -0
  107. package/dist/claude/tasks-overlay-scraper.js +94 -0
  108. package/dist/claude/tip-scraper.js +78 -0
  109. package/dist/claude/tui-modal.js +501 -0
  110. package/dist/claude/tui-state.js +384 -0
  111. package/dist/claude/turn-end.js +91 -0
  112. package/dist/claude/turn-prose.js +64 -0
  113. package/dist/claude/update-banner-relay.js +70 -0
  114. package/dist/cli/commands/doctor.js +305 -0
  115. package/dist/cli/commands/help.js +25 -0
  116. package/dist/cli/commands/init.js +123 -0
  117. package/dist/cli/commands/service.js +678 -0
  118. package/dist/cli/commands/start.js +53 -0
  119. package/dist/cli/commands/version.js +11 -0
  120. package/dist/cli/dispatch.js +79 -0
  121. package/dist/cli/init/env-file.js +99 -0
  122. package/dist/cli/init/flow.js +638 -0
  123. package/dist/cli/init/prompter.js +116 -0
  124. package/dist/cli/init/telegram.js +94 -0
  125. package/dist/cli/service/render.js +212 -0
  126. package/dist/cli.js +18 -0
  127. package/dist/config-report.js +107 -0
  128. package/dist/config.js +500 -0
  129. package/dist/index.js +367 -0
  130. package/dist/launcher.js +933 -0
  131. package/dist/node-version-check.js +27 -0
  132. package/dist/providers/ccr-health.js +119 -0
  133. package/dist/providers/ccr-introspect.js +149 -0
  134. package/dist/providers/ccr-provider.js +60 -0
  135. package/dist/providers/claude-provider.js +63 -0
  136. package/dist/providers/prefs-sync.js +164 -0
  137. package/dist/providers/project-favorites.js +74 -0
  138. package/dist/providers/provider-router.js +127 -0
  139. package/dist/providers/provider-switch.js +91 -0
  140. package/dist/providers/sdk-provider.js +37 -0
  141. package/dist/providers/types.js +8 -0
  142. package/dist/providers/user-preferences.js +214 -0
  143. package/dist/restart-when-idle.js +153 -0
  144. package/dist/startup/auto-continue.js +67 -0
  145. package/dist/startup/auto-resume.js +173 -0
  146. package/dist/startup/notices.js +120 -0
  147. package/dist/startup/shared.js +44 -0
  148. package/dist/startup/verify-token.js +31 -0
  149. package/dist/telegram/access-request.js +153 -0
  150. package/dist/telegram/action-logger.js +684 -0
  151. package/dist/telegram/admin-mention.js +107 -0
  152. package/dist/telegram/background-activity-card.js +502 -0
  153. package/dist/telegram/botname-settings.js +336 -0
  154. package/dist/telegram/button-text.js +26 -0
  155. package/dist/telegram/client-options.js +27 -0
  156. package/dist/telegram/deduplication.js +33 -0
  157. package/dist/telegram/entities.js +295 -0
  158. package/dist/telegram/force-reply-tracker.js +57 -0
  159. package/dist/telegram/lettered-options.js +87 -0
  160. package/dist/telegram/markdown.js +362 -0
  161. package/dist/telegram/message-sender.js +1287 -0
  162. package/dist/telegram/prompt-label.js +142 -0
  163. package/dist/telegram/prompt-suggestion.js +54 -0
  164. package/dist/telegram/send.js +123 -0
  165. package/dist/telegram/streaming-turn.js +105 -0
  166. package/dist/telegram/suggestions-settings.js +30 -0
  167. package/dist/telegram/task-list.js +367 -0
  168. package/dist/telegram/task-tracker.js +209 -0
  169. package/dist/telegram/telegraph-settings.js +31 -0
  170. package/dist/telegram/telegraph.js +453 -0
  171. package/dist/telegram/terminal-renderer.js +671 -0
  172. package/dist/telegram/terminal-settings.js +25 -0
  173. package/dist/telegram/thread-titles.js +190 -0
  174. package/dist/telegram/threads-setup.js +117 -0
  175. package/dist/tts/tts-settings.js +62 -0
  176. package/dist/tts/tts.js +245 -0
  177. package/dist/tts/voice-reply.js +78 -0
  178. package/dist/utils/admins.js +143 -0
  179. package/dist/utils/agent-timer.js +55 -0
  180. package/dist/utils/atomic-write.js +24 -0
  181. package/dist/utils/bot-token.js +74 -0
  182. package/dist/utils/bounded-map.js +55 -0
  183. package/dist/utils/build-info.js +57 -0
  184. package/dist/utils/caffeinate.js +50 -0
  185. package/dist/utils/claude-env.js +54 -0
  186. package/dist/utils/claude-version.js +48 -0
  187. package/dist/utils/config-home.js +62 -0
  188. package/dist/utils/debug-agent.js +117 -0
  189. package/dist/utils/debug-watchdog.js +121 -0
  190. package/dist/utils/download.js +111 -0
  191. package/dist/utils/exit-codes.js +48 -0
  192. package/dist/utils/file-type.js +149 -0
  193. package/dist/utils/format.js +81 -0
  194. package/dist/utils/home-project.js +30 -0
  195. package/dist/utils/host-stall.js +51 -0
  196. package/dist/utils/id-list.js +44 -0
  197. package/dist/utils/idle-restart.js +92 -0
  198. package/dist/utils/install-mode.js +63 -0
  199. package/dist/utils/instance-config.js +148 -0
  200. package/dist/utils/instances.js +95 -0
  201. package/dist/utils/json-store.js +140 -0
  202. package/dist/utils/keyed-settings.js +62 -0
  203. package/dist/utils/legacy-env.js +35 -0
  204. package/dist/utils/npm-version.js +134 -0
  205. package/dist/utils/prefs-relay.js +107 -0
  206. package/dist/utils/proc-children.js +102 -0
  207. package/dist/utils/project-data-dir.js +33 -0
  208. package/dist/utils/reasoning-summary.js +12 -0
  209. package/dist/utils/resolve-bin.js +86 -0
  210. package/dist/utils/resolve-claude-bin.js +63 -0
  211. package/dist/utils/respawn-backoff.js +19 -0
  212. package/dist/utils/sanitize.js +91 -0
  213. package/dist/utils/session-key.js +37 -0
  214. package/dist/utils/stale-launcher.js +109 -0
  215. package/dist/utils/state-dir-migration.js +92 -0
  216. package/dist/utils/systemd.js +126 -0
  217. package/dist/utils/user-roster.js +275 -0
  218. package/dist/utils/verbosity.js +118 -0
  219. package/dist/utils/version-check.js +166 -0
  220. package/dist/utils/workspace-guard.js +44 -0
  221. package/dist/worker-restart.js +141 -0
  222. package/instances.json.example +41 -0
  223. package/package.json +76 -4
@@ -0,0 +1,295 @@
1
+ /**
2
+ * Plain-text messages carrying explicit Telegram entities.
3
+ *
4
+ * Every message TeleCoder sends is formatted this way; nothing goes out with a
5
+ * parse mode. MarkdownV2 meant escaping, and escaping is exactly what fails
6
+ * when the text being formatted came from the model or from a shell command — a
7
+ * stray underscore in a URL parameter or an unbalanced backtick in a `sed`
8
+ * script turned a `sendMessage` into a 400. It also could not be split: a long
9
+ * reply cut in the middle of a bold run or a link broke both halves.
10
+ *
11
+ * Entities sidestep that: the text is sent verbatim with no parse mode, and the
12
+ * formatting rides alongside as offsets. Nothing in the payload can be
13
+ * misparsed, because nothing is parsed.
14
+ *
15
+ * It also buys the one thing MarkdownV2 cannot express — `text_mention`, a
16
+ * mention of a user by numeric id. That is what makes an approval prompt raise
17
+ * a notification for the admin who has to answer it, even in a muted group,
18
+ * and even for an admin who has no @username.
19
+ *
20
+ * Offsets are UTF-16 code units, which is what `String.length` counts, so the
21
+ * running length below is the offset Telegram expects — including for emoji,
22
+ * which occupy two units each.
23
+ */
24
+ /**
25
+ * Accumulates text and the entities that describe it. Every method returns
26
+ * `this` so a message reads top-to-bottom in the order it renders.
27
+ */
28
+ export class EntityText {
29
+ parts = [];
30
+ offset = 0;
31
+ entities = [];
32
+ /** Append unstyled text. */
33
+ add(text) {
34
+ if (text) {
35
+ this.parts.push(text);
36
+ this.offset += text.length;
37
+ }
38
+ return this;
39
+ }
40
+ /** Append a newline (or several). */
41
+ newline(count = 1) {
42
+ return this.add('\n'.repeat(count));
43
+ }
44
+ styled(text, entity) {
45
+ if (!text)
46
+ return this;
47
+ this.entities.push(entity(this.offset, text.length));
48
+ return this.add(text);
49
+ }
50
+ bold(text) {
51
+ return this.styled(text, (offset, length) => ({ type: 'bold', offset, length }));
52
+ }
53
+ italic(text) {
54
+ return this.styled(text, (offset, length) => ({ type: 'italic', offset, length }));
55
+ }
56
+ /** Inline monospace — for a tool name, a path, a flag. */
57
+ code(text) {
58
+ return this.styled(text, (offset, length) => ({ type: 'code', offset, length }));
59
+ }
60
+ /**
61
+ * A monospace block, for a shell command or other multi-line verbatim text.
62
+ * Telegram renders `pre` with its own trailing newline, so callers should not
63
+ * add one inside `text`.
64
+ */
65
+ pre(text, language) {
66
+ return this.styled(text, (offset, length) => ({
67
+ type: 'pre',
68
+ offset,
69
+ length,
70
+ ...(language ? { language } : {}),
71
+ }));
72
+ }
73
+ strikethrough(text) {
74
+ return this.styled(text, (offset, length) => ({ type: 'strikethrough', offset, length }));
75
+ }
76
+ underline(text) {
77
+ return this.styled(text, (offset, length) => ({ type: 'underline', offset, length }));
78
+ }
79
+ spoiler(text) {
80
+ return this.styled(text, (offset, length) => ({ type: 'spoiler', offset, length }));
81
+ }
82
+ /**
83
+ * `text` as a link to `url`, which the reader doesn't have to see spelled out.
84
+ *
85
+ * Telegram refuses the whole message over a link it won't accept — one to
86
+ * `http://localhost:3000`, say, which has no TLD. Such a link goes out as
87
+ * plain text instead, with the address after it when the label hides it.
88
+ */
89
+ link(text, url) {
90
+ if (!isLinkableUrl(url))
91
+ return this.add(text === url || !text ? url : `${text} (${url})`);
92
+ return this.styled(text || url, (offset, length) => ({ type: 'text_link', offset, length, url }));
93
+ }
94
+ /**
95
+ * A quote; `expandable` collapses it to its first lines until tapped. Telegram
96
+ * does not nest quotes, so callers must not open one inside another.
97
+ */
98
+ quote(text, expandable = false) {
99
+ const type = expandable ? 'expandable_blockquote' : 'blockquote';
100
+ return this.wrap(type, (b) => (typeof text === 'string' ? b.add(text) : b.append(text)));
101
+ }
102
+ /**
103
+ * Wrap whatever `build` appends in one entity of `type`, so it can carry
104
+ * entities of its own: bold inside a link, code inside a quote.
105
+ */
106
+ wrap(type, build, extra = {}) {
107
+ const start = this.offset;
108
+ const at = this.entities.length;
109
+ build(this);
110
+ const length = this.offset - start;
111
+ if (length > 0) {
112
+ // Before the entities appended inside it, so a reader of the list meets
113
+ // the outer one first, as Telegram itself orders them.
114
+ this.entities.splice(at, 0, { type, offset: start, length, ...extra });
115
+ }
116
+ return this;
117
+ }
118
+ /**
119
+ * Mention a user by numeric id. Telegram notifies them if they are a member
120
+ * of the chat, whether or not they have a @username, and renders `label` as
121
+ * a link to their profile.
122
+ */
123
+ mention(label, userId) {
124
+ return this.styled(label, (offset, length) => ({
125
+ type: 'text_mention',
126
+ offset,
127
+ length,
128
+ // Telegram only reads `id` off this object; the rest of grammy's User
129
+ // shape is required by the type but ignored on the wire.
130
+ user: { id: userId, is_bot: false, first_name: label },
131
+ }));
132
+ }
133
+ /**
134
+ * A moment in time, which Telegram shows in the reader's own timezone and
135
+ * format — Bot API 9.5's `date_time` entity. The bot runs on a server whose
136
+ * clock can be hours off the reader's, so a time it writes out itself can be
137
+ * too. `text` is what a client too old for the entity shows instead.
138
+ *
139
+ * `format` is Telegram's: `t` a short time (22:45), `T` one with seconds.
140
+ */
141
+ dateTime(text, unixMs, format = 't') {
142
+ return this.styled(text, (offset, length) => ({
143
+ type: 'date_time',
144
+ offset,
145
+ length,
146
+ unix_time: Math.floor(unixMs / 1000),
147
+ date_time_format: format,
148
+ // grammy's MessageEntity predates Bot API 9.5 and has no `date_time`.
149
+ }));
150
+ }
151
+ /** Append another built message, its entities shifted to where it lands. */
152
+ append(message) {
153
+ for (const entity of message.entities) {
154
+ this.entities.push({ ...entity, offset: entity.offset + this.offset });
155
+ }
156
+ return this.add(message.text);
157
+ }
158
+ /** Current length in UTF-16 code units — the unit Telegram's 4096 cap counts. */
159
+ get length() {
160
+ return this.offset;
161
+ }
162
+ build() {
163
+ return { text: this.parts.join(''), entities: this.entities };
164
+ }
165
+ }
166
+ /**
167
+ * Clip text to `max` code units, marking the cut. Entity offsets are computed
168
+ * from the text as appended, so anything long has to be shortened *before* it
169
+ * goes into the builder rather than after.
170
+ */
171
+ export function clip(text, max) {
172
+ if (text.length <= max)
173
+ return text;
174
+ // Never between the halves of a surrogate pair: half an emoji is invalid
175
+ // UTF-16, which Telegram refuses.
176
+ let cut = Math.max(0, max - 1);
177
+ if (cut > 0 && isHighSurrogate(text.charCodeAt(cut - 1)))
178
+ cut--;
179
+ return text.slice(0, cut) + '…';
180
+ }
181
+ export function isHighSurrogate(code) {
182
+ return code >= 0xd800 && code <= 0xdbff;
183
+ }
184
+ /**
185
+ * Whether Telegram accepts `url` on a `text_link`. It wants a web address with
186
+ * a real top-level domain (no `localhost`, no bare IP, no single-label
187
+ * intranet host) or one of its own `tg:` links; anything else makes it refuse
188
+ * the entire message.
189
+ */
190
+ export function isLinkableUrl(url) {
191
+ let parsed;
192
+ try {
193
+ parsed = new URL(url);
194
+ }
195
+ catch {
196
+ return false;
197
+ }
198
+ if (parsed.protocol === 'tg:')
199
+ return true;
200
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
201
+ return false;
202
+ const labels = parsed.hostname.split('.');
203
+ if (labels.length < 2 || labels.some((l) => !l))
204
+ return false;
205
+ const tld = labels[labels.length - 1];
206
+ return /^(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$/i.test(tld);
207
+ }
208
+ /** Plain text, no formatting. */
209
+ export function plain(text) {
210
+ return { text, entities: [] };
211
+ }
212
+ /** Join messages with `separator`, shifting each one's entities into place. */
213
+ export function joinMessages(messages, separator = '\n\n') {
214
+ const b = new EntityText();
215
+ messages.forEach((m, i) => {
216
+ if (i > 0)
217
+ b.add(separator);
218
+ b.append(m);
219
+ });
220
+ return b.build();
221
+ }
222
+ /**
223
+ * The slice `[start, end)` of a message, with its entities cut to fit. An
224
+ * entity running across either edge keeps the part inside, which is what lets
225
+ * a long reply be split in the middle of a bold run or a code block and keep
226
+ * the formatting on both sides.
227
+ */
228
+ export function sliceMessage(message, start, end = message.text.length) {
229
+ const entities = [];
230
+ for (const e of message.entities) {
231
+ const from = Math.max(e.offset, start);
232
+ const to = Math.min(e.offset + e.length, end);
233
+ if (to <= from)
234
+ continue;
235
+ entities.push({ ...e, offset: from - start, length: to - from });
236
+ }
237
+ return { text: message.text.slice(start, end), entities: dropBlankEntities(message.text.slice(start, end), entities) };
238
+ }
239
+ /**
240
+ * Strip leading and trailing whitespace, as Telegram does to every message on
241
+ * arrival. It strips it *before* applying the offsets, so a message that
242
+ * starts with a newline would otherwise have all its formatting shifted one
243
+ * character to the left — or refused, when an entity then runs off the end.
244
+ */
245
+ export function trimMessage(message) {
246
+ const start = message.text.length - message.text.trimStart().length;
247
+ const end = message.text.trimEnd().length;
248
+ if (start === 0 && end === message.text.length)
249
+ return message;
250
+ if (end <= start)
251
+ return plain('');
252
+ return sliceMessage(message, start, end);
253
+ }
254
+ /**
255
+ * Drop entities with nothing visible in them. Telegram rejects a message with
256
+ * an entity over whitespace alone ("text must be non-empty") for some types,
257
+ * and a slice can leave one behind at either edge.
258
+ */
259
+ function dropBlankEntities(text, entities) {
260
+ return entities.filter((e) => e.length > 0 && (e.type === 'pre' || text.slice(e.offset, e.offset + e.length).trim() !== ''));
261
+ }
262
+ /**
263
+ * Prefix every line of `message` with `prefix`, keeping its entities on the
264
+ * same characters. For list items: a nested paragraph or sub-list lines up
265
+ * under its bullet.
266
+ */
267
+ export function indentMessage(message, prefix, skipFirstLine = false) {
268
+ if (!prefix)
269
+ return message;
270
+ const { text } = message;
271
+ // shift[i] is how far character i moves: one prefix for every line start at
272
+ // or before it.
273
+ const shift = new Array(text.length + 1);
274
+ let added = 0;
275
+ let out = '';
276
+ for (let i = 0; i <= text.length; i++) {
277
+ const lineStart = i === 0 ? !skipFirstLine : text[i - 1] === '\n';
278
+ if (lineStart && i < text.length && text[i] !== '\n') {
279
+ out += prefix;
280
+ added += prefix.length;
281
+ }
282
+ shift[i] = added;
283
+ if (i < text.length)
284
+ out += text[i];
285
+ }
286
+ const entities = message.entities.map((e) => {
287
+ const from = e.offset + shift[e.offset];
288
+ // The end keeps the shift of the last character inside the entity, so a
289
+ // prefix inserted at the next line's start stays outside it.
290
+ const lastShift = e.length > 0 ? shift[e.offset + e.length - 1] : shift[e.offset];
291
+ return { ...e, offset: from, length: e.offset + e.length + lastShift - from };
292
+ });
293
+ return { text: out, entities };
294
+ }
295
+ //# sourceMappingURL=entities.js.map
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Remembers which of the bot's own messages were ForceReply prompts.
3
+ *
4
+ * In a group the bot only answers when it is @mentioned, but the ForceReply
5
+ * flows (`/project`, `/plan`, `/file`, …) are answered by replying to the
6
+ * prompt — Telegram pops the composer open with the reply already attached,
7
+ * and there is nowhere to put a mention. Those replies have to stay
8
+ * addressed, so the gate needs to tell "answering a prompt" apart from
9
+ * "quoting something the bot said".
10
+ *
11
+ * Rather than re-deriving that from the prompt's wording (a list that would
12
+ * drift from the handlers), a transformer watches outgoing sendMessage calls
13
+ * and records the id of any message sent with a force_reply keyboard.
14
+ *
15
+ * The ids live in memory only: these prompts are answered within seconds, and
16
+ * a prompt left hanging across a restart is better re-opened than resurrected.
17
+ */
18
+ /** Plenty for any realistic number of prompts open at once; bounds the set. */
19
+ const MAX_TRACKED = 200;
20
+ const prompts = new Set();
21
+ const key = (chatId, messageId) => `${chatId}:${messageId}`;
22
+ export function rememberForceReplyPrompt(chatId, messageId) {
23
+ const k = key(chatId, messageId);
24
+ // Re-inserting moves it to the end, so the oldest entry is always first out.
25
+ prompts.delete(k);
26
+ prompts.add(k);
27
+ while (prompts.size > MAX_TRACKED) {
28
+ const oldest = prompts.values().next();
29
+ if (oldest.done)
30
+ break;
31
+ prompts.delete(oldest.value);
32
+ }
33
+ }
34
+ export function isForceReplyPrompt(chatId, messageId) {
35
+ return prompts.has(key(chatId, messageId));
36
+ }
37
+ /** Test seam — the set is module state that would otherwise leak between cases. */
38
+ export function clearForceReplyPrompts() {
39
+ prompts.clear();
40
+ }
41
+ /** Record every ForceReply prompt this bot sends. Call once, at startup. */
42
+ export function trackForceReplyPrompts(bot) {
43
+ bot.api.config.use(async (prev, method, payload, signal) => {
44
+ const res = await prev(method, payload, signal);
45
+ if (method !== 'sendMessage' || !res.ok)
46
+ return res;
47
+ const markup = payload.reply_markup;
48
+ if (!markup?.force_reply)
49
+ return res;
50
+ const sent = res.result;
51
+ if (typeof sent?.message_id === 'number' && typeof sent.chat?.id === 'number') {
52
+ rememberForceReplyPrompt(sent.chat.id, sent.message_id);
53
+ }
54
+ return res;
55
+ });
56
+ }
57
+ //# 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