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
package/dist/config.js ADDED
@@ -0,0 +1,525 @@
1
+ import { config as loadEnv } from 'dotenv';
2
+ import { z } from 'zod';
3
+ import * as path from 'path';
4
+ import { legacyEnv } from './utils/legacy-env.js';
5
+ import { parseIdList } from './utils/id-list.js';
6
+ import { configFile } from './utils/config-home.js';
7
+ import { isWellFormedBotToken, MALFORMED_TOKEN_MESSAGE } from './utils/bot-token.js';
8
+ import { envFileStatus, formatConfigReport, problemsFromIssues, } from './config-report.js';
9
+ import { exitForConfigError } from './utils/exit-codes.js';
10
+ // Next to package.json in a checkout, ~/.telecoder/.env for an npm install —
11
+ // see utils/config-home.ts.
12
+ const defaultEnvPath = configFile('.env');
13
+ // Read from the real process env, not the .env file — this is the var that
14
+ // says *which* .env to load, so it can't come from inside one.
15
+ const envPath = legacyEnv('ENV_PATH') || defaultEnvPath;
16
+ const loadedEnv = loadEnv({ path: envPath });
17
+ /** The .env file this process read, for messages that tell the user where to add a setting. */
18
+ export const envFilePath = envPath;
19
+ /**
20
+ * Which values in the .env file are being ignored because the process was
21
+ * started with them already in its environment.
22
+ *
23
+ * dotenv never overwrites what is already there, which is the right default —
24
+ * it is how a launcher hands each worker its own instance config. The trap is
25
+ * that a restart inherits the environment it was started from, so a value
26
+ * exported into the shell that first launched the bot outranks the file
27
+ * forever, and no amount of editing .env or restarting from chat can dislodge
28
+ * it. Naming the shadowed keys at startup turns a silent mystery into a line
29
+ * in the log.
30
+ */
31
+ export function findShadowedEnvKeys(fromFile, env = process.env) {
32
+ if (!fromFile)
33
+ return [];
34
+ // A launcher worker is handed its config through the environment on purpose.
35
+ if (env.TELECODER_INSTANCE_NAME)
36
+ return [];
37
+ return Object.keys(fromFile).filter((key) => env[key] !== fromFile[key]);
38
+ }
39
+ const shadowed = findShadowedEnvKeys(loadedEnv.parsed);
40
+ if (shadowed.length > 0) {
41
+ // Names only — one of these is the bot token.
42
+ console.warn(`[env] Ignoring ${shadowed.length} value(s) from ${envPath}: this process was started with ` +
43
+ `them already set in its environment, and that wins over the file — ${shadowed.join(', ')}. ` +
44
+ 'Restart from a shell that does not export them if you meant the file to apply.');
45
+ }
46
+ const toBool = (val) => val.toLowerCase() === 'true';
47
+ /**
48
+ * A comma-separated id list, validated by parseIdList: non-numeric entries
49
+ * (`@alice`) and the .env.example placeholder fail startup with a message
50
+ * saying what to put there instead.
51
+ */
52
+ const idList = (name, kind = 'user') => (val, ctx) => {
53
+ const result = parseIdList(name, val, kind);
54
+ if (!result.ok) {
55
+ ctx.addIssue({ code: 'custom', message: result.error });
56
+ return z.NEVER;
57
+ }
58
+ return result.ids;
59
+ };
60
+ const envSchema = z.object({
61
+ // Checked by shape here, before anything uses it; whether Telegram accepts
62
+ // it is checked at startup (startup/verify-token.ts).
63
+ TELEGRAM_BOT_TOKEN: z
64
+ .string()
65
+ .min(1, 'Telegram bot token is required')
66
+ .refine(isWellFormedBotToken, MALFORMED_TOKEN_MESSAGE),
67
+ ALLOWED_USER_IDS: z
68
+ .string()
69
+ .min(1, 'At least one allowed user ID is required (your own numeric Telegram id — get it from @userinfobot)')
70
+ .transform(idList('ALLOWED_USER_IDS'))
71
+ .refine((ids) => ids.length > 0, 'ALLOWED_USER_IDS has no ids in it — put your own numeric Telegram id there (get it from @userinfobot)'),
72
+ ALLOWED_GROUP_IDS: z
73
+ .string()
74
+ .default('')
75
+ .transform(idList('ALLOWED_GROUP_IDS', 'group')),
76
+ // The subset of ALLOWED_USER_IDS that may approve permission prompts and run
77
+ // bot-lifecycle / transport commands. Empty means every allowed user is an
78
+ // admin, which is the behaviour every install had before this existed — so a
79
+ // solo bot is unaffected and only a shared one needs to set it.
80
+ // See src/utils/admins.ts for the roster logic.
81
+ ADMIN_USER_IDS: z
82
+ .string()
83
+ .default('')
84
+ .transform(idList('ADMIN_USER_IDS')),
85
+ // The subset of ALLOWED_USER_IDS that may answer an approval prompt without
86
+ // owning the bot. An approver is still a guest everywhere else — the charter
87
+ // judge still reads their messages, the gate still stops their tool calls,
88
+ // and the lifecycle commands are still closed to them. All they gain is the
89
+ // right to answer *someone else's* prompt, which is what stops one owner
90
+ // being the bottleneck for a bot several people use.
91
+ //
92
+ // They cannot answer their own: an approval the requester taps themselves
93
+ // confirms nothing, which is the whole reason the roster is narrowed at all.
94
+ // Ids that ADMIN_USER_IDS already carries are ignored here — admins can
95
+ // approve anyway, and listing someone twice should not mean something new.
96
+ // Only meaningful alongside ADMIN_USER_IDS; with that unset every allowed
97
+ // user is already an admin and there is nothing left for this to widen.
98
+ // See src/utils/admins.ts for the roster logic.
99
+ APPROVER_USER_IDS: z
100
+ .string()
101
+ .default('')
102
+ .transform(idList('APPROVER_USER_IDS')),
103
+ // Confine non-admins to the groups in ALLOWED_GROUP_IDS. Without this a
104
+ // shared bot is still reachable in a private chat, where the owner cannot
105
+ // see what is being asked of it — which defeats the point of sharing it in a
106
+ // group. Admins are unaffected and can always DM the bot.
107
+ RESTRICT_TO_GROUPS: z.string().default('false').transform(toBool),
108
+ // Scope guard: prompt when a tool call names a path outside the shared
109
+ // projects, or a credential path anywhere. 'auto' follows the permission
110
+ // gate, which is what a shared bot wants; 'on'/'off' force it.
111
+ SCOPE_GUARD: z.enum(['auto', 'on', 'off']).default('auto'),
112
+ // Extra directories the scope guard treats as in-bounds, on top of
113
+ // WORKSPACE_DIR and the temp dir. Comma-separated absolute paths.
114
+ SCOPE_ALLOWED_PATHS: z
115
+ .string()
116
+ .default('')
117
+ .transform((val) => (val ? val.split(',').map((p) => p.trim()).filter(Boolean) : [])),
118
+ // Charter judge: a Haiku side-call that reads each guest's message against a
119
+ // plain-language charter and holds anything out of bounds for an admin.
120
+ // 'auto' turns it on when the bot has guests.
121
+ CHARTER_JUDGE: z.enum(['auto', 'on', 'off']).default('auto'),
122
+ // Path to the charter the judge reads. Defaults to CHARTER.md in the
123
+ // workspace root when that file exists, and to a generated one otherwise.
124
+ CHARTER_FILE: z.string().default(''),
125
+ // How long a permission prompt waits for an admin before auto-denying.
126
+ // Ten minutes is fine when the approver is the person who typed the request;
127
+ // when it is someone else's request waiting on you, it usually is not.
128
+ PERMISSION_PROMPT_TIMEOUT_MINUTES: z
129
+ .string()
130
+ .default('10')
131
+ .transform((val) => parseInt(val, 10)),
132
+ // In a group, only act on messages that address the bot — an @mention, a
133
+ // reply to something the bot sent, or a slash command. Off means every
134
+ // message in an allow-listed group is a prompt, which drowns out any human
135
+ // conversation happening in the same group.
136
+ GROUP_REQUIRE_MENTION: z.string().default('true').transform(toBool),
137
+ // Treat any reply to one of the bot's messages as addressing it, the way it
138
+ // worked before mentions were required. Off by default: replying is also how
139
+ // you quote a message, so a reply is a poor signal of intent. Answers to the
140
+ // bot's own ForceReply prompts are always addressed regardless.
141
+ GROUP_REPLY_IS_MENTION: z.string().default('false').transform(toBool),
142
+ // What membership of an allow-listed group grants. 'spectator' makes it
143
+ // presence only — people talk in the group and watch the bot work, but only
144
+ // someone an admin has /allow'd can send it prompts. 'contributor' makes
145
+ // Telegram membership the whole gate, so everyone in the room can drive the
146
+ // agent; that is the right answer for a group of peers and the wrong one for
147
+ // a group with an audience in it.
148
+ //
149
+ // Defaults to spectator, which is the safe direction and matches what the
150
+ // roster gate already enforced before this setting existed: someone who is
151
+ // in the group but not admitted could never prompt the bot.
152
+ GROUP_MEMBERS_DEFAULT: z.enum(['contributor', 'spectator']).default('spectator'),
153
+ ANTHROPIC_API_KEY: z.string().optional(), // Optional - uses Claude Max subscription if not set
154
+ WORKSPACE_DIR: z.string().default(process.env.HOME || '.'),
155
+ // The project this bot is for, set by /newbot for the bots it creates. A
156
+ // conversation with nowhere else to be starts here, and a thread in it is
157
+ // named without the project in front, since the bot's name already says it.
158
+ // Absolute, or relative to WORKSPACE_DIR.
159
+ HOME_PROJECT: z.string().optional(),
160
+ // The `claude` the Haiku side calls (topic names, the charter judge) run
161
+ // through: the copy bundled with the agent SDK, or CLAUDE_EXECUTABLE_PATH
162
+ // when the flag is false. The ptys spawn CLAUDE_BIN, else the one on PATH.
163
+ CLAUDE_EXECUTABLE_PATH: z.string().default('claude'),
164
+ CLAUDE_USE_BUNDLED_EXECUTABLE: z
165
+ .string()
166
+ .default('true')
167
+ .transform((val) => val.toLowerCase() === 'true'),
168
+ // Whether the pty gets the Claude Code setup of the account the bot runs as:
169
+ // ~/.claude (CLAUDE.md, skills, commands, agents, settings.json), its MCP
170
+ // servers, its plugins' servers and its claude.ai connectors. 'auto' brings
171
+ // it along unless the bot has guests, who would otherwise work with the
172
+ // owner's own instructions and connectors; 'on'/'off' force it. See
173
+ // loadsUserSetup in src/claude/pty-spawn-config.ts.
174
+ CLAUDE_USER_SETUP: z.enum(['auto', 'on', 'off']).default('auto'),
175
+ // Path to a JSON file of extra MCP servers ({"mcpServers": {...}}) to hand the
176
+ // pty alongside the bot's own. For a server only the bot should have, and
177
+ // the one way to add any while the user setup stays out (CLAUDE_USER_SETUP):
178
+ // the spawn then passes --strict-mcp-config, and MCP servers live in
179
+ // ~/.claude.json rather than in settings.json.
180
+ EXTRA_MCP_CONFIG: z.string().optional(),
181
+ // Marketplace plugins to enable inside the agent, as the `plugin@marketplace`
182
+ // ids `claude plugin list` prints, comma-separated. A plugin enabled in the
183
+ // terminal sits in ~/.claude/settings.json and comes with the user setup;
184
+ // this names the ones to bring while that stays out (CLAUDE_USER_SETUP), or
185
+ // to enable for the bot alone. See src/claude/enabled-plugins.ts.
186
+ CLAUDE_PLUGINS: z
187
+ .string()
188
+ .default('')
189
+ .transform((val) => val ? val.split(',').map((name) => name.trim()).filter(Boolean) : []),
190
+ BOT_NAME: z.string().default('TeleCoder'),
191
+ // Fire a parallel Haiku side-call on every user message to derive a topic
192
+ // label for the status line and the thread name, independent of the main
193
+ // agent's tool calls. Deferral-immune because it bypasses settingSources and
194
+ // tools entirely. Skipped when nothing in the chat shows the topic.
195
+ AUTO_TOPIC_HAIKU: z
196
+ .string()
197
+ .default('true')
198
+ .transform((val) => val.toLowerCase() === 'true'),
199
+ // Default for the per-chat "predicted next prompt" feature: when enabled,
200
+ // TeleCoder sets CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=1 on the PTY spawn
201
+ // and scrapes the ghost-text suggestion that claude renders into its input
202
+ // box after each turn, surfacing it as an inline button under the response.
203
+ // Per-chat override via /suggestions; takes effect on next session spawn.
204
+ // Off by default — feature relies on Anthropic's growthbook flag being on
205
+ // for the account, and the suggestion is a speculative API call.
206
+ PROMPT_SUGGESTIONS_DEFAULT: z
207
+ .string()
208
+ .default('false')
209
+ .transform((val) => val.toLowerCase() === 'true'),
210
+ // The status line that closes every reply (project, effort, model, context),
211
+ // for chats that haven't used /footer. On: in Telegram it's the only
212
+ // place those show, and a new user doesn't know the command. The topic
213
+ // line comes with it; the last prompts and the resume command stay opt-in.
214
+ STATUS_LINE_DEFAULT: z
215
+ .string()
216
+ .default('true')
217
+ .transform((val) => val.toLowerCase() === 'true'),
218
+ MAX_MESSAGE_LENGTH: z
219
+ .string()
220
+ .default('4000')
221
+ .transform((val) => parseInt(val, 10)),
222
+ IMAGE_MAX_FILE_SIZE_MB: z
223
+ .string()
224
+ .default('20')
225
+ .transform((val) => parseInt(val, 10)),
226
+ // 19, not 25: Telegram's getFile refuses anything over 20MB, so a 25MB
227
+ // ceiling let files through this guard only to fail at download with an
228
+ // opaque 400. Matches VOICE_MAX_FILE_SIZE_MB, which already sat under the cap.
229
+ DOCUMENT_MAX_FILE_SIZE_MB: z
230
+ .string()
231
+ .default('19')
232
+ .transform((val) => parseInt(val, 10)),
233
+ AUTO_RESTORE_SESSION: z.string().default('false').transform(toBool),
234
+ // Voice transcription (Groq Whisper)
235
+ GROQ_API_KEY: z.string().optional(),
236
+ TRANSCRIBE_ENABLED: z.string().default('true').transform(toBool),
237
+ VOICE_SHOW_TRANSCRIPT: z
238
+ .string()
239
+ .default('true')
240
+ .transform((val) => val.toLowerCase() === 'true'),
241
+ VOICE_MAX_FILE_SIZE_MB: z
242
+ .string()
243
+ .default('19')
244
+ .transform((val) => parseInt(val, 10)),
245
+ VOICE_LANGUAGE: z.string().default('en'),
246
+ VOICE_TIMEOUT_MS: z
247
+ .string()
248
+ .default('60000')
249
+ .transform((val) => parseInt(val, 10)),
250
+ // Verbosity tier (quiet | normal | verbose | debug). Drives the defaults
251
+ // for several rendering flags below; per-chat /verbosity overrides this,
252
+ // and explicit env vars (CONTEXT_SHOW_USAGE etc.) override the tier.
253
+ VERBOSITY_DEFAULT: z.enum(['quiet', 'normal', 'verbose', 'debug']).default('normal'),
254
+ // Context visibility — when set, overrides the verbosity tier. Leave unset
255
+ // to let the tier decide (recommended).
256
+ CONTEXT_SHOW_USAGE: z
257
+ .string()
258
+ .default('false')
259
+ .transform((val) => val.toLowerCase() === 'true'),
260
+ CONTEXT_NOTIFY_COMPACTION: z
261
+ .string()
262
+ .default('true')
263
+ .transform((val) => val.toLowerCase() === 'true'),
264
+ // Show a tool's full input — the whole Bash command, the full path or URL —
265
+ // in the live status message instead of a shortened one. When set, overrides
266
+ // the verbosity tier, which turns it on from verbose up. Was TERMINAL_UI_VERBOSE.
267
+ FULL_TOOL_INPUTS: z
268
+ .string()
269
+ .default('false')
270
+ .transform((val) => val.toLowerCase() === 'true'),
271
+ // Message batching: combine the parts of a long paste Telegram split up into
272
+ // a single prompt. How long to wait for the next part, in ms. 0 = disabled.
273
+ MESSAGE_BATCH_TIMEOUT_MS: z
274
+ .string()
275
+ .default('1500')
276
+ .transform((val) => parseInt(val, 10)),
277
+ // Absolute wall-clock cap for a single PTY turn (ms). The turn is killed
278
+ // with a "turn exceeded" error if it runs longer. Default 2 h — long
279
+ // enough for genuinely intensive multi-step work; raise it if you regularly
280
+ // hit the cap on legitimately long turns.
281
+ CLAUDE_PTY_HARD_TIMEOUT_MS: z
282
+ .string()
283
+ .default('7200000')
284
+ .transform((val) => parseInt(val, 10)),
285
+ // How long an idle PTY session's `claude` process is kept (ms). Each one
286
+ // holds a few hundred MB between turns; past this it is ended, and the next
287
+ // message resumes the conversation from its transcript in a new one. A
288
+ // session with a turn, a background task or a background shell running is
289
+ // never ended. Also what cleans up after a thread deleted by hand, which
290
+ // Telegram doesn't tell the bot about. 0 = keep them until a restart.
291
+ CLAUDE_PTY_IDLE_TIMEOUT_MS: z
292
+ .string()
293
+ .default('3600000')
294
+ .transform((val) => parseInt(val, 10)),
295
+ // `telecoder watch`: serve each chat's live Claude Code screen, read-only,
296
+ // on a Unix socket in ~/.telecoder/watch that only this user can open.
297
+ // false turns it off.
298
+ PTY_WATCH: z
299
+ .string()
300
+ .default('true')
301
+ .transform((val) => val.toLowerCase() === 'true'),
302
+ // Start a chat's `claude` as soon as its conversation is chosen — /dir,
303
+ // /clear, /resume — instead of on the first message after, so that message
304
+ // doesn't wait for Claude Code to start. Skipped without a word when memory
305
+ // is under the guard's floor; one nobody ends up using is ended by the idle
306
+ // timeout like any other. false starts it on the first message.
307
+ PREWARM_CLAUDE: z
308
+ .string()
309
+ .default('true')
310
+ .transform((val) => val.toLowerCase() === 'true'),
311
+ // Memory guard. Before a typed message starts a new `claude` for a chat
312
+ // — a new chat or thread, or one whose claude was ended — the machine's
313
+ // available memory (MemAvailable) is checked, less a few hundred MB for
314
+ // every claude still starting up (one just let through hasn't taken its
315
+ // memory yet). Under this many MB, claudes idle longer than
316
+ // MEMORY_GUARD_REAP_IDLE_MS are ended first; if that still leaves too
317
+ // little, the chat is asked whether to start anyway, end the longest-idle
318
+ // claude first, or drop the message. "auto" (the default) is a quarter of
319
+ // the machine's RAM, at least 1024 MB: with 1 GB left on an 8 GB box the
320
+ // machine is usually deep in swap already. 0 turns the guard off.
321
+ MEMORY_GUARD_MIN_AVAILABLE_MB: z
322
+ .string()
323
+ .default('auto')
324
+ .transform((val) => (val.trim().toLowerCase() === 'auto' ? 'auto' : parseInt(val, 10))),
325
+ // Swap in use above this many MB also counts as tight, so the guard asks
326
+ // even while MemAvailable looks fine. Off by default (0): pages stay in swap
327
+ // long after the pressure that put them there has passed, so on a machine
328
+ // that swaps at all this nags on every new chat.
329
+ MEMORY_GUARD_MAX_SWAP_USED_MB: z
330
+ .string()
331
+ .default('0')
332
+ .transform((val) => parseInt(val, 10)),
333
+ // The shorter idle window the guard reaps with when memory is tight, in ms.
334
+ // A chat whose claude was reaped this way resumes from its transcript on its
335
+ // next message, a few seconds slower. Default 300000 = 5 min.
336
+ MEMORY_GUARD_REAP_IDLE_MS: z
337
+ .string()
338
+ .default('300000')
339
+ .transform((val) => parseInt(val, 10)),
340
+ // How long a question from the agent — telecoder_ask_user buttons, a
341
+ // telecoder_poll_user poll, a Claude Code dialog relayed to the chat —
342
+ // waits for an answer before the turn carries on without one. The turn is
343
+ // paused for the whole wait, so a long timeout is a long stall whenever a
344
+ // question goes unanswered; keep it well under CLAUDE_PTY_HARD_TIMEOUT_MS,
345
+ // which ends the turn regardless. Permission prompts have their own,
346
+ // PERMISSION_PROMPT_TIMEOUT_MINUTES.
347
+ QUESTION_TIMEOUT_MINUTES: z
348
+ .string()
349
+ .default('10')
350
+ .transform((val) => parseInt(val, 10)),
351
+ // HTTP or HTTPS proxy for Telegram API requests and for downloading files
352
+ // sent to the bot (e.g. http://127.0.0.1:8080). Not SOCKS: the client is an
353
+ // HttpsProxyAgent (src/telegram/client-options.ts).
354
+ TELEGRAM_PROXY_URL: z.string().optional(),
355
+ // Completion notification (send a new message after long streaming tasks)
356
+ NOTIFICATION_ENABLED: z.string().default('true').transform(toBool),
357
+ NOTIFICATION_THRESHOLD_SECONDS: z
358
+ .string()
359
+ .default('60')
360
+ .transform((val) => parseInt(val, 10)),
361
+ // Claude Code Router (CCR) provider — redirects the spawned `claude` binary
362
+ // through a local CCR proxy so it can be backed by non-Anthropic models.
363
+ // Useful as a fallback when the Max usage limit is reached.
364
+ CCR_ENABLED: z
365
+ .string()
366
+ .default('false')
367
+ .transform((val) => val.toLowerCase() === 'true'),
368
+ CCR_BASE_URL: z.string().default('http://localhost:3456'),
369
+ CCR_AUTH_TOKEN: z.string().default(''),
370
+ // When the CCR proxy isn't reachable, automatically spawn `ccr start` in
371
+ // the background instead of letting the spawned `claude` CLI hang on a
372
+ // ConnectionRefused. Off by default — opt in if you want hands-off recovery.
373
+ CCR_AUTOSTART: z
374
+ .string()
375
+ .default('false')
376
+ .transform((val) => val.toLowerCase() === 'true'),
377
+ // Path or name of the `ccr` binary used for autostart. Defaults to `ccr`
378
+ // (resolved via PATH). Override if `ccr` lives somewhere systemd can't see.
379
+ CCR_BINARY: z.string().default('ccr'),
380
+ });
381
+ /**
382
+ * Print the configuration report and stop. Everything that keeps the bot from
383
+ * starting goes through here, so a first run sees one message in one shape —
384
+ * which file was read, what is wrong, and how to fix it — whichever check
385
+ * caught it. See config-report.ts.
386
+ */
387
+ function failConfig(problems) {
388
+ console.error(formatConfigReport(problems, { path: envPath, status: envFileStatus(loadedEnv) }, { instanceName: process.env.TELECODER_INSTANCE_NAME }));
389
+ exitForConfigError();
390
+ }
391
+ /**
392
+ * Settings that took a new name, old → new. The old name keeps working, read
393
+ * only when the new one isn't set, and index.ts says once at startup to rename
394
+ * it in the .env.
395
+ */
396
+ export const RENAMED_SETTINGS = {
397
+ TERMINAL_UI_VERBOSE: 'FULL_TOOL_INPUTS',
398
+ };
399
+ /** `env` with each renamed setting's old value under its new name, unless the new one is set. */
400
+ export function withRenamedSettings(env) {
401
+ const out = { ...env };
402
+ for (const [old, now] of Object.entries(RENAMED_SETTINGS)) {
403
+ if (!out[now] && out[old])
404
+ out[now] = out[old];
405
+ }
406
+ return out;
407
+ }
408
+ const env = withRenamedSettings(process.env);
409
+ const parsed = envSchema.safeParse(env);
410
+ if (!parsed.success) {
411
+ failConfig(problemsFromIssues(parsed.error.issues, env));
412
+ }
413
+ /**
414
+ * ADMIN_USER_IDS narrows who, among the people ALLOWED_USER_IDS lets in, may
415
+ * approve prompts and run lifecycle commands. It does not grant access itself.
416
+ *
417
+ * Reading it as a replacement rather than a subset is the natural mistake — the
418
+ * variable that mentions "admin" looks like the more powerful one — and the
419
+ * failure it produces is misleading: the bot dies on ALLOWED_USER_IDS being
420
+ * empty and never mentions the line you actually filled in. So the check names
421
+ * both, here, at the point of exit.
422
+ */
423
+ if (parsed.data.ADMIN_USER_IDS.length > 0) {
424
+ const orphaned = parsed.data.ADMIN_USER_IDS.filter((id) => !parsed.data.ALLOWED_USER_IDS.includes(id));
425
+ if (orphaned.length > 0) {
426
+ failConfig([{
427
+ key: 'ADMIN_USER_IDS',
428
+ message: `ADMIN_USER_IDS lists ${orphaned.join(', ')}, which ALLOWED_USER_IDS does not. ` +
429
+ 'ADMIN_USER_IDS picks the admins out of ALLOWED_USER_IDS; it does not grant access ' +
430
+ 'on its own, so an id in one and not the other can never do anything. ' +
431
+ `Add ${orphaned.length === 1 ? 'it' : 'them'} to ALLOWED_USER_IDS too — the same id in both lines is normal.`,
432
+ }]);
433
+ }
434
+ }
435
+ /**
436
+ * APPROVER_USER_IDS with no ADMIN_USER_IDS is a no-op: with that unset every
437
+ * allowed user is already an admin, so there is nobody left for this list to
438
+ * promote. Someone who filled it in wanted a split and got none, which is the
439
+ * same silent nothing the ADMIN_USER_IDS check above exists to prevent.
440
+ *
441
+ * The other way of getting it wrong — an approver no allow-list carries —
442
+ * is checked at startup instead, by findOrphanedApprovers(). It has to read the
443
+ * roster that `/allow` writes to, and this file cannot: user-roster.ts imports
444
+ * it. Checking only ALLOWED_USER_IDS here was wrong in precisely the case the
445
+ * tier exists for — a friend admitted from chat is never in that line.
446
+ */
447
+ if (parsed.data.APPROVER_USER_IDS.length > 0 && parsed.data.ADMIN_USER_IDS.length === 0) {
448
+ failConfig([{
449
+ key: 'APPROVER_USER_IDS',
450
+ message: 'APPROVER_USER_IDS is set but ADMIN_USER_IDS is not. With no admin subset configured every ' +
451
+ 'allowed user is already an admin and can approve anything, so this list would promote nobody ' +
452
+ 'and change nothing. Set ADMIN_USER_IDS to the people who own the bot, and leave the rest here.',
453
+ }]);
454
+ }
455
+ export const config = { ...parsed.data };
456
+ // Capture which override env vars were explicitly set (after dotenv has loaded
457
+ // process.env). The verbosity resolver consults these to decide whether to
458
+ // honor the env value or fall back to the per-tier default; the startup name
459
+ // sync only renames the bot when BOT_NAME was asked for.
460
+ function isEnvSet(key) {
461
+ const raw = env[key];
462
+ return raw !== undefined && raw !== '';
463
+ }
464
+ export const explicitFlags = {
465
+ CONTEXT_SHOW_USAGE: isEnvSet('CONTEXT_SHOW_USAGE'),
466
+ CONTEXT_NOTIFY_COMPACTION: isEnvSet('CONTEXT_NOTIFY_COMPACTION'),
467
+ FULL_TOOL_INPUTS: isEnvSet('FULL_TOOL_INPUTS'),
468
+ BOT_NAME: isEnvSet('BOT_NAME'),
469
+ };
470
+ // ---------------------------------------------------------------------------
471
+ // Derived helpers (used by index.ts, command.handler.ts, session-history.ts)
472
+ // ---------------------------------------------------------------------------
473
+ import * as fs from 'fs';
474
+ import { getStateDir, ensureStateDir, readJsonFile, writeJsonFile } from './utils/json-store.js';
475
+ /** Numeric bot ID extracted from the Telegram token (e.g. "123456" from "123456:ABC..."). */
476
+ export const BOT_ID = config.TELEGRAM_BOT_TOKEN.split(':')[0];
477
+ const STATE_DIR = getStateDir();
478
+ const botNameFileSchema = z.object({ name: z.string().min(1).max(64) });
479
+ const envBotName = config.BOT_NAME;
480
+ let botNameSource = explicitFlags.BOT_NAME ? 'env' : 'default';
481
+ /** The file holding the name set with `/botname`, one per bot. */
482
+ export function getBotNameFilePath() {
483
+ return path.join(STATE_DIR, `botname-${BOT_ID}.json`);
484
+ }
485
+ // A name set with /botname wins over BOT_NAME. It's applied here, as the config
486
+ // loads, so every module that reads config.BOT_NAME at import time sees it too.
487
+ {
488
+ const stored = readJsonFile(getBotNameFilePath(), botNameFileSchema, 'BotName')?.name;
489
+ if (stored) {
490
+ config.BOT_NAME = stored;
491
+ botNameSource = 'command';
492
+ }
493
+ }
494
+ export function getBotNameSource() {
495
+ return botNameSource;
496
+ }
497
+ /**
498
+ * Save the name set with `/botname`, or clear it (`undefined`) so the bot goes
499
+ * back to `BOT_NAME`. Updates `config.BOT_NAME` in place for the running process;
500
+ * the Telegram side is the caller's job. Throws when the file can't be written.
501
+ */
502
+ export function setStoredBotName(name) {
503
+ const file = getBotNameFilePath();
504
+ if (name) {
505
+ ensureStateDir(STATE_DIR, 'BotName');
506
+ writeJsonFile(file, { name }, 'BotName', { rethrow: true });
507
+ config.BOT_NAME = name;
508
+ botNameSource = 'command';
509
+ return;
510
+ }
511
+ fs.rmSync(file, { force: true });
512
+ config.BOT_NAME = envBotName;
513
+ botNameSource = explicitFlags.BOT_NAME ? 'env' : 'default';
514
+ }
515
+ /** Per-bot reload marker file path so multi-instance setups don't cross-restore. */
516
+ export function getReloadMarkerPath() {
517
+ return getReloadMarkerPathForBotId(BOT_ID);
518
+ }
519
+ /** Same as getReloadMarkerPath, but for an arbitrary bot ID — used by the
520
+ * launcher when it needs to write markers for sibling bots on /botrestart all
521
+ * and /botrebuild all. */
522
+ export function getReloadMarkerPathForBotId(botId) {
523
+ return path.join(STATE_DIR, `pending-reload-${botId}.json`);
524
+ }
525
+ //# sourceMappingURL=config.js.map