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,573 @@
1
+ import { startIpcServer } from '../claude/ipc-server.js';
2
+ import { Bot } from 'grammy';
3
+ import { autoRetry } from '@grammyjs/auto-retry';
4
+ import { sequentialize } from '@grammyjs/runner';
5
+ import { telegramClientOptions, telegramProxyUrl } from '../telegram/client-options.js';
6
+ import { redactSecrets } from '../utils/sanitize.js';
7
+ import { config } from '../config.js';
8
+ import { buildSessionKey } from '../utils/session-key.js';
9
+ import { authMiddleware } from './middleware/auth.middleware.js';
10
+ import { adminOnly, adminOrApproverOnly } from './middleware/admin-only.js';
11
+ import { trackQueuedMessage, holdQueuedMessage, handleQueuedCallback, handleEditedMessage, handleLater, handleSteer, initParkedMessages, setQueuedDiverters, } from './middleware/queued-messages.js';
12
+ import { handleStart, handleClear, handleDir, handleDirCallback, handleInfo, handlePermissionMode, handlePermissionModeCallback, handleSuggestions, handleSuggestionsCallback, handleBotStatus, handleBotVersion, handleBotRestart, handleBotRestartCallback, handleRestartCallback, handleStartupCallback, handleUsage, handleBotUpdate, handleBotUpdateCallback, handleCancel, handleCommands, handleModelCommand, handleModelCallback, handlePrefsScopeCallback, handleProviderSwitchCallback, handleCcrCommand, handleResume, handleResumeCallback, handleHistory, handleResend, handleGate, handleProjectCommands, handleTerminal, handleFile, handleFooter, handleFooterCallback, handleBotName, handleTopic, handleBotRebuild, handleBotRebuildCallback, handleBtw, handleEffort, handleEffortCallback, handleTasks, handleTasksCallback, handleShells, handleShellsCallback, handleVerbosity, handleVerbosityCallback, } from './handlers/command.handler.js';
13
+ import { handleMessage, handleNativeCommand } from './handlers/message.handler.js';
14
+ import { handleLoop, handleLoops, handleLoopsCallback } from './handlers/loop.handler.js';
15
+ import { handleBranchCallback, handleBranchAcceptCommand, handleBranchDeclineCommand, handleBranchCommand, handleSpinoffCommand, branchPastRunningTurnIntoThread } from './handlers/branch.handler.js';
16
+ import { askBtw } from './handlers/command/btw.js';
17
+ import { handleNewBot, handleManagedBotCreated } from './handlers/newbot.handler.js';
18
+ import { handleTreeCommand, handleTreeCallback } from './handlers/tree.handler.js';
19
+ import { handlePromptsCommand, handlePromptsCallback } from './handlers/prompts.handler.js';
20
+ import { handleAllow, handleDeny, handleUsers, handleMembers, handleAccessCallback, } from './handlers/command/access.js';
21
+ import { handleAutoApprove } from './handlers/command/auto-approve.js';
22
+ import { handleSuggestionTapCallback } from './handlers/suggestion.handler.js';
23
+ import { handleVoice } from './handlers/voice.handler.js';
24
+ import { handlePhoto, handleImageDocument, handleTextDocument } from './handlers/photo.handler.js';
25
+ import { handleUnsupportedVideo, handleUnsupportedAudio, handleUnsupportedMediaDocument, } from './handlers/media-fallback.js';
26
+ import { createBatchMiddleware } from './middleware/message-batcher.js';
27
+ import { albumParts, createAlbumMiddleware } from './middleware/album-collector.js';
28
+ import { handleAlbum } from './handlers/album.handler.js';
29
+ import { countUpdatesInFlight } from '../restart-when-idle.js';
30
+ import { resolvePendingQuestion, getQuestionResponders, getQuestionOptionLabel, questionOwnerCloses, appendAnsweredFooter, buildAnswerConfirmation, } from '../claude/ask-user.js';
31
+ import { describeResponderRefusal } from '../telegram/admin-mention.js';
32
+ import { handleAskUserFormCallback } from '../claude/ask-user-form.js';
33
+ import { groupMentionMiddleware } from './middleware/group-mention.middleware.js';
34
+ import { groupRoleMiddleware } from './middleware/group-role.middleware.js';
35
+ import { trackForceReplyPrompts } from '../telegram/force-reply-tracker.js';
36
+ import { initThreadTitles } from '../telegram/thread-titles.js';
37
+ import { watchForDeletedThreads } from './deleted-threads.js';
38
+ import { startPtyIdleReaper } from '../claude/pty-idle-reaper.js';
39
+ import { handleThreadDelete, handleThreadDeleteCallback, handleThreadKeep } from './handlers/command/thread.js';
40
+ import { handleThreadCleanup, handleThreadCleanupCallback } from './handlers/command/cleanup.js';
41
+ import { handleCtrlB } from './handlers/command/background.js';
42
+ import { initThreadsSetup } from '../telegram/threads-setup.js';
43
+ import { resolvePendingPoll } from '../claude/poll-user.js';
44
+ import { captureSecretMessages, handleSecretCallback } from '../claude/secret-request.js';
45
+ import { captureTypedAnswers } from '../claude/typed-answer.js';
46
+ import { registerBotCommandName } from '../claude/command-parser.js';
47
+ import { buildCommandMenu, setCommandCatalog } from './command-catalog.js';
48
+ import { handleCommandFixCallback, initCommandFallback } from './handlers/command-fallback.js';
49
+ import { withRunningNote } from './handlers/running-note.js';
50
+ /** The toast under a button no handler knows, which is one from before an update. */
51
+ export const STALE_BUTTON_NOTE = 'This button is from before an update and no longer works. Send the command again.';
52
+ // Resolve sequentialize constraint: same-chat updates are ordered,
53
+ // but /cancel is registered BEFORE this middleware so it bypasses it.
54
+ async function handleAskUserCallback(ctx) {
55
+ const data = ctx.callbackQuery?.data;
56
+ if (!data)
57
+ return;
58
+ const parts = data.split(':');
59
+ if (parts.length !== 3)
60
+ return;
61
+ const [, id, idxStr] = parts;
62
+ const idx = parseInt(idxStr, 10);
63
+ if (Number.isNaN(idx))
64
+ return;
65
+ // Read the label before resolving — resolving drops the entry. It comes from
66
+ // the registry rather than off the tapped button because the button may be a
67
+ // bare letter: a keyboard whose labels are too wide for Telegram renders as
68
+ // `A` `B` `C` with the full text in the message body, and "✅ Answered: A"
69
+ // is not an answer anyone can read back later.
70
+ const optionLabel = getQuestionOptionLabel(id, idx);
71
+ const ownerCloses = questionOwnerCloses(id);
72
+ const outcome = resolvePendingQuestion(id, idx, ctx.from?.id);
73
+ if (outcome === 'expired') {
74
+ await ctx.answerCallbackQuery({ text: 'This question already expired.' });
75
+ // A question that timed out is closed by whoever was waiting on it, but a
76
+ // restart forgets every open question without touching its message. Take
77
+ // the keyboard down so it stops looking answerable. Text left alone: a
78
+ // quick second tap on a question just answered lands here too, and its
79
+ // "✅ Answered" footer must survive.
80
+ try {
81
+ await ctx.editMessageReplyMarkup();
82
+ }
83
+ catch {
84
+ // Already gone, or the message can't be edited — nothing left to do.
85
+ }
86
+ return;
87
+ }
88
+ if (outcome === 'forbidden') {
89
+ // Leave the keyboard up — the people who *can* answer still need it.
90
+ await ctx.answerCallbackQuery({
91
+ text: describeResponderRefusal(getQuestionResponders(id), ctx.from?.id),
92
+ show_alert: true,
93
+ });
94
+ return;
95
+ }
96
+ await ctx.answerCallbackQuery();
97
+ // A question its asker keeps re-posting over the same message (the memory
98
+ // guard's "Check again") is the asker's to mark up and close; an "Answered"
99
+ // footer here would race its next edit.
100
+ if (ownerCloses)
101
+ return;
102
+ const message = ctx.callbackQuery?.message;
103
+ const answerText = optionLabel ?? `option ${idx + 1}`;
104
+ // Strip the keyboard so the user can't tap again, and mark the chosen option
105
+ // in place so the question doesn't read as unanswered.
106
+ //
107
+ // Plain text: the label is model-supplied and may contain unbalanced
108
+ // Markdown punctuation (underscores in URL params, stray asterisks, …)
109
+ // which would 400 the edit. A question that went out with entities — a
110
+ // relayed dialog, a permission prompt — gets them back, or the edit strips
111
+ // it to plain text; the footer only appends, so their offsets still hold.
112
+ try {
113
+ const answered = appendAnsweredFooter(message?.text ?? '', answerText);
114
+ if (answered === null)
115
+ await ctx.editMessageReplyMarkup();
116
+ else if (!message?.entities)
117
+ await ctx.editMessageText(answered);
118
+ else {
119
+ // An entity Telegram balks at the second time round — a mention it no
120
+ // longer allows — shouldn't cost the footer as well.
121
+ await ctx.editMessageText(answered, { entities: message.entities })
122
+ .catch(() => ctx.editMessageText(answered));
123
+ }
124
+ }
125
+ catch {
126
+ // Edit may fail if the message changed shape. Losing the footer is
127
+ // cosmetic; leaving a live keyboard on a resolved question is not, so
128
+ // retry the keyboard removal on its own.
129
+ try {
130
+ await ctx.editMessageReplyMarkup();
131
+ }
132
+ catch {
133
+ // Non-fatal — a second tap is rejected by resolvePendingQuestion anyway.
134
+ }
135
+ }
136
+ // The answer also goes out as its own message. See buildAnswerConfirmation:
137
+ // an edit is silent, anonymous, and buried at the bottom of a long question,
138
+ // so the choice never really lands in the conversation. Replying to the
139
+ // question keeps the two linked even when several questions are open at once.
140
+ try {
141
+ await ctx.reply(buildAnswerConfirmation(answerText, {
142
+ isPrivate: ctx.chat?.type === 'private',
143
+ who: ctx.from?.first_name,
144
+ }), message?.message_id === undefined
145
+ ? undefined
146
+ : { reply_parameters: { message_id: message.message_id, allow_sending_without_reply: true } });
147
+ }
148
+ catch {
149
+ // Non-fatal — the in-place footer above already recorded the choice.
150
+ }
151
+ }
152
+ function getSequentializeKey(ctx) {
153
+ const chatId = ctx.chat?.id;
154
+ if (!chatId)
155
+ return undefined;
156
+ const msg = (ctx.message ?? ctx.callbackQuery?.message);
157
+ const threadId = msg?.is_topic_message ? msg.message_thread_id : undefined;
158
+ return buildSessionKey(chatId, threadId);
159
+ }
160
+ /**
161
+ * `botInfo` is what the startup token check already fetched (see
162
+ * startup/verify-token.ts). Handing it in makes `bot.init()` a no-op instead
163
+ * of a second getMe.
164
+ */
165
+ export async function createBot(botInfo) {
166
+ // Start the IPC server for hook callbacks and the standalone MCP subprocess.
167
+ // Awaited so the bound port is known before anything else tries to spawn a
168
+ // subprocess that needs to reach us.
169
+ await startIpcServer();
170
+ // Support an HTTP or HTTPS proxy for the Telegram API (useful in restricted networks)
171
+ const proxyUrl = telegramProxyUrl();
172
+ if (proxyUrl) {
173
+ // A proxy URL can carry a user and password.
174
+ console.log(`[Bot] Using proxy: ${redactSecrets(proxyUrl)}`);
175
+ }
176
+ const bot = new Bot(config.TELEGRAM_BOT_TOKEN, {
177
+ botInfo,
178
+ client: telegramClientOptions(),
179
+ });
180
+ // Note which messages are ForceReply prompts, so a reply answering one still
181
+ // reaches the handlers in a group that otherwise requires an @mention.
182
+ trackForceReplyPrompts(bot);
183
+ // Telegram says nothing when a thread is deleted, but a send into one fails:
184
+ // take that as the news, and end the session the thread had.
185
+ watchForDeletedThreads(bot);
186
+ // And end PTY claudes left idle, a thread deleted by hand among them.
187
+ startPtyIdleReaper();
188
+ // Auto-retry on transient network errors (ECONNRESET, socket hang up, etc.)
189
+ // Also handles 429 rate limits by respecting Telegram's retry_after
190
+ bot.api.config.use(autoRetry({
191
+ maxRetryAttempts: 5,
192
+ maxDelaySeconds: 60, // Cap retry delay at 60 seconds (will retry sooner rather than wait 900s)
193
+ rethrowInternalServerErrors: false, // Retry on 5xx errors
194
+ }));
195
+ // Register command menu for autocomplete (non-blocking). The list lives in
196
+ // command-catalog.ts, where /commands <search> and the typo fallback read it.
197
+ const commandList = buildCommandMenu();
198
+ setCommandCatalog(commandList);
199
+ bot.api.setMyCommands(commandList).then(() => {
200
+ console.log('📋 Command menu registered');
201
+ }).catch((err) => {
202
+ console.warn('⚠️ Failed to register commands:', err.message);
203
+ });
204
+ // Before everything else, so /botrebuild's "when idle" sees an update from
205
+ // the moment it arrives until its reply has gone out.
206
+ bot.use(countUpdatesInFlight);
207
+ // Apply auth middleware to all updates
208
+ bot.use(authMiddleware);
209
+ // Note who named each private-chat thread, from the notices passing by, so a
210
+ // name the user chose is never replaced by the session topic.
211
+ initThreadTitles(bot);
212
+ // A project bot made by /newbot starts without threads, which only its owner
213
+ // can turn on: tell them how, with the first message they send it.
214
+ initThreadsSetup(bot);
215
+ // Files sent together arrive one message each: gather them into one. Ahead of
216
+ // the mention gate, which reads the caption only one of them carries.
217
+ bot.use(createAlbumMiddleware());
218
+ // In groups, ignore messages that aren't addressed to the bot, so people can
219
+ // talk to each other without triggering a turn. Runs before the command
220
+ // handlers below because they'd otherwise answer a `/info@other_bot`
221
+ // aimed at a different bot in the same group.
222
+ bot.use(groupMentionMiddleware);
223
+ // Of the people an allow-listed group lets in, which ones may actually drive
224
+ // the agent. Runs after the mention gate so a spectator talking to the humans
225
+ // is never answered, and before every command handler below.
226
+ //
227
+ // Handles are learned upstream in authMiddleware, which records everyone the
228
+ // group sees — spectators included — so `/allow @someone` resolves for people
229
+ // who have only ever talked to the other humans.
230
+ bot.use(groupRoleMiddleware);
231
+ // A message answering telecoder_request_secret comes out of the stream
232
+ // here, deleted from the chat before anything below can batch it, queue it
233
+ // or hand it to the agent. The turn that asked is blocked on the answer, so
234
+ // the answer can't wait in line behind it either. Commands pass, so /cancel
235
+ // still works.
236
+ bot.use(captureSecretMessages);
237
+ // A message sent while telecoder_ask_user waits on a tap is the answer in
238
+ // the user's own words, and leaves the stream here for the same reason. So
239
+ // does one sent at a Claude Code dialog that takes text.
240
+ bot.use(captureTypedAnswers);
241
+ // Register through `cmd` rather than `bot.command` directly so the set of
242
+ // names TeleCoder claims stays discoverable at runtime. Registration order
243
+ // and placement relative to sequentialize are unchanged — `cmd` calls
244
+ // `bot.command` immediately. /projectcommands uses the recorded names to
245
+ // report which native Claude Code commands this bot shadows.
246
+ const cmd = (name, handler, opts) => {
247
+ registerBotCommandName(name, opts?.forwardsToAgent);
248
+ bot.command(name, handler);
249
+ };
250
+ // These commands fire BEFORE sequentialize so they bypass per-chat ordering.
251
+ // This lets them interrupt, inspect, or restart even when a query is hung.
252
+ cmd('cancel', handleCancel);
253
+ cmd('info', withRunningNote(handleInfo));
254
+ cmd('botversion', withRunningNote(handleBotVersion));
255
+ // Lifecycle and transport are admin-only: they act on every session in the
256
+ // bot, not just the caller's.
257
+ cmd('botrestart', adminOnly(handleBotRestart));
258
+ cmd('botrebuild', adminOnly(handleBotRebuild));
259
+ // Access control is admin-only and bypasses sequentialize: a stranger
260
+ // typically turns up mid-turn, and an admin should be able to wave them in
261
+ // without waiting for whatever the group is already running to finish.
262
+ cmd('allow', adminOnly(handleAllow));
263
+ cmd('deny', adminOnly(handleDeny));
264
+ cmd('users', adminOnly(handleUsers));
265
+ cmd('btw', withRunningNote(handleBtw)); // Side question — must bypass queue to work mid-task
266
+ cmd('spinoff', handleSpinoffCommand); // Splits a task off into a new thread — bypasses the queue so it works mid-task
267
+ // Deletes the thread it's sent in, stopping its turn — bypasses the queue so a
268
+ // busy thread can still be deleted. Admin-only: in a group it takes everyone's
269
+ // messages with it.
270
+ cmd('threaddelete', adminOnly(handleThreadDelete));
271
+ // Deletes other threads, never the one it's sent in, and leaves alone any
272
+ // with a turn or messages going — so it has no reason to wait for this
273
+ // thread's turn. Admin-only, like /threaddelete. /threadkeep only flips a mark.
274
+ cmd('threadcleanup', adminOnly(handleThreadCleanup));
275
+ cmd('threadkeep', handleThreadKeep);
276
+ // Sets an idea aside for after the turn, so it can't wait behind that turn. And
277
+ // with nothing running, it's the one message that doesn't start one.
278
+ cmd('later', withRunningNote(handleLater));
279
+ // Stops the turn and sends a message in its place, so it can't wait behind that turn.
280
+ cmd('steer', handleSteer);
281
+ // Read-only, with nothing a running turn could be disturbed by, so they answer
282
+ // mid-turn rather than after it: a fixed list, a look at the bot process, a
283
+ // re-read of the transcript, and one that asks a probe of its own rather
284
+ // than the live session. Anything that changes the session
285
+ // or starts a turn stays behind sequentialize below.
286
+ cmd('commands', withRunningNote(handleCommands));
287
+ cmd('botstatus', withRunningNote(handleBotStatus));
288
+ cmd('history', withRunningNote(handleHistory));
289
+ cmd('projectcommands', handleProjectCommands);
290
+ cmd('tasks', handleTasks); // Read-only; must bypass queue so it works mid-stream
291
+ cmd('bashes', handleTasks); // Claude Code's alias of /tasks
292
+ // Claude Code's Ctrl+B: moves what the turn is waiting on to the background, so it is for mid-turn only.
293
+ cmd('ctrlb', handleCtrlB);
294
+ // Read-only probe + a peek at the live TUI panel; bypasses the queue so it
295
+ // answers mid-turn. Three names because Claude Code has all three: /cost
296
+ // and /stats are its aliases of /usage.
297
+ cmd('usage', withRunningNote(handleUsage));
298
+ cmd('cost', withRunningNote(handleUsage));
299
+ cmd('stats', withRunningNote(handleUsage));
300
+ cmd('shells', withRunningNote(handleShells)); // Lists/kills OS-level bg processes; must bypass queue to rescue hung sessions
301
+ cmd('members', handleMembers);
302
+ // /resend exists for the "I think a reply went missing" scenario, which by
303
+ // definition includes hung or sluggish turns — gating it on sequentialize
304
+ // would queue it behind the very turn the user wants to inspect.
305
+ cmd('resend', handleResend);
306
+ // /tree and /prompts are read-only until a button is tapped, so they answer
307
+ // mid-turn — "what did I just ask?" comes up while a long turn runs — and the
308
+ // buttons that switch conversations refuse while a reply is running.
309
+ cmd('tree', handleTreeCommand);
310
+ cmd('prompts', withRunningNote(handlePromptsCommand));
311
+ // Display preferences: each only flips a stored setting that a turn reads
312
+ // when it starts, so changing one mid-turn applies from the next turn and
313
+ // has no reason to wait for this one. Their menu buttons likewise.
314
+ cmd('footer', handleFooter);
315
+ cmd('verbosity', handleVerbosity);
316
+ cmd('suggestions', handleSuggestions);
317
+ bot.callbackQuery(/^footer:/, handleFooterCallback);
318
+ bot.callbackQuery(/^verbosity:/, handleVerbosityCallback);
319
+ bot.callbackQuery(/^sugg:/, handleSuggestionsCallback);
320
+ // The same goes for the permission mode, which a turn applies as it starts,
321
+ // and for the bot's and the thread's names.
322
+ // /mode was the streaming toggle's name until this landed, and was kept as
323
+ // an alias for exactly as long as nothing better wanted it. Permission mode
324
+ // is what people were always going to mean by it.
325
+ cmd('mode', adminOnly(handlePermissionMode));
326
+ cmd('botname', adminOnly(handleBotName));
327
+ cmd('topic', handleTopic);
328
+ bot.callbackQuery(/^permmode:/, adminOnly(handlePermissionModeCallback));
329
+ // An auto-approve window matters most mid-turn: that's when the prompts it
330
+ // answers are turning up, and closing one can't wait for the turn either.
331
+ // Admins *and* approvers: opening a window is a decision about prompts, not
332
+ // a power over the bot, so it sits with the people who answer them.
333
+ cmd('autoapprove', adminOrApproverOnly(handleAutoApprove));
334
+ cmd('gate', adminOnly(handleGate));
335
+ // Nothing here touches the session: a welcome text, a file sent from disk,
336
+ // and a new bot, which is a process of its own.
337
+ cmd('start', handleStart);
338
+ cmd('file', handleFile);
339
+ // Creating a bot adds a process to the launcher and a token to instances.json.
340
+ cmd('newbot', adminOnly(handleNewBot));
341
+ // Loop commands bypass sequentialize so they remain responsive even
342
+ // when a loop's turn is already running (the cap-enforcing create, the
343
+ // list and its stop buttons all need to work mid-stream). /proactive is
344
+ // Claude Code's alias of /loop.
345
+ cmd('loop', handleLoop);
346
+ cmd('proactive', handleLoop);
347
+ cmd('loops', handleLoops);
348
+ bot.callbackQuery(/^loops:/, handleLoopsCallback);
349
+ // /tasks inline-keyboard buttons (view/back/refresh) also need to bypass
350
+ // sequentialize so they're responsive while a stream is active.
351
+ bot.callbackQuery(/^tasks:/, handleTasksCallback);
352
+ // /shells kill buttons must also bypass sequentialize — the whole point is to
353
+ // rescue a session whose current turn is hung waiting on a bg shell.
354
+ bot.callbackQuery(/^shells:/, handleShellsCallback);
355
+ // "Did you mean" buttons under a mistyped command. Before sequentialize: the
356
+ // tap only re-sends the message, which then waits its turn like any other.
357
+ bot.callbackQuery(/^cmdfix:/, handleCommandFixCallback);
358
+ bot.callbackQuery(/^threaddelete:/, adminOnly(handleThreadDeleteCallback));
359
+ bot.callbackQuery(/^threadcleanup:/, adminOnly(handleThreadCleanupCallback));
360
+ // telecoder_ask_user button taps MUST bypass sequentialize: the agent
361
+ // query is mid-flight and waiting on this exact tap to complete the tool
362
+ // call. If the callback got queued, it'd deadlock behind the query that's
363
+ // waiting for it.
364
+ bot.callbackQuery(/^q:/, handleAskUserCallback);
365
+ // A multi-question form's option, jump and Submit buttons, for the same reason.
366
+ bot.callbackQuery(/^qf:/, handleAskUserFormCallback);
367
+ // The Cancel button under a secret request, for the same reason.
368
+ bot.callbackQuery(/^secret:/, handleSecretCallback);
369
+ // /branch callbacks bypass sequentialize too: the user often taps Branch on a
370
+ // past message while a turn is running. Picker UI is non-destructive (it
371
+ // just shows another message), and accept/decline operate on file state,
372
+ // not the live agent, so they don't need to wait in line.
373
+ bot.callbackQuery(/^branch:/, handleBranchCallback);
374
+ // /tree's buttons likewise: opening a point only redraws the message, and
375
+ // carrying on a branch or branching from a point checks for a running reply
376
+ // itself, so a tap mid-turn gets an answer instead of waiting in line.
377
+ bot.callbackQuery(/^tree:/, handleTreeCallback);
378
+ // /prompts' buttons for the same reasons: opening a prompt only redraws the
379
+ // message, and branching from one checks for a running reply itself.
380
+ bot.callbackQuery(/^prompts:/, handlePromptsCallback);
381
+ // "Take back" and "Ask me after" on a queued message: the turn it's waiting
382
+ // behind is exactly what these have to get past.
383
+ bot.callbackQuery(/^queued:/, handleQueuedCallback);
384
+ // An edit to a message that's still waiting has to land before the wait ends,
385
+ // so it can't wait in line itself.
386
+ bot.on('edited_message', handleEditedMessage);
387
+ initParkedMessages(bot);
388
+ initCommandFallback(bot);
389
+ setQueuedDiverters({ btw: askBtw, branch: branchPastRunningTurnIntoThread });
390
+ // Menu buttons for /botrestart and /botrebuild must bypass sequentialize
391
+ // for the same reason their parent commands do: users tap these precisely
392
+ // when the bot is hung, so the callback can't be queued behind the stuck
393
+ // request.
394
+ // Access cards: same reasoning as the commands above — the card lands while
395
+ // a turn is running, and it is the fastest way to answer it.
396
+ bot.callbackQuery(/^access:/, adminOnly(handleAccessCallback));
397
+ bot.callbackQuery(/^botrestart:/, adminOnly(handleBotRestartCallback));
398
+ bot.callbackQuery(/^botrebuild:/, adminOnly(handleBotRebuildCallback));
399
+ // Batch consecutive text messages BEFORE sequentialize.
400
+ // When Telegram splits a long paste into multiple messages, this combines
401
+ // them into a single prompt. Must run before sequentialize because that
402
+ // middleware serializes same-session updates (preventing concurrent batching).
403
+ bot.use(createBatchMiddleware());
404
+ // Sequentialize: same-chat updates are processed in order.
405
+ // This runs AFTER /cancel so cancel bypasses it.
406
+ //
407
+ // It's also where a message waits while a turn runs, so the two either side
408
+ // of it tell the sender so and let them take the message back. They have to
409
+ // stay wrapped around it: see middleware/queued-messages.ts.
410
+ bot.use(trackQueuedMessage);
411
+ bot.use(sequentialize(getSequentializeKey));
412
+ bot.use(holdQueuedMessage);
413
+ // Bot command handlers (sequentialized per chat)
414
+ //
415
+ // Where the bot has a command of Claude Code's, it answers to Claude Code's
416
+ // aliases of it too, so that /new does what /clear does rather than
417
+ // reaching Claude Code past the bot's bookkeeping.
418
+ cmd('clear', handleClear);
419
+ cmd('reset', handleClear);
420
+ cmd('new', handleClear);
421
+ // Admin-only now that a group can hold contributors: repointing the bot
422
+ // moves everyone's session, and /terminal and /gate reach the
423
+ // guardrails rather than the conversation.
424
+ cmd('dir', adminOnly(handleDir));
425
+ // /compact is a native Claude Code slash command, not a bot command — route it
426
+ // through the normal message pipeline (handleMessage), which forwards it to
427
+ // the active provider; the pty runs the real compaction and reports the token
428
+ // reduction. Registering it here (rather than relying on fall-through to the
429
+ // text handler) makes dispatch explicit and lets grammY match the group-chat
430
+ // `/compact@BotName` form.
431
+ cmd('compact', handleMessage, { forwardsToAgent: true });
432
+ // /context is Claude Code's own, routed the same way: the chat's claude
433
+ // reports what fills its context window, MCP tools and skills included,
434
+ // and the reply is the markdown copy of that report it logs (see
435
+ // commandReplyIn). Like any prompt, it waits for a running turn.
436
+ cmd('context', handleMessage, { forwardsToAgent: true });
437
+ // /rewind is Claude Code's own as well. Its two screens, the prompt to go
438
+ // back to and what to restore, come to the chat through the dialog relay,
439
+ // and rewind.ts reports what was restored, since the command itself prints
440
+ // nothing.
441
+ cmd('rewind', handleMessage, { forwardsToAgent: true });
442
+ cmd('undo', handleMessage, { forwardsToAgent: true });
443
+ cmd('checkpoint', handleMessage, { forwardsToAgent: true });
444
+ // /cd is Claude Code's too: it moves the session to another directory, and
445
+ // the bot follows through the CwdChanged hook (session-move.ts). Registered
446
+ // so the typo fallback, which would take it for /cc, lets it through.
447
+ cmd('cd', handleMessage, { forwardsToAgent: true });
448
+ // /cc <command> is the way past a bot command to Claude Code's own of the
449
+ // same name: `/cc model`, `/cc usage`. What goes to the agent is the
450
+ // command named, so it counts as forwarded, not as a command of the bot's.
451
+ cmd('cc', handleNativeCommand, { forwardsToAgent: true });
452
+ cmd('botupdate', adminOnly(handleBotUpdate));
453
+ cmd('model', handleModelCommand);
454
+ cmd('effort', handleEffort);
455
+ if (config.CCR_ENABLED) {
456
+ cmd('ccr', adminOnly(handleCcrCommand));
457
+ }
458
+ // Session resume commands
459
+ cmd('resume', handleResume);
460
+ cmd('continue', handleResume); // Claude Code's alias of /resume
461
+ // /branch copies the conversation as it stands; /branchaccept and /branchdecline are the
462
+ // slash-command equivalents of the target-side inline buttons.
463
+ cmd('branch', handleBranchCommand);
464
+ cmd('branchaccept', handleBranchAcceptCommand);
465
+ cmd('branchdecline', handleBranchDeclineCommand);
466
+ // The command line that carries a session on in a terminal. Not /teleport:
467
+ // that name is Claude Code's own (send a session to the cloud, or resume one
468
+ // from claude.ai), and a bot command of that name would keep it out of reach.
469
+ cmd('terminal', adminOnly(handleTerminal));
470
+ // Callback query handler for inline keyboards
471
+ bot.on('callback_query:data', async (ctx) => {
472
+ const data = ctx.callbackQuery.data;
473
+ if (data.startsWith('resume:')) {
474
+ await handleResumeCallback(ctx);
475
+ }
476
+ else if (data.startsWith('provider_switch:')) {
477
+ await adminOnly(handleProviderSwitchCallback)(ctx);
478
+ }
479
+ else if (data.startsWith('pscope:')) {
480
+ await handlePrefsScopeCallback(ctx);
481
+ }
482
+ else if (data.startsWith('model:')) {
483
+ await handleModelCallback(ctx);
484
+ }
485
+ else if (data.startsWith('dir:')) {
486
+ await adminOnly(handleDirCallback)(ctx);
487
+ }
488
+ else if (data.startsWith('restart:')) {
489
+ await handleRestartCallback(ctx);
490
+ }
491
+ else if (data.startsWith('startup:')) {
492
+ await handleStartupCallback(ctx);
493
+ }
494
+ else if (data.startsWith('botupdate:')) {
495
+ await adminOnly(handleBotUpdateCallback)(ctx);
496
+ }
497
+ else if (data.startsWith('effort:')) {
498
+ await handleEffortCallback(ctx);
499
+ }
500
+ else if (data.startsWith('sgt:')) {
501
+ await handleSuggestionTapCallback(ctx);
502
+ }
503
+ else {
504
+ // Nothing answers to this button: it is on a message from a build that
505
+ // named its buttons differently. Say so rather than leave the tap spinning.
506
+ await ctx.answerCallbackQuery({ text: STALE_BUTTON_NOTE }).catch(() => { });
507
+ }
508
+ // Note: `tasks:` callback queries are handled by the pre-sequentialize
509
+ // bot.callbackQuery handler above so they remain responsive mid-stream.
510
+ });
511
+ // Resolve pending telecoder_poll_user MCP calls on first vote. Must be
512
+ // registered before the catch-all paths so the poll_answer update reaches
513
+ // us; non-anonymous polls only fire poll_answer for non-anonymous voting,
514
+ // which is required for the resolve-on-first-vote semantics to work.
515
+ bot.on('poll_answer', async (ctx) => {
516
+ const pa = ctx.pollAnswer;
517
+ if (!pa)
518
+ return;
519
+ const resolved = resolvePendingPoll(pa.poll_id, pa.option_ids);
520
+ if (!resolved) {
521
+ // Not a TeleCoder-tracked poll — ignore (could be a user-created poll
522
+ // in the same chat).
523
+ }
524
+ });
525
+ // The bot a /newbot button created. The handler checks for an admin itself,
526
+ // and quietly: anyone with a t.me/newbot link can create one.
527
+ bot.on('message:managed_bot_created', handleManagedBotCreated);
528
+ // Files sent together, gathered by the album collector, whatever kind its
529
+ // first part is: ahead of the handlers that would take that part alone.
530
+ bot.filter((ctx) => albumParts(ctx.message) !== undefined, handleAlbum);
531
+ // Handle voice messages
532
+ bot.on('message:voice', handleVoice);
533
+ // Audio files (music, recordings — not voice notes) have no ingestion path;
534
+ // the handler says so rather than dropping them.
535
+ bot.on('message:audio', handleUnsupportedAudio);
536
+ // Handle images
537
+ bot.on('message:photo', handlePhoto);
538
+ // Handle documents: route by MIME type
539
+ // image/* → image vision
540
+ // audio/*, video/* → explained as unsupported
541
+ // anything else → read as text/PDF/etc.
542
+ bot.on('message:document', async (ctx) => {
543
+ const doc = ctx.message?.document;
544
+ const mime = doc?.mime_type ?? '';
545
+ if (mime.startsWith('image/')) {
546
+ await handleImageDocument(ctx);
547
+ return;
548
+ }
549
+ // Audio and video documents have no ingestion path, but say so rather than
550
+ // dropping them. This used to be a bare `return`: an mp3 sent as a file
551
+ // produced no reply, no log line, nothing — indistinguishable from the bot
552
+ // being down. Everything else (PDF, text, code, CSV, …) goes to the
553
+ // document reader.
554
+ if (mime.startsWith('video/') || mime.startsWith('audio/')) {
555
+ await handleUnsupportedMediaDocument(ctx);
556
+ return;
557
+ }
558
+ await handleTextDocument(ctx);
559
+ });
560
+ // Video, round video notes and GIFs — no handler matched these at all
561
+ // before, so they fell through the whole chain silently.
562
+ bot.on('message:video', handleUnsupportedVideo);
563
+ bot.on('message:video_note', handleUnsupportedVideo);
564
+ bot.on('message:animation', handleUnsupportedVideo);
565
+ // Handle regular text messages
566
+ bot.on('message:text', handleMessage);
567
+ // Error handler
568
+ bot.catch((err) => {
569
+ console.error('Bot error:', err);
570
+ });
571
+ return bot;
572
+ }
573
+ //# sourceMappingURL=bot.js.map