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.
Files changed (223) hide show
  1. package/.env.example +363 -0
  2. package/CHANGELOG.md +1186 -0
  3. package/LICENSE +22 -0
  4. package/README.md +126 -2
  5. package/dist/audio/transcribe.js +50 -0
  6. package/dist/bin/mcp-server.js +378 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +592 -0
  10. package/dist/bot/file-access.js +141 -0
  11. package/dist/bot/handlers/command/access.js +407 -0
  12. package/dist/bot/handlers/command/admin.js +827 -0
  13. package/dist/bot/handlers/command/auto-approve.js +138 -0
  14. package/dist/bot/handlers/command/btw.js +224 -0
  15. package/dist/bot/handlers/command/cost.js +409 -0
  16. package/dist/bot/handlers/command/media.js +197 -0
  17. package/dist/bot/handlers/command/model.js +305 -0
  18. package/dist/bot/handlers/command/prefs-scope.js +197 -0
  19. package/dist/bot/handlers/command/project.js +536 -0
  20. package/dist/bot/handlers/command/resume.js +321 -0
  21. package/dist/bot/handlers/command/session.js +438 -0
  22. package/dist/bot/handlers/command/settings.js +1012 -0
  23. package/dist/bot/handlers/command/shared.js +210 -0
  24. package/dist/bot/handlers/command/streaming-mode.js +16 -0
  25. package/dist/bot/handlers/command/tasks.js +513 -0
  26. package/dist/bot/handlers/command/topic-store.js +113 -0
  27. package/dist/bot/handlers/command/topic.js +80 -0
  28. package/dist/bot/handlers/command.handler.js +772 -0
  29. package/dist/bot/handlers/fork.handler.js +1109 -0
  30. package/dist/bot/handlers/media-fallback.js +121 -0
  31. package/dist/bot/handlers/message/replies.js +133 -0
  32. package/dist/bot/handlers/message/shared.js +117 -0
  33. package/dist/bot/handlers/message/throttle.js +49 -0
  34. package/dist/bot/handlers/message/turn-notify.js +169 -0
  35. package/dist/bot/handlers/message/turn-runner.js +141 -0
  36. package/dist/bot/handlers/message.handler.js +107 -0
  37. package/dist/bot/handlers/newbot.handler.js +221 -0
  38. package/dist/bot/handlers/photo.handler.js +327 -0
  39. package/dist/bot/handlers/prompts.handler.js +343 -0
  40. package/dist/bot/handlers/running-note.js +44 -0
  41. package/dist/bot/handlers/schedule.handler.js +303 -0
  42. package/dist/bot/handlers/session-guard.js +78 -0
  43. package/dist/bot/handlers/suggestion.handler.js +84 -0
  44. package/dist/bot/handlers/tree.handler.js +480 -0
  45. package/dist/bot/handlers/view.js +41 -0
  46. package/dist/bot/handlers/voice.handler.js +209 -0
  47. package/dist/bot/middleware/admin-only.js +49 -0
  48. package/dist/bot/middleware/auth.middleware.js +122 -0
  49. package/dist/bot/middleware/group-mention.middleware.js +139 -0
  50. package/dist/bot/middleware/group-role.middleware.js +75 -0
  51. package/dist/bot/middleware/message-batcher.js +87 -0
  52. package/dist/bot/middleware/queued-messages.js +971 -0
  53. package/dist/bot/middleware/stale-filter.js +31 -0
  54. package/dist/build-info.json +8 -0
  55. package/dist/claude/agent-watchdog.js +162 -0
  56. package/dist/claude/agent.js +1458 -0
  57. package/dist/claude/ask-user.js +295 -0
  58. package/dist/claude/auto-approve.js +225 -0
  59. package/dist/claude/auto-topic-haiku.js +126 -0
  60. package/dist/claude/available-commands.js +153 -0
  61. package/dist/claude/carry-over.js +27 -0
  62. package/dist/claude/ccr-shim.js +46 -0
  63. package/dist/claude/charter-judge.js +214 -0
  64. package/dist/claude/claude-auth.js +121 -0
  65. package/dist/claude/command-parser.js +200 -0
  66. package/dist/claude/cost-overlay-scraper.js +129 -0
  67. package/dist/claude/enabled-plugins.js +56 -0
  68. package/dist/claude/fork-tree.js +393 -0
  69. package/dist/claude/held-query.js +190 -0
  70. package/dist/claude/in-flight-tracker.js +61 -0
  71. package/dist/claude/ipc-server.js +192 -0
  72. package/dist/claude/mcp-bridge.js +453 -0
  73. package/dist/claude/mcp-tools.js +354 -0
  74. package/dist/claude/message-offsets.js +88 -0
  75. package/dist/claude/modal-relay.js +450 -0
  76. package/dist/claude/model-catalog.js +85 -0
  77. package/dist/claude/monitor-relay.js +597 -0
  78. package/dist/claude/pending-forks.js +93 -0
  79. package/dist/claude/pending-suggestions.js +50 -0
  80. package/dist/claude/permission-gate.js +337 -0
  81. package/dist/claude/permission-mode.js +178 -0
  82. package/dist/claude/poll-user.js +51 -0
  83. package/dist/claude/project-commands.js +69 -0
  84. package/dist/claude/prompt-hold.js +124 -0
  85. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  86. package/dist/claude/pty-provider.js +2214 -0
  87. package/dist/claude/pty-spawn-config.js +296 -0
  88. package/dist/claude/pty-stream.js +363 -0
  89. package/dist/claude/request-queue.js +135 -0
  90. package/dist/claude/scheduled-runner.js +91 -0
  91. package/dist/claude/scheduler.js +237 -0
  92. package/dist/claude/scope-guard.js +274 -0
  93. package/dist/claude/sdk-permission-gate.js +77 -0
  94. package/dist/claude/secret-request.js +576 -0
  95. package/dist/claude/session-cost.js +41 -0
  96. package/dist/claude/session-history.js +286 -0
  97. package/dist/claude/session-jsonl.js +920 -0
  98. package/dist/claude/session-manager.js +195 -0
  99. package/dist/claude/session-scan.js +270 -0
  100. package/dist/claude/setup-token.js +285 -0
  101. package/dist/claude/side-call-options.js +45 -0
  102. package/dist/claude/side-question.js +249 -0
  103. package/dist/claude/stage-images.js +62 -0
  104. package/dist/claude/subagent-tools.js +12 -0
  105. package/dist/claude/synthetic-ctx.js +51 -0
  106. package/dist/claude/system-prompt.js +162 -0
  107. package/dist/claude/tasks-overlay-scraper.js +94 -0
  108. package/dist/claude/tip-scraper.js +78 -0
  109. package/dist/claude/tui-modal.js +501 -0
  110. package/dist/claude/tui-state.js +384 -0
  111. package/dist/claude/turn-end.js +91 -0
  112. package/dist/claude/turn-prose.js +64 -0
  113. package/dist/claude/update-banner-relay.js +70 -0
  114. package/dist/cli/commands/doctor.js +305 -0
  115. package/dist/cli/commands/help.js +25 -0
  116. package/dist/cli/commands/init.js +123 -0
  117. package/dist/cli/commands/service.js +678 -0
  118. package/dist/cli/commands/start.js +53 -0
  119. package/dist/cli/commands/version.js +11 -0
  120. package/dist/cli/dispatch.js +79 -0
  121. package/dist/cli/init/env-file.js +99 -0
  122. package/dist/cli/init/flow.js +638 -0
  123. package/dist/cli/init/prompter.js +116 -0
  124. package/dist/cli/init/telegram.js +94 -0
  125. package/dist/cli/service/render.js +212 -0
  126. package/dist/cli.js +18 -0
  127. package/dist/config-report.js +107 -0
  128. package/dist/config.js +500 -0
  129. package/dist/index.js +367 -0
  130. package/dist/launcher.js +933 -0
  131. package/dist/node-version-check.js +27 -0
  132. package/dist/providers/ccr-health.js +119 -0
  133. package/dist/providers/ccr-introspect.js +149 -0
  134. package/dist/providers/ccr-provider.js +60 -0
  135. package/dist/providers/claude-provider.js +63 -0
  136. package/dist/providers/prefs-sync.js +164 -0
  137. package/dist/providers/project-favorites.js +74 -0
  138. package/dist/providers/provider-router.js +127 -0
  139. package/dist/providers/provider-switch.js +91 -0
  140. package/dist/providers/sdk-provider.js +37 -0
  141. package/dist/providers/types.js +8 -0
  142. package/dist/providers/user-preferences.js +214 -0
  143. package/dist/restart-when-idle.js +153 -0
  144. package/dist/startup/auto-continue.js +67 -0
  145. package/dist/startup/auto-resume.js +173 -0
  146. package/dist/startup/notices.js +120 -0
  147. package/dist/startup/shared.js +44 -0
  148. package/dist/startup/verify-token.js +31 -0
  149. package/dist/telegram/access-request.js +153 -0
  150. package/dist/telegram/action-logger.js +684 -0
  151. package/dist/telegram/admin-mention.js +107 -0
  152. package/dist/telegram/background-activity-card.js +502 -0
  153. package/dist/telegram/botname-settings.js +336 -0
  154. package/dist/telegram/button-text.js +26 -0
  155. package/dist/telegram/client-options.js +27 -0
  156. package/dist/telegram/deduplication.js +33 -0
  157. package/dist/telegram/entities.js +295 -0
  158. package/dist/telegram/force-reply-tracker.js +57 -0
  159. package/dist/telegram/lettered-options.js +87 -0
  160. package/dist/telegram/markdown.js +362 -0
  161. package/dist/telegram/message-sender.js +1287 -0
  162. package/dist/telegram/prompt-label.js +142 -0
  163. package/dist/telegram/prompt-suggestion.js +54 -0
  164. package/dist/telegram/send.js +123 -0
  165. package/dist/telegram/streaming-turn.js +105 -0
  166. package/dist/telegram/suggestions-settings.js +30 -0
  167. package/dist/telegram/task-list.js +367 -0
  168. package/dist/telegram/task-tracker.js +209 -0
  169. package/dist/telegram/telegraph-settings.js +31 -0
  170. package/dist/telegram/telegraph.js +453 -0
  171. package/dist/telegram/terminal-renderer.js +671 -0
  172. package/dist/telegram/terminal-settings.js +25 -0
  173. package/dist/telegram/thread-titles.js +190 -0
  174. package/dist/telegram/threads-setup.js +117 -0
  175. package/dist/tts/tts-settings.js +62 -0
  176. package/dist/tts/tts.js +245 -0
  177. package/dist/tts/voice-reply.js +78 -0
  178. package/dist/utils/admins.js +143 -0
  179. package/dist/utils/agent-timer.js +55 -0
  180. package/dist/utils/atomic-write.js +24 -0
  181. package/dist/utils/bot-token.js +74 -0
  182. package/dist/utils/bounded-map.js +55 -0
  183. package/dist/utils/build-info.js +57 -0
  184. package/dist/utils/caffeinate.js +50 -0
  185. package/dist/utils/claude-env.js +54 -0
  186. package/dist/utils/claude-version.js +48 -0
  187. package/dist/utils/config-home.js +62 -0
  188. package/dist/utils/debug-agent.js +117 -0
  189. package/dist/utils/debug-watchdog.js +121 -0
  190. package/dist/utils/download.js +111 -0
  191. package/dist/utils/exit-codes.js +48 -0
  192. package/dist/utils/file-type.js +149 -0
  193. package/dist/utils/format.js +81 -0
  194. package/dist/utils/home-project.js +30 -0
  195. package/dist/utils/host-stall.js +51 -0
  196. package/dist/utils/id-list.js +44 -0
  197. package/dist/utils/idle-restart.js +92 -0
  198. package/dist/utils/install-mode.js +63 -0
  199. package/dist/utils/instance-config.js +148 -0
  200. package/dist/utils/instances.js +95 -0
  201. package/dist/utils/json-store.js +140 -0
  202. package/dist/utils/keyed-settings.js +62 -0
  203. package/dist/utils/legacy-env.js +35 -0
  204. package/dist/utils/npm-version.js +134 -0
  205. package/dist/utils/prefs-relay.js +107 -0
  206. package/dist/utils/proc-children.js +102 -0
  207. package/dist/utils/project-data-dir.js +33 -0
  208. package/dist/utils/reasoning-summary.js +12 -0
  209. package/dist/utils/resolve-bin.js +86 -0
  210. package/dist/utils/resolve-claude-bin.js +63 -0
  211. package/dist/utils/respawn-backoff.js +19 -0
  212. package/dist/utils/sanitize.js +91 -0
  213. package/dist/utils/session-key.js +37 -0
  214. package/dist/utils/stale-launcher.js +109 -0
  215. package/dist/utils/state-dir-migration.js +92 -0
  216. package/dist/utils/systemd.js +126 -0
  217. package/dist/utils/user-roster.js +275 -0
  218. package/dist/utils/verbosity.js +118 -0
  219. package/dist/utils/version-check.js +166 -0
  220. package/dist/utils/workspace-guard.js +44 -0
  221. package/dist/worker-restart.js +141 -0
  222. package/instances.json.example +41 -0
  223. package/package.json +76 -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
@@ -0,0 +1,41 @@
1
+ /**
2
+ * What a conversation has cost, accumulated turn by turn.
3
+ *
4
+ * Claude Code cannot answer this. Its own cost counter belongs to the CLI
5
+ * process that spent the money: ask `/cost` in a live process and you get its
6
+ * running total, resume that same session in a fresh one and you get zero,
7
+ * because the session log records token counts but no pricing. So the total
8
+ * for a conversation that spans many turns — many processes, in SDK mode —
9
+ * only exists if something keeps it, and this is that something.
10
+ *
11
+ * Only SDK-mode turns feed it. They end in a result message carrying
12
+ * `total_cost_usd` for the process that just answered, which is exactly one
13
+ * turn's spend. PTY mode never sees a cost figure at all: its numbers come
14
+ * from tailing the session JSONL, which has none to give. The turn count
15
+ * travels with the total so the figure stays interpretable — a resumed
16
+ * session starts from zero here, and "$0.42 across 7 turns" says that plainly
17
+ * where a bare "$0.42" would imply the whole history.
18
+ */
19
+ import { BoundedMap } from '../utils/bounded-map.js';
20
+ const sessionCosts = new BoundedMap(1000);
21
+ /** Add one turn's cost to a session's running total, and return the total. */
22
+ export function recordTurnCost(sessionKey, turnCostUsd) {
23
+ const prior = sessionCosts.get(sessionKey);
24
+ // A turn with no cost still counts as a turn — PTY-mode zeros never reach
25
+ // here, so a zero from the SDK is a real turn that happened to be free.
26
+ const next = {
27
+ usd: (prior?.usd ?? 0) + (Number.isFinite(turnCostUsd) ? turnCostUsd : 0),
28
+ turns: (prior?.turns ?? 0) + 1,
29
+ };
30
+ sessionCosts.set(sessionKey, next);
31
+ return next;
32
+ }
33
+ /** The running total for a session, or zero when nothing has been recorded. */
34
+ export function getSessionCost(sessionKey) {
35
+ return sessionCosts.get(sessionKey) ?? { usd: 0, turns: 0 };
36
+ }
37
+ /** Forget a session's total — it starts again from zero on the next turn. */
38
+ export function clearSessionCost(sessionKey) {
39
+ sessionCosts.delete(sessionKey);
40
+ }
41
+ //# sourceMappingURL=session-cost.js.map