telecoder 0.0.0-stage → 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 (235) hide show
  1. package/.env.example +375 -0
  2. package/CHANGELOG.md +1867 -0
  3. package/LICENSE +22 -0
  4. package/README.md +130 -2
  5. package/dist/audio/transcribe.js +41 -0
  6. package/dist/bin/mcp-server.js +363 -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 +573 -0
  10. package/dist/bot/command-catalog.js +263 -0
  11. package/dist/bot/deleted-threads.js +103 -0
  12. package/dist/bot/file-access.js +150 -0
  13. package/dist/bot/handlers/album.handler.js +128 -0
  14. package/dist/bot/handlers/branch.handler.js +1096 -0
  15. package/dist/bot/handlers/command/access.js +407 -0
  16. package/dist/bot/handlers/command/admin.js +803 -0
  17. package/dist/bot/handlers/command/all-view.js +33 -0
  18. package/dist/bot/handlers/command/auto-approve.js +138 -0
  19. package/dist/bot/handlers/command/background.js +37 -0
  20. package/dist/bot/handlers/command/botname.js +76 -0
  21. package/dist/bot/handlers/command/btw.js +175 -0
  22. package/dist/bot/handlers/command/cleanup.js +329 -0
  23. package/dist/bot/handlers/command/model.js +226 -0
  24. package/dist/bot/handlers/command/prefs-scope.js +362 -0
  25. package/dist/bot/handlers/command/project.js +458 -0
  26. package/dist/bot/handlers/command/resume.js +325 -0
  27. package/dist/bot/handlers/command/session.js +299 -0
  28. package/dist/bot/handlers/command/settings.js +657 -0
  29. package/dist/bot/handlers/command/shared.js +207 -0
  30. package/dist/bot/handlers/command/tasks.js +681 -0
  31. package/dist/bot/handlers/command/thread.js +128 -0
  32. package/dist/bot/handlers/command/topic-store.js +74 -0
  33. package/dist/bot/handlers/command/topic.js +27 -0
  34. package/dist/bot/handlers/command/usage.js +382 -0
  35. package/dist/bot/handlers/command-fallback.js +179 -0
  36. package/dist/bot/handlers/command.handler.js +446 -0
  37. package/dist/bot/handlers/loop.handler.js +389 -0
  38. package/dist/bot/handlers/media-fallback.js +126 -0
  39. package/dist/bot/handlers/message/replies.js +56 -0
  40. package/dist/bot/handlers/message/shared.js +95 -0
  41. package/dist/bot/handlers/message/turn-notify.js +135 -0
  42. package/dist/bot/handlers/message/turn-runner.js +56 -0
  43. package/dist/bot/handlers/message.handler.js +114 -0
  44. package/dist/bot/handlers/newbot.handler.js +230 -0
  45. package/dist/bot/handlers/photo.handler.js +286 -0
  46. package/dist/bot/handlers/prompts.handler.js +343 -0
  47. package/dist/bot/handlers/running-note.js +44 -0
  48. package/dist/bot/handlers/session-guard.js +78 -0
  49. package/dist/bot/handlers/suggestion.handler.js +84 -0
  50. package/dist/bot/handlers/tree.handler.js +480 -0
  51. package/dist/bot/handlers/view.js +41 -0
  52. package/dist/bot/handlers/voice.handler.js +147 -0
  53. package/dist/bot/kept-threads.js +51 -0
  54. package/dist/bot/middleware/admin-only.js +49 -0
  55. package/dist/bot/middleware/album-collector.js +69 -0
  56. package/dist/bot/middleware/auth.middleware.js +122 -0
  57. package/dist/bot/middleware/group-mention.middleware.js +145 -0
  58. package/dist/bot/middleware/group-role.middleware.js +75 -0
  59. package/dist/bot/middleware/message-batcher.js +87 -0
  60. package/dist/bot/middleware/queued-messages.js +1082 -0
  61. package/dist/bot/middleware/stale-filter.js +9 -0
  62. package/dist/build-info.json +8 -0
  63. package/dist/claude/ask-user-form.js +517 -0
  64. package/dist/claude/ask-user.js +363 -0
  65. package/dist/claude/auto-approve.js +225 -0
  66. package/dist/claude/auto-topic-haiku.js +143 -0
  67. package/dist/claude/available-commands.js +156 -0
  68. package/dist/claude/background-hint.js +91 -0
  69. package/dist/claude/branch-tree.js +393 -0
  70. package/dist/claude/carry-over.js +25 -0
  71. package/dist/claude/ccr-shim.js +48 -0
  72. package/dist/claude/charter-judge.js +214 -0
  73. package/dist/claude/claude-auth.js +117 -0
  74. package/dist/claude/command-parser.js +206 -0
  75. package/dist/claude/cost-overlay-scraper.js +134 -0
  76. package/dist/claude/effort-level.js +5 -0
  77. package/dist/claude/enabled-plugins.js +52 -0
  78. package/dist/claude/in-flight-tracker.js +82 -0
  79. package/dist/claude/ipc-server.js +192 -0
  80. package/dist/claude/mcp-bridge.js +481 -0
  81. package/dist/claude/memory-guard.js +400 -0
  82. package/dist/claude/message-offsets.js +88 -0
  83. package/dist/claude/modal-relay.js +817 -0
  84. package/dist/claude/model-catalog.js +102 -0
  85. package/dist/claude/monitor-relay.js +712 -0
  86. package/dist/claude/native-commands.js +40 -0
  87. package/dist/claude/pending-branches.js +93 -0
  88. package/dist/claude/pending-suggestions.js +50 -0
  89. package/dist/claude/permission-gate.js +338 -0
  90. package/dist/claude/permission-mode.js +152 -0
  91. package/dist/claude/poll-user.js +51 -0
  92. package/dist/claude/prewarm.js +70 -0
  93. package/dist/claude/project-commands.js +69 -0
  94. package/dist/claude/prompt-hold.js +124 -0
  95. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  96. package/dist/claude/pty-idle-reaper.js +96 -0
  97. package/dist/claude/pty-provider.js +2499 -0
  98. package/dist/claude/pty-spawn-config.js +343 -0
  99. package/dist/claude/pty-stream.js +363 -0
  100. package/dist/claude/pty-watch.js +201 -0
  101. package/dist/claude/request-queue.js +107 -0
  102. package/dist/claude/rewind.js +111 -0
  103. package/dist/claude/scheduled-runner.js +89 -0
  104. package/dist/claude/scheduler.js +241 -0
  105. package/dist/claude/scope-guard.js +279 -0
  106. package/dist/claude/screen-marks.js +83 -0
  107. package/dist/claude/screen-render.js +96 -0
  108. package/dist/claude/secret-request.js +576 -0
  109. package/dist/claude/session-history.js +288 -0
  110. package/dist/claude/session-jsonl.js +1067 -0
  111. package/dist/claude/session-manager.js +216 -0
  112. package/dist/claude/session-move.js +70 -0
  113. package/dist/claude/session-scan.js +270 -0
  114. package/dist/claude/setup-token.js +285 -0
  115. package/dist/claude/shell-mode-gate.js +60 -0
  116. package/dist/claude/side-call-options.js +45 -0
  117. package/dist/claude/side-question.js +252 -0
  118. package/dist/claude/stage-images.js +62 -0
  119. package/dist/claude/subagent-tools.js +12 -0
  120. package/dist/claude/synthetic-ctx.js +51 -0
  121. package/dist/claude/tasks-overlay-scraper.js +217 -0
  122. package/dist/claude/thread-judge-haiku.js +88 -0
  123. package/dist/claude/tip-scraper.js +77 -0
  124. package/dist/claude/tui-modal.js +746 -0
  125. package/dist/claude/tui-state.js +456 -0
  126. package/dist/claude/turn-end.js +105 -0
  127. package/dist/claude/turn-prose.js +64 -0
  128. package/dist/claude/typed-answer.js +104 -0
  129. package/dist/claude/update-banner-relay.js +70 -0
  130. package/dist/cli/commands/doctor.js +338 -0
  131. package/dist/cli/commands/help.js +34 -0
  132. package/dist/cli/commands/init.js +126 -0
  133. package/dist/cli/commands/service.js +710 -0
  134. package/dist/cli/commands/start.js +63 -0
  135. package/dist/cli/commands/version.js +11 -0
  136. package/dist/cli/commands/watch.js +322 -0
  137. package/dist/cli/dispatch.js +84 -0
  138. package/dist/cli/init/env-file.js +99 -0
  139. package/dist/cli/init/flow.js +705 -0
  140. package/dist/cli/init/prompter.js +124 -0
  141. package/dist/cli/init/telegram.js +120 -0
  142. package/dist/cli/service/render.js +212 -0
  143. package/dist/cli.js +18 -0
  144. package/dist/config-report.js +107 -0
  145. package/dist/config.js +525 -0
  146. package/dist/index.js +443 -0
  147. package/dist/launcher.js +960 -0
  148. package/dist/node-version-check.js +27 -0
  149. package/dist/providers/ccr-health.js +119 -0
  150. package/dist/providers/ccr-introspect.js +142 -0
  151. package/dist/providers/ccr-provider.js +59 -0
  152. package/dist/providers/claude-provider.js +10 -0
  153. package/dist/providers/prefs-sync.js +121 -0
  154. package/dist/providers/project-favorites.js +74 -0
  155. package/dist/providers/provider-router.js +128 -0
  156. package/dist/providers/provider-switch.js +91 -0
  157. package/dist/providers/spawn-settings.js +45 -0
  158. package/dist/providers/types.js +8 -0
  159. package/dist/providers/user-preferences.js +322 -0
  160. package/dist/restart-when-idle.js +173 -0
  161. package/dist/startup/auto-continue.js +67 -0
  162. package/dist/startup/auto-resume.js +161 -0
  163. package/dist/startup/notices.js +120 -0
  164. package/dist/startup/shared.js +44 -0
  165. package/dist/startup/verify-token.js +31 -0
  166. package/dist/telegram/access-request.js +153 -0
  167. package/dist/telegram/action-logger.js +522 -0
  168. package/dist/telegram/admin-mention.js +107 -0
  169. package/dist/telegram/background-activity-card.js +502 -0
  170. package/dist/telegram/botname-settings.js +282 -0
  171. package/dist/telegram/button-text.js +26 -0
  172. package/dist/telegram/client-options.js +26 -0
  173. package/dist/telegram/deduplication.js +33 -0
  174. package/dist/telegram/entities.js +295 -0
  175. package/dist/telegram/force-reply-tracker.js +96 -0
  176. package/dist/telegram/lettered-options.js +87 -0
  177. package/dist/telegram/markdown.js +362 -0
  178. package/dist/telegram/message-sender.js +1019 -0
  179. package/dist/telegram/prompt-label.js +148 -0
  180. package/dist/telegram/prompt-suggestion.js +54 -0
  181. package/dist/telegram/send.js +123 -0
  182. package/dist/telegram/streaming-turn.js +103 -0
  183. package/dist/telegram/suggestions-settings.js +30 -0
  184. package/dist/telegram/table-lists.js +56 -0
  185. package/dist/telegram/task-list.js +367 -0
  186. package/dist/telegram/task-tracker.js +128 -0
  187. package/dist/telegram/terminal-renderer.js +667 -0
  188. package/dist/telegram/thread-titles.js +262 -0
  189. package/dist/telegram/threads-setup.js +117 -0
  190. package/dist/utils/admins.js +143 -0
  191. package/dist/utils/agent-timer.js +55 -0
  192. package/dist/utils/atomic-write.js +24 -0
  193. package/dist/utils/bot-icon.js +248 -0
  194. package/dist/utils/bot-token.js +77 -0
  195. package/dist/utils/bounded-map.js +55 -0
  196. package/dist/utils/build-info.js +57 -0
  197. package/dist/utils/caffeinate.js +53 -0
  198. package/dist/utils/claude-env.js +53 -0
  199. package/dist/utils/claude-version.js +48 -0
  200. package/dist/utils/config-home.js +62 -0
  201. package/dist/utils/download.js +137 -0
  202. package/dist/utils/exit-codes.js +59 -0
  203. package/dist/utils/file-type.js +149 -0
  204. package/dist/utils/format.js +78 -0
  205. package/dist/utils/home-project.js +30 -0
  206. package/dist/utils/host-stall.js +51 -0
  207. package/dist/utils/id-list.js +44 -0
  208. package/dist/utils/idle-restart.js +92 -0
  209. package/dist/utils/install-mode.js +63 -0
  210. package/dist/utils/instance-config.js +148 -0
  211. package/dist/utils/instances.js +95 -0
  212. package/dist/utils/json-store.js +140 -0
  213. package/dist/utils/keyed-settings.js +62 -0
  214. package/dist/utils/legacy-env.js +35 -0
  215. package/dist/utils/memory-pressure.js +60 -0
  216. package/dist/utils/npm-version.js +134 -0
  217. package/dist/utils/prefs-relay.js +107 -0
  218. package/dist/utils/proc-children.js +102 -0
  219. package/dist/utils/resolve-bin.js +86 -0
  220. package/dist/utils/resolve-claude-bin.js +52 -0
  221. package/dist/utils/respawn-backoff.js +28 -0
  222. package/dist/utils/sanitize.js +91 -0
  223. package/dist/utils/session-key.js +37 -0
  224. package/dist/utils/stale-launcher.js +109 -0
  225. package/dist/utils/state-dir-migration.js +92 -0
  226. package/dist/utils/systemd.js +126 -0
  227. package/dist/utils/telegram-proxy.js +72 -0
  228. package/dist/utils/uploads-dir.js +27 -0
  229. package/dist/utils/user-roster.js +275 -0
  230. package/dist/utils/verbosity.js +118 -0
  231. package/dist/utils/version-check.js +166 -0
  232. package/dist/utils/workspace-guard.js +44 -0
  233. package/dist/worker-restart.js +141 -0
  234. package/instances.json.example +41 -0
  235. package/package.json +75 -4
@@ -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,45 @@
1
+ /**
2
+ * Setting a model or effort at a level — one thread, a chat's default, a whole
3
+ * chat, or the whole bot — and getting the claudes it concerns onto it.
4
+ *
5
+ * Both are flags the CLI reads at spawn, so a change only reaches a session
6
+ * once its pty is restarted. Which ones that is follows from the values
7
+ * themselves: every live session whose resolved value differs before and
8
+ * after the change. Those idle now restart on their next message; those
9
+ * mid-turn restart when the turn ends, so nothing is cut short and nothing
10
+ * stays on the old value until some unrelated respawn. The conversation
11
+ * survives either way, as the next spawn resumes the same session id.
12
+ */
13
+ import { getPtyProvider } from './claude-provider.js';
14
+ import { isInFlight, runAfterTurn } from '../claude/in-flight-tracker.js';
15
+ import { userPreferences } from './user-preferences.js';
16
+ import { scopeChatId } from '../utils/session-key.js';
17
+ function read(scope, field) {
18
+ return field === 'model' ? userPreferences.getModel(scope) : userPreferences.getEffort(scope);
19
+ }
20
+ /**
21
+ * Apply `value` at `level` from `scope` and restart what it changed.
22
+ * `current` is the session the command was typed in: a restart there is
23
+ * immediate even mid-turn, as a /model there always was.
24
+ */
25
+ export function applySpawnSetting(scope, field, value, level, current) {
26
+ const pty = getPtyProvider();
27
+ const live = level === 'all' ? pty.listSessionKeys() : pty.listSessionKeysForChat(scopeChatId(scope));
28
+ const before = new Map(live.map((k) => [k, read(k, field)]));
29
+ const dropped = userPreferences.applyLevel(scope, field, value, level);
30
+ const restarted = [];
31
+ const busy = [];
32
+ for (const k of live) {
33
+ if (read(k, field) === before.get(k))
34
+ continue;
35
+ if (k !== current && isInFlight(k)) {
36
+ busy.push(k);
37
+ runAfterTurn(k, () => pty.clearConversation(k));
38
+ continue;
39
+ }
40
+ pty.clearConversation(k);
41
+ restarted.push(k);
42
+ }
43
+ return { dropped, restarted, busy };
44
+ }
45
+ //# sourceMappingURL=spawn-settings.js.map
@@ -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,322 @@
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, config } 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
+ // The clearable settings also take null: a thread that resets one to the
28
+ // default has to say so, or it would fall back to the chat's choice.
29
+ model: z.string().nullable().optional(),
30
+ effort: z.enum(['low', 'medium', 'high', 'xhigh', 'max']).nullable().optional(),
31
+ verbosity: z.enum(['quiet', 'normal', 'verbose', 'debug']).nullable().optional(),
32
+ // `.catch` for the same reason as provider: a mode this build no longer
33
+ // knows about should drop, not take every other saved setting with it.
34
+ permissionMode: z
35
+ .enum(['manual', 'acceptEdits', 'plan', 'auto', 'bypassPermissions'])
36
+ .nullable()
37
+ .optional()
38
+ .catch(undefined),
39
+ showStatusLine: z.boolean().optional(),
40
+ showTopicInStatusLine: z.boolean().optional(),
41
+ showSessionInStatusLine: z.boolean().optional(),
42
+ showPromptInStatusLine: z.boolean().optional(),
43
+ lastUpdated: z.string(),
44
+ });
45
+ const preferencesDataSchema = z.object({
46
+ users: z.record(z.string(), userPreferencesSchema),
47
+ });
48
+ /**
49
+ * The entry every chat falls back to for a spawn setting it never chose:
50
+ * what `/model … all` writes. Not a chat id, so it never collides with one.
51
+ */
52
+ const BOT_DEFAULT_KEY = '*';
53
+ const SPAWN_SETTINGS = new Set(['model', 'effort']);
54
+ const PREFS_DIR = getStateDir();
55
+ const PREFS_FILE = path.join(PREFS_DIR, `user-preferences-${BOT_ID}.json`);
56
+ /** The single shared file every instance wrote to before preferences were per-bot. */
57
+ const LEGACY_PREFS_FILE = path.join(PREFS_DIR, 'user-preferences.json');
58
+ /**
59
+ * Entries are keyed by settings scope (see SettingsScope): a chat id for the
60
+ * chat-wide value, `chatId:threadId` for one thread's. A thread reads its own
61
+ * entry first and the chat's after, field by field, so a thread only holds the
62
+ * settings it changed and picks up the rest from the chat. Model and effort
63
+ * fall back once more, to the bot-wide entry under BOT_DEFAULT_KEY.
64
+ */
65
+ class UserPreferencesManager {
66
+ data = {};
67
+ constructor() {
68
+ ensureStateDir(PREFS_DIR, 'UserPreferences');
69
+ this.load();
70
+ }
71
+ load() {
72
+ // First start after the split: inherit whatever the shared file holds, so
73
+ // nobody's model or effort resets. The legacy file is read, never removed
74
+ // — sibling bots still on their first start need to seed from it too, and
75
+ // a downgrade should still find it.
76
+ const seeding = !fs.existsSync(PREFS_FILE);
77
+ const loaded = seeding
78
+ ? readJsonFile(LEGACY_PREFS_FILE, preferencesDataSchema, 'UserPreferences')
79
+ : readJsonFile(PREFS_FILE, preferencesDataSchema, 'UserPreferences');
80
+ this.data = { ...(loaded?.users ?? {}) };
81
+ // Claim the per-bot file straight away rather than on the next setting
82
+ // change, so the inherited values are visibly this bot's from now on.
83
+ if (seeding && Object.keys(this.data).length > 0) {
84
+ console.log(`[UserPreferences] Seeded ${path.basename(PREFS_FILE)} from ${path.basename(LEGACY_PREFS_FILE)} (${Object.keys(this.data).length} chat(s))`);
85
+ this.save();
86
+ }
87
+ }
88
+ save() {
89
+ writeJsonFile(PREFS_FILE, { users: { ...this.data } }, 'UserPreferences');
90
+ }
91
+ /**
92
+ * The entries a scope reads, in order: its own, the chat's, and for the
93
+ * spawn settings the bot-wide default.
94
+ */
95
+ chain(scope, field) {
96
+ const key = String(scope);
97
+ const chatKey = String(scopeChatId(scope));
98
+ const keys = chatKey === key ? [key] : [key, chatKey];
99
+ if (SPAWN_SETTINGS.has(field))
100
+ keys.push(BOT_DEFAULT_KEY);
101
+ return keys;
102
+ }
103
+ /** The first entry in the chain that holds the field, null included. */
104
+ holder(scope, field) {
105
+ return this.chain(scope, field).find((k) => this.data[k]?.[field] !== undefined);
106
+ }
107
+ /** The nearest value along the chain; null (an explicit default) reads as unset. */
108
+ get(scope, field) {
109
+ const k = this.holder(scope, field);
110
+ if (k === undefined)
111
+ return undefined;
112
+ return (this.data[k][field] ?? undefined);
113
+ }
114
+ /** Apply a field change for `scope`, stamping `lastUpdated` and persisting. */
115
+ patch(scope, changes) {
116
+ const key = String(scope);
117
+ this.data[key] = {
118
+ ...this.data[key],
119
+ ...changes,
120
+ lastUpdated: new Date().toISOString(),
121
+ };
122
+ this.save();
123
+ }
124
+ /**
125
+ * Back to the default for `scope`. A chat-wide entry just drops the field. A
126
+ * thread stores null instead, so "default" isn't read as "whatever the chat
127
+ * has". `lastUpdated` is excluded — it is the one required field, and
128
+ * clearing it would leave an entry that no longer round-trips the schema.
129
+ */
130
+ unset(scope, field) {
131
+ const key = String(scope);
132
+ if (key !== String(scopeChatId(scope))) {
133
+ this.patch(scope, { [field]: null });
134
+ return;
135
+ }
136
+ if (!this.data[key])
137
+ return;
138
+ delete this.data[key][field];
139
+ this.data[key].lastUpdated = new Date().toISOString();
140
+ this.save();
141
+ }
142
+ /**
143
+ * Drop a thread's own settings, for a thread that no longer exists. A chat's
144
+ * entry is never dropped this way: its threads fall back to it.
145
+ */
146
+ forgetThread(scope) {
147
+ const key = String(scope);
148
+ if (key === String(scopeChatId(scope)) || !this.data[key])
149
+ return;
150
+ delete this.data[key];
151
+ this.save();
152
+ }
153
+ getProvider(scope) {
154
+ return this.get(scope, 'provider');
155
+ }
156
+ setProvider(scope, provider) {
157
+ this.patch(scope, { provider });
158
+ }
159
+ getModel(scope) {
160
+ return this.get(scope, 'model');
161
+ }
162
+ setModel(scope, model) {
163
+ this.patch(scope, { model });
164
+ }
165
+ clearModel(scope) {
166
+ this.unset(scope, 'model');
167
+ }
168
+ getEffort(scope) {
169
+ return this.get(scope, 'effort');
170
+ }
171
+ setEffort(scope, effort) {
172
+ this.patch(scope, { effort: effort });
173
+ }
174
+ clearEffort(scope) {
175
+ this.unset(scope, 'effort');
176
+ }
177
+ getPermissionMode(scope) {
178
+ return this.get(scope, 'permissionMode');
179
+ }
180
+ setPermissionMode(scope, mode) {
181
+ this.patch(scope, { permissionMode: mode });
182
+ }
183
+ clearPermissionMode(scope) {
184
+ this.unset(scope, 'permissionMode');
185
+ }
186
+ getVerbosity(scope) {
187
+ return this.get(scope, 'verbosity');
188
+ }
189
+ setVerbosity(scope, verbosity) {
190
+ this.patch(scope, { verbosity });
191
+ }
192
+ clearVerbosity(scope) {
193
+ this.unset(scope, 'verbosity');
194
+ }
195
+ // The status line and its topic line are on until a chat turns them off;
196
+ // the prompts and the resume command are off until it turns them on.
197
+ getShowStatusLine(scope) {
198
+ return this.get(scope, 'showStatusLine') ?? config.STATUS_LINE_DEFAULT;
199
+ }
200
+ setShowStatusLine(scope, enabled) {
201
+ this.patch(scope, { showStatusLine: enabled });
202
+ }
203
+ getShowTopicInStatusLine(scope) {
204
+ return this.get(scope, 'showTopicInStatusLine') ?? true;
205
+ }
206
+ setShowTopicInStatusLine(scope, enabled) {
207
+ this.patch(scope, { showTopicInStatusLine: enabled });
208
+ }
209
+ getShowSessionInStatusLine(scope) {
210
+ return this.get(scope, 'showSessionInStatusLine') === true;
211
+ }
212
+ setShowSessionInStatusLine(scope, enabled) {
213
+ this.patch(scope, { showSessionInStatusLine: enabled });
214
+ }
215
+ getShowPromptInStatusLine(scope) {
216
+ return this.get(scope, 'showPromptInStatusLine') === true;
217
+ }
218
+ setShowPromptInStatusLine(scope, enabled) {
219
+ this.patch(scope, { showPromptInStatusLine: enabled });
220
+ }
221
+ /**
222
+ * Which level a scope's model or effort comes from: its own pin, the chat's
223
+ * default, or the bot's. Undefined when nothing chose, so the CLI's own
224
+ * default applies. A level that chose "the CLI default" on purpose counts.
225
+ */
226
+ sourceOf(scope, field) {
227
+ const k = this.holder(scope, field);
228
+ if (k === undefined)
229
+ return undefined;
230
+ if (k === BOT_DEFAULT_KEY)
231
+ return 'bot';
232
+ return k === String(scopeChatId(scope)) ? 'chat' : 'thread';
233
+ }
234
+ /**
235
+ * The threads of a chat that pin `field` to something other than `value`:
236
+ * the ones a `default`-level change leaves alone.
237
+ */
238
+ threadsPinnedOtherThan(chatId, field, value) {
239
+ const prefix = `${chatId}:`;
240
+ return Object.keys(this.data).filter((k) => {
241
+ if (!k.startsWith(prefix))
242
+ return false;
243
+ const v = this.data[k][field];
244
+ return v !== undefined && v !== value;
245
+ });
246
+ }
247
+ /**
248
+ * Set a model or effort at a level (see SettingLevel). `value: null` means
249
+ * the CLI's own default, chosen on purpose: it is stored, so it isn't read
250
+ * as "whatever the wider level says". At `all` there is nothing wider, so
251
+ * null just clears the bot-wide entry.
252
+ *
253
+ * Returns the entries whose own, different pin was dropped to follow the
254
+ * new value, for the confirmation to name.
255
+ */
256
+ applyLevel(scope, field, value, level) {
257
+ const key = String(scope);
258
+ const chatKey = String(scopeChatId(scope));
259
+ const inThread = key !== chatKey;
260
+ const now = new Date().toISOString();
261
+ const dropped = [];
262
+ const drop = (k) => {
263
+ const entry = this.data[k];
264
+ if (!entry || entry[field] === undefined)
265
+ return;
266
+ if (entry[field] !== value)
267
+ dropped.push(k);
268
+ delete entry[field];
269
+ entry.lastUpdated = now;
270
+ };
271
+ const set = (k, v) => {
272
+ this.data[k] = { ...this.data[k], [field]: v, lastUpdated: now };
273
+ };
274
+ if (level === 'all') {
275
+ for (const k of Object.keys(this.data)) {
276
+ if (k !== BOT_DEFAULT_KEY)
277
+ drop(k);
278
+ }
279
+ if (value !== null)
280
+ set(BOT_DEFAULT_KEY, value);
281
+ else if (this.data[BOT_DEFAULT_KEY]) {
282
+ delete this.data[BOT_DEFAULT_KEY][field];
283
+ this.data[BOT_DEFAULT_KEY].lastUpdated = now;
284
+ }
285
+ }
286
+ else if (level === 'thread' && inThread) {
287
+ set(key, value);
288
+ }
289
+ else {
290
+ if (level === 'chat') {
291
+ for (const k of Object.keys(this.data)) {
292
+ if (k.startsWith(`${chatKey}:`))
293
+ drop(k);
294
+ }
295
+ }
296
+ else if (inThread) {
297
+ drop(key);
298
+ }
299
+ set(chatKey, value);
300
+ }
301
+ this.save();
302
+ return dropped;
303
+ }
304
+ /**
305
+ * Start `to` with the settings `from` chose for itself — for a thread branched
306
+ * off another, which should carry on with the same model and transport. A
307
+ * chat-wide `from` copies nothing: `to` falls back to it anyway.
308
+ */
309
+ copyScope(from, to) {
310
+ const own = this.data[String(from)];
311
+ if (!own || String(from) === String(scopeChatId(from)))
312
+ return;
313
+ this.data[String(to)] = { ...own, lastUpdated: new Date().toISOString() };
314
+ this.save();
315
+ }
316
+ clearPreferences(scope) {
317
+ delete this.data[String(scope)];
318
+ this.save();
319
+ }
320
+ }
321
+ export const userPreferences = new UserPreferencesManager();
322
+ //# sourceMappingURL=user-preferences.js.map
@@ -0,0 +1,173 @@
1
+ /**
2
+ * The worker's half of /botrebuild'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 several 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 (/loop runs);
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
+ * - a shell command claude left running in the background, which dies with
22
+ * its claude — the same check the PTY idle reaper makes;
23
+ * - the Haiku side-call naming a turn's topic, and a thread rename held for
24
+ * its cooldown or on its way to Telegram: fire-and-forget after the reply,
25
+ * so nothing above counts them, and a restart over one loses the name.
26
+ */
27
+ import { isMainThread, parentPort } from 'worker_threads';
28
+ import { busySessionCount } from './claude/request-queue.js';
29
+ import { hasSelfStartedTurn, whenRepliesSent } from './claude/monitor-relay.js';
30
+ import { sessionsWithBackgroundShell } from './claude/pty-idle-reaper.js';
31
+ import { topicCallsInFlight } from './claude/auto-topic-haiku.js';
32
+ import { taskTracker } from './telegram/task-tracker.js';
33
+ import { renamesOutstanding } from './telegram/thread-titles.js';
34
+ /** How often a draining worker looks again. */
35
+ const CHECK_MS = 2000;
36
+ let updatesInFlight = 0;
37
+ /**
38
+ * Counts updates from the moment they arrive until their handler returns.
39
+ * Registered first, so an update waiting on the batcher or behind another in
40
+ * sequentialize counts as much as one being answered.
41
+ */
42
+ export const countUpdatesInFlight = async (_ctx, next) => {
43
+ updatesInFlight++;
44
+ try {
45
+ await next();
46
+ }
47
+ finally {
48
+ updatesInFlight--;
49
+ }
50
+ };
51
+ function plural(n, one, many) {
52
+ return `${n} ${n === 1 ? one : many}`;
53
+ }
54
+ /** What is keeping the worker busy, in a few words — or null when nothing is. */
55
+ export function describeWork(work) {
56
+ const parts = [];
57
+ if (work.turns > 0)
58
+ parts.push(plural(work.turns, 'turn running', 'turns running'));
59
+ // Every turn an update started is an update too, so these only say
60
+ // something when no turn accounts for them.
61
+ else if (work.updates > 0)
62
+ parts.push(plural(work.updates, 'message being handled', 'messages being handled'));
63
+ if (work.selfStartedTurn)
64
+ parts.push('answering a background task');
65
+ if (work.backgroundTasks > 0)
66
+ parts.push(plural(work.backgroundTasks, 'background task', 'background tasks'));
67
+ if (work.backgroundShells > 0)
68
+ parts.push(plural(work.backgroundShells, 'background shell command', 'background shell commands'));
69
+ if (work.topicCalls > 0)
70
+ parts.push(work.topicCalls === 1 ? 'naming the topic' : `naming ${work.topicCalls} topics`);
71
+ if (work.threadRenames > 0)
72
+ parts.push(work.threadRenames === 1 ? 'renaming a thread' : `renaming ${work.threadRenames} threads`);
73
+ return parts.length > 0 ? parts.join(', ') : null;
74
+ }
75
+ function currentWork() {
76
+ return {
77
+ updates: updatesInFlight,
78
+ turns: busySessionCount(),
79
+ selfStartedTurn: hasSelfStartedTurn(),
80
+ backgroundTasks: taskTracker.getBackgroundedTotal(),
81
+ backgroundShells: sessionsWithBackgroundShell(),
82
+ topicCalls: topicCallsInFlight(),
83
+ threadRenames: renamesOutstanding(),
84
+ };
85
+ }
86
+ /** The status message's buttons: route back through handleBotRebuildCallback. */
87
+ export const IDLE_RESTART_BUTTONS = [
88
+ [
89
+ { text: '⚡ Restart the rest now', callback_data: 'botrebuild:idle_force' },
90
+ { text: '✖️ Cancel', callback_data: 'botrebuild:idle_cancel' },
91
+ ],
92
+ ];
93
+ /**
94
+ * Listen for the launcher's drain messages and say we can take them. Called
95
+ * once the bot is up; a no-op outside multi-instance mode.
96
+ *
97
+ * The 'ready' is what the launcher waits for before sending anything: a
98
+ * worker still starting up has no listener yet, and a 'drain' sent into that
99
+ * gap would leave the launcher waiting on an instance that never heard it.
100
+ */
101
+ export function initRestartWhenIdle(api) {
102
+ if (isMainThread || !parentPort)
103
+ return;
104
+ const pp = parentPort;
105
+ let timer = null;
106
+ let lastReported = null;
107
+ let checking = false;
108
+ const stop = () => {
109
+ if (timer)
110
+ clearInterval(timer);
111
+ timer = null;
112
+ lastReported = null;
113
+ };
114
+ const check = async () => {
115
+ if (!timer || checking)
116
+ return;
117
+ const busy = describeWork(currentWork());
118
+ if (busy) {
119
+ if (busy !== lastReported)
120
+ pp.postMessage({ type: 'drain_busy', detail: busy });
121
+ lastReported = busy;
122
+ return;
123
+ }
124
+ // A reply the relay has handed on may still be on its way to Telegram.
125
+ // Let it land, then make sure nothing new started while it did.
126
+ checking = true;
127
+ try {
128
+ await whenRepliesSent();
129
+ }
130
+ finally {
131
+ checking = false;
132
+ }
133
+ if (!timer || describeWork(currentWork()))
134
+ return;
135
+ stop();
136
+ console.log('[IdleRestart] Nothing left to finish — asking to be restarted');
137
+ pp.postMessage({ type: 'drain_idle' });
138
+ };
139
+ pp.on('message', (msg) => {
140
+ if (msg?.type === 'drain') {
141
+ // A rebuild while one is still pending: the launcher's new tally starts
142
+ // out blank, so say again what is holding this worker up.
143
+ lastReported = null;
144
+ if (timer)
145
+ return;
146
+ console.log('[IdleRestart] Restart pending — waiting until nothing is left to finish');
147
+ // Not checked straight away: the bot that ran the command is still in
148
+ // that command's handler, and so are the others for a moment if this
149
+ // arrived alongside a message.
150
+ timer = setInterval(() => { void check(); }, CHECK_MS);
151
+ timer.unref();
152
+ }
153
+ else if (msg?.type === 'drain_cancel') {
154
+ if (timer)
155
+ console.log('[IdleRestart] Pending restart cancelled');
156
+ stop();
157
+ }
158
+ else if (msg?.type === 'drain_render') {
159
+ if (msg.chatId === undefined || msg.messageId === undefined || !msg.text)
160
+ return;
161
+ api.editMessageText(msg.chatId, msg.messageId, msg.text, {
162
+ reply_markup: { inline_keyboard: msg.buttons ? IDLE_RESTART_BUTTONS : [] },
163
+ }).catch((err) => {
164
+ const message = err instanceof Error ? err.message : String(err);
165
+ if (message.includes('message is not modified'))
166
+ return;
167
+ console.warn('[IdleRestart] Could not update the status message:', message);
168
+ });
169
+ }
170
+ });
171
+ pp.postMessage({ type: 'ready' });
172
+ }
173
+ //# sourceMappingURL=restart-when-idle.js.map