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,64 +1,210 @@
1
1
  /**
2
- * The "just this bot, or all of them?" half of /model and /effort.
2
+ * How far a /model or /effort choice reaches: this thread, this thread and
3
+ * new ones, every thread in this chat, or every chat on every bot.
3
4
  *
4
- * Both settings are per-bot, and that stays the default: it is the answer that
5
- * matches how the rest of a multi-bot setup already behaves, and it is the one
6
- * you can undo by typing the command again. Fleet-wide is a deliberate extra —
7
- * a trailing `all` on the command, or one tap on the confirmation — so the
8
- * common case never grows a question it has to answer.
5
+ * A bare command or a picker tap sets the thread it's in: the cheap case, and
6
+ * the one undone by typing the command again. The wider levels are a word on
7
+ * the command (`/model sonnet new`, `… chat`, `… all`) or a tap on the
8
+ * confirmation, which offers each level wider than the one just applied.
9
+ * That holds in the "All" view too, where Telegram opens a fresh thread for
10
+ * whatever is typed: the bare command pins that new thread (see all-view.ts).
9
11
  *
10
- * Nothing here is offered in a single-bot setup: with no siblings the choice
11
- * has exactly one answer, and asking it would be noise.
12
+ * A wider level drops the narrower pins it covers, so one "everywhere" brings
13
+ * every thread back in line, branches of pinned threads included. "New threads"
14
+ * is the exception: it leaves threads that chose their own model alone.
12
15
  */
13
16
  import { EntityText } from '../../../telegram/entities.js';
14
17
  import { editCallbackMessage } from '../../../telegram/send.js';
15
18
  import { broadcastPrefsChange, siblingBotNames, } from '../../../providers/prefs-sync.js';
16
- import { getActiveProviderName, getAvailableModels } from '../../../providers/provider-router.js';
19
+ import { getActiveProviderName, getAvailableModels, isValidEffortLevel } from '../../../providers/provider-router.js';
20
+ import { applySpawnSetting } from '../../../providers/spawn-settings.js';
21
+ import { userPreferences, } from '../../../providers/user-preferences.js';
22
+ import { isPassthroughModelId } from '../../../claude/model-catalog.js';
23
+ import { threadDisplayName } from '../../../telegram/thread-titles.js';
24
+ import { isAdmin } from '../../../utils/admins.js';
17
25
  import { config } from '../../../config.js';
18
- import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
19
- import { EFFORT_LEVELS, needsPtyRestart, PTY_RESTART_NOTE } from './shared.js';
20
- /** Callback-data prefix for the "apply to all bots" button. */
21
- export const PREFS_ALL_PREFIX = 'prefs_all:';
26
+ import { getSessionKeyFromCtx, parseSessionKey } from '../../../utils/session-key.js';
27
+ import { EFFORT_LEVELS, PTY_RESTART_NOTE } from './shared.js';
28
+ import { isFreshAllViewThread } from './all-view.js';
29
+ /** Callback-data prefix for the widen-the-scope buttons. */
30
+ export const PREFS_SCOPE_PREFIX = 'pscope:';
22
31
  /** Telegram's hard cap on callback_data. */
23
32
  const CALLBACK_DATA_MAX_BYTES = 64;
33
+ const LEVEL_WORDS = {
34
+ this: 'thread',
35
+ here: 'thread',
36
+ one: 'thread',
37
+ thread: 'thread',
38
+ new: 'default',
39
+ default: 'default',
40
+ chat: 'chat',
41
+ threads: 'chat',
42
+ all: 'all',
43
+ everywhere: 'all',
44
+ };
45
+ const LEVEL_ORDER = ['thread', 'default', 'chat', 'all'];
24
46
  /**
25
- * Split a trailing scope word off a command argument.
47
+ * Split a trailing level word off a command argument.
26
48
  *
27
- * `/model sonnet all` → `{ value: 'sonnet', scope: 'all' }`. The word is only
28
- * taken as a scope when something precedes it, so `/model all` still reaches
29
- * the normal "is that a model?" path rather than silently becoming a no-op
30
- * broadcast of nothing.
49
+ * `/model sonnet chat` → `{ value: 'sonnet', level: 'chat' }`. The word is
50
+ * only taken as a level when something precedes it, so `/model all` still
51
+ * reaches the "that needs a model" path and `/effort default` stays the
52
+ * effort reset it always was. No word leaves `level` undefined, for the
53
+ * caller to decide (see resolveLevel).
31
54
  */
32
55
  export function parseScopeArg(raw) {
33
56
  const parts = raw.trim().split(/\s+/).filter(Boolean);
34
57
  if (parts.length < 2)
35
- return { value: raw.trim(), scope: 'this' };
36
- const last = parts[parts.length - 1].toLowerCase();
37
- if (last === 'all' || last === 'everywhere') {
38
- return { value: parts.slice(0, -1).join(' '), scope: 'all' };
58
+ return { value: raw.trim() };
59
+ const level = LEVEL_WORDS[parts[parts.length - 1].toLowerCase()];
60
+ if (!level)
61
+ return { value: raw.trim() };
62
+ return { value: parts.slice(0, -1).join(' '), level };
63
+ }
64
+ /** Whether `word` is a level word typed on its own, with no value before it. */
65
+ export function isBareLevelWord(word) {
66
+ return word.toLowerCase() in LEVEL_WORDS && LEVEL_WORDS[word.toLowerCase()] !== 'thread';
67
+ }
68
+ export function scopeSite(ctx) {
69
+ const keyInfo = getSessionKeyFromCtx(ctx);
70
+ return {
71
+ inThread: keyInfo?.threadId !== undefined,
72
+ allView: isFreshAllViewThread(ctx),
73
+ admin: isAdmin(ctx.from?.id),
74
+ };
75
+ }
76
+ /** " on **<bot>**" when there are siblings it could be confused with. */
77
+ function withBotName(b) {
78
+ return hasSiblings() ? b.add(' on ').bold(config.BOT_NAME) : b;
79
+ }
80
+ /** Where a level reaches, worded for where it was applied from. */
81
+ function levelPhrase(level, site) {
82
+ switch (level) {
83
+ case 'all':
84
+ return 'everywhere';
85
+ case 'chat':
86
+ return 'for every thread in this chat';
87
+ case 'default':
88
+ return site.inThread ? 'for this thread and new threads in this chat' : 'in this chat';
89
+ case 'thread':
90
+ return site.inThread ? 'in this thread' : 'in this chat';
91
+ }
92
+ }
93
+ /**
94
+ * "✅ Model set to **opus** in this thread", plus " on **TeleCoder 2**" once
95
+ * there is more than one bot it could have meant. Everywhere names no bot:
96
+ * the summary under it lists them.
97
+ */
98
+ export function prefsConfirmation(setting, displayLabel, level = 'thread', site = { inThread: true }) {
99
+ const what = setting === 'model' ? 'Model set to' : 'Effort set to';
100
+ const b = new EntityText().add(`✅ ${what} `).bold(displayLabel).add(` ${levelPhrase(level, site)}`);
101
+ return (level === 'all' ? b : withBotName(b)).build();
102
+ }
103
+ const MAX_NAMED_THREADS = 5;
104
+ function threadNames(keys) {
105
+ const names = keys.map((k) => threadDisplayName(k) ?? `thread ${parseSessionKey(k).threadId ?? k}`);
106
+ if (names.length <= MAX_NAMED_THREADS)
107
+ return names.join(', ');
108
+ return `${names.slice(0, MAX_NAMED_THREADS).join(', ')} and ${names.length - MAX_NAMED_THREADS} more`;
109
+ }
110
+ function plural(n, one, many = `${one}s`) {
111
+ return `${n} ${n === 1 ? one : many}`;
112
+ }
113
+ /**
114
+ * What a change did beyond the setting itself: pins it replaced or left
115
+ * alone, and which claudes restart when. A block that opens with a blank
116
+ * line, empty when there is nothing to say.
117
+ */
118
+ export function describeOutcome(outcome, opts) {
119
+ const b = new EntityText();
120
+ const { level, current, keptPins } = opts;
121
+ if (level === 'chat' && outcome.dropped.length > 0) {
122
+ b.add('\n\n').add(`Now following it instead of their own choice: ${threadNames(outcome.dropped)}.`);
123
+ }
124
+ else if (level === 'all' && outcome.dropped.length > 0) {
125
+ b.add('\n\n').add(`${plural(outcome.dropped.length, 'thread or chat', 'threads and chats')} that had chosen their own follow it now.`);
126
+ }
127
+ if (keptPins.length > 0) {
128
+ b.add('\n\n').add(`${plural(keptPins.length, 'thread')} chose their own and keep it: ${threadNames(keptPins)}. `)
129
+ .bold('All threads here').add(' sets those too.');
130
+ }
131
+ const others = outcome.restarted.filter((k) => k !== current);
132
+ if (outcome.restarted.includes(current) && others.length === 0) {
133
+ b.append(PTY_RESTART_NOTE);
134
+ }
135
+ else if (outcome.restarted.length > 0) {
136
+ b.add('\n\n').italic(`Claude Code restarts in ${plural(outcome.restarted.length, 'thread')} on the next message there (the conversations are kept).`);
39
137
  }
40
- if (last === 'this' || last === 'here' || last === 'one') {
41
- return { value: parts.slice(0, -1).join(' '), scope: 'this' };
138
+ if (outcome.busy.length > 0) {
139
+ b.add('\n\n').italic(`${plural(outcome.busy.length, 'thread is', 'threads are')} mid-turn and switch${outcome.busy.length === 1 ? 'es' : ''} when that turn ends.`);
42
140
  }
43
- return { value: raw.trim(), scope: 'this' };
141
+ return b.build();
142
+ }
143
+ /**
144
+ * Buttons for every level wider than the one just applied that means
145
+ * something here, plus, once a wider level was applied from the "All" view,
146
+ * a way to remove the empty thread it opened. Undefined when there is
147
+ * nothing to offer.
148
+ */
149
+ export function buildWidenKeyboard(setting, buttonValue, level, site) {
150
+ const wider = LEVEL_ORDER.slice(LEVEL_ORDER.indexOf(level) + 1);
151
+ const buttons = [];
152
+ const offer = (l, text) => {
153
+ const data = `${PREFS_SCOPE_PREFIX}${l}:${setting}:${buttonValue}`;
154
+ if (Buffer.byteLength(data, 'utf8') > CALLBACK_DATA_MAX_BYTES)
155
+ return;
156
+ buttons.push({ text, callback_data: data });
157
+ };
158
+ if (wider.includes('default') && site.inThread)
159
+ offer('default', '🆕 New threads too');
160
+ if (wider.includes('chat') && site.inThread)
161
+ offer('chat', '🧵 All threads here');
162
+ if (wider.includes('all') && site.admin) {
163
+ const bots = siblingBotNames().length + 1;
164
+ offer('all', bots > 1 ? `🌐 Everywhere (${bots} bots)` : '🌐 Every chat');
165
+ }
166
+ const rows = [];
167
+ for (let i = 0; i < buttons.length; i += 2)
168
+ rows.push(buttons.slice(i, i + 2));
169
+ // A thread-level pick there is the thread being started on that model;
170
+ // anything wider left it with nothing to do.
171
+ if (site.allView && level !== 'thread')
172
+ rows.push([{ text: '🗑️ Delete this thread', callback_data: 'threaddelete:confirm' }]);
173
+ return rows.length > 0 ? rows : undefined;
44
174
  }
45
175
  /**
46
- * The one-tap offer appended to a local confirmation. Undefined when there are
47
- * no other bots, or when the value is long enough that the callback data
48
- * wouldn't fit — the typed `all` form still works in that case.
176
+ * Apply a choice at a level from the session the user is in, and build the
177
+ * confirmation and buttons for it. The caller adds anything specific to the
178
+ * setting (the premium note, the unverified-model warning) and sends it.
49
179
  */
50
- export function buildApplyToAllKeyboard(setting, value) {
51
- const siblings = siblingBotNames();
52
- if (siblings.length === 0)
53
- return undefined;
54
- const data = `${PREFS_ALL_PREFIX}${setting}:${value}`;
55
- if (Buffer.byteLength(data, 'utf8') > CALLBACK_DATA_MAX_BYTES)
56
- return undefined;
57
- return [[{ text: `🌐 Apply to all ${siblings.length + 1} bots`, callback_data: data }]];
180
+ export async function applyAtLevel(ctx, args) {
181
+ const { sessionKey, setting, value, label, level, site } = args;
182
+ const chatId = parseSessionKey(sessionKey).chatId;
183
+ const outcome = applySpawnSetting(sessionKey, setting, value, level, sessionKey);
184
+ const keptPins = level === 'default' && site.inThread
185
+ ? userPreferences.threadsPinnedOtherThan(chatId, setting, value).filter((k) => k !== sessionKey)
186
+ : [];
187
+ const message = new EntityText()
188
+ .append(prefsConfirmation(setting, label, level, site))
189
+ .append(describeOutcome(outcome, { level, current: sessionKey, keptPins }));
190
+ if (level === 'all') {
191
+ message.append(await applyToAllBots({
192
+ chatId,
193
+ setting,
194
+ value,
195
+ provider: getActiveProviderName(sessionKey),
196
+ level: 'all',
197
+ }));
198
+ }
199
+ const buttonValue = value ?? 'auto';
200
+ return { message, keyboard: buildWidenKeyboard(setting, buttonValue, level, site) };
58
201
  }
202
+ /** The refusal for a non-admin asking for every chat. */
203
+ export const EVERYWHERE_ADMIN_ONLY = 'Only an admin can set every chat. Use chat to set every thread here.';
59
204
  /**
60
205
  * Relay a change to the other instances and describe what happened, as a
61
206
  * block (opening with a blank line) to append to the local confirmation.
207
+ * Says nothing in a single-bot setup, where "everywhere" is this bot.
62
208
  */
63
209
  export async function applyToAllBots(change) {
64
210
  const result = await broadcastPrefsChange(change);
@@ -66,23 +212,20 @@ export async function applyToAllBots(change) {
66
212
  }
67
213
  /** Render a broadcast outcome. Exported for tests. */
68
214
  export function formatBroadcastResult(result) {
69
- const nothingElse = new EntityText()
70
- .add('\n\n')
71
- .italic('This is the only bot running, so there was nothing else to apply it to.')
72
- .build();
215
+ const nothing = new EntityText().build();
73
216
  if (!result.multiInstance)
74
- return nothingElse;
217
+ return nothing;
75
218
  if (result.timedOut) {
76
219
  return new EntityText()
77
220
  .add('\n\n⚠️ The launcher didn\'t answer, so the other bots were ')
78
221
  .bold('not')
79
- .add(' changed. It may be running code from before fleet-wide settings existed — /restartbot all picks it up.')
222
+ .add(' changed. It may be running code from before fleet-wide settings existed — /botrestart all picks it up.')
80
223
  .build();
81
224
  }
82
225
  // A launcher with a one-instance config: multi-instance plumbing, nobody on
83
226
  // the other end of it.
84
227
  if (result.applied.length + result.skipped.length + result.unreachable.length === 0) {
85
- return nothingElse;
228
+ return nothing;
86
229
  }
87
230
  // Each line opens with its own newline; this one more sets the block off
88
231
  // from the confirmation with a blank line.
@@ -92,12 +235,12 @@ export function formatBroadcastResult(result) {
92
235
  b.add('\n🌐 Also applied to ')
93
236
  .bold(String(result.applied.length))
94
237
  .add(` other bot${result.applied.length === 1 ? '' : 's'}: ${names}`);
95
- // A bot mid-turn keeps its running session on the old value; say so rather
96
- // than let the next answer from it look like the setting didn't take.
238
+ // A busy bot switches when its turn ends; say so rather than let the
239
+ // reply it's writing now look like the setting didn't take.
97
240
  const busy = result.applied.filter((o) => (o.busy ?? 0) > 0);
98
241
  if (busy.length > 0) {
99
242
  b.add('\n').italic(`${busy.map((o) => o.name).join(', ')} ${busy.length === 1 ? 'is' : 'are'} mid-turn — ` +
100
- 'the running session keeps the old value until it restarts.');
243
+ 'switching when that turn ends.');
101
244
  }
102
245
  }
103
246
  else {
@@ -119,27 +262,48 @@ export function hasSiblings() {
119
262
  return siblingBotNames().length > 0;
120
263
  }
121
264
  /**
122
- * "✅ Model set to **opus**", plus " for **TeleCoder 2**" once there is more
123
- * than one bot it could have meant. Shared so the confirmation reads the same
124
- * whether it was typed, tapped, or rebuilt after a fan-out.
265
+ * Where a scope's model or effort comes from, as the pickers and /info say
266
+ * it: "pinned in this thread", "this chat's default", "the default
267
+ * everywhere", or Claude Code's own default when nothing chose.
125
268
  */
126
- export function prefsConfirmation(setting, displayLabel) {
127
- const what = setting === 'model' ? 'Model set to' : 'Effort set to';
128
- return withBotName(new EntityText().add(`✅ ${what} `).bold(displayLabel)).build();
129
- }
130
- /** The confirmation for clearing the effort preference, worded like {@link prefsConfirmation}. */
131
- export function effortResetConfirmation() {
132
- return withBotName(new EntityText().add('✅ Effort reset to ').bold('auto').add(' (CLI default)')).build();
269
+ export function describeSource(scope, setting) {
270
+ const source = userPreferences.sourceOf(scope, setting);
271
+ const inThread = parseSessionKey(String(scope)).threadId !== undefined;
272
+ switch (source) {
273
+ case 'thread':
274
+ return 'pinned in this thread';
275
+ case 'chat':
276
+ return inThread ? "this chat's default" : 'set for this chat';
277
+ case 'bot':
278
+ return 'the default everywhere';
279
+ default:
280
+ return "Claude Code's default";
281
+ }
133
282
  }
134
- /** " for **<bot>**" when there are siblings it could be confused with. */
135
- function withBotName(b) {
136
- return hasSiblings() ? b.add(' for ').bold(config.BOT_NAME) : b;
283
+ /** The picker's closing note on how far a choice reaches. */
284
+ export function levelHelp(command, example, site) {
285
+ const b = new EntityText().add('\n\n');
286
+ if (site.inThread) {
287
+ b.add('Picking sets this thread; the confirmation can widen it to new threads, every thread here');
288
+ b.add(site.admin ? ' or everywhere.' : '.');
289
+ }
290
+ else {
291
+ // Without threads, new and chat are this chat again: only all says more.
292
+ b.add('Picking sets this chat');
293
+ if (!site.admin)
294
+ return b.add('.').build();
295
+ return b.add('; ').code(`/${command} ${example} all`).add(' sets every chat.').build();
296
+ }
297
+ b.add(' Typed: ').code(`/${command} ${example} new`).add(', ').code('chat');
298
+ if (site.admin)
299
+ b.add(' or ').code('all');
300
+ return b.add('.').build();
137
301
  }
138
302
  /** Human-readable name for a value, matching what the pickers show. */
139
303
  async function describeValue(scope, setting, value) {
140
304
  if (setting === 'effort') {
141
305
  if (value === null)
142
- return 'auto';
306
+ return 'Auto (CLI default)';
143
307
  return EFFORT_LEVELS.find((l) => l.id === value)?.label ?? value;
144
308
  }
145
309
  if (value === null)
@@ -148,50 +312,51 @@ async function describeValue(scope, setting, value) {
148
312
  return models.find((m) => m.id === value)?.label ?? value;
149
313
  }
150
314
  /**
151
- * The "apply to all bots" button under a /model or /effort confirmation. The
152
- * local change already happened when that message was sent; this only fans it
153
- * out, then rewrites the message with what each bot did.
315
+ * A widen button under a /model or /effort confirmation. The narrower
316
+ * change already happened when the message was sent; this applies the wider
317
+ * one and rewrites the message with what it did.
154
318
  */
155
- export async function handlePrefsAllCallback(ctx) {
319
+ export async function handlePrefsScopeCallback(ctx) {
156
320
  const keyInfo = getSessionKeyFromCtx(ctx);
157
321
  const data = ctx.callbackQuery?.data;
158
- if (!keyInfo || !data?.startsWith(PREFS_ALL_PREFIX))
322
+ if (!keyInfo || !data)
323
+ return;
324
+ const { sessionKey } = keyInfo;
325
+ if (!data.startsWith(PREFS_SCOPE_PREFIX))
159
326
  return;
160
- const { chatId, sessionKey } = keyInfo;
161
- const rest = data.slice(PREFS_ALL_PREFIX.length);
162
- const sep = rest.indexOf(':');
163
- if (sep === -1)
327
+ const [word, setting, ...rest] = data.slice(PREFS_SCOPE_PREFIX.length).split(':');
328
+ if (!LEVEL_ORDER.includes(word) || rest.length === 0)
164
329
  return;
165
- const setting = rest.slice(0, sep);
166
- const raw = rest.slice(sep + 1);
330
+ const level = word;
331
+ const raw = rest.join(':');
167
332
  if (setting !== 'model' && setting !== 'effort')
168
333
  return;
169
- // 'auto' is how the effort picker spells "no preference"; there is no such
170
- // spelling for a model, so only effort can carry a null through the button.
334
+ // 'auto' is how the effort picker spells "no preference"; a model has no
335
+ // such spelling.
171
336
  const value = setting === 'effort' && raw === 'auto' ? null : raw;
172
- await ctx.answerCallbackQuery({ text: 'Applying to all bots…' });
173
- // Drop the button first: the broadcast takes a round trip, and a second tap
174
- // would fan the same change out again.
337
+ const valid = setting === 'effort'
338
+ ? value === null || isValidEffortLevel(value)
339
+ : (await getAvailableModels(sessionKey)).some((m) => m.id === raw) || isPassthroughModelId(raw);
340
+ if (!valid) {
341
+ await ctx.answerCallbackQuery({ text: 'Unknown value' });
342
+ return;
343
+ }
344
+ const site = scopeSite(ctx);
345
+ if (level === 'all' && !site.admin) {
346
+ await ctx.answerCallbackQuery({ text: EVERYWHERE_ADMIN_ONLY, show_alert: true });
347
+ return;
348
+ }
349
+ await ctx.answerCallbackQuery({ text: level === 'all' ? 'Applying everywhere…' : 'Applying…' });
350
+ // Drop the buttons first: an everywhere change takes a round trip, and a
351
+ // second tap would apply it again.
175
352
  try {
176
353
  await ctx.editMessageReplyMarkup({ reply_markup: { inline_keyboard: [] } });
177
354
  }
178
355
  catch {
179
356
  // ignore — the message may already have been edited
180
357
  }
181
- const change = {
182
- chatId,
183
- setting,
184
- value,
185
- provider: getActiveProviderName(sessionKey),
186
- };
187
358
  const label = await describeValue(sessionKey, setting, value);
188
- const confirmation = value === null && setting === 'effort'
189
- ? effortResetConfirmation()
190
- : prefsConfirmation(setting, label);
191
- const summary = await applyToAllBots(change);
192
- const message = new EntityText().append(confirmation);
193
- if (needsPtyRestart(sessionKey))
194
- message.append(PTY_RESTART_NOTE);
195
- await editCallbackMessage(ctx, message.append(summary).build());
359
+ const { message, keyboard } = await applyAtLevel(ctx, { sessionKey, setting, value, label, level, site });
360
+ await editCallbackMessage(ctx, message.build(), keyboard ? { reply_markup: { inline_keyboard: keyboard } } : {});
196
361
  }
197
362
  //# sourceMappingURL=prefs-scope.js.map