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,354 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP Tools — In-process MCP server factory for TeleCoder.
|
|
3
|
+
*
|
|
4
|
+
* Wraps existing standalone functions (project management, files, questions,
|
|
5
|
+
* telegraph) as MCP tools so Claude can invoke them automatically
|
|
6
|
+
* based on conversation context instead of requiring explicit /commands.
|
|
7
|
+
*/
|
|
8
|
+
import { z } from 'zod';
|
|
9
|
+
import { sanitizeError } from '../utils/sanitize.js';
|
|
10
|
+
import { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';
|
|
11
|
+
import { InputFile } from 'grammy';
|
|
12
|
+
import * as fs from 'fs';
|
|
13
|
+
import * as path from 'path';
|
|
14
|
+
import { config } from '../config.js';
|
|
15
|
+
import { sessionManager } from './session-manager.js';
|
|
16
|
+
import { getWorkspaceRoot, isPathWithinRoot } from '../utils/workspace-guard.js';
|
|
17
|
+
import { setSessionTopic, clearTopicAndRefreshBotName } from '../bot/handlers/command/topic-store.js';
|
|
18
|
+
import { messageSender } from '../telegram/message-sender.js';
|
|
19
|
+
import { createPendingQuestion, buildAskUserMessageText, buildAskUserKeyboard, buildAskUserExpiredNote, closeExpiredQuestion, questionTimeoutMinutes, } from './ask-user.js';
|
|
20
|
+
import { parseSessionKey } from '../utils/session-key.js';
|
|
21
|
+
import { parseSecretRequest, requestSecret } from './secret-request.js';
|
|
22
|
+
// Lazy imports to avoid circular deps and unnecessary module loading
|
|
23
|
+
async function importTelegraph() {
|
|
24
|
+
return import('../telegram/telegraph.js');
|
|
25
|
+
}
|
|
26
|
+
// ── Factory ──────────────────────────────────────────────────────────
|
|
27
|
+
export function createTeleCoderMcpServer(toolsCtx) {
|
|
28
|
+
const tools = buildToolList(toolsCtx);
|
|
29
|
+
return createSdkMcpServer({
|
|
30
|
+
name: 'telecoder-tools',
|
|
31
|
+
version: '1.0.0',
|
|
32
|
+
tools,
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
function buildToolList(toolsCtx) {
|
|
36
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
37
|
+
const tools = [
|
|
38
|
+
listProjectsTool(toolsCtx),
|
|
39
|
+
switchProjectTool(toolsCtx),
|
|
40
|
+
createBotTool(toolsCtx),
|
|
41
|
+
sendFileTool(toolsCtx),
|
|
42
|
+
askUserTool(toolsCtx),
|
|
43
|
+
requestSecretTool(toolsCtx),
|
|
44
|
+
];
|
|
45
|
+
if (config.DYNAMIC_BOT_NAME) {
|
|
46
|
+
tools.push(setTopicTool(toolsCtx));
|
|
47
|
+
}
|
|
48
|
+
if (config.TELEGRAPH_ENABLED) {
|
|
49
|
+
tools.push(publishTelegraphTool(toolsCtx));
|
|
50
|
+
}
|
|
51
|
+
return tools;
|
|
52
|
+
}
|
|
53
|
+
// ── Tool Definitions ─────────────────────────────────────────────────
|
|
54
|
+
function listProjectsTool(_toolsCtx) {
|
|
55
|
+
return tool('telecoder_list_projects', 'List all available projects in the workspace directory. Use this to see what projects the user can switch to.', {}, async () => {
|
|
56
|
+
try {
|
|
57
|
+
const workspaceRoot = getWorkspaceRoot();
|
|
58
|
+
const entries = fs.readdirSync(workspaceRoot, { withFileTypes: true });
|
|
59
|
+
const projects = entries
|
|
60
|
+
.filter(e => e.isDirectory() && !e.name.startsWith('.'))
|
|
61
|
+
.map(e => e.name);
|
|
62
|
+
return {
|
|
63
|
+
content: [{
|
|
64
|
+
type: 'text',
|
|
65
|
+
text: `Projects in ${workspaceRoot}:\n${projects.join('\n')}`,
|
|
66
|
+
}],
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
return {
|
|
71
|
+
content: [{ type: 'text', text: `Error listing projects: ${error instanceof Error ? error.message : String(error)}` }],
|
|
72
|
+
isError: true,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
function switchProjectTool(toolsCtx) {
|
|
78
|
+
return tool('telecoder_switch_project', 'Switch the working directory to a different project. The change takes effect on the next query. Use telecoder_list_projects first to see available projects.', { project_name: z.string().describe('Name of the project directory to switch to') }, async ({ project_name }) => {
|
|
79
|
+
try {
|
|
80
|
+
const workspaceRoot = getWorkspaceRoot();
|
|
81
|
+
const targetPath = path.resolve(workspaceRoot, project_name);
|
|
82
|
+
if (!isPathWithinRoot(workspaceRoot, targetPath)) {
|
|
83
|
+
return {
|
|
84
|
+
content: [{ type: 'text', text: `Error: Path must be within workspace root: ${workspaceRoot}` }],
|
|
85
|
+
isError: true,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
if (!fs.existsSync(targetPath) || !fs.statSync(targetPath).isDirectory()) {
|
|
89
|
+
return {
|
|
90
|
+
content: [{ type: 'text', text: `Error: Project not found: ${project_name}` }],
|
|
91
|
+
isError: true,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
sessionManager.setWorkingDirectory(toolsCtx.sessionKey, targetPath);
|
|
95
|
+
await clearTopicAndRefreshBotName(toolsCtx.telegramCtx, toolsCtx.sessionKey);
|
|
96
|
+
return {
|
|
97
|
+
content: [{
|
|
98
|
+
type: 'text',
|
|
99
|
+
text: `Switched to project: ${project_name} (${targetPath}). The new working directory will take effect on the next query.`,
|
|
100
|
+
}],
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
return {
|
|
105
|
+
content: [{ type: 'text', text: `Error switching project: ${error instanceof Error ? error.message : String(error)}` }],
|
|
106
|
+
isError: true,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
function createBotTool(toolsCtx) {
|
|
112
|
+
return tool('telecoder_create_bot', "Create a Telegram bot for one project: sends the user a button that opens Telegram's create-a-bot screen. Once they confirm, the new bot is added to the launcher and starts in that project. Use when the user asks for a bot for a project. Only from a private chat, and only for an admin.", { project_name: z.string().describe('Project directory name in the workspace, or an absolute path') }, async ({ project_name }) => {
|
|
113
|
+
try {
|
|
114
|
+
const { offerNewBotForSession } = await import('../bot/handlers/newbot.handler.js');
|
|
115
|
+
const result = await offerNewBotForSession(toolsCtx.telegramCtx.api, toolsCtx.sessionKey, project_name);
|
|
116
|
+
return { content: [{ type: 'text', text: result.message }], ...(result.ok ? {} : { isError: true }) };
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
return {
|
|
120
|
+
content: [{ type: 'text', text: `Error creating bot: ${sanitizeError(error)}` }],
|
|
121
|
+
isError: true,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
const TELEGRAM_MAX_FILE_SIZE = 50 * 1024 * 1024; // 50 MB
|
|
127
|
+
function sendFileTool(toolsCtx) {
|
|
128
|
+
return tool('telecoder_send_file', 'Send a file from the server to the user via Telegram. The file must be within the current working directory or /tmp. Use this after creating files (SVGs, images, reports, etc.) to deliver them directly to the user. Maximum file size: 50MB.', {
|
|
129
|
+
file_path: z.string().describe('Absolute or relative path to the file to send. Relative paths are resolved from the current working directory.'),
|
|
130
|
+
caption: z.string().optional().describe('Optional caption to display with the file in Telegram'),
|
|
131
|
+
}, async ({ file_path, caption }) => {
|
|
132
|
+
try {
|
|
133
|
+
const ctx = toolsCtx.telegramCtx;
|
|
134
|
+
const session = sessionManager.getSession(toolsCtx.sessionKey);
|
|
135
|
+
if (!session) {
|
|
136
|
+
return {
|
|
137
|
+
content: [{ type: 'text', text: 'Error: No active session.' }],
|
|
138
|
+
isError: true,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
// Resolve relative paths against the session working directory
|
|
142
|
+
const resolvedPath = path.isAbsolute(file_path)
|
|
143
|
+
? file_path
|
|
144
|
+
: path.resolve(session.workingDirectory, file_path);
|
|
145
|
+
// Security: validate the path is within allowed directories
|
|
146
|
+
const workspaceRoot = getWorkspaceRoot();
|
|
147
|
+
const inWorkspace = isPathWithinRoot(workspaceRoot, resolvedPath);
|
|
148
|
+
const inTmp = isPathWithinRoot('/tmp', resolvedPath);
|
|
149
|
+
if (!inWorkspace && !inTmp) {
|
|
150
|
+
return {
|
|
151
|
+
content: [{ type: 'text', text: `Error: File path must be within the workspace (${workspaceRoot}) or /tmp. Access denied.` }],
|
|
152
|
+
isError: true,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
156
|
+
return {
|
|
157
|
+
content: [{ type: 'text', text: `Error: File not found: ${path.basename(resolvedPath)}` }],
|
|
158
|
+
isError: true,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
const stat = fs.statSync(resolvedPath);
|
|
162
|
+
if (stat.isDirectory()) {
|
|
163
|
+
return {
|
|
164
|
+
content: [{ type: 'text', text: `Error: Path is a directory, not a file: ${path.basename(resolvedPath)}` }],
|
|
165
|
+
isError: true,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
if (stat.size > TELEGRAM_MAX_FILE_SIZE) {
|
|
169
|
+
const sizeMB = (stat.size / (1024 * 1024)).toFixed(1);
|
|
170
|
+
return {
|
|
171
|
+
content: [{ type: 'text', text: `Error: File too large (${sizeMB}MB). Telegram limit is 50MB.` }],
|
|
172
|
+
isError: true,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
const fileName = path.basename(resolvedPath);
|
|
176
|
+
const fileBuffer = fs.readFileSync(resolvedPath);
|
|
177
|
+
const inputFile = new InputFile(fileBuffer, fileName);
|
|
178
|
+
await ctx.replyWithDocument(inputFile, {
|
|
179
|
+
caption: caption || undefined,
|
|
180
|
+
});
|
|
181
|
+
const sizeMB = (stat.size / (1024 * 1024)).toFixed(2);
|
|
182
|
+
return {
|
|
183
|
+
content: [{
|
|
184
|
+
type: 'text',
|
|
185
|
+
text: `File sent to user: ${fileName} (${sizeMB}MB)`,
|
|
186
|
+
}],
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
return {
|
|
191
|
+
content: [{ type: 'text', text: `File send error: ${error instanceof Error ? error.message : String(error)}` }],
|
|
192
|
+
isError: true,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
function setTopicTool(toolsCtx) {
|
|
198
|
+
return tool('telecoder_set_topic', 'Update the conversation topic shown in the status line. Call this proactively when the work topic changes. Pass an empty string to clear. Keep topics very short (1-4 words).', {
|
|
199
|
+
topic: z.string().describe('Short topic label (1-4 words, e.g. "auth refactor", "CI fix", "dark mode"). Empty string to clear.'),
|
|
200
|
+
}, async ({ topic }) => {
|
|
201
|
+
try {
|
|
202
|
+
const { sessionKey } = toolsCtx;
|
|
203
|
+
// The topic lives in the status line, not the Telegram bot display name
|
|
204
|
+
// (which only carries BOT_NAME — project). So we update in-memory +
|
|
205
|
+
// persistent topic state and DO NOT call setMyName. Telegram rate-limits
|
|
206
|
+
// setMyName brutally — firing it on every proactive topic change is what
|
|
207
|
+
// trips multi-hour 429 flood-waits. Mirrors the /topic command handler.
|
|
208
|
+
const trimmedTopic = topic.trim();
|
|
209
|
+
setSessionTopic(sessionKey, trimmedTopic);
|
|
210
|
+
return {
|
|
211
|
+
content: [{
|
|
212
|
+
type: 'text',
|
|
213
|
+
text: trimmedTopic
|
|
214
|
+
? `Topic set to "${trimmedTopic}".`
|
|
215
|
+
: 'Topic cleared.',
|
|
216
|
+
}],
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
catch (error) {
|
|
220
|
+
return {
|
|
221
|
+
content: [{
|
|
222
|
+
type: 'text',
|
|
223
|
+
text: `Failed to set topic: ${error instanceof Error ? error.message : String(error)}`,
|
|
224
|
+
}],
|
|
225
|
+
isError: true,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
function publishTelegraphTool(_toolsCtx) {
|
|
231
|
+
return tool('telecoder_publish_telegraph', 'Publish markdown content as a Telegraph (telegra.ph) Instant View page. Returns the URL. Useful for sharing long-form content as a readable link.', {
|
|
232
|
+
title: z.string().describe('Page title'),
|
|
233
|
+
markdown: z.string().describe('Markdown content for the page'),
|
|
234
|
+
}, async ({ title, markdown }) => {
|
|
235
|
+
try {
|
|
236
|
+
const { createTelegraphPage } = await importTelegraph();
|
|
237
|
+
const url = await createTelegraphPage(title, markdown);
|
|
238
|
+
if (!url) {
|
|
239
|
+
return {
|
|
240
|
+
content: [{ type: 'text', text: 'Failed to create Telegraph page.' }],
|
|
241
|
+
isError: true,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
return {
|
|
245
|
+
content: [{ type: 'text', text: `Telegraph page created: ${url}` }],
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
catch (error) {
|
|
249
|
+
return {
|
|
250
|
+
content: [{ type: 'text', text: `Telegraph error: ${error instanceof Error ? error.message : String(error)}` }],
|
|
251
|
+
isError: true,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
function askUserTool(toolsCtx) {
|
|
257
|
+
return tool('telecoder_ask_user', 'Ask the user a multiple-choice question via a Telegram inline keyboard. Use when you need a clear decision from the user (e.g. picking between approaches, confirming a destructive action, choosing among options) instead of free-text. Pauses the agent loop until the user taps a button or the question times out. Keep the question short and the options crisp — a label of ≤ 25 chars stays on its button; anything longer makes the whole keyboard fall back to lettered buttons (A/B/C) with the full labels listed in the message body. IMPORTANT: `context` is required and carries everything the user needs to decide (the comparison, trade-offs, findings, rationale) — it renders in the SAME message as the buttons. Do NOT write that explanation as prose before calling this tool: text you emit before an ask_user call is not delivered to the user until after they answer, so they would be choosing blind.', {
|
|
258
|
+
question: z.string().describe('The question to display to the user. Keep concise (1-2 sentences).'),
|
|
259
|
+
context: z
|
|
260
|
+
.string()
|
|
261
|
+
.min(1)
|
|
262
|
+
.describe('Required. The multi-line explanation shown above the buttons in the same message (e.g. a comparison table, trade-offs, findings the user needs to make an informed choice). Put decision-relevant detail here, not in prose before the call — that prose is not shown until after the user answers. If the choice genuinely needs no explanation, restate what each option will do.'),
|
|
263
|
+
options: z
|
|
264
|
+
.array(z.object({
|
|
265
|
+
label: z.string().describe('Button label. ≤ 25 chars keeps the label on its own button; longer labels are still shown in full in the message body, keyed A/B/C. Keep it to one line either way.'),
|
|
266
|
+
description: z.string().optional().describe('Optional one-line context shown in the question body.'),
|
|
267
|
+
}))
|
|
268
|
+
.min(2)
|
|
269
|
+
.max(8)
|
|
270
|
+
.describe('Between 2 and 8 options for the user to choose from.'),
|
|
271
|
+
}, async ({ question, context, options }) => {
|
|
272
|
+
try {
|
|
273
|
+
const ctx = toolsCtx.telegramCtx;
|
|
274
|
+
if (!ctx?.chat?.id) {
|
|
275
|
+
return {
|
|
276
|
+
content: [{ type: 'text', text: 'Error: no Telegram context available to ask the user.' }],
|
|
277
|
+
isError: true,
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
const optionLabels = options.map((o) => o.label);
|
|
281
|
+
const { id, promise } = createPendingQuestion(optionLabels, undefined, toolsCtx.sessionKey);
|
|
282
|
+
const messageText = buildAskUserMessageText(question, options, context);
|
|
283
|
+
const keyboard = buildAskUserKeyboard(id, options);
|
|
284
|
+
// Plain text (no parse_mode): model-supplied question/context/label/
|
|
285
|
+
// description text can contain stray underscores, asterisks, or
|
|
286
|
+
// backticks (e.g. URL params like `f_WT=2`) that break legacy Markdown
|
|
287
|
+
// parsing — Telegram returns 400 and the tool fails with no useful
|
|
288
|
+
// signal to the model. The body lists every option in full, keyed by
|
|
289
|
+
// the letter on its button.
|
|
290
|
+
// From the session key, not `ctx.message` — a turn started by a tapped
|
|
291
|
+
// button carries a callback-query context with no `message`, which
|
|
292
|
+
// would silently drop the thread and post into General.
|
|
293
|
+
const threadId = parseSessionKey(toolsCtx.sessionKey).threadId;
|
|
294
|
+
const sent = await ctx.api.sendMessage(ctx.chat.id, messageText, {
|
|
295
|
+
reply_markup: { inline_keyboard: keyboard },
|
|
296
|
+
...(threadId !== undefined ? { message_thread_id: threadId } : {}),
|
|
297
|
+
});
|
|
298
|
+
await messageSender.noteQuestionPosted(ctx, toolsCtx.sessionKey);
|
|
299
|
+
const answer = await promise;
|
|
300
|
+
await messageSender.noteQuestionAnswered(ctx, toolsCtx.sessionKey);
|
|
301
|
+
if (!answer) {
|
|
302
|
+
await closeExpiredQuestion(ctx.api, sent, messageText, buildAskUserExpiredNote());
|
|
303
|
+
return {
|
|
304
|
+
content: [{ type: 'text', text: `User did not respond within ${questionTimeoutMinutes()} minutes. Proceed using your best judgment or ask again.` }],
|
|
305
|
+
isError: false,
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
return {
|
|
309
|
+
content: [{ type: 'text', text: `User selected: ${answer.label}` }],
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
catch (error) {
|
|
313
|
+
return {
|
|
314
|
+
content: [{ type: 'text', text: `Ask-user error: ${error instanceof Error ? error.message : String(error)}` }],
|
|
315
|
+
isError: true,
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* The SDK side of telecoder_request_secret; secret-request.ts has the flow.
|
|
322
|
+
* The description and fields match src/bin/mcp-server.ts's, which PTY mode
|
|
323
|
+
* registers.
|
|
324
|
+
*/
|
|
325
|
+
function requestSecretTool(toolsCtx) {
|
|
326
|
+
return tool('telecoder_request_secret', 'Get a secret from the user (an API key, token or password) without it entering this conversation. The user sends it in Telegram; TeleCoder deletes their message at once and runs `command` with the secret in $SECRET and on stdin. You get the exit code and the output with the secret blanked out, never the value. Use this whenever a task needs a credential from the user: never ask them to paste one into the chat, and don\'t send them to a terminal for it. They see the command before they send anything, so make it do exactly what it says. For a long-lived Claude token (CLAUDE_CODE_OAUTH_TOKEN), set source to "claude-setup-token": TeleCoder runs `claude setup-token` on this machine and walks them through signing in, and the token goes straight into your command without passing through Telegram. Works only in a private chat with an admin of the bot. Blocks until the command has run, the user cancels, or the request times out.', {
|
|
327
|
+
name: z.string().min(1).max(100).describe('What the secret is, as the user knows it: an env var name like CLAUDE_CODE_OAUTH_TOKEN, or a label like "Stripe test key".'),
|
|
328
|
+
purpose: z.string().min(1).describe('One or two sentences for the user: what it is for, and where to get it.'),
|
|
329
|
+
command: z.string().min(1).describe('Bash that consumes the secret, from $SECRET or from stdin (the secret and a newline). It runs once, with no terminal, and has 2 minutes. Prefer stdin where the tool reads it: an argument shows in the process list while the command runs. Example: npx dotenvx set API_KEY "$SECRET" -f .env'),
|
|
330
|
+
cwd: z.string().optional().describe('Directory to run the command in. Defaults to the session\'s working directory; ~ works.'),
|
|
331
|
+
pattern: z.string().optional().describe('A regular expression the secret has to match, e.g. ^sk-ant-oat01-. A message that doesn\'t match is deleted unused and the user asked again, so a stray reply can\'t end up stored as the secret.'),
|
|
332
|
+
source: z.enum(['paste', 'claude-setup-token']).optional().describe('"paste" (the default): the user sends the secret. "claude-setup-token": TeleCoder makes a long-lived Claude OAuth token by running `claude setup-token` here; the user signs in through a link and sends back the code the page shows. A token they already have is accepted too.'),
|
|
333
|
+
}, async ({ name, purpose, command, cwd, pattern, source }, extra) => {
|
|
334
|
+
try {
|
|
335
|
+
const req = parseSecretRequest({ name, purpose, command, cwd, pattern, source });
|
|
336
|
+
if (typeof req === 'string')
|
|
337
|
+
return { content: [{ type: 'text', text: req }], isError: true };
|
|
338
|
+
const signal = extra?.signal;
|
|
339
|
+
const { sessionKey, telegramCtx: ctx } = toolsCtx;
|
|
340
|
+
const result = await requestSecret(ctx, sessionKey, req, signal, {
|
|
341
|
+
onPosted: () => messageSender.noteQuestionPosted(ctx, sessionKey),
|
|
342
|
+
onSettled: () => messageSender.noteQuestionAnswered(ctx, sessionKey),
|
|
343
|
+
});
|
|
344
|
+
return { content: [{ type: 'text', text: result.message }], isError: !result.success };
|
|
345
|
+
}
|
|
346
|
+
catch (error) {
|
|
347
|
+
return {
|
|
348
|
+
content: [{ type: 'text', text: `Secret request error: ${error instanceof Error ? error.message : String(error)}` }],
|
|
349
|
+
isError: true,
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
//# sourceMappingURL=mcp-tools.js.map
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Index from a Telegram assistant message_id → the JSONL truncation point
|
|
3
|
+
* that recreates the conversation state at the moment that message was sent.
|
|
4
|
+
*
|
|
5
|
+
* Used by /fork: the user taps a "🍴 Fork" button on a past assistant message,
|
|
6
|
+
* we look up the recorded {claudeSessionId, lineCount, projectPath} for that
|
|
7
|
+
* message, and slice the source JSONL to lineCount to build the truncated
|
|
8
|
+
* transcript that gets handed off to the target bot.
|
|
9
|
+
*
|
|
10
|
+
* File-backed (~/.telecoder/message-offsets-<botId>.json) so a restart
|
|
11
|
+
* doesn't invalidate fork buttons that were posted before the restart.
|
|
12
|
+
* Bounded per sessionKey to keep the file from growing forever — old
|
|
13
|
+
* entries simply lose their fork button (the button still exists in chat
|
|
14
|
+
* history; on tap we report "fork point no longer available").
|
|
15
|
+
*/
|
|
16
|
+
import * as fs from 'fs';
|
|
17
|
+
import * as path from 'path';
|
|
18
|
+
import { z } from 'zod';
|
|
19
|
+
import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
|
|
20
|
+
import { BOT_ID } from '../config.js';
|
|
21
|
+
const HISTORY_DIR = getStateDir();
|
|
22
|
+
const entrySchema = z.object({
|
|
23
|
+
claudeSessionId: z.string(),
|
|
24
|
+
projectPath: z.string(),
|
|
25
|
+
lineCount: z.number().int().nonnegative(),
|
|
26
|
+
topic: z.string().optional(),
|
|
27
|
+
conversationId: z.string().optional(),
|
|
28
|
+
ts: z.string(),
|
|
29
|
+
});
|
|
30
|
+
const fileSchema = z.object({
|
|
31
|
+
sessions: z.record(z.string(), z.record(z.string(), entrySchema)),
|
|
32
|
+
});
|
|
33
|
+
const MAX_OFFSETS_PER_SESSION = 200;
|
|
34
|
+
class MessageOffsetStore {
|
|
35
|
+
data = { sessions: {} };
|
|
36
|
+
filePath;
|
|
37
|
+
constructor() {
|
|
38
|
+
this.filePath = path.join(HISTORY_DIR, `message-offsets-${BOT_ID}.json`);
|
|
39
|
+
ensureStateDir(HISTORY_DIR, 'MessageOffsets');
|
|
40
|
+
this.load();
|
|
41
|
+
}
|
|
42
|
+
load() {
|
|
43
|
+
const loaded = readJsonFile(this.filePath, fileSchema, 'MessageOffsets');
|
|
44
|
+
if (loaded)
|
|
45
|
+
this.data = loaded;
|
|
46
|
+
}
|
|
47
|
+
save() {
|
|
48
|
+
writeJsonFile(this.filePath, this.data, 'MessageOffsets');
|
|
49
|
+
}
|
|
50
|
+
record(sessionKey, telegramMessageId, entry) {
|
|
51
|
+
const bucket = this.data.sessions[sessionKey] ?? {};
|
|
52
|
+
bucket[String(telegramMessageId)] = { ...entry, ts: new Date().toISOString() };
|
|
53
|
+
// Trim oldest entries beyond the cap (by ts ascending).
|
|
54
|
+
const keys = Object.keys(bucket);
|
|
55
|
+
if (keys.length > MAX_OFFSETS_PER_SESSION) {
|
|
56
|
+
const sorted = keys.sort((a, b) => bucket[a].ts.localeCompare(bucket[b].ts));
|
|
57
|
+
const excess = sorted.slice(0, keys.length - MAX_OFFSETS_PER_SESSION);
|
|
58
|
+
for (const k of excess)
|
|
59
|
+
delete bucket[k];
|
|
60
|
+
}
|
|
61
|
+
this.data.sessions[sessionKey] = bucket;
|
|
62
|
+
this.save();
|
|
63
|
+
}
|
|
64
|
+
lookup(sessionKey, telegramMessageId) {
|
|
65
|
+
return this.data.sessions[sessionKey]?.[String(telegramMessageId)];
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export const messageOffsets = new MessageOffsetStore();
|
|
69
|
+
/**
|
|
70
|
+
* Count current JSONL lines for a session. Used at "turn finished" time to
|
|
71
|
+
* record the truncation boundary for the Fork button.
|
|
72
|
+
*/
|
|
73
|
+
export function countJsonlLines(filePath) {
|
|
74
|
+
try {
|
|
75
|
+
const raw = fs.readFileSync(filePath, 'utf-8');
|
|
76
|
+
if (!raw)
|
|
77
|
+
return 0;
|
|
78
|
+
// JSONL is line-delimited; trailing newline shouldn't count as a record.
|
|
79
|
+
const lines = raw.split('\n');
|
|
80
|
+
if (lines[lines.length - 1] === '')
|
|
81
|
+
lines.pop();
|
|
82
|
+
return lines.length;
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return 0;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
//# sourceMappingURL=message-offsets.js.map
|