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.
- package/.env.example +363 -0
- package/CHANGELOG.md +1186 -0
- package/LICENSE +22 -0
- package/README.md +126 -2
- package/dist/audio/transcribe.js +50 -0
- package/dist/bin/mcp-server.js +378 -0
- package/dist/bin/tool-result.js +22 -0
- package/dist/bot/access/group-access.js +147 -0
- package/dist/bot/bot.js +592 -0
- package/dist/bot/file-access.js +141 -0
- package/dist/bot/handlers/command/access.js +407 -0
- package/dist/bot/handlers/command/admin.js +827 -0
- package/dist/bot/handlers/command/auto-approve.js +138 -0
- package/dist/bot/handlers/command/btw.js +224 -0
- package/dist/bot/handlers/command/cost.js +409 -0
- package/dist/bot/handlers/command/media.js +197 -0
- package/dist/bot/handlers/command/model.js +305 -0
- package/dist/bot/handlers/command/prefs-scope.js +197 -0
- package/dist/bot/handlers/command/project.js +536 -0
- package/dist/bot/handlers/command/resume.js +321 -0
- package/dist/bot/handlers/command/session.js +438 -0
- package/dist/bot/handlers/command/settings.js +1012 -0
- package/dist/bot/handlers/command/shared.js +210 -0
- package/dist/bot/handlers/command/streaming-mode.js +16 -0
- package/dist/bot/handlers/command/tasks.js +513 -0
- package/dist/bot/handlers/command/topic-store.js +113 -0
- package/dist/bot/handlers/command/topic.js +80 -0
- package/dist/bot/handlers/command.handler.js +772 -0
- package/dist/bot/handlers/fork.handler.js +1109 -0
- package/dist/bot/handlers/media-fallback.js +121 -0
- package/dist/bot/handlers/message/replies.js +133 -0
- package/dist/bot/handlers/message/shared.js +117 -0
- package/dist/bot/handlers/message/throttle.js +49 -0
- package/dist/bot/handlers/message/turn-notify.js +169 -0
- package/dist/bot/handlers/message/turn-runner.js +141 -0
- package/dist/bot/handlers/message.handler.js +107 -0
- package/dist/bot/handlers/newbot.handler.js +221 -0
- package/dist/bot/handlers/photo.handler.js +327 -0
- package/dist/bot/handlers/prompts.handler.js +343 -0
- package/dist/bot/handlers/running-note.js +44 -0
- package/dist/bot/handlers/schedule.handler.js +303 -0
- package/dist/bot/handlers/session-guard.js +78 -0
- package/dist/bot/handlers/suggestion.handler.js +84 -0
- package/dist/bot/handlers/tree.handler.js +480 -0
- package/dist/bot/handlers/view.js +41 -0
- package/dist/bot/handlers/voice.handler.js +209 -0
- package/dist/bot/middleware/admin-only.js +49 -0
- package/dist/bot/middleware/auth.middleware.js +122 -0
- package/dist/bot/middleware/group-mention.middleware.js +139 -0
- package/dist/bot/middleware/group-role.middleware.js +75 -0
- package/dist/bot/middleware/message-batcher.js +87 -0
- package/dist/bot/middleware/queued-messages.js +971 -0
- package/dist/bot/middleware/stale-filter.js +31 -0
- package/dist/build-info.json +8 -0
- package/dist/claude/agent-watchdog.js +162 -0
- package/dist/claude/agent.js +1458 -0
- package/dist/claude/ask-user.js +295 -0
- package/dist/claude/auto-approve.js +225 -0
- package/dist/claude/auto-topic-haiku.js +126 -0
- package/dist/claude/available-commands.js +153 -0
- package/dist/claude/carry-over.js +27 -0
- package/dist/claude/ccr-shim.js +46 -0
- package/dist/claude/charter-judge.js +214 -0
- package/dist/claude/claude-auth.js +121 -0
- package/dist/claude/command-parser.js +200 -0
- package/dist/claude/cost-overlay-scraper.js +129 -0
- package/dist/claude/enabled-plugins.js +56 -0
- package/dist/claude/fork-tree.js +393 -0
- package/dist/claude/held-query.js +190 -0
- package/dist/claude/in-flight-tracker.js +61 -0
- package/dist/claude/ipc-server.js +192 -0
- package/dist/claude/mcp-bridge.js +453 -0
- package/dist/claude/mcp-tools.js +354 -0
- package/dist/claude/message-offsets.js +88 -0
- package/dist/claude/modal-relay.js +450 -0
- package/dist/claude/model-catalog.js +85 -0
- package/dist/claude/monitor-relay.js +597 -0
- package/dist/claude/pending-forks.js +93 -0
- package/dist/claude/pending-suggestions.js +50 -0
- package/dist/claude/permission-gate.js +337 -0
- package/dist/claude/permission-mode.js +178 -0
- package/dist/claude/poll-user.js +51 -0
- package/dist/claude/project-commands.js +69 -0
- package/dist/claude/prompt-hold.js +124 -0
- package/dist/claude/prompt-suggestion-scraper.js +89 -0
- package/dist/claude/pty-provider.js +2214 -0
- package/dist/claude/pty-spawn-config.js +296 -0
- package/dist/claude/pty-stream.js +363 -0
- package/dist/claude/request-queue.js +135 -0
- package/dist/claude/scheduled-runner.js +91 -0
- package/dist/claude/scheduler.js +237 -0
- package/dist/claude/scope-guard.js +274 -0
- package/dist/claude/sdk-permission-gate.js +77 -0
- package/dist/claude/secret-request.js +576 -0
- package/dist/claude/session-cost.js +41 -0
- package/dist/claude/session-history.js +286 -0
- package/dist/claude/session-jsonl.js +920 -0
- package/dist/claude/session-manager.js +195 -0
- package/dist/claude/session-scan.js +270 -0
- package/dist/claude/setup-token.js +285 -0
- package/dist/claude/side-call-options.js +45 -0
- package/dist/claude/side-question.js +249 -0
- package/dist/claude/stage-images.js +62 -0
- package/dist/claude/subagent-tools.js +12 -0
- package/dist/claude/synthetic-ctx.js +51 -0
- package/dist/claude/system-prompt.js +162 -0
- package/dist/claude/tasks-overlay-scraper.js +94 -0
- package/dist/claude/tip-scraper.js +78 -0
- package/dist/claude/tui-modal.js +501 -0
- package/dist/claude/tui-state.js +384 -0
- package/dist/claude/turn-end.js +91 -0
- package/dist/claude/turn-prose.js +64 -0
- package/dist/claude/update-banner-relay.js +70 -0
- package/dist/cli/commands/doctor.js +305 -0
- package/dist/cli/commands/help.js +25 -0
- package/dist/cli/commands/init.js +123 -0
- package/dist/cli/commands/service.js +678 -0
- package/dist/cli/commands/start.js +53 -0
- package/dist/cli/commands/version.js +11 -0
- package/dist/cli/dispatch.js +79 -0
- package/dist/cli/init/env-file.js +99 -0
- package/dist/cli/init/flow.js +638 -0
- package/dist/cli/init/prompter.js +116 -0
- package/dist/cli/init/telegram.js +94 -0
- package/dist/cli/service/render.js +212 -0
- package/dist/cli.js +18 -0
- package/dist/config-report.js +107 -0
- package/dist/config.js +500 -0
- package/dist/index.js +367 -0
- package/dist/launcher.js +933 -0
- package/dist/node-version-check.js +27 -0
- package/dist/providers/ccr-health.js +119 -0
- package/dist/providers/ccr-introspect.js +149 -0
- package/dist/providers/ccr-provider.js +60 -0
- package/dist/providers/claude-provider.js +63 -0
- package/dist/providers/prefs-sync.js +164 -0
- package/dist/providers/project-favorites.js +74 -0
- package/dist/providers/provider-router.js +127 -0
- package/dist/providers/provider-switch.js +91 -0
- package/dist/providers/sdk-provider.js +37 -0
- package/dist/providers/types.js +8 -0
- package/dist/providers/user-preferences.js +214 -0
- package/dist/restart-when-idle.js +153 -0
- package/dist/startup/auto-continue.js +67 -0
- package/dist/startup/auto-resume.js +173 -0
- package/dist/startup/notices.js +120 -0
- package/dist/startup/shared.js +44 -0
- package/dist/startup/verify-token.js +31 -0
- package/dist/telegram/access-request.js +153 -0
- package/dist/telegram/action-logger.js +684 -0
- package/dist/telegram/admin-mention.js +107 -0
- package/dist/telegram/background-activity-card.js +502 -0
- package/dist/telegram/botname-settings.js +336 -0
- package/dist/telegram/button-text.js +26 -0
- package/dist/telegram/client-options.js +27 -0
- package/dist/telegram/deduplication.js +33 -0
- package/dist/telegram/entities.js +295 -0
- package/dist/telegram/force-reply-tracker.js +57 -0
- package/dist/telegram/lettered-options.js +87 -0
- package/dist/telegram/markdown.js +362 -0
- package/dist/telegram/message-sender.js +1287 -0
- package/dist/telegram/prompt-label.js +142 -0
- package/dist/telegram/prompt-suggestion.js +54 -0
- package/dist/telegram/send.js +123 -0
- package/dist/telegram/streaming-turn.js +105 -0
- package/dist/telegram/suggestions-settings.js +30 -0
- package/dist/telegram/task-list.js +367 -0
- package/dist/telegram/task-tracker.js +209 -0
- package/dist/telegram/telegraph-settings.js +31 -0
- package/dist/telegram/telegraph.js +453 -0
- package/dist/telegram/terminal-renderer.js +671 -0
- package/dist/telegram/terminal-settings.js +25 -0
- package/dist/telegram/thread-titles.js +190 -0
- package/dist/telegram/threads-setup.js +117 -0
- package/dist/tts/tts-settings.js +62 -0
- package/dist/tts/tts.js +245 -0
- package/dist/tts/voice-reply.js +78 -0
- package/dist/utils/admins.js +143 -0
- package/dist/utils/agent-timer.js +55 -0
- package/dist/utils/atomic-write.js +24 -0
- package/dist/utils/bot-token.js +74 -0
- package/dist/utils/bounded-map.js +55 -0
- package/dist/utils/build-info.js +57 -0
- package/dist/utils/caffeinate.js +50 -0
- package/dist/utils/claude-env.js +54 -0
- package/dist/utils/claude-version.js +48 -0
- package/dist/utils/config-home.js +62 -0
- package/dist/utils/debug-agent.js +117 -0
- package/dist/utils/debug-watchdog.js +121 -0
- package/dist/utils/download.js +111 -0
- package/dist/utils/exit-codes.js +48 -0
- package/dist/utils/file-type.js +149 -0
- package/dist/utils/format.js +81 -0
- package/dist/utils/home-project.js +30 -0
- package/dist/utils/host-stall.js +51 -0
- package/dist/utils/id-list.js +44 -0
- package/dist/utils/idle-restart.js +92 -0
- package/dist/utils/install-mode.js +63 -0
- package/dist/utils/instance-config.js +148 -0
- package/dist/utils/instances.js +95 -0
- package/dist/utils/json-store.js +140 -0
- package/dist/utils/keyed-settings.js +62 -0
- package/dist/utils/legacy-env.js +35 -0
- package/dist/utils/npm-version.js +134 -0
- package/dist/utils/prefs-relay.js +107 -0
- package/dist/utils/proc-children.js +102 -0
- package/dist/utils/project-data-dir.js +33 -0
- package/dist/utils/reasoning-summary.js +12 -0
- package/dist/utils/resolve-bin.js +86 -0
- package/dist/utils/resolve-claude-bin.js +63 -0
- package/dist/utils/respawn-backoff.js +19 -0
- package/dist/utils/sanitize.js +91 -0
- package/dist/utils/session-key.js +37 -0
- package/dist/utils/stale-launcher.js +109 -0
- package/dist/utils/state-dir-migration.js +92 -0
- package/dist/utils/systemd.js +126 -0
- package/dist/utils/user-roster.js +275 -0
- package/dist/utils/verbosity.js +118 -0
- package/dist/utils/version-check.js +166 -0
- package/dist/utils/workspace-guard.js +44 -0
- package/dist/worker-restart.js +141 -0
- package/instances.json.example +41 -0
- package/package.json +76 -4
package/dist/bot/bot.js
ADDED
|
@@ -0,0 +1,592 @@
|
|
|
1
|
+
import { startIpcServer } from '../claude/ipc-server.js';
|
|
2
|
+
import { Bot } from 'grammy';
|
|
3
|
+
import { autoRetry } from '@grammyjs/auto-retry';
|
|
4
|
+
import { sequentialize } from '@grammyjs/runner';
|
|
5
|
+
import { telegramClientOptions, telegramProxyUrl } from '../telegram/client-options.js';
|
|
6
|
+
import { redactSecrets } from '../utils/sanitize.js';
|
|
7
|
+
import { config } from '../config.js';
|
|
8
|
+
import { buildSessionKey } from '../utils/session-key.js';
|
|
9
|
+
import { authMiddleware } from './middleware/auth.middleware.js';
|
|
10
|
+
import { adminOnly, adminOrApproverOnly } from './middleware/admin-only.js';
|
|
11
|
+
import { trackQueuedMessage, holdQueuedMessage, handleQueuedCallback, handleEditedMessage, handleLater, handleSteer, initParkedMessages, setQueuedDiverters, } from './middleware/queued-messages.js';
|
|
12
|
+
import { handleStart, handleClear, handleClearCallback, handleProject, handleNewProject, handleProjectCallback, handleStatus, handleStreaming, handleModeCallback, handlePermissionMode, handlePermissionModeCallback, handleTTS, handleTTSCallback, handleTelegraph, handleTelegraphCallback, handleSuggestions, handleSuggestionsCallback, handleBotStatus, handleVersion, handleRestartBot, handleRestartBotCallback, handleRestartCallback, handleStartupCallback, handleContext, handleCost, handleUpdate, handleUpdateCallback, handlePing, handleCancel, handleCommands, handleModelCommand, handleModelCallback, handlePrefsAllCallback, handleProviderCommand, handleProviderCallback, handleProviderSwitchCallback, handleCcrCommand, handlePlan, handleExplore, handleResume, handleResumeCallback, handleContinue, handleRecap, handleSync, handleHandoff, handlePermissions, handleProjectCommands, handleLoop, handleSessions, handleTeleport, handleFile, handleTerminalUI, handleTerminalUICallback, handleStatusLine, handleStatusLineCallback, handleTranscribe, handleTranscribeAudio, handleTranscribeDocument, handleBotName, handleBotNameCallback, handleTopic, handleRebuild, handleRebuildCallback, handleBtw, handleEffort, handleEffortCallback, handleTasks, handleTasksCallback, handleShells, handleShellsCallback, handleVerbosity, handleVerbosityCallback, handleMethodCommand, handleMethodCallback, } from './handlers/command.handler.js';
|
|
13
|
+
import { handleMessage, handleCcrThrottleCallback } from './handlers/message.handler.js';
|
|
14
|
+
import { handleSchedule, handleSchedules, handleUnschedule } from './handlers/schedule.handler.js';
|
|
15
|
+
import { handleForkCallback, handleAcceptCommand, handleDeclineCommand, handleForkCommand, handleSpinoffCommand, forkPastRunningTurnIntoThread } from './handlers/fork.handler.js';
|
|
16
|
+
import { askBtw } from './handlers/command/btw.js';
|
|
17
|
+
import { handleNewBot, handleManagedBotCreated } from './handlers/newbot.handler.js';
|
|
18
|
+
import { handleTreeCommand, handleTreeCallback } from './handlers/tree.handler.js';
|
|
19
|
+
import { handlePromptsCommand, handlePromptsCallback } from './handlers/prompts.handler.js';
|
|
20
|
+
import { handleAllow, handleDeny, handleUsers, handleMembers, handleAccessCallback, } from './handlers/command/access.js';
|
|
21
|
+
import { handleAutoApprove } from './handlers/command/auto-approve.js';
|
|
22
|
+
import { handleSuggestionTapCallback } from './handlers/suggestion.handler.js';
|
|
23
|
+
import { handleVoice } from './handlers/voice.handler.js';
|
|
24
|
+
import { handlePhoto, handleImageDocument, handleTextDocument } from './handlers/photo.handler.js';
|
|
25
|
+
import { handleUnsupportedVideo, handleUnsupportedMediaDocument, } from './handlers/media-fallback.js';
|
|
26
|
+
import { createBatchMiddleware } from './middleware/message-batcher.js';
|
|
27
|
+
import { countUpdatesInFlight } from '../restart-when-idle.js';
|
|
28
|
+
import { resolvePendingQuestion, getQuestionResponders, getQuestionOptionLabel, appendAnsweredFooter, buildAnswerConfirmation, } from '../claude/ask-user.js';
|
|
29
|
+
import { describeResponderRefusal } from '../telegram/admin-mention.js';
|
|
30
|
+
import { groupMentionMiddleware } from './middleware/group-mention.middleware.js';
|
|
31
|
+
import { groupRoleMiddleware } from './middleware/group-role.middleware.js';
|
|
32
|
+
import { trackForceReplyPrompts } from '../telegram/force-reply-tracker.js';
|
|
33
|
+
import { initThreadTitles } from '../telegram/thread-titles.js';
|
|
34
|
+
import { initThreadsSetup } from '../telegram/threads-setup.js';
|
|
35
|
+
import { resolvePendingPoll } from '../claude/poll-user.js';
|
|
36
|
+
import { captureSecretMessages, handleSecretCallback } from '../claude/secret-request.js';
|
|
37
|
+
import { registerBotCommandName } from '../claude/command-parser.js';
|
|
38
|
+
import { withRunningNote } from './handlers/running-note.js';
|
|
39
|
+
import { isCheckout } from '../utils/install-mode.js';
|
|
40
|
+
// Resolve sequentialize constraint: same-chat updates are ordered,
|
|
41
|
+
// but /cancel is registered BEFORE this middleware so it bypasses it.
|
|
42
|
+
async function handleAskUserCallback(ctx) {
|
|
43
|
+
const data = ctx.callbackQuery?.data;
|
|
44
|
+
if (!data)
|
|
45
|
+
return;
|
|
46
|
+
const parts = data.split(':');
|
|
47
|
+
if (parts.length !== 3)
|
|
48
|
+
return;
|
|
49
|
+
const [, id, idxStr] = parts;
|
|
50
|
+
const idx = parseInt(idxStr, 10);
|
|
51
|
+
if (Number.isNaN(idx))
|
|
52
|
+
return;
|
|
53
|
+
// Read the label before resolving — resolving drops the entry. It comes from
|
|
54
|
+
// the registry rather than off the tapped button because the button may be a
|
|
55
|
+
// bare letter: a keyboard whose labels are too wide for Telegram renders as
|
|
56
|
+
// `A` `B` `C` with the full text in the message body, and "✅ Answered: A"
|
|
57
|
+
// is not an answer anyone can read back later.
|
|
58
|
+
const optionLabel = getQuestionOptionLabel(id, idx);
|
|
59
|
+
const outcome = resolvePendingQuestion(id, idx, ctx.from?.id);
|
|
60
|
+
if (outcome === 'expired') {
|
|
61
|
+
await ctx.answerCallbackQuery({ text: 'This question already expired.' });
|
|
62
|
+
// A question that timed out is closed by whoever was waiting on it, but a
|
|
63
|
+
// restart forgets every open question without touching its message. Take
|
|
64
|
+
// the keyboard down so it stops looking answerable. Text left alone: a
|
|
65
|
+
// quick second tap on a question just answered lands here too, and its
|
|
66
|
+
// "✅ Answered" footer must survive.
|
|
67
|
+
try {
|
|
68
|
+
await ctx.editMessageReplyMarkup();
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
// Already gone, or the message can't be edited — nothing left to do.
|
|
72
|
+
}
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (outcome === 'forbidden') {
|
|
76
|
+
// Leave the keyboard up — the people who *can* answer still need it.
|
|
77
|
+
await ctx.answerCallbackQuery({
|
|
78
|
+
text: describeResponderRefusal(getQuestionResponders(id), ctx.from?.id),
|
|
79
|
+
show_alert: true,
|
|
80
|
+
});
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
await ctx.answerCallbackQuery();
|
|
84
|
+
const message = ctx.callbackQuery?.message;
|
|
85
|
+
const answerText = optionLabel ?? `option ${idx + 1}`;
|
|
86
|
+
// Strip the keyboard so the user can't tap again, and mark the chosen option
|
|
87
|
+
// in place so the question doesn't read as unanswered.
|
|
88
|
+
//
|
|
89
|
+
// Plain text: the label is model-supplied and may contain unbalanced
|
|
90
|
+
// Markdown punctuation (underscores in URL params, stray asterisks, …)
|
|
91
|
+
// which would 400 the edit. A question that went out with entities — a
|
|
92
|
+
// relayed dialog, a permission prompt — gets them back, or the edit strips
|
|
93
|
+
// it to plain text; the footer only appends, so their offsets still hold.
|
|
94
|
+
try {
|
|
95
|
+
const answered = appendAnsweredFooter(message?.text ?? '', answerText);
|
|
96
|
+
if (answered === null)
|
|
97
|
+
await ctx.editMessageReplyMarkup();
|
|
98
|
+
else if (!message?.entities)
|
|
99
|
+
await ctx.editMessageText(answered);
|
|
100
|
+
else {
|
|
101
|
+
// An entity Telegram balks at the second time round — a mention it no
|
|
102
|
+
// longer allows — shouldn't cost the footer as well.
|
|
103
|
+
await ctx.editMessageText(answered, { entities: message.entities })
|
|
104
|
+
.catch(() => ctx.editMessageText(answered));
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
// Edit may fail if the message changed shape. Losing the footer is
|
|
109
|
+
// cosmetic; leaving a live keyboard on a resolved question is not, so
|
|
110
|
+
// retry the keyboard removal on its own.
|
|
111
|
+
try {
|
|
112
|
+
await ctx.editMessageReplyMarkup();
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
// Non-fatal — a second tap is rejected by resolvePendingQuestion anyway.
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
// The answer also goes out as its own message. See buildAnswerConfirmation:
|
|
119
|
+
// an edit is silent, anonymous, and buried at the bottom of a long question,
|
|
120
|
+
// so the choice never really lands in the conversation. Replying to the
|
|
121
|
+
// question keeps the two linked even when several questions are open at once.
|
|
122
|
+
try {
|
|
123
|
+
await ctx.reply(buildAnswerConfirmation(answerText, {
|
|
124
|
+
isPrivate: ctx.chat?.type === 'private',
|
|
125
|
+
who: ctx.from?.first_name,
|
|
126
|
+
}), message?.message_id === undefined
|
|
127
|
+
? undefined
|
|
128
|
+
: { reply_parameters: { message_id: message.message_id, allow_sending_without_reply: true } });
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
// Non-fatal — the in-place footer above already recorded the choice.
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function getSequentializeKey(ctx) {
|
|
135
|
+
const chatId = ctx.chat?.id;
|
|
136
|
+
if (!chatId)
|
|
137
|
+
return undefined;
|
|
138
|
+
const msg = (ctx.message ?? ctx.callbackQuery?.message);
|
|
139
|
+
const threadId = msg?.is_topic_message ? msg.message_thread_id : undefined;
|
|
140
|
+
return buildSessionKey(chatId, threadId);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* `botInfo` is what the startup token check already fetched (see
|
|
144
|
+
* startup/verify-token.ts). Handing it in makes `bot.init()` a no-op instead
|
|
145
|
+
* of a second getMe.
|
|
146
|
+
*/
|
|
147
|
+
export async function createBot(botInfo) {
|
|
148
|
+
// Start the IPC server for hook callbacks and the standalone MCP subprocess.
|
|
149
|
+
// Awaited so the bound port is known before anything else tries to spawn a
|
|
150
|
+
// subprocess that needs to reach us.
|
|
151
|
+
await startIpcServer();
|
|
152
|
+
// Support HTTP/HTTPS/SOCKS proxy for Telegram API (useful in restricted networks)
|
|
153
|
+
const proxyUrl = telegramProxyUrl();
|
|
154
|
+
if (proxyUrl) {
|
|
155
|
+
// A proxy URL can carry a user and password.
|
|
156
|
+
console.log(`[Bot] Using proxy: ${redactSecrets(proxyUrl)}`);
|
|
157
|
+
}
|
|
158
|
+
const bot = new Bot(config.TELEGRAM_BOT_TOKEN, {
|
|
159
|
+
botInfo,
|
|
160
|
+
client: telegramClientOptions(),
|
|
161
|
+
});
|
|
162
|
+
// Note which messages are ForceReply prompts, so a reply answering one still
|
|
163
|
+
// reaches the handlers in a group that otherwise requires an @mention.
|
|
164
|
+
trackForceReplyPrompts(bot);
|
|
165
|
+
// Auto-retry on transient network errors (ECONNRESET, socket hang up, etc.)
|
|
166
|
+
// Also handles 429 rate limits by respecting Telegram's retry_after
|
|
167
|
+
bot.api.config.use(autoRetry({
|
|
168
|
+
maxRetryAttempts: 5,
|
|
169
|
+
maxDelaySeconds: 60, // Cap retry delay at 60 seconds (will retry sooner rather than wait 900s)
|
|
170
|
+
rethrowInternalServerErrors: false, // Retry on 5xx errors
|
|
171
|
+
}));
|
|
172
|
+
// Register command menu for autocomplete (non-blocking)
|
|
173
|
+
const commandList = [
|
|
174
|
+
{ command: 'start', description: '🚀 Show help and getting started' },
|
|
175
|
+
{ command: 'project', description: '📁 Set working directory' },
|
|
176
|
+
{ command: 'newproject', description: '📁 Create a new project' },
|
|
177
|
+
{ command: 'newbot', description: '🤖 Create a bot for a project' },
|
|
178
|
+
{ command: 'status', description: '📊 Show current session status' },
|
|
179
|
+
{ command: 'clear', description: '🗑️ Clear conversation history' },
|
|
180
|
+
{ command: 'cancel', description: '⏹️ Stop the current request and drop anything queued' },
|
|
181
|
+
{ command: 'resume', description: '▶️ Resume a session' },
|
|
182
|
+
{ command: 'continue', description: '▶️ Continue last session' },
|
|
183
|
+
{ command: 'botstatus', description: '🩺 Show bot process status' },
|
|
184
|
+
{ command: 'version', description: '🏷️ Show the running version and whether it is the latest' },
|
|
185
|
+
{ command: 'restartbot', description: '🔁 Restart the bot' },
|
|
186
|
+
// An npm install has no source to rebuild; /update replaces it instead.
|
|
187
|
+
...(isCheckout() ? [{ command: 'rebuildbot', description: '🔄 Rebuild and restart with session restore' }] : []),
|
|
188
|
+
{ command: 'context', description: '🧠 Show Claude context usage' },
|
|
189
|
+
{ command: 'cost', description: '💰 Show usage limits and cost' },
|
|
190
|
+
{ command: 'compact', description: '🗜️ Compact the context window' },
|
|
191
|
+
{ command: 'update', description: isCheckout() ? '⬆️ Update the Claude Code CLI' : '⬆️ Update TeleCoder or the Claude Code CLI' },
|
|
192
|
+
{ command: 'plan', description: '📋 Start planning mode' },
|
|
193
|
+
{ command: 'explore', description: '🔍 Explore codebase' },
|
|
194
|
+
{ command: 'loop', description: '🔄 Run in loop mode' },
|
|
195
|
+
{ command: 'sessions', description: '📚 View saved sessions' },
|
|
196
|
+
{ command: 'fork', description: '🍴 Fork this conversation to another bot' },
|
|
197
|
+
{ command: 'spinoff', description: '🍴 Split a task off into a new thread' },
|
|
198
|
+
{ command: 'tree', description: '🌳 Show where this conversation branched, and jump between branches' },
|
|
199
|
+
{ command: 'accept', description: '📦 Accept a pending fork from another bot' },
|
|
200
|
+
{ command: 'decline', description: '🚫 Discard a pending fork' },
|
|
201
|
+
{ command: 'recap', description: '📋 Recap last messages of current session' },
|
|
202
|
+
{ command: 'prompts', description: '💬 List the prompts you sent, and branch from any of them' },
|
|
203
|
+
{ command: 'sync', description: '📨 Resend any missed reply from the session log' },
|
|
204
|
+
{ command: 'handoff', description: '📦 Export the session as a markdown handoff document' },
|
|
205
|
+
{ command: 'schedule', description: '🔔 Schedule a recurring prompt (e.g. every 1h, daily 9am)' },
|
|
206
|
+
{ command: 'schedules', description: '🔔 List active scheduled tasks' },
|
|
207
|
+
{ command: 'unschedule', description: '🔕 Remove a scheduled task by id' },
|
|
208
|
+
{ command: 'projectcommands', description: '📜 List slash commands from .claude/commands/' },
|
|
209
|
+
{ command: 'permissions', description: '🔐 Show the permission-gate state and guarded patterns' },
|
|
210
|
+
{ command: 'users', description: '👥 Show who can use this bot' },
|
|
211
|
+
{ command: 'allow', description: '✅ Let someone in — reply to them, or /allow @user' },
|
|
212
|
+
{ command: 'deny', description: '🚫 Remove someone admitted with /allow' },
|
|
213
|
+
{ command: 'members', description: '👥 Show who may prompt the agent in this group' },
|
|
214
|
+
{ command: 'teleport', description: '🚀 Move session to terminal' },
|
|
215
|
+
...(config.TRANSCRIBE_ENABLED ? [{ command: 'transcribe', description: '🎤 Transcribe audio to text' }] : []),
|
|
216
|
+
{ command: 'file', description: '📎 Download a file from project' },
|
|
217
|
+
{ command: 'telegraph', description: '📄 View markdown with Instant View' },
|
|
218
|
+
{ command: 'suggestions', description: '💡 Toggle predicted next-prompt buttons' },
|
|
219
|
+
{ command: 'model', description: '🤖 Switch AI model' },
|
|
220
|
+
{ command: 'effort', description: '🎯 Set reasoning effort level' },
|
|
221
|
+
{ command: 'verbosity', description: '🎚️ Set verbosity tier (quiet/normal/verbose/debug)' },
|
|
222
|
+
{ command: 'method', description: '🛰️ Switch Claude transport (SDK / PTY)' },
|
|
223
|
+
{ command: 'btw', description: '💬 Side question without interrupting' },
|
|
224
|
+
{ command: 'later', description: '🔔 Set an idea aside for after the turn' },
|
|
225
|
+
{ command: 'steer', description: '⚡ Stop the turn and send this instead' },
|
|
226
|
+
{ command: 'tasks', description: '🔄 List active background tasks' },
|
|
227
|
+
{ command: 'shells', description: '🔍 List & kill background shells (PTY mode)' },
|
|
228
|
+
...(config.CCR_ENABLED ? [{ command: 'provider', description: '🔌 Switch AI provider' }] : []),
|
|
229
|
+
...(config.CCR_ENABLED ? [{ command: 'ccr', description: '🔌 Toggle CCR routing (alt providers)' }] : []),
|
|
230
|
+
{ command: 'mode', description: '🔐 How much Claude asks before acting' },
|
|
231
|
+
{ command: 'autoapprove', description: '⚡ Approve guarded commands for a while' },
|
|
232
|
+
{ command: 'streaming', description: '⚙️ Toggle streaming / wait replies' },
|
|
233
|
+
{ command: 'terminalui', description: '🖥️ Toggle terminal-style display' },
|
|
234
|
+
{ command: 'statusline', description: '📍 Toggle per-turn status line' },
|
|
235
|
+
{ command: 'botname', description: '✏️ Toggle dynamic bot name' },
|
|
236
|
+
{ command: 'topic', description: '💬 Set current work topic in bot name' },
|
|
237
|
+
{ command: 'tts', description: '🔊 Toggle voice replies' },
|
|
238
|
+
{ command: 'ping', description: '🏓 Check if bot is responsive' },
|
|
239
|
+
{ command: 'commands', description: '📜 List all commands' },
|
|
240
|
+
];
|
|
241
|
+
bot.api.setMyCommands(commandList).then(() => {
|
|
242
|
+
console.log('📋 Command menu registered');
|
|
243
|
+
}).catch((err) => {
|
|
244
|
+
console.warn('⚠️ Failed to register commands:', err.message);
|
|
245
|
+
});
|
|
246
|
+
// Before everything else, so /rebuildbot's "when idle" sees an update from
|
|
247
|
+
// the moment it arrives until its reply has gone out.
|
|
248
|
+
bot.use(countUpdatesInFlight);
|
|
249
|
+
// Apply auth middleware to all updates
|
|
250
|
+
bot.use(authMiddleware);
|
|
251
|
+
// Note who named each private-chat thread, from the notices passing by, so a
|
|
252
|
+
// name the user chose is never replaced by the session topic.
|
|
253
|
+
initThreadTitles(bot);
|
|
254
|
+
// A project bot made by /newbot starts without threads, which only its owner
|
|
255
|
+
// can turn on: tell them how, with the first message they send it.
|
|
256
|
+
initThreadsSetup(bot);
|
|
257
|
+
// In groups, ignore messages that aren't addressed to the bot, so people can
|
|
258
|
+
// talk to each other without triggering a turn. Runs before the command
|
|
259
|
+
// handlers below because they'd otherwise answer a `/status@other_bot`
|
|
260
|
+
// aimed at a different bot in the same group.
|
|
261
|
+
bot.use(groupMentionMiddleware);
|
|
262
|
+
// Of the people an allow-listed group lets in, which ones may actually drive
|
|
263
|
+
// the agent. Runs after the mention gate so a spectator talking to the humans
|
|
264
|
+
// is never answered, and before every command handler below.
|
|
265
|
+
//
|
|
266
|
+
// Handles are learned upstream in authMiddleware, which records everyone the
|
|
267
|
+
// group sees — spectators included — so `/allow @someone` resolves for people
|
|
268
|
+
// who have only ever talked to the other humans.
|
|
269
|
+
bot.use(groupRoleMiddleware);
|
|
270
|
+
// A message answering telecoder_request_secret comes out of the stream
|
|
271
|
+
// here, deleted from the chat before anything below can batch it, queue it
|
|
272
|
+
// or hand it to the agent. The turn that asked is blocked on the answer, so
|
|
273
|
+
// the answer can't wait in line behind it either. Commands pass, so /cancel
|
|
274
|
+
// still works.
|
|
275
|
+
bot.use(captureSecretMessages);
|
|
276
|
+
// Register through `cmd` rather than `bot.command` directly so the set of
|
|
277
|
+
// names TeleCoder claims stays discoverable at runtime. Registration order
|
|
278
|
+
// and placement relative to sequentialize are unchanged — `cmd` calls
|
|
279
|
+
// `bot.command` immediately. /projectcommands uses the recorded names to
|
|
280
|
+
// report which native Claude Code commands this bot shadows.
|
|
281
|
+
const cmd = (name, handler, opts) => {
|
|
282
|
+
registerBotCommandName(name, opts?.forwardsToAgent);
|
|
283
|
+
bot.command(name, handler);
|
|
284
|
+
};
|
|
285
|
+
// These commands fire BEFORE sequentialize so they bypass per-chat ordering.
|
|
286
|
+
// This lets them interrupt, inspect, or restart even when a query is hung.
|
|
287
|
+
cmd('cancel', handleCancel);
|
|
288
|
+
cmd('stop', handleCancel); // alias — natural expectation for "stop the current turn"
|
|
289
|
+
cmd('ping', withRunningNote(handlePing));
|
|
290
|
+
cmd('status', withRunningNote(handleStatus));
|
|
291
|
+
cmd('version', withRunningNote(handleVersion));
|
|
292
|
+
// Lifecycle and transport are admin-only: they act on every session in the
|
|
293
|
+
// bot, not just the caller's.
|
|
294
|
+
cmd('restartbot', adminOnly(handleRestartBot));
|
|
295
|
+
cmd('rebuildbot', adminOnly(handleRebuild));
|
|
296
|
+
// Access control is admin-only and bypasses sequentialize: a stranger
|
|
297
|
+
// typically turns up mid-turn, and an admin should be able to wave them in
|
|
298
|
+
// without waiting for whatever the group is already running to finish.
|
|
299
|
+
cmd('allow', adminOnly(handleAllow));
|
|
300
|
+
cmd('deny', adminOnly(handleDeny));
|
|
301
|
+
cmd('users', adminOnly(handleUsers));
|
|
302
|
+
cmd('btw', withRunningNote(handleBtw)); // Side question — must bypass queue to work mid-task
|
|
303
|
+
cmd('spinoff', handleSpinoffCommand); // Splits a task off into a new thread — bypasses the queue so it works mid-task
|
|
304
|
+
// Sets an idea aside for after the turn, so it can't wait behind that turn. And
|
|
305
|
+
// with nothing running, it's the one message that doesn't start one.
|
|
306
|
+
cmd('later', withRunningNote(handleLater));
|
|
307
|
+
// Stops the turn and sends a message in its place, so it can't wait behind that turn.
|
|
308
|
+
cmd('steer', handleSteer);
|
|
309
|
+
// Read-only, with nothing a running turn could be disturbed by, so they answer
|
|
310
|
+
// mid-turn rather than after it: a fixed list, a look at the session list or
|
|
311
|
+
// the bot process, a re-read of the transcript, and two that ask a probe of
|
|
312
|
+
// their own rather than the live session. Anything that changes the session
|
|
313
|
+
// or starts a turn stays behind sequentialize below.
|
|
314
|
+
cmd('commands', withRunningNote(handleCommands));
|
|
315
|
+
cmd('sessions', withRunningNote(handleSessions));
|
|
316
|
+
cmd('botstatus', withRunningNote(handleBotStatus));
|
|
317
|
+
cmd('recap', withRunningNote(handleRecap));
|
|
318
|
+
cmd('projectcommands', handleProjectCommands);
|
|
319
|
+
cmd('context', withRunningNote(handleContext));
|
|
320
|
+
cmd('tasks', handleTasks); // Read-only; must bypass queue so it works mid-stream
|
|
321
|
+
cmd('cost', withRunningNote(handleCost)); // Read-only probe + a peek at the live TUI panel; bypasses the queue so it answers mid-turn
|
|
322
|
+
cmd('shells', withRunningNote(handleShells)); // Lists/kills OS-level bg processes; must bypass queue to rescue hung sessions
|
|
323
|
+
cmd('members', handleMembers);
|
|
324
|
+
// /sync exists for the "I think a reply went missing" scenario, which by
|
|
325
|
+
// definition includes hung or sluggish turns — gating it on sequentialize
|
|
326
|
+
// would queue it behind the very turn the user wants to inspect.
|
|
327
|
+
cmd('sync', handleSync);
|
|
328
|
+
cmd('handoff', handleHandoff);
|
|
329
|
+
// /tree and /prompts are read-only until a button is tapped, so they answer
|
|
330
|
+
// mid-turn — "what did I just ask?" comes up while a long turn runs — and the
|
|
331
|
+
// buttons that switch conversations refuse while a reply is running.
|
|
332
|
+
cmd('tree', handleTreeCommand);
|
|
333
|
+
cmd('prompts', withRunningNote(handlePromptsCommand));
|
|
334
|
+
// Display preferences: each only flips a stored setting that a turn reads
|
|
335
|
+
// when it starts, so changing one mid-turn applies from the next turn and
|
|
336
|
+
// has no reason to wait for this one. Their menu buttons likewise.
|
|
337
|
+
cmd('statusline', handleStatusLine);
|
|
338
|
+
cmd('verbosity', handleVerbosity);
|
|
339
|
+
cmd('terminalui', handleTerminalUI);
|
|
340
|
+
cmd('streaming', handleStreaming);
|
|
341
|
+
cmd('tts', handleTTS);
|
|
342
|
+
cmd('suggestions', handleSuggestions);
|
|
343
|
+
bot.callbackQuery(/^statusline:/, handleStatusLineCallback);
|
|
344
|
+
bot.callbackQuery(/^verbosity:/, handleVerbosityCallback);
|
|
345
|
+
bot.callbackQuery(/^terminalui:/, handleTerminalUICallback);
|
|
346
|
+
bot.callbackQuery(/^mode:/, handleModeCallback);
|
|
347
|
+
bot.callbackQuery(/^tts:/, handleTTSCallback);
|
|
348
|
+
bot.callbackQuery(/^sugg:/, handleSuggestionsCallback);
|
|
349
|
+
// The same goes for the permission mode, which a turn applies as it starts,
|
|
350
|
+
// and for the bot's and the thread's names.
|
|
351
|
+
// /mode was the streaming toggle's name until this landed, and was kept as
|
|
352
|
+
// an alias for exactly as long as nothing better wanted it. Permission mode
|
|
353
|
+
// is what people were always going to mean by it.
|
|
354
|
+
cmd('mode', adminOnly(handlePermissionMode));
|
|
355
|
+
cmd('botname', handleBotName);
|
|
356
|
+
cmd('topic', handleTopic);
|
|
357
|
+
bot.callbackQuery(/^permmode:/, adminOnly(handlePermissionModeCallback));
|
|
358
|
+
bot.callbackQuery(/^botname:/, handleBotNameCallback);
|
|
359
|
+
// An auto-approve window matters most mid-turn: that's when the prompts it
|
|
360
|
+
// answers are turning up, and closing one can't wait for the turn either.
|
|
361
|
+
// Admins *and* approvers: opening a window is a decision about prompts, not
|
|
362
|
+
// a power over the bot, so it sits with the people who answer them.
|
|
363
|
+
cmd('autoapprove', adminOrApproverOnly(handleAutoApprove));
|
|
364
|
+
cmd('permissions', adminOnly(handlePermissions));
|
|
365
|
+
// Nothing here touches the session: a welcome text, a file sent from disk or
|
|
366
|
+
// published, and a new bot, which is a process of its own.
|
|
367
|
+
cmd('start', handleStart);
|
|
368
|
+
cmd('file', handleFile);
|
|
369
|
+
cmd('telegraph', handleTelegraph);
|
|
370
|
+
bot.callbackQuery(/^telegraph:/, handleTelegraphCallback);
|
|
371
|
+
// Creating a bot adds a process to the launcher and a token to instances.json.
|
|
372
|
+
cmd('newbot', adminOnly(handleNewBot));
|
|
373
|
+
// Schedule commands bypass sequentialize so they remain responsive even
|
|
374
|
+
// when a scheduled-fire turn is already running (the cap-enforcing create,
|
|
375
|
+
// the list, and the remove all need to work mid-stream).
|
|
376
|
+
cmd('schedule', handleSchedule);
|
|
377
|
+
cmd('schedules', handleSchedules);
|
|
378
|
+
cmd('unschedule', handleUnschedule);
|
|
379
|
+
// /tasks inline-keyboard buttons (view/back/refresh) also need to bypass
|
|
380
|
+
// sequentialize so they're responsive while a stream is active.
|
|
381
|
+
bot.callbackQuery(/^tasks:/, handleTasksCallback);
|
|
382
|
+
// /shells kill buttons must also bypass sequentialize — the whole point is to
|
|
383
|
+
// rescue a session whose current turn is hung waiting on a bg shell.
|
|
384
|
+
bot.callbackQuery(/^shells:/, handleShellsCallback);
|
|
385
|
+
// telecoder_ask_user button taps MUST bypass sequentialize: the agent
|
|
386
|
+
// query is mid-flight and waiting on this exact tap to complete the tool
|
|
387
|
+
// call. If the callback got queued, it'd deadlock behind the query that's
|
|
388
|
+
// waiting for it.
|
|
389
|
+
bot.callbackQuery(/^q:/, handleAskUserCallback);
|
|
390
|
+
// The Cancel button under a secret request, for the same reason.
|
|
391
|
+
bot.callbackQuery(/^secret:/, handleSecretCallback);
|
|
392
|
+
// /fork callbacks bypass sequentialize too: the user often taps Fork on a
|
|
393
|
+
// past message while a turn is running. Picker UI is non-destructive (it
|
|
394
|
+
// just shows another message), and accept/decline operate on file state,
|
|
395
|
+
// not the live agent, so they don't need to wait in line.
|
|
396
|
+
bot.callbackQuery(/^fork:/, handleForkCallback);
|
|
397
|
+
// /tree's buttons likewise: opening a point only redraws the message, and
|
|
398
|
+
// carrying on a branch or branching from a point checks for a running reply
|
|
399
|
+
// itself, so a tap mid-turn gets an answer instead of waiting in line.
|
|
400
|
+
bot.callbackQuery(/^tree:/, handleTreeCallback);
|
|
401
|
+
// /prompts' buttons for the same reasons: opening a prompt only redraws the
|
|
402
|
+
// message, and branching from one checks for a running reply itself.
|
|
403
|
+
bot.callbackQuery(/^prompts:/, handlePromptsCallback);
|
|
404
|
+
// "Take back" and "Ask me after" on a queued message: the turn it's waiting
|
|
405
|
+
// behind is exactly what these have to get past.
|
|
406
|
+
bot.callbackQuery(/^queued:/, handleQueuedCallback);
|
|
407
|
+
// An edit to a message that's still waiting has to land before the wait ends,
|
|
408
|
+
// so it can't wait in line itself.
|
|
409
|
+
bot.on('edited_message', handleEditedMessage);
|
|
410
|
+
initParkedMessages(bot);
|
|
411
|
+
setQueuedDiverters({ btw: askBtw, fork: forkPastRunningTurnIntoThread });
|
|
412
|
+
// Menu buttons for /restartbot and /rebuildbot must bypass sequentialize
|
|
413
|
+
// for the same reason their parent commands do: users tap these precisely
|
|
414
|
+
// when the bot is hung, so the callback can't be queued behind the stuck
|
|
415
|
+
// request.
|
|
416
|
+
// Access cards: same reasoning as the commands above — the card lands while
|
|
417
|
+
// a turn is running, and it is the fastest way to answer it.
|
|
418
|
+
bot.callbackQuery(/^access:/, adminOnly(handleAccessCallback));
|
|
419
|
+
bot.callbackQuery(/^restartbot:/, adminOnly(handleRestartBotCallback));
|
|
420
|
+
bot.callbackQuery(/^rebuild:/, adminOnly(handleRebuildCallback));
|
|
421
|
+
// Batch consecutive text messages BEFORE sequentialize.
|
|
422
|
+
// When Telegram splits a long paste into multiple messages, this combines
|
|
423
|
+
// them into a single prompt. Must run before sequentialize because that
|
|
424
|
+
// middleware serializes same-session updates (preventing concurrent batching).
|
|
425
|
+
bot.use(createBatchMiddleware());
|
|
426
|
+
// Sequentialize: same-chat updates are processed in order.
|
|
427
|
+
// This runs AFTER /cancel so cancel bypasses it.
|
|
428
|
+
//
|
|
429
|
+
// It's also where a message waits while a turn runs, so the two either side
|
|
430
|
+
// of it tell the sender so and let them take the message back. They have to
|
|
431
|
+
// stay wrapped around it: see middleware/queued-messages.ts.
|
|
432
|
+
bot.use(trackQueuedMessage);
|
|
433
|
+
bot.use(sequentialize(getSequentializeKey));
|
|
434
|
+
bot.use(holdQueuedMessage);
|
|
435
|
+
// Bot command handlers (sequentialized per chat)
|
|
436
|
+
cmd('clear', handleClear);
|
|
437
|
+
// Admin-only now that a group can hold contributors: repointing the bot
|
|
438
|
+
// moves everyone's session, and /teleport and /permissions reach the
|
|
439
|
+
// guardrails rather than the conversation.
|
|
440
|
+
cmd('project', adminOnly(handleProject));
|
|
441
|
+
cmd('newproject', adminOnly(handleNewProject));
|
|
442
|
+
// /compact is a native Claude Code slash command, not a bot command — route it
|
|
443
|
+
// through the normal message pipeline (handleMessage), which forwards it to
|
|
444
|
+
// the active provider. The PTY provider runs the real compaction and reports
|
|
445
|
+
// the token reduction; the SDK provider explains it's PTY-only. Registering it
|
|
446
|
+
// here (rather than relying on fall-through to the text handler) makes dispatch
|
|
447
|
+
// explicit and lets grammY match the group-chat `/compact@BotName` form.
|
|
448
|
+
cmd('compact', handleMessage, { forwardsToAgent: true });
|
|
449
|
+
cmd('update', adminOnly(handleUpdate));
|
|
450
|
+
cmd('model', handleModelCommand);
|
|
451
|
+
cmd('effort', handleEffort);
|
|
452
|
+
cmd('method', adminOnly(handleMethodCommand));
|
|
453
|
+
if (config.CCR_ENABLED) {
|
|
454
|
+
cmd('provider', adminOnly(handleProviderCommand));
|
|
455
|
+
}
|
|
456
|
+
if (config.CCR_ENABLED) {
|
|
457
|
+
cmd('ccr', adminOnly(handleCcrCommand));
|
|
458
|
+
}
|
|
459
|
+
cmd('plan', handlePlan);
|
|
460
|
+
cmd('explore', handleExplore);
|
|
461
|
+
// Session resume commands
|
|
462
|
+
cmd('resume', handleResume);
|
|
463
|
+
cmd('continue', handleContinue);
|
|
464
|
+
// Fork: /fork forks from current state; /accept and /decline are the
|
|
465
|
+
// slash-command equivalents of the target-side inline buttons.
|
|
466
|
+
cmd('fork', handleForkCommand);
|
|
467
|
+
cmd('accept', handleAcceptCommand);
|
|
468
|
+
cmd('decline', handleDeclineCommand);
|
|
469
|
+
// Loop mode
|
|
470
|
+
cmd('loop', handleLoop);
|
|
471
|
+
// Teleport to terminal
|
|
472
|
+
cmd('teleport', adminOnly(handleTeleport));
|
|
473
|
+
// Transcribe
|
|
474
|
+
if (config.TRANSCRIBE_ENABLED) {
|
|
475
|
+
cmd('transcribe', handleTranscribe);
|
|
476
|
+
}
|
|
477
|
+
// Callback query handler for inline keyboards
|
|
478
|
+
bot.on('callback_query:data', async (ctx) => {
|
|
479
|
+
const data = ctx.callbackQuery.data;
|
|
480
|
+
if (data.startsWith('resume:')) {
|
|
481
|
+
await handleResumeCallback(ctx);
|
|
482
|
+
}
|
|
483
|
+
else if (data.startsWith('provider_switch:')) {
|
|
484
|
+
await adminOnly(handleProviderSwitchCallback)(ctx);
|
|
485
|
+
}
|
|
486
|
+
else if (data.startsWith('provider:')) {
|
|
487
|
+
await adminOnly(handleProviderCallback)(ctx);
|
|
488
|
+
}
|
|
489
|
+
else if (data.startsWith('prefs_all:')) {
|
|
490
|
+
await handlePrefsAllCallback(ctx);
|
|
491
|
+
}
|
|
492
|
+
else if (data.startsWith('model:')) {
|
|
493
|
+
await handleModelCallback(ctx);
|
|
494
|
+
}
|
|
495
|
+
else if (data.startsWith('clear:')) {
|
|
496
|
+
await handleClearCallback(ctx);
|
|
497
|
+
}
|
|
498
|
+
else if (data.startsWith('project:')) {
|
|
499
|
+
await adminOnly(handleProjectCallback)(ctx);
|
|
500
|
+
}
|
|
501
|
+
else if (data.startsWith('restart:')) {
|
|
502
|
+
await handleRestartCallback(ctx);
|
|
503
|
+
}
|
|
504
|
+
else if (data.startsWith('startup:')) {
|
|
505
|
+
await handleStartupCallback(ctx);
|
|
506
|
+
}
|
|
507
|
+
else if (data.startsWith('update:')) {
|
|
508
|
+
await adminOnly(handleUpdateCallback)(ctx);
|
|
509
|
+
}
|
|
510
|
+
else if (data.startsWith('effort:')) {
|
|
511
|
+
await handleEffortCallback(ctx);
|
|
512
|
+
}
|
|
513
|
+
else if (data.startsWith('method:')) {
|
|
514
|
+
await adminOnly(handleMethodCallback)(ctx);
|
|
515
|
+
}
|
|
516
|
+
else if (data.startsWith('ccr_throttle:')) {
|
|
517
|
+
await handleCcrThrottleCallback(ctx);
|
|
518
|
+
}
|
|
519
|
+
else if (data.startsWith('sgt:')) {
|
|
520
|
+
await handleSuggestionTapCallback(ctx);
|
|
521
|
+
}
|
|
522
|
+
// Note: `tasks:` callback queries are handled by the pre-sequentialize
|
|
523
|
+
// bot.callbackQuery handler above so they remain responsive mid-stream.
|
|
524
|
+
});
|
|
525
|
+
// Resolve pending telecoder_poll_user MCP calls on first vote. Must be
|
|
526
|
+
// registered before the catch-all paths so the poll_answer update reaches
|
|
527
|
+
// us; non-anonymous polls only fire poll_answer for non-anonymous voting,
|
|
528
|
+
// which is required for the resolve-on-first-vote semantics to work.
|
|
529
|
+
bot.on('poll_answer', async (ctx) => {
|
|
530
|
+
const pa = ctx.pollAnswer;
|
|
531
|
+
if (!pa)
|
|
532
|
+
return;
|
|
533
|
+
const resolved = resolvePendingPoll(pa.poll_id, pa.option_ids);
|
|
534
|
+
if (!resolved) {
|
|
535
|
+
// Not a TeleCoder-tracked poll — ignore (could be a user-created poll
|
|
536
|
+
// in the same chat).
|
|
537
|
+
}
|
|
538
|
+
});
|
|
539
|
+
// The bot a /newbot button created. The handler checks for an admin itself,
|
|
540
|
+
// and quietly: anyone with a t.me/newbot link can create one.
|
|
541
|
+
bot.on('message:managed_bot_created', handleManagedBotCreated);
|
|
542
|
+
// Handle voice messages
|
|
543
|
+
bot.on('message:voice', handleVoice);
|
|
544
|
+
// Handle audio messages (music/audio files - separate from voice notes)
|
|
545
|
+
bot.on('message:audio', handleTranscribeAudio);
|
|
546
|
+
// Handle images
|
|
547
|
+
bot.on('message:photo', handlePhoto);
|
|
548
|
+
// Handle documents: route by MIME type
|
|
549
|
+
// audio/* (replying to transcribe prompt) → transcribe
|
|
550
|
+
// image/* → image vision
|
|
551
|
+
// anything else → read as text/PDF/etc.
|
|
552
|
+
bot.on('message:document', async (ctx) => {
|
|
553
|
+
const doc = ctx.message?.document;
|
|
554
|
+
const mime = doc?.mime_type ?? '';
|
|
555
|
+
// Try transcribe-document path first (audio MIME + reply to ForceReply)
|
|
556
|
+
const replyTo = ctx.message?.reply_to_message;
|
|
557
|
+
if (replyTo && replyTo.from?.is_bot && mime.startsWith('audio/')) {
|
|
558
|
+
const replyText = replyTo.text || '';
|
|
559
|
+
if (replyText.includes('Transcribe Audio')) {
|
|
560
|
+
await handleTranscribeDocument(ctx);
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
if (mime.startsWith('image/')) {
|
|
565
|
+
await handleImageDocument(ctx);
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
// Audio and video documents have no ingestion path, but say so rather than
|
|
569
|
+
// dropping them. This used to be a bare `return`: an mp3 sent as a file
|
|
570
|
+
// produced no reply, no log line, nothing — indistinguishable from the bot
|
|
571
|
+
// being down. Everything else (PDF, text, code, CSV, …) goes to the
|
|
572
|
+
// document reader.
|
|
573
|
+
if (mime.startsWith('video/') || mime.startsWith('audio/')) {
|
|
574
|
+
await handleUnsupportedMediaDocument(ctx);
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
await handleTextDocument(ctx);
|
|
578
|
+
});
|
|
579
|
+
// Video, round video notes and GIFs — no handler matched these at all
|
|
580
|
+
// before, so they fell through the whole chain silently.
|
|
581
|
+
bot.on('message:video', handleUnsupportedVideo);
|
|
582
|
+
bot.on('message:video_note', handleUnsupportedVideo);
|
|
583
|
+
bot.on('message:animation', handleUnsupportedVideo);
|
|
584
|
+
// Handle regular text messages
|
|
585
|
+
bot.on('message:text', handleMessage);
|
|
586
|
+
// Error handler
|
|
587
|
+
bot.catch((err) => {
|
|
588
|
+
console.error('Bot error:', err);
|
|
589
|
+
});
|
|
590
|
+
return bot;
|
|
591
|
+
}
|
|
592
|
+
//# sourceMappingURL=bot.js.map
|