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,116 @@
1
+ /**
2
+ * Terminal I/O for `telecoder init`, behind an interface the wizard's tests
3
+ * replace with a script of answers.
4
+ *
5
+ * node:readline/promises, no prompt library. The one thing readline doesn't do
6
+ * is hide what is typed, so its output goes through a stream that can be
7
+ * muted: while a secret is read, the echo of each keystroke is dropped.
8
+ *
9
+ * Ctrl+C anywhere — at a prompt or while waiting on Telegram — aborts `signal`,
10
+ * and whatever was waiting rejects with an AbortError.
11
+ */
12
+ import { spawnSync } from 'child_process';
13
+ import * as readline from 'readline/promises';
14
+ import { Writable } from 'stream';
15
+ export class AbortedError extends Error {
16
+ constructor() {
17
+ super('Cancelled');
18
+ this.name = 'AbortError';
19
+ }
20
+ }
21
+ export function isAbort(error) {
22
+ return error instanceof Error && error.name === 'AbortError';
23
+ }
24
+ export function createTerminalPrompter(input = process.stdin, output = process.stdout) {
25
+ const interactive = Boolean(input.isTTY);
26
+ const controller = new AbortController();
27
+ let muted = false;
28
+ const echo = new Writable({
29
+ write(chunk, encoding, callback) {
30
+ if (!muted)
31
+ output.write(chunk, encoding);
32
+ callback();
33
+ },
34
+ });
35
+ let rl;
36
+ const open = () => {
37
+ if (rl)
38
+ return rl;
39
+ rl = readline.createInterface({ input, output: echo, terminal: interactive });
40
+ rl.on('SIGINT', () => controller.abort(new AbortedError()));
41
+ return rl;
42
+ };
43
+ const question = async (text, signal) => {
44
+ if (controller.signal.aborted)
45
+ throw new AbortedError();
46
+ const combined = signal ? AbortSignal.any([controller.signal, signal]) : controller.signal;
47
+ try {
48
+ return await open().question(text, { signal: combined });
49
+ }
50
+ catch (error) {
51
+ if (combined.aborted)
52
+ throw new AbortedError();
53
+ throw error;
54
+ }
55
+ };
56
+ const prompter = {
57
+ interactive,
58
+ signal: controller.signal,
59
+ say: (line = '') => { output.write(`${line}\n`); },
60
+ async ask(text, opts = {}) {
61
+ const hint = opts.default ? ` [${opts.default}]` : '';
62
+ const answer = (await question(`${text}${hint} `, opts.signal)).trim();
63
+ return answer || opts.default || '';
64
+ },
65
+ async secret(text) {
66
+ output.write(`${text} (input hidden) `);
67
+ muted = true;
68
+ try {
69
+ return (await question('')).trim();
70
+ }
71
+ finally {
72
+ muted = false;
73
+ output.write('\n');
74
+ }
75
+ },
76
+ async confirm(text, def) {
77
+ for (;;) {
78
+ const answer = (await question(`${text} ${def ? '[Y/n]' : '[y/N]'} `)).trim().toLowerCase();
79
+ if (!answer)
80
+ return def;
81
+ if (['y', 'yes'].includes(answer))
82
+ return true;
83
+ if (['n', 'no'].includes(answer))
84
+ return false;
85
+ }
86
+ },
87
+ async choose(text, choices, def) {
88
+ output.write(`${text}\n`);
89
+ choices.forEach((c, i) => output.write(` ${i + 1}) ${c.label}${c.key === def ? ' (default)' : ''}\n`));
90
+ for (;;) {
91
+ const answer = (await question(`Choose 1-${choices.length} [${choices.findIndex((c) => c.key === def) + 1}] `)).trim();
92
+ if (!answer)
93
+ return def;
94
+ const n = Number(answer);
95
+ if (Number.isInteger(n) && n >= 1 && n <= choices.length)
96
+ return choices[n - 1].key;
97
+ const byKey = choices.find((c) => c.key === answer.toLowerCase());
98
+ if (byKey)
99
+ return byKey.key;
100
+ }
101
+ },
102
+ runAttached(cmd, args) {
103
+ // readline holds the terminal in raw mode; give it back for the child.
104
+ rl?.close();
105
+ rl = undefined;
106
+ const result = spawnSync(cmd, args, { stdio: 'inherit' });
107
+ return result.status;
108
+ },
109
+ close() {
110
+ rl?.close();
111
+ rl = undefined;
112
+ },
113
+ };
114
+ return prompter;
115
+ }
116
+ //# sourceMappingURL=prompter.js.map
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The handful of Bot API calls `telecoder init` makes, over plain fetch.
3
+ *
4
+ * Not grammY: the wizard needs five methods, wants to own the long poll (so
5
+ * Ctrl+C can cancel it), and must never let the token reach a log line — every
6
+ * error leaving this module has been through redactSecrets, and the token
7
+ * itself is replaced too, in case Telegram ever changes its shape.
8
+ *
9
+ * TELECODER_TELEGRAM_API_ROOT points the calls at another server. It exists for
10
+ * tests and for trying the wizard against a fake Telegram; the bot doesn't read
11
+ * it, and nothing else should set it.
12
+ */
13
+ import { redactSecrets } from '../../utils/sanitize.js';
14
+ export const DEFAULT_API_ROOT = 'https://api.telegram.org';
15
+ /** Telegram answered, with ok: false. */
16
+ export class TelegramApiError extends Error {
17
+ method;
18
+ code;
19
+ description;
20
+ constructor(method, code, description) {
21
+ super(`${method} failed (${code}: ${description})`);
22
+ this.method = method;
23
+ this.code = code;
24
+ this.description = description;
25
+ this.name = 'TelegramApiError';
26
+ }
27
+ }
28
+ /** Telegram couldn't be reached at all. The message is already redacted. */
29
+ export class TelegramNetworkError extends Error {
30
+ constructor(message) {
31
+ super(message);
32
+ this.name = 'TelegramNetworkError';
33
+ }
34
+ }
35
+ export function createTelegramClient(token, { apiRoot = DEFAULT_API_ROOT, fetchImpl = fetch } = {}) {
36
+ const base = `${apiRoot.replace(/\/+$/, '')}/bot${token}`;
37
+ const scrub = (text) => redactSecrets(text.replaceAll(token, '<token>'));
38
+ async function call(method, params = {}, signal, timeoutMs = 15_000) {
39
+ const timeout = AbortSignal.timeout(timeoutMs);
40
+ let res;
41
+ try {
42
+ res = await fetchImpl(`${base}/${method}`, {
43
+ method: 'POST',
44
+ headers: { 'content-type': 'application/json' },
45
+ body: JSON.stringify(params),
46
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
47
+ });
48
+ }
49
+ catch (error) {
50
+ if (signal?.aborted)
51
+ throw signal.reason ?? error;
52
+ throw new TelegramNetworkError(scrub(describeFetchError(error)));
53
+ }
54
+ let body;
55
+ try {
56
+ body = await res.json();
57
+ }
58
+ catch {
59
+ throw new TelegramApiError(method, res.status, scrub(`HTTP ${res.status}, not a Bot API answer`));
60
+ }
61
+ if (!body.ok) {
62
+ throw new TelegramApiError(method, body.error_code ?? res.status, scrub(body.description ?? `HTTP ${res.status}`));
63
+ }
64
+ return body.result;
65
+ }
66
+ return {
67
+ getMe: () => call('getMe'),
68
+ getWebhookInfo: () => call('getWebhookInfo'),
69
+ deleteWebhook: async () => { await call('deleteWebhook'); },
70
+ // No allowed_updates: Telegram remembers it for the bot, and a narrow list
71
+ // here would quietly stop the bot getting button presses later.
72
+ getUpdates: ({ offset, timeout = 0, signal }) => call('getUpdates', { offset, timeout }, signal, (timeout + 15) * 1000),
73
+ sendMessage: async (chatId, text, entities) => {
74
+ await call('sendMessage', { chat_id: chatId, text, ...(entities ? { entities } : {}) });
75
+ },
76
+ };
77
+ }
78
+ /** "fetch failed" says nothing; its cause (ENOTFOUND, ECONNREFUSED…) does. */
79
+ function describeFetchError(error) {
80
+ let current = error;
81
+ let best = error instanceof Error ? error.message : String(error);
82
+ for (let depth = 0; depth < 4 && current instanceof Error; depth++) {
83
+ if (current.message)
84
+ best = current.message;
85
+ const code = current.code;
86
+ if (typeof code === 'string' && !best.includes(code))
87
+ best = `${best} (${code})`;
88
+ current = current.cause;
89
+ }
90
+ if (error instanceof Error && error.name === 'TimeoutError')
91
+ return 'timed out';
92
+ return best;
93
+ }
94
+ //# sourceMappingURL=telegram.js.map
@@ -0,0 +1,212 @@
1
+ /**
2
+ * The service files `telecoder service install` writes, rendered from a
3
+ * resolved spec. Pure: no fs, no environment — everything that varies by
4
+ * machine is decided in ../commands/service.ts and handed in here, which is
5
+ * what lets the tests pin the output line by line.
6
+ */
7
+ import * as path from 'path';
8
+ import { EXIT_CONFIG, SERVICE_MANAGER_ENV } from '../../utils/exit-codes.js';
9
+ import { RESTART_EXIT_CODE } from '../../utils/systemd.js';
10
+ export const DEFAULT_SERVICE_NAME = 'telecoder';
11
+ // ── Names ───────────────────────────────────────────────────────
12
+ /**
13
+ * Check a --name and strip a `.service` the user may have typed. Returns the
14
+ * bare name, or an error message.
15
+ */
16
+ export function normalizeServiceName(raw) {
17
+ const name = raw.trim().replace(/\.service$/, '');
18
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(name)) {
19
+ return { error: `Invalid service name "${raw}": use letters, digits, ".", "_" and "-" (e.g. telecoder-work).` };
20
+ }
21
+ return { name };
22
+ }
23
+ export const systemdUnitName = (name) => `${name}.service`;
24
+ export const launchdLabel = (name) => `dev.telecoder.${name}`;
25
+ // ── PATH ────────────────────────────────────────────────────────
26
+ const DEFAULT_PATH = {
27
+ linux: ['/usr/local/bin', '/usr/bin', '/bin'],
28
+ darwin: ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin'],
29
+ };
30
+ /**
31
+ * The PATH baked into the unit: the required directories, then the installing
32
+ * shell's PATH, then the system defaults — deduplicated, absolute entries
33
+ * only. A project's node_modules/.bin is left out: it belongs to wherever the
34
+ * install happened to be run from, not to the bot.
35
+ */
36
+ export function buildServicePath({ required, inherited, platform, keep = () => true }) {
37
+ const seen = new Set();
38
+ const out = [];
39
+ const add = (dir, check) => {
40
+ const clean = dir.replace(/\/+$/, '') || '/';
41
+ if (!path.isAbsolute(clean) || /[\n\r:]/.test(clean) || seen.has(clean))
42
+ return;
43
+ if (clean.split('/').includes('node_modules'))
44
+ return;
45
+ if (check && !keep(clean))
46
+ return;
47
+ seen.add(clean);
48
+ out.push(clean);
49
+ };
50
+ for (const dir of required)
51
+ add(dir, false);
52
+ for (const dir of (inherited ?? '').split(':'))
53
+ if (dir)
54
+ add(dir, true);
55
+ for (const dir of DEFAULT_PATH[platform])
56
+ add(dir, false);
57
+ return out.join(':');
58
+ }
59
+ // ── systemd ─────────────────────────────────────────────────────
60
+ /** A line break in a path would end the directive and start another. */
61
+ function assertOneLine(value) {
62
+ if (/[\n\r]/.test(value))
63
+ throw new Error(`A line break in "${value}" can't go in a service file`);
64
+ return value;
65
+ }
66
+ /** `%` starts a specifier in almost every unit setting. */
67
+ const escapeSpecifiers = (value) => assertOneLine(value).replace(/%/g, '%%');
68
+ /**
69
+ * One ExecStart= word: quoted only when it has to be, `%` escaped, and `$`
70
+ * escaped in the arguments — systemd expands variables there but not in the
71
+ * executable's own path (systemd-analyze verify confirms both).
72
+ */
73
+ export function systemdExecArg(value, isExecutable = false) {
74
+ const specifiersEscaped = escapeSpecifiers(value);
75
+ const escaped = isExecutable ? specifiersEscaped : specifiersEscaped.replace(/\$/g, '$$$$');
76
+ if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(escaped))
77
+ return escaped;
78
+ return `"${escaped.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
79
+ }
80
+ /** One `Environment=` line, always quoted. */
81
+ export function systemdEnvironment(key, value) {
82
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
83
+ throw new Error(`Invalid environment variable name: ${key}`);
84
+ const escaped = escapeSpecifiers(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
85
+ return `Environment="${key}=${escaped}"`;
86
+ }
87
+ export function renderSystemdUnit(spec) {
88
+ const exec = [systemdExecArg(spec.nodePath, true), systemdExecArg(spec.cliPath), 'start'].join(' ');
89
+ return [
90
+ '# Written by `telecoder service install`. Run it again to rewrite this file,',
91
+ '# `telecoder service uninstall` to remove it. No secrets here: the bot reads',
92
+ '# its token from the .env in WorkingDirectory.',
93
+ '[Unit]',
94
+ 'Description=TeleCoder (Claude Code from Telegram)',
95
+ 'Documentation=https://telecoder.dev',
96
+ // A bot that keeps dying within seconds stops after 20 tries in 5 minutes
97
+ // instead of retrying forever; `telecoder service restart` resets that.
98
+ 'StartLimitIntervalSec=300',
99
+ 'StartLimitBurst=20',
100
+ '',
101
+ '[Service]',
102
+ 'Type=simple',
103
+ `WorkingDirectory=${escapeSpecifiers(spec.workingDirectory)}`,
104
+ `ExecStart=${exec}`,
105
+ systemdEnvironment('PATH', spec.pathEnv),
106
+ ...spec.env.map(([key, value]) => systemdEnvironment(key, value)),
107
+ systemdEnvironment(SERVICE_MANAGER_ENV, 'systemd'),
108
+ '# always, not on-failure: /restartbot exits for systemd to bring the bot back.',
109
+ '# `systemctl --user stop` is still a stop — systemd never restarts a unit it',
110
+ '# was told to stop.',
111
+ 'Restart=always',
112
+ 'RestartSec=5',
113
+ `# ${RESTART_EXIT_CODE} is the exit /restartbot uses: logged as a clean exit, restarted all the same.`,
114
+ `SuccessExitStatus=${RESTART_EXIT_CODE}`,
115
+ `# ${EXIT_CONFIG} is a configuration problem (a missing setting, a rejected token):`,
116
+ '# starting again would only print the same error. Fix it, then',
117
+ '# `telecoder service restart`.',
118
+ `RestartPreventExitStatus=${EXIT_CONFIG}`,
119
+ '',
120
+ '[Install]',
121
+ 'WantedBy=default.target',
122
+ '',
123
+ ].join('\n');
124
+ }
125
+ // ── launchd ─────────────────────────────────────────────────────
126
+ const xml = (value) => assertOneLine(value)
127
+ .replace(/&/g, '&amp;')
128
+ .replace(/</g, '&lt;')
129
+ .replace(/>/g, '&gt;')
130
+ .replace(/"/g, '&quot;');
131
+ /**
132
+ * The LaunchAgent. KeepAlive restarts on any non-zero exit (so /restartbot's
133
+ * 75 and a crash both come back) and not on a zero one — launchd has no way to
134
+ * single out one exit code the way RestartPreventExitStatus= does, so a bot
135
+ * stopped by its config exits 0 under launchd instead (see
136
+ * utils/exit-codes.ts).
137
+ */
138
+ export function renderLaunchdPlist(spec) {
139
+ const env = [['PATH', spec.pathEnv], ...spec.env, [SERVICE_MANAGER_ENV, 'launchd']];
140
+ return [
141
+ '<?xml version="1.0" encoding="UTF-8"?>',
142
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
143
+ '<!-- Written by `telecoder service install`; `telecoder service uninstall` removes it. -->',
144
+ '<plist version="1.0">',
145
+ '<dict>',
146
+ ' <key>Label</key>',
147
+ ` <string>${xml(launchdLabel(spec.name))}</string>`,
148
+ ' <key>ProgramArguments</key>',
149
+ ' <array>',
150
+ ...[spec.nodePath, spec.cliPath, 'start'].map((arg) => ` <string>${xml(arg)}</string>`),
151
+ ' </array>',
152
+ ' <key>WorkingDirectory</key>',
153
+ ` <string>${xml(spec.workingDirectory)}</string>`,
154
+ ' <key>EnvironmentVariables</key>',
155
+ ' <dict>',
156
+ ...env.flatMap(([key, value]) => [` <key>${xml(key)}</key>`, ` <string>${xml(value)}</string>`]),
157
+ ' </dict>',
158
+ ' <key>RunAtLoad</key>',
159
+ ' <true/>',
160
+ ' <key>KeepAlive</key>',
161
+ ' <dict>',
162
+ ' <key>SuccessfulExit</key>',
163
+ ' <false/>',
164
+ ' </dict>',
165
+ ' <key>ThrottleInterval</key>',
166
+ ' <integer>10</integer>',
167
+ ' <key>StandardOutPath</key>',
168
+ ` <string>${xml(spec.logFile)}</string>`,
169
+ ' <key>StandardErrorPath</key>',
170
+ ` <string>${xml(spec.logFile)}</string>`,
171
+ '</dict>',
172
+ '</plist>',
173
+ '',
174
+ ].join('\n');
175
+ }
176
+ // ── Diff ────────────────────────────────────────────────────────
177
+ /**
178
+ * The lines that differ between two versions of a file, `- ` for removed and
179
+ * `+ ` for added, in file order. A plain LCS: service files are a few dozen
180
+ * lines.
181
+ */
182
+ export function lineDiff(before, after) {
183
+ const a = before.split('\n');
184
+ const b = after.split('\n');
185
+ const lcs = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
186
+ for (let i = a.length - 1; i >= 0; i--) {
187
+ for (let j = b.length - 1; j >= 0; j--) {
188
+ lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
189
+ }
190
+ }
191
+ const out = [];
192
+ let i = 0;
193
+ let j = 0;
194
+ while (i < a.length && j < b.length) {
195
+ if (a[i] === b[j]) {
196
+ i++;
197
+ j++;
198
+ }
199
+ else if (lcs[i + 1][j] >= lcs[i][j + 1]) {
200
+ out.push(`- ${a[i++]}`);
201
+ }
202
+ else {
203
+ out.push(`+ ${b[j++]}`);
204
+ }
205
+ }
206
+ while (i < a.length)
207
+ out.push(`- ${a[i++]}`);
208
+ while (j < b.length)
209
+ out.push(`+ ${b[j++]}`);
210
+ return out;
211
+ }
212
+ //# sourceMappingURL=render.js.map
package/dist/cli.js ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The `telecoder` command (package.json "bin"). Everything past the shebang is
4
+ * in ./cli/: dispatch.ts parses the arguments, ./cli/commands/ has one module
5
+ * per subcommand.
6
+ */
7
+ // First, so an old Node gets a message about its version rather than a crash.
8
+ import './node-version-check.js';
9
+ import { dispatch } from './cli/dispatch.js';
10
+ dispatch(process.argv.slice(2)).then((code) => {
11
+ // No code: the command handed the process to the bot, which exits itself.
12
+ if (typeof code === 'number')
13
+ process.exitCode = code;
14
+ }, (error) => {
15
+ console.error(error instanceof Error ? error.message : String(error));
16
+ process.exitCode = 1;
17
+ });
18
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1,107 @@
1
+ /**
2
+ * The message a bot prints when its configuration stops it from starting.
3
+ *
4
+ * Kept free of config imports so config.ts can use it before it has a config,
5
+ * and tests can call it directly. What it replaces was Zod's own report, which
6
+ * a first run always hit: with no .env at all, TELEGRAM_BOT_TOKEN fails as
7
+ * `invalid_type` before the schema's friendlier `.min()` message is reached,
8
+ * and the user got a JSON dump naming an "expected string, received undefined"
9
+ * rather than where to get a token.
10
+ *
11
+ * So this says three things in plain words: which .env was read (or that there
12
+ * wasn't one), what is missing or wrong with one line each on how to fix it,
13
+ * and how to make a .env if there is none.
14
+ */
15
+ /** How to get each required value, for the keys a fresh install has to fill in. */
16
+ export const HOW_TO_GET = {
17
+ TELEGRAM_BOT_TOKEN: 'Create a bot by messaging @BotFather on Telegram (/newbot), and paste the token it gives you.',
18
+ ALLOWED_USER_IDS: 'Your numeric Telegram user id, like 412345678 (not your @username). Message @userinfobot on ' +
19
+ 'Telegram to get it; a TeleCoder bot that is already running also tells you yours when you send it /start.',
20
+ };
21
+ /**
22
+ * Turn schema issues into one problem per variable, in a sentence each.
23
+ *
24
+ * A variable that is unset or blank is "not set", whatever check caught it —
25
+ * the `invalid_type` an absent key gets and the `.min(1)` an empty one gets are
26
+ * the same mistake. Anything else keeps the schema's own message, which for the
27
+ * id lists and the token is already written for a person (see id-list.ts and
28
+ * bot-token.ts). Only the first issue per variable is kept: a blank value
29
+ * trips every check after `.min(1)` too, and saying so twice helps nobody.
30
+ *
31
+ * Values are never echoed here. One of these variables is the bot token.
32
+ */
33
+ export function problemsFromIssues(issues, env) {
34
+ const seen = new Set();
35
+ const problems = [];
36
+ for (const issue of issues) {
37
+ const key = String(issue.path[0] ?? '(unknown)');
38
+ if (seen.has(key))
39
+ continue;
40
+ seen.add(key);
41
+ const raw = env[key];
42
+ if (raw === undefined || raw.trim() === '') {
43
+ problems.push({ key, message: `${key} is not set.` });
44
+ continue;
45
+ }
46
+ const message = issue.message.startsWith(key) ? issue.message : `${key}: ${issue.message}`;
47
+ problems.push({ key, message: /[.!?]$/.test(message) ? message : `${message}.` });
48
+ }
49
+ return problems;
50
+ }
51
+ /**
52
+ * The whole report, ready to print.
53
+ *
54
+ * `instanceName` is set for a bot the multi-bot launcher started: its token
55
+ * comes from instances.json rather than .env, and saying so saves a hunt for
56
+ * a TELEGRAM_BOT_TOKEN line that was never meant to be there.
57
+ */
58
+ export function formatConfigReport(problems, envFile, options = {}) {
59
+ const lines = [];
60
+ const who = options.instanceName ? `The bot "${options.instanceName}"` : 'TeleCoder';
61
+ lines.push(`❌ ${who} can't start: its configuration needs fixing.`);
62
+ lines.push('');
63
+ switch (envFile.status) {
64
+ case 'loaded':
65
+ lines.push(`Settings were read from ${envFile.path}`);
66
+ break;
67
+ case 'missing':
68
+ lines.push(`No .env file was found at ${envFile.path}, so only the environment was read.`);
69
+ break;
70
+ case 'unreadable':
71
+ lines.push(`The .env file at ${envFile.path} couldn't be read, so only the environment was read.`);
72
+ break;
73
+ }
74
+ if (options.instanceName) {
75
+ lines.push('It was started by the multi-bot launcher: its token comes from instances.json, and its other settings from there and from .env.');
76
+ }
77
+ lines.push('');
78
+ for (const problem of problems) {
79
+ lines.push(` • ${problem.message}`);
80
+ const how = HOW_TO_GET[problem.key];
81
+ // The id-list messages already say where to get an id; repeating it under
82
+ // them is noise. A missing value has said nothing yet.
83
+ if (how && !problem.message.includes('@userinfobot') && !problem.message.includes('@BotFather')) {
84
+ lines.push(` ${how}`);
85
+ }
86
+ }
87
+ lines.push('');
88
+ if (options.instanceName) {
89
+ lines.push('Fix it in instances.json, and the launcher starts the bot again on its own; ' +
90
+ 'or fix it in .env, and restart the launcher.');
91
+ }
92
+ else if (envFile.status === 'loaded') {
93
+ lines.push(`Fix ${problems.length === 1 ? 'it' : 'these'} in ${envFile.path}, then start TeleCoder again.`);
94
+ }
95
+ else {
96
+ lines.push('To create one, run `telecoder init`, or copy .env.example to .env and fill in the values above. ' +
97
+ 'Then start TeleCoder again.');
98
+ }
99
+ return lines.join('\n');
100
+ }
101
+ /** What dotenv's result says about the file it was pointed at. */
102
+ export function envFileStatus(result) {
103
+ if (!result.error)
104
+ return 'loaded';
105
+ return result.error.code === 'ENOENT' ? 'missing' : 'unreadable';
106
+ }
107
+ //# sourceMappingURL=config-report.js.map