telecoder 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/.env.example +363 -0
  2. package/CHANGELOG.md +1186 -0
  3. package/LICENSE +22 -0
  4. package/README.md +126 -2
  5. package/dist/audio/transcribe.js +50 -0
  6. package/dist/bin/mcp-server.js +378 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +592 -0
  10. package/dist/bot/file-access.js +141 -0
  11. package/dist/bot/handlers/command/access.js +407 -0
  12. package/dist/bot/handlers/command/admin.js +827 -0
  13. package/dist/bot/handlers/command/auto-approve.js +138 -0
  14. package/dist/bot/handlers/command/btw.js +224 -0
  15. package/dist/bot/handlers/command/cost.js +409 -0
  16. package/dist/bot/handlers/command/media.js +197 -0
  17. package/dist/bot/handlers/command/model.js +305 -0
  18. package/dist/bot/handlers/command/prefs-scope.js +197 -0
  19. package/dist/bot/handlers/command/project.js +536 -0
  20. package/dist/bot/handlers/command/resume.js +321 -0
  21. package/dist/bot/handlers/command/session.js +438 -0
  22. package/dist/bot/handlers/command/settings.js +1012 -0
  23. package/dist/bot/handlers/command/shared.js +210 -0
  24. package/dist/bot/handlers/command/streaming-mode.js +16 -0
  25. package/dist/bot/handlers/command/tasks.js +513 -0
  26. package/dist/bot/handlers/command/topic-store.js +113 -0
  27. package/dist/bot/handlers/command/topic.js +80 -0
  28. package/dist/bot/handlers/command.handler.js +772 -0
  29. package/dist/bot/handlers/fork.handler.js +1109 -0
  30. package/dist/bot/handlers/media-fallback.js +121 -0
  31. package/dist/bot/handlers/message/replies.js +133 -0
  32. package/dist/bot/handlers/message/shared.js +117 -0
  33. package/dist/bot/handlers/message/throttle.js +49 -0
  34. package/dist/bot/handlers/message/turn-notify.js +169 -0
  35. package/dist/bot/handlers/message/turn-runner.js +141 -0
  36. package/dist/bot/handlers/message.handler.js +107 -0
  37. package/dist/bot/handlers/newbot.handler.js +221 -0
  38. package/dist/bot/handlers/photo.handler.js +327 -0
  39. package/dist/bot/handlers/prompts.handler.js +343 -0
  40. package/dist/bot/handlers/running-note.js +44 -0
  41. package/dist/bot/handlers/schedule.handler.js +303 -0
  42. package/dist/bot/handlers/session-guard.js +78 -0
  43. package/dist/bot/handlers/suggestion.handler.js +84 -0
  44. package/dist/bot/handlers/tree.handler.js +480 -0
  45. package/dist/bot/handlers/view.js +41 -0
  46. package/dist/bot/handlers/voice.handler.js +209 -0
  47. package/dist/bot/middleware/admin-only.js +49 -0
  48. package/dist/bot/middleware/auth.middleware.js +122 -0
  49. package/dist/bot/middleware/group-mention.middleware.js +139 -0
  50. package/dist/bot/middleware/group-role.middleware.js +75 -0
  51. package/dist/bot/middleware/message-batcher.js +87 -0
  52. package/dist/bot/middleware/queued-messages.js +971 -0
  53. package/dist/bot/middleware/stale-filter.js +31 -0
  54. package/dist/build-info.json +8 -0
  55. package/dist/claude/agent-watchdog.js +162 -0
  56. package/dist/claude/agent.js +1458 -0
  57. package/dist/claude/ask-user.js +295 -0
  58. package/dist/claude/auto-approve.js +225 -0
  59. package/dist/claude/auto-topic-haiku.js +126 -0
  60. package/dist/claude/available-commands.js +153 -0
  61. package/dist/claude/carry-over.js +27 -0
  62. package/dist/claude/ccr-shim.js +46 -0
  63. package/dist/claude/charter-judge.js +214 -0
  64. package/dist/claude/claude-auth.js +121 -0
  65. package/dist/claude/command-parser.js +200 -0
  66. package/dist/claude/cost-overlay-scraper.js +129 -0
  67. package/dist/claude/enabled-plugins.js +56 -0
  68. package/dist/claude/fork-tree.js +393 -0
  69. package/dist/claude/held-query.js +190 -0
  70. package/dist/claude/in-flight-tracker.js +61 -0
  71. package/dist/claude/ipc-server.js +192 -0
  72. package/dist/claude/mcp-bridge.js +453 -0
  73. package/dist/claude/mcp-tools.js +354 -0
  74. package/dist/claude/message-offsets.js +88 -0
  75. package/dist/claude/modal-relay.js +450 -0
  76. package/dist/claude/model-catalog.js +85 -0
  77. package/dist/claude/monitor-relay.js +597 -0
  78. package/dist/claude/pending-forks.js +93 -0
  79. package/dist/claude/pending-suggestions.js +50 -0
  80. package/dist/claude/permission-gate.js +337 -0
  81. package/dist/claude/permission-mode.js +178 -0
  82. package/dist/claude/poll-user.js +51 -0
  83. package/dist/claude/project-commands.js +69 -0
  84. package/dist/claude/prompt-hold.js +124 -0
  85. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  86. package/dist/claude/pty-provider.js +2214 -0
  87. package/dist/claude/pty-spawn-config.js +296 -0
  88. package/dist/claude/pty-stream.js +363 -0
  89. package/dist/claude/request-queue.js +135 -0
  90. package/dist/claude/scheduled-runner.js +91 -0
  91. package/dist/claude/scheduler.js +237 -0
  92. package/dist/claude/scope-guard.js +274 -0
  93. package/dist/claude/sdk-permission-gate.js +77 -0
  94. package/dist/claude/secret-request.js +576 -0
  95. package/dist/claude/session-cost.js +41 -0
  96. package/dist/claude/session-history.js +286 -0
  97. package/dist/claude/session-jsonl.js +920 -0
  98. package/dist/claude/session-manager.js +195 -0
  99. package/dist/claude/session-scan.js +270 -0
  100. package/dist/claude/setup-token.js +285 -0
  101. package/dist/claude/side-call-options.js +45 -0
  102. package/dist/claude/side-question.js +249 -0
  103. package/dist/claude/stage-images.js +62 -0
  104. package/dist/claude/subagent-tools.js +12 -0
  105. package/dist/claude/synthetic-ctx.js +51 -0
  106. package/dist/claude/system-prompt.js +162 -0
  107. package/dist/claude/tasks-overlay-scraper.js +94 -0
  108. package/dist/claude/tip-scraper.js +78 -0
  109. package/dist/claude/tui-modal.js +501 -0
  110. package/dist/claude/tui-state.js +384 -0
  111. package/dist/claude/turn-end.js +91 -0
  112. package/dist/claude/turn-prose.js +64 -0
  113. package/dist/claude/update-banner-relay.js +70 -0
  114. package/dist/cli/commands/doctor.js +305 -0
  115. package/dist/cli/commands/help.js +25 -0
  116. package/dist/cli/commands/init.js +123 -0
  117. package/dist/cli/commands/service.js +678 -0
  118. package/dist/cli/commands/start.js +53 -0
  119. package/dist/cli/commands/version.js +11 -0
  120. package/dist/cli/dispatch.js +79 -0
  121. package/dist/cli/init/env-file.js +99 -0
  122. package/dist/cli/init/flow.js +638 -0
  123. package/dist/cli/init/prompter.js +116 -0
  124. package/dist/cli/init/telegram.js +94 -0
  125. package/dist/cli/service/render.js +212 -0
  126. package/dist/cli.js +18 -0
  127. package/dist/config-report.js +107 -0
  128. package/dist/config.js +500 -0
  129. package/dist/index.js +367 -0
  130. package/dist/launcher.js +933 -0
  131. package/dist/node-version-check.js +27 -0
  132. package/dist/providers/ccr-health.js +119 -0
  133. package/dist/providers/ccr-introspect.js +149 -0
  134. package/dist/providers/ccr-provider.js +60 -0
  135. package/dist/providers/claude-provider.js +63 -0
  136. package/dist/providers/prefs-sync.js +164 -0
  137. package/dist/providers/project-favorites.js +74 -0
  138. package/dist/providers/provider-router.js +127 -0
  139. package/dist/providers/provider-switch.js +91 -0
  140. package/dist/providers/sdk-provider.js +37 -0
  141. package/dist/providers/types.js +8 -0
  142. package/dist/providers/user-preferences.js +214 -0
  143. package/dist/restart-when-idle.js +153 -0
  144. package/dist/startup/auto-continue.js +67 -0
  145. package/dist/startup/auto-resume.js +173 -0
  146. package/dist/startup/notices.js +120 -0
  147. package/dist/startup/shared.js +44 -0
  148. package/dist/startup/verify-token.js +31 -0
  149. package/dist/telegram/access-request.js +153 -0
  150. package/dist/telegram/action-logger.js +684 -0
  151. package/dist/telegram/admin-mention.js +107 -0
  152. package/dist/telegram/background-activity-card.js +502 -0
  153. package/dist/telegram/botname-settings.js +336 -0
  154. package/dist/telegram/button-text.js +26 -0
  155. package/dist/telegram/client-options.js +27 -0
  156. package/dist/telegram/deduplication.js +33 -0
  157. package/dist/telegram/entities.js +295 -0
  158. package/dist/telegram/force-reply-tracker.js +57 -0
  159. package/dist/telegram/lettered-options.js +87 -0
  160. package/dist/telegram/markdown.js +362 -0
  161. package/dist/telegram/message-sender.js +1287 -0
  162. package/dist/telegram/prompt-label.js +142 -0
  163. package/dist/telegram/prompt-suggestion.js +54 -0
  164. package/dist/telegram/send.js +123 -0
  165. package/dist/telegram/streaming-turn.js +105 -0
  166. package/dist/telegram/suggestions-settings.js +30 -0
  167. package/dist/telegram/task-list.js +367 -0
  168. package/dist/telegram/task-tracker.js +209 -0
  169. package/dist/telegram/telegraph-settings.js +31 -0
  170. package/dist/telegram/telegraph.js +453 -0
  171. package/dist/telegram/terminal-renderer.js +671 -0
  172. package/dist/telegram/terminal-settings.js +25 -0
  173. package/dist/telegram/thread-titles.js +190 -0
  174. package/dist/telegram/threads-setup.js +117 -0
  175. package/dist/tts/tts-settings.js +62 -0
  176. package/dist/tts/tts.js +245 -0
  177. package/dist/tts/voice-reply.js +78 -0
  178. package/dist/utils/admins.js +143 -0
  179. package/dist/utils/agent-timer.js +55 -0
  180. package/dist/utils/atomic-write.js +24 -0
  181. package/dist/utils/bot-token.js +74 -0
  182. package/dist/utils/bounded-map.js +55 -0
  183. package/dist/utils/build-info.js +57 -0
  184. package/dist/utils/caffeinate.js +50 -0
  185. package/dist/utils/claude-env.js +54 -0
  186. package/dist/utils/claude-version.js +48 -0
  187. package/dist/utils/config-home.js +62 -0
  188. package/dist/utils/debug-agent.js +117 -0
  189. package/dist/utils/debug-watchdog.js +121 -0
  190. package/dist/utils/download.js +111 -0
  191. package/dist/utils/exit-codes.js +48 -0
  192. package/dist/utils/file-type.js +149 -0
  193. package/dist/utils/format.js +81 -0
  194. package/dist/utils/home-project.js +30 -0
  195. package/dist/utils/host-stall.js +51 -0
  196. package/dist/utils/id-list.js +44 -0
  197. package/dist/utils/idle-restart.js +92 -0
  198. package/dist/utils/install-mode.js +63 -0
  199. package/dist/utils/instance-config.js +148 -0
  200. package/dist/utils/instances.js +95 -0
  201. package/dist/utils/json-store.js +140 -0
  202. package/dist/utils/keyed-settings.js +62 -0
  203. package/dist/utils/legacy-env.js +35 -0
  204. package/dist/utils/npm-version.js +134 -0
  205. package/dist/utils/prefs-relay.js +107 -0
  206. package/dist/utils/proc-children.js +102 -0
  207. package/dist/utils/project-data-dir.js +33 -0
  208. package/dist/utils/reasoning-summary.js +12 -0
  209. package/dist/utils/resolve-bin.js +86 -0
  210. package/dist/utils/resolve-claude-bin.js +63 -0
  211. package/dist/utils/respawn-backoff.js +19 -0
  212. package/dist/utils/sanitize.js +91 -0
  213. package/dist/utils/session-key.js +37 -0
  214. package/dist/utils/stale-launcher.js +109 -0
  215. package/dist/utils/state-dir-migration.js +92 -0
  216. package/dist/utils/systemd.js +126 -0
  217. package/dist/utils/user-roster.js +275 -0
  218. package/dist/utils/verbosity.js +118 -0
  219. package/dist/utils/version-check.js +166 -0
  220. package/dist/utils/workspace-guard.js +44 -0
  221. package/dist/worker-restart.js +141 -0
  222. package/instances.json.example +41 -0
  223. package/package.json +76 -4
package/dist/index.js ADDED
@@ -0,0 +1,367 @@
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 } 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 { startPendingForkWatcher } from './bot/handlers/fork.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 { describeRunningBuild } from './utils/build-info.js';
40
+ import { migrateLegacyStateDirAndLog } from './utils/state-dir-migration.js';
41
+ import { verifyBotTokenOrExit } from './startup/verify-token.js';
42
+ import { warnIfClaudeNotLoggedIn } from './claude/claude-auth.js';
43
+ import { redactSecrets } from './utils/sanitize.js';
44
+ export { requestRestart, requestSiblingRestart, requestRestartAll } from './worker-restart.js';
45
+ // When running as a worker thread (multi-instance mode), prefix all console
46
+ // output with the instance name so logs from different bots are distinguishable.
47
+ const instanceName = process.env.TELECODER_INSTANCE_NAME;
48
+ if (instanceName) {
49
+ const prefix = `[${instanceName}]`;
50
+ const origLog = console.log.bind(console);
51
+ const origError = console.error.bind(console);
52
+ const origWarn = console.warn.bind(console);
53
+ console.log = (...args) => origLog(prefix, ...args);
54
+ console.error = (...args) => origError(prefix, ...args);
55
+ console.warn = (...args) => origWarn(prefix, ...args);
56
+ }
57
+ // Drop any Claude Code session markers we inherited before a provider spawns
58
+ // anything. Restarting the bot from inside a claude session (which is how it
59
+ // happens here — the bot's own session runs `pm2 start`) otherwise leaves every
60
+ // claude we spawn believing it's a nested session, with transcript persistence
61
+ // off and no session log for us to read replies from. See utils/claude-env.ts.
62
+ const strippedClaudeVars = stripParentClaudeSession();
63
+ if (strippedClaudeVars.length > 0) {
64
+ console.warn(`[Env] Bot was launched from inside a Claude Code session; dropped inherited markers so spawned sessions persist normally: ${strippedClaudeVars.join(', ')}`);
65
+ }
66
+ // Log unhandled rejections — prevents silent failures where the process stays
67
+ // alive but functionality is broken (e.g. fire-and-forget async calls that fail).
68
+ process.on('unhandledRejection', (reason) => {
69
+ console.error('[FATAL] Unhandled promise rejection:', reason);
70
+ });
71
+ // How long a graceful shutdown may take before we exit regardless.
72
+ const SHUTDOWN_TIMEOUT_MS = 5_000;
73
+ async function main() {
74
+ console.log('🤖 Starting TeleCoder...');
75
+ // Before anything else starts: a token Telegram turns down stops the bot
76
+ // here with one sentence, rather than after the IPC server is listening.
77
+ const botInfo = await verifyBotTokenOrExit();
78
+ // A single bot run without the launcher has nobody to move the pre-rename
79
+ // state directory for it. Stores loaded during import may already hold the
80
+ // old path; the link the move leaves there keeps those working too.
81
+ if (isMainThread)
82
+ migrateLegacyStateDirAndLog('Startup');
83
+ const build = describeRunningBuild();
84
+ if (build)
85
+ console.log(`🏷️ Version: ${build}`);
86
+ console.log(`📋 Allowed users: ${config.ALLOWED_USER_IDS.join(', ')}`);
87
+ // The roster is the other half of the allow-list, and the half that changed
88
+ // while nobody was reading the log — worth naming at startup so "who can use
89
+ // this bot" is answerable from the boot output alone.
90
+ const admittedIds = listAdmitted().map((user) => user.id);
91
+ if (admittedIds.length > 0) {
92
+ console.log(`📋 Admitted from chat: ${admittedIds.join(', ')}`);
93
+ }
94
+ if (config.ADMIN_USER_IDS.length > 0) {
95
+ console.log(`📋 Admins: ${config.ADMIN_USER_IDS.join(', ')}`);
96
+ }
97
+ // Checked here rather than in config.ts because it reads the roster logged
98
+ // above. An approver nothing admits can never tap a prompt, so it is always a
99
+ // typo — and finding it now beats finding it as a prompt nobody answered.
100
+ const orphanedApprovers = findOrphanedApprovers();
101
+ if (orphanedApprovers.length > 0) {
102
+ console.error('❌ Invalid configuration:');
103
+ console.error(` APPROVER_USER_IDS lists ${orphanedApprovers.join(', ')}, whom nothing admits to this bot.\n` +
104
+ ' An approver has to be able to reach the bot first: add them to ALLOWED_USER_IDS,\n' +
105
+ ' or /allow them from chat. APPROVER_USER_IDS only says what they may do once in.');
106
+ process.exit(1);
107
+ }
108
+ const approverIds = getApproverIds();
109
+ if (approverIds.length > 0) {
110
+ console.log(`📋 Approvers: ${approverIds.join(', ')}`);
111
+ }
112
+ if (config.ALLOWED_GROUP_IDS.length > 0) {
113
+ console.log(`📋 Allowed groups: ${config.ALLOWED_GROUP_IDS.join(', ')} ` +
114
+ `(members default to ${config.GROUP_MEMBERS_DEFAULT})`);
115
+ }
116
+ console.log(`📝 Mode: ${config.STREAMING_MODE}`);
117
+ // Scope session history to this bot instance so multi-bot setups don't cross-restore
118
+ sessionHistory.initForBot(BOT_ID);
119
+ // Accept model/effort changes another instance chose to apply fleet-wide.
120
+ initPrefsSync();
121
+ // Prevent system sleep on macOS (only when running standalone, not as worker)
122
+ if (isMainThread)
123
+ preventSleep();
124
+ // Only a warning: a login this can't see (the macOS keychain, a helper
125
+ // script) would otherwise lock the bot out. A turn that does fail on it
126
+ // says how to sign in.
127
+ warnIfClaudeNotLoggedIn();
128
+ const bot = await createBot(botInfo);
129
+ // Already initialised from the token check above, so this makes no request.
130
+ await bot.init();
131
+ console.log(`✅ Bot started as @${bot.botInfo.username}`);
132
+ resumeThreadsSetup(bot);
133
+ console.log('📱 Send /start in Telegram to begin');
134
+ // Start concurrent runner — updates are processed in parallel,
135
+ // with per-chat ordering enforced by the sequentialize middleware in bot.ts.
136
+ // This lets /cancel bypass the per-chat queue and interrupt running queries.
137
+ // Reassigned when a polling conflict forces a fresh runner (see below).
138
+ let runner = run(bot);
139
+ // Chats that received a startup message, so the restart confirmation below
140
+ // doesn't pile a second one on top.
141
+ const notified = new Set();
142
+ // Auto-resume sessions after /rebuildbot or /restartbot
143
+ let markerHandled = false;
144
+ try {
145
+ markerHandled = await autoResumeAfterReload(bot, notified);
146
+ }
147
+ catch (err) {
148
+ console.error('[AutoResume] Failed:', err);
149
+ }
150
+ // Notify any chats whose tasks were interrupted by an unexpected exit.
151
+ try {
152
+ await notifyInterruptedSessions(bot, notified);
153
+ }
154
+ catch (err) {
155
+ console.error('[InFlight] Failed:', err);
156
+ }
157
+ // Cold-start auto-continue: every other chat used within the past week
158
+ // carries straight on in its conversation, without a word. Runs even after
159
+ // a reload marker was consumed, since auto-resume only restores sessions
160
+ // idle < 1h. Chats that DID get the "Reloaded and session restored" recap
161
+ // are live in memory by then and skip themselves via the alreadyLive guard.
162
+ try {
163
+ autoContinueOnStartup();
164
+ }
165
+ catch (err) {
166
+ console.error('[AutoContinue] Failed:', err);
167
+ }
168
+ // Confirm the restart itself, but only for a user-initiated one — a fresh
169
+ // reload marker is what distinguishes /rebuildbot and /restartbot from a
170
+ // crash respawn or a plain pm2 restart.
171
+ if (markerHandled) {
172
+ try {
173
+ await notifyRestartComplete(bot, notified);
174
+ }
175
+ catch (err) {
176
+ console.error('[Restart] Failed:', err);
177
+ }
178
+ }
179
+ // Reconcile the Telegram display name with BOT_NAME. Runs after the resume
180
+ // paths above so a session restore — which pushes its own "BOT_NAME —
181
+ // project" name — wins and this becomes a no-op; only a bot whose name
182
+ // nobody claimed this startup gets rewritten.
183
+ try {
184
+ await syncBotNameOnStartup(bot.api);
185
+ }
186
+ catch (err) {
187
+ console.debug('[BotName] Startup sync failed:', err instanceof Error ? err.message : err);
188
+ }
189
+ // Re-arm persisted scheduled tasks (/schedule). Runs after session
190
+ // restore so the first scheduled fire can resolve the live session
191
+ // instead of paying a cold-spawn tax.
192
+ try {
193
+ startScheduledRunner(bot);
194
+ }
195
+ catch (err) {
196
+ console.error('[Scheduler] Failed to start:', err);
197
+ }
198
+ // Ask about anything set aside before the restart. Runs after the resume paths
199
+ // above so the question lands below whatever they post.
200
+ armReminders();
201
+ // Register the bot reference for the PTY-mode Monitor relay so Monitor
202
+ // events that fire between user turns can be posted to Telegram.
203
+ setMonitorRelayBot(bot);
204
+ // And the update-banner relay, so claude code's "Update available" notice
205
+ // (printed once at PTY startup) is forwarded to the user instead of being
206
+ // silently consumed by the headless xterm.
207
+ setUpdateBannerRelayBot(bot);
208
+ // Watch for cross-bot fork handoffs landing in our pending-forks file and
209
+ // proactively DM the user so they don't have to message us first to see
210
+ // the offer.
211
+ try {
212
+ startPendingForkWatcher(bot);
213
+ }
214
+ catch (err) {
215
+ console.error('[Fork] Failed to start pending-fork watcher:', err);
216
+ }
217
+ // Liveness heartbeat: periodically verify the bot can still reach the
218
+ // Telegram API. If the runner has stopped or getMe fails repeatedly,
219
+ // exit so PM2 can restart the process.
220
+ const HEARTBEAT_INTERVAL_MS = 60_000;
221
+ const MAX_HEARTBEAT_FAILURES = 3;
222
+ // Timeouts get a longer leash than errors. An error is Telegram answering
223
+ // with a fault we can act on; a timeout is us not hearing back, which on a
224
+ // host under memory pressure says more about the host than the bot — and
225
+ // exiting there tears down every live Claude session to "fix" a machine
226
+ // that's merely busy. Restarting doesn't cure a stall, so ride it out.
227
+ const MAX_HEARTBEAT_TIMEOUTS = 10;
228
+ // Same reasoning as the launcher's stall guard: an interval that fires far
229
+ // later than scheduled means this thread wasn't running, so the round it
230
+ // would have done tells us nothing about Telegram's reachability.
231
+ const HEARTBEAT_STALL_SLACK_MS = 30_000;
232
+ const isTimeoutError = (err) => err instanceof Error && /timed out after/i.test(err.message);
233
+ let heartbeatFailures = 0;
234
+ let heartbeatTimeouts = 0;
235
+ let lastHeartbeatAt = Date.now();
236
+ // True only while we're deliberately between runners, waiting out a polling
237
+ // conflict. The check below would otherwise read that gap as a dead runner.
238
+ let replacingRunner = false;
239
+ const heartbeatTimer = setInterval(async () => {
240
+ const now = Date.now();
241
+ const sinceLast = now - lastHeartbeatAt;
242
+ lastHeartbeatAt = now;
243
+ if (tickWasStalled({ sinceLastTickMs: sinceLast, intervalMs: HEARTBEAT_INTERVAL_MS, slackMs: HEARTBEAT_STALL_SLACK_MS })) {
244
+ 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`);
245
+ heartbeatFailures = 0;
246
+ heartbeatTimeouts = 0;
247
+ return;
248
+ }
249
+ if (!replacingRunner && !runner.isRunning()) {
250
+ console.error('[HEARTBEAT] Runner is no longer running — exiting for restart');
251
+ process.exit(1);
252
+ }
253
+ try {
254
+ await bot.api.getMe();
255
+ heartbeatFailures = 0;
256
+ heartbeatTimeouts = 0;
257
+ }
258
+ catch (err) {
259
+ if (isTimeoutError(err)) {
260
+ heartbeatTimeouts++;
261
+ console.error(`[HEARTBEAT] getMe timed out (${heartbeatTimeouts}/${MAX_HEARTBEAT_TIMEOUTS}):`, err);
262
+ if (heartbeatTimeouts >= MAX_HEARTBEAT_TIMEOUTS) {
263
+ console.error('[HEARTBEAT] Telegram unreachable for too long — exiting for restart');
264
+ process.exit(1);
265
+ }
266
+ return;
267
+ }
268
+ heartbeatFailures++;
269
+ console.error(`[HEARTBEAT] getMe failed (${heartbeatFailures}/${MAX_HEARTBEAT_FAILURES}):`, err);
270
+ if (heartbeatFailures >= MAX_HEARTBEAT_FAILURES) {
271
+ console.error('[HEARTBEAT] Too many consecutive failures — exiting for restart');
272
+ process.exit(1);
273
+ }
274
+ }
275
+ }, HEARTBEAT_INTERVAL_MS);
276
+ heartbeatTimer.unref(); // Don't prevent graceful shutdown
277
+ // Graceful shutdown (guarded against duplicate signals)
278
+ let shuttingDown = false;
279
+ // Normally 0 — a shutdown is a shutdown. /restartbot under systemd sets
280
+ // process.exitCode first, because there the exit *is* the restart and the
281
+ // code is what tells systemd to bring us back rather than stand down.
282
+ const exitCode = () => (typeof process.exitCode === 'number' ? process.exitCode : 0);
283
+ const shutdown = async () => {
284
+ if (shuttingDown)
285
+ return;
286
+ shuttingDown = true;
287
+ console.log('\n👋 Shutting down...');
288
+ clearInterval(heartbeatTimer);
289
+ allowSleep();
290
+ stopCleanup();
291
+ // Don't let a stuck runner.stop() (e.g. a getUpdates call that never
292
+ // settles) hold the exit open — the launcher is waiting on it to restart us.
293
+ const exitWatchdog = setTimeout(() => {
294
+ console.warn(`[Shutdown] Runner did not stop within ${Math.round(SHUTDOWN_TIMEOUT_MS / 1000)}s — exiting anyway`);
295
+ process.exit(exitCode());
296
+ }, SHUTDOWN_TIMEOUT_MS);
297
+ exitWatchdog.unref();
298
+ // The claudes too: left to the exit, one goes on for as long as it takes
299
+ // to notice, while the bot that replaces this one may already have resumed
300
+ // its conversation in another.
301
+ await Promise.all([runner.stop(), getPtyProvider().closeAll()]);
302
+ process.exit(exitCode());
303
+ };
304
+ process.on('SIGINT', () => { shutdown(); });
305
+ process.on('SIGTERM', () => { shutdown(); });
306
+ // When running as a worker thread, communicate with the launcher
307
+ if (!isMainThread && parentPort) {
308
+ parentPort.on('message', (msg) => {
309
+ // 'exit_for_restart' is the launcher answering a restart request: we exit
310
+ // ourselves rather than waiting to be terminated. A worker.terminate()
311
+ // only lands when the thread next runs JS, so a worker blocked in native
312
+ // code would never die — and never be respawned.
313
+ if (msg?.type === 'shutdown' || msg?.type === 'exit_for_restart')
314
+ shutdown();
315
+ });
316
+ // Tells the launcher this worker is listening, so only once it is: the
317
+ // bot is up and the shutdown above is wired to the restart it may ask for.
318
+ initRestartWhenIdle(bot.api);
319
+ // Send periodic heartbeat so the launcher can detect stuck workers
320
+ const pp = parentPort;
321
+ const workerHeartbeat = setInterval(() => pp.postMessage({ type: 'heartbeat' }), 30_000);
322
+ workerHeartbeat.unref();
323
+ }
324
+ // Keep alive until the runner stops (crash or explicit stop).
325
+ //
326
+ // A 409 from getUpdates means something else is polling this same token —
327
+ // nearly always our own predecessor, whose long poll Telegram hasn't dropped
328
+ // yet during a restart. grammY's runner classes it as unrecoverable and stops
329
+ // (throwIfUnrecoverable in @grammyjs/runner), but the condition clears itself
330
+ // within a poll timeout. Exiting over it would tear down every live Claude
331
+ // session this bot owns, so put a fresh runner on the same bot instead and
332
+ // only give up if the conflict is still there after several tries — by then
333
+ // it's a real second instance, not an overlap.
334
+ const CONFLICT_RETRY_DELAYS_MS = [5_000, 15_000, 30_000, 60_000];
335
+ const isConflict = (err) => typeof err === 'object' && err !== null &&
336
+ err.error_code === 409;
337
+ for (let attempt = 0;; attempt++) {
338
+ try {
339
+ await runner.task();
340
+ return;
341
+ }
342
+ catch (err) {
343
+ if (shuttingDown || !isConflict(err))
344
+ throw err;
345
+ const delay = CONFLICT_RETRY_DELAYS_MS[attempt];
346
+ if (delay === undefined) {
347
+ console.error(`[Conflict] getUpdates still conflicting after ${CONFLICT_RETRY_DELAYS_MS.length} retries — another instance is polling this token for real`);
348
+ throw err;
349
+ }
350
+ 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})`);
351
+ replacingRunner = true;
352
+ await new Promise(resolve => setTimeout(resolve, delay));
353
+ if (shuttingDown)
354
+ return;
355
+ runner = run(bot);
356
+ replacingRunner = false;
357
+ }
358
+ }
359
+ }
360
+ main().catch((error) => {
361
+ // grammY puts the request URL, token and all, into some of its errors.
362
+ const detail = error instanceof Error ? (error.stack ?? error.message) : String(error);
363
+ console.error('Fatal error:', redactSecrets(detail));
364
+ allowSleep();
365
+ process.exit(1);
366
+ });
367
+ //# sourceMappingURL=index.js.map