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,91 @@
1
+ import * as os from 'os';
2
+ const HOME_DIR = os.homedir();
3
+ let USERNAME = '';
4
+ try {
5
+ USERNAME = os.userInfo().username;
6
+ }
7
+ catch {
8
+ USERNAME = '';
9
+ }
10
+ /**
11
+ * Sanitize a string by replacing sensitive paths and usernames.
12
+ * Useful for error messages and logs to prevent information leakage.
13
+ */
14
+ export function sanitizePath(str) {
15
+ if (!str)
16
+ return str;
17
+ let sanitized = str;
18
+ // Replace home directory with ~
19
+ if (HOME_DIR) {
20
+ sanitized = sanitized.replace(new RegExp(escapeRegExp(HOME_DIR), 'g'), '~');
21
+ }
22
+ // Replace username if it appears in paths
23
+ if (USERNAME && USERNAME.length > 2) {
24
+ // Only replace in path-like contexts to avoid false positives
25
+ sanitized = sanitized.replace(new RegExp(`/Users/${escapeRegExp(USERNAME)}`, 'g'), '/Users/<user>');
26
+ sanitized = sanitized.replace(new RegExp(`/home/${escapeRegExp(USERNAME)}`, 'g'), '/home/<user>');
27
+ }
28
+ return sanitized;
29
+ }
30
+ /**
31
+ * Secrets that turn up in error messages: a failed request echoes its URL, a
32
+ * failed command echoes its arguments. Each pattern keeps enough context
33
+ * (a `bot` prefix, a key name) to say what was there, and drops the value.
34
+ */
35
+ const SECRET_PATTERNS = [
36
+ // Telegram bot token, bare or as the `bot<token>` path segment of an API URL.
37
+ [/\d{6,}:[A-Za-z0-9_-]{30,}/g, '<telegram-token>'],
38
+ // Anthropic, OpenAI and similar `sk-` keys.
39
+ [/\bsk-(?:ant-)?[A-Za-z0-9_-]{20,}/g, '<api-key>'],
40
+ // GitHub tokens.
41
+ [/\bgh[pousr]_[A-Za-z0-9]{30,}/g, '<github-token>'],
42
+ [/\bgithub_pat_[A-Za-z0-9_]{30,}/g, '<github-token>'],
43
+ // Slack, AWS and Google API keys.
44
+ [/\bxox[abposr]-[A-Za-z0-9-]{10,}/g, '<slack-token>'],
45
+ [/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, '<aws-key>'],
46
+ [/\bAIza[0-9A-Za-z_-]{35}/g, '<google-key>'],
47
+ // Authorization headers.
48
+ [/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{16,}/gi, '$1 <redacted>'],
49
+ // Credentials in a URL: scheme://user:password@host
50
+ [/([a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/gi, '$1<redacted>@'],
51
+ // key=value and key: value pairs whose key names a secret.
52
+ [
53
+ /\b([A-Za-z0-9_]*(?:token(?!s)|secret|password|passwd|api[_-]?key|access[_-]?key)[A-Za-z0-9_]*)(["']?\s*[=:]\s*["']?)[^\s"'&,;]{6,}/gi,
54
+ '$1$2<redacted>',
55
+ ],
56
+ ];
57
+ /**
58
+ * Replace tokens, API keys and credentials in a string with placeholders.
59
+ * Applied by sanitizeError; use directly on anything else headed for a chat
60
+ * or a log that might contain a URL or command line.
61
+ */
62
+ export function redactSecrets(str) {
63
+ if (!str)
64
+ return str;
65
+ let out = str;
66
+ for (const [pattern, replacement] of SECRET_PATTERNS) {
67
+ out = out.replace(pattern, replacement);
68
+ }
69
+ return out;
70
+ }
71
+ /**
72
+ * Extract and sanitize an error message for user-facing display.
73
+ * Returns a sanitized message string with secrets and sensitive paths removed.
74
+ * Note: Does not sanitize stack traces — avoid logging raw error objects to users.
75
+ */
76
+ export function sanitizeError(error) {
77
+ if (error instanceof Error) {
78
+ return sanitizePath(redactSecrets(error.message));
79
+ }
80
+ if (typeof error === 'string') {
81
+ return sanitizePath(redactSecrets(error));
82
+ }
83
+ return 'Unknown error';
84
+ }
85
+ /**
86
+ * Escape special regex characters in a string.
87
+ */
88
+ function escapeRegExp(str) {
89
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
90
+ }
91
+ //# sourceMappingURL=sanitize.js.map
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Session key utilities for forum topic support.
3
+ *
4
+ * In regular chats, the session key is just the chatId as a string: "12345"
5
+ * In forum topics, it combines chatId and threadId: "12345:42"
6
+ * This allows each forum topic to have an independent session.
7
+ */
8
+ export function buildSessionKey(chatId, threadId) {
9
+ return threadId !== undefined ? `${chatId}:${threadId}` : String(chatId);
10
+ }
11
+ export function parseSessionKey(key) {
12
+ const colonIdx = key.indexOf(':');
13
+ if (colonIdx === -1) {
14
+ return { chatId: Number(key) };
15
+ }
16
+ return {
17
+ chatId: Number(key.slice(0, colonIdx)),
18
+ threadId: Number(key.slice(colonIdx + 1)),
19
+ };
20
+ }
21
+ /** The chat a settings scope belongs to. */
22
+ export function scopeChatId(scope) {
23
+ return typeof scope === 'number' ? scope : parseSessionKey(scope).chatId;
24
+ }
25
+ /**
26
+ * Extract session key info from a Grammy context.
27
+ * Uses message_thread_id only when is_topic_message is true (forum topics).
28
+ */
29
+ export function getSessionKeyFromCtx(ctx) {
30
+ const chatId = ctx.chat?.id;
31
+ if (!chatId)
32
+ return null;
33
+ const msg = ctx.message ?? ctx.callbackQuery?.message;
34
+ const threadId = msg?.is_topic_message ? msg.message_thread_id : undefined;
35
+ return { chatId, threadId, sessionKey: buildSessionKey(chatId, threadId) };
36
+ }
37
+ //# sourceMappingURL=session-key.js.map
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Recognising a launcher that is running code the build has already replaced.
3
+ *
4
+ * /rebuildbot rebuilds every file and then has the launcher respawn its
5
+ * workers. A respawned worker is a fresh isolate that re-imports dist from
6
+ * disk, so worker-side changes are live the moment it comes back. The launcher
7
+ * is the exception: it is the process the workers are threads in, and the copy
8
+ * of dist/launcher.js it loaded at startup stays in memory until the process
9
+ * manager restarts it. Nothing said so, which is the problem — a rebuild that
10
+ * changed the launcher reported success and changed nothing, quietly, for as
11
+ * long as the process lived.
12
+ *
13
+ * So the launcher fingerprints its own module graph at startup, compares it
14
+ * against the same fingerprint taken after a build, and the rebuild reply says
15
+ * when the two differ.
16
+ */
17
+ import { createHash } from 'crypto';
18
+ import { readFileSync, existsSync } from 'fs';
19
+ import * as path from 'path';
20
+ /**
21
+ * Imports of files in this repo, in all three shapes the compiler emits:
22
+ * `from './x.js'`, a side-effect `import './x.js'`, and a dynamic
23
+ * `import('./x.js')`. Package imports are left out — their code can't change
24
+ * without a reinstall, which is its own restart.
25
+ */
26
+ const LOCAL_IMPORT = /(?:\bfrom|\bimport)\s*\(?\s*['"](\.[^'"]+)['"]/g;
27
+ /** A pm2 app name we're willing to paste into a command we show the user. */
28
+ const SAFE_APP_NAME = /^[\w.@-]{1,64}$/;
29
+ /**
30
+ * Compiled code imports `./x.js`. So does the TypeScript it was compiled from,
31
+ * and under tsx that specifier has to land on `./x.ts` instead.
32
+ */
33
+ function resolveLocal(fromFile, specifier) {
34
+ const target = path.resolve(path.dirname(fromFile), specifier);
35
+ if (existsSync(target))
36
+ return target;
37
+ const asTs = target.replace(/\.js$/, '.ts');
38
+ return existsSync(asTs) ? asTs : null;
39
+ }
40
+ /**
41
+ * A hash of `entry` and everything it imports from this repo.
42
+ *
43
+ * Contents, not timestamps: tsc rewrites every output on every build, so the
44
+ * mtimes always differ — comparing those would report a changed launcher after
45
+ * every rebuild, including the ones that changed nothing about it.
46
+ *
47
+ * Returns '' when the entry can't be read, which callers should take as "no
48
+ * idea" rather than "changed". A file that disappears mid-graph just stops
49
+ * contributing, which changes the hash on its own.
50
+ */
51
+ export function fingerprintModuleGraph(entry) {
52
+ const sources = new Map();
53
+ const walk = (file) => {
54
+ if (sources.has(file))
55
+ return;
56
+ let source;
57
+ try {
58
+ source = readFileSync(file, 'utf-8');
59
+ }
60
+ catch {
61
+ return;
62
+ }
63
+ sources.set(file, source);
64
+ for (const [, specifier] of source.matchAll(LOCAL_IMPORT)) {
65
+ const target = resolveLocal(file, specifier);
66
+ if (target)
67
+ walk(target);
68
+ }
69
+ };
70
+ walk(entry);
71
+ if (!sources.has(entry))
72
+ return '';
73
+ const root = path.dirname(entry);
74
+ const hash = createHash('sha256');
75
+ for (const file of [...sources.keys()].sort()) {
76
+ hash.update(path.relative(root, file));
77
+ hash.update('\0');
78
+ hash.update(sources.get(file));
79
+ hash.update('\0');
80
+ }
81
+ return hash.digest('hex');
82
+ }
83
+ /**
84
+ * Has the launcher's code changed under it?
85
+ *
86
+ * Only ever true when both fingerprints could be read. An empty one means we
87
+ * couldn't tell, and "couldn't tell" must not reach anyone as "restart your
88
+ * launcher" — the check runs on every rebuild, restart and status, so being
89
+ * wrong in that direction would train people to ignore it.
90
+ */
91
+ export function launcherHasChanged(atStartup, now) {
92
+ return atStartup !== '' && now !== '' && atStartup !== now;
93
+ }
94
+ /**
95
+ * What to tell someone to do about it, phrased to drop into a sentence.
96
+ *
97
+ * pm2 hands every process it manages its app name and id, so under pm2 we can
98
+ * name the exact command. Anywhere else — systemd, a bare
99
+ * `npm run start:multi`, a terminal — all we know is that the process has to
100
+ * go down and come back. The name is checked before it goes into a command we
101
+ * hand the user, since it arrives from the environment.
102
+ */
103
+ export function launcherRestartHint(env = process.env) {
104
+ const app = env.pm_id !== undefined ? env.name : undefined;
105
+ if (app && SAFE_APP_NAME.test(app))
106
+ return `run "pm2 restart ${app}"`;
107
+ return 'restart the launcher process';
108
+ }
109
+ //# sourceMappingURL=stale-launcher.js.map
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Move the pre-rename state directory `~/.claudegram` to `~/.telecoder`.
3
+ *
4
+ * TeleCoder was called Claudegram until July 2026, and its state directory kept
5
+ * the old name for a while after. The move is a rename within the home
6
+ * directory, so it is instant and every file comes across as it was. A symlink
7
+ * is left at the old path for anything that still has that path: a process
8
+ * started before the move, or a pty spawned with a script inside the directory
9
+ * (the CCR shim), carries on through the link.
10
+ *
11
+ * Only the launcher and a single-bot `npm start` call this, before any bot is
12
+ * running, so no live bot sees the directory move. Workers never call it: see
13
+ * getStateDir() in json-store.ts for how they cope with an unmoved directory.
14
+ */
15
+ import * as fs from 'fs';
16
+ import * as os from 'os';
17
+ import * as path from 'path';
18
+ import { LEGACY_STATE_DIR_NAME, STATE_DIR_NAME, isRealDirectory } from './json-store.js';
19
+ export function migrateLegacyStateDir(home = os.homedir()) {
20
+ const legacy = path.join(home, LEGACY_STATE_DIR_NAME);
21
+ const current = path.join(home, STATE_DIR_NAME);
22
+ if (!isRealDirectory(legacy))
23
+ return { outcome: 'none' };
24
+ // Something is already at the new path. An empty directory holds nothing to
25
+ // lose, so it makes way; anything else might be state, so both are left alone.
26
+ if (pathExists(current)) {
27
+ if (!isEmptyDirectory(current))
28
+ return { outcome: 'conflict' };
29
+ try {
30
+ fs.rmdirSync(current);
31
+ }
32
+ catch (err) {
33
+ return { outcome: 'failed', error: describe(err) };
34
+ }
35
+ }
36
+ try {
37
+ fs.renameSync(legacy, current);
38
+ }
39
+ catch (err) {
40
+ return { outcome: 'failed', error: describe(err) };
41
+ }
42
+ // Relative, so the link still resolves if the home directory is mounted or
43
+ // moved somewhere else.
44
+ try {
45
+ fs.symlinkSync(STATE_DIR_NAME, legacy);
46
+ return { outcome: 'moved', linked: true };
47
+ }
48
+ catch {
49
+ return { outcome: 'moved', linked: false };
50
+ }
51
+ }
52
+ /** Run the move and log anything worth knowing about it under `label`. */
53
+ export function migrateLegacyStateDirAndLog(label, home) {
54
+ const result = migrateLegacyStateDir(home);
55
+ const from = `~/${LEGACY_STATE_DIR_NAME}`;
56
+ const to = `~/${STATE_DIR_NAME}`;
57
+ switch (result.outcome) {
58
+ case 'moved':
59
+ console.log(`[${label}] Moved ${from} to ${to}${result.linked ? ` (${from} links to it)` : ''}`);
60
+ break;
61
+ case 'conflict':
62
+ console.warn(`[${label}] Both ${from} and ${to} exist — using ${to}. Move anything you still need out of ${from} by hand.`);
63
+ break;
64
+ case 'failed':
65
+ console.error(`[${label}] Could not move ${from} to ${to} (${result.error}) — still using ${from}`);
66
+ break;
67
+ case 'none':
68
+ break;
69
+ }
70
+ return result;
71
+ }
72
+ function pathExists(p) {
73
+ try {
74
+ fs.lstatSync(p);
75
+ return true;
76
+ }
77
+ catch {
78
+ return false;
79
+ }
80
+ }
81
+ function isEmptyDirectory(p) {
82
+ try {
83
+ return isRealDirectory(p) && fs.readdirSync(p).length === 0;
84
+ }
85
+ catch {
86
+ return false;
87
+ }
88
+ }
89
+ function describe(err) {
90
+ return err instanceof Error ? err.message : String(err);
91
+ }
92
+ //# sourceMappingURL=state-dir-migration.js.map
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Whether this process is a systemd service — and whether systemd will bring
3
+ * it back if it exits.
4
+ *
5
+ * This matters because the botctl restart dance cannot work under systemd.
6
+ * `spawn(..., { detached: true })` escapes the process group and session but
7
+ * not the cgroup, so the helper that would start the replacement stays inside
8
+ * the unit. The moment the bot exits, systemd deactivates the unit and (with
9
+ * the default `KillMode=control-group`) reaps everything left in it — the
10
+ * helper included, before it ever gets to the start half of its job. The bot
11
+ * has to exit and let systemd restart it instead, which means first knowing
12
+ * whether systemd actually will.
13
+ */
14
+ import { execFile } from 'child_process';
15
+ import * as fs from 'fs';
16
+ /**
17
+ * Exit code that asks systemd for a restart: EX_TEMPFAIL, conventionally
18
+ * "temporary failure, try again". Non-zero on purpose — it is the only value
19
+ * that both `Restart=always` and `Restart=on-failure` act on, so an install
20
+ * whose unit predates this code still restarts correctly.
21
+ */
22
+ export const RESTART_EXIT_CODE = 75;
23
+ /**
24
+ * True only for the process systemd forked for ExecStart.
25
+ *
26
+ * `INVOCATION_ID` alone is not enough: it is inherited, so every Claude
27
+ * session and shell the bot spawns would also claim to be the service.
28
+ * `SYSTEMD_EXEC_PID` is inherited too, but it only *equals* the reader's own
29
+ * pid in the one process systemd started.
30
+ */
31
+ export function isSystemdService() {
32
+ return (Boolean(process.env.INVOCATION_ID) &&
33
+ process.env.SYSTEMD_EXEC_PID === String(process.pid));
34
+ }
35
+ /** A user manager nests its units under `user@<uid>.service`. */
36
+ const USER_MANAGER = /^user@\d+\.service$/;
37
+ /**
38
+ * Pull the unit out of the contents of `/proc/self/cgroup`.
39
+ *
40
+ * Lines are `hierarchy:controllers:path`; cgroup v2 emits a single `0::<path>`
41
+ * line, v1 one line per controller. The unit is the deepest `.service`
42
+ * component of the path — deepest because a user unit sits below the
43
+ * `user@<uid>.service` manager that runs it, and that manager is not us.
44
+ */
45
+ export function parseCgroupUnit(cgroup) {
46
+ for (const line of cgroup.split('\n')) {
47
+ const cgroupPath = line.split(':')[2];
48
+ if (!cgroupPath)
49
+ continue;
50
+ const segments = cgroupPath.split('/').filter(Boolean);
51
+ const name = [...segments]
52
+ .reverse()
53
+ .find((segment) => segment.endsWith('.service') && !USER_MANAGER.test(segment));
54
+ if (!name)
55
+ continue;
56
+ return { name, user: segments.some((segment) => USER_MANAGER.test(segment)) };
57
+ }
58
+ return null;
59
+ }
60
+ /** The unit this process runs as, or null if it cannot be determined. */
61
+ export function getSystemdUnit() {
62
+ try {
63
+ return parseCgroupUnit(fs.readFileSync('/proc/self/cgroup', 'utf8'));
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ }
69
+ /**
70
+ * Ask systemd how the unit is configured, or null if systemctl cannot answer.
71
+ */
72
+ export function getRestartBehaviour(unit) {
73
+ return new Promise((resolve) => {
74
+ const args = [
75
+ ...(unit.user ? ['--user'] : []),
76
+ 'show',
77
+ unit.name,
78
+ '--property=Restart',
79
+ '--property=SuccessExitStatus',
80
+ ];
81
+ execFile('systemctl', args, { timeout: 5_000 }, (error, stdout) => {
82
+ if (error)
83
+ return resolve(null);
84
+ const properties = new Map(stdout
85
+ .split('\n')
86
+ .map((line) => line.split('='))
87
+ .filter((parts) => parts.length >= 2)
88
+ .map(([key, ...rest]) => [key, rest.join('=')]));
89
+ const policy = properties.get('Restart')?.trim();
90
+ if (!policy)
91
+ return resolve(null);
92
+ resolve({
93
+ policy,
94
+ successExitStatuses: (properties.get('SuccessExitStatus') ?? '')
95
+ .split(/\s+/)
96
+ .map(Number)
97
+ .filter((code) => Number.isInteger(code)),
98
+ });
99
+ });
100
+ });
101
+ }
102
+ /**
103
+ * Whether exiting `RESTART_EXIT_CODE` under this configuration brings the bot
104
+ * back.
105
+ *
106
+ * Only `always` and `on-failure` count: `on-abnormal` and `on-watchdog`
107
+ * restart on signals and timeouts but not on a non-zero exit, and `on-success`
108
+ * is the opposite of what we need.
109
+ *
110
+ * `SuccessExitStatus` is the trap. Naming 75 there makes an intentional
111
+ * restart read as a clean exit in the journal, which is why the shipped unit
112
+ * does it — but it also means `on-failure` would no longer see a failure to
113
+ * act on. The two settings are only safe together with `Restart=always`.
114
+ */
115
+ export function willRestartOnRequestedExit(behaviour) {
116
+ if (behaviour.policy === 'always')
117
+ return true;
118
+ if (behaviour.policy !== 'on-failure')
119
+ return false;
120
+ return !behaviour.successExitStatuses.includes(RESTART_EXIT_CODE);
121
+ }
122
+ /** The shell command an operator would run to restart this unit by hand. */
123
+ export function manualRestartCommand(unit) {
124
+ return `systemctl ${unit.user ? '--user ' : ''}restart ${unit.name}`;
125
+ }
126
+ //# sourceMappingURL=systemd.js.map