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,263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bot's command catalog: the `/` menu Telegram shows, and the two ways to
|
|
3
|
+
* find a command in it when the menu's prefix filter doesn't help.
|
|
4
|
+
*
|
|
5
|
+
* Telegram's menu filters on the start of the command name only — `/kill`
|
|
6
|
+
* finds nothing, `/task` finds nothing because the command is `/tasks`. So
|
|
7
|
+
* `/commands <words>` searches names and descriptions (`searchCommands`), and
|
|
8
|
+
* a slash command nobody registered is matched against the catalog for a
|
|
9
|
+
* likely typo (`suggestCommands`) before it would otherwise be typed into
|
|
10
|
+
* Claude as a prompt.
|
|
11
|
+
*
|
|
12
|
+
* The menu list lives here rather than in bot.ts so both lookups read the
|
|
13
|
+
* same names and descriptions Telegram shows. `site/scripts/check-commands.mjs`
|
|
14
|
+
* reads the `{ command: '…' }` entries off this file.
|
|
15
|
+
*/
|
|
16
|
+
import { config } from '../config.js';
|
|
17
|
+
import { isCheckout } from '../utils/install-mode.js';
|
|
18
|
+
import { EntityText } from '../telegram/entities.js';
|
|
19
|
+
import { isClaudeCommand } from '../claude/command-parser.js';
|
|
20
|
+
/** The menu Telegram shows for `/`, for this install's configuration. */
|
|
21
|
+
export function buildCommandMenu() {
|
|
22
|
+
return [
|
|
23
|
+
{ command: 'start', description: '🚀 Show help and getting started' },
|
|
24
|
+
{ command: 'dir', description: '📁 Set working directory' },
|
|
25
|
+
{ command: 'newbot', description: '🤖 Create a bot for a project' },
|
|
26
|
+
{ command: 'info', description: '📊 Show current session info' },
|
|
27
|
+
{ command: 'clear', description: '🗑️ Clear conversation history' },
|
|
28
|
+
{ command: 'cancel', description: '⏹️ Stop the current request and drop anything queued' },
|
|
29
|
+
{ command: 'resume', description: '▶️ Resume a session' },
|
|
30
|
+
{ command: 'botstatus', description: '🩺 Show bot process status' },
|
|
31
|
+
{ command: 'botversion', description: '🏷️ Show the running version and whether it is the latest' },
|
|
32
|
+
{ command: 'botrestart', description: '🔁 Restart the bot' },
|
|
33
|
+
// An npm install has no source to rebuild; /botupdate replaces it instead.
|
|
34
|
+
...(isCheckout() ? [{ command: 'botrebuild', description: '🔄 Rebuild and restart with session restore' }] : []),
|
|
35
|
+
{ command: 'context', description: '🧠 Show what fills the context window' },
|
|
36
|
+
{ command: 'usage', description: '💰 Show usage limits and cost (also /cost)' },
|
|
37
|
+
{ command: 'compact', description: '🗜️ Compact the context window' },
|
|
38
|
+
{ command: 'rewind', description: '⏪ Go back to an earlier prompt: conversation, code, or both' },
|
|
39
|
+
{ command: 'cc', description: "⤵️ Run Claude Code's own command where the bot has one too: /cc model" },
|
|
40
|
+
{ command: 'botupdate', description: isCheckout() ? '⬆️ Update the Claude Code CLI' : '⬆️ Update TeleCoder or the Claude Code CLI' },
|
|
41
|
+
{ command: 'branch', description: '🌱 Branch this conversation into a new thread or another bot' },
|
|
42
|
+
{ command: 'spinoff', description: '🌱 Split a task off into a new thread' },
|
|
43
|
+
{ command: 'threaddelete', description: '🗑️ Delete this thread and end its session' },
|
|
44
|
+
{ command: 'threadcleanup', description: '🧹 Delete idle threads in one go, leaving unfinished work alone' },
|
|
45
|
+
{ command: 'threadkeep', description: '📌 Keep this thread out of /threadcleanup' },
|
|
46
|
+
{ command: 'tree', description: '🌳 Show where this conversation branched, and jump between branches' },
|
|
47
|
+
{ command: 'branchaccept', description: '📦 Accept a pending branch from another bot' },
|
|
48
|
+
{ command: 'branchdecline', description: '🚫 Discard a pending branch' },
|
|
49
|
+
{ command: 'history', description: '📋 Re-read the last messages of this session' },
|
|
50
|
+
{ command: 'prompts', description: '💬 List the prompts you sent, and branch from any of them' },
|
|
51
|
+
{ command: 'resend', description: '📨 Resend any missed reply from the session log' },
|
|
52
|
+
{ command: 'loop', description: '🔁 Run a prompt now and again on an interval (5m, every 1h, daily 9am)' },
|
|
53
|
+
{ command: 'loops', description: '🔁 List your loops, with a button to stop each' },
|
|
54
|
+
{ command: 'projectcommands', description: '📜 List slash commands from .claude/commands/' },
|
|
55
|
+
{ command: 'gate', description: '🔐 Show the permission-gate state and guarded patterns' },
|
|
56
|
+
{ command: 'users', description: '👥 Show who can use this bot' },
|
|
57
|
+
{ command: 'allow', description: '✅ Let someone in — reply to them, or /allow @user' },
|
|
58
|
+
{ command: 'deny', description: '🚫 Remove someone admitted with /allow' },
|
|
59
|
+
{ command: 'members', description: '👥 Show who may prompt the agent in this group' },
|
|
60
|
+
{ command: 'terminal', description: '💻 Continue this session in a terminal' },
|
|
61
|
+
{ command: 'file', description: '📎 Download a file from project' },
|
|
62
|
+
{ command: 'suggestions', description: '💡 Toggle predicted next-prompt buttons' },
|
|
63
|
+
{ command: 'model', description: '🤖 Switch AI model' },
|
|
64
|
+
{ command: 'effort', description: '🎯 Set reasoning effort level' },
|
|
65
|
+
{ command: 'verbosity', description: '🎚️ Set verbosity tier (quiet/normal/verbose/debug)' },
|
|
66
|
+
{ command: 'btw', description: '💬 Side question without interrupting' },
|
|
67
|
+
{ command: 'later', description: '🔔 Set an idea aside for after the turn' },
|
|
68
|
+
{ command: 'steer', description: '⚡ Stop the turn and send this instead' },
|
|
69
|
+
{ command: 'tasks', description: '🔄 List active background tasks' },
|
|
70
|
+
{ command: 'ctrlb', description: "⏬ Move the command Claude is waiting on to the background (Claude Code's Ctrl+B)" },
|
|
71
|
+
{ command: 'shells', description: '🔍 List & kill background shells' },
|
|
72
|
+
...(config.CCR_ENABLED ? [{ command: 'ccr', description: '🔌 Switch between Claude and CCR (alt providers)' }] : []),
|
|
73
|
+
{ command: 'mode', description: '🔐 How much Claude asks before acting' },
|
|
74
|
+
{ command: 'autoapprove', description: '⚡ Approve guarded commands for a while' },
|
|
75
|
+
{ command: 'footer', description: '📍 Toggle the footer under each reply' },
|
|
76
|
+
{ command: 'botname', description: '✏️ Rename the bot (admins)' },
|
|
77
|
+
{ command: 'topic', description: '💬 Set the conversation topic' },
|
|
78
|
+
{ command: 'commands', description: '📜 List all commands' },
|
|
79
|
+
];
|
|
80
|
+
}
|
|
81
|
+
let catalog = [];
|
|
82
|
+
/** Remember the menu as registered, for the lookups below. */
|
|
83
|
+
export function setCommandCatalog(entries) {
|
|
84
|
+
catalog = [...entries];
|
|
85
|
+
}
|
|
86
|
+
export function getCommandCatalog() {
|
|
87
|
+
return catalog;
|
|
88
|
+
}
|
|
89
|
+
/** Leading emoji and other symbols off a menu description, lower-cased. */
|
|
90
|
+
function plainWords(text) {
|
|
91
|
+
return text
|
|
92
|
+
.toLowerCase()
|
|
93
|
+
.replace(/[^\p{L}\p{N}\s/.-]/gu, ' ')
|
|
94
|
+
.split(/\s+/)
|
|
95
|
+
.filter(Boolean);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Damerau–Levenshtein distance (optimal string alignment): one insertion,
|
|
99
|
+
* deletion, substitution or adjacent swap each count one.
|
|
100
|
+
*/
|
|
101
|
+
export function editDistance(a, b) {
|
|
102
|
+
const rows = a.length + 1;
|
|
103
|
+
const cols = b.length + 1;
|
|
104
|
+
const d = Array.from({ length: rows }, () => new Array(cols).fill(0));
|
|
105
|
+
for (let i = 0; i < rows; i++)
|
|
106
|
+
d[i][0] = i;
|
|
107
|
+
for (let j = 0; j < cols; j++)
|
|
108
|
+
d[0][j] = j;
|
|
109
|
+
for (let i = 1; i < rows; i++) {
|
|
110
|
+
for (let j = 1; j < cols; j++) {
|
|
111
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
112
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
113
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
114
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return d[a.length][b.length];
|
|
119
|
+
}
|
|
120
|
+
/** How many edits a typo of `token` may be away and still count. */
|
|
121
|
+
function typoBudget(token) {
|
|
122
|
+
return token.length >= 5 ? 2 : 1;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Commands a mistyped `/token` probably meant: a name the token is the start
|
|
126
|
+
* of (`/thread` → `/threadkeep`, `/threaddelete`), or one within a couple of
|
|
127
|
+
* edits (`/modle` → `/model`). Closest first, at most `limit`. Names outside
|
|
128
|
+
* the menu (`/cost`, the alias of `/usage`) come with an empty description.
|
|
129
|
+
*/
|
|
130
|
+
export function suggestCommands(token, names, entries = catalog, limit = 3) {
|
|
131
|
+
const typo = token.toLowerCase();
|
|
132
|
+
if (!typo)
|
|
133
|
+
return [];
|
|
134
|
+
const described = new Map(entries.map((e) => [e.command, e.description]));
|
|
135
|
+
const candidates = new Set([...described.keys(), ...names]);
|
|
136
|
+
const scored = [];
|
|
137
|
+
for (const name of candidates) {
|
|
138
|
+
let score;
|
|
139
|
+
if (name === typo) {
|
|
140
|
+
// Only a case variant gets here (`/Tasks`): the real name was never registered as typed.
|
|
141
|
+
score = -1;
|
|
142
|
+
}
|
|
143
|
+
else if (typo.length >= 3 && name.startsWith(typo)) {
|
|
144
|
+
// A prefix is the strongest signal; a shorter completion ranks higher.
|
|
145
|
+
score = (name.length - typo.length) / 100;
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
const d = editDistance(typo, name);
|
|
149
|
+
if (d <= typoBudget(typo))
|
|
150
|
+
score = d;
|
|
151
|
+
}
|
|
152
|
+
if (score !== undefined)
|
|
153
|
+
scored.push({ name, score });
|
|
154
|
+
}
|
|
155
|
+
scored.sort((a, b) => a.score - b.score || a.name.localeCompare(b.name));
|
|
156
|
+
return scored.slice(0, limit).map(({ name }) => ({ command: name, description: described.get(name) ?? '' }));
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Is `text` a slash command the bot never registered that looks like a typo of
|
|
160
|
+
* one it did? Pure: the caller still has to check Claude Code doesn't know the
|
|
161
|
+
* name either, since anything the bot doesn't own is Claude's to run.
|
|
162
|
+
*/
|
|
163
|
+
export function findCommandFix(text, opts) {
|
|
164
|
+
const m = text.match(/^\/([\w:-]+)(?:\s+([\s\S]*))?$/);
|
|
165
|
+
if (!m)
|
|
166
|
+
return null;
|
|
167
|
+
const token = m[1];
|
|
168
|
+
if (isClaudeCommand(text))
|
|
169
|
+
return null;
|
|
170
|
+
const names = new Set(opts.botNames);
|
|
171
|
+
if (names.has(token) || new Set(opts.forwarded).has(token))
|
|
172
|
+
return null;
|
|
173
|
+
const suggestions = suggestCommands(token, names, opts.entries ?? catalog);
|
|
174
|
+
return suggestions.length ? { token, args: (m[2] ?? '').trim(), suggestions } : null;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Menu entries matching every word of `query`, by name or description. A
|
|
178
|
+
* word matches a name it is part of, a description word it starts, or either
|
|
179
|
+
* within one edit when the word is long enough for that to mean something.
|
|
180
|
+
* Name matches rank above description matches.
|
|
181
|
+
*/
|
|
182
|
+
export function searchCommands(query, entries = catalog) {
|
|
183
|
+
const terms = plainWords(query.replace(/^\//, ''));
|
|
184
|
+
if (terms.length === 0)
|
|
185
|
+
return [];
|
|
186
|
+
// Spelling tolerance is for when nothing matches as typed; next to a real
|
|
187
|
+
// match it only adds noise (`model` would drag in `mode`).
|
|
188
|
+
return rank(terms, entries, false) ?? rank(terms, entries, true) ?? [];
|
|
189
|
+
}
|
|
190
|
+
function rank(terms, entries, fuzzy) {
|
|
191
|
+
const scored = [];
|
|
192
|
+
for (const entry of entries) {
|
|
193
|
+
const name = entry.command.toLowerCase();
|
|
194
|
+
const words = plainWords(entry.description);
|
|
195
|
+
let total = 0;
|
|
196
|
+
let all = true;
|
|
197
|
+
for (const term of terms) {
|
|
198
|
+
const s = termScore(term, name, words, fuzzy);
|
|
199
|
+
if (s === undefined) {
|
|
200
|
+
all = false;
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
total += s;
|
|
204
|
+
}
|
|
205
|
+
if (all)
|
|
206
|
+
scored.push({ entry, score: total });
|
|
207
|
+
}
|
|
208
|
+
if (scored.length === 0)
|
|
209
|
+
return undefined;
|
|
210
|
+
scored.sort((a, b) => a.score - b.score || a.entry.command.localeCompare(b.entry.command));
|
|
211
|
+
return scored.map(({ entry }) => entry);
|
|
212
|
+
}
|
|
213
|
+
/** Lower is better; undefined is no match. */
|
|
214
|
+
function termScore(term, name, words, fuzzy) {
|
|
215
|
+
if (name === term)
|
|
216
|
+
return 0;
|
|
217
|
+
if (name.startsWith(term))
|
|
218
|
+
return 1;
|
|
219
|
+
if (name.includes(term))
|
|
220
|
+
return 2;
|
|
221
|
+
if (words.some((w) => w.startsWith(term)))
|
|
222
|
+
return 3;
|
|
223
|
+
if (!fuzzy || term.length < 4)
|
|
224
|
+
return undefined;
|
|
225
|
+
if (editDistance(term, name) <= 1)
|
|
226
|
+
return 4;
|
|
227
|
+
if (words.some((w) => w.length >= 4 && editDistance(term, w) <= 1))
|
|
228
|
+
return 5;
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
|
231
|
+
/** A listing line per entry; the command is tappable in Telegram as typed. */
|
|
232
|
+
function listEntries(b, entries) {
|
|
233
|
+
entries.forEach((e, i) => {
|
|
234
|
+
if (i > 0)
|
|
235
|
+
b.newline();
|
|
236
|
+
b.add(`/${e.command}`);
|
|
237
|
+
if (e.description)
|
|
238
|
+
b.add(` — ${e.description}`);
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
/** What `/commands <query>` replies. */
|
|
242
|
+
export function buildCommandSearchMessage(query, matches) {
|
|
243
|
+
const b = new EntityText();
|
|
244
|
+
if (matches.length === 0) {
|
|
245
|
+
return b.add('🔎 No command matches ').italic(query).add('. ')
|
|
246
|
+
.code('/commands').add(' lists them all; ').code('/projectcommands')
|
|
247
|
+
.add(" lists Claude Code's own.").build();
|
|
248
|
+
}
|
|
249
|
+
b.add('🔎 Commands matching ').italic(query).add(':').newline(2);
|
|
250
|
+
listEntries(b, matches);
|
|
251
|
+
return b.build();
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* What a mistyped command gets instead of a trip to Claude. The buttons
|
|
255
|
+
* underneath run a suggestion with the arguments as typed.
|
|
256
|
+
*/
|
|
257
|
+
export function buildUnknownCommandMessage(token, suggestions) {
|
|
258
|
+
const b = new EntityText();
|
|
259
|
+
b.add('🤔 ').code(`/${token}`).add(" isn't a command of the bot's, and Claude Code didn't list one. Did you mean:").newline(2);
|
|
260
|
+
listEntries(b, suggestions);
|
|
261
|
+
return b.build();
|
|
262
|
+
}
|
|
263
|
+
//# sourceMappingURL=command-catalog.js.map
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Letting go of a thread that no longer exists.
|
|
3
|
+
*
|
|
4
|
+
* Telegram tells a bot nothing when a thread is deleted: no update, no service
|
|
5
|
+
* message. Left alone, the thread's session lives on — its PTY claude running
|
|
6
|
+
* until the next restart, a turn still working, renames and replies sent into
|
|
7
|
+
* the void. So the bot notices for itself, two ways:
|
|
8
|
+
*
|
|
9
|
+
* - /threaddelete deletes the thread and lets it go in the same step.
|
|
10
|
+
* - Any send into a deleted thread fails, with "message thread not found" for
|
|
11
|
+
* a message and TOPIC_ID_INVALID for a topic call (tested 2026-11-14), and
|
|
12
|
+
* that failure is taken as the news.
|
|
13
|
+
*
|
|
14
|
+
* A thread deleted by hand while idle sends nothing, so neither sees it; the
|
|
15
|
+
* PTY idle reaper (claude/pty-idle-reaper.ts) ends its claude instead.
|
|
16
|
+
*
|
|
17
|
+
* What's let go is what lives for the thread alone: its claude and turn, its
|
|
18
|
+
* in-memory session, its name, its own settings and its keep mark. The
|
|
19
|
+
* transcript stays on disk, so /resume in any chat can still pick the
|
|
20
|
+
* conversation up, and so does the chat history entry /resume takes its
|
|
21
|
+
* titles from. Which threads were let go is kept on disk, so /threadcleanup doesn't
|
|
22
|
+
* offer a deleted thread again after a restart.
|
|
23
|
+
*/
|
|
24
|
+
import * as path from 'path';
|
|
25
|
+
import { z } from 'zod';
|
|
26
|
+
import { BOT_ID } from '../config.js';
|
|
27
|
+
import { sessionManager } from '../claude/session-manager.js';
|
|
28
|
+
import { clearConversation } from '../providers/provider-router.js';
|
|
29
|
+
import { userPreferences } from '../providers/user-preferences.js';
|
|
30
|
+
import { forgetThreadTitle } from '../telegram/thread-titles.js';
|
|
31
|
+
import { buildSessionKey, parseSessionKey } from '../utils/session-key.js';
|
|
32
|
+
import { sanitizeError } from '../utils/sanitize.js';
|
|
33
|
+
import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
|
|
34
|
+
import { stopTurn } from './middleware/queued-messages.js';
|
|
35
|
+
import { forgetKeptThread } from './kept-threads.js';
|
|
36
|
+
const fileSchema = z.object({ threads: z.array(z.string()) });
|
|
37
|
+
function stateFile() {
|
|
38
|
+
return path.join(getStateDir(), `deleted-threads-${BOT_ID}.json`);
|
|
39
|
+
}
|
|
40
|
+
/** Thread ids aren't reused, so a thread let go stays let go. Loaded on first use. */
|
|
41
|
+
let forgottenSet;
|
|
42
|
+
function forgotten() {
|
|
43
|
+
forgottenSet ??= new Set(readJsonFile(stateFile(), fileSchema, 'DeletedThreads')?.threads ?? []);
|
|
44
|
+
return forgottenSet;
|
|
45
|
+
}
|
|
46
|
+
function remember(sessionKey) {
|
|
47
|
+
forgotten().add(sessionKey);
|
|
48
|
+
ensureStateDir(getStateDir(), 'DeletedThreads');
|
|
49
|
+
writeJsonFile(stateFile(), { threads: [...forgotten()] }, 'DeletedThreads');
|
|
50
|
+
}
|
|
51
|
+
/** Whether this thread was deleted, by /threaddelete, /threadcleanup or by hand as far as the bot noticed. */
|
|
52
|
+
export function isThreadForgotten(sessionKey) {
|
|
53
|
+
return forgotten().has(sessionKey);
|
|
54
|
+
}
|
|
55
|
+
/** Whether a failed Bot API call says the thread it was aimed at is gone. */
|
|
56
|
+
export function isThreadGoneError(description) {
|
|
57
|
+
return description !== undefined && /message thread not found|TOPIC_ID_INVALID|TOPIC_DELETED/i.test(description);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Stop and forget everything a deleted thread had going. Safe to call more
|
|
61
|
+
* than once, and from inside a send that failed: only the first call acts.
|
|
62
|
+
* Returns whether this call did.
|
|
63
|
+
*/
|
|
64
|
+
export async function forgetThread(api, sessionKey, why) {
|
|
65
|
+
if (parseSessionKey(sessionKey).threadId === undefined || forgotten().has(sessionKey))
|
|
66
|
+
return false;
|
|
67
|
+
// Before anything else, since stopping the turn can send into the thread again.
|
|
68
|
+
remember(sessionKey);
|
|
69
|
+
console.log(`[DeletedThreads] ${sessionKey} is gone (${why}), ending its session`);
|
|
70
|
+
try {
|
|
71
|
+
await stopTurn(api, sessionKey);
|
|
72
|
+
}
|
|
73
|
+
catch (err) {
|
|
74
|
+
console.error(`[DeletedThreads] Stopping the turn in ${sessionKey} failed:`, sanitizeError(err));
|
|
75
|
+
}
|
|
76
|
+
clearConversation(sessionKey);
|
|
77
|
+
sessionManager.clearSession(sessionKey);
|
|
78
|
+
forgetThreadTitle(sessionKey);
|
|
79
|
+
userPreferences.forgetThread(sessionKey);
|
|
80
|
+
forgetKeptThread(sessionKey);
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
/** Take a send that failed on a deleted thread as word that it's gone. Call once, at startup. */
|
|
84
|
+
export function watchForDeletedThreads(bot) {
|
|
85
|
+
bot.api.config.use(async (prev, method, payload, signal) => {
|
|
86
|
+
const res = await prev(method, payload, signal);
|
|
87
|
+
if (res.ok || !isThreadGoneError(res.description))
|
|
88
|
+
return res;
|
|
89
|
+
const { chat_id: chatId, message_thread_id: threadId } = payload;
|
|
90
|
+
if (typeof chatId === 'number' && typeof threadId === 'number') {
|
|
91
|
+
// Not awaited: the turn being stopped may be the very one waiting on this send.
|
|
92
|
+
void forgetThread(bot.api, buildSessionKey(chatId, threadId), `${method}: ${res.description}`);
|
|
93
|
+
}
|
|
94
|
+
return res;
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
/** Test seam: forget which threads were let go, on disk too. */
|
|
98
|
+
export function resetDeletedThreadsForTest() {
|
|
99
|
+
forgottenSet = new Set();
|
|
100
|
+
ensureStateDir(getStateDir(), 'DeletedThreads');
|
|
101
|
+
writeJsonFile(stateFile(), { threads: [] }, 'DeletedThreads');
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=deleted-threads.js.map
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which files may be sent out of the machine, by `/file` from chat and by
|
|
3
|
+
* claude's send-file tool.
|
|
4
|
+
*
|
|
5
|
+
* It used to accept any path under WORKSPACE_DIR, which defaults to $HOME.
|
|
6
|
+
* On a shared bot that let any guest fetch `~/.claude/.credentials.json` or
|
|
7
|
+
* `~/.ssh/id_rsa`. Two rules now:
|
|
8
|
+
*
|
|
9
|
+
* - The scope guard's credential/bot-state denylist applies to everyone,
|
|
10
|
+
* admins included. An admin who wants their own SSH key has a shell; a chat
|
|
11
|
+
* command that sends one is only ever a mistake or someone else's request.
|
|
12
|
+
* - Guests are confined to the chat's project directory. Admins keep the
|
|
13
|
+
* whole workspace, since they already choose which project a chat is in.
|
|
14
|
+
*
|
|
15
|
+
* Containment is judged on the real path, so a symlink in the project that
|
|
16
|
+
* points at `~/.ssh` is followed before anything is decided. The denylist is
|
|
17
|
+
* checked on both the typed path and the real one.
|
|
18
|
+
*/
|
|
19
|
+
import * as fs from 'fs';
|
|
20
|
+
import * as os from 'os';
|
|
21
|
+
import * as path from 'path';
|
|
22
|
+
import { isSensitivePath } from '../claude/scope-guard.js';
|
|
23
|
+
import { isAdmin } from '../utils/admins.js';
|
|
24
|
+
import { getWorkspaceRoot } from '../utils/workspace-guard.js';
|
|
25
|
+
import { EntityText } from '../telegram/entities.js';
|
|
26
|
+
import { replyFormatted } from '../telegram/send.js';
|
|
27
|
+
/** Expand `~`, then resolve against `cwd` unless already absolute. */
|
|
28
|
+
function toAbsolute(raw, cwd) {
|
|
29
|
+
let value = raw.trim();
|
|
30
|
+
if (value === '~')
|
|
31
|
+
value = os.homedir();
|
|
32
|
+
else if (value.startsWith('~/'))
|
|
33
|
+
value = path.join(os.homedir(), value.slice(2));
|
|
34
|
+
return path.isAbsolute(value) ? path.resolve(value) : path.resolve(cwd, value);
|
|
35
|
+
}
|
|
36
|
+
function within(root, target) {
|
|
37
|
+
return target === root || target.startsWith(root.endsWith(path.sep) ? root : root + path.sep);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Decide whether `raw` names a file that may leave the machine.
|
|
41
|
+
*
|
|
42
|
+
* Containment is checked before existence, so someone confined to a project
|
|
43
|
+
* can't use the answers to probe what exists outside it.
|
|
44
|
+
*/
|
|
45
|
+
export function resolveShareablePath(raw, opts) {
|
|
46
|
+
const lexical = toAbsolute(raw, opts.cwd);
|
|
47
|
+
if (isSensitivePath(lexical))
|
|
48
|
+
return { ok: false, reason: 'sensitive' };
|
|
49
|
+
let real;
|
|
50
|
+
try {
|
|
51
|
+
real = fs.realpathSync(lexical);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
real = undefined;
|
|
55
|
+
}
|
|
56
|
+
let realRoot;
|
|
57
|
+
try {
|
|
58
|
+
realRoot = fs.realpathSync(opts.root);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return { ok: false, reason: 'outside-root' };
|
|
62
|
+
}
|
|
63
|
+
if (!within(realRoot, real ?? lexical))
|
|
64
|
+
return { ok: false, reason: 'outside-root' };
|
|
65
|
+
if (real === undefined)
|
|
66
|
+
return { ok: false, reason: 'not-found' };
|
|
67
|
+
if (isSensitivePath(real))
|
|
68
|
+
return { ok: false, reason: 'sensitive' };
|
|
69
|
+
let stat;
|
|
70
|
+
try {
|
|
71
|
+
stat = fs.statSync(real);
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return { ok: false, reason: 'not-found' };
|
|
75
|
+
}
|
|
76
|
+
if (stat.isDirectory())
|
|
77
|
+
return { ok: false, reason: 'directory' };
|
|
78
|
+
return { ok: true, path: real };
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The root a user's paths are confined to: the whole workspace for an admin,
|
|
82
|
+
* the chat's project for anyone else.
|
|
83
|
+
*/
|
|
84
|
+
export function shareRootFor(userId, projectDir) {
|
|
85
|
+
return isAdmin(userId) ? getWorkspaceRoot() : projectDir;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Where claude's send-file tool may read from: the share root of the user whose
|
|
89
|
+
* message the turn answers (see {@link shareRootFor}), and failing that /tmp,
|
|
90
|
+
* where claude drops files it made to send. A self-started turn has no user and
|
|
91
|
+
* is held to the project. A refusal names the root the caller is confined to,
|
|
92
|
+
* so claude can tell the user why.
|
|
93
|
+
*/
|
|
94
|
+
export function resolveSendablePath(raw, cwd, userId) {
|
|
95
|
+
const root = shareRootFor(userId, cwd);
|
|
96
|
+
const inRoot = resolveShareablePath(raw, { cwd, root });
|
|
97
|
+
if (inRoot.ok)
|
|
98
|
+
return inRoot;
|
|
99
|
+
if (inRoot.reason !== 'outside-root')
|
|
100
|
+
return { ...inRoot, root };
|
|
101
|
+
const inTmp = resolveShareablePath(raw, { cwd, root: '/tmp' });
|
|
102
|
+
return inTmp.ok ? inTmp : { ...inTmp, root };
|
|
103
|
+
}
|
|
104
|
+
/** What the tool tells claude for each refusal. */
|
|
105
|
+
export function sendableRefusalMessage(reason, raw, root) {
|
|
106
|
+
const shown = path.basename(raw.trim()) || raw.trim();
|
|
107
|
+
switch (reason) {
|
|
108
|
+
case 'sensitive':
|
|
109
|
+
return `Error: ${shown} is a credential or bot-state path (SSH, cloud and Claude credentials, .env files and the like). Such files are never sent. Access denied.`;
|
|
110
|
+
case 'outside-root':
|
|
111
|
+
return `Error: File path must be within ${root} or /tmp. Access denied.`;
|
|
112
|
+
case 'not-found':
|
|
113
|
+
return `Error: File not found: ${shown}`;
|
|
114
|
+
case 'directory':
|
|
115
|
+
return `Error: Path is a directory, not a file: ${shown}`;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Resolve a path typed in chat against the session's project, reporting any
|
|
120
|
+
* refusal to the chat. Returns the real path to send, or null.
|
|
121
|
+
*/
|
|
122
|
+
export async function resolveShareableFile(ctx, projectDir, raw) {
|
|
123
|
+
const root = shareRootFor(ctx.from?.id, projectDir);
|
|
124
|
+
const result = resolveShareablePath(raw, { cwd: projectDir, root });
|
|
125
|
+
if (result.ok)
|
|
126
|
+
return result.path;
|
|
127
|
+
const shown = raw.trim();
|
|
128
|
+
switch (result.reason) {
|
|
129
|
+
case 'sensitive':
|
|
130
|
+
console.log(`[file-access] REFUSED credential path for user:${ctx.from?.id ?? 'unknown'}`);
|
|
131
|
+
await replyFormatted(ctx, new EntityText()
|
|
132
|
+
.add('🔒 ').code(shown)
|
|
133
|
+
.add(' is a credential or bot-state path (SSH, cloud and Claude credentials, .env files and the like), and those are never sent from chat.')
|
|
134
|
+
.build());
|
|
135
|
+
break;
|
|
136
|
+
case 'outside-root':
|
|
137
|
+
await replyFormatted(ctx, isAdmin(ctx.from?.id)
|
|
138
|
+
? new EntityText().add('❌ File path must be within workspace root: ').code(root).build()
|
|
139
|
+
: new EntityText().add("❌ You can only get files from this chat's project: ").code(root).build());
|
|
140
|
+
break;
|
|
141
|
+
case 'not-found':
|
|
142
|
+
await replyFormatted(ctx, new EntityText().add('❌ File not found: ').code(shown).build());
|
|
143
|
+
break;
|
|
144
|
+
case 'directory':
|
|
145
|
+
await replyFormatted(ctx, new EntityText().add("❌ That's a directory, not a file: ").code(shown).build());
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
//# sourceMappingURL=file-access.js.map
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { config } from '../../config.js';
|
|
2
|
+
import { isDuplicate, markProcessed } from '../../telegram/deduplication.js';
|
|
3
|
+
import { isStaleMessage } from '../middleware/stale-filter.js';
|
|
4
|
+
import { albumParts } from '../middleware/album-collector.js';
|
|
5
|
+
import { sanitizeError } from '../../utils/sanitize.js';
|
|
6
|
+
import { getSessionKeyFromCtx } from '../../utils/session-key.js';
|
|
7
|
+
import { ensureUploadsDir } from '../../utils/uploads-dir.js';
|
|
8
|
+
import { requireSession } from './session-guard.js';
|
|
9
|
+
import { exceedsDownloadLimit, TELEGRAM_DOWNLOAD_LIMIT_MB } from './media-fallback.js';
|
|
10
|
+
import { imageAttachment, pickLargestPhoto, runUploadTurn, saveDocument, saveImageDocument, savePhoto, } from './photo.handler.js';
|
|
11
|
+
const isSaved = (file) => 'kind' in file;
|
|
12
|
+
const isSkipped = (file) => 'skipped' in file;
|
|
13
|
+
function sizeMB(bytes) {
|
|
14
|
+
return (bytes ?? 0) / (1024 * 1024);
|
|
15
|
+
}
|
|
16
|
+
/** Why a file of this size can't be taken, or undefined when it can. */
|
|
17
|
+
function tooLarge(bytes, limitMB) {
|
|
18
|
+
if (exceedsDownloadLimit(bytes))
|
|
19
|
+
return `too large (${sizeMB(bytes).toFixed(1)}MB), Telegram caps bot downloads at ${TELEGRAM_DOWNLOAD_LIMIT_MB}MB`;
|
|
20
|
+
if (sizeMB(bytes) > limitMB)
|
|
21
|
+
return `too large (${sizeMB(bytes).toFixed(1)}MB), the limit is ${limitMB}MB`;
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Save one part of an album the way it would be saved sent alone. A part that
|
|
26
|
+
* can't be read comes back as skipped rather than failing the rest.
|
|
27
|
+
*/
|
|
28
|
+
async function saveAlbumPart(ctx, uploadsDir, part, stamp) {
|
|
29
|
+
const caption = part.caption?.trim() || undefined;
|
|
30
|
+
const doc = part.document;
|
|
31
|
+
const name = part.photo ? 'Photo'
|
|
32
|
+
: doc?.file_name ?? part.video?.file_name ?? part.audio?.file_name ?? part.animation?.file_name ?? 'file';
|
|
33
|
+
const mime = doc?.mime_type ?? '';
|
|
34
|
+
if (part.video || part.animation || mime.startsWith('video/'))
|
|
35
|
+
return { name, skipped: "video isn't supported" };
|
|
36
|
+
if (part.audio || mime.startsWith('audio/'))
|
|
37
|
+
return { name, skipped: "audio files aren't supported" };
|
|
38
|
+
if (!part.photo && !doc)
|
|
39
|
+
return { name, skipped: "this kind of message isn't supported" };
|
|
40
|
+
const isImage = !!part.photo || mime.startsWith('image/');
|
|
41
|
+
const bytes = part.photo ? pickLargestPhoto(part.photo).file_size : doc?.file_size;
|
|
42
|
+
const limit = isImage ? config.IMAGE_MAX_FILE_SIZE_MB : config.DOCUMENT_MAX_FILE_SIZE_MB;
|
|
43
|
+
const oversize = tooLarge(bytes, limit);
|
|
44
|
+
if (oversize)
|
|
45
|
+
return { name, skipped: oversize };
|
|
46
|
+
try {
|
|
47
|
+
const path = part.photo ? await savePhoto(ctx, uploadsDir, pickLargestPhoto(part.photo), stamp)
|
|
48
|
+
: isImage ? await saveImageDocument(ctx, uploadsDir, doc, stamp)
|
|
49
|
+
: await saveDocument(ctx, uploadsDir, doc, stamp);
|
|
50
|
+
return { name, kind: isImage ? 'image' : 'file', path, caption };
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
const reason = sanitizeError(error);
|
|
54
|
+
console.error('[Album] Error:', reason);
|
|
55
|
+
return { name, skipped: reason };
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** The note an album becomes for Claude: every file, where it went, and the caption. */
|
|
59
|
+
export function albumPrompt(files, caption) {
|
|
60
|
+
const lines = [`User sent ${files.length} files together.`];
|
|
61
|
+
files.forEach((file, i) => {
|
|
62
|
+
if (isSkipped(file)) {
|
|
63
|
+
lines.push(`${i + 1}. ${file.name}, not available: ${file.skipped}`);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
lines.push(`${i + 1}. ${file.name}, saved at: ${file.path}`);
|
|
67
|
+
if (file.caption)
|
|
68
|
+
lines.push(` With its own caption: "${file.caption}"`);
|
|
69
|
+
});
|
|
70
|
+
lines.push(caption ? `Caption: "${caption}"` : 'Caption: (none)');
|
|
71
|
+
const images = files.filter((f) => isSaved(f) && f.kind === 'image').length;
|
|
72
|
+
const others = files.filter((f) => isSaved(f) && f.kind === 'file').length;
|
|
73
|
+
const howToRead = images === 0
|
|
74
|
+
? 'Use the Read tool to read their contents.'
|
|
75
|
+
: (images === 1
|
|
76
|
+
? 'The image is attached as a vision input — you can see it directly.'
|
|
77
|
+
: 'The images are attached as vision input — you can see them directly.')
|
|
78
|
+
+ (others > 0 ? ' Use the Read tool for the other files.' : '');
|
|
79
|
+
lines.push(others > 0 ? `${howToRead} For PDFs use Read with \`pages\` for large files.` : howToRead);
|
|
80
|
+
lines.push('They were sent as one message, so take them together. If the caption includes a question or request, answer it. Otherwise say briefly what they are and ask what they want done with them.');
|
|
81
|
+
return lines.join('\n');
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Files sent together, gathered by the album collector: saved one by one, then
|
|
85
|
+
* sent to Claude as a single prompt with the images attached.
|
|
86
|
+
*/
|
|
87
|
+
export async function handleAlbum(ctx) {
|
|
88
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
89
|
+
const message = ctx.message;
|
|
90
|
+
const others = albumParts(message);
|
|
91
|
+
if (!keyInfo || !message || !others)
|
|
92
|
+
return;
|
|
93
|
+
const { sessionKey } = keyInfo;
|
|
94
|
+
if (isStaleMessage(message.date)) {
|
|
95
|
+
console.log(`[Album] Ignoring stale album ${message.message_id}`);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (isDuplicate(message.message_id)) {
|
|
99
|
+
console.log(`[Album] Ignoring duplicate album ${message.message_id}`);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const parts = [message, ...others].sort((a, b) => a.message_id - b.message_id);
|
|
103
|
+
for (const part of parts)
|
|
104
|
+
markProcessed(part.message_id);
|
|
105
|
+
const session = await requireSession(ctx, sessionKey);
|
|
106
|
+
if (!session)
|
|
107
|
+
return;
|
|
108
|
+
const uploadsDir = ensureUploadsDir(session.workingDirectory);
|
|
109
|
+
const stamp = Date.now();
|
|
110
|
+
const files = await Promise.all(parts.map((part, i) => saveAlbumPart(ctx, uploadsDir, part, `${stamp}_${i + 1}`)));
|
|
111
|
+
const skipped = files.filter(isSkipped);
|
|
112
|
+
if (skipped.length > 0) {
|
|
113
|
+
const list = skipped.map((f) => `• ${f.name}: ${f.skipped}`).join('\n');
|
|
114
|
+
const heading = skipped.length === files.length
|
|
115
|
+
? `❌ None of the ${files.length} files could be read:`
|
|
116
|
+
: `⚠️ ${skipped.length} of the ${files.length} files couldn't be read, so Claude gets the rest:`;
|
|
117
|
+
await ctx.reply(`${heading}\n${list}`);
|
|
118
|
+
if (skipped.length === files.length)
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
// The collector moved the album's caption onto the message it handed on.
|
|
122
|
+
const caption = message.caption?.trim() || undefined;
|
|
123
|
+
const images = files.filter(isSaved).filter((f) => f.kind === 'image').map((f) => imageAttachment(f.path));
|
|
124
|
+
// The leading message's caption is the album's, so it isn't repeated per file.
|
|
125
|
+
const listed = files.map((f) => (isSaved(f) && f.caption === caption ? { ...f, caption: undefined } : f));
|
|
126
|
+
await runUploadTurn(ctx, sessionKey, albumPrompt(listed, caption), images.length > 0 ? images : undefined);
|
|
127
|
+
}
|
|
128
|
+
//# sourceMappingURL=album.handler.js.map
|