telecoder 1.2.0 → 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 (197) hide show
  1. package/.env.example +142 -130
  2. package/CHANGELOG.md +683 -2
  3. package/README.md +36 -32
  4. package/dist/audio/transcribe.js +0 -9
  5. package/dist/bin/mcp-server.js +46 -61
  6. package/dist/bot/bot.js +162 -181
  7. package/dist/bot/command-catalog.js +263 -0
  8. package/dist/bot/deleted-threads.js +103 -0
  9. package/dist/bot/file-access.js +35 -26
  10. package/dist/bot/handlers/album.handler.js +128 -0
  11. package/dist/bot/handlers/{fork.handler.js → branch.handler.js} +267 -280
  12. package/dist/bot/handlers/command/access.js +1 -1
  13. package/dist/bot/handlers/command/admin.js +86 -110
  14. package/dist/bot/handlers/command/all-view.js +33 -0
  15. package/dist/bot/handlers/command/auto-approve.js +3 -3
  16. package/dist/bot/handlers/command/background.js +37 -0
  17. package/dist/bot/handlers/command/botname.js +76 -0
  18. package/dist/bot/handlers/command/btw.js +20 -69
  19. package/dist/bot/handlers/command/cleanup.js +329 -0
  20. package/dist/bot/handlers/command/model.js +40 -119
  21. package/dist/bot/handlers/command/prefs-scope.js +255 -90
  22. package/dist/bot/handlers/command/project.js +31 -109
  23. package/dist/bot/handlers/command/resume.js +8 -4
  24. package/dist/bot/handlers/command/session.js +74 -213
  25. package/dist/bot/handlers/command/settings.js +92 -447
  26. package/dist/bot/handlers/command/shared.js +32 -35
  27. package/dist/bot/handlers/command/tasks.js +263 -95
  28. package/dist/bot/handlers/command/thread.js +128 -0
  29. package/dist/bot/handlers/command/topic-store.js +14 -53
  30. package/dist/bot/handlers/command/topic.js +8 -61
  31. package/dist/bot/handlers/command/{cost.js → usage.js} +32 -59
  32. package/dist/bot/handlers/command-fallback.js +179 -0
  33. package/dist/bot/handlers/command.handler.js +96 -422
  34. package/dist/bot/handlers/{schedule.handler.js → loop.handler.js} +159 -73
  35. package/dist/bot/handlers/media-fallback.js +12 -7
  36. package/dist/bot/handlers/message/replies.js +10 -87
  37. package/dist/bot/handlers/message/shared.js +9 -31
  38. package/dist/bot/handlers/message/turn-notify.js +15 -49
  39. package/dist/bot/handlers/message/turn-runner.js +18 -103
  40. package/dist/bot/handlers/message.handler.js +59 -52
  41. package/dist/bot/handlers/newbot.handler.js +13 -4
  42. package/dist/bot/handlers/photo.handler.js +88 -129
  43. package/dist/bot/handlers/prompts.handler.js +11 -11
  44. package/dist/bot/handlers/running-note.js +2 -2
  45. package/dist/bot/handlers/session-guard.js +4 -4
  46. package/dist/bot/handlers/suggestion.handler.js +2 -2
  47. package/dist/bot/handlers/tree.handler.js +20 -20
  48. package/dist/bot/handlers/voice.handler.js +23 -85
  49. package/dist/bot/kept-threads.js +51 -0
  50. package/dist/bot/middleware/album-collector.js +69 -0
  51. package/dist/bot/middleware/auth.middleware.js +1 -1
  52. package/dist/bot/middleware/group-mention.middleware.js +11 -5
  53. package/dist/bot/middleware/queued-messages.js +143 -32
  54. package/dist/bot/middleware/stale-filter.js +0 -22
  55. package/dist/build-info.json +5 -5
  56. package/dist/claude/ask-user-form.js +517 -0
  57. package/dist/claude/ask-user.js +94 -26
  58. package/dist/claude/auto-topic-haiku.js +17 -0
  59. package/dist/claude/available-commands.js +22 -19
  60. package/dist/claude/background-hint.js +91 -0
  61. package/dist/claude/{fork-tree.js → branch-tree.js} +9 -9
  62. package/dist/claude/carry-over.js +0 -2
  63. package/dist/claude/ccr-shim.js +12 -10
  64. package/dist/claude/claude-auth.js +6 -10
  65. package/dist/claude/command-parser.js +49 -43
  66. package/dist/claude/cost-overlay-scraper.js +7 -2
  67. package/dist/claude/effort-level.js +5 -0
  68. package/dist/claude/enabled-plugins.js +12 -16
  69. package/dist/claude/in-flight-tracker.js +21 -0
  70. package/dist/claude/mcp-bridge.js +86 -58
  71. package/dist/claude/memory-guard.js +400 -0
  72. package/dist/claude/message-offsets.js +5 -5
  73. package/dist/claude/modal-relay.js +401 -34
  74. package/dist/claude/model-catalog.js +20 -3
  75. package/dist/claude/monitor-relay.js +130 -15
  76. package/dist/claude/native-commands.js +40 -0
  77. package/dist/claude/{pending-forks.js → pending-branches.js} +26 -26
  78. package/dist/claude/permission-gate.js +11 -10
  79. package/dist/claude/permission-mode.js +19 -45
  80. package/dist/claude/prewarm.js +70 -0
  81. package/dist/claude/pty-idle-reaper.js +96 -0
  82. package/dist/claude/pty-provider.js +473 -188
  83. package/dist/claude/pty-spawn-config.js +79 -32
  84. package/dist/claude/pty-watch.js +201 -0
  85. package/dist/claude/request-queue.js +7 -35
  86. package/dist/claude/rewind.js +111 -0
  87. package/dist/claude/scheduled-runner.js +1 -3
  88. package/dist/claude/scheduler.js +6 -2
  89. package/dist/claude/scope-guard.js +8 -3
  90. package/dist/claude/screen-marks.js +83 -0
  91. package/dist/claude/screen-render.js +96 -0
  92. package/dist/claude/session-history.js +4 -2
  93. package/dist/claude/session-jsonl.js +162 -15
  94. package/dist/claude/session-manager.js +29 -8
  95. package/dist/claude/session-move.js +70 -0
  96. package/dist/claude/shell-mode-gate.js +60 -0
  97. package/dist/claude/side-question.js +20 -17
  98. package/dist/claude/stage-images.js +5 -5
  99. package/dist/claude/tasks-overlay-scraper.js +143 -20
  100. package/dist/claude/thread-judge-haiku.js +88 -0
  101. package/dist/claude/tip-scraper.js +3 -4
  102. package/dist/claude/tui-modal.js +272 -27
  103. package/dist/claude/tui-state.js +74 -2
  104. package/dist/claude/turn-end.js +15 -1
  105. package/dist/claude/turn-prose.js +1 -1
  106. package/dist/claude/typed-answer.js +104 -0
  107. package/dist/claude/update-banner-relay.js +1 -1
  108. package/dist/cli/commands/doctor.js +48 -15
  109. package/dist/cli/commands/help.js +11 -2
  110. package/dist/cli/commands/init.js +16 -13
  111. package/dist/cli/commands/service.js +40 -8
  112. package/dist/cli/commands/start.js +10 -0
  113. package/dist/cli/commands/watch.js +322 -0
  114. package/dist/cli/dispatch.js +5 -0
  115. package/dist/cli/init/env-file.js +1 -1
  116. package/dist/cli/init/flow.js +114 -47
  117. package/dist/cli/init/prompter.js +8 -0
  118. package/dist/cli/init/telegram.js +35 -9
  119. package/dist/cli/service/render.js +3 -3
  120. package/dist/config.js +156 -131
  121. package/dist/index.js +107 -31
  122. package/dist/launcher.js +34 -7
  123. package/dist/providers/ccr-introspect.js +1 -8
  124. package/dist/providers/ccr-provider.js +19 -20
  125. package/dist/providers/claude-provider.js +4 -57
  126. package/dist/providers/prefs-sync.js +16 -59
  127. package/dist/providers/provider-router.js +24 -23
  128. package/dist/providers/spawn-settings.js +45 -0
  129. package/dist/providers/user-preferences.js +127 -19
  130. package/dist/restart-when-idle.js +27 -7
  131. package/dist/startup/auto-continue.js +2 -2
  132. package/dist/startup/auto-resume.js +3 -15
  133. package/dist/startup/notices.js +1 -1
  134. package/dist/startup/verify-token.js +4 -4
  135. package/dist/telegram/action-logger.js +3 -165
  136. package/dist/telegram/background-activity-card.js +1 -1
  137. package/dist/telegram/botname-settings.js +71 -125
  138. package/dist/telegram/client-options.js +6 -7
  139. package/dist/telegram/force-reply-tracker.js +55 -16
  140. package/dist/telegram/message-sender.js +92 -360
  141. package/dist/telegram/prompt-label.js +11 -5
  142. package/dist/telegram/streaming-turn.js +5 -7
  143. package/dist/telegram/table-lists.js +56 -0
  144. package/dist/telegram/task-list.js +4 -4
  145. package/dist/telegram/task-tracker.js +45 -126
  146. package/dist/telegram/terminal-renderer.js +1 -5
  147. package/dist/telegram/thread-titles.js +74 -2
  148. package/dist/telegram/threads-setup.js +1 -1
  149. package/dist/utils/admins.js +2 -2
  150. package/dist/utils/bot-icon.js +248 -0
  151. package/dist/utils/bot-token.js +8 -5
  152. package/dist/utils/build-info.js +3 -3
  153. package/dist/utils/caffeinate.js +6 -3
  154. package/dist/utils/claude-env.js +0 -1
  155. package/dist/utils/claude-version.js +2 -2
  156. package/dist/utils/config-home.js +3 -3
  157. package/dist/utils/download.js +41 -15
  158. package/dist/utils/exit-codes.js +11 -0
  159. package/dist/utils/format.js +3 -6
  160. package/dist/utils/home-project.js +1 -1
  161. package/dist/utils/idle-restart.js +1 -1
  162. package/dist/utils/install-mode.js +1 -1
  163. package/dist/utils/instance-config.js +1 -1
  164. package/dist/utils/instances.js +1 -1
  165. package/dist/utils/keyed-settings.js +2 -2
  166. package/dist/utils/memory-pressure.js +60 -0
  167. package/dist/utils/npm-version.js +2 -2
  168. package/dist/utils/resolve-claude-bin.js +13 -24
  169. package/dist/utils/respawn-backoff.js +9 -0
  170. package/dist/utils/stale-launcher.js +1 -1
  171. package/dist/utils/systemd.js +8 -8
  172. package/dist/utils/telegram-proxy.js +72 -0
  173. package/dist/utils/uploads-dir.js +27 -0
  174. package/dist/utils/verbosity.js +8 -8
  175. package/dist/utils/version-check.js +5 -5
  176. package/package.json +3 -4
  177. package/dist/bot/handlers/command/media.js +0 -197
  178. package/dist/bot/handlers/command/streaming-mode.js +0 -16
  179. package/dist/bot/handlers/message/throttle.js +0 -49
  180. package/dist/claude/agent-watchdog.js +0 -162
  181. package/dist/claude/agent.js +0 -1458
  182. package/dist/claude/held-query.js +0 -190
  183. package/dist/claude/mcp-tools.js +0 -354
  184. package/dist/claude/sdk-permission-gate.js +0 -77
  185. package/dist/claude/session-cost.js +0 -41
  186. package/dist/claude/system-prompt.js +0 -162
  187. package/dist/providers/sdk-provider.js +0 -37
  188. package/dist/telegram/telegraph-settings.js +0 -31
  189. package/dist/telegram/telegraph.js +0 -453
  190. package/dist/telegram/terminal-settings.js +0 -25
  191. package/dist/tts/tts-settings.js +0 -62
  192. package/dist/tts/tts.js +0 -245
  193. package/dist/tts/voice-reply.js +0 -78
  194. package/dist/utils/debug-agent.js +0 -117
  195. package/dist/utils/debug-watchdog.js +0 -121
  196. package/dist/utils/project-data-dir.js +0 -33
  197. package/dist/utils/reasoning-summary.js +0 -12
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Typed answers to a question: Claude Code's "Type something" row.
3
+ *
4
+ * Claude Code's own question dialog ends on a row where you type an answer of
5
+ * your own instead of picking one. A Telegram keyboard has no text field, so
6
+ * here the answer is an ordinary message: while a question is open, the next
7
+ * text sent in its chat or thread answers it. A reply to a question picks that
8
+ * one, should several be open; anything else answers the one asked last. In a
9
+ * form it answers the question on screen.
10
+ *
11
+ * Before this, a message sent while a question was open waited behind the
12
+ * turn, which was itself waiting on a tap, so nothing happened until the
13
+ * question timed out.
14
+ *
15
+ * {@link captureTypedAnswers} takes the message out of the update stream ahead
16
+ * of the batcher, the queue and sequentialize, for the reason secret-request.ts
17
+ * gives: an answer waiting behind the turn that asked would never arrive.
18
+ * Commands pass, so /cancel, /steer and /later still work.
19
+ *
20
+ * telecoder_ask_user opens a question to typed answers, and so does one of
21
+ * Claude Code's own dialogs when it has a place for words: a text field, or a
22
+ * permission prompt's note (modal-relay.ts). TeleCoder's own questions (the
23
+ * permission gate, the memory guard, a held message) have fixed outcomes and
24
+ * take a tap.
25
+ */
26
+ import { clip } from '../telegram/entities.js';
27
+ import { repliedForceReplyFlow } from '../telegram/force-reply-tracker.js';
28
+ import { getSessionKeyFromCtx } from '../utils/session-key.js';
29
+ /** The line a question ends on, saying it takes a typed answer. */
30
+ export const TYPED_ANSWER_HINT = '✏️ Or reply with your own answer.';
31
+ /** Longest stretch of a typed answer written back into a question's message. */
32
+ const MAX_SHOWN_CHARS = 200;
33
+ /** Open questions, in the order they were asked. */
34
+ const takers = [];
35
+ /**
36
+ * Open a question to typed answers, once its message is posted. Returns the
37
+ * call that closes it again, which is safe to make more than once.
38
+ */
39
+ export function acceptTypedAnswers(taker) {
40
+ takers.push(taker);
41
+ return () => {
42
+ const i = takers.indexOf(taker);
43
+ if (i !== -1)
44
+ takers.splice(i, 1);
45
+ };
46
+ }
47
+ /**
48
+ * Stop taking messages as answers in this session, as /cancel does. The
49
+ * question itself closes once claude has cancelled the tool call, which takes
50
+ * a moment, and the message after /cancel must not land in it meanwhile.
51
+ */
52
+ export function stopTypedAnswers(sessionKey) {
53
+ for (let i = takers.length - 1; i >= 0; i--) {
54
+ if (takers[i].sessionKey === sessionKey)
55
+ takers.splice(i, 1);
56
+ }
57
+ }
58
+ /** Whether this message is an open question. In a group, a reply to one addresses the bot. */
59
+ export function isOpenQuestionMessage(chatId, messageId) {
60
+ return takers.some((t) => t.chatId === chatId && t.messageId === messageId);
61
+ }
62
+ /** The question a message in this session answers: the one it replies to, or else the one asked last. */
63
+ export function pickTaker(sessionKey, replyToId) {
64
+ const open = takers.filter((t) => t.sessionKey === sessionKey);
65
+ return open.find((t) => t.messageId === replyToId) ?? open.at(-1);
66
+ }
67
+ /** A typed answer as a question's message shows it: on one line, and clipped. */
68
+ export function shownTypedAnswer(text) {
69
+ return `✏️ ${clip(text.replace(/\s+/g, ' ').trim(), MAX_SHOWN_CHARS)}`;
70
+ }
71
+ /**
72
+ * Mark the message that answered a question. The question's own message
73
+ * changes too, but an edit is silent and may be scrolled out of view; the
74
+ * sender looks for the answer where they typed it.
75
+ */
76
+ export async function acknowledgeTypedAnswer(ctx) {
77
+ try {
78
+ await ctx.react('👌');
79
+ }
80
+ catch {
81
+ // Cosmetic: a group can turn reactions off, and the question still records the answer.
82
+ }
83
+ }
84
+ /**
85
+ * Hand a text message to the open question it answers, and nothing after this
86
+ * middleware sees it. Registered after the secret capture and ahead of the
87
+ * batcher, the queue and sequentialize. An answer to one of the bot's
88
+ * ForceReply prompts goes on to the flow that asked.
89
+ */
90
+ export const captureTypedAnswers = async (ctx, next) => {
91
+ const message = ctx.message;
92
+ const text = message?.text;
93
+ if (!message || text === undefined || text.startsWith('/') || repliedForceReplyFlow(ctx))
94
+ return next();
95
+ const keyInfo = getSessionKeyFromCtx(ctx);
96
+ const taker = keyInfo ? pickTaker(keyInfo.sessionKey, message.reply_to_message?.message_id) : undefined;
97
+ if (!taker || !(await taker.take(ctx, text)))
98
+ return next();
99
+ };
100
+ /** For tests: forget every open question. */
101
+ export function _resetTypedAnswersForTests() {
102
+ takers.length = 0;
103
+ }
104
+ //# sourceMappingURL=typed-answer.js.map
@@ -5,7 +5,7 @@ import { sendMarkdown } from '../telegram/send.js';
5
5
  * notice at the top of its TUI when a newer version is available (or when
6
6
  * the auto-updater just installed one): "Update available! Run: claude update"
7
7
  * or "Successfully updated to version X. Restart to apply changes." These
8
- * only show during the first render of the TUI, so in PTY mode we scrape the
8
+ * only show during the first render of the TUI, so we scrape the
9
9
  * rendered xterm screen right after _waitForReady and forward whichever
10
10
  * banner we find to Telegram.
11
11
  *
@@ -6,7 +6,7 @@
6
6
  * exits on the first invalid value) so it can report every problem at once.
7
7
  * Nothing here costs money: the Claude login is checked with
8
8
  * `claude auth status`, and the Telegram token only goes over the network
9
- * with --live (a getMe call).
9
+ * with --live (a getMe call, through the proxy the bot would use).
10
10
  */
11
11
  import { execFile } from 'child_process';
12
12
  import * as fs from 'fs';
@@ -20,6 +20,9 @@ import { parseIdList, PLACEHOLDER_USER_ID } from '../../utils/id-list.js';
20
20
  import { resolveInstances, InstancesConfigError } from '../../utils/instance-config.js';
21
21
  import { resolveBin } from '../../utils/resolve-bin.js';
22
22
  import { redactSecrets } from '../../utils/sanitize.js';
23
+ import { unreachableHint } from '../../utils/bot-token.js';
24
+ import { fetchThroughProxy, findProxy } from '../../utils/telegram-proxy.js';
25
+ import { describeFetchError } from '../init/telegram.js';
23
26
  import { MIN_NODE_MAJOR } from '../../node-version-check.js';
24
27
  import { SERVICE_MANAGER_ENV } from '../../utils/exit-codes.js';
25
28
  export { MIN_NODE_MAJOR };
@@ -79,7 +82,7 @@ export function checkLoginSurvivesService(envOnly, fileEnv, envPath) {
79
82
  if (!envOnly.length || envOnly.some((key) => fileEnv[key]?.trim()))
80
83
  return null;
81
84
  const vars = envOnly.join(' / ');
82
- return warn(`Claude Code's login comes from ${vars} in this shell's environment, not stored credentials`, `A background service (telecoder service install) won't see it, so the bot would start logged out there.`, `Add ${vars} to ${envPath} (readable by you only), or log in with "claude auth login".`);
85
+ return warn(`Claude Code's login comes from ${vars} in this shell's environment, not stored credentials`, `When TeleCoder runs as a service (telecoder service install), it starts outside your shell and doesn't have ${vars}, so Claude Code would be logged out.`, `Add ${vars} to ${envPath} (readable by you only), or log in with "claude auth login".`);
83
86
  }
84
87
  // ── Checks that look at the machine ────────────────────────────
85
88
  function exec(cmd, args, timeout = 15_000, env) {
@@ -186,21 +189,41 @@ export async function checkNodePty() {
186
189
  const fix = process.platform === 'darwin'
187
190
  ? 'Install the Xcode command line tools (xcode-select --install), then reinstall TeleCoder.'
188
191
  : 'Install a build toolchain (e.g. apt install build-essential python3), then reinstall TeleCoder.';
189
- return [fail('node-pty failed to load (the terminal mode needs it)', redactSecrets(error instanceof Error ? error.message.split('\n')[0] : String(error)), ...(missing.length ? [`Missing: ${missing.join(', ')}.`, fix] : ['A build toolchain is present; try reinstalling TeleCoder.']))];
192
+ return [fail('node-pty failed to load (Claude Code runs in it, so chats need it)', redactSecrets(error instanceof Error ? error.message.split('\n')[0] : String(error)), ...(missing.length ? [`Missing: ${missing.join(', ')}.`, fix] : ['A build toolchain is present; try reinstalling TeleCoder.']))];
190
193
  }
191
194
  }
192
- async function checkLive(token) {
195
+ /**
196
+ * Ask Telegram who the token belongs to (getMe), through `proxyUrl` when the
197
+ * bot with this token would use a proxy. `apiRoot` is for tests.
198
+ */
199
+ export async function checkLive(token, proxyUrl, apiRoot = 'https://api.telegram.org') {
200
+ // The message of a failed request can carry the URL, and the URL the token;
201
+ // a proxy URL can carry a password.
202
+ const scrub = (text) => redactSecrets(text.replaceAll(token, '<token>'));
203
+ const via = proxyUrl ? ` through the proxy ${scrub(proxyUrl)}` : '';
204
+ const unreachable = (reason) => warn(`Couldn't reach Telegram${via}`, scrub(reason), unreachableHint(proxyUrl));
205
+ let status;
206
+ let text;
193
207
  try {
194
- const res = await fetch(`https://api.telegram.org/bot${token}/getMe`, { signal: AbortSignal.timeout(10_000) });
195
- const body = await res.json();
196
- if (body.ok && body.result?.username)
197
- return ok(`Telegram knows the token: @${body.result.username}`);
198
- return fail('Telegram rejected the token', redactSecrets(body.description ?? `HTTP ${res.status}`));
208
+ const request = proxyUrl ? fetchThroughProxy(proxyUrl) : fetch;
209
+ const res = await request(`${apiRoot}/bot${token}/getMe`, { signal: AbortSignal.timeout(10_000) });
210
+ status = res.status;
211
+ text = await res.text();
199
212
  }
200
213
  catch (error) {
201
- // The message of a failed fetch can carry the URL, and the URL the token.
202
- return warn("Couldn't reach Telegram", redactSecrets(error instanceof Error ? error.message : String(error)).replaceAll(token, '<token>'));
214
+ return unreachable(describeFetchError(error));
215
+ }
216
+ let body;
217
+ try {
218
+ body = JSON.parse(text);
203
219
  }
220
+ catch {
221
+ // A proxy's own error (a 407, an error page) or a gateway in between.
222
+ return unreachable(`HTTP ${status}, not a Bot API answer`);
223
+ }
224
+ if (body.ok && body.result?.username)
225
+ return ok(`Telegram knows the token: @${body.result.username}${via ? ` (${via.trim()})` : ''}`);
226
+ return fail('Telegram rejected the token', scrub(body.description ?? `HTTP ${status}`));
204
227
  }
205
228
  // ── The command ────────────────────────────────────────────────
206
229
  const ICON = { ok: '✓', warn: '!', fail: '✗' };
@@ -234,6 +257,7 @@ export async function runChecks(args) {
234
257
  }
235
258
  // The environment wins over the file, as it does in the bot.
236
259
  const value = (key) => process.env[key] ?? fileEnv[key];
260
+ /** Each token to check with --live, and the proxy its bot would reach Telegram through. */
237
261
  const tokens = [];
238
262
  if (fs.existsSync(instancesPath)) {
239
263
  try {
@@ -246,8 +270,9 @@ export async function runChecks(args) {
246
270
  const r = checkToken(inst.token, instancesPath);
247
271
  if (r.status !== 'ok')
248
272
  results.push({ ...r, label: `${inst.name}: ${r.label}` });
273
+ // An instance's overrides are its environment, over the launcher's own.
249
274
  else
250
- tokens.push(inst.token);
275
+ tokens.push({ token: inst.token, proxyUrl: findProxy((key) => inst.overrides?.[key] ?? value(key))?.url });
251
276
  }
252
277
  const users = instances.map((i) => i.overrides?.ALLOWED_USER_IDS ?? value('ALLOWED_USER_IDS'));
253
278
  for (const r of new Set(users))
@@ -264,7 +289,7 @@ export async function runChecks(args) {
264
289
  const r = checkToken(token, envPath);
265
290
  results.push(r);
266
291
  if (r.status === 'ok' && token)
267
- tokens.push(token);
292
+ tokens.push({ token, proxyUrl: findProxy(value)?.url });
268
293
  results.push(checkAllowedUsers(value('ALLOWED_USER_IDS')));
269
294
  }
270
295
  const claudeBin = value('CLAUDE_EXECUTABLE_PATH') || 'claude';
@@ -280,11 +305,19 @@ export async function runChecks(args) {
280
305
  }
281
306
  results.push(...await checkNodePty());
282
307
  if (live) {
283
- for (const token of tokens)
284
- results.push(await checkLive(token));
308
+ for (const { token, proxyUrl } of tokens)
309
+ results.push(await checkLive(token, proxyUrl));
285
310
  }
286
311
  return results;
287
312
  }
313
+ export function usage() {
314
+ return [
315
+ 'Usage: telecoder doctor [--live]',
316
+ '',
317
+ 'Checks Node, the claude CLI and its login, node-pty and your config. Writes nothing.',
318
+ ' --live also check each bot token with Telegram (through the proxy, when one is set)',
319
+ ];
320
+ }
288
321
  export async function run(args, io) {
289
322
  const results = await runChecks(args);
290
323
  for (const r of results)
@@ -18,8 +18,17 @@ export function helpText(only) {
18
18
  'next to package.json in a source checkout. Docs: https://telecoder.dev',
19
19
  ].join('\n');
20
20
  }
21
- export async function run(args, io) {
22
- io.out(helpText(args[0]));
21
+ export async function run(args, io, commands = COMMANDS) {
22
+ const only = args[0];
23
+ // About one command: its own usage, with every option, when it has one.
24
+ if (only && Object.hasOwn(commands, only)) {
25
+ const mod = await commands[only].load();
26
+ if (mod.usage) {
27
+ io.out([commands[only].summary, '', ...mod.usage()].join('\n'));
28
+ return 0;
29
+ }
30
+ }
31
+ io.out(helpText(only));
23
32
  return 0;
24
33
  }
25
34
  //# sourceMappingURL=help.js.map
@@ -12,7 +12,7 @@ import { isCheckout, detectPackageRunner } from '../../utils/install-mode.js';
12
12
  import { legacyEnv } from '../../utils/legacy-env.js';
13
13
  import { checkClaude, checkNodePty, checkNodeVersion, envOnlyLogin } from './doctor.js';
14
14
  import { runInit } from '../init/flow.js';
15
- import { runServiceInstall } from './service.js';
15
+ import { planServiceInstall, runServiceInstall } from './service.js';
16
16
  import { createTerminalPrompter } from '../init/prompter.js';
17
17
  import { createTelegramClient, DEFAULT_API_ROOT } from '../init/telegram.js';
18
18
  const USAGE = [
@@ -23,13 +23,20 @@ const USAGE = [
23
23
  ' (never pass the token itself: arguments show up in ps)',
24
24
  ' --owner-id ID your numeric Telegram user id',
25
25
  ' --workspace DIR the folder your projects are in (default: ~/projects or ~)',
26
- ' --transport sdk|pty how Claude Code runs (default: sdk)',
27
26
  ' --groq-key-env VAR turn voice transcription on, with the Groq key in VAR',
28
- ' --telegraph publish long replies to Telegraph (public pages)',
27
+ ' --icon give the bot the TeleCoder icon as its profile picture,',
28
+ ' replacing one it has (default: only when it has none)',
29
+ ' --no-icon leave the bot\'s picture alone',
29
30
  ' --no-test-message don\'t have the bot message you at the end',
30
31
  ' --yes ask nothing: take defaults, replace an existing .env',
31
32
  ' (backed up first), remove a webhook if one is set',
33
+ '',
34
+ 'Where Telegram is blocked, set TELEGRAM_PROXY_URL (or HTTPS_PROXY) to an HTTP or',
35
+ 'HTTPS proxy first. The wizard goes through it and writes it to the .env.',
32
36
  ];
37
+ export function usage() {
38
+ return USAGE;
39
+ }
33
40
  export function parseInitArgs(args) {
34
41
  const opts = {};
35
42
  const valued = {
@@ -37,20 +44,15 @@ export function parseInitArgs(args) {
37
44
  '--owner-id': (v) => { opts.ownerId = v; },
38
45
  '--workspace': (v) => { opts.workspace = v; },
39
46
  '--groq-key-env': (v) => { opts.groqKeyEnv = v; },
40
- '--transport': (v) => {
41
- if (v !== 'sdk' && v !== 'pty')
42
- return '--transport takes sdk or pty.';
43
- opts.transport = v;
44
- },
45
47
  };
46
48
  for (let i = 0; i < args.length; i++) {
47
49
  const [flag, inline] = args[i].includes('=') ? args[i].split(/=(.*)/s, 2) : [args[i], undefined];
48
50
  if (flag === '--yes' || flag === '-y')
49
51
  opts.yes = true;
50
- else if (flag === '--telegraph')
51
- opts.telegraph = true;
52
- else if (flag === '--no-telegraph')
53
- opts.telegraph = false;
52
+ else if (flag === '--icon')
53
+ opts.icon = true;
54
+ else if (flag === '--no-icon')
55
+ opts.icon = false;
54
56
  else if (flag === '--no-test-message')
55
57
  opts.noTestMessage = true;
56
58
  else if (flag === '--token' || flag === '--groq-key') {
@@ -88,7 +90,7 @@ export async function run(args, io) {
88
90
  try {
89
91
  code = await runInit(parsed.opts, {
90
92
  prompter,
91
- makeClient: (token) => createTelegramClient(token, { apiRoot }),
93
+ makeClient: (token, proxyUrl) => createTelegramClient(token, { apiRoot, proxyUrl }),
92
94
  preflight: async () => {
93
95
  const claude = await checkClaude(claudeBin);
94
96
  return {
@@ -109,6 +111,7 @@ export async function run(args, io) {
109
111
  // Not from npx: its cache can be cleared under the unit, and the installer
110
112
  // refuses it anyway.
111
113
  requestService: detectPackageRunner() === 'npx' ? undefined : () => { serviceRequested = true; },
114
+ planService: () => planServiceInstall(),
112
115
  });
113
116
  }
114
117
  finally {
@@ -3,10 +3,10 @@
3
3
  * in the background under the machine's own service manager: a systemd user
4
4
  * unit on Linux, a LaunchAgent on macOS.
5
5
  *
6
- * An npm install has no botctl script: /restartbot exits (RESTART_EXIT_CODE)
7
- * and counts on whatever started the bot to start it again. The unit written
8
- * here does — Restart=always, KeepAlive — and stands down on the config-error
9
- * code instead (see ../service/render.ts and utils/exit-codes.ts).
6
+ * /botrestart exits (RESTART_EXIT_CODE) and counts on whatever started the
7
+ * bot to start it again. The unit written here does — Restart=always,
8
+ * KeepAlive — and stands down on the config-error code instead (see
9
+ * ../service/render.ts and utils/exit-codes.ts).
10
10
  *
11
11
  * Everything that touches the machine — files, systemctl, the prompt — comes
12
12
  * in through ServiceDeps, so the flows are tested with fakes; the unit text
@@ -179,8 +179,8 @@ export function resolveServiceSpec(deps, options) {
179
179
  ok: false,
180
180
  lines: [
181
181
  `This is a source checkout (${deps.packageRoot}).`,
182
- 'A checkout is usually run with pm2 through scripts/telecoder-botctl.sh, or with',
183
- '"npm start" — /restartbot and /rebuildbot already know how to work with those.',
182
+ 'A checkout is usually run under pm2 ("pm2 start npm -- start"), which',
183
+ '/botrestart and /botrebuild already know how to work with.',
184
184
  '',
185
185
  "To run it as a service instead, pointing at this checkout's dist/:",
186
186
  ' node dist/cli.js service install --from-checkout',
@@ -225,7 +225,7 @@ export function resolveServiceSpec(deps, options) {
225
225
  const warnings = [];
226
226
  const nodePath = chooseNodePath(deps);
227
227
  const required = [path.dirname(nodePath)];
228
- for (const tool of ['claude', 'git', 'ffmpeg']) {
228
+ for (const tool of ['claude', 'git']) {
229
229
  const found = which(deps, tool);
230
230
  if (found)
231
231
  required.push(path.dirname(found));
@@ -310,6 +310,38 @@ export async function systemdUnavailableReason(deps) {
310
310
  return null;
311
311
  }
312
312
  const firstLine = (text) => text.trim().split('\n')[0] ?? '';
313
+ export async function planServiceInstall(givenDeps = realDeps()) {
314
+ const { deps } = withUserBus(givenDeps);
315
+ if (deps.platform === 'darwin') {
316
+ return { manager: 'launchd', ready: true, lines: ['a LaunchAgent (launchd), loaded now and whenever you log in.'] };
317
+ }
318
+ if (deps.platform !== 'linux') {
319
+ return {
320
+ manager: null,
321
+ ready: false,
322
+ lines: [
323
+ `telecoder service supports Linux (systemd) and macOS (launchd), not ${deps.platform}.`,
324
+ 'Run "telecoder start" under any supervisor that starts it again when it exits.',
325
+ ],
326
+ };
327
+ }
328
+ const unavailable = await systemdUnavailableReason(deps);
329
+ if (unavailable) {
330
+ return {
331
+ manager: 'systemd',
332
+ ready: false,
333
+ lines: [
334
+ `a systemd user service, but ${unavailable.reason}.`,
335
+ 'Run "telecoder service install" for how to fix that, and other ways to keep the bot running.',
336
+ ],
337
+ };
338
+ }
339
+ const lines = ['a systemd user service (systemctl --user), started now and at boot.'];
340
+ lines.push(await lingerEnabled(deps)
341
+ ? 'Lingering is on, so it keeps running after you log out.'
342
+ : `It will ask to enable lingering for ${deps.username}, so it keeps running after you log out.`);
343
+ return { manager: 'systemd', ready: true, lines };
344
+ }
313
345
  /** How to get the user's systemd manager running without a login, first in the fallback. */
314
346
  async function userManagerFix(deps, name) {
315
347
  const user = deps.username;
@@ -466,7 +498,7 @@ function printNextSteps(io, name) {
466
498
  io.out('');
467
499
  io.out(` telecoder service status${flag} is it running?`);
468
500
  io.out(` telecoder service logs${flag} follow its output`);
469
- io.out(` telecoder service restart${flag} restart it (/restartbot from chat works too)`);
501
+ io.out(` telecoder service restart${flag} restart it (/botrestart from chat works too)`);
470
502
  io.out(` telecoder service uninstall${flag} stop and remove it`);
471
503
  }
472
504
  // ── launchd ─────────────────────────────────────────────────────
@@ -22,6 +22,16 @@ export function chooseStartTarget({ args, instancesExists }) {
22
22
  return 'multi';
23
23
  return instancesExists ? 'multi' : 'single';
24
24
  }
25
+ export function usage() {
26
+ return [
27
+ 'Usage: telecoder start [--single|--multi] [--config <file>]',
28
+ '',
29
+ 'Runs in the foreground until Ctrl+C. With an instances.json it runs every bot in it.',
30
+ ' --single just the bot in .env, even when instances.json exists',
31
+ ' --multi the multi-bot launcher',
32
+ ' --config <file> the launcher, with another instances file',
33
+ ];
34
+ }
25
35
  /** The lines to print when there is no config to start from. */
26
36
  export function missingConfigMessage(envPath) {
27
37
  return [