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
@@ -1,8 +1,8 @@
1
1
  /**
2
- * Applying one chat's model or effort choice to every bot instance at once.
2
+ * Applying a model or effort choice on every bot instance at once — the
3
+ * "everywhere" level of /model and /effort.
3
4
  *
4
- * Preferences are per-bot (see user-preferences.ts), which is the right default
5
- * — but "put all my bots on Haiku" is a real thing to want, and writing to the
5
+ * Preferences are per-bot (see user-preferences.ts), and writing to the
6
6
  * siblings' files behind their backs would not work: every worker holds its
7
7
  * preferences in memory and would overwrite the edit on its next save, and the
8
8
  * pty reads `--model` at spawn, so a bot with a live session would go on using
@@ -10,20 +10,18 @@
10
10
  *
11
11
  * So the change is sent, not written. The requesting worker asks the launcher
12
12
  * to relay it; each sibling applies it through the same code path as a local
13
- * /model, tears down the pty sessions for that chat so the next turn respawns
14
- * with the new flag, and reports back what it did. The requester waits for the
15
- * round trip so it can tell the user which bots actually took the change.
13
+ * change at that level, restarts the claudes it concerns, and reports back
14
+ * what it did. The requester waits for the round trip so it can tell the user
15
+ * which bots actually took the change.
16
16
  *
17
17
  * Single-instance mode has no launcher to relay through: every function here
18
18
  * degrades to "this bot only" rather than failing.
19
19
  */
20
20
  import { isMainThread, parentPort } from 'worker_threads';
21
21
  import { BOT_ID } from '../config.js';
22
- import { isInFlight } from '../claude/in-flight-tracker.js';
23
22
  import { listSiblingBots } from '../utils/instances.js';
24
- import { getPtyProvider } from './claude-provider.js';
25
- import { setModel, clearModel, setEffort, clearEffort, getActiveProviderName, isValidEffortLevel, } from './provider-router.js';
26
- import { userPreferences } from './user-preferences.js';
23
+ import { getActiveProviderName, isValidEffortLevel } from './provider-router.js';
24
+ import { applySpawnSetting } from './spawn-settings.js';
27
25
  /** Bots other than this one, from instances.json. Empty in single-bot setups. */
28
26
  export function siblingBotNames() {
29
27
  if (isMainThread)
@@ -34,16 +32,10 @@ export function siblingBotNames() {
34
32
  // Applying a change locally (the receiving side)
35
33
  // ---------------------------------------------------------------------------
36
34
  /**
37
- * Apply a relayed change to this instance.
38
- *
39
- * Goes through provider-router rather than the preferences file directly, so
40
- * the in-memory caches that actually serve the next turn are updated too.
41
- *
42
- * A pty holding a session that is mid-turn is left alone: killing it would
43
- * abort a turn nobody in this chat asked to interrupt, and the user isn't
44
- * watching that bot — they're in the one they typed the command into. Those
45
- * sessions keep the old value until they next respawn, and the count comes
46
- * back so the confirmation can say so.
35
+ * Apply a relayed change to this instance, at the level it was made, and
36
+ * restart the claudes it concerns: idle ones on their next message, mid-turn
37
+ * ones when that turn ends. The count of the latter comes back so the
38
+ * confirmation can say so.
47
39
  */
48
40
  export function applyPrefsChange(change) {
49
41
  const { chatId } = change;
@@ -51,46 +43,11 @@ export function applyPrefsChange(change) {
51
43
  if (active !== change.provider) {
52
44
  return { name: '', status: 'skipped', reason: `on ${active}, not ${change.provider}` };
53
45
  }
54
- if (change.setting === 'model') {
55
- if (change.value === null)
56
- clearModel(chatId);
57
- else
58
- setModel(chatId, change.value);
59
- }
60
- else {
61
- if (change.value === null) {
62
- clearEffort(chatId);
63
- }
64
- else if (isValidEffortLevel(change.value)) {
65
- setEffort(chatId, change.value);
66
- }
67
- else {
68
- return { name: '', status: 'skipped', reason: `unknown effort level "${change.value}"` };
69
- }
70
- }
71
- return { name: '', status: 'applied', busy: restartPtySessionsForChat(chatId) };
72
- }
73
- /**
74
- * Tear down this chat's idle pty sessions so the next turn respawns with the
75
- * new flag. Returns how many were left running because they were mid-turn.
76
- * Only sessions that actually run on the pty transport count; with threads,
77
- * that is decided per thread, since each can have picked its own.
78
- */
79
- function restartPtySessionsForChat(chatId) {
80
- const pty = getPtyProvider();
81
- let busy = 0;
82
- for (const sessionKey of pty.listSessionKeysForChat(chatId)) {
83
- if (getActiveProviderName(sessionKey) !== 'claude')
84
- continue;
85
- if (userPreferences.getMethod(sessionKey) !== 'pty')
86
- continue;
87
- if (isInFlight(sessionKey)) {
88
- busy++;
89
- continue;
90
- }
91
- pty.clearConversation(sessionKey);
46
+ if (change.setting === 'effort' && change.value !== null && !isValidEffortLevel(change.value)) {
47
+ return { name: '', status: 'skipped', reason: `unknown effort level "${change.value}"` };
92
48
  }
93
- return busy;
49
+ const outcome = applySpawnSetting(chatId, change.setting, change.value, change.level ?? 'chat');
50
+ return { name: '', status: 'applied', busy: outcome.busy.length };
94
51
  }
95
52
  /**
96
53
  * Listen for changes relayed from sibling bots. Called once at startup; a
@@ -1,7 +1,7 @@
1
1
  import { config } from '../config.js';
2
2
  import { claudeProvider } from './claude-provider.js';
3
3
  import { ccrProvider } from './ccr-provider.js';
4
- import { setEffort as claudeSetEffort, getEffort as claudeGetEffort, clearEffort as claudeClearEffort, isValidEffortLevel, } from '../claude/agent.js';
4
+ import { isValidEffortLevel } from '../claude/effort-level.js';
5
5
  import { userPreferences } from './user-preferences.js';
6
6
  import { isPremiumModel } from '../claude/model-catalog.js';
7
7
  function getProvider(scope) {
@@ -15,7 +15,7 @@ function getProvider(scope) {
15
15
  }
16
16
  return claudeProvider;
17
17
  }
18
- // --- Public API (identical signatures to agent.ts) ---
18
+ // --- Public API ---
19
19
  /**
20
20
  * The backend a chat or thread runs on. Read straight from the preferences,
21
21
  * which are in memory already: a cache of its own here would go stale for the
@@ -39,18 +39,30 @@ export function getAvailableProviders() {
39
39
  * The screening point for guest messages.
40
40
  *
41
41
  * Every user-originated prompt funnels through the two exports below — typed
42
- * text, a transcribed voice note, a photo caption, a reply, /plan, /explore,
43
- * /btw — so this is the one place a hold can be applied without having to be
44
- * remembered at a dozen call sites. Loop iterations and scheduled fires call
45
- * their provider directly and are deliberately not re-screened: they are
46
- * continuations of a prompt that was already screened once.
42
+ * text, a transcribed voice note, a photo caption, a reply, /btw — so this is
43
+ * the one place a hold can be applied without having to be remembered at a
44
+ * dozen call sites. A scheduled prompt comes through here as well, each time
45
+ * it fires.
46
+ *
47
+ * Two checks. A `!command` runs in Claude Code's shell mode without a tool
48
+ * call, so the permission gate's hook never sees it and it is put to the gate
49
+ * here (shell-mode-gate.ts). Then the charter judge reads a guest's message.
50
+ * A command an approver has just allowed skips the judge: they read exactly
51
+ * what will run, and a hold would ask them the same thing again.
47
52
  *
48
53
  * A blocked message returns as an ordinary response rather than an error, so
49
54
  * the streaming UI already in flight renders the explanation in place.
50
55
  */
51
56
  async function screened(sessionKey, message, options) {
57
+ const ctx = options?.telegramCtx;
58
+ const { screenShellCommand } = await import('../claude/shell-mode-gate.js');
59
+ const shell = await screenShellCommand(ctx, sessionKey, message);
60
+ if (!shell.proceed)
61
+ return { text: shell.message, toolsUsed: [] };
62
+ if (shell.approved)
63
+ return null;
52
64
  const { screenPrompt } = await import('../claude/prompt-hold.js');
53
- const outcome = await screenPrompt(options?.telegramCtx, sessionKey, message);
65
+ const outcome = await screenPrompt(ctx, sessionKey, message);
54
66
  if (outcome.proceed)
55
67
  return null;
56
68
  return { text: outcome.message, toolsUsed: [] };
@@ -62,13 +74,6 @@ export async function sendToAgent(sessionKey, message, options) {
62
74
  const providerName = getActiveProviderName(sessionKey);
63
75
  return getProvider(sessionKey).sendToAgent(sessionKey, message, { ...options, providerName });
64
76
  }
65
- export async function sendLoopToAgent(sessionKey, message, options) {
66
- const blocked = await screened(sessionKey, message, options);
67
- if (blocked)
68
- return blocked;
69
- const providerName = getActiveProviderName(sessionKey);
70
- return getProvider(sessionKey).sendLoopToAgent(sessionKey, message, { ...options, providerName });
71
- }
72
77
  export function clearConversation(sessionKey) {
73
78
  // Clear all providers to avoid stale state
74
79
  claudeProvider.clearConversation(sessionKey);
@@ -102,20 +107,16 @@ export function clearModel(scope) {
102
107
  export function getCachedUsage(sessionKey) {
103
108
  return getProvider(sessionKey).getCachedUsage(sessionKey);
104
109
  }
105
- export function isDangerousMode() {
106
- // Dangerous mode is a Claude-specific concept; always check Claude provider
107
- return claudeProvider.isDangerousMode();
108
- }
109
- // Effort is Claude-specific; re-export directly from agent.ts
110
+ // Effort is Claude-specific; re-exported from claude/effort-level.ts
110
111
  export { isValidEffortLevel };
111
112
  export function setEffort(scope, effort) {
112
- claudeSetEffort(scope, effort);
113
+ userPreferences.setEffort(scope, effort);
113
114
  }
114
115
  export function getEffort(scope) {
115
- return claudeGetEffort(scope);
116
+ return userPreferences.getEffort(scope);
116
117
  }
117
118
  export function clearEffort(scope) {
118
- claudeClearEffort(scope);
119
+ userPreferences.clearEffort(scope);
119
120
  }
120
121
  export async function getAvailableModels(scope) {
121
122
  const providerName = getActiveProviderName(scope);
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Setting a model or effort at a level — one thread, a chat's default, a whole
3
+ * chat, or the whole bot — and getting the claudes it concerns onto it.
4
+ *
5
+ * Both are flags the CLI reads at spawn, so a change only reaches a session
6
+ * once its pty is restarted. Which ones that is follows from the values
7
+ * themselves: every live session whose resolved value differs before and
8
+ * after the change. Those idle now restart on their next message; those
9
+ * mid-turn restart when the turn ends, so nothing is cut short and nothing
10
+ * stays on the old value until some unrelated respawn. The conversation
11
+ * survives either way, as the next spawn resumes the same session id.
12
+ */
13
+ import { getPtyProvider } from './claude-provider.js';
14
+ import { isInFlight, runAfterTurn } from '../claude/in-flight-tracker.js';
15
+ import { userPreferences } from './user-preferences.js';
16
+ import { scopeChatId } from '../utils/session-key.js';
17
+ function read(scope, field) {
18
+ return field === 'model' ? userPreferences.getModel(scope) : userPreferences.getEffort(scope);
19
+ }
20
+ /**
21
+ * Apply `value` at `level` from `scope` and restart what it changed.
22
+ * `current` is the session the command was typed in: a restart there is
23
+ * immediate even mid-turn, as a /model there always was.
24
+ */
25
+ export function applySpawnSetting(scope, field, value, level, current) {
26
+ const pty = getPtyProvider();
27
+ const live = level === 'all' ? pty.listSessionKeys() : pty.listSessionKeysForChat(scopeChatId(scope));
28
+ const before = new Map(live.map((k) => [k, read(k, field)]));
29
+ const dropped = userPreferences.applyLevel(scope, field, value, level);
30
+ const restarted = [];
31
+ const busy = [];
32
+ for (const k of live) {
33
+ if (read(k, field) === before.get(k))
34
+ continue;
35
+ if (k !== current && isInFlight(k)) {
36
+ busy.push(k);
37
+ runAfterTurn(k, () => pty.clearConversation(k));
38
+ continue;
39
+ }
40
+ pty.clearConversation(k);
41
+ restarted.push(k);
42
+ }
43
+ return { dropped, restarted, busy };
44
+ }
45
+ //# sourceMappingURL=spawn-settings.js.map
@@ -15,7 +15,7 @@ import * as fs from 'fs';
15
15
  import * as path from 'path';
16
16
  import { z } from 'zod';
17
17
  import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
18
- import { BOT_ID } from '../config.js';
18
+ import { BOT_ID, config } from '../config.js';
19
19
  import { scopeChatId } from '../utils/session-key.js';
20
20
  // Zod schema for user preferences
21
21
  const userPreferencesSchema = z.object({
@@ -24,7 +24,6 @@ const userPreferencesSchema = z.object({
24
24
  // file in one shot, so a strict enum would make one stale value wipe every
25
25
  // user's saved model/effort/verbosity too.
26
26
  provider: z.enum(['claude', 'ccr']).optional().catch(undefined),
27
- method: z.enum(['sdk', 'pty']).optional(),
28
27
  // The clearable settings also take null: a thread that resets one to the
29
28
  // default has to say so, or it would fall back to the chat's choice.
30
29
  model: z.string().nullable().optional(),
@@ -46,6 +45,12 @@ const userPreferencesSchema = z.object({
46
45
  const preferencesDataSchema = z.object({
47
46
  users: z.record(z.string(), userPreferencesSchema),
48
47
  });
48
+ /**
49
+ * The entry every chat falls back to for a spawn setting it never chose:
50
+ * what `/model … all` writes. Not a chat id, so it never collides with one.
51
+ */
52
+ const BOT_DEFAULT_KEY = '*';
53
+ const SPAWN_SETTINGS = new Set(['model', 'effort']);
49
54
  const PREFS_DIR = getStateDir();
50
55
  const PREFS_FILE = path.join(PREFS_DIR, `user-preferences-${BOT_ID}.json`);
51
56
  /** The single shared file every instance wrote to before preferences were per-bot. */
@@ -54,7 +59,8 @@ const LEGACY_PREFS_FILE = path.join(PREFS_DIR, 'user-preferences.json');
54
59
  * Entries are keyed by settings scope (see SettingsScope): a chat id for the
55
60
  * chat-wide value, `chatId:threadId` for one thread's. A thread reads its own
56
61
  * entry first and the chat's after, field by field, so a thread only holds the
57
- * settings it changed and picks up the rest from the chat.
62
+ * settings it changed and picks up the rest from the chat. Model and effort
63
+ * fall back once more, to the bot-wide entry under BOT_DEFAULT_KEY.
58
64
  */
59
65
  class UserPreferencesManager {
60
66
  data = {};
@@ -82,16 +88,28 @@ class UserPreferencesManager {
82
88
  save() {
83
89
  writeJsonFile(PREFS_FILE, { users: { ...this.data } }, 'UserPreferences');
84
90
  }
85
- /** The scope's own value, else the chat's; null (an explicit default) reads as unset. */
86
- get(scope, field) {
91
+ /**
92
+ * The entries a scope reads, in order: its own, the chat's, and for the
93
+ * spawn settings the bot-wide default.
94
+ */
95
+ chain(scope, field) {
87
96
  const key = String(scope);
88
- const own = this.data[key];
89
- if (own && own[field] !== undefined)
90
- return (own[field] ?? undefined);
91
97
  const chatKey = String(scopeChatId(scope));
92
- if (chatKey === key)
98
+ const keys = chatKey === key ? [key] : [key, chatKey];
99
+ if (SPAWN_SETTINGS.has(field))
100
+ keys.push(BOT_DEFAULT_KEY);
101
+ return keys;
102
+ }
103
+ /** The first entry in the chain that holds the field, null included. */
104
+ holder(scope, field) {
105
+ return this.chain(scope, field).find((k) => this.data[k]?.[field] !== undefined);
106
+ }
107
+ /** The nearest value along the chain; null (an explicit default) reads as unset. */
108
+ get(scope, field) {
109
+ const k = this.holder(scope, field);
110
+ if (k === undefined)
93
111
  return undefined;
94
- return (this.data[chatKey]?.[field] ?? undefined);
112
+ return (this.data[k][field] ?? undefined);
95
113
  }
96
114
  /** Apply a field change for `scope`, stamping `lastUpdated` and persisting. */
97
115
  patch(scope, changes) {
@@ -121,18 +139,23 @@ class UserPreferencesManager {
121
139
  this.data[key].lastUpdated = new Date().toISOString();
122
140
  this.save();
123
141
  }
142
+ /**
143
+ * Drop a thread's own settings, for a thread that no longer exists. A chat's
144
+ * entry is never dropped this way: its threads fall back to it.
145
+ */
146
+ forgetThread(scope) {
147
+ const key = String(scope);
148
+ if (key === String(scopeChatId(scope)) || !this.data[key])
149
+ return;
150
+ delete this.data[key];
151
+ this.save();
152
+ }
124
153
  getProvider(scope) {
125
154
  return this.get(scope, 'provider');
126
155
  }
127
156
  setProvider(scope, provider) {
128
157
  this.patch(scope, { provider });
129
158
  }
130
- getMethod(scope) {
131
- return this.get(scope, 'method');
132
- }
133
- setMethod(scope, method) {
134
- this.patch(scope, { method });
135
- }
136
159
  getModel(scope) {
137
160
  return this.get(scope, 'model');
138
161
  }
@@ -169,14 +192,16 @@ class UserPreferencesManager {
169
192
  clearVerbosity(scope) {
170
193
  this.unset(scope, 'verbosity');
171
194
  }
195
+ // The status line and its topic line are on until a chat turns them off;
196
+ // the prompts and the resume command are off until it turns them on.
172
197
  getShowStatusLine(scope) {
173
- return this.get(scope, 'showStatusLine') === true;
198
+ return this.get(scope, 'showStatusLine') ?? config.STATUS_LINE_DEFAULT;
174
199
  }
175
200
  setShowStatusLine(scope, enabled) {
176
201
  this.patch(scope, { showStatusLine: enabled });
177
202
  }
178
203
  getShowTopicInStatusLine(scope) {
179
- return this.get(scope, 'showTopicInStatusLine') === true;
204
+ return this.get(scope, 'showTopicInStatusLine') ?? true;
180
205
  }
181
206
  setShowTopicInStatusLine(scope, enabled) {
182
207
  this.patch(scope, { showTopicInStatusLine: enabled });
@@ -194,7 +219,90 @@ class UserPreferencesManager {
194
219
  this.patch(scope, { showPromptInStatusLine: enabled });
195
220
  }
196
221
  /**
197
- * Start `to` with the settings `from` chose for itself — for a thread forked
222
+ * Which level a scope's model or effort comes from: its own pin, the chat's
223
+ * default, or the bot's. Undefined when nothing chose, so the CLI's own
224
+ * default applies. A level that chose "the CLI default" on purpose counts.
225
+ */
226
+ sourceOf(scope, field) {
227
+ const k = this.holder(scope, field);
228
+ if (k === undefined)
229
+ return undefined;
230
+ if (k === BOT_DEFAULT_KEY)
231
+ return 'bot';
232
+ return k === String(scopeChatId(scope)) ? 'chat' : 'thread';
233
+ }
234
+ /**
235
+ * The threads of a chat that pin `field` to something other than `value`:
236
+ * the ones a `default`-level change leaves alone.
237
+ */
238
+ threadsPinnedOtherThan(chatId, field, value) {
239
+ const prefix = `${chatId}:`;
240
+ return Object.keys(this.data).filter((k) => {
241
+ if (!k.startsWith(prefix))
242
+ return false;
243
+ const v = this.data[k][field];
244
+ return v !== undefined && v !== value;
245
+ });
246
+ }
247
+ /**
248
+ * Set a model or effort at a level (see SettingLevel). `value: null` means
249
+ * the CLI's own default, chosen on purpose: it is stored, so it isn't read
250
+ * as "whatever the wider level says". At `all` there is nothing wider, so
251
+ * null just clears the bot-wide entry.
252
+ *
253
+ * Returns the entries whose own, different pin was dropped to follow the
254
+ * new value, for the confirmation to name.
255
+ */
256
+ applyLevel(scope, field, value, level) {
257
+ const key = String(scope);
258
+ const chatKey = String(scopeChatId(scope));
259
+ const inThread = key !== chatKey;
260
+ const now = new Date().toISOString();
261
+ const dropped = [];
262
+ const drop = (k) => {
263
+ const entry = this.data[k];
264
+ if (!entry || entry[field] === undefined)
265
+ return;
266
+ if (entry[field] !== value)
267
+ dropped.push(k);
268
+ delete entry[field];
269
+ entry.lastUpdated = now;
270
+ };
271
+ const set = (k, v) => {
272
+ this.data[k] = { ...this.data[k], [field]: v, lastUpdated: now };
273
+ };
274
+ if (level === 'all') {
275
+ for (const k of Object.keys(this.data)) {
276
+ if (k !== BOT_DEFAULT_KEY)
277
+ drop(k);
278
+ }
279
+ if (value !== null)
280
+ set(BOT_DEFAULT_KEY, value);
281
+ else if (this.data[BOT_DEFAULT_KEY]) {
282
+ delete this.data[BOT_DEFAULT_KEY][field];
283
+ this.data[BOT_DEFAULT_KEY].lastUpdated = now;
284
+ }
285
+ }
286
+ else if (level === 'thread' && inThread) {
287
+ set(key, value);
288
+ }
289
+ else {
290
+ if (level === 'chat') {
291
+ for (const k of Object.keys(this.data)) {
292
+ if (k.startsWith(`${chatKey}:`))
293
+ drop(k);
294
+ }
295
+ }
296
+ else if (inThread) {
297
+ drop(key);
298
+ }
299
+ set(chatKey, value);
300
+ }
301
+ this.save();
302
+ return dropped;
303
+ }
304
+ /**
305
+ * Start `to` with the settings `from` chose for itself — for a thread branched
198
306
  * off another, which should carry on with the same model and transport. A
199
307
  * chat-wide `from` copies nothing: `to` falls back to it anyway.
200
308
  */
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The worker's half of /rebuildbot's "when idle" option: restart once there is
2
+ * The worker's half of /botrebuild's "when idle" option: restart once there is
3
3
  * nothing left to finish, rather than cutting a turn off halfway.
4
4
  *
5
5
  * The launcher starts it ('drain'), and from then on this worker watches its
@@ -10,19 +10,27 @@
10
10
  * ('drain_render') — whichever incarnation of that bot is live by then, since
11
11
  * it may well have restarted first.
12
12
  *
13
- * "Nothing left" is four things, because no one of them sees everything:
13
+ * "Nothing left" is several things, because no one of them sees everything:
14
14
  * - updates still in the middleware chain: a voice note being transcribed,
15
15
  * a message in the batcher, a turn that answers it — every handler awaits
16
16
  * its turn, so the count only drops once the reply has gone out;
17
- * - the request queue, for turns no update started (/schedule fires);
17
+ * - the request queue, for turns no update started (/loop runs);
18
18
  * - a turn claude started itself on a background task's result, which
19
19
  * nothing in either of those knows about;
20
- * - background tasks still running, whose results would start one of those.
20
+ * - background tasks still running, whose results would start one of those;
21
+ * - a shell command claude left running in the background, which dies with
22
+ * its claude — the same check the PTY idle reaper makes;
23
+ * - the Haiku side-call naming a turn's topic, and a thread rename held for
24
+ * its cooldown or on its way to Telegram: fire-and-forget after the reply,
25
+ * so nothing above counts them, and a restart over one loses the name.
21
26
  */
22
27
  import { isMainThread, parentPort } from 'worker_threads';
23
28
  import { busySessionCount } from './claude/request-queue.js';
24
29
  import { hasSelfStartedTurn, whenRepliesSent } from './claude/monitor-relay.js';
30
+ import { sessionsWithBackgroundShell } from './claude/pty-idle-reaper.js';
31
+ import { topicCallsInFlight } from './claude/auto-topic-haiku.js';
25
32
  import { taskTracker } from './telegram/task-tracker.js';
33
+ import { renamesOutstanding } from './telegram/thread-titles.js';
26
34
  /** How often a draining worker looks again. */
27
35
  const CHECK_MS = 2000;
28
36
  let updatesInFlight = 0;
@@ -56,6 +64,12 @@ export function describeWork(work) {
56
64
  parts.push('answering a background task');
57
65
  if (work.backgroundTasks > 0)
58
66
  parts.push(plural(work.backgroundTasks, 'background task', 'background tasks'));
67
+ if (work.backgroundShells > 0)
68
+ parts.push(plural(work.backgroundShells, 'background shell command', 'background shell commands'));
69
+ if (work.topicCalls > 0)
70
+ parts.push(work.topicCalls === 1 ? 'naming the topic' : `naming ${work.topicCalls} topics`);
71
+ if (work.threadRenames > 0)
72
+ parts.push(work.threadRenames === 1 ? 'renaming a thread' : `renaming ${work.threadRenames} threads`);
59
73
  return parts.length > 0 ? parts.join(', ') : null;
60
74
  }
61
75
  function currentWork() {
@@ -64,13 +78,16 @@ function currentWork() {
64
78
  turns: busySessionCount(),
65
79
  selfStartedTurn: hasSelfStartedTurn(),
66
80
  backgroundTasks: taskTracker.getBackgroundedTotal(),
81
+ backgroundShells: sessionsWithBackgroundShell(),
82
+ topicCalls: topicCallsInFlight(),
83
+ threadRenames: renamesOutstanding(),
67
84
  };
68
85
  }
69
- /** The status message's buttons: route back through handleRebuildCallback. */
86
+ /** The status message's buttons: route back through handleBotRebuildCallback. */
70
87
  export const IDLE_RESTART_BUTTONS = [
71
88
  [
72
- { text: '⚡ Restart the rest now', callback_data: 'rebuild:idle_force' },
73
- { text: '✖️ Cancel', callback_data: 'rebuild:idle_cancel' },
89
+ { text: '⚡ Restart the rest now', callback_data: 'botrebuild:idle_force' },
90
+ { text: '✖️ Cancel', callback_data: 'botrebuild:idle_cancel' },
74
91
  ],
75
92
  ];
76
93
  /**
@@ -121,6 +138,9 @@ export function initRestartWhenIdle(api) {
121
138
  };
122
139
  pp.on('message', (msg) => {
123
140
  if (msg?.type === 'drain') {
141
+ // A rebuild while one is still pending: the launcher's new tally starts
142
+ // out blank, so say again what is holding this worker up.
143
+ lastReported = null;
124
144
  if (timer)
125
145
  return;
126
146
  console.log('[IdleRestart] Restart pending — waiting until nothing is left to finish');
@@ -5,7 +5,7 @@
5
5
  * says a word: a restart shouldn't change which conversation a chat is in, so
6
6
  * every chat used within the restore window carries straight on where it left
7
7
  * off. Whoever wants a clean slate sends /clear. Auto-resume only covers
8
- * sessions idle under an hour, and only after /rebuildbot or /restartbot —
8
+ * sessions idle under an hour, and only after /botrebuild or /botrestart —
9
9
  * this is what brings back everything else.
10
10
  */
11
11
  import { sessionManager, RESTORE_MAX_IDLE_MS } from '../claude/session-manager.js';
@@ -16,7 +16,7 @@ import { allowedChatIds } from './shared.js';
16
16
  * Cold-start auto-continue. For every chat with a prior session belonging to
17
17
  * this instance:
18
18
  * - idle ≤ 7d → silently restore in memory (no chat noise)
19
- * - idle > 7d → skip (user can /continue manually)
19
+ * - idle > 7d → skip (the chat can /resume it)
20
20
  *
21
21
  * Sessions already live in memory are skipped — that covers both the ones
22
22
  * autoResumeAfterReload just restored (they got the fuller "Reloaded and
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Auto-resume after /rebuildbot or /restartbot.
2
+ * Auto-resume after /botrebuild or /botrestart.
3
3
  *
4
4
  * The restarting worker (or the launcher, for a restart-all) leaves a reload
5
5
  * marker on disk. Finding a *fresh* one here is what distinguishes a
@@ -16,7 +16,6 @@ import { parseSessionKey } from '../utils/session-key.js';
16
16
  import { describeRunningBuild } from '../utils/build-info.js';
17
17
  import { setSessionTopic } from '../bot/handlers/command/topic-store.js';
18
18
  import { getEffortLabel } from '../bot/handlers/command.handler.js';
19
- import { isBotNameEnabled, rateLimitedSetMyName, notifyBotNameBlockToChat } from '../telegram/botname-settings.js';
20
19
  import { sendParts } from '../telegram/send.js';
21
20
  import { taskListDisplay } from '../telegram/task-list.js';
22
21
  import { allowedChatIds, threadOpts, sendBlockWithPlainFallback } from './shared.js';
@@ -106,19 +105,8 @@ export async function autoResumeAfterReload(bot, notified) {
106
105
  }
107
106
  console.log(`[AutoResume] resuming ${sessionKey}: project=${entry.projectName}, claudeSessionId=${entry.claudeSessionId}, idle=${Math.round(idleMs / 1000)}s`);
108
107
  clearConversation(sessionKey);
109
- // Restore topic in memory and update bot name. Refresh the name even
110
- // when no topic was persisted — otherwise the bot keeps whatever name
111
- // was last sent (potentially for a different chat/project) after restart.
112
- if (isBotNameEnabled(sessionKey)) {
113
- const displayName = setSessionTopic(sessionKey, entry.topic || '');
114
- try {
115
- const result = await rateLimitedSetMyName(bot.api, (n) => bot.api.setMyName(n), displayName);
116
- await notifyBotNameBlockToChat(bot.api, chatId, result, threadId);
117
- }
118
- catch (e) {
119
- console.debug('[AutoResume] Failed to update bot name:', e instanceof Error ? e.message : e);
120
- }
121
- }
108
+ // Restore the topic in memory, for the status line and the thread name.
109
+ setSessionTopic(sessionKey, entry.topic || '');
122
110
  const projectName = path.basename(session.workingDirectory);
123
111
  const opts = threadOpts(threadId);
124
112
  // Header: plain status text, sent without formatting so topic/project
@@ -67,7 +67,7 @@ export async function notifyInterruptedSessions(bot, notified) {
67
67
  * Apart from this, only the resume recap and the interrupted-task warning speak
68
68
  * on startup, and the recap only for a session idle under an hour — a chat that
69
69
  * carries on silently, or one quiet for longer than the restore window, hears
70
- * nothing. After an explicit /rebuildbot or /restartbot that reads as "did my
70
+ * nothing. After an explicit /botrebuild or /botrestart that reads as "did my
71
71
  * restart even land?", especially for `all`, where five sibling instances
72
72
  * restart with no visible sign either way. Like the recap, it says which build
73
73
  * came back, since landing on the wrong one reads just the same.
@@ -11,7 +11,7 @@ import { Api } from 'grammy';
11
11
  import { config } from '../config.js';
12
12
  import { telegramClientOptions, telegramProxyUrl } from '../telegram/client-options.js';
13
13
  import { describeTokenCheckFailure } from '../utils/bot-token.js';
14
- import { exitForConfigError } from '../utils/exit-codes.js';
14
+ import { EXIT_TELEGRAM_UNAVAILABLE, exitForConfigError } from '../utils/exit-codes.js';
15
15
  /** getMe with the bot's own token and proxy, or exit with a plain-language reason. */
16
16
  export async function verifyBotTokenOrExit() {
17
17
  const api = new Api(config.TELEGRAM_BOT_TOKEN, { ...telegramClientOptions(), timeoutSeconds: 30 });
@@ -21,11 +21,11 @@ export async function verifyBotTokenOrExit() {
21
21
  catch (err) {
22
22
  const failure = describeTokenCheckFailure(err, telegramProxyUrl());
23
23
  console.error(`❌ ${failure.message}`);
24
- // A rejected token stays rejected; a network failure might not, so it
25
- // exits the ordinary way and lets whatever restarts the bot try again.
24
+ // A rejected token stays rejected; a network failure or a Telegram error
25
+ // might not, so it exits for whatever restarts the bot to try again.
26
26
  if (failure.fatal)
27
27
  exitForConfigError();
28
- process.exit(1);
28
+ process.exit(EXIT_TELEGRAM_UNAVAILABLE);
29
29
  }
30
30
  }
31
31
  //# sourceMappingURL=verify-token.js.map