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,121 @@
1
+ import { EntityText } from '../../telegram/entities.js';
2
+ import { replyFormatted } from '../../telegram/send.js';
3
+ import { isDuplicate, markProcessed } from '../../telegram/deduplication.js';
4
+ import { isStaleMessage } from '../middleware/stale-filter.js';
5
+ /**
6
+ * Telegram caps what a bot may *download* at 20MB. `getFile` itself fails with
7
+ * "file is too big" past that, so no bot-side setting can raise it — the guard
8
+ * exists to turn an opaque Telegram 400 into an explanation.
9
+ *
10
+ * Not to be confused with the 50MB *send* limit in mcp-bridge.ts: outbound and
11
+ * inbound are separate budgets, and inbound is the tighter one. Only a
12
+ * self-hosted Bot API server in --local mode lifts this.
13
+ */
14
+ export const TELEGRAM_DOWNLOAD_LIMIT_MB = 20;
15
+ export function exceedsDownloadLimit(fileSizeBytes) {
16
+ return (fileSizeBytes ?? 0) / (1024 * 1024) > TELEGRAM_DOWNLOAD_LIMIT_MB;
17
+ }
18
+ /** ` (172.0MB)` — or empty when Telegram omitted the size. */
19
+ function sizeSuffix(fileSizeBytes) {
20
+ const mb = (fileSizeBytes ?? 0) / (1024 * 1024);
21
+ return mb > 0 ? ` (${mb.toFixed(1)}MB)` : '';
22
+ }
23
+ /**
24
+ * Explain that a file is past Telegram's download ceiling. Every inbound media
25
+ * path should call this instead of letting `getFile` throw, so the user learns
26
+ * the limit is Telegram's rather than a bug here.
27
+ */
28
+ export async function replyTooLargeToFetch(ctx, kindTitle, fileSizeBytes) {
29
+ // Log the answer, not just the drops. The original bug was invisible in the
30
+ // logs precisely because nothing recorded a decision, and "user reports
31
+ // nothing arrived" is unfalsifiable without a line to point at.
32
+ console.log(`[Media] ${kindTitle} over the ${TELEGRAM_DOWNLOAD_LIMIT_MB}MB fetch limit `
33
+ + `(${((fileSizeBytes ?? 0) / (1024 * 1024)).toFixed(1)}MB) — explained to user`);
34
+ await replyFormatted(ctx, new EntityText()
35
+ .add('❌ ').bold(`${kindTitle} too large`).add(sizeSuffix(fileSizeBytes)).add('\n\n')
36
+ .add(`Telegram caps bot downloads at ${TELEGRAM_DOWNLOAD_LIMIT_MB}MB, so I can't fetch this one `
37
+ + 'no matter how the bot is configured.\n\n'
38
+ + 'Re-encode it smaller, or — if the file is already on this machine — send me its path instead.')
39
+ .build());
40
+ }
41
+ /**
42
+ * A bare audio upload. Transcription is opt-in via /transcribe, so rather than
43
+ * dropping the file we say so; silence here read as "the bot is broken".
44
+ */
45
+ export async function replyBareAudio(ctx, fileSizeBytes) {
46
+ if (exceedsDownloadLimit(fileSizeBytes)) {
47
+ await replyTooLargeToFetch(ctx, 'Audio file', fileSizeBytes);
48
+ return;
49
+ }
50
+ console.log('[Media] Bare audio upload — pointed user at /transcribe');
51
+ await replyFormatted(ctx, new EntityText()
52
+ .add('🎵 ').bold('Audio received').add(sizeSuffix(fileSizeBytes)).add('\n\n')
53
+ .add("I don't read audio files on their own. To transcribe this, run /transcribe "
54
+ + 'and reply to the prompt with the same file.')
55
+ .build());
56
+ }
57
+ /**
58
+ * Video, video notes and GIFs have no ingestion path at all. Previously these
59
+ * updates matched no handler whatsoever and vanished without a trace.
60
+ */
61
+ export async function replyUnsupportedVideo(ctx, fileSizeBytes) {
62
+ if (exceedsDownloadLimit(fileSizeBytes)) {
63
+ await replyTooLargeToFetch(ctx, 'Video', fileSizeBytes);
64
+ return;
65
+ }
66
+ console.log('[Media] Video upload — unsupported, told user');
67
+ await replyFormatted(ctx, new EntityText()
68
+ .add('🎬 ').bold("Video isn't supported").add(sizeSuffix(fileSizeBytes)).add('\n\n')
69
+ .add("I can't read video files. Extract the audio and send that via /transcribe, "
70
+ + "or point me at the file's path if it's already on this machine.")
71
+ .build());
72
+ }
73
+ /**
74
+ * Stale/duplicate gate, shared by every path that now *answers* instead of
75
+ * returning silently. Skipping it would mean a restart replying to each video
76
+ * and mp3 sent while the bot was down — noisier than the bug being fixed.
77
+ *
78
+ * Claims the message id on success, so callers must not delegate to another
79
+ * handler that runs its own dedup afterwards.
80
+ */
81
+ function claimsMediaMessage(ctx, label) {
82
+ const messageId = ctx.message?.message_id;
83
+ const messageDate = ctx.message?.date;
84
+ if (!messageId || !messageDate)
85
+ return false;
86
+ if (isStaleMessage(messageDate)) {
87
+ console.log(`[Media] Ignoring stale ${label} ${messageId}`);
88
+ return false;
89
+ }
90
+ if (isDuplicate(messageId)) {
91
+ console.log(`[Media] Ignoring duplicate ${label} ${messageId}`);
92
+ return false;
93
+ }
94
+ markProcessed(messageId);
95
+ return true;
96
+ }
97
+ /**
98
+ * Entry point for `message:video` / `message:video_note` / `message:animation`,
99
+ * none of which had a handler before.
100
+ */
101
+ export async function handleUnsupportedVideo(ctx) {
102
+ if (!claimsMediaMessage(ctx, 'video'))
103
+ return;
104
+ const media = ctx.message?.video ?? ctx.message?.video_note ?? ctx.message?.animation;
105
+ await replyUnsupportedVideo(ctx, media?.file_size);
106
+ }
107
+ /**
108
+ * Entry point for audio/video sent as a *document* — the path a 172MB mp3 takes
109
+ * when Telegram declines to treat it as playable audio.
110
+ */
111
+ export async function handleUnsupportedMediaDocument(ctx) {
112
+ const doc = ctx.message?.document;
113
+ if (!doc || !claimsMediaMessage(ctx, 'media document'))
114
+ return;
115
+ if (doc.mime_type?.startsWith('video/')) {
116
+ await replyUnsupportedVideo(ctx, doc.file_size);
117
+ return;
118
+ }
119
+ await replyBareAudio(ctx, doc.file_size);
120
+ }
121
+ //# sourceMappingURL=media-fallback.js.map
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Handlers for replies to the bot's ForceReply prompts — the flows where a
3
+ * command posts a question and the user's *next* message is the answer
4
+ * (/project path, /file path, /telegraph path, /plan|/explore|/loop task).
5
+ *
6
+ * `handleMessage` routes here by matching the prompt text it is replying to.
7
+ */
8
+ import * as fs from 'fs';
9
+ import * as path from 'path';
10
+ import { sendToAgent, sendLoopToAgent, clearConversation } from '../../../providers/provider-router.js';
11
+ import { sessionManager } from '../../../claude/session-manager.js';
12
+ import { messageSender } from '../../../telegram/message-sender.js';
13
+ import { EntityText } from '../../../telegram/entities.js';
14
+ import { replyFormatted } from '../../../telegram/send.js';
15
+ import { createTelegraphFromFile } from '../../../telegram/telegraph.js';
16
+ import { maybeSendVoiceReply } from '../../../tts/voice-reply.js';
17
+ import { projectStatusSuffix, resumeCommandMessage, clearTopicAndRefreshBotName, } from '../command.handler.js';
18
+ import { fireAutoTopic, requireSession, resolveUserFilePath, runQueuedTurn } from './shared.js';
19
+ import { refuseFilePublish } from '../../file-access.js';
20
+ import { progressCallbacks, toolCallbacks, withStreamingTurn } from '../../../telegram/streaming-turn.js';
21
+ import { closeTurn, relayCatchUpIfMissed } from './turn-notify.js';
22
+ // Handle reply to project ForceReply prompt
23
+ export async function handleProjectReply(ctx, sessionKey, projectPath) {
24
+ let resolvedPath = projectPath.trim();
25
+ // Handle ~ expansion
26
+ if (resolvedPath.startsWith('~')) {
27
+ resolvedPath = path.join(process.env.HOME || '', resolvedPath.slice(1));
28
+ }
29
+ // Resolve to absolute path. Manual path entry is treated as an explicit
30
+ // user choice and may point anywhere on disk (mirrors typing `/project <abs>`).
31
+ resolvedPath = path.resolve(resolvedPath);
32
+ // Check if exists
33
+ if (!fs.existsSync(resolvedPath)) {
34
+ await replyFormatted(ctx, new EntityText()
35
+ .add('❌ Path not found: ').code(resolvedPath).add('\n\nPlease check the path and try again.')
36
+ .build());
37
+ return;
38
+ }
39
+ // Check if directory
40
+ if (!fs.statSync(resolvedPath).isDirectory()) {
41
+ await replyFormatted(ctx, new EntityText().add('❌ Not a directory: ').code(resolvedPath).build());
42
+ return;
43
+ }
44
+ // Set the project
45
+ sessionManager.setWorkingDirectory(sessionKey, resolvedPath);
46
+ clearConversation(sessionKey);
47
+ await clearTopicAndRefreshBotName(ctx, sessionKey);
48
+ const projectName = path.basename(resolvedPath);
49
+ await replyFormatted(ctx, new EntityText()
50
+ .add('✅ Project set: ').bold(projectName).newline(2)
51
+ .code(resolvedPath).newline(2)
52
+ .add('You can now chat with Claude about this project!')
53
+ .append(projectStatusSuffix(sessionKey))
54
+ .build());
55
+ const s = sessionManager.getSession(sessionKey);
56
+ if (s?.claudeSessionId) {
57
+ await replyFormatted(ctx, resumeCommandMessage(s.claudeSessionId));
58
+ }
59
+ }
60
+ // Handle reply to file ForceReply prompt
61
+ export async function handleFileReply(ctx, sessionKey, filePath) {
62
+ const fullPath = await resolveUserFilePath(ctx, sessionKey, filePath);
63
+ if (!fullPath)
64
+ return;
65
+ const success = await messageSender.sendDocument(ctx, fullPath, `📎 ${path.basename(fullPath)}`);
66
+ if (!success) {
67
+ await ctx.reply('❌ Failed to send file. It may be too large (>50MB) or inaccessible.');
68
+ }
69
+ }
70
+ // Handle reply to plan/explore/loop ForceReply prompts
71
+ export async function handleAgentReply(ctx, sessionKey, input, mode) {
72
+ if (!await requireSession(ctx, sessionKey))
73
+ return;
74
+ const trimmedInput = input.trim();
75
+ if (!trimmedInput) {
76
+ await ctx.reply('❌ Please provide a description.');
77
+ return;
78
+ }
79
+ fireAutoTopic(ctx, sessionKey, trimmedInput);
80
+ await runQueuedTurn(ctx, sessionKey, trimmedInput, `AgentReply:${mode}`, async () => {
81
+ const startTime = Date.now();
82
+ await withStreamingTurn(ctx, sessionKey, trimmedInput, async (abortController) => {
83
+ let response;
84
+ if (mode === 'loop') {
85
+ response = await sendLoopToAgent(sessionKey, trimmedInput, {
86
+ ...progressCallbacks(ctx),
87
+ abortController,
88
+ telegramCtx: ctx,
89
+ });
90
+ }
91
+ else {
92
+ response = await sendToAgent(sessionKey, trimmedInput, {
93
+ ...progressCallbacks(ctx),
94
+ ...toolCallbacks(ctx, sessionKey),
95
+ abortController,
96
+ command: mode,
97
+ telegramCtx: ctx,
98
+ });
99
+ }
100
+ await messageSender.finishStreaming(ctx, response.text, { nextPromptSuggestion: response.nextPromptSuggestion });
101
+ await relayCatchUpIfMissed(ctx, sessionKey, response.text || '');
102
+ await maybeSendVoiceReply(ctx, response.text);
103
+ // Completion notification for long tasks
104
+ await messageSender.sendCompletionNotification(ctx, Date.now() - startTime);
105
+ await closeTurn(ctx, sessionKey, response, trimmedInput);
106
+ });
107
+ });
108
+ }
109
+ // Handle reply to telegraph ForceReply prompt
110
+ export async function handleTelegraphReply(ctx, sessionKey, filePath) {
111
+ if (await refuseFilePublish(ctx))
112
+ return;
113
+ const fullPath = await resolveUserFilePath(ctx, sessionKey, filePath);
114
+ if (!fullPath)
115
+ return;
116
+ const ext = path.extname(fullPath).toLowerCase();
117
+ if (ext !== '.md' && ext !== '.markdown') {
118
+ await ctx.reply('⚠️ Telegraph works best with Markdown files (.md)');
119
+ }
120
+ await ctx.reply('📤 Creating Telegraph page...');
121
+ const pageUrl = await createTelegraphFromFile(fullPath);
122
+ if (pageUrl) {
123
+ const fileName = path.basename(fullPath);
124
+ await replyFormatted(ctx, new EntityText()
125
+ .add('📄 ').bold(fileName).newline(2)
126
+ .link('Open in Instant View', pageUrl)
127
+ .build());
128
+ }
129
+ else {
130
+ await ctx.reply('❌ Failed to create Telegraph page.');
131
+ }
132
+ }
133
+ //# sourceMappingURL=replies.js.map
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Helpers shared by every message-handling entry point.
3
+ *
4
+ * These sit below the domain modules rather than inside any one of them:
5
+ * `handleMessage`, the ForceReply handlers and the turn runner all need
6
+ * them, so putting them in a domain module would make the other two import
7
+ * across domains for a two-line helper.
8
+ */
9
+ import * as path from 'path';
10
+ import { config } from '../../../config.js';
11
+ import { sessionManager } from '../../../claude/session-manager.js';
12
+ import { queueRequest } from '../../../claude/request-queue.js';
13
+ import { summarizeTopicWithHaiku } from '../../../claude/auto-topic-haiku.js';
14
+ import { readLastAiTitle } from '../../../claude/session-jsonl.js';
15
+ import { isBotNameEnabled } from '../../../telegram/botname-settings.js';
16
+ import { namesThread } from '../../../telegram/thread-titles.js';
17
+ import { userPreferences } from '../../../providers/user-preferences.js';
18
+ import { parseSessionKey } from '../../../utils/session-key.js';
19
+ import { resolveShareableFile } from '../../file-access.js';
20
+ import { getSessionTopic, setSessionTopic } from '../command.handler.js';
21
+ import { getMsSinceTopicSet } from '../command/topic-store.js';
22
+ import { requireSession } from '../session-guard.js';
23
+ import { turnErrorReply } from '../../../claude/claude-auth.js';
24
+ export { requireSession } from '../session-guard.js';
25
+ export async function replyFeatureDisabled(ctx, feature) {
26
+ await ctx.reply(`⚠️ ${feature} feature is disabled in configuration.`);
27
+ }
28
+ /**
29
+ * Fire-and-forget topic update via a parallel Haiku call. Runs alongside
30
+ * the main agent turn so the bot name reflects the new topic almost
31
+ * immediately, without depending on the main agent calling telecoder_set_topic.
32
+ */
33
+ export function fireAutoTopic(ctx, sessionKey, userMessage) {
34
+ if (!config.AUTO_TOPIC_HAIKU)
35
+ return;
36
+ // Fire if the topic will be visible somewhere — the bot name, the status
37
+ // line or the thread's name. Skipping when nothing displays it avoids wasted
38
+ // Haiku calls.
39
+ const { chatId } = parseSessionKey(sessionKey);
40
+ const wantsTopic = isBotNameEnabled(sessionKey)
41
+ || userPreferences.getShowTopicInStatusLine(chatId)
42
+ || namesThread(sessionKey);
43
+ if (!wantsTopic)
44
+ return;
45
+ void (async () => {
46
+ try {
47
+ const previousTopic = getSessionTopic(sessionKey);
48
+ const startedAt = Date.now();
49
+ const workingDirectory = sessionManager.getSession(sessionKey)?.workingDirectory;
50
+ let topic = await summarizeTopicWithHaiku(userMessage, previousTopic, workingDirectory ? path.basename(workingDirectory) : undefined);
51
+ // The agent (or the user's /topic) set one while Haiku was thinking:
52
+ // that topic is newer and deliberate, and Haiku's guess, made from the
53
+ // topic before it, would otherwise land a few seconds later on top.
54
+ const setSince = getMsSinceTopicSet(sessionKey);
55
+ if (setSince !== undefined && setSince < Date.now() - startedAt)
56
+ return;
57
+ // If Haiku failed AND we have no prior topic at all, seed from Claude
58
+ // Code's aiTitle so the status line shows *something* instead of staying
59
+ // blank until the next turn succeeds. With a prior topic we keep it.
60
+ if (!topic && !previousTopic) {
61
+ const session = sessionManager.getSession(sessionKey);
62
+ if (session?.claudeSessionId) {
63
+ topic = readLastAiTitle(session.workingDirectory, session.claudeSessionId);
64
+ }
65
+ }
66
+ if (!topic)
67
+ return;
68
+ // Topic lives in the status line, not the Telegram bot name. Updating
69
+ // the topic doesn't change buildBotDisplayName, so no setMyName call —
70
+ // we don't want to burn Telegram's bot-name rate limit on a no-op.
71
+ setSessionTopic(sessionKey, topic);
72
+ }
73
+ catch (err) {
74
+ console.debug('[AutoTopic] Side-call update failed:', err instanceof Error ? err.message : err);
75
+ }
76
+ })();
77
+ }
78
+ /**
79
+ * Resolve a user-typed file path against the active session, enforcing the
80
+ * file-access rules (see bot/file-access.ts: the credential denylist for
81
+ * everyone, the project directory for guests, the workspace for admins) and
82
+ * that the target is an existing regular file.
83
+ *
84
+ * Every rejection is reported to the chat and returns null, so callers only
85
+ * need to early-return. Shared by the /file and /telegraph reply handlers —
86
+ * they used to carry identical copies of these three checks, which meant a
87
+ * tightening of the containment rule could reach one and miss the other.
88
+ */
89
+ export async function resolveUserFilePath(ctx, sessionKey, filePath) {
90
+ const session = await requireSession(ctx, sessionKey);
91
+ if (!session)
92
+ return null;
93
+ return resolveShareableFile(ctx, session.workingDirectory, filePath);
94
+ }
95
+ /**
96
+ * Queue a turn and turn any failure into a user-facing error.
97
+ *
98
+ * "Queue cleared" is the normal signal that a newer message superseded this
99
+ * one, so it exits quietly. Anything else is logged as well as reported —
100
+ * three of the four call sites this replaces only replied to the chat, which
101
+ * left failures in the plan/explore, suggestion-tap and throttle-retry paths
102
+ * invisible from the server side.
103
+ */
104
+ export async function runQueuedTurn(ctx, sessionKey, message, label, run) {
105
+ try {
106
+ await queueRequest(sessionKey, message, run);
107
+ }
108
+ catch (error) {
109
+ if (error.message === 'Queue cleared')
110
+ return;
111
+ console.error(`[${label}] Turn failed:`, error);
112
+ // An auth failure gets a reply saying how to sign in rather than the
113
+ // CLI's own "Please run /login", which nobody can do from a phone.
114
+ await ctx.reply(turnErrorReply(error));
115
+ }
116
+ }
117
+ //# sourceMappingURL=shared.js.map
@@ -0,0 +1,49 @@
1
+ /**
2
+ * CCR throttle state and the "switch & retry" prompt.
3
+ *
4
+ * Deliberately holds no reference to the turn runner: the retry *callback*
5
+ * lives in turn-runner.ts alongside the other turn entry points, so this
6
+ * module stays a leaf that the runner can import without a cycle.
7
+ */
8
+ import { config } from '../../../config.js';
9
+ import { EntityText } from '../../../telegram/entities.js';
10
+ import { replyFormatted } from '../../../telegram/send.js';
11
+ // Last user prompt that hit a throttle, keyed by sessionKey. Used by the
12
+ // "Switch & Retry" callback so the bot can replay the prompt under CCR
13
+ // without the user having to retype it. Cleared on consumption or on a
14
+ // new successful query.
15
+ export const lastThrottledPrompt = new Map();
16
+ export function formatResetIn(resetAt) {
17
+ if (!resetAt)
18
+ return '';
19
+ const ms = resetAt - Date.now();
20
+ if (ms <= 0)
21
+ return '';
22
+ const mins = Math.round(ms / 60_000);
23
+ if (mins < 60)
24
+ return ` Resets in ~${mins} min.`;
25
+ const hours = Math.floor(mins / 60);
26
+ const remainder = mins % 60;
27
+ return ` Resets in ~${hours}h${remainder ? ` ${remainder}m` : ''}.`;
28
+ }
29
+ export async function postThrottlePrompt(ctx, sessionKey, message, throttle) {
30
+ if (!config.CCR_ENABLED || !config.CCR_AUTO_PROMPT_ON_THROTTLE)
31
+ return;
32
+ lastThrottledPrompt.set(sessionKey, message);
33
+ const resetTxt = formatResetIn(throttle.resetAt);
34
+ await replyFormatted(ctx, new EntityText()
35
+ .add('⚠️ ').bold('Max usage limit reached.').add(resetTxt).newline(2)
36
+ .add('Route your message through Claude Code Router (CCR) instead?').newline()
37
+ .italic('The switch is sticky — use /ccr to flip back.')
38
+ .build(), {
39
+ reply_markup: {
40
+ inline_keyboard: [
41
+ [
42
+ { text: '🔌 Switch to CCR & retry', callback_data: 'ccr_throttle:switch' },
43
+ { text: 'Cancel', callback_data: 'ccr_throttle:cancel' },
44
+ ],
45
+ ],
46
+ },
47
+ });
48
+ }
49
+ //# sourceMappingURL=throttle.js.map
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Everything posted to the chat *after* a turn's main response: the catch-up
3
+ * relay that recovers prose the extractors dropped, the context-visibility
4
+ * notices (compaction, new-agent-session), and the status line that comes
5
+ * last. The usage footer isn't a message of its own: it goes out at the bottom
6
+ * of the status line, see `sendStatusLine`.
7
+ *
8
+ * Each notice consults the chat's verbosity settings itself, and the status
9
+ * line the chat's /statusline ones, so callers fire them unconditionally via
10
+ * `closeTurn`.
11
+ */
12
+ import { sessionManager } from '../../../claude/session-manager.js';
13
+ import { readLastAssistantTurnText } from '../../../claude/session-jsonl.js';
14
+ import { getPtyProvider } from '../../../providers/claude-provider.js';
15
+ import { getCachedUsage } from '../../../providers/provider-router.js';
16
+ import { messageSender } from '../../../telegram/message-sender.js';
17
+ import { EntityText } from '../../../telegram/entities.js';
18
+ import { replyFormatted } from '../../../telegram/send.js';
19
+ import { bringCardDown } from '../../../telegram/background-activity-card.js';
20
+ import { resolveVerbosityFlags } from '../../../utils/verbosity.js';
21
+ import { fmtTokens } from '../../../utils/format.js';
22
+ import { stripReasoningSummary } from '../../../utils/reasoning-summary.js';
23
+ import { sendStatusLine } from '../command/settings.js';
24
+ /**
25
+ * After a turn's main response has been sent to Telegram, compare what we
26
+ * relayed against the canonical assistant text in Claude Code's session JSONL.
27
+ * If the JSONL has more prose than we sent — typical for the lossy extractor
28
+ * paths (pure tool-call turns that returned empty, multi-block screen-scrape
29
+ * dropping earlier blocks, early end-of-turn before JSONL flush) — post the
30
+ * missing content as a follow-up. Updates the per-session tracker either way.
31
+ *
32
+ * Best-effort: any failure logs and swallows so a catch-up bug can never
33
+ * break the primary relay path. Skips silently when the session has no
34
+ * claudeSessionId (e.g. SDK mode), since the JSONL doesn't exist there.
35
+ */
36
+ export async function relayCatchUpIfMissed(ctx, sessionKey, relayedText) {
37
+ try {
38
+ const session = sessionManager.getSession(sessionKey);
39
+ if (!session?.claudeSessionId) {
40
+ sessionManager.setLastRelayedAssistantText(sessionKey, relayedText);
41
+ return;
42
+ }
43
+ // The relayed text went out without its reasoning summary; the log still
44
+ // has it. Compared as is, the summary alone counts as missing prose, and
45
+ // a turn with a tool call in it gets the whole reply posted again.
46
+ const jsonlText = stripReasoningSummary(readLastAssistantTurnText(session.workingDirectory, session.claudeSessionId) ?? '');
47
+ if (!jsonlText) {
48
+ sessionManager.setLastRelayedAssistantText(sessionKey, relayedText);
49
+ return;
50
+ }
51
+ // 20-char slack absorbs trailing-whitespace / trim differences between
52
+ // the screen-scrape and JSONL forms. Below that, treat as in sync.
53
+ if (jsonlText.length <= relayedText.length + 20) {
54
+ sessionManager.setLastRelayedAssistantText(sessionKey, jsonlText);
55
+ return;
56
+ }
57
+ // If what we sent is a prefix of the canonical text (PTY happy path that
58
+ // truncated mid-stream), post only the suffix. Otherwise post the full
59
+ // canonical version — the texts come from different extractors and any
60
+ // mid-string diff would risk dropping the actually-missing content.
61
+ const missing = jsonlText.startsWith(relayedText) && relayedText.length > 0
62
+ ? jsonlText.slice(relayedText.length).trim()
63
+ : jsonlText;
64
+ if (!missing) {
65
+ sessionManager.setLastRelayedAssistantText(sessionKey, jsonlText);
66
+ return;
67
+ }
68
+ await replyFormatted(ctx, new EntityText().add('📨 ').bold('Catch-up').add(' — recovered from session log').build());
69
+ await messageSender.sendMessage(ctx, missing);
70
+ sessionManager.setLastRelayedAssistantText(sessionKey, jsonlText);
71
+ }
72
+ catch (err) {
73
+ console.error('[CatchUp] post-relay check failed:', err instanceof Error ? err.message : err);
74
+ }
75
+ }
76
+ async function sendCompactionNotification(ctx, compaction) {
77
+ if (!compaction)
78
+ return;
79
+ const chatId = ctx.chat?.id;
80
+ if (chatId === undefined)
81
+ return;
82
+ if (!resolveVerbosityFlags(chatId).notifyCompaction)
83
+ return;
84
+ const c = compaction;
85
+ console.log(`[Compaction] Sending notification: trigger=${c.trigger}, preTokens=${c.preTokens}`);
86
+ const emoji = c.trigger === 'auto' ? '⚠️' : 'ℹ️';
87
+ const triggerLabel = c.trigger === 'auto' ? 'Auto-compacted' : 'Manually compacted';
88
+ try {
89
+ // replyFormatted already retries unformatted if Telegram refuses the entities.
90
+ await replyFormatted(ctx, new EntityText()
91
+ .add(`${emoji} `).bold('Context Compacted').newline(2)
92
+ .add(`${triggerLabel} — previous context was ${fmtTokens(c.preTokens)} tokens.\n`)
93
+ .add('The agent now has a summarized version of your conversation.').newline(2)
94
+ .italic('Tip: Use /handoff before compaction to save a detailed context document.')
95
+ .build());
96
+ }
97
+ catch (err) {
98
+ console.error('[Compaction] Failed to send notification:', err);
99
+ }
100
+ }
101
+ async function sendSessionInitNotification(ctx, sessionKey, sessionInit) {
102
+ if (!sessionInit)
103
+ return;
104
+ const chatId = ctx.chat?.id;
105
+ if (chatId === undefined)
106
+ return;
107
+ if (!resolveVerbosityFlags(chatId).notifyCompaction)
108
+ return;
109
+ const previousSessionId = sessionManager.getSession(sessionKey)?.claudeSessionId;
110
+ if (previousSessionId && sessionInit.sessionId !== previousSessionId) {
111
+ await replyFormatted(ctx, new EntityText()
112
+ .add('🔄 ').bold('New Agent Session').newline(2)
113
+ .add('A new agent session has started (previous context may be summarized).\n')
114
+ .add('Model: ').code(sessionInit.model).newline(2)
115
+ .italic('The agent may not remember earlier details. Consider sharing context.')
116
+ .build());
117
+ }
118
+ }
119
+ /**
120
+ * The context-visibility notices every finished turn posts, in the order the
121
+ * user expects to read them. Each one decides for itself whether the chat's
122
+ * verbosity settings want it, so callers just fire both.
123
+ */
124
+ export async function sendTurnNotifications(ctx, sessionKey, response) {
125
+ await sendCompactionNotification(ctx, response.compaction);
126
+ await sendSessionInitNotification(ctx, sessionKey, response.sessionInit);
127
+ }
128
+ /**
129
+ * What closes a turn, however it started: the context notices, then the status
130
+ * line. A typed message, a voice note, an upload, /plan, /explore, /loop and a
131
+ * scheduled fire all end here. Each used to write its own ending, and only the
132
+ * typed message's had the status line, so a turn started any other way left
133
+ * the chat on the tail of its reply with nothing to say where things stood.
134
+ *
135
+ * `prompt` is what the turn was sent, for a session whose log has no prompts
136
+ * for the status line to list.
137
+ */
138
+ export async function closeTurn(ctx, sessionKey, response, prompt, options) {
139
+ await sendTurnNotifications(ctx, sessionKey, response);
140
+ const chatId = ctx.chat?.id;
141
+ if (chatId === undefined)
142
+ return;
143
+ // Not every response carries a usage: a /loop's doesn't, though each of its
144
+ // iterations left one behind, and neither does a cancelled turn's. The line
145
+ // then shows what the session last had, rather than no model and no context.
146
+ const usage = response.usage ?? getCachedUsage(sessionKey);
147
+ await sendStatusLine(ctx, chatId, sessionKey, usage, prompt, options);
148
+ // The reply buried the card; tasks still running get it back below.
149
+ bringCardDown(sessionKey);
150
+ }
151
+ /**
152
+ * The close of a turn claude started itself, when a background task reported
153
+ * back. Its reply is often the answer the exchange was for, it tends to land
154
+ * while the user is elsewhere, and no prompt of theirs sits above it, so it
155
+ * closes with the status line like any other.
156
+ *
157
+ * Nothing ran that turn for us: there's no response to take the usage from,
158
+ * and the cached figure is the one the turn before it left. The session log
159
+ * has what this one left. The prompts come from the log as well, which lists
160
+ * what the user sent and not what a task reported.
161
+ */
162
+ export async function closeSelfStartedTurn(ctx, sessionKey) {
163
+ const chatId = ctx.chat?.id;
164
+ if (chatId === undefined)
165
+ return;
166
+ await sendStatusLine(ctx, chatId, sessionKey, getPtyProvider().refreshUsage(sessionKey));
167
+ bringCardDown(sessionKey);
168
+ }
169
+ //# sourceMappingURL=turn-notify.js.map