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,27 @@
1
+ /**
2
+ * Refuse to start on a Node.js older than 22.
3
+ *
4
+ * Imported first by every entry point, so it runs before the modules that
5
+ * would otherwise fail on an old runtime with an error that doesn't mention
6
+ * the version at all. It has no imports of its own for the same reason, and
7
+ * sticks to syntax and APIs every Node release still in use understands.
8
+ *
9
+ * Node 20 reached end of life in April 2026; 22 is the oldest line that still
10
+ * gets security fixes, and the one CI runs.
11
+ */
12
+ export const MIN_NODE_MAJOR = 22;
13
+ /** The message to print for `version` (like "v20.11.1"), or undefined if it is new enough. */
14
+ export function nodeVersionProblem(version, minMajor = MIN_NODE_MAJOR) {
15
+ const major = parseInt(version.replace(/^v/, '').split('.')[0], 10);
16
+ if (Number.isFinite(major) && major >= minMajor)
17
+ return undefined;
18
+ return (`TeleCoder needs Node.js ${minMajor} or newer, and this is Node.js ${version}.\n` +
19
+ `Install Node.js ${minMajor} (https://nodejs.org, or e.g. \`nvm install ${minMajor}\`), ` +
20
+ 'then run `npm install` again so native modules are rebuilt for it.');
21
+ }
22
+ const problem = nodeVersionProblem(process.version);
23
+ if (problem) {
24
+ console.error(`❌ ${problem}`);
25
+ process.exit(1);
26
+ }
27
+ //# sourceMappingURL=node-version-check.js.map
@@ -0,0 +1,119 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import * as os from 'os';
4
+ import { spawn } from 'child_process';
5
+ import { config } from '../config.js';
6
+ const CCR_PID_PATH = path.join(os.homedir(), '.claude-code-router', '.claude-code-router.pid');
7
+ const PROBE_TIMEOUT_MS = 1500;
8
+ const START_POLL_INTERVAL_MS = 250;
9
+ const START_TIMEOUT_MS = 8000;
10
+ export async function isCcrRunning(timeoutMs = PROBE_TIMEOUT_MS) {
11
+ try {
12
+ const url = `${config.CCR_BASE_URL.replace(/\/$/, '')}/api/config`;
13
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
14
+ return res.ok;
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ }
20
+ function isPidAlive(pid) {
21
+ try {
22
+ process.kill(pid, 0);
23
+ return true;
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ }
29
+ function clearStalePidfile() {
30
+ try {
31
+ if (!fs.existsSync(CCR_PID_PATH))
32
+ return;
33
+ const raw = fs.readFileSync(CCR_PID_PATH, 'utf-8').trim();
34
+ const pid = parseInt(raw, 10);
35
+ if (!Number.isFinite(pid) || !isPidAlive(pid)) {
36
+ fs.unlinkSync(CCR_PID_PATH);
37
+ console.log(`[CCR] Removed stale pidfile (pid ${raw} not running)`);
38
+ }
39
+ }
40
+ catch (err) {
41
+ console.warn('[CCR] Failed to inspect pidfile:', err instanceof Error ? err.message : err);
42
+ }
43
+ }
44
+ async function waitUntilUp(deadline) {
45
+ while (Date.now() < deadline) {
46
+ if (await isCcrRunning(800))
47
+ return true;
48
+ await new Promise((resolve) => setTimeout(resolve, START_POLL_INTERVAL_MS));
49
+ }
50
+ return false;
51
+ }
52
+ async function startCcrProcess() {
53
+ clearStalePidfile();
54
+ return new Promise((resolve) => {
55
+ let resolved = false;
56
+ const finish = (result) => {
57
+ if (!resolved) {
58
+ resolved = true;
59
+ resolve(result);
60
+ }
61
+ };
62
+ try {
63
+ const child = spawn(config.CCR_BINARY, ['start'], {
64
+ detached: true,
65
+ stdio: 'ignore',
66
+ });
67
+ child.on('error', (err) => {
68
+ const msg = err instanceof Error ? err.message : String(err);
69
+ finish({ ok: false, message: `failed to spawn \`${config.CCR_BINARY} start\`: ${msg}` });
70
+ });
71
+ child.unref();
72
+ // Give spawn a brief moment to surface ENOENT before declaring success.
73
+ setTimeout(() => finish({ ok: true }), 100);
74
+ }
75
+ catch (err) {
76
+ const msg = err instanceof Error ? err.message : String(err);
77
+ finish({ ok: false, message: `failed to spawn \`${config.CCR_BINARY} start\`: ${msg}` });
78
+ }
79
+ });
80
+ }
81
+ /**
82
+ * Preflight check used by the CCR provider before each query.
83
+ *
84
+ * Strategy:
85
+ * - Probe the proxy. If up, return `ok` immediately.
86
+ * - If down and autostart is disabled, return `not_running` with a
87
+ * user-facing message telling them how to start CCR.
88
+ * - If down and autostart is enabled, attempt `ccr start`, poll until the
89
+ * proxy responds, and return `started` on success or `start_failed`
90
+ * with the underlying reason otherwise.
91
+ */
92
+ export async function ensureCcrRunning() {
93
+ if (await isCcrRunning())
94
+ return { status: 'ok' };
95
+ if (!config.CCR_AUTOSTART) {
96
+ return {
97
+ status: 'not_running',
98
+ message: `CCR proxy isn't reachable at ${config.CCR_BASE_URL}. Start it with \`ccr start\`, or set \`CCR_AUTOSTART=true\` to let TeleCoder start it on demand.`,
99
+ };
100
+ }
101
+ console.log('[CCR] Proxy unreachable — attempting autostart');
102
+ const spawnResult = await startCcrProcess();
103
+ if (!spawnResult.ok) {
104
+ return {
105
+ status: 'start_failed',
106
+ message: `CCR autostart failed: ${spawnResult.message}. Start it manually with \`ccr start\`.`,
107
+ };
108
+ }
109
+ const up = await waitUntilUp(Date.now() + START_TIMEOUT_MS);
110
+ if (up) {
111
+ console.log('[CCR] Proxy is up after autostart');
112
+ return { status: 'started' };
113
+ }
114
+ return {
115
+ status: 'start_failed',
116
+ message: `CCR autostart launched but the proxy didn't come up within ${Math.round(START_TIMEOUT_MS / 1000)}s. Check \`ccr status\` and \`~/.claude-code-router/logs/\`.`,
117
+ };
118
+ }
119
+ //# sourceMappingURL=ccr-health.js.map
@@ -0,0 +1,142 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import * as os from 'os';
4
+ import { config } from '../config.js';
5
+ const CCR_LOG_DIR = path.join(os.homedir(), '.claude-code-router', 'logs');
6
+ // Read this many bytes from the tail of the latest CCR log. Plenty to
7
+ // contain at least one full response chunk (largest observed ~5KB) without
8
+ // having to slurp megabytes when the log grows.
9
+ const TAIL_BYTES = 32 * 1024;
10
+ function findLatestLog() {
11
+ if (!fs.existsSync(CCR_LOG_DIR))
12
+ return undefined;
13
+ let best;
14
+ for (const entry of fs.readdirSync(CCR_LOG_DIR)) {
15
+ if (!entry.endsWith('.log'))
16
+ continue;
17
+ const full = path.join(CCR_LOG_DIR, entry);
18
+ try {
19
+ const stat = fs.statSync(full);
20
+ if (!best || stat.mtimeMs > best.mtime) {
21
+ best = { name: full, mtime: stat.mtimeMs };
22
+ }
23
+ }
24
+ catch {
25
+ // ignore unreadable entries
26
+ }
27
+ }
28
+ return best?.name;
29
+ }
30
+ function readTail(filePath, bytes) {
31
+ const stat = fs.statSync(filePath);
32
+ const size = stat.size;
33
+ if (size === 0)
34
+ return '';
35
+ const start = Math.max(0, size - bytes);
36
+ const length = size - start;
37
+ const buf = Buffer.alloc(length);
38
+ const fd = fs.openSync(filePath, 'r');
39
+ try {
40
+ fs.readSync(fd, buf, 0, length, start);
41
+ }
42
+ finally {
43
+ fs.closeSync(fd);
44
+ }
45
+ return buf.toString('utf-8');
46
+ }
47
+ /**
48
+ * Best-effort: scan the most recent CCR log for the actual provider+model
49
+ * that served the last response. Returns undefined if no CCR log exists or
50
+ * no usable entry is found.
51
+ *
52
+ * Caveat: in a multi-user/multi-client setup the most recent log entry may
53
+ * not belong to the caller. For TeleCoder's single-user case it's fine.
54
+ */
55
+ function getLastCcrRouteFromLog() {
56
+ try {
57
+ const latest = findLatestLog();
58
+ if (!latest)
59
+ return undefined;
60
+ const tail = readTail(latest, TAIL_BYTES);
61
+ const lines = tail.split('\n');
62
+ for (let i = lines.length - 1; i >= 0; i--) {
63
+ const line = lines[i];
64
+ if (!line || !line.includes('"provider"'))
65
+ continue;
66
+ try {
67
+ const obj = JSON.parse(line);
68
+ const resp = obj?.response;
69
+ if (resp && typeof resp.provider === 'string' && typeof resp.model === 'string') {
70
+ return { provider: resp.provider, model: resp.model };
71
+ }
72
+ }
73
+ catch {
74
+ // Tail can start mid-line; skip malformed entries.
75
+ }
76
+ }
77
+ return undefined;
78
+ }
79
+ catch (err) {
80
+ console.debug('[CCR] log introspection failed:', err instanceof Error ? err.message : err);
81
+ return undefined;
82
+ }
83
+ }
84
+ const CONFIG_TTL_MS = 60_000;
85
+ let cachedCcrConfig;
86
+ async function fetchCcrConfig() {
87
+ if (cachedCcrConfig && Date.now() - cachedCcrConfig.fetchedAt < CONFIG_TTL_MS) {
88
+ return cachedCcrConfig.router;
89
+ }
90
+ try {
91
+ const url = `${config.CCR_BASE_URL.replace(/\/$/, '')}/api/config`;
92
+ const res = await fetch(url, { signal: AbortSignal.timeout(2000) });
93
+ if (!res.ok) {
94
+ cachedCcrConfig = { router: undefined, fetchedAt: Date.now() };
95
+ return undefined;
96
+ }
97
+ const data = (await res.json());
98
+ cachedCcrConfig = { router: data.Router, fetchedAt: Date.now() };
99
+ return data.Router;
100
+ }
101
+ catch {
102
+ cachedCcrConfig = { router: undefined, fetchedAt: Date.now() };
103
+ return undefined;
104
+ }
105
+ }
106
+ function parseRoute(spec) {
107
+ if (!spec || !spec.includes(','))
108
+ return undefined;
109
+ const idx = spec.indexOf(',');
110
+ const provider = spec.substring(0, idx).trim();
111
+ const model = spec.substring(idx + 1).trim();
112
+ if (!provider || !model)
113
+ return undefined;
114
+ return { provider, model };
115
+ }
116
+ /**
117
+ * Resolve which provider+model CCR routed the last response to.
118
+ *
119
+ * Strategy:
120
+ * 1. Read CCR's log tail (authoritative — what *actually* served).
121
+ * 2. Fall back to CCR's `/api/config` `Router.default` (a prediction —
122
+ * what would serve a typical chat turn, accurate for most cases).
123
+ *
124
+ * Returns undefined when neither source is available (CCR down, logs off,
125
+ * unreachable proxy). Callers should treat undefined as "show CCR tag but
126
+ * keep the alias as the model name".
127
+ */
128
+ export async function getCcrRoute() {
129
+ const fromLog = getLastCcrRouteFromLog();
130
+ if (fromLog)
131
+ return { ...fromLog, source: 'log' };
132
+ const router = await fetchCcrConfig();
133
+ const fromConfig = parseRoute(router?.default);
134
+ if (fromConfig)
135
+ return { ...fromConfig, source: 'config' };
136
+ return undefined;
137
+ }
138
+ /** Convenience: synchronous log-only check (no /api/config fallback). */
139
+ export function getLastCcrRoute() {
140
+ return getLastCcrRouteFromLog();
141
+ }
142
+ //# sourceMappingURL=ccr-introspect.js.map
@@ -0,0 +1,59 @@
1
+ import { getPtyProvider } from './claude-provider.js';
2
+ import { getCcrShimPath } from '../claude/ccr-shim.js';
3
+ import { ensureCcrRunning } from './ccr-health.js';
4
+ // CCR's router config decides the actual backend model per request — the
5
+ // model name claude is started with is largely advisory. Deliberately just the
6
+ // three tiers CCR configs actually route on, rather than the Claude provider's
7
+ // full alias list: aliases like `opusplan` or `fable[1m]` mean nothing to a
8
+ // router whose rules key off opus/sonnet/haiku.
9
+ const CCR_MODELS = [
10
+ { id: 'opus', label: 'opus', description: 'Routed via CCR' },
11
+ { id: 'sonnet', label: 'sonnet', description: 'Routed via CCR' },
12
+ { id: 'haiku', label: 'haiku', description: 'Routed via CCR' },
13
+ ];
14
+ /**
15
+ * The same pty as the Claude provider's, spawning CCR's wrapper script in
16
+ * place of `claude`: it exports the proxy's address and token and execs the
17
+ * real binary, so nothing about the session changes but where its requests
18
+ * go. The pty respawns when a chat switches backend, and the provider switch
19
+ * forks the session first (see provider-switch.ts), since one backend's
20
+ * thinking blocks can't be replayed against another.
21
+ */
22
+ function withShim(options) {
23
+ const shim = getCcrShimPath();
24
+ return { ...(options ?? {}), executableOverride: shim };
25
+ }
26
+ async function preflightOrFailure() {
27
+ const result = await ensureCcrRunning();
28
+ if (result.status === 'ok' || result.status === 'started')
29
+ return undefined;
30
+ return { text: `⚠️ ${result.message}`, toolsUsed: [] };
31
+ }
32
+ export const ccrProvider = {
33
+ name: 'ccr',
34
+ async sendToAgent(sessionKey, message, options) {
35
+ const failure = await preflightOrFailure();
36
+ if (failure)
37
+ return failure;
38
+ return getPtyProvider().sendToAgent(sessionKey, message, withShim(options));
39
+ },
40
+ clearConversation(sessionKey) {
41
+ getPtyProvider().clearConversation(sessionKey);
42
+ },
43
+ setModel(scope, model) {
44
+ getPtyProvider().setModel(scope, model);
45
+ },
46
+ getModel(scope) {
47
+ return getPtyProvider().getModel(scope);
48
+ },
49
+ clearModel(scope) {
50
+ getPtyProvider().clearModel(scope);
51
+ },
52
+ getCachedUsage(sessionKey) {
53
+ return getPtyProvider().getCachedUsage(sessionKey);
54
+ },
55
+ async getAvailableModels() {
56
+ return CCR_MODELS;
57
+ },
58
+ };
59
+ //# sourceMappingURL=ccr-provider.js.map
@@ -0,0 +1,10 @@
1
+ import { PtyProvider } from '../claude/pty-provider.js';
2
+ // Claude Code runs in a pty: the real `claude` CLI, driven in a pseudo-terminal
3
+ // with its dialogs relayed to the chat. The one instance is shared with the
4
+ // CCR provider, which runs the same pty around CCR's wrapper script.
5
+ const ptyProvider = new PtyProvider();
6
+ export function getPtyProvider() {
7
+ return ptyProvider;
8
+ }
9
+ export const claudeProvider = ptyProvider;
10
+ //# sourceMappingURL=claude-provider.js.map
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Applying a model or effort choice on every bot instance at once — the
3
+ * "everywhere" level of /model and /effort.
4
+ *
5
+ * Preferences are per-bot (see user-preferences.ts), and writing to the
6
+ * siblings' files behind their backs would not work: every worker holds its
7
+ * preferences in memory and would overwrite the edit on its next save, and the
8
+ * pty reads `--model` at spawn, so a bot with a live session would go on using
9
+ * the old one regardless.
10
+ *
11
+ * So the change is sent, not written. The requesting worker asks the launcher
12
+ * to relay it; each sibling applies it through the same code path as a local
13
+ * change at that level, restarts the claudes it concerns, and reports back
14
+ * what it did. The requester waits for the round trip so it can tell the user
15
+ * which bots actually took the change.
16
+ *
17
+ * Single-instance mode has no launcher to relay through: every function here
18
+ * degrades to "this bot only" rather than failing.
19
+ */
20
+ import { isMainThread, parentPort } from 'worker_threads';
21
+ import { BOT_ID } from '../config.js';
22
+ import { listSiblingBots } from '../utils/instances.js';
23
+ import { getActiveProviderName, isValidEffortLevel } from './provider-router.js';
24
+ import { applySpawnSetting } from './spawn-settings.js';
25
+ /** Bots other than this one, from instances.json. Empty in single-bot setups. */
26
+ export function siblingBotNames() {
27
+ if (isMainThread)
28
+ return [];
29
+ return listSiblingBots(BOT_ID).map((b) => b.name);
30
+ }
31
+ // ---------------------------------------------------------------------------
32
+ // Applying a change locally (the receiving side)
33
+ // ---------------------------------------------------------------------------
34
+ /**
35
+ * Apply a relayed change to this instance, at the level it was made, and
36
+ * restart the claudes it concerns: idle ones on their next message, mid-turn
37
+ * ones when that turn ends. The count of the latter comes back so the
38
+ * confirmation can say so.
39
+ */
40
+ export function applyPrefsChange(change) {
41
+ const { chatId } = change;
42
+ const active = getActiveProviderName(chatId);
43
+ if (active !== change.provider) {
44
+ return { name: '', status: 'skipped', reason: `on ${active}, not ${change.provider}` };
45
+ }
46
+ if (change.setting === 'effort' && change.value !== null && !isValidEffortLevel(change.value)) {
47
+ return { name: '', status: 'skipped', reason: `unknown effort level "${change.value}"` };
48
+ }
49
+ const outcome = applySpawnSetting(chatId, change.setting, change.value, change.level ?? 'chat');
50
+ return { name: '', status: 'applied', busy: outcome.busy.length };
51
+ }
52
+ /**
53
+ * Listen for changes relayed from sibling bots. Called once at startup; a
54
+ * no-op outside multi-instance mode, where nothing can relay to us.
55
+ */
56
+ export function initPrefsSync() {
57
+ if (isMainThread || !parentPort)
58
+ return;
59
+ const pp = parentPort;
60
+ pp.on('message', (msg) => {
61
+ if (msg?.type !== 'prefs_apply' || !msg.change || !msg.requestId)
62
+ return;
63
+ let outcome;
64
+ try {
65
+ outcome = applyPrefsChange(msg.change);
66
+ }
67
+ catch (err) {
68
+ outcome = {
69
+ name: '',
70
+ status: 'skipped',
71
+ reason: err instanceof Error ? err.message : 'failed to apply',
72
+ };
73
+ }
74
+ const { setting, value } = msg.change;
75
+ console.log(`[PrefsSync] ${outcome.status} relayed ${setting}=${value ?? 'default'} for chat ${msg.change.chatId}${outcome.reason ? ` (${outcome.reason})` : ''}`);
76
+ pp.postMessage({ type: 'prefs_apply_result', requestId: msg.requestId, ...outcome });
77
+ });
78
+ }
79
+ let requestCounter = 0;
80
+ /**
81
+ * How long to wait for the launcher's aggregate reply. Each sibling's work is
82
+ * a couple of synchronous file writes plus a pty kill, so the only thing this
83
+ * really covers is a worker too busy to service its message queue — and one
84
+ * that unresponsive is better reported as unreachable than waited on.
85
+ */
86
+ const BROADCAST_TIMEOUT_MS = 5000;
87
+ /**
88
+ * Ask every other instance to apply `change`. Resolves once they have all
89
+ * answered, or on timeout with whatever came back by then.
90
+ */
91
+ export function broadcastPrefsChange(change) {
92
+ return new Promise((resolve) => {
93
+ if (isMainThread || !parentPort) {
94
+ resolve({ applied: [], skipped: [], unreachable: [], multiInstance: false });
95
+ return;
96
+ }
97
+ const pp = parentPort;
98
+ const requestId = `${BOT_ID}-${++requestCounter}`;
99
+ const handler = (msg) => {
100
+ if (msg?.type !== 'prefs_broadcast_result' || msg.requestId !== requestId)
101
+ return;
102
+ pp.off('message', handler);
103
+ clearTimeout(timer);
104
+ resolve({
105
+ applied: msg.applied ?? [],
106
+ skipped: msg.skipped ?? [],
107
+ unreachable: msg.unreachable ?? [],
108
+ multiInstance: true,
109
+ });
110
+ };
111
+ pp.on('message', handler);
112
+ pp.postMessage({ type: 'prefs_broadcast', requestId, change });
113
+ const timer = setTimeout(() => {
114
+ pp.off('message', handler);
115
+ // A launcher too old to know this message type never answers at all.
116
+ console.warn('[PrefsSync] Launcher did not answer the preference broadcast — is it running current code?');
117
+ resolve({ applied: [], skipped: [], unreachable: [], multiInstance: true, timedOut: true });
118
+ }, BROADCAST_TIMEOUT_MS);
119
+ });
120
+ }
121
+ //# sourceMappingURL=prefs-sync.js.map
@@ -0,0 +1,74 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { z } from 'zod';
4
+ import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
5
+ const favoriteSchema = z.object({
6
+ path: z.string(),
7
+ addedAt: z.string(),
8
+ });
9
+ const favoritesDataSchema = z.object({
10
+ sessions: z.record(z.string(), z.array(favoriteSchema)),
11
+ });
12
+ const FAVORITES_DIR = getStateDir();
13
+ const FAVORITES_FILE = path.join(FAVORITES_DIR, 'project-favorites.json');
14
+ /**
15
+ * One list per chat, shared by every bot: the same person moves their bots across
16
+ * the same projects. Each bot is its own process, so the file is the only copy
17
+ * that counts, and it's read before every use. A bot saving from what it loaded
18
+ * earlier would put back whatever the others had changed since.
19
+ *
20
+ * Saves aren't locked against each other. They only happen on a button tap, so
21
+ * two landing in the same instant isn't worth guarding, and at worst loses a tap.
22
+ */
23
+ class ProjectFavoritesManager {
24
+ data = {};
25
+ constructor() {
26
+ ensureStateDir(FAVORITES_DIR, 'ProjectFavorites');
27
+ }
28
+ refresh() {
29
+ if (!fs.existsSync(FAVORITES_FILE)) {
30
+ this.data = {};
31
+ return;
32
+ }
33
+ // A file that's there but can't be read isn't an empty one: keep what we last
34
+ // read, or the next save would wipe every chat's favorites.
35
+ const loaded = readJsonFile(FAVORITES_FILE, favoritesDataSchema, 'ProjectFavorites');
36
+ if (loaded)
37
+ this.data = loaded.sessions;
38
+ }
39
+ save() {
40
+ writeJsonFile(FAVORITES_FILE, { sessions: this.data }, 'ProjectFavorites');
41
+ }
42
+ list(sessionKey) {
43
+ this.refresh();
44
+ return this.data[sessionKey] ?? [];
45
+ }
46
+ has(sessionKey, projectPath) {
47
+ const normalized = path.resolve(projectPath);
48
+ return this.list(sessionKey).some((f) => f.path === normalized);
49
+ }
50
+ add(sessionKey, projectPath) {
51
+ this.refresh();
52
+ const normalized = path.resolve(projectPath);
53
+ const existing = this.data[sessionKey] ?? [];
54
+ if (existing.some((f) => f.path === normalized))
55
+ return false;
56
+ existing.push({ path: normalized, addedAt: new Date().toISOString() });
57
+ this.data[sessionKey] = existing;
58
+ this.save();
59
+ return true;
60
+ }
61
+ remove(sessionKey, projectPath) {
62
+ this.refresh();
63
+ const normalized = path.resolve(projectPath);
64
+ const existing = this.data[sessionKey] ?? [];
65
+ const filtered = existing.filter((f) => f.path !== normalized);
66
+ if (filtered.length === existing.length)
67
+ return false;
68
+ this.data[sessionKey] = filtered;
69
+ this.save();
70
+ return true;
71
+ }
72
+ }
73
+ export const projectFavorites = new ProjectFavoritesManager();
74
+ //# sourceMappingURL=project-favorites.js.map
@@ -0,0 +1,128 @@
1
+ import { config } from '../config.js';
2
+ import { claudeProvider } from './claude-provider.js';
3
+ import { ccrProvider } from './ccr-provider.js';
4
+ import { isValidEffortLevel } from '../claude/effort-level.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 ---
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, /btw — so this is
43
+ * the one place a hold can be applied without having to be remembered at a
44
+ * dozen call sites. A scheduled prompt comes through here as well, each time
45
+ * it fires.
46
+ *
47
+ * Two checks. A `!command` runs in Claude Code's shell mode without a tool
48
+ * call, so the permission gate's hook never sees it and it is put to the gate
49
+ * here (shell-mode-gate.ts). Then the charter judge reads a guest's message.
50
+ * A command an approver has just allowed skips the judge: they read exactly
51
+ * what will run, and a hold would ask them the same thing again.
52
+ *
53
+ * A blocked message returns as an ordinary response rather than an error, so
54
+ * the streaming UI already in flight renders the explanation in place.
55
+ */
56
+ async function screened(sessionKey, message, options) {
57
+ const ctx = options?.telegramCtx;
58
+ const { screenShellCommand } = await import('../claude/shell-mode-gate.js');
59
+ const shell = await screenShellCommand(ctx, sessionKey, message);
60
+ if (!shell.proceed)
61
+ return { text: shell.message, toolsUsed: [] };
62
+ if (shell.approved)
63
+ return null;
64
+ const { screenPrompt } = await import('../claude/prompt-hold.js');
65
+ const outcome = await screenPrompt(ctx, sessionKey, message);
66
+ if (outcome.proceed)
67
+ return null;
68
+ return { text: outcome.message, toolsUsed: [] };
69
+ }
70
+ export async function sendToAgent(sessionKey, message, options) {
71
+ const blocked = await screened(sessionKey, message, options);
72
+ if (blocked)
73
+ return blocked;
74
+ const providerName = getActiveProviderName(sessionKey);
75
+ return getProvider(sessionKey).sendToAgent(sessionKey, message, { ...options, providerName });
76
+ }
77
+ export function clearConversation(sessionKey) {
78
+ // Clear all providers to avoid stale state
79
+ claudeProvider.clearConversation(sessionKey);
80
+ ccrProvider.clearConversation(sessionKey);
81
+ }
82
+ export function setModel(scope, model) {
83
+ getProvider(scope).setModel(scope, model);
84
+ }
85
+ export function getModel(scope) {
86
+ return getProvider(scope).getModel(scope);
87
+ }
88
+ /**
89
+ * The premium model this session runs on, or undefined when it's on an
90
+ * ordinary one. `best` counts once a turn has shown it resolving to one. CCR
91
+ * is left out: its aliases map onto other backends, so the name says nothing
92
+ * about the cost.
93
+ */
94
+ export function getPremiumModel(sessionKey) {
95
+ if (getActiveProviderName(sessionKey) === 'ccr')
96
+ return undefined;
97
+ const model = getModel(sessionKey);
98
+ if (isPremiumModel(model))
99
+ return model;
100
+ if (model === 'best' && isPremiumModel(getCachedUsage(sessionKey)?.model))
101
+ return model;
102
+ return undefined;
103
+ }
104
+ export function clearModel(scope) {
105
+ getProvider(scope).clearModel(scope);
106
+ }
107
+ export function getCachedUsage(sessionKey) {
108
+ return getProvider(sessionKey).getCachedUsage(sessionKey);
109
+ }
110
+ // Effort is Claude-specific; re-exported from claude/effort-level.ts
111
+ export { isValidEffortLevel };
112
+ export function setEffort(scope, effort) {
113
+ userPreferences.setEffort(scope, effort);
114
+ }
115
+ export function getEffort(scope) {
116
+ return userPreferences.getEffort(scope);
117
+ }
118
+ export function clearEffort(scope) {
119
+ userPreferences.clearEffort(scope);
120
+ }
121
+ export async function getAvailableModels(scope) {
122
+ const providerName = getActiveProviderName(scope);
123
+ if (providerName === 'ccr') {
124
+ return ccrProvider.getAvailableModels(scope);
125
+ }
126
+ return claudeProvider.getAvailableModels(scope);
127
+ }
128
+ //# sourceMappingURL=provider-router.js.map