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,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How much memory the machine has left, read the way the kernel means it.
|
|
3
|
+
*
|
|
4
|
+
* Node's os.freemem() is "MemFree": what nobody has touched. On Linux that is
|
|
5
|
+
* nearly always small, because the kernel keeps every page it can as file
|
|
6
|
+
* cache and gives it back on demand. "MemAvailable" is the kernel's own
|
|
7
|
+
* estimate of what a new process can have without swapping, and the number
|
|
8
|
+
* `free -m` prints under "available". That is the one that says whether
|
|
9
|
+
* another claude fits.
|
|
10
|
+
*/
|
|
11
|
+
import fs from 'fs';
|
|
12
|
+
import os from 'os';
|
|
13
|
+
const KB_PER_MB = 1024;
|
|
14
|
+
/** Parse the text of /proc/meminfo. Exported for tests. */
|
|
15
|
+
export function parseMeminfo(text) {
|
|
16
|
+
const kb = new Map();
|
|
17
|
+
for (const line of text.split('\n')) {
|
|
18
|
+
const m = /^(\w+):\s+(\d+)/.exec(line);
|
|
19
|
+
if (m)
|
|
20
|
+
kb.set(m[1], Number(m[2]));
|
|
21
|
+
}
|
|
22
|
+
const total = kb.get('MemTotal');
|
|
23
|
+
const available = kb.get('MemAvailable');
|
|
24
|
+
if (total === undefined || available === undefined)
|
|
25
|
+
return null;
|
|
26
|
+
const swapTotal = kb.get('SwapTotal') ?? 0;
|
|
27
|
+
const swapFree = kb.get('SwapFree') ?? swapTotal;
|
|
28
|
+
return {
|
|
29
|
+
totalMB: Math.round(total / KB_PER_MB),
|
|
30
|
+
availableMB: Math.round(available / KB_PER_MB),
|
|
31
|
+
swapTotalMB: Math.round(swapTotal / KB_PER_MB),
|
|
32
|
+
swapUsedMB: Math.round((swapTotal - swapFree) / KB_PER_MB),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The machine's memory right now, or null when it can't be read. Off Linux
|
|
37
|
+
* there is no MemAvailable; os.freemem() stands in, which errs on the side of
|
|
38
|
+
* looking tight.
|
|
39
|
+
*/
|
|
40
|
+
export function readMemory() {
|
|
41
|
+
try {
|
|
42
|
+
const parsed = parseMeminfo(fs.readFileSync('/proc/meminfo', 'utf8'));
|
|
43
|
+
if (parsed)
|
|
44
|
+
return parsed;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
// not Linux, or /proc unreadable
|
|
48
|
+
}
|
|
49
|
+
const total = os.totalmem();
|
|
50
|
+
const free = os.freemem();
|
|
51
|
+
if (!Number.isFinite(total) || total <= 0)
|
|
52
|
+
return null;
|
|
53
|
+
return {
|
|
54
|
+
totalMB: Math.round(total / 1024 / 1024),
|
|
55
|
+
availableMB: Math.round(free / 1024 / 1024),
|
|
56
|
+
swapTotalMB: 0,
|
|
57
|
+
swapUsedMB: 0,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=memory-pressure.js.map
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The npm side of /botversion and /botupdate, for a package install (see
|
|
3
|
+
* utils/install-mode.ts). A checkout asks git instead (utils/version-check.ts).
|
|
4
|
+
*
|
|
5
|
+
* `npm view` goes to the registry, so its answer is cached in the state
|
|
6
|
+
* directory and only asked for on demand — never on the way up.
|
|
7
|
+
*/
|
|
8
|
+
import { execFile } from 'child_process';
|
|
9
|
+
import * as fs from 'fs';
|
|
10
|
+
import * as path from 'path';
|
|
11
|
+
import { getStateDir } from './json-store.js';
|
|
12
|
+
import { atomicWriteFileSync } from './atomic-write.js';
|
|
13
|
+
export const PACKAGE_NAME = 'telecoder';
|
|
14
|
+
const VIEW_TIMEOUT_MS = 10_000;
|
|
15
|
+
const CACHE_TTL_MS = 6 * 60 * 60 * 1000;
|
|
16
|
+
const CACHE_FILE = 'npm-latest.json';
|
|
17
|
+
/** -1, 0 or 1, comparing the numeric x.y.z parts; a prerelease sorts below its release. */
|
|
18
|
+
export function compareVersions(a, b) {
|
|
19
|
+
const parse = (v) => {
|
|
20
|
+
const [core, pre] = v.trim().replace(/^v/, '').split('-', 2);
|
|
21
|
+
return { nums: core.split('.').map((n) => parseInt(n, 10) || 0), pre: pre ?? null };
|
|
22
|
+
};
|
|
23
|
+
const x = parse(a);
|
|
24
|
+
const y = parse(b);
|
|
25
|
+
for (let i = 0; i < Math.max(x.nums.length, y.nums.length); i++) {
|
|
26
|
+
const d = (x.nums[i] ?? 0) - (y.nums[i] ?? 0);
|
|
27
|
+
if (d !== 0)
|
|
28
|
+
return d < 0 ? -1 : 1;
|
|
29
|
+
}
|
|
30
|
+
if (x.pre === y.pre)
|
|
31
|
+
return 0;
|
|
32
|
+
if (x.pre === null)
|
|
33
|
+
return 1;
|
|
34
|
+
if (y.pre === null)
|
|
35
|
+
return -1;
|
|
36
|
+
return x.pre < y.pre ? -1 : 1;
|
|
37
|
+
}
|
|
38
|
+
/** What `npm view telecoder version` answers, or null when it can't be asked. */
|
|
39
|
+
export function fetchLatestVersion(timeout = VIEW_TIMEOUT_MS) {
|
|
40
|
+
return new Promise((resolve) => {
|
|
41
|
+
execFile('npm', ['view', PACKAGE_NAME, 'version'], { timeout }, (error, stdout) => {
|
|
42
|
+
if (error) {
|
|
43
|
+
console.debug(`[Version] npm view failed (${error.code ?? error.signal})`);
|
|
44
|
+
resolve(null);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const version = stdout.trim().split('\n').pop()?.trim() ?? '';
|
|
48
|
+
resolve(/^\d+\.\d+\.\d+/.test(version) ? version : null);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
function cachePath() {
|
|
53
|
+
return path.join(getStateDir(), CACHE_FILE);
|
|
54
|
+
}
|
|
55
|
+
function readCache(now) {
|
|
56
|
+
try {
|
|
57
|
+
const entry = JSON.parse(fs.readFileSync(cachePath(), 'utf-8'));
|
|
58
|
+
if (typeof entry.version !== 'string' || typeof entry.checkedAt !== 'number')
|
|
59
|
+
return null;
|
|
60
|
+
return now - entry.checkedAt < CACHE_TTL_MS ? entry.version : null;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function writeCache(version, now) {
|
|
67
|
+
try {
|
|
68
|
+
fs.mkdirSync(path.dirname(cachePath()), { recursive: true, mode: 0o700 });
|
|
69
|
+
atomicWriteFileSync(cachePath(), JSON.stringify({ version, checkedAt: now }), { mode: 0o600 });
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
// A cache that can't be written only costs the next caller a registry call.
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** The latest published version, from the cache when it's fresh. */
|
|
76
|
+
export async function getLatestVersion({ fresh = false, fetch = fetchLatestVersion, now = Date.now() } = {}) {
|
|
77
|
+
if (!fresh) {
|
|
78
|
+
const cached = readCache(now);
|
|
79
|
+
if (cached)
|
|
80
|
+
return cached;
|
|
81
|
+
}
|
|
82
|
+
const latest = await fetch();
|
|
83
|
+
if (latest)
|
|
84
|
+
writeCache(latest, now);
|
|
85
|
+
return latest;
|
|
86
|
+
}
|
|
87
|
+
export function compareInstalled(installed, latest) {
|
|
88
|
+
if (!installed || !latest)
|
|
89
|
+
return { kind: 'unknown', installed };
|
|
90
|
+
const order = compareVersions(installed, latest);
|
|
91
|
+
if (order === 0)
|
|
92
|
+
return { kind: 'current', installed, latest };
|
|
93
|
+
return order < 0 ? { kind: 'behind', installed, latest } : { kind: 'ahead', installed, latest };
|
|
94
|
+
}
|
|
95
|
+
/** The command that updates this install, as a person would type it. */
|
|
96
|
+
export function updateCommand(runner) {
|
|
97
|
+
switch (runner) {
|
|
98
|
+
case 'global':
|
|
99
|
+
return `npm install -g ${PACKAGE_NAME}@latest`;
|
|
100
|
+
case 'npx':
|
|
101
|
+
return `npx ${PACKAGE_NAME}@latest start`;
|
|
102
|
+
case 'local':
|
|
103
|
+
return `npm install ${PACKAGE_NAME}@latest`;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
export function describeNpmCheck(check, runner) {
|
|
107
|
+
switch (check.kind) {
|
|
108
|
+
case 'unknown':
|
|
109
|
+
return check.installed
|
|
110
|
+
? `❓ Couldn't ask npm for the latest version, so v${check.installed} may or may not be current.`
|
|
111
|
+
: "❓ Couldn't tell which version this is.";
|
|
112
|
+
case 'current':
|
|
113
|
+
return `✅ v${check.installed} is the latest release.`;
|
|
114
|
+
case 'ahead':
|
|
115
|
+
return `⬆️ v${check.installed} is newer than the latest release (v${check.latest}).`;
|
|
116
|
+
case 'behind':
|
|
117
|
+
return runner === 'global'
|
|
118
|
+
? `⚠️ v${check.latest} is out (this is v${check.installed}). /botupdate installs it.`
|
|
119
|
+
: `⚠️ v${check.latest} is out (this is v${check.installed}). Update with: ${updateCommand(runner)}`;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** Run `npm install -g telecoder@latest`. Resolves with npm's output, rejects with its error. */
|
|
123
|
+
export function installLatestGlobally() {
|
|
124
|
+
return new Promise((resolve, reject) => {
|
|
125
|
+
execFile('npm', ['install', '-g', `${PACKAGE_NAME}@latest`], { timeout: 300_000, maxBuffer: 4 * 1024 * 1024 }, (error, stdout, stderr) => {
|
|
126
|
+
if (error) {
|
|
127
|
+
reject(new Error((stderr || error.message || 'npm install failed').trim()));
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
resolve((stdout || stderr || '').trim());
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
//# sourceMappingURL=npm-version.js.map
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bookkeeping for a preference change one bot asked to apply to all of them.
|
|
3
|
+
*
|
|
4
|
+
* The launcher is the only path between workers, so it has to hold each
|
|
5
|
+
* broadcast open until every sibling has answered, then hand the requester a
|
|
6
|
+
* summary of what they each did. Getting that wrong is invisible in the good
|
|
7
|
+
* case and misleading in the bad one — a bot reported as "applied" that never
|
|
8
|
+
* got the message, or a requester left waiting on a worker that died mid-relay.
|
|
9
|
+
*
|
|
10
|
+
* Kept out of launcher.ts, alongside the backoff and host-stall policies, for
|
|
11
|
+
* the same reason those are: the launcher spawns worker threads at import time
|
|
12
|
+
* and can't be loaded in a test, and this is the part with the edge cases.
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* Tracks broadcasts in flight and decides when each is done.
|
|
16
|
+
*
|
|
17
|
+
* A broadcast settles exactly once: on the last reply, on the timeout, or
|
|
18
|
+
* immediately when there was nobody to wait for. Everything after that —
|
|
19
|
+
* a late reply from a slow worker, a duplicate — is dropped, because the
|
|
20
|
+
* requester has already been answered and been told that bot didn't respond.
|
|
21
|
+
*/
|
|
22
|
+
export class PrefsRelay {
|
|
23
|
+
pending = new Map();
|
|
24
|
+
/** Whether this id is still open. */
|
|
25
|
+
has(requestId) {
|
|
26
|
+
return this.pending.has(requestId);
|
|
27
|
+
}
|
|
28
|
+
/** Bots this broadcast is still waiting on. Empty for an unknown id. */
|
|
29
|
+
awaiting(requestId) {
|
|
30
|
+
return [...(this.pending.get(requestId)?.awaiting ?? [])];
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Open a broadcast. Settles synchronously — before returning — when there
|
|
34
|
+
* are no siblings to wait on, so a lone bot gets an answer straight away
|
|
35
|
+
* rather than after the timeout.
|
|
36
|
+
*/
|
|
37
|
+
begin(requestId, input) {
|
|
38
|
+
// A reused id would orphan the first requester; settling it first at least
|
|
39
|
+
// answers them rather than leaving them on their own timeout.
|
|
40
|
+
if (this.pending.has(requestId))
|
|
41
|
+
this.settle(requestId);
|
|
42
|
+
const entry = {
|
|
43
|
+
awaiting: new Set(input.awaiting),
|
|
44
|
+
outcomes: [],
|
|
45
|
+
unreachable: [...input.unreachable],
|
|
46
|
+
onSettle: input.onSettle,
|
|
47
|
+
};
|
|
48
|
+
this.pending.set(requestId, entry);
|
|
49
|
+
if (entry.awaiting.size === 0) {
|
|
50
|
+
this.settle(requestId);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
entry.timer = setTimeout(() => {
|
|
54
|
+
input.onTimeout?.(this.awaiting(requestId));
|
|
55
|
+
this.settle(requestId);
|
|
56
|
+
}, input.timeoutMs);
|
|
57
|
+
// The launcher must not be held alive by a broadcast nobody is waiting on.
|
|
58
|
+
entry.timer.unref?.();
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Record one bot's answer, settling the broadcast if it was the last one
|
|
62
|
+
* outstanding. Ignores answers for unknown ids and bots not being awaited —
|
|
63
|
+
* a duplicate reply, or one that arrives after the timeout.
|
|
64
|
+
*/
|
|
65
|
+
record(requestId, outcome) {
|
|
66
|
+
const entry = this.pending.get(requestId);
|
|
67
|
+
if (!entry || !entry.awaiting.delete(outcome.name))
|
|
68
|
+
return;
|
|
69
|
+
entry.outcomes.push(outcome);
|
|
70
|
+
if (entry.awaiting.size === 0)
|
|
71
|
+
this.settle(requestId);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Give up on a bot without an answer from it — it exited while the broadcast
|
|
75
|
+
* was open. Settles if it was the last one outstanding.
|
|
76
|
+
*/
|
|
77
|
+
abandon(requestId, name) {
|
|
78
|
+
const entry = this.pending.get(requestId);
|
|
79
|
+
if (!entry || !entry.awaiting.delete(name))
|
|
80
|
+
return;
|
|
81
|
+
entry.unreachable.push(name);
|
|
82
|
+
if (entry.awaiting.size === 0)
|
|
83
|
+
this.settle(requestId);
|
|
84
|
+
}
|
|
85
|
+
/** Same, for every broadcast currently waiting on `name`. */
|
|
86
|
+
abandonEverywhere(name) {
|
|
87
|
+
for (const requestId of [...this.pending.keys()]) {
|
|
88
|
+
this.abandon(requestId, name);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** Answer the requester now, with whatever has come back. */
|
|
92
|
+
settle(requestId) {
|
|
93
|
+
const entry = this.pending.get(requestId);
|
|
94
|
+
if (!entry)
|
|
95
|
+
return;
|
|
96
|
+
if (entry.timer)
|
|
97
|
+
clearTimeout(entry.timer);
|
|
98
|
+
this.pending.delete(requestId);
|
|
99
|
+
entry.onSettle({
|
|
100
|
+
applied: entry.outcomes.filter((o) => o.status === 'applied'),
|
|
101
|
+
skipped: entry.outcomes.filter((o) => o.status === 'skipped'),
|
|
102
|
+
// Anything still awaited when we settle never answered.
|
|
103
|
+
unreachable: [...entry.unreachable, ...entry.awaiting],
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
//# sourceMappingURL=prefs-relay.js.map
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
const CLK_TCK = 100;
|
|
3
|
+
export function getDirectChildren(pid) {
|
|
4
|
+
let tids;
|
|
5
|
+
try {
|
|
6
|
+
tids = fs.readdirSync(`/proc/${pid}/task`);
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
return [];
|
|
10
|
+
}
|
|
11
|
+
const out = new Set();
|
|
12
|
+
for (const tid of tids) {
|
|
13
|
+
try {
|
|
14
|
+
const content = fs.readFileSync(`/proc/${pid}/task/${tid}/children`, 'utf8');
|
|
15
|
+
for (const part of content.trim().split(/\s+/)) {
|
|
16
|
+
if (!part)
|
|
17
|
+
continue;
|
|
18
|
+
const child = Number.parseInt(part, 10);
|
|
19
|
+
if (Number.isFinite(child))
|
|
20
|
+
out.add(child);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
catch { /* tid raced away */ }
|
|
24
|
+
}
|
|
25
|
+
return [...out].sort((a, b) => a - b);
|
|
26
|
+
}
|
|
27
|
+
export function getDescendantPids(rootPid) {
|
|
28
|
+
const out = [];
|
|
29
|
+
const queue = [rootPid];
|
|
30
|
+
const seen = new Set([rootPid]);
|
|
31
|
+
while (queue.length) {
|
|
32
|
+
const cur = queue.shift();
|
|
33
|
+
for (const child of getDirectChildren(cur)) {
|
|
34
|
+
if (seen.has(child))
|
|
35
|
+
continue;
|
|
36
|
+
seen.add(child);
|
|
37
|
+
out.push(child);
|
|
38
|
+
queue.push(child);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
export function describeProcess(pid) {
|
|
44
|
+
let argvRaw;
|
|
45
|
+
let statRaw;
|
|
46
|
+
try {
|
|
47
|
+
argvRaw = fs.readFileSync(`/proc/${pid}/cmdline`);
|
|
48
|
+
statRaw = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
const argv = argvRaw.toString('utf8').split('\0').filter(Boolean);
|
|
54
|
+
if (argv.length === 0)
|
|
55
|
+
return undefined;
|
|
56
|
+
// /proc/<pid>/stat: "<pid> (<comm>) <state> <ppid> ..."
|
|
57
|
+
// comm can contain spaces and parens, so split after the LAST ')'.
|
|
58
|
+
const lastParen = statRaw.lastIndexOf(')');
|
|
59
|
+
const fields = statRaw.substring(lastParen + 2).split(' ');
|
|
60
|
+
const ppid = Number.parseInt(fields[1], 10) || 0;
|
|
61
|
+
// starttime is stat field 22 (1-indexed). After dropping pid, comm, and the
|
|
62
|
+
// post-')' state field, the offset into `fields` is 19.
|
|
63
|
+
const startTimeTicks = Number.parseInt(fields[19], 10);
|
|
64
|
+
let ageSec = 0;
|
|
65
|
+
try {
|
|
66
|
+
const uptimeSec = Number.parseFloat(fs.readFileSync('/proc/uptime', 'utf8').split(' ')[0]);
|
|
67
|
+
if (Number.isFinite(startTimeTicks) && Number.isFinite(uptimeSec)) {
|
|
68
|
+
ageSec = Math.max(0, Math.round(uptimeSec - startTimeTicks / CLK_TCK));
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
catch { /* keep 0 */ }
|
|
72
|
+
return { pid, ppid, cmd: argv.join(' '), argv, ageSec };
|
|
73
|
+
}
|
|
74
|
+
export function isDescendantOf(rootPid, candidatePid) {
|
|
75
|
+
if (rootPid === candidatePid)
|
|
76
|
+
return false;
|
|
77
|
+
let cur = candidatePid;
|
|
78
|
+
for (let i = 0; i < 64; i++) {
|
|
79
|
+
const info = describeProcess(cur);
|
|
80
|
+
if (!info || info.ppid <= 1)
|
|
81
|
+
return false;
|
|
82
|
+
if (info.ppid === rootPid)
|
|
83
|
+
return true;
|
|
84
|
+
cur = info.ppid;
|
|
85
|
+
}
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
export function killTree(rootPid, signal = 'SIGTERM') {
|
|
89
|
+
// Leaves first — otherwise the kernel reparents live grandchildren to init
|
|
90
|
+
// before we get to them.
|
|
91
|
+
const targets = [...getDescendantPids(rootPid), rootPid].reverse();
|
|
92
|
+
let killed = 0;
|
|
93
|
+
for (const pid of targets) {
|
|
94
|
+
try {
|
|
95
|
+
process.kill(pid, signal);
|
|
96
|
+
killed++;
|
|
97
|
+
}
|
|
98
|
+
catch { /* already gone or no perms */ }
|
|
99
|
+
}
|
|
100
|
+
return killed;
|
|
101
|
+
}
|
|
102
|
+
//# sourceMappingURL=proc-children.js.map
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { execFileSync } from 'child_process';
|
|
2
|
+
import * as fs from 'fs';
|
|
3
|
+
import * as os from 'os';
|
|
4
|
+
import * as path from 'path';
|
|
5
|
+
const cache = new Map();
|
|
6
|
+
const isWin = process.platform === 'win32';
|
|
7
|
+
/**
|
|
8
|
+
* Check if a resolved path is a valid executable file.
|
|
9
|
+
* Follows symlinks (required for Homebrew, snap, etc.).
|
|
10
|
+
*/
|
|
11
|
+
function isValidExecutable(filePath) {
|
|
12
|
+
try {
|
|
13
|
+
const resolved = fs.realpathSync(filePath);
|
|
14
|
+
const stats = fs.statSync(resolved);
|
|
15
|
+
if (!stats.isFile())
|
|
16
|
+
return false;
|
|
17
|
+
if (!isWin && !(stats.mode & 0o111))
|
|
18
|
+
return false;
|
|
19
|
+
return true;
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function getSearchDirs() {
|
|
26
|
+
const home = os.homedir();
|
|
27
|
+
switch (process.platform) {
|
|
28
|
+
case 'win32':
|
|
29
|
+
return [];
|
|
30
|
+
case 'darwin':
|
|
31
|
+
return [
|
|
32
|
+
'/opt/homebrew/bin',
|
|
33
|
+
'/usr/local/bin',
|
|
34
|
+
'/usr/bin',
|
|
35
|
+
path.join(home, '.local', 'bin'),
|
|
36
|
+
];
|
|
37
|
+
default:
|
|
38
|
+
return [
|
|
39
|
+
path.join(home, '.local', 'bin'),
|
|
40
|
+
'/usr/local/bin',
|
|
41
|
+
'/usr/bin',
|
|
42
|
+
'/snap/bin',
|
|
43
|
+
];
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const SEARCH_DIRS = getSearchDirs();
|
|
47
|
+
/**
|
|
48
|
+
* Resolve a binary name to its full path.
|
|
49
|
+
* Checks platform-specific install locations so execFile works under
|
|
50
|
+
* systemd, launchd, and other environments with minimal PATH.
|
|
51
|
+
*/
|
|
52
|
+
export function resolveBin(name) {
|
|
53
|
+
// Reject names with path separators to prevent traversal
|
|
54
|
+
if (name.includes('/') || name.includes('\\') || name.includes('..')) {
|
|
55
|
+
throw new Error(`Invalid binary name: path separators not allowed`);
|
|
56
|
+
}
|
|
57
|
+
const cached = cache.get(name);
|
|
58
|
+
if (cached) {
|
|
59
|
+
if (isValidExecutable(cached)) {
|
|
60
|
+
return cached;
|
|
61
|
+
}
|
|
62
|
+
cache.delete(name);
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
const cmd = isWin ? 'where' : 'which';
|
|
66
|
+
const result = execFileSync(cmd, [name], { encoding: 'utf8', timeout: 3000 }).trim();
|
|
67
|
+
const resolved = result.split(/\r?\n/)[0];
|
|
68
|
+
if (resolved && isValidExecutable(resolved)) {
|
|
69
|
+
cache.set(name, resolved);
|
|
70
|
+
return resolved;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
// Lookup failed or binary not found in PATH
|
|
75
|
+
}
|
|
76
|
+
for (const dir of SEARCH_DIRS) {
|
|
77
|
+
const fullPath = path.join(dir, name);
|
|
78
|
+
if (isValidExecutable(fullPath)) {
|
|
79
|
+
cache.set(name, fullPath);
|
|
80
|
+
return fullPath;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
// Fall back to bare name and let execFile resolve via PATH
|
|
84
|
+
return name;
|
|
85
|
+
}
|
|
86
|
+
//# sourceMappingURL=resolve-bin.js.map
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { resolveBin } from './resolve-bin.js';
|
|
3
|
+
const require = createRequire(import.meta.url);
|
|
4
|
+
let cachedBundled;
|
|
5
|
+
function isMuslLibc() {
|
|
6
|
+
// On glibc systems, process.report.header includes glibcVersionRuntime.
|
|
7
|
+
// On musl (Alpine etc.), that field is absent.
|
|
8
|
+
const header = process.report?.getReport?.()?.header;
|
|
9
|
+
return !header?.glibcVersionRuntime;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Resolve the bundled Claude Code binary for the current Linux libc: the
|
|
13
|
+
* `claude` the Haiku side calls run through (side-call-options.ts). The ptys
|
|
14
|
+
* spawn resolvePtyClaudeBin below instead.
|
|
15
|
+
*
|
|
16
|
+
* The SDK's own auto-detection (sdk.mjs `N7`) tries the musl package first
|
|
17
|
+
* and only falls back when require.resolve throws. Both packages are
|
|
18
|
+
* installed as optional deps, so it always picks musl — which fails to
|
|
19
|
+
* spawn on glibc systems with a misleading "binary not found" error.
|
|
20
|
+
*
|
|
21
|
+
* Returns undefined on non-Linux platforms (SDK detection works correctly
|
|
22
|
+
* there) or when the matching package isn't installed.
|
|
23
|
+
*/
|
|
24
|
+
export function resolveBundledClaudeBin() {
|
|
25
|
+
if (process.platform !== 'linux')
|
|
26
|
+
return undefined;
|
|
27
|
+
if (cachedBundled !== undefined)
|
|
28
|
+
return cachedBundled ?? undefined;
|
|
29
|
+
const variant = isMuslLibc() ? `linux-${process.arch}-musl` : `linux-${process.arch}`;
|
|
30
|
+
const pkg = `@anthropic-ai/claude-agent-sdk-${variant}/claude`;
|
|
31
|
+
try {
|
|
32
|
+
cachedBundled = require.resolve(pkg);
|
|
33
|
+
return cachedBundled;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
cachedBundled = null;
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The `claude` the ptys run: CLAUDE_BIN, else the CLI found on PATH with
|
|
42
|
+
* ~/.local/bin searched first (see resolve-bin.ts). A path, not a bare name:
|
|
43
|
+
* node-pty execs the name as given, in the service's PATH, and a systemd user
|
|
44
|
+
* unit gets the bare default without ~/.local/bin, which is where the native
|
|
45
|
+
* installer puts the CLI. That failure is silent in the worst way: execvp
|
|
46
|
+
* writes "No such file or directory" into the pty and exits, so the bot sees a
|
|
47
|
+
* session that produced nothing and reports that the input box never appeared.
|
|
48
|
+
*/
|
|
49
|
+
export function resolvePtyClaudeBin() {
|
|
50
|
+
return process.env.CLAUDE_BIN || resolveBin('claude');
|
|
51
|
+
}
|
|
52
|
+
//# sourceMappingURL=resolve-claude-bin.js.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Backoff policy for respawning a bot instance that exited unexpectedly.
|
|
3
|
+
*
|
|
4
|
+
* Kept separate from the launcher so it can be tested directly — the launcher
|
|
5
|
+
* spawns worker threads and reads config at import time, and this is the part
|
|
6
|
+
* that only ever runs when something has already gone wrong.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Decide whether a crashed instance gets another respawn, and how long to wait.
|
|
10
|
+
*
|
|
11
|
+
* Crashes only accumulate while they cluster. An instance that survived
|
|
12
|
+
* `streakResetMs` before dying is treated as a first crash again, so two
|
|
13
|
+
* unrelated failures days apart never add up to a give-up.
|
|
14
|
+
*/
|
|
15
|
+
export function planRespawn({ aliveMs, previousStreak, delays, streakResetMs, }) {
|
|
16
|
+
const streak = aliveMs >= streakResetMs ? 1 : previousStreak + 1;
|
|
17
|
+
return { streak, delayMs: delays[streak - 1] ?? null };
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* How long to wait before respawning an instance that exited because Telegram
|
|
21
|
+
* couldn't be reached. Unlike a crash this never gives up: an outage ends on
|
|
22
|
+
* its own, and the bot should be back when it does.
|
|
23
|
+
*/
|
|
24
|
+
export function planOutageRespawn({ aliveMs, previousAttempts, delays, streakResetMs, }) {
|
|
25
|
+
const attempts = aliveMs >= streakResetMs ? 1 : previousAttempts + 1;
|
|
26
|
+
return { attempts, delayMs: delays[Math.min(attempts, delays.length) - 1] };
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=respawn-backoff.js.map
|
|
@@ -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
|