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,286 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { config } from '../../config.js';
4
+ import { sendToAgent } from '../../providers/provider-router.js';
5
+ import { sessionManager } from '../../claude/session-manager.js';
6
+ import { messageSender } from '../../telegram/message-sender.js';
7
+ import { closeTurn, relayCatchUpIfMissed } from './message/turn-notify.js';
8
+ import { isDuplicate, markProcessed } from '../../telegram/deduplication.js';
9
+ import { isStaleMessage } from '../middleware/stale-filter.js';
10
+ import { queueRequest } from '../../claude/request-queue.js';
11
+ import { downloadFileSecure, getTelegramFileUrl } from '../../utils/download.js';
12
+ import { telegramProxyUrl } from '../../telegram/client-options.js';
13
+ import { sanitizeError } from '../../utils/sanitize.js';
14
+ import { isValidImageFile, getFileType } from '../../utils/file-type.js';
15
+ import { getSessionKeyFromCtx } from '../../utils/session-key.js';
16
+ import { requireSession } from './session-guard.js';
17
+ import { progressCallbacks, withStreamingTurn } from '../../telegram/streaming-turn.js';
18
+ import { ensureUploadsDir } from '../../utils/uploads-dir.js';
19
+ function sanitizeFileName(name) {
20
+ return path.basename(name).replace(/[^a-zA-Z0-9._-]/g, '_');
21
+ }
22
+ export function pickLargestPhoto(photoSizes) {
23
+ return photoSizes.reduce((best, current) => {
24
+ const bestSize = best.file_size || 0;
25
+ const currentSize = current.file_size || 0;
26
+ return currentSize > bestSize ? current : best;
27
+ });
28
+ }
29
+ async function downloadTelegramFile(ctx, fileId, destPath) {
30
+ const file = await ctx.api.getFile(fileId);
31
+ if (!file.file_path) {
32
+ throw new Error('Telegram did not provide file_path for this image.');
33
+ }
34
+ const fileUrl = getTelegramFileUrl(config.TELEGRAM_BOT_TOKEN, file.file_path);
35
+ await downloadFileSecure(fileUrl, destPath, { proxyUrl: telegramProxyUrl() });
36
+ return file.file_path;
37
+ }
38
+ function getMediaType(filePath) {
39
+ const ext = path.extname(filePath).toLowerCase();
40
+ const mimeTypes = {
41
+ '.jpg': 'image/jpeg',
42
+ '.jpeg': 'image/jpeg',
43
+ '.png': 'image/png',
44
+ '.gif': 'image/gif',
45
+ '.webp': 'image/webp',
46
+ };
47
+ return mimeTypes[ext] || 'image/jpeg';
48
+ }
49
+ async function handleSavedImage(ctx, savedPath, caption) {
50
+ const keyInfo = getSessionKeyFromCtx(ctx);
51
+ if (!keyInfo)
52
+ return;
53
+ const { sessionKey } = keyInfo;
54
+ const session = sessionManager.getSession(sessionKey);
55
+ if (!session)
56
+ return;
57
+ const captionText = caption?.trim();
58
+ const noteLines = [
59
+ 'User sent an image.',
60
+ `Saved at: ${savedPath}`,
61
+ captionText ? `Caption: "${captionText}"` : 'Caption: (none)',
62
+ 'The image is attached as a vision input — you can see it directly.',
63
+ 'If the caption includes a question or request, answer it. Otherwise, describe what you see and ask if they want any analysis or edits.',
64
+ ];
65
+ const agentPrompt = noteLines.join('\n');
66
+ await runUploadTurn(ctx, sessionKey, agentPrompt, [imageAttachment(savedPath)]);
67
+ }
68
+ /** A saved image as vision input for the turn. */
69
+ export function imageAttachment(savedPath) {
70
+ // Read image as base64 for multimodal vision input
71
+ const data = fs.readFileSync(savedPath).toString('base64');
72
+ // savedPath is what the prompt names in "Saved at:", and naming it is
73
+ // what makes claude attach it — so hand the provider that same
74
+ // path rather than letting it stage a duplicate copy of the same picture.
75
+ return { data, mediaType: getMediaType(savedPath), path: savedPath };
76
+ }
77
+ /** Send the note an upload became to Claude as a turn, behind any turn already running. */
78
+ export async function runUploadTurn(ctx, sessionKey, agentPrompt, images) {
79
+ await queueRequest(sessionKey, agentPrompt, async () => {
80
+ const startTime = Date.now();
81
+ await withStreamingTurn(ctx, sessionKey, agentPrompt, async (abortController) => {
82
+ const response = await sendToAgent(sessionKey, agentPrompt, {
83
+ ...progressCallbacks(ctx),
84
+ abortController,
85
+ images,
86
+ telegramCtx: ctx,
87
+ });
88
+ await messageSender.finishStreaming(ctx, response.text);
89
+ await relayCatchUpIfMissed(ctx, sessionKey, response.text || '');
90
+ await messageSender.sendCompletionNotification(ctx, Date.now() - startTime);
91
+ await closeTurn(ctx, sessionKey, response, agentPrompt);
92
+ });
93
+ });
94
+ }
95
+ /** Drop a download that turned out not to be an image, and say so. */
96
+ function requireValidImage(destPath) {
97
+ // Validate file content via magic bytes (defense against spoofed MIME types)
98
+ let isValid = false;
99
+ try {
100
+ isValid = isValidImageFile(destPath);
101
+ }
102
+ catch {
103
+ // Validation threw — treat as invalid
104
+ }
105
+ if (!isValid) {
106
+ if (fs.existsSync(destPath))
107
+ fs.unlinkSync(destPath);
108
+ throw new Error('Downloaded file is not a valid image.');
109
+ }
110
+ if (!fs.readFileSync(destPath).length) {
111
+ throw new Error('Downloaded image is empty.');
112
+ }
113
+ }
114
+ /**
115
+ * Save a photo under `uploadsDir` and return where it went. `stamp` starts the
116
+ * file name, so photos saved together can be told apart.
117
+ */
118
+ export async function savePhoto(ctx, uploadsDir, photo, stamp = String(Date.now())) {
119
+ const safeUniqueId = sanitizeFileName(photo.file_unique_id);
120
+ const destPath = path.join(uploadsDir, `photo_${stamp}_${safeUniqueId}.jpg`);
121
+ const filePath = await downloadTelegramFile(ctx, photo.file_id, destPath);
122
+ requireValidImage(destPath);
123
+ // Get actual file type from magic bytes instead of trusting extension
124
+ const actualType = getFileType(destPath);
125
+ const rawExt = actualType?.extension || path.extname(filePath) || '.jpg';
126
+ const ext = rawExt.startsWith('.') ? rawExt : `.${rawExt}`;
127
+ const finalPath = ext && ext !== '.jpg'
128
+ ? destPath.replace(/\.jpg$/, ext)
129
+ : destPath;
130
+ if (finalPath !== destPath) {
131
+ fs.renameSync(destPath, finalPath);
132
+ }
133
+ return finalPath;
134
+ }
135
+ /** Save an image sent as a file under `uploadsDir` and return where it went. */
136
+ export async function saveImageDocument(ctx, uploadsDir, document, stamp = String(Date.now())) {
137
+ const originalName = document.file_name ? sanitizeFileName(document.file_name) : '';
138
+ const ext = originalName.includes('.') ? '' : '.jpg';
139
+ const baseName = originalName || `image_${stamp}_${document.file_unique_id}${ext}`;
140
+ const destPath = path.join(uploadsDir, `${stamp}_${baseName}`);
141
+ await downloadTelegramFile(ctx, document.file_id, destPath);
142
+ requireValidImage(destPath);
143
+ return destPath;
144
+ }
145
+ /** Save any other file under `uploadsDir` and return where it went. */
146
+ export async function saveDocument(ctx, uploadsDir, document, stamp = String(Date.now())) {
147
+ const originalName = document.file_name ? sanitizeFileName(document.file_name) : `file_${document.file_unique_id}`;
148
+ const destPath = path.join(uploadsDir, `${stamp}_${originalName}`);
149
+ await downloadTelegramFile(ctx, document.file_id, destPath);
150
+ if (!fs.existsSync(destPath) || fs.statSync(destPath).size === 0) {
151
+ throw new Error('Downloaded document is empty.');
152
+ }
153
+ return destPath;
154
+ }
155
+ export async function handlePhoto(ctx) {
156
+ const keyInfo = getSessionKeyFromCtx(ctx);
157
+ const messageId = ctx.message?.message_id;
158
+ const messageDate = ctx.message?.date;
159
+ const photos = ctx.message?.photo;
160
+ if (!keyInfo || !messageId || !messageDate || !photos || photos.length === 0)
161
+ return;
162
+ const { sessionKey } = keyInfo;
163
+ if (isStaleMessage(messageDate)) {
164
+ console.log(`[Photo] Ignoring stale photo message ${messageId}`);
165
+ return;
166
+ }
167
+ if (isDuplicate(messageId)) {
168
+ console.log(`[Photo] Ignoring duplicate photo message ${messageId}`);
169
+ return;
170
+ }
171
+ markProcessed(messageId);
172
+ const session = await requireSession(ctx, sessionKey);
173
+ if (!session)
174
+ return;
175
+ const largest = pickLargestPhoto(photos);
176
+ const fileSizeBytes = largest.file_size || 0;
177
+ const fileSizeMB = fileSizeBytes / (1024 * 1024);
178
+ if (fileSizeMB > config.IMAGE_MAX_FILE_SIZE_MB) {
179
+ await ctx.reply(`❌ Image too large (${fileSizeMB.toFixed(1)}MB).\n\nPlease send images under ${config.IMAGE_MAX_FILE_SIZE_MB}MB.`);
180
+ return;
181
+ }
182
+ const uploadsDir = ensureUploadsDir(session.workingDirectory);
183
+ try {
184
+ const finalPath = await savePhoto(ctx, uploadsDir, largest);
185
+ await handleSavedImage(ctx, finalPath, ctx.message?.caption);
186
+ }
187
+ catch (error) {
188
+ const errorMessage = sanitizeError(error);
189
+ console.error('[Photo] Error:', errorMessage);
190
+ await ctx.reply(`❌ Image error: ${errorMessage}`);
191
+ }
192
+ }
193
+ /**
194
+ * Handle non-image, non-audio document uploads (PDFs, .txt, .csv, .md, code
195
+ * files, etc.). Saves to the project's uploads dir and prompts claude to
196
+ * Read the file. Image and audio MIME types are filtered out before this
197
+ * runs by the dispatcher in bot.ts.
198
+ */
199
+ export async function handleTextDocument(ctx) {
200
+ const keyInfo = getSessionKeyFromCtx(ctx);
201
+ const messageId = ctx.message?.message_id;
202
+ const messageDate = ctx.message?.date;
203
+ const document = ctx.message?.document;
204
+ if (!keyInfo || !messageId || !messageDate || !document)
205
+ return;
206
+ const { sessionKey } = keyInfo;
207
+ if (isStaleMessage(messageDate)) {
208
+ console.log(`[Doc] Ignoring stale document ${messageId}`);
209
+ return;
210
+ }
211
+ if (isDuplicate(messageId)) {
212
+ console.log(`[Doc] Ignoring duplicate document ${messageId}`);
213
+ return;
214
+ }
215
+ markProcessed(messageId);
216
+ const session = await requireSession(ctx, sessionKey);
217
+ if (!session)
218
+ return;
219
+ const fileSizeMB = (document.file_size || 0) / (1024 * 1024);
220
+ if (fileSizeMB > config.DOCUMENT_MAX_FILE_SIZE_MB) {
221
+ await ctx.reply(`❌ Document too large (${fileSizeMB.toFixed(1)}MB). Limit: ${config.DOCUMENT_MAX_FILE_SIZE_MB}MB.`);
222
+ return;
223
+ }
224
+ const uploadsDir = ensureUploadsDir(session.workingDirectory);
225
+ const originalName = document.file_name ? sanitizeFileName(document.file_name) : `file_${document.file_unique_id}`;
226
+ try {
227
+ const destPath = await saveDocument(ctx, uploadsDir, document);
228
+ const caption = ctx.message?.caption?.trim();
229
+ const noteLines = [
230
+ `User sent a file: ${document.file_name ?? originalName}`,
231
+ `Saved at: ${destPath}`,
232
+ caption ? `Caption: "${caption}"` : 'Caption: (none)',
233
+ 'Use the Read tool to read its contents. For PDFs use Read with `pages` for large files.',
234
+ 'If the caption asks a question, answer it based on the file. Otherwise summarize the contents and ask if they want a specific analysis.',
235
+ ];
236
+ const agentPrompt = noteLines.join('\n');
237
+ await runUploadTurn(ctx, sessionKey, agentPrompt);
238
+ }
239
+ catch (error) {
240
+ const errorMessage = sanitizeError(error);
241
+ console.error('[Doc] Error:', errorMessage);
242
+ await ctx.reply(`❌ Document error: ${errorMessage}`);
243
+ }
244
+ }
245
+ export async function handleImageDocument(ctx) {
246
+ const keyInfo = getSessionKeyFromCtx(ctx);
247
+ const messageId = ctx.message?.message_id;
248
+ const messageDate = ctx.message?.date;
249
+ const document = ctx.message?.document;
250
+ if (!keyInfo || !messageId || !messageDate || !document)
251
+ return;
252
+ const { sessionKey } = keyInfo;
253
+ // Only handle image documents
254
+ if (!document.mime_type || !document.mime_type.startsWith('image/')) {
255
+ return;
256
+ }
257
+ if (isStaleMessage(messageDate)) {
258
+ console.log(`[ImageDoc] Ignoring stale document ${messageId}`);
259
+ return;
260
+ }
261
+ if (isDuplicate(messageId)) {
262
+ console.log(`[ImageDoc] Ignoring duplicate document ${messageId}`);
263
+ return;
264
+ }
265
+ markProcessed(messageId);
266
+ const session = await requireSession(ctx, sessionKey);
267
+ if (!session)
268
+ return;
269
+ const fileSizeBytes = document.file_size || 0;
270
+ const fileSizeMB = fileSizeBytes / (1024 * 1024);
271
+ if (fileSizeMB > config.IMAGE_MAX_FILE_SIZE_MB) {
272
+ await ctx.reply(`❌ Image too large (${fileSizeMB.toFixed(1)}MB).\n\nPlease send images under ${config.IMAGE_MAX_FILE_SIZE_MB}MB.`);
273
+ return;
274
+ }
275
+ const uploadsDir = ensureUploadsDir(session.workingDirectory);
276
+ try {
277
+ const destPath = await saveImageDocument(ctx, uploadsDir, document);
278
+ await handleSavedImage(ctx, destPath, ctx.message?.caption);
279
+ }
280
+ catch (error) {
281
+ const errorMessage = sanitizeError(error);
282
+ console.error('[ImageDoc] Error:', errorMessage);
283
+ await ctx.reply(`❌ Image error: ${errorMessage}`);
284
+ }
285
+ }
286
+ //# sourceMappingURL=photo.handler.js.map
@@ -0,0 +1,343 @@
1
+ /**
2
+ * /prompts — what you typed in a conversation, a line each, and a way back to
3
+ * any point in it.
4
+ *
5
+ * The list answers "what was this conversation about?" without paying for the
6
+ * replies again — that's the whole difference from /history, which re-sends
7
+ * every reply in full and buries the prompts you came back to read. It keys
8
+ * each prompt by a letter the way /tree keys its points, and the buttons are
9
+ * just the letters. A letter opens its prompt — the exchange it started — and
10
+ * what can be done from where that exchange ended:
11
+ *
12
+ * 🌱 New branch from here carry on just after that reply, in a new
13
+ * conversation; this one stays in /resume
14
+ *
15
+ * which is the 🌱 Branch button under that reply, without scrolling up to it.
16
+ * A prompt another branch already splits off at is marked 🌿, and 🌳 shows
17
+ * the tree, where that branch can be carried on.
18
+ *
19
+ * Callback data has to fit in 64 bytes. A prompt is named by its record's
20
+ * uuid, and its conversation by the first 8 characters of the session id:
21
+ *
22
+ * prompts:l:<session8>:<n> the list, of the last n prompts
23
+ * prompts:o:<session8>:<n>:<uuid> open a prompt; n is for the way back
24
+ * prompts:b:<session8>:<uuid> branch from the end of its exchange
25
+ *
26
+ * Every tap re-reads the transcript, which only ever grows, so a message sent
27
+ * before the conversation moved on still finds each prompt where it was.
28
+ */
29
+ import * as fs from 'fs';
30
+ import * as path from 'path';
31
+ import { BOT_ID, config } from '../../config.js';
32
+ import { getSessionKeyFromCtx } from '../../utils/session-key.js';
33
+ import { sanitizeError } from '../../utils/sanitize.js';
34
+ import { findHistoryOwners } from '../../claude/session-history.js';
35
+ import { isProcessing } from '../../claude/request-queue.js';
36
+ import { lastAssistantTurnText, lastExchangeIn, sessionJsonlPath, userPromptsIn, } from '../../claude/session-jsonl.js';
37
+ import { splitsAlong, transcriptDir, treeOf } from '../../claude/branch-tree.js';
38
+ import { EntityText, joinMessages, plain } from '../../telegram/entities.js';
39
+ import { replyFormatted } from '../../telegram/send.js';
40
+ import { buildLetterKeyboard, optionLetter } from '../../telegram/lettered-options.js';
41
+ import { cutLabel, promptLabel } from '../../telegram/prompt-label.js';
42
+ import { getSessionTopic } from './command.handler.js';
43
+ import { formatTimeAgo } from './command/shared.js';
44
+ import { NO_PROJECT_MESSAGE, whereChatIs } from './session-guard.js';
45
+ import { LEFT_ABOVE, loadBranch, replyQuote, youLine } from './branch.handler.js';
46
+ import { showTreeButton } from './tree.handler.js';
47
+ import { refuseWhileBusy, sendView } from './view.js';
48
+ // Most prompts are short (a median line of 72 characters across 40 recent
49
+ // sessions), so the default can reach well back: 15 fit in one message in all
50
+ // 40, about two phone screens. 25 fit in 35 of them, and the budget below cuts
51
+ // the rest oldest-first, so a higher cap would mostly buy a "trimmed" note.
52
+ // Past 300 characters a prompt shows by its start and its end, as /tree and
53
+ // the status line show one.
54
+ const PROMPTS_MAX_CHARS = 300;
55
+ const PROMPTS_DEFAULT_N = 15;
56
+ const PROMPTS_MAX_N = 25;
57
+ // Telegram's hard cap is 4096 chars per message. Budget below it for the
58
+ // lines, leaving room for the header, the legend and the newlines.
59
+ const PROMPTS_BUDGET_CHARS = 3800;
60
+ /**
61
+ * How much of the reply a prompt's view shows: as much as a /tree point's
62
+ * view. It's a menu, read before choosing, and the whole reply is up in the
63
+ * chat.
64
+ */
65
+ const PROMPT_REPLY_LEN = 1200;
66
+ /** The first 8 characters of a session id: enough to find it among one project's transcripts. */
67
+ const session8Of = (conversation) => conversation.sessionId.slice(0, 8);
68
+ // ── Reading ──────────────────────────────────────────────────────────────
69
+ function readConversation(projectPath, sessionId) {
70
+ let raw;
71
+ try {
72
+ raw = fs.readFileSync(sessionJsonlPath(projectPath, sessionId), 'utf-8');
73
+ }
74
+ catch {
75
+ return undefined;
76
+ }
77
+ // A /compact and the records it leaves aren't prompts, and would each take
78
+ // one of the n lines.
79
+ const turns = userPromptsIn(raw).flatMap((p) => {
80
+ const label = promptLabel(p.text);
81
+ return label ? [{ ...p, label }] : [];
82
+ });
83
+ // A branch splitting off anywhere between one prompt and the next splits off
84
+ // during the first one's exchange.
85
+ const tree = treeOf(projectPath, sessionId);
86
+ const branched = tree && tree.transcripts.size > 1 ? tree : undefined;
87
+ const splits = branched ? splitsAlong(branched, sessionId) : [];
88
+ const prompts = turns.map((p, i) => {
89
+ const next = turns[i + 1]?.line ?? Infinity;
90
+ return { ...p, branched: splits.some((s) => s.line >= p.line && s.line < next) };
91
+ });
92
+ return { projectPath, sessionId, raw, prompts, tree: branched };
93
+ }
94
+ /**
95
+ * The conversation a button names by `session8`, in the chat's project — the
96
+ * chat's own when its id starts that way — holding the prompt `uuid` when one
97
+ * is named.
98
+ */
99
+ function findConversation(projectPath, session8, chatSessionId, uuid) {
100
+ const holds = (c) => c && (!uuid || c.prompts.some((p) => p.uuid === uuid));
101
+ if (chatSessionId?.startsWith(session8)) {
102
+ const conversation = readConversation(projectPath, chatSessionId);
103
+ if (holds(conversation))
104
+ return conversation;
105
+ }
106
+ let names = [];
107
+ try {
108
+ names = fs.readdirSync(transcriptDir(projectPath));
109
+ }
110
+ catch { /* nothing has run in this project */ }
111
+ for (const name of names) {
112
+ if (!name.startsWith(session8) || !name.endsWith('.jsonl'))
113
+ continue;
114
+ const sessionId = name.slice(0, -'.jsonl'.length);
115
+ if (sessionId === chatSessionId)
116
+ continue;
117
+ const conversation = readConversation(projectPath, sessionId);
118
+ if (holds(conversation))
119
+ return conversation;
120
+ }
121
+ return undefined;
122
+ }
123
+ /** The topic of the history that last had the conversation open, in any bot. */
124
+ function lastTopicOf(sessionId) {
125
+ return [...findHistoryOwners([sessionId], BOT_ID).values()].flat()
126
+ .sort((a, b) => b.entry.lastActivity.localeCompare(a.entry.lastActivity))[0]?.entry.topic;
127
+ }
128
+ /** The transcript up to the end of `prompt`'s exchange: what a branch from just after its reply starts with. */
129
+ function cutAfter(conversation, prompt) {
130
+ return conversation.raw.split('\n').slice(0, prompt.endLine).join('\n') + '\n';
131
+ }
132
+ // ── Views ────────────────────────────────────────────────────────────────
133
+ const timeOf = (prompt) => (prompt.timestamp ? formatTimeAgo(new Date(prompt.timestamp)) : 'earlier');
134
+ /** A prompt's line in the list. Its marks sit by the time, where a long prompt doesn't bury them. */
135
+ function listLine(prompt, letter) {
136
+ const marks = `${prompt.branched ? ' 🌿' : ''}${prompt.pending ? ' ⏳' : ''}`;
137
+ return new EntityText()
138
+ .bold(letter).add(' · ').italic(timeOf(prompt))
139
+ .add(`${marks} — ${cutLabel(prompt.label, PROMPTS_MAX_CHARS)}`)
140
+ .build();
141
+ }
142
+ /**
143
+ * The prompts the list shows: the last `n`, less the oldest of them when they
144
+ * won't all fit in one message.
145
+ *
146
+ * The budget is spent newest-first: 25 pasted prompts can exceed one Telegram
147
+ * message, and when something has to go it should be the oldest, not the one
148
+ * you just sent. Every letter is one character, so measuring each line as `A`
149
+ * measures it as whichever letter it ends up with.
150
+ */
151
+ function listed(conversation, n) {
152
+ const recent = conversation.prompts.slice(-n);
153
+ let from = recent.length;
154
+ let used = 0;
155
+ while (from > 0) {
156
+ const length = listLine(recent[from - 1], 'A').text.length + 1;
157
+ if (from < recent.length && used + length > PROMPTS_BUDGET_CHARS)
158
+ break;
159
+ used += length;
160
+ from--;
161
+ }
162
+ return recent.slice(from);
163
+ }
164
+ /**
165
+ * The last `n` prompts of a conversation in one message, oldest first so it
166
+ * reads in the same order as the chat above it: a letter per prompt and a
167
+ * button per letter, the way /tree draws its points.
168
+ */
169
+ export function renderPrompts(conversation, n) {
170
+ const shown = listed(conversation, n);
171
+ const project = path.basename(conversation.projectPath);
172
+ const heading = new EntityText().add('💬 ').bold(project);
173
+ if (shown.length === 0)
174
+ return { text: heading.add(' — no prompts yet.').build(), keyboard: [] };
175
+ const noun = shown.length === 1 ? 'prompt' : 'prompts';
176
+ const count = shown.length === conversation.prompts.length ? `${shown.length} ${noun}` : `last ${shown.length} ${noun}`;
177
+ const dropped = Math.min(n, conversation.prompts.length) - shown.length;
178
+ const legend = [
179
+ ...(shown.some((p) => p.branched) ? ['🌿 a branch splits off here'] : []),
180
+ ...(shown.some((p) => p.pending) ? ['⏳ no reply'] : []),
181
+ ];
182
+ const text = joinMessages([
183
+ heading.add(` — ${count}${dropped > 0 ? ` (${dropped} older trimmed to fit)` : ''}`).build(),
184
+ plain(''),
185
+ ...shown.map((p, i) => listLine(p, optionLetter(i))),
186
+ plain(''),
187
+ ...(legend.length > 0 ? [new EntityText().italic(legend.join(' · ')).build()] : []),
188
+ plain('Tap a letter to open that prompt.'),
189
+ ], '\n');
190
+ const keyboard = [
191
+ ...buildLetterKeyboard(shown.map((p) => `prompts:o:${session8Of(conversation)}:${n}:${p.uuid}`)),
192
+ ...(conversation.tree && shown.some((p) => p.branched) ? [[showTreeButton(conversation.tree)]] : []),
193
+ ];
194
+ return { text, keyboard };
195
+ }
196
+ /**
197
+ * One prompt: the exchange it started, and what can be done from where that
198
+ * exchange ended. `running` says the chat's reply to it is being written now.
199
+ */
200
+ export function renderPrompt(conversation, prompt, n, running = false) {
201
+ // Its letter in the list as it stands now; one the conversation has since
202
+ // moved past the last n of goes without.
203
+ const index = listed(conversation, n).indexOf(prompt);
204
+ const facts = [timeOf(prompt)];
205
+ if (prompt.pending)
206
+ facts.push(running ? 'being answered now' : 'no reply');
207
+ const reply = prompt.pending ? undefined : lastExchangeIn(cutAfter(conversation, prompt))?.assistant;
208
+ const title = new EntityText().add('💬 ');
209
+ if (index >= 0)
210
+ title.bold(optionLetter(index)).add(' · ');
211
+ const text = joinMessages([
212
+ title.add(facts.join(' · ')).build(),
213
+ ...(prompt.branched ? [plain('🌿 Another branch splits off here.')] : []),
214
+ plain(''),
215
+ youLine(prompt.text, PROMPTS_MAX_CHARS),
216
+ // Cut without pointing at /history: that shows the last few exchanges, which
217
+ // this one may not be among.
218
+ ...(reply ? replyQuote(reply, PROMPT_REPLY_LEN, null) : []),
219
+ ], '\n');
220
+ const keyboard = [
221
+ // A prompt with no reply has no end to its exchange to branch from.
222
+ ...(prompt.pending
223
+ ? []
224
+ : [[{ text: '🌱 New branch from here', callback_data: `prompts:b:${session8Of(conversation)}:${prompt.uuid}` }]]),
225
+ ...(prompt.branched && conversation.tree ? [[showTreeButton(conversation.tree)]] : []),
226
+ [{ text: '⬅️ Back to the prompts', callback_data: `prompts:l:${session8Of(conversation)}:${n}` }],
227
+ ];
228
+ return { text, keyboard };
229
+ }
230
+ // ── Commands and taps ────────────────────────────────────────────────────
231
+ /** `n` as the list takes it: the default when missing or not a count, never past the most. */
232
+ function countOf(arg) {
233
+ if (!arg)
234
+ return PROMPTS_DEFAULT_N;
235
+ const parsed = parseInt(arg, 10);
236
+ return Number.isNaN(parsed) || parsed < 1 ? undefined : Math.min(parsed, PROMPTS_MAX_N);
237
+ }
238
+ export async function handlePromptsCommand(ctx) {
239
+ const keyInfo = getSessionKeyFromCtx(ctx);
240
+ if (!keyInfo)
241
+ return;
242
+ const n = countOf((ctx.message?.text || '').split(' ').slice(1).join(' ').trim());
243
+ if (n === undefined) {
244
+ await replyFormatted(ctx, new EntityText()
245
+ .add('⚠️ Usage: ').code('/prompts [N]')
246
+ .add(` where N is the number of prompts (default ${PROMPTS_DEFAULT_N}, max ${PROMPTS_MAX_N}).`)
247
+ .build());
248
+ return;
249
+ }
250
+ // Read, never loaded: after a restart it's where the chat left off, as /tree draws it.
251
+ const where = whereChatIs(keyInfo.sessionKey);
252
+ if (!where) {
253
+ await replyFormatted(ctx, NO_PROJECT_MESSAGE);
254
+ return;
255
+ }
256
+ if (!where.sessionId) {
257
+ await replyFormatted(ctx, 'ℹ️ This session has no recorded messages yet.');
258
+ return;
259
+ }
260
+ const conversation = readConversation(where.projectPath, where.sessionId);
261
+ if (!conversation || conversation.prompts.length === 0) {
262
+ await replyFormatted(ctx, 'ℹ️ No prompts found in this session yet.');
263
+ return;
264
+ }
265
+ await sendView(ctx, renderPrompts(conversation, n), 'reply');
266
+ }
267
+ export async function handlePromptsCallback(ctx) {
268
+ const data = ctx.callbackQuery?.data;
269
+ const keyInfo = getSessionKeyFromCtx(ctx);
270
+ if (!data || !keyInfo)
271
+ return;
272
+ const { sessionKey } = keyInfo;
273
+ const [, action, session8, ...rest] = data.split(':');
274
+ const n = countOf(action === 'b' ? undefined : rest[0]) ?? PROMPTS_DEFAULT_N;
275
+ const uuid = action === 'o' ? rest[1] : action === 'b' ? rest[0] : undefined;
276
+ try {
277
+ const where = whereChatIs(sessionKey);
278
+ const conversation = where && session8 ? findConversation(where.projectPath, session8, where.sessionId, uuid) : undefined;
279
+ if (!where || !conversation) {
280
+ await ctx.answerCallbackQuery({ text: "That conversation isn't in this chat's project any more — send /prompts again." });
281
+ return;
282
+ }
283
+ if (action === 'l') {
284
+ await ctx.answerCallbackQuery();
285
+ await sendView(ctx, renderPrompts(conversation, n), 'edit');
286
+ return;
287
+ }
288
+ const prompt = conversation.prompts.find((p) => p.uuid === uuid);
289
+ if (!prompt) {
290
+ await ctx.answerCallbackQuery({ text: "That prompt isn't in the conversation any more — send /prompts again." });
291
+ return;
292
+ }
293
+ // The chat is on this conversation: not a restart's leftover, which isn't loaded.
294
+ const onIt = where.live && where.sessionId === conversation.sessionId;
295
+ if (action === 'o') {
296
+ await ctx.answerCallbackQuery();
297
+ const running = onIt && isProcessing(sessionKey) && prompt === conversation.prompts.at(-1);
298
+ await sendView(ctx, renderPrompt(conversation, prompt, n, running), 'edit');
299
+ }
300
+ else if (action === 'b') {
301
+ await onBranch(ctx, sessionKey, conversation, prompt, onIt);
302
+ }
303
+ else {
304
+ await ctx.answerCallbackQuery({ text: 'Unknown prompts action.' });
305
+ }
306
+ }
307
+ catch (err) {
308
+ console.error('[Prompts] callback failed:', sanitizeError(err));
309
+ try {
310
+ await ctx.answerCallbackQuery({ text: 'That failed — see bot logs.' });
311
+ }
312
+ catch { /* already answered */ }
313
+ }
314
+ }
315
+ /**
316
+ * Start a conversation in this chat from the transcript cut just after
317
+ * `prompt`'s reply: a branch, loaded straight away, the way /tree branches
318
+ * from a point and the 🌱 under a reply does.
319
+ */
320
+ async function onBranch(ctx, sessionKey, conversation, prompt, onIt) {
321
+ if (prompt.pending) {
322
+ await ctx.answerCallbackQuery({ text: 'That prompt has no reply to branch after.' });
323
+ return;
324
+ }
325
+ if (await refuseWhileBusy(ctx, sessionKey))
326
+ return;
327
+ const jsonl = cutAfter(conversation, prompt);
328
+ const branch = {
329
+ fromBotName: config.BOT_NAME,
330
+ fromBotId: BOT_ID,
331
+ fromChatId: ctx.chat?.id,
332
+ projectPath: conversation.projectPath,
333
+ jsonl,
334
+ topic: onIt ? getSessionTopic(sessionKey) : lastTopicOf(conversation.sessionId),
335
+ assistantPreview: lastAssistantTurnText(jsonl)?.substring(0, 200),
336
+ createdAt: new Date().toISOString(),
337
+ };
338
+ // Above the banner is the conversation branched from, unless the chat had
339
+ // moved on from it before the tap.
340
+ await loadBranch(ctx, sessionKey, branch, onIt ? {} : { above: LEFT_ABOVE });
341
+ await ctx.answerCallbackQuery({ text: 'Branched.' });
342
+ }
343
+ //# sourceMappingURL=prompts.handler.js.map
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Keeps work still running in the background in sight after a command answers.
3
+ *
4
+ * A turn closes with the status line, which counts what runs. A command's
5
+ * answer doesn't, and lands below whatever said a task was running, so after
6
+ * a /btw or a /cost the chat reads as if nothing is going on. Under such an
7
+ * answer the background card comes down again; without a card, a line says
8
+ * how many tasks run.
9
+ */
10
+ import { isProcessing } from '../../claude/request-queue.js';
11
+ import { bringCardDown } from '../../telegram/background-activity-card.js';
12
+ import { taskTracker } from '../../telegram/task-tracker.js';
13
+ import { EntityText } from '../../telegram/entities.js';
14
+ import { replyFormatted } from '../../telegram/send.js';
15
+ import { getSessionKeyFromCtx } from '../../utils/session-key.js';
16
+ export async function noteStillRunning(ctx) {
17
+ const keyInfo = getSessionKeyFromCtx(ctx);
18
+ if (!keyInfo)
19
+ return;
20
+ const { sessionKey } = keyInfo;
21
+ // A turn is under way: it closes with the status line, and the card under it.
22
+ if (isProcessing(sessionKey))
23
+ return;
24
+ if (bringCardDown(sessionKey))
25
+ return;
26
+ const running = taskTracker.getBackgroundedCount(sessionKey);
27
+ if (running === 0)
28
+ return;
29
+ const tasks = `${running} task${running === 1 ? '' : 's'}`;
30
+ try {
31
+ await replyFormatted(ctx, new EntityText().italic(`⏳ ${tasks} still running · `).add('/tasks').build(), { disable_notification: true });
32
+ }
33
+ catch (err) {
34
+ console.debug('[RunningNote] Failed to send:', err instanceof Error ? err.message : err);
35
+ }
36
+ }
37
+ /** A command handler that ends with {@link noteStillRunning}. */
38
+ export function withRunningNote(handler) {
39
+ return async (ctx) => {
40
+ await handler(ctx);
41
+ await noteStillRunning(ctx);
42
+ };
43
+ }
44
+ //# sourceMappingURL=running-note.js.map