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.
- package/.env.example +375 -0
- package/CHANGELOG.md +1867 -0
- package/LICENSE +22 -0
- package/README.md +130 -2
- package/dist/audio/transcribe.js +41 -0
- package/dist/bin/mcp-server.js +363 -0
- package/dist/bin/tool-result.js +22 -0
- package/dist/bot/access/group-access.js +147 -0
- package/dist/bot/bot.js +573 -0
- package/dist/bot/command-catalog.js +263 -0
- package/dist/bot/deleted-threads.js +103 -0
- package/dist/bot/file-access.js +150 -0
- package/dist/bot/handlers/album.handler.js +128 -0
- package/dist/bot/handlers/branch.handler.js +1096 -0
- package/dist/bot/handlers/command/access.js +407 -0
- package/dist/bot/handlers/command/admin.js +803 -0
- package/dist/bot/handlers/command/all-view.js +33 -0
- package/dist/bot/handlers/command/auto-approve.js +138 -0
- package/dist/bot/handlers/command/background.js +37 -0
- package/dist/bot/handlers/command/botname.js +76 -0
- package/dist/bot/handlers/command/btw.js +175 -0
- package/dist/bot/handlers/command/cleanup.js +329 -0
- package/dist/bot/handlers/command/model.js +226 -0
- package/dist/bot/handlers/command/prefs-scope.js +362 -0
- package/dist/bot/handlers/command/project.js +458 -0
- package/dist/bot/handlers/command/resume.js +325 -0
- package/dist/bot/handlers/command/session.js +299 -0
- package/dist/bot/handlers/command/settings.js +657 -0
- package/dist/bot/handlers/command/shared.js +207 -0
- package/dist/bot/handlers/command/tasks.js +681 -0
- package/dist/bot/handlers/command/thread.js +128 -0
- package/dist/bot/handlers/command/topic-store.js +74 -0
- package/dist/bot/handlers/command/topic.js +27 -0
- package/dist/bot/handlers/command/usage.js +382 -0
- package/dist/bot/handlers/command-fallback.js +179 -0
- package/dist/bot/handlers/command.handler.js +446 -0
- package/dist/bot/handlers/loop.handler.js +389 -0
- package/dist/bot/handlers/media-fallback.js +126 -0
- package/dist/bot/handlers/message/replies.js +56 -0
- package/dist/bot/handlers/message/shared.js +95 -0
- package/dist/bot/handlers/message/turn-notify.js +135 -0
- package/dist/bot/handlers/message/turn-runner.js +56 -0
- package/dist/bot/handlers/message.handler.js +114 -0
- package/dist/bot/handlers/newbot.handler.js +230 -0
- package/dist/bot/handlers/photo.handler.js +286 -0
- package/dist/bot/handlers/prompts.handler.js +343 -0
- package/dist/bot/handlers/running-note.js +44 -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 +147 -0
- package/dist/bot/kept-threads.js +51 -0
- package/dist/bot/middleware/admin-only.js +49 -0
- package/dist/bot/middleware/album-collector.js +69 -0
- package/dist/bot/middleware/auth.middleware.js +122 -0
- package/dist/bot/middleware/group-mention.middleware.js +145 -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 +1082 -0
- package/dist/bot/middleware/stale-filter.js +9 -0
- package/dist/build-info.json +8 -0
- package/dist/claude/ask-user-form.js +517 -0
- package/dist/claude/ask-user.js +363 -0
- package/dist/claude/auto-approve.js +225 -0
- package/dist/claude/auto-topic-haiku.js +143 -0
- package/dist/claude/available-commands.js +156 -0
- package/dist/claude/background-hint.js +91 -0
- package/dist/claude/branch-tree.js +393 -0
- package/dist/claude/carry-over.js +25 -0
- package/dist/claude/ccr-shim.js +48 -0
- package/dist/claude/charter-judge.js +214 -0
- package/dist/claude/claude-auth.js +117 -0
- package/dist/claude/command-parser.js +206 -0
- package/dist/claude/cost-overlay-scraper.js +134 -0
- package/dist/claude/effort-level.js +5 -0
- package/dist/claude/enabled-plugins.js +52 -0
- package/dist/claude/in-flight-tracker.js +82 -0
- package/dist/claude/ipc-server.js +192 -0
- package/dist/claude/mcp-bridge.js +481 -0
- package/dist/claude/memory-guard.js +400 -0
- package/dist/claude/message-offsets.js +88 -0
- package/dist/claude/modal-relay.js +817 -0
- package/dist/claude/model-catalog.js +102 -0
- package/dist/claude/monitor-relay.js +712 -0
- package/dist/claude/native-commands.js +40 -0
- package/dist/claude/pending-branches.js +93 -0
- package/dist/claude/pending-suggestions.js +50 -0
- package/dist/claude/permission-gate.js +338 -0
- package/dist/claude/permission-mode.js +152 -0
- package/dist/claude/poll-user.js +51 -0
- package/dist/claude/prewarm.js +70 -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-idle-reaper.js +96 -0
- package/dist/claude/pty-provider.js +2499 -0
- package/dist/claude/pty-spawn-config.js +343 -0
- package/dist/claude/pty-stream.js +363 -0
- package/dist/claude/pty-watch.js +201 -0
- package/dist/claude/request-queue.js +107 -0
- package/dist/claude/rewind.js +111 -0
- package/dist/claude/scheduled-runner.js +89 -0
- package/dist/claude/scheduler.js +241 -0
- package/dist/claude/scope-guard.js +279 -0
- package/dist/claude/screen-marks.js +83 -0
- package/dist/claude/screen-render.js +96 -0
- package/dist/claude/secret-request.js +576 -0
- package/dist/claude/session-history.js +288 -0
- package/dist/claude/session-jsonl.js +1067 -0
- package/dist/claude/session-manager.js +216 -0
- package/dist/claude/session-move.js +70 -0
- package/dist/claude/session-scan.js +270 -0
- package/dist/claude/setup-token.js +285 -0
- package/dist/claude/shell-mode-gate.js +60 -0
- package/dist/claude/side-call-options.js +45 -0
- package/dist/claude/side-question.js +252 -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/tasks-overlay-scraper.js +217 -0
- package/dist/claude/thread-judge-haiku.js +88 -0
- package/dist/claude/tip-scraper.js +77 -0
- package/dist/claude/tui-modal.js +746 -0
- package/dist/claude/tui-state.js +456 -0
- package/dist/claude/turn-end.js +105 -0
- package/dist/claude/turn-prose.js +64 -0
- package/dist/claude/typed-answer.js +104 -0
- package/dist/claude/update-banner-relay.js +70 -0
- package/dist/cli/commands/doctor.js +338 -0
- package/dist/cli/commands/help.js +34 -0
- package/dist/cli/commands/init.js +126 -0
- package/dist/cli/commands/service.js +710 -0
- package/dist/cli/commands/start.js +63 -0
- package/dist/cli/commands/version.js +11 -0
- package/dist/cli/commands/watch.js +322 -0
- package/dist/cli/dispatch.js +84 -0
- package/dist/cli/init/env-file.js +99 -0
- package/dist/cli/init/flow.js +705 -0
- package/dist/cli/init/prompter.js +124 -0
- package/dist/cli/init/telegram.js +120 -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 +525 -0
- package/dist/index.js +443 -0
- package/dist/launcher.js +960 -0
- package/dist/node-version-check.js +27 -0
- package/dist/providers/ccr-health.js +119 -0
- package/dist/providers/ccr-introspect.js +142 -0
- package/dist/providers/ccr-provider.js +59 -0
- package/dist/providers/claude-provider.js +10 -0
- package/dist/providers/prefs-sync.js +121 -0
- package/dist/providers/project-favorites.js +74 -0
- package/dist/providers/provider-router.js +128 -0
- package/dist/providers/provider-switch.js +91 -0
- package/dist/providers/spawn-settings.js +45 -0
- package/dist/providers/types.js +8 -0
- package/dist/providers/user-preferences.js +322 -0
- package/dist/restart-when-idle.js +173 -0
- package/dist/startup/auto-continue.js +67 -0
- package/dist/startup/auto-resume.js +161 -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 +522 -0
- package/dist/telegram/admin-mention.js +107 -0
- package/dist/telegram/background-activity-card.js +502 -0
- package/dist/telegram/botname-settings.js +282 -0
- package/dist/telegram/button-text.js +26 -0
- package/dist/telegram/client-options.js +26 -0
- package/dist/telegram/deduplication.js +33 -0
- package/dist/telegram/entities.js +295 -0
- package/dist/telegram/force-reply-tracker.js +96 -0
- package/dist/telegram/lettered-options.js +87 -0
- package/dist/telegram/markdown.js +362 -0
- package/dist/telegram/message-sender.js +1019 -0
- package/dist/telegram/prompt-label.js +148 -0
- package/dist/telegram/prompt-suggestion.js +54 -0
- package/dist/telegram/send.js +123 -0
- package/dist/telegram/streaming-turn.js +103 -0
- package/dist/telegram/suggestions-settings.js +30 -0
- package/dist/telegram/table-lists.js +56 -0
- package/dist/telegram/task-list.js +367 -0
- package/dist/telegram/task-tracker.js +128 -0
- package/dist/telegram/terminal-renderer.js +667 -0
- package/dist/telegram/thread-titles.js +262 -0
- package/dist/telegram/threads-setup.js +117 -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-icon.js +248 -0
- package/dist/utils/bot-token.js +77 -0
- package/dist/utils/bounded-map.js +55 -0
- package/dist/utils/build-info.js +57 -0
- package/dist/utils/caffeinate.js +53 -0
- package/dist/utils/claude-env.js +53 -0
- package/dist/utils/claude-version.js +48 -0
- package/dist/utils/config-home.js +62 -0
- package/dist/utils/download.js +137 -0
- package/dist/utils/exit-codes.js +59 -0
- package/dist/utils/file-type.js +149 -0
- package/dist/utils/format.js +78 -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/memory-pressure.js +60 -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/resolve-bin.js +86 -0
- package/dist/utils/resolve-claude-bin.js +52 -0
- package/dist/utils/respawn-backoff.js +28 -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/telegram-proxy.js +72 -0
- package/dist/utils/uploads-dir.js +27 -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 +75 -4
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Everything posted to the chat *after* a turn's main response: the catch-up
|
|
3
|
+
* relay that recovers prose the extractors dropped, the compaction notice,
|
|
4
|
+
* and the status line that comes last. The usage footer isn't a message of its
|
|
5
|
+
* own: it goes out at the bottom of the status line, see `sendStatusLine`.
|
|
6
|
+
*
|
|
7
|
+
* The notice consults the chat's verbosity settings itself, and the status
|
|
8
|
+
* line the chat's /footer ones, so callers fire both unconditionally via
|
|
9
|
+
* `closeTurn`.
|
|
10
|
+
*/
|
|
11
|
+
import { sessionManager } from '../../../claude/session-manager.js';
|
|
12
|
+
import { readLastAssistantTurnText } from '../../../claude/session-jsonl.js';
|
|
13
|
+
import { getPtyProvider } from '../../../providers/claude-provider.js';
|
|
14
|
+
import { getCachedUsage } from '../../../providers/provider-router.js';
|
|
15
|
+
import { messageSender } from '../../../telegram/message-sender.js';
|
|
16
|
+
import { EntityText } from '../../../telegram/entities.js';
|
|
17
|
+
import { replyFormatted } from '../../../telegram/send.js';
|
|
18
|
+
import { bringCardDown } from '../../../telegram/background-activity-card.js';
|
|
19
|
+
import { resolveVerbosityFlags } from '../../../utils/verbosity.js';
|
|
20
|
+
import { fmtTokens } from '../../../utils/format.js';
|
|
21
|
+
import { sendStatusLine } from '../command/settings.js';
|
|
22
|
+
/**
|
|
23
|
+
* After a turn's main response has been sent to Telegram, compare what we
|
|
24
|
+
* relayed against the canonical assistant text in Claude Code's session JSONL.
|
|
25
|
+
* If the JSONL has more prose than we sent — typical for the lossy extractor
|
|
26
|
+
* paths (pure tool-call turns that returned empty, multi-block screen-scrape
|
|
27
|
+
* dropping earlier blocks, early end-of-turn before JSONL flush) — post the
|
|
28
|
+
* missing content as a follow-up. Updates the per-session tracker either way.
|
|
29
|
+
*
|
|
30
|
+
* Best-effort: any failure logs and swallows so a catch-up bug can never
|
|
31
|
+
* break the primary relay path. Skips silently when the session has no
|
|
32
|
+
* claudeSessionId yet, since there is no log to compare against.
|
|
33
|
+
*/
|
|
34
|
+
export async function relayCatchUpIfMissed(ctx, sessionKey, relayedText) {
|
|
35
|
+
try {
|
|
36
|
+
const session = sessionManager.getSession(sessionKey);
|
|
37
|
+
if (!session?.claudeSessionId) {
|
|
38
|
+
sessionManager.setLastRelayedAssistantText(sessionKey, relayedText);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
const jsonlText = readLastAssistantTurnText(session.workingDirectory, session.claudeSessionId) ?? '';
|
|
42
|
+
if (!jsonlText) {
|
|
43
|
+
sessionManager.setLastRelayedAssistantText(sessionKey, relayedText);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
// 20-char slack absorbs trailing-whitespace / trim differences between
|
|
47
|
+
// the screen-scrape and JSONL forms. Below that, treat as in sync.
|
|
48
|
+
if (jsonlText.length <= relayedText.length + 20) {
|
|
49
|
+
sessionManager.setLastRelayedAssistantText(sessionKey, jsonlText);
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
// If what we sent is a prefix of the canonical text (PTY happy path that
|
|
53
|
+
// truncated mid-stream), post only the suffix. Otherwise post the full
|
|
54
|
+
// canonical version — the texts come from different extractors and any
|
|
55
|
+
// mid-string diff would risk dropping the actually-missing content.
|
|
56
|
+
const missing = jsonlText.startsWith(relayedText) && relayedText.length > 0
|
|
57
|
+
? jsonlText.slice(relayedText.length).trim()
|
|
58
|
+
: jsonlText;
|
|
59
|
+
if (!missing) {
|
|
60
|
+
sessionManager.setLastRelayedAssistantText(sessionKey, jsonlText);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
await replyFormatted(ctx, new EntityText().add('📨 ').bold('Catch-up').add(' — recovered from session log').build());
|
|
64
|
+
await messageSender.sendMessage(ctx, missing);
|
|
65
|
+
sessionManager.setLastRelayedAssistantText(sessionKey, jsonlText);
|
|
66
|
+
}
|
|
67
|
+
catch (err) {
|
|
68
|
+
console.error('[CatchUp] post-relay check failed:', err instanceof Error ? err.message : err);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
async function sendCompactionNotification(ctx, compaction) {
|
|
72
|
+
if (!compaction)
|
|
73
|
+
return;
|
|
74
|
+
const chatId = ctx.chat?.id;
|
|
75
|
+
if (chatId === undefined)
|
|
76
|
+
return;
|
|
77
|
+
if (!resolveVerbosityFlags(chatId).notifyCompaction)
|
|
78
|
+
return;
|
|
79
|
+
const c = compaction;
|
|
80
|
+
console.log(`[Compaction] Sending notification: trigger=${c.trigger}, preTokens=${c.preTokens}`);
|
|
81
|
+
const emoji = c.trigger === 'auto' ? '⚠️' : 'ℹ️';
|
|
82
|
+
const triggerLabel = c.trigger === 'auto' ? 'Auto-compacted' : 'Manually compacted';
|
|
83
|
+
try {
|
|
84
|
+
// replyFormatted already retries unformatted if Telegram refuses the entities.
|
|
85
|
+
await replyFormatted(ctx, new EntityText()
|
|
86
|
+
.add(`${emoji} `).bold('Context Compacted').newline(2)
|
|
87
|
+
.add(`${triggerLabel} — previous context was ${fmtTokens(c.preTokens)} tokens.\n`)
|
|
88
|
+
.add('The agent now has a summarized version of your conversation.')
|
|
89
|
+
.build());
|
|
90
|
+
}
|
|
91
|
+
catch (err) {
|
|
92
|
+
console.error('[Compaction] Failed to send notification:', err);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* What closes a turn, however it started: the compaction notice, then the
|
|
97
|
+
* status line. A typed message, a voice note, an upload and a scheduled fire
|
|
98
|
+
* all end here. Each used to write its own ending, and only the typed
|
|
99
|
+
* message's had the status line, so a turn started any other way left the
|
|
100
|
+
* chat on the tail of its reply with nothing to say where things stood.
|
|
101
|
+
*
|
|
102
|
+
* `prompt` is what the turn was sent, for a session whose log has no prompts
|
|
103
|
+
* for the status line to list.
|
|
104
|
+
*/
|
|
105
|
+
export async function closeTurn(ctx, sessionKey, response, prompt, options) {
|
|
106
|
+
await sendCompactionNotification(ctx, response.compaction);
|
|
107
|
+
const chatId = ctx.chat?.id;
|
|
108
|
+
if (chatId === undefined)
|
|
109
|
+
return;
|
|
110
|
+
// Not every response carries a usage: a cancelled turn's doesn't. The line
|
|
111
|
+
// then shows what the session last had, rather than no model and no context.
|
|
112
|
+
const usage = response.usage ?? getCachedUsage(sessionKey);
|
|
113
|
+
await sendStatusLine(ctx, chatId, sessionKey, usage, prompt, options);
|
|
114
|
+
// The reply buried the card; tasks still running get it back below.
|
|
115
|
+
bringCardDown(sessionKey);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* The close of a turn claude started itself, when a background task reported
|
|
119
|
+
* back. Its reply is often the answer the exchange was for, it tends to land
|
|
120
|
+
* while the user is elsewhere, and no prompt of theirs sits above it, so it
|
|
121
|
+
* closes with the status line like any other.
|
|
122
|
+
*
|
|
123
|
+
* Nothing ran that turn for us: there's no response to take the usage from,
|
|
124
|
+
* and the cached figure is the one the turn before it left. The session log
|
|
125
|
+
* has what this one left. The prompts come from the log as well, which lists
|
|
126
|
+
* what the user sent and not what a task reported.
|
|
127
|
+
*/
|
|
128
|
+
export async function closeSelfStartedTurn(ctx, sessionKey) {
|
|
129
|
+
const chatId = ctx.chat?.id;
|
|
130
|
+
if (chatId === undefined)
|
|
131
|
+
return;
|
|
132
|
+
await sendStatusLine(ctx, chatId, sessionKey, getPtyProvider().refreshUsage(sessionKey));
|
|
133
|
+
bringCardDown(sessionKey);
|
|
134
|
+
}
|
|
135
|
+
//# sourceMappingURL=turn-notify.js.map
|
|
@@ -0,0 +1,56 @@
|
|
|
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 one path a prompt takes, so the typed-message and
|
|
6
|
+
* suggestion-tap entry points cannot drift apart.
|
|
7
|
+
*/
|
|
8
|
+
import { sendToAgent } from '../../../providers/provider-router.js';
|
|
9
|
+
import { messageSender } from '../../../telegram/message-sender.js';
|
|
10
|
+
import { progressCallbacks, toolCallbacks, withStreamingTurn } from '../../../telegram/streaming-turn.js';
|
|
11
|
+
import { fireAutoTopic } from './shared.js';
|
|
12
|
+
import { closeTurn, relayCatchUpIfMissed } from './turn-notify.js';
|
|
13
|
+
import { guardSpawn } from '../../../claude/memory-guard.js';
|
|
14
|
+
/**
|
|
15
|
+
* Run one prompt in whichever response mode the chat is currently set to.
|
|
16
|
+
* Every entry point that executes a user prompt funnels through here, so the
|
|
17
|
+
* streaming-vs-wait decision lives in exactly one place.
|
|
18
|
+
*/
|
|
19
|
+
export async function runTurn(ctx, sessionKey, message) {
|
|
20
|
+
// A message that would start a new claude on a machine short of memory is
|
|
21
|
+
// held until the chat says so (see memory-guard.ts). One to a running
|
|
22
|
+
// claude passes straight through.
|
|
23
|
+
const guard = await guardSpawn(ctx, sessionKey);
|
|
24
|
+
if (!guard.proceed) {
|
|
25
|
+
await ctx.reply(guard.message);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
await streamTurn(ctx, sessionKey, message);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Entry point used by callback-triggered prompts (suggestion-tap, CCR
|
|
32
|
+
* throttle retry). Dispatches through the same code path a typed message
|
|
33
|
+
* would take, and fires the topic update so the bot name still tracks the
|
|
34
|
+
* topic the user implicitly chose by tapping.
|
|
35
|
+
*/
|
|
36
|
+
export async function dispatchPromptFromCallback(ctx, sessionKey, message) {
|
|
37
|
+
fireAutoTopic(ctx, sessionKey, message);
|
|
38
|
+
await runTurn(ctx, sessionKey, message);
|
|
39
|
+
}
|
|
40
|
+
async function streamTurn(ctx, sessionKey, message) {
|
|
41
|
+
const startTime = Date.now();
|
|
42
|
+
await withStreamingTurn(ctx, sessionKey, message, async (abortController) => {
|
|
43
|
+
const response = await sendToAgent(sessionKey, message, {
|
|
44
|
+
...progressCallbacks(ctx),
|
|
45
|
+
...toolCallbacks(ctx, sessionKey),
|
|
46
|
+
abortController,
|
|
47
|
+
telegramCtx: ctx,
|
|
48
|
+
});
|
|
49
|
+
await messageSender.finishStreaming(ctx, response.text, { nextPromptSuggestion: response.nextPromptSuggestion });
|
|
50
|
+
await relayCatchUpIfMissed(ctx, sessionKey, response.text || '');
|
|
51
|
+
// Completion notification for long tasks (streaming edits don't trigger push notifications)
|
|
52
|
+
await messageSender.sendCompletionNotification(ctx, Date.now() - startTime);
|
|
53
|
+
await closeTurn(ctx, sessionKey, response, message);
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=turn-runner.js.map
|
|
@@ -0,0 +1,114 @@
|
|
|
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 branch 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
|
+
*
|
|
14
|
+
* Re-exports below keep the import path stable for bot.ts and the other
|
|
15
|
+
* consumers that predate the split.
|
|
16
|
+
*/
|
|
17
|
+
import { isDuplicate, markProcessed } from '../../telegram/deduplication.js';
|
|
18
|
+
import { isStaleMessage } from '../middleware/stale-filter.js';
|
|
19
|
+
import { isClaudeCommand, nativeCommandIn, stripCommandBotMention } from '../../claude/command-parser.js';
|
|
20
|
+
import { offerPendingBranchIfAny } from './branch.handler.js';
|
|
21
|
+
import { offerCommandFix } from './command-fallback.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 { handleDirReply } from './message/replies.js';
|
|
26
|
+
import { repliedForceReplyFlow } from '../../telegram/force-reply-tracker.js';
|
|
27
|
+
export { closeTurn, relayCatchUpIfMissed } from './message/turn-notify.js';
|
|
28
|
+
export { runQueuedTurn } from './message/shared.js';
|
|
29
|
+
export { dispatchPromptFromCallback } from './message/turn-runner.js';
|
|
30
|
+
export async function handleMessage(ctx) {
|
|
31
|
+
const rawText = ctx.message?.text;
|
|
32
|
+
if (!rawText)
|
|
33
|
+
return;
|
|
34
|
+
// In group chats Telegram appends `@BotName` to slash commands
|
|
35
|
+
// (`/compact@MyBot`). Strip it so command detection below — and native
|
|
36
|
+
// slash commands forwarded to the agent, like /compact — see a clean token
|
|
37
|
+
// rather than one the PTY TUI would type verbatim. No-op for ordinary text.
|
|
38
|
+
await deliver(ctx, stripCommandBotMention(rawText), false);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* `/cc <command>`: Claude Code's own command of that name, typed at it as if
|
|
42
|
+
* the bot had no command called the same. `/cc model` opens the picker the
|
|
43
|
+
* bot's `/model` stands in front of, and `/cc usage` the dialog behind the
|
|
44
|
+
* bot's `/usage`. From there it is a prompt like any
|
|
45
|
+
* other slash command the bot passes on: it waits its turn, and its dialog
|
|
46
|
+
* comes to the chat as buttons.
|
|
47
|
+
*/
|
|
48
|
+
export async function handleNativeCommand(ctx) {
|
|
49
|
+
const rawText = ctx.message?.text;
|
|
50
|
+
if (!rawText)
|
|
51
|
+
return;
|
|
52
|
+
const command = nativeCommandIn(rawText);
|
|
53
|
+
if (!command) {
|
|
54
|
+
await ctx.reply('Name the Claude Code command to run, as in /cc model or /cc usage.\n\n'
|
|
55
|
+
+ "It is for the commands a bot command of the same name hides. Claude Code's "
|
|
56
|
+
+ 'other commands work by typing them as they are.');
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
await deliver(ctx, command, true);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Take `text` through to the agent. `native` marks text that is a Claude Code
|
|
63
|
+
* command by the sender's own word (`/cc`), so it is neither checked for a
|
|
64
|
+
* typo of a bot command nor read as one.
|
|
65
|
+
*/
|
|
66
|
+
async function deliver(ctx, text, native) {
|
|
67
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
68
|
+
const messageId = ctx.message?.message_id;
|
|
69
|
+
const messageDate = ctx.message?.date;
|
|
70
|
+
if (!keyInfo || !messageId || !messageDate)
|
|
71
|
+
return;
|
|
72
|
+
const { sessionKey } = keyInfo;
|
|
73
|
+
// Filter stale messages (sent before bot started)
|
|
74
|
+
if (isStaleMessage(messageDate)) {
|
|
75
|
+
console.log(`[Message] Ignoring stale message ${messageId} from before bot start`);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
// Check for duplicate messages (Telegram retries)
|
|
79
|
+
if (isDuplicate(messageId)) {
|
|
80
|
+
console.log(`[Message] Ignoring duplicate message ${messageId}`);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
markProcessed(messageId);
|
|
84
|
+
// An answer to one of the bot's ForceReply prompts goes to the flow that asked.
|
|
85
|
+
const flow = repliedForceReplyFlow(ctx);
|
|
86
|
+
if (flow === 'dir') {
|
|
87
|
+
await handleDirReply(ctx, sessionKey, text);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
// A slash command the bot didn't register is on its way to Claude as a
|
|
91
|
+
// prompt. If it looks like a typo of a bot command, and Claude Code doesn't
|
|
92
|
+
// know it either, offer the likely commands instead.
|
|
93
|
+
if (!native && await offerCommandFix(ctx, sessionKey, text)) {
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
// Skip if this is a Claude command (handled by command handler)
|
|
97
|
+
if (!native && isClaudeCommand(text)) {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
// If a /branch from another bot is sitting in our pending-branches file, the
|
|
101
|
+
// user's first non-command message triggers the accept/decline prompt and
|
|
102
|
+
// gets held back. /branchaccept and /branchdecline (handled above as commands) bypass
|
|
103
|
+
// this — slash commands route to the command handler, not handleMessage.
|
|
104
|
+
if (await offerPendingBranchIfAny(ctx)) {
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
// Check for active session — falls back to disk if the bot restarted recently.
|
|
108
|
+
if (!await requireSession(ctx, sessionKey))
|
|
109
|
+
return;
|
|
110
|
+
fireAutoTopic(ctx, sessionKey, text);
|
|
111
|
+
// Queue the request - process one at a time per session
|
|
112
|
+
await runQueuedTurn(ctx, sessionKey, text, 'Message', () => runTurn(ctx, sessionKey, text));
|
|
113
|
+
}
|
|
114
|
+
//# sourceMappingURL=message.handler.js.map
|
|
@@ -0,0 +1,230 @@
|
|
|
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, give it the TeleCoder icon, 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, InputFile } from 'grammy';
|
|
18
|
+
import { isAdmin } from '../../utils/admins.js';
|
|
19
|
+
import { sanitizeError } from '../../utils/sanitize.js';
|
|
20
|
+
import { BOT_ICON_FILENAME, botIconJpeg } from '../../utils/bot-icon.js';
|
|
21
|
+
import { addInstance } from '../../utils/instances.js';
|
|
22
|
+
import { InstancesConfigError } from '../../utils/instance-config.js';
|
|
23
|
+
import { getWorkspaceRoot } from '../../utils/workspace-guard.js';
|
|
24
|
+
import { getSessionKeyFromCtx, parseSessionKey } from '../../utils/session-key.js';
|
|
25
|
+
import { sessionManager } from '../../claude/session-manager.js';
|
|
26
|
+
import { EntityText } from '../../telegram/entities.js';
|
|
27
|
+
import { replyFormatted, sendFormatted } from '../../telegram/send.js';
|
|
28
|
+
/** How long a /newbot waits for the bot it asked for. */
|
|
29
|
+
const PENDING_TTL_MS = 60 * 60_000;
|
|
30
|
+
/** Telegram's limits on a bot's name and username. */
|
|
31
|
+
const MAX_NAME_LENGTH = 64;
|
|
32
|
+
const MAX_USERNAME_LENGTH = 32;
|
|
33
|
+
const pending = new Map();
|
|
34
|
+
/** The name a new bot for `project` is offered: the user can change it. */
|
|
35
|
+
export function suggestedBotName(project) {
|
|
36
|
+
return `TeleCoder — ${project}`.slice(0, MAX_NAME_LENGTH);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The username a new bot for `project` is offered: lowercase letters, digits
|
|
40
|
+
* and underscores, ending in "bot", at most 32 long. Taken ones are refused
|
|
41
|
+
* on the creation screen, where the user can change it.
|
|
42
|
+
*/
|
|
43
|
+
export function suggestedBotUsername(project) {
|
|
44
|
+
const suffix = '_telecoder_bot';
|
|
45
|
+
const slug = project.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'project';
|
|
46
|
+
return `${slug.slice(0, MAX_USERNAME_LENGTH - suffix.length).replace(/_+$/, '')}${suffix}`;
|
|
47
|
+
}
|
|
48
|
+
let canManageBots;
|
|
49
|
+
/**
|
|
50
|
+
* Put the create-a-bot button for `projectPath` in front of `userId`, in
|
|
51
|
+
* their private chat with this bot (and in `threadId`, when given). Shared by
|
|
52
|
+
* /newbot and the telecoder_create_bot tool, so asking the agent for a bot
|
|
53
|
+
* gets the same button: Telegram only creates one when its user confirms.
|
|
54
|
+
*/
|
|
55
|
+
export async function offerNewBot(api, userId, projectPath, threadId) {
|
|
56
|
+
if (!isAdmin(userId))
|
|
57
|
+
return { ok: false, message: 'Only an admin of this bot can create bots.' };
|
|
58
|
+
// Only a yes is kept: a no should notice Bot Management Mode being turned on.
|
|
59
|
+
if (!canManageBots)
|
|
60
|
+
canManageBots = (await api.getMe()).can_manage_bots;
|
|
61
|
+
if (!canManageBots) {
|
|
62
|
+
return {
|
|
63
|
+
ok: false,
|
|
64
|
+
message: 'This bot can\'t create bots. Turn on Bot Management Mode for it in @BotFather\'s Mini App, then try again.',
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
if (!fs.existsSync(projectPath) || !fs.statSync(projectPath).isDirectory()) {
|
|
68
|
+
return { ok: false, message: `There's no project folder at ${projectPath}. Create it first — ask Claude to, or run mkdir.` };
|
|
69
|
+
}
|
|
70
|
+
const project = path.basename(projectPath);
|
|
71
|
+
pending.set(userId, { projectPath, at: Date.now() });
|
|
72
|
+
await sendFormatted(api, userId, new EntityText()
|
|
73
|
+
.add('🤖 Tap the button to create a bot for ').bold(project)
|
|
74
|
+
.add('. You can change its name and username on the next screen.\n\n')
|
|
75
|
+
.add('It starts in that project, and its threads are named without the project in front.')
|
|
76
|
+
.build(), {
|
|
77
|
+
...(threadId !== undefined ? { message_thread_id: threadId } : {}),
|
|
78
|
+
reply_markup: {
|
|
79
|
+
keyboard: [[{
|
|
80
|
+
text: `🤖 Create a bot for ${project}`,
|
|
81
|
+
request_managed_bot: {
|
|
82
|
+
request_id: Math.floor(Math.random() * 2 ** 31),
|
|
83
|
+
suggested_name: suggestedBotName(project),
|
|
84
|
+
suggested_username: suggestedBotUsername(project),
|
|
85
|
+
},
|
|
86
|
+
}]],
|
|
87
|
+
resize_keyboard: true,
|
|
88
|
+
one_time_keyboard: true,
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
return { ok: true, project };
|
|
92
|
+
}
|
|
93
|
+
/** The folder a project name or path means, the way /dir reads it. */
|
|
94
|
+
export function resolveProject(args) {
|
|
95
|
+
if (args.startsWith('~'))
|
|
96
|
+
return path.resolve(path.join(process.env.HOME || '', args.slice(1)));
|
|
97
|
+
if (args.startsWith('/'))
|
|
98
|
+
return path.resolve(args);
|
|
99
|
+
return path.join(getWorkspaceRoot(), args);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* The telecoder_create_bot tool: offer the button in the chat a turn runs
|
|
103
|
+
* in. Returns what to tell the agent, which is also what the user is waiting
|
|
104
|
+
* on: the bot only exists once they tap and confirm.
|
|
105
|
+
*/
|
|
106
|
+
export async function offerNewBotForSession(api, sessionKey, projectName) {
|
|
107
|
+
const { chatId, threadId } = parseSessionKey(sessionKey);
|
|
108
|
+
// A private chat's id is its user's id, and only there can the button go.
|
|
109
|
+
if (chatId <= 0)
|
|
110
|
+
return { ok: false, message: 'Bots can only be created from a private chat with this bot.' };
|
|
111
|
+
const projectPath = resolveProject(projectName.trim());
|
|
112
|
+
const result = await offerNewBot(api, chatId, projectPath, threadId);
|
|
113
|
+
if (!result.ok)
|
|
114
|
+
return result;
|
|
115
|
+
return {
|
|
116
|
+
ok: true,
|
|
117
|
+
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; ` +
|
|
118
|
+
'then this bot adds it to instances.json, the launcher starts it, and a confirmation follows in this chat.',
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
export async function handleNewBot(ctx) {
|
|
122
|
+
if (ctx.chat?.type !== 'private' || !ctx.from) {
|
|
123
|
+
await ctx.reply('/newbot works in a private chat with the bot.');
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const args = (ctx.message?.text ?? '').split(' ').slice(1).join(' ').trim();
|
|
127
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
128
|
+
const current = keyInfo ? sessionManager.getSession(keyInfo.sessionKey)?.workingDirectory : undefined;
|
|
129
|
+
const projectPath = args ? resolveProject(args) : current;
|
|
130
|
+
if (!projectPath) {
|
|
131
|
+
await ctx.reply('Usage: /newbot <project>, or /newbot alone for the project this chat is in.');
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
const threadId = ctx.message?.is_topic_message ? ctx.message.message_thread_id : undefined;
|
|
135
|
+
const result = await offerNewBot(ctx.api, ctx.from.id, projectPath, threadId);
|
|
136
|
+
if (!result.ok)
|
|
137
|
+
await ctx.reply(`🤖 ${result.message}`);
|
|
138
|
+
}
|
|
139
|
+
export async function handleManagedBotCreated(ctx) {
|
|
140
|
+
const created = ctx.message?.managed_bot_created?.bot;
|
|
141
|
+
const from = ctx.from;
|
|
142
|
+
if (!created || !from)
|
|
143
|
+
return;
|
|
144
|
+
if (!isAdmin(from.id)) {
|
|
145
|
+
console.log(`[NewBot] Ignoring bot ${created.id} created by non-admin ${from.id}`);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const waiting = pending.get(from.id);
|
|
149
|
+
pending.delete(from.id);
|
|
150
|
+
const projectPath = waiting && Date.now() - waiting.at < PENDING_TTL_MS ? waiting.projectPath : undefined;
|
|
151
|
+
const handle = created.username ? `@${created.username}` : created.first_name;
|
|
152
|
+
const done = { reply_markup: { remove_keyboard: true } };
|
|
153
|
+
let token;
|
|
154
|
+
try {
|
|
155
|
+
token = await ctx.api.getManagedBotToken(created.id);
|
|
156
|
+
}
|
|
157
|
+
catch (err) {
|
|
158
|
+
console.error('[NewBot] getManagedBotToken failed:', sanitizeError(err));
|
|
159
|
+
await ctx.reply(`❌ ${handle} was created, but its token couldn't be fetched: ${sanitizeError(err)}`, done);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
// ALLOWED_USER_IDS already keeps strangers out of the conversation; this
|
|
163
|
+
// keeps them from opening a chat with the bot at all. The creator is named
|
|
164
|
+
// as well as being its owner, which costs nothing: it was the first suspect
|
|
165
|
+
// when a creator's /start went missing, until the lost first message below
|
|
166
|
+
// turned out to be the cause.
|
|
167
|
+
let locked = true;
|
|
168
|
+
try {
|
|
169
|
+
await ctx.api.setManagedBotAccessSettings(created.id, true, { added_user_ids: [from.id] });
|
|
170
|
+
}
|
|
171
|
+
catch (err) {
|
|
172
|
+
locked = false;
|
|
173
|
+
console.warn('[NewBot] setManagedBotAccessSettings failed:', sanitizeError(err));
|
|
174
|
+
}
|
|
175
|
+
// Telegram seems to keep a new bot's updates only once it has asked for
|
|
176
|
+
// them: the first /start to two new bots, sent seconds after creation while
|
|
177
|
+
// their workers were still booting, was never delivered, and the second
|
|
178
|
+
// was. So ask once now, before anything links to the bot. No offset, so
|
|
179
|
+
// nothing is confirmed; whatever this returns, the worker gets again.
|
|
180
|
+
try {
|
|
181
|
+
await new Api(token).getUpdates({ timeout: 0, limit: 1 });
|
|
182
|
+
}
|
|
183
|
+
catch (err) {
|
|
184
|
+
console.warn('[NewBot] Priming getUpdates failed:', sanitizeError(err));
|
|
185
|
+
}
|
|
186
|
+
// A plain letter on a coloured disc is hard to tell from the next bot's, so
|
|
187
|
+
// the new bot starts with the TeleCoder icon. Its owner can change it later.
|
|
188
|
+
try {
|
|
189
|
+
await new Api(token).setMyProfilePhoto({ type: 'static', photo: new InputFile(botIconJpeg(), BOT_ICON_FILENAME) });
|
|
190
|
+
}
|
|
191
|
+
catch (err) {
|
|
192
|
+
console.warn('[NewBot] setMyProfilePhoto failed:', sanitizeError(err));
|
|
193
|
+
}
|
|
194
|
+
let name;
|
|
195
|
+
try {
|
|
196
|
+
name = addInstance({
|
|
197
|
+
name: created.first_name,
|
|
198
|
+
token,
|
|
199
|
+
overrides: projectPath ? { HOME_PROJECT: projectPath } : {},
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
catch (err) {
|
|
203
|
+
const reason = err instanceof InstancesConfigError ? err.message : sanitizeError(err);
|
|
204
|
+
console.error(`[NewBot] Couldn't add bot ${created.id} to instances.json: ${reason}`);
|
|
205
|
+
await ctx.reply(`❌ ${handle} was created, but instances.json couldn't take it: ${reason}`, done);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
console.log(`[NewBot] Added bot ${created.id} as "${name}"${projectPath ? ` for ${projectPath}` : ''}`);
|
|
209
|
+
const text = new EntityText().add('✅ ');
|
|
210
|
+
if (created.username)
|
|
211
|
+
text.link(handle, `https://t.me/${created.username}`);
|
|
212
|
+
else
|
|
213
|
+
text.bold(handle);
|
|
214
|
+
if (projectPath)
|
|
215
|
+
text.add(' is set up for ').bold(path.basename(projectPath)).add(' and starts in a few seconds.');
|
|
216
|
+
else
|
|
217
|
+
text.add(' is set up and starts in a few seconds. It has no project of its own: this /newbot had expired.');
|
|
218
|
+
text.newline(2)
|
|
219
|
+
.add('It has no threads yet: only you can turn them on, in ').link('@BotFather', 'https://t.me/BotFather')
|
|
220
|
+
.add("'s Mini App. Message it and it walks you through it, and tells you once they're on.");
|
|
221
|
+
if (!locked)
|
|
222
|
+
text.newline(2).add("⚠️ Couldn't restrict who can open it. Only allowed users get answers either way.");
|
|
223
|
+
await replyFormatted(ctx, text.build(), done);
|
|
224
|
+
}
|
|
225
|
+
/** Test hook. */
|
|
226
|
+
export function resetNewBotForTest() {
|
|
227
|
+
pending.clear();
|
|
228
|
+
canManageBots = undefined;
|
|
229
|
+
}
|
|
230
|
+
//# sourceMappingURL=newbot.handler.js.map
|