@online-tools/agent-runner 0.0.1-alpha-3 → 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 CHANGED
@@ -50,7 +50,7 @@ gitcode-agent-runner service install # 可选:注册为后台服务,开
50
50
  - 配置:`${XDG_CONFIG_HOME:-~/.config}/gitcode-agent-runner/config.json`(0600)
51
51
  - Skill 缓存:`${XDG_CACHE_HOME:-~/.cache}/gitcode-agent-runner/skills/`
52
52
  - 自动下载的 Node(只有系统 Node 过旧时才有):`${XDG_DATA_HOME:-~/.local/share}/gitcode-agent-runner/node/`
53
- - 工作目录: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
54
 
55
55
  ## 上报给网站的信息
56
56
 
@@ -95,6 +95,8 @@ gitcode-agent-runner service install # 可选:注册为后台服务,开
95
95
 
96
96
  退出码:0 正常退出;1 出错;78 需要人处理(没有令牌、令牌已删除、机器已封禁、同一配置在两台机器上运行、系统或 Node 不支持、以 root 运行、已有实例在运行),后台服务遇到 78 不会自动重启。
97
97
 
98
+ 沙箱检测(启动时和之后每小时)会像真实任务一样启动 claude,并让它在沙箱里执行一条 `echo`:模型换成本机 127.0.0.1 上的一个替身,不访问网络、不需要 API Key。命令能在沙箱里跑通才算可用,否则网页和 `doctor` 会显示 Claude Code 给出的原因(例如 `Failed to create bridge sockets…`、bubblewrap 无法创建命名空间)。
99
+
98
100
  沙箱不可用时请先运行 `gitcode-agent-runner setup`;在非特权容器或禁用了非特权 user namespace 的系统(例如开启了 AppArmor 限制的 Ubuntu 24.04+)上沙箱可能无法启动,详见 https://code.claude.com/docs/en/sandboxing 。
99
101
 
100
102
  ## 卸载
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 the Claude Code sandbox starts. The result is
3
- // reported to the website as `capabilities` (it decides which features run).
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 { caPaths, createRunLayout, homeReadAllow, passThroughEnv, writeSandboxSettings } from './sandbox.mjs';
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 = 20_000;
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
- * 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.
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(fs.mkdtempSync(path.join(workRoot, 'probe-')));
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: 'http://127.0.0.1:9',
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 === 'system' && event.subtype === 'init') finish({ ok: true, reason: '' });
177
- else if (event?.type === 'result' && typeof event.result === 'string') resultText = event.result;
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 { caPaths, createRunLayout, homeReadAllow, passThroughEnv, writeSandboxSettings } from './sandbox.mjs';
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
- const runDir = path.join(this.runsDir, runId);
381
+ // A short directory name, not the run id: see socketPathProblem().
382
+ let runDir = '';
374
383
  let layout;
375
384
  try {
376
- fs.rmSync(runDir, { recursive: true, force: true });
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/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 });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@online-tools/agent-runner",
3
- "version": "0.0.1-alpha-3",
3
+ "version": "0.0.1-alpha-4",
4
4
  "description": "GitCode 在线工具的 Agent 执行机器:在自己的机器上运行 PR 描述、代码检视任务",
5
5
  "license": "MIT",
6
6
  "type": "module",