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,209 @@
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, setAbortController, } from '../../claude/request-queue.js';
11
+ import { getStreamingMode } from './command.handler.js';
12
+ import { maybeSendVoiceReply } from '../../tts/voice-reply.js';
13
+ import { transcribeFile } from '../../audio/transcribe.js';
14
+ import { sendTranscriptResult } from './command.handler.js';
15
+ import { downloadFileSecure, getTelegramFileUrl } from '../../utils/download.js';
16
+ import { sanitizeError, sanitizePath } from '../../utils/sanitize.js';
17
+ import { getSessionKeyFromCtx } from '../../utils/session-key.js';
18
+ import { requireSession } from './session-guard.js';
19
+ import { progressCallbacks, withStreamingTurn } from '../../telegram/streaming-turn.js';
20
+ export async function handleVoice(ctx) {
21
+ const keyInfo = getSessionKeyFromCtx(ctx);
22
+ const messageId = ctx.message?.message_id;
23
+ const messageDate = ctx.message?.date;
24
+ const voice = ctx.message?.voice;
25
+ if (!keyInfo || !messageId || !messageDate || !voice)
26
+ return;
27
+ const { chatId, sessionKey } = keyInfo;
28
+ // Stale/duplicate filters
29
+ if (isStaleMessage(messageDate)) {
30
+ console.log(`[Voice] Ignoring stale voice message ${messageId}`);
31
+ return;
32
+ }
33
+ if (isDuplicate(messageId)) {
34
+ console.log(`[Voice] Ignoring duplicate voice message ${messageId}`);
35
+ return;
36
+ }
37
+ markProcessed(messageId);
38
+ // If this is a reply to the bot's "Transcribe Audio" ForceReply, route to transcribe-only flow
39
+ const replyTo = ctx.message?.reply_to_message;
40
+ if (replyTo && replyTo.from?.is_bot) {
41
+ const replyText = replyTo.text || '';
42
+ if (replyText.includes('Transcribe Audio')) {
43
+ await handleTranscribeOnly(ctx, chatId, messageId, voice);
44
+ return;
45
+ }
46
+ }
47
+ // Check session — fall back to disk if the bot restarted recently.
48
+ const session = await requireSession(ctx, sessionKey);
49
+ if (!session)
50
+ return;
51
+ // Check file size
52
+ const fileSizeBytes = voice.file_size || 0;
53
+ const fileSizeMB = fileSizeBytes / (1024 * 1024);
54
+ if (fileSizeMB > config.VOICE_MAX_FILE_SIZE_MB) {
55
+ await ctx.reply(`❌ Voice note too large (${fileSizeMB.toFixed(1)}MB).\n\nPlease send shorter notes (max ${config.VOICE_MAX_FILE_SIZE_MB}MB).`);
56
+ return;
57
+ }
58
+ // Acknowledge receipt
59
+ const ackMsg = await ctx.reply('🎤 Transcribing...');
60
+ let tempFilePath = null;
61
+ try {
62
+ // Download voice file from Telegram (with retry for transient network errors)
63
+ const file = await ctx.api.getFile(voice.file_id);
64
+ if (!file.file_path) {
65
+ throw new Error('Telegram did not provide a file path.');
66
+ }
67
+ const fileUrl = getTelegramFileUrl(config.TELEGRAM_BOT_TOKEN, file.file_path);
68
+ // In-process fetch: the token-bearing URL never reaches a process argument list.
69
+ const ext = voice.mime_type?.includes('ogg') ? '.ogg' : '.oga';
70
+ tempFilePath = path.join(os.tmpdir(), `telecoder_voice_${messageId}${ext}`);
71
+ await downloadFileSecure(fileUrl, tempFilePath);
72
+ const audioBuffer = fs.readFileSync(tempFilePath);
73
+ if (!audioBuffer.length) {
74
+ throw new Error('Downloaded empty voice file.');
75
+ }
76
+ console.log(`[Voice] Downloaded ${fileSizeMB.toFixed(1)}MB to ${tempFilePath}`);
77
+ // Transcribe using Groq Whisper API (native TypeScript)
78
+ const transcript = await transcribeFile(tempFilePath);
79
+ console.log(`[Voice] Transcript received (${transcript.length} chars)`);
80
+ // Show full transcript if configured (uses smart Telegram chunking)
81
+ if (config.VOICE_SHOW_TRANSCRIPT) {
82
+ try {
83
+ await ctx.api.editMessageText(chatId, ackMsg.message_id, '🎤 Transcript received.');
84
+ }
85
+ catch {
86
+ try {
87
+ await ctx.api.deleteMessage(chatId, ackMsg.message_id);
88
+ }
89
+ catch (e) {
90
+ // Telegram message deletion can fail if already deleted or expired
91
+ console.debug('[Voice] Failed to delete ack message:', e instanceof Error ? e.message : e);
92
+ }
93
+ }
94
+ await messageSender.sendMessage(ctx, `👤 ${transcript}`);
95
+ }
96
+ else {
97
+ // Remove ack message
98
+ try {
99
+ await ctx.api.deleteMessage(chatId, ackMsg.message_id);
100
+ }
101
+ catch (e) {
102
+ console.debug('[Voice] Failed to delete ack message:', e instanceof Error ? e.message : e);
103
+ }
104
+ }
105
+ // Feed transcript into agent
106
+ await queueRequest(sessionKey, transcript, async () => {
107
+ if (getStreamingMode() === 'streaming') {
108
+ await withStreamingTurn(ctx, sessionKey, transcript, async (abortController) => {
109
+ const response = await sendToAgent(sessionKey, transcript, {
110
+ ...progressCallbacks(ctx),
111
+ abortController,
112
+ telegramCtx: ctx,
113
+ });
114
+ await messageSender.finishStreaming(ctx, response.text);
115
+ await relayCatchUpIfMissed(ctx, sessionKey, response.text || '');
116
+ await maybeSendVoiceReply(ctx, response.text);
117
+ await closeTurn(ctx, sessionKey, response, transcript);
118
+ });
119
+ }
120
+ else {
121
+ await ctx.replyWithChatAction('typing');
122
+ const abortController = new AbortController();
123
+ setAbortController(sessionKey, abortController);
124
+ const response = await sendToAgent(sessionKey, transcript, { abortController, telegramCtx: ctx });
125
+ await messageSender.sendMessage(ctx, response.text);
126
+ await relayCatchUpIfMissed(ctx, sessionKey, response.text || '');
127
+ await maybeSendVoiceReply(ctx, response.text);
128
+ await closeTurn(ctx, sessionKey, response, transcript);
129
+ }
130
+ });
131
+ }
132
+ catch (error) {
133
+ if (error.message === 'Queue cleared')
134
+ return;
135
+ const errorMessage = sanitizeError(error);
136
+ console.error('[Voice] Error:', errorMessage);
137
+ // Try to update ack message with error
138
+ try {
139
+ await ctx.api.editMessageText(chatId, ackMsg.message_id, `❌ ${errorMessage}`);
140
+ }
141
+ catch {
142
+ await ctx.reply(`❌ Voice error: ${errorMessage}`);
143
+ }
144
+ }
145
+ finally {
146
+ // Clean up temp file
147
+ if (tempFilePath && fs.existsSync(tempFilePath)) {
148
+ try {
149
+ fs.unlinkSync(tempFilePath);
150
+ console.log(`[Voice] Cleaned up ${sanitizePath(tempFilePath)}`);
151
+ }
152
+ catch (e) {
153
+ console.warn(`[Voice] Cleanup failed for ${sanitizePath(tempFilePath)}:`, sanitizeError(e));
154
+ }
155
+ }
156
+ }
157
+ }
158
+ /**
159
+ * Transcribe-only flow: voice note sent as reply to "Transcribe Audio" ForceReply.
160
+ * Does NOT send transcript to the Claude agent.
161
+ */
162
+ async function handleTranscribeOnly(ctx, chatId, messageId, voice) {
163
+ const ackMsg = await ctx.reply('🎤 Transcribing...');
164
+ let tempFilePath = null;
165
+ try {
166
+ const file = await ctx.api.getFile(voice.file_id);
167
+ if (!file.file_path) {
168
+ throw new Error('Telegram did not provide a file path.');
169
+ }
170
+ const fileUrl = getTelegramFileUrl(config.TELEGRAM_BOT_TOKEN, file.file_path);
171
+ const ext = voice.mime_type?.includes('ogg') ? '.ogg' : '.oga';
172
+ tempFilePath = path.join(os.tmpdir(), `telecoder_transcribe_${messageId}${ext}`);
173
+ await downloadFileSecure(fileUrl, tempFilePath);
174
+ const audioBuffer = fs.readFileSync(tempFilePath);
175
+ if (!audioBuffer.length) {
176
+ throw new Error('Downloaded empty voice file.');
177
+ }
178
+ const transcript = await transcribeFile(tempFilePath);
179
+ // Remove ack
180
+ try {
181
+ await ctx.api.deleteMessage(chatId, ackMsg.message_id);
182
+ }
183
+ catch (e) {
184
+ console.debug('[Transcribe] Failed to delete ack message:', e instanceof Error ? e.message : e);
185
+ }
186
+ await sendTranscriptResult(ctx, transcript);
187
+ }
188
+ catch (error) {
189
+ const errorMessage = sanitizeError(error);
190
+ console.error('[Transcribe] Voice ForceReply error:', errorMessage);
191
+ try {
192
+ await ctx.api.editMessageText(chatId, ackMsg.message_id, `❌ ${errorMessage}`);
193
+ }
194
+ catch {
195
+ await ctx.reply(`❌ Transcription error: ${errorMessage}`);
196
+ }
197
+ }
198
+ finally {
199
+ if (tempFilePath && fs.existsSync(tempFilePath)) {
200
+ try {
201
+ fs.unlinkSync(tempFilePath);
202
+ }
203
+ catch (e) {
204
+ console.warn(`[Transcribe] Cleanup failed for ${sanitizePath(tempFilePath)}:`, sanitizeError(e));
205
+ }
206
+ }
207
+ }
208
+ }
209
+ //# sourceMappingURL=voice.handler.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,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 /fork 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,139 @@
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 (`/status` or `/status@this_bot`)
13
+ * - an answer to one of the bot's ForceReply prompts (/project, /plan, …),
14
+ * where Telegram attaches the reply itself and leaves nowhere to put a
15
+ * mention
16
+ *
17
+ * A plain reply is deliberately not enough: replying is how you quote someone
18
+ * in Telegram, so people reply to the bot to talk *about* what it said as
19
+ * often as to answer it. GROUP_REPLY_IS_MENTION brings the old behaviour back.
20
+ *
21
+ * Private chats are never gated: a DM is addressed to the bot by definition.
22
+ */
23
+ import { config } from '../../config.js';
24
+ import { isForceReplyPrompt } from '../../telegram/force-reply-tracker.js';
25
+ /**
26
+ * Updates this gate has already let through, going round again: a message set
27
+ * aside and then sent. It can't judge one a second time, because stripBotMention
28
+ * has taken out the very mention it would look for.
29
+ */
30
+ const alreadyAddressed = new WeakSet();
31
+ export function markAlreadyAddressed(update) {
32
+ alreadyAddressed.add(update);
33
+ }
34
+ /** A message's text or its media caption, whichever carries the words. */
35
+ function textAndEntities(msg) {
36
+ if (typeof msg.text === 'string')
37
+ return { text: msg.text, entities: msg.entities ?? [] };
38
+ return { text: msg.caption ?? '', entities: msg.caption_entities ?? [] };
39
+ }
40
+ /** True if `@username` (or a text_mention of the bot's user) appears in the message. */
41
+ function mentionsBot({ text, entities }, me) {
42
+ const handle = `@${me.username.toLowerCase()}`;
43
+ return entities.some((e) => {
44
+ if (e.type === 'text_mention')
45
+ return e.user.id === me.id;
46
+ if (e.type !== 'mention')
47
+ return false;
48
+ return text.slice(e.offset, e.offset + e.length).toLowerCase() === handle;
49
+ });
50
+ }
51
+ /**
52
+ * True if the message opens with a slash command this bot should see.
53
+ *
54
+ * `/status@other_bot` in a group with several bots is not ours; a bare
55
+ * `/status` is, and grammy's command handlers decide from there.
56
+ *
57
+ * Telegram also tags the first segment of an absolute path as a command —
58
+ * `/home/me/projects` arrives with a bot_command entity on `/home` — so the
59
+ * token has to be followed by whitespace or nothing to count. Otherwise
60
+ * anyone pasting a path into the group would be talking to the bot.
61
+ */
62
+ function isCommandForBot({ text, entities }, me) {
63
+ const cmd = entities.find((e) => e.type === 'bot_command' && e.offset === 0);
64
+ if (!cmd)
65
+ return false;
66
+ const after = text[cmd.offset + cmd.length];
67
+ if (after !== undefined && !/\s/.test(after))
68
+ return false;
69
+ const token = text.slice(cmd.offset, cmd.offset + cmd.length);
70
+ const at = token.indexOf('@');
71
+ return at === -1 || token.slice(at + 1).toLowerCase() === me.username.toLowerCase();
72
+ }
73
+ /**
74
+ * Whether an update should reach the handlers. Non-message updates (callback
75
+ * queries from inline keyboards, edits, service messages) pass untouched —
76
+ * a button tap is already an explicit interaction with the bot.
77
+ */
78
+ export function isAddressedToBot(ctx) {
79
+ const chatType = ctx.chat?.type;
80
+ if (chatType !== 'group' && chatType !== 'supergroup')
81
+ return true;
82
+ const msg = ctx.message;
83
+ if (!msg)
84
+ return true;
85
+ const content = textAndEntities(msg);
86
+ const repliedTo = msg.reply_to_message;
87
+ if (repliedTo?.from?.id === ctx.me.id) {
88
+ if (config.GROUP_REPLY_IS_MENTION)
89
+ return true;
90
+ // An answer to a ForceReply prompt is addressed by construction: the user
91
+ // typed into a composer the bot opened, and could not have mentioned it.
92
+ if (isForceReplyPrompt(ctx.chat.id, repliedTo.message_id))
93
+ return true;
94
+ }
95
+ return isCommandForBot(content, ctx.me) || mentionsBot(content, ctx.me);
96
+ }
97
+ /**
98
+ * Remove the bot's @mention from the prompt so the agent reads "what's the
99
+ * state of this project?" rather than "@this_bot what's the state of this
100
+ * project?". Nothing downstream reads entities, so rewriting the text in
101
+ * place is safe; a message that is *only* a mention keeps its text, since an
102
+ * empty prompt is worse than a redundant one.
103
+ */
104
+ export function stripBotMention(msg, me) {
105
+ const { text, entities } = textAndEntities(msg);
106
+ if (!text)
107
+ return;
108
+ const handle = `@${me.username.toLowerCase()}`;
109
+ const mentions = entities.filter((e) => e.type === 'mention' && text.slice(e.offset, e.offset + e.length).toLowerCase() === handle);
110
+ if (mentions.length === 0)
111
+ return;
112
+ let stripped = text;
113
+ // Right to left, so each removal leaves the earlier offsets valid.
114
+ for (const e of [...mentions].sort((a, b) => b.offset - a.offset)) {
115
+ stripped = stripped.slice(0, e.offset) + stripped.slice(e.offset + e.length);
116
+ }
117
+ stripped = stripped.replace(/\s{2,}/g, ' ').trim();
118
+ if (!stripped)
119
+ return;
120
+ if (typeof msg.text === 'string')
121
+ msg.text = stripped;
122
+ else
123
+ msg.caption = stripped;
124
+ }
125
+ /**
126
+ * Drop group messages that aren't addressed to the bot. Silent by design —
127
+ * the point is that people can talk to each other without the bot chiming in
128
+ * or logging a line per message.
129
+ */
130
+ export const groupMentionMiddleware = async (ctx, next) => {
131
+ if (!config.GROUP_REQUIRE_MENTION || alreadyAddressed.has(ctx.update))
132
+ return next();
133
+ if (!isAddressedToBot(ctx))
134
+ return;
135
+ if (ctx.message)
136
+ stripBotMention(ctx.message, ctx.me);
137
+ return next();
138
+ };
139
+ //# sourceMappingURL=group-mention.middleware.js.map
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The second gate in a group: not "is this message for the bot?" but "is this
3
+ * person allowed to tell it what to do?".
4
+ *
5
+ * It runs after the mention gate on purpose. A spectator chatting with the
6
+ * humans is not addressing the bot, so it never reaches here and the group
7
+ * stays quiet; only a message that genuinely asks the agent for something gets
8
+ * turned away, and then only once every REMINDER_INTERVAL_MS so a confused
9
+ * newcomer can't be made to flood the chat.
10
+ *
11
+ * There is no third, owner-only tier here. An earlier draft carried a list of
12
+ * command names that only admins could run, but the handlers those names point
13
+ * at are already wrapped in `adminOnly` at registration — and a list sitting a
14
+ * long way from the registrations it governs is one rename away from silently
15
+ * covering nothing. The wrapper is the gate; this file is only about roles.
16
+ */
17
+ import { BoundedMap } from '../../utils/bounded-map.js';
18
+ import { resolveRole } from '../access/group-access.js';
19
+ import { identifyUser } from '../../utils/user-roster.js';
20
+ import { requestAccess } from '../../telegram/access-request.js';
21
+ /** How long a turned-away spectator is left alone before being told again. */
22
+ const REMINDER_INTERVAL_MS = 10 * 60 * 1000;
23
+ const lastReminder = new BoundedMap(500);
24
+ /** True once per chat+user per REMINDER_INTERVAL_MS. */
25
+ function shouldRemind(chatId, userId, now = Date.now()) {
26
+ const key = `${chatId}:${userId}`;
27
+ const previous = lastReminder.get(key);
28
+ if (previous !== undefined && now - previous < REMINDER_INTERVAL_MS)
29
+ return false;
30
+ lastReminder.set(key, now);
31
+ return true;
32
+ }
33
+ /** Forget the throttle state. Test seam. */
34
+ export function resetSpectatorReminders() {
35
+ lastReminder.clear();
36
+ }
37
+ /** Refuse the update, in the quietest channel available. */
38
+ async function refuse(ctx, text, alert) {
39
+ if (ctx.callbackQuery) {
40
+ await ctx.answerCallbackQuery({ text: alert, show_alert: true });
41
+ return;
42
+ }
43
+ await ctx.reply(text);
44
+ }
45
+ export const groupRoleMiddleware = async (ctx, next) => {
46
+ const chatType = ctx.chat?.type;
47
+ const chatId = ctx.chat?.id;
48
+ const userId = ctx.from?.id;
49
+ // A DM only ever reaches here from someone already on the roster: the auth
50
+ // gate admits nobody else to a private chat.
51
+ if (chatType !== 'group' && chatType !== 'supergroup')
52
+ return next();
53
+ if (chatId === undefined || userId === undefined)
54
+ return next();
55
+ // Only the update types that can actually drive the bot are gated: a message
56
+ // or a button tap. Everything else in a group — someone being promoted to
57
+ // admin, the bot's own membership changing, an edit nothing listens for —
58
+ // reaches no handler anyway, and answering those in the chat would have the
59
+ // bot piping up about events nobody addressed to it.
60
+ if (!ctx.message && !ctx.callbackQuery)
61
+ return next();
62
+ if (resolveRole(chatId, userId) !== 'spectator')
63
+ return next();
64
+ console.log(`[access] spectator ${userId} addressed the bot in ${chatId} — ignored`);
65
+ // Put the decision in front of an admin rather than only telling the
66
+ // spectator no. The card carries its own re-ask cooldown, so this cannot
67
+ // become a way to page the admins by typing repeatedly.
68
+ if (ctx.from)
69
+ await requestAccess(ctx, identifyUser(ctx.from));
70
+ if (shouldRemind(chatId, userId)) {
71
+ await refuse(ctx, '👀 You can read along here, but you are not set up to send prompts. ' +
72
+ 'An admin can reply to one of your messages with /allow to change that.', 'You are a spectator in this chat.');
73
+ }
74
+ };
75
+ //# sourceMappingURL=group-role.middleware.js.map