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,576 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* telecoder_request_secret: a secret from the user that never enters the
|
|
3
|
+
* conversation.
|
|
4
|
+
*
|
|
5
|
+
* A task that needed a credential used to stop at a set of instructions: open
|
|
6
|
+
* a terminal on the machine, over SSH, and type it there, because anything
|
|
7
|
+
* sent in the chat, or run there with `!`, lands in the session log, in the
|
|
8
|
+
* context sent to the model, and in the Telegram history. From a phone that's
|
|
9
|
+
* as far as it goes.
|
|
10
|
+
*
|
|
11
|
+
* Instead the agent names the secret and the command that consumes it, and
|
|
12
|
+
* the user sends the secret as an ordinary message. {@link captureSecretMessages}
|
|
13
|
+
* takes it out of the update stream before anything can queue, batch or
|
|
14
|
+
* forward it, and deletes it from the chat. The command then runs with the
|
|
15
|
+
* secret in $SECRET and on stdin, and the agent gets the exit code and the
|
|
16
|
+
* output with the secret blanked out. Never the value.
|
|
17
|
+
*
|
|
18
|
+
* For a long-lived Claude token the user needs no terminal at all. With source
|
|
19
|
+
* "claude-setup-token" the bot runs `claude setup-token` in a pty of its own
|
|
20
|
+
* (setup-token.ts) and passes the sign-in link on. The user approves in any
|
|
21
|
+
* browser and sends back the code the page shows, and the token goes from that
|
|
22
|
+
* pty straight into the command, without passing through Telegram.
|
|
23
|
+
*
|
|
24
|
+
* The limits are what keep it a secret:
|
|
25
|
+
* - private chats only, because in a group everyone sees a message before
|
|
26
|
+
* it can be deleted
|
|
27
|
+
* - admins only, because the command runs outside Claude Code's permission
|
|
28
|
+
* prompts and TeleCoder's permission gate, approved by whoever supplies
|
|
29
|
+
* the secret
|
|
30
|
+
* - the user sees the command before they send anything
|
|
31
|
+
* - one request per chat, waiting at most QUESTION_TIMEOUT_MINUTES
|
|
32
|
+
* - nothing kept: the value lives in this process until the command has
|
|
33
|
+
* run, and is never logged
|
|
34
|
+
*/
|
|
35
|
+
import * as crypto from 'crypto';
|
|
36
|
+
import * as fs from 'fs';
|
|
37
|
+
import * as os from 'os';
|
|
38
|
+
import * as path from 'path';
|
|
39
|
+
import { spawn, spawnSync } from 'child_process';
|
|
40
|
+
import { EntityText, clip } from '../telegram/entities.js';
|
|
41
|
+
import { envWithoutParentSession } from '../utils/claude-env.js';
|
|
42
|
+
import { isAdmin } from '../utils/admins.js';
|
|
43
|
+
import { sanitizeError } from '../utils/sanitize.js';
|
|
44
|
+
import { getSessionKeyFromCtx, parseSessionKey } from '../utils/session-key.js';
|
|
45
|
+
import { noteAwaitingUser, questionTimeoutMs } from './ask-user.js';
|
|
46
|
+
import { sessionManager } from './session-manager.js';
|
|
47
|
+
import { SetupTokenRun, looksLikeOAuthToken } from './setup-token.js';
|
|
48
|
+
/** How long the command gets. npx may have to download its package first. */
|
|
49
|
+
export const COMMAND_TIMEOUT_MS = 2 * 60 * 1000;
|
|
50
|
+
/** What the secret is shown as in output passed on. */
|
|
51
|
+
export const REDACTED = '[secret]';
|
|
52
|
+
/** Codes a user can try before the setup-token run is given up on. */
|
|
53
|
+
const MAX_CODE_ATTEMPTS = 3;
|
|
54
|
+
const LINK_TIMEOUT_MS = 30_000;
|
|
55
|
+
const CODE_CHECK_TIMEOUT_MS = 60_000;
|
|
56
|
+
/** Command output kept before the secret is blanked out and the tail taken. */
|
|
57
|
+
const MAX_OUTPUT_KEPT = 1024 * 1024;
|
|
58
|
+
const OUTPUT_FOR_USER = 700;
|
|
59
|
+
const OUTPUT_FOR_AGENT = 3000;
|
|
60
|
+
const NAME_MAX = 100;
|
|
61
|
+
const PURPOSE_MAX = 1200;
|
|
62
|
+
const COMMAND_MAX = 1500;
|
|
63
|
+
const ANSI = /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-Z\\-_]/g;
|
|
64
|
+
/** Read a request out of an MCP call's arguments, or say what's wrong with it. */
|
|
65
|
+
export function parseSecretRequest(body) {
|
|
66
|
+
const text = (value) => (typeof value === 'string' ? value.trim() : '');
|
|
67
|
+
const name = text(body.name);
|
|
68
|
+
const command = text(body.command);
|
|
69
|
+
if (!name)
|
|
70
|
+
return 'Error: name is required.';
|
|
71
|
+
if (name.length > NAME_MAX) {
|
|
72
|
+
return `Error: name is over ${NAME_MAX} characters. It's a label, like CLAUDE_CODE_OAUTH_TOKEN.`;
|
|
73
|
+
}
|
|
74
|
+
if (!command)
|
|
75
|
+
return 'Error: command is required.';
|
|
76
|
+
return {
|
|
77
|
+
name,
|
|
78
|
+
purpose: text(body.purpose),
|
|
79
|
+
command,
|
|
80
|
+
cwd: text(body.cwd) || undefined,
|
|
81
|
+
pattern: text(body.pattern) || undefined,
|
|
82
|
+
source: body.source === 'claude-setup-token' ? 'claude-setup-token' : 'paste',
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/** The directory a command runs in, or why it can't run there. */
|
|
86
|
+
export function resolveCommandCwd(cwd, sessionDir) {
|
|
87
|
+
const base = sessionDir ?? os.homedir();
|
|
88
|
+
let dir = cwd || base;
|
|
89
|
+
if (dir === '~')
|
|
90
|
+
dir = os.homedir();
|
|
91
|
+
else if (dir.startsWith('~/'))
|
|
92
|
+
dir = path.join(os.homedir(), dir.slice(2));
|
|
93
|
+
dir = path.resolve(base, dir);
|
|
94
|
+
try {
|
|
95
|
+
if (!fs.statSync(dir).isDirectory())
|
|
96
|
+
return { error: `Error: cwd is not a directory: ${dir}` };
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return { error: `Error: cwd doesn't exist: ${dir}` };
|
|
100
|
+
}
|
|
101
|
+
return { dir };
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Bash's own syntax check, so a quoting slip turns up before the user is asked
|
|
105
|
+
* for anything rather than after they've handed the secret over.
|
|
106
|
+
*/
|
|
107
|
+
export function checkCommandSyntax(command) {
|
|
108
|
+
const result = spawnSync('bash', ['-n', '-c', command], { encoding: 'utf8', timeout: 5000 });
|
|
109
|
+
// No bash to check with: running it will say so.
|
|
110
|
+
if (result.error || result.status === 0)
|
|
111
|
+
return undefined;
|
|
112
|
+
return result.stderr.trim() || `bash -n exited with code ${result.status}`;
|
|
113
|
+
}
|
|
114
|
+
export function redactSecret(text, secret) {
|
|
115
|
+
return secret ? text.split(secret).join(REDACTED) : text;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Run `command` with the secret in $SECRET and on stdin, followed by a
|
|
119
|
+
* newline. No terminal: a command that prompts gets end-of-file.
|
|
120
|
+
*/
|
|
121
|
+
export function runWithSecret(command, cwd, secret, timeoutMs = COMMAND_TIMEOUT_MS) {
|
|
122
|
+
return new Promise((resolve) => {
|
|
123
|
+
let output = '';
|
|
124
|
+
let timedOut = false;
|
|
125
|
+
let settled = false;
|
|
126
|
+
const child = spawn('bash', ['-c', command], {
|
|
127
|
+
cwd,
|
|
128
|
+
env: { ...envWithoutParentSession(), SECRET: secret },
|
|
129
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
130
|
+
// A group of its own, so a timeout also reaches whatever it started.
|
|
131
|
+
detached: true,
|
|
132
|
+
});
|
|
133
|
+
const collect = (chunk) => {
|
|
134
|
+
output = (output + chunk.toString('utf8')).slice(-MAX_OUTPUT_KEPT);
|
|
135
|
+
};
|
|
136
|
+
child.stdout.on('data', collect);
|
|
137
|
+
child.stderr.on('data', collect);
|
|
138
|
+
// A command that never reads stdin can be gone before the write lands.
|
|
139
|
+
child.stdin.on('error', () => { });
|
|
140
|
+
child.stdin.end(`${secret}\n`);
|
|
141
|
+
const signalGroup = (signal) => {
|
|
142
|
+
try {
|
|
143
|
+
if (child.pid)
|
|
144
|
+
process.kill(-child.pid, signal);
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
try {
|
|
148
|
+
child.kill(signal);
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
// Already gone.
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
const timer = setTimeout(() => {
|
|
156
|
+
timedOut = true;
|
|
157
|
+
signalGroup('SIGTERM');
|
|
158
|
+
setTimeout(() => signalGroup('SIGKILL'), 5000).unref();
|
|
159
|
+
}, timeoutMs);
|
|
160
|
+
const finish = (exitCode, signal, note = '') => {
|
|
161
|
+
if (settled)
|
|
162
|
+
return;
|
|
163
|
+
settled = true;
|
|
164
|
+
clearTimeout(timer);
|
|
165
|
+
const text = redactSecret((output + note).replace(ANSI, ''), secret).trim();
|
|
166
|
+
resolve({ exitCode, signal, timedOut, output: text });
|
|
167
|
+
};
|
|
168
|
+
child.on('error', (err) => finish(null, null, `\n${err.message}`));
|
|
169
|
+
child.on('close', (code, signal) => finish(code, signal));
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
export function describeExit(run, timeoutMs = COMMAND_TIMEOUT_MS) {
|
|
173
|
+
if (run.timedOut)
|
|
174
|
+
return `timed out after ${Math.round(timeoutMs / 1000)}s`;
|
|
175
|
+
if (run.signal)
|
|
176
|
+
return `killed by ${run.signal}`;
|
|
177
|
+
if (run.exitCode === null)
|
|
178
|
+
return "couldn't start";
|
|
179
|
+
return `exit ${run.exitCode}`;
|
|
180
|
+
}
|
|
181
|
+
function tailOf(text, max) {
|
|
182
|
+
return text.length <= max ? text : `…${text.slice(-(max - 1))}`;
|
|
183
|
+
}
|
|
184
|
+
function tildify(dir) {
|
|
185
|
+
const home = os.homedir();
|
|
186
|
+
return dir === home ? '~' : dir.startsWith(`${home}/`) ? `~${dir.slice(home.length)}` : dir;
|
|
187
|
+
}
|
|
188
|
+
/** The message that asks for the secret, before any status is added under it. */
|
|
189
|
+
export function buildSecretPrompt(req, cwd, state = {}) {
|
|
190
|
+
const b = new EntityText();
|
|
191
|
+
b.add('🔐 Claude asks for a secret: ').bold(clip(req.name, NAME_MAX)).newline(2);
|
|
192
|
+
if (req.purpose)
|
|
193
|
+
b.add(clip(req.purpose, PURPOSE_MAX)).newline(2);
|
|
194
|
+
b.add('It goes into this command, not to Claude:').newline();
|
|
195
|
+
b.pre(clip(`cd ${tildify(cwd)}\n${req.command}`, COMMAND_MAX), 'bash').newline();
|
|
196
|
+
if (state.link) {
|
|
197
|
+
b.add('To make a token, open the ')
|
|
198
|
+
.link('sign-in page', state.link)
|
|
199
|
+
.add(', approve, and send me the code it shows. Already have a token? Send that instead. ')
|
|
200
|
+
.add('Either way I delete your message the moment it arrives, and a token made here never passes through this chat.');
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
if (state.setupProblem) {
|
|
204
|
+
b.add(`I couldn't start claude setup-token here: ${clip(state.setupProblem, 300)}`).newline(2);
|
|
205
|
+
}
|
|
206
|
+
b.add('Send it as your next message. I delete it from the chat the moment it arrives.');
|
|
207
|
+
}
|
|
208
|
+
return b.build();
|
|
209
|
+
}
|
|
210
|
+
/** `prompt` with a status line, or block, under it. */
|
|
211
|
+
export function withStatus(prompt, status) {
|
|
212
|
+
const b = new EntityText().append(prompt).newline(2);
|
|
213
|
+
if (typeof status === 'string')
|
|
214
|
+
b.add(status);
|
|
215
|
+
else
|
|
216
|
+
b.append(status);
|
|
217
|
+
return b.build();
|
|
218
|
+
}
|
|
219
|
+
export function secretKeyboard(id, link) {
|
|
220
|
+
const rows = [];
|
|
221
|
+
if (link)
|
|
222
|
+
rows.push([{ text: '🔑 Sign in to Claude', url: link }]);
|
|
223
|
+
rows.push([{ text: 'Cancel', callback_data: `secret:${id}:cancel` }]);
|
|
224
|
+
return rows;
|
|
225
|
+
}
|
|
226
|
+
function statusWithOutput(head, output, footer) {
|
|
227
|
+
const b = new EntityText().add(head);
|
|
228
|
+
if (output)
|
|
229
|
+
b.newline().pre(tailOf(output, OUTPUT_FOR_USER));
|
|
230
|
+
if (footer)
|
|
231
|
+
b.newline().add(footer);
|
|
232
|
+
return b.build();
|
|
233
|
+
}
|
|
234
|
+
/** Open requests, by session key. */
|
|
235
|
+
const pending = new Map();
|
|
236
|
+
export function hasPendingSecret(sessionKey) {
|
|
237
|
+
return pending.has(sessionKey);
|
|
238
|
+
}
|
|
239
|
+
/** Stop waiting on a secret in this chat, as /cancel does. False when there was none. */
|
|
240
|
+
export function cancelSecretRequest(sessionKey) {
|
|
241
|
+
const entry = pending.get(sessionKey);
|
|
242
|
+
if (!entry)
|
|
243
|
+
return false;
|
|
244
|
+
entry.end('user');
|
|
245
|
+
return true;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Take a message meant as a secret out of the update stream: delete it from
|
|
249
|
+
* the chat and hand it to the request, and nothing after this middleware sees
|
|
250
|
+
* it. Registered ahead of the batcher, the queue and sequentialize, since the
|
|
251
|
+
* turn that asked is blocked until it gets an answer, and an answer waiting
|
|
252
|
+
* behind that turn would never arrive.
|
|
253
|
+
*
|
|
254
|
+
* Commands go through, so /cancel works. A secret that starts with `/` can't
|
|
255
|
+
* be given this way.
|
|
256
|
+
*/
|
|
257
|
+
export const captureSecretMessages = async (ctx, next) => {
|
|
258
|
+
const message = ctx.message;
|
|
259
|
+
const text = message?.text;
|
|
260
|
+
if (!message || text === undefined || text.startsWith('/'))
|
|
261
|
+
return next();
|
|
262
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
263
|
+
const entry = keyInfo ? pending.get(keyInfo.sessionKey) : undefined;
|
|
264
|
+
if (!entry || !entry.capturing || ctx.from?.id !== entry.userId)
|
|
265
|
+
return next();
|
|
266
|
+
let deleted = true;
|
|
267
|
+
try {
|
|
268
|
+
await ctx.api.deleteMessage(message.chat.id, message.message_id);
|
|
269
|
+
}
|
|
270
|
+
catch (err) {
|
|
271
|
+
deleted = false;
|
|
272
|
+
console.warn('[Secret] Could not delete a captured message:', sanitizeError(err));
|
|
273
|
+
}
|
|
274
|
+
entry.receive(text, deleted);
|
|
275
|
+
};
|
|
276
|
+
/** The Cancel button under a request. Registered ahead of sequentialize too. */
|
|
277
|
+
export async function handleSecretCallback(ctx) {
|
|
278
|
+
const [, id, action] = (ctx.callbackQuery?.data ?? '').split(':');
|
|
279
|
+
const entry = [...pending.values()].find((p) => p.id === id);
|
|
280
|
+
if (!entry || action !== 'cancel') {
|
|
281
|
+
await ctx.answerCallbackQuery({ text: 'This request is already closed.' }).catch(() => { });
|
|
282
|
+
await ctx.editMessageReplyMarkup().catch(() => { });
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
if (ctx.from?.id !== entry.userId) {
|
|
286
|
+
await ctx.answerCallbackQuery({ text: 'Only the person asked can cancel this.' }).catch(() => { });
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
entry.end('user');
|
|
290
|
+
await ctx.answerCallbackQuery({ text: 'Cancelled' }).catch(() => { });
|
|
291
|
+
}
|
|
292
|
+
function race(work, ended) {
|
|
293
|
+
return Promise.race([
|
|
294
|
+
work.then((value) => ({ ok: true, value })),
|
|
295
|
+
ended.then((why) => ({ ok: false, why })),
|
|
296
|
+
]);
|
|
297
|
+
}
|
|
298
|
+
const refuse = (message) => ({ success: false, message });
|
|
299
|
+
/**
|
|
300
|
+
* Ask the user for a secret, and run the request's command with it. Resolves
|
|
301
|
+
* once the command has run or the request has ended without a secret, with
|
|
302
|
+
* what the agent should be told. The secret itself is in neither.
|
|
303
|
+
*/
|
|
304
|
+
export async function requestSecret(ctx, sessionKey, req, signal, deps = {}) {
|
|
305
|
+
const chat = ctx.chat;
|
|
306
|
+
if (!chat)
|
|
307
|
+
return refuse('Error: there is no Telegram chat to ask in.');
|
|
308
|
+
if (chat.type !== 'private') {
|
|
309
|
+
return refuse('Error: secrets can only be asked for in a private chat with the bot. In a group, everyone would see the '
|
|
310
|
+
+ 'message before it could be deleted. Ask the user to message the bot directly, or to do this step themselves.');
|
|
311
|
+
}
|
|
312
|
+
// In a private chat the chat's id is the user's.
|
|
313
|
+
if (!isAdmin(chat.id)) {
|
|
314
|
+
return refuse("Error: only an admin of this bot can supply secrets, since the command runs outside TeleCoder's "
|
|
315
|
+
+ 'permission gate. Ask the owner of the bot to do this step.');
|
|
316
|
+
}
|
|
317
|
+
if (pending.has(sessionKey)) {
|
|
318
|
+
return refuse('Error: a secret request is already open in this chat. Wait for it to finish first.');
|
|
319
|
+
}
|
|
320
|
+
const where = resolveCommandCwd(req.cwd, sessionManager.getSession(sessionKey)?.workingDirectory);
|
|
321
|
+
if ('error' in where)
|
|
322
|
+
return refuse(where.error);
|
|
323
|
+
const syntaxError = checkCommandSyntax(req.command);
|
|
324
|
+
if (syntaxError)
|
|
325
|
+
return refuse(`Error: the command doesn't parse, so the user wasn't asked:\n${syntaxError}`);
|
|
326
|
+
let pattern;
|
|
327
|
+
if (req.pattern) {
|
|
328
|
+
try {
|
|
329
|
+
pattern = new RegExp(req.pattern);
|
|
330
|
+
}
|
|
331
|
+
catch (err) {
|
|
332
|
+
return refuse(`Error: pattern isn't a valid regular expression: ${err instanceof Error ? err.message : err}`);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
const cwd = where.dir;
|
|
336
|
+
const chatId = chat.id;
|
|
337
|
+
const threadId = parseSessionKey(sessionKey).threadId;
|
|
338
|
+
const thread = threadId !== undefined ? { message_thread_id: threadId } : {};
|
|
339
|
+
const id = crypto.randomBytes(4).toString('hex');
|
|
340
|
+
const waitMs = deps.waitMs ?? questionTimeoutMs();
|
|
341
|
+
const minutes = Math.max(1, Math.round(waitMs / 60_000));
|
|
342
|
+
const inMinutes = `${minutes} minute${minutes === 1 ? '' : 's'}`;
|
|
343
|
+
const runCommand = deps.runCommand ?? runWithSecret;
|
|
344
|
+
let endWith;
|
|
345
|
+
const ended = new Promise((resolve) => {
|
|
346
|
+
endWith = resolve;
|
|
347
|
+
});
|
|
348
|
+
// Messages the middleware has taken, waiting to be read.
|
|
349
|
+
const inbox = [];
|
|
350
|
+
let wake;
|
|
351
|
+
const nextText = () => new Promise((resolve) => {
|
|
352
|
+
const take = () => {
|
|
353
|
+
wake = undefined;
|
|
354
|
+
resolve(inbox.shift());
|
|
355
|
+
};
|
|
356
|
+
if (inbox.length > 0)
|
|
357
|
+
take();
|
|
358
|
+
else
|
|
359
|
+
wake = take;
|
|
360
|
+
});
|
|
361
|
+
// Only while this is true is the next message taken as a secret or a code.
|
|
362
|
+
// Outside it a message is still taken out of the chat, unread: a second
|
|
363
|
+
// paste of the same secret is the likeliest one to arrive then.
|
|
364
|
+
let accepting = false;
|
|
365
|
+
let undeleted = false;
|
|
366
|
+
let toldBusy = false;
|
|
367
|
+
let prompt = { text: '', entities: [] };
|
|
368
|
+
let messageId;
|
|
369
|
+
const entry = {
|
|
370
|
+
id,
|
|
371
|
+
sessionKey,
|
|
372
|
+
userId: chatId,
|
|
373
|
+
get capturing() {
|
|
374
|
+
return messageId !== undefined;
|
|
375
|
+
},
|
|
376
|
+
receive: (text, deleted) => {
|
|
377
|
+
if (!deleted)
|
|
378
|
+
undeleted = true;
|
|
379
|
+
if (accepting) {
|
|
380
|
+
inbox.push(text);
|
|
381
|
+
wake?.();
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
if (toldBusy)
|
|
385
|
+
return;
|
|
386
|
+
toldBusy = true;
|
|
387
|
+
void ctx.api.sendMessage(chatId, "🔐 I took that message out of the chat without passing it on: while I'm busy with the secret, "
|
|
388
|
+
+ "nothing you send goes to Claude. Send it again when I'm done.", thread).catch(() => { });
|
|
389
|
+
},
|
|
390
|
+
end: (why) => endWith(why),
|
|
391
|
+
};
|
|
392
|
+
const show = async (status, keyboard = []) => {
|
|
393
|
+
if (messageId === undefined)
|
|
394
|
+
return;
|
|
395
|
+
const message = status === undefined ? prompt : withStatus(prompt, status);
|
|
396
|
+
try {
|
|
397
|
+
await ctx.api.editMessageText(chatId, messageId, message.text, {
|
|
398
|
+
entities: message.entities,
|
|
399
|
+
reply_markup: { inline_keyboard: keyboard },
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
catch {
|
|
403
|
+
// Cosmetic: the agent's answer doesn't depend on the message.
|
|
404
|
+
}
|
|
405
|
+
};
|
|
406
|
+
const undeletedWarning = "⚠️ I couldn't delete your message, so please delete it yourself.";
|
|
407
|
+
const stopped = async (why) => {
|
|
408
|
+
accepting = false;
|
|
409
|
+
console.log(`[Secret] ${sessionKey}: the request for ${req.name} ended (${why})`);
|
|
410
|
+
// A message that was taken but not used can still be one the user meant
|
|
411
|
+
// as the secret.
|
|
412
|
+
const warning = undeleted ? `\n${undeletedWarning}` : '';
|
|
413
|
+
if (why === 'timeout') {
|
|
414
|
+
await show(`⏱️ Nothing came within ${minutes} min, so Claude carried on without it.${warning}`);
|
|
415
|
+
return {
|
|
416
|
+
success: true,
|
|
417
|
+
message: `The user didn't send ${req.name} within ${inMinutes}. Carry on without it, or ask again.`,
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
if (why === 'user') {
|
|
421
|
+
await show(`🚫 Cancelled.${warning}`);
|
|
422
|
+
return {
|
|
423
|
+
success: true,
|
|
424
|
+
message: `The user cancelled the request for ${req.name}, so you don't have it. `
|
|
425
|
+
+ "Carry on without it, or ask them how they'd like to go on.",
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
await show(`🚫 Claude stopped waiting for it.${warning}`);
|
|
429
|
+
return { success: false, message: 'The request was withdrawn before the user answered.' };
|
|
430
|
+
};
|
|
431
|
+
pending.set(sessionKey, entry);
|
|
432
|
+
const stopAwaiting = noteAwaitingUser(sessionKey);
|
|
433
|
+
const timer = setTimeout(() => endWith('timeout'), waitMs);
|
|
434
|
+
const onAbort = () => endWith('agent');
|
|
435
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
436
|
+
if (signal?.aborted)
|
|
437
|
+
endWith('agent');
|
|
438
|
+
let setup;
|
|
439
|
+
console.log(`[Secret] ${sessionKey}: asking for ${req.name} (${req.source})`);
|
|
440
|
+
try {
|
|
441
|
+
let link;
|
|
442
|
+
let setupProblem;
|
|
443
|
+
if (req.source === 'claude-setup-token') {
|
|
444
|
+
try {
|
|
445
|
+
setup = (deps.startSetupToken ?? (() => new SetupTokenRun()))();
|
|
446
|
+
const got = await race(setup.waitForLink(LINK_TIMEOUT_MS), ended);
|
|
447
|
+
if (!got.ok)
|
|
448
|
+
return await stopped(got.why);
|
|
449
|
+
link = got.value;
|
|
450
|
+
}
|
|
451
|
+
catch (err) {
|
|
452
|
+
setupProblem = err instanceof Error ? err.message : String(err);
|
|
453
|
+
console.warn(`[Secret] ${sessionKey}: claude setup-token didn't start: ${sanitizeError(err)}`);
|
|
454
|
+
setup?.kill();
|
|
455
|
+
setup = undefined;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
prompt = buildSecretPrompt(req, cwd, { link, setupProblem });
|
|
459
|
+
let sent;
|
|
460
|
+
try {
|
|
461
|
+
sent = await ctx.api.sendMessage(chatId, prompt.text, {
|
|
462
|
+
entities: prompt.entities,
|
|
463
|
+
reply_markup: { inline_keyboard: secretKeyboard(id, link) },
|
|
464
|
+
...thread,
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
catch (err) {
|
|
468
|
+
if (!link)
|
|
469
|
+
throw err;
|
|
470
|
+
// Should Telegram refuse the link as a button, the one in the text
|
|
471
|
+
// still works.
|
|
472
|
+
console.warn(`[Secret] ${sessionKey}: sending with the sign-in button failed: ${sanitizeError(err)}`);
|
|
473
|
+
sent = await ctx.api.sendMessage(chatId, prompt.text, {
|
|
474
|
+
entities: prompt.entities,
|
|
475
|
+
reply_markup: { inline_keyboard: secretKeyboard(id) },
|
|
476
|
+
...thread,
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
// Both at once: the request is on screen, so a message can be an answer
|
|
480
|
+
// to it from now on, and one that came in before the next line ran would
|
|
481
|
+
// be taken for a second paste and dropped.
|
|
482
|
+
messageId = sent.message_id;
|
|
483
|
+
accepting = true;
|
|
484
|
+
await deps.onPosted?.();
|
|
485
|
+
let secret;
|
|
486
|
+
let madeHere = false;
|
|
487
|
+
let codes = 0;
|
|
488
|
+
while (secret === undefined) {
|
|
489
|
+
const got = await race(nextText(), ended);
|
|
490
|
+
if (!got.ok)
|
|
491
|
+
return await stopped(got.why);
|
|
492
|
+
const text = got.value.trim();
|
|
493
|
+
if (!text)
|
|
494
|
+
continue;
|
|
495
|
+
if (!setup || looksLikeOAuthToken(text)) {
|
|
496
|
+
if (pattern && !pattern.test(text)) {
|
|
497
|
+
await show(`❌ That doesn't look like ${req.name}, so I deleted it without using it. Send it again, or tap Cancel.`, secretKeyboard(id, link));
|
|
498
|
+
continue;
|
|
499
|
+
}
|
|
500
|
+
secret = text;
|
|
501
|
+
break;
|
|
502
|
+
}
|
|
503
|
+
// Anything else, while claude setup-token waits, is the sign-in code.
|
|
504
|
+
accepting = false;
|
|
505
|
+
codes++;
|
|
506
|
+
await show('⏳ Checking the code…');
|
|
507
|
+
const checked = await race(setup.submitCode(text, CODE_CHECK_TIMEOUT_MS), ended);
|
|
508
|
+
if (!checked.ok)
|
|
509
|
+
return await stopped(checked.why);
|
|
510
|
+
const outcome = checked.value;
|
|
511
|
+
if (outcome.kind === 'token') {
|
|
512
|
+
secret = outcome.token;
|
|
513
|
+
madeHere = true;
|
|
514
|
+
break;
|
|
515
|
+
}
|
|
516
|
+
if (outcome.kind === 'rejected' && outcome.link && codes < MAX_CODE_ATTEMPTS) {
|
|
517
|
+
link = outcome.link;
|
|
518
|
+
prompt = buildSecretPrompt(req, cwd, { link });
|
|
519
|
+
await show(`❌ That code wasn't accepted: ${clip(outcome.reason, 300)}\n\nOpen the sign-in page again for a new code, and send me that.`, secretKeyboard(id, link));
|
|
520
|
+
accepting = true;
|
|
521
|
+
continue;
|
|
522
|
+
}
|
|
523
|
+
console.log(`[Secret] ${sessionKey}: claude setup-token gave no token for ${req.name}`);
|
|
524
|
+
await show(`❌ No token: ${clip(outcome.reason, 300)}`);
|
|
525
|
+
return {
|
|
526
|
+
success: false,
|
|
527
|
+
message: `The user tried to make ${req.name} with claude setup-token, but it gave no token: ${outcome.reason}\n\n`
|
|
528
|
+
+ 'Nothing was run. Call telecoder_request_secret again to give them another go.',
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
// The secret is in hand: from here on, nothing the user sends is one.
|
|
532
|
+
accepting = false;
|
|
533
|
+
clearTimeout(timer);
|
|
534
|
+
setup?.kill();
|
|
535
|
+
setup = undefined;
|
|
536
|
+
const secretLength = secret.length;
|
|
537
|
+
await show(madeHere
|
|
538
|
+
? '⏳ Token made. Running the command…'
|
|
539
|
+
: `⏳ Got it, ${undeleted ? 'though I could not delete your message' : 'and deleted your message'}. Running the command…`);
|
|
540
|
+
const run = await runCommand(req.command, cwd, secret);
|
|
541
|
+
secret = undefined;
|
|
542
|
+
const exit = describeExit(run);
|
|
543
|
+
const ok = !run.timedOut && run.exitCode === 0;
|
|
544
|
+
console.log(`[Secret] ${sessionKey}: ran the command for ${req.name}: ${exit}`);
|
|
545
|
+
await show(statusWithOutput(ok ? '✅ Done: the command finished OK.' : `❌ The command failed (${exit}), and the secret wasn't kept.`, run.output, undeleted ? undeletedWarning : undefined));
|
|
546
|
+
const got = madeHere
|
|
547
|
+
? `The user made ${req.name} with claude setup-token on this machine`
|
|
548
|
+
: `The user sent ${req.name} (${secretLength} characters)`;
|
|
549
|
+
const lines = [`${got}, and your command ran with it: ${exit}.`];
|
|
550
|
+
lines.push(run.output
|
|
551
|
+
? `Output, with the secret shown as ${REDACTED}:\n${tailOf(run.output, OUTPUT_FOR_AGENT)}`
|
|
552
|
+
: 'It printed nothing.');
|
|
553
|
+
if (!ok) {
|
|
554
|
+
lines.push('The secret was not kept. To try again, fix the command and call telecoder_request_secret again.');
|
|
555
|
+
}
|
|
556
|
+
if (undeleted) {
|
|
557
|
+
lines.push("TeleCoder couldn't delete the user's message with the secret in it, and has asked them to delete it.");
|
|
558
|
+
}
|
|
559
|
+
return { success: ok, message: lines.join('\n\n') };
|
|
560
|
+
}
|
|
561
|
+
catch (err) {
|
|
562
|
+
console.error(`[Secret] ${sessionKey}: the request for ${req.name} failed: ${sanitizeError(err)}`);
|
|
563
|
+
await show('❌ Something went wrong here, and nothing was run.');
|
|
564
|
+
return refuse(`Error: the secret request failed: ${sanitizeError(err)}`);
|
|
565
|
+
}
|
|
566
|
+
finally {
|
|
567
|
+
clearTimeout(timer);
|
|
568
|
+
signal?.removeEventListener('abort', onAbort);
|
|
569
|
+
setup?.kill();
|
|
570
|
+
if (pending.get(sessionKey) === entry)
|
|
571
|
+
pending.delete(sessionKey);
|
|
572
|
+
stopAwaiting();
|
|
573
|
+
await deps.onSettled?.().catch(() => { });
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
//# sourceMappingURL=secret-request.js.map
|