telecoder 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/.env.example +363 -0
  2. package/CHANGELOG.md +1186 -0
  3. package/LICENSE +22 -0
  4. package/README.md +126 -2
  5. package/dist/audio/transcribe.js +50 -0
  6. package/dist/bin/mcp-server.js +378 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +592 -0
  10. package/dist/bot/file-access.js +141 -0
  11. package/dist/bot/handlers/command/access.js +407 -0
  12. package/dist/bot/handlers/command/admin.js +827 -0
  13. package/dist/bot/handlers/command/auto-approve.js +138 -0
  14. package/dist/bot/handlers/command/btw.js +224 -0
  15. package/dist/bot/handlers/command/cost.js +409 -0
  16. package/dist/bot/handlers/command/media.js +197 -0
  17. package/dist/bot/handlers/command/model.js +305 -0
  18. package/dist/bot/handlers/command/prefs-scope.js +197 -0
  19. package/dist/bot/handlers/command/project.js +536 -0
  20. package/dist/bot/handlers/command/resume.js +321 -0
  21. package/dist/bot/handlers/command/session.js +438 -0
  22. package/dist/bot/handlers/command/settings.js +1012 -0
  23. package/dist/bot/handlers/command/shared.js +210 -0
  24. package/dist/bot/handlers/command/streaming-mode.js +16 -0
  25. package/dist/bot/handlers/command/tasks.js +513 -0
  26. package/dist/bot/handlers/command/topic-store.js +113 -0
  27. package/dist/bot/handlers/command/topic.js +80 -0
  28. package/dist/bot/handlers/command.handler.js +772 -0
  29. package/dist/bot/handlers/fork.handler.js +1109 -0
  30. package/dist/bot/handlers/media-fallback.js +121 -0
  31. package/dist/bot/handlers/message/replies.js +133 -0
  32. package/dist/bot/handlers/message/shared.js +117 -0
  33. package/dist/bot/handlers/message/throttle.js +49 -0
  34. package/dist/bot/handlers/message/turn-notify.js +169 -0
  35. package/dist/bot/handlers/message/turn-runner.js +141 -0
  36. package/dist/bot/handlers/message.handler.js +107 -0
  37. package/dist/bot/handlers/newbot.handler.js +221 -0
  38. package/dist/bot/handlers/photo.handler.js +327 -0
  39. package/dist/bot/handlers/prompts.handler.js +343 -0
  40. package/dist/bot/handlers/running-note.js +44 -0
  41. package/dist/bot/handlers/schedule.handler.js +303 -0
  42. package/dist/bot/handlers/session-guard.js +78 -0
  43. package/dist/bot/handlers/suggestion.handler.js +84 -0
  44. package/dist/bot/handlers/tree.handler.js +480 -0
  45. package/dist/bot/handlers/view.js +41 -0
  46. package/dist/bot/handlers/voice.handler.js +209 -0
  47. package/dist/bot/middleware/admin-only.js +49 -0
  48. package/dist/bot/middleware/auth.middleware.js +122 -0
  49. package/dist/bot/middleware/group-mention.middleware.js +139 -0
  50. package/dist/bot/middleware/group-role.middleware.js +75 -0
  51. package/dist/bot/middleware/message-batcher.js +87 -0
  52. package/dist/bot/middleware/queued-messages.js +971 -0
  53. package/dist/bot/middleware/stale-filter.js +31 -0
  54. package/dist/build-info.json +8 -0
  55. package/dist/claude/agent-watchdog.js +162 -0
  56. package/dist/claude/agent.js +1458 -0
  57. package/dist/claude/ask-user.js +295 -0
  58. package/dist/claude/auto-approve.js +225 -0
  59. package/dist/claude/auto-topic-haiku.js +126 -0
  60. package/dist/claude/available-commands.js +153 -0
  61. package/dist/claude/carry-over.js +27 -0
  62. package/dist/claude/ccr-shim.js +46 -0
  63. package/dist/claude/charter-judge.js +214 -0
  64. package/dist/claude/claude-auth.js +121 -0
  65. package/dist/claude/command-parser.js +200 -0
  66. package/dist/claude/cost-overlay-scraper.js +129 -0
  67. package/dist/claude/enabled-plugins.js +56 -0
  68. package/dist/claude/fork-tree.js +393 -0
  69. package/dist/claude/held-query.js +190 -0
  70. package/dist/claude/in-flight-tracker.js +61 -0
  71. package/dist/claude/ipc-server.js +192 -0
  72. package/dist/claude/mcp-bridge.js +453 -0
  73. package/dist/claude/mcp-tools.js +354 -0
  74. package/dist/claude/message-offsets.js +88 -0
  75. package/dist/claude/modal-relay.js +450 -0
  76. package/dist/claude/model-catalog.js +85 -0
  77. package/dist/claude/monitor-relay.js +597 -0
  78. package/dist/claude/pending-forks.js +93 -0
  79. package/dist/claude/pending-suggestions.js +50 -0
  80. package/dist/claude/permission-gate.js +337 -0
  81. package/dist/claude/permission-mode.js +178 -0
  82. package/dist/claude/poll-user.js +51 -0
  83. package/dist/claude/project-commands.js +69 -0
  84. package/dist/claude/prompt-hold.js +124 -0
  85. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  86. package/dist/claude/pty-provider.js +2214 -0
  87. package/dist/claude/pty-spawn-config.js +296 -0
  88. package/dist/claude/pty-stream.js +363 -0
  89. package/dist/claude/request-queue.js +135 -0
  90. package/dist/claude/scheduled-runner.js +91 -0
  91. package/dist/claude/scheduler.js +237 -0
  92. package/dist/claude/scope-guard.js +274 -0
  93. package/dist/claude/sdk-permission-gate.js +77 -0
  94. package/dist/claude/secret-request.js +576 -0
  95. package/dist/claude/session-cost.js +41 -0
  96. package/dist/claude/session-history.js +286 -0
  97. package/dist/claude/session-jsonl.js +920 -0
  98. package/dist/claude/session-manager.js +195 -0
  99. package/dist/claude/session-scan.js +270 -0
  100. package/dist/claude/setup-token.js +285 -0
  101. package/dist/claude/side-call-options.js +45 -0
  102. package/dist/claude/side-question.js +249 -0
  103. package/dist/claude/stage-images.js +62 -0
  104. package/dist/claude/subagent-tools.js +12 -0
  105. package/dist/claude/synthetic-ctx.js +51 -0
  106. package/dist/claude/system-prompt.js +162 -0
  107. package/dist/claude/tasks-overlay-scraper.js +94 -0
  108. package/dist/claude/tip-scraper.js +78 -0
  109. package/dist/claude/tui-modal.js +501 -0
  110. package/dist/claude/tui-state.js +384 -0
  111. package/dist/claude/turn-end.js +91 -0
  112. package/dist/claude/turn-prose.js +64 -0
  113. package/dist/claude/update-banner-relay.js +70 -0
  114. package/dist/cli/commands/doctor.js +305 -0
  115. package/dist/cli/commands/help.js +25 -0
  116. package/dist/cli/commands/init.js +123 -0
  117. package/dist/cli/commands/service.js +678 -0
  118. package/dist/cli/commands/start.js +53 -0
  119. package/dist/cli/commands/version.js +11 -0
  120. package/dist/cli/dispatch.js +79 -0
  121. package/dist/cli/init/env-file.js +99 -0
  122. package/dist/cli/init/flow.js +638 -0
  123. package/dist/cli/init/prompter.js +116 -0
  124. package/dist/cli/init/telegram.js +94 -0
  125. package/dist/cli/service/render.js +212 -0
  126. package/dist/cli.js +18 -0
  127. package/dist/config-report.js +107 -0
  128. package/dist/config.js +500 -0
  129. package/dist/index.js +367 -0
  130. package/dist/launcher.js +933 -0
  131. package/dist/node-version-check.js +27 -0
  132. package/dist/providers/ccr-health.js +119 -0
  133. package/dist/providers/ccr-introspect.js +149 -0
  134. package/dist/providers/ccr-provider.js +60 -0
  135. package/dist/providers/claude-provider.js +63 -0
  136. package/dist/providers/prefs-sync.js +164 -0
  137. package/dist/providers/project-favorites.js +74 -0
  138. package/dist/providers/provider-router.js +127 -0
  139. package/dist/providers/provider-switch.js +91 -0
  140. package/dist/providers/sdk-provider.js +37 -0
  141. package/dist/providers/types.js +8 -0
  142. package/dist/providers/user-preferences.js +214 -0
  143. package/dist/restart-when-idle.js +153 -0
  144. package/dist/startup/auto-continue.js +67 -0
  145. package/dist/startup/auto-resume.js +173 -0
  146. package/dist/startup/notices.js +120 -0
  147. package/dist/startup/shared.js +44 -0
  148. package/dist/startup/verify-token.js +31 -0
  149. package/dist/telegram/access-request.js +153 -0
  150. package/dist/telegram/action-logger.js +684 -0
  151. package/dist/telegram/admin-mention.js +107 -0
  152. package/dist/telegram/background-activity-card.js +502 -0
  153. package/dist/telegram/botname-settings.js +336 -0
  154. package/dist/telegram/button-text.js +26 -0
  155. package/dist/telegram/client-options.js +27 -0
  156. package/dist/telegram/deduplication.js +33 -0
  157. package/dist/telegram/entities.js +295 -0
  158. package/dist/telegram/force-reply-tracker.js +57 -0
  159. package/dist/telegram/lettered-options.js +87 -0
  160. package/dist/telegram/markdown.js +362 -0
  161. package/dist/telegram/message-sender.js +1287 -0
  162. package/dist/telegram/prompt-label.js +142 -0
  163. package/dist/telegram/prompt-suggestion.js +54 -0
  164. package/dist/telegram/send.js +123 -0
  165. package/dist/telegram/streaming-turn.js +105 -0
  166. package/dist/telegram/suggestions-settings.js +30 -0
  167. package/dist/telegram/task-list.js +367 -0
  168. package/dist/telegram/task-tracker.js +209 -0
  169. package/dist/telegram/telegraph-settings.js +31 -0
  170. package/dist/telegram/telegraph.js +453 -0
  171. package/dist/telegram/terminal-renderer.js +671 -0
  172. package/dist/telegram/terminal-settings.js +25 -0
  173. package/dist/telegram/thread-titles.js +190 -0
  174. package/dist/telegram/threads-setup.js +117 -0
  175. package/dist/tts/tts-settings.js +62 -0
  176. package/dist/tts/tts.js +245 -0
  177. package/dist/tts/voice-reply.js +78 -0
  178. package/dist/utils/admins.js +143 -0
  179. package/dist/utils/agent-timer.js +55 -0
  180. package/dist/utils/atomic-write.js +24 -0
  181. package/dist/utils/bot-token.js +74 -0
  182. package/dist/utils/bounded-map.js +55 -0
  183. package/dist/utils/build-info.js +57 -0
  184. package/dist/utils/caffeinate.js +50 -0
  185. package/dist/utils/claude-env.js +54 -0
  186. package/dist/utils/claude-version.js +48 -0
  187. package/dist/utils/config-home.js +62 -0
  188. package/dist/utils/debug-agent.js +117 -0
  189. package/dist/utils/debug-watchdog.js +121 -0
  190. package/dist/utils/download.js +111 -0
  191. package/dist/utils/exit-codes.js +48 -0
  192. package/dist/utils/file-type.js +149 -0
  193. package/dist/utils/format.js +81 -0
  194. package/dist/utils/home-project.js +30 -0
  195. package/dist/utils/host-stall.js +51 -0
  196. package/dist/utils/id-list.js +44 -0
  197. package/dist/utils/idle-restart.js +92 -0
  198. package/dist/utils/install-mode.js +63 -0
  199. package/dist/utils/instance-config.js +148 -0
  200. package/dist/utils/instances.js +95 -0
  201. package/dist/utils/json-store.js +140 -0
  202. package/dist/utils/keyed-settings.js +62 -0
  203. package/dist/utils/legacy-env.js +35 -0
  204. package/dist/utils/npm-version.js +134 -0
  205. package/dist/utils/prefs-relay.js +107 -0
  206. package/dist/utils/proc-children.js +102 -0
  207. package/dist/utils/project-data-dir.js +33 -0
  208. package/dist/utils/reasoning-summary.js +12 -0
  209. package/dist/utils/resolve-bin.js +86 -0
  210. package/dist/utils/resolve-claude-bin.js +63 -0
  211. package/dist/utils/respawn-backoff.js +19 -0
  212. package/dist/utils/sanitize.js +91 -0
  213. package/dist/utils/session-key.js +37 -0
  214. package/dist/utils/stale-launcher.js +109 -0
  215. package/dist/utils/state-dir-migration.js +92 -0
  216. package/dist/utils/systemd.js +126 -0
  217. package/dist/utils/user-roster.js +275 -0
  218. package/dist/utils/verbosity.js +118 -0
  219. package/dist/utils/version-check.js +166 -0
  220. package/dist/utils/workspace-guard.js +44 -0
  221. package/dist/worker-restart.js +141 -0
  222. package/instances.json.example +41 -0
  223. package/package.json +76 -4
@@ -0,0 +1,305 @@
1
+ /**
2
+ * /model, /provider and /ccr — choosing which backend answers.
3
+ *
4
+ * Kept together because the model list is provider-scoped: switching provider
5
+ * changes what /model can offer, and both changes need the same pty restart.
6
+ */
7
+ import { config } from '../../../config.js';
8
+ import { setModel, getModel, clearModel, getActiveProviderName, getAvailableProviders, getAvailableModels, } from '../../../providers/provider-router.js';
9
+ import { isPassthroughModelId, isPremiumModel, PREMIUM_MODEL_ICON } from '../../../claude/model-catalog.js';
10
+ import { switchProvider, switchRequiresConfirm } from '../../../providers/provider-switch.js';
11
+ import { EntityText } from '../../../telegram/entities.js';
12
+ import { replyFormatted, editCallbackMessage } from '../../../telegram/send.js';
13
+ import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
14
+ import { replyMd, parseCallback, restartPtyForSettingChange, PTY_RESTART_NOTE } from './shared.js';
15
+ import { parseScopeArg, applyToAllBots, buildApplyToAllKeyboard, prefsConfirmation, hasSiblings, } from './prefs-scope.js';
16
+ export async function handleModelCommand(ctx) {
17
+ const keyInfo = getSessionKeyFromCtx(ctx);
18
+ if (!keyInfo)
19
+ return;
20
+ const { chatId, sessionKey } = keyInfo;
21
+ const text = ctx.message?.text || '';
22
+ // Aliases are all lowercase, but a hand-typed full ID may not be — match
23
+ // case-insensitively, then pass the original through so vendor-cased IDs
24
+ // reach the CLI intact.
25
+ const { value: rawArg, scope } = parseScopeArg(text.split(' ').slice(1).join(' '));
26
+ const args = rawArg.toLowerCase();
27
+ const providerName = getActiveProviderName(sessionKey);
28
+ const models = await getAvailableModels(sessionKey);
29
+ const validIds = models.map(m => m.id);
30
+ if (!args) {
31
+ const currentModel = getModel(sessionKey);
32
+ // Two per row — the alias list is long enough now (fable/opus/sonnet/haiku
33
+ // plus opusplan, best and the [1m] variants) that one row each turns the
34
+ // picker into a scroll on mobile.
35
+ const buttons = models.map((m) => ({
36
+ text: m.id === currentModel ? `✓ ${m.label}` : m.label,
37
+ callback_data: `model:${m.id}`,
38
+ }));
39
+ const keyboard = [];
40
+ for (let i = 0; i < buttons.length; i += 2) {
41
+ keyboard.push(buttons.slice(i, i + 2));
42
+ }
43
+ const picker = new EntityText()
44
+ .add('🤖 ').bold('Select Model').add(` (${providerName})`)
45
+ .newline(2)
46
+ .italic(`Current: ${currentModel}`)
47
+ .newline(2);
48
+ models.forEach((m, i) => {
49
+ if (i > 0)
50
+ picker.newline();
51
+ picker.add('• ').bold(m.label).add(` - ${m.description || ''}`);
52
+ });
53
+ picker.add('\n\nOr ').code('/model <full-id>').add(' to pin an exact release, e.g. ')
54
+ .code('claude-opus-4-8').add('.');
55
+ // Picking from the keyboard applies to this bot; the confirmation then
56
+ // offers the fan-out. Say so up front so nobody assumes either scope.
57
+ if (hasSiblings()) {
58
+ picker.add('\n\nApplies to ').bold(config.BOT_NAME).add(' only — add ').code('all')
59
+ .add(' (').code('/model sonnet all').add(') or use the button afterwards to set every bot.');
60
+ }
61
+ await replyFormatted(ctx, picker.build(), {
62
+ reply_markup: {
63
+ inline_keyboard: keyboard,
64
+ },
65
+ });
66
+ return;
67
+ }
68
+ // `all` on its own is a scope with no model attached. Passthrough would
69
+ // otherwise take it at face value and hand the CLI `--model all`, which is
70
+ // a confusing way to learn the argument order.
71
+ if (args === 'all' || args === 'everywhere') {
72
+ await replyMd(ctx, '`all` sets every bot, but it needs a model to set them to.\n\n' +
73
+ 'Try `/model sonnet all`, or /model to pick one.');
74
+ return;
75
+ }
76
+ // Anything off the catalog is taken at face value — the CLI accepts a full
77
+ // model name wherever it accepts an alias, and pinning an exact release is a
78
+ // legitimate thing to want. We can't verify it, so say so rather than
79
+ // pretending the choice was checked.
80
+ const known = validIds.includes(args);
81
+ if (!known && !isPassthroughModelId(rawArg)) {
82
+ await replyFormatted(ctx, new EntityText()
83
+ .add(`❌ "${rawArg}" isn't a usable model name.\n\n`)
84
+ .add(`Aliases: ${validIds.join(', ')}\n`)
85
+ .add('Or pass a full model ID (e.g. ').code('claude-opus-5').add(').')
86
+ .build());
87
+ return;
88
+ }
89
+ const chosen = known ? args : rawArg;
90
+ setModel(sessionKey, chosen);
91
+ const restarted = restartPtyForSettingChange(keyInfo.sessionKey);
92
+ const confirmation = new EntityText().append(prefsConfirmation('model', chosen));
93
+ if (restarted)
94
+ confirmation.append(PTY_RESTART_NOTE);
95
+ appendPremiumNote(confirmation, chosen, providerName);
96
+ if (!known) {
97
+ confirmation.add("\n\n⚠️ Not a known alias — passed to the CLI as-is. If your install can't serve it, the next turn fails; /model to pick again.");
98
+ }
99
+ if (scope === 'all') {
100
+ const summary = await applyToAllBots({
101
+ chatId,
102
+ setting: 'model',
103
+ value: chosen,
104
+ provider: providerName,
105
+ });
106
+ await replyFormatted(ctx, confirmation.append(summary).build());
107
+ return;
108
+ }
109
+ const keyboard = buildApplyToAllKeyboard('model', chosen);
110
+ await replyFormatted(ctx, confirmation.build(), {
111
+ ...(keyboard ? { reply_markup: { inline_keyboard: keyboard } } : {}),
112
+ });
113
+ }
114
+ export async function handleModelCallback(ctx) {
115
+ const cb = parseCallback(ctx, 'model:');
116
+ if (!cb)
117
+ return;
118
+ const { chatId, sessionKey, data } = cb;
119
+ const model = data.replace('model:', '');
120
+ // Validate against current provider's models
121
+ const models = await getAvailableModels(sessionKey);
122
+ const validIds = models.map(m => m.id);
123
+ if (!validIds.includes(model)) {
124
+ await ctx.answerCallbackQuery({ text: 'Invalid model' });
125
+ return;
126
+ }
127
+ setModel(sessionKey, model);
128
+ const restarted = restartPtyForSettingChange(sessionKey);
129
+ const modelInfo = models.find(m => m.id === model);
130
+ const displayName = modelInfo?.label || model;
131
+ await ctx.answerCallbackQuery({ text: `Model set to ${displayName}!` });
132
+ const keyboard = buildApplyToAllKeyboard('model', model);
133
+ const confirmation = new EntityText().append(prefsConfirmation('model', displayName));
134
+ if (restarted)
135
+ confirmation.append(PTY_RESTART_NOTE);
136
+ appendPremiumNote(confirmation, model, getActiveProviderName(sessionKey));
137
+ await editCallbackMessage(ctx, confirmation.build(), {
138
+ ...(keyboard ? { reply_markup: { inline_keyboard: keyboard } } : {}),
139
+ });
140
+ }
141
+ /**
142
+ * Said once, when a premium model is picked: from then on the status line's
143
+ * 💎 is the reminder, and it only works if it was explained here.
144
+ */
145
+ function appendPremiumNote(confirmation, model, provider) {
146
+ if (provider === 'ccr' || !isPremiumModel(model))
147
+ return;
148
+ confirmation.newline(2).italic(`${PREMIUM_MODEL_ICON} ${model} costs more per turn than opus, so it uses up your plan's limits faster. ` +
149
+ `The status line shows ${PREMIUM_MODEL_ICON} while it's on; /model opus to switch back.`);
150
+ }
151
+ const PROVIDER_DESCRIPTIONS = {
152
+ claude: 'Claude Code SDK (Anthropic / Max)',
153
+ ccr: 'Routed via Claude Code Router (alt providers)',
154
+ };
155
+ export async function handleProviderCommand(ctx) {
156
+ const keyInfo = getSessionKeyFromCtx(ctx);
157
+ if (!keyInfo)
158
+ return;
159
+ const { sessionKey } = keyInfo;
160
+ const providers = getAvailableProviders();
161
+ const active = getActiveProviderName(sessionKey);
162
+ const keyboard = providers.map((p) => {
163
+ const label = p === active ? `✓ ${p}` : p;
164
+ return [{ text: label, callback_data: `provider:${p}` }];
165
+ });
166
+ const picker = new EntityText()
167
+ .add('🔌 ').bold('Select Provider')
168
+ .newline(2)
169
+ .italic(`Current: ${active}`)
170
+ .newline(2);
171
+ providers.forEach((p, i) => {
172
+ if (i > 0)
173
+ picker.newline();
174
+ picker.add('• ').bold(p).add(` - ${PROVIDER_DESCRIPTIONS[p]}`);
175
+ });
176
+ await replyFormatted(ctx, picker.build(), {
177
+ reply_markup: {
178
+ inline_keyboard: keyboard,
179
+ },
180
+ });
181
+ }
182
+ /**
183
+ * Quick toggle between Claude (Max) and CCR. Designed for the common case of
184
+ * "I'm throttled on Max, send subsequent messages through CCR instead."
185
+ * Sticky — stays on CCR until the user toggles back.
186
+ */
187
+ export async function handleCcrCommand(ctx) {
188
+ const keyInfo = getSessionKeyFromCtx(ctx);
189
+ if (!keyInfo)
190
+ return;
191
+ const { sessionKey } = keyInfo;
192
+ if (!config.CCR_ENABLED) {
193
+ await replyMd(ctx, '⚠️ CCR is not enabled. Set `CCR_ENABLED=true` in `.env` and restart the bot.');
194
+ return;
195
+ }
196
+ const active = getActiveProviderName(sessionKey);
197
+ const next = active === 'ccr' ? 'claude' : 'ccr';
198
+ // If a live session owned by the other backend would be abandoned, confirm
199
+ // first (switching starts a fresh session — sessions can't cross backends).
200
+ if (switchRequiresConfirm(sessionKey, next)) {
201
+ await replyFormatted(ctx, buildSwitchConfirmText(sessionKey, next), {
202
+ reply_markup: { inline_keyboard: buildSwitchConfirmKeyboard(next) },
203
+ });
204
+ return;
205
+ }
206
+ // switchProvider forks the session (clears the stale session_id and carries
207
+ // over a summary) so the next message starts clean on the new backend.
208
+ await switchProvider(sessionKey, next);
209
+ // Clear model — Claude and CCR share labels but CCR's mapping is different.
210
+ clearModel(sessionKey);
211
+ const label = next === 'ccr' ? 'CCR (routed)' : 'Claude (Max)';
212
+ await replyMd(ctx, `🔌 Switched provider to **${label}**.\n\n_Sticky — use /ccr again or /provider to switch back._`);
213
+ }
214
+ export async function handleProviderCallback(ctx) {
215
+ const keyInfo = getSessionKeyFromCtx(ctx);
216
+ if (!keyInfo)
217
+ return;
218
+ const { sessionKey } = keyInfo;
219
+ const data = ctx.callbackQuery?.data;
220
+ if (!data || !data.startsWith('provider:'))
221
+ return;
222
+ const provider = data.replace('provider:', '');
223
+ const providers = getAvailableProviders();
224
+ if (!providers.includes(provider)) {
225
+ await ctx.answerCallbackQuery({ text: 'Invalid provider' });
226
+ return;
227
+ }
228
+ if (provider === getActiveProviderName(sessionKey)) {
229
+ await ctx.answerCallbackQuery({ text: `Already using ${provider}` });
230
+ return;
231
+ }
232
+ // If a live session owned by a different backend would be abandoned, confirm
233
+ // first — switching starts a fresh session (sessions can't cross backends).
234
+ if (switchRequiresConfirm(sessionKey, provider)) {
235
+ await ctx.answerCallbackQuery();
236
+ await editCallbackMessage(ctx, buildSwitchConfirmText(sessionKey, provider), {
237
+ reply_markup: { inline_keyboard: buildSwitchConfirmKeyboard(provider) },
238
+ });
239
+ return;
240
+ }
241
+ // No live session (or already owned by target): switch transparently.
242
+ await switchProvider(sessionKey, provider);
243
+ clearModel(sessionKey); // Models differ between providers
244
+ await ctx.answerCallbackQuery({ text: `Switched to ${provider}!` });
245
+ await editCallbackMessage(ctx, new EntityText()
246
+ .add('✅ Provider set to ').bold(provider)
247
+ .newline(2)
248
+ .italic(MODEL_CLEARED_NOTE)
249
+ .build());
250
+ }
251
+ const MODEL_CLEARED_NOTE = 'Model selection cleared — use /model to pick a model.';
252
+ /** Confirmation body shown before a destructive provider switch. */
253
+ function buildSwitchConfirmText(sessionKey, target) {
254
+ const current = getActiveProviderName(sessionKey);
255
+ return new EntityText()
256
+ .add('🔀 ').bold(`Switch to ${target}?`)
257
+ .newline(2)
258
+ .add('Your current conversation runs on ').bold(current)
259
+ .add(". Sessions can't move between model backends, so I'll start a ")
260
+ .bold('fresh session')
261
+ .add(` on ${target} and carry over a short summary of this conversation for continuity.`)
262
+ .newline(2)
263
+ .add('Continue?')
264
+ .build();
265
+ }
266
+ function buildSwitchConfirmKeyboard(target) {
267
+ return [
268
+ [
269
+ { text: '✓ Switch & carry over', callback_data: `provider_switch:${target}` },
270
+ { text: '✗ Cancel', callback_data: 'provider_switch:cancel' },
271
+ ],
272
+ ];
273
+ }
274
+ /** Handles the confirm/cancel buttons from a provider-switch prompt. */
275
+ export async function handleProviderSwitchCallback(ctx) {
276
+ const keyInfo = getSessionKeyFromCtx(ctx);
277
+ if (!keyInfo)
278
+ return;
279
+ const { sessionKey } = keyInfo;
280
+ const data = ctx.callbackQuery?.data;
281
+ if (!data || !data.startsWith('provider_switch:'))
282
+ return;
283
+ const target = data.replace('provider_switch:', '');
284
+ if (target === 'cancel') {
285
+ await ctx.answerCallbackQuery({ text: 'Cancelled' });
286
+ await ctx.editMessageReplyMarkup({ reply_markup: undefined });
287
+ return;
288
+ }
289
+ const providers = getAvailableProviders();
290
+ if (!providers.includes(target)) {
291
+ await ctx.answerCallbackQuery({ text: 'Invalid provider' });
292
+ return;
293
+ }
294
+ const provider = target;
295
+ await switchProvider(sessionKey, provider);
296
+ clearModel(sessionKey);
297
+ await ctx.answerCallbackQuery({ text: `Switched to ${provider}!` });
298
+ await editCallbackMessage(ctx, new EntityText()
299
+ .add('✅ Provider set to ').bold(provider)
300
+ .add('. Started a fresh session with a summary of the previous conversation carried over.')
301
+ .newline(2)
302
+ .italic(MODEL_CLEARED_NOTE)
303
+ .build());
304
+ }
305
+ //# sourceMappingURL=model.js.map
@@ -0,0 +1,197 @@
1
+ /**
2
+ * The "just this bot, or all of them?" half of /model and /effort.
3
+ *
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.
9
+ *
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
+ */
13
+ import { EntityText } from '../../../telegram/entities.js';
14
+ import { editCallbackMessage } from '../../../telegram/send.js';
15
+ import { broadcastPrefsChange, siblingBotNames, } from '../../../providers/prefs-sync.js';
16
+ import { getActiveProviderName, getAvailableModels } from '../../../providers/provider-router.js';
17
+ 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:';
22
+ /** Telegram's hard cap on callback_data. */
23
+ const CALLBACK_DATA_MAX_BYTES = 64;
24
+ /**
25
+ * Split a trailing scope word off a command argument.
26
+ *
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.
31
+ */
32
+ export function parseScopeArg(raw) {
33
+ const parts = raw.trim().split(/\s+/).filter(Boolean);
34
+ 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' };
39
+ }
40
+ if (last === 'this' || last === 'here' || last === 'one') {
41
+ return { value: parts.slice(0, -1).join(' '), scope: 'this' };
42
+ }
43
+ return { value: raw.trim(), scope: 'this' };
44
+ }
45
+ /**
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.
49
+ */
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 }]];
58
+ }
59
+ /**
60
+ * Relay a change to the other instances and describe what happened, as a
61
+ * block (opening with a blank line) to append to the local confirmation.
62
+ */
63
+ export async function applyToAllBots(change) {
64
+ const result = await broadcastPrefsChange(change);
65
+ return formatBroadcastResult(result);
66
+ }
67
+ /** Render a broadcast outcome. Exported for tests. */
68
+ 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();
73
+ if (!result.multiInstance)
74
+ return nothingElse;
75
+ if (result.timedOut) {
76
+ return new EntityText()
77
+ .add('\n\n⚠️ The launcher didn\'t answer, so the other bots were ')
78
+ .bold('not')
79
+ .add(' changed. It may be running code from before fleet-wide settings existed — /restartbot all picks it up.')
80
+ .build();
81
+ }
82
+ // A launcher with a one-instance config: multi-instance plumbing, nobody on
83
+ // the other end of it.
84
+ if (result.applied.length + result.skipped.length + result.unreachable.length === 0) {
85
+ return nothingElse;
86
+ }
87
+ // Each line opens with its own newline; this one more sets the block off
88
+ // from the confirmation with a blank line.
89
+ const b = new EntityText().add('\n');
90
+ if (result.applied.length > 0) {
91
+ const names = result.applied.map((o) => o.name).join(', ');
92
+ b.add('\n🌐 Also applied to ')
93
+ .bold(String(result.applied.length))
94
+ .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.
97
+ const busy = result.applied.filter((o) => (o.busy ?? 0) > 0);
98
+ if (busy.length > 0) {
99
+ 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.');
101
+ }
102
+ }
103
+ else {
104
+ b.add('\n🌐 No other bot took the change.');
105
+ }
106
+ for (const o of result.skipped) {
107
+ b.add('\n⚠️ Not applied to ').bold(o.name).add(`${o.reason ? ` — ${o.reason}` : ''}.`);
108
+ }
109
+ if (result.unreachable.length > 0) {
110
+ b.add(`\n⚠️ Not running, so unchanged: ${result.unreachable.join(', ')}.`);
111
+ }
112
+ return b.build();
113
+ }
114
+ /**
115
+ * Whether a confirmation should name the bot it applied to. Pointless when
116
+ * there is only one.
117
+ */
118
+ export function hasSiblings() {
119
+ return siblingBotNames().length > 0;
120
+ }
121
+ /**
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.
125
+ */
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();
133
+ }
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;
137
+ }
138
+ /** Human-readable name for a value, matching what the pickers show. */
139
+ async function describeValue(scope, setting, value) {
140
+ if (setting === 'effort') {
141
+ if (value === null)
142
+ return 'auto';
143
+ return EFFORT_LEVELS.find((l) => l.id === value)?.label ?? value;
144
+ }
145
+ if (value === null)
146
+ return 'default';
147
+ const models = await getAvailableModels(scope);
148
+ return models.find((m) => m.id === value)?.label ?? value;
149
+ }
150
+ /**
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.
154
+ */
155
+ export async function handlePrefsAllCallback(ctx) {
156
+ const keyInfo = getSessionKeyFromCtx(ctx);
157
+ const data = ctx.callbackQuery?.data;
158
+ if (!keyInfo || !data?.startsWith(PREFS_ALL_PREFIX))
159
+ return;
160
+ const { chatId, sessionKey } = keyInfo;
161
+ const rest = data.slice(PREFS_ALL_PREFIX.length);
162
+ const sep = rest.indexOf(':');
163
+ if (sep === -1)
164
+ return;
165
+ const setting = rest.slice(0, sep);
166
+ const raw = rest.slice(sep + 1);
167
+ if (setting !== 'model' && setting !== 'effort')
168
+ 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.
171
+ 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.
175
+ try {
176
+ await ctx.editMessageReplyMarkup({ reply_markup: { inline_keyboard: [] } });
177
+ }
178
+ catch {
179
+ // ignore — the message may already have been edited
180
+ }
181
+ const change = {
182
+ chatId,
183
+ setting,
184
+ value,
185
+ provider: getActiveProviderName(sessionKey),
186
+ };
187
+ 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());
196
+ }
197
+ //# sourceMappingURL=prefs-scope.js.map