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,92 @@
1
+ /**
2
+ * The launcher's tally for /botrebuild's "when idle" option: which instances
3
+ * have restarted onto the new build, which are still finishing something and
4
+ * what, and the status message that says so.
5
+ *
6
+ * Bookkeeping only — the launcher does the restarting and the messaging, and
7
+ * src/restart-when-idle.ts is the workers' end. Kept apart from the launcher,
8
+ * like prefs-relay.ts, because the launcher runs its code at import.
9
+ */
10
+ export class IdleRestart {
11
+ origin;
12
+ /** Instances still to restart, with what each last said it was doing. */
13
+ waiting = new Map();
14
+ restarted = [];
15
+ forced = [];
16
+ /** Set by cancel(): the instances it left on the old build. */
17
+ leftOnCancel = null;
18
+ superseded = false;
19
+ constructor(origin, instances) {
20
+ this.origin = origin;
21
+ for (const name of instances)
22
+ this.waiting.set(name, '');
23
+ }
24
+ isWaitingOn(name) {
25
+ return this.waiting.has(name);
26
+ }
27
+ waitingOn() {
28
+ return [...this.waiting.keys()];
29
+ }
30
+ /** Record what an instance says it is still doing. False if not waiting on it. */
31
+ busy(name, detail) {
32
+ if (!this.waiting.has(name))
33
+ return false;
34
+ this.waiting.set(name, detail);
35
+ return true;
36
+ }
37
+ /** An instance is going. False if it had already gone. */
38
+ restarting(name, opts = {}) {
39
+ if (!this.waiting.delete(name))
40
+ return false;
41
+ this.restarted.push(name);
42
+ if (opts.forced)
43
+ this.forced.push(name);
44
+ return true;
45
+ }
46
+ /** Stop waiting. Returns the instances left on the old build. */
47
+ cancel() {
48
+ const left = this.waitingOn();
49
+ this.waiting.clear();
50
+ this.leftOnCancel = left;
51
+ return left;
52
+ }
53
+ /** A newer rebuild took over; this message only needs closing. */
54
+ supersede() {
55
+ this.superseded = true;
56
+ }
57
+ isFinished() {
58
+ return this.leftOnCancel !== null || this.superseded || this.waiting.size === 0;
59
+ }
60
+ render() {
61
+ const note = this.origin.note ? `\n\n${this.origin.note}` : '';
62
+ const done = this.restarted.join(', ');
63
+ if (this.superseded) {
64
+ return { text: `🔄 Superseded by a newer rebuild.${done ? `\n\n✅ Restarted: ${done}` : ''}`, buttons: false };
65
+ }
66
+ if (this.leftOnCancel) {
67
+ const left = this.leftOnCancel;
68
+ return {
69
+ text: '✖️ Restart cancelled.'
70
+ + (done ? `\n\n✅ Restarted: ${done}` : '')
71
+ + (left.length ? `\n⏸ Still on the old build: ${left.join(', ')}` : '')
72
+ + note,
73
+ buttons: false,
74
+ };
75
+ }
76
+ if (this.waiting.size === 0) {
77
+ const count = this.restarted.length;
78
+ const forced = this.forced.length ? ` (${this.forced.join(', ')} without waiting)` : '';
79
+ return {
80
+ text: `✅ ${count === 1 ? 'The bot is' : `All ${count} bots are`} on the new build${forced}.\n\n${done}${note}`,
81
+ buttons: false,
82
+ };
83
+ }
84
+ const lines = ['🔄 Restarting each bot on the new build once it has nothing left to finish.', ''];
85
+ if (done)
86
+ lines.push(`✅ ${done}`);
87
+ for (const [name, detail] of this.waiting)
88
+ lines.push(`⏳ ${name} — ${detail || 'checking'}`);
89
+ return { text: lines.join('\n') + note, buttons: true };
90
+ }
91
+ }
92
+ //# sourceMappingURL=idle-restart.js.map
@@ -0,0 +1,63 @@
1
+ /**
2
+ * How this copy of TeleCoder was installed, decided once for every caller.
3
+ *
4
+ * - `checkout`: a git clone (or any tree with its sources beside it). It builds
5
+ * itself — /botrebuild, the git-based /botversion check.
6
+ * - `package`: an npm install (`npm install -g telecoder`, or npx). There is no
7
+ * source to build and no git to ask; updating goes through npm, and a restart
8
+ * is an exit for the service manager to answer.
9
+ *
10
+ * Nothing here reads config: where the .env lives is utils/config-home.ts.
11
+ */
12
+ import * as fs from 'fs';
13
+ import * as path from 'path';
14
+ import { fileURLToPath } from 'url';
15
+ /**
16
+ * The directory holding package.json. Two levels up from here both as
17
+ * src/utils/install-mode.ts (tsx) and dist/utils/install-mode.js (built).
18
+ */
19
+ export const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
20
+ /**
21
+ * A checkout has its git metadata or its sources next to package.json; a
22
+ * published package ships neither (see `files` in package.json). Either one is
23
+ * enough, so a tarball of a checkout or a clone with .git removed still counts.
24
+ */
25
+ export function detectInstallMode(packageRoot, exists = fs.existsSync) {
26
+ return exists(path.join(packageRoot, '.git')) || exists(path.join(packageRoot, 'src'))
27
+ ? 'checkout'
28
+ : 'package';
29
+ }
30
+ let cachedMode;
31
+ export function getInstallMode() {
32
+ cachedMode ??= detectInstallMode(PACKAGE_ROOT);
33
+ return cachedMode;
34
+ }
35
+ export function isCheckout() {
36
+ return getInstallMode() === 'checkout';
37
+ }
38
+ export function detectPackageRunner(packageRoot = PACKAGE_ROOT) {
39
+ const normalized = packageRoot.split(path.sep).join('/');
40
+ if (normalized.includes('/_npx/'))
41
+ return 'npx';
42
+ // A global install lives in <prefix>/lib/node_modules/telecoder (or
43
+ // <prefix>/node_modules on Windows); a local one in <project>/node_modules.
44
+ if (/\/lib\/node_modules\/telecoder$/.test(normalized) || /\/npm\/node_modules\/telecoder$/i.test(normalized)) {
45
+ return 'global';
46
+ }
47
+ return 'local';
48
+ }
49
+ /** The version in package.json, or null if it can't be read. */
50
+ export function getInstalledVersion(packageRoot = PACKAGE_ROOT) {
51
+ try {
52
+ const pkg = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8'));
53
+ return typeof pkg?.version === 'string' ? pkg.version : null;
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
59
+ /** Test seam: forget the cached mode. */
60
+ export function resetInstallModeCache() {
61
+ cachedMode = undefined;
62
+ }
63
+ //# sourceMappingURL=install-mode.js.map
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Shared parsing helpers for `instances.json`. Used by both the launcher
3
+ * (resolving instances to spawn, and again whenever the file changes) and
4
+ * worker-side enumeration (listing sibling bots for /branch). The two have
5
+ * different output shapes so they each parse independently — only the tiny
6
+ * utility functions are shared between them.
7
+ */
8
+ /** Strip full-line `//` comments so we can JSON.parse a commented config. */
9
+ export function stripJsonComments(text) {
10
+ return text.replace(/^\s*\/\/.*$/gm, '');
11
+ }
12
+ function padNumber(n, total) {
13
+ const digits = String(total).length;
14
+ return String(n).padStart(digits, '0');
15
+ }
16
+ /** Substitute `{n}` / `{N}` placeholders in a name template. */
17
+ export function expandName(template, index, total) {
18
+ return template.replace(/\{n\}/g, String(index)).replace(/\{N\}/g, padNumber(index, total));
19
+ }
20
+ /** An instances.json the launcher can't run as it stands. */
21
+ export class InstancesConfigError extends Error {
22
+ constructor(message) {
23
+ super(message);
24
+ this.name = 'InstancesConfigError';
25
+ }
26
+ }
27
+ /** The bot id a token starts with (`<id>:<secret>`), or '' for a malformed one. */
28
+ export function botIdOf(token) {
29
+ return /^(\d+):\S+$/.exec(token)?.[1] ?? '';
30
+ }
31
+ /**
32
+ * The bots an instances.json describes, in file order.
33
+ *
34
+ * Throws InstancesConfigError when it isn't JSON, lists no usable bot, or names
35
+ * two bots the same or lists one bot twice. The launcher keys each worker by
36
+ * name, so two bots sharing one would take each other's place, and one token
37
+ * polled by two workers gets every poll after the first refused.
38
+ *
39
+ * An entry without a token, or with one that has no bot id, is skipped and
40
+ * reported through `onWarning`; the rest still run.
41
+ */
42
+ export function resolveInstances(text, onWarning = () => { }) {
43
+ let parsed;
44
+ try {
45
+ parsed = JSON.parse(stripJsonComments(text));
46
+ }
47
+ catch (err) {
48
+ throw new InstancesConfigError(`not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
49
+ }
50
+ const defaults = parsed.defaults ?? {};
51
+ const resolved = [];
52
+ const add = (name, token, overrides) => {
53
+ if (!botIdOf(token)) {
54
+ onWarning(`Skipping instance "${name}": its token isn't in the <bot id>:<secret> form`);
55
+ return;
56
+ }
57
+ resolved.push({ name, token, overrides });
58
+ };
59
+ for (const entry of parsed.instances ?? []) {
60
+ const overrides = { ...defaults, ...entry.overrides };
61
+ if (entry.tokens?.length) {
62
+ // List of tokens → auto-template: expand name with {n}/{N}
63
+ const total = entry.tokens.length;
64
+ entry.tokens.forEach((token, i) => add(expandName(entry.name, i + 1, total), token, overrides));
65
+ }
66
+ else if (entry.token) {
67
+ add(entry.name, entry.token, overrides);
68
+ }
69
+ else {
70
+ onWarning(`Skipping instance "${entry.name}": no token or tokens provided`);
71
+ }
72
+ }
73
+ if (resolved.length === 0) {
74
+ throw new InstancesConfigError('no bots to run — add instances with a token or tokens');
75
+ }
76
+ const names = new Set();
77
+ const ids = new Set();
78
+ for (const inst of resolved) {
79
+ const id = botIdOf(inst.token);
80
+ if (names.has(inst.name))
81
+ throw new InstancesConfigError(`two bots are named "${inst.name}"`);
82
+ if (ids.has(id))
83
+ throw new InstancesConfigError(`bot ${id} is listed twice`);
84
+ names.add(inst.name);
85
+ ids.add(id);
86
+ }
87
+ return resolved;
88
+ }
89
+ /**
90
+ * Compare two resolved instance lists by bot id. A bot is the same bot under a
91
+ * new token, which is what a revoked or replaced token gives you, so a token
92
+ * change reads as a change to that bot rather than one bot leaving and another
93
+ * arriving.
94
+ */
95
+ export function diffInstances(current, next) {
96
+ const before = new Map(current.map((inst) => [botIdOf(inst.token), inst]));
97
+ const after = new Map(next.map((inst) => [botIdOf(inst.token), inst]));
98
+ const added = next.filter((inst) => !before.has(botIdOf(inst.token)));
99
+ const removed = current.filter((inst) => !after.has(botIdOf(inst.token)));
100
+ const changed = [];
101
+ for (const [id, to] of after) {
102
+ const from = before.get(id);
103
+ if (from && !sameInstance(from, to))
104
+ changed.push({ from, to });
105
+ }
106
+ return { added, removed, changed };
107
+ }
108
+ function sameInstance(a, b) {
109
+ if (a.name !== b.name || a.token !== b.token)
110
+ return false;
111
+ const ao = a.overrides ?? {};
112
+ const bo = b.overrides ?? {};
113
+ const keys = Object.keys(ao);
114
+ return keys.length === Object.keys(bo).length && keys.every((k) => ao[k] === bo[k]);
115
+ }
116
+ // ---------------------------------------------------------------------------
117
+ // Adding a bot
118
+ // ---------------------------------------------------------------------------
119
+ /**
120
+ * `text` with one more single-token bot in it, for /newbot to write back.
121
+ *
122
+ * Its name is `entry.name`, or that with " 2", " 3"… after it when another bot
123
+ * has the name already: the launcher keys its workers by name. Throws
124
+ * InstancesConfigError when the bot is listed already, or when the file has
125
+ * comments, which a rewrite through JSON would lose.
126
+ */
127
+ export function withInstanceAdded(text, entry) {
128
+ if (stripJsonComments(text) !== text) {
129
+ throw new InstancesConfigError('it has comments, which rewriting it would drop');
130
+ }
131
+ const current = resolveInstances(text);
132
+ if (current.some((inst) => botIdOf(inst.token) === botIdOf(entry.token))) {
133
+ throw new InstancesConfigError(`bot ${botIdOf(entry.token)} is listed already`);
134
+ }
135
+ const names = new Set(current.map((inst) => inst.name));
136
+ let name = entry.name;
137
+ for (let n = 2; names.has(name); n++)
138
+ name = `${entry.name} ${n}`;
139
+ const parsed = JSON.parse(text);
140
+ const added = { name, token: entry.token };
141
+ if (entry.overrides && Object.keys(entry.overrides).length)
142
+ added.overrides = entry.overrides;
143
+ parsed.instances = [...(parsed.instances ?? []), added];
144
+ const next = `${JSON.stringify(parsed, null, 2)}\n`;
145
+ resolveInstances(next);
146
+ return { text: next, name };
147
+ }
148
+ //# sourceMappingURL=instance-config.js.map
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Read instances.json so any running worker can enumerate its sibling bots
3
+ * (name + botId). The launcher exports the resolved config path through
4
+ * TELECODER_INSTANCES_CONFIG so workers don't have to reproduce its
5
+ * --config flag handling.
6
+ */
7
+ import { readFileSync, existsSync, writeFileSync, renameSync } from 'fs';
8
+ import { stripJsonComments, expandName, withInstanceAdded } from './instance-config.js';
9
+ import { legacyEnv } from './legacy-env.js';
10
+ import { configFile } from './config-home.js';
11
+ let cached = null;
12
+ let cachedAtMs = 0;
13
+ const CACHE_TTL_MS = 5_000;
14
+ function configPath() {
15
+ return legacyEnv('INSTANCES_CONFIG') || configFile('instances.json');
16
+ }
17
+ /**
18
+ * Read instances.json and return one entry per configured bot. Short-lived
19
+ * cache so a chat session that lists bots repeatedly doesn't hammer the disk.
20
+ */
21
+ export function listAllBots() {
22
+ const now = Date.now();
23
+ if (cached && now - cachedAtMs < CACHE_TTL_MS)
24
+ return cached;
25
+ const cfgPath = configPath();
26
+ if (!existsSync(cfgPath)) {
27
+ cached = [];
28
+ cachedAtMs = now;
29
+ return cached;
30
+ }
31
+ let parsed;
32
+ try {
33
+ const raw = readFileSync(cfgPath, 'utf-8');
34
+ parsed = JSON.parse(stripJsonComments(raw));
35
+ }
36
+ catch (err) {
37
+ console.warn('[Instances] Failed to read instances.json:', err instanceof Error ? err.message : err);
38
+ cached = [];
39
+ cachedAtMs = now;
40
+ return cached;
41
+ }
42
+ const out = [];
43
+ for (const entry of parsed.instances ?? []) {
44
+ if (entry.tokens?.length) {
45
+ const total = entry.tokens.length;
46
+ entry.tokens.forEach((token, i) => {
47
+ const botId = token.split(':')[0];
48
+ if (!botId)
49
+ return;
50
+ out.push({ name: expandName(entry.name, i + 1, total), botId });
51
+ });
52
+ }
53
+ else if (entry.token) {
54
+ const botId = entry.token.split(':')[0];
55
+ if (!botId)
56
+ continue;
57
+ out.push({ name: entry.name, botId });
58
+ }
59
+ }
60
+ cached = out;
61
+ cachedAtMs = now;
62
+ return cached;
63
+ }
64
+ /**
65
+ * Bots other than this one. `selfBotId` defaults to the current worker's
66
+ * BOT_ID derived from its token.
67
+ */
68
+ export function listSiblingBots(selfBotId) {
69
+ return listAllBots().filter((b) => b.botId !== selfBotId);
70
+ }
71
+ /** Resolve a name to its botId, case-insensitive. Used by /branchaccept etc. */
72
+ export function findBotByName(name) {
73
+ const lower = name.toLowerCase();
74
+ return listAllBots().find((b) => b.name.toLowerCase() === lower);
75
+ }
76
+ export function findBotById(botId) {
77
+ return listAllBots().find((b) => b.botId === botId);
78
+ }
79
+ /**
80
+ * Add a bot to instances.json, which the launcher watches: it starts the bot
81
+ * a few seconds later. Written to a temporary file and renamed into place, so
82
+ * the launcher never reads half a file. Returns the name it got, which has a
83
+ * number after it if another bot had the name already. Throws
84
+ * InstancesConfigError when the file can't take it as it stands.
85
+ */
86
+ export function addInstance(entry) {
87
+ const cfgPath = configPath();
88
+ const { text, name } = withInstanceAdded(readFileSync(cfgPath, 'utf-8'), entry);
89
+ const tmp = `${cfgPath}.${process.pid}.tmp`;
90
+ writeFileSync(tmp, text, { mode: 0o600 });
91
+ renameSync(tmp, cfgPath);
92
+ cached = null;
93
+ return name;
94
+ }
95
+ //# sourceMappingURL=instances.js.map
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Shared persistence for the small JSON state files under `~/.telecoder`.
3
+ *
4
+ * Every persisted store in the bot (settings, preferences, favorites, name
5
+ * cooldowns) used to hand-roll the same four steps: create the state dir,
6
+ * read + zod-validate the file, log and fall back to empty on trouble, and
7
+ * write it back out. The copies drifted — some wrote atomically, some didn't;
8
+ * one checked the directory permissions, the rest assumed them. These helpers
9
+ * are the single implementation, so a fix here reaches every store.
10
+ */
11
+ import * as fs from 'fs';
12
+ import * as os from 'os';
13
+ import * as path from 'path';
14
+ import { atomicWriteFileSync } from './atomic-write.js';
15
+ /** Owner-only, matching the permissions the state dir has always been created with. */
16
+ const DIR_MODE = 0o700;
17
+ const FILE_MODE = 0o600;
18
+ /** Basename of the state directory, under the home directory. */
19
+ export const STATE_DIR_NAME = '.telecoder';
20
+ /** Its name before TeleCoder was renamed from Claudegram. */
21
+ export const LEGACY_STATE_DIR_NAME = '.claudegram';
22
+ /**
23
+ * Shared directory holding all persisted bot state: `~/.telecoder`.
24
+ *
25
+ * Until the launcher has moved the pre-rename `~/.claudegram` across (see
26
+ * utils/state-dir-migration.ts), that one is still where the state is, so it is
27
+ * answered instead. That is the case for workers rebuilt under a launcher that
28
+ * started on an older build: it keeps running its old code, which never moves
29
+ * anything, and its new workers must go on reading the state it still writes.
30
+ * Workers never move the directory themselves, so several of them can't race
31
+ * each other doing it.
32
+ */
33
+ export function getStateDir() {
34
+ const home = os.homedir();
35
+ const current = path.join(home, STATE_DIR_NAME);
36
+ if (fs.existsSync(current))
37
+ return current;
38
+ const legacy = path.join(home, LEGACY_STATE_DIR_NAME);
39
+ return isRealDirectory(legacy) ? legacy : current;
40
+ }
41
+ /** A directory that is not a symlink — a moved state dir leaves a link behind. */
42
+ export function isRealDirectory(p) {
43
+ try {
44
+ const stats = fs.lstatSync(p);
45
+ return stats.isDirectory() && !stats.isSymbolicLink();
46
+ }
47
+ catch {
48
+ return false;
49
+ }
50
+ }
51
+ /**
52
+ * Create the state directory if it is missing, and tighten its permissions if
53
+ * an existing one is more permissive than owner-only.
54
+ *
55
+ * A failure to *create* the directory propagates — nothing can be persisted
56
+ * without it, so surfacing that at startup beats a silent read-only bot. A
57
+ * failure to *inspect* an existing one is only logged.
58
+ */
59
+ export function ensureStateDir(dir, label) {
60
+ if (!fs.existsSync(dir)) {
61
+ fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE });
62
+ return;
63
+ }
64
+ try {
65
+ const stats = fs.statSync(dir);
66
+ if (!stats.isDirectory()) {
67
+ throw new Error(`${dir} exists but is not a directory`);
68
+ }
69
+ if (process.platform !== 'win32' && (stats.mode & 0o777) !== DIR_MODE) {
70
+ fs.chmodSync(dir, DIR_MODE);
71
+ }
72
+ }
73
+ catch (error) {
74
+ if (error.code !== 'ENOENT') {
75
+ console.warn(`[${label}] State directory check failed:`, error);
76
+ }
77
+ }
78
+ }
79
+ /**
80
+ * Read and validate a JSON state file.
81
+ *
82
+ * Returns undefined when the file is missing, unreadable, malformed, or fails
83
+ * validation — in every one of those cases the caller starts from empty state
84
+ * rather than crashing, which is what all the hand-rolled copies did too.
85
+ */
86
+ export function readJsonFile(filePath, schema, label) {
87
+ if (!fs.existsSync(filePath))
88
+ return undefined;
89
+ try {
90
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
91
+ const result = schema.safeParse(parsed);
92
+ if (!result.success) {
93
+ console.warn(`[${label}] Invalid ${path.basename(filePath)} format, starting fresh:`, result.error.message);
94
+ return undefined;
95
+ }
96
+ return result.data;
97
+ }
98
+ catch (error) {
99
+ console.error(`[${label}] Failed to load ${path.basename(filePath)}:`, error);
100
+ return undefined;
101
+ }
102
+ }
103
+ /**
104
+ * Write a JSON state file atomically, owner-readable only.
105
+ *
106
+ * Failures are logged and swallowed by default: losing a settings toggle
107
+ * should never take down a turn. Pass `rethrow` when the caller reports
108
+ * success to the user right after writing — there, a silent failure would
109
+ * claim the write happened when it didn't.
110
+ */
111
+ export function writeJsonFile(filePath, data, label, opts) {
112
+ try {
113
+ atomicWriteFileSync(filePath, JSON.stringify(data, null, 2), { mode: FILE_MODE });
114
+ }
115
+ catch (error) {
116
+ if (opts?.rethrow)
117
+ throw error;
118
+ console.error(`[${label}] Failed to save ${path.basename(filePath)}:`, error);
119
+ }
120
+ }
121
+ /**
122
+ * Read a bot's own state file, for state all the bots used to share in one file.
123
+ *
124
+ * A bot's first start finds no file of its own, so it inherits whatever the
125
+ * shared file holds and nothing resets. It claims its own file straight away, so
126
+ * the shared one is no longer needed. That one is read, never removed: sibling
127
+ * bots still on their first start need to seed from it too, and a downgrade
128
+ * should still find it.
129
+ */
130
+ export function readSeededJsonFile(filePath, sharedPath, schema, label) {
131
+ if (fs.existsSync(filePath))
132
+ return readJsonFile(filePath, schema, label);
133
+ const seed = readJsonFile(sharedPath, schema, label);
134
+ if (seed) {
135
+ console.log(`[${label}] Seeded ${path.basename(filePath)} from ${path.basename(sharedPath)}`);
136
+ writeJsonFile(filePath, seed, label);
137
+ }
138
+ return seed;
139
+ }
140
+ //# sourceMappingURL=json-store.js.map
@@ -0,0 +1,62 @@
1
+ /**
2
+ * A per-session settings store backed by a JSON file in the state directory.
3
+ *
4
+ * The prompt-suggestion settings (and the TTS, Terminal UI and bot-name ones
5
+ * before them) are all the same thing: a `sessionKey → settings` map, persisted as
6
+ * `{ settings: { [key]: entry } }`, where any field absent from disk falls back
7
+ * to an env-level default. This factory is that shape, once.
8
+ *
9
+ * Each bot has its own file. Each bot is its own process with its own copy of
10
+ * the entries, so when they shared one, every save put back whatever the others
11
+ * had changed since that copy was loaded. Merging by key wouldn't have helped:
12
+ * a private chat's key is the user's id, the same for every bot they talk to.
13
+ */
14
+ import * as path from 'path';
15
+ import { z } from 'zod';
16
+ import { BOT_ID } from '../config.js';
17
+ import { ensureStateDir, getStateDir, readSeededJsonFile, writeJsonFile } from './json-store.js';
18
+ export function createKeyedSettings(opts) {
19
+ const dir = opts.dir ?? getStateDir();
20
+ const filePath = path.join(dir, `${path.basename(opts.file, '.json')}-${opts.botId ?? BOT_ID}.json`);
21
+ const sharedPath = path.join(dir, opts.file);
22
+ const fileSchema = z.object({ settings: z.record(z.string(), opts.entrySchema) });
23
+ const entries = new Map();
24
+ ensureStateDir(dir, opts.label);
25
+ // A seed is copied as it was on disk rather than normalized: a field nobody
26
+ // chose has to keep following its env-level default, see get().
27
+ const loaded = readSeededJsonFile(filePath, sharedPath, fileSchema, opts.label);
28
+ if (loaded) {
29
+ for (const [key, stored] of Object.entries(loaded.settings)) {
30
+ entries.set(key, opts.normalize(stored));
31
+ }
32
+ }
33
+ function assertKey(key) {
34
+ if (!key || typeof key !== 'string') {
35
+ throw new Error(`[${opts.label}] Invalid settings key: ${key}`);
36
+ }
37
+ }
38
+ function save() {
39
+ ensureStateDir(dir, opts.label);
40
+ writeJsonFile(filePath, { settings: Object.fromEntries(entries) }, opts.label);
41
+ }
42
+ function get(key) {
43
+ assertKey(key);
44
+ const existing = entries.get(key);
45
+ if (existing)
46
+ return existing;
47
+ // Deliberately not stored: a session that has never chosen keeps tracking
48
+ // its env-level default, so changing the default in config still reaches
49
+ // every user who hasn't overridden it. Persisting here would freeze the
50
+ // default at whatever it happened to be the first time something read it.
51
+ return opts.normalize();
52
+ }
53
+ function update(key, patch) {
54
+ assertKey(key);
55
+ const next = { ...get(key), ...patch };
56
+ entries.set(key, next);
57
+ save();
58
+ return next;
59
+ }
60
+ return { get, update };
61
+ }
62
+ //# sourceMappingURL=keyed-settings.js.map
@@ -0,0 +1,35 @@
1
+ /**
2
+ * TeleCoder was renamed from Claudegram in July 2026, and its environment
3
+ * variables moved from `CLAUDEGRAM_*` to `TELECODER_*`. Anyone upgrading across
4
+ * that rename still has the old names in their `.env` or exported shell env, so
5
+ * every *user-settable* var reads the new name first and falls back to the old
6
+ * one — warning once per var so the deprecation is visible without spamming a
7
+ * line on every read.
8
+ *
9
+ * Internal parent→child vars are deliberately NOT routed through here. The ones
10
+ * `launcher.ts` sets for its workers and `pty-provider.ts` sets for the MCP
11
+ * subprocess are written and read by the same build, so they rename in lockstep
12
+ * and have no older peer to stay compatible with.
13
+ */
14
+ const warned = new Set();
15
+ /**
16
+ * Read `TELECODER_<suffix>`, falling back to the pre-rename `CLAUDEGRAM_<suffix>`.
17
+ * Pass the suffix only — e.g. `legacyEnv('PERMISSION_PROMPTS')`.
18
+ */
19
+ export function legacyEnv(suffix) {
20
+ const current = process.env[`TELECODER_${suffix}`];
21
+ if (current !== undefined)
22
+ return current;
23
+ const legacy = process.env[`CLAUDEGRAM_${suffix}`];
24
+ if (legacy !== undefined && !warned.has(suffix)) {
25
+ warned.add(suffix);
26
+ console.warn(`[env] CLAUDEGRAM_${suffix} is deprecated — rename it to TELECODER_${suffix}. ` +
27
+ 'The old name still works, but support for it will be dropped.');
28
+ }
29
+ return legacy;
30
+ }
31
+ /** Reset the warn-once state. Test seam — production never needs this. */
32
+ export function resetLegacyEnvWarnings() {
33
+ warned.clear();
34
+ }
35
+ //# sourceMappingURL=legacy-env.js.map