telecoder 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/.env.example +375 -0
  2. package/CHANGELOG.md +1867 -0
  3. package/LICENSE +22 -0
  4. package/README.md +130 -2
  5. package/dist/audio/transcribe.js +41 -0
  6. package/dist/bin/mcp-server.js +363 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +573 -0
  10. package/dist/bot/command-catalog.js +263 -0
  11. package/dist/bot/deleted-threads.js +103 -0
  12. package/dist/bot/file-access.js +150 -0
  13. package/dist/bot/handlers/album.handler.js +128 -0
  14. package/dist/bot/handlers/branch.handler.js +1096 -0
  15. package/dist/bot/handlers/command/access.js +407 -0
  16. package/dist/bot/handlers/command/admin.js +803 -0
  17. package/dist/bot/handlers/command/all-view.js +33 -0
  18. package/dist/bot/handlers/command/auto-approve.js +138 -0
  19. package/dist/bot/handlers/command/background.js +37 -0
  20. package/dist/bot/handlers/command/botname.js +76 -0
  21. package/dist/bot/handlers/command/btw.js +175 -0
  22. package/dist/bot/handlers/command/cleanup.js +329 -0
  23. package/dist/bot/handlers/command/model.js +226 -0
  24. package/dist/bot/handlers/command/prefs-scope.js +362 -0
  25. package/dist/bot/handlers/command/project.js +458 -0
  26. package/dist/bot/handlers/command/resume.js +325 -0
  27. package/dist/bot/handlers/command/session.js +299 -0
  28. package/dist/bot/handlers/command/settings.js +657 -0
  29. package/dist/bot/handlers/command/shared.js +207 -0
  30. package/dist/bot/handlers/command/tasks.js +681 -0
  31. package/dist/bot/handlers/command/thread.js +128 -0
  32. package/dist/bot/handlers/command/topic-store.js +74 -0
  33. package/dist/bot/handlers/command/topic.js +27 -0
  34. package/dist/bot/handlers/command/usage.js +382 -0
  35. package/dist/bot/handlers/command-fallback.js +179 -0
  36. package/dist/bot/handlers/command.handler.js +446 -0
  37. package/dist/bot/handlers/loop.handler.js +389 -0
  38. package/dist/bot/handlers/media-fallback.js +126 -0
  39. package/dist/bot/handlers/message/replies.js +56 -0
  40. package/dist/bot/handlers/message/shared.js +95 -0
  41. package/dist/bot/handlers/message/turn-notify.js +135 -0
  42. package/dist/bot/handlers/message/turn-runner.js +56 -0
  43. package/dist/bot/handlers/message.handler.js +114 -0
  44. package/dist/bot/handlers/newbot.handler.js +230 -0
  45. package/dist/bot/handlers/photo.handler.js +286 -0
  46. package/dist/bot/handlers/prompts.handler.js +343 -0
  47. package/dist/bot/handlers/running-note.js +44 -0
  48. package/dist/bot/handlers/session-guard.js +78 -0
  49. package/dist/bot/handlers/suggestion.handler.js +84 -0
  50. package/dist/bot/handlers/tree.handler.js +480 -0
  51. package/dist/bot/handlers/view.js +41 -0
  52. package/dist/bot/handlers/voice.handler.js +147 -0
  53. package/dist/bot/kept-threads.js +51 -0
  54. package/dist/bot/middleware/admin-only.js +49 -0
  55. package/dist/bot/middleware/album-collector.js +69 -0
  56. package/dist/bot/middleware/auth.middleware.js +122 -0
  57. package/dist/bot/middleware/group-mention.middleware.js +145 -0
  58. package/dist/bot/middleware/group-role.middleware.js +75 -0
  59. package/dist/bot/middleware/message-batcher.js +87 -0
  60. package/dist/bot/middleware/queued-messages.js +1082 -0
  61. package/dist/bot/middleware/stale-filter.js +9 -0
  62. package/dist/build-info.json +8 -0
  63. package/dist/claude/ask-user-form.js +517 -0
  64. package/dist/claude/ask-user.js +363 -0
  65. package/dist/claude/auto-approve.js +225 -0
  66. package/dist/claude/auto-topic-haiku.js +143 -0
  67. package/dist/claude/available-commands.js +156 -0
  68. package/dist/claude/background-hint.js +91 -0
  69. package/dist/claude/branch-tree.js +393 -0
  70. package/dist/claude/carry-over.js +25 -0
  71. package/dist/claude/ccr-shim.js +48 -0
  72. package/dist/claude/charter-judge.js +214 -0
  73. package/dist/claude/claude-auth.js +117 -0
  74. package/dist/claude/command-parser.js +206 -0
  75. package/dist/claude/cost-overlay-scraper.js +134 -0
  76. package/dist/claude/effort-level.js +5 -0
  77. package/dist/claude/enabled-plugins.js +52 -0
  78. package/dist/claude/in-flight-tracker.js +82 -0
  79. package/dist/claude/ipc-server.js +192 -0
  80. package/dist/claude/mcp-bridge.js +481 -0
  81. package/dist/claude/memory-guard.js +400 -0
  82. package/dist/claude/message-offsets.js +88 -0
  83. package/dist/claude/modal-relay.js +817 -0
  84. package/dist/claude/model-catalog.js +102 -0
  85. package/dist/claude/monitor-relay.js +712 -0
  86. package/dist/claude/native-commands.js +40 -0
  87. package/dist/claude/pending-branches.js +93 -0
  88. package/dist/claude/pending-suggestions.js +50 -0
  89. package/dist/claude/permission-gate.js +338 -0
  90. package/dist/claude/permission-mode.js +152 -0
  91. package/dist/claude/poll-user.js +51 -0
  92. package/dist/claude/prewarm.js +70 -0
  93. package/dist/claude/project-commands.js +69 -0
  94. package/dist/claude/prompt-hold.js +124 -0
  95. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  96. package/dist/claude/pty-idle-reaper.js +96 -0
  97. package/dist/claude/pty-provider.js +2499 -0
  98. package/dist/claude/pty-spawn-config.js +343 -0
  99. package/dist/claude/pty-stream.js +363 -0
  100. package/dist/claude/pty-watch.js +201 -0
  101. package/dist/claude/request-queue.js +107 -0
  102. package/dist/claude/rewind.js +111 -0
  103. package/dist/claude/scheduled-runner.js +89 -0
  104. package/dist/claude/scheduler.js +241 -0
  105. package/dist/claude/scope-guard.js +279 -0
  106. package/dist/claude/screen-marks.js +83 -0
  107. package/dist/claude/screen-render.js +96 -0
  108. package/dist/claude/secret-request.js +576 -0
  109. package/dist/claude/session-history.js +288 -0
  110. package/dist/claude/session-jsonl.js +1067 -0
  111. package/dist/claude/session-manager.js +216 -0
  112. package/dist/claude/session-move.js +70 -0
  113. package/dist/claude/session-scan.js +270 -0
  114. package/dist/claude/setup-token.js +285 -0
  115. package/dist/claude/shell-mode-gate.js +60 -0
  116. package/dist/claude/side-call-options.js +45 -0
  117. package/dist/claude/side-question.js +252 -0
  118. package/dist/claude/stage-images.js +62 -0
  119. package/dist/claude/subagent-tools.js +12 -0
  120. package/dist/claude/synthetic-ctx.js +51 -0
  121. package/dist/claude/tasks-overlay-scraper.js +217 -0
  122. package/dist/claude/thread-judge-haiku.js +88 -0
  123. package/dist/claude/tip-scraper.js +77 -0
  124. package/dist/claude/tui-modal.js +746 -0
  125. package/dist/claude/tui-state.js +456 -0
  126. package/dist/claude/turn-end.js +105 -0
  127. package/dist/claude/turn-prose.js +64 -0
  128. package/dist/claude/typed-answer.js +104 -0
  129. package/dist/claude/update-banner-relay.js +70 -0
  130. package/dist/cli/commands/doctor.js +338 -0
  131. package/dist/cli/commands/help.js +34 -0
  132. package/dist/cli/commands/init.js +126 -0
  133. package/dist/cli/commands/service.js +710 -0
  134. package/dist/cli/commands/start.js +63 -0
  135. package/dist/cli/commands/version.js +11 -0
  136. package/dist/cli/commands/watch.js +322 -0
  137. package/dist/cli/dispatch.js +84 -0
  138. package/dist/cli/init/env-file.js +99 -0
  139. package/dist/cli/init/flow.js +705 -0
  140. package/dist/cli/init/prompter.js +124 -0
  141. package/dist/cli/init/telegram.js +120 -0
  142. package/dist/cli/service/render.js +212 -0
  143. package/dist/cli.js +18 -0
  144. package/dist/config-report.js +107 -0
  145. package/dist/config.js +525 -0
  146. package/dist/index.js +443 -0
  147. package/dist/launcher.js +960 -0
  148. package/dist/node-version-check.js +27 -0
  149. package/dist/providers/ccr-health.js +119 -0
  150. package/dist/providers/ccr-introspect.js +142 -0
  151. package/dist/providers/ccr-provider.js +59 -0
  152. package/dist/providers/claude-provider.js +10 -0
  153. package/dist/providers/prefs-sync.js +121 -0
  154. package/dist/providers/project-favorites.js +74 -0
  155. package/dist/providers/provider-router.js +128 -0
  156. package/dist/providers/provider-switch.js +91 -0
  157. package/dist/providers/spawn-settings.js +45 -0
  158. package/dist/providers/types.js +8 -0
  159. package/dist/providers/user-preferences.js +322 -0
  160. package/dist/restart-when-idle.js +173 -0
  161. package/dist/startup/auto-continue.js +67 -0
  162. package/dist/startup/auto-resume.js +161 -0
  163. package/dist/startup/notices.js +120 -0
  164. package/dist/startup/shared.js +44 -0
  165. package/dist/startup/verify-token.js +31 -0
  166. package/dist/telegram/access-request.js +153 -0
  167. package/dist/telegram/action-logger.js +522 -0
  168. package/dist/telegram/admin-mention.js +107 -0
  169. package/dist/telegram/background-activity-card.js +502 -0
  170. package/dist/telegram/botname-settings.js +282 -0
  171. package/dist/telegram/button-text.js +26 -0
  172. package/dist/telegram/client-options.js +26 -0
  173. package/dist/telegram/deduplication.js +33 -0
  174. package/dist/telegram/entities.js +295 -0
  175. package/dist/telegram/force-reply-tracker.js +96 -0
  176. package/dist/telegram/lettered-options.js +87 -0
  177. package/dist/telegram/markdown.js +362 -0
  178. package/dist/telegram/message-sender.js +1019 -0
  179. package/dist/telegram/prompt-label.js +148 -0
  180. package/dist/telegram/prompt-suggestion.js +54 -0
  181. package/dist/telegram/send.js +123 -0
  182. package/dist/telegram/streaming-turn.js +103 -0
  183. package/dist/telegram/suggestions-settings.js +30 -0
  184. package/dist/telegram/table-lists.js +56 -0
  185. package/dist/telegram/task-list.js +367 -0
  186. package/dist/telegram/task-tracker.js +128 -0
  187. package/dist/telegram/terminal-renderer.js +667 -0
  188. package/dist/telegram/thread-titles.js +262 -0
  189. package/dist/telegram/threads-setup.js +117 -0
  190. package/dist/utils/admins.js +143 -0
  191. package/dist/utils/agent-timer.js +55 -0
  192. package/dist/utils/atomic-write.js +24 -0
  193. package/dist/utils/bot-icon.js +248 -0
  194. package/dist/utils/bot-token.js +77 -0
  195. package/dist/utils/bounded-map.js +55 -0
  196. package/dist/utils/build-info.js +57 -0
  197. package/dist/utils/caffeinate.js +53 -0
  198. package/dist/utils/claude-env.js +53 -0
  199. package/dist/utils/claude-version.js +48 -0
  200. package/dist/utils/config-home.js +62 -0
  201. package/dist/utils/download.js +137 -0
  202. package/dist/utils/exit-codes.js +59 -0
  203. package/dist/utils/file-type.js +149 -0
  204. package/dist/utils/format.js +78 -0
  205. package/dist/utils/home-project.js +30 -0
  206. package/dist/utils/host-stall.js +51 -0
  207. package/dist/utils/id-list.js +44 -0
  208. package/dist/utils/idle-restart.js +92 -0
  209. package/dist/utils/install-mode.js +63 -0
  210. package/dist/utils/instance-config.js +148 -0
  211. package/dist/utils/instances.js +95 -0
  212. package/dist/utils/json-store.js +140 -0
  213. package/dist/utils/keyed-settings.js +62 -0
  214. package/dist/utils/legacy-env.js +35 -0
  215. package/dist/utils/memory-pressure.js +60 -0
  216. package/dist/utils/npm-version.js +134 -0
  217. package/dist/utils/prefs-relay.js +107 -0
  218. package/dist/utils/proc-children.js +102 -0
  219. package/dist/utils/resolve-bin.js +86 -0
  220. package/dist/utils/resolve-claude-bin.js +52 -0
  221. package/dist/utils/respawn-backoff.js +28 -0
  222. package/dist/utils/sanitize.js +91 -0
  223. package/dist/utils/session-key.js +37 -0
  224. package/dist/utils/stale-launcher.js +109 -0
  225. package/dist/utils/state-dir-migration.js +92 -0
  226. package/dist/utils/systemd.js +126 -0
  227. package/dist/utils/telegram-proxy.js +72 -0
  228. package/dist/utils/uploads-dir.js +27 -0
  229. package/dist/utils/user-roster.js +275 -0
  230. package/dist/utils/verbosity.js +118 -0
  231. package/dist/utils/version-check.js +166 -0
  232. package/dist/utils/workspace-guard.js +44 -0
  233. package/dist/worker-restart.js +141 -0
  234. package/instances.json.example +41 -0
  235. package/package.json +75 -4
@@ -0,0 +1,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
+ * /botrebuild 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 a restart cannot be done by a helper process under
6
+ * systemd. `spawn(..., { detached: true })` escapes the process group and
7
+ * session but not the cgroup, so a helper that would start the replacement
8
+ * stays inside the unit. The moment the bot exits, systemd deactivates the
9
+ * unit and (with the default `KillMode=control-group`) reaps everything left
10
+ * in it — the helper included, before it ever gets to the start half of its
11
+ * job. The bot has to exit and let systemd restart it instead, which means
12
+ * first knowing 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
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Finding the proxy for requests to Telegram, and making a request through
3
+ * it, without the bot's config module.
4
+ *
5
+ * The bot itself gives the proxy to grammY (telegram/client-options.ts).
6
+ * `telecoder init` runs before there is a config, and `telecoder doctor` reads
7
+ * the .env itself, so both make their few Bot API calls through here.
8
+ */
9
+ import * as http from 'http';
10
+ import * as https from 'https';
11
+ import { HttpsProxyAgent } from 'https-proxy-agent';
12
+ /** Where the proxy is read from. The first one set wins. */
13
+ export const PROXY_SETTINGS = ['TELEGRAM_PROXY_URL', 'HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy'];
14
+ /** The proxy for requests to Telegram, given how to read a setting. */
15
+ export function findProxy(lookup) {
16
+ for (const setting of PROXY_SETTINGS) {
17
+ const url = lookup(setting)?.trim();
18
+ if (url)
19
+ return { url, setting };
20
+ }
21
+ return undefined;
22
+ }
23
+ /**
24
+ * A fetch that goes through `proxyUrl`, an HTTP or HTTPS proxy.
25
+ *
26
+ * Node's own fetch takes no proxy agent, so the request goes out over
27
+ * `http(s).request` with the agent the bot's requests to Telegram use. The
28
+ * answer is read whole before the promise settles, which suits what this is
29
+ * for: Bot API calls, a few KB each way. Redirects aren't followed. A request
30
+ * that is aborted rejects with the signal's reason, as fetch does.
31
+ */
32
+ export function fetchThroughProxy(proxyUrl) {
33
+ return async (url, init) => {
34
+ const { signal, ...rest } = init;
35
+ // Request works out the body and its content-type as fetch would, a
36
+ // FormData's multipart boundary included.
37
+ const request = new Request(url, rest);
38
+ const body = request.body ? Buffer.from(await request.arrayBuffer()) : undefined;
39
+ const headers = Object.fromEntries(request.headers);
40
+ if (body)
41
+ headers['content-length'] = String(body.length);
42
+ signal?.throwIfAborted();
43
+ const agent = new HttpsProxyAgent(proxyUrl);
44
+ return new Promise((resolve, reject) => {
45
+ const fail = (error) => reject(signal?.aborted ? signal.reason ?? error : error);
46
+ const send = new URL(url).protocol === 'https:' ? https.request : http.request;
47
+ const req = send(url, { method: request.method, headers, agent, signal: signal ?? undefined }, (res) => {
48
+ const chunks = [];
49
+ res.on('data', (chunk) => chunks.push(chunk));
50
+ res.on('error', fail);
51
+ res.on('end', () => {
52
+ const answered = new Headers();
53
+ for (const [name, value] of Object.entries(res.headers)) {
54
+ for (const one of Array.isArray(value) ? value : value === undefined ? [] : [value])
55
+ answered.append(name, one);
56
+ }
57
+ const text = Buffer.concat(chunks);
58
+ try {
59
+ // A status that carries no body (204, 304) refuses even an empty one.
60
+ resolve(new Response(text.length ? text : null, { status: res.statusCode, headers: answered }));
61
+ }
62
+ catch (error) {
63
+ reject(error);
64
+ }
65
+ });
66
+ });
67
+ req.on('error', fail);
68
+ req.end(body);
69
+ });
70
+ };
71
+ }
72
+ //# sourceMappingURL=telegram-proxy.js.map
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Where files sent in a chat are saved for Claude to read:
3
+ * `~/.telecoder/uploads/<project name>/`.
4
+ *
5
+ * They used to go to `<project>/.telecoder/uploads/`, which left a folder in
6
+ * every project someone had sent a photo to, and needed a `.gitignore` of its
7
+ * own so the photos stayed out of commits. The bot's state directory has
8
+ * neither problem. Claude still gets the absolute path in the prompt, so where
9
+ * the file lives makes no difference to it — except that the scope guard
10
+ * treats the rest of `~/.telecoder` as bot state and prompts on every read;
11
+ * `uploads/` is the one subfolder it exempts, since what's in it is the user's
12
+ * own files (see claude/scope-guard.ts).
13
+ */
14
+ import * as fs from 'fs';
15
+ import * as path from 'path';
16
+ import { getStateDir } from './json-store.js';
17
+ /** The folder every upload lives under. */
18
+ export function getUploadsRoot() {
19
+ return path.join(getStateDir(), 'uploads');
20
+ }
21
+ /** Create the uploads folder for a project if needed, and return its path. */
22
+ export function ensureUploadsDir(projectDir) {
23
+ const dir = path.join(getUploadsRoot(), path.basename(projectDir));
24
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
25
+ return dir;
26
+ }
27
+ //# sourceMappingURL=uploads-dir.js.map