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,127 @@
1
+ import { config } from '../config.js';
2
+ import { claudeProvider } from './claude-provider.js';
3
+ import { ccrProvider } from './ccr-provider.js';
4
+ import { setEffort as claudeSetEffort, getEffort as claudeGetEffort, clearEffort as claudeClearEffort, isValidEffortLevel, } from '../claude/agent.js';
5
+ import { userPreferences } from './user-preferences.js';
6
+ import { isPremiumModel } from '../claude/model-catalog.js';
7
+ function getProvider(scope) {
8
+ const name = getActiveProviderName(scope);
9
+ if (name === 'ccr') {
10
+ if (!config.CCR_ENABLED) {
11
+ console.warn('[ProviderRouter] CCR provider selected but CCR_ENABLED=false; falling back to Claude');
12
+ return claudeProvider;
13
+ }
14
+ return ccrProvider;
15
+ }
16
+ return claudeProvider;
17
+ }
18
+ // --- Public API (identical signatures to agent.ts) ---
19
+ /**
20
+ * The backend a chat or thread runs on. Read straight from the preferences,
21
+ * which are in memory already: a cache of its own here would go stale for the
22
+ * threads that fall back to a chat-wide value when that value changes.
23
+ */
24
+ export function getActiveProviderName(scope) {
25
+ if (!config.CCR_ENABLED)
26
+ return 'claude';
27
+ return userPreferences.getProvider(scope) ?? 'claude';
28
+ }
29
+ export async function setActiveProvider(scope, provider) {
30
+ userPreferences.setProvider(scope, provider);
31
+ }
32
+ export function getAvailableProviders() {
33
+ const list = ['claude'];
34
+ if (config.CCR_ENABLED)
35
+ list.push('ccr');
36
+ return list;
37
+ }
38
+ /**
39
+ * The screening point for guest messages.
40
+ *
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.
47
+ *
48
+ * A blocked message returns as an ordinary response rather than an error, so
49
+ * the streaming UI already in flight renders the explanation in place.
50
+ */
51
+ async function screened(sessionKey, message, options) {
52
+ const { screenPrompt } = await import('../claude/prompt-hold.js');
53
+ const outcome = await screenPrompt(options?.telegramCtx, sessionKey, message);
54
+ if (outcome.proceed)
55
+ return null;
56
+ return { text: outcome.message, toolsUsed: [] };
57
+ }
58
+ export async function sendToAgent(sessionKey, message, options) {
59
+ const blocked = await screened(sessionKey, message, options);
60
+ if (blocked)
61
+ return blocked;
62
+ const providerName = getActiveProviderName(sessionKey);
63
+ return getProvider(sessionKey).sendToAgent(sessionKey, message, { ...options, providerName });
64
+ }
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
+ export function clearConversation(sessionKey) {
73
+ // Clear all providers to avoid stale state
74
+ claudeProvider.clearConversation(sessionKey);
75
+ ccrProvider.clearConversation(sessionKey);
76
+ }
77
+ export function setModel(scope, model) {
78
+ getProvider(scope).setModel(scope, model);
79
+ }
80
+ export function getModel(scope) {
81
+ return getProvider(scope).getModel(scope);
82
+ }
83
+ /**
84
+ * The premium model this session runs on, or undefined when it's on an
85
+ * ordinary one. `best` counts once a turn has shown it resolving to one. CCR
86
+ * is left out: its aliases map onto other backends, so the name says nothing
87
+ * about the cost.
88
+ */
89
+ export function getPremiumModel(sessionKey) {
90
+ if (getActiveProviderName(sessionKey) === 'ccr')
91
+ return undefined;
92
+ const model = getModel(sessionKey);
93
+ if (isPremiumModel(model))
94
+ return model;
95
+ if (model === 'best' && isPremiumModel(getCachedUsage(sessionKey)?.model))
96
+ return model;
97
+ return undefined;
98
+ }
99
+ export function clearModel(scope) {
100
+ getProvider(scope).clearModel(scope);
101
+ }
102
+ export function getCachedUsage(sessionKey) {
103
+ return getProvider(sessionKey).getCachedUsage(sessionKey);
104
+ }
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
+ export { isValidEffortLevel };
111
+ export function setEffort(scope, effort) {
112
+ claudeSetEffort(scope, effort);
113
+ }
114
+ export function getEffort(scope) {
115
+ return claudeGetEffort(scope);
116
+ }
117
+ export function clearEffort(scope) {
118
+ claudeClearEffort(scope);
119
+ }
120
+ export async function getAvailableModels(scope) {
121
+ const providerName = getActiveProviderName(scope);
122
+ if (providerName === 'ccr') {
123
+ return ccrProvider.getAvailableModels(scope);
124
+ }
125
+ return claudeProvider.getAvailableModels(scope);
126
+ }
127
+ //# sourceMappingURL=provider-router.js.map
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Provider-switch orchestration.
3
+ *
4
+ * A Claude session is bound to the chat, not the backend — each turn resumes
5
+ * the same Claude Code session id, and the "provider" (claude / ccr)
6
+ * is just a per-turn executable choice. That means a session whose thinking
7
+ * blocks were minted by DeepSeek-via-CCR (placeholder signatures) cannot be
8
+ * replayed against the real Anthropic API without a `400 Invalid signature in
9
+ * thinking block`.
10
+ *
11
+ * So switching provider mid-conversation starts a *fresh* session on the new
12
+ * backend, optionally seeded with a plain-text summary of the prior
13
+ * conversation (thinking/tool blocks stripped, so it's backend-agnostic). This
14
+ * gives continuity of context without continuity of session.
15
+ */
16
+ import { sessionManager } from '../claude/session-manager.js';
17
+ import { readRecentExchanges } from '../claude/session-jsonl.js';
18
+ import { setPendingCarryOver } from '../claude/carry-over.js';
19
+ import { setActiveProvider, getActiveProviderName, clearConversation, } from './provider-router.js';
20
+ // How many recent exchanges to carry over, and how much of each turn to keep.
21
+ const CARRY_OVER_EXCHANGES = 6;
22
+ const CARRY_OVER_TURN_CHARS = 800;
23
+ /** Provider that owns the session currently active for `sessionKey`, if any. */
24
+ export function getSessionOwnerProvider(sessionKey) {
25
+ const session = sessionManager.getSession(sessionKey);
26
+ return session?.ownerProvider;
27
+ }
28
+ /**
29
+ * True if switching `sessionKey` to `target` would abandon a live session that
30
+ * a *different* backend owns — i.e. the switch is destructive and worth a
31
+ * confirmation prompt. A session with no established Claude session id (nothing
32
+ * sent yet) or one already owned by `target` switches transparently.
33
+ */
34
+ export function switchRequiresConfirm(sessionKey, target) {
35
+ const session = sessionManager.getSession(sessionKey);
36
+ if (!session?.claudeSessionId)
37
+ return false; // nothing to lose
38
+ const owner = session.ownerProvider;
39
+ // Unknown owner (legacy/restart): treat as a different backend to be safe.
40
+ return owner !== target;
41
+ }
42
+ function truncate(text, max) {
43
+ const t = text.trim();
44
+ return t.length > max ? t.slice(0, max) + '…' : t;
45
+ }
46
+ /**
47
+ * Build a plain-text recap of the recent conversation for `sessionKey`, or
48
+ * undefined if there's nothing to carry over. Reads the prior session's JSONL
49
+ * (thinking/tool blocks already stripped by readRecentExchanges).
50
+ */
51
+ export function buildCarryOverPreamble(sessionKey) {
52
+ const session = sessionManager.getSession(sessionKey);
53
+ if (!session?.claudeSessionId)
54
+ return undefined;
55
+ const exchanges = readRecentExchanges(session.workingDirectory, session.claudeSessionId, CARRY_OVER_EXCHANGES);
56
+ if (exchanges.length === 0)
57
+ return undefined;
58
+ const transcript = exchanges
59
+ .map((ex) => `User: ${truncate(ex.user, CARRY_OVER_TURN_CHARS)}\n` +
60
+ `Assistant: ${truncate(ex.assistant, CARRY_OVER_TURN_CHARS)}`)
61
+ .join('\n\n');
62
+ return ('[The previous conversation ran on a different model backend and could not ' +
63
+ 'be resumed directly, so it was summarized below for continuity. Treat it ' +
64
+ 'as prior context and continue from where it left off.]\n\n' +
65
+ '--- Previous conversation ---\n' +
66
+ transcript +
67
+ '\n--- End of previous conversation ---');
68
+ }
69
+ /**
70
+ * Switch `sessionKey` to `target`, starting a fresh session. When
71
+ * `carryOver` is true (default) the prior conversation is summarized and queued
72
+ * as a preamble for the next turn. Safe to call even when no session is active.
73
+ */
74
+ export async function switchProvider(sessionKey, target, carryOver = true) {
75
+ if (carryOver) {
76
+ const preamble = buildCarryOverPreamble(sessionKey);
77
+ if (preamble)
78
+ setPendingCarryOver(sessionKey, preamble);
79
+ }
80
+ // Sever the old session BEFORE flipping the provider: drop in-memory
81
+ // session ids/history, then mint a new conversation with no claudeSessionId
82
+ // so the next turn starts clean on the new backend.
83
+ clearConversation(sessionKey);
84
+ sessionManager.startNewConversation(sessionKey);
85
+ await setActiveProvider(sessionKey, target);
86
+ }
87
+ /** Resolve the provider that would be active after a no-op (current). */
88
+ export function currentProvider(scope) {
89
+ return getActiveProviderName(scope);
90
+ }
91
+ //# sourceMappingURL=provider-switch.js.map
@@ -0,0 +1,37 @@
1
+ import { sendToAgent as claudeSendToAgent, sendLoopToAgent as claudeSendLoopToAgent, clearConversation as claudeClearConversation, setModel as claudeSetModel, getModel as claudeGetModel, clearModel as claudeClearModel, getCachedUsage as claudeGetCachedUsage, isDangerousMode as claudeIsDangerousMode, } from '../claude/agent.js';
2
+ import { getModelsForBinary } from '../claude/model-catalog.js';
3
+ import { resolveActiveClaudeExecutable } from '../utils/resolve-claude-bin.js';
4
+ export const sdkProvider = {
5
+ name: 'claude',
6
+ sendToAgent(sessionKey, message, options) {
7
+ return claudeSendToAgent(sessionKey, message, options);
8
+ },
9
+ sendLoopToAgent(sessionKey, message, options) {
10
+ return claudeSendLoopToAgent(sessionKey, message, options);
11
+ },
12
+ clearConversation(sessionKey) {
13
+ claudeClearConversation(sessionKey);
14
+ },
15
+ setModel(scope, model) {
16
+ claudeSetModel(scope, model);
17
+ },
18
+ getModel(scope) {
19
+ return claudeGetModel(scope);
20
+ },
21
+ clearModel(scope) {
22
+ claudeClearModel(scope);
23
+ },
24
+ getCachedUsage(sessionKey) {
25
+ return claudeGetCachedUsage(sessionKey);
26
+ },
27
+ isDangerousMode() {
28
+ return claudeIsDangerousMode();
29
+ },
30
+ async getAvailableModels() {
31
+ // The SDK forwards `model` to whichever binary it spawns — usually the one
32
+ // bundled with claude-agent-sdk, which lags the CLI on PATH. Ask that
33
+ // binary rather than assuming it matches PTY mode's.
34
+ return getModelsForBinary(resolveActiveClaudeExecutable());
35
+ },
36
+ };
37
+ //# sourceMappingURL=sdk-provider.js.map
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Tokens the context holds: the whole prompt of the last call — uncached,
3
+ * cache-read and cache-written alike — plus the reply it produced.
4
+ */
5
+ export function contextTokens(usage) {
6
+ return usage.inputTokens + usage.cacheReadTokens + usage.cacheWriteTokens + usage.outputTokens;
7
+ }
8
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Per-chat and per-thread settings — model, effort, verbosity, transport,
3
+ * status-line toggles.
4
+ *
5
+ * One file per bot. Every instance used to share a single `user-preferences.json`
6
+ * keyed by chatId alone, which in a private chat is the same key on every bot:
7
+ * a `/model` on one instance silently became everyone's model, and — because
8
+ * each worker holds the whole file in memory and rewrites all of it on any
9
+ * change — the next instance to save any setting at all clobbered that choice
10
+ * back. Splitting the file by BOT_ID makes each bot the sole writer of its own
11
+ * state; deliberately sharing a setting across bots is now an explicit
12
+ * broadcast (see providers/prefs-sync.ts) rather than an accident of storage.
13
+ */
14
+ import * as fs from 'fs';
15
+ import * as path from 'path';
16
+ import { z } from 'zod';
17
+ import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
18
+ import { BOT_ID } from '../config.js';
19
+ import { scopeChatId } from '../utils/session-key.js';
20
+ // Zod schema for user preferences
21
+ const userPreferencesSchema = z.object({
22
+ // `.catch` drops values this build no longer knows about (e.g. the retired
23
+ // 'opencode' backend) instead of failing the parse. load() parses the whole
24
+ // file in one shot, so a strict enum would make one stale value wipe every
25
+ // user's saved model/effort/verbosity too.
26
+ provider: z.enum(['claude', 'ccr']).optional().catch(undefined),
27
+ method: z.enum(['sdk', 'pty']).optional(),
28
+ // The clearable settings also take null: a thread that resets one to the
29
+ // default has to say so, or it would fall back to the chat's choice.
30
+ model: z.string().nullable().optional(),
31
+ effort: z.enum(['low', 'medium', 'high', 'xhigh', 'max']).nullable().optional(),
32
+ verbosity: z.enum(['quiet', 'normal', 'verbose', 'debug']).nullable().optional(),
33
+ // `.catch` for the same reason as provider: a mode this build no longer
34
+ // knows about should drop, not take every other saved setting with it.
35
+ permissionMode: z
36
+ .enum(['manual', 'acceptEdits', 'plan', 'auto', 'bypassPermissions'])
37
+ .nullable()
38
+ .optional()
39
+ .catch(undefined),
40
+ showStatusLine: z.boolean().optional(),
41
+ showTopicInStatusLine: z.boolean().optional(),
42
+ showSessionInStatusLine: z.boolean().optional(),
43
+ showPromptInStatusLine: z.boolean().optional(),
44
+ lastUpdated: z.string(),
45
+ });
46
+ const preferencesDataSchema = z.object({
47
+ users: z.record(z.string(), userPreferencesSchema),
48
+ });
49
+ const PREFS_DIR = getStateDir();
50
+ const PREFS_FILE = path.join(PREFS_DIR, `user-preferences-${BOT_ID}.json`);
51
+ /** The single shared file every instance wrote to before preferences were per-bot. */
52
+ const LEGACY_PREFS_FILE = path.join(PREFS_DIR, 'user-preferences.json');
53
+ /**
54
+ * Entries are keyed by settings scope (see SettingsScope): a chat id for the
55
+ * chat-wide value, `chatId:threadId` for one thread's. A thread reads its own
56
+ * 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.
58
+ */
59
+ class UserPreferencesManager {
60
+ data = {};
61
+ constructor() {
62
+ ensureStateDir(PREFS_DIR, 'UserPreferences');
63
+ this.load();
64
+ }
65
+ load() {
66
+ // First start after the split: inherit whatever the shared file holds, so
67
+ // nobody's model or effort resets. The legacy file is read, never removed
68
+ // — sibling bots still on their first start need to seed from it too, and
69
+ // a downgrade should still find it.
70
+ const seeding = !fs.existsSync(PREFS_FILE);
71
+ const loaded = seeding
72
+ ? readJsonFile(LEGACY_PREFS_FILE, preferencesDataSchema, 'UserPreferences')
73
+ : readJsonFile(PREFS_FILE, preferencesDataSchema, 'UserPreferences');
74
+ this.data = { ...(loaded?.users ?? {}) };
75
+ // Claim the per-bot file straight away rather than on the next setting
76
+ // change, so the inherited values are visibly this bot's from now on.
77
+ if (seeding && Object.keys(this.data).length > 0) {
78
+ console.log(`[UserPreferences] Seeded ${path.basename(PREFS_FILE)} from ${path.basename(LEGACY_PREFS_FILE)} (${Object.keys(this.data).length} chat(s))`);
79
+ this.save();
80
+ }
81
+ }
82
+ save() {
83
+ writeJsonFile(PREFS_FILE, { users: { ...this.data } }, 'UserPreferences');
84
+ }
85
+ /** The scope's own value, else the chat's; null (an explicit default) reads as unset. */
86
+ get(scope, field) {
87
+ const key = String(scope);
88
+ const own = this.data[key];
89
+ if (own && own[field] !== undefined)
90
+ return (own[field] ?? undefined);
91
+ const chatKey = String(scopeChatId(scope));
92
+ if (chatKey === key)
93
+ return undefined;
94
+ return (this.data[chatKey]?.[field] ?? undefined);
95
+ }
96
+ /** Apply a field change for `scope`, stamping `lastUpdated` and persisting. */
97
+ patch(scope, changes) {
98
+ const key = String(scope);
99
+ this.data[key] = {
100
+ ...this.data[key],
101
+ ...changes,
102
+ lastUpdated: new Date().toISOString(),
103
+ };
104
+ this.save();
105
+ }
106
+ /**
107
+ * Back to the default for `scope`. A chat-wide entry just drops the field. A
108
+ * thread stores null instead, so "default" isn't read as "whatever the chat
109
+ * has". `lastUpdated` is excluded — it is the one required field, and
110
+ * clearing it would leave an entry that no longer round-trips the schema.
111
+ */
112
+ unset(scope, field) {
113
+ const key = String(scope);
114
+ if (key !== String(scopeChatId(scope))) {
115
+ this.patch(scope, { [field]: null });
116
+ return;
117
+ }
118
+ if (!this.data[key])
119
+ return;
120
+ delete this.data[key][field];
121
+ this.data[key].lastUpdated = new Date().toISOString();
122
+ this.save();
123
+ }
124
+ getProvider(scope) {
125
+ return this.get(scope, 'provider');
126
+ }
127
+ setProvider(scope, provider) {
128
+ this.patch(scope, { provider });
129
+ }
130
+ getMethod(scope) {
131
+ return this.get(scope, 'method');
132
+ }
133
+ setMethod(scope, method) {
134
+ this.patch(scope, { method });
135
+ }
136
+ getModel(scope) {
137
+ return this.get(scope, 'model');
138
+ }
139
+ setModel(scope, model) {
140
+ this.patch(scope, { model });
141
+ }
142
+ clearModel(scope) {
143
+ this.unset(scope, 'model');
144
+ }
145
+ getEffort(scope) {
146
+ return this.get(scope, 'effort');
147
+ }
148
+ setEffort(scope, effort) {
149
+ this.patch(scope, { effort: effort });
150
+ }
151
+ clearEffort(scope) {
152
+ this.unset(scope, 'effort');
153
+ }
154
+ getPermissionMode(scope) {
155
+ return this.get(scope, 'permissionMode');
156
+ }
157
+ setPermissionMode(scope, mode) {
158
+ this.patch(scope, { permissionMode: mode });
159
+ }
160
+ clearPermissionMode(scope) {
161
+ this.unset(scope, 'permissionMode');
162
+ }
163
+ getVerbosity(scope) {
164
+ return this.get(scope, 'verbosity');
165
+ }
166
+ setVerbosity(scope, verbosity) {
167
+ this.patch(scope, { verbosity });
168
+ }
169
+ clearVerbosity(scope) {
170
+ this.unset(scope, 'verbosity');
171
+ }
172
+ getShowStatusLine(scope) {
173
+ return this.get(scope, 'showStatusLine') === true;
174
+ }
175
+ setShowStatusLine(scope, enabled) {
176
+ this.patch(scope, { showStatusLine: enabled });
177
+ }
178
+ getShowTopicInStatusLine(scope) {
179
+ return this.get(scope, 'showTopicInStatusLine') === true;
180
+ }
181
+ setShowTopicInStatusLine(scope, enabled) {
182
+ this.patch(scope, { showTopicInStatusLine: enabled });
183
+ }
184
+ getShowSessionInStatusLine(scope) {
185
+ return this.get(scope, 'showSessionInStatusLine') === true;
186
+ }
187
+ setShowSessionInStatusLine(scope, enabled) {
188
+ this.patch(scope, { showSessionInStatusLine: enabled });
189
+ }
190
+ getShowPromptInStatusLine(scope) {
191
+ return this.get(scope, 'showPromptInStatusLine') === true;
192
+ }
193
+ setShowPromptInStatusLine(scope, enabled) {
194
+ this.patch(scope, { showPromptInStatusLine: enabled });
195
+ }
196
+ /**
197
+ * Start `to` with the settings `from` chose for itself — for a thread forked
198
+ * off another, which should carry on with the same model and transport. A
199
+ * chat-wide `from` copies nothing: `to` falls back to it anyway.
200
+ */
201
+ copyScope(from, to) {
202
+ const own = this.data[String(from)];
203
+ if (!own || String(from) === String(scopeChatId(from)))
204
+ return;
205
+ this.data[String(to)] = { ...own, lastUpdated: new Date().toISOString() };
206
+ this.save();
207
+ }
208
+ clearPreferences(scope) {
209
+ delete this.data[String(scope)];
210
+ this.save();
211
+ }
212
+ }
213
+ export const userPreferences = new UserPreferencesManager();
214
+ //# sourceMappingURL=user-preferences.js.map
@@ -0,0 +1,153 @@
1
+ /**
2
+ * The worker's half of /rebuildbot's "when idle" option: restart once there is
3
+ * nothing left to finish, rather than cutting a turn off halfway.
4
+ *
5
+ * The launcher starts it ('drain'), and from then on this worker watches its
6
+ * own work and tells the launcher what is holding it up ('drain_busy') until
7
+ * there is nothing, at which point it says so ('drain_idle') and the launcher
8
+ * restarts it the way it restarts any worker. The bot that ran the command
9
+ * shows the launcher's tally in one message, edited as instances go
10
+ * ('drain_render') — whichever incarnation of that bot is live by then, since
11
+ * it may well have restarted first.
12
+ *
13
+ * "Nothing left" is four things, because no one of them sees everything:
14
+ * - updates still in the middleware chain: a voice note being transcribed,
15
+ * a message in the batcher, a turn that answers it — every handler awaits
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);
18
+ * - a turn claude started itself on a background task's result, which
19
+ * nothing in either of those knows about;
20
+ * - background tasks still running, whose results would start one of those.
21
+ */
22
+ import { isMainThread, parentPort } from 'worker_threads';
23
+ import { busySessionCount } from './claude/request-queue.js';
24
+ import { hasSelfStartedTurn, whenRepliesSent } from './claude/monitor-relay.js';
25
+ import { taskTracker } from './telegram/task-tracker.js';
26
+ /** How often a draining worker looks again. */
27
+ const CHECK_MS = 2000;
28
+ let updatesInFlight = 0;
29
+ /**
30
+ * Counts updates from the moment they arrive until their handler returns.
31
+ * Registered first, so an update waiting on the batcher or behind another in
32
+ * sequentialize counts as much as one being answered.
33
+ */
34
+ export const countUpdatesInFlight = async (_ctx, next) => {
35
+ updatesInFlight++;
36
+ try {
37
+ await next();
38
+ }
39
+ finally {
40
+ updatesInFlight--;
41
+ }
42
+ };
43
+ function plural(n, one, many) {
44
+ return `${n} ${n === 1 ? one : many}`;
45
+ }
46
+ /** What is keeping the worker busy, in a few words — or null when nothing is. */
47
+ export function describeWork(work) {
48
+ const parts = [];
49
+ if (work.turns > 0)
50
+ parts.push(plural(work.turns, 'turn running', 'turns running'));
51
+ // Every turn an update started is an update too, so these only say
52
+ // something when no turn accounts for them.
53
+ else if (work.updates > 0)
54
+ parts.push(plural(work.updates, 'message being handled', 'messages being handled'));
55
+ if (work.selfStartedTurn)
56
+ parts.push('answering a background task');
57
+ if (work.backgroundTasks > 0)
58
+ parts.push(plural(work.backgroundTasks, 'background task', 'background tasks'));
59
+ return parts.length > 0 ? parts.join(', ') : null;
60
+ }
61
+ function currentWork() {
62
+ return {
63
+ updates: updatesInFlight,
64
+ turns: busySessionCount(),
65
+ selfStartedTurn: hasSelfStartedTurn(),
66
+ backgroundTasks: taskTracker.getBackgroundedTotal(),
67
+ };
68
+ }
69
+ /** The status message's buttons: route back through handleRebuildCallback. */
70
+ export const IDLE_RESTART_BUTTONS = [
71
+ [
72
+ { text: '⚡ Restart the rest now', callback_data: 'rebuild:idle_force' },
73
+ { text: '✖️ Cancel', callback_data: 'rebuild:idle_cancel' },
74
+ ],
75
+ ];
76
+ /**
77
+ * Listen for the launcher's drain messages and say we can take them. Called
78
+ * once the bot is up; a no-op outside multi-instance mode.
79
+ *
80
+ * The 'ready' is what the launcher waits for before sending anything: a
81
+ * worker still starting up has no listener yet, and a 'drain' sent into that
82
+ * gap would leave the launcher waiting on an instance that never heard it.
83
+ */
84
+ export function initRestartWhenIdle(api) {
85
+ if (isMainThread || !parentPort)
86
+ return;
87
+ const pp = parentPort;
88
+ let timer = null;
89
+ let lastReported = null;
90
+ let checking = false;
91
+ const stop = () => {
92
+ if (timer)
93
+ clearInterval(timer);
94
+ timer = null;
95
+ lastReported = null;
96
+ };
97
+ const check = async () => {
98
+ if (!timer || checking)
99
+ return;
100
+ const busy = describeWork(currentWork());
101
+ if (busy) {
102
+ if (busy !== lastReported)
103
+ pp.postMessage({ type: 'drain_busy', detail: busy });
104
+ lastReported = busy;
105
+ return;
106
+ }
107
+ // A reply the relay has handed on may still be on its way to Telegram.
108
+ // Let it land, then make sure nothing new started while it did.
109
+ checking = true;
110
+ try {
111
+ await whenRepliesSent();
112
+ }
113
+ finally {
114
+ checking = false;
115
+ }
116
+ if (!timer || describeWork(currentWork()))
117
+ return;
118
+ stop();
119
+ console.log('[IdleRestart] Nothing left to finish — asking to be restarted');
120
+ pp.postMessage({ type: 'drain_idle' });
121
+ };
122
+ pp.on('message', (msg) => {
123
+ if (msg?.type === 'drain') {
124
+ if (timer)
125
+ return;
126
+ console.log('[IdleRestart] Restart pending — waiting until nothing is left to finish');
127
+ // Not checked straight away: the bot that ran the command is still in
128
+ // that command's handler, and so are the others for a moment if this
129
+ // arrived alongside a message.
130
+ timer = setInterval(() => { void check(); }, CHECK_MS);
131
+ timer.unref();
132
+ }
133
+ else if (msg?.type === 'drain_cancel') {
134
+ if (timer)
135
+ console.log('[IdleRestart] Pending restart cancelled');
136
+ stop();
137
+ }
138
+ else if (msg?.type === 'drain_render') {
139
+ if (msg.chatId === undefined || msg.messageId === undefined || !msg.text)
140
+ return;
141
+ api.editMessageText(msg.chatId, msg.messageId, msg.text, {
142
+ reply_markup: { inline_keyboard: msg.buttons ? IDLE_RESTART_BUTTONS : [] },
143
+ }).catch((err) => {
144
+ const message = err instanceof Error ? err.message : String(err);
145
+ if (message.includes('message is not modified'))
146
+ return;
147
+ console.warn('[IdleRestart] Could not update the status message:', message);
148
+ });
149
+ }
150
+ });
151
+ pp.postMessage({ type: 'ready' });
152
+ }
153
+ //# sourceMappingURL=restart-when-idle.js.map