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