telecoder 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/.env.example +375 -0
  2. package/CHANGELOG.md +1867 -0
  3. package/LICENSE +22 -0
  4. package/README.md +130 -2
  5. package/dist/audio/transcribe.js +41 -0
  6. package/dist/bin/mcp-server.js +363 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +573 -0
  10. package/dist/bot/command-catalog.js +263 -0
  11. package/dist/bot/deleted-threads.js +103 -0
  12. package/dist/bot/file-access.js +150 -0
  13. package/dist/bot/handlers/album.handler.js +128 -0
  14. package/dist/bot/handlers/branch.handler.js +1096 -0
  15. package/dist/bot/handlers/command/access.js +407 -0
  16. package/dist/bot/handlers/command/admin.js +803 -0
  17. package/dist/bot/handlers/command/all-view.js +33 -0
  18. package/dist/bot/handlers/command/auto-approve.js +138 -0
  19. package/dist/bot/handlers/command/background.js +37 -0
  20. package/dist/bot/handlers/command/botname.js +76 -0
  21. package/dist/bot/handlers/command/btw.js +175 -0
  22. package/dist/bot/handlers/command/cleanup.js +329 -0
  23. package/dist/bot/handlers/command/model.js +226 -0
  24. package/dist/bot/handlers/command/prefs-scope.js +362 -0
  25. package/dist/bot/handlers/command/project.js +458 -0
  26. package/dist/bot/handlers/command/resume.js +325 -0
  27. package/dist/bot/handlers/command/session.js +299 -0
  28. package/dist/bot/handlers/command/settings.js +657 -0
  29. package/dist/bot/handlers/command/shared.js +207 -0
  30. package/dist/bot/handlers/command/tasks.js +681 -0
  31. package/dist/bot/handlers/command/thread.js +128 -0
  32. package/dist/bot/handlers/command/topic-store.js +74 -0
  33. package/dist/bot/handlers/command/topic.js +27 -0
  34. package/dist/bot/handlers/command/usage.js +382 -0
  35. package/dist/bot/handlers/command-fallback.js +179 -0
  36. package/dist/bot/handlers/command.handler.js +446 -0
  37. package/dist/bot/handlers/loop.handler.js +389 -0
  38. package/dist/bot/handlers/media-fallback.js +126 -0
  39. package/dist/bot/handlers/message/replies.js +56 -0
  40. package/dist/bot/handlers/message/shared.js +95 -0
  41. package/dist/bot/handlers/message/turn-notify.js +135 -0
  42. package/dist/bot/handlers/message/turn-runner.js +56 -0
  43. package/dist/bot/handlers/message.handler.js +114 -0
  44. package/dist/bot/handlers/newbot.handler.js +230 -0
  45. package/dist/bot/handlers/photo.handler.js +286 -0
  46. package/dist/bot/handlers/prompts.handler.js +343 -0
  47. package/dist/bot/handlers/running-note.js +44 -0
  48. package/dist/bot/handlers/session-guard.js +78 -0
  49. package/dist/bot/handlers/suggestion.handler.js +84 -0
  50. package/dist/bot/handlers/tree.handler.js +480 -0
  51. package/dist/bot/handlers/view.js +41 -0
  52. package/dist/bot/handlers/voice.handler.js +147 -0
  53. package/dist/bot/kept-threads.js +51 -0
  54. package/dist/bot/middleware/admin-only.js +49 -0
  55. package/dist/bot/middleware/album-collector.js +69 -0
  56. package/dist/bot/middleware/auth.middleware.js +122 -0
  57. package/dist/bot/middleware/group-mention.middleware.js +145 -0
  58. package/dist/bot/middleware/group-role.middleware.js +75 -0
  59. package/dist/bot/middleware/message-batcher.js +87 -0
  60. package/dist/bot/middleware/queued-messages.js +1082 -0
  61. package/dist/bot/middleware/stale-filter.js +9 -0
  62. package/dist/build-info.json +8 -0
  63. package/dist/claude/ask-user-form.js +517 -0
  64. package/dist/claude/ask-user.js +363 -0
  65. package/dist/claude/auto-approve.js +225 -0
  66. package/dist/claude/auto-topic-haiku.js +143 -0
  67. package/dist/claude/available-commands.js +156 -0
  68. package/dist/claude/background-hint.js +91 -0
  69. package/dist/claude/branch-tree.js +393 -0
  70. package/dist/claude/carry-over.js +25 -0
  71. package/dist/claude/ccr-shim.js +48 -0
  72. package/dist/claude/charter-judge.js +214 -0
  73. package/dist/claude/claude-auth.js +117 -0
  74. package/dist/claude/command-parser.js +206 -0
  75. package/dist/claude/cost-overlay-scraper.js +134 -0
  76. package/dist/claude/effort-level.js +5 -0
  77. package/dist/claude/enabled-plugins.js +52 -0
  78. package/dist/claude/in-flight-tracker.js +82 -0
  79. package/dist/claude/ipc-server.js +192 -0
  80. package/dist/claude/mcp-bridge.js +481 -0
  81. package/dist/claude/memory-guard.js +400 -0
  82. package/dist/claude/message-offsets.js +88 -0
  83. package/dist/claude/modal-relay.js +817 -0
  84. package/dist/claude/model-catalog.js +102 -0
  85. package/dist/claude/monitor-relay.js +712 -0
  86. package/dist/claude/native-commands.js +40 -0
  87. package/dist/claude/pending-branches.js +93 -0
  88. package/dist/claude/pending-suggestions.js +50 -0
  89. package/dist/claude/permission-gate.js +338 -0
  90. package/dist/claude/permission-mode.js +152 -0
  91. package/dist/claude/poll-user.js +51 -0
  92. package/dist/claude/prewarm.js +70 -0
  93. package/dist/claude/project-commands.js +69 -0
  94. package/dist/claude/prompt-hold.js +124 -0
  95. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  96. package/dist/claude/pty-idle-reaper.js +96 -0
  97. package/dist/claude/pty-provider.js +2499 -0
  98. package/dist/claude/pty-spawn-config.js +343 -0
  99. package/dist/claude/pty-stream.js +363 -0
  100. package/dist/claude/pty-watch.js +201 -0
  101. package/dist/claude/request-queue.js +107 -0
  102. package/dist/claude/rewind.js +111 -0
  103. package/dist/claude/scheduled-runner.js +89 -0
  104. package/dist/claude/scheduler.js +241 -0
  105. package/dist/claude/scope-guard.js +279 -0
  106. package/dist/claude/screen-marks.js +83 -0
  107. package/dist/claude/screen-render.js +96 -0
  108. package/dist/claude/secret-request.js +576 -0
  109. package/dist/claude/session-history.js +288 -0
  110. package/dist/claude/session-jsonl.js +1067 -0
  111. package/dist/claude/session-manager.js +216 -0
  112. package/dist/claude/session-move.js +70 -0
  113. package/dist/claude/session-scan.js +270 -0
  114. package/dist/claude/setup-token.js +285 -0
  115. package/dist/claude/shell-mode-gate.js +60 -0
  116. package/dist/claude/side-call-options.js +45 -0
  117. package/dist/claude/side-question.js +252 -0
  118. package/dist/claude/stage-images.js +62 -0
  119. package/dist/claude/subagent-tools.js +12 -0
  120. package/dist/claude/synthetic-ctx.js +51 -0
  121. package/dist/claude/tasks-overlay-scraper.js +217 -0
  122. package/dist/claude/thread-judge-haiku.js +88 -0
  123. package/dist/claude/tip-scraper.js +77 -0
  124. package/dist/claude/tui-modal.js +746 -0
  125. package/dist/claude/tui-state.js +456 -0
  126. package/dist/claude/turn-end.js +105 -0
  127. package/dist/claude/turn-prose.js +64 -0
  128. package/dist/claude/typed-answer.js +104 -0
  129. package/dist/claude/update-banner-relay.js +70 -0
  130. package/dist/cli/commands/doctor.js +338 -0
  131. package/dist/cli/commands/help.js +34 -0
  132. package/dist/cli/commands/init.js +126 -0
  133. package/dist/cli/commands/service.js +710 -0
  134. package/dist/cli/commands/start.js +63 -0
  135. package/dist/cli/commands/version.js +11 -0
  136. package/dist/cli/commands/watch.js +322 -0
  137. package/dist/cli/dispatch.js +84 -0
  138. package/dist/cli/init/env-file.js +99 -0
  139. package/dist/cli/init/flow.js +705 -0
  140. package/dist/cli/init/prompter.js +124 -0
  141. package/dist/cli/init/telegram.js +120 -0
  142. package/dist/cli/service/render.js +212 -0
  143. package/dist/cli.js +18 -0
  144. package/dist/config-report.js +107 -0
  145. package/dist/config.js +525 -0
  146. package/dist/index.js +443 -0
  147. package/dist/launcher.js +960 -0
  148. package/dist/node-version-check.js +27 -0
  149. package/dist/providers/ccr-health.js +119 -0
  150. package/dist/providers/ccr-introspect.js +142 -0
  151. package/dist/providers/ccr-provider.js +59 -0
  152. package/dist/providers/claude-provider.js +10 -0
  153. package/dist/providers/prefs-sync.js +121 -0
  154. package/dist/providers/project-favorites.js +74 -0
  155. package/dist/providers/provider-router.js +128 -0
  156. package/dist/providers/provider-switch.js +91 -0
  157. package/dist/providers/spawn-settings.js +45 -0
  158. package/dist/providers/types.js +8 -0
  159. package/dist/providers/user-preferences.js +322 -0
  160. package/dist/restart-when-idle.js +173 -0
  161. package/dist/startup/auto-continue.js +67 -0
  162. package/dist/startup/auto-resume.js +161 -0
  163. package/dist/startup/notices.js +120 -0
  164. package/dist/startup/shared.js +44 -0
  165. package/dist/startup/verify-token.js +31 -0
  166. package/dist/telegram/access-request.js +153 -0
  167. package/dist/telegram/action-logger.js +522 -0
  168. package/dist/telegram/admin-mention.js +107 -0
  169. package/dist/telegram/background-activity-card.js +502 -0
  170. package/dist/telegram/botname-settings.js +282 -0
  171. package/dist/telegram/button-text.js +26 -0
  172. package/dist/telegram/client-options.js +26 -0
  173. package/dist/telegram/deduplication.js +33 -0
  174. package/dist/telegram/entities.js +295 -0
  175. package/dist/telegram/force-reply-tracker.js +96 -0
  176. package/dist/telegram/lettered-options.js +87 -0
  177. package/dist/telegram/markdown.js +362 -0
  178. package/dist/telegram/message-sender.js +1019 -0
  179. package/dist/telegram/prompt-label.js +148 -0
  180. package/dist/telegram/prompt-suggestion.js +54 -0
  181. package/dist/telegram/send.js +123 -0
  182. package/dist/telegram/streaming-turn.js +103 -0
  183. package/dist/telegram/suggestions-settings.js +30 -0
  184. package/dist/telegram/table-lists.js +56 -0
  185. package/dist/telegram/task-list.js +367 -0
  186. package/dist/telegram/task-tracker.js +128 -0
  187. package/dist/telegram/terminal-renderer.js +667 -0
  188. package/dist/telegram/thread-titles.js +262 -0
  189. package/dist/telegram/threads-setup.js +117 -0
  190. package/dist/utils/admins.js +143 -0
  191. package/dist/utils/agent-timer.js +55 -0
  192. package/dist/utils/atomic-write.js +24 -0
  193. package/dist/utils/bot-icon.js +248 -0
  194. package/dist/utils/bot-token.js +77 -0
  195. package/dist/utils/bounded-map.js +55 -0
  196. package/dist/utils/build-info.js +57 -0
  197. package/dist/utils/caffeinate.js +53 -0
  198. package/dist/utils/claude-env.js +53 -0
  199. package/dist/utils/claude-version.js +48 -0
  200. package/dist/utils/config-home.js +62 -0
  201. package/dist/utils/download.js +137 -0
  202. package/dist/utils/exit-codes.js +59 -0
  203. package/dist/utils/file-type.js +149 -0
  204. package/dist/utils/format.js +78 -0
  205. package/dist/utils/home-project.js +30 -0
  206. package/dist/utils/host-stall.js +51 -0
  207. package/dist/utils/id-list.js +44 -0
  208. package/dist/utils/idle-restart.js +92 -0
  209. package/dist/utils/install-mode.js +63 -0
  210. package/dist/utils/instance-config.js +148 -0
  211. package/dist/utils/instances.js +95 -0
  212. package/dist/utils/json-store.js +140 -0
  213. package/dist/utils/keyed-settings.js +62 -0
  214. package/dist/utils/legacy-env.js +35 -0
  215. package/dist/utils/memory-pressure.js +60 -0
  216. package/dist/utils/npm-version.js +134 -0
  217. package/dist/utils/prefs-relay.js +107 -0
  218. package/dist/utils/proc-children.js +102 -0
  219. package/dist/utils/resolve-bin.js +86 -0
  220. package/dist/utils/resolve-claude-bin.js +52 -0
  221. package/dist/utils/respawn-backoff.js +28 -0
  222. package/dist/utils/sanitize.js +91 -0
  223. package/dist/utils/session-key.js +37 -0
  224. package/dist/utils/stale-launcher.js +109 -0
  225. package/dist/utils/state-dir-migration.js +92 -0
  226. package/dist/utils/systemd.js +126 -0
  227. package/dist/utils/telegram-proxy.js +72 -0
  228. package/dist/utils/uploads-dir.js +27 -0
  229. package/dist/utils/user-roster.js +275 -0
  230. package/dist/utils/verbosity.js +118 -0
  231. package/dist/utils/version-check.js +166 -0
  232. package/dist/utils/workspace-guard.js +44 -0
  233. package/dist/worker-restart.js +141 -0
  234. package/instances.json.example +41 -0
  235. package/package.json +75 -4
@@ -0,0 +1,960 @@
1
+ /**
2
+ * Multi-instance launcher — runs multiple bot instances in a single process
3
+ * using worker threads. Each worker gets its own module scope + environment,
4
+ * so the existing global config singleton works without any changes.
5
+ *
6
+ * Usage:
7
+ * npm run start:multi # uses instances.json
8
+ * npm run start:multi -- --config my.json # custom config path
9
+ * npx tsx src/launcher.ts # dev mode
10
+ */
11
+ // First, so an old Node.js is told so before any other module loads.
12
+ import './node-version-check.js';
13
+ import { Worker, isMainThread } from 'worker_threads';
14
+ import { readFileSync, existsSync, mkdirSync, writeFileSync, watchFile } from 'fs';
15
+ import { config as loadEnv } from 'dotenv';
16
+ import * as path from 'path';
17
+ import { fileURLToPath } from 'url';
18
+ import { getStateDir } from './utils/json-store.js';
19
+ import { migrateLegacyStateDirAndLog } from './utils/state-dir-migration.js';
20
+ import { resolveInstances, diffInstances, botIdOf, InstancesConfigError, } from './utils/instance-config.js';
21
+ import { legacyEnv } from './utils/legacy-env.js';
22
+ import { planOutageRespawn, planRespawn } from './utils/respawn-backoff.js';
23
+ import { tickWasStalled, withinStallCooldown, shouldEscalateWedged } from './utils/host-stall.js';
24
+ import { fingerprintModuleGraph, launcherHasChanged } from './utils/stale-launcher.js';
25
+ import { PrefsRelay } from './utils/prefs-relay.js';
26
+ import { IdleRestart } from './utils/idle-restart.js';
27
+ import { configFile } from './utils/config-home.js';
28
+ import { PACKAGE_ROOT, isCheckout } from './utils/install-mode.js';
29
+ import { EXIT_CONFIG, EXIT_TELEGRAM_UNAVAILABLE, configErrorExitCode } from './utils/exit-codes.js';
30
+ const projectRoot = PACKAGE_ROOT;
31
+ // Heartbeat: workers ping the launcher periodically. If a worker goes silent
32
+ // for too long, the launcher force-terminates and respawns it.
33
+ const HEARTBEAT_CHECK_MS = 30_000;
34
+ const HEARTBEAT_TIMEOUT_MS = 90_000;
35
+ // If the monitor's own interval fires this much later than scheduled, the
36
+ // launcher's event loop was frozen (host stall) — every worker will look
37
+ // silent for that reason, so we skip the round instead of mass-restarting.
38
+ const HEARTBEAT_STALL_SLACK_MS = 30_000;
39
+ // When >1 worker is silent at once it's almost certainly the host, not the
40
+ // bots. Hold off this many consecutive checks before restarting them, so a
41
+ // transient stall doesn't trigger a fleet-wide thundering-herd respawn.
42
+ const HEARTBEAT_MASS_SILENCE_LIMIT = 3;
43
+ // How long a detected host stall keeps the monitor's hands off. The stall
44
+ // guard above only covers the tick that fired late; a freeze that starves the
45
+ // workers without delaying our own tick — or one that lifts a moment before
46
+ // the next tick — still leaves them looking silent through no fault of their
47
+ // own. Workers go quiet one at a time in that state, which slips past the
48
+ // mass-silence guard, so give the whole fleet a quiet period to check back in
49
+ // after any stall we saw.
50
+ const HEARTBEAT_STALL_COOLDOWN_MS = 180_000;
51
+ // While a wedged worker is being escalated, how often to re-check whether the
52
+ // host has recovered enough to tell "wedged" from "starved" apart, and how
53
+ // long to keep deferring before escalating anyway. A host that stalls every
54
+ // few minutes for hours would otherwise defer forever, leaving the instance
55
+ // offline for good — the outcome the escalation exists to prevent.
56
+ const RESTART_WEDGED_RECHECK_MS = 30_000;
57
+ const RESTART_WEDGED_MAX_DEFER_MS = 1_800_000;
58
+ // A worker asked to restart exits itself (see 'exit_for_restart' in index.ts),
59
+ // which unwinds cleanly. If it hasn't gone this long after being asked, fall
60
+ // back to terminating the thread.
61
+ const RESTART_GRACEFUL_EXIT_MS = 10_000;
62
+ // terminate() only takes effect when the worker next runs JS: a thread blocked
63
+ // in a synchronous native call ignores it indefinitely, so the exit event never
64
+ // fires and the respawn below never runs — that instance stays dead for good.
65
+ // Rather than leave a bot silently offline, take the launcher down and let the
66
+ // process manager bring every instance back. Comfortably longer than the
67
+ // longest legitimate block (/botrebuild's 120s build cap) so a slow-but-alive
68
+ // worker is never punished.
69
+ const RESTART_WEDGED_ESCALATION_MS = 180_000;
70
+ // An unplanned worker exit — a crash, or a fatal error the bot exited on — used
71
+ // to drop that instance for good. Bring it back instead, backing off so an
72
+ // instance that cannot start (a revoked token, say) doesn't spin. One delay per
73
+ // attempt; running out of delays is what "give up" means.
74
+ const CRASH_RESPAWN_DELAYS_MS = [1_000, 5_000, 15_000, 60_000];
75
+ // Crashes only count as a streak while they cluster. An instance that stayed up
76
+ // this long before dying starts its retry budget over, so two unrelated crashes
77
+ // days apart don't add up to a give-up.
78
+ const CRASH_STREAK_RESET_MS = 300_000;
79
+ // A bot that exits because Telegram didn't answer (EXIT_TELEGRAM_UNAVAILABLE)
80
+ // isn't crashing, and an outage can outlast every crash delay above: a few
81
+ // minutes of 502s once left a bot given up on until the launcher restarted.
82
+ // These respawns never give up; the last wait repeats until Telegram is back.
83
+ const OUTAGE_RESPAWN_DELAYS_MS = [5_000, 15_000, 60_000, 300_000];
84
+ // How often the launcher looks at instances.json for edits, and how long it
85
+ // lets an edit settle before reading it: an editor or a script can take more
86
+ // than one write to save a file.
87
+ const CONFIG_POLL_MS = 2_000;
88
+ const CONFIG_SETTLE_MS = 500;
89
+ // ---------------------------------------------------------------------------
90
+ // Load & expand instances config
91
+ // ---------------------------------------------------------------------------
92
+ function loadInstancesConfig(configPath) {
93
+ if (!existsSync(configPath)) {
94
+ console.error(`\u274c Instances config not found: ${configPath}`);
95
+ console.error(isCheckout()
96
+ ? ' Copy instances.json.example to instances.json and configure your bots.'
97
+ : ' Create it to run several bots (see instances.json.example in the TeleCoder repo), or run "telecoder start" without one for a single bot.');
98
+ process.exit(configErrorExitCode());
99
+ }
100
+ try {
101
+ return resolveInstances(readFileSync(configPath, 'utf-8'), (warning) => console.warn(`\u26a0\ufe0f ${warning}`));
102
+ }
103
+ catch (err) {
104
+ if (!(err instanceof InstancesConfigError))
105
+ throw err;
106
+ console.error(`\u274c ${path.basename(configPath)}: ${err.message}`);
107
+ process.exit(configErrorExitCode());
108
+ }
109
+ }
110
+ // ---------------------------------------------------------------------------
111
+ // Main
112
+ // ---------------------------------------------------------------------------
113
+ if (!isMainThread) {
114
+ console.error('launcher.ts must run on the main thread');
115
+ process.exit(1);
116
+ }
117
+ // Parse --config flag
118
+ const args = process.argv.slice(2);
119
+ const configFlagIdx = args.indexOf('--config');
120
+ const configPath = configFlagIdx !== -1 && args[configFlagIdx + 1]
121
+ ? path.resolve(args[configFlagIdx + 1])
122
+ : configFile('instances.json');
123
+ // Load base .env so all env vars are available as defaults
124
+ const envPath = legacyEnv('ENV_PATH') || configFile('.env');
125
+ loadEnv({ path: envPath });
126
+ // Before any worker exists to be reading or writing the state directory.
127
+ migrateLegacyStateDirAndLog('Launcher');
128
+ // Kept up to date with instances.json while the launcher runs: see "Live
129
+ // instances.json" below. Mutated in place, never reassigned.
130
+ const instances = loadInstancesConfig(configPath);
131
+ console.log(`\ud83d\ude80 Launching ${instances.length} bot instance(s)...`);
132
+ // Resolve the worker entry point (compiled JS, or tsx for dev in a checkout —
133
+ // a package install has no src/ and no tsx, only dist/)
134
+ const workerEntry = !isCheckout() || existsSync(path.join(projectRoot, 'dist', 'index.js'))
135
+ ? path.join(projectRoot, 'dist', 'index.js')
136
+ : path.join(projectRoot, 'src', 'index.ts');
137
+ const isTsx = workerEntry.endsWith('.ts');
138
+ // The launcher's own code, as it was when this process loaded it. A rebuild
139
+ // replaces the file on disk and respawns every worker off the new one, but
140
+ // nothing can replace what this process is already running — so this value is
141
+ // taken once and never refreshed, and a later build that disagrees with it is
142
+ // a build the launcher hasn't picked up.
143
+ const launcherEntry = fileURLToPath(import.meta.url);
144
+ const launcherCodeAtStartup = fingerprintModuleGraph(launcherEntry);
145
+ const workers = new Map();
146
+ const pendingRestarts = new Set();
147
+ const lastHeartbeat = new Map();
148
+ // Per-worker "start restarting this one" callbacks, owned by spawnWorker so the
149
+ // exit/backstop bookkeeping stays with the worker it belongs to. Every restart
150
+ // path (self, sibling, all, missed heartbeat) goes through these rather than
151
+ // calling terminate() directly.
152
+ const restarters = new Map();
153
+ // Consecutive unplanned exits per instance, used to pick a backoff delay and to
154
+ // decide when to stop trying. Reset by a planned restart or by an instance that
155
+ // stayed up longer than CRASH_STREAK_RESET_MS.
156
+ const crashStreaks = new Map();
157
+ // The same for exits on a Telegram outage, which only pick a delay.
158
+ const outageStreaks = new Map();
159
+ // Instances waiting out a respawn backoff. They have no entry in `workers`
160
+ // during the gap, so without this the "everything's gone" check below would
161
+ // fire mid-backoff and take the launcher down with it.
162
+ const respawning = new Set();
163
+ // Set once a shutdown signal arrives. Workers exiting after that are supposed
164
+ // to be gone, so nothing should respawn them.
165
+ let shuttingDown = false;
166
+ // When the heartbeat monitor last caught its own event loop running late —
167
+ // proof the host froze. Both the monitor and the wedged-worker escalation
168
+ // consult it before concluding a worker is at fault.
169
+ let lastHostStallAt = 0;
170
+ /** How long ago the host was last seen frozen. Infinity if we've never seen it. */
171
+ function hostStalledAgoMs() {
172
+ return lastHostStallAt === 0 ? Infinity : Date.now() - lastHostStallAt;
173
+ }
174
+ function restartWorker(name) {
175
+ const begin = restarters.get(name);
176
+ if (!begin) {
177
+ console.warn(`[Launcher] restart requested for ${name} but it has no live worker — skipping`);
178
+ return;
179
+ }
180
+ begin();
181
+ }
182
+ function scheduleRespawn(inst, delayMs) {
183
+ if (shuttingDown)
184
+ return;
185
+ respawning.add(inst.name);
186
+ setTimeout(() => {
187
+ respawning.delete(inst.name);
188
+ if (shuttingDown)
189
+ return;
190
+ // instances.json may have changed while this one was down. Bring the bot
191
+ // back as the file has it now, or not at all if it was taken out.
192
+ const current = configuredEntryFor(inst);
193
+ if (!current) {
194
+ console.log(`[Launcher] ${inst.name} is no longer in ${path.basename(configPath)} — not bringing it back`);
195
+ releaseName(inst.name);
196
+ shutdownIfNothingLeft(0);
197
+ return;
198
+ }
199
+ const renamed = current.name !== inst.name;
200
+ if (startWhenNameIsFree(current)) {
201
+ console.log(`[Launcher] ✓ ${current.name} respawned${renamed ? ` (was ${inst.name})` : ''}`);
202
+ }
203
+ else {
204
+ console.log(`[Launcher] ${current.name} (was ${inst.name}) will start once its new name is free`);
205
+ }
206
+ if (renamed)
207
+ releaseName(inst.name);
208
+ }, delayMs);
209
+ }
210
+ /** The bot's entry in instances.json as it reads now, matched by bot id. */
211
+ function configuredEntryFor(inst) {
212
+ const id = botIdOf(inst.token);
213
+ return instances.find((i) => botIdOf(i.token) === id);
214
+ }
215
+ // Which bot each live worker runs, by worker name. Names move between bots when
216
+ // instances.json is edited, so "is there a worker called X" doesn't answer "is
217
+ // this bot running".
218
+ const workerBotIds = new Map();
219
+ function isRunning(inst) {
220
+ return workerBotIds.get(inst.name) === botIdOf(inst.token);
221
+ }
222
+ // Bots waiting to start under a name another worker still holds, keyed by that
223
+ // name. This is how a bot takes over the name of one on its way out: a bot
224
+ // renamed in the same edit that takes another one out, say, or several
225
+ // renumbered at once when a bot is taken out of the middle of a `tokens` list.
226
+ const waitingForName = new Map();
227
+ function isWaiting(inst) {
228
+ const id = botIdOf(inst.token);
229
+ return [...waitingForName.values()].some((w) => botIdOf(w.token) === id);
230
+ }
231
+ /** Start `inst` now if its name is free, or as soon as it is. True if it started now. */
232
+ function startWhenNameIsFree(inst) {
233
+ // Whatever it was waiting for before, this is the start it gets.
234
+ const id = botIdOf(inst.token);
235
+ for (const [name, w] of waitingForName)
236
+ if (botIdOf(w.token) === id)
237
+ waitingForName.delete(name);
238
+ if (workers.has(inst.name) || respawning.has(inst.name)) {
239
+ waitingForName.set(inst.name, inst);
240
+ return false;
241
+ }
242
+ spawnWorker(inst);
243
+ return true;
244
+ }
245
+ /** A worker has given up `name` for good: start whoever was waiting for it. */
246
+ function releaseName(name) {
247
+ const waiting = waitingForName.get(name);
248
+ if (!waiting)
249
+ return;
250
+ waitingForName.delete(name);
251
+ if (shuttingDown)
252
+ return;
253
+ // The file may have moved on while it waited: start the bot as it reads now,
254
+ // under whatever name that is, or not at all if it was taken out.
255
+ const current = configuredEntryFor(waiting);
256
+ if (current && startWhenNameIsFree(current))
257
+ console.log(`[Launcher] ✓ ${current.name} started`);
258
+ }
259
+ function shutdownIfNothingLeft(code) {
260
+ if (workers.size > 0 || respawning.size > 0)
261
+ return;
262
+ // Every worker fired its exit event, so no thread is left to block teardown
263
+ // and a plain exit is safe here — unlike hardExit()'s case below.
264
+ console.log('All workers exited. Shutting down launcher.');
265
+ process.exit(code ?? 0);
266
+ }
267
+ // process.exit() is not an escape hatch from a wedged worker. Node's teardown
268
+ // joins the worker threads on the way out, so the very thread stuck in a native
269
+ // call that defeated terminate() also blocks the exit: the process stops
270
+ // logging, never dies, and the process manager goes on reporting it healthy.
271
+ // SIGKILL is handled by the kernel and cannot be blocked by anything in-process.
272
+ // The brief delay is only to give the reason a chance to reach the log.
273
+ function hardExit() {
274
+ setTimeout(() => process.kill(process.pid, 'SIGKILL'), 250);
275
+ }
276
+ // ---------------------------------------------------------------------------
277
+ // Preference broadcasts
278
+ //
279
+ // One bot's /model or /effort, applied to the rest on request. The launcher is
280
+ // only a relay: it forwards the change to every other live worker, collects
281
+ // what each did with it and hands the summary back to whoever asked, so the
282
+ // confirmation in Telegram names the bots that actually took the change rather
283
+ // than the ones that were merely configured. See providers/prefs-sync.ts for
284
+ // both ends, and utils/prefs-relay.ts for the bookkeeping in between.
285
+ // ---------------------------------------------------------------------------
286
+ const prefsRelay = new PrefsRelay();
287
+ // Shorter than the requesting worker's own timeout, so a silent sibling costs
288
+ // it a partial answer rather than no answer at all.
289
+ const PREFS_BROADCAST_TIMEOUT_MS = 3500;
290
+ // Mirrors getReloadMarkerPathForBotId in src/config.ts. We can't import config
291
+ // here because the launcher process has no TELEGRAM_BOT_TOKEN env var (only
292
+ // workers do), and config.ts validates it at import time.
293
+ const STATE_DIR = getStateDir();
294
+ function writeReloadMarkerForToken(token, instanceName) {
295
+ let botId = '';
296
+ try {
297
+ botId = token.split(':')[0];
298
+ if (!botId) {
299
+ console.warn(`[Launcher] writeReloadMarkerForToken (${instanceName ?? '?'}) called with malformed token (no colon) — skipping`);
300
+ return;
301
+ }
302
+ const markerPath = path.join(STATE_DIR, `pending-reload-${botId}.json`);
303
+ mkdirSync(STATE_DIR, { recursive: true });
304
+ writeFileSync(markerPath, JSON.stringify({ timestamp: new Date().toISOString() }));
305
+ console.log(`[Launcher] Wrote reload marker for ${instanceName ?? botId} (botId=${botId}) at ${markerPath}`);
306
+ }
307
+ catch (err) {
308
+ console.error(`[Launcher] Failed to write reload marker for ${instanceName ?? (botId || '?')}:`, err);
309
+ }
310
+ }
311
+ // ---------------------------------------------------------------------------
312
+ // Restarting when idle
313
+ //
314
+ // /botrebuild's "when idle" option. Every live worker is told to drain; each
315
+ // says what it is still finishing until it has nothing left, and is restarted
316
+ // then, on its own schedule rather than the slowest one's. The tally goes back
317
+ // to the bot that asked, as edits to one message. See src/restart-when-idle.ts
318
+ // for the workers' end and utils/idle-restart.ts for the tally.
319
+ // ---------------------------------------------------------------------------
320
+ let idleRestart = null;
321
+ // Workers that have said they're listening. One still starting up has no
322
+ // handler for these messages yet, so they wait in its outbox until it does —
323
+ // and the status message is often edited by an incarnation of the asking bot
324
+ // that didn't exist when the edit was made, because that bot restarted first.
325
+ const readyWorkers = new Set();
326
+ const outboxes = new Map();
327
+ function sendWhenReady(name, msg) {
328
+ const worker = workers.get(name);
329
+ if (worker && readyWorkers.has(name)) {
330
+ try {
331
+ worker.postMessage(msg);
332
+ return;
333
+ }
334
+ catch (err) {
335
+ console.warn(`[Launcher] Could not send ${msg.type} to ${name}: ${err instanceof Error ? err.message : err}`);
336
+ }
337
+ }
338
+ // Only the latest edit of a message is worth making.
339
+ const queued = (outboxes.get(name) ?? []).filter((m) => {
340
+ const q = m;
341
+ return !(msg.type === 'drain_render' && q.type === 'drain_render' && q.messageId === msg.messageId);
342
+ });
343
+ queued.push(msg);
344
+ outboxes.set(name, queued);
345
+ }
346
+ function flushOutbox(name) {
347
+ const queued = outboxes.get(name);
348
+ outboxes.delete(name);
349
+ for (const msg of queued ?? [])
350
+ sendWhenReady(name, msg);
351
+ }
352
+ // Instances report within a couple of seconds of each other, and each report
353
+ // would be its own edit of the same message; Telegram rate-limits those.
354
+ const IDLE_RESTART_RENDER_DELAY_MS = 1500;
355
+ let renderTimer = null;
356
+ function renderIdleRestart(tally, opts = {}) {
357
+ const deliver = () => {
358
+ const { text, buttons } = tally.render();
359
+ const { instance, chatId, messageId } = tally.origin;
360
+ sendWhenReady(instance, { type: 'drain_render', chatId, messageId, text, buttons });
361
+ };
362
+ if (opts.now) {
363
+ deliver();
364
+ return;
365
+ }
366
+ if (renderTimer)
367
+ return;
368
+ renderTimer = setTimeout(() => {
369
+ renderTimer = null;
370
+ // The tally may have finished, or been replaced, since this was asked
371
+ // for — whatever it says now is what the message should say.
372
+ if (idleRestart)
373
+ renderIdleRestart(idleRestart, { now: true });
374
+ }, IDLE_RESTART_RENDER_DELAY_MS);
375
+ }
376
+ function finishIdleRestartIfDone(tally) {
377
+ if (!tally.isFinished())
378
+ return;
379
+ if (idleRestart === tally)
380
+ idleRestart = null;
381
+ renderIdleRestart(tally, { now: true });
382
+ }
383
+ // Whether the instances an idle restart restarts should restore their sessions.
384
+ let idleRestartAutoResume = false;
385
+ function restartForIdleRestart(name) {
386
+ const inst = instances.find((i) => i.name === name);
387
+ if (idleRestartAutoResume && inst)
388
+ writeReloadMarkerForToken(inst.token, inst.name);
389
+ restartWorker(name);
390
+ }
391
+ function buildWorkerEnv(inst) {
392
+ const env = {};
393
+ // Copy base process.env (includes .env values)
394
+ for (const [k, v] of Object.entries(process.env)) {
395
+ if (v !== undefined)
396
+ env[k] = v;
397
+ }
398
+ // Apply instance overrides
399
+ if (inst.overrides) {
400
+ Object.assign(env, inst.overrides);
401
+ }
402
+ // Always set token and bot name
403
+ env.TELEGRAM_BOT_TOKEN = inst.token;
404
+ env.BOT_NAME = inst.name;
405
+ // Tag for log prefixing inside the worker
406
+ env.TELECODER_INSTANCE_NAME = inst.name;
407
+ // Workers use this to enumerate sibling bots (e.g. for /branch). Mirrors the
408
+ // launcher's own --config resolution so a custom config path still works.
409
+ env.TELECODER_INSTANCES_CONFIG = configPath;
410
+ // A pre-rename value inherited from the parent env would otherwise win the
411
+ // fallback in utils/legacy-env.ts and point workers at a stale config.
412
+ delete env.CLAUDEGRAM_INSTANCES_CONFIG;
413
+ delete env.CLAUDEGRAM_INSTANCE_NAME;
414
+ return env;
415
+ }
416
+ function spawnWorker(inst) {
417
+ const env = buildWorkerEnv(inst);
418
+ const workerOptions = {
419
+ env,
420
+ ...(isTsx ? {
421
+ // When running .ts files directly, use tsx as the loader
422
+ execArgv: ['--import', 'tsx'],
423
+ } : {}),
424
+ };
425
+ const worker = new Worker(workerEntry, workerOptions);
426
+ const spawnedAt = Date.now();
427
+ workerBotIds.set(inst.name, botIdOf(inst.token));
428
+ readyWorkers.delete(inst.name);
429
+ lastHeartbeat.set(inst.name, Date.now());
430
+ let exited = false;
431
+ let restartBegun = false;
432
+ // Drive this worker through a restart. Asking it to exit itself is the only
433
+ // path that reliably works — terminate() is powerless against a thread stuck
434
+ // in native code — so that comes first, with terminate() as a backstop and a
435
+ // launcher-level bail-out if even that doesn't land.
436
+ const beginRestart = () => {
437
+ if (restartBegun || exited)
438
+ return;
439
+ restartBegun = true;
440
+ pendingRestarts.add(inst.name);
441
+ // On its way out: an edit sent now could die with it, so it waits for
442
+ // the successor instead.
443
+ readyWorkers.delete(inst.name);
444
+ try {
445
+ worker.postMessage({ type: 'exit_for_restart' });
446
+ }
447
+ catch (err) {
448
+ console.warn(`[Launcher] Could not ask ${inst.name} to exit (${err instanceof Error ? err.message : err}) — terminating instead`);
449
+ worker.terminate();
450
+ }
451
+ setTimeout(() => {
452
+ if (exited)
453
+ return;
454
+ console.warn(`[Launcher] ${inst.name} did not exit within ${Math.round(RESTART_GRACEFUL_EXIT_MS / 1000)}s of being asked — terminating the thread`);
455
+ worker.terminate();
456
+ }, RESTART_GRACEFUL_EXIT_MS).unref();
457
+ // A thread starved of CPU looks exactly like one wedged in native code:
458
+ // both ignore terminate() and neither reaches the exit handler. Taking the
459
+ // whole fleet down is the right answer only for the wedged one, so hold
460
+ // off while the host is still frozen and re-check until it recovers.
461
+ const restartAskedAt = Date.now();
462
+ const escalationDueAt = restartAskedAt + RESTART_WEDGED_ESCALATION_MS;
463
+ const escalateIfWedged = () => {
464
+ if (exited)
465
+ return;
466
+ const stalledAgo = hostStalledAgoMs();
467
+ const aliveFor = Math.round((Date.now() - restartAskedAt) / 1000);
468
+ const escalate = shouldEscalateWedged({
469
+ stalledAgoMs: stalledAgo,
470
+ cooldownMs: HEARTBEAT_STALL_COOLDOWN_MS,
471
+ deferredForMs: Date.now() - escalationDueAt,
472
+ maxDeferMs: RESTART_WEDGED_MAX_DEFER_MS,
473
+ });
474
+ if (!escalate) {
475
+ console.warn(`[Launcher] ${inst.name} hasn't exited ${aliveFor}s after being asked to restart, but the host stalled ${Math.round(stalledAgo / 1000)}s ago — a starved thread is indistinguishable from a wedged one, so re-checking in ${Math.round(RESTART_WEDGED_RECHECK_MS / 1000)}s instead of killing the launcher`);
476
+ setTimeout(escalateIfWedged, RESTART_WEDGED_RECHECK_MS).unref();
477
+ return;
478
+ }
479
+ console.error(`[Launcher] ${inst.name} still alive ${aliveFor}s after a restart was requested — the thread is wedged in native code and terminate() cannot reach it. Killing the launcher so the process manager restarts every instance.`);
480
+ hardExit();
481
+ };
482
+ setTimeout(escalateIfWedged, RESTART_WEDGED_ESCALATION_MS).unref();
483
+ };
484
+ restarters.set(inst.name, beginRestart);
485
+ worker.on('message', (msg) => {
486
+ if (msg?.type === 'heartbeat') {
487
+ lastHeartbeat.set(inst.name, Date.now());
488
+ }
489
+ else if (msg?.type === 'ready') {
490
+ readyWorkers.add(inst.name);
491
+ flushOutbox(inst.name);
492
+ }
493
+ else if (msg?.type === 'restart_all_when_idle') {
494
+ if (msg.chatId === undefined || msg.messageId === undefined)
495
+ return;
496
+ const names = [...workers.keys()];
497
+ console.log(`[Launcher] ${inst.name} requested a restart of ALL instances once each is idle${msg.autoResume ? ' (with auto-resume)' : ''} — ${names.length} live`);
498
+ // A newer build makes the older wait moot, but not its instances: the
499
+ // ones it was still waiting on are waiting on this one now, and so is
500
+ // everyone it already restarted, which is running the older build.
501
+ if (idleRestart) {
502
+ idleRestart.supersede();
503
+ renderIdleRestart(idleRestart, { now: true });
504
+ }
505
+ idleRestartAutoResume = !!msg.autoResume;
506
+ idleRestart = new IdleRestart({ instance: inst.name, chatId: msg.chatId, messageId: msg.messageId, note: msg.note || undefined }, names);
507
+ for (const name of names)
508
+ sendWhenReady(name, { type: 'drain' });
509
+ worker.postMessage({ type: 'restart_all_when_idle_result', names });
510
+ renderIdleRestart(idleRestart, { now: true });
511
+ }
512
+ else if (msg?.type === 'drain_busy') {
513
+ if (idleRestart?.busy(inst.name, msg.detail ?? ''))
514
+ renderIdleRestart(idleRestart);
515
+ }
516
+ else if (msg?.type === 'drain_idle') {
517
+ const tally = idleRestart;
518
+ if (!tally?.isWaitingOn(inst.name)) {
519
+ // Cancelled, or superseded and already restarted, while this was on
520
+ // its way. Nothing is waiting for it any more.
521
+ worker.postMessage({ type: 'drain_cancel' });
522
+ return;
523
+ }
524
+ console.log(`[Launcher] ${inst.name} has nothing left to finish — restarting it`);
525
+ tally.restarting(inst.name);
526
+ restartForIdleRestart(inst.name);
527
+ renderIdleRestart(tally);
528
+ finishIdleRestartIfDone(tally);
529
+ }
530
+ else if (msg?.type === 'idle_restart_force' || msg?.type === 'idle_restart_cancel') {
531
+ const tally = idleRestart;
532
+ worker.postMessage({ type: 'drain_control_result', found: !!tally });
533
+ if (!tally)
534
+ return;
535
+ if (msg.type === 'idle_restart_force') {
536
+ const left = tally.waitingOn();
537
+ console.log(`[Launcher] ${inst.name} asked to restart the rest now: ${left.join(', ')}`);
538
+ let delay = 0;
539
+ for (const name of left) {
540
+ tally.restarting(name, { forced: true });
541
+ // Staggered for the same reason restart_all is.
542
+ setTimeout(() => restartForIdleRestart(name), delay);
543
+ delay += 200;
544
+ }
545
+ }
546
+ else {
547
+ const left = tally.cancel();
548
+ console.log(`[Launcher] ${inst.name} cancelled the pending restart${left.length ? ` — still on the old build: ${left.join(', ')}` : ''}`);
549
+ for (const name of left)
550
+ sendWhenReady(name, { type: 'drain_cancel' });
551
+ }
552
+ finishIdleRestartIfDone(tally);
553
+ }
554
+ else if (msg?.type === 'restart') {
555
+ // Self-restart: this worker wants to be restarted
556
+ console.log(`[Launcher] ${inst.name} requested self-restart`);
557
+ beginRestart();
558
+ }
559
+ else if (msg?.type === 'restart_sibling') {
560
+ // Cross-bot restart: restart a different worker by name
561
+ const targetName = msg.name;
562
+ if (!targetName) {
563
+ worker.postMessage({ type: 'restart_sibling_result', success: false, name: targetName, reason: 'no name provided' });
564
+ return;
565
+ }
566
+ const restartTarget = (resolvedName) => {
567
+ const targetInst = instances.find(i => i.name === resolvedName);
568
+ if (msg.autoResume && targetInst) {
569
+ writeReloadMarkerForToken(targetInst.token, targetInst.name);
570
+ }
571
+ restartWorker(resolvedName);
572
+ };
573
+ const sibling = workers.get(targetName);
574
+ if (!sibling) {
575
+ // Try case-insensitive match
576
+ const match = [...workers.keys()].find(k => k.toLowerCase() === targetName.toLowerCase());
577
+ if (match) {
578
+ console.log(`[Launcher] ${inst.name} requested restart of sibling ${match}`);
579
+ restartTarget(match);
580
+ worker.postMessage({ type: 'restart_sibling_result', success: true, name: match });
581
+ }
582
+ else {
583
+ const available = [...workers.keys()].filter(k => k !== inst.name);
584
+ worker.postMessage({
585
+ type: 'restart_sibling_result', success: false, name: targetName,
586
+ reason: available.length ? `not found (available: ${available.join(', ')})` : 'no other instances running',
587
+ });
588
+ }
589
+ }
590
+ else if (targetName === inst.name) {
591
+ worker.postMessage({ type: 'restart_sibling_result', success: false, name: targetName, reason: 'use /botrestart without arguments to restart yourself' });
592
+ }
593
+ else {
594
+ console.log(`[Launcher] ${inst.name} requested restart of sibling ${targetName}`);
595
+ restartTarget(targetName);
596
+ worker.postMessage({ type: 'restart_sibling_result', success: true, name: targetName });
597
+ }
598
+ }
599
+ else if (msg?.type === 'launcher_stale') {
600
+ // Answered from disk each time it's asked: the question only comes up
601
+ // right after a build, and that build is what we're comparing against.
602
+ const stale = launcherHasChanged(launcherCodeAtStartup, fingerprintModuleGraph(launcherEntry));
603
+ if (stale) {
604
+ console.warn(`[Launcher] ${inst.name} rebuilt the launcher's own code — this process keeps running the copy it started with until it is restarted`);
605
+ }
606
+ worker.postMessage({ type: 'launcher_stale_result', stale });
607
+ }
608
+ else if (msg?.type === 'prefs_broadcast') {
609
+ const requestId = msg.requestId;
610
+ if (!requestId)
611
+ return;
612
+ const liveNames = new Set(workers.keys());
613
+ const unreachable = instances.filter(i => !liveNames.has(i.name)).map(i => i.name);
614
+ const delivered = [];
615
+ for (const [name, sibling] of workers) {
616
+ if (name === inst.name)
617
+ continue;
618
+ try {
619
+ sibling.postMessage({ type: 'prefs_apply', requestId, change: msg.change });
620
+ delivered.push(name);
621
+ }
622
+ catch (err) {
623
+ console.warn(`[Launcher] Could not relay preference change to ${name}: ${err instanceof Error ? err.message : err}`);
624
+ unreachable.push(name);
625
+ }
626
+ }
627
+ console.log(`[Launcher] ${inst.name} broadcast a preference change to ${delivered.length} sibling(s)${unreachable.length ? ` (${unreachable.length} unreachable)` : ''}`);
628
+ prefsRelay.begin(requestId, {
629
+ awaiting: delivered,
630
+ unreachable,
631
+ timeoutMs: PREFS_BROADCAST_TIMEOUT_MS,
632
+ onTimeout: (stillAwaiting) => {
633
+ console.warn(`[Launcher] prefs broadcast ${requestId} timed out waiting on: ${stillAwaiting.join(', ')}`);
634
+ },
635
+ onSettle: (summary) => {
636
+ try {
637
+ worker.postMessage({ type: 'prefs_broadcast_result', requestId, ...summary });
638
+ }
639
+ catch (err) {
640
+ console.warn(`[Launcher] Could not return prefs broadcast result to ${inst.name}: ${err instanceof Error ? err.message : err}`);
641
+ }
642
+ },
643
+ });
644
+ }
645
+ else if (msg?.type === 'prefs_apply_result') {
646
+ if (!msg.requestId)
647
+ return;
648
+ prefsRelay.record(msg.requestId, {
649
+ name: inst.name,
650
+ status: msg.status === 'applied' ? 'applied' : 'skipped',
651
+ reason: msg.reason,
652
+ busy: msg.busy,
653
+ });
654
+ }
655
+ else if (msg?.type === 'restart_all') {
656
+ console.log(`[Launcher] ${inst.name} requested restart of ALL instances${msg.autoResume ? ' (with auto-resume)' : ''} — ${instances.length} configured, ${workers.size} live`);
657
+ const liveNames = new Set(workers.keys());
658
+ const missingFromWorkers = instances.filter(i => !liveNames.has(i.name)).map(i => i.name);
659
+ if (missingFromWorkers.length > 0) {
660
+ console.warn(`[Launcher] restart_all: configured instances with no live worker (won't be respawned by terminate): ${missingFromWorkers.join(', ')}`);
661
+ }
662
+ for (const i of instances) {
663
+ // Only instances we're about to restart get the flag. Setting it for one
664
+ // that has no worker leaves it stuck there with nothing to consume it,
665
+ // and the next exit of that instance — whenever it comes back — reads as
666
+ // planned, clearing its crash streak and skipping the backoff.
667
+ if (liveNames.has(i.name))
668
+ pendingRestarts.add(i.name);
669
+ // The marker still goes to everyone: an instance mid-backoff should
670
+ // auto-resume when it does come up.
671
+ if (msg.autoResume) {
672
+ writeReloadMarkerForToken(i.token, i.name);
673
+ }
674
+ }
675
+ // Stagger restarts to avoid port conflicts on respawn
676
+ let delay = 0;
677
+ for (const name of workers.keys()) {
678
+ const scheduledAt = delay;
679
+ setTimeout(() => {
680
+ console.log(`[Launcher] restart_all: restarting ${name} (scheduled +${scheduledAt}ms)`);
681
+ restartWorker(name);
682
+ }, delay);
683
+ delay += 200;
684
+ }
685
+ }
686
+ });
687
+ worker.on('error', (err) => {
688
+ console.error(`[${inst.name}] Worker error:`, err);
689
+ });
690
+ worker.on('exit', (code) => {
691
+ console.log(`[${inst.name}] Worker exited with code ${code}`);
692
+ exited = true;
693
+ lastHeartbeat.delete(inst.name);
694
+ readyWorkers.delete(inst.name);
695
+ // What was queued for this incarnation dies with it; an edit of the status
696
+ // message is still owed, and the next one can make it.
697
+ const owed = (outboxes.get(inst.name) ?? []).filter((m) => m.type === 'drain_render');
698
+ if (owed.length)
699
+ outboxes.set(inst.name, owed);
700
+ else
701
+ outboxes.delete(inst.name);
702
+ // An instance that went down on its own while it was being waited for
703
+ // comes back on the new build all the same.
704
+ if (idleRestart?.restarting(inst.name)) {
705
+ renderIdleRestart(idleRestart);
706
+ finishIdleRestartIfDone(idleRestart);
707
+ }
708
+ restarters.delete(inst.name);
709
+ // Drop it now, in every path: the heartbeat monitor keys off `workers`, and
710
+ // leaving a dead entry there makes it chase an instance that no longer has
711
+ // a restarter to drive.
712
+ workers.delete(inst.name);
713
+ workerBotIds.delete(inst.name);
714
+ // A dead worker will never answer a preference broadcast. Say so now
715
+ // rather than making the bot that asked wait out the timeout.
716
+ prefsRelay.abandonEverywhere(inst.name);
717
+ if (pendingRestarts.has(inst.name)) {
718
+ // Planned restart — respawn after a short delay
719
+ pendingRestarts.delete(inst.name);
720
+ crashStreaks.delete(inst.name);
721
+ outageStreaks.delete(inst.name);
722
+ console.log(`[Launcher] Respawning ${inst.name} in 1s...`);
723
+ scheduleRespawn(inst, 1000);
724
+ return;
725
+ }
726
+ // The bot stopped on its own configuration — a missing setting, or a
727
+ // token Telegram rejected — and has already said what is wrong, naming
728
+ // itself. Respawning would print the same thing four times over.
729
+ if (code === EXIT_CONFIG) {
730
+ crashStreaks.delete(inst.name);
731
+ outageStreaks.delete(inst.name);
732
+ console.error(`[Launcher] ${inst.name} stopped on a configuration problem (its message is above) — not restarting it. ` +
733
+ `Fix its entry in ${path.basename(configPath)} and it starts again; for a fix in .env, restart the launcher.`);
734
+ releaseName(inst.name);
735
+ // The last one standing went down on its config: a service unit should
736
+ // stand down too (RestartPreventExitStatus=), not start us into it again.
737
+ shutdownIfNothingLeft(configErrorExitCode());
738
+ return;
739
+ }
740
+ const aliveMs = Date.now() - spawnedAt;
741
+ // Telegram didn't answer, and the bot has said how. Not a crash: try again
742
+ // for as long as the outage lasts, without touching the crash streak.
743
+ if (code === EXIT_TELEGRAM_UNAVAILABLE) {
744
+ const { attempts, delayMs } = planOutageRespawn({
745
+ aliveMs,
746
+ previousAttempts: outageStreaks.get(inst.name) ?? 0,
747
+ delays: OUTAGE_RESPAWN_DELAYS_MS,
748
+ streakResetMs: CRASH_STREAK_RESET_MS,
749
+ });
750
+ outageStreaks.set(inst.name, attempts);
751
+ console.warn(`[Launcher] ${inst.name} couldn't reach Telegram (its message is above) — trying again in ${Math.round(delayMs / 1000)}s (attempt ${attempts})`);
752
+ scheduleRespawn(inst, delayMs);
753
+ return;
754
+ }
755
+ outageStreaks.delete(inst.name);
756
+ // Unplanned exit. Whatever took it down — a fatal error, a 409 from a
757
+ // predecessor's long poll that hadn't been dropped yet — this bot is now
758
+ // silently offline and nothing else will notice, because the heartbeat
759
+ // monitor only watches instances that still have a worker. Respawn it.
760
+ const { streak, delayMs: delay } = planRespawn({
761
+ aliveMs,
762
+ previousStreak: crashStreaks.get(inst.name) ?? 0,
763
+ delays: CRASH_RESPAWN_DELAYS_MS,
764
+ streakResetMs: CRASH_STREAK_RESET_MS,
765
+ });
766
+ crashStreaks.set(inst.name, streak);
767
+ if (delay === null) {
768
+ console.error(`[Launcher] ${inst.name} exited unexpectedly ${streak} times in a row — giving up on it (restart the launcher, or fix its entry in ${path.basename(configPath)}, to bring it back)`);
769
+ releaseName(inst.name);
770
+ shutdownIfNothingLeft(code);
771
+ return;
772
+ }
773
+ console.warn(`[Launcher] ${inst.name} exited unexpectedly (code ${code}) after ${Math.round(aliveMs / 1000)}s up — respawning in ${Math.round(delay / 1000)}s (attempt ${streak}/${CRASH_RESPAWN_DELAYS_MS.length})`);
774
+ scheduleRespawn(inst, delay);
775
+ });
776
+ workers.set(inst.name, worker);
777
+ return worker;
778
+ }
779
+ // ---------------------------------------------------------------------------
780
+ // Spawn all instances
781
+ // ---------------------------------------------------------------------------
782
+ for (const inst of instances) {
783
+ spawnWorker(inst);
784
+ console.log(` \u2713 ${inst.name}`);
785
+ }
786
+ // ---------------------------------------------------------------------------
787
+ // Live instances.json
788
+ //
789
+ // Edits to instances.json take effect without restarting the launcher, bot by
790
+ // bot: one added to the file starts, one taken out stops, and one whose entry
791
+ // changed (a new token, name or setting) restarts on it and resumes its
792
+ // sessions. The rest carry on untouched. A file that can't be read, or that
793
+ // would leave no bots at all, is ignored until it's fixed, so a half-saved
794
+ // edit can't take everything down with it.
795
+ // ---------------------------------------------------------------------------
796
+ function applyConfigChange() {
797
+ if (shuttingDown)
798
+ return;
799
+ const file = path.basename(configPath);
800
+ let next;
801
+ try {
802
+ next = resolveInstances(readFileSync(configPath, 'utf-8'), (warning) => console.warn(`[Launcher] ${warning}`));
803
+ }
804
+ catch (err) {
805
+ const why = err instanceof Error ? err.message : String(err);
806
+ console.warn(`[Launcher] ${file} changed but can't be used (${why}) — leaving the running bots as they are`);
807
+ return;
808
+ }
809
+ const { added, removed, changed } = diffInstances(instances, next);
810
+ if (added.length === 0 && removed.length === 0 && changed.length === 0)
811
+ return;
812
+ instances.splice(0, instances.length, ...next);
813
+ // Departures first: they free the names arrivals may be taking over.
814
+ for (const inst of removed) {
815
+ console.log(`[Launcher] ${inst.name} was taken out of ${file} — stopping it`);
816
+ // Its respawn finds no entry for it and stands down. One mid-backoff or
817
+ // still waiting for a name stands down the same way when its turn comes.
818
+ if (isRunning(inst))
819
+ restartWorker(inst.name);
820
+ }
821
+ for (const { from, to } of changed) {
822
+ const renamed = to.name !== from.name ? ` as ${to.name}` : '';
823
+ if (isRunning(from)) {
824
+ console.log(`[Launcher] ${from.name}'s entry in ${file} changed — restarting it${renamed}`);
825
+ writeReloadMarkerForToken(to.token, to.name);
826
+ restartWorker(from.name);
827
+ }
828
+ else if (respawning.has(from.name) || isWaiting(from)) {
829
+ // Comes back as the file reads now when its turn comes.
830
+ console.log(`[Launcher] ${from.name}'s entry in ${file} changed — it starts that way once it's back`);
831
+ }
832
+ else {
833
+ // Given up on after crashing: a fixed entry is a reason to try again.
834
+ console.log(`[Launcher] ${from.name}'s entry in ${file} changed — starting it again${renamed}`);
835
+ crashStreaks.delete(from.name);
836
+ crashStreaks.delete(to.name);
837
+ outageStreaks.delete(from.name);
838
+ outageStreaks.delete(to.name);
839
+ startWhenNameIsFree(to);
840
+ }
841
+ }
842
+ for (const inst of added) {
843
+ crashStreaks.delete(inst.name);
844
+ outageStreaks.delete(inst.name);
845
+ const now = startWhenNameIsFree(inst);
846
+ console.log(`[Launcher] ${inst.name} was added to ${file} — ${now ? 'starting it' : 'it starts once its name is free'}`);
847
+ }
848
+ }
849
+ let configSettleTimer = null;
850
+ watchFile(configPath, { interval: CONFIG_POLL_MS, persistent: false }, (curr, prev) => {
851
+ if (curr.mtimeMs === prev.mtimeMs && curr.size === prev.size && curr.ino === prev.ino)
852
+ return;
853
+ if (configSettleTimer)
854
+ clearTimeout(configSettleTimer);
855
+ configSettleTimer = setTimeout(() => {
856
+ configSettleTimer = null;
857
+ applyConfigChange();
858
+ }, CONFIG_SETTLE_MS);
859
+ });
860
+ // ---------------------------------------------------------------------------
861
+ // Heartbeat monitor — detect stuck workers and auto-respawn them
862
+ // ---------------------------------------------------------------------------
863
+ let lastHeartbeatCheck = Date.now();
864
+ let consecutiveMassSilence = 0;
865
+ setInterval(() => {
866
+ const now = Date.now();
867
+ const sinceLastCheck = now - lastHeartbeatCheck;
868
+ lastHeartbeatCheck = now;
869
+ // Guard 1 — self-stall: if our own interval fired far later than scheduled,
870
+ // the launcher's event loop was frozen (host memory/CPU stall). Every
871
+ // worker's "silence" is an artifact of that freeze, not a hung worker, and
872
+ // their lastHeartbeat baselines haven't had a fair chance to update. Skip
873
+ // this round and re-baseline so workers get a grace tick to check back in.
874
+ if (tickWasStalled({ sinceLastTickMs: sinceLastCheck, intervalMs: HEARTBEAT_CHECK_MS, slackMs: HEARTBEAT_STALL_SLACK_MS })) {
875
+ console.warn(`[Launcher] heartbeat monitor stalled for ${Math.round(sinceLastCheck / 1000)}s (expected ${Math.round(HEARTBEAT_CHECK_MS / 1000)}s) — host was likely frozen; skipping this round to let workers recover`);
876
+ lastHostStallAt = now;
877
+ consecutiveMassSilence = 0;
878
+ return;
879
+ }
880
+ const silent = [];
881
+ for (const inst of instances) {
882
+ if (!workers.get(inst.name))
883
+ continue;
884
+ // A restart is already in flight for this one — it stopped beating because
885
+ // it's on its way out, and beginRestart() owns the escalation from here.
886
+ // Re-requesting every tick would just log the same line forever.
887
+ if (pendingRestarts.has(inst.name))
888
+ continue;
889
+ const last = lastHeartbeat.get(inst.name) ?? 0;
890
+ if (now - last > HEARTBEAT_TIMEOUT_MS)
891
+ silent.push(inst.name);
892
+ }
893
+ if (silent.length === 0) {
894
+ consecutiveMassSilence = 0;
895
+ return;
896
+ }
897
+ // Guard 1b — stall cooldown: our own loop ran on time, but the host was
898
+ // frozen recently enough that this silence is far more likely to be the
899
+ // tail of that freeze than a hung bot. Restarting now would kill a live
900
+ // session to fix a problem the worker doesn't have.
901
+ const stalledAgo = hostStalledAgoMs();
902
+ if (withinStallCooldown({ stalledAgoMs: stalledAgo, cooldownMs: HEARTBEAT_STALL_COOLDOWN_MS })) {
903
+ console.warn(`[Launcher] ${silent.length} worker(s) silent (${silent.join(', ')}) but the host stalled ${Math.round(stalledAgo / 1000)}s ago — holding off restarts for another ${Math.round((HEARTBEAT_STALL_COOLDOWN_MS - stalledAgo) / 1000)}s`);
904
+ // Ticks spent inside the cooldown aren't evidence of a hung fleet, so the
905
+ // mass-silence tally starts over once the host is trusted again.
906
+ consecutiveMassSilence = 0;
907
+ return;
908
+ }
909
+ // Guard 2 — mass silence: more than one worker silent in the same tick is
910
+ // almost always a host-level problem, not independent per-bot hangs.
911
+ // Restarting them all at once loses every session and dumps respawn load
912
+ // onto an already-struggling host. Hold off a few rounds first; only if it
913
+ // persists do we restart, and then staggered to avoid a thundering herd.
914
+ if (silent.length > 1) {
915
+ consecutiveMassSilence++;
916
+ if (consecutiveMassSilence < HEARTBEAT_MASS_SILENCE_LIMIT) {
917
+ console.error(`[Launcher] ${silent.length} workers silent simultaneously (${silent.join(', ')}) — likely a host-level stall (load/memory); holding off ${consecutiveMassSilence}/${HEARTBEAT_MASS_SILENCE_LIMIT} before restarting`);
918
+ return;
919
+ }
920
+ console.error(`[Launcher] ${silent.length} workers still silent after ${consecutiveMassSilence} checks — restarting them staggered`);
921
+ let delay = 0;
922
+ for (const name of silent) {
923
+ setTimeout(() => restartWorker(name), delay);
924
+ delay += 1000;
925
+ }
926
+ consecutiveMassSilence = 0;
927
+ return;
928
+ }
929
+ // Single worker silent — genuinely stuck, restart just that one.
930
+ consecutiveMassSilence = 0;
931
+ const name = silent[0];
932
+ const last = lastHeartbeat.get(name) ?? 0;
933
+ console.error(`[Launcher] ${name} missed heartbeat (${Math.round((now - last) / 1000)}s silent) — force-restarting`);
934
+ restartWorker(name);
935
+ }, HEARTBEAT_CHECK_MS).unref();
936
+ // ---------------------------------------------------------------------------
937
+ // Forward signals to all workers for graceful shutdown
938
+ // ---------------------------------------------------------------------------
939
+ for (const signal of ['SIGINT', 'SIGTERM']) {
940
+ process.on(signal, () => {
941
+ console.log(`\n\ud83d\udc4b Received ${signal}, stopping all instances...`);
942
+ // Stop every respawn path: the planned one keys off pendingRestarts, the
943
+ // crash-backoff one off this flag.
944
+ shuttingDown = true;
945
+ pendingRestarts.clear();
946
+ for (const [name, worker] of workers) {
947
+ console.log(` Stopping ${name}...`);
948
+ worker.postMessage({ type: 'shutdown' });
949
+ }
950
+ // Give workers 5 seconds to shut down gracefully
951
+ setTimeout(() => {
952
+ console.log('Force-terminating remaining workers...');
953
+ for (const worker of workers.values()) {
954
+ worker.terminate();
955
+ }
956
+ process.exit(0);
957
+ }, 5000).unref();
958
+ });
959
+ }
960
+ //# sourceMappingURL=launcher.js.map