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
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turn execution: every path that actually runs a user prompt through a
|
|
3
|
+
* provider and renders the result into the chat.
|
|
4
|
+
*
|
|
5
|
+
* `runTurn` is the single place the streaming-vs-wait choice is made, so the
|
|
6
|
+
* typed-message, suggestion-tap and throttle-retry entry points cannot drift
|
|
7
|
+
* apart. `handleCcrThrottleCallback` lives here rather than in throttle.ts
|
|
8
|
+
* because it re-runs a prompt — keeping it here lets throttle.ts stay a leaf.
|
|
9
|
+
*/
|
|
10
|
+
import { sendToAgent, getActiveProviderName } from '../../../providers/provider-router.js';
|
|
11
|
+
import { switchProvider } from '../../../providers/provider-switch.js';
|
|
12
|
+
import { config } from '../../../config.js';
|
|
13
|
+
import { setAbortController } from '../../../claude/request-queue.js';
|
|
14
|
+
import { messageSender } from '../../../telegram/message-sender.js';
|
|
15
|
+
import { makeToolResultHandler, makeEditDiffHandler, progressCallbacks, toolCallbacks, withStreamingTurn } from '../../../telegram/streaming-turn.js';
|
|
16
|
+
import { maybeSendVoiceReply } from '../../../tts/voice-reply.js';
|
|
17
|
+
import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
|
|
18
|
+
import { getStreamingMode } from '../command.handler.js';
|
|
19
|
+
import { fireAutoTopic, runQueuedTurn } from './shared.js';
|
|
20
|
+
import { closeTurn, relayCatchUpIfMissed } from './turn-notify.js';
|
|
21
|
+
import { lastThrottledPrompt, postThrottlePrompt } from './throttle.js';
|
|
22
|
+
export async function handleCcrThrottleCallback(ctx) {
|
|
23
|
+
const data = ctx.callbackQuery?.data;
|
|
24
|
+
if (!data || !data.startsWith('ccr_throttle:'))
|
|
25
|
+
return;
|
|
26
|
+
const action = data.replace('ccr_throttle:', '');
|
|
27
|
+
const sessionKeyInfo = getSessionKeyFromCtx(ctx);
|
|
28
|
+
if (!sessionKeyInfo) {
|
|
29
|
+
await ctx.answerCallbackQuery({ text: 'Session not found' });
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
const { sessionKey } = sessionKeyInfo;
|
|
33
|
+
const chatId = ctx.chat?.id;
|
|
34
|
+
if (action === 'cancel') {
|
|
35
|
+
lastThrottledPrompt.delete(sessionKey);
|
|
36
|
+
await ctx.answerCallbackQuery({ text: 'Cancelled' });
|
|
37
|
+
await ctx.editMessageReplyMarkup({ reply_markup: undefined });
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (action === 'switch') {
|
|
41
|
+
if (!config.CCR_ENABLED || !chatId) {
|
|
42
|
+
await ctx.answerCallbackQuery({ text: 'CCR not available' });
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const pending = lastThrottledPrompt.get(sessionKey);
|
|
46
|
+
if (getActiveProviderName(sessionKey) !== 'ccr') {
|
|
47
|
+
// Fork onto a fresh CCR session, carrying over a summary so the retry
|
|
48
|
+
// keeps context. A direct resume would replay the Anthropic session's
|
|
49
|
+
// thinking blocks; CCR tolerates that, but forking keeps the two
|
|
50
|
+
// backends' sessions cleanly separated for the eventual switch back.
|
|
51
|
+
await switchProvider(sessionKey, 'ccr');
|
|
52
|
+
}
|
|
53
|
+
lastThrottledPrompt.delete(sessionKey);
|
|
54
|
+
await ctx.answerCallbackQuery({ text: 'Switched to CCR' });
|
|
55
|
+
await ctx.editMessageReplyMarkup({ reply_markup: undefined });
|
|
56
|
+
if (!pending) {
|
|
57
|
+
await ctx.reply('🔌 Switched to CCR. Send your message again to retry.');
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
await ctx.reply('🔁 Retrying via CCR...');
|
|
61
|
+
await runQueuedTurn(ctx, sessionKey, pending, 'CcrRetry', () => runTurn(ctx, sessionKey, chatId, pending));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Run one prompt in whichever response mode the chat is currently set to.
|
|
66
|
+
* Every entry point that executes a user prompt funnels through here, so the
|
|
67
|
+
* streaming-vs-wait decision lives in exactly one place.
|
|
68
|
+
*/
|
|
69
|
+
export async function runTurn(ctx, sessionKey, chatId, message) {
|
|
70
|
+
if (getStreamingMode() === 'streaming') {
|
|
71
|
+
await handleStreamingResponse(ctx, sessionKey, message);
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
await handleWaitResponse(ctx, sessionKey, chatId, message);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Entry point used by callback-triggered prompts (suggestion-tap, CCR
|
|
79
|
+
* throttle retry). Dispatches through the same code path a typed message
|
|
80
|
+
* would take, and fires the topic update so the bot name still tracks the
|
|
81
|
+
* topic the user implicitly chose by tapping.
|
|
82
|
+
*/
|
|
83
|
+
export async function dispatchPromptFromCallback(ctx, sessionKey, chatId, message) {
|
|
84
|
+
fireAutoTopic(ctx, sessionKey, message);
|
|
85
|
+
await runTurn(ctx, sessionKey, chatId, message);
|
|
86
|
+
}
|
|
87
|
+
async function handleStreamingResponse(ctx, sessionKey, message) {
|
|
88
|
+
const startTime = Date.now();
|
|
89
|
+
await withStreamingTurn(ctx, sessionKey, message, async (abortController) => {
|
|
90
|
+
const response = await sendToAgent(sessionKey, message, {
|
|
91
|
+
...progressCallbacks(ctx),
|
|
92
|
+
...toolCallbacks(ctx, sessionKey),
|
|
93
|
+
abortController,
|
|
94
|
+
telegramCtx: ctx,
|
|
95
|
+
});
|
|
96
|
+
await messageSender.finishStreaming(ctx, response.text, { nextPromptSuggestion: response.nextPromptSuggestion });
|
|
97
|
+
await relayCatchUpIfMissed(ctx, sessionKey, response.text || '');
|
|
98
|
+
await maybeSendVoiceReply(ctx, response.text);
|
|
99
|
+
// Completion notification for long tasks (streaming edits don't trigger push notifications)
|
|
100
|
+
await messageSender.sendCompletionNotification(ctx, Date.now() - startTime);
|
|
101
|
+
await closeTurn(ctx, sessionKey, response, message);
|
|
102
|
+
if (response.throttle) {
|
|
103
|
+
await postThrottlePrompt(ctx, sessionKey, message, response.throttle);
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
lastThrottledPrompt.delete(sessionKey);
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
async function handleWaitResponse(ctx, sessionKey, chatId, message) {
|
|
111
|
+
// Start continuous typing indicator (every 4s)
|
|
112
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
113
|
+
const typingInterval = messageSender.startTypingIndicator(ctx.api, chatId, keyInfo?.threadId);
|
|
114
|
+
const abortController = new AbortController();
|
|
115
|
+
setAbortController(sessionKey, abortController);
|
|
116
|
+
try {
|
|
117
|
+
const response = await sendToAgent(sessionKey, message, {
|
|
118
|
+
abortController,
|
|
119
|
+
telegramCtx: ctx,
|
|
120
|
+
onToolResult: makeToolResultHandler(ctx),
|
|
121
|
+
onEditDiff: makeEditDiffHandler(ctx),
|
|
122
|
+
});
|
|
123
|
+
messageSender.stopTypingInterval(typingInterval);
|
|
124
|
+
const sentId = await messageSender.sendMessage(ctx, response.text);
|
|
125
|
+
await messageSender.attachForkButton(ctx, sessionKey, sentId);
|
|
126
|
+
await relayCatchUpIfMissed(ctx, sessionKey, response.text || '');
|
|
127
|
+
await maybeSendVoiceReply(ctx, response.text);
|
|
128
|
+
await closeTurn(ctx, sessionKey, response, message);
|
|
129
|
+
if (response.throttle) {
|
|
130
|
+
await postThrottlePrompt(ctx, sessionKey, message, response.throttle);
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
lastThrottledPrompt.delete(sessionKey);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
messageSender.stopTypingInterval(typingInterval);
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
//# sourceMappingURL=turn-runner.js.map
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Entry point for ordinary (non-command) Telegram messages, plus the public
|
|
3
|
+
* surface of the message-handling domain.
|
|
4
|
+
*
|
|
5
|
+
* `handleMessage` decides what a message *is* — a reply to a ForceReply
|
|
6
|
+
* prompt, a pending fork to offer, or a prompt for the agent — and hands off to the module that owns that flow. The domains
|
|
7
|
+
* live in `./message/`:
|
|
8
|
+
*
|
|
9
|
+
* shared.ts helpers every entry point needs (session, topic, queueing)
|
|
10
|
+
* turn-runner.ts running a prompt through a provider; all turn entry points
|
|
11
|
+
* turn-notify.ts what gets posted after a turn: catch-up relay + notices
|
|
12
|
+
* replies.ts the ForceReply answer handlers
|
|
13
|
+
* throttle.ts CCR throttle state and the switch-and-retry prompt
|
|
14
|
+
*
|
|
15
|
+
* Re-exports below keep the import path stable for bot.ts and the other
|
|
16
|
+
* consumers that predate the split.
|
|
17
|
+
*/
|
|
18
|
+
import { isDuplicate, markProcessed } from '../../telegram/deduplication.js';
|
|
19
|
+
import { isStaleMessage } from '../middleware/stale-filter.js';
|
|
20
|
+
import { isClaudeCommand, stripCommandBotMention } from '../../claude/command-parser.js';
|
|
21
|
+
import { offerPendingForkIfAny } from './fork.handler.js';
|
|
22
|
+
import { getSessionKeyFromCtx } from '../../utils/session-key.js';
|
|
23
|
+
import { fireAutoTopic, requireSession, runQueuedTurn } from './message/shared.js';
|
|
24
|
+
import { runTurn } from './message/turn-runner.js';
|
|
25
|
+
import { handleProjectReply, handleFileReply, handleAgentReply, handleTelegraphReply, } from './message/replies.js';
|
|
26
|
+
export { closeTurn, relayCatchUpIfMissed } from './message/turn-notify.js';
|
|
27
|
+
export { runQueuedTurn } from './message/shared.js';
|
|
28
|
+
export { formatResetIn } from './message/throttle.js';
|
|
29
|
+
export { handleCcrThrottleCallback, dispatchPromptFromCallback } from './message/turn-runner.js';
|
|
30
|
+
export async function handleMessage(ctx) {
|
|
31
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
32
|
+
const rawText = ctx.message?.text;
|
|
33
|
+
const messageId = ctx.message?.message_id;
|
|
34
|
+
const messageDate = ctx.message?.date;
|
|
35
|
+
if (!keyInfo || !rawText || !messageId || !messageDate)
|
|
36
|
+
return;
|
|
37
|
+
const { chatId, sessionKey } = keyInfo;
|
|
38
|
+
// In group chats Telegram appends `@BotName` to slash commands
|
|
39
|
+
// (`/compact@MyBot`). Strip it so command detection below — and native
|
|
40
|
+
// slash commands forwarded to the agent, like /compact — see a clean token
|
|
41
|
+
// rather than one the PTY TUI would type verbatim. No-op for ordinary text.
|
|
42
|
+
const text = stripCommandBotMention(rawText);
|
|
43
|
+
// Filter stale messages (sent before bot started)
|
|
44
|
+
if (isStaleMessage(messageDate)) {
|
|
45
|
+
console.log(`[Message] Ignoring stale message ${messageId} from before bot start`);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
// Check for duplicate messages (Telegram retries)
|
|
49
|
+
if (isDuplicate(messageId)) {
|
|
50
|
+
console.log(`[Message] Ignoring duplicate message ${messageId}`);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
markProcessed(messageId);
|
|
54
|
+
// Check if this is a reply to a ForceReply prompt
|
|
55
|
+
const replyTo = ctx.message?.reply_to_message;
|
|
56
|
+
if (replyTo && replyTo.from?.is_bot) {
|
|
57
|
+
const replyText = replyTo.text || '';
|
|
58
|
+
// Handle project path reply
|
|
59
|
+
if (replyText.includes('Set Project Directory')) {
|
|
60
|
+
await handleProjectReply(ctx, sessionKey, text);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
// Handle telegraph/instant view reply (check BEFORE file - both have "file path")
|
|
64
|
+
if (replyText.includes('Instant View') || replyText.includes('Markdown files')) {
|
|
65
|
+
await handleTelegraphReply(ctx, sessionKey, text);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
// Handle file download reply
|
|
69
|
+
if (replyText.includes('Download File')) {
|
|
70
|
+
await handleFileReply(ctx, sessionKey, text);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
// Handle plan mode reply
|
|
74
|
+
if (replyText.includes('Plan Mode') || replyText.includes('Describe your task')) {
|
|
75
|
+
await handleAgentReply(ctx, sessionKey, text, 'plan');
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
// Handle explore mode reply
|
|
79
|
+
if (replyText.includes('Explore Mode') || replyText.includes('What would you like to know')) {
|
|
80
|
+
await handleAgentReply(ctx, sessionKey, text, 'explore');
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
// Handle loop mode reply
|
|
84
|
+
if (replyText.includes('Loop Mode') || replyText.includes('work iteratively')) {
|
|
85
|
+
await handleAgentReply(ctx, sessionKey, text, 'loop');
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
// Skip if this is a Claude command (handled by command handler)
|
|
90
|
+
if (isClaudeCommand(text)) {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
// If a /fork from another bot is sitting in our pending-forks file, the
|
|
94
|
+
// user's first non-command message triggers the accept/decline prompt and
|
|
95
|
+
// gets held back. /accept and /decline (handled above as commands) bypass
|
|
96
|
+
// this — slash commands route to the command handler, not handleMessage.
|
|
97
|
+
if (await offerPendingForkIfAny(ctx)) {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
// Check for active session — falls back to disk if the bot restarted recently.
|
|
101
|
+
if (!await requireSession(ctx, sessionKey))
|
|
102
|
+
return;
|
|
103
|
+
fireAutoTopic(ctx, sessionKey, text);
|
|
104
|
+
// Queue the request - process one at a time per session
|
|
105
|
+
await runQueuedTurn(ctx, sessionKey, text, 'Message', () => runTurn(ctx, sessionKey, chatId, text));
|
|
106
|
+
}
|
|
107
|
+
//# sourceMappingURL=message.handler.js.map
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* /newbot: a bot for one project, without a trip to BotFather.
|
|
3
|
+
*
|
|
4
|
+
* A bot with Bot Management Mode on (BotFather's Mini App) can offer a button
|
|
5
|
+
* that opens Telegram's own create-a-bot screen. Telegram reports the new bot
|
|
6
|
+
* in a `managed_bot_created` message, we fetch its token, lock it to its
|
|
7
|
+
* owner, and add it to instances.json with HOME_PROJECT set. The launcher
|
|
8
|
+
* watches that file and starts it.
|
|
9
|
+
*
|
|
10
|
+
* Telegram doesn't say which button a new bot came from, so the project
|
|
11
|
+
* waits here per user, from the /newbot to the bot it creates. And anyone can
|
|
12
|
+
* create a bot managed by ours through a t.me/newbot link, so only an admin's
|
|
13
|
+
* is adopted.
|
|
14
|
+
*/
|
|
15
|
+
import * as fs from 'fs';
|
|
16
|
+
import * as path from 'path';
|
|
17
|
+
import { Api } from 'grammy';
|
|
18
|
+
import { isAdmin } from '../../utils/admins.js';
|
|
19
|
+
import { sanitizeError } from '../../utils/sanitize.js';
|
|
20
|
+
import { addInstance } from '../../utils/instances.js';
|
|
21
|
+
import { InstancesConfigError } from '../../utils/instance-config.js';
|
|
22
|
+
import { getWorkspaceRoot } from '../../utils/workspace-guard.js';
|
|
23
|
+
import { getSessionKeyFromCtx, parseSessionKey } from '../../utils/session-key.js';
|
|
24
|
+
import { sessionManager } from '../../claude/session-manager.js';
|
|
25
|
+
import { EntityText } from '../../telegram/entities.js';
|
|
26
|
+
import { replyFormatted, sendFormatted } from '../../telegram/send.js';
|
|
27
|
+
/** How long a /newbot waits for the bot it asked for. */
|
|
28
|
+
const PENDING_TTL_MS = 60 * 60_000;
|
|
29
|
+
/** Telegram's limits on a bot's name and username. */
|
|
30
|
+
const MAX_NAME_LENGTH = 64;
|
|
31
|
+
const MAX_USERNAME_LENGTH = 32;
|
|
32
|
+
const pending = new Map();
|
|
33
|
+
/** The name a new bot for `project` is offered: the user can change it. */
|
|
34
|
+
export function suggestedBotName(project) {
|
|
35
|
+
return `TeleCoder — ${project}`.slice(0, MAX_NAME_LENGTH);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The username a new bot for `project` is offered: lowercase letters, digits
|
|
39
|
+
* and underscores, ending in "bot", at most 32 long. Taken ones are refused
|
|
40
|
+
* on the creation screen, where the user can change it.
|
|
41
|
+
*/
|
|
42
|
+
export function suggestedBotUsername(project) {
|
|
43
|
+
const suffix = '_telecoder_bot';
|
|
44
|
+
const slug = project.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'project';
|
|
45
|
+
return `${slug.slice(0, MAX_USERNAME_LENGTH - suffix.length).replace(/_+$/, '')}${suffix}`;
|
|
46
|
+
}
|
|
47
|
+
let canManageBots;
|
|
48
|
+
/**
|
|
49
|
+
* Put the create-a-bot button for `projectPath` in front of `userId`, in
|
|
50
|
+
* their private chat with this bot (and in `threadId`, when given). Shared by
|
|
51
|
+
* /newbot and the telecoder_create_bot tool, so asking the agent for a bot
|
|
52
|
+
* gets the same button: Telegram only creates one when its user confirms.
|
|
53
|
+
*/
|
|
54
|
+
export async function offerNewBot(api, userId, projectPath, threadId) {
|
|
55
|
+
if (!isAdmin(userId))
|
|
56
|
+
return { ok: false, message: 'Only an admin of this bot can create bots.' };
|
|
57
|
+
// Only a yes is kept: a no should notice Bot Management Mode being turned on.
|
|
58
|
+
if (!canManageBots)
|
|
59
|
+
canManageBots = (await api.getMe()).can_manage_bots;
|
|
60
|
+
if (!canManageBots) {
|
|
61
|
+
return {
|
|
62
|
+
ok: false,
|
|
63
|
+
message: 'This bot can\'t create bots. Turn on Bot Management Mode for it in @BotFather\'s Mini App, then try again.',
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
if (!fs.existsSync(projectPath) || !fs.statSync(projectPath).isDirectory()) {
|
|
67
|
+
return { ok: false, message: `There's no project folder at ${projectPath}. Create it with /newproject first.` };
|
|
68
|
+
}
|
|
69
|
+
const project = path.basename(projectPath);
|
|
70
|
+
pending.set(userId, { projectPath, at: Date.now() });
|
|
71
|
+
await sendFormatted(api, userId, new EntityText()
|
|
72
|
+
.add('🤖 Tap the button to create a bot for ').bold(project)
|
|
73
|
+
.add('. You can change its name and username on the next screen.\n\n')
|
|
74
|
+
.add('It starts in that project, and its threads are named without the project in front.')
|
|
75
|
+
.build(), {
|
|
76
|
+
...(threadId !== undefined ? { message_thread_id: threadId } : {}),
|
|
77
|
+
reply_markup: {
|
|
78
|
+
keyboard: [[{
|
|
79
|
+
text: `🤖 Create a bot for ${project}`,
|
|
80
|
+
request_managed_bot: {
|
|
81
|
+
request_id: Math.floor(Math.random() * 2 ** 31),
|
|
82
|
+
suggested_name: suggestedBotName(project),
|
|
83
|
+
suggested_username: suggestedBotUsername(project),
|
|
84
|
+
},
|
|
85
|
+
}]],
|
|
86
|
+
resize_keyboard: true,
|
|
87
|
+
one_time_keyboard: true,
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
return { ok: true, project };
|
|
91
|
+
}
|
|
92
|
+
/** The folder a project name or path means, the way /project reads it. */
|
|
93
|
+
export function resolveProject(args) {
|
|
94
|
+
if (args.startsWith('~'))
|
|
95
|
+
return path.resolve(path.join(process.env.HOME || '', args.slice(1)));
|
|
96
|
+
if (args.startsWith('/'))
|
|
97
|
+
return path.resolve(args);
|
|
98
|
+
return path.join(getWorkspaceRoot(), args);
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* The telecoder_create_bot tool: offer the button in the chat a turn runs
|
|
102
|
+
* in. Returns what to tell the agent, which is also what the user is waiting
|
|
103
|
+
* on: the bot only exists once they tap and confirm.
|
|
104
|
+
*/
|
|
105
|
+
export async function offerNewBotForSession(api, sessionKey, projectName) {
|
|
106
|
+
const { chatId, threadId } = parseSessionKey(sessionKey);
|
|
107
|
+
// A private chat's id is its user's id, and only there can the button go.
|
|
108
|
+
if (chatId <= 0)
|
|
109
|
+
return { ok: false, message: 'Bots can only be created from a private chat with this bot.' };
|
|
110
|
+
const projectPath = resolveProject(projectName.trim());
|
|
111
|
+
const result = await offerNewBot(api, chatId, projectPath, threadId);
|
|
112
|
+
if (!result.ok)
|
|
113
|
+
return result;
|
|
114
|
+
return {
|
|
115
|
+
ok: true,
|
|
116
|
+
message: `Sent the user a button to create a bot for ${result.project}. Nothing exists until they tap it and confirm on Telegram's screen; ` +
|
|
117
|
+
'then this bot adds it to instances.json, the launcher starts it, and a confirmation follows in this chat.',
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
export async function handleNewBot(ctx) {
|
|
121
|
+
if (ctx.chat?.type !== 'private' || !ctx.from) {
|
|
122
|
+
await ctx.reply('/newbot works in a private chat with the bot.');
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
const args = (ctx.message?.text ?? '').split(' ').slice(1).join(' ').trim();
|
|
126
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
127
|
+
const current = keyInfo ? sessionManager.getSession(keyInfo.sessionKey)?.workingDirectory : undefined;
|
|
128
|
+
const projectPath = args ? resolveProject(args) : current;
|
|
129
|
+
if (!projectPath) {
|
|
130
|
+
await ctx.reply('Usage: /newbot <project>, or /newbot alone for the project this chat is in.');
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
const threadId = ctx.message?.is_topic_message ? ctx.message.message_thread_id : undefined;
|
|
134
|
+
const result = await offerNewBot(ctx.api, ctx.from.id, projectPath, threadId);
|
|
135
|
+
if (!result.ok)
|
|
136
|
+
await ctx.reply(`🤖 ${result.message}`);
|
|
137
|
+
}
|
|
138
|
+
export async function handleManagedBotCreated(ctx) {
|
|
139
|
+
const created = ctx.message?.managed_bot_created?.bot;
|
|
140
|
+
const from = ctx.from;
|
|
141
|
+
if (!created || !from)
|
|
142
|
+
return;
|
|
143
|
+
if (!isAdmin(from.id)) {
|
|
144
|
+
console.log(`[NewBot] Ignoring bot ${created.id} created by non-admin ${from.id}`);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
const waiting = pending.get(from.id);
|
|
148
|
+
pending.delete(from.id);
|
|
149
|
+
const projectPath = waiting && Date.now() - waiting.at < PENDING_TTL_MS ? waiting.projectPath : undefined;
|
|
150
|
+
const handle = created.username ? `@${created.username}` : created.first_name;
|
|
151
|
+
const done = { reply_markup: { remove_keyboard: true } };
|
|
152
|
+
let token;
|
|
153
|
+
try {
|
|
154
|
+
token = await ctx.api.getManagedBotToken(created.id);
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
console.error('[NewBot] getManagedBotToken failed:', sanitizeError(err));
|
|
158
|
+
await ctx.reply(`❌ ${handle} was created, but its token couldn't be fetched: ${sanitizeError(err)}`, done);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
// ALLOWED_USER_IDS already keeps strangers out of the conversation; this
|
|
162
|
+
// keeps them from opening a chat with the bot at all. The creator is named
|
|
163
|
+
// as well as being its owner, which costs nothing: it was the first suspect
|
|
164
|
+
// when a creator's /start went missing, until the lost first message below
|
|
165
|
+
// turned out to be the cause.
|
|
166
|
+
let locked = true;
|
|
167
|
+
try {
|
|
168
|
+
await ctx.api.setManagedBotAccessSettings(created.id, true, { added_user_ids: [from.id] });
|
|
169
|
+
}
|
|
170
|
+
catch (err) {
|
|
171
|
+
locked = false;
|
|
172
|
+
console.warn('[NewBot] setManagedBotAccessSettings failed:', sanitizeError(err));
|
|
173
|
+
}
|
|
174
|
+
// Telegram seems to keep a new bot's updates only once it has asked for
|
|
175
|
+
// them: the first /start to two new bots, sent seconds after creation while
|
|
176
|
+
// their workers were still booting, was never delivered, and the second
|
|
177
|
+
// was. So ask once now, before anything links to the bot. No offset, so
|
|
178
|
+
// nothing is confirmed; whatever this returns, the worker gets again.
|
|
179
|
+
try {
|
|
180
|
+
await new Api(token).getUpdates({ timeout: 0, limit: 1 });
|
|
181
|
+
}
|
|
182
|
+
catch (err) {
|
|
183
|
+
console.warn('[NewBot] Priming getUpdates failed:', sanitizeError(err));
|
|
184
|
+
}
|
|
185
|
+
let name;
|
|
186
|
+
try {
|
|
187
|
+
name = addInstance({
|
|
188
|
+
name: created.first_name,
|
|
189
|
+
token,
|
|
190
|
+
overrides: projectPath ? { HOME_PROJECT: projectPath } : {},
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
catch (err) {
|
|
194
|
+
const reason = err instanceof InstancesConfigError ? err.message : sanitizeError(err);
|
|
195
|
+
console.error(`[NewBot] Couldn't add bot ${created.id} to instances.json: ${reason}`);
|
|
196
|
+
await ctx.reply(`❌ ${handle} was created, but instances.json couldn't take it: ${reason}`, done);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
console.log(`[NewBot] Added bot ${created.id} as "${name}"${projectPath ? ` for ${projectPath}` : ''}`);
|
|
200
|
+
const text = new EntityText().add('✅ ');
|
|
201
|
+
if (created.username)
|
|
202
|
+
text.link(handle, `https://t.me/${created.username}`);
|
|
203
|
+
else
|
|
204
|
+
text.bold(handle);
|
|
205
|
+
if (projectPath)
|
|
206
|
+
text.add(' is set up for ').bold(path.basename(projectPath)).add(' and starts in a few seconds.');
|
|
207
|
+
else
|
|
208
|
+
text.add(' is set up and starts in a few seconds. It has no project of its own: this /newbot had expired.');
|
|
209
|
+
text.newline(2)
|
|
210
|
+
.add('It has no threads yet: only you can turn them on, in ').link('@BotFather', 'https://t.me/BotFather')
|
|
211
|
+
.add("'s Mini App. Message it and it walks you through it, and tells you once they're on.");
|
|
212
|
+
if (!locked)
|
|
213
|
+
text.newline(2).add("⚠️ Couldn't restrict who can open it. Only allowed users get answers either way.");
|
|
214
|
+
await replyFormatted(ctx, text.build(), done);
|
|
215
|
+
}
|
|
216
|
+
/** Test hook. */
|
|
217
|
+
export function resetNewBotForTest() {
|
|
218
|
+
pending.clear();
|
|
219
|
+
canManageBots = undefined;
|
|
220
|
+
}
|
|
221
|
+
//# sourceMappingURL=newbot.handler.js.map
|