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
@@ -389,7 +389,7 @@ export async function handleAccessCallback(ctx) {
389
389
  await editCardOutcome(ctx, `🚫 ${describeUser(known)} was not let in.`);
390
390
  console.log(`[access] ${by} ignored ${describeUser(known)}`);
391
391
  }
392
- /** The role the sender holds here — used by /status to show it. */
392
+ /** The role the sender holds here — used by /info to show it. */
393
393
  export function describeRole(ctx) {
394
394
  const chatId = groupScope(ctx);
395
395
  const userId = ctx.from?.id;
@@ -1,27 +1,27 @@
1
1
  /**
2
- * Bot lifecycle commands: /update, /botstatus, /version, /restartbot, /rebuildbot.
2
+ * Bot lifecycle commands: /botupdate, /botstatus, /botversion, /botrestart, /botrebuild.
3
3
  *
4
4
  * These are the handlers that act on the bot process itself rather than on a
5
- * conversation, so they are the only ones that touch botctl, the reload marker
6
- * and the build.
5
+ * conversation, so they are the only ones that touch the reload marker and
6
+ * the build.
7
7
  */
8
8
  import * as fs from 'fs';
9
9
  import * as path from 'path';
10
- import { execFile, spawn } from 'child_process';
10
+ import { execFile } from 'child_process';
11
11
  import { isMainThread } from 'worker_threads';
12
12
  import { config, getReloadMarkerPath } from '../../../config.js';
13
13
  import { getModel } from '../../../providers/provider-router.js';
14
+ import { getPtyProvider } from '../../../providers/claude-provider.js';
15
+ import { readMemory } from '../../../utils/memory-pressure.js';
14
16
  import { EntityText } from '../../../telegram/entities.js';
15
17
  import { replyFormatted, replyParts } from '../../../telegram/send.js';
16
- import { sanitizeError } from '../../../utils/sanitize.js';
17
18
  import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
18
- import { botctlExists, PROJECT_ROOT, BOTCTL_PATH } from './shared.js';
19
- import { handleContinue, handleClear } from './session.js';
19
+ import { PROJECT_ROOT } from './shared.js';
20
+ import { continueLastSession, handleClear } from './session.js';
20
21
  import { handleResume } from './resume.js';
21
22
  import { requestRestart, requestRestartAll, requestRestartAllWhenIdle, controlIdleRestart, requestSiblingRestart, launcherIsStale, } from '../../../worker-restart.js';
22
23
  import { isSystemdService, getSystemdUnit, getRestartBehaviour, willRestartOnRequestedExit, manualRestartCommand, RESTART_EXIT_CODE, } from '../../../utils/systemd.js';
23
24
  import { launcherRestartHint } from '../../../utils/stale-launcher.js';
24
- import { getServiceManager } from '../../../utils/exit-codes.js';
25
25
  import { describeRunningBuild, getLatestBuild, getRunningBuild } from '../../../utils/build-info.js';
26
26
  import { checkCode, checkRemote, describeCodeCheck, describeRemoteCheck } from '../../../utils/version-check.js';
27
27
  import { isCheckout, detectPackageRunner, getInstalledVersion } from '../../../utils/install-mode.js';
@@ -57,7 +57,7 @@ export async function sendRestoreButtons(ctx) {
57
57
  });
58
58
  }
59
59
  catch (e) {
60
- console.debug('[RestartBot] Failed to send restore buttons:', e instanceof Error ? e.message : e);
60
+ console.debug('[BotRestart] Failed to send restore buttons:', e instanceof Error ? e.message : e);
61
61
  }
62
62
  }
63
63
  async function getClaudeVersion() {
@@ -90,9 +90,9 @@ async function runClaudeUpdate() {
90
90
  });
91
91
  });
92
92
  }
93
- export async function handleUpdate(ctx) {
93
+ export async function handleBotUpdate(ctx) {
94
94
  // An npm install updates itself too; a checkout updates with git pull and
95
- // /rebuildbot, so there /update stays about Claude Code alone.
95
+ // /botrebuild, so there /botupdate stays about Claude Code alone.
96
96
  if (!isCheckout()) {
97
97
  await offerPackageUpdate(ctx);
98
98
  return;
@@ -105,14 +105,14 @@ export async function handleUpdate(ctx) {
105
105
  reply_markup: {
106
106
  inline_keyboard: [
107
107
  [
108
- { text: '✅ Update', callback_data: 'update:confirm' },
109
- { text: '❌ Cancel', callback_data: 'update:cancel' },
108
+ { text: '✅ Update', callback_data: 'botupdate:confirm' },
109
+ { text: '❌ Cancel', callback_data: 'botupdate:cancel' },
110
110
  ],
111
111
  ],
112
112
  },
113
113
  });
114
114
  }
115
- export async function handleUpdateCallback(ctx) {
115
+ export async function handleBotUpdateCallback(ctx) {
116
116
  const data = ctx.callbackQuery?.data;
117
117
  if (!data)
118
118
  return;
@@ -124,15 +124,15 @@ export async function handleUpdateCallback(ctx) {
124
124
  catch {
125
125
  // ignore — message may have been edited or deleted
126
126
  }
127
- if (data === 'update:cancel') {
127
+ if (data === 'botupdate:cancel') {
128
128
  await ctx.reply('❌ Update cancelled.');
129
129
  return;
130
130
  }
131
- if (data === 'update:telecoder') {
131
+ if (data === 'botupdate:telecoder') {
132
132
  await updateTeleCoder(ctx);
133
133
  return;
134
134
  }
135
- if (data !== 'update:confirm')
135
+ if (data !== 'botupdate:confirm')
136
136
  return;
137
137
  const chatId = ctx.chat?.id;
138
138
  const ack = await ctx.reply('⬆️ Updating Claude Code…');
@@ -168,7 +168,7 @@ export async function handleUpdateCallback(ctx) {
168
168
  }
169
169
  }
170
170
  }
171
- /** The /update menu of a package install: TeleCoder itself, or Claude Code. */
171
+ /** The /botupdate menu of a package install: TeleCoder itself, or Claude Code. */
172
172
  async function offerPackageUpdate(ctx) {
173
173
  const [claudeVersion, latest] = await Promise.all([getClaudeVersion(), getLatestVersion()]);
174
174
  const check = compareInstalled(getInstalledVersion(), latest);
@@ -182,13 +182,13 @@ async function offerPackageUpdate(ctx) {
182
182
  // Only a global install can replace itself: npx and a local install are
183
183
  // updated from wherever they were started.
184
184
  const telecoderButton = runner === 'global'
185
- ? [{ text: '⬆️ TeleCoder', callback_data: 'update:telecoder' }]
185
+ ? [{ text: '⬆️ TeleCoder', callback_data: 'botupdate:telecoder' }]
186
186
  : [];
187
187
  await ctx.reply(lines.join('\n'), {
188
188
  reply_markup: {
189
189
  inline_keyboard: [
190
- [...telecoderButton, { text: '⬆️ Claude Code', callback_data: 'update:confirm' }],
191
- [{ text: '❌ Cancel', callback_data: 'update:cancel' }],
190
+ [...telecoderButton, { text: '⬆️ Claude Code', callback_data: 'botupdate:confirm' }],
191
+ [{ text: '❌ Cancel', callback_data: 'botupdate:cancel' }],
192
192
  ],
193
193
  },
194
194
  });
@@ -216,7 +216,7 @@ async function updateTeleCoder(ctx) {
216
216
  if (raw)
217
217
  b.pre(raw.slice(-1500)).newline(2);
218
218
  b.add(installed ? `v${installed} is installed. ` : 'Installed. ')
219
- .add('It runs from the next restart: /restartbot.');
219
+ .add('It runs from the next restart: /botrestart.');
220
220
  await replyParts(ctx, b.build());
221
221
  }
222
222
  catch (error) {
@@ -226,7 +226,7 @@ async function updateTeleCoder(ctx) {
226
226
  b.newline(2)
227
227
  .add("npm can't write to its global directory as this user. Run ")
228
228
  .code(updateCommand('global'))
229
- .add(' yourself (with the rights it needs), then /restartbot.');
229
+ .add(' yourself (with the rights it needs), then /botrestart.');
230
230
  }
231
231
  await replyParts(ctx, b.build());
232
232
  }
@@ -251,10 +251,8 @@ export async function handleBotStatus(ctx) {
251
251
  : minutes > 0
252
252
  ? `${minutes}m ${seconds}s`
253
253
  : `${seconds}s`;
254
- const mode = config.BOT_MODE === 'prod' ? 'Production' : 'Development';
255
254
  const keyInfo = getSessionKeyFromCtx(ctx);
256
255
  const model = keyInfo ? getModel(keyInfo.sessionKey) : 'opus';
257
- const streaming = config.STREAMING_MODE || 'streaming';
258
256
  const pid = process.pid;
259
257
  const memMB = (process.memoryUsage.rss() / 1024 / 1024).toFixed(1);
260
258
  // The uptime above is this worker's, and a worker that restarted an hour ago
@@ -264,19 +262,25 @@ export async function handleBotStatus(ctx) {
264
262
  const msg = new EntityText().add('🟢 ').bold(`${config.BOT_NAME} is running`).newline(2);
265
263
  /** A `Label: value` line; every one but the last ends in a newline. */
266
264
  const field = (label, value) => msg.bold(`${label}:`).add(` ${value}`);
267
- field('Mode', mode).newline();
268
265
  if (build)
269
266
  field('Version', build).newline();
270
267
  field('Uptime', uptimeStr).newline();
271
268
  field('PID', String(pid)).newline();
272
269
  field('Memory', `${memMB} MB`).newline();
273
- field('Model', model).newline();
274
- field('Streaming', streaming);
270
+ const machine = readMemory();
271
+ if (machine) {
272
+ const swap = machine.swapTotalMB > 0 ? `, swap ${machine.swapUsedMB.toLocaleString('en-US')} MB in use` : '';
273
+ field('Machine', `${machine.availableMB.toLocaleString('en-US')} MB available of ${machine.totalMB.toLocaleString('en-US')} MB${swap}`).newline();
274
+ }
275
+ const claudes = getPtyProvider().describeSessions();
276
+ const generating = claudes.filter((s) => s.generating).length;
277
+ field('Claude processes', claudes.length === 0 ? 'none' : `${claudes.length} (${generating} generating)`).newline();
278
+ field('Model', model);
275
279
  if (warning)
276
280
  msg.newline(2).add(warning);
277
281
  await replyFormatted(ctx, msg.build());
278
282
  }
279
- export async function handleVersion(ctx) {
283
+ export async function handleBotVersion(ctx) {
280
284
  if (!isCheckout()) {
281
285
  await handlePackageVersion(ctx);
282
286
  return;
@@ -294,7 +298,7 @@ export async function handleVersion(ctx) {
294
298
  // Plain text: a commit subject goes out exactly as written.
295
299
  await ctx.reply(warning ? `${answer}\n\n${warning}` : answer);
296
300
  }
297
- /** /version for a package install: the installed version against npm's latest. */
301
+ /** /botversion for a package install: the installed version against npm's latest. */
298
302
  async function handlePackageVersion(ctx) {
299
303
  const installed = getInstalledVersion();
300
304
  const [latest, warning] = await Promise.all([getLatestVersion(), staleLauncherWarning()]);
@@ -316,9 +320,8 @@ async function handlePackageVersion(ctx) {
316
320
  */
317
321
  async function planRestart() {
318
322
  if (isSystemdService()) {
319
- // botctl is not an option here: it would be reaped with us (see
320
- // utils/systemd.ts). Exiting and letting systemd restart us is, but only
321
- // if the unit is set up to.
323
+ // Exiting and letting systemd restart us works only if the unit is set up
324
+ // to (see utils/systemd.ts).
322
325
  const unit = getSystemdUnit();
323
326
  if (!unit) {
324
327
  return {
@@ -364,38 +367,21 @@ async function planRestart() {
364
367
  }
365
368
  return { plan: { kind: 'systemd', unit } };
366
369
  }
367
- // A checkout under the launchd agent `telecoder service install
368
- // --from-checkout` writes takes this path too: botctl would start a second
369
- // copy beside the one launchd is about to bring back.
370
- if (!isCheckout() || getServiceManager() === 'launchd') {
371
- // A package install has no botctl. It expects a supervisor (a systemd or
372
- // launchd unit with Restart=always, pm2, ...) that starts it again when it
373
- // exits — and in a terminal there is none, so there it says so instead.
374
- if (process.stdin.isTTY && process.stdout.isTTY) {
375
- return {
376
- error: new EntityText()
377
- .add('This bot is running in a terminal, so nothing would start it again after it exits.')
378
- .newline(2)
379
- .add('Stop it there and run ')
380
- .code('telecoder start')
381
- .add(' again, or run it as a service so restarts work from chat.')
382
- .build(),
383
- };
384
- }
385
- return { plan: { kind: 'exit' } };
386
- }
387
- if (!botctlExists()) {
370
+ // Anything else expects a supervisor (a launchd unit with KeepAlive, pm2,
371
+ // ...) that starts it again when it exits — and in a terminal there is none,
372
+ // so there it says so instead.
373
+ if (process.stdin.isTTY && process.stdout.isTTY) {
388
374
  return {
389
375
  error: new EntityText()
390
- .add('Bot control script not found.')
376
+ .add('This bot is running in a terminal, so nothing would start it again after it exits.')
391
377
  .newline(2)
392
- .add('Expected at ')
393
- .code('scripts/telecoder-botctl.sh')
394
- .add('.')
378
+ .add('Stop it there and run ')
379
+ .code(isCheckout() ? 'npm start' : 'telecoder start')
380
+ .add(' again, or run it as a service so restarts work from chat.')
395
381
  .build(),
396
382
  };
397
383
  }
398
- return { plan: { kind: 'botctl' } };
384
+ return { plan: { kind: 'exit' } };
399
385
  }
400
386
  /**
401
387
  * Act on a plan from `planRestart`. The systemd path does not come back — the
@@ -410,22 +396,12 @@ function executeRestart(plan) {
410
396
  process.kill(process.pid, 'SIGTERM');
411
397
  return;
412
398
  }
413
- if (plan.kind === 'systemd') {
414
- // The exit *is* the restart. Non-zero so both Restart=always and
415
- // Restart=on-failure act on it; SIGTERM rather than process.exit so the
416
- // normal graceful shutdown still runs.
417
- console.log(`[Restart] Exiting for systemd to restart ${plan.unit.name}`);
418
- process.exitCode = RESTART_EXIT_CODE;
419
- process.kill(process.pid, 'SIGTERM');
420
- return;
421
- }
422
- try {
423
- const child = spawn(BOTCTL_PATH, ['recover'], { cwd: PROJECT_ROOT, detached: true, stdio: 'ignore', env: { ...process.env, MODE: config.BOT_MODE } });
424
- child.unref();
425
- }
426
- catch (error) {
427
- console.error('[BotCtl] Failed to restart:', sanitizeError(error));
428
- }
399
+ // The exit *is* the restart. Non-zero so both Restart=always and
400
+ // Restart=on-failure act on it; SIGTERM rather than process.exit so the
401
+ // normal graceful shutdown still runs.
402
+ console.log(`[Restart] Exiting for systemd to restart ${plan.unit.name}`);
403
+ process.exitCode = RESTART_EXIT_CODE;
404
+ process.kill(process.pid, 'SIGTERM');
429
405
  }
430
406
  async function performRestart(ctx, scope) {
431
407
  // Multi-instance mode (worker thread) — restart via launcher, not shell script
@@ -458,7 +434,7 @@ async function performRestart(ctx, scope) {
458
434
  requestRestart();
459
435
  return;
460
436
  }
461
- // Single-instance mode — systemd restarts us, or botctl starts a successor
437
+ // Single-instance mode — the supervisor restarts us once we exit
462
438
  const planned = await planRestart();
463
439
  if ('error' in planned) {
464
440
  await replyFormatted(ctx, new EntityText().add('❌ Cannot restart.').newline(2).append(planned.error).build());
@@ -480,9 +456,9 @@ async function performRestart(ctx, scope) {
480
456
  }
481
457
  executeRestart(planned.plan);
482
458
  }
483
- export async function handleRestartBot(ctx) {
459
+ export async function handleBotRestart(ctx) {
484
460
  const args = ctx.message?.text?.split(/\s+/).slice(1).join(' ').trim();
485
- // Cross-bot restart: /restartbot <name> — direct, no menu
461
+ // Cross-bot restart: /botrestart <name> — direct, no menu
486
462
  if (args && !isMainThread && args.toLowerCase() !== 'all' && args.toLowerCase() !== 'one' && args.toLowerCase() !== 'this') {
487
463
  const result = await requestSiblingRestart(args, config.AUTO_RESTORE_SESSION);
488
464
  if (result.success) {
@@ -501,7 +477,7 @@ export async function handleRestartBot(ctx) {
501
477
  }
502
478
  return;
503
479
  }
504
- // Legacy direct invocations: /restartbot all | /restartbot one | /restartbot this
480
+ // Legacy direct invocations: /botrestart all | /botrestart one | /botrestart this
505
481
  if (args?.toLowerCase() === 'all') {
506
482
  await performRestart(ctx, 'all');
507
483
  return;
@@ -516,8 +492,8 @@ export async function handleRestartBot(ctx) {
516
492
  reply_markup: {
517
493
  inline_keyboard: [
518
494
  [
519
- { text: '✅ Restart', callback_data: 'restartbot:one' },
520
- { text: '❌ Cancel', callback_data: 'restartbot:cancel' },
495
+ { text: '✅ Restart', callback_data: 'botrestart:one' },
496
+ { text: '❌ Cancel', callback_data: 'botrestart:cancel' },
521
497
  ],
522
498
  ],
523
499
  },
@@ -528,14 +504,14 @@ export async function handleRestartBot(ctx) {
528
504
  await ctx.reply('🔁 Restart which?', {
529
505
  reply_markup: {
530
506
  inline_keyboard: [
531
- [{ text: '🔧 This instance only', callback_data: 'restartbot:one' }],
532
- [{ text: '🌐 All instances', callback_data: 'restartbot:all' }],
533
- [{ text: '❌ Cancel', callback_data: 'restartbot:cancel' }],
507
+ [{ text: '🔧 This instance only', callback_data: 'botrestart:one' }],
508
+ [{ text: '🌐 All instances', callback_data: 'botrestart:all' }],
509
+ [{ text: '❌ Cancel', callback_data: 'botrestart:cancel' }],
534
510
  ],
535
511
  },
536
512
  });
537
513
  }
538
- export async function handleRestartBotCallback(ctx) {
514
+ export async function handleBotRestartCallback(ctx) {
539
515
  const data = ctx.callbackQuery?.data;
540
516
  if (!data)
541
517
  return;
@@ -547,15 +523,15 @@ export async function handleRestartBotCallback(ctx) {
547
523
  catch {
548
524
  // ignore — message may have been edited or deleted
549
525
  }
550
- if (data === 'restartbot:cancel') {
526
+ if (data === 'botrestart:cancel') {
551
527
  await ctx.reply('❌ Restart cancelled.');
552
528
  return;
553
529
  }
554
- if (data === 'restartbot:all') {
530
+ if (data === 'botrestart:all') {
555
531
  await performRestart(ctx, 'all');
556
532
  return;
557
533
  }
558
- if (data === 'restartbot:one') {
534
+ if (data === 'botrestart:one') {
559
535
  await performRestart(ctx, 'one');
560
536
  return;
561
537
  }
@@ -598,7 +574,7 @@ async function performRebuild(ctx, scope) {
598
574
  // Only a launcher can wait on other instances; checked before building, so
599
575
  // the answer isn't a build nobody restarts onto.
600
576
  if (scope === 'idle' && isMainThread) {
601
- await ctx.reply('⚠️ "When idle" restarts the instances of a multi-instance setup — this bot runs on its own. Use /rebuildbot to rebuild and restart it now.');
577
+ await ctx.reply('⚠️ "When idle" restarts the instances of a multi-instance setup — this bot runs on its own. Use /botrebuild to rebuild and restart it now.');
602
578
  return;
603
579
  }
604
580
  // Step 1: Build
@@ -677,7 +653,7 @@ async function restartAllWhenIdle(ctx, warning) {
677
653
  // which the stale check usually says outright.
678
654
  const text = '✅ Build succeeded, but the launcher did not take the restart — it is running code from '
679
655
  + `before "when idle" existed, so nothing is restarting. To pick it up, ${launcherRestartHint()}; that drops `
680
- + 'every live session. /rebuildbot all restarts the instances now instead.';
656
+ + 'every live session. /botrebuild all restarts the instances now instead.';
681
657
  try {
682
658
  await ctx.api.editMessageText(chatId, status.message_id, text);
683
659
  }
@@ -686,21 +662,21 @@ async function restartAllWhenIdle(ctx, warning) {
686
662
  }
687
663
  }
688
664
  /**
689
- * /rebuildbot needs the source to build, which only a checkout has. Says so,
665
+ * /botrebuild needs the source to build, which only a checkout has. Says so,
690
666
  * and returns true, when this isn't one.
691
667
  */
692
668
  async function refuseRebuildOutsideCheckout(ctx) {
693
669
  if (isCheckout())
694
670
  return false;
695
- await ctx.reply('⚠️ /rebuildbot rebuilds a source checkout of TeleCoder, and this one was installed from npm — there is no source here to build. '
696
- + 'Use /update to install a newer release, and /restartbot to restart.');
671
+ await ctx.reply('⚠️ /botrebuild rebuilds a source checkout of TeleCoder, and this one was installed from npm — there is no source here to build. '
672
+ + 'Use /botupdate to install a newer release, and /botrestart to restart.');
697
673
  return true;
698
674
  }
699
- export async function handleRebuild(ctx) {
675
+ export async function handleBotRebuild(ctx) {
700
676
  if (await refuseRebuildOutsideCheckout(ctx))
701
677
  return;
702
678
  const args = ctx.message?.text?.split(/\s+/).slice(1).join(' ').trim();
703
- // Legacy direct invocation: /rebuildbot all
679
+ // Legacy direct invocation: /botrebuild all
704
680
  if (args?.toLowerCase() === 'all') {
705
681
  await performRebuild(ctx, 'all');
706
682
  return;
@@ -720,8 +696,8 @@ export async function handleRebuild(ctx) {
720
696
  reply_markup: {
721
697
  inline_keyboard: [
722
698
  [
723
- { text: '✅ Rebuild', callback_data: 'rebuild:one' },
724
- { text: '❌ Cancel', callback_data: 'rebuild:cancel' },
699
+ { text: '✅ Rebuild', callback_data: 'botrebuild:one' },
700
+ { text: '❌ Cancel', callback_data: 'botrebuild:cancel' },
725
701
  ],
726
702
  ],
727
703
  },
@@ -732,15 +708,15 @@ export async function handleRebuild(ctx) {
732
708
  await ctx.reply('🔄 Rebuild and restart which?', {
733
709
  reply_markup: {
734
710
  inline_keyboard: [
735
- [{ text: '🔧 This instance only', callback_data: 'rebuild:one' }],
736
- [{ text: '🌐 All instances', callback_data: 'rebuild:all' }],
737
- [{ text: '⏳ All instances, each once it is idle', callback_data: 'rebuild:idle' }],
738
- [{ text: '❌ Cancel', callback_data: 'rebuild:cancel' }],
711
+ [{ text: '🔧 This instance only', callback_data: 'botrebuild:one' }],
712
+ [{ text: '🌐 All instances', callback_data: 'botrebuild:all' }],
713
+ [{ text: '⏳ All instances, each once it is idle', callback_data: 'botrebuild:idle' }],
714
+ [{ text: '❌ Cancel', callback_data: 'botrebuild:cancel' }],
739
715
  ],
740
716
  },
741
717
  });
742
718
  }
743
- export async function handleRebuildCallback(ctx) {
719
+ export async function handleBotRebuildCallback(ctx) {
744
720
  const data = ctx.callbackQuery?.data;
745
721
  if (!data)
746
722
  return;
@@ -752,29 +728,29 @@ export async function handleRebuildCallback(ctx) {
752
728
  catch {
753
729
  // ignore — message may have been edited or deleted
754
730
  }
755
- if (data === 'rebuild:cancel') {
731
+ if (data === 'botrebuild:cancel') {
756
732
  await ctx.reply('❌ Rebuild cancelled.');
757
733
  return;
758
734
  }
759
735
  if (await refuseRebuildOutsideCheckout(ctx))
760
736
  return;
761
- if (data === 'rebuild:all') {
737
+ if (data === 'botrebuild:all') {
762
738
  await performRebuild(ctx, 'all');
763
739
  return;
764
740
  }
765
- if (data === 'rebuild:one') {
741
+ if (data === 'botrebuild:one') {
766
742
  await performRebuild(ctx, 'one');
767
743
  return;
768
744
  }
769
- if (data === 'rebuild:idle') {
745
+ if (data === 'botrebuild:idle') {
770
746
  await performRebuild(ctx, 'idle');
771
747
  return;
772
748
  }
773
749
  // The buttons on the "when idle" status message. The launcher redraws that
774
750
  // message itself, buttons and all, so a tap only needs an answer when there
775
751
  // was nothing left to act on.
776
- if (data === 'rebuild:idle_force' || data === 'rebuild:idle_cancel') {
777
- const found = await controlIdleRestart(data === 'rebuild:idle_force' ? 'force' : 'cancel');
752
+ if (data === 'botrebuild:idle_force' || data === 'botrebuild:idle_cancel') {
753
+ const found = await controlIdleRestart(data === 'botrebuild:idle_force' ? 'force' : 'cancel');
778
754
  if (!found)
779
755
  await ctx.reply('Nothing is waiting to restart any more.');
780
756
  return;
@@ -786,7 +762,7 @@ export async function handleRestartCallback(ctx) {
786
762
  return;
787
763
  if (data === 'restart:continue') {
788
764
  await ctx.answerCallbackQuery();
789
- await handleContinue(ctx);
765
+ await continueLastSession(ctx);
790
766
  }
791
767
  else if (data === 'restart:resume') {
792
768
  await ctx.answerCallbackQuery();
@@ -814,7 +790,7 @@ export async function handleStartupCallback(ctx) {
814
790
  // ignore — message may have been edited or deleted
815
791
  }
816
792
  if (data === 'startup:continue') {
817
- await handleContinue(ctx);
793
+ await continueLastSession(ctx);
818
794
  return;
819
795
  }
820
796
  if (data === 'startup:fresh') {
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Telling a command typed in a bot's "All" view from one typed in a thread.
3
+ *
4
+ * Telegram has no chat-level place to type in a private chat with threads:
5
+ * a message sent from the "All" view opens a new thread, named "New chat",
6
+ * and arrives inside it. A bare `/model fable` there pins that thread like
7
+ * anywhere else, which is how to start one thread on another model while new
8
+ * threads keep the default. A wider level typed there (`/model opus new`)
9
+ * leaves the thread with nothing in it, so that confirmation offers to
10
+ * delete it.
11
+ */
12
+ import { sessionManager } from '../../../claude/session-manager.js';
13
+ import { hasImplicitName } from '../../../telegram/thread-titles.js';
14
+ import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
15
+ /**
16
+ * Whether this update comes from a private-chat thread opened from the "All"
17
+ * view that no conversation has happened in yet. Works for a typed command,
18
+ * whose creation notice says the name was implicit, and for a button tapped
19
+ * in that thread afterwards, through the name recorded from that notice.
20
+ */
21
+ export function isFreshAllViewThread(ctx) {
22
+ const keyInfo = getSessionKeyFromCtx(ctx);
23
+ if (!keyInfo || keyInfo.threadId === undefined || keyInfo.chatId <= 0)
24
+ return false;
25
+ const { sessionKey } = keyInfo;
26
+ const created = ctx.message?.reply_to_message?.forum_topic_created;
27
+ if (!created?.is_name_implicit && !hasImplicitName(sessionKey))
28
+ return false;
29
+ if (sessionManager.getSession(sessionKey)?.claudeSessionId)
30
+ return false;
31
+ return sessionManager.getSessionHistory(sessionKey, 1).length === 0;
32
+ }
33
+ //# sourceMappingURL=all-view.js.map
@@ -44,7 +44,7 @@ export async function handleAutoApprove(ctx) {
44
44
  return;
45
45
  }
46
46
  if (lowered === 'status') {
47
- await handleStatus(ctx, chatId);
47
+ await handleInfo(ctx, chatId);
48
48
  return;
49
49
  }
50
50
  const duration = parseWindowDuration(arg);
@@ -57,7 +57,7 @@ export async function handleAutoApprove(ctx) {
57
57
  async function handleOpen(ctx, chatId, durationMs) {
58
58
  const existing = getWindow(chatId);
59
59
  const openerName = describeOpener(ctx);
60
- const window = openWindow(chatId, {
60
+ openWindow(chatId, {
61
61
  openedBy: ctx.from?.id ?? 0,
62
62
  openedByName: openerName,
63
63
  durationMs,
@@ -100,7 +100,7 @@ async function handleClose(ctx, chatId) {
100
100
  b.add('\n\n').italic(`It was ${closed.openedByName}'s window.`);
101
101
  await replyFormatted(ctx, b.build());
102
102
  }
103
- async function handleStatus(ctx, chatId) {
103
+ async function handleInfo(ctx, chatId) {
104
104
  const window = getWindow(chatId);
105
105
  if (!window) {
106
106
  const b = heading('🔒', 'Auto-approve is off here.')
@@ -0,0 +1,37 @@
1
+ /**
2
+ * /ctrlb: Claude Code's Ctrl+B, for a chat that has no such key.
3
+ *
4
+ * In a terminal, Ctrl+B moves the shell command or subagent a turn is waiting
5
+ * on to the background: the turn carries on at once, and the command reports
6
+ * back when it ends, as one started in the background does. Here the command
7
+ * does the pressing. The status line offers it while Claude Code's own screen
8
+ * offers the key, and the provider presses it only then.
9
+ *
10
+ * Registered ahead of the per-chat queue: it is for a turn that is running.
11
+ */
12
+ import { getPtyProvider } from '../../../providers/claude-provider.js';
13
+ import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
14
+ /** What the chat is told for each way a press can go. Exported for tests. */
15
+ export function backgroundReply(result) {
16
+ if (result.ok)
17
+ return '⏬ Moved to the background. Claude carries on without waiting for it · /tasks';
18
+ switch (result.reason) {
19
+ case 'no-session':
20
+ case 'not-offered':
21
+ return 'ℹ️ Nothing to move to the background. That takes a shell command or subagent Claude is waiting on; the live status message offers /ctrlb while there is one.';
22
+ case 'dialog-open':
23
+ return 'ℹ️ Claude Code has a dialog open, which takes the keys. Answer it first.';
24
+ case 'unknown-key':
25
+ return `⚠️ Claude Code names "${result.key}" as its key for this, which the bot can't press.`;
26
+ case 'still-running':
27
+ return "⚠️ Pressed Claude Code's key, but what is running stayed in the foreground.";
28
+ }
29
+ }
30
+ export async function handleCtrlB(ctx) {
31
+ const keyInfo = getSessionKeyFromCtx(ctx);
32
+ if (!keyInfo)
33
+ return;
34
+ const result = await getPtyProvider().moveToBackground(keyInfo.sessionKey);
35
+ await ctx.reply(backgroundReply(result));
36
+ }
37
+ //# sourceMappingURL=background.js.map