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,41 @@
1
+ /**
2
+ * A view: one message that /tree and /prompts redraw in place as their
3
+ * buttons are tapped — a list keyed by letters, the item a letter opens, back
4
+ * to the list — and the check the buttons that switch conversations share.
5
+ */
6
+ import { isProcessing } from '../../claude/request-queue.js';
7
+ import { editCallbackMessage, replyFormatted } from '../../telegram/send.js';
8
+ /**
9
+ * Send `view` as a reply, or put it in place of the tapped message. A view
10
+ * Telegram won't format goes out as plain text instead (the send helpers
11
+ * retry it), so a formatting slip costs the formatting and not the view.
12
+ */
13
+ export async function sendView(ctx, view, how) {
14
+ const reply_markup = { inline_keyboard: view.keyboard };
15
+ try {
16
+ if (how === 'edit')
17
+ await editCallbackMessage(ctx, view.text, { reply_markup });
18
+ else
19
+ await replyFormatted(ctx, view.text, { reply_markup });
20
+ }
21
+ catch (err) {
22
+ // "message is not modified": the same view, tapped again. Nothing to do.
23
+ if (err instanceof Error && err.message.includes('not modified'))
24
+ return;
25
+ throw err;
26
+ }
27
+ }
28
+ /**
29
+ * Switching conversations under a running reply would cut it off, so the
30
+ * switches wait for it. Says so on the button and returns true when busy.
31
+ */
32
+ export async function refuseWhileBusy(ctx, sessionKey) {
33
+ if (!isProcessing(sessionKey))
34
+ return false;
35
+ await ctx.answerCallbackQuery({
36
+ text: 'A reply is still running here — wait for it to finish, or /cancel it, then tap again.',
37
+ show_alert: true,
38
+ });
39
+ return true;
40
+ }
41
+ //# sourceMappingURL=view.js.map
@@ -0,0 +1,147 @@
1
+ import * as fs from 'fs';
2
+ import * as os from 'os';
3
+ import * as path from 'path';
4
+ import { config } from '../../config.js';
5
+ import { sendToAgent } from '../../providers/provider-router.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 { transcribeFile } from '../../audio/transcribe.js';
12
+ import { downloadFileSecure, getTelegramFileUrl } from '../../utils/download.js';
13
+ import { telegramProxyUrl } from '../../telegram/client-options.js';
14
+ import { sanitizeError, sanitizePath } from '../../utils/sanitize.js';
15
+ import { getSessionKeyFromCtx } from '../../utils/session-key.js';
16
+ import { requireSession } from './session-guard.js';
17
+ import { replyFeatureDisabled, replyVoiceNotSetUp } from './command/shared.js';
18
+ import { progressCallbacks, withStreamingTurn } from '../../telegram/streaming-turn.js';
19
+ export async function handleVoice(ctx) {
20
+ const keyInfo = getSessionKeyFromCtx(ctx);
21
+ const messageId = ctx.message?.message_id;
22
+ const messageDate = ctx.message?.date;
23
+ const voice = ctx.message?.voice;
24
+ if (!keyInfo || !messageId || !messageDate || !voice)
25
+ return;
26
+ const { chatId, sessionKey } = keyInfo;
27
+ // Stale/duplicate filters
28
+ if (isStaleMessage(messageDate)) {
29
+ console.log(`[Voice] Ignoring stale voice message ${messageId}`);
30
+ return;
31
+ }
32
+ if (isDuplicate(messageId)) {
33
+ console.log(`[Voice] Ignoring duplicate voice message ${messageId}`);
34
+ return;
35
+ }
36
+ markProcessed(messageId);
37
+ // TRANSCRIBE_ENABLED=false turns voice notes off.
38
+ if (!config.TRANSCRIBE_ENABLED) {
39
+ await replyFeatureDisabled(ctx, 'Voice transcription');
40
+ return;
41
+ }
42
+ // No Groq key, the common state after declining voice in `telecoder init`:
43
+ // say how to turn it on, instead of an ack and then a raw "not configured" error.
44
+ if (!config.GROQ_API_KEY) {
45
+ await replyVoiceNotSetUp(ctx);
46
+ return;
47
+ }
48
+ // Check session — fall back to disk if the bot restarted recently.
49
+ const session = await requireSession(ctx, sessionKey);
50
+ if (!session)
51
+ return;
52
+ // Check file size
53
+ const fileSizeBytes = voice.file_size || 0;
54
+ const fileSizeMB = fileSizeBytes / (1024 * 1024);
55
+ if (fileSizeMB > config.VOICE_MAX_FILE_SIZE_MB) {
56
+ await ctx.reply(`❌ Voice note too large (${fileSizeMB.toFixed(1)}MB).\n\nPlease send shorter notes (max ${config.VOICE_MAX_FILE_SIZE_MB}MB).`);
57
+ return;
58
+ }
59
+ // Acknowledge receipt
60
+ const ackMsg = await ctx.reply('🎤 Transcribing...');
61
+ let tempFilePath = null;
62
+ try {
63
+ // Download voice file from Telegram (with retry for transient network errors)
64
+ const file = await ctx.api.getFile(voice.file_id);
65
+ if (!file.file_path) {
66
+ throw new Error('Telegram did not provide a file path.');
67
+ }
68
+ const fileUrl = getTelegramFileUrl(config.TELEGRAM_BOT_TOKEN, file.file_path);
69
+ // Fetched in this process: the token-bearing URL never reaches a process
70
+ // argument list. Through the proxy, when the bot reaches Telegram by one.
71
+ const ext = voice.mime_type?.includes('ogg') ? '.ogg' : '.oga';
72
+ tempFilePath = path.join(os.tmpdir(), `telecoder_voice_${messageId}${ext}`);
73
+ await downloadFileSecure(fileUrl, tempFilePath, { proxyUrl: telegramProxyUrl() });
74
+ const audioBuffer = fs.readFileSync(tempFilePath);
75
+ if (!audioBuffer.length) {
76
+ throw new Error('Downloaded empty voice file.');
77
+ }
78
+ console.log(`[Voice] Downloaded ${fileSizeMB.toFixed(1)}MB to ${tempFilePath}`);
79
+ // Transcribe using Groq Whisper API (native TypeScript)
80
+ const transcript = await transcribeFile(tempFilePath);
81
+ console.log(`[Voice] Transcript received (${transcript.length} chars)`);
82
+ // Show full transcript if configured (uses smart Telegram chunking)
83
+ if (config.VOICE_SHOW_TRANSCRIPT) {
84
+ try {
85
+ await ctx.api.editMessageText(chatId, ackMsg.message_id, '🎤 Transcript received.');
86
+ }
87
+ catch {
88
+ try {
89
+ await ctx.api.deleteMessage(chatId, ackMsg.message_id);
90
+ }
91
+ catch (e) {
92
+ // Telegram message deletion can fail if already deleted or expired
93
+ console.debug('[Voice] Failed to delete ack message:', e instanceof Error ? e.message : e);
94
+ }
95
+ }
96
+ await messageSender.sendMessage(ctx, `👤 ${transcript}`);
97
+ }
98
+ else {
99
+ // Remove ack message
100
+ try {
101
+ await ctx.api.deleteMessage(chatId, ackMsg.message_id);
102
+ }
103
+ catch (e) {
104
+ console.debug('[Voice] Failed to delete ack message:', e instanceof Error ? e.message : e);
105
+ }
106
+ }
107
+ // Feed transcript into agent
108
+ await queueRequest(sessionKey, transcript, async () => {
109
+ await withStreamingTurn(ctx, sessionKey, transcript, async (abortController) => {
110
+ const response = await sendToAgent(sessionKey, transcript, {
111
+ ...progressCallbacks(ctx),
112
+ abortController,
113
+ telegramCtx: ctx,
114
+ });
115
+ await messageSender.finishStreaming(ctx, response.text);
116
+ await relayCatchUpIfMissed(ctx, sessionKey, response.text || '');
117
+ await closeTurn(ctx, sessionKey, response, transcript);
118
+ });
119
+ });
120
+ }
121
+ catch (error) {
122
+ if (error.message === 'Queue cleared')
123
+ return;
124
+ const errorMessage = sanitizeError(error);
125
+ console.error('[Voice] Error:', errorMessage);
126
+ // Try to update ack message with error
127
+ try {
128
+ await ctx.api.editMessageText(chatId, ackMsg.message_id, `❌ ${errorMessage}`);
129
+ }
130
+ catch {
131
+ await ctx.reply(`❌ Voice error: ${errorMessage}`);
132
+ }
133
+ }
134
+ finally {
135
+ // Clean up temp file
136
+ if (tempFilePath && fs.existsSync(tempFilePath)) {
137
+ try {
138
+ fs.unlinkSync(tempFilePath);
139
+ console.log(`[Voice] Cleaned up ${sanitizePath(tempFilePath)}`);
140
+ }
141
+ catch (e) {
142
+ console.warn(`[Voice] Cleanup failed for ${sanitizePath(tempFilePath)}:`, sanitizeError(e));
143
+ }
144
+ }
145
+ }
146
+ }
147
+ //# sourceMappingURL=voice.handler.js.map
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Threads marked with /threadkeep, which /threadcleanup leaves alone.
3
+ *
4
+ * A thread is kept until /threadkeep off, or until it's deleted anyway (by
5
+ * /threaddelete, or by hand): a deleted thread has nothing left to keep.
6
+ * Kept per bot, since each bot has its own threads.
7
+ */
8
+ import * as path from 'path';
9
+ import { z } from 'zod';
10
+ import { BOT_ID } from '../config.js';
11
+ import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
12
+ const fileSchema = z.object({ threads: z.array(z.string()) });
13
+ /** What goes in front of a kept thread's name, where the bot names it. */
14
+ export const KEEP_MARK = '📌 ';
15
+ let keptSet;
16
+ function stateFile() {
17
+ return path.join(getStateDir(), `kept-threads-${BOT_ID}.json`);
18
+ }
19
+ function kept() {
20
+ keptSet ??= new Set(readJsonFile(stateFile(), fileSchema, 'KeptThreads')?.threads ?? []);
21
+ return keptSet;
22
+ }
23
+ function save() {
24
+ ensureStateDir(getStateDir(), 'KeptThreads');
25
+ writeJsonFile(stateFile(), { threads: [...kept()] }, 'KeptThreads');
26
+ }
27
+ export function isThreadKept(sessionKey) {
28
+ return kept().has(sessionKey);
29
+ }
30
+ /** Mark or unmark a thread. Whether that changed anything. */
31
+ export function setThreadKept(sessionKey, keep) {
32
+ if (kept().has(sessionKey) === keep)
33
+ return false;
34
+ if (keep)
35
+ kept().add(sessionKey);
36
+ else
37
+ kept().delete(sessionKey);
38
+ save();
39
+ return true;
40
+ }
41
+ /** Drop the mark of a thread that no longer exists. */
42
+ export function forgetKeptThread(sessionKey) {
43
+ if (kept().delete(sessionKey))
44
+ save();
45
+ }
46
+ /** Test seam: forget every mark, on disk too. */
47
+ export function resetKeptThreadsForTest() {
48
+ keptSet = new Set();
49
+ save();
50
+ }
51
+ //# sourceMappingURL=kept-threads.js.map
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The admin guard for handlers that act on the bot rather than on a
3
+ * conversation.
4
+ *
5
+ * Restarting the bot, rebuilding it, pulling an update, or switching the
6
+ * transport are not "things you do with the agent" — they are things you do to
7
+ * everyone else's session — and a restart or rebuild cuts short every turn
8
+ * that is waiting on someone's answer, the permission gate's prompts included.
9
+ *
10
+ * Wrapping is per handler rather than one middleware matching a name list,
11
+ * because the list would live a long way from the registrations it governs and
12
+ * would silently stop covering a command the day one gets renamed.
13
+ */
14
+ import { isAdmin, isApprover } from '../../utils/admins.js';
15
+ const DENIAL = 'Admins only — ask an admin of this bot to run it.';
16
+ const APPROVER_DENIAL = 'Admins and approvers only — ask one of them to run it.';
17
+ /**
18
+ * Wrap a command or callback handler so only admins reach it. Non-admins get a
19
+ * toast (callback) or a reply (command); with no admin subset configured every
20
+ * allowed user is an admin, so this is transparent on a solo bot.
21
+ */
22
+ function guard(handler, allowed, denial, label) {
23
+ return async (ctx) => {
24
+ if (allowed(ctx.from?.id)) {
25
+ await handler(ctx);
26
+ return;
27
+ }
28
+ console.log(`[admins] DENIED user:${ctx.from?.id ?? 'unknown'} chat:${ctx.chat?.id ?? 'unknown'} ${label} handler`);
29
+ if (ctx.callbackQuery) {
30
+ await ctx.answerCallbackQuery({ text: `\u{1f512} ${denial}`, show_alert: true }).catch(() => { });
31
+ return;
32
+ }
33
+ await ctx.reply(`\u{1f512} ${denial}`).catch(() => { });
34
+ };
35
+ }
36
+ /**
37
+ * Wrap a handler so admins and approvers reach it, and guests do not.
38
+ *
39
+ * For the things an approver is trusted with beyond answering a single prompt
40
+ * — opening an auto-approve window — which is a decision about prompts rather
41
+ * than a power over the bot, and so does not belong behind {@link adminOnly}.
42
+ */
43
+ export function adminOrApproverOnly(handler) {
44
+ return guard(handler, (userId) => isAdmin(userId) || isApprover(userId), APPROVER_DENIAL, 'admin-or-approver');
45
+ }
46
+ export function adminOnly(handler) {
47
+ return guard(handler, isAdmin, DENIAL, 'admin-only');
48
+ }
49
+ //# sourceMappingURL=admin-only.js.map
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Albums: files sent together, gathered into one message.
3
+ *
4
+ * Telegram has no message holding several files. Files picked together and sent
5
+ * with "Group items" on arrive one message each, sharing a `media_group_id`,
6
+ * with the caption on just one of them. Taken one at a time, each became a turn
7
+ * of its own: Claude answered once per file, never knowing the others came with
8
+ * it, and all but one went without the caption.
9
+ *
10
+ * So the parts are gathered here into the first to arrive, which carries the
11
+ * others in `album` and goes on alone. handlers/album.handler.ts sends the lot
12
+ * as one prompt. The others leave the stream.
13
+ *
14
+ * The caption moves onto that first part when another has it. The group
15
+ * mention gate reads it to decide whether a message is for the bot, and this
16
+ * runs ahead of the gate, since a part without the caption would fail it on its
17
+ * own. It runs behind auth, so only an allowed sender's parts are gathered, and
18
+ * ahead of sequentialize, like the message batcher: the parts would otherwise
19
+ * wait there behind the first one's turn.
20
+ *
21
+ * The parts ride on the message itself, so they stay with a message set aside
22
+ * and sent later, which comes back through here and goes straight on.
23
+ */
24
+ /**
25
+ * How long after the last part an album is taken as complete. A client uploads
26
+ * every file before it sends any of the messages, so the parts arrive within
27
+ * moments of each other.
28
+ */
29
+ export const ALBUM_WAIT_MS = 1000;
30
+ const albums = new Map();
31
+ /** The other parts of the album this message leads, or undefined when it leads none. */
32
+ export function albumParts(message) {
33
+ return message?.album;
34
+ }
35
+ export function createAlbumMiddleware() {
36
+ return async (ctx, next) => {
37
+ const message = ctx.message;
38
+ const groupId = message?.media_group_id;
39
+ if (!message || !groupId || albumParts(message) || !ctx.chat)
40
+ return next();
41
+ const key = `${ctx.chat.id}:${groupId}`;
42
+ const existing = albums.get(key);
43
+ if (existing) {
44
+ existing.parts.push(message);
45
+ existing.timer.refresh();
46
+ return; // absorbed into the album's first part
47
+ }
48
+ const parts = [];
49
+ await new Promise((resolve) => {
50
+ const timer = setTimeout(() => {
51
+ albums.delete(key);
52
+ resolve();
53
+ }, ALBUM_WAIT_MS);
54
+ albums.set(key, { parts, timer, resolve });
55
+ });
56
+ if (parts.length > 0) {
57
+ const captioned = message.caption ? undefined : parts.find((part) => part.caption);
58
+ if (captioned) {
59
+ Object.assign(message, { caption: captioned.caption, caption_entities: captioned.caption_entities });
60
+ delete captioned.caption;
61
+ delete captioned.caption_entities;
62
+ }
63
+ console.log(`[Album] Gathered ${parts.length + 1} files sent together`);
64
+ Object.assign(message, { album: parts });
65
+ }
66
+ return next();
67
+ };
68
+ }
69
+ //# sourceMappingURL=album-collector.js.map
@@ -0,0 +1,122 @@
1
+ import { config } from '../../config.js';
2
+ import { GROUP_ANONYMOUS_BOT_ID, isAdmin } from '../../utils/admins.js';
3
+ import { isAllowedUser, noteSeenUser, identifyUser as identify } from '../../utils/user-roster.js';
4
+ import { requestAccess } from '../../telegram/access-request.js';
5
+ /**
6
+ * Log authentication attempt for security auditing.
7
+ * Avoids logging message content to protect privacy.
8
+ */
9
+ function logAuthAttempt(success, userId, username, chatType) {
10
+ const timestamp = new Date().toISOString();
11
+ const userInfo = userId ? `user:${userId}` : 'user:unknown';
12
+ const usernameInfo = username ? `@${username}` : '';
13
+ const status = success ? 'ALLOWED' : 'DENIED';
14
+ console.log(`[auth] ${timestamp} ${status} ${userInfo} ${usernameInfo} chat:${chatType || 'unknown'}`);
15
+ }
16
+ /**
17
+ * Someone was added to, or joined, an allow-listed group.
18
+ *
19
+ * This is the other half of "how does an admin find out who to allow": the
20
+ * `@username` in `/allow @someone` can only ever resolve against people the bot
21
+ * has watched go by, and waiting for a newcomer to speak first means the admin
22
+ * cannot admit them until after they have been turned away once. The join
23
+ * itself is the earlier, better moment.
24
+ *
25
+ * Service messages stop here either way — nothing downstream handles them, and
26
+ * the adder is not necessarily an allowed user, so letting one fall through to
27
+ * the ordinary denial would answer a join with "⛔ You are not authorized".
28
+ */
29
+ async function handleNewMembers(ctx, members) {
30
+ const chatId = ctx.chat?.id;
31
+ if (chatId === undefined || !config.ALLOWED_GROUP_IDS.includes(chatId))
32
+ return;
33
+ for (const member of members) {
34
+ if (member.is_bot)
35
+ continue;
36
+ const identity = identify(member);
37
+ noteSeenUser(identity, chatId);
38
+ if (!isAllowedUser(member.id)) {
39
+ await requestAccess(ctx, identity);
40
+ }
41
+ }
42
+ }
43
+ export async function authMiddleware(ctx, next) {
44
+ const userId = ctx.from?.id;
45
+ const username = ctx.from?.username;
46
+ const chatType = ctx.chat?.type;
47
+ const chatId = ctx.chat?.id;
48
+ if (!userId) {
49
+ logAuthAttempt(false, undefined, undefined, chatType);
50
+ return;
51
+ }
52
+ // The bot's own doings come back as updates too: opening a thread in a
53
+ // private chat delivers its forum_topic_created service message, sent by the
54
+ // bot. Nothing downstream wants those, and refusing one answered the bot with
55
+ // "⛔ You are not authorized" as the first message of every /branch and
56
+ // /spinoff thread.
57
+ if (userId === ctx.me?.id)
58
+ return;
59
+ const newMembers = ctx.message?.new_chat_members;
60
+ if (newMembers && newMembers.length > 0) {
61
+ await handleNewMembers(ctx, newMembers);
62
+ return;
63
+ }
64
+ // Allow anonymous admins in explicitly allowed groups (forum topics)
65
+ if (userId === GROUP_ANONYMOUS_BOT_ID && chatId && config.ALLOWED_GROUP_IDS.includes(chatId)) {
66
+ logAuthAttempt(true, userId, username, chatType);
67
+ await next();
68
+ return;
69
+ }
70
+ // Membership of an allow-listed group is the coarse gate: an invite-only
71
+ // group is a vetted room, and being in it is enough to reach the bot at all.
72
+ // What that membership is *worth* is the finer question, and it is answered
73
+ // downstream by group-role.middleware — under GROUP_MEMBERS_DEFAULT, which
74
+ // ships as `spectator`, being in the room only buys the right to read along.
75
+ //
76
+ // Fails closed on a missing chat id: an update we can't place is not one we
77
+ // can say is inside the group.
78
+ const inAllowedGroup = chatId !== undefined && config.ALLOWED_GROUP_IDS.includes(chatId);
79
+ // Record everyone the shared group sees, on the roster or not. `/allow
80
+ // @handle` can only resolve against handles the bot has watched go by, and
81
+ // the person an admin is about to name is precisely the one not admitted
82
+ // yet; /users lists them as pending on the strength of this.
83
+ if (inAllowedGroup && ctx.from)
84
+ noteSeenUser(identify(ctx.from), chatId);
85
+ // Outside the shared group the roster is the whole answer. Inside it, a
86
+ // stranger is not refused here — they fall through to the role gate, which
87
+ // turns them away only if they actually address the bot, so the group stays
88
+ // quiet while people talk to each other.
89
+ if (!isAllowedUser(userId) && !inAllowedGroup) {
90
+ logAuthAttempt(false, userId, username, chatType);
91
+ // A group nobody allow-listed gets no reply at all. With privacy mode off
92
+ // the bot sees every message there, and answering each one with a denial
93
+ // turns someone else's group chat into a wall of "not authorized".
94
+ if (chatType !== 'private')
95
+ return;
96
+ const outcome = ctx.from ? await requestAccess(ctx, identify(ctx.from)) : 'not-asked';
97
+ // The id is the one thing the owner needs and the sender can't easily
98
+ // find, so the denial carries it, and the log repeats it for the owner.
99
+ console.log(`[auth] To let user ${userId}${username ? ` (@${username})` : ''} in, add ${userId} to ALLOWED_USER_IDS ` +
100
+ 'or /allow them from an admin chat.');
101
+ await ctx.reply(outcome === 'pending'
102
+ ? `⛔ Not authorized yet — an admin has been asked to let you in. Your Telegram ID is ${userId}.`
103
+ : `⛔ You are not authorized to use this bot. Your Telegram ID is ${userId}. ` +
104
+ 'Ask the owner to add it to ALLOWED_USER_IDS.').catch(() => { });
105
+ return;
106
+ }
107
+ // Keep display names current for /users. In the group this already ran.
108
+ if (!inAllowedGroup && ctx.from)
109
+ noteSeenUser(identify(ctx.from), chatId);
110
+ // Confine non-admins to the allow-listed groups. A bot shared in a group is
111
+ // shared on the understanding that the owner can see what is asked of it, and
112
+ // a private chat with the same bot is the one place they cannot. Admins are
113
+ // exempt — being able to DM your own bot is the normal way to use it.
114
+ if (config.RESTRICT_TO_GROUPS && !isAdmin(userId) && !inAllowedGroup) {
115
+ logAuthAttempt(false, userId, username, chatType);
116
+ await ctx.reply('⛔ This bot only works in its shared group chat, not in private messages.');
117
+ return;
118
+ }
119
+ logAuthAttempt(true, userId, username, chatType);
120
+ await next();
121
+ }
122
+ //# sourceMappingURL=auth.middleware.js.map
@@ -0,0 +1,145 @@
1
+ /**
2
+ * "Is this message actually for the bot?" — the group-chat gate.
3
+ *
4
+ * With Telegram's privacy mode disabled (required for the bot to see ordinary
5
+ * text at all), every message in the group reaches us, including people
6
+ * talking to each other. Running an agent turn on all of it makes the bot
7
+ * unusable in a group that has human conversation in it, so in groups a
8
+ * message has to address the bot to get through.
9
+ *
10
+ * Addressed means one of:
11
+ * - an @mention of this bot's username
12
+ * - a slash command meant for this bot (`/info` or `/info@this_bot`)
13
+ * - an answer to one of the bot's ForceReply prompts (/dir), where Telegram attaches the reply itself and leaves nowhere to put a
14
+ * mention
15
+ * - a reply to a question Claude is waiting on: an answer in the sender's
16
+ * own words (see claude/typed-answer.ts)
17
+ *
18
+ * A plain reply is deliberately not enough: replying is how you quote someone
19
+ * in Telegram, so people reply to the bot to talk *about* what it said as
20
+ * often as to answer it. GROUP_REPLY_IS_MENTION brings the old behaviour back.
21
+ *
22
+ * Private chats are never gated: a DM is addressed to the bot by definition.
23
+ */
24
+ import { config } from '../../config.js';
25
+ import { isForceReplyPrompt } from '../../telegram/force-reply-tracker.js';
26
+ import { isOpenQuestionMessage } from '../../claude/typed-answer.js';
27
+ /**
28
+ * Updates this gate has already let through, going round again: a message set
29
+ * aside and then sent. It can't judge one a second time, because stripBotMention
30
+ * has taken out the very mention it would look for.
31
+ */
32
+ const alreadyAddressed = new WeakSet();
33
+ export function markAlreadyAddressed(update) {
34
+ alreadyAddressed.add(update);
35
+ }
36
+ /** A message's text or its media caption, whichever carries the words. */
37
+ function textAndEntities(msg) {
38
+ if (typeof msg.text === 'string')
39
+ return { text: msg.text, entities: msg.entities ?? [] };
40
+ return { text: msg.caption ?? '', entities: msg.caption_entities ?? [] };
41
+ }
42
+ /** True if `@username` (or a text_mention of the bot's user) appears in the message. */
43
+ function mentionsBot({ text, entities }, me) {
44
+ const handle = `@${me.username.toLowerCase()}`;
45
+ return entities.some((e) => {
46
+ if (e.type === 'text_mention')
47
+ return e.user.id === me.id;
48
+ if (e.type !== 'mention')
49
+ return false;
50
+ return text.slice(e.offset, e.offset + e.length).toLowerCase() === handle;
51
+ });
52
+ }
53
+ /**
54
+ * True if the message opens with a slash command this bot should see.
55
+ *
56
+ * `/info@other_bot` in a group with several bots is not ours; a bare
57
+ * `/info` is, and grammy's command handlers decide from there.
58
+ *
59
+ * Telegram also tags the first segment of an absolute path as a command —
60
+ * `/home/me/projects` arrives with a bot_command entity on `/home` — so the
61
+ * token has to be followed by whitespace or nothing to count. Otherwise
62
+ * anyone pasting a path into the group would be talking to the bot.
63
+ */
64
+ function isCommandForBot({ text, entities }, me) {
65
+ const cmd = entities.find((e) => e.type === 'bot_command' && e.offset === 0);
66
+ if (!cmd)
67
+ return false;
68
+ const after = text[cmd.offset + cmd.length];
69
+ if (after !== undefined && !/\s/.test(after))
70
+ return false;
71
+ const token = text.slice(cmd.offset, cmd.offset + cmd.length);
72
+ const at = token.indexOf('@');
73
+ return at === -1 || token.slice(at + 1).toLowerCase() === me.username.toLowerCase();
74
+ }
75
+ /**
76
+ * Whether an update should reach the handlers. Non-message updates (callback
77
+ * queries from inline keyboards, edits, service messages) pass untouched —
78
+ * a button tap is already an explicit interaction with the bot.
79
+ */
80
+ export function isAddressedToBot(ctx) {
81
+ const chatType = ctx.chat?.type;
82
+ if (chatType !== 'group' && chatType !== 'supergroup')
83
+ return true;
84
+ const msg = ctx.message;
85
+ if (!msg)
86
+ return true;
87
+ const content = textAndEntities(msg);
88
+ const repliedTo = msg.reply_to_message;
89
+ if (repliedTo?.from?.id === ctx.me.id) {
90
+ if (config.GROUP_REPLY_IS_MENTION)
91
+ return true;
92
+ // An answer to a ForceReply prompt is addressed by construction: the user
93
+ // typed into a composer the bot opened, and could not have mentioned it.
94
+ if (isForceReplyPrompt(ctx.chat.id, repliedTo.message_id))
95
+ return true;
96
+ // Likewise a reply to a question Claude is waiting on: quoting one to
97
+ // talk about it can wait until it's answered.
98
+ if (isOpenQuestionMessage(ctx.chat.id, repliedTo.message_id))
99
+ return true;
100
+ }
101
+ return isCommandForBot(content, ctx.me) || mentionsBot(content, ctx.me);
102
+ }
103
+ /**
104
+ * Remove the bot's @mention from the prompt so the agent reads "what's the
105
+ * state of this project?" rather than "@this_bot what's the state of this
106
+ * project?". Nothing downstream reads entities, so rewriting the text in
107
+ * place is safe; a message that is *only* a mention keeps its text, since an
108
+ * empty prompt is worse than a redundant one.
109
+ */
110
+ export function stripBotMention(msg, me) {
111
+ const { text, entities } = textAndEntities(msg);
112
+ if (!text)
113
+ return;
114
+ const handle = `@${me.username.toLowerCase()}`;
115
+ const mentions = entities.filter((e) => e.type === 'mention' && text.slice(e.offset, e.offset + e.length).toLowerCase() === handle);
116
+ if (mentions.length === 0)
117
+ return;
118
+ let stripped = text;
119
+ // Right to left, so each removal leaves the earlier offsets valid.
120
+ for (const e of [...mentions].sort((a, b) => b.offset - a.offset)) {
121
+ stripped = stripped.slice(0, e.offset) + stripped.slice(e.offset + e.length);
122
+ }
123
+ stripped = stripped.replace(/\s{2,}/g, ' ').trim();
124
+ if (!stripped)
125
+ return;
126
+ if (typeof msg.text === 'string')
127
+ msg.text = stripped;
128
+ else
129
+ msg.caption = stripped;
130
+ }
131
+ /**
132
+ * Drop group messages that aren't addressed to the bot. Silent by design —
133
+ * the point is that people can talk to each other without the bot chiming in
134
+ * or logging a line per message.
135
+ */
136
+ export const groupMentionMiddleware = async (ctx, next) => {
137
+ if (!config.GROUP_REQUIRE_MENTION || alreadyAddressed.has(ctx.update))
138
+ return next();
139
+ if (!isAddressedToBot(ctx))
140
+ return;
141
+ if (ctx.message)
142
+ stripBotMention(ctx.message, ctx.me);
143
+ return next();
144
+ };
145
+ //# sourceMappingURL=group-mention.middleware.js.map