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.
Files changed (235) hide show
  1. package/.env.example +375 -0
  2. package/CHANGELOG.md +1867 -0
  3. package/LICENSE +22 -0
  4. package/README.md +130 -2
  5. package/dist/audio/transcribe.js +41 -0
  6. package/dist/bin/mcp-server.js +363 -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 +573 -0
  10. package/dist/bot/command-catalog.js +263 -0
  11. package/dist/bot/deleted-threads.js +103 -0
  12. package/dist/bot/file-access.js +150 -0
  13. package/dist/bot/handlers/album.handler.js +128 -0
  14. package/dist/bot/handlers/branch.handler.js +1096 -0
  15. package/dist/bot/handlers/command/access.js +407 -0
  16. package/dist/bot/handlers/command/admin.js +803 -0
  17. package/dist/bot/handlers/command/all-view.js +33 -0
  18. package/dist/bot/handlers/command/auto-approve.js +138 -0
  19. package/dist/bot/handlers/command/background.js +37 -0
  20. package/dist/bot/handlers/command/botname.js +76 -0
  21. package/dist/bot/handlers/command/btw.js +175 -0
  22. package/dist/bot/handlers/command/cleanup.js +329 -0
  23. package/dist/bot/handlers/command/model.js +226 -0
  24. package/dist/bot/handlers/command/prefs-scope.js +362 -0
  25. package/dist/bot/handlers/command/project.js +458 -0
  26. package/dist/bot/handlers/command/resume.js +325 -0
  27. package/dist/bot/handlers/command/session.js +299 -0
  28. package/dist/bot/handlers/command/settings.js +657 -0
  29. package/dist/bot/handlers/command/shared.js +207 -0
  30. package/dist/bot/handlers/command/tasks.js +681 -0
  31. package/dist/bot/handlers/command/thread.js +128 -0
  32. package/dist/bot/handlers/command/topic-store.js +74 -0
  33. package/dist/bot/handlers/command/topic.js +27 -0
  34. package/dist/bot/handlers/command/usage.js +382 -0
  35. package/dist/bot/handlers/command-fallback.js +179 -0
  36. package/dist/bot/handlers/command.handler.js +446 -0
  37. package/dist/bot/handlers/loop.handler.js +389 -0
  38. package/dist/bot/handlers/media-fallback.js +126 -0
  39. package/dist/bot/handlers/message/replies.js +56 -0
  40. package/dist/bot/handlers/message/shared.js +95 -0
  41. package/dist/bot/handlers/message/turn-notify.js +135 -0
  42. package/dist/bot/handlers/message/turn-runner.js +56 -0
  43. package/dist/bot/handlers/message.handler.js +114 -0
  44. package/dist/bot/handlers/newbot.handler.js +230 -0
  45. package/dist/bot/handlers/photo.handler.js +286 -0
  46. package/dist/bot/handlers/prompts.handler.js +343 -0
  47. package/dist/bot/handlers/running-note.js +44 -0
  48. package/dist/bot/handlers/session-guard.js +78 -0
  49. package/dist/bot/handlers/suggestion.handler.js +84 -0
  50. package/dist/bot/handlers/tree.handler.js +480 -0
  51. package/dist/bot/handlers/view.js +41 -0
  52. package/dist/bot/handlers/voice.handler.js +147 -0
  53. package/dist/bot/kept-threads.js +51 -0
  54. package/dist/bot/middleware/admin-only.js +49 -0
  55. package/dist/bot/middleware/album-collector.js +69 -0
  56. package/dist/bot/middleware/auth.middleware.js +122 -0
  57. package/dist/bot/middleware/group-mention.middleware.js +145 -0
  58. package/dist/bot/middleware/group-role.middleware.js +75 -0
  59. package/dist/bot/middleware/message-batcher.js +87 -0
  60. package/dist/bot/middleware/queued-messages.js +1082 -0
  61. package/dist/bot/middleware/stale-filter.js +9 -0
  62. package/dist/build-info.json +8 -0
  63. package/dist/claude/ask-user-form.js +517 -0
  64. package/dist/claude/ask-user.js +363 -0
  65. package/dist/claude/auto-approve.js +225 -0
  66. package/dist/claude/auto-topic-haiku.js +143 -0
  67. package/dist/claude/available-commands.js +156 -0
  68. package/dist/claude/background-hint.js +91 -0
  69. package/dist/claude/branch-tree.js +393 -0
  70. package/dist/claude/carry-over.js +25 -0
  71. package/dist/claude/ccr-shim.js +48 -0
  72. package/dist/claude/charter-judge.js +214 -0
  73. package/dist/claude/claude-auth.js +117 -0
  74. package/dist/claude/command-parser.js +206 -0
  75. package/dist/claude/cost-overlay-scraper.js +134 -0
  76. package/dist/claude/effort-level.js +5 -0
  77. package/dist/claude/enabled-plugins.js +52 -0
  78. package/dist/claude/in-flight-tracker.js +82 -0
  79. package/dist/claude/ipc-server.js +192 -0
  80. package/dist/claude/mcp-bridge.js +481 -0
  81. package/dist/claude/memory-guard.js +400 -0
  82. package/dist/claude/message-offsets.js +88 -0
  83. package/dist/claude/modal-relay.js +817 -0
  84. package/dist/claude/model-catalog.js +102 -0
  85. package/dist/claude/monitor-relay.js +712 -0
  86. package/dist/claude/native-commands.js +40 -0
  87. package/dist/claude/pending-branches.js +93 -0
  88. package/dist/claude/pending-suggestions.js +50 -0
  89. package/dist/claude/permission-gate.js +338 -0
  90. package/dist/claude/permission-mode.js +152 -0
  91. package/dist/claude/poll-user.js +51 -0
  92. package/dist/claude/prewarm.js +70 -0
  93. package/dist/claude/project-commands.js +69 -0
  94. package/dist/claude/prompt-hold.js +124 -0
  95. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  96. package/dist/claude/pty-idle-reaper.js +96 -0
  97. package/dist/claude/pty-provider.js +2499 -0
  98. package/dist/claude/pty-spawn-config.js +343 -0
  99. package/dist/claude/pty-stream.js +363 -0
  100. package/dist/claude/pty-watch.js +201 -0
  101. package/dist/claude/request-queue.js +107 -0
  102. package/dist/claude/rewind.js +111 -0
  103. package/dist/claude/scheduled-runner.js +89 -0
  104. package/dist/claude/scheduler.js +241 -0
  105. package/dist/claude/scope-guard.js +279 -0
  106. package/dist/claude/screen-marks.js +83 -0
  107. package/dist/claude/screen-render.js +96 -0
  108. package/dist/claude/secret-request.js +576 -0
  109. package/dist/claude/session-history.js +288 -0
  110. package/dist/claude/session-jsonl.js +1067 -0
  111. package/dist/claude/session-manager.js +216 -0
  112. package/dist/claude/session-move.js +70 -0
  113. package/dist/claude/session-scan.js +270 -0
  114. package/dist/claude/setup-token.js +285 -0
  115. package/dist/claude/shell-mode-gate.js +60 -0
  116. package/dist/claude/side-call-options.js +45 -0
  117. package/dist/claude/side-question.js +252 -0
  118. package/dist/claude/stage-images.js +62 -0
  119. package/dist/claude/subagent-tools.js +12 -0
  120. package/dist/claude/synthetic-ctx.js +51 -0
  121. package/dist/claude/tasks-overlay-scraper.js +217 -0
  122. package/dist/claude/thread-judge-haiku.js +88 -0
  123. package/dist/claude/tip-scraper.js +77 -0
  124. package/dist/claude/tui-modal.js +746 -0
  125. package/dist/claude/tui-state.js +456 -0
  126. package/dist/claude/turn-end.js +105 -0
  127. package/dist/claude/turn-prose.js +64 -0
  128. package/dist/claude/typed-answer.js +104 -0
  129. package/dist/claude/update-banner-relay.js +70 -0
  130. package/dist/cli/commands/doctor.js +338 -0
  131. package/dist/cli/commands/help.js +34 -0
  132. package/dist/cli/commands/init.js +126 -0
  133. package/dist/cli/commands/service.js +710 -0
  134. package/dist/cli/commands/start.js +63 -0
  135. package/dist/cli/commands/version.js +11 -0
  136. package/dist/cli/commands/watch.js +322 -0
  137. package/dist/cli/dispatch.js +84 -0
  138. package/dist/cli/init/env-file.js +99 -0
  139. package/dist/cli/init/flow.js +705 -0
  140. package/dist/cli/init/prompter.js +124 -0
  141. package/dist/cli/init/telegram.js +120 -0
  142. package/dist/cli/service/render.js +212 -0
  143. package/dist/cli.js +18 -0
  144. package/dist/config-report.js +107 -0
  145. package/dist/config.js +525 -0
  146. package/dist/index.js +443 -0
  147. package/dist/launcher.js +960 -0
  148. package/dist/node-version-check.js +27 -0
  149. package/dist/providers/ccr-health.js +119 -0
  150. package/dist/providers/ccr-introspect.js +142 -0
  151. package/dist/providers/ccr-provider.js +59 -0
  152. package/dist/providers/claude-provider.js +10 -0
  153. package/dist/providers/prefs-sync.js +121 -0
  154. package/dist/providers/project-favorites.js +74 -0
  155. package/dist/providers/provider-router.js +128 -0
  156. package/dist/providers/provider-switch.js +91 -0
  157. package/dist/providers/spawn-settings.js +45 -0
  158. package/dist/providers/types.js +8 -0
  159. package/dist/providers/user-preferences.js +322 -0
  160. package/dist/restart-when-idle.js +173 -0
  161. package/dist/startup/auto-continue.js +67 -0
  162. package/dist/startup/auto-resume.js +161 -0
  163. package/dist/startup/notices.js +120 -0
  164. package/dist/startup/shared.js +44 -0
  165. package/dist/startup/verify-token.js +31 -0
  166. package/dist/telegram/access-request.js +153 -0
  167. package/dist/telegram/action-logger.js +522 -0
  168. package/dist/telegram/admin-mention.js +107 -0
  169. package/dist/telegram/background-activity-card.js +502 -0
  170. package/dist/telegram/botname-settings.js +282 -0
  171. package/dist/telegram/button-text.js +26 -0
  172. package/dist/telegram/client-options.js +26 -0
  173. package/dist/telegram/deduplication.js +33 -0
  174. package/dist/telegram/entities.js +295 -0
  175. package/dist/telegram/force-reply-tracker.js +96 -0
  176. package/dist/telegram/lettered-options.js +87 -0
  177. package/dist/telegram/markdown.js +362 -0
  178. package/dist/telegram/message-sender.js +1019 -0
  179. package/dist/telegram/prompt-label.js +148 -0
  180. package/dist/telegram/prompt-suggestion.js +54 -0
  181. package/dist/telegram/send.js +123 -0
  182. package/dist/telegram/streaming-turn.js +103 -0
  183. package/dist/telegram/suggestions-settings.js +30 -0
  184. package/dist/telegram/table-lists.js +56 -0
  185. package/dist/telegram/task-list.js +367 -0
  186. package/dist/telegram/task-tracker.js +128 -0
  187. package/dist/telegram/terminal-renderer.js +667 -0
  188. package/dist/telegram/thread-titles.js +262 -0
  189. package/dist/telegram/threads-setup.js +117 -0
  190. package/dist/utils/admins.js +143 -0
  191. package/dist/utils/agent-timer.js +55 -0
  192. package/dist/utils/atomic-write.js +24 -0
  193. package/dist/utils/bot-icon.js +248 -0
  194. package/dist/utils/bot-token.js +77 -0
  195. package/dist/utils/bounded-map.js +55 -0
  196. package/dist/utils/build-info.js +57 -0
  197. package/dist/utils/caffeinate.js +53 -0
  198. package/dist/utils/claude-env.js +53 -0
  199. package/dist/utils/claude-version.js +48 -0
  200. package/dist/utils/config-home.js +62 -0
  201. package/dist/utils/download.js +137 -0
  202. package/dist/utils/exit-codes.js +59 -0
  203. package/dist/utils/file-type.js +149 -0
  204. package/dist/utils/format.js +78 -0
  205. package/dist/utils/home-project.js +30 -0
  206. package/dist/utils/host-stall.js +51 -0
  207. package/dist/utils/id-list.js +44 -0
  208. package/dist/utils/idle-restart.js +92 -0
  209. package/dist/utils/install-mode.js +63 -0
  210. package/dist/utils/instance-config.js +148 -0
  211. package/dist/utils/instances.js +95 -0
  212. package/dist/utils/json-store.js +140 -0
  213. package/dist/utils/keyed-settings.js +62 -0
  214. package/dist/utils/legacy-env.js +35 -0
  215. package/dist/utils/memory-pressure.js +60 -0
  216. package/dist/utils/npm-version.js +134 -0
  217. package/dist/utils/prefs-relay.js +107 -0
  218. package/dist/utils/proc-children.js +102 -0
  219. package/dist/utils/resolve-bin.js +86 -0
  220. package/dist/utils/resolve-claude-bin.js +52 -0
  221. package/dist/utils/respawn-backoff.js +28 -0
  222. package/dist/utils/sanitize.js +91 -0
  223. package/dist/utils/session-key.js +37 -0
  224. package/dist/utils/stale-launcher.js +109 -0
  225. package/dist/utils/state-dir-migration.js +92 -0
  226. package/dist/utils/systemd.js +126 -0
  227. package/dist/utils/telegram-proxy.js +72 -0
  228. package/dist/utils/uploads-dir.js +27 -0
  229. package/dist/utils/user-roster.js +275 -0
  230. package/dist/utils/verbosity.js +118 -0
  231. package/dist/utils/version-check.js +166 -0
  232. package/dist/utils/workspace-guard.js +44 -0
  233. package/dist/worker-restart.js +141 -0
  234. package/instances.json.example +41 -0
  235. package/package.json +75 -4
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Drives `claude setup-token` in a pty of its own, for telecoder_request_secret.
3
+ *
4
+ * `claude setup-token` makes a long-lived (one-year) OAuth token for a Claude
5
+ * subscription, for a machine or an agent to run on without anyone's own
6
+ * login. It signs in through a browser, and on a machine with no browser of
7
+ * its own it prints a sign-in link and waits at a prompt for the code the
8
+ * sign-in page shows. Measured on 2.1.319:
9
+ *
10
+ * Browser didn't open? Use the url below to sign in (c to copy)
11
+ *
12
+ * https://claude.com/cai/oauth/authorize?code=true&client_id=…
13
+ *
14
+ * Paste code here if prompted >
15
+ *
16
+ * The link is drawn as an OSC 8 hyperlink, so the whole URL comes through in
17
+ * the escape sequence however the terminal wraps the text. A code it doesn't
18
+ * accept ends in `OAuth error: That code wasn't accepted. …` and `Press Enter
19
+ * to retry.`, and Enter starts over with a fresh link. A good one prints the
20
+ * token, by itself on a row, between "Your OAuth token (valid for 1 year):" and
21
+ * "Store this token securely".
22
+ *
23
+ * Nothing here relays what the pty draws. The token is handed back to the
24
+ * caller and nowhere else, and the one bit of screen text that does go out — a
25
+ * reason a code was refused, or why the run ended — goes through
26
+ * {@link redactTokens} first.
27
+ *
28
+ * The terminal is 500 columns wide so the token never wraps, which keeps it
29
+ * whole on a single row for {@link findOAuthToken}. The sign-in link (about
30
+ * 420 characters) fits too, which lets the screen stand in for the escape
31
+ * sequence if a later version stops sending one.
32
+ */
33
+ import { spawn } from 'node-pty';
34
+ import headless from '@xterm/headless';
35
+ import * as os from 'os';
36
+ import { envWithoutParentSession } from '../utils/claude-env.js';
37
+ import { resolveBin } from '../utils/resolve-bin.js';
38
+ const { Terminal } = headless;
39
+ const COLS = 500;
40
+ const ROWS = 50;
41
+ /** How long the screen has to stay still before it's read. */
42
+ const SETTLE_MS = 150;
43
+ /** Raw output kept for finding the sign-in link. The newest link is at the end. */
44
+ const MAX_RAW = 1024 * 1024;
45
+ /** Between typing a code and pressing Enter, as a person would. */
46
+ const TYPE_TO_ENTER_MS = 300;
47
+ /** OSC 8: ESC ] 8 ; params ; URI, ended by BEL or ESC \. */
48
+ const OSC8_LINK = /\x1b\]8;[^;\x07\x1b]*;([^\x07\x1b]*)(?:\x07|\x1b\\)/g;
49
+ const AUTHORIZE_PATH = '/oauth/authorize';
50
+ const SCREEN_LINK = /https:\/\/\S+\/oauth\/authorize\?\S+/g;
51
+ /** A Claude OAuth token, as `claude setup-token` prints it. */
52
+ const OAUTH_TOKEN = /sk-ant-oat\d+-[A-Za-z0-9_-]{20,}/;
53
+ const OAUTH_TOKEN_EXACT = /^sk-ant-oat\d+-[A-Za-z0-9_-]{20,}$/;
54
+ const OAUTH_ERROR = /OAuth error:\s*(.+)/;
55
+ const ANY_ANTHROPIC_KEY = /sk-ant-[A-Za-z0-9_-]+/g;
56
+ /**
57
+ * Variables that would point claude at other credentials or another endpoint.
58
+ * The bot's environment can carry any of them for its own sessions; a token
59
+ * made for the user's subscription should come out of the same flow it would
60
+ * in a plain terminal.
61
+ */
62
+ const AUTH_VARS = ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL', 'CLAUDE_CODE_OAUTH_TOKEN'];
63
+ /** The newest sign-in link in the raw pty output, from its OSC 8 sequence. */
64
+ export function findSignInLink(raw) {
65
+ let found;
66
+ for (const match of raw.matchAll(OSC8_LINK)) {
67
+ if (match[1].includes(AUTHORIZE_PATH))
68
+ found = match[1];
69
+ }
70
+ return found;
71
+ }
72
+ /** The last sign-in link written out on the screen, for a version without OSC 8. */
73
+ export function findSignInLinkOnScreen(screen) {
74
+ const matches = screen.match(SCREEN_LINK);
75
+ return matches ? matches[matches.length - 1] : undefined;
76
+ }
77
+ export function findOAuthToken(screen) {
78
+ return OAUTH_TOKEN.exec(screen)?.[0];
79
+ }
80
+ /** Why a code was refused, from the `OAuth error:` line. */
81
+ export function findOAuthError(screen) {
82
+ return OAUTH_ERROR.exec(screen)?.[1].trim() || undefined;
83
+ }
84
+ /** True when `text` is a Claude OAuth token itself, not a sign-in code. */
85
+ export function looksLikeOAuthToken(text) {
86
+ return OAUTH_TOKEN_EXACT.test(text.trim());
87
+ }
88
+ /** Blank out anything shaped like an Anthropic key or token. */
89
+ export function redactTokens(text) {
90
+ return text.replace(ANY_ANTHROPIC_KEY, 'sk-ant-…');
91
+ }
92
+ /**
93
+ * The last few rows of the screen that say something, to explain how a run
94
+ * ended. The welcome logo is block art and dots, so a row needs a word in it
95
+ * to count.
96
+ */
97
+ export function describeScreen(screen, maxLines = 4) {
98
+ const lines = screen
99
+ .split('\n')
100
+ .map((line) => line.trim())
101
+ .filter((line) => /[A-Za-z]{3}/.test(line));
102
+ return redactTokens(lines.slice(-maxLines).join('\n'));
103
+ }
104
+ function defaultBin() {
105
+ return process.env.CLAUDE_BIN || resolveBin('claude');
106
+ }
107
+ /** The environment `claude setup-token` runs in. */
108
+ export function setupTokenEnv(base = process.env) {
109
+ const env = envWithoutParentSession(base);
110
+ for (const name of AUTH_VARS)
111
+ delete env[name];
112
+ return {
113
+ ...env,
114
+ TERM: 'xterm-256color',
115
+ // The bot's own ptys pin claude's classic renderer for the same reason:
116
+ // the fullscreen one draws on the alternate screen, and a launch can
117
+ // switch to it without being asked.
118
+ CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN: '1',
119
+ };
120
+ }
121
+ /** One run of `claude setup-token`, from the sign-in link to the token. */
122
+ export class SetupTokenRun {
123
+ term;
124
+ xterm;
125
+ raw = '';
126
+ exit;
127
+ settleTimer;
128
+ watchers = new Set();
129
+ closed = false;
130
+ constructor(options = {}) {
131
+ this.term = spawn(options.bin ?? defaultBin(), options.args ?? ['setup-token'], {
132
+ name: 'xterm-256color',
133
+ cols: COLS,
134
+ rows: ROWS,
135
+ cwd: os.homedir(),
136
+ env: options.env ?? setupTokenEnv(),
137
+ });
138
+ this.xterm = new Terminal({ cols: COLS, rows: ROWS, scrollback: 200, allowProposedApi: true });
139
+ this.term.onData((data) => {
140
+ if (this.closed)
141
+ return;
142
+ this.raw = (this.raw + data).slice(-MAX_RAW);
143
+ this.xterm.write(data, () => this.scheduleSettle());
144
+ });
145
+ this.term.onExit((exit) => {
146
+ this.exit = exit;
147
+ // Let the last frame land before anyone reads the screen for a reason.
148
+ setTimeout(() => this.notify(), SETTLE_MS);
149
+ });
150
+ }
151
+ scheduleSettle() {
152
+ if (this.settleTimer)
153
+ clearTimeout(this.settleTimer);
154
+ this.settleTimer = setTimeout(() => this.notify(), SETTLE_MS);
155
+ }
156
+ notify() {
157
+ for (const watcher of [...this.watchers])
158
+ watcher();
159
+ }
160
+ /** Everything on the terminal, scrollback included, one row per line. */
161
+ screen() {
162
+ const buffer = this.xterm.buffer.active;
163
+ const lines = [];
164
+ for (let i = 0; i < buffer.length; i++) {
165
+ lines.push(buffer.getLine(i)?.translateToString(true) ?? '');
166
+ }
167
+ return lines.join('\n');
168
+ }
169
+ /** Keystrokes for the run, unless it's already over. */
170
+ type(keys) {
171
+ if (this.closed || this.exit)
172
+ return;
173
+ try {
174
+ this.term.write(keys);
175
+ }
176
+ catch {
177
+ // The run is ending; whatever waits on it next says so.
178
+ }
179
+ }
180
+ currentLink() {
181
+ return findSignInLink(this.raw) ?? findSignInLinkOnScreen(this.screen());
182
+ }
183
+ ending() {
184
+ const said = describeScreen(this.screen());
185
+ const how = this.exit?.signal ? `was stopped (signal ${this.exit.signal})` : `exited with code ${this.exit?.exitCode}`;
186
+ return said ? `claude setup-token ${how}: ${said}` : `claude setup-token ${how}`;
187
+ }
188
+ /**
189
+ * Resolve with the first thing `probe` finds, checked now and each time the
190
+ * screen settles. Rejects when the run ends or `timeoutMs` passes first.
191
+ */
192
+ waitFor(probe, timeoutMs, what) {
193
+ return new Promise((resolve, reject) => {
194
+ const finish = () => {
195
+ clearTimeout(timer);
196
+ this.watchers.delete(check);
197
+ };
198
+ const check = () => {
199
+ const value = probe();
200
+ if (value !== undefined) {
201
+ finish();
202
+ resolve(value);
203
+ }
204
+ else if (this.exit || this.closed) {
205
+ finish();
206
+ reject(new Error(this.closed ? 'stopped' : this.ending()));
207
+ }
208
+ };
209
+ const timer = setTimeout(() => {
210
+ finish();
211
+ reject(new Error(`claude setup-token showed no ${what} within ${Math.round(timeoutMs / 1000)}s`));
212
+ }, timeoutMs);
213
+ this.watchers.add(check);
214
+ check();
215
+ });
216
+ }
217
+ /** The sign-in link to send the user to. */
218
+ waitForLink(timeoutMs = 30_000) {
219
+ return this.waitFor(() => this.currentLink(), timeoutMs, 'sign-in link');
220
+ }
221
+ /**
222
+ * Type the code the sign-in page gave the user, and see what it gets. A
223
+ * refused code is answered with Enter, which starts over with a new link,
224
+ * so the user can sign in again without another run.
225
+ */
226
+ async submitCode(code, timeoutMs = 60_000) {
227
+ if (this.exit || this.closed)
228
+ return { kind: 'failed', reason: this.closed ? 'stopped' : this.ending() };
229
+ const before = this.currentLink();
230
+ // Control characters would be keystrokes, not part of the code.
231
+ this.type(code.replace(/[\x00-\x1f\x7f]/g, ''));
232
+ await new Promise((resolve) => setTimeout(resolve, TYPE_TO_ENTER_MS));
233
+ if (this.closed)
234
+ return { kind: 'failed', reason: 'stopped' };
235
+ this.type('\r');
236
+ let refused;
237
+ try {
238
+ const answer = await this.waitFor(() => {
239
+ const screen = this.screen();
240
+ const token = findOAuthToken(screen);
241
+ if (token)
242
+ return { token };
243
+ const error = findOAuthError(screen);
244
+ return error ? { error } : undefined;
245
+ }, timeoutMs, 'token');
246
+ if ('token' in answer)
247
+ return { kind: 'token', token: answer.token };
248
+ refused = redactTokens(answer.error);
249
+ }
250
+ catch (err) {
251
+ return { kind: 'failed', reason: err instanceof Error ? err.message : String(err) };
252
+ }
253
+ this.type('\r');
254
+ try {
255
+ const link = await this.waitFor(() => {
256
+ const current = this.currentLink();
257
+ return current && current !== before ? current : undefined;
258
+ }, 30_000, 'new sign-in link');
259
+ return { kind: 'rejected', reason: refused, link };
260
+ }
261
+ catch {
262
+ return { kind: 'rejected', reason: refused };
263
+ }
264
+ }
265
+ /** End the run. Safe to call more than once. */
266
+ kill() {
267
+ if (this.closed)
268
+ return;
269
+ this.closed = true;
270
+ if (this.settleTimer)
271
+ clearTimeout(this.settleTimer);
272
+ this.notify();
273
+ this.watchers.clear();
274
+ if (!this.exit) {
275
+ try {
276
+ this.term.kill();
277
+ }
278
+ catch {
279
+ // Already gone.
280
+ }
281
+ }
282
+ this.xterm.dispose();
283
+ }
284
+ }
285
+ //# sourceMappingURL=setup-token.js.map
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The permission gate for Claude Code's shell mode.
3
+ *
4
+ * A prompt whose first character is `!` never reaches the model. Claude Code
5
+ * runs the rest of it as a shell command, and because that is not a tool call
6
+ * it raises no PreToolUse hook: measured on 2.1.326, a pasted `!echo x > f`
7
+ * wrote the file and the only hook that fired was Stop. The gate and the scope
8
+ * guard live in that hook, so neither saw a command someone typed themselves.
9
+ * On a shared bot a guest's `!sudo …` ran where Claude's own `sudo` would have
10
+ * waited for an admin.
11
+ *
12
+ * So such a message is put to the gate here, as the Bash call it amounts to,
13
+ * before it is typed into the pty. Everything else is the gate's: off on a
14
+ * solo bot, the same patterns and paths, the same people to answer, the same
15
+ * auto-approve window. An admin's `!` is checked as an admin's turn is.
16
+ */
17
+ import { gateToolCall } from './permission-gate.js';
18
+ /** What the approval prompt names as the tool: the command was typed, not Claude's. */
19
+ export const SHELL_MODE_LABEL = '! shell mode';
20
+ /**
21
+ * The command a prompt runs in shell mode, or undefined for an ordinary prompt.
22
+ *
23
+ * Measured against the same CLI: only a `!` in the very first position
24
+ * switches the editor to shell mode (` !echo x` stayed a prompt), and a
25
+ * multi-line message runs whole as one script, also when it is long enough to
26
+ * be collapsed into a `[Pasted text]` chip. So everything after the `!` is the
27
+ * command.
28
+ */
29
+ export function shellModeCommand(prompt) {
30
+ if (!prompt.startsWith('!'))
31
+ return undefined;
32
+ const command = prompt.slice(1).trim();
33
+ return command === '' ? undefined : command;
34
+ }
35
+ /**
36
+ * Put a `!command` to the permission gate before it runs. Anything else, and
37
+ * everything while the gate is off, proceeds untouched.
38
+ */
39
+ export async function screenShellCommand(ctx, sessionKey, prompt) {
40
+ const command = shellModeCommand(prompt);
41
+ if (command === undefined)
42
+ return { proceed: true, message: '', approved: false };
43
+ const decision = await gateToolCall({
44
+ sessionKey,
45
+ toolName: 'Bash',
46
+ toolInput: { command },
47
+ telegramCtx: ctx,
48
+ toolLabel: SHELL_MODE_LABEL,
49
+ });
50
+ if (decision.block) {
51
+ console.log(`[ShellModeGate] blocked session:${sessionKey} user:${ctx?.from?.id ?? '?'}`);
52
+ return {
53
+ proceed: false,
54
+ message: `🔐 ${decision.reason.replace(/\.$/, '')}. Nothing ran.`,
55
+ approved: false,
56
+ };
57
+ }
58
+ return { proceed: true, message: '', approved: decision.approvedByPerson === true };
59
+ }
60
+ //# sourceMappingURL=shell-mode-gate.js.map
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Options for a one-shot Haiku side-call: the topic summarizer, the charter
3
+ * judge.
4
+ *
5
+ * `settingSources: []` keeps out plugins, MCP and hooks, but not the rest of
6
+ * what a `claude` process picks up from where it runs. Started in the bot's
7
+ * own folder, Haiku also read the default system prompt with that folder's
8
+ * git status, and the auto-memory kept for it. That's TeleCoder's, whatever
9
+ * project the message was about: a thread about launching SJS got named
10
+ * "TeleCoder launch" after the launch plan in TeleCoder's memory.
11
+ *
12
+ * So the call runs in an empty folder, with its own system prompt in place of
13
+ * the default one and auto-memory off. All it knows is what it's handed.
14
+ */
15
+ import * as fs from 'fs';
16
+ import * as os from 'os';
17
+ import * as path from 'path';
18
+ import { config } from '../config.js';
19
+ import { resolveBundledClaudeBin } from '../utils/resolve-claude-bin.js';
20
+ export const HAIKU_MODEL = 'claude-haiku-4-5-20251001';
21
+ const EMPTY_CWD = path.join(os.tmpdir(), 'telecoder-side-call');
22
+ function executableOption() {
23
+ if (!config.CLAUDE_USE_BUNDLED_EXECUTABLE) {
24
+ return { pathToClaudeCodeExecutable: config.CLAUDE_EXECUTABLE_PATH };
25
+ }
26
+ const bundled = resolveBundledClaudeBin();
27
+ return bundled ? { pathToClaudeCodeExecutable: bundled } : {};
28
+ }
29
+ export function sideCallOptions(systemPrompt, abortController) {
30
+ fs.mkdirSync(EMPTY_CWD, { recursive: true });
31
+ return {
32
+ model: HAIKU_MODEL,
33
+ systemPrompt,
34
+ cwd: EMPTY_CWD,
35
+ env: { ...process.env, CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' },
36
+ settingSources: [],
37
+ allowedTools: [],
38
+ // A throwaway one-shot: saving it would leave a session file per message.
39
+ persistSession: false,
40
+ abortController,
41
+ includePartialMessages: false,
42
+ ...executableOption(),
43
+ };
44
+ }
45
+ //# sourceMappingURL=side-call-options.js.map
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Side questions for `/btw`.
3
+ *
4
+ * The conversation lives inside a real `claude` CLI process driven through a
5
+ * pseudo-terminal, and typing into it mid-turn would just queue a normal
6
+ * prompt (i.e. interrupt the task, which is exactly what `/btw` promises not
7
+ * to do).
8
+ *
9
+ * Instead we answer from a throwaway fork of the live session:
10
+ *
11
+ * claude -p "<question>" --resume <id> --fork-session --no-session-persistence
12
+ * --output-format stream-json --verbose
13
+ *
14
+ * `--resume` replays the session JSONL, which claude flushes after every
15
+ * assistant message and tool call — so the fork sees the conversation right up
16
+ * to whatever the live turn has produced so far. `--fork-session` gives it a
17
+ * fresh session id and `--no-session-persistence` keeps it entirely off disk,
18
+ * so the live session's transcript is never touched.
19
+ *
20
+ * `stream-json` makes the fork narrate its own tool calls on stdout, which is
21
+ * how `/btw` shows live progress. Nothing of the bot's is needed for that — no
22
+ * hooks, no MCP server, no IPC — because we already own the child process.
23
+ */
24
+ import { execFile } from 'child_process';
25
+ import { resolvePtyClaudeBin } from '../utils/resolve-claude-bin.js';
26
+ import { userSetupIsolationArgs } from './pty-spawn-config.js';
27
+ import { sessionJsonlPath } from './session-jsonl.js';
28
+ import * as fs from 'fs';
29
+ /** Same shape claude uses for session ids; also guards the execFile argv. */
30
+ const SESSION_ID_RE = /^[a-zA-Z0-9_-]{8,128}$/;
31
+ const DEFAULT_TIMEOUT_MS = 180_000;
32
+ const MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
33
+ /**
34
+ * Tools the fork must not touch. A side question is a read; it should never
35
+ * edit the working tree out from under the turn that's actually running.
36
+ */
37
+ const DISALLOWED_TOOLS = ['Write', 'Edit', 'NotebookEdit'];
38
+ const SIDE_QUESTION_PROMPT = [
39
+ 'You are answering a SIDE QUESTION about the conversation you just resumed.',
40
+ 'A separate agent is still working on the main task in this session — you are a read-only fork.',
41
+ 'Do not modify files, do not run state-changing commands, and do not start work.',
42
+ 'Answer the question directly and concisely using the conversation context.',
43
+ ].join(' ');
44
+ export class SideQuestionError extends Error {
45
+ }
46
+ /** True if the CLI rejected one of our flags rather than failing the query. */
47
+ function isUnknownOptionError(message) {
48
+ return /unknown option|unknown argument|unrecognized option/i.test(message);
49
+ }
50
+ /** Turn one parsed result record into the value we hand back. */
51
+ function resultRecordToAnswer(parsed) {
52
+ const result = typeof parsed.result === 'string' ? parsed.result.trim() : '';
53
+ if (parsed.is_error === true) {
54
+ throw new SideQuestionError(result || String(parsed.error ?? 'claude reported an error'));
55
+ }
56
+ return {
57
+ response: result,
58
+ forkSessionId: typeof parsed.session_id === 'string' ? parsed.session_id : undefined,
59
+ };
60
+ }
61
+ /**
62
+ * Pull the answer out of claude's stdout. Handles both output formats:
63
+ * `stream-json` (newline-delimited records, the last one being the result) and
64
+ * the single-object `json` we fall back to on older CLIs. Anything that isn't
65
+ * recognisable JSON is handed back verbatim rather than swallowed.
66
+ */
67
+ export function extractAnswer(stdout) {
68
+ const trimmed = stdout.trim();
69
+ if (!trimmed.startsWith('{')) {
70
+ return { response: trimmed };
71
+ }
72
+ // stream-json: scan for the final `result` record. Deliberately tolerant —
73
+ // interleaved non-JSON noise is skipped rather than failing the whole parse.
74
+ let lastResult;
75
+ let sawRecord = false;
76
+ for (const line of trimmed.split('\n')) {
77
+ const candidate = line.trim();
78
+ if (!candidate.startsWith('{'))
79
+ continue;
80
+ let parsed;
81
+ try {
82
+ parsed = JSON.parse(candidate);
83
+ }
84
+ catch {
85
+ continue;
86
+ }
87
+ sawRecord = true;
88
+ // stream-json tags every record with `type`; the single-object `json`
89
+ // format has none, so a typeless record carrying any result field is the
90
+ // legacy shape. Requiring one of those fields keeps stray objects in a
91
+ // stream from being mistaken for the answer.
92
+ const isLegacyBlob = parsed.type === undefined
93
+ && ('result' in parsed || 'is_error' in parsed || 'error' in parsed);
94
+ if (parsed.type === 'result' || isLegacyBlob) {
95
+ lastResult = resultRecordToAnswer(parsed);
96
+ }
97
+ }
98
+ if (lastResult)
99
+ return lastResult;
100
+ // No result record — a stream cut short, or output we don't recognise.
101
+ // Hand back what claude printed rather than losing it.
102
+ if (sawRecord)
103
+ console.warn('[btw] stream ended with no result record');
104
+ return { response: trimmed };
105
+ }
106
+ /**
107
+ * Best-effort one-line description of what a tool call is doing, for the
108
+ * progress line. Mirrors the field precedence pty-provider uses when it
109
+ * describes async tool calls.
110
+ */
111
+ function toolHint(input) {
112
+ for (const key of ['command', 'file_path', 'pattern', 'path', 'url', 'description', 'prompt']) {
113
+ const value = input[key];
114
+ if (typeof value === 'string' && value.trim())
115
+ return value.trim();
116
+ }
117
+ return undefined;
118
+ }
119
+ /**
120
+ * Feed one `stream-json` record to the progress callback. Only two record
121
+ * shapes matter: an assistant message carrying a `tool_use` block (a tool
122
+ * started) and a user message carrying `tool_result` (it finished). Thinking,
123
+ * rate-limit and system records are noise here.
124
+ */
125
+ function consumeStreamRecord(record, state, onProgress) {
126
+ const message = record.message;
127
+ const blocks = Array.isArray(message?.content) ? message.content : [];
128
+ let changed = false;
129
+ for (const block of blocks) {
130
+ if (record.type === 'assistant' && block.type === 'tool_use') {
131
+ state.toolCount += 1;
132
+ state.currentTool = typeof block.name === 'string' ? block.name : 'tool';
133
+ state.currentHint = toolHint((block.input ?? {}));
134
+ changed = true;
135
+ }
136
+ else if (record.type === 'user' && block.type === 'tool_result') {
137
+ // Tool finished; keep the name on screen but drop the "running" detail.
138
+ state.currentHint = undefined;
139
+ changed = true;
140
+ }
141
+ }
142
+ if (changed) {
143
+ onProgress({
144
+ toolCount: state.toolCount,
145
+ currentTool: state.currentTool,
146
+ currentHint: state.currentHint,
147
+ elapsedMs: Date.now() - state.startedAt,
148
+ });
149
+ }
150
+ }
151
+ function runClaude(executable, args, cwd, timeoutMs, onProgress) {
152
+ return new Promise((resolve, reject) => {
153
+ const child = execFile(executable, args, { cwd, timeout: timeoutMs, maxBuffer: MAX_OUTPUT_BYTES, env: process.env }, (error, stdout, stderr) => {
154
+ if (error) {
155
+ const message = (stderr || error.message).trim();
156
+ reject(new SideQuestionError(message || 'Failed to run claude'));
157
+ return;
158
+ }
159
+ resolve(stdout || '');
160
+ });
161
+ if (!onProgress)
162
+ return;
163
+ // Watch the same stdout execFile is buffering for us, so we can report
164
+ // tool calls as they happen without changing how the result is read.
165
+ const state = { toolCount: 0, startedAt: Date.now() };
166
+ let pending = '';
167
+ child.stdout?.on('data', (chunk) => {
168
+ pending += chunk.toString();
169
+ const lines = pending.split('\n');
170
+ pending = lines.pop() ?? ''; // keep the partial line for the next chunk
171
+ for (const line of lines) {
172
+ const candidate = line.trim();
173
+ if (!candidate.startsWith('{'))
174
+ continue;
175
+ try {
176
+ consumeStreamRecord(JSON.parse(candidate), state, onProgress);
177
+ }
178
+ catch {
179
+ // Malformed or unrecognised record — progress is best-effort.
180
+ }
181
+ }
182
+ });
183
+ });
184
+ }
185
+ /**
186
+ * Answer `question` from a read-only fork of the PTY session `sessionId`.
187
+ * Throws {@link SideQuestionError} with a user-presentable message on failure.
188
+ */
189
+ export async function askForkedSideQuestion(opts) {
190
+ const { question, sessionId, cwd, onProgress } = opts;
191
+ const executable = opts.executable ?? resolvePtyClaudeBin();
192
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
193
+ const startedAt = Date.now();
194
+ if (!SESSION_ID_RE.test(sessionId)) {
195
+ throw new SideQuestionError('Invalid session ID format');
196
+ }
197
+ if (!fs.existsSync(sessionJsonlPath(cwd, sessionId))) {
198
+ throw new SideQuestionError('No transcript on disk for this session yet — send a message first.');
199
+ }
200
+ const baseArgs = [
201
+ '-p', question,
202
+ '--resume', sessionId,
203
+ '--fork-session',
204
+ // The account's own Claude Code setup, or not, as the pty it forks from
205
+ // has it: the same instructions, default model and plugins, and the
206
+ // servers those plugins' hooks send claude to. Never the bot's own MCP
207
+ // server, which no flag here names — the fork must not be able to message
208
+ // Telegram.
209
+ ...userSetupIsolationArgs(),
210
+ // The fork inherits the live session's bypassed permissions so tool calls
211
+ // resolve instead of hanging on approval; the disallow list below is what
212
+ // actually keeps it read-only.
213
+ '--dangerously-skip-permissions',
214
+ '--disallowed-tools', ...DISALLOWED_TOOLS,
215
+ '--append-system-prompt', SIDE_QUESTION_PROMPT,
216
+ ];
217
+ // stream-json reports every tool call as it happens, which is what drives the
218
+ // live progress line. `--verbose` is required alongside it in print mode.
219
+ const streamArgs = [...baseArgs, '--output-format', 'stream-json', '--verbose', '--no-session-persistence'];
220
+ // Fallback for CLIs that don't know one of the flags above: one JSON blob at
221
+ // the end, no progress. `--fork-session` alone still protects the live
222
+ // transcript, it just leaves a stray log behind for us to delete.
223
+ const fallbackArgs = [...baseArgs, '--output-format', 'json'];
224
+ // Remember the last progress tick so the caller can render a receipt
225
+ // ("3 tools · 22s") without tracking it itself.
226
+ let toolCount = 0;
227
+ const trackProgress = (p) => {
228
+ toolCount = p.toolCount;
229
+ onProgress?.(p);
230
+ };
231
+ let result;
232
+ try {
233
+ result = extractAnswer(await runClaude(executable, streamArgs, cwd, timeoutMs, trackProgress));
234
+ }
235
+ catch (error) {
236
+ const message = error instanceof Error ? error.message : String(error);
237
+ if (!isUnknownOptionError(message))
238
+ throw error;
239
+ console.warn('[btw] CLI rejected the streaming flags — retrying without progress');
240
+ result = extractAnswer(await runClaude(executable, fallbackArgs, cwd, timeoutMs));
241
+ if (result.forkSessionId && result.forkSessionId !== sessionId) {
242
+ try {
243
+ fs.rmSync(sessionJsonlPath(cwd, result.forkSessionId), { force: true });
244
+ }
245
+ catch {
246
+ // Leftover fork log is harmless — it's never resumed by the bot.
247
+ }
248
+ }
249
+ }
250
+ return { ...result, toolCount, elapsedMs: Date.now() - startedAt };
251
+ }
252
+ //# sourceMappingURL=side-question.js.map