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
package/dist/index.js ADDED
@@ -0,0 +1,443 @@
1
+ /**
2
+ * Process entry point.
3
+ *
4
+ * Everything here is bootstrap: environment fixups that must land before any
5
+ * provider spawns, then `main()` — build the bot, run the startup routines in
6
+ * order, arm the background services, and hold the process open until the
7
+ * runner stops.
8
+ *
9
+ * The startup routines themselves live in `./startup/`, and the worker-to-
10
+ * launcher restart requests in `./worker-restart.ts`, re-exported below
11
+ * because they were part of this module's public surface.
12
+ */
13
+ // First, so an old Node.js is told so before any other module loads.
14
+ import './node-version-check.js';
15
+ import { run } from '@grammyjs/runner';
16
+ import { isMainThread, parentPort } from 'worker_threads';
17
+ import { createBot } from './bot/bot.js';
18
+ import { resumeThreadsSetup } from './telegram/threads-setup.js';
19
+ import { armReminders } from './bot/middleware/queued-messages.js';
20
+ import { config, BOT_ID, RENAMED_SETTINGS } from './config.js';
21
+ import { preventSleep, allowSleep } from './utils/caffeinate.js';
22
+ import { stopCleanup } from './telegram/deduplication.js';
23
+ import { sessionHistory } from './claude/session-history.js';
24
+ import { listAdmitted } from './utils/user-roster.js';
25
+ import { findOrphanedApprovers, getApproverIds } from './utils/admins.js';
26
+ import { startScheduledRunner } from './claude/scheduled-runner.js';
27
+ import { setMonitorRelayBot } from './claude/monitor-relay.js';
28
+ import { getPtyProvider } from './providers/claude-provider.js';
29
+ import { setUpdateBannerRelayBot } from './claude/update-banner-relay.js';
30
+ import { startPendingBranchWatcher } from './bot/handlers/branch.handler.js';
31
+ import { initPrefsSync } from './providers/prefs-sync.js';
32
+ import { initRestartWhenIdle } from './restart-when-idle.js';
33
+ import { stripParentClaudeSession } from './utils/claude-env.js';
34
+ import { syncBotNameOnStartup } from './telegram/botname-settings.js';
35
+ import { autoResumeAfterReload } from './startup/auto-resume.js';
36
+ import { autoContinueOnStartup } from './startup/auto-continue.js';
37
+ import { notifyInterruptedSessions, notifyRestartComplete } from './startup/notices.js';
38
+ import { tickWasStalled } from './utils/host-stall.js';
39
+ import { EXIT_TELEGRAM_UNAVAILABLE } from './utils/exit-codes.js';
40
+ import { describeRunningBuild } from './utils/build-info.js';
41
+ import { migrateLegacyStateDirAndLog } from './utils/state-dir-migration.js';
42
+ import { verifyBotTokenOrExit } from './startup/verify-token.js';
43
+ import { warnIfClaudeNotLoggedIn } from './claude/claude-auth.js';
44
+ import { loadsUserSetup } from './claude/pty-spawn-config.js';
45
+ import { redactSecrets, sanitizeError } from './utils/sanitize.js';
46
+ import { startWatchServer, stopWatchServer } from './claude/pty-watch.js';
47
+ export { requestRestart, requestSiblingRestart, requestRestartAll } from './worker-restart.js';
48
+ // When running as a worker thread (multi-instance mode), prefix all console
49
+ // output with the instance name so logs from different bots are distinguishable.
50
+ const instanceName = process.env.TELECODER_INSTANCE_NAME;
51
+ if (instanceName) {
52
+ const prefix = `[${instanceName}]`;
53
+ const origLog = console.log.bind(console);
54
+ const origError = console.error.bind(console);
55
+ const origWarn = console.warn.bind(console);
56
+ console.log = (...args) => origLog(prefix, ...args);
57
+ console.error = (...args) => origError(prefix, ...args);
58
+ console.warn = (...args) => origWarn(prefix, ...args);
59
+ }
60
+ // Drop any Claude Code session markers we inherited before a provider spawns
61
+ // anything. Restarting the bot from inside a claude session (which is how it
62
+ // happens here — the bot's own session runs `pm2 start`) otherwise leaves every
63
+ // claude we spawn believing it's a nested session, with transcript persistence
64
+ // off and no session log for us to read replies from. See utils/claude-env.ts.
65
+ const strippedClaudeVars = stripParentClaudeSession();
66
+ if (strippedClaudeVars.length > 0) {
67
+ console.warn(`[Env] Bot was launched from inside a Claude Code session; dropped inherited markers so spawned sessions persist normally: ${strippedClaudeVars.join(', ')}`);
68
+ }
69
+ // Settings of features that are gone. A .env that still sets one gets one
70
+ // line saying so, rather than behaviour that silently stopped. Only a value
71
+ // that asked for something — not the old default — earns the line.
72
+ const isOn = (v) => /^(true|1|yes)$/i.test(v);
73
+ const REMOVED_SETTINGS = [
74
+ { name: 'TELEGRAPH_ENABLED', stale: isOn, note: 'Telegraph pages were removed: long replies arrive in full in the chat.' },
75
+ { name: 'STREAMING_MODE', stale: (v) => v === 'wait', note: 'the wait mode was removed: replies always stream.' },
76
+ { name: 'DANGEROUS_MODE', stale: isOn, note: 'it was removed: /mode sets how much Claude asks before acting.' },
77
+ { name: 'MAX_LOOP_ITERATIONS', stale: (v) => v !== '5', note: '/loop was removed: Claude Code works until a task is done, and its own /loop skill reaches it now.' },
78
+ { name: 'BOT_MODE', stale: () => true, note: 'it was removed with the botctl script: the bot runs under pm2, systemd or launchd.' },
79
+ { name: 'TERMINAL_UI_DEFAULT', stale: (v) => !isOn(v), note: '/terminalui was removed: every turn has the live status message, and /verbosity sets how much it shows.' },
80
+ { name: 'CLAUDE_METHOD_DEFAULT', stale: () => true, note: 'the SDK transport was removed: every chat runs Claude Code in a pty.' },
81
+ { name: 'CLAUDE_SDK_LOG_LEVEL', stale: () => true, note: 'the SDK transport was removed: every chat runs Claude Code in a pty.' },
82
+ { name: 'CLAUDE_SDK_LOAD_USER_SETTINGS', stale: () => true, note: 'the SDK transport was removed: the pty brings your own Claude Code setup along unless the bot has guests (CLAUDE_USER_SETUP).' },
83
+ { name: 'TTS_ENABLED', stale: isOn, note: 'voice replies (/tts) were removed: Claude Code answers in text.' },
84
+ ...['TTS_PROVIDER', 'TTS_MODEL', 'TTS_VOICE', 'TTS_INSTRUCTIONS', 'TTS_SPEED', 'TTS_MAX_CHARS', 'TTS_RESPONSE_FORMAT', 'OPENAI_API_KEY']
85
+ .map((name) => ({ name, stale: () => true, note: 'voice replies (/tts) were removed: Claude Code answers in text.' })),
86
+ { name: 'TRANSCRIBE_FILE_THRESHOLD_CHARS', stale: () => true, note: '/transcribe was removed: voice notes still become prompts.' },
87
+ { name: 'CCR_AUTO_PROMPT_ON_THROTTLE', stale: () => true, note: 'the one-tap CCR retry went with the SDK transport: /ccr switches a throttled chat over.' },
88
+ ...['AGENT_WATCHDOG_ENABLED', 'AGENT_WATCHDOG_WARN_SECONDS', 'AGENT_WATCHDOG_LOG_SECONDS', 'AGENT_QUERY_TIMEOUT_MS', 'AGENT_SILENCE_TIMEOUT_MS', 'AGENT_STALE_TOOL_TIMEOUT_MS']
89
+ .map((name) => ({ name, stale: () => true, note: 'the SDK transport\'s watchdog went with it: CLAUDE_PTY_HARD_TIMEOUT_MS caps a turn in the pty.' })),
90
+ { name: 'CLAUDE_REASONING_SUMMARY', stale: () => true, note: 'the summary was something the SDK transport asked for in its own prompt; Claude Code in the pty writes none.' },
91
+ // .env.example set this one uncommented, so only a changed value was asked for.
92
+ { name: 'CANCEL_ON_NEW_MESSAGE', stale: isOn, note: 'it was removed: a new message waits for the turn, as in Claude Code, and /steer or ⚡ Interrupt & send replaces the turn with one.' },
93
+ { name: 'STREAMING_DEBOUNCE_MS', stale: (v) => v !== '500', note: 'nothing has read it since February: the live reply paces its own edits.' },
94
+ ];
95
+ for (const { name, stale, note } of REMOVED_SETTINGS) {
96
+ const value = process.env[name];
97
+ if (value !== undefined && value !== '' && stale(value)) {
98
+ console.warn(`[Env] ${name} is set, but ${note} The setting can go from .env.`);
99
+ }
100
+ }
101
+ // Settings that took a new name still work under the old one; say so once.
102
+ for (const [old, now] of Object.entries(RENAMED_SETTINGS)) {
103
+ if (!process.env[old])
104
+ continue;
105
+ const ignored = process.env[now] ? `, and ${now} is set too, so ${old} is ignored` : '';
106
+ console.warn(`[Env] ${old} is now called ${now}${ignored}. Rename it in .env.`);
107
+ }
108
+ // Log unhandled rejections — prevents silent failures where the process stays
109
+ // alive but functionality is broken (e.g. fire-and-forget async calls that fail).
110
+ process.on('unhandledRejection', (reason) => {
111
+ console.error('[FATAL] Unhandled promise rejection:', reason);
112
+ });
113
+ // How long a graceful shutdown may take before we exit regardless.
114
+ const SHUTDOWN_TIMEOUT_MS = 5_000;
115
+ async function main() {
116
+ console.log('🤖 Starting TeleCoder...');
117
+ // As a worker thread: the heartbeat and the exit listener come first, before
118
+ // anything awaited. The launcher restarts a worker that's silent for 90s,
119
+ // and startup can take longer than that: during a Telegram outage every
120
+ // awaited call below waits out autoRetry's 5xx backoff, 3+6+12+24+48s. Sent
121
+ // only from the end of startup, the heartbeat made a slow start look like a
122
+ // wedged thread, and with no listener yet the restart could only terminate()
123
+ // it, so a bot crash-looped through every outage. The heartbeat only says
124
+ // the event loop runs, which is all the launcher checks; whether Telegram
125
+ // answers is the getMe heartbeat's job further down.
126
+ //
127
+ // 'exit_for_restart' is the launcher answering a restart request: we exit
128
+ // ourselves rather than waiting to be terminated. A worker.terminate() only
129
+ // lands when the thread next runs JS, so a worker blocked in native code
130
+ // would never die, and never be respawned. Until the full shutdown is wired
131
+ // up below, an exit request ends the claudes started so far and exits.
132
+ let onExitRequest = () => {
133
+ const exit = () => process.exit(typeof process.exitCode === 'number' ? process.exitCode : 0);
134
+ setTimeout(exit, SHUTDOWN_TIMEOUT_MS).unref();
135
+ getPtyProvider().closeAll().then(exit, exit);
136
+ };
137
+ if (!isMainThread && parentPort) {
138
+ const pp = parentPort;
139
+ pp.on('message', (msg) => {
140
+ if (msg?.type === 'shutdown' || msg?.type === 'exit_for_restart')
141
+ onExitRequest();
142
+ });
143
+ setInterval(() => pp.postMessage({ type: 'heartbeat' }), 30_000).unref();
144
+ }
145
+ // Before anything else starts: a token Telegram turns down stops the bot
146
+ // here with one sentence, rather than after the IPC server is listening.
147
+ const botInfo = await verifyBotTokenOrExit();
148
+ // A single bot run without the launcher has nobody to move the pre-rename
149
+ // state directory for it. Stores loaded during import may already hold the
150
+ // old path; the link the move leaves there keeps those working too.
151
+ if (isMainThread)
152
+ migrateLegacyStateDirAndLog('Startup');
153
+ const build = describeRunningBuild();
154
+ if (build)
155
+ console.log(`🏷️ Version: ${build}`);
156
+ console.log(`📋 Allowed users: ${config.ALLOWED_USER_IDS.join(', ')}`);
157
+ // The roster is the other half of the allow-list, and the half that changed
158
+ // while nobody was reading the log — worth naming at startup so "who can use
159
+ // this bot" is answerable from the boot output alone.
160
+ const admittedIds = listAdmitted().map((user) => user.id);
161
+ if (admittedIds.length > 0) {
162
+ console.log(`📋 Admitted from chat: ${admittedIds.join(', ')}`);
163
+ }
164
+ if (config.ADMIN_USER_IDS.length > 0) {
165
+ console.log(`📋 Admins: ${config.ADMIN_USER_IDS.join(', ')}`);
166
+ }
167
+ // Checked here rather than in config.ts because it reads the roster logged
168
+ // above. An approver nothing admits can never tap a prompt, so it is always a
169
+ // typo — and finding it now beats finding it as a prompt nobody answered.
170
+ const orphanedApprovers = findOrphanedApprovers();
171
+ if (orphanedApprovers.length > 0) {
172
+ console.error('❌ Invalid configuration:');
173
+ console.error(` APPROVER_USER_IDS lists ${orphanedApprovers.join(', ')}, whom nothing admits to this bot.\n` +
174
+ ' An approver has to be able to reach the bot first: add them to ALLOWED_USER_IDS,\n' +
175
+ ' or /allow them from chat. APPROVER_USER_IDS only says what they may do once in.');
176
+ process.exit(1);
177
+ }
178
+ const approverIds = getApproverIds();
179
+ if (approverIds.length > 0) {
180
+ console.log(`📋 Approvers: ${approverIds.join(', ')}`);
181
+ }
182
+ if (config.ALLOWED_GROUP_IDS.length > 0) {
183
+ console.log(`📋 Allowed groups: ${config.ALLOWED_GROUP_IDS.join(', ')} ` +
184
+ `(members default to ${config.GROUP_MEMBERS_DEFAULT})`);
185
+ }
186
+ // Which Claude this bot runs: the terminal's, or one that knows only the
187
+ // project. 'auto' follows the roster logged above, so admitting a first
188
+ // guest changes it, and a missing skill or MCP server is otherwise a puzzle.
189
+ if (loadsUserSetup()) {
190
+ console.log('🧰 Claude Code user setup: loaded (~/.claude, your MCP servers and connectors)');
191
+ }
192
+ else {
193
+ const why = config.CLAUDE_USER_SETUP === 'off'
194
+ ? 'CLAUDE_USER_SETUP=off'
195
+ : 'this bot has guests; CLAUDE_USER_SETUP=on loads it anyway';
196
+ console.log(`🧰 Claude Code user setup: left out (${why})`);
197
+ }
198
+ // Scope session history to this bot instance so multi-bot setups don't cross-restore
199
+ sessionHistory.initForBot(BOT_ID);
200
+ // Accept model/effort changes another instance chose to apply fleet-wide.
201
+ initPrefsSync();
202
+ // Prevent system sleep on macOS (only when running standalone, not as worker)
203
+ if (isMainThread)
204
+ preventSleep();
205
+ // Only a warning: a login this can't see (the macOS keychain, a helper
206
+ // script) would otherwise lock the bot out. A turn that does fail on it
207
+ // says how to sign in.
208
+ warnIfClaudeNotLoggedIn();
209
+ const bot = await createBot(botInfo);
210
+ // Already initialised from the token check above, so this makes no request.
211
+ await bot.init();
212
+ console.log(`✅ Bot started as @${bot.botInfo.username}`);
213
+ resumeThreadsSetup(bot);
214
+ if (config.PTY_WATCH) {
215
+ // Never worth failing the start over: the bot works the same without it.
216
+ await startWatchServer(bot.botInfo.username).catch((err) => {
217
+ console.warn(`[Watch] "telecoder watch" is unavailable: ${sanitizeError(err)}`);
218
+ });
219
+ }
220
+ console.log('📱 Send /start in Telegram to begin');
221
+ // Start concurrent runner — updates are processed in parallel,
222
+ // with per-chat ordering enforced by the sequentialize middleware in bot.ts.
223
+ // This lets /cancel bypass the per-chat queue and interrupt running queries.
224
+ // Reassigned when a polling conflict forces a fresh runner (see below).
225
+ let runner = run(bot);
226
+ // Chats that received a startup message, so the restart confirmation below
227
+ // doesn't pile a second one on top.
228
+ const notified = new Set();
229
+ // Auto-resume sessions after /botrebuild or /botrestart
230
+ let markerHandled = false;
231
+ try {
232
+ markerHandled = await autoResumeAfterReload(bot, notified);
233
+ }
234
+ catch (err) {
235
+ console.error('[AutoResume] Failed:', err);
236
+ }
237
+ // Notify any chats whose tasks were interrupted by an unexpected exit.
238
+ try {
239
+ await notifyInterruptedSessions(bot, notified);
240
+ }
241
+ catch (err) {
242
+ console.error('[InFlight] Failed:', err);
243
+ }
244
+ // Cold-start auto-continue: every other chat used within the past week
245
+ // carries straight on in its conversation, without a word. Runs even after
246
+ // a reload marker was consumed, since auto-resume only restores sessions
247
+ // idle < 1h. Chats that DID get the "Reloaded and session restored" recap
248
+ // are live in memory by then and skip themselves via the alreadyLive guard.
249
+ try {
250
+ autoContinueOnStartup();
251
+ }
252
+ catch (err) {
253
+ console.error('[AutoContinue] Failed:', err);
254
+ }
255
+ // Confirm the restart itself, but only for a user-initiated one — a fresh
256
+ // reload marker is what distinguishes /botrebuild and /botrestart from a
257
+ // crash respawn or a plain pm2 restart.
258
+ if (markerHandled) {
259
+ try {
260
+ await notifyRestartComplete(bot, notified);
261
+ }
262
+ catch (err) {
263
+ console.error('[Restart] Failed:', err);
264
+ }
265
+ }
266
+ // Reconcile the Telegram display name with the configured one (/botname or
267
+ // BOT_NAME), in case it changed between runs or a rename was refused.
268
+ try {
269
+ await syncBotNameOnStartup(bot.api);
270
+ }
271
+ catch (err) {
272
+ console.debug('[BotName] Startup sync failed:', err instanceof Error ? err.message : err);
273
+ }
274
+ // Re-arm persisted scheduled tasks (/loop). Runs after session
275
+ // restore so the first scheduled fire can resolve the live session
276
+ // instead of paying a cold-spawn tax.
277
+ try {
278
+ startScheduledRunner(bot);
279
+ }
280
+ catch (err) {
281
+ console.error('[Scheduler] Failed to start:', err);
282
+ }
283
+ // Ask about anything set aside before the restart. Runs after the resume paths
284
+ // above so the question lands below whatever they post.
285
+ armReminders();
286
+ // Register the bot reference for the Monitor relay so Monitor
287
+ // events that fire between user turns can be posted to Telegram.
288
+ setMonitorRelayBot(bot);
289
+ // And the update-banner relay, so claude code's "Update available" notice
290
+ // (printed once at PTY startup) is forwarded to the user instead of being
291
+ // silently consumed by the headless xterm.
292
+ setUpdateBannerRelayBot(bot);
293
+ // Watch for cross-bot branch handoffs landing in our pending-branches file and
294
+ // proactively DM the user so they don't have to message us first to see
295
+ // the offer.
296
+ try {
297
+ startPendingBranchWatcher(bot);
298
+ }
299
+ catch (err) {
300
+ console.error('[Branch] Failed to start pending-branch watcher:', err);
301
+ }
302
+ // Liveness heartbeat: periodically verify the bot can still reach the
303
+ // Telegram API. If the runner has stopped or getMe fails repeatedly,
304
+ // exit so PM2 can restart the process.
305
+ const HEARTBEAT_INTERVAL_MS = 60_000;
306
+ const MAX_HEARTBEAT_FAILURES = 3;
307
+ // Timeouts get a longer leash than errors. An error is Telegram answering
308
+ // with a fault we can act on; a timeout is us not hearing back, which on a
309
+ // host under memory pressure says more about the host than the bot — and
310
+ // exiting there tears down every live Claude session to "fix" a machine
311
+ // that's merely busy. Restarting doesn't cure a stall, so ride it out.
312
+ const MAX_HEARTBEAT_TIMEOUTS = 10;
313
+ // Same reasoning as the launcher's stall guard: an interval that fires far
314
+ // later than scheduled means this thread wasn't running, so the round it
315
+ // would have done tells us nothing about Telegram's reachability.
316
+ const HEARTBEAT_STALL_SLACK_MS = 30_000;
317
+ const isTimeoutError = (err) => err instanceof Error && /timed out after/i.test(err.message);
318
+ let heartbeatFailures = 0;
319
+ let heartbeatTimeouts = 0;
320
+ let lastHeartbeatAt = Date.now();
321
+ // True only while we're deliberately between runners, waiting out a polling
322
+ // conflict. The check below would otherwise read that gap as a dead runner.
323
+ let replacingRunner = false;
324
+ const heartbeatTimer = setInterval(async () => {
325
+ const now = Date.now();
326
+ const sinceLast = now - lastHeartbeatAt;
327
+ lastHeartbeatAt = now;
328
+ if (tickWasStalled({ sinceLastTickMs: sinceLast, intervalMs: HEARTBEAT_INTERVAL_MS, slackMs: HEARTBEAT_STALL_SLACK_MS })) {
329
+ console.warn(`[HEARTBEAT] tick fired ${Math.round(sinceLast / 1000)}s late (expected ${Math.round(HEARTBEAT_INTERVAL_MS / 1000)}s) — host was frozen, skipping this round`);
330
+ heartbeatFailures = 0;
331
+ heartbeatTimeouts = 0;
332
+ return;
333
+ }
334
+ if (!replacingRunner && !runner.isRunning()) {
335
+ console.error('[HEARTBEAT] Runner is no longer running — exiting for restart');
336
+ process.exit(1);
337
+ }
338
+ try {
339
+ await bot.api.getMe();
340
+ heartbeatFailures = 0;
341
+ heartbeatTimeouts = 0;
342
+ }
343
+ catch (err) {
344
+ if (isTimeoutError(err)) {
345
+ heartbeatTimeouts++;
346
+ console.error(`[HEARTBEAT] getMe timed out (${heartbeatTimeouts}/${MAX_HEARTBEAT_TIMEOUTS}):`, err);
347
+ if (heartbeatTimeouts >= MAX_HEARTBEAT_TIMEOUTS) {
348
+ console.error('[HEARTBEAT] Telegram unreachable for too long — exiting for restart');
349
+ process.exit(EXIT_TELEGRAM_UNAVAILABLE);
350
+ }
351
+ return;
352
+ }
353
+ heartbeatFailures++;
354
+ console.error(`[HEARTBEAT] getMe failed (${heartbeatFailures}/${MAX_HEARTBEAT_FAILURES}):`, err);
355
+ if (heartbeatFailures >= MAX_HEARTBEAT_FAILURES) {
356
+ console.error('[HEARTBEAT] Too many consecutive failures — exiting for restart');
357
+ process.exit(EXIT_TELEGRAM_UNAVAILABLE);
358
+ }
359
+ }
360
+ }, HEARTBEAT_INTERVAL_MS);
361
+ heartbeatTimer.unref(); // Don't prevent graceful shutdown
362
+ // Graceful shutdown (guarded against duplicate signals)
363
+ let shuttingDown = false;
364
+ // Normally 0 — a shutdown is a shutdown. /botrestart under systemd sets
365
+ // process.exitCode first, because there the exit *is* the restart and the
366
+ // code is what tells systemd to bring us back rather than stand down.
367
+ const exitCode = () => (typeof process.exitCode === 'number' ? process.exitCode : 0);
368
+ const shutdown = async () => {
369
+ if (shuttingDown)
370
+ return;
371
+ shuttingDown = true;
372
+ console.log('\n👋 Shutting down...');
373
+ clearInterval(heartbeatTimer);
374
+ allowSleep();
375
+ stopCleanup();
376
+ // Don't let a stuck runner.stop() (e.g. a getUpdates call that never
377
+ // settles) hold the exit open — the launcher is waiting on it to restart us.
378
+ const exitWatchdog = setTimeout(() => {
379
+ console.warn(`[Shutdown] Runner did not stop within ${Math.round(SHUTDOWN_TIMEOUT_MS / 1000)}s — exiting anyway`);
380
+ process.exit(exitCode());
381
+ }, SHUTDOWN_TIMEOUT_MS);
382
+ exitWatchdog.unref();
383
+ // The claudes too: left to the exit, one goes on for as long as it takes
384
+ // to notice, while the bot that replaces this one may already have resumed
385
+ // its conversation in another.
386
+ await Promise.all([runner.stop(), getPtyProvider().closeAll()]);
387
+ stopWatchServer();
388
+ process.exit(exitCode());
389
+ };
390
+ process.on('SIGINT', () => { shutdown(); });
391
+ process.on('SIGTERM', () => { shutdown(); });
392
+ // When running as a worker thread, the launcher's exit requests now get the
393
+ // full shutdown (the listener and heartbeat were set up at the top of main).
394
+ if (!isMainThread && parentPort) {
395
+ onExitRequest = shutdown;
396
+ // Tells the launcher this worker is listening, so only once it is: the
397
+ // bot is up and the shutdown above is wired to the restart it may ask for.
398
+ initRestartWhenIdle(bot.api);
399
+ }
400
+ // Keep alive until the runner stops (crash or explicit stop).
401
+ //
402
+ // A 409 from getUpdates means something else is polling this same token —
403
+ // nearly always our own predecessor, whose long poll Telegram hasn't dropped
404
+ // yet during a restart. grammY's runner classes it as unrecoverable and stops
405
+ // (throwIfUnrecoverable in @grammyjs/runner), but the condition clears itself
406
+ // within a poll timeout. Exiting over it would tear down every live Claude
407
+ // session this bot owns, so put a fresh runner on the same bot instead and
408
+ // only give up if the conflict is still there after several tries — by then
409
+ // it's a real second instance, not an overlap.
410
+ const CONFLICT_RETRY_DELAYS_MS = [5_000, 15_000, 30_000, 60_000];
411
+ const isConflict = (err) => typeof err === 'object' && err !== null &&
412
+ err.error_code === 409;
413
+ for (let attempt = 0;; attempt++) {
414
+ try {
415
+ await runner.task();
416
+ return;
417
+ }
418
+ catch (err) {
419
+ if (shuttingDown || !isConflict(err))
420
+ throw err;
421
+ const delay = CONFLICT_RETRY_DELAYS_MS[attempt];
422
+ if (delay === undefined) {
423
+ console.error(`[Conflict] getUpdates still conflicting after ${CONFLICT_RETRY_DELAYS_MS.length} retries — another instance is polling this token for real`);
424
+ throw err;
425
+ }
426
+ console.warn(`[Conflict] Another poller holds this bot's token — retrying in ${Math.round(delay / 1000)}s (attempt ${attempt + 1}/${CONFLICT_RETRY_DELAYS_MS.length})`);
427
+ replacingRunner = true;
428
+ await new Promise(resolve => setTimeout(resolve, delay));
429
+ if (shuttingDown)
430
+ return;
431
+ runner = run(bot);
432
+ replacingRunner = false;
433
+ }
434
+ }
435
+ }
436
+ main().catch((error) => {
437
+ // grammY puts the request URL, token and all, into some of its errors.
438
+ const detail = error instanceof Error ? (error.stack ?? error.message) : String(error);
439
+ console.error('Fatal error:', redactSecrets(detail));
440
+ allowSleep();
441
+ process.exit(1);
442
+ });
443
+ //# sourceMappingURL=index.js.map