@online-tools/agent-runner 0.0.1-alpha-2 → 0.0.1-alpha-4
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/README.md +16 -6
- package/bin/main.mjs +86 -16
- package/lib/config.mjs +3 -1
- package/lib/connection.mjs +36 -2
- package/lib/doctor.mjs +64 -15
- package/lib/jobs.mjs +15 -4
- package/lib/probe-model.mjs +129 -0
- package/lib/prompt.mjs +18 -0
- package/lib/sandbox.mjs +26 -0
- package/lib/system-info.mjs +132 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -10,12 +10,16 @@ GitCode 在线工具的 Agent 执行机器:把「在线 Agent」里的 **PR
|
|
|
10
10
|
|
|
11
11
|
```bash
|
|
12
12
|
npm i -g @online-tools/agent-runner
|
|
13
|
-
gitcode-agent-runner # 首次运行:粘贴接入令牌 → 连接 → 检查并安装依赖 → 保持在线
|
|
13
|
+
gitcode-agent-runner # 首次运行:粘贴接入令牌 → 起名字 → 连接 → 检查并安装依赖 → 保持在线
|
|
14
14
|
gitcode-agent-runner service install # 可选:注册为后台服务,开机自启
|
|
15
15
|
```
|
|
16
16
|
|
|
17
17
|
接入令牌在网页「在线 Agent → 模型配置 → 接入令牌」里新建。粘贴后先向网站校验,通过才保存;以后启动直接连接。
|
|
18
18
|
|
|
19
|
+
粘贴令牌后会问这台机器叫什么(回车用主机名;脚本里用 `--name <名称>`),网页上就用这个名字。之后改名请在网页上改。
|
|
20
|
+
|
|
21
|
+
**新机器要在网页上确认后才会收到任务**:打开「在线 Agent → 模型配置 → 执行机器」,核对主机名、IP 和令牌后点「确认」(也可以在这里改名字)。确认前程序照样保持在线,确认后会提示「可以接收任务了」。不是你的机器出现在那里时,请封禁它并删除对应的令牌。
|
|
22
|
+
|
|
19
23
|
首次运行会检查依赖并列出要执行的安装命令,确认后才执行:
|
|
20
24
|
|
|
21
25
|
- `git`、`curl`、`python3`、`jq`、`sed`、`base64`:Skill 需要(各功能需要的不完全一样)
|
|
@@ -31,22 +35,26 @@ gitcode-agent-runner service install # 可选:注册为后台服务,开
|
|
|
31
35
|
| 命令 | 作用 |
|
|
32
36
|
|---|---|
|
|
33
37
|
| `gitcode-agent-runner [start]` | 连接网站并等待任务 |
|
|
34
|
-
| `login [--new-id] [--token-stdin]` | 输入(更换)接入令牌,校验通过才保存。`--new-id`
|
|
38
|
+
| `login [--new-id] [--token-stdin] [--name <名称>]` | 输入(更换)接入令牌,校验通过才保存。`--new-id` 重新生成机器标识(网页上会作为新机器出现,需要重新确认);`--token-stdin` 从标准输入读令牌 |
|
|
35
39
|
| `logout` | 清除本机保存的令牌(机器标识保留) |
|
|
36
40
|
| `setup [--yes]` | 检查并安装缺少或版本过低的依赖(只在终端里运行;`--yes` 跳过确认) |
|
|
37
|
-
| `doctor [--json]` |
|
|
38
|
-
| `status` | 网站地址、令牌前 12
|
|
41
|
+
| `doctor [--json]` | 检查依赖、沙箱和各功能是否可用,显示系统信息 |
|
|
42
|
+
| `status` | 网站地址、令牌前 12 位、机器标识、登记名称、工作目录、系统信息、服务状态和连接测试 |
|
|
39
43
|
| `service install \| uninstall \| status` | 后台服务:Linux 为 systemd 用户服务,macOS 为 launchd |
|
|
40
44
|
| `version` / `help` | — |
|
|
41
45
|
|
|
42
|
-
全局选项:`--server <url>`(默认 `https://online-tools.closerouter.site`,会保存)、`--work-dir <dir>`(会保存)、`--allow-root`。
|
|
46
|
+
全局选项:`--server <url>`(默认 `https://online-tools.closerouter.site`,会保存)、`--work-dir <dir>`(会保存)、`--name <名称>`(机器登记时用的名称,1–40 个字符,会保存)、`--allow-root`。
|
|
43
47
|
|
|
44
48
|
文件位置:
|
|
45
49
|
|
|
46
50
|
- 配置:`${XDG_CONFIG_HOME:-~/.config}/gitcode-agent-runner/config.json`(0600)
|
|
47
51
|
- Skill 缓存:`${XDG_CACHE_HOME:-~/.cache}/gitcode-agent-runner/skills/`
|
|
48
52
|
- 自动下载的 Node(只有系统 Node 过旧时才有):`${XDG_DATA_HOME:-~/.local/share}/gitcode-agent-runner/node/`
|
|
49
|
-
- 工作目录:Linux `/var/tmp/gitcode-agent-runner-<uid>/`,macOS `$TMPDIR/gitcode-agent-runner
|
|
53
|
+
- 工作目录:Linux `/var/tmp/gitcode-agent-runner-<uid>/`,macOS `$TMPDIR/gitcode-agent-runner/`。**不能在主目录之内**(沙箱不允许读取主目录);Linux 上路径不能超过 49 字节(沙箱的通信 socket 建在每个任务的临时目录里,socket 路径最多 107 字节),默认目录没有问题。每个任务一个 `runs/<7 个字符>` 运行目录,结束即删
|
|
54
|
+
|
|
55
|
+
## 上报给网站的信息
|
|
56
|
+
|
|
57
|
+
除了程序版本和各项依赖是否可用,程序还会在连接和每次心跳(约 20 秒)时上报这台机器的概况,显示在网页「执行机器」的「资源」和「详情」里(只有你和网站管理员看得到):系统和内核、CPU 型号和核数、内存总量和可用量(容器有内存限制时同时显示限制)、工作目录所在磁盘的总量和可用量、负载、系统运行时间、运行程序的账号、是否在容器内、是否在用程序自动下载的 Node。不上报文件内容、环境变量或进程列表。
|
|
50
58
|
|
|
51
59
|
## 任务怎么运行
|
|
52
60
|
|
|
@@ -87,6 +95,8 @@ gitcode-agent-runner service install # 可选:注册为后台服务,开
|
|
|
87
95
|
|
|
88
96
|
退出码:0 正常退出;1 出错;78 需要人处理(没有令牌、令牌已删除、机器已封禁、同一配置在两台机器上运行、系统或 Node 不支持、以 root 运行、已有实例在运行),后台服务遇到 78 不会自动重启。
|
|
89
97
|
|
|
98
|
+
沙箱检测(启动时和之后每小时)会像真实任务一样启动 claude,并让它在沙箱里执行一条 `echo`:模型换成本机 127.0.0.1 上的一个替身,不访问网络、不需要 API Key。命令能在沙箱里跑通才算可用,否则网页和 `doctor` 会显示 Claude Code 给出的原因(例如 `Failed to create bridge sockets…`、bubblewrap 无法创建命名空间)。
|
|
99
|
+
|
|
90
100
|
沙箱不可用时请先运行 `gitcode-agent-runner setup`;在非特权容器或禁用了非特权 user namespace 的系统(例如开启了 AppArmor 限制的 Ubuntu 24.04+)上沙箱可能无法启动,详见 https://code.claude.com/docs/en/sandboxing 。
|
|
91
101
|
|
|
92
102
|
## 卸载
|
package/bin/main.mjs
CHANGED
|
@@ -33,15 +33,17 @@ import { FEATURE_LABELS, JobManager } from '../lib/jobs.mjs';
|
|
|
33
33
|
import { LockedError, acquireLock, isRunnerAlive } from '../lib/lock.mjs';
|
|
34
34
|
import { NODE_REQUIREMENT, nodeSupported } from '../lib/node-runtime.cjs';
|
|
35
35
|
import { createLogger } from '../lib/log.mjs';
|
|
36
|
-
import { CancelledError, askYesNo, isInteractive, readHidden, readStdin } from '../lib/prompt.mjs';
|
|
36
|
+
import { CancelledError, askText, askYesNo, isInteractive, readHidden, readStdin } from '../lib/prompt.mjs';
|
|
37
37
|
import { EXIT_NEEDS_ATTENTION, installService, serviceExitCode, serviceStatus, uninstallService } from '../lib/service.mjs';
|
|
38
38
|
import { DEFAULT_REQUIRED_TOOLS, npmPrefixWritable, planSetup, runSetup } from '../lib/setup.mjs';
|
|
39
39
|
import { SkillCache } from '../lib/skills.mjs';
|
|
40
|
+
import { collectSystemInfo, describeSystem } from '../lib/system-info.mjs';
|
|
40
41
|
|
|
41
42
|
// The command's entry point (it checks the Node version, then loads this file).
|
|
42
43
|
const ENTRY = fileURLToPath(new URL('./gitcode-agent-runner.cjs', import.meta.url));
|
|
43
44
|
const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
44
45
|
const TOKEN_PATTERN = /^gcm_[A-Za-z0-9_-]{43}$/;
|
|
46
|
+
const NAME_MAX_CHARS = 40; // the website's limit (normalizeMachineName)
|
|
45
47
|
const DOCTOR_INTERVAL_MS = 60 * 60_000;
|
|
46
48
|
const ATTENTION = EXIT_NEEDS_ATTENTION;
|
|
47
49
|
|
|
@@ -58,7 +60,7 @@ const USAGE = `GitCode Agent 执行机器 ${VERSION}
|
|
|
58
60
|
|
|
59
61
|
命令:
|
|
60
62
|
start 连接网站并等待任务(默认)
|
|
61
|
-
login [--new-id] [--token-stdin]
|
|
63
|
+
login [--new-id] [--token-stdin] [--name <名称>]
|
|
62
64
|
输入接入令牌(校验通过才保存);--new-id 重新生成机器标识
|
|
63
65
|
logout 清除本机保存的令牌(机器标识保留)
|
|
64
66
|
setup [--yes] 检查并安装缺少的依赖(需在终端里运行)
|
|
@@ -71,6 +73,7 @@ const USAGE = `GitCode Agent 执行机器 ${VERSION}
|
|
|
71
73
|
选项:
|
|
72
74
|
--server <url> 网站地址(默认 ${DEFAULT_SERVER},会保存)
|
|
73
75
|
--work-dir <dir> 工作目录(不能在主目录之内,会保存)
|
|
76
|
+
--name <名称> 这台机器登记时用的名称(默认主机名,会保存;登记后在网页上修改)
|
|
74
77
|
--allow-root 允许以 root 运行(仅限容器等确有需要的场合)`;
|
|
75
78
|
|
|
76
79
|
class ExitError extends Error {
|
|
@@ -113,7 +116,14 @@ function realHome() {
|
|
|
113
116
|
}
|
|
114
117
|
}
|
|
115
118
|
|
|
116
|
-
/**
|
|
119
|
+
/** A name the website accepts: trimmed, 1–40 characters, no control characters; else ''. */
|
|
120
|
+
function machineName(value) {
|
|
121
|
+
const name = String(value ?? '').trim();
|
|
122
|
+
const length = [...name].length;
|
|
123
|
+
return length >= 1 && length <= NAME_MAX_CHARS && !/\p{Cc}/u.test(name) ? name : '';
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Config, server, client id and work root; --server / --work-dir / --name are saved. */
|
|
117
127
|
function loadContext(values, { workRoot: needWorkRoot = true } = {}) {
|
|
118
128
|
const paths = configPaths();
|
|
119
129
|
const config = loadConfig(paths);
|
|
@@ -132,6 +142,14 @@ function loadContext(values, { workRoot: needWorkRoot = true } = {}) {
|
|
|
132
142
|
config.server = server;
|
|
133
143
|
changed = true;
|
|
134
144
|
}
|
|
145
|
+
if (values.name !== undefined) {
|
|
146
|
+
const name = machineName(values.name);
|
|
147
|
+
if (!name) throw new ExitError(1, `名称需为 1–${NAME_MAX_CHARS} 个字符,不能包含控制字符`);
|
|
148
|
+
if (name !== config.machineName) {
|
|
149
|
+
config.machineName = name;
|
|
150
|
+
changed = true;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
135
153
|
if (values['work-dir']) {
|
|
136
154
|
const dir = path.resolve(values['work-dir']);
|
|
137
155
|
if (dir !== config.workRoot) {
|
|
@@ -152,8 +170,49 @@ function clientFor(ctx, token = ctx.config.token) {
|
|
|
152
170
|
return createClient({ server: ctx.server, token, clientId: ctx.config.clientId, version: VERSION });
|
|
153
171
|
}
|
|
154
172
|
|
|
155
|
-
|
|
156
|
-
|
|
173
|
+
/** POST /connect. `name` only names a machine the website does not know yet. */
|
|
174
|
+
function connect(ctx, client, capabilities) {
|
|
175
|
+
return client.request('POST', '/connect', {
|
|
176
|
+
hostname: os.hostname(),
|
|
177
|
+
name: ctx.config.machineName || '',
|
|
178
|
+
version: VERSION,
|
|
179
|
+
capabilities,
|
|
180
|
+
system: systemInfo(ctx),
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function systemInfo(ctx) {
|
|
185
|
+
return collectSystemInfo({ workRoot: ctx.workRoot || ctx.config.workRoot || defaultWorkRoot() });
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** After /connect: what the machine is called there, and whether its owner confirmed it. */
|
|
189
|
+
function sayRegistered(ctx, reply) {
|
|
190
|
+
say(`✓ 已连接 ${ctx.server},本机登记为「${reply.name}」(令牌:${reply.tokenName})`);
|
|
191
|
+
if (!reply.created && ctx.config.machineName && reply.name !== ctx.config.machineName) {
|
|
192
|
+
say(` 这台机器之前已登记为「${reply.name}」,名称请在网页上修改`);
|
|
193
|
+
}
|
|
194
|
+
if (reply.confirmed === false) {
|
|
195
|
+
say('⚠ 这台机器还没有确认,确认后才会收到任务:请在网页「在线 Agent → 模型配置 → 执行机器」里核对主机名和 IP 后点「确认」');
|
|
196
|
+
say(` ${ctx.server}/features#agent/config`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** First login in a terminal: the name this machine registers with (Enter = hostname). */
|
|
201
|
+
async function askMachineName(ctx) {
|
|
202
|
+
const hostname = os.hostname();
|
|
203
|
+
for (;;) {
|
|
204
|
+
const answer = await askText(`给这台机器起个名字(回车使用主机名 ${hostname}):`);
|
|
205
|
+
if (!answer) {
|
|
206
|
+
ctx.config.machineName = machineName(hostname) || '';
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
const name = machineName(answer);
|
|
210
|
+
if (name) {
|
|
211
|
+
ctx.config.machineName = name;
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
say(`名称需为 1–${NAME_MAX_CHARS} 个字符,不能包含控制字符`);
|
|
215
|
+
}
|
|
157
216
|
}
|
|
158
217
|
|
|
159
218
|
function networkReason(error) {
|
|
@@ -193,12 +252,13 @@ async function obtainToken(ctx, { fromStdin = false, capabilities }) {
|
|
|
193
252
|
say('令牌格式不正确(应为 gcm_ 开头的 47 个字符),请重新粘贴');
|
|
194
253
|
continue;
|
|
195
254
|
}
|
|
255
|
+
if (!fromStdin && !ctx.config.machineName) await askMachineName(ctx);
|
|
196
256
|
const client = clientFor(ctx, token);
|
|
197
257
|
try {
|
|
198
|
-
const reply = await connect(client, capabilities);
|
|
258
|
+
const reply = await connect(ctx, client, capabilities);
|
|
199
259
|
ctx.config.token = token;
|
|
200
260
|
save(ctx);
|
|
201
|
-
|
|
261
|
+
sayRegistered(ctx, reply);
|
|
202
262
|
return { client, reply };
|
|
203
263
|
} catch (error) {
|
|
204
264
|
if (error instanceof ApiError && error.status === 401) {
|
|
@@ -218,7 +278,7 @@ async function connectSaved(ctx, client, capabilities) {
|
|
|
218
278
|
let delay = 1000;
|
|
219
279
|
for (;;) {
|
|
220
280
|
try {
|
|
221
|
-
return await connect(client, capabilities);
|
|
281
|
+
return await connect(ctx, client, capabilities);
|
|
222
282
|
} catch (error) {
|
|
223
283
|
const fatal = fatalFor(error);
|
|
224
284
|
if (fatal) {
|
|
@@ -337,7 +397,7 @@ async function start(values) {
|
|
|
337
397
|
} else {
|
|
338
398
|
client = clientFor(ctx);
|
|
339
399
|
reply = await connectSaved(ctx, client, result.capabilities);
|
|
340
|
-
|
|
400
|
+
sayRegistered(ctx, reply);
|
|
341
401
|
}
|
|
342
402
|
printDoctor(result);
|
|
343
403
|
if (!ctx.config.setupDone && interactive) {
|
|
@@ -409,8 +469,10 @@ async function serve(ctx, client, initial, reply) {
|
|
|
409
469
|
jobs,
|
|
410
470
|
log,
|
|
411
471
|
version: VERSION,
|
|
412
|
-
connect: () => connect(client, capabilities),
|
|
472
|
+
connect: () => connect(ctx, client, capabilities),
|
|
413
473
|
capabilities: { current: () => capabilities },
|
|
474
|
+
system: { current: () => systemInfo(ctx) },
|
|
475
|
+
confirmed: reply.confirmed !== false,
|
|
414
476
|
heartbeatMs: reply.heartbeatMs,
|
|
415
477
|
signal: controller.signal,
|
|
416
478
|
});
|
|
@@ -433,8 +495,10 @@ async function login(values) {
|
|
|
433
495
|
const ctx = loadContext(values);
|
|
434
496
|
if (values['new-id']) {
|
|
435
497
|
ctx.config.clientId = newClientId();
|
|
498
|
+
// A new machine on the website: ask for its name again (unless --name gave one).
|
|
499
|
+
if (values.name === undefined) ctx.config.machineName = '';
|
|
436
500
|
save(ctx);
|
|
437
|
-
say('
|
|
501
|
+
say('已生成新的机器标识:这台机器在网页上会作为新机器出现,需要在网页上确认');
|
|
438
502
|
}
|
|
439
503
|
if (!values['token-stdin'] && !isInteractive()) throw new ExitError(ATTENTION, 'login 需要在终端里运行(脚本里请用 --token-stdin)');
|
|
440
504
|
say('检查依赖和沙箱……');
|
|
@@ -465,7 +529,7 @@ async function setup(values) {
|
|
|
465
529
|
if (ctx.config.token) {
|
|
466
530
|
client = clientFor(ctx);
|
|
467
531
|
try {
|
|
468
|
-
reply = await connect(client, result.capabilities);
|
|
532
|
+
reply = await connect(ctx, client, result.capabilities);
|
|
469
533
|
} catch (error) {
|
|
470
534
|
say(`无法从网站读取要求(${error.message}),按默认要求检查`);
|
|
471
535
|
client = null;
|
|
@@ -484,7 +548,7 @@ async function setup(values) {
|
|
|
484
548
|
if (outcome.ran) {
|
|
485
549
|
say('重新检查……');
|
|
486
550
|
result = await doctorFor(ctx);
|
|
487
|
-
if (client) reply = await connect(client, result.capabilities).catch(() => reply);
|
|
551
|
+
if (client) reply = await connect(ctx, client, result.capabilities).catch(() => reply);
|
|
488
552
|
printDoctor(result);
|
|
489
553
|
}
|
|
490
554
|
printFeatures(reply);
|
|
@@ -502,18 +566,21 @@ async function doctor(values) {
|
|
|
502
566
|
if (ctx.config.token) {
|
|
503
567
|
try {
|
|
504
568
|
// Also brings the website's copy of this machine's capabilities up to date.
|
|
505
|
-
reply = await connect(clientFor(ctx), result.capabilities);
|
|
569
|
+
reply = await connect(ctx, clientFor(ctx), result.capabilities);
|
|
506
570
|
} catch (error) {
|
|
507
571
|
note = error instanceof ApiError && error.status === 401 ? '令牌无效或已删除' : `无法连接网站:${error instanceof ApiError ? error.message : networkReason(error)}`;
|
|
508
572
|
}
|
|
509
573
|
} else note = '还没有接入令牌,无法判断各功能(运行 gitcode-agent-runner login)';
|
|
574
|
+
const system = systemInfo(ctx);
|
|
510
575
|
if (values.json) {
|
|
511
|
-
say(JSON.stringify({ version: VERSION, capabilities: result.capabilities, claudePath: result.claude.path, features: reply?.features || null, note }, null, 2));
|
|
576
|
+
say(JSON.stringify({ version: VERSION, capabilities: result.capabilities, system, claudePath: result.claude.path, features: reply?.features || null, confirmed: reply?.confirmed ?? null, note }, null, 2));
|
|
512
577
|
return 0;
|
|
513
578
|
}
|
|
514
579
|
say(`GitCode Agent 执行机器 ${VERSION} · Node ${process.versions.node} · ${process.platform}/${process.arch}`);
|
|
580
|
+
say(`系统:${describeSystem(system)}`);
|
|
515
581
|
printDoctor(result);
|
|
516
582
|
printFeatures(reply);
|
|
583
|
+
if (reply?.confirmed === false) say('这台机器还没有在网页上确认,确认后才会收到任务(在线 Agent → 模型配置 → 执行机器)');
|
|
517
584
|
if (note) say(note);
|
|
518
585
|
return 0;
|
|
519
586
|
}
|
|
@@ -527,7 +594,9 @@ async function status(values) {
|
|
|
527
594
|
say(`网站:${ctx.server}`);
|
|
528
595
|
say(`令牌:${config.token ? `${config.token.slice(0, 12)}…` : '未登录(运行 gitcode-agent-runner login)'}`);
|
|
529
596
|
say(`机器标识:${config.clientId}`);
|
|
597
|
+
say(`登记名称:${config.machineName || `${os.hostname()}(主机名)`}`);
|
|
530
598
|
say(`工作目录:${config.workRoot || defaultWorkRoot()}`);
|
|
599
|
+
say(`系统:${describeSystem(systemInfo(ctx))}`);
|
|
531
600
|
say(`配置文件:${ctx.paths.configFile}`);
|
|
532
601
|
const service = serviceStatus();
|
|
533
602
|
say(`后台服务:${service.installed ? service.state : '未安装'}${service.installed ? `(${service.logHint})` : ''}`);
|
|
@@ -549,7 +618,7 @@ async function status(values) {
|
|
|
549
618
|
404: '正常',
|
|
550
619
|
401: '令牌无效或已删除(运行 gitcode-agent-runner login)',
|
|
551
620
|
403: '这台机器已被封禁',
|
|
552
|
-
409: '令牌有效,这台机器尚未登记(运行 gitcode-agent-runner
|
|
621
|
+
409: '令牌有效,这台机器尚未登记(运行 gitcode-agent-runner 会自动登记,之后在网页上确认)',
|
|
553
622
|
}[error.status] || error.message;
|
|
554
623
|
say(`连接测试:${text}`);
|
|
555
624
|
} else say(`连接测试:失败(${networkReason(error)})`);
|
|
@@ -608,6 +677,7 @@ async function main(argv) {
|
|
|
608
677
|
options: {
|
|
609
678
|
server: { type: 'string' },
|
|
610
679
|
'work-dir': { type: 'string' },
|
|
680
|
+
name: { type: 'string' },
|
|
611
681
|
'allow-root': { type: 'boolean' },
|
|
612
682
|
'new-id': { type: 'boolean' },
|
|
613
683
|
'token-stdin': { type: 'boolean' },
|
package/lib/config.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Where the program keeps things, and its config file:
|
|
2
2
|
// config ${XDG_CONFIG_HOME:-~/.config}/gitcode-agent-runner/config.json (dir 0700, file 0600)
|
|
3
|
-
// { server, token, clientId, setupDone, workRoot?, claudePath? }
|
|
3
|
+
// { server, token, clientId, setupDone, workRoot?, claudePath?, machineName? }
|
|
4
4
|
// lock same directory, run.lock
|
|
5
5
|
// cache ${XDG_CACHE_HOME:-~/.cache}/gitcode-agent-runner/skills/
|
|
6
6
|
// work /var/tmp/gitcode-agent-runner-<uid>/ (Linux) or <tmpdir>/gitcode-agent-runner/
|
|
@@ -47,6 +47,8 @@ function normalize(raw) {
|
|
|
47
47
|
};
|
|
48
48
|
if (typeof raw.workRoot === 'string' && raw.workRoot) config.workRoot = raw.workRoot;
|
|
49
49
|
if (typeof raw.claudePath === 'string' && raw.claudePath) config.claudePath = raw.claudePath;
|
|
50
|
+
// The name sent with /connect: it names this machine when the website registers it.
|
|
51
|
+
if (typeof raw.machineName === 'string' && raw.machineName) config.machineName = raw.machineName.slice(0, 100);
|
|
50
52
|
return config;
|
|
51
53
|
}
|
|
52
54
|
|
package/lib/connection.mjs
CHANGED
|
@@ -68,12 +68,33 @@ function jitter(ms) {
|
|
|
68
68
|
* jobs JobManager (handle / cancel / runningIds)
|
|
69
69
|
* connect() POST /connect again (after 409 machine_unknown); returns its reply
|
|
70
70
|
* capabilities { current(): object } — sent when changed and after every hello
|
|
71
|
+
* system { current(): object } — system details, sent with every heartbeat (optional)
|
|
72
|
+
* confirmed whether the owner has confirmed this machine (from the connect reply);
|
|
73
|
+
* the program says so once when that changes
|
|
71
74
|
* heartbeatMs from the connect reply
|
|
72
75
|
*/
|
|
73
|
-
export async function runConnection({
|
|
76
|
+
export async function runConnection({
|
|
77
|
+
client,
|
|
78
|
+
jobs,
|
|
79
|
+
log,
|
|
80
|
+
version,
|
|
81
|
+
connect,
|
|
82
|
+
capabilities,
|
|
83
|
+
system,
|
|
84
|
+
confirmed = true,
|
|
85
|
+
heartbeatMs = 20_000,
|
|
86
|
+
signal,
|
|
87
|
+
}) {
|
|
74
88
|
const stopper = new AbortController();
|
|
75
89
|
const stop = AbortSignal.any([signal || new AbortController().signal, stopper.signal]);
|
|
76
|
-
const state = { result: null, heartbeatMs, replaced: [], sentCapabilities: '', warnedOutdated: false, toldLatest: '' };
|
|
90
|
+
const state = { result: null, heartbeatMs, replaced: [], sentCapabilities: '', warnedOutdated: false, toldLatest: '', confirmed };
|
|
91
|
+
|
|
92
|
+
const noteConfirmed = (value, name = '') => {
|
|
93
|
+
if (typeof value !== 'boolean' || value === state.confirmed) return;
|
|
94
|
+
state.confirmed = value;
|
|
95
|
+
if (value) log.info(`✓ 网页上已确认这台机器${name ? `「${name}」` : ''},可以接收任务了`);
|
|
96
|
+
else log.warn('这台机器需要在网页上(重新)确认后才会收到任务:在线 Agent → 模型配置 → 执行机器');
|
|
97
|
+
};
|
|
77
98
|
|
|
78
99
|
const end = (result) => {
|
|
79
100
|
if (state.result) return;
|
|
@@ -93,6 +114,7 @@ export async function runConnection({ client, jobs, log, version, connect, capab
|
|
|
93
114
|
const reply = await connect();
|
|
94
115
|
if (reply?.heartbeatMs) state.heartbeatMs = reply.heartbeatMs;
|
|
95
116
|
state.sentCapabilities = '';
|
|
117
|
+
noteConfirmed(reply?.confirmed, reply?.name);
|
|
96
118
|
} catch (failure) {
|
|
97
119
|
const again = fatalFor(failure);
|
|
98
120
|
if (again) end(again);
|
|
@@ -107,10 +129,14 @@ export async function runConnection({ client, jobs, log, version, connect, capab
|
|
|
107
129
|
if (Number.isInteger(event.heartbeatMs) && event.heartbeatMs >= 1000) state.heartbeatMs = event.heartbeatMs;
|
|
108
130
|
// The website may have restarted: report capabilities again with the next heartbeat.
|
|
109
131
|
state.sentCapabilities = '';
|
|
132
|
+
noteConfirmed(event.confirmed);
|
|
110
133
|
break;
|
|
111
134
|
case 'job':
|
|
112
135
|
jobs.handle(event.job);
|
|
113
136
|
break;
|
|
137
|
+
case 'confirmed':
|
|
138
|
+
noteConfirmed(true, typeof event.name === 'string' ? event.name.slice(0, 40) : '');
|
|
139
|
+
break;
|
|
114
140
|
case 'cancel':
|
|
115
141
|
if (typeof event.runId === 'string') jobs.cancel(event.runId);
|
|
116
142
|
break;
|
|
@@ -137,10 +163,18 @@ export async function runConnection({ client, jobs, log, version, connect, capab
|
|
|
137
163
|
const body = { version, running: jobs.runningIds().slice(0, 200) };
|
|
138
164
|
const current = JSON.stringify(capabilities.current());
|
|
139
165
|
if (current !== state.sentCapabilities) body.capabilities = capabilities.current();
|
|
166
|
+
if (system) {
|
|
167
|
+
try {
|
|
168
|
+
body.system = system.current();
|
|
169
|
+
} catch (error) {
|
|
170
|
+
log.warn(`读取系统信息失败:${error.message}`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
140
173
|
try {
|
|
141
174
|
const reply = await client.request('POST', '/heartbeat', body, { signal: stop });
|
|
142
175
|
if (body.capabilities) state.sentCapabilities = current;
|
|
143
176
|
for (const runId of Array.isArray(reply?.cancel) ? reply.cancel : []) jobs.cancel(runId);
|
|
177
|
+
noteConfirmed(reply?.confirmed);
|
|
144
178
|
if (reply?.outdated && !state.warnedOutdated) {
|
|
145
179
|
state.warnedOutdated = true;
|
|
146
180
|
log.warn(`程序版本 ${version} 已低于网站要求的 ${reply.minVersion},请运行 ${UPDATE_COMMAND} 后重启`);
|
package/lib/doctor.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// What this machine can do: tools on PATH, claude and its version, the
|
|
2
|
-
// package manager, and whether
|
|
3
|
-
// reported to the website as `capabilities` (it
|
|
2
|
+
// package manager, and whether a command really runs in the Claude Code
|
|
3
|
+
// sandbox. The result is reported to the website as `capabilities` (it
|
|
4
|
+
// decides which features run).
|
|
4
5
|
|
|
5
6
|
import { spawn, spawnSync } from 'node:child_process';
|
|
6
7
|
import fs from 'node:fs';
|
|
@@ -9,9 +10,18 @@ import readline from 'node:readline';
|
|
|
9
10
|
|
|
10
11
|
import { claudeArgs, claudeEnv } from './claude-cli.mjs';
|
|
11
12
|
import { SANDBOX_TOOLS, SKILL_TOOLS, detectPackageManager } from './packages.mjs';
|
|
12
|
-
import {
|
|
13
|
+
import { PROBE_MARKER, PROBE_TOOL_ID, startProbeModel } from './probe-model.mjs';
|
|
14
|
+
import {
|
|
15
|
+
caPaths,
|
|
16
|
+
createRunLayout,
|
|
17
|
+
homeReadAllow,
|
|
18
|
+
newRunDir,
|
|
19
|
+
passThroughEnv,
|
|
20
|
+
socketPathProblem,
|
|
21
|
+
writeSandboxSettings,
|
|
22
|
+
} from './sandbox.mjs';
|
|
13
23
|
|
|
14
|
-
export const PROBE_TIMEOUT_MS =
|
|
24
|
+
export const PROBE_TIMEOUT_MS = 60_000;
|
|
15
25
|
export const SANDBOX_DOCS = 'https://code.claude.com/docs/en/sandboxing';
|
|
16
26
|
|
|
17
27
|
function isExecutableFile(file) {
|
|
@@ -111,13 +121,41 @@ function failureReason(stderr, resultText, code) {
|
|
|
111
121
|
return [...line.replace(/\p{Cc}/gu, ' ').replace(/^error:\s*/i, '').trim()].slice(0, 300).join('');
|
|
112
122
|
}
|
|
113
123
|
|
|
124
|
+
function blockText(content) {
|
|
125
|
+
if (typeof content === 'string') return content;
|
|
126
|
+
if (!Array.isArray(content)) return '';
|
|
127
|
+
return content.map((item) => (typeof item?.text === 'string' ? item.text : '')).join('\n');
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** What went wrong with the probe command, without Claude Code's boilerplate. */
|
|
131
|
+
export function sandboxFailure(text) {
|
|
132
|
+
const cleaned = String(text || '')
|
|
133
|
+
.replace(/^Exit code \d+\s*/i, '')
|
|
134
|
+
.replace(/^Sandbox is required but failed to initialize:\s*/i, '')
|
|
135
|
+
.replace(/\s*Restart to retry\.?/i, '')
|
|
136
|
+
.replace(/\s*Running it outside the sandbox[^.]*\.?/i, '')
|
|
137
|
+
.replace(/\p{Cc}/gu, ' ')
|
|
138
|
+
.replace(/\s+/g, ' ')
|
|
139
|
+
.trim();
|
|
140
|
+
return [...(cleaned || '沙箱里的命令没有正常执行')].slice(0, 300).join('');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** NO_PROXY with the stand-in model's address added, so a proxy never sits between claude and it. */
|
|
144
|
+
function localNoProxy(env) {
|
|
145
|
+
const current = env.NO_PROXY || env.no_proxy || '';
|
|
146
|
+
const value = [current, '127.0.0.1', 'localhost'].filter(Boolean).join(',');
|
|
147
|
+
return { NO_PROXY: value, no_proxy: value };
|
|
148
|
+
}
|
|
149
|
+
|
|
114
150
|
/**
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
-
* sandbox
|
|
119
|
-
*
|
|
120
|
-
*
|
|
151
|
+
* Runs claude exactly as for a job (same arguments, sandbox settings,
|
|
152
|
+
* environment and run directory shape) against a stand-in model on 127.0.0.1
|
|
153
|
+
* (probe-model.mjs) that asks for one Bash call: `echo <PROBE_MARKER>`. The
|
|
154
|
+
* sandbox only starts on a job's first command, so only the command's result
|
|
155
|
+
* tells whether jobs can run: its output means yes; an error is the reason
|
|
156
|
+
* (e.g. "Failed to create bridge sockets…"). claude exiting first gives its
|
|
157
|
+
* own reason (missing bubblewrap…). No request leaves the machine. The real
|
|
158
|
+
* guarantee remains failIfUnavailable in every job's settings.
|
|
121
159
|
*/
|
|
122
160
|
export async function probeSandbox({
|
|
123
161
|
claudePath,
|
|
@@ -129,13 +167,17 @@ export async function probeSandbox({
|
|
|
129
167
|
}) {
|
|
130
168
|
if (!claudePath) return { ok: false, reason: '未安装 claude' };
|
|
131
169
|
const pathEnv = env.PATH || '';
|
|
132
|
-
const layout = createRunLayout(
|
|
170
|
+
const layout = createRunLayout(newRunDir(path.join(workRoot, 'runs'), 'p'));
|
|
171
|
+
let model = null;
|
|
133
172
|
try {
|
|
173
|
+
const tooLong = socketPathProblem(layout.tmpDir, platform);
|
|
174
|
+
if (tooLong) return { ok: false, reason: tooLong };
|
|
134
175
|
writeSandboxSettings(layout.settingsFile, {
|
|
135
176
|
workDir: layout.workDir,
|
|
136
177
|
realHome,
|
|
137
178
|
readAllow: homeReadAllow({ realHome, pathEnv, caPaths: caPaths(env) }),
|
|
138
179
|
});
|
|
180
|
+
model = await startProbeModel();
|
|
139
181
|
const child = spawn(claudePath, claudeArgs({ settingsFile: layout.settingsFile }), {
|
|
140
182
|
cwd: layout.workDir,
|
|
141
183
|
detached: true,
|
|
@@ -146,10 +188,10 @@ export async function probeSandbox({
|
|
|
146
188
|
homeDir: layout.homeDir,
|
|
147
189
|
configDir: layout.configDir,
|
|
148
190
|
tmpDir: layout.tmpDir,
|
|
149
|
-
baseUrl:
|
|
191
|
+
baseUrl: model.baseUrl,
|
|
150
192
|
apiKey: 'probe',
|
|
151
193
|
model: 'probe',
|
|
152
|
-
extra: passThroughEnv(env, platform),
|
|
194
|
+
extra: { ...passThroughEnv(env, platform), ...localNoProxy(env) },
|
|
153
195
|
}),
|
|
154
196
|
});
|
|
155
197
|
const exited = new Promise((resolve) => child.once('close', resolve));
|
|
@@ -173,8 +215,14 @@ export async function probeSandbox({
|
|
|
173
215
|
} catch {
|
|
174
216
|
return;
|
|
175
217
|
}
|
|
176
|
-
if (event?.type === '
|
|
177
|
-
|
|
218
|
+
if (event?.type === 'result' && typeof event.result === 'string') resultText = event.result;
|
|
219
|
+
if (event?.type !== 'user' || !Array.isArray(event.message?.content)) return;
|
|
220
|
+
for (const block of event.message.content) {
|
|
221
|
+
if (block?.type !== 'tool_result' || block.tool_use_id !== PROBE_TOOL_ID) continue;
|
|
222
|
+
const text = blockText(block.content);
|
|
223
|
+
if (!block.is_error && text.includes(PROBE_MARKER)) finish({ ok: true, reason: '' });
|
|
224
|
+
else finish({ ok: false, reason: sandboxFailure(text) });
|
|
225
|
+
}
|
|
178
226
|
});
|
|
179
227
|
readline.createInterface({ input: child.stderr }).on('line', (line) => {
|
|
180
228
|
if (line.trim()) stderr.push(line.trim());
|
|
@@ -188,6 +236,7 @@ export async function probeSandbox({
|
|
|
188
236
|
await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 3000).unref())]);
|
|
189
237
|
return result;
|
|
190
238
|
} finally {
|
|
239
|
+
await model?.close();
|
|
191
240
|
fs.rmSync(layout.runDir, { recursive: true, force: true });
|
|
192
241
|
}
|
|
193
242
|
}
|
package/lib/jobs.mjs
CHANGED
|
@@ -16,7 +16,15 @@ import { StringDecoder } from 'node:string_decoder';
|
|
|
16
16
|
|
|
17
17
|
import { claudeArgs, claudeEnv } from './claude-cli.mjs';
|
|
18
18
|
import { ApiError } from './http.mjs';
|
|
19
|
-
import {
|
|
19
|
+
import {
|
|
20
|
+
caPaths,
|
|
21
|
+
createRunLayout,
|
|
22
|
+
homeReadAllow,
|
|
23
|
+
newRunDir,
|
|
24
|
+
passThroughEnv,
|
|
25
|
+
socketPathProblem,
|
|
26
|
+
writeSandboxSettings,
|
|
27
|
+
} from './sandbox.mjs';
|
|
20
28
|
|
|
21
29
|
export const FEATURE_LABELS = {
|
|
22
30
|
'pr-desc-issue-gen': 'PR 描述 / Issue',
|
|
@@ -370,11 +378,14 @@ export class JobManager {
|
|
|
370
378
|
return;
|
|
371
379
|
}
|
|
372
380
|
|
|
373
|
-
|
|
381
|
+
// A short directory name, not the run id: see socketPathProblem().
|
|
382
|
+
let runDir = '';
|
|
374
383
|
let layout;
|
|
375
384
|
try {
|
|
376
|
-
|
|
385
|
+
runDir = newRunDir(this.runsDir, 'r');
|
|
377
386
|
layout = createRunLayout(runDir);
|
|
387
|
+
const tooLong = socketPathProblem(layout.tmpDir, this.platform);
|
|
388
|
+
if (tooLong) throw new Error(tooLong);
|
|
378
389
|
this.skills.copyInto(job.skillsHash, files, layout.skillsDir, layout.workAgentDir);
|
|
379
390
|
writeSandboxSettings(layout.settingsFile, {
|
|
380
391
|
workDir: fs.realpathSync(layout.workDir),
|
|
@@ -382,7 +393,7 @@ export class JobManager {
|
|
|
382
393
|
readAllow: homeReadAllow({ realHome: this.realHome, pathEnv: this.env.PATH || '', caPaths: caPaths(this.env) }),
|
|
383
394
|
});
|
|
384
395
|
} catch (error) {
|
|
385
|
-
fs.rmSync(runDir, { recursive: true, force: true });
|
|
396
|
+
if (runDir) fs.rmSync(runDir, { recursive: true, force: true });
|
|
386
397
|
await this.reportExit(entry, { error: `准备运行目录失败:${error?.message || error}` });
|
|
387
398
|
return;
|
|
388
399
|
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// A stand-in model for the sandbox check (doctor.mjs probeSandbox): an
|
|
2
|
+
// Anthropic Messages API on 127.0.0.1 that answers Claude Code's first request
|
|
3
|
+
// with one Bash call, `echo <PROBE_MARKER>`, and everything else with a short
|
|
4
|
+
// text. Claude Code then runs that command in its sandbox exactly as in a job,
|
|
5
|
+
// so the check sees what a job would see (the sandbox only starts on the
|
|
6
|
+
// first command; a started claude proves little). No request leaves the
|
|
7
|
+
// machine and no key is involved.
|
|
8
|
+
|
|
9
|
+
import http from 'node:http';
|
|
10
|
+
|
|
11
|
+
export const PROBE_TOOL_ID = 'toolu_01GitcodeSandboxProbe';
|
|
12
|
+
export const PROBE_MARKER = 'gitcode-sandbox-probe-ok';
|
|
13
|
+
const BODY_LIMIT = 16 * 1024 * 1024;
|
|
14
|
+
|
|
15
|
+
function hasProbeResult(messages) {
|
|
16
|
+
return messages.some(
|
|
17
|
+
(message) =>
|
|
18
|
+
Array.isArray(message?.content) &&
|
|
19
|
+
message.content.some((block) => block?.type === 'tool_result' && block.tool_use_id === PROBE_TOOL_ID),
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The probe call for the main conversation (it offers Bash); text for anything else. */
|
|
24
|
+
export function probeReply(request) {
|
|
25
|
+
const messages = Array.isArray(request?.messages) ? request.messages : [];
|
|
26
|
+
const offersBash = Array.isArray(request?.tools) && request.tools.some((tool) => tool?.name === 'Bash');
|
|
27
|
+
if (offersBash && !hasProbeResult(messages)) {
|
|
28
|
+
return {
|
|
29
|
+
block: { type: 'tool_use', id: PROBE_TOOL_ID, name: 'Bash', input: { command: `echo ${PROBE_MARKER}`, description: 'Sandbox check' } },
|
|
30
|
+
stopReason: 'tool_use',
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
return { block: { type: 'text', text: 'ok' }, stopReason: 'end_turn' };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function send(res, status, body) {
|
|
37
|
+
res.writeHead(status, { 'content-type': 'application/json' });
|
|
38
|
+
res.end(JSON.stringify(body));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function stream(res, message, { block, stopReason }) {
|
|
42
|
+
const events = [
|
|
43
|
+
{ type: 'message_start', message },
|
|
44
|
+
{
|
|
45
|
+
type: 'content_block_start',
|
|
46
|
+
index: 0,
|
|
47
|
+
content_block: block.type === 'tool_use' ? { ...block, input: {} } : { type: 'text', text: '' },
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
type: 'content_block_delta',
|
|
51
|
+
index: 0,
|
|
52
|
+
delta:
|
|
53
|
+
block.type === 'tool_use'
|
|
54
|
+
? { type: 'input_json_delta', partial_json: JSON.stringify(block.input) }
|
|
55
|
+
: { type: 'text_delta', text: block.text },
|
|
56
|
+
},
|
|
57
|
+
{ type: 'content_block_stop', index: 0 },
|
|
58
|
+
{ type: 'message_delta', delta: { stop_reason: stopReason, stop_sequence: null }, usage: { output_tokens: 1 } },
|
|
59
|
+
{ type: 'message_stop' },
|
|
60
|
+
];
|
|
61
|
+
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
|
|
62
|
+
for (const event of events) res.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);
|
|
63
|
+
res.end();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function handle(req, res, body) {
|
|
67
|
+
const url = String(req.url || '');
|
|
68
|
+
if (req.method !== 'POST' || !url.startsWith('/v1/messages')) {
|
|
69
|
+
send(res, 404, { type: 'error', error: { type: 'not_found_error', message: 'not found' } });
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
let request = {};
|
|
73
|
+
try {
|
|
74
|
+
request = JSON.parse(body || '{}');
|
|
75
|
+
} catch {
|
|
76
|
+
send(res, 400, { type: 'error', error: { type: 'invalid_request_error', message: 'invalid JSON' } });
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (url.startsWith('/v1/messages/count_tokens')) {
|
|
80
|
+
send(res, 200, { input_tokens: 1 });
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const reply = probeReply(request);
|
|
84
|
+
const message = {
|
|
85
|
+
id: 'msg_gitcode_sandbox_probe',
|
|
86
|
+
type: 'message',
|
|
87
|
+
role: 'assistant',
|
|
88
|
+
model: typeof request.model === 'string' ? request.model : 'probe',
|
|
89
|
+
content: [],
|
|
90
|
+
stop_reason: null,
|
|
91
|
+
stop_sequence: null,
|
|
92
|
+
usage: { input_tokens: 1, output_tokens: 1 },
|
|
93
|
+
};
|
|
94
|
+
if (request.stream === true) stream(res, message, reply);
|
|
95
|
+
else send(res, 200, { ...message, content: [reply.block], stop_reason: reply.stopReason });
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Starts the stand-in on a free port of 127.0.0.1: { baseUrl, close() }. */
|
|
99
|
+
export async function startProbeModel() {
|
|
100
|
+
const server = http.createServer((req, res) => {
|
|
101
|
+
const chunks = [];
|
|
102
|
+
let size = 0;
|
|
103
|
+
req.on('data', (chunk) => {
|
|
104
|
+
size += chunk.length;
|
|
105
|
+
if (size > BODY_LIMIT) {
|
|
106
|
+
send(res, 413, { type: 'error', error: { type: 'request_too_large', message: 'too large' } });
|
|
107
|
+
req.destroy();
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
chunks.push(chunk);
|
|
111
|
+
});
|
|
112
|
+
req.on('end', () => {
|
|
113
|
+
if (!res.headersSent) handle(req, res, Buffer.concat(chunks).toString('utf8'));
|
|
114
|
+
});
|
|
115
|
+
req.on('error', () => {});
|
|
116
|
+
});
|
|
117
|
+
await new Promise((resolve, reject) => {
|
|
118
|
+
server.once('error', reject);
|
|
119
|
+
server.listen(0, '127.0.0.1', resolve);
|
|
120
|
+
});
|
|
121
|
+
return {
|
|
122
|
+
baseUrl: `http://127.0.0.1:${server.address().port}`,
|
|
123
|
+
close: () =>
|
|
124
|
+
new Promise((resolve) => {
|
|
125
|
+
server.closeAllConnections();
|
|
126
|
+
server.close(() => resolve());
|
|
127
|
+
}),
|
|
128
|
+
};
|
|
129
|
+
}
|
package/lib/prompt.mjs
CHANGED
|
@@ -51,6 +51,24 @@ export function readHidden(question, { input = process.stdin, output = process.s
|
|
|
51
51
|
});
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
+
/** One line of visible text, trimmed; Ctrl+C / Ctrl+D reject with CancelledError. */
|
|
55
|
+
export function askText(question, { input = process.stdin, output = process.stdout } = {}) {
|
|
56
|
+
return new Promise((resolve, reject) => {
|
|
57
|
+
const rl = readline.createInterface({ input, output });
|
|
58
|
+
let answered = false;
|
|
59
|
+
rl.on('close', () => {
|
|
60
|
+
if (answered) return;
|
|
61
|
+
output.write('\n');
|
|
62
|
+
reject(new CancelledError());
|
|
63
|
+
});
|
|
64
|
+
rl.question(question, (answer) => {
|
|
65
|
+
answered = true;
|
|
66
|
+
rl.close();
|
|
67
|
+
resolve(String(answer || '').trim());
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
54
72
|
/** [Y/n] question; an empty answer takes the default. */
|
|
55
73
|
export async function askYesNo(question, { defaultYes = true, input = process.stdin, output = process.stdout } = {}) {
|
|
56
74
|
const rl = readline.createInterface({ input, output });
|
package/lib/sandbox.mjs
CHANGED
|
@@ -70,6 +70,32 @@ export function homeReadAllow({ realHome, pathEnv = '', caPaths = [] }) {
|
|
|
70
70
|
return [...allowed];
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
+
// Claude Code's Linux sandbox bridges its network proxies into the sandbox
|
|
74
|
+
// through Unix sockets named $TMPDIR/claude-http-<16 hex>.sock and
|
|
75
|
+
// claude-socks-<16 hex>.sock, and a Unix socket path holds at most 107 bytes.
|
|
76
|
+
// With a longer TMPDIR every sandboxed command fails ("Failed to create bridge
|
|
77
|
+
// sockets"), so run directories are kept short: <work root>/runs/<7 characters>,
|
|
78
|
+
// TMPDIR <run>/work/.tmp. Jobs and the sandbox check use the same shape, so the
|
|
79
|
+
// check sees the same path lengths a job does.
|
|
80
|
+
const UNIX_SOCKET_PATH_MAX = 107;
|
|
81
|
+
const BRIDGE_SOCKET_NAME = '/claude-socks-0123456789abcdef.sock';
|
|
82
|
+
const RUN_TMP_SUFFIX = '/runs/r123456/work/.tmp';
|
|
83
|
+
export const WORK_ROOT_MAX_BYTES = UNIX_SOCKET_PATH_MAX - BRIDGE_SOCKET_NAME.length - RUN_TMP_SUFFIX.length;
|
|
84
|
+
|
|
85
|
+
/** Why the sandbox cannot start with this TMPDIR ('' = it can). Linux only: macOS bridges over TCP. */
|
|
86
|
+
export function socketPathProblem(tmpDir, platform = process.platform) {
|
|
87
|
+
if (platform !== 'linux') return '';
|
|
88
|
+
const bytes = Buffer.byteLength(String(tmpDir)) + BRIDGE_SOCKET_NAME.length;
|
|
89
|
+
if (bytes <= UNIX_SOCKET_PATH_MAX) return '';
|
|
90
|
+
return `工作目录的路径太长:沙箱的通信 socket 路径要 ${bytes} 字节,超过 Linux 的上限 ${UNIX_SOCKET_PATH_MAX};请用 --work-dir 换一个不超过 ${WORK_ROOT_MAX_BYTES} 字节的目录`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** A new, empty run directory <runsDir>/<prefix + 6 random characters> (0700); `prefix` is one character. */
|
|
94
|
+
export function newRunDir(runsDir, prefix) {
|
|
95
|
+
fs.mkdirSync(runsDir, { recursive: true, mode: 0o700 });
|
|
96
|
+
return fs.mkdtempSync(path.join(runsDir, prefix));
|
|
97
|
+
}
|
|
98
|
+
|
|
73
99
|
/** Creates the run directory tree (0700) and returns its paths. */
|
|
74
100
|
export function createRunLayout(runDir) {
|
|
75
101
|
fs.mkdirSync(runDir, { recursive: true, mode: 0o700 });
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// What the website shows about this machine (模型配置 → 执行机器 → 详情):
|
|
2
|
+
// system, kernel, CPU, memory, the work directory's disk, load, uptime, the
|
|
3
|
+
// account running the program, whether it looks like a container, and
|
|
4
|
+
// whether the program runs on the Node it downloaded. Sent with /connect and
|
|
5
|
+
// every heartbeat; the parts that cannot change while the program runs are
|
|
6
|
+
// read once. Display only: the website decides nothing on these.
|
|
7
|
+
|
|
8
|
+
import { spawnSync } from 'node:child_process';
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
|
|
12
|
+
let fixed = null;
|
|
13
|
+
|
|
14
|
+
function readText(file, max = 64 * 1024) {
|
|
15
|
+
try {
|
|
16
|
+
return fs.readFileSync(file, 'utf8').slice(0, max);
|
|
17
|
+
} catch {
|
|
18
|
+
return '';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function output(command, args) {
|
|
23
|
+
const result = spawnSync(command, args, {
|
|
24
|
+
encoding: 'utf8',
|
|
25
|
+
timeout: 5000,
|
|
26
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
27
|
+
env: { ...process.env, LC_ALL: 'C' },
|
|
28
|
+
});
|
|
29
|
+
return result.status === 0 ? String(result.stdout || '') : '';
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** "Ubuntu 24.04.1 LTS", "macOS 15.1"… */
|
|
33
|
+
export function osName(platform = process.platform, { osRelease } = {}) {
|
|
34
|
+
if (platform === 'darwin') {
|
|
35
|
+
const name = output('sw_vers', ['-productName']).trim() || 'macOS';
|
|
36
|
+
return `${name} ${output('sw_vers', ['-productVersion']).trim()}`.trim();
|
|
37
|
+
}
|
|
38
|
+
if (platform !== 'linux') return platform;
|
|
39
|
+
const text = osRelease ?? (readText('/etc/os-release') || readText('/usr/lib/os-release'));
|
|
40
|
+
const value = (key) => {
|
|
41
|
+
const match = new RegExp(`^${key}=(.*)$`, 'm').exec(text);
|
|
42
|
+
return match ? match[1].trim().replace(/^(["'])(.*)\1$/, '$2') : '';
|
|
43
|
+
};
|
|
44
|
+
return value('PRETTY_NAME') || [value('NAME'), value('VERSION')].filter(Boolean).join(' ') || 'Linux';
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function cpuModel(platform) {
|
|
48
|
+
const model = String(os.cpus()[0]?.model || '').trim();
|
|
49
|
+
if (model && model.toLowerCase() !== 'unknown') return model;
|
|
50
|
+
// ARM Linux: /proc/cpuinfo has no model name, lscpu knows it (e.g. Kunpeng-920).
|
|
51
|
+
if (platform === 'linux') return /^Model name:\s*(.+)$/m.exec(output('lscpu', []))?.[1].trim() || '';
|
|
52
|
+
return '';
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** A guess: Docker / Podman / Kubernetes markers, or an overlay root filesystem. */
|
|
56
|
+
export function looksLikeContainer({
|
|
57
|
+
platform = process.platform,
|
|
58
|
+
env = process.env,
|
|
59
|
+
exists = fs.existsSync,
|
|
60
|
+
read = readText,
|
|
61
|
+
} = {}) {
|
|
62
|
+
if (platform !== 'linux') return false;
|
|
63
|
+
if (exists('/.dockerenv') || exists('/run/.containerenv')) return true;
|
|
64
|
+
if (env.KUBERNETES_SERVICE_HOST || env.container) return true;
|
|
65
|
+
if (/\b(docker|kubepods|containerd|libpod|lxc)\b/.test(read('/proc/1/cgroup'))) return true;
|
|
66
|
+
return /^\d+ \d+ \d+:\d+ \S+ \/ [^\n]* - overlay /m.test(read('/proc/self/mountinfo', 256 * 1024));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function fixedPart(platform) {
|
|
70
|
+
if (!fixed) {
|
|
71
|
+
let user = '';
|
|
72
|
+
try {
|
|
73
|
+
user = os.userInfo().username;
|
|
74
|
+
} catch {
|
|
75
|
+
// No passwd entry (some containers).
|
|
76
|
+
}
|
|
77
|
+
fixed = { osName: osName(platform), cpuModel: cpuModel(platform), user, container: looksLikeContainer({ platform }) };
|
|
78
|
+
}
|
|
79
|
+
return fixed;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function disk(dir) {
|
|
83
|
+
try {
|
|
84
|
+
const stat = fs.statfsSync(dir);
|
|
85
|
+
return { diskTotal: stat.blocks * stat.bsize, diskAvailable: stat.bavail * stat.bsize };
|
|
86
|
+
} catch {
|
|
87
|
+
return { diskTotal: 0, diskAvailable: 0 };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The report (sizes in bytes, uptime in seconds); `workRoot` is the directory whose disk counts. */
|
|
92
|
+
export function collectSystemInfo({ workRoot = '', platform = process.platform, env = process.env } = {}) {
|
|
93
|
+
const base = fixedPart(platform);
|
|
94
|
+
const memTotal = os.totalmem();
|
|
95
|
+
// A container's limit, when there is one (unlimited reads as 0 or a huge number).
|
|
96
|
+
const constrained = Number(process.constrainedMemory?.() || 0);
|
|
97
|
+
const available = Number(process.availableMemory?.() ?? os.freemem());
|
|
98
|
+
return {
|
|
99
|
+
osName: base.osName,
|
|
100
|
+
kernel: os.release(),
|
|
101
|
+
cpuModel: base.cpuModel,
|
|
102
|
+
cpuCount: os.availableParallelism?.() || os.cpus().length || 1,
|
|
103
|
+
memTotal,
|
|
104
|
+
memAvailable: Math.max(0, Math.min(available, memTotal)),
|
|
105
|
+
memLimit: constrained > 0 && constrained < memTotal ? constrained : 0,
|
|
106
|
+
diskPath: workRoot,
|
|
107
|
+
...(workRoot ? disk(workRoot) : { diskTotal: 0, diskAvailable: 0 }),
|
|
108
|
+
uptime: Math.round(os.uptime()),
|
|
109
|
+
loadAvg: os.loadavg().map((value) => Math.round(value * 100) / 100),
|
|
110
|
+
user: base.user,
|
|
111
|
+
container: base.container,
|
|
112
|
+
nodeManaged: Boolean(env.GC_RUNNER_NODE_SWITCHED),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const GB = 1024 ** 3;
|
|
117
|
+
|
|
118
|
+
function size(bytes) {
|
|
119
|
+
return `${(bytes / GB).toFixed(bytes >= 100 * GB ? 0 : 1).replace(/\.0$/, '')} GB`;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** One line for doctor / status: "Ubuntu 24.04 · arm64 · 8 核 · 内存 16 GB · 工作目录可用 120 GB". */
|
|
123
|
+
export function describeSystem(info, arch = process.arch) {
|
|
124
|
+
const memory = info.memLimit || info.memTotal;
|
|
125
|
+
return [
|
|
126
|
+
`${info.osName}${info.container ? '(容器)' : ''}`,
|
|
127
|
+
arch,
|
|
128
|
+
info.cpuCount ? `${info.cpuCount} 核` : '',
|
|
129
|
+
memory ? `内存 ${size(memory)}${info.memLimit ? '(容器限制)' : ''}` : '',
|
|
130
|
+
info.diskTotal ? `工作目录可用 ${size(info.diskAvailable)} / ${size(info.diskTotal)}` : '',
|
|
131
|
+
].filter(Boolean).join(' · ');
|
|
132
|
+
}
|