telecoder 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/.env.example +142 -130
  2. package/CHANGELOG.md +683 -2
  3. package/README.md +36 -32
  4. package/dist/audio/transcribe.js +0 -9
  5. package/dist/bin/mcp-server.js +46 -61
  6. package/dist/bot/bot.js +162 -181
  7. package/dist/bot/command-catalog.js +263 -0
  8. package/dist/bot/deleted-threads.js +103 -0
  9. package/dist/bot/file-access.js +35 -26
  10. package/dist/bot/handlers/album.handler.js +128 -0
  11. package/dist/bot/handlers/{fork.handler.js → branch.handler.js} +267 -280
  12. package/dist/bot/handlers/command/access.js +1 -1
  13. package/dist/bot/handlers/command/admin.js +86 -110
  14. package/dist/bot/handlers/command/all-view.js +33 -0
  15. package/dist/bot/handlers/command/auto-approve.js +3 -3
  16. package/dist/bot/handlers/command/background.js +37 -0
  17. package/dist/bot/handlers/command/botname.js +76 -0
  18. package/dist/bot/handlers/command/btw.js +20 -69
  19. package/dist/bot/handlers/command/cleanup.js +329 -0
  20. package/dist/bot/handlers/command/model.js +40 -119
  21. package/dist/bot/handlers/command/prefs-scope.js +255 -90
  22. package/dist/bot/handlers/command/project.js +31 -109
  23. package/dist/bot/handlers/command/resume.js +8 -4
  24. package/dist/bot/handlers/command/session.js +74 -213
  25. package/dist/bot/handlers/command/settings.js +92 -447
  26. package/dist/bot/handlers/command/shared.js +32 -35
  27. package/dist/bot/handlers/command/tasks.js +263 -95
  28. package/dist/bot/handlers/command/thread.js +128 -0
  29. package/dist/bot/handlers/command/topic-store.js +14 -53
  30. package/dist/bot/handlers/command/topic.js +8 -61
  31. package/dist/bot/handlers/command/{cost.js → usage.js} +32 -59
  32. package/dist/bot/handlers/command-fallback.js +179 -0
  33. package/dist/bot/handlers/command.handler.js +96 -422
  34. package/dist/bot/handlers/{schedule.handler.js → loop.handler.js} +159 -73
  35. package/dist/bot/handlers/media-fallback.js +12 -7
  36. package/dist/bot/handlers/message/replies.js +10 -87
  37. package/dist/bot/handlers/message/shared.js +9 -31
  38. package/dist/bot/handlers/message/turn-notify.js +15 -49
  39. package/dist/bot/handlers/message/turn-runner.js +18 -103
  40. package/dist/bot/handlers/message.handler.js +59 -52
  41. package/dist/bot/handlers/newbot.handler.js +13 -4
  42. package/dist/bot/handlers/photo.handler.js +88 -129
  43. package/dist/bot/handlers/prompts.handler.js +11 -11
  44. package/dist/bot/handlers/running-note.js +2 -2
  45. package/dist/bot/handlers/session-guard.js +4 -4
  46. package/dist/bot/handlers/suggestion.handler.js +2 -2
  47. package/dist/bot/handlers/tree.handler.js +20 -20
  48. package/dist/bot/handlers/voice.handler.js +23 -85
  49. package/dist/bot/kept-threads.js +51 -0
  50. package/dist/bot/middleware/album-collector.js +69 -0
  51. package/dist/bot/middleware/auth.middleware.js +1 -1
  52. package/dist/bot/middleware/group-mention.middleware.js +11 -5
  53. package/dist/bot/middleware/queued-messages.js +143 -32
  54. package/dist/bot/middleware/stale-filter.js +0 -22
  55. package/dist/build-info.json +5 -5
  56. package/dist/claude/ask-user-form.js +517 -0
  57. package/dist/claude/ask-user.js +94 -26
  58. package/dist/claude/auto-topic-haiku.js +17 -0
  59. package/dist/claude/available-commands.js +22 -19
  60. package/dist/claude/background-hint.js +91 -0
  61. package/dist/claude/{fork-tree.js → branch-tree.js} +9 -9
  62. package/dist/claude/carry-over.js +0 -2
  63. package/dist/claude/ccr-shim.js +12 -10
  64. package/dist/claude/claude-auth.js +6 -10
  65. package/dist/claude/command-parser.js +49 -43
  66. package/dist/claude/cost-overlay-scraper.js +7 -2
  67. package/dist/claude/effort-level.js +5 -0
  68. package/dist/claude/enabled-plugins.js +12 -16
  69. package/dist/claude/in-flight-tracker.js +21 -0
  70. package/dist/claude/mcp-bridge.js +86 -58
  71. package/dist/claude/memory-guard.js +400 -0
  72. package/dist/claude/message-offsets.js +5 -5
  73. package/dist/claude/modal-relay.js +401 -34
  74. package/dist/claude/model-catalog.js +20 -3
  75. package/dist/claude/monitor-relay.js +130 -15
  76. package/dist/claude/native-commands.js +40 -0
  77. package/dist/claude/{pending-forks.js → pending-branches.js} +26 -26
  78. package/dist/claude/permission-gate.js +11 -10
  79. package/dist/claude/permission-mode.js +19 -45
  80. package/dist/claude/prewarm.js +70 -0
  81. package/dist/claude/pty-idle-reaper.js +96 -0
  82. package/dist/claude/pty-provider.js +473 -188
  83. package/dist/claude/pty-spawn-config.js +79 -32
  84. package/dist/claude/pty-watch.js +201 -0
  85. package/dist/claude/request-queue.js +7 -35
  86. package/dist/claude/rewind.js +111 -0
  87. package/dist/claude/scheduled-runner.js +1 -3
  88. package/dist/claude/scheduler.js +6 -2
  89. package/dist/claude/scope-guard.js +8 -3
  90. package/dist/claude/screen-marks.js +83 -0
  91. package/dist/claude/screen-render.js +96 -0
  92. package/dist/claude/session-history.js +4 -2
  93. package/dist/claude/session-jsonl.js +162 -15
  94. package/dist/claude/session-manager.js +29 -8
  95. package/dist/claude/session-move.js +70 -0
  96. package/dist/claude/shell-mode-gate.js +60 -0
  97. package/dist/claude/side-question.js +20 -17
  98. package/dist/claude/stage-images.js +5 -5
  99. package/dist/claude/tasks-overlay-scraper.js +143 -20
  100. package/dist/claude/thread-judge-haiku.js +88 -0
  101. package/dist/claude/tip-scraper.js +3 -4
  102. package/dist/claude/tui-modal.js +272 -27
  103. package/dist/claude/tui-state.js +74 -2
  104. package/dist/claude/turn-end.js +15 -1
  105. package/dist/claude/turn-prose.js +1 -1
  106. package/dist/claude/typed-answer.js +104 -0
  107. package/dist/claude/update-banner-relay.js +1 -1
  108. package/dist/cli/commands/doctor.js +48 -15
  109. package/dist/cli/commands/help.js +11 -2
  110. package/dist/cli/commands/init.js +16 -13
  111. package/dist/cli/commands/service.js +40 -8
  112. package/dist/cli/commands/start.js +10 -0
  113. package/dist/cli/commands/watch.js +322 -0
  114. package/dist/cli/dispatch.js +5 -0
  115. package/dist/cli/init/env-file.js +1 -1
  116. package/dist/cli/init/flow.js +114 -47
  117. package/dist/cli/init/prompter.js +8 -0
  118. package/dist/cli/init/telegram.js +35 -9
  119. package/dist/cli/service/render.js +3 -3
  120. package/dist/config.js +156 -131
  121. package/dist/index.js +107 -31
  122. package/dist/launcher.js +34 -7
  123. package/dist/providers/ccr-introspect.js +1 -8
  124. package/dist/providers/ccr-provider.js +19 -20
  125. package/dist/providers/claude-provider.js +4 -57
  126. package/dist/providers/prefs-sync.js +16 -59
  127. package/dist/providers/provider-router.js +24 -23
  128. package/dist/providers/spawn-settings.js +45 -0
  129. package/dist/providers/user-preferences.js +127 -19
  130. package/dist/restart-when-idle.js +27 -7
  131. package/dist/startup/auto-continue.js +2 -2
  132. package/dist/startup/auto-resume.js +3 -15
  133. package/dist/startup/notices.js +1 -1
  134. package/dist/startup/verify-token.js +4 -4
  135. package/dist/telegram/action-logger.js +3 -165
  136. package/dist/telegram/background-activity-card.js +1 -1
  137. package/dist/telegram/botname-settings.js +71 -125
  138. package/dist/telegram/client-options.js +6 -7
  139. package/dist/telegram/force-reply-tracker.js +55 -16
  140. package/dist/telegram/message-sender.js +92 -360
  141. package/dist/telegram/prompt-label.js +11 -5
  142. package/dist/telegram/streaming-turn.js +5 -7
  143. package/dist/telegram/table-lists.js +56 -0
  144. package/dist/telegram/task-list.js +4 -4
  145. package/dist/telegram/task-tracker.js +45 -126
  146. package/dist/telegram/terminal-renderer.js +1 -5
  147. package/dist/telegram/thread-titles.js +74 -2
  148. package/dist/telegram/threads-setup.js +1 -1
  149. package/dist/utils/admins.js +2 -2
  150. package/dist/utils/bot-icon.js +248 -0
  151. package/dist/utils/bot-token.js +8 -5
  152. package/dist/utils/build-info.js +3 -3
  153. package/dist/utils/caffeinate.js +6 -3
  154. package/dist/utils/claude-env.js +0 -1
  155. package/dist/utils/claude-version.js +2 -2
  156. package/dist/utils/config-home.js +3 -3
  157. package/dist/utils/download.js +41 -15
  158. package/dist/utils/exit-codes.js +11 -0
  159. package/dist/utils/format.js +3 -6
  160. package/dist/utils/home-project.js +1 -1
  161. package/dist/utils/idle-restart.js +1 -1
  162. package/dist/utils/install-mode.js +1 -1
  163. package/dist/utils/instance-config.js +1 -1
  164. package/dist/utils/instances.js +1 -1
  165. package/dist/utils/keyed-settings.js +2 -2
  166. package/dist/utils/memory-pressure.js +60 -0
  167. package/dist/utils/npm-version.js +2 -2
  168. package/dist/utils/resolve-claude-bin.js +13 -24
  169. package/dist/utils/respawn-backoff.js +9 -0
  170. package/dist/utils/stale-launcher.js +1 -1
  171. package/dist/utils/systemd.js +8 -8
  172. package/dist/utils/telegram-proxy.js +72 -0
  173. package/dist/utils/uploads-dir.js +27 -0
  174. package/dist/utils/verbosity.js +8 -8
  175. package/dist/utils/version-check.js +5 -5
  176. package/package.json +3 -4
  177. package/dist/bot/handlers/command/media.js +0 -197
  178. package/dist/bot/handlers/command/streaming-mode.js +0 -16
  179. package/dist/bot/handlers/message/throttle.js +0 -49
  180. package/dist/claude/agent-watchdog.js +0 -162
  181. package/dist/claude/agent.js +0 -1458
  182. package/dist/claude/held-query.js +0 -190
  183. package/dist/claude/mcp-tools.js +0 -354
  184. package/dist/claude/sdk-permission-gate.js +0 -77
  185. package/dist/claude/session-cost.js +0 -41
  186. package/dist/claude/system-prompt.js +0 -162
  187. package/dist/providers/sdk-provider.js +0 -37
  188. package/dist/telegram/telegraph-settings.js +0 -31
  189. package/dist/telegram/telegraph.js +0 -453
  190. package/dist/telegram/terminal-settings.js +0 -25
  191. package/dist/tts/tts-settings.js +0 -62
  192. package/dist/tts/tts.js +0 -245
  193. package/dist/tts/voice-reply.js +0 -78
  194. package/dist/utils/debug-agent.js +0 -117
  195. package/dist/utils/debug-watchdog.js +0 -121
  196. package/dist/utils/project-data-dir.js +0 -33
  197. package/dist/utils/reasoning-summary.js +0 -12
package/dist/index.js CHANGED
@@ -17,7 +17,7 @@ import { isMainThread, parentPort } from 'worker_threads';
17
17
  import { createBot } from './bot/bot.js';
18
18
  import { resumeThreadsSetup } from './telegram/threads-setup.js';
19
19
  import { armReminders } from './bot/middleware/queued-messages.js';
20
- import { config, BOT_ID } from './config.js';
20
+ import { config, BOT_ID, RENAMED_SETTINGS } from './config.js';
21
21
  import { preventSleep, allowSleep } from './utils/caffeinate.js';
22
22
  import { stopCleanup } from './telegram/deduplication.js';
23
23
  import { sessionHistory } from './claude/session-history.js';
@@ -27,7 +27,7 @@ import { startScheduledRunner } from './claude/scheduled-runner.js';
27
27
  import { setMonitorRelayBot } from './claude/monitor-relay.js';
28
28
  import { getPtyProvider } from './providers/claude-provider.js';
29
29
  import { setUpdateBannerRelayBot } from './claude/update-banner-relay.js';
30
- import { startPendingForkWatcher } from './bot/handlers/fork.handler.js';
30
+ import { startPendingBranchWatcher } from './bot/handlers/branch.handler.js';
31
31
  import { initPrefsSync } from './providers/prefs-sync.js';
32
32
  import { initRestartWhenIdle } from './restart-when-idle.js';
33
33
  import { stripParentClaudeSession } from './utils/claude-env.js';
@@ -36,11 +36,14 @@ import { autoResumeAfterReload } from './startup/auto-resume.js';
36
36
  import { autoContinueOnStartup } from './startup/auto-continue.js';
37
37
  import { notifyInterruptedSessions, notifyRestartComplete } from './startup/notices.js';
38
38
  import { tickWasStalled } from './utils/host-stall.js';
39
+ import { EXIT_TELEGRAM_UNAVAILABLE } from './utils/exit-codes.js';
39
40
  import { describeRunningBuild } from './utils/build-info.js';
40
41
  import { migrateLegacyStateDirAndLog } from './utils/state-dir-migration.js';
41
42
  import { verifyBotTokenOrExit } from './startup/verify-token.js';
42
43
  import { warnIfClaudeNotLoggedIn } from './claude/claude-auth.js';
43
- import { redactSecrets } from './utils/sanitize.js';
44
+ import { loadsUserSetup } from './claude/pty-spawn-config.js';
45
+ import { redactSecrets, sanitizeError } from './utils/sanitize.js';
46
+ import { startWatchServer, stopWatchServer } from './claude/pty-watch.js';
44
47
  export { requestRestart, requestSiblingRestart, requestRestartAll } from './worker-restart.js';
45
48
  // When running as a worker thread (multi-instance mode), prefix all console
46
49
  // output with the instance name so logs from different bots are distinguishable.
@@ -63,6 +66,45 @@ const strippedClaudeVars = stripParentClaudeSession();
63
66
  if (strippedClaudeVars.length > 0) {
64
67
  console.warn(`[Env] Bot was launched from inside a Claude Code session; dropped inherited markers so spawned sessions persist normally: ${strippedClaudeVars.join(', ')}`);
65
68
  }
69
+ // Settings of features that are gone. A .env that still sets one gets one
70
+ // line saying so, rather than behaviour that silently stopped. Only a value
71
+ // that asked for something — not the old default — earns the line.
72
+ const isOn = (v) => /^(true|1|yes)$/i.test(v);
73
+ const REMOVED_SETTINGS = [
74
+ { name: 'TELEGRAPH_ENABLED', stale: isOn, note: 'Telegraph pages were removed: long replies arrive in full in the chat.' },
75
+ { name: 'STREAMING_MODE', stale: (v) => v === 'wait', note: 'the wait mode was removed: replies always stream.' },
76
+ { name: 'DANGEROUS_MODE', stale: isOn, note: 'it was removed: /mode sets how much Claude asks before acting.' },
77
+ { name: 'MAX_LOOP_ITERATIONS', stale: (v) => v !== '5', note: '/loop was removed: Claude Code works until a task is done, and its own /loop skill reaches it now.' },
78
+ { name: 'BOT_MODE', stale: () => true, note: 'it was removed with the botctl script: the bot runs under pm2, systemd or launchd.' },
79
+ { name: 'TERMINAL_UI_DEFAULT', stale: (v) => !isOn(v), note: '/terminalui was removed: every turn has the live status message, and /verbosity sets how much it shows.' },
80
+ { name: 'CLAUDE_METHOD_DEFAULT', stale: () => true, note: 'the SDK transport was removed: every chat runs Claude Code in a pty.' },
81
+ { name: 'CLAUDE_SDK_LOG_LEVEL', stale: () => true, note: 'the SDK transport was removed: every chat runs Claude Code in a pty.' },
82
+ { name: 'CLAUDE_SDK_LOAD_USER_SETTINGS', stale: () => true, note: 'the SDK transport was removed: the pty brings your own Claude Code setup along unless the bot has guests (CLAUDE_USER_SETUP).' },
83
+ { name: 'TTS_ENABLED', stale: isOn, note: 'voice replies (/tts) were removed: Claude Code answers in text.' },
84
+ ...['TTS_PROVIDER', 'TTS_MODEL', 'TTS_VOICE', 'TTS_INSTRUCTIONS', 'TTS_SPEED', 'TTS_MAX_CHARS', 'TTS_RESPONSE_FORMAT', 'OPENAI_API_KEY']
85
+ .map((name) => ({ name, stale: () => true, note: 'voice replies (/tts) were removed: Claude Code answers in text.' })),
86
+ { name: 'TRANSCRIBE_FILE_THRESHOLD_CHARS', stale: () => true, note: '/transcribe was removed: voice notes still become prompts.' },
87
+ { name: 'CCR_AUTO_PROMPT_ON_THROTTLE', stale: () => true, note: 'the one-tap CCR retry went with the SDK transport: /ccr switches a throttled chat over.' },
88
+ ...['AGENT_WATCHDOG_ENABLED', 'AGENT_WATCHDOG_WARN_SECONDS', 'AGENT_WATCHDOG_LOG_SECONDS', 'AGENT_QUERY_TIMEOUT_MS', 'AGENT_SILENCE_TIMEOUT_MS', 'AGENT_STALE_TOOL_TIMEOUT_MS']
89
+ .map((name) => ({ name, stale: () => true, note: 'the SDK transport\'s watchdog went with it: CLAUDE_PTY_HARD_TIMEOUT_MS caps a turn in the pty.' })),
90
+ { name: 'CLAUDE_REASONING_SUMMARY', stale: () => true, note: 'the summary was something the SDK transport asked for in its own prompt; Claude Code in the pty writes none.' },
91
+ // .env.example set this one uncommented, so only a changed value was asked for.
92
+ { name: 'CANCEL_ON_NEW_MESSAGE', stale: isOn, note: 'it was removed: a new message waits for the turn, as in Claude Code, and /steer or ⚡ Interrupt & send replaces the turn with one.' },
93
+ { name: 'STREAMING_DEBOUNCE_MS', stale: (v) => v !== '500', note: 'nothing has read it since February: the live reply paces its own edits.' },
94
+ ];
95
+ for (const { name, stale, note } of REMOVED_SETTINGS) {
96
+ const value = process.env[name];
97
+ if (value !== undefined && value !== '' && stale(value)) {
98
+ console.warn(`[Env] ${name} is set, but ${note} The setting can go from .env.`);
99
+ }
100
+ }
101
+ // Settings that took a new name still work under the old one; say so once.
102
+ for (const [old, now] of Object.entries(RENAMED_SETTINGS)) {
103
+ if (!process.env[old])
104
+ continue;
105
+ const ignored = process.env[now] ? `, and ${now} is set too, so ${old} is ignored` : '';
106
+ console.warn(`[Env] ${old} is now called ${now}${ignored}. Rename it in .env.`);
107
+ }
66
108
  // Log unhandled rejections — prevents silent failures where the process stays
67
109
  // alive but functionality is broken (e.g. fire-and-forget async calls that fail).
68
110
  process.on('unhandledRejection', (reason) => {
@@ -72,6 +114,34 @@ process.on('unhandledRejection', (reason) => {
72
114
  const SHUTDOWN_TIMEOUT_MS = 5_000;
73
115
  async function main() {
74
116
  console.log('🤖 Starting TeleCoder...');
117
+ // As a worker thread: the heartbeat and the exit listener come first, before
118
+ // anything awaited. The launcher restarts a worker that's silent for 90s,
119
+ // and startup can take longer than that: during a Telegram outage every
120
+ // awaited call below waits out autoRetry's 5xx backoff, 3+6+12+24+48s. Sent
121
+ // only from the end of startup, the heartbeat made a slow start look like a
122
+ // wedged thread, and with no listener yet the restart could only terminate()
123
+ // it, so a bot crash-looped through every outage. The heartbeat only says
124
+ // the event loop runs, which is all the launcher checks; whether Telegram
125
+ // answers is the getMe heartbeat's job further down.
126
+ //
127
+ // 'exit_for_restart' is the launcher answering a restart request: we exit
128
+ // ourselves rather than waiting to be terminated. A worker.terminate() only
129
+ // lands when the thread next runs JS, so a worker blocked in native code
130
+ // would never die, and never be respawned. Until the full shutdown is wired
131
+ // up below, an exit request ends the claudes started so far and exits.
132
+ let onExitRequest = () => {
133
+ const exit = () => process.exit(typeof process.exitCode === 'number' ? process.exitCode : 0);
134
+ setTimeout(exit, SHUTDOWN_TIMEOUT_MS).unref();
135
+ getPtyProvider().closeAll().then(exit, exit);
136
+ };
137
+ if (!isMainThread && parentPort) {
138
+ const pp = parentPort;
139
+ pp.on('message', (msg) => {
140
+ if (msg?.type === 'shutdown' || msg?.type === 'exit_for_restart')
141
+ onExitRequest();
142
+ });
143
+ setInterval(() => pp.postMessage({ type: 'heartbeat' }), 30_000).unref();
144
+ }
75
145
  // Before anything else starts: a token Telegram turns down stops the bot
76
146
  // here with one sentence, rather than after the IPC server is listening.
77
147
  const botInfo = await verifyBotTokenOrExit();
@@ -113,7 +183,18 @@ async function main() {
113
183
  console.log(`📋 Allowed groups: ${config.ALLOWED_GROUP_IDS.join(', ')} ` +
114
184
  `(members default to ${config.GROUP_MEMBERS_DEFAULT})`);
115
185
  }
116
- console.log(`📝 Mode: ${config.STREAMING_MODE}`);
186
+ // Which Claude this bot runs: the terminal's, or one that knows only the
187
+ // project. 'auto' follows the roster logged above, so admitting a first
188
+ // guest changes it, and a missing skill or MCP server is otherwise a puzzle.
189
+ if (loadsUserSetup()) {
190
+ console.log('🧰 Claude Code user setup: loaded (~/.claude, your MCP servers and connectors)');
191
+ }
192
+ else {
193
+ const why = config.CLAUDE_USER_SETUP === 'off'
194
+ ? 'CLAUDE_USER_SETUP=off'
195
+ : 'this bot has guests; CLAUDE_USER_SETUP=on loads it anyway';
196
+ console.log(`🧰 Claude Code user setup: left out (${why})`);
197
+ }
117
198
  // Scope session history to this bot instance so multi-bot setups don't cross-restore
118
199
  sessionHistory.initForBot(BOT_ID);
119
200
  // Accept model/effort changes another instance chose to apply fleet-wide.
@@ -130,6 +211,12 @@ async function main() {
130
211
  await bot.init();
131
212
  console.log(`✅ Bot started as @${bot.botInfo.username}`);
132
213
  resumeThreadsSetup(bot);
214
+ if (config.PTY_WATCH) {
215
+ // Never worth failing the start over: the bot works the same without it.
216
+ await startWatchServer(bot.botInfo.username).catch((err) => {
217
+ console.warn(`[Watch] "telecoder watch" is unavailable: ${sanitizeError(err)}`);
218
+ });
219
+ }
133
220
  console.log('📱 Send /start in Telegram to begin');
134
221
  // Start concurrent runner — updates are processed in parallel,
135
222
  // with per-chat ordering enforced by the sequentialize middleware in bot.ts.
@@ -139,7 +226,7 @@ async function main() {
139
226
  // Chats that received a startup message, so the restart confirmation below
140
227
  // doesn't pile a second one on top.
141
228
  const notified = new Set();
142
- // Auto-resume sessions after /rebuildbot or /restartbot
229
+ // Auto-resume sessions after /botrebuild or /botrestart
143
230
  let markerHandled = false;
144
231
  try {
145
232
  markerHandled = await autoResumeAfterReload(bot, notified);
@@ -166,7 +253,7 @@ async function main() {
166
253
  console.error('[AutoContinue] Failed:', err);
167
254
  }
168
255
  // Confirm the restart itself, but only for a user-initiated one — a fresh
169
- // reload marker is what distinguishes /rebuildbot and /restartbot from a
256
+ // reload marker is what distinguishes /botrebuild and /botrestart from a
170
257
  // crash respawn or a plain pm2 restart.
171
258
  if (markerHandled) {
172
259
  try {
@@ -176,17 +263,15 @@ async function main() {
176
263
  console.error('[Restart] Failed:', err);
177
264
  }
178
265
  }
179
- // Reconcile the Telegram display name with BOT_NAME. Runs after the resume
180
- // paths above so a session restore — which pushes its own "BOT_NAME —
181
- // project" name — wins and this becomes a no-op; only a bot whose name
182
- // nobody claimed this startup gets rewritten.
266
+ // Reconcile the Telegram display name with the configured one (/botname or
267
+ // BOT_NAME), in case it changed between runs or a rename was refused.
183
268
  try {
184
269
  await syncBotNameOnStartup(bot.api);
185
270
  }
186
271
  catch (err) {
187
272
  console.debug('[BotName] Startup sync failed:', err instanceof Error ? err.message : err);
188
273
  }
189
- // Re-arm persisted scheduled tasks (/schedule). Runs after session
274
+ // Re-arm persisted scheduled tasks (/loop). Runs after session
190
275
  // restore so the first scheduled fire can resolve the live session
191
276
  // instead of paying a cold-spawn tax.
192
277
  try {
@@ -198,21 +283,21 @@ async function main() {
198
283
  // Ask about anything set aside before the restart. Runs after the resume paths
199
284
  // above so the question lands below whatever they post.
200
285
  armReminders();
201
- // Register the bot reference for the PTY-mode Monitor relay so Monitor
286
+ // Register the bot reference for the Monitor relay so Monitor
202
287
  // events that fire between user turns can be posted to Telegram.
203
288
  setMonitorRelayBot(bot);
204
289
  // And the update-banner relay, so claude code's "Update available" notice
205
290
  // (printed once at PTY startup) is forwarded to the user instead of being
206
291
  // silently consumed by the headless xterm.
207
292
  setUpdateBannerRelayBot(bot);
208
- // Watch for cross-bot fork handoffs landing in our pending-forks file and
293
+ // Watch for cross-bot branch handoffs landing in our pending-branches file and
209
294
  // proactively DM the user so they don't have to message us first to see
210
295
  // the offer.
211
296
  try {
212
- startPendingForkWatcher(bot);
297
+ startPendingBranchWatcher(bot);
213
298
  }
214
299
  catch (err) {
215
- console.error('[Fork] Failed to start pending-fork watcher:', err);
300
+ console.error('[Branch] Failed to start pending-branch watcher:', err);
216
301
  }
217
302
  // Liveness heartbeat: periodically verify the bot can still reach the
218
303
  // Telegram API. If the runner has stopped or getMe fails repeatedly,
@@ -261,7 +346,7 @@ async function main() {
261
346
  console.error(`[HEARTBEAT] getMe timed out (${heartbeatTimeouts}/${MAX_HEARTBEAT_TIMEOUTS}):`, err);
262
347
  if (heartbeatTimeouts >= MAX_HEARTBEAT_TIMEOUTS) {
263
348
  console.error('[HEARTBEAT] Telegram unreachable for too long — exiting for restart');
264
- process.exit(1);
349
+ process.exit(EXIT_TELEGRAM_UNAVAILABLE);
265
350
  }
266
351
  return;
267
352
  }
@@ -269,14 +354,14 @@ async function main() {
269
354
  console.error(`[HEARTBEAT] getMe failed (${heartbeatFailures}/${MAX_HEARTBEAT_FAILURES}):`, err);
270
355
  if (heartbeatFailures >= MAX_HEARTBEAT_FAILURES) {
271
356
  console.error('[HEARTBEAT] Too many consecutive failures — exiting for restart');
272
- process.exit(1);
357
+ process.exit(EXIT_TELEGRAM_UNAVAILABLE);
273
358
  }
274
359
  }
275
360
  }, HEARTBEAT_INTERVAL_MS);
276
361
  heartbeatTimer.unref(); // Don't prevent graceful shutdown
277
362
  // Graceful shutdown (guarded against duplicate signals)
278
363
  let shuttingDown = false;
279
- // Normally 0 — a shutdown is a shutdown. /restartbot under systemd sets
364
+ // Normally 0 — a shutdown is a shutdown. /botrestart under systemd sets
280
365
  // process.exitCode first, because there the exit *is* the restart and the
281
366
  // code is what tells systemd to bring us back rather than stand down.
282
367
  const exitCode = () => (typeof process.exitCode === 'number' ? process.exitCode : 0);
@@ -299,27 +384,18 @@ async function main() {
299
384
  // to notice, while the bot that replaces this one may already have resumed
300
385
  // its conversation in another.
301
386
  await Promise.all([runner.stop(), getPtyProvider().closeAll()]);
387
+ stopWatchServer();
302
388
  process.exit(exitCode());
303
389
  };
304
390
  process.on('SIGINT', () => { shutdown(); });
305
391
  process.on('SIGTERM', () => { shutdown(); });
306
- // When running as a worker thread, communicate with the launcher
392
+ // When running as a worker thread, the launcher's exit requests now get the
393
+ // full shutdown (the listener and heartbeat were set up at the top of main).
307
394
  if (!isMainThread && parentPort) {
308
- parentPort.on('message', (msg) => {
309
- // 'exit_for_restart' is the launcher answering a restart request: we exit
310
- // ourselves rather than waiting to be terminated. A worker.terminate()
311
- // only lands when the thread next runs JS, so a worker blocked in native
312
- // code would never die — and never be respawned.
313
- if (msg?.type === 'shutdown' || msg?.type === 'exit_for_restart')
314
- shutdown();
315
- });
395
+ onExitRequest = shutdown;
316
396
  // Tells the launcher this worker is listening, so only once it is: the
317
397
  // bot is up and the shutdown above is wired to the restart it may ask for.
318
398
  initRestartWhenIdle(bot.api);
319
- // Send periodic heartbeat so the launcher can detect stuck workers
320
- const pp = parentPort;
321
- const workerHeartbeat = setInterval(() => pp.postMessage({ type: 'heartbeat' }), 30_000);
322
- workerHeartbeat.unref();
323
399
  }
324
400
  // Keep alive until the runner stops (crash or explicit stop).
325
401
  //
package/dist/launcher.js CHANGED
@@ -19,14 +19,14 @@ import { getStateDir } from './utils/json-store.js';
19
19
  import { migrateLegacyStateDirAndLog } from './utils/state-dir-migration.js';
20
20
  import { resolveInstances, diffInstances, botIdOf, InstancesConfigError, } from './utils/instance-config.js';
21
21
  import { legacyEnv } from './utils/legacy-env.js';
22
- import { planRespawn } from './utils/respawn-backoff.js';
22
+ import { planOutageRespawn, planRespawn } from './utils/respawn-backoff.js';
23
23
  import { tickWasStalled, withinStallCooldown, shouldEscalateWedged } from './utils/host-stall.js';
24
24
  import { fingerprintModuleGraph, launcherHasChanged } from './utils/stale-launcher.js';
25
25
  import { PrefsRelay } from './utils/prefs-relay.js';
26
26
  import { IdleRestart } from './utils/idle-restart.js';
27
27
  import { configFile } from './utils/config-home.js';
28
28
  import { PACKAGE_ROOT, isCheckout } from './utils/install-mode.js';
29
- import { EXIT_CONFIG, configErrorExitCode } from './utils/exit-codes.js';
29
+ import { EXIT_CONFIG, EXIT_TELEGRAM_UNAVAILABLE, configErrorExitCode } from './utils/exit-codes.js';
30
30
  const projectRoot = PACKAGE_ROOT;
31
31
  // Heartbeat: workers ping the launcher periodically. If a worker goes silent
32
32
  // for too long, the launcher force-terminates and respawns it.
@@ -64,7 +64,7 @@ const RESTART_GRACEFUL_EXIT_MS = 10_000;
64
64
  // fires and the respawn below never runs — that instance stays dead for good.
65
65
  // Rather than leave a bot silently offline, take the launcher down and let the
66
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
67
+ // longest legitimate block (/botrebuild's 120s build cap) so a slow-but-alive
68
68
  // worker is never punished.
69
69
  const RESTART_WEDGED_ESCALATION_MS = 180_000;
70
70
  // An unplanned worker exit — a crash, or a fatal error the bot exited on — used
@@ -76,6 +76,11 @@ const CRASH_RESPAWN_DELAYS_MS = [1_000, 5_000, 15_000, 60_000];
76
76
  // this long before dying starts its retry budget over, so two unrelated crashes
77
77
  // days apart don't add up to a give-up.
78
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];
79
84
  // How often the launcher looks at instances.json for edits, and how long it
80
85
  // lets an edit settle before reading it: an editor or a script can take more
81
86
  // than one write to save a file.
@@ -149,6 +154,8 @@ const restarters = new Map();
149
154
  // decide when to stop trying. Reset by a planned restart or by an instance that
150
155
  // stayed up longer than CRASH_STREAK_RESET_MS.
151
156
  const crashStreaks = new Map();
157
+ // The same for exits on a Telegram outage, which only pick a delay.
158
+ const outageStreaks = new Map();
152
159
  // Instances waiting out a respawn backoff. They have no entry in `workers`
153
160
  // during the gap, so without this the "everything's gone" check below would
154
161
  // fire mid-backoff and take the launcher down with it.
@@ -304,7 +311,7 @@ function writeReloadMarkerForToken(token, instanceName) {
304
311
  // ---------------------------------------------------------------------------
305
312
  // Restarting when idle
306
313
  //
307
- // /rebuildbot's "when idle" option. Every live worker is told to drain; each
314
+ // /botrebuild's "when idle" option. Every live worker is told to drain; each
308
315
  // says what it is still finishing until it has nothing left, and is restarted
309
316
  // then, on its own schedule rather than the slowest one's. The tally goes back
310
317
  // to the bot that asked, as edits to one message. See src/restart-when-idle.ts
@@ -397,7 +404,7 @@ function buildWorkerEnv(inst) {
397
404
  env.BOT_NAME = inst.name;
398
405
  // Tag for log prefixing inside the worker
399
406
  env.TELECODER_INSTANCE_NAME = inst.name;
400
- // Workers use this to enumerate sibling bots (e.g. for /fork). Mirrors the
407
+ // Workers use this to enumerate sibling bots (e.g. for /branch). Mirrors the
401
408
  // launcher's own --config resolution so a custom config path still works.
402
409
  env.TELECODER_INSTANCES_CONFIG = configPath;
403
410
  // A pre-rename value inherited from the parent env would otherwise win the
@@ -581,7 +588,7 @@ function spawnWorker(inst) {
581
588
  }
582
589
  }
583
590
  else if (targetName === inst.name) {
584
- worker.postMessage({ type: 'restart_sibling_result', success: false, name: targetName, reason: 'use /restartbot without arguments to restart yourself' });
591
+ worker.postMessage({ type: 'restart_sibling_result', success: false, name: targetName, reason: 'use /botrestart without arguments to restart yourself' });
585
592
  }
586
593
  else {
587
594
  console.log(`[Launcher] ${inst.name} requested restart of sibling ${targetName}`);
@@ -711,6 +718,7 @@ function spawnWorker(inst) {
711
718
  // Planned restart — respawn after a short delay
712
719
  pendingRestarts.delete(inst.name);
713
720
  crashStreaks.delete(inst.name);
721
+ outageStreaks.delete(inst.name);
714
722
  console.log(`[Launcher] Respawning ${inst.name} in 1s...`);
715
723
  scheduleRespawn(inst, 1000);
716
724
  return;
@@ -720,6 +728,7 @@ function spawnWorker(inst) {
720
728
  // itself. Respawning would print the same thing four times over.
721
729
  if (code === EXIT_CONFIG) {
722
730
  crashStreaks.delete(inst.name);
731
+ outageStreaks.delete(inst.name);
723
732
  console.error(`[Launcher] ${inst.name} stopped on a configuration problem (its message is above) — not restarting it. ` +
724
733
  `Fix its entry in ${path.basename(configPath)} and it starts again; for a fix in .env, restart the launcher.`);
725
734
  releaseName(inst.name);
@@ -728,11 +737,26 @@ function spawnWorker(inst) {
728
737
  shutdownIfNothingLeft(configErrorExitCode());
729
738
  return;
730
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);
731
756
  // Unplanned exit. Whatever took it down — a fatal error, a 409 from a
732
757
  // predecessor's long poll that hadn't been dropped yet — this bot is now
733
758
  // silently offline and nothing else will notice, because the heartbeat
734
759
  // monitor only watches instances that still have a worker. Respawn it.
735
- const aliveMs = Date.now() - spawnedAt;
736
760
  const { streak, delayMs: delay } = planRespawn({
737
761
  aliveMs,
738
762
  previousStreak: crashStreaks.get(inst.name) ?? 0,
@@ -810,11 +834,14 @@ function applyConfigChange() {
810
834
  console.log(`[Launcher] ${from.name}'s entry in ${file} changed — starting it again${renamed}`);
811
835
  crashStreaks.delete(from.name);
812
836
  crashStreaks.delete(to.name);
837
+ outageStreaks.delete(from.name);
838
+ outageStreaks.delete(to.name);
813
839
  startWhenNameIsFree(to);
814
840
  }
815
841
  }
816
842
  for (const inst of added) {
817
843
  crashStreaks.delete(inst.name);
844
+ outageStreaks.delete(inst.name);
818
845
  const now = startWhenNameIsFree(inst);
819
846
  console.log(`[Launcher] ${inst.name} was added to ${file} — ${now ? 'starting it' : 'it starts once its name is free'}`);
820
847
  }
@@ -7,8 +7,6 @@ const CCR_LOG_DIR = path.join(os.homedir(), '.claude-code-router', 'logs');
7
7
  // contain at least one full response chunk (largest observed ~5KB) without
8
8
  // having to slurp megabytes when the log grows.
9
9
  const TAIL_BYTES = 32 * 1024;
10
- let cachedLatestLog;
11
- let cachedLatestLogMtime = 0;
12
10
  function findLatestLog() {
13
11
  if (!fs.existsSync(CCR_LOG_DIR))
14
12
  return undefined;
@@ -59,11 +57,6 @@ function getLastCcrRouteFromLog() {
59
57
  const latest = findLatestLog();
60
58
  if (!latest)
61
59
  return undefined;
62
- // Quick mtime check — if the file hasn't changed since last call we
63
- // could skip work, but we want freshness here, so always re-read tail.
64
- const stat = fs.statSync(latest);
65
- cachedLatestLog = latest;
66
- cachedLatestLogMtime = stat.mtimeMs;
67
60
  const tail = readTail(latest, TAIL_BYTES);
68
61
  const lines = tail.split('\n');
69
62
  for (let i = lines.length - 1; i >= 0; i--) {
@@ -130,7 +123,7 @@ function parseRoute(spec) {
130
123
  *
131
124
  * Returns undefined when neither source is available (CCR down, logs off,
132
125
  * unreachable proxy). Callers should treat undefined as "show CCR tag but
133
- * keep the SDK alias as the model name".
126
+ * keep the alias as the model name".
134
127
  */
135
128
  export async function getCcrRoute() {
136
129
  const fromLog = getLastCcrRouteFromLog();
@@ -1,16 +1,24 @@
1
- import { sendToAgent as claudeSendToAgent, sendLoopToAgent as claudeSendLoopToAgent, clearConversation as claudeClearConversation, setModel as claudeSetModel, getModel as claudeGetModel, clearModel as claudeClearModel, getCachedUsage as claudeGetCachedUsage, isDangerousMode as claudeIsDangerousMode, } from '../claude/agent.js';
1
+ import { getPtyProvider } from './claude-provider.js';
2
2
  import { getCcrShimPath } from '../claude/ccr-shim.js';
3
3
  import { ensureCcrRunning } from './ccr-health.js';
4
4
  // CCR's router config decides the actual backend model per request — the
5
- // SDK-level model name is largely advisory. Deliberately just the three tiers
6
- // CCR configs actually route on, rather than the Claude provider's full alias
7
- // list: aliases like `opusplan` or `fable[1m]` mean nothing to a router whose
8
- // rules key off opus/sonnet/haiku.
5
+ // model name claude is started with is largely advisory. Deliberately just the
6
+ // three tiers CCR configs actually route on, rather than the Claude provider's
7
+ // full alias list: aliases like `opusplan` or `fable[1m]` mean nothing to a
8
+ // router whose rules key off opus/sonnet/haiku.
9
9
  const CCR_MODELS = [
10
10
  { id: 'opus', label: 'opus', description: 'Routed via CCR' },
11
11
  { id: 'sonnet', label: 'sonnet', description: 'Routed via CCR' },
12
12
  { id: 'haiku', label: 'haiku', description: 'Routed via CCR' },
13
13
  ];
14
+ /**
15
+ * The same pty as the Claude provider's, spawning CCR's wrapper script in
16
+ * place of `claude`: it exports the proxy's address and token and execs the
17
+ * real binary, so nothing about the session changes but where its requests
18
+ * go. The pty respawns when a chat switches backend, and the provider switch
19
+ * forks the session first (see provider-switch.ts), since one backend's
20
+ * thinking blocks can't be replayed against another.
21
+ */
14
22
  function withShim(options) {
15
23
  const shim = getCcrShimPath();
16
24
  return { ...(options ?? {}), executableOverride: shim };
@@ -27,31 +35,22 @@ export const ccrProvider = {
27
35
  const failure = await preflightOrFailure();
28
36
  if (failure)
29
37
  return failure;
30
- return claudeSendToAgent(sessionKey, message, withShim(options));
31
- },
32
- async sendLoopToAgent(sessionKey, message, options) {
33
- const failure = await preflightOrFailure();
34
- if (failure)
35
- return failure;
36
- return claudeSendLoopToAgent(sessionKey, message, withShim(options));
38
+ return getPtyProvider().sendToAgent(sessionKey, message, withShim(options));
37
39
  },
38
40
  clearConversation(sessionKey) {
39
- claudeClearConversation(sessionKey);
41
+ getPtyProvider().clearConversation(sessionKey);
40
42
  },
41
43
  setModel(scope, model) {
42
- claudeSetModel(scope, model);
44
+ getPtyProvider().setModel(scope, model);
43
45
  },
44
46
  getModel(scope) {
45
- return claudeGetModel(scope);
47
+ return getPtyProvider().getModel(scope);
46
48
  },
47
49
  clearModel(scope) {
48
- claudeClearModel(scope);
50
+ getPtyProvider().clearModel(scope);
49
51
  },
50
52
  getCachedUsage(sessionKey) {
51
- return claudeGetCachedUsage(sessionKey);
52
- },
53
- isDangerousMode() {
54
- return claudeIsDangerousMode();
53
+ return getPtyProvider().getCachedUsage(sessionKey);
55
54
  },
56
55
  async getAvailableModels() {
57
56
  return CCR_MODELS;
@@ -1,63 +1,10 @@
1
- import { userPreferences } from './user-preferences.js';
2
- import { sdkProvider } from './sdk-provider.js';
3
1
  import { PtyProvider } from '../claude/pty-provider.js';
4
- import { config } from '../config.js';
5
- // Instantiate both providers. The router will decide which one to use.
2
+ // Claude Code runs in a pty: the real `claude` CLI, driven in a pseudo-terminal
3
+ // with its dialogs relayed to the chat. The one instance is shared with the
4
+ // CCR provider, which runs the same pty around CCR's wrapper script.
6
5
  const ptyProvider = new PtyProvider();
7
6
  export function getPtyProvider() {
8
7
  return ptyProvider;
9
8
  }
10
- function getMethod(scope) {
11
- // The thread's or chat's /method wins; CLAUDE_METHOD_DEFAULT decides for one
12
- // that has never picked one. The permission gate runs on both.
13
- return userPreferences.getMethod(scope) || config.CLAUDE_METHOD_DEFAULT;
14
- }
15
- /**
16
- * Which transport this chat's turns run through. Exported for the handlers
17
- * that need to match the transport's behaviour without routing a turn — e.g.
18
- * inspecting the CLI build that would actually serve the chat.
19
- */
20
- export function getActiveMethod(scope) {
21
- return getMethod(scope);
22
- }
23
- function getInternalProvider(scope) {
24
- const method = getMethod(scope);
25
- if (method === 'pty') {
26
- return ptyProvider;
27
- }
28
- return sdkProvider;
29
- }
30
- // This new claudeProvider is a router that delegates to either the
31
- // SDK or PTY provider based on user preference.
32
- export const claudeProvider = {
33
- name: 'claude',
34
- sendToAgent(sessionKey, message, options) {
35
- return getInternalProvider(sessionKey).sendToAgent(sessionKey, message, options);
36
- },
37
- sendLoopToAgent(sessionKey, message, options) {
38
- return getInternalProvider(sessionKey).sendLoopToAgent(sessionKey, message, options);
39
- },
40
- clearConversation(sessionKey) {
41
- getInternalProvider(sessionKey).clearConversation(sessionKey);
42
- },
43
- setModel(scope, model) {
44
- getInternalProvider(scope).setModel(scope, model);
45
- },
46
- getModel(scope) {
47
- return getInternalProvider(scope).getModel(scope);
48
- },
49
- clearModel(scope) {
50
- getInternalProvider(scope).clearModel(scope);
51
- },
52
- getCachedUsage(sessionKey) {
53
- return getInternalProvider(sessionKey).getCachedUsage(sessionKey);
54
- },
55
- isDangerousMode() {
56
- // This is consistent across both methods.
57
- return sdkProvider.isDangerousMode();
58
- },
59
- async getAvailableModels(scope) {
60
- return getInternalProvider(scope).getAvailableModels(scope);
61
- },
62
- };
9
+ export const claudeProvider = ptyProvider;
63
10
  //# sourceMappingURL=claude-provider.js.map