@online-tools/agent-runner 0.0.0-stage → 0.0.1-alpha-2
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/LICENSE +21 -0
- package/README.md +104 -2
- package/bin/gitcode-agent-runner.cjs +139 -0
- package/bin/main.mjs +675 -0
- package/lib/claude-cli.mjs +85 -0
- package/lib/config.mjs +126 -0
- package/lib/connection.mjs +191 -0
- package/lib/doctor.mjs +240 -0
- package/lib/http.mjs +198 -0
- package/lib/jobs.mjs +494 -0
- package/lib/lock.mjs +66 -0
- package/lib/log.mjs +22 -0
- package/lib/node-runtime.cjs +594 -0
- package/lib/packages.mjs +74 -0
- package/lib/prompt.mjs +76 -0
- package/lib/sandbox.mjs +110 -0
- package/lib/service.mjs +187 -0
- package/lib/setup.mjs +152 -0
- package/lib/skill-text.mjs +29 -0
- package/lib/skills.mjs +211 -0
- package/package.json +10 -4
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// Claude Code command line and environment, shared by the website
|
|
2
|
+
// (lib/agent-runners.js re-exports these for server runs) and the execution
|
|
3
|
+
// machine program (lib/jobs.mjs, lib/doctor.mjs). One copy only: the machine
|
|
4
|
+
// builds the exact command line the server uses, plus its sandbox settings.
|
|
5
|
+
//
|
|
6
|
+
// Only node: built-ins and files in this directory may be imported here, and
|
|
7
|
+
// importing must have no side effects.
|
|
8
|
+
|
|
9
|
+
export const CLAUDE_TOOLS = 'Bash,Read,Glob,Grep,Edit,Write,Skill,Agent';
|
|
10
|
+
|
|
11
|
+
const DEFAULT_PATH = '/usr/local/bin:/usr/bin:/bin';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* `interactive` (交互执行): the task and our answers go over stdin as stream-json,
|
|
15
|
+
* and permission prompts come to us (`--permission-prompt-tool stdio`, see
|
|
16
|
+
* lib/agent-interaction.js). AskUserQuestion is offered but deliberately not
|
|
17
|
+
* pre-allowed, so each call becomes a prompt we forward to the user.
|
|
18
|
+
*
|
|
19
|
+
* `settingsFile` (execution machines): appended as `--settings <file>`, which
|
|
20
|
+
* carries the sandbox settings; without it the arguments are exactly the
|
|
21
|
+
* server's.
|
|
22
|
+
*/
|
|
23
|
+
export function claudeArgs({ addDirs = [], interactive = false, settingsFile = '' } = {}) {
|
|
24
|
+
const args = [
|
|
25
|
+
'-p',
|
|
26
|
+
'--output-format',
|
|
27
|
+
'stream-json',
|
|
28
|
+
'--verbose',
|
|
29
|
+
...(interactive
|
|
30
|
+
? ['--input-format', 'stream-json', '--permission-prompt-tool', 'stdio']
|
|
31
|
+
: []),
|
|
32
|
+
// The service runs as root, where bypassPermissions is refused; an explicit
|
|
33
|
+
// allowlist plus acceptEdits runs unattended (anything else is auto-denied).
|
|
34
|
+
'--permission-mode',
|
|
35
|
+
'acceptEdits',
|
|
36
|
+
'--tools',
|
|
37
|
+
interactive ? `${CLAUDE_TOOLS},AskUserQuestion` : CLAUDE_TOOLS,
|
|
38
|
+
'--allowedTools',
|
|
39
|
+
CLAUDE_TOOLS,
|
|
40
|
+
// Only the per-run project (.claude/skills copy); never the host's user settings.
|
|
41
|
+
'--setting-sources',
|
|
42
|
+
'project',
|
|
43
|
+
'--strict-mcp-config',
|
|
44
|
+
'--no-session-persistence',
|
|
45
|
+
];
|
|
46
|
+
for (const dir of addDirs) args.push('--add-dir', dir);
|
|
47
|
+
if (settingsFile) args.push('--settings', settingsFile);
|
|
48
|
+
return args;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Claude Code appends /v1/messages itself.
|
|
52
|
+
export function claudeBaseUrl(baseUrl) {
|
|
53
|
+
return String(baseUrl || '').replace(/\/+$/, '').replace(/\/v1$/, '');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Environment of one claude process: run-local homes, the user's key and
|
|
58
|
+
* model, nothing else from the caller's environment except `path`. `extra`
|
|
59
|
+
* comes last (Skill credentials, run markers, pass-through proxy variables).
|
|
60
|
+
*/
|
|
61
|
+
export function claudeEnv({ path, runDir, homeDir, configDir, tmpDir = runDir, baseUrl, apiKey, model, extra = {} }) {
|
|
62
|
+
return {
|
|
63
|
+
PATH: path || DEFAULT_PATH,
|
|
64
|
+
HOME: homeDir,
|
|
65
|
+
CLAUDE_CONFIG_DIR: configDir,
|
|
66
|
+
TMPDIR: tmpDir,
|
|
67
|
+
LANG: 'C.UTF-8',
|
|
68
|
+
ANTHROPIC_BASE_URL: claudeBaseUrl(baseUrl),
|
|
69
|
+
ANTHROPIC_AUTH_TOKEN: apiKey,
|
|
70
|
+
// Every model slot (main, subagents, background helpers) uses the chosen model,
|
|
71
|
+
// so third-party endpoints never receive an unknown Claude model id.
|
|
72
|
+
ANTHROPIC_MODEL: model,
|
|
73
|
+
ANTHROPIC_DEFAULT_OPUS_MODEL: model,
|
|
74
|
+
ANTHROPIC_DEFAULT_SONNET_MODEL: model,
|
|
75
|
+
ANTHROPIC_DEFAULT_HAIKU_MODEL: model,
|
|
76
|
+
ANTHROPIC_SMALL_FAST_MODEL: model,
|
|
77
|
+
CLAUDE_CODE_SUBAGENT_MODEL: model,
|
|
78
|
+
API_TIMEOUT_MS: '600000',
|
|
79
|
+
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
|
|
80
|
+
DISABLE_AUTOUPDATER: '1',
|
|
81
|
+
DISABLE_TELEMETRY: '1',
|
|
82
|
+
DISABLE_ERROR_REPORTING: '1',
|
|
83
|
+
...extra,
|
|
84
|
+
};
|
|
85
|
+
}
|
package/lib/config.mjs
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// Where the program keeps things, and its config file:
|
|
2
|
+
// config ${XDG_CONFIG_HOME:-~/.config}/gitcode-agent-runner/config.json (dir 0700, file 0600)
|
|
3
|
+
// { server, token, clientId, setupDone, workRoot?, claudePath? }
|
|
4
|
+
// lock same directory, run.lock
|
|
5
|
+
// cache ${XDG_CACHE_HOME:-~/.cache}/gitcode-agent-runner/skills/
|
|
6
|
+
// work /var/tmp/gitcode-agent-runner-<uid>/ (Linux) or <tmpdir>/gitcode-agent-runner/
|
|
7
|
+
// (macOS): never inside HOME, which the sandbox may not read.
|
|
8
|
+
// Functions only; bin/ decides when to read or write.
|
|
9
|
+
|
|
10
|
+
import crypto from 'node:crypto';
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import os from 'node:os';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
|
|
15
|
+
export const DEFAULT_SERVER = 'https://online-tools.closerouter.site';
|
|
16
|
+
|
|
17
|
+
const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
18
|
+
|
|
19
|
+
export class ConfigError extends Error {}
|
|
20
|
+
|
|
21
|
+
export function configPaths(env = process.env, home = os.homedir()) {
|
|
22
|
+
const configDir = path.join(env.XDG_CONFIG_HOME || path.join(home, '.config'), 'gitcode-agent-runner');
|
|
23
|
+
const cacheDir = path.join(env.XDG_CACHE_HOME || path.join(home, '.cache'), 'gitcode-agent-runner');
|
|
24
|
+
return {
|
|
25
|
+
configDir,
|
|
26
|
+
configFile: path.join(configDir, 'config.json'),
|
|
27
|
+
lockFile: path.join(configDir, 'run.lock'),
|
|
28
|
+
cacheDir,
|
|
29
|
+
skillsDir: path.join(cacheDir, 'skills'),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function newClientId() {
|
|
34
|
+
return crypto.randomUUID();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function isClientId(value) {
|
|
38
|
+
return typeof value === 'string' && UUID_V4.test(value);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function normalize(raw) {
|
|
42
|
+
const config = {
|
|
43
|
+
server: typeof raw.server === 'string' ? raw.server : '',
|
|
44
|
+
token: typeof raw.token === 'string' ? raw.token : '',
|
|
45
|
+
clientId: isClientId(raw.clientId) ? raw.clientId : '',
|
|
46
|
+
setupDone: raw.setupDone === true,
|
|
47
|
+
};
|
|
48
|
+
if (typeof raw.workRoot === 'string' && raw.workRoot) config.workRoot = raw.workRoot;
|
|
49
|
+
if (typeof raw.claudePath === 'string' && raw.claudePath) config.claudePath = raw.claudePath;
|
|
50
|
+
return config;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The saved config (defaults when there is none); throws ConfigError when it is unreadable. */
|
|
54
|
+
export function loadConfig(paths) {
|
|
55
|
+
let text;
|
|
56
|
+
try {
|
|
57
|
+
text = fs.readFileSync(paths.configFile, 'utf8');
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (error.code === 'ENOENT') return normalize({});
|
|
60
|
+
throw new ConfigError(`无法读取配置文件 ${paths.configFile}:${error.message}`);
|
|
61
|
+
}
|
|
62
|
+
let raw;
|
|
63
|
+
try {
|
|
64
|
+
raw = JSON.parse(text);
|
|
65
|
+
} catch {
|
|
66
|
+
throw new ConfigError(`配置文件已损坏:${paths.configFile}(删除后运行 gitcode-agent-runner login)`);
|
|
67
|
+
}
|
|
68
|
+
return normalize(raw && typeof raw === 'object' ? raw : {});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Writes the config atomically (temporary file, then rename); dir 0700, file 0600. */
|
|
72
|
+
export function saveConfig(paths, config) {
|
|
73
|
+
fs.mkdirSync(paths.configDir, { recursive: true, mode: 0o700 });
|
|
74
|
+
fs.chmodSync(paths.configDir, 0o700);
|
|
75
|
+
const temp = `${paths.configFile}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
|
|
76
|
+
try {
|
|
77
|
+
fs.writeFileSync(temp, `${JSON.stringify(normalize(config), null, 2)}\n`, { mode: 0o600 });
|
|
78
|
+
fs.renameSync(temp, paths.configFile);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
fs.rmSync(temp, { force: true });
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
fs.chmodSync(paths.configFile, 0o600);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function defaultWorkRoot({ platform = process.platform, uid = process.getuid?.() ?? 0, tmpdir = os.tmpdir() } = {}) {
|
|
87
|
+
return platform === 'darwin' ? path.join(tmpdir, 'gitcode-agent-runner') : `/var/tmp/gitcode-agent-runner-${uid}`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function isInside(child, parent) {
|
|
91
|
+
return child === parent || child.startsWith(parent.endsWith(path.sep) ? parent : `${parent}${path.sep}`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function realpathOr(value) {
|
|
95
|
+
try {
|
|
96
|
+
return fs.realpathSync(value);
|
|
97
|
+
} catch {
|
|
98
|
+
return path.resolve(value);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export class WorkRootError extends Error {}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Creates (0700) and checks the work root: not inside HOME (also after
|
|
106
|
+
* resolving symlinks), not a symlink itself, owned by this user. Returns its
|
|
107
|
+
* real path, which everything else uses.
|
|
108
|
+
*/
|
|
109
|
+
export function prepareWorkRoot(dir, { home = os.homedir(), uid = process.getuid?.() ?? 0 } = {}) {
|
|
110
|
+
const resolved = path.resolve(dir);
|
|
111
|
+
const realHome = realpathOr(home);
|
|
112
|
+
const inHome = (value) => isInside(value, path.resolve(home)) || isInside(value, realHome);
|
|
113
|
+
const message = `工作目录 ${resolved} 在主目录(${home})之内;沙箱不允许读取主目录,请用 --work-dir 换到主目录之外`;
|
|
114
|
+
if (inHome(resolved) || inHome(path.join(realpathOr(path.dirname(resolved)), path.basename(resolved)))) {
|
|
115
|
+
throw new WorkRootError(message);
|
|
116
|
+
}
|
|
117
|
+
fs.mkdirSync(resolved, { recursive: true, mode: 0o700 });
|
|
118
|
+
const stat = fs.lstatSync(resolved);
|
|
119
|
+
if (stat.isSymbolicLink()) throw new WorkRootError(`工作目录 ${resolved} 不能是符号链接`);
|
|
120
|
+
if (!stat.isDirectory()) throw new WorkRootError(`${resolved} 不是目录`);
|
|
121
|
+
if (stat.uid !== uid) throw new WorkRootError(`工作目录 ${resolved} 的属主不是当前用户,请删除它或用 --work-dir 换一个目录`);
|
|
122
|
+
if ((stat.mode & 0o777) !== 0o700) fs.chmodSync(resolved, 0o700);
|
|
123
|
+
const real = fs.realpathSync(resolved);
|
|
124
|
+
if (inHome(real)) throw new WorkRootError(message);
|
|
125
|
+
return real;
|
|
126
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// Staying connected: the SSE control channel (jobs, cancels, revocation) and
|
|
2
|
+
// heartbeats, independent of each other. The channel reconnects with backoff
|
|
3
|
+
// (1 s doubling to 60 s, ±20 % jitter, reset after 60 s connected); heartbeats
|
|
4
|
+
// keep going while it is down, so running jobs are not lost.
|
|
5
|
+
//
|
|
6
|
+
// Ends with { code, message, clearToken? }: code 78 when someone must act
|
|
7
|
+
// (token deleted, machine blocked, the same config running twice), 0 when
|
|
8
|
+
// stopped through `signal`.
|
|
9
|
+
|
|
10
|
+
import { ApiError, IdleError } from './http.mjs';
|
|
11
|
+
|
|
12
|
+
export const UPDATE_COMMAND = 'npm i -g @online-tools/agent-runner@latest';
|
|
13
|
+
const IDLE_MS = 45_000;
|
|
14
|
+
const BACKOFF_START_MS = 1000;
|
|
15
|
+
const BACKOFF_MAX_MS = 60_000;
|
|
16
|
+
const STABLE_MS = 60_000;
|
|
17
|
+
const REPLACED_WINDOW_MS = 10 * 60_000;
|
|
18
|
+
const REPLACED_LIMIT = 3;
|
|
19
|
+
|
|
20
|
+
export const FATAL = {
|
|
21
|
+
tokenDeleted: {
|
|
22
|
+
code: 78,
|
|
23
|
+
clearToken: true,
|
|
24
|
+
message: '接入令牌已失效或已在网页上删除,已清除本机保存的令牌;请新建令牌后运行 gitcode-agent-runner login',
|
|
25
|
+
},
|
|
26
|
+
blocked: { code: 78, message: '这台机器已在网页上被封禁;解除封禁后请重新启动程序或服务' },
|
|
27
|
+
replaced: {
|
|
28
|
+
code: 78,
|
|
29
|
+
message: '控制通道 10 分钟内被挤掉 3 次:可能有另一台机器使用了相同的配置,请在复制出来的那台上运行 gitcode-agent-runner login --new-id',
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** The fatal result an API error means, or null. */
|
|
34
|
+
export function fatalFor(error) {
|
|
35
|
+
if (!(error instanceof ApiError)) return null;
|
|
36
|
+
if (error.status === 401) return FATAL.tokenDeleted;
|
|
37
|
+
if (error.status === 403 && error.code === 'machine_blocked') return FATAL.blocked;
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function compareVersions(a, b) {
|
|
42
|
+
const parse = (value) => (/^(\d+)\.(\d+)\.(\d+)/.exec(String(value)) || [0, 0, 0, 0]).slice(1, 4).map(Number);
|
|
43
|
+
const [x, y] = [parse(a), parse(b)];
|
|
44
|
+
for (let index = 0; index < 3; index += 1) if (x[index] !== y[index]) return x[index] < y[index] ? -1 : 1;
|
|
45
|
+
return 0;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function sleep(ms, signal) {
|
|
49
|
+
return new Promise((resolve) => {
|
|
50
|
+
if (signal?.aborted) return resolve();
|
|
51
|
+
const timer = setTimeout(done, ms);
|
|
52
|
+
function done() {
|
|
53
|
+
clearTimeout(timer);
|
|
54
|
+
signal?.removeEventListener('abort', done);
|
|
55
|
+
resolve();
|
|
56
|
+
}
|
|
57
|
+
signal?.addEventListener('abort', done, { once: true });
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function jitter(ms) {
|
|
62
|
+
return Math.round(ms * (0.8 + Math.random() * 0.4));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Runs until stopped or fatal.
|
|
67
|
+
* client http.mjs client
|
|
68
|
+
* jobs JobManager (handle / cancel / runningIds)
|
|
69
|
+
* connect() POST /connect again (after 409 machine_unknown); returns its reply
|
|
70
|
+
* capabilities { current(): object } — sent when changed and after every hello
|
|
71
|
+
* heartbeatMs from the connect reply
|
|
72
|
+
*/
|
|
73
|
+
export async function runConnection({ client, jobs, log, version, connect, capabilities, heartbeatMs = 20_000, signal }) {
|
|
74
|
+
const stopper = new AbortController();
|
|
75
|
+
const stop = AbortSignal.any([signal || new AbortController().signal, stopper.signal]);
|
|
76
|
+
const state = { result: null, heartbeatMs, replaced: [], sentCapabilities: '', warnedOutdated: false, toldLatest: '' };
|
|
77
|
+
|
|
78
|
+
const end = (result) => {
|
|
79
|
+
if (state.result) return;
|
|
80
|
+
state.result = result;
|
|
81
|
+
stopper.abort();
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const handleError = async (error) => {
|
|
85
|
+
const fatal = fatalFor(error);
|
|
86
|
+
if (fatal) {
|
|
87
|
+
end(fatal);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (error instanceof ApiError && error.status === 409 && error.code === 'machine_unknown') {
|
|
91
|
+
log.warn('网站上没有这台机器的记录(可能已被移除),重新登记');
|
|
92
|
+
try {
|
|
93
|
+
const reply = await connect();
|
|
94
|
+
if (reply?.heartbeatMs) state.heartbeatMs = reply.heartbeatMs;
|
|
95
|
+
state.sentCapabilities = '';
|
|
96
|
+
} catch (failure) {
|
|
97
|
+
const again = fatalFor(failure);
|
|
98
|
+
if (again) end(again);
|
|
99
|
+
else log.warn(`重新登记失败:${failure.message}`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const onEvent = (event) => {
|
|
105
|
+
switch (event?.type) {
|
|
106
|
+
case 'hello':
|
|
107
|
+
if (Number.isInteger(event.heartbeatMs) && event.heartbeatMs >= 1000) state.heartbeatMs = event.heartbeatMs;
|
|
108
|
+
// The website may have restarted: report capabilities again with the next heartbeat.
|
|
109
|
+
state.sentCapabilities = '';
|
|
110
|
+
break;
|
|
111
|
+
case 'job':
|
|
112
|
+
jobs.handle(event.job);
|
|
113
|
+
break;
|
|
114
|
+
case 'cancel':
|
|
115
|
+
if (typeof event.runId === 'string') jobs.cancel(event.runId);
|
|
116
|
+
break;
|
|
117
|
+
case 'revoked':
|
|
118
|
+
if (event.reason === 'token_deleted') end(FATAL.tokenDeleted);
|
|
119
|
+
else if (event.reason === 'machine_blocked') end(FATAL.blocked);
|
|
120
|
+
else if (event.reason === 'replaced') {
|
|
121
|
+
const now = Date.now();
|
|
122
|
+
state.replaced = state.replaced.filter((at) => now - at < REPLACED_WINDOW_MS);
|
|
123
|
+
state.replaced.push(now);
|
|
124
|
+
if (state.replaced.length >= REPLACED_LIMIT) end(FATAL.replaced);
|
|
125
|
+
else log.warn('控制通道被同一台机器的另一个连接替换,稍后重连');
|
|
126
|
+
}
|
|
127
|
+
break;
|
|
128
|
+
default:
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const heartbeats = (async () => {
|
|
134
|
+
while (!stop.aborted) {
|
|
135
|
+
await sleep(state.heartbeatMs, stop);
|
|
136
|
+
if (stop.aborted) break;
|
|
137
|
+
const body = { version, running: jobs.runningIds().slice(0, 200) };
|
|
138
|
+
const current = JSON.stringify(capabilities.current());
|
|
139
|
+
if (current !== state.sentCapabilities) body.capabilities = capabilities.current();
|
|
140
|
+
try {
|
|
141
|
+
const reply = await client.request('POST', '/heartbeat', body, { signal: stop });
|
|
142
|
+
if (body.capabilities) state.sentCapabilities = current;
|
|
143
|
+
for (const runId of Array.isArray(reply?.cancel) ? reply.cancel : []) jobs.cancel(runId);
|
|
144
|
+
if (reply?.outdated && !state.warnedOutdated) {
|
|
145
|
+
state.warnedOutdated = true;
|
|
146
|
+
log.warn(`程序版本 ${version} 已低于网站要求的 ${reply.minVersion},请运行 ${UPDATE_COMMAND} 后重启`);
|
|
147
|
+
} else if (reply?.latestVersion && reply.latestVersion !== state.toldLatest && compareVersions(version, reply.latestVersion) < 0) {
|
|
148
|
+
state.toldLatest = reply.latestVersion;
|
|
149
|
+
log.info(`有新版本 ${reply.latestVersion}:${UPDATE_COMMAND}`);
|
|
150
|
+
}
|
|
151
|
+
} catch (error) {
|
|
152
|
+
if (stop.aborted) break;
|
|
153
|
+
await handleError(error);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
})();
|
|
157
|
+
|
|
158
|
+
const channel = (async () => {
|
|
159
|
+
let delay = BACKOFF_START_MS;
|
|
160
|
+
while (!stop.aborted) {
|
|
161
|
+
let openedAt = 0;
|
|
162
|
+
try {
|
|
163
|
+
await client.stream('/stream', {
|
|
164
|
+
signal: stop,
|
|
165
|
+
idleMs: IDLE_MS,
|
|
166
|
+
onOpen: () => {
|
|
167
|
+
openedAt = Date.now();
|
|
168
|
+
log.info('控制通道已连接,等待任务');
|
|
169
|
+
},
|
|
170
|
+
onEvent,
|
|
171
|
+
});
|
|
172
|
+
if (!stop.aborted) log.warn('控制通道已断开,稍后重连');
|
|
173
|
+
} catch (error) {
|
|
174
|
+
if (stop.aborted) break;
|
|
175
|
+
if (error instanceof IdleError) log.warn(`${error.message},重新连接`);
|
|
176
|
+
else if (error instanceof ApiError) {
|
|
177
|
+
await handleError(error);
|
|
178
|
+
if (error.status === 429 && error.retryAfterMs) await sleep(error.retryAfterMs, stop);
|
|
179
|
+
else if (!state.result) log.warn(`控制通道连接失败:${error.message}`);
|
|
180
|
+
} else log.warn(`控制通道连接失败:${error?.cause?.code || error.message}`);
|
|
181
|
+
}
|
|
182
|
+
if (stop.aborted) break;
|
|
183
|
+
if (openedAt && Date.now() - openedAt >= STABLE_MS) delay = BACKOFF_START_MS;
|
|
184
|
+
await sleep(jitter(delay), stop);
|
|
185
|
+
delay = Math.min(BACKOFF_MAX_MS, delay * 2);
|
|
186
|
+
}
|
|
187
|
+
})();
|
|
188
|
+
|
|
189
|
+
await Promise.allSettled([heartbeats, channel]);
|
|
190
|
+
return state.result || { code: 0, message: '' };
|
|
191
|
+
}
|
package/lib/doctor.mjs
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
// What this machine can do: tools on PATH, claude and its version, the
|
|
2
|
+
// package manager, and whether the Claude Code sandbox starts. The result is
|
|
3
|
+
// reported to the website as `capabilities` (it decides which features run).
|
|
4
|
+
|
|
5
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import readline from 'node:readline';
|
|
9
|
+
|
|
10
|
+
import { claudeArgs, claudeEnv } from './claude-cli.mjs';
|
|
11
|
+
import { SANDBOX_TOOLS, SKILL_TOOLS, detectPackageManager } from './packages.mjs';
|
|
12
|
+
import { caPaths, createRunLayout, homeReadAllow, passThroughEnv, writeSandboxSettings } from './sandbox.mjs';
|
|
13
|
+
|
|
14
|
+
export const PROBE_TIMEOUT_MS = 20_000;
|
|
15
|
+
export const SANDBOX_DOCS = 'https://code.claude.com/docs/en/sandboxing';
|
|
16
|
+
|
|
17
|
+
function isExecutableFile(file) {
|
|
18
|
+
try {
|
|
19
|
+
fs.accessSync(file, fs.constants.X_OK);
|
|
20
|
+
return fs.statSync(file).isFile();
|
|
21
|
+
} catch {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Absolute path of `name` on PATH, or ''. */
|
|
27
|
+
export function which(name, pathEnv = process.env.PATH) {
|
|
28
|
+
for (const dir of String(pathEnv || '').split(path.delimiter)) {
|
|
29
|
+
if (!dir || !path.isAbsolute(dir)) continue;
|
|
30
|
+
const candidate = path.join(dir, name);
|
|
31
|
+
if (isExecutableFile(candidate)) return candidate;
|
|
32
|
+
}
|
|
33
|
+
return '';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** First group of `pattern` in `file --version`; null when it does not run (exit ≠ 0). */
|
|
37
|
+
function versionOf(file, pattern, env) {
|
|
38
|
+
const result = spawnSync(file, ['--version'], {
|
|
39
|
+
encoding: 'utf8',
|
|
40
|
+
timeout: 10_000,
|
|
41
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
42
|
+
env,
|
|
43
|
+
});
|
|
44
|
+
if (result.error || result.status !== 0) return null;
|
|
45
|
+
return pattern.exec(`${result.stdout || ''}\n${result.stderr || ''}`)?.[1] || '';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* { [tool]: { ok, path, version } } for the Skill tools (git and python3 must
|
|
50
|
+
* also run: on macOS they may be stubs that only offer to install the
|
|
51
|
+
* Command Line Tools) and, on Linux, the sandbox's bwrap and socat.
|
|
52
|
+
*/
|
|
53
|
+
export function checkTools({ platform = process.platform, pathEnv = process.env.PATH } = {}) {
|
|
54
|
+
const tools = {};
|
|
55
|
+
for (const name of SKILL_TOOLS) {
|
|
56
|
+
const file = which(name, pathEnv);
|
|
57
|
+
let ok = Boolean(file);
|
|
58
|
+
let version = '';
|
|
59
|
+
if (ok && (name === 'git' || name === 'python3')) {
|
|
60
|
+
const found = versionOf(file, name === 'git' ? /git version (\d+(?:\.\d+)*)/ : /Python (\d+(?:\.\d+)*)/);
|
|
61
|
+
ok = found !== null;
|
|
62
|
+
version = found || '';
|
|
63
|
+
}
|
|
64
|
+
tools[name] = { ok, path: file, version };
|
|
65
|
+
}
|
|
66
|
+
if (platform === 'linux') {
|
|
67
|
+
for (const name of SANDBOX_TOOLS) {
|
|
68
|
+
const file = which(name, pathEnv);
|
|
69
|
+
tools[name] = { ok: Boolean(file), path: file, version: '' };
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return tools;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Where claude is: CLAUDE_BIN, the saved claudePath, PATH, then
|
|
77
|
+
* `$(npm prefix -g)/bin/claude` (viaNpmPrefix: tell the user to add it to PATH).
|
|
78
|
+
*/
|
|
79
|
+
export function resolveClaude({ env = process.env, configured = '', pathEnv = env.PATH } = {}) {
|
|
80
|
+
for (const candidate of [env.CLAUDE_BIN, configured]) {
|
|
81
|
+
if (candidate && isExecutableFile(candidate)) return { path: candidate, viaNpmPrefix: false };
|
|
82
|
+
}
|
|
83
|
+
const found = which('claude', pathEnv);
|
|
84
|
+
if (found) return { path: found, viaNpmPrefix: false };
|
|
85
|
+
const npm = which('npm', pathEnv);
|
|
86
|
+
if (npm) {
|
|
87
|
+
const result = spawnSync(npm, ['prefix', '-g'], { encoding: 'utf8', timeout: 20_000, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
88
|
+
const prefix = result.status === 0 ? result.stdout.trim() : '';
|
|
89
|
+
const file = prefix ? path.join(prefix, 'bin', 'claude') : '';
|
|
90
|
+
if (file && isExecutableFile(file)) return { path: file, viaNpmPrefix: true };
|
|
91
|
+
}
|
|
92
|
+
return { path: '', viaNpmPrefix: false };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** claude's version (x.y.z), '' when it does not run. */
|
|
96
|
+
export function claudeVersion(file, env = process.env) {
|
|
97
|
+
if (!file) return '';
|
|
98
|
+
return versionOf(file, /^(\d+\.\d+\.\d+)/m, { ...env, DISABLE_AUTOUPDATER: '1' }) || '';
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function killGroup(child, signal) {
|
|
102
|
+
try {
|
|
103
|
+
process.kill(-child.pid, signal);
|
|
104
|
+
} catch {
|
|
105
|
+
// Already gone.
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function failureReason(stderr, resultText, code) {
|
|
110
|
+
const line = stderr.find((item) => /sandbox/i.test(item)) || stderr[0] || resultText || `claude 退出码 ${code}`;
|
|
111
|
+
return [...line.replace(/\p{Cc}/gu, ' ').replace(/^error:\s*/i, '').trim()].slice(0, 300).join('');
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Starts claude exactly as for a job (same arguments, settings, environment)
|
|
116
|
+
* but with an unreachable model address (http://127.0.0.1:9) and the task
|
|
117
|
+
* "probe": no request leaves the machine. `system/init` on stdout means the
|
|
118
|
+
* sandbox started (the process group is then killed). Exiting without it
|
|
119
|
+
* means it did not; the reason is claude's error line. The real guarantee is
|
|
120
|
+
* failIfUnavailable in every job's settings, not this check.
|
|
121
|
+
*/
|
|
122
|
+
export async function probeSandbox({
|
|
123
|
+
claudePath,
|
|
124
|
+
workRoot,
|
|
125
|
+
realHome,
|
|
126
|
+
env = process.env,
|
|
127
|
+
platform = process.platform,
|
|
128
|
+
timeoutMs = PROBE_TIMEOUT_MS,
|
|
129
|
+
}) {
|
|
130
|
+
if (!claudePath) return { ok: false, reason: '未安装 claude' };
|
|
131
|
+
const pathEnv = env.PATH || '';
|
|
132
|
+
const layout = createRunLayout(fs.mkdtempSync(path.join(workRoot, 'probe-')));
|
|
133
|
+
try {
|
|
134
|
+
writeSandboxSettings(layout.settingsFile, {
|
|
135
|
+
workDir: layout.workDir,
|
|
136
|
+
realHome,
|
|
137
|
+
readAllow: homeReadAllow({ realHome, pathEnv, caPaths: caPaths(env) }),
|
|
138
|
+
});
|
|
139
|
+
const child = spawn(claudePath, claudeArgs({ settingsFile: layout.settingsFile }), {
|
|
140
|
+
cwd: layout.workDir,
|
|
141
|
+
detached: true,
|
|
142
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
143
|
+
env: claudeEnv({
|
|
144
|
+
path: pathEnv,
|
|
145
|
+
runDir: layout.runDir,
|
|
146
|
+
homeDir: layout.homeDir,
|
|
147
|
+
configDir: layout.configDir,
|
|
148
|
+
tmpDir: layout.tmpDir,
|
|
149
|
+
baseUrl: 'http://127.0.0.1:9',
|
|
150
|
+
apiKey: 'probe',
|
|
151
|
+
model: 'probe',
|
|
152
|
+
extra: passThroughEnv(env, platform),
|
|
153
|
+
}),
|
|
154
|
+
});
|
|
155
|
+
const exited = new Promise((resolve) => child.once('close', resolve));
|
|
156
|
+
const verdict = new Promise((resolve) => {
|
|
157
|
+
const stderr = [];
|
|
158
|
+
let resultText = '';
|
|
159
|
+
let done = false;
|
|
160
|
+
const finish = (value) => {
|
|
161
|
+
if (done) return;
|
|
162
|
+
done = true;
|
|
163
|
+
clearTimeout(timer);
|
|
164
|
+
killGroup(child, 'SIGKILL');
|
|
165
|
+
resolve(value);
|
|
166
|
+
};
|
|
167
|
+
const timer = setTimeout(() => finish({ ok: false, reason: '沙箱检测超时' }), timeoutMs);
|
|
168
|
+
child.once('error', (error) => finish({ ok: false, reason: `无法启动 claude:${error.code || error.message}` }));
|
|
169
|
+
readline.createInterface({ input: child.stdout }).on('line', (line) => {
|
|
170
|
+
let event;
|
|
171
|
+
try {
|
|
172
|
+
event = JSON.parse(line);
|
|
173
|
+
} catch {
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (event?.type === 'system' && event.subtype === 'init') finish({ ok: true, reason: '' });
|
|
177
|
+
else if (event?.type === 'result' && typeof event.result === 'string') resultText = event.result;
|
|
178
|
+
});
|
|
179
|
+
readline.createInterface({ input: child.stderr }).on('line', (line) => {
|
|
180
|
+
if (line.trim()) stderr.push(line.trim());
|
|
181
|
+
});
|
|
182
|
+
child.once('close', (code) => finish({ ok: false, reason: failureReason(stderr, resultText, code) }));
|
|
183
|
+
});
|
|
184
|
+
child.stdin.on('error', () => {});
|
|
185
|
+
child.stdin.end('probe');
|
|
186
|
+
const result = await verdict;
|
|
187
|
+
// The process group is gone (or going): give it a moment before deleting its directory.
|
|
188
|
+
await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 3000).unref())]);
|
|
189
|
+
return result;
|
|
190
|
+
} finally {
|
|
191
|
+
fs.rmSync(layout.runDir, { recursive: true, force: true });
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Full check. `probe: false` skips the sandbox probe (it then reads as not
|
|
197
|
+
* checked). Returns { capabilities, tools, claude, claudeVersion, packageManager }.
|
|
198
|
+
*/
|
|
199
|
+
export async function runDoctor({
|
|
200
|
+
env = process.env,
|
|
201
|
+
platform = process.platform,
|
|
202
|
+
arch = process.arch,
|
|
203
|
+
configuredClaude = '',
|
|
204
|
+
workRoot,
|
|
205
|
+
realHome,
|
|
206
|
+
probe = true,
|
|
207
|
+
probeTimeoutMs = PROBE_TIMEOUT_MS,
|
|
208
|
+
}) {
|
|
209
|
+
const pathEnv = env.PATH || '';
|
|
210
|
+
const tools = checkTools({ platform, pathEnv });
|
|
211
|
+
const claude = resolveClaude({ env, configured: configuredClaude, pathEnv });
|
|
212
|
+
const version = claudeVersion(claude.path, env);
|
|
213
|
+
const packageManager = detectPackageManager({ platform, which: (name) => which(name, pathEnv) });
|
|
214
|
+
let sandbox;
|
|
215
|
+
if (!claude.path) sandbox = { ok: false, reason: '未安装 claude' };
|
|
216
|
+
else if (!probe) sandbox = { ok: false, reason: '尚未检测沙箱' };
|
|
217
|
+
else {
|
|
218
|
+
sandbox = await probeSandbox({ claudePath: claude.path, workRoot, realHome, env, platform, timeoutMs: probeTimeoutMs });
|
|
219
|
+
if (!sandbox.ok && platform === 'linux') {
|
|
220
|
+
// The common case, in words the user can act on (setup installs them).
|
|
221
|
+
const missing = SANDBOX_TOOLS.filter((name) => !tools[name]?.ok).map((name) => (name === 'bwrap' ? 'bubblewrap' : name));
|
|
222
|
+
if (missing.length) sandbox = { ok: false, reason: `缺少 ${missing.join('、')}` };
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return {
|
|
226
|
+
capabilities: {
|
|
227
|
+
os: platform,
|
|
228
|
+
arch,
|
|
229
|
+
node: process.versions.node,
|
|
230
|
+
claude: version,
|
|
231
|
+
tools: Object.fromEntries(SKILL_TOOLS.map((name) => [name, Boolean(tools[name]?.ok)])),
|
|
232
|
+
sandbox,
|
|
233
|
+
packageManager,
|
|
234
|
+
},
|
|
235
|
+
tools,
|
|
236
|
+
claude,
|
|
237
|
+
claudeVersion: version,
|
|
238
|
+
packageManager,
|
|
239
|
+
};
|
|
240
|
+
}
|