telecoder 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/.env.example +363 -0
  2. package/CHANGELOG.md +1186 -0
  3. package/LICENSE +22 -0
  4. package/README.md +126 -2
  5. package/dist/audio/transcribe.js +50 -0
  6. package/dist/bin/mcp-server.js +378 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +592 -0
  10. package/dist/bot/file-access.js +141 -0
  11. package/dist/bot/handlers/command/access.js +407 -0
  12. package/dist/bot/handlers/command/admin.js +827 -0
  13. package/dist/bot/handlers/command/auto-approve.js +138 -0
  14. package/dist/bot/handlers/command/btw.js +224 -0
  15. package/dist/bot/handlers/command/cost.js +409 -0
  16. package/dist/bot/handlers/command/media.js +197 -0
  17. package/dist/bot/handlers/command/model.js +305 -0
  18. package/dist/bot/handlers/command/prefs-scope.js +197 -0
  19. package/dist/bot/handlers/command/project.js +536 -0
  20. package/dist/bot/handlers/command/resume.js +321 -0
  21. package/dist/bot/handlers/command/session.js +438 -0
  22. package/dist/bot/handlers/command/settings.js +1012 -0
  23. package/dist/bot/handlers/command/shared.js +210 -0
  24. package/dist/bot/handlers/command/streaming-mode.js +16 -0
  25. package/dist/bot/handlers/command/tasks.js +513 -0
  26. package/dist/bot/handlers/command/topic-store.js +113 -0
  27. package/dist/bot/handlers/command/topic.js +80 -0
  28. package/dist/bot/handlers/command.handler.js +772 -0
  29. package/dist/bot/handlers/fork.handler.js +1109 -0
  30. package/dist/bot/handlers/media-fallback.js +121 -0
  31. package/dist/bot/handlers/message/replies.js +133 -0
  32. package/dist/bot/handlers/message/shared.js +117 -0
  33. package/dist/bot/handlers/message/throttle.js +49 -0
  34. package/dist/bot/handlers/message/turn-notify.js +169 -0
  35. package/dist/bot/handlers/message/turn-runner.js +141 -0
  36. package/dist/bot/handlers/message.handler.js +107 -0
  37. package/dist/bot/handlers/newbot.handler.js +221 -0
  38. package/dist/bot/handlers/photo.handler.js +327 -0
  39. package/dist/bot/handlers/prompts.handler.js +343 -0
  40. package/dist/bot/handlers/running-note.js +44 -0
  41. package/dist/bot/handlers/schedule.handler.js +303 -0
  42. package/dist/bot/handlers/session-guard.js +78 -0
  43. package/dist/bot/handlers/suggestion.handler.js +84 -0
  44. package/dist/bot/handlers/tree.handler.js +480 -0
  45. package/dist/bot/handlers/view.js +41 -0
  46. package/dist/bot/handlers/voice.handler.js +209 -0
  47. package/dist/bot/middleware/admin-only.js +49 -0
  48. package/dist/bot/middleware/auth.middleware.js +122 -0
  49. package/dist/bot/middleware/group-mention.middleware.js +139 -0
  50. package/dist/bot/middleware/group-role.middleware.js +75 -0
  51. package/dist/bot/middleware/message-batcher.js +87 -0
  52. package/dist/bot/middleware/queued-messages.js +971 -0
  53. package/dist/bot/middleware/stale-filter.js +31 -0
  54. package/dist/build-info.json +8 -0
  55. package/dist/claude/agent-watchdog.js +162 -0
  56. package/dist/claude/agent.js +1458 -0
  57. package/dist/claude/ask-user.js +295 -0
  58. package/dist/claude/auto-approve.js +225 -0
  59. package/dist/claude/auto-topic-haiku.js +126 -0
  60. package/dist/claude/available-commands.js +153 -0
  61. package/dist/claude/carry-over.js +27 -0
  62. package/dist/claude/ccr-shim.js +46 -0
  63. package/dist/claude/charter-judge.js +214 -0
  64. package/dist/claude/claude-auth.js +121 -0
  65. package/dist/claude/command-parser.js +200 -0
  66. package/dist/claude/cost-overlay-scraper.js +129 -0
  67. package/dist/claude/enabled-plugins.js +56 -0
  68. package/dist/claude/fork-tree.js +393 -0
  69. package/dist/claude/held-query.js +190 -0
  70. package/dist/claude/in-flight-tracker.js +61 -0
  71. package/dist/claude/ipc-server.js +192 -0
  72. package/dist/claude/mcp-bridge.js +453 -0
  73. package/dist/claude/mcp-tools.js +354 -0
  74. package/dist/claude/message-offsets.js +88 -0
  75. package/dist/claude/modal-relay.js +450 -0
  76. package/dist/claude/model-catalog.js +85 -0
  77. package/dist/claude/monitor-relay.js +597 -0
  78. package/dist/claude/pending-forks.js +93 -0
  79. package/dist/claude/pending-suggestions.js +50 -0
  80. package/dist/claude/permission-gate.js +337 -0
  81. package/dist/claude/permission-mode.js +178 -0
  82. package/dist/claude/poll-user.js +51 -0
  83. package/dist/claude/project-commands.js +69 -0
  84. package/dist/claude/prompt-hold.js +124 -0
  85. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  86. package/dist/claude/pty-provider.js +2214 -0
  87. package/dist/claude/pty-spawn-config.js +296 -0
  88. package/dist/claude/pty-stream.js +363 -0
  89. package/dist/claude/request-queue.js +135 -0
  90. package/dist/claude/scheduled-runner.js +91 -0
  91. package/dist/claude/scheduler.js +237 -0
  92. package/dist/claude/scope-guard.js +274 -0
  93. package/dist/claude/sdk-permission-gate.js +77 -0
  94. package/dist/claude/secret-request.js +576 -0
  95. package/dist/claude/session-cost.js +41 -0
  96. package/dist/claude/session-history.js +286 -0
  97. package/dist/claude/session-jsonl.js +920 -0
  98. package/dist/claude/session-manager.js +195 -0
  99. package/dist/claude/session-scan.js +270 -0
  100. package/dist/claude/setup-token.js +285 -0
  101. package/dist/claude/side-call-options.js +45 -0
  102. package/dist/claude/side-question.js +249 -0
  103. package/dist/claude/stage-images.js +62 -0
  104. package/dist/claude/subagent-tools.js +12 -0
  105. package/dist/claude/synthetic-ctx.js +51 -0
  106. package/dist/claude/system-prompt.js +162 -0
  107. package/dist/claude/tasks-overlay-scraper.js +94 -0
  108. package/dist/claude/tip-scraper.js +78 -0
  109. package/dist/claude/tui-modal.js +501 -0
  110. package/dist/claude/tui-state.js +384 -0
  111. package/dist/claude/turn-end.js +91 -0
  112. package/dist/claude/turn-prose.js +64 -0
  113. package/dist/claude/update-banner-relay.js +70 -0
  114. package/dist/cli/commands/doctor.js +305 -0
  115. package/dist/cli/commands/help.js +25 -0
  116. package/dist/cli/commands/init.js +123 -0
  117. package/dist/cli/commands/service.js +678 -0
  118. package/dist/cli/commands/start.js +53 -0
  119. package/dist/cli/commands/version.js +11 -0
  120. package/dist/cli/dispatch.js +79 -0
  121. package/dist/cli/init/env-file.js +99 -0
  122. package/dist/cli/init/flow.js +638 -0
  123. package/dist/cli/init/prompter.js +116 -0
  124. package/dist/cli/init/telegram.js +94 -0
  125. package/dist/cli/service/render.js +212 -0
  126. package/dist/cli.js +18 -0
  127. package/dist/config-report.js +107 -0
  128. package/dist/config.js +500 -0
  129. package/dist/index.js +367 -0
  130. package/dist/launcher.js +933 -0
  131. package/dist/node-version-check.js +27 -0
  132. package/dist/providers/ccr-health.js +119 -0
  133. package/dist/providers/ccr-introspect.js +149 -0
  134. package/dist/providers/ccr-provider.js +60 -0
  135. package/dist/providers/claude-provider.js +63 -0
  136. package/dist/providers/prefs-sync.js +164 -0
  137. package/dist/providers/project-favorites.js +74 -0
  138. package/dist/providers/provider-router.js +127 -0
  139. package/dist/providers/provider-switch.js +91 -0
  140. package/dist/providers/sdk-provider.js +37 -0
  141. package/dist/providers/types.js +8 -0
  142. package/dist/providers/user-preferences.js +214 -0
  143. package/dist/restart-when-idle.js +153 -0
  144. package/dist/startup/auto-continue.js +67 -0
  145. package/dist/startup/auto-resume.js +173 -0
  146. package/dist/startup/notices.js +120 -0
  147. package/dist/startup/shared.js +44 -0
  148. package/dist/startup/verify-token.js +31 -0
  149. package/dist/telegram/access-request.js +153 -0
  150. package/dist/telegram/action-logger.js +684 -0
  151. package/dist/telegram/admin-mention.js +107 -0
  152. package/dist/telegram/background-activity-card.js +502 -0
  153. package/dist/telegram/botname-settings.js +336 -0
  154. package/dist/telegram/button-text.js +26 -0
  155. package/dist/telegram/client-options.js +27 -0
  156. package/dist/telegram/deduplication.js +33 -0
  157. package/dist/telegram/entities.js +295 -0
  158. package/dist/telegram/force-reply-tracker.js +57 -0
  159. package/dist/telegram/lettered-options.js +87 -0
  160. package/dist/telegram/markdown.js +362 -0
  161. package/dist/telegram/message-sender.js +1287 -0
  162. package/dist/telegram/prompt-label.js +142 -0
  163. package/dist/telegram/prompt-suggestion.js +54 -0
  164. package/dist/telegram/send.js +123 -0
  165. package/dist/telegram/streaming-turn.js +105 -0
  166. package/dist/telegram/suggestions-settings.js +30 -0
  167. package/dist/telegram/task-list.js +367 -0
  168. package/dist/telegram/task-tracker.js +209 -0
  169. package/dist/telegram/telegraph-settings.js +31 -0
  170. package/dist/telegram/telegraph.js +453 -0
  171. package/dist/telegram/terminal-renderer.js +671 -0
  172. package/dist/telegram/terminal-settings.js +25 -0
  173. package/dist/telegram/thread-titles.js +190 -0
  174. package/dist/telegram/threads-setup.js +117 -0
  175. package/dist/tts/tts-settings.js +62 -0
  176. package/dist/tts/tts.js +245 -0
  177. package/dist/tts/voice-reply.js +78 -0
  178. package/dist/utils/admins.js +143 -0
  179. package/dist/utils/agent-timer.js +55 -0
  180. package/dist/utils/atomic-write.js +24 -0
  181. package/dist/utils/bot-token.js +74 -0
  182. package/dist/utils/bounded-map.js +55 -0
  183. package/dist/utils/build-info.js +57 -0
  184. package/dist/utils/caffeinate.js +50 -0
  185. package/dist/utils/claude-env.js +54 -0
  186. package/dist/utils/claude-version.js +48 -0
  187. package/dist/utils/config-home.js +62 -0
  188. package/dist/utils/debug-agent.js +117 -0
  189. package/dist/utils/debug-watchdog.js +121 -0
  190. package/dist/utils/download.js +111 -0
  191. package/dist/utils/exit-codes.js +48 -0
  192. package/dist/utils/file-type.js +149 -0
  193. package/dist/utils/format.js +81 -0
  194. package/dist/utils/home-project.js +30 -0
  195. package/dist/utils/host-stall.js +51 -0
  196. package/dist/utils/id-list.js +44 -0
  197. package/dist/utils/idle-restart.js +92 -0
  198. package/dist/utils/install-mode.js +63 -0
  199. package/dist/utils/instance-config.js +148 -0
  200. package/dist/utils/instances.js +95 -0
  201. package/dist/utils/json-store.js +140 -0
  202. package/dist/utils/keyed-settings.js +62 -0
  203. package/dist/utils/legacy-env.js +35 -0
  204. package/dist/utils/npm-version.js +134 -0
  205. package/dist/utils/prefs-relay.js +107 -0
  206. package/dist/utils/proc-children.js +102 -0
  207. package/dist/utils/project-data-dir.js +33 -0
  208. package/dist/utils/reasoning-summary.js +12 -0
  209. package/dist/utils/resolve-bin.js +86 -0
  210. package/dist/utils/resolve-claude-bin.js +63 -0
  211. package/dist/utils/respawn-backoff.js +19 -0
  212. package/dist/utils/sanitize.js +91 -0
  213. package/dist/utils/session-key.js +37 -0
  214. package/dist/utils/stale-launcher.js +109 -0
  215. package/dist/utils/state-dir-migration.js +92 -0
  216. package/dist/utils/systemd.js +126 -0
  217. package/dist/utils/user-roster.js +275 -0
  218. package/dist/utils/verbosity.js +118 -0
  219. package/dist/utils/version-check.js +166 -0
  220. package/dist/utils/workspace-guard.js +44 -0
  221. package/dist/worker-restart.js +141 -0
  222. package/instances.json.example +41 -0
  223. package/package.json +76 -4
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Who counts as an admin of this bot instance.
3
+ *
4
+ * TeleCoder's original access model is one flat list: every id in
5
+ * `ALLOWED_USER_IDS` can do everything. That is the right model for a bot with
6
+ * one user, and it stops being right the moment the bot is shared. An approval
7
+ * prompt the person who triggered it can tap themselves is not an approval, and
8
+ * a guest who can `/restartbot` or flip the transport can step around every
9
+ * guardrail the owner configured.
10
+ *
11
+ * `ADMIN_USER_IDS` names the subset that keeps those unrestricted rights. Left
12
+ * unset it resolves to *every* allowed user, so a single-user install behaves
13
+ * exactly as it did before this module existed and nobody has to migrate.
14
+ *
15
+ * Admin-ness is deliberately not inferred from Telegram's own group-admin
16
+ * status: who may promote someone in a Telegram group is a different question
17
+ * from who may approve a `sudo` on the machine the bot runs on.
18
+ */
19
+ import { config } from '../config.js';
20
+ import { allAllowedUserIds } from './user-roster.js';
21
+ /**
22
+ * Telegram's GroupAnonymousBot id — the sender id on messages posted
23
+ * anonymously by a group admin. Shared with the auth middleware, which lets it
24
+ * through in allow-listed groups.
25
+ *
26
+ * It is never an admin here. Any Telegram group admin can post anonymously, so
27
+ * honouring it would hand bot-admin rights to whoever holds group-admin rights
28
+ * — a promotion the bot owner may not have intended to be the same thing.
29
+ */
30
+ export const GROUP_ANONYMOUS_BOT_ID = 1087968824;
31
+ /**
32
+ * The effective admin roster. Falls back to the full allow-list when
33
+ * `ADMIN_USER_IDS` is unset, which is what keeps existing installs unchanged.
34
+ *
35
+ * An id here that `ALLOWED_USER_IDS` does not also carry can never act — the
36
+ * auth middleware turns it away before any admin check runs — so config.ts
37
+ * refuses to start on one rather than leaving it to surface later, as an
38
+ * approval prompt that silently went to the wrong person.
39
+ */
40
+ export function getAdminIds() {
41
+ if (config.ADMIN_USER_IDS.length === 0)
42
+ return [...config.ALLOWED_USER_IDS];
43
+ return [...config.ADMIN_USER_IDS];
44
+ }
45
+ /** True when this user may approve prompts and run bot-lifecycle commands. */
46
+ export function isAdmin(userId) {
47
+ if (userId === undefined)
48
+ return false;
49
+ if (userId === GROUP_ANONYMOUS_BOT_ID)
50
+ return false;
51
+ return getAdminIds().includes(userId);
52
+ }
53
+ /**
54
+ * The people who may answer an approval prompt but do not own the bot.
55
+ *
56
+ * This exists because "can approve" and "can restart the bot" were one flag,
57
+ * and on a bot shared with several people that forces a choice between one
58
+ * owner being the bottleneck for every prompt and handing guests the controls
59
+ * — including `/method` and `/permissionmode`, either of which switches the
60
+ * gate off. An approver is a guest in every other respect: the charter judge
61
+ * still reads their messages, the gate still stops their tool calls, and the
62
+ * lifecycle commands still refuse them.
63
+ *
64
+ * Empty when `ADMIN_USER_IDS` is unset, because then every allowed user is
65
+ * already an admin and there is nothing to widen. Ids the admin roster already
66
+ * carries are dropped rather than counted twice.
67
+ */
68
+ export function getApproverIds() {
69
+ // config.ts refuses to start on approvers-without-admins, so this is a
70
+ // belt-and-braces restatement of the invariant rather than a reachable path.
71
+ if (config.ADMIN_USER_IDS.length === 0)
72
+ return [];
73
+ const admins = getAdminIds();
74
+ return config.APPROVER_USER_IDS.filter((id) => id !== GROUP_ANONYMOUS_BOT_ID && !admins.includes(id));
75
+ }
76
+ /**
77
+ * Approver ids that no allow-list carries — neither `ALLOWED_USER_IDS` nor the
78
+ * roster `/allow` writes to. Those can never act, so they are always a typo.
79
+ *
80
+ * This lives here rather than beside the matching `ADMIN_USER_IDS` check in
81
+ * config.ts because it has to read the runtime roster, and user-roster.ts
82
+ * imports config.ts. The env-only version of this check was wrong in exactly
83
+ * the case the tier exists for: a friend admitted from chat with `/allow` is
84
+ * never in `ALLOWED_USER_IDS`, so promoting them would have refused to start
85
+ * the bot — and the message would have told them to widen a list that had
86
+ * nothing to do with it.
87
+ *
88
+ * Reported at startup rather than enforced here: the roster moves while the
89
+ * bot runs, and an approver who is later `/deny`'d should stop being able to
90
+ * act, not take the process down with them.
91
+ */
92
+ export function findOrphanedApprovers() {
93
+ if (config.APPROVER_USER_IDS.length === 0)
94
+ return [];
95
+ const reachable = new Set(allAllowedUserIds());
96
+ return config.APPROVER_USER_IDS.filter((id) => !reachable.has(id));
97
+ }
98
+ /** True when this user may answer someone else's approval prompt. */
99
+ export function isApprover(userId) {
100
+ if (userId === undefined)
101
+ return false;
102
+ return getApproverIds().includes(userId);
103
+ }
104
+ /**
105
+ * Who may answer a prompt raised by `requesterId`.
106
+ *
107
+ * Approvers are filtered against the requester: tapping "allow" on your own
108
+ * request confirms nothing, and a tier that let you do it would be a speed
109
+ * bump rather than supervision. Admins are not filtered, because an admin
110
+ * approving their own `sudo` is the owner of the machine agreeing with
111
+ * themselves — which is what a solo bot has always done.
112
+ *
113
+ * Never empty: `getAdminIds()` falls back to the whole allow-list.
114
+ */
115
+ export function getPromptResponderIds(requesterId) {
116
+ const admins = getAdminIds();
117
+ const approvers = getApproverIds().filter((id) => id !== requesterId);
118
+ return [...admins, ...approvers];
119
+ }
120
+ /**
121
+ * True when at least one allowed user is not an admin — i.e. the bot is shared
122
+ * with someone who is meant to be supervised.
123
+ *
124
+ * This is the predicate the rest of the codebase should branch on rather than
125
+ * "is ADMIN_USER_IDS set": a roster that happens to list everybody restricts
126
+ * nobody, and should not switch on supervision UI or change any default.
127
+ *
128
+ * It reads the *effective* allow-list, `.env` plus everyone `/allow` has
129
+ * admitted since — this is what turns the permission gate, the scope guard and
130
+ * the charter judge on, and admitting a guest from chat has to switch on the
131
+ * supervision meant for guests. Reading only `.env` here would leave a bot that
132
+ * had just gained its first guest running with every guardrail off.
133
+ */
134
+ export function hasGuestUsers() {
135
+ const admins = getAdminIds();
136
+ return allAllowedUserIds().some((id) => !admins.includes(id));
137
+ }
138
+ /** The allowed users who are not admins. Used by `/permissions` to report the split. */
139
+ export function getGuestIds() {
140
+ const admins = getAdminIds();
141
+ return allAllowedUserIds().filter((id) => !admins.includes(id));
142
+ }
143
+ //# sourceMappingURL=admins.js.map
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Agent timer utility for tracking elapsed time during agent queries.
3
+ * Provides human-readable duration formatting and timing state management.
4
+ */
5
+ /**
6
+ * Create a new agent timer initialized to the current time.
7
+ */
8
+ export function createAgentTimer() {
9
+ const now = Date.now();
10
+ return {
11
+ startTime: now,
12
+ lastMessageTime: now,
13
+ messageCount: 0,
14
+ };
15
+ }
16
+ /**
17
+ * Record that a message was received, updating the last message time.
18
+ */
19
+ export function recordMessage(timer) {
20
+ timer.lastMessageTime = Date.now();
21
+ timer.messageCount++;
22
+ }
23
+ /**
24
+ * Get elapsed milliseconds since timer start.
25
+ */
26
+ export function getElapsedMs(timer) {
27
+ return Date.now() - timer.startTime;
28
+ }
29
+ /**
30
+ * Get milliseconds since last message was recorded.
31
+ */
32
+ export function getSinceLastMessageMs(timer) {
33
+ return Date.now() - timer.lastMessageTime;
34
+ }
35
+ /**
36
+ * Format a duration in milliseconds to human-readable string.
37
+ * Examples: "0s", "45s", "1m 30s", "2m 0s"
38
+ */
39
+ export function formatDuration(ms) {
40
+ const totalSeconds = Math.floor(ms / 1000);
41
+ const minutes = Math.floor(totalSeconds / 60);
42
+ const seconds = totalSeconds % 60;
43
+ if (minutes === 0) {
44
+ return `${seconds}s`;
45
+ }
46
+ return `${minutes}m ${seconds}s`;
47
+ }
48
+ /**
49
+ * Get a timing report string for logging.
50
+ */
51
+ export function getTimingReport(timer) {
52
+ const elapsed = formatDuration(getElapsedMs(timer));
53
+ return `${elapsed} elapsed, ${timer.messageCount} messages`;
54
+ }
55
+ //# sourceMappingURL=agent-timer.js.map
@@ -0,0 +1,24 @@
1
+ import * as fs from 'fs';
2
+ /**
3
+ * Write a file atomically using write-to-temp + rename.
4
+ * On POSIX, rename is atomic. On Windows, it's best-effort but still
5
+ * safer than a direct writeFileSync which can corrupt on crash.
6
+ */
7
+ export function atomicWriteFileSync(filePath, data, options) {
8
+ const tmpPath = filePath + '.tmp';
9
+ try {
10
+ fs.writeFileSync(tmpPath, data, { mode: options?.mode });
11
+ fs.renameSync(tmpPath, filePath);
12
+ }
13
+ catch (err) {
14
+ // Clean up temp file on failure
15
+ try {
16
+ fs.unlinkSync(tmpPath);
17
+ }
18
+ catch {
19
+ // Ignore cleanup errors
20
+ }
21
+ throw err;
22
+ }
23
+ }
24
+ //# sourceMappingURL=atomic-write.js.map
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Checking the Telegram bot token before anything is done with it.
3
+ *
4
+ * Kept free of config imports, like id-list.ts, so config.ts can use it and
5
+ * tests can call it directly.
6
+ *
7
+ * Two failures used to reach the user as a grammY stack trace — `Fatal error:
8
+ * GrammyError: Call to 'getMe' failed! (404: Not Found)` — after the IPC server
9
+ * had already started. A value that can't be a token at all (the .env.example
10
+ * placeholder, a half-pasted line) is now caught by its shape when the config
11
+ * is read. One that has the right shape but that Telegram turns down is caught
12
+ * by a getMe made before any other service starts, and described here.
13
+ */
14
+ import { GrammyError, HttpError } from 'grammy';
15
+ import { redactSecrets } from './sanitize.js';
16
+ /**
17
+ * What @BotFather hands out: the bot's numeric id, a colon, and a secret of
18
+ * 35 characters from the URL-safe base64 alphabet. 30 rather than 35 leaves
19
+ * room for Telegram changing the length without letting a placeholder through.
20
+ */
21
+ export const BOT_TOKEN_FORMAT = /^\d+:[A-Za-z0-9_-]{30,}$/;
22
+ export function isWellFormedBotToken(token) {
23
+ return BOT_TOKEN_FORMAT.test(token);
24
+ }
25
+ /** The config error for a token with the wrong shape. Never includes the token. */
26
+ export const MALFORMED_TOKEN_MESSAGE = "TELEGRAM_BOT_TOKEN doesn't look like a bot token. A token from @BotFather is the bot's number, " +
27
+ 'a colon, and about 35 letters, digits, - and _ (like 1234567890:AAH...). Check that the whole token ' +
28
+ 'was pasted, with no spaces or quotes around it.';
29
+ export const REJECTED_TOKEN_MESSAGE = 'TELEGRAM_BOT_TOKEN was rejected by Telegram — get a fresh one from @BotFather (/mybots → API Token).';
30
+ /**
31
+ * Describe a failed getMe for the person running the bot.
32
+ *
33
+ * 401 and 404 are what Telegram answers for a revoked or made-up token. A
34
+ * network failure is the other common first-run problem — Telegram is blocked
35
+ * on some networks — and is worth naming as such, with the setting that works
36
+ * around it. Everything is passed through redactSecrets: grammY puts the
37
+ * request URL, token included, into some of its messages.
38
+ */
39
+ export function describeTokenCheckFailure(err, proxyUrl) {
40
+ if (err instanceof GrammyError) {
41
+ if (err.error_code === 401 || err.error_code === 404) {
42
+ return { message: REJECTED_TOKEN_MESSAGE, fatal: true };
43
+ }
44
+ return {
45
+ message: redactSecrets(`Telegram answered the startup check with an error (${err.error_code}: ${err.description}).`),
46
+ fatal: false,
47
+ };
48
+ }
49
+ const reason = err instanceof HttpError
50
+ ? describeCause(err.error) ?? err.message
51
+ : err instanceof Error ? err.message : String(err);
52
+ const via = proxyUrl ? ` through the proxy ${redactSecrets(proxyUrl)}` : '';
53
+ const hint = proxyUrl
54
+ ? 'Check that the proxy is running and reachable.'
55
+ : 'Check the network connection. If Telegram is blocked on this network, set TELEGRAM_PROXY_URL ' +
56
+ '(e.g. socks5://127.0.0.1:1080 or http://proxy:8080).';
57
+ return {
58
+ message: redactSecrets(`Couldn't reach api.telegram.org${via} (${reason}). ${hint}`),
59
+ fatal: false,
60
+ };
61
+ }
62
+ /** The innermost useful reason from a fetch failure: ENOTFOUND beats "fetch failed". */
63
+ function describeCause(error) {
64
+ let current = error;
65
+ let best;
66
+ for (let depth = 0; depth < 4 && current instanceof Error; depth++) {
67
+ // node-fetch says "request to <url> failed, reason: <why>"; the why is
68
+ // the part worth reading, and the URL carries the token.
69
+ best = current.message.match(/reason: (.+)$/)?.[1] ?? current.message;
70
+ current = current.cause;
71
+ }
72
+ return best;
73
+ }
74
+ //# sourceMappingURL=bot-token.js.map
@@ -0,0 +1,55 @@
1
+ /**
2
+ * A Map wrapper with a configurable maximum size.
3
+ * When capacity is reached, the oldest entry (first inserted) is evicted.
4
+ * Re-setting an existing key moves it to the end (most recent).
5
+ */
6
+ export class BoundedMap {
7
+ map = new Map();
8
+ maxSize;
9
+ constructor(maxSize = 1000) {
10
+ this.maxSize = maxSize;
11
+ }
12
+ get(key) {
13
+ return this.map.get(key);
14
+ }
15
+ set(key, value) {
16
+ // If key already exists, delete first so re-insert moves it to the end
17
+ if (this.map.has(key)) {
18
+ this.map.delete(key);
19
+ }
20
+ else if (this.map.size >= this.maxSize) {
21
+ // Evict the oldest entry (first key in insertion order)
22
+ const oldest = this.map.keys().next().value;
23
+ if (oldest !== undefined) {
24
+ this.map.delete(oldest);
25
+ }
26
+ }
27
+ this.map.set(key, value);
28
+ return this;
29
+ }
30
+ delete(key) {
31
+ return this.map.delete(key);
32
+ }
33
+ has(key) {
34
+ return this.map.has(key);
35
+ }
36
+ clear() {
37
+ this.map.clear();
38
+ }
39
+ get size() {
40
+ return this.map.size;
41
+ }
42
+ entries() {
43
+ return this.map.entries();
44
+ }
45
+ keys() {
46
+ return this.map.keys();
47
+ }
48
+ values() {
49
+ return this.map.values();
50
+ }
51
+ forEach(callbackfn) {
52
+ this.map.forEach(callbackfn);
53
+ }
54
+ }
55
+ //# sourceMappingURL=bounded-map.js.map
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Which build this process is running, for the messages that follow a restart,
3
+ * /botstatus and /version.
4
+ *
5
+ * Asking git at startup would answer a different question. HEAD is what's
6
+ * checked out and the bot runs dist/, so after a commit and a plain /restartbot
7
+ * the two differ, and the reply would name a fix that isn't live. Instead
8
+ * `npm run build` stamps dist/ with what it compiled (scripts/stamp-build.mjs).
9
+ *
10
+ * The stamp is read once, on import, because it describes the code loaded then:
11
+ * a later build replaces the file but not what this worker has in memory.
12
+ */
13
+ import { readFileSync } from 'fs';
14
+ import { formatTimeAgo } from './format.js';
15
+ import { isCheckout } from './install-mode.js';
16
+ /** The stamp in `file`, or null when there's none that can be read. */
17
+ export function readBuildInfo(file) {
18
+ try {
19
+ const stamp = JSON.parse(readFileSync(file, 'utf-8'));
20
+ if (typeof stamp?.version !== 'string' || Number.isNaN(Date.parse(stamp?.builtAt)))
21
+ return null;
22
+ return stamp;
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ /** E.g. "63dcf45 feat: end /recap the way a turn ends (built 5m ago)". */
29
+ export function describeBuild(build) {
30
+ const name = build.commit
31
+ ? [build.commit, build.subject].filter(Boolean).join(' ') + (build.dirty ? ', plus uncommitted changes' : '')
32
+ : `v${build.version}`;
33
+ return `${name} (built ${formatTimeAgo(new Date(build.builtAt))})`;
34
+ }
35
+ // dist/utils/build-info.js finds dist/build-info.json. Run from source under
36
+ // tsx this looks in src/ and finds nothing, which is right: that code is the
37
+ // working tree, not any build.
38
+ const STAMP = new URL('../build-info.json', import.meta.url);
39
+ const runningBuild = readBuildInfo(STAMP);
40
+ /** The build this process loaded, or null when it isn't running a stamped one. */
41
+ export function getRunningBuild() {
42
+ return runningBuild;
43
+ }
44
+ /** The last build on disk, which this process hasn't loaded if it came after the start. */
45
+ export function getLatestBuild() {
46
+ return readBuildInfo(STAMP);
47
+ }
48
+ /**
49
+ * getRunningBuild, in words. An npm install goes by its version: the commit it
50
+ * was published from names nothing its owner has a copy of.
51
+ */
52
+ export function describeRunningBuild() {
53
+ if (!runningBuild)
54
+ return null;
55
+ return describeBuild(isCheckout() ? runningBuild : { version: runningBuild.version, builtAt: runningBuild.builtAt });
56
+ }
57
+ //# sourceMappingURL=build-info.js.map
@@ -0,0 +1,50 @@
1
+ import { spawn } from 'child_process';
2
+ let caffeinateProcess = null;
3
+ export function preventSleep() {
4
+ if (process.platform !== 'darwin') {
5
+ console.log('[Caffeinate] Not on macOS, skipping sleep prevention');
6
+ return;
7
+ }
8
+ if (caffeinateProcess) {
9
+ console.log('[Caffeinate] Already running');
10
+ return;
11
+ }
12
+ try {
13
+ // -d: prevent display sleep, -i: prevent idle sleep
14
+ caffeinateProcess = spawn('caffeinate', ['-di'], {
15
+ stdio: 'ignore',
16
+ detached: true,
17
+ });
18
+ caffeinateProcess.unref();
19
+ caffeinateProcess.on('error', (err) => {
20
+ console.error('[Caffeinate] Error:', err.message);
21
+ caffeinateProcess = null;
22
+ });
23
+ caffeinateProcess.on('exit', (code) => {
24
+ if (code !== null && code !== 0) {
25
+ console.log('[Caffeinate] Exited with code:', code);
26
+ }
27
+ caffeinateProcess = null;
28
+ });
29
+ console.log('[Caffeinate] Preventing system sleep');
30
+ }
31
+ catch (error) {
32
+ console.error('[Caffeinate] Failed to start:', error);
33
+ }
34
+ }
35
+ export function allowSleep() {
36
+ if (caffeinateProcess) {
37
+ try {
38
+ caffeinateProcess.kill();
39
+ }
40
+ catch {
41
+ // Ignore errors when killing process
42
+ }
43
+ caffeinateProcess = null;
44
+ console.log('[Caffeinate] Sleep prevention disabled');
45
+ }
46
+ }
47
+ export function isPreventingSleep() {
48
+ return caffeinateProcess !== null;
49
+ }
50
+ //# sourceMappingURL=caffeinate.js.map
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Claude Code stamps its own session's identity into the environment of every
3
+ * process it spawns, and anything started from inside a session inherits it.
4
+ * That is exactly how this bot gets deployed: a claude session running *in* the
5
+ * bot runs `pm2 start`, and pm2 captures that environment for the app's whole
6
+ * lifetime — so every worker, and every claude the bot itself spawns, inherits
7
+ * the parent session's markers.
8
+ *
9
+ * The damaging one is CLAUDE_CODE_CHILD_SESSION. A claude that sees it decides
10
+ * it is a nested session and turns transcript persistence OFF ("⚠ Transcript
11
+ * saving is off — inherited CLAUDE_CODE_CHILD_SESSION marker" in its status
12
+ * line). The session JSONL is then never written — and since the bot reads each
13
+ * reply out of that log, every turn returns the *previous* conversation's text.
14
+ * The model answers correctly; the user gets a stale answer to a question it
15
+ * did receive, and no error anywhere says why.
16
+ *
17
+ * None of these are read by the bot itself, so the safe move is to drop them at
18
+ * startup, before any provider spawns anything.
19
+ */
20
+ export const INHERITED_CLAUDE_SESSION_VARS = [
21
+ 'CLAUDECODE',
22
+ 'CLAUDE_CODE_CHILD_SESSION',
23
+ 'CLAUDE_CODE_SESSION_ID',
24
+ 'CLAUDE_CODE_BRIDGE_SESSION_ID',
25
+ 'CLAUDE_CODE_ENTRYPOINT',
26
+ 'CLAUDE_CODE_EXECPATH',
27
+ 'CLAUDE_PID',
28
+ 'CLAUDE_AGENT_SDK_VERSION',
29
+ 'CLAUDE_SDK_LOAD_USER_SETTINGS',
30
+ ];
31
+ /** A copy of `env` with the parent session's markers removed. */
32
+ export function envWithoutParentSession(env = process.env) {
33
+ const copy = { ...env };
34
+ for (const key of INHERITED_CLAUDE_SESSION_VARS)
35
+ delete copy[key];
36
+ return copy;
37
+ }
38
+ /**
39
+ * Drop the markers from this process's own environment so every child inherits
40
+ * a clean slate. Returns the names that were actually present — the caller logs
41
+ * them, because "the bot was launched from inside a claude session" is worth
42
+ * knowing when diagnosing session-log weirdness later.
43
+ */
44
+ export function stripParentClaudeSession(env = process.env) {
45
+ const removed = [];
46
+ for (const key of INHERITED_CLAUDE_SESSION_VARS) {
47
+ if (env[key] !== undefined) {
48
+ removed.push(key);
49
+ delete env[key];
50
+ }
51
+ }
52
+ return removed;
53
+ }
54
+ //# sourceMappingURL=claude-env.js.map
@@ -0,0 +1,48 @@
1
+ import { execFile } from 'node:child_process';
2
+ /** `claude --version` prints e.g. "2.1.226 (Claude Code)". */
3
+ export function parseClaudeVersion(output) {
4
+ const match = /(\d+)\.(\d+)\.(\d+)/.exec(output);
5
+ if (!match)
6
+ return undefined;
7
+ return {
8
+ major: Number(match[1]),
9
+ minor: Number(match[2]),
10
+ patch: Number(match[3]),
11
+ raw: match[0],
12
+ };
13
+ }
14
+ /** True when `version` is at or above `[major, minor, patch]`. */
15
+ export function isAtLeast(version, [major, minor, patch]) {
16
+ if (!version)
17
+ return false;
18
+ if (version.major !== major)
19
+ return version.major > major;
20
+ if (version.minor !== minor)
21
+ return version.minor > minor;
22
+ return version.patch >= patch;
23
+ }
24
+ // Keyed by binary path — PTY mode spawns CLAUDE_BIN while SDK mode usually
25
+ // spawns the SDK's bundled binary, and the two are often different releases.
26
+ const cache = new Map();
27
+ export async function getClaudeVersion(bin) {
28
+ const cached = cache.get(bin);
29
+ if (cached)
30
+ return cached;
31
+ const probe = new Promise((resolve) => {
32
+ execFile(bin, ['--version'], { timeout: 10_000, maxBuffer: 64 * 1024 }, (error, stdout) => {
33
+ if (error) {
34
+ console.debug('[ClaudeVersion] probe failed:', error.message);
35
+ resolve(undefined);
36
+ return;
37
+ }
38
+ resolve(parseClaudeVersion(stdout));
39
+ });
40
+ });
41
+ cache.set(bin, probe);
42
+ return probe;
43
+ }
44
+ /** Test seam — drops memoised probes so a fresh binary is re-read. */
45
+ export function clearClaudeVersionCache() {
46
+ cache.clear();
47
+ }
48
+ //# sourceMappingURL=claude-version.js.map
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Where TeleCoder's configuration lives: the .env, instances.json and the
3
+ * Telegraph account file. Every reader goes through here.
4
+ *
5
+ * In order:
6
+ * 1. TELECODER_HOME, when set — an explicit choice always wins.
7
+ * 2. The package root, when a .env or instances.json sits next to
8
+ * package.json. That is a git checkout set up the way it always has been,
9
+ * and it keeps working exactly as before.
10
+ * 3. ~/.telecoder — an npm install, whose package directory is no place for
11
+ * config (an update replaces it).
12
+ *
13
+ * ~/.telecoder is also the state directory (utils/json-store.ts). The two share
14
+ * it without colliding: state is per-bot `*-<botId>.json` files and the like,
15
+ * config is `.env`, `.env.*`, `instances.json` and `.telegraph-account.json`.
16
+ * TELECODER_HOME moves only the config; state stays in ~/.telecoder.
17
+ *
18
+ * ENV_PATH and INSTANCES_CONFIG still point at a single file directly, ahead
19
+ * of all this; their readers check them first.
20
+ */
21
+ import * as fs from 'fs';
22
+ import * as os from 'os';
23
+ import * as path from 'path';
24
+ import { PACKAGE_ROOT } from './install-mode.js';
25
+ /** The files whose presence next to package.json marks a checkout-style setup. */
26
+ export const CHECKOUT_CONFIG_FILES = ['.env', 'instances.json'];
27
+ /** The pure decision, for tests and for `telecoder doctor` to explain itself. */
28
+ export function resolveConfigHome({ packageRoot, env, homedir, exists }) {
29
+ const override = env.TELECODER_HOME?.trim();
30
+ if (override)
31
+ return { dir: path.resolve(override), source: 'override' };
32
+ if (CHECKOUT_CONFIG_FILES.some((name) => exists(path.join(packageRoot, name)))) {
33
+ return { dir: packageRoot, source: 'package-root' };
34
+ }
35
+ return { dir: path.join(homedir, '.telecoder'), source: 'home' };
36
+ }
37
+ let cached;
38
+ /**
39
+ * The config home for this process. Decided once: a .env created while the bot
40
+ * runs (by `telecoder init`, say) must not move it halfway through.
41
+ */
42
+ export function getConfigHomeInfo() {
43
+ cached ??= resolveConfigHome({
44
+ packageRoot: PACKAGE_ROOT,
45
+ env: process.env,
46
+ homedir: os.homedir(),
47
+ exists: fs.existsSync,
48
+ });
49
+ return cached;
50
+ }
51
+ export function getConfigHome() {
52
+ return getConfigHomeInfo().dir;
53
+ }
54
+ /** A file in the config home, e.g. `configFile('.env')`. */
55
+ export function configFile(name) {
56
+ return path.join(getConfigHome(), name);
57
+ }
58
+ /** Test seam: forget the cached decision. */
59
+ export function resetConfigHomeCache() {
60
+ cached = undefined;
61
+ }
62
+ //# sourceMappingURL=config-home.js.map