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,772 @@
|
|
|
1
|
+
import { sessionManager } from '../../claude/session-manager.js';
|
|
2
|
+
import { sendToAgent, sendLoopToAgent, getModel, isDangerousMode, getCachedUsage, getActiveProviderName } from '../../providers/provider-router.js';
|
|
3
|
+
import { config } from '../../config.js';
|
|
4
|
+
import { messageSender } from '../../telegram/message-sender.js';
|
|
5
|
+
import { closeTurn, relayCatchUpIfMissed } from './message/turn-notify.js';
|
|
6
|
+
import { getUptimeFormatted } from '../middleware/stale-filter.js';
|
|
7
|
+
import { getAvailableCommands } from '../../claude/command-parser.js';
|
|
8
|
+
import { isProcessing, queueRequest } from '../../claude/request-queue.js';
|
|
9
|
+
import { createTelegraphFromFile } from '../../telegram/telegraph.js';
|
|
10
|
+
import { EntityText, joinMessages, trimMessage } from '../../telegram/entities.js';
|
|
11
|
+
import { replyFormatted, replyParts } from '../../telegram/send.js';
|
|
12
|
+
import { maybeSendVoiceReply } from '../../tts/voice-reply.js';
|
|
13
|
+
import { contextHealthColor, fmtTokens, getProgressBar } from '../../utils/format.js';
|
|
14
|
+
import * as path from 'path';
|
|
15
|
+
import { execFile } from 'child_process';
|
|
16
|
+
import { refuseFilePublish, resolveShareableFile } from '../file-access.js';
|
|
17
|
+
import { resolveClaudeExecutableForMethod } from '../../utils/resolve-claude-bin.js';
|
|
18
|
+
import { getActiveMethod } from '../../providers/claude-provider.js';
|
|
19
|
+
import { contextTokens } from '../../providers/types.js';
|
|
20
|
+
import { stopTurn } from '../middleware/queued-messages.js';
|
|
21
|
+
import { groupAvailableCommands } from '../../claude/available-commands.js';
|
|
22
|
+
import { getSessionKeyFromCtx, parseSessionKey } from '../../utils/session-key.js';
|
|
23
|
+
import { replyMd, getEffortLabel, withBackToPrevious } from './command/shared.js';
|
|
24
|
+
import { getSessionTopic } from './command/topic.js';
|
|
25
|
+
import { describeRole } from './command/access.js';
|
|
26
|
+
import { requireActiveSession } from './session-guard.js';
|
|
27
|
+
import { progressCallbacks, withStreamingTurn } from '../../telegram/streaming-turn.js';
|
|
28
|
+
// Re-exported so the modules that already import from this file keep working
|
|
29
|
+
// while the command handlers are split out domain by domain.
|
|
30
|
+
export { parseCallback, projectStatusSuffix, resumeCommandMessage, truncateToBytes, getEffortLabel, withBackToPrevious, } from './command/shared.js';
|
|
31
|
+
export { setSessionTopic, getSessionTopic, getMsSinceTopicSet, clearTopicAndRefreshBotName, restoreTopicAndRefreshBotName, handleTopic, handleBotName, handleBotNameCallback, } from './command/topic.js';
|
|
32
|
+
export { getStreamingMode } from './command/streaming-mode.js';
|
|
33
|
+
export { handleAllow, handleDeny, handleMembers } from './command/access.js';
|
|
34
|
+
export { sendTranscriptResult, handleTranscribe, handleTranscribeAudio, handleTranscribeDocument, } from './command/media.js';
|
|
35
|
+
export { handleCost, parseCostOutput } from './command/cost.js';
|
|
36
|
+
export { handleTasks, handleTasksCallback, handleShells, handleShellsCallback } from './command/tasks.js';
|
|
37
|
+
export { handleBtw, btwLabel, formatSideAnswer } from './command/btw.js';
|
|
38
|
+
import { listProjectFiles } from './command/project.js';
|
|
39
|
+
export { handleProject, handleNewProject, handleProjectCallback, } from './command/project.js';
|
|
40
|
+
export { handleUpdate, handleUpdateCallback, handleBotStatus, handleVersion, handleRestartBot, handleRestartBotCallback, handleRestartCallback, handleStartupCallback, handleRebuild, handleRebuildCallback, } from './command/admin.js';
|
|
41
|
+
export { handleClear, handleClearCallback, handleContinue, handleRecap, handleHandoff, handleSync, handleSessions, handleTeleport, } from './command/session.js';
|
|
42
|
+
export { handleResume, handleResumeCallback } from './command/resume.js';
|
|
43
|
+
import { buildTelegraphMenu } from './command/settings.js';
|
|
44
|
+
import { turnErrorReply } from '../../claude/claude-auth.js';
|
|
45
|
+
export { handleStreaming, handleModeCallback, handlePermissionMode, handlePermissionModeCallback, handleTerminalUI, handleTerminalUICallback, handleTTS, handleTTSCallback, handleTelegraphCallback, handleEffort, handleEffortCallback, handleVerbosity, handleVerbosityCallback, handleMethodCommand, handleMethodCallback, handleSuggestions, handleSuggestionsCallback, handleStatusLine, handleStatusLineCallback, sendStatusLine, } from './command/settings.js';
|
|
46
|
+
export { handleModelCommand, handleModelCallback, handleProviderCommand, handleCcrCommand, handleProviderCallback, handleProviderSwitchCallback, } from './command/model.js';
|
|
47
|
+
export { handlePrefsAllCallback } from './command/prefs-scope.js';
|
|
48
|
+
export function parseContextOutput(raw) {
|
|
49
|
+
const trimmed = raw.trim();
|
|
50
|
+
if (!trimmed) {
|
|
51
|
+
return '⚠️ No context output received.';
|
|
52
|
+
}
|
|
53
|
+
const lines = trimmed
|
|
54
|
+
.split('\n')
|
|
55
|
+
.map((line) => line.trim())
|
|
56
|
+
.filter((line) => line.length > 0);
|
|
57
|
+
let model = '';
|
|
58
|
+
let tokensLine = '';
|
|
59
|
+
const categories = [];
|
|
60
|
+
let inCategories = false;
|
|
61
|
+
for (const line of lines) {
|
|
62
|
+
if (/^model:/i.test(line)) {
|
|
63
|
+
model = line.replace(/^model:/i, '').trim();
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (/^tokens:/i.test(line)) {
|
|
67
|
+
tokensLine = line.replace(/^tokens:/i, '').trim();
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (/estimated usage by category/i.test(line)) {
|
|
71
|
+
inCategories = true;
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (inCategories) {
|
|
75
|
+
if (/^category/i.test(line))
|
|
76
|
+
continue;
|
|
77
|
+
if (/^-+$/.test(line))
|
|
78
|
+
continue;
|
|
79
|
+
const match = line.match(/^(.+?)\s{2,}([0-9.,kKmM]+)\s+([0-9.,]+%)$/);
|
|
80
|
+
if (match) {
|
|
81
|
+
categories.push({ name: match[1].trim(), tokens: match[2], percent: match[3] });
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
const parts = line.split(/\s+/);
|
|
85
|
+
if (parts.length >= 3 && parts[parts.length - 1].endsWith('%')) {
|
|
86
|
+
const percent = parts.pop();
|
|
87
|
+
const tokens = parts.pop();
|
|
88
|
+
const name = parts.join(' ');
|
|
89
|
+
categories.push({ name, tokens, percent });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (!model && !tokensLine && categories.length === 0) {
|
|
94
|
+
return `## 🧠 Context Usage\n\n\`\`\`\n${trimmed}\n\`\`\``;
|
|
95
|
+
}
|
|
96
|
+
let output = '## 🧠 Context Usage';
|
|
97
|
+
if (model)
|
|
98
|
+
output += `\n- **Model:** ${model}`;
|
|
99
|
+
if (tokensLine)
|
|
100
|
+
output += `\n- **Tokens:** ${tokensLine}`;
|
|
101
|
+
if (categories.length > 0) {
|
|
102
|
+
output += '\n\n### Estimated usage by category';
|
|
103
|
+
for (const category of categories) {
|
|
104
|
+
output += `\n- **${category.name}:** ${category.tokens} (${category.percent})`;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
output += '\n\n_If this looks stale, send a new message then run /context again._';
|
|
108
|
+
return output;
|
|
109
|
+
}
|
|
110
|
+
const SESSION_ID_RE = /^[a-zA-Z0-9_-]{8,128}$/;
|
|
111
|
+
async function runClaudeContext(sessionId, cwd) {
|
|
112
|
+
if (!SESSION_ID_RE.test(sessionId)) {
|
|
113
|
+
throw new Error('Invalid session ID format');
|
|
114
|
+
}
|
|
115
|
+
return new Promise((resolve, reject) => {
|
|
116
|
+
execFile(
|
|
117
|
+
// Match the binary PTY mode spawns — CLAUDE_BIN and CLAUDE_EXECUTABLE_PATH
|
|
118
|
+
// can point at different installs, and this resumes a PTY-written session.
|
|
119
|
+
process.env.CLAUDE_BIN || config.CLAUDE_EXECUTABLE_PATH,
|
|
120
|
+
// --fork-session + --no-session-persistence are load-bearing: a bare
|
|
121
|
+
// `-p --resume <id>` CONTINUES that session and appends its own turn to
|
|
122
|
+
// the JSONL. In PTY mode <id> is the *live* session, so /context would
|
|
123
|
+
// inject a stray turn into the real conversation while the pty process
|
|
124
|
+
// is writing the same file.
|
|
125
|
+
['-p', '--resume', sessionId, '--fork-session', '--no-session-persistence', '/context'], {
|
|
126
|
+
cwd,
|
|
127
|
+
timeout: 20_000,
|
|
128
|
+
maxBuffer: 1024 * 1024,
|
|
129
|
+
env: process.env,
|
|
130
|
+
}, (error, stdout, stderr) => {
|
|
131
|
+
if (error) {
|
|
132
|
+
const message = (stderr || error.message).trim();
|
|
133
|
+
reject(new Error(message || 'Failed to run /context'));
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
resolve((stdout || stderr || '').trim());
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
export async function handleStart(ctx) {
|
|
141
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
142
|
+
const effortLabel = keyInfo ? (getEffortLabel(keyInfo.sessionKey) ?? 'Default') : 'Default';
|
|
143
|
+
const welcome = new EntityText()
|
|
144
|
+
.add('👋 ').bold('Welcome to TeleCoder!')
|
|
145
|
+
.add('\n\nI bridge your messages to Claude Code running on your local machine.\n\n')
|
|
146
|
+
.bold('Getting Started:')
|
|
147
|
+
.add('\n1. Set your project directory with ').code('/project /path/to/project')
|
|
148
|
+
.add('\n2. Start chatting with Claude about your code!\n\n')
|
|
149
|
+
.bold('Commands:')
|
|
150
|
+
.add('\n• ').code('/project <path>').add(' - Open a project')
|
|
151
|
+
.add('\n• ').code('/newproject <name>').add(' - Create a new project')
|
|
152
|
+
.add('\n• ').code('/clear').add(' - Clear session and start fresh')
|
|
153
|
+
.add('\n• ').code('/status').add(' - Show current session info')
|
|
154
|
+
.add('\n• ').code('/commands').add(' - Show all available commands')
|
|
155
|
+
.add(`\n\nReplies: ${config.STREAMING_MODE}\nEffort: ${effortLabel}`);
|
|
156
|
+
if (isDangerousMode()) {
|
|
157
|
+
welcome.add('\n\n⚠️ ').bold('DANGEROUS MODE ENABLED').add(' - All tool permissions auto-approved');
|
|
158
|
+
}
|
|
159
|
+
const currentConv = keyInfo
|
|
160
|
+
? sessionManager.getSession(keyInfo.sessionKey)?.conversationId
|
|
161
|
+
: undefined;
|
|
162
|
+
const back = withBackToPrevious(welcome.build(), keyInfo?.sessionKey, currentConv);
|
|
163
|
+
await replyFormatted(ctx, back.text, back.options);
|
|
164
|
+
}
|
|
165
|
+
export async function handleStatus(ctx) {
|
|
166
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
167
|
+
if (!keyInfo) {
|
|
168
|
+
await ctx.reply('❌ Could not determine chat context for /status.');
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
try {
|
|
172
|
+
const { sessionKey } = keyInfo;
|
|
173
|
+
const { chatId } = parseSessionKey(sessionKey);
|
|
174
|
+
const session = sessionManager.getSession(sessionKey);
|
|
175
|
+
if (!session) {
|
|
176
|
+
await replyMd(ctx, 'ℹ️ No active session.\n\nUse `/project /path/to/project` to get started.');
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
const currentModel = getModel(sessionKey);
|
|
180
|
+
const provider = getActiveProviderName(sessionKey);
|
|
181
|
+
const dangerousMode = isDangerousMode() ? '⚠️ ENABLED' : 'Disabled';
|
|
182
|
+
const effortLabel = getEffortLabel(sessionKey) ?? 'Default';
|
|
183
|
+
const topic = getSessionTopic(sessionKey);
|
|
184
|
+
const projectName = path.basename(session.workingDirectory);
|
|
185
|
+
// On CCR, the SDK alias doesn't reflect which backend actually served
|
|
186
|
+
// the turn — CCR picks per-request based on its router config. We
|
|
187
|
+
// don't try to discover the true backend (would require log parsing).
|
|
188
|
+
// The "Provider: ccr" line below already signals the routing.
|
|
189
|
+
const cached = getCachedUsage(sessionKey);
|
|
190
|
+
const status = new EntityText().add('📊 ').bold('Session Status').add('\n');
|
|
191
|
+
// One `emoji *Label:* value` line; the value is added by the caller.
|
|
192
|
+
const field = (emoji, label) => status.add(`\n${emoji} `).bold(`${label}:`).add(' ');
|
|
193
|
+
field('🤖', 'Bot Name').add(config.BOT_NAME);
|
|
194
|
+
field('📦', 'Project').add(projectName);
|
|
195
|
+
if (topic)
|
|
196
|
+
field('🏷️', 'Topic').add(topic);
|
|
197
|
+
else
|
|
198
|
+
field('🏷️', 'Topic').italic('none');
|
|
199
|
+
field('🎚️', 'Effort').add(effortLabel);
|
|
200
|
+
field('🧠', 'Model').add(currentModel);
|
|
201
|
+
if (provider === 'ccr')
|
|
202
|
+
status.add(' ').italic('(routed via CCR)');
|
|
203
|
+
field('🔌', 'Provider').add(provider);
|
|
204
|
+
field('🆔', 'Session ID').code(session.claudeSessionId ?? session.conversationId);
|
|
205
|
+
field('📁', 'Working Directory').code(session.workingDirectory);
|
|
206
|
+
field('📡', 'Mode').add(config.STREAMING_MODE);
|
|
207
|
+
field(isDangerousMode() ? '⚠️' : '🛡️', 'Dangerous Mode').add(dangerousMode);
|
|
208
|
+
if (cached) {
|
|
209
|
+
// Cache reads and writes are most of the context, and without them this
|
|
210
|
+
// read about 0%. Same sum as the usage footer's.
|
|
211
|
+
const used = contextTokens(cached);
|
|
212
|
+
const pct = cached.contextWindow > 0
|
|
213
|
+
? Math.round((used / cached.contextWindow) * 100)
|
|
214
|
+
: 0;
|
|
215
|
+
field('📐', 'Context').add(`${pct}% (${fmtTokens(used)}/${fmtTokens(cached.contextWindow)})`);
|
|
216
|
+
// Only when something has actually been tallied: PTY mode never receives
|
|
217
|
+
// a cost figure, and a flat $0.0000 there reads as a free conversation
|
|
218
|
+
// rather than as an unanswerable question.
|
|
219
|
+
if (cached.sessionCostTurns > 0) {
|
|
220
|
+
field('💰', 'Session Cost').add(`$${cached.sessionCostUsd.toFixed(4)} (${cached.sessionCostTurns} turns)`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
// Only in a group, and only for a non-admin — it is the line that explains
|
|
224
|
+
// why /restartbot just refused. Spectators never see it: they can't reach
|
|
225
|
+
// /status in the first place.
|
|
226
|
+
const role = describeRole(ctx);
|
|
227
|
+
if (role && role !== 'admin') {
|
|
228
|
+
field('👤', 'Your role here').add(role);
|
|
229
|
+
}
|
|
230
|
+
field('🕰️', 'Created').add(session.createdAt.toLocaleString());
|
|
231
|
+
field('⏱️', 'Last Activity').add(session.lastActivity.toLocaleString());
|
|
232
|
+
field('⏳', 'Uptime').add(getUptimeFormatted());
|
|
233
|
+
await replyFormatted(ctx, status.build());
|
|
234
|
+
}
|
|
235
|
+
catch (err) {
|
|
236
|
+
console.error('[Status] Error:', err);
|
|
237
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
238
|
+
await ctx.reply(`❌ /status failed: ${msg}`).catch(() => { });
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
export async function handlePing(ctx) {
|
|
242
|
+
const uptime = getUptimeFormatted();
|
|
243
|
+
await ctx.reply(`🏓 Pong!\n\nUptime: ${uptime}`);
|
|
244
|
+
}
|
|
245
|
+
export async function handleContext(ctx) {
|
|
246
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
247
|
+
if (!keyInfo)
|
|
248
|
+
return;
|
|
249
|
+
const { chatId, sessionKey } = keyInfo;
|
|
250
|
+
const session = await requireActiveSession(ctx, sessionKey);
|
|
251
|
+
if (!session)
|
|
252
|
+
return;
|
|
253
|
+
// Try cached SDK usage first (instant, no CLI shell-out)
|
|
254
|
+
const cached = getCachedUsage(sessionKey);
|
|
255
|
+
if (cached) {
|
|
256
|
+
const used = contextTokens(cached);
|
|
257
|
+
const pct = cached.contextWindow > 0
|
|
258
|
+
? Math.round((used / cached.contextWindow) * 100)
|
|
259
|
+
: 0;
|
|
260
|
+
const bar = getProgressBar(pct, contextHealthColor(used, cached.contextWindow));
|
|
261
|
+
const output = `## 🧠 Context Usage\n\n`
|
|
262
|
+
+ `${bar} **${pct}%** of context window\n\n`
|
|
263
|
+
+ `- **Model:** ${cached.model}\n`
|
|
264
|
+
+ `- **Input tokens:** ${fmtTokens(cached.inputTokens)}\n`
|
|
265
|
+
+ `- **Output tokens:** ${fmtTokens(cached.outputTokens)}\n`
|
|
266
|
+
+ `- **Cache read:** ${fmtTokens(cached.cacheReadTokens)}\n`
|
|
267
|
+
+ `- **Cache write:** ${fmtTokens(cached.cacheWriteTokens)}\n`
|
|
268
|
+
+ `- **Context window:** ${fmtTokens(cached.contextWindow)}\n`
|
|
269
|
+
+ `- **Turns this session:** ${cached.numTurns}\n`
|
|
270
|
+
+ `- **Cost this query:** $${cached.totalCostUsd.toFixed(4)}\n`
|
|
271
|
+
+ (cached.sessionCostTurns > 0
|
|
272
|
+
? `- **Cost this chat:** $${cached.sessionCostUsd.toFixed(4)} across ${cached.sessionCostTurns} turns\n`
|
|
273
|
+
: '')
|
|
274
|
+
+ `\n_Data from last query. Send a message then run /context for fresh data._`;
|
|
275
|
+
await messageSender.sendMessage(ctx, output);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
// Fallback: CLI shell-out approach (Claude only)
|
|
279
|
+
if (!session.claudeSessionId) {
|
|
280
|
+
await replyMd(ctx, '⚠️ No Claude session ID found.\n\nSend a message to Claude after resuming, then run `/context` again.');
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
const ack = await ctx.reply('🧠 Checking context...');
|
|
284
|
+
try {
|
|
285
|
+
const raw = await runClaudeContext(session.claudeSessionId, session.workingDirectory);
|
|
286
|
+
const formatted = parseContextOutput(raw);
|
|
287
|
+
await messageSender.sendMessage(ctx, formatted);
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
const message = error instanceof Error ? error.message : 'Unknown error';
|
|
291
|
+
const hint = message.toLowerCase().includes('unknown') || message.toLowerCase().includes('command')
|
|
292
|
+
? '\n\nThis CLI may not support `/context` yet.'
|
|
293
|
+
: '';
|
|
294
|
+
await messageSender.sendMessage(ctx, `❌ Failed to fetch context: ${message}${hint}`);
|
|
295
|
+
}
|
|
296
|
+
finally {
|
|
297
|
+
try {
|
|
298
|
+
await ctx.api.deleteMessage(chatId, ack.message_id);
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
// ignore cleanup errors
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
export async function handleCancel(ctx) {
|
|
306
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
307
|
+
if (!keyInfo)
|
|
308
|
+
return;
|
|
309
|
+
const { sessionKey } = keyInfo;
|
|
310
|
+
const wasProcessing = isProcessing(sessionKey);
|
|
311
|
+
const { stopped: cancelled, dropped: clearedCount } = await stopTurn(ctx.api, sessionKey);
|
|
312
|
+
if (cancelled || clearedCount > 0) {
|
|
313
|
+
let message = '🛑 Cancelled.';
|
|
314
|
+
if (clearedCount > 0) {
|
|
315
|
+
message += ` (${clearedCount} queued request${clearedCount > 1 ? 's' : ''} cleared)`;
|
|
316
|
+
}
|
|
317
|
+
await ctx.reply(message);
|
|
318
|
+
}
|
|
319
|
+
else if (!wasProcessing) {
|
|
320
|
+
await ctx.reply('ℹ️ Nothing to cancel.');
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
export async function handleCommands(ctx) {
|
|
324
|
+
await replyParts(ctx, getAvailableCommands());
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* What a mode command (/plan, /explore, /loop, /file) shows when it arrives
|
|
328
|
+
* without its argument: the mode, the project, what the mode does, and the
|
|
329
|
+
* ask the force-reply answers.
|
|
330
|
+
*/
|
|
331
|
+
function modePrompt(emoji, title, workingDirectory, body, ask) {
|
|
332
|
+
const b = new EntityText()
|
|
333
|
+
.add(`${emoji} `).bold(title)
|
|
334
|
+
.add('\n\n').italic(`Project: ${path.basename(workingDirectory)}`);
|
|
335
|
+
if (body) {
|
|
336
|
+
b.add('\n\n');
|
|
337
|
+
if (typeof body === 'string')
|
|
338
|
+
b.add(body);
|
|
339
|
+
else
|
|
340
|
+
b.append(body);
|
|
341
|
+
}
|
|
342
|
+
return b.add('\n\n👇 ').italic(ask).build();
|
|
343
|
+
}
|
|
344
|
+
export async function handlePlan(ctx) {
|
|
345
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
346
|
+
if (!keyInfo)
|
|
347
|
+
return;
|
|
348
|
+
const { sessionKey } = keyInfo;
|
|
349
|
+
const session = await requireActiveSession(ctx, sessionKey);
|
|
350
|
+
if (!session)
|
|
351
|
+
return;
|
|
352
|
+
const text = ctx.message?.text || '';
|
|
353
|
+
const task = text.split(' ').slice(1).join(' ').trim();
|
|
354
|
+
if (!task) {
|
|
355
|
+
await replyFormatted(ctx, modePrompt('📋', 'Plan Mode', session.workingDirectory, 'Claude will analyze your task and create a detailed implementation plan before coding.', 'Describe your task:'), {
|
|
356
|
+
reply_markup: {
|
|
357
|
+
force_reply: true,
|
|
358
|
+
input_field_placeholder: 'Add user authentication with JWT...',
|
|
359
|
+
selective: true,
|
|
360
|
+
},
|
|
361
|
+
});
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
try {
|
|
365
|
+
await queueRequest(sessionKey, task, async () => {
|
|
366
|
+
await withStreamingTurn(ctx, sessionKey, task, async (abortController) => {
|
|
367
|
+
const response = await sendToAgent(sessionKey, task, {
|
|
368
|
+
...progressCallbacks(ctx),
|
|
369
|
+
abortController,
|
|
370
|
+
telegramCtx: ctx,
|
|
371
|
+
command: 'plan',
|
|
372
|
+
});
|
|
373
|
+
await messageSender.finishStreaming(ctx, response.text);
|
|
374
|
+
await relayCatchUpIfMissed(ctx, sessionKey, response.text || '');
|
|
375
|
+
await maybeSendVoiceReply(ctx, response.text);
|
|
376
|
+
await closeTurn(ctx, sessionKey, response, task);
|
|
377
|
+
});
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
catch (error) {
|
|
381
|
+
if (error.message === 'Queue cleared')
|
|
382
|
+
return;
|
|
383
|
+
await ctx.reply(turnErrorReply(error));
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
export async function handleExplore(ctx) {
|
|
387
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
388
|
+
if (!keyInfo)
|
|
389
|
+
return;
|
|
390
|
+
const { sessionKey } = keyInfo;
|
|
391
|
+
const session = await requireActiveSession(ctx, sessionKey);
|
|
392
|
+
if (!session)
|
|
393
|
+
return;
|
|
394
|
+
const text = ctx.message?.text || '';
|
|
395
|
+
const question = text.split(' ').slice(1).join(' ').trim();
|
|
396
|
+
if (!question) {
|
|
397
|
+
await replyFormatted(ctx, modePrompt('🔍', 'Explore Mode', session.workingDirectory, 'Claude will search and analyze the codebase to answer your question.', 'What would you like to know?'), {
|
|
398
|
+
reply_markup: {
|
|
399
|
+
force_reply: true,
|
|
400
|
+
input_field_placeholder: 'How does the auth system work?',
|
|
401
|
+
selective: true,
|
|
402
|
+
},
|
|
403
|
+
});
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
try {
|
|
407
|
+
await queueRequest(sessionKey, question, async () => {
|
|
408
|
+
await withStreamingTurn(ctx, sessionKey, question, async (abortController) => {
|
|
409
|
+
const response = await sendToAgent(sessionKey, question, {
|
|
410
|
+
...progressCallbacks(ctx),
|
|
411
|
+
abortController,
|
|
412
|
+
telegramCtx: ctx,
|
|
413
|
+
command: 'explore',
|
|
414
|
+
});
|
|
415
|
+
await messageSender.finishStreaming(ctx, response.text);
|
|
416
|
+
await relayCatchUpIfMissed(ctx, sessionKey, response.text || '');
|
|
417
|
+
await maybeSendVoiceReply(ctx, response.text);
|
|
418
|
+
await closeTurn(ctx, sessionKey, response, question);
|
|
419
|
+
});
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
catch (error) {
|
|
423
|
+
if (error.message === 'Queue cleared')
|
|
424
|
+
return;
|
|
425
|
+
await ctx.reply(turnErrorReply(error));
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
/** Show the current permission-gate state and the patterns it enforces. */
|
|
429
|
+
export async function handlePermissions(ctx) {
|
|
430
|
+
const { isPermissionGateEnabled, isPermissionGateImplicit, listDangerousPatterns } = await import('../../claude/permission-gate.js');
|
|
431
|
+
const { getAdminIds, getApproverIds, getGuestIds, hasGuestUsers, isAdmin, isApprover } = await import('../../utils/admins.js');
|
|
432
|
+
const enabled = isPermissionGateEnabled();
|
|
433
|
+
const patterns = listDangerousPatterns();
|
|
434
|
+
// One line each; an empty one is the gap between sections.
|
|
435
|
+
const lines = [];
|
|
436
|
+
const line = (build = () => { }) => {
|
|
437
|
+
const b = new EntityText();
|
|
438
|
+
build(b);
|
|
439
|
+
lines.push(b.build());
|
|
440
|
+
};
|
|
441
|
+
line((b) => b.add('🔐 ').bold('Permission gate').add(` — ${enabled ? '✅ enabled' : '⛔️ disabled'}`));
|
|
442
|
+
line();
|
|
443
|
+
if (enabled) {
|
|
444
|
+
line((b) => b.add('Bash commands matching the patterns below trigger a Telegram approval prompt before claude executes them. Other tools auto-allow.'));
|
|
445
|
+
}
|
|
446
|
+
else {
|
|
447
|
+
line((b) => b.add('Disabled. Set ').code('TELECODER_PERMISSION_PROMPTS=1').add(' and restart the bot to enable.'));
|
|
448
|
+
}
|
|
449
|
+
// An open window changes what the gate does right now, so it belongs above
|
|
450
|
+
// everything that describes what it would do otherwise.
|
|
451
|
+
const { getWindow, formatRemaining } = await import('../../claude/auto-approve.js');
|
|
452
|
+
const window = ctx.chat?.id !== undefined ? getWindow(ctx.chat.id) : null;
|
|
453
|
+
if (window) {
|
|
454
|
+
line();
|
|
455
|
+
line((b) => b.add('⚡ ').bold('Auto-approve is on here')
|
|
456
|
+
.add(` — ${formatRemaining(window)} left, opened by ${window.openedByName}.`));
|
|
457
|
+
line((b) => b.add('Guarded commands run without asking and are posted as they happen. End it with ')
|
|
458
|
+
.code('/autoapprove off').add('.'));
|
|
459
|
+
}
|
|
460
|
+
if (enabled && isPermissionGateImplicit()) {
|
|
461
|
+
line();
|
|
462
|
+
line((b) => b.add('On automatically because this bot has non-admin users. Set ')
|
|
463
|
+
.code('TELECODER_PERMISSION_PROMPTS=0').add(' to turn it off.'));
|
|
464
|
+
}
|
|
465
|
+
if (enabled) {
|
|
466
|
+
const { isScopeGuardEnabled, getAllowedRoots } = await import('../../claude/scope-guard.js');
|
|
467
|
+
line();
|
|
468
|
+
if (isScopeGuardEnabled(true)) {
|
|
469
|
+
line((b) => b.bold('Scope guard:').add(' ✅ on'));
|
|
470
|
+
line((b) => b.add('Tool calls naming a path outside these prompt too:'));
|
|
471
|
+
for (const root of getAllowedRoots())
|
|
472
|
+
line((b) => b.add('• ').code(root));
|
|
473
|
+
}
|
|
474
|
+
else {
|
|
475
|
+
line((b) => b.bold('Scope guard:').add(' ⛔️ off'));
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
const { isCharterJudgeEnabled, getCharter } = await import('../../claude/charter-judge.js');
|
|
479
|
+
if (isCharterJudgeEnabled()) {
|
|
480
|
+
const { source } = getCharter();
|
|
481
|
+
line();
|
|
482
|
+
line((b) => b.bold('Charter judge:').add(' ✅ on'));
|
|
483
|
+
line((b) => {
|
|
484
|
+
b.add('Every guest message is read against ');
|
|
485
|
+
if (source === '(default)')
|
|
486
|
+
b.add('the built-in charter');
|
|
487
|
+
else
|
|
488
|
+
b.code(source);
|
|
489
|
+
b.add(' before it reaches Claude.');
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
if (hasGuestUsers()) {
|
|
493
|
+
const admins = getAdminIds();
|
|
494
|
+
const approvers = getApproverIds();
|
|
495
|
+
// getGuestIds() means "not an admin", which includes the approvers. Split
|
|
496
|
+
// them out so the counts add up to the roster rather than double-counting.
|
|
497
|
+
const guests = getGuestIds().filter((id) => !approvers.includes(id));
|
|
498
|
+
const roles = [
|
|
499
|
+
`${admins.length} admin${admins.length === 1 ? '' : 's'}`,
|
|
500
|
+
...(approvers.length > 0 ? [`${approvers.length} approver${approvers.length === 1 ? '' : 's'}`] : []),
|
|
501
|
+
`${guests.length} guest${guests.length === 1 ? '' : 's'}`,
|
|
502
|
+
];
|
|
503
|
+
line();
|
|
504
|
+
line((b) => b.bold('Roles:').add(` ${roles.join(', ')}`));
|
|
505
|
+
if (isAdmin(ctx.from?.id)) {
|
|
506
|
+
line((b) => b.add('You are an ').bold('admin')
|
|
507
|
+
.add(' — approval prompts and bot-lifecycle commands are yours to answer.'));
|
|
508
|
+
}
|
|
509
|
+
else if (isApprover(ctx.from?.id)) {
|
|
510
|
+
line((b) => b.add('You are an ').bold('approver')
|
|
511
|
+
.add(' — you can answer anyone else’s approval prompt, but not your own. ' +
|
|
512
|
+
'Bot-lifecycle commands stay with the admins.'));
|
|
513
|
+
}
|
|
514
|
+
else {
|
|
515
|
+
line((b) => b.add('You are a ').bold('guest')
|
|
516
|
+
.add(' — an admin or approver answers guarded commands, and admins own ' +
|
|
517
|
+
'bot-lifecycle commands.'));
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
line();
|
|
521
|
+
line((b) => b.bold('Guarded patterns:'));
|
|
522
|
+
for (const p of patterns)
|
|
523
|
+
line((b) => b.add(`• ${p.reason}`));
|
|
524
|
+
await replyParts(ctx, joinMessages(lines, '\n'));
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* List the current project's `.claude/commands/*.md` slash commands. They
|
|
528
|
+
* pass through to claude code untouched (typing `/mycommand` in chat sends
|
|
529
|
+
* `/mycommand` to claude, which dispatches to the file), so this is purely
|
|
530
|
+
* a discoverability helper — no per-command registration needed.
|
|
531
|
+
*/
|
|
532
|
+
export async function handleProjectCommands(ctx) {
|
|
533
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
534
|
+
if (!keyInfo)
|
|
535
|
+
return;
|
|
536
|
+
const { sessionKey } = keyInfo;
|
|
537
|
+
const session = sessionManager.getSession(sessionKey);
|
|
538
|
+
if (!session) {
|
|
539
|
+
await replyMd(ctx, '⚠️ No project set. Use `/project` first.');
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
const { getProjectCommands } = await import('../../claude/project-commands.js');
|
|
543
|
+
const { getAvailableCommands: getClaudeCommands } = await import('../../claude/available-commands.js');
|
|
544
|
+
const { getBotCommandNames } = await import('../../claude/command-parser.js');
|
|
545
|
+
const projectCommands = getProjectCommands(session.workingDirectory);
|
|
546
|
+
// Ask the binary this chat's turns actually run through. SDK and PTY mode
|
|
547
|
+
// can be different installs at different versions, and their command sets
|
|
548
|
+
// differ — listing the wrong one would name commands that don't exist here.
|
|
549
|
+
const executable = resolveClaudeExecutableForMethod(getActiveMethod(keyInfo.sessionKey));
|
|
550
|
+
// A cold cache means a probe — a fresh headless process — so show a typing
|
|
551
|
+
// indicator rather than leaving the chat silent for a second or two.
|
|
552
|
+
const typing = ctx.replyWithChatAction?.('typing');
|
|
553
|
+
const snapshot = await getClaudeCommands(session.workingDirectory, executable);
|
|
554
|
+
await typing?.catch(() => { });
|
|
555
|
+
await replyFormatted(ctx, buildProjectCommandsMessage({
|
|
556
|
+
directory: path.basename(session.workingDirectory),
|
|
557
|
+
projectCommands,
|
|
558
|
+
snapshot,
|
|
559
|
+
botCommandNames: getBotCommandNames(),
|
|
560
|
+
}));
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* Render the `/projectcommands` listing. Pure so what it sends — the command
|
|
564
|
+
* names as code, the descriptions as they were written — is unit-testable.
|
|
565
|
+
*
|
|
566
|
+
* `snapshot` is undefined when Claude Code's own command list couldn't be
|
|
567
|
+
* read; the project commands still list, since those come off disk.
|
|
568
|
+
*/
|
|
569
|
+
export function buildProjectCommandsMessage(input) {
|
|
570
|
+
const { directory, projectCommands, snapshot, botCommandNames } = input;
|
|
571
|
+
const lines = [];
|
|
572
|
+
const line = (build = () => { }) => {
|
|
573
|
+
const b = new EntityText();
|
|
574
|
+
build(b);
|
|
575
|
+
lines.push(b.build());
|
|
576
|
+
};
|
|
577
|
+
// `/a`, `/b`, … as one line of code spans.
|
|
578
|
+
const commandList = (names) => (b) => {
|
|
579
|
+
names.forEach((n, i) => {
|
|
580
|
+
if (i > 0)
|
|
581
|
+
b.add(', ');
|
|
582
|
+
b.code(`/${n}`);
|
|
583
|
+
});
|
|
584
|
+
};
|
|
585
|
+
line((b) => b.add('📜 ').bold('Commands available in').add(' ').code(directory));
|
|
586
|
+
line();
|
|
587
|
+
if (projectCommands.length > 0) {
|
|
588
|
+
line((b) => b.bold('Project').add(' (').code('.claude/commands/').add('):'));
|
|
589
|
+
line();
|
|
590
|
+
for (const c of projectCommands) {
|
|
591
|
+
line((b) => {
|
|
592
|
+
b.add('• ').code(`/${c.name}`);
|
|
593
|
+
if (c.description)
|
|
594
|
+
b.add(` — ${c.description}`);
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
line();
|
|
598
|
+
}
|
|
599
|
+
if (snapshot) {
|
|
600
|
+
const { skills, plugins, builtIns } = groupAvailableCommands(snapshot);
|
|
601
|
+
// A command TeleCoder registers never reaches Claude Code — grammY matches
|
|
602
|
+
// it first — so listing it as passthrough would be a lie. Name them
|
|
603
|
+
// separately instead, so nobody wonders why /loop isn't the skill.
|
|
604
|
+
const shadowed = snapshot.slashCommands.filter((n) => botCommandNames.has(n)).sort();
|
|
605
|
+
const passthrough = (names) => names.filter((n) => !botCommandNames.has(n));
|
|
606
|
+
const groups = [
|
|
607
|
+
['Skills:', passthrough(skills)],
|
|
608
|
+
['Plugin:', passthrough(plugins)],
|
|
609
|
+
['Built-in:', passthrough(builtIns)],
|
|
610
|
+
];
|
|
611
|
+
for (const [title, names] of groups) {
|
|
612
|
+
if (names.length === 0)
|
|
613
|
+
continue;
|
|
614
|
+
line((b) => b.bold(title));
|
|
615
|
+
line();
|
|
616
|
+
line(commandList(names));
|
|
617
|
+
line();
|
|
618
|
+
}
|
|
619
|
+
if (shadowed.length > 0) {
|
|
620
|
+
line((b) => b.add('⚠️ ').bold('Shadowed by TeleCoder')
|
|
621
|
+
.add(" — these run the bot's own command, not Claude Code's:"));
|
|
622
|
+
line();
|
|
623
|
+
line(commandList(shadowed));
|
|
624
|
+
line();
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
else {
|
|
628
|
+
line((b) => b.italic("Claude Code's own command list is unavailable right now."));
|
|
629
|
+
line();
|
|
630
|
+
}
|
|
631
|
+
if (projectCommands.length === 0) {
|
|
632
|
+
line((b) => b.add('Add markdown files under ').code('.claude/commands/')
|
|
633
|
+
.add(' to define project commands — see ')
|
|
634
|
+
.link('docs', 'https://docs.claude.com/en/docs/claude-code/slash-commands').add('.'));
|
|
635
|
+
}
|
|
636
|
+
return joinWithinLimit(lines, 3900);
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Join lines up to a length budget, dropping whole lines rather than cutting
|
|
640
|
+
* mid-line, so the list ends on a whole command name and says it was cut.
|
|
641
|
+
* Counted in UTF-16 code units, the unit of Telegram's 4096 cap.
|
|
642
|
+
*/
|
|
643
|
+
function joinWithinLimit(lines, maxLength) {
|
|
644
|
+
const notice = new EntityText().add('\n').italic('…list truncated.').build();
|
|
645
|
+
const budget = maxLength - notice.text.length;
|
|
646
|
+
const kept = [];
|
|
647
|
+
let size = 0;
|
|
648
|
+
for (const line of lines) {
|
|
649
|
+
const cost = line.text.length + 1;
|
|
650
|
+
if (size + cost > budget) {
|
|
651
|
+
return joinMessages([trimMessage(joinMessages(kept, '\n')), notice], '');
|
|
652
|
+
}
|
|
653
|
+
kept.push(line);
|
|
654
|
+
size += cost;
|
|
655
|
+
}
|
|
656
|
+
return trimMessage(joinMessages(kept, '\n'));
|
|
657
|
+
}
|
|
658
|
+
export async function handleLoop(ctx) {
|
|
659
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
660
|
+
if (!keyInfo)
|
|
661
|
+
return;
|
|
662
|
+
const { sessionKey } = keyInfo;
|
|
663
|
+
const session = await requireActiveSession(ctx, sessionKey);
|
|
664
|
+
if (!session)
|
|
665
|
+
return;
|
|
666
|
+
const text = ctx.message?.text || '';
|
|
667
|
+
const task = text.split(' ').slice(1).join(' ').trim();
|
|
668
|
+
if (!task) {
|
|
669
|
+
await replyFormatted(ctx, modePrompt('🔄', 'Loop Mode', session.workingDirectory, `Claude will work iteratively until done (max ${config.MAX_LOOP_ITERATIONS} iterations).`, 'Describe the task:'), {
|
|
670
|
+
reply_markup: {
|
|
671
|
+
force_reply: true,
|
|
672
|
+
input_field_placeholder: 'Fix all TypeScript errors in src/',
|
|
673
|
+
selective: true,
|
|
674
|
+
},
|
|
675
|
+
});
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
try {
|
|
679
|
+
await queueRequest(sessionKey, task, async () => {
|
|
680
|
+
await withStreamingTurn(ctx, sessionKey, task, async (abortController) => {
|
|
681
|
+
const response = await sendLoopToAgent(sessionKey, task, {
|
|
682
|
+
...progressCallbacks(ctx),
|
|
683
|
+
abortController,
|
|
684
|
+
telegramCtx: ctx,
|
|
685
|
+
});
|
|
686
|
+
await messageSender.finishStreaming(ctx, response.text);
|
|
687
|
+
await maybeSendVoiceReply(ctx, response.text);
|
|
688
|
+
await closeTurn(ctx, sessionKey, response, task);
|
|
689
|
+
});
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
catch (error) {
|
|
693
|
+
if (error.message === 'Queue cleared')
|
|
694
|
+
return;
|
|
695
|
+
await ctx.reply(turnErrorReply(error));
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
export async function handleFile(ctx) {
|
|
699
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
700
|
+
if (!keyInfo)
|
|
701
|
+
return;
|
|
702
|
+
const { sessionKey } = keyInfo;
|
|
703
|
+
const text = ctx.message?.text || '';
|
|
704
|
+
const filePath = text.split(' ').slice(1).join(' ').trim();
|
|
705
|
+
const session = await requireActiveSession(ctx, sessionKey);
|
|
706
|
+
if (!session)
|
|
707
|
+
return;
|
|
708
|
+
if (!filePath) {
|
|
709
|
+
// List some files in the project to help user
|
|
710
|
+
const projectFiles = listProjectFiles(session.workingDirectory);
|
|
711
|
+
let fileList;
|
|
712
|
+
if (projectFiles.length > 0) {
|
|
713
|
+
const b = new EntityText().bold('Recent files:');
|
|
714
|
+
for (const f of projectFiles.slice(0, 8))
|
|
715
|
+
b.add('\n• ').code(f);
|
|
716
|
+
fileList = b.build();
|
|
717
|
+
}
|
|
718
|
+
await replyFormatted(ctx, modePrompt('📎', 'Download File', session.workingDirectory, fileList, 'Enter the file path:'), {
|
|
719
|
+
reply_markup: {
|
|
720
|
+
force_reply: true,
|
|
721
|
+
input_field_placeholder: 'src/index.ts',
|
|
722
|
+
selective: true,
|
|
723
|
+
},
|
|
724
|
+
});
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
const fullPath = await resolveShareableFile(ctx, session.workingDirectory, filePath);
|
|
728
|
+
if (!fullPath)
|
|
729
|
+
return;
|
|
730
|
+
const success = await messageSender.sendDocument(ctx, fullPath, `📎 ${path.basename(fullPath)}`);
|
|
731
|
+
if (!success) {
|
|
732
|
+
await ctx.reply('❌ Failed to send file. It may be too large (>50MB) or inaccessible.');
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
export async function handleTelegraph(ctx) {
|
|
736
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
737
|
+
if (!keyInfo)
|
|
738
|
+
return;
|
|
739
|
+
const { sessionKey } = keyInfo;
|
|
740
|
+
const text = ctx.message?.text || '';
|
|
741
|
+
const filePath = text.split(' ').slice(1).join(' ').trim();
|
|
742
|
+
// If no argument provided, show the settings menu
|
|
743
|
+
if (!filePath) {
|
|
744
|
+
const menu = buildTelegraphMenu(sessionKey);
|
|
745
|
+
await replyFormatted(ctx, menu.text, {
|
|
746
|
+
reply_markup: menu.keyboard.length > 0 ? { inline_keyboard: menu.keyboard } : undefined,
|
|
747
|
+
});
|
|
748
|
+
return;
|
|
749
|
+
}
|
|
750
|
+
if (await refuseFilePublish(ctx))
|
|
751
|
+
return;
|
|
752
|
+
const session = await requireActiveSession(ctx, sessionKey);
|
|
753
|
+
if (!session)
|
|
754
|
+
return;
|
|
755
|
+
const fullPath = await resolveShareableFile(ctx, session.workingDirectory, filePath);
|
|
756
|
+
if (!fullPath)
|
|
757
|
+
return;
|
|
758
|
+
const ext = path.extname(fullPath).toLowerCase();
|
|
759
|
+
if (ext !== '.md' && ext !== '.markdown') {
|
|
760
|
+
await ctx.reply('⚠️ Telegraph works best with Markdown files (.md)');
|
|
761
|
+
}
|
|
762
|
+
await ctx.reply('📤 Creating Telegraph page...');
|
|
763
|
+
const pageUrl = await createTelegraphFromFile(fullPath);
|
|
764
|
+
if (pageUrl) {
|
|
765
|
+
const fileName = path.basename(fullPath);
|
|
766
|
+
await replyFormatted(ctx, new EntityText().add('📄 ').bold(fileName).add('\n\n').link('Open in Instant View', pageUrl).build());
|
|
767
|
+
}
|
|
768
|
+
else {
|
|
769
|
+
await ctx.reply('❌ Failed to create Telegraph page.');
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
//# sourceMappingURL=command.handler.js.map
|