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.
- package/.env.example +375 -0
- package/CHANGELOG.md +1867 -0
- package/LICENSE +22 -0
- package/README.md +130 -2
- package/dist/audio/transcribe.js +41 -0
- package/dist/bin/mcp-server.js +363 -0
- package/dist/bin/tool-result.js +22 -0
- package/dist/bot/access/group-access.js +147 -0
- package/dist/bot/bot.js +573 -0
- package/dist/bot/command-catalog.js +263 -0
- package/dist/bot/deleted-threads.js +103 -0
- package/dist/bot/file-access.js +150 -0
- package/dist/bot/handlers/album.handler.js +128 -0
- package/dist/bot/handlers/branch.handler.js +1096 -0
- package/dist/bot/handlers/command/access.js +407 -0
- package/dist/bot/handlers/command/admin.js +803 -0
- package/dist/bot/handlers/command/all-view.js +33 -0
- package/dist/bot/handlers/command/auto-approve.js +138 -0
- package/dist/bot/handlers/command/background.js +37 -0
- package/dist/bot/handlers/command/botname.js +76 -0
- package/dist/bot/handlers/command/btw.js +175 -0
- package/dist/bot/handlers/command/cleanup.js +329 -0
- package/dist/bot/handlers/command/model.js +226 -0
- package/dist/bot/handlers/command/prefs-scope.js +362 -0
- package/dist/bot/handlers/command/project.js +458 -0
- package/dist/bot/handlers/command/resume.js +325 -0
- package/dist/bot/handlers/command/session.js +299 -0
- package/dist/bot/handlers/command/settings.js +657 -0
- package/dist/bot/handlers/command/shared.js +207 -0
- package/dist/bot/handlers/command/tasks.js +681 -0
- package/dist/bot/handlers/command/thread.js +128 -0
- package/dist/bot/handlers/command/topic-store.js +74 -0
- package/dist/bot/handlers/command/topic.js +27 -0
- package/dist/bot/handlers/command/usage.js +382 -0
- package/dist/bot/handlers/command-fallback.js +179 -0
- package/dist/bot/handlers/command.handler.js +446 -0
- package/dist/bot/handlers/loop.handler.js +389 -0
- package/dist/bot/handlers/media-fallback.js +126 -0
- package/dist/bot/handlers/message/replies.js +56 -0
- package/dist/bot/handlers/message/shared.js +95 -0
- package/dist/bot/handlers/message/turn-notify.js +135 -0
- package/dist/bot/handlers/message/turn-runner.js +56 -0
- package/dist/bot/handlers/message.handler.js +114 -0
- package/dist/bot/handlers/newbot.handler.js +230 -0
- package/dist/bot/handlers/photo.handler.js +286 -0
- package/dist/bot/handlers/prompts.handler.js +343 -0
- package/dist/bot/handlers/running-note.js +44 -0
- package/dist/bot/handlers/session-guard.js +78 -0
- package/dist/bot/handlers/suggestion.handler.js +84 -0
- package/dist/bot/handlers/tree.handler.js +480 -0
- package/dist/bot/handlers/view.js +41 -0
- package/dist/bot/handlers/voice.handler.js +147 -0
- package/dist/bot/kept-threads.js +51 -0
- package/dist/bot/middleware/admin-only.js +49 -0
- package/dist/bot/middleware/album-collector.js +69 -0
- package/dist/bot/middleware/auth.middleware.js +122 -0
- package/dist/bot/middleware/group-mention.middleware.js +145 -0
- package/dist/bot/middleware/group-role.middleware.js +75 -0
- package/dist/bot/middleware/message-batcher.js +87 -0
- package/dist/bot/middleware/queued-messages.js +1082 -0
- package/dist/bot/middleware/stale-filter.js +9 -0
- package/dist/build-info.json +8 -0
- package/dist/claude/ask-user-form.js +517 -0
- package/dist/claude/ask-user.js +363 -0
- package/dist/claude/auto-approve.js +225 -0
- package/dist/claude/auto-topic-haiku.js +143 -0
- package/dist/claude/available-commands.js +156 -0
- package/dist/claude/background-hint.js +91 -0
- package/dist/claude/branch-tree.js +393 -0
- package/dist/claude/carry-over.js +25 -0
- package/dist/claude/ccr-shim.js +48 -0
- package/dist/claude/charter-judge.js +214 -0
- package/dist/claude/claude-auth.js +117 -0
- package/dist/claude/command-parser.js +206 -0
- package/dist/claude/cost-overlay-scraper.js +134 -0
- package/dist/claude/effort-level.js +5 -0
- package/dist/claude/enabled-plugins.js +52 -0
- package/dist/claude/in-flight-tracker.js +82 -0
- package/dist/claude/ipc-server.js +192 -0
- package/dist/claude/mcp-bridge.js +481 -0
- package/dist/claude/memory-guard.js +400 -0
- package/dist/claude/message-offsets.js +88 -0
- package/dist/claude/modal-relay.js +817 -0
- package/dist/claude/model-catalog.js +102 -0
- package/dist/claude/monitor-relay.js +712 -0
- package/dist/claude/native-commands.js +40 -0
- package/dist/claude/pending-branches.js +93 -0
- package/dist/claude/pending-suggestions.js +50 -0
- package/dist/claude/permission-gate.js +338 -0
- package/dist/claude/permission-mode.js +152 -0
- package/dist/claude/poll-user.js +51 -0
- package/dist/claude/prewarm.js +70 -0
- package/dist/claude/project-commands.js +69 -0
- package/dist/claude/prompt-hold.js +124 -0
- package/dist/claude/prompt-suggestion-scraper.js +89 -0
- package/dist/claude/pty-idle-reaper.js +96 -0
- package/dist/claude/pty-provider.js +2499 -0
- package/dist/claude/pty-spawn-config.js +343 -0
- package/dist/claude/pty-stream.js +363 -0
- package/dist/claude/pty-watch.js +201 -0
- package/dist/claude/request-queue.js +107 -0
- package/dist/claude/rewind.js +111 -0
- package/dist/claude/scheduled-runner.js +89 -0
- package/dist/claude/scheduler.js +241 -0
- package/dist/claude/scope-guard.js +279 -0
- package/dist/claude/screen-marks.js +83 -0
- package/dist/claude/screen-render.js +96 -0
- package/dist/claude/secret-request.js +576 -0
- package/dist/claude/session-history.js +288 -0
- package/dist/claude/session-jsonl.js +1067 -0
- package/dist/claude/session-manager.js +216 -0
- package/dist/claude/session-move.js +70 -0
- package/dist/claude/session-scan.js +270 -0
- package/dist/claude/setup-token.js +285 -0
- package/dist/claude/shell-mode-gate.js +60 -0
- package/dist/claude/side-call-options.js +45 -0
- package/dist/claude/side-question.js +252 -0
- package/dist/claude/stage-images.js +62 -0
- package/dist/claude/subagent-tools.js +12 -0
- package/dist/claude/synthetic-ctx.js +51 -0
- package/dist/claude/tasks-overlay-scraper.js +217 -0
- package/dist/claude/thread-judge-haiku.js +88 -0
- package/dist/claude/tip-scraper.js +77 -0
- package/dist/claude/tui-modal.js +746 -0
- package/dist/claude/tui-state.js +456 -0
- package/dist/claude/turn-end.js +105 -0
- package/dist/claude/turn-prose.js +64 -0
- package/dist/claude/typed-answer.js +104 -0
- package/dist/claude/update-banner-relay.js +70 -0
- package/dist/cli/commands/doctor.js +338 -0
- package/dist/cli/commands/help.js +34 -0
- package/dist/cli/commands/init.js +126 -0
- package/dist/cli/commands/service.js +710 -0
- package/dist/cli/commands/start.js +63 -0
- package/dist/cli/commands/version.js +11 -0
- package/dist/cli/commands/watch.js +322 -0
- package/dist/cli/dispatch.js +84 -0
- package/dist/cli/init/env-file.js +99 -0
- package/dist/cli/init/flow.js +705 -0
- package/dist/cli/init/prompter.js +124 -0
- package/dist/cli/init/telegram.js +120 -0
- package/dist/cli/service/render.js +212 -0
- package/dist/cli.js +18 -0
- package/dist/config-report.js +107 -0
- package/dist/config.js +525 -0
- package/dist/index.js +443 -0
- package/dist/launcher.js +960 -0
- package/dist/node-version-check.js +27 -0
- package/dist/providers/ccr-health.js +119 -0
- package/dist/providers/ccr-introspect.js +142 -0
- package/dist/providers/ccr-provider.js +59 -0
- package/dist/providers/claude-provider.js +10 -0
- package/dist/providers/prefs-sync.js +121 -0
- package/dist/providers/project-favorites.js +74 -0
- package/dist/providers/provider-router.js +128 -0
- package/dist/providers/provider-switch.js +91 -0
- package/dist/providers/spawn-settings.js +45 -0
- package/dist/providers/types.js +8 -0
- package/dist/providers/user-preferences.js +322 -0
- package/dist/restart-when-idle.js +173 -0
- package/dist/startup/auto-continue.js +67 -0
- package/dist/startup/auto-resume.js +161 -0
- package/dist/startup/notices.js +120 -0
- package/dist/startup/shared.js +44 -0
- package/dist/startup/verify-token.js +31 -0
- package/dist/telegram/access-request.js +153 -0
- package/dist/telegram/action-logger.js +522 -0
- package/dist/telegram/admin-mention.js +107 -0
- package/dist/telegram/background-activity-card.js +502 -0
- package/dist/telegram/botname-settings.js +282 -0
- package/dist/telegram/button-text.js +26 -0
- package/dist/telegram/client-options.js +26 -0
- package/dist/telegram/deduplication.js +33 -0
- package/dist/telegram/entities.js +295 -0
- package/dist/telegram/force-reply-tracker.js +96 -0
- package/dist/telegram/lettered-options.js +87 -0
- package/dist/telegram/markdown.js +362 -0
- package/dist/telegram/message-sender.js +1019 -0
- package/dist/telegram/prompt-label.js +148 -0
- package/dist/telegram/prompt-suggestion.js +54 -0
- package/dist/telegram/send.js +123 -0
- package/dist/telegram/streaming-turn.js +103 -0
- package/dist/telegram/suggestions-settings.js +30 -0
- package/dist/telegram/table-lists.js +56 -0
- package/dist/telegram/task-list.js +367 -0
- package/dist/telegram/task-tracker.js +128 -0
- package/dist/telegram/terminal-renderer.js +667 -0
- package/dist/telegram/thread-titles.js +262 -0
- package/dist/telegram/threads-setup.js +117 -0
- package/dist/utils/admins.js +143 -0
- package/dist/utils/agent-timer.js +55 -0
- package/dist/utils/atomic-write.js +24 -0
- package/dist/utils/bot-icon.js +248 -0
- package/dist/utils/bot-token.js +77 -0
- package/dist/utils/bounded-map.js +55 -0
- package/dist/utils/build-info.js +57 -0
- package/dist/utils/caffeinate.js +53 -0
- package/dist/utils/claude-env.js +53 -0
- package/dist/utils/claude-version.js +48 -0
- package/dist/utils/config-home.js +62 -0
- package/dist/utils/download.js +137 -0
- package/dist/utils/exit-codes.js +59 -0
- package/dist/utils/file-type.js +149 -0
- package/dist/utils/format.js +78 -0
- package/dist/utils/home-project.js +30 -0
- package/dist/utils/host-stall.js +51 -0
- package/dist/utils/id-list.js +44 -0
- package/dist/utils/idle-restart.js +92 -0
- package/dist/utils/install-mode.js +63 -0
- package/dist/utils/instance-config.js +148 -0
- package/dist/utils/instances.js +95 -0
- package/dist/utils/json-store.js +140 -0
- package/dist/utils/keyed-settings.js +62 -0
- package/dist/utils/legacy-env.js +35 -0
- package/dist/utils/memory-pressure.js +60 -0
- package/dist/utils/npm-version.js +134 -0
- package/dist/utils/prefs-relay.js +107 -0
- package/dist/utils/proc-children.js +102 -0
- package/dist/utils/resolve-bin.js +86 -0
- package/dist/utils/resolve-claude-bin.js +52 -0
- package/dist/utils/respawn-backoff.js +28 -0
- package/dist/utils/sanitize.js +91 -0
- package/dist/utils/session-key.js +37 -0
- package/dist/utils/stale-launcher.js +109 -0
- package/dist/utils/state-dir-migration.js +92 -0
- package/dist/utils/systemd.js +126 -0
- package/dist/utils/telegram-proxy.js +72 -0
- package/dist/utils/uploads-dir.js +27 -0
- package/dist/utils/user-roster.js +275 -0
- package/dist/utils/verbosity.js +118 -0
- package/dist/utils/version-check.js +166 -0
- package/dist/utils/workspace-guard.js +44 -0
- package/dist/worker-restart.js +141 -0
- package/instances.json.example +41 -0
- 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
|