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,179 @@
1
+ /**
2
+ * "Did you mean" for a mistyped bot command.
3
+ *
4
+ * A slash command the bot never registered falls through to the agent as a
5
+ * prompt, so `/task` or `/shel` ends up typed into Claude, which answers
6
+ * "unknown command" at best. Before that happens, a token within a typo of a
7
+ * bot command is checked against what Claude Code accepts here (its own
8
+ * commands, skills, plugins and `.claude/commands/`), and when Claude doesn't
9
+ * know it either the likely commands come back as buttons. A tap re-sends the
10
+ * message with the corrected command and the arguments as typed, back through
11
+ * the whole middleware chain as if the user had typed it.
12
+ *
13
+ * Anything Claude Code does know, or that we can't check, goes through as
14
+ * before: the fallback only ever answers for a name nobody accepts. What
15
+ * Claude Code knows is the headless probe's list plus CLAUDE_CODE_COMMAND_NAMES,
16
+ * the interactive-only commands and aliases the probe can't see. A name both
17
+ * miss still has a button that sends it to Claude Code as typed.
18
+ */
19
+ import { InlineKeyboard } from 'grammy';
20
+ import { sessionManager } from '../../claude/session-manager.js';
21
+ import { getBotCommandNames, getForwardedCommandNames } from '../../claude/command-parser.js';
22
+ import { getAvailableCommands, getCachedAvailableCommands } from '../../claude/available-commands.js';
23
+ import { getProjectCommands } from '../../claude/project-commands.js';
24
+ import { resolvePtyClaudeBin } from '../../utils/resolve-claude-bin.js';
25
+ import { CLAUDE_CODE_COMMAND_NAMES } from '../../claude/native-commands.js';
26
+ import { sanitizeError } from '../../utils/sanitize.js';
27
+ import { markAlreadyAddressed } from '../middleware/group-mention.middleware.js';
28
+ import { buildUnknownCommandMessage, findCommandFix } from '../command-catalog.js';
29
+ import { EntityText } from '../../telegram/entities.js';
30
+ import { editCallbackMessage, replyFormatted } from '../../telegram/send.js';
31
+ import { parseCallback } from './command/shared.js';
32
+ /** Keyed by the notice that carries the buttons. */
33
+ const pending = new Map();
34
+ const PENDING_TTL_MS = 15 * 60 * 1000;
35
+ const PENDING_MAX = 200;
36
+ /** How long to wait for a cold command probe before letting the message through. */
37
+ const PROBE_WAIT_MS = 6000;
38
+ const CALLBACK_PREFIX = 'cmdfix:';
39
+ /** The button that sends the message as it was typed, to Claude Code. */
40
+ const AS_TYPED = 'typed';
41
+ /** Messages the "as typed" button re-sent, which the fallback lets through. */
42
+ const letThrough = new Set();
43
+ const BUTTON_MAX = 48;
44
+ let botRef;
45
+ /** Called once, so a tap can send the corrected message back through the bot. */
46
+ export function initCommandFallback(bot) {
47
+ botRef = bot;
48
+ }
49
+ function key(chatId, messageId) {
50
+ return `${chatId}:${messageId}`;
51
+ }
52
+ function prune() {
53
+ const now = Date.now();
54
+ for (const [k, entry] of pending) {
55
+ if (entry.expiresAt < now)
56
+ pending.delete(k);
57
+ }
58
+ while (pending.size >= PENDING_MAX) {
59
+ const oldest = pending.keys().next().value;
60
+ if (oldest === undefined)
61
+ break;
62
+ pending.delete(oldest);
63
+ }
64
+ }
65
+ function commandLine(command, args) {
66
+ return args ? `/${command} ${args}` : `/${command}`;
67
+ }
68
+ /** The command line, cut to fit on a button. */
69
+ function shortLine(command, args) {
70
+ const line = commandLine(command, args);
71
+ return line.length > BUTTON_MAX ? line.slice(0, BUTTON_MAX - 1) + '…' : line;
72
+ }
73
+ function buttonLabel(command, args) {
74
+ return `▶️ ${shortLine(command, args)}`;
75
+ }
76
+ function delay(ms) {
77
+ return new Promise((resolve) => setTimeout(() => resolve(undefined), ms));
78
+ }
79
+ /**
80
+ * Answer a mistyped command with the likely ones. Returns true when it did,
81
+ * false when the message should go on to the agent as usual.
82
+ */
83
+ export async function offerCommandFix(ctx, sessionKey, text) {
84
+ const message = ctx.message;
85
+ if (message && letThrough.delete(key(message.chat.id, message.message_id)))
86
+ return false;
87
+ const fix = findCommandFix(text, {
88
+ botNames: getBotCommandNames(),
89
+ forwarded: getForwardedCommandNames(),
90
+ });
91
+ if (!fix)
92
+ return false;
93
+ if (CLAUDE_CODE_COMMAND_NAMES.has(fix.token))
94
+ return false;
95
+ const session = sessionManager.getSession(sessionKey);
96
+ if (!session)
97
+ return false;
98
+ const workingDirectory = session.workingDirectory;
99
+ // A project command added since the last probe isn't in the snapshot yet.
100
+ if (getProjectCommands(workingDirectory).some((c) => c.name === fix.token))
101
+ return false;
102
+ const executable = resolvePtyClaudeBin();
103
+ let snapshot = getCachedAvailableCommands(workingDirectory, executable);
104
+ if (!snapshot) {
105
+ // A cold cache means a probe — a fresh headless process — so show typing
106
+ // rather than leave the chat silent; the probe keeps running past the
107
+ // wait and fills the cache for next time.
108
+ const typing = ctx.replyWithChatAction?.('typing');
109
+ snapshot = await Promise.race([getAvailableCommands(workingDirectory, executable), delay(PROBE_WAIT_MS)]);
110
+ await typing?.catch(() => { });
111
+ }
112
+ // Without Claude's list there's no telling a typo from a command we don't
113
+ // know about, so let it through.
114
+ if (!snapshot)
115
+ return false;
116
+ if (snapshot.slashCommands.includes(fix.token))
117
+ return false;
118
+ const keyboard = new InlineKeyboard();
119
+ fix.suggestions.forEach((s, i) => {
120
+ keyboard.text(buttonLabel(s.command, fix.args), `${CALLBACK_PREFIX}${i}`).row();
121
+ });
122
+ keyboard.text(`⤵️ ${shortLine(fix.token, '')} to Claude Code, as typed`, `${CALLBACK_PREFIX}${AS_TYPED}`).row();
123
+ const sent = await replyFormatted(ctx, buildUnknownCommandMessage(fix.token, fix.suggestions), {
124
+ reply_markup: keyboard,
125
+ });
126
+ prune();
127
+ pending.set(key(sent.chat.id, sent.message_id), {
128
+ update: ctx.update,
129
+ fix,
130
+ expiresAt: Date.now() + PENDING_TTL_MS,
131
+ });
132
+ console.log(`[Commands] /${fix.token} isn't a command; suggested ${fix.suggestions.map((s) => '/' + s.command).join(', ')}`);
133
+ return true;
134
+ }
135
+ /** A tap on a suggestion: send the corrected message as if it had been typed. */
136
+ export async function handleCommandFixCallback(ctx) {
137
+ const parsed = parseCallback(ctx, CALLBACK_PREFIX);
138
+ const notice = ctx.callbackQuery?.message;
139
+ if (!parsed || !notice)
140
+ return;
141
+ const k = key(notice.chat.id, notice.message_id);
142
+ const entry = pending.get(k);
143
+ const picked = parsed.data.slice(CALLBACK_PREFIX.length);
144
+ const asTyped = picked === AS_TYPED;
145
+ const choice = asTyped ? undefined : entry?.fix.suggestions[Number(picked)];
146
+ if (!entry || (!choice && !asTyped) || entry.expiresAt < Date.now() || !botRef) {
147
+ await ctx.answerCallbackQuery({ text: 'That suggestion has expired — type the command again.' });
148
+ return;
149
+ }
150
+ pending.delete(k);
151
+ const update = structuredClone(entry.update);
152
+ const text = choice ? commandLine(choice.command, entry.fix.args) : update.message.text ?? '';
153
+ if (choice) {
154
+ update.message.text = text;
155
+ // grammY finds commands by their entity, so the new token needs one.
156
+ update.message.entities = [{ type: 'bot_command', offset: 0, length: choice.command.length + 1 }];
157
+ }
158
+ update.message.date = Math.floor(Date.now() / 1000);
159
+ // The typo's own id has been through the duplicate filter once already;
160
+ // the notice's never arrived as a message, so it is free.
161
+ update.message.message_id = notice.message_id;
162
+ // Whoever tapped sends it, under their own access.
163
+ if (ctx.from)
164
+ update.message.from = ctx.from;
165
+ // As typed, it goes past this fallback to Claude Code.
166
+ if (asTyped)
167
+ letThrough.add(key(update.message.chat.id, update.message.message_id));
168
+ await ctx.answerCallbackQuery();
169
+ await editCallbackMessage(ctx, new EntityText().add('▶️ ').code(text).build())
170
+ .catch((err) => console.warn('[Commands] Could not update the suggestion notice:', sanitizeError(err)));
171
+ markAlreadyAddressed(update);
172
+ console.log(asTyped
173
+ ? `[Commands] Sending /${entry.fix.token} to Claude Code as typed`
174
+ : `[Commands] Sending ${text.split(' ')[0]} for a mistyped /${entry.fix.token}`);
175
+ void botRef.handleUpdate(update).catch((err) => {
176
+ console.error('[Commands] Sending the corrected command failed:', sanitizeError(err));
177
+ });
178
+ }
179
+ //# sourceMappingURL=command-fallback.js.map
@@ -0,0 +1,446 @@
1
+ import { sessionManager } from '../../claude/session-manager.js';
2
+ import { getCachedUsage, getActiveProviderName } from '../../providers/provider-router.js';
3
+ import { userPreferences } from '../../providers/user-preferences.js';
4
+ import { describeModelId, isPremiumModel, PREMIUM_MODEL_ICON } from '../../claude/model-catalog.js';
5
+ import { config } from '../../config.js';
6
+ import { messageSender } from '../../telegram/message-sender.js';
7
+ import { getAvailableCommands } from '../../claude/command-parser.js';
8
+ import { isProcessing } from '../../claude/request-queue.js';
9
+ import { EntityText, joinMessages, trimMessage } from '../../telegram/entities.js';
10
+ import { replyFormatted, replyParts } from '../../telegram/send.js';
11
+ import { fmtTokens } from '../../utils/format.js';
12
+ import * as path from 'path';
13
+ import { resolveShareableFile } from '../file-access.js';
14
+ import { resolvePtyClaudeBin } from '../../utils/resolve-claude-bin.js';
15
+ import { contextTokens } from '../../providers/types.js';
16
+ import { stopTurn } from '../middleware/queued-messages.js';
17
+ import { groupAvailableCommands } from '../../claude/available-commands.js';
18
+ import { buildCommandSearchMessage, searchCommands } from '../command-catalog.js';
19
+ import { getSessionKeyFromCtx } from '../../utils/session-key.js';
20
+ import { replyMd, getEffortLabel, effortLevelLabel, withBackToPrevious } from './command/shared.js';
21
+ import { getSessionTopic } from './command/topic.js';
22
+ import { describeSource } from './command/prefs-scope.js';
23
+ import { describeRole } from './command/access.js';
24
+ import { requireActiveSession } from './session-guard.js';
25
+ // Re-exported so the modules that already import from this file keep working
26
+ // while the command handlers are split out domain by domain.
27
+ export { parseCallback, projectStatusSuffix, resumeCommandMessage, truncateToBytes, getEffortLabel, withBackToPrevious, } from './command/shared.js';
28
+ export { setSessionTopic, getSessionTopic, getMsSinceTopicSet, clearTopic, restoreTopic, handleTopic, } from './command/topic.js';
29
+ export { handleBotName } from './command/botname.js';
30
+ export { handleAllow, handleDeny, handleMembers } from './command/access.js';
31
+ export { handleUsage, parseCostOutput } from './command/usage.js';
32
+ export { handleTasks, handleTasksCallback, handleShells, handleShellsCallback } from './command/tasks.js';
33
+ export { handleBtw, btwLabel, formatSideAnswer } from './command/btw.js';
34
+ export { handleDir, handleDirCallback, } from './command/project.js';
35
+ export { handleBotUpdate, handleBotUpdateCallback, handleBotStatus, handleBotVersion, handleBotRestart, handleBotRestartCallback, handleRestartCallback, handleStartupCallback, handleBotRebuild, handleBotRebuildCallback, } from './command/admin.js';
36
+ export { handleClear, handleHistory, handleResend, handleTerminal, } from './command/session.js';
37
+ export { handleResume, handleResumeCallback } from './command/resume.js';
38
+ export { handlePermissionMode, handlePermissionModeCallback, handleEffort, handleEffortCallback, handleVerbosity, handleVerbosityCallback, handleSuggestions, handleSuggestionsCallback, handleFooter, handleFooterCallback, sendStatusLine, } from './command/settings.js';
39
+ export { handleModelCommand, handleModelCallback, handleCcrCommand, handleProviderSwitchCallback, } from './command/model.js';
40
+ export { handlePrefsScopeCallback } from './command/prefs-scope.js';
41
+ export async function handleStart(ctx) {
42
+ const keyInfo = getSessionKeyFromCtx(ctx);
43
+ const effortLabel = keyInfo ? (getEffortLabel(keyInfo.sessionKey) ?? 'Default') : 'Default';
44
+ const welcome = new EntityText()
45
+ .add('👋 ').bold('Welcome to TeleCoder!')
46
+ .add('\n\nI bridge your messages to Claude Code running on your local machine.\n\n')
47
+ .bold('Getting Started:')
48
+ .add('\n1. Set your project directory with ').code('/dir /path/to/project')
49
+ .add('\n2. Start chatting with Claude about your code!\n\n')
50
+ .bold('Commands:')
51
+ .add('\n• ').code('/dir <path>').add(' - Open a project')
52
+ .add('\n• ').code('/clear').add(' - Clear session and start fresh')
53
+ .add('\n• ').code('/info').add(' - Show current session info')
54
+ .add('\n• ').code('/commands').add(' - Show all commands; ').code('/commands <words>').add(' searches them')
55
+ .add(`\n\nEffort: ${effortLabel}`);
56
+ const currentConv = keyInfo
57
+ ? sessionManager.getSession(keyInfo.sessionKey)?.conversationId
58
+ : undefined;
59
+ const back = withBackToPrevious(welcome.build(), keyInfo?.sessionKey, currentConv);
60
+ await replyFormatted(ctx, back.text, back.options);
61
+ }
62
+ export async function handleInfo(ctx) {
63
+ const keyInfo = getSessionKeyFromCtx(ctx);
64
+ if (!keyInfo) {
65
+ await ctx.reply('❌ Could not determine chat context for /info.');
66
+ return;
67
+ }
68
+ try {
69
+ const { sessionKey } = keyInfo;
70
+ const session = sessionManager.getSession(sessionKey);
71
+ if (!session) {
72
+ await replyMd(ctx, 'ℹ️ No active session.\n\nUse `/dir /path/to/project` to get started.');
73
+ return;
74
+ }
75
+ const provider = getActiveProviderName(sessionKey);
76
+ const topic = getSessionTopic(sessionKey);
77
+ const projectName = path.basename(session.workingDirectory);
78
+ // On CCR, the model alias doesn't reflect which backend actually served
79
+ // the turn — CCR picks per-request based on its router config. We
80
+ // don't try to discover the true backend (would require log parsing).
81
+ // The "Provider: ccr" line below already signals the routing.
82
+ const cached = getCachedUsage(sessionKey);
83
+ // Effort and model are what the session log says the last reply ran with,
84
+ // each followed by who picked it: the chat, with /effort or /model, or
85
+ // Claude Code. Before the first reply the log has nothing, and saying so
86
+ // beats a bare "Default" that could mean either.
87
+ const chosenEffort = getEffortLabel(sessionKey);
88
+ const askedModel = userPreferences.getModel(sessionKey);
89
+ // The cache's model falls back on the asked-for alias and then on a
90
+ // placeholder when the log names none; neither is a model that served.
91
+ const servedModel = cached?.model && cached.model !== askedModel && cached.model !== 'Claude Code default'
92
+ ? cached.model
93
+ : undefined;
94
+ const status = new EntityText().add('📊 ').bold('Session Status').add('\n');
95
+ // One `emoji *Label:* value` line; the value is added by the caller.
96
+ const field = (emoji, label) => status.add(`\n${emoji} `).bold(`${label}:`).add(' ');
97
+ field('🤖', 'Bot Name').add(config.BOT_NAME);
98
+ field('📦', 'Project').add(projectName);
99
+ if (topic)
100
+ field('🏷️', 'Topic').add(topic);
101
+ else
102
+ field('🏷️', 'Topic').italic('none');
103
+ field('🎚️', 'Effort');
104
+ if (chosenEffort)
105
+ status.add(chosenEffort).add(' ').italic(`(${describeSource(sessionKey, 'effort')} with /effort)`);
106
+ else if (cached?.effort)
107
+ status.add(effortLevelLabel(cached.effort)).add(' ').italic("(Claude Code's default)");
108
+ else
109
+ status.italic("Claude Code's default — known after the first reply");
110
+ field('🧠', 'Model');
111
+ if (servedModel) {
112
+ const name = describeModelId(servedModel);
113
+ if (isPremiumModel(servedModel))
114
+ status.add(`${PREMIUM_MODEL_ICON} `);
115
+ status.add(name);
116
+ if (name !== servedModel)
117
+ status.add(' ').code(servedModel);
118
+ if (provider === 'ccr')
119
+ status.add(' ').italic('(routed via CCR)');
120
+ else if (askedModel)
121
+ status.add(' ').italic(`(${describeSource(sessionKey, 'model')} with /model ${askedModel})`);
122
+ else
123
+ status.add(' ').italic("(Claude Code's default)");
124
+ }
125
+ else if (askedModel) {
126
+ status.code(askedModel).add(' ').italic(`(${describeSource(sessionKey, 'model')}, serving from the next reply)`);
127
+ }
128
+ else {
129
+ status.italic("Claude Code's default — known after the first reply");
130
+ }
131
+ field('🔌', 'Provider').add(provider);
132
+ if (cached) {
133
+ // Cache reads and writes are most of the context, and without them this
134
+ // read about 0%. Same sum as the usage footer's.
135
+ const used = contextTokens(cached);
136
+ const pct = cached.contextWindow > 0
137
+ ? Math.round((used / cached.contextWindow) * 100)
138
+ : 0;
139
+ field('📐', 'Context').add(`${pct}% (${fmtTokens(used)}/${fmtTokens(cached.contextWindow)})`);
140
+ }
141
+ // Only in a group, and only for a non-admin — it is the line that explains
142
+ // why /botrestart just refused. Spectators never see it: they can't reach
143
+ // /info in the first place.
144
+ const role = describeRole(ctx);
145
+ if (role && role !== 'admin') {
146
+ field('👤', 'Your role here').add(role);
147
+ }
148
+ // The session id is one tap away under /footer's "Show session", and
149
+ // the bot's uptime is /botstatus's business.
150
+ field('⏱️', 'Last Activity').add(session.lastActivity.toLocaleString());
151
+ await replyFormatted(ctx, status.build());
152
+ }
153
+ catch (err) {
154
+ console.error('[Info] Error:', err);
155
+ const msg = err instanceof Error ? err.message : String(err);
156
+ await ctx.reply(`❌ /info failed: ${msg}`).catch(() => { });
157
+ }
158
+ }
159
+ export async function handleCancel(ctx) {
160
+ const keyInfo = getSessionKeyFromCtx(ctx);
161
+ if (!keyInfo)
162
+ return;
163
+ const { sessionKey } = keyInfo;
164
+ const wasProcessing = isProcessing(sessionKey);
165
+ const { stopped: cancelled, dropped: clearedCount } = await stopTurn(ctx.api, sessionKey);
166
+ if (cancelled || clearedCount > 0) {
167
+ let message = '🛑 Cancelled.';
168
+ if (clearedCount > 0) {
169
+ message += ` (${clearedCount} queued request${clearedCount > 1 ? 's' : ''} cleared)`;
170
+ }
171
+ await ctx.reply(message);
172
+ }
173
+ else if (!wasProcessing) {
174
+ await ctx.reply('ℹ️ Nothing to cancel.');
175
+ }
176
+ }
177
+ export async function handleCommands(ctx) {
178
+ // `/commands kill` searches names and descriptions — Telegram's own `/`
179
+ // menu only filters on the start of a name.
180
+ const query = (ctx.message?.text ?? '').split(' ').slice(1).join(' ').trim();
181
+ if (query) {
182
+ await replyFormatted(ctx, buildCommandSearchMessage(query, searchCommands(query)));
183
+ return;
184
+ }
185
+ await replyParts(ctx, getAvailableCommands());
186
+ }
187
+ /** Show the current permission-gate state and the patterns it enforces. */
188
+ export async function handleGate(ctx) {
189
+ const { isPermissionGateEnabled, isPermissionGateImplicit, listDangerousPatterns } = await import('../../claude/permission-gate.js');
190
+ const { getAdminIds, getApproverIds, getGuestIds, hasGuestUsers, isAdmin, isApprover } = await import('../../utils/admins.js');
191
+ const enabled = isPermissionGateEnabled();
192
+ const patterns = listDangerousPatterns();
193
+ // One line each; an empty one is the gap between sections.
194
+ const lines = [];
195
+ const line = (build = () => { }) => {
196
+ const b = new EntityText();
197
+ build(b);
198
+ lines.push(b.build());
199
+ };
200
+ line((b) => b.add('🔐 ').bold('Permission gate').add(` — ${enabled ? '✅ enabled' : '⛔️ disabled'}`));
201
+ line();
202
+ if (enabled) {
203
+ line((b) => b.add('Bash commands matching the patterns below trigger a Telegram approval prompt before they run: Claude\'s own, and a ')
204
+ .code('!command').add(' someone sends. Other tools auto-allow.'));
205
+ }
206
+ else {
207
+ line((b) => b.add('Disabled. Set ').code('TELECODER_PERMISSION_PROMPTS=1').add(' and restart the bot to enable.'));
208
+ }
209
+ // An open window changes what the gate does right now, so it belongs above
210
+ // everything that describes what it would do otherwise.
211
+ const { getWindow, formatRemaining } = await import('../../claude/auto-approve.js');
212
+ const window = ctx.chat?.id !== undefined ? getWindow(ctx.chat.id) : null;
213
+ if (window) {
214
+ line();
215
+ line((b) => b.add('⚡ ').bold('Auto-approve is on here')
216
+ .add(` — ${formatRemaining(window)} left, opened by ${window.openedByName}.`));
217
+ line((b) => b.add('Guarded commands run without asking and are posted as they happen. End it with ')
218
+ .code('/autoapprove off').add('.'));
219
+ }
220
+ if (enabled && isPermissionGateImplicit()) {
221
+ line();
222
+ line((b) => b.add('On automatically because this bot has non-admin users. Set ')
223
+ .code('TELECODER_PERMISSION_PROMPTS=0').add(' to turn it off.'));
224
+ }
225
+ if (enabled) {
226
+ const { isScopeGuardEnabled, getAllowedRoots } = await import('../../claude/scope-guard.js');
227
+ line();
228
+ if (isScopeGuardEnabled(true)) {
229
+ line((b) => b.bold('Scope guard:').add(' ✅ on'));
230
+ line((b) => b.add('Tool calls naming a path outside these prompt too:'));
231
+ for (const root of getAllowedRoots())
232
+ line((b) => b.add('• ').code(root));
233
+ }
234
+ else {
235
+ line((b) => b.bold('Scope guard:').add(' ⛔️ off'));
236
+ }
237
+ }
238
+ const { isCharterJudgeEnabled, getCharter } = await import('../../claude/charter-judge.js');
239
+ if (isCharterJudgeEnabled()) {
240
+ const { source } = getCharter();
241
+ line();
242
+ line((b) => b.bold('Charter judge:').add(' ✅ on'));
243
+ line((b) => {
244
+ b.add('Every guest message is read against ');
245
+ if (source === '(default)')
246
+ b.add('the built-in charter');
247
+ else
248
+ b.code(source);
249
+ b.add(' before it reaches Claude.');
250
+ });
251
+ }
252
+ if (hasGuestUsers()) {
253
+ const admins = getAdminIds();
254
+ const approvers = getApproverIds();
255
+ // getGuestIds() means "not an admin", which includes the approvers. Split
256
+ // them out so the counts add up to the roster rather than double-counting.
257
+ const guests = getGuestIds().filter((id) => !approvers.includes(id));
258
+ const roles = [
259
+ `${admins.length} admin${admins.length === 1 ? '' : 's'}`,
260
+ ...(approvers.length > 0 ? [`${approvers.length} approver${approvers.length === 1 ? '' : 's'}`] : []),
261
+ `${guests.length} guest${guests.length === 1 ? '' : 's'}`,
262
+ ];
263
+ line();
264
+ line((b) => b.bold('Roles:').add(` ${roles.join(', ')}`));
265
+ if (isAdmin(ctx.from?.id)) {
266
+ line((b) => b.add('You are an ').bold('admin')
267
+ .add(' — approval prompts and bot-lifecycle commands are yours to answer.'));
268
+ }
269
+ else if (isApprover(ctx.from?.id)) {
270
+ line((b) => b.add('You are an ').bold('approver')
271
+ .add(' — you can answer anyone else’s approval prompt, but not your own. ' +
272
+ 'Bot-lifecycle commands stay with the admins.'));
273
+ }
274
+ else {
275
+ line((b) => b.add('You are a ').bold('guest')
276
+ .add(' — an admin or approver answers guarded commands, and admins own ' +
277
+ 'bot-lifecycle commands.'));
278
+ }
279
+ }
280
+ line();
281
+ line((b) => b.bold('Guarded patterns:'));
282
+ for (const p of patterns)
283
+ line((b) => b.add(`• ${p.reason}`));
284
+ await replyParts(ctx, joinMessages(lines, '\n'));
285
+ }
286
+ /**
287
+ * List the current project's `.claude/commands/*.md` slash commands. They
288
+ * pass through to claude code untouched (typing `/mycommand` in chat sends
289
+ * `/mycommand` to claude, which dispatches to the file), so this is purely
290
+ * a discoverability helper — no per-command registration needed.
291
+ */
292
+ export async function handleProjectCommands(ctx) {
293
+ const keyInfo = getSessionKeyFromCtx(ctx);
294
+ if (!keyInfo)
295
+ return;
296
+ const { sessionKey } = keyInfo;
297
+ const session = sessionManager.getSession(sessionKey);
298
+ if (!session) {
299
+ await replyMd(ctx, '⚠️ No project set. Use `/dir` first.');
300
+ return;
301
+ }
302
+ const { getProjectCommands } = await import('../../claude/project-commands.js');
303
+ const { getAvailableCommands: getClaudeCommands } = await import('../../claude/available-commands.js');
304
+ const { getBotCommandNames } = await import('../../claude/command-parser.js');
305
+ const projectCommands = getProjectCommands(session.workingDirectory);
306
+ // Ask the binary the chat's turns actually run through: command sets differ
307
+ // between releases, and another install's list would name commands that
308
+ // don't exist here.
309
+ const executable = resolvePtyClaudeBin();
310
+ // A cold cache means a probe — a fresh headless process — so show a typing
311
+ // indicator rather than leaving the chat silent for a second or two.
312
+ const typing = ctx.replyWithChatAction?.('typing');
313
+ const snapshot = await getClaudeCommands(session.workingDirectory, executable);
314
+ await typing?.catch(() => { });
315
+ await replyFormatted(ctx, buildProjectCommandsMessage({
316
+ directory: path.basename(session.workingDirectory),
317
+ projectCommands,
318
+ snapshot,
319
+ botCommandNames: getBotCommandNames(),
320
+ }));
321
+ }
322
+ /**
323
+ * Render the `/projectcommands` listing. Pure so what it sends — the command
324
+ * names as code, the descriptions as they were written — is unit-testable.
325
+ *
326
+ * `snapshot` is undefined when Claude Code's own command list couldn't be
327
+ * read; the project commands still list, since those come off disk.
328
+ */
329
+ export function buildProjectCommandsMessage(input) {
330
+ const { directory, projectCommands, snapshot, botCommandNames } = input;
331
+ const lines = [];
332
+ const line = (build = () => { }) => {
333
+ const b = new EntityText();
334
+ build(b);
335
+ lines.push(b.build());
336
+ };
337
+ // `/a`, `/b`, … as one line of code spans.
338
+ const commandList = (names) => (b) => {
339
+ names.forEach((n, i) => {
340
+ if (i > 0)
341
+ b.add(', ');
342
+ b.code(`/${n}`);
343
+ });
344
+ };
345
+ line((b) => b.add('📜 ').bold('Commands available in').add(' ').code(directory));
346
+ line();
347
+ if (projectCommands.length > 0) {
348
+ line((b) => b.bold('Project').add(' (').code('.claude/commands/').add('):'));
349
+ line();
350
+ for (const c of projectCommands) {
351
+ line((b) => {
352
+ b.add('• ').code(`/${c.name}`);
353
+ if (c.description)
354
+ b.add(` — ${c.description}`);
355
+ });
356
+ }
357
+ line();
358
+ }
359
+ if (snapshot) {
360
+ const { skills, plugins, builtIns } = groupAvailableCommands(snapshot);
361
+ // A command TeleCoder registers never reaches Claude Code — grammY matches
362
+ // it first — so listing it as passthrough would be a lie. Name them
363
+ // separately instead, so nobody wonders why /model isn't Claude Code's picker.
364
+ const shadowed = snapshot.slashCommands.filter((n) => botCommandNames.has(n)).sort();
365
+ const passthrough = (names) => names.filter((n) => !botCommandNames.has(n));
366
+ const groups = [
367
+ ['Skills:', passthrough(skills)],
368
+ ['Plugin:', passthrough(plugins)],
369
+ ['Built-in:', passthrough(builtIns)],
370
+ ];
371
+ for (const [title, names] of groups) {
372
+ if (names.length === 0)
373
+ continue;
374
+ line((b) => b.bold(title));
375
+ line();
376
+ line(commandList(names));
377
+ line();
378
+ }
379
+ if (shadowed.length > 0) {
380
+ line((b) => b.add('⚠️ ').bold('Shadowed by TeleCoder')
381
+ .add(" — these run the bot's own command, not Claude Code's:"));
382
+ line();
383
+ line(commandList(shadowed));
384
+ line();
385
+ line((b) => b.add("For Claude Code's own, put ").code('/cc').add(' in front: ').code(`/cc ${shadowed[0]}`).add('.'));
386
+ line();
387
+ }
388
+ }
389
+ else {
390
+ line((b) => b.italic("Claude Code's own command list is unavailable right now."));
391
+ line();
392
+ }
393
+ if (projectCommands.length === 0) {
394
+ line((b) => b.add('Add markdown files under ').code('.claude/commands/')
395
+ .add(' to define project commands — see ')
396
+ .link('docs', 'https://docs.claude.com/en/docs/claude-code/slash-commands').add('.'));
397
+ }
398
+ return joinWithinLimit(lines, 3900);
399
+ }
400
+ /**
401
+ * Join lines up to a length budget, dropping whole lines rather than cutting
402
+ * mid-line, so the list ends on a whole command name and says it was cut.
403
+ * Counted in UTF-16 code units, the unit of Telegram's 4096 cap.
404
+ */
405
+ function joinWithinLimit(lines, maxLength) {
406
+ const notice = new EntityText().add('\n').italic('…list truncated.').build();
407
+ const budget = maxLength - notice.text.length;
408
+ const kept = [];
409
+ let size = 0;
410
+ for (const line of lines) {
411
+ const cost = line.text.length + 1;
412
+ if (size + cost > budget) {
413
+ return joinMessages([trimMessage(joinMessages(kept, '\n')), notice], '');
414
+ }
415
+ kept.push(line);
416
+ size += cost;
417
+ }
418
+ return trimMessage(joinMessages(kept, '\n'));
419
+ }
420
+ export async function handleFile(ctx) {
421
+ const keyInfo = getSessionKeyFromCtx(ctx);
422
+ if (!keyInfo)
423
+ return;
424
+ const { sessionKey } = keyInfo;
425
+ const text = ctx.message?.text || '';
426
+ const filePath = text.split(' ').slice(1).join(' ').trim();
427
+ const session = await requireActiveSession(ctx, sessionKey);
428
+ if (!session)
429
+ return;
430
+ if (!filePath) {
431
+ await replyFormatted(ctx, new EntityText()
432
+ .add('📎 Usage: ').code('/file <path>')
433
+ .add(', relative to the project, e.g. ').code('/file src/index.ts')
434
+ .add('. Or just ask Claude to send you the file.')
435
+ .build());
436
+ return;
437
+ }
438
+ const fullPath = await resolveShareableFile(ctx, session.workingDirectory, filePath);
439
+ if (!fullPath)
440
+ return;
441
+ const success = await messageSender.sendDocument(ctx, fullPath, `📎 ${path.basename(fullPath)}`);
442
+ if (!success) {
443
+ await ctx.reply('❌ Failed to send file. It may be too large (>50MB) or inaccessible.');
444
+ }
445
+ }
446
+ //# sourceMappingURL=command.handler.js.map