@online-tools/work-agent-runner 0.0.5-alpha-1 → 0.1.0-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/lib/check.mjs ADDED
@@ -0,0 +1,391 @@
1
+ // `work-agent-runner check` (docs/remediation-and-install-plan.md 4.2): what
2
+ // this machine needs, group by group, each item with its result, what it
3
+ // keeps from running, how to fix it and an error code. assessCheck() turns
4
+ // the facts bin/main.mjs collects into the report; it does no I/O, so every
5
+ // verdict is tested with made-up facts.
6
+ //
7
+ // Exit code: 0 every feature can run; 1 some cannot; 2 none can. The
8
+ // knowledge pool is optional: without it CANN 知识问答 cannot run, which is
9
+ // shown as a warning and does not change the exit code.
10
+ //
11
+ // Only node: built-ins and files in this directory.
12
+
13
+ import fs from 'node:fs';
14
+
15
+ import { FEATURE_LABELS } from './jobs.mjs';
16
+ import { WORK_ROOT_MAX_BYTES } from './sandbox.mjs';
17
+
18
+ /** Which tools each feature needs (the website's FEATURE_TOOLS; the website decides, this explains). */
19
+ export const FEATURE_TOOLS = {
20
+ 'pr-desc-issue-gen': ['git', 'curl', 'python3'],
21
+ 'ascend-code-review': ['git', 'python3', 'curl', 'jq', 'sed'],
22
+ 'code-review-flash': ['python3', 'git', 'base64'],
23
+ 'cann-knowledge': ['rg'],
24
+ };
25
+ export const ALL_FEATURES = Object.keys(FEATURE_TOOLS);
26
+ export const FEATURE_NAMES = FEATURE_LABELS;
27
+ export const CHECK_GROUPS = [
28
+ ['system', '系统'],
29
+ ['runtime', '运行环境'],
30
+ ['network', '网络'],
31
+ ['tools', '依赖'],
32
+ ['sandbox', '沙箱'],
33
+ ['claude', 'Claude Code'],
34
+ ['repos', '仓库'],
35
+ ['service', '服务'],
36
+ ['website', '网站'],
37
+ ];
38
+ export const SANDBOX_DOCS = 'https://code.claude.com/docs/en/sandboxing';
39
+ const GB = 1024 ** 3;
40
+ const WARN_FREE_BYTES = 5 * GB;
41
+ const POOL_FREE_BYTES = 10 * GB;
42
+
43
+ function readText(file, readFile) {
44
+ try {
45
+ return String(readFile(file)).trim();
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * AppArmor's say over user namespaces: { restrict: true | false | null
53
+ * (unknown), profiles: [names of loaded profiles that mention bwrap or
54
+ * userns] } — the profile list is only readable by root; [] otherwise.
55
+ */
56
+ export function readApparmor({ readFile = (file) => fs.readFileSync(file, 'utf8') } = {}) {
57
+ const flag = readText('/proc/sys/kernel/apparmor_restrict_unprivileged_userns', readFile);
58
+ const listed = readText('/sys/kernel/security/apparmor/profiles', readFile) || '';
59
+ const profiles = listed
60
+ .split('\n')
61
+ .map((line) => line.replace(/\s+\((enforce|complain|kill|unconfined|prompt)\)\s*$/, '').trim())
62
+ .filter((name) => /bwrap|userns/.test(name));
63
+ return { restrict: flag === null ? null : flag === '1', profiles };
64
+ }
65
+
66
+ /** { max, clone }: user.max_user_namespaces and (Debian) kernel.unprivileged_userns_clone; null where absent. */
67
+ export function readUserns({ readFile = (file) => fs.readFileSync(file, 'utf8') } = {}) {
68
+ const number = (file) => {
69
+ const text = readText(file, readFile);
70
+ return text !== null && /^\d+$/.test(text) ? Number(text) : null;
71
+ };
72
+ return { max: number('/proc/sys/user/max_user_namespaces'), clone: number('/proc/sys/kernel/unprivileged_userns_clone') };
73
+ }
74
+
75
+ function compareVersions(a, b) {
76
+ const parse = (value) => (/^(\d+)\.(\d+)\.(\d+)/.exec(String(value)) || [0, 0, 0, 0]).slice(1, 4).map(Number);
77
+ const [x, y] = [parse(a), parse(b)];
78
+ for (let index = 0; index < 3; index += 1) if (x[index] !== y[index]) return x[index] < y[index] ? -1 : 1;
79
+ return 0;
80
+ }
81
+
82
+ function gigabytes(bytes) {
83
+ return `${(bytes / GB).toFixed(bytes >= 100 * GB ? 0 : 1)} GB`;
84
+ }
85
+
86
+ function item(id, title, status, detail, extra = {}) {
87
+ return { id, title, status, detail, notes: [], affects: [], fix: '', docs: '', code: '', ...extra };
88
+ }
89
+
90
+ /**
91
+ * Why the sandbox does not start, in words an administrator can act on:
92
+ * { code, detail, notes, fix }. AppArmor's restriction of unprivileged user
93
+ * namespaces (Ubuntu 24.04 and later) is told apart (E1402): Claude Code's
94
+ * sandbox creates a user namespace inside bubblewrap's, which the restriction
95
+ * — or the bwrap profile that ships with it — does not allow.
96
+ */
97
+ export function sandboxProblem({ reason = '', platform = 'linux', apparmor = {}, userns = {} } = {}) {
98
+ const text = String(reason || '原因未知');
99
+ if (platform === 'linux' && (userns.max === 0 || userns.clone === 0)) {
100
+ return {
101
+ code: 'E4101',
102
+ detail: `系统关闭了非特权 user namespace(${userns.max === 0 ? 'user.max_user_namespaces=0' : 'kernel.unprivileged_userns_clone=0'}),bubblewrap 无法运行`,
103
+ notes: [],
104
+ fix: '需要管理员打开非特权 user namespace(这会改变本机的安全设置,请先评估)',
105
+ };
106
+ }
107
+ const namespaceError = /setgroups|user ?namespace|userns|uid_map|unshare|CAP_SYS_ADMIN/i.test(text);
108
+ if (platform === 'linux' && apparmor.restrict === true && namespaceError) {
109
+ const profiles = (apparmor.profiles || []).filter((name) => /bwrap/.test(name));
110
+ return {
111
+ code: 'E1402',
112
+ detail: 'AppArmor 限制了非特权 user namespace:Claude Code 的沙箱要在 bubblewrap 里再建一层,被拒绝了',
113
+ notes: [
114
+ `检测到:kernel.apparmor_restrict_unprivileged_userns=1${profiles.length ? `;已加载的 bubblewrap profile:${profiles.join('、')}` : ''}`,
115
+ `沙箱报错:${text}`,
116
+ ],
117
+ fix:
118
+ '需要管理员处理,本程序不会自动修改:让 /usr/bin/bwrap 及其子进程可以使用 user namespace(换掉 bubblewrap 的受限 profile),' +
119
+ '或关闭 kernel.apparmor_restrict_unprivileged_userns。两种做法都会放宽本机的安全设置,请先评估,具体步骤见说明链接',
120
+ };
121
+ }
122
+ return { code: 'E4101', detail: `沙箱不可用:${text}`, notes: [], fix: '运行 work-agent-runner setup 安装缺少的组件后再检查' };
123
+ }
124
+
125
+ /**
126
+ * The report: { groups: [{ id, title, items }], blocked, exitCode, summary }.
127
+ * `facts` (bin/main.mjs collectCheckFacts()): see the fields read below;
128
+ * anything missing reads as not checked.
129
+ */
130
+ export function assessCheck(facts) {
131
+ const groups = Object.fromEntries(CHECK_GROUPS.map(([id, title]) => [id, { id, title, items: [] }]));
132
+ const add = (group, entry) => groups[group].items.push(entry);
133
+ const linux = facts.platform === 'linux';
134
+
135
+ // ---- 系统
136
+ const system = [facts.osName, facts.arch, facts.libc?.family ? `${facts.libc.family}${facts.libc.version ? ` ${facts.libc.version}` : ''}` : ''];
137
+ add('system', item('os', '系统', 'ok', system.filter(Boolean).join(' · ')));
138
+ if (facts.root) {
139
+ add(
140
+ 'system',
141
+ item('account', '运行账号', 'warn', 'root:沙箱里的命令也拥有 root 权限(需要 --allow-root)', {
142
+ code: 'E1103',
143
+ fix: '建议改用专用的低权限账号运行本程序',
144
+ }),
145
+ );
146
+ } else {
147
+ add('system', item('account', '运行账号', 'ok', facts.user || '普通账号'));
148
+ }
149
+ if (facts.container) add('system', item('container', '容器', 'info', '在容器里运行:沙箱需要容器允许 user namespace'));
150
+ const workRoot = facts.workRoot || {};
151
+ if (linux && workRoot.bytes > WORK_ROOT_MAX_BYTES) {
152
+ add(
153
+ 'system',
154
+ item('work-root-length', '工作目录路径', 'fail', `${workRoot.path} 有 ${workRoot.bytes} 字节,超过 ${WORK_ROOT_MAX_BYTES}:沙箱的 socket 放不下`, {
155
+ affects: ALL_FEATURES,
156
+ code: 'E1105',
157
+ fix: '用 --work-dir 换一个更短的路径',
158
+ }),
159
+ );
160
+ } else if (workRoot.path) {
161
+ add('system', item('work-root-length', '工作目录路径', 'ok', `${workRoot.path}${linux ? `(${workRoot.bytes} / ${WORK_ROOT_MAX_BYTES} 字节)` : ''}`));
162
+ }
163
+ const control = facts.control || {};
164
+ if (control.error) {
165
+ add('system', item('control', '管理接口', 'warn', control.error, { code: 'E1112', fix: '把 WORK_AGENT_RUNNER_HOME 设为更短的路径;status、jobs 等命令在那之前只能读记录' }));
166
+ } else if (control.socket) {
167
+ add('system', item('control', '管理接口', 'ok', `${control.socket}${control.fallback ? '(程序目录的路径太长,放在这里)' : ''}`));
168
+ }
169
+
170
+ // ---- 运行环境
171
+ if (facts.node?.version) add('runtime', item('node', 'Node', 'ok', `${facts.node.version}${facts.node.managed ? '(程序下载的)' : '(系统的)'}`));
172
+ const disk = facts.disk || {};
173
+ const minFree = disk.minFree ?? GB;
174
+ if (Number.isFinite(disk.workRoot) && disk.workRoot > 0) {
175
+ if (minFree && disk.workRoot < minFree) {
176
+ add(
177
+ 'runtime',
178
+ item('disk-work', '工作目录磁盘', 'fail', `只剩 ${gigabytes(disk.workRoot)},少于接任务的下限 ${gigabytes(minFree)}`, {
179
+ affects: ALL_FEATURES,
180
+ code: 'E3301',
181
+ fix: '清理这块磁盘,或用 --work-dir 换到空间更大的盘',
182
+ }),
183
+ );
184
+ } else if (disk.workRoot < WARN_FREE_BYTES) {
185
+ add('runtime', item('disk-work', '工作目录磁盘', 'warn', `可用 ${gigabytes(disk.workRoot)}:代码检视要克隆被检视的仓,空间可能不够`, { fix: '建议留出 5 GB 以上' }));
186
+ } else {
187
+ add('runtime', item('disk-work', '工作目录磁盘', 'ok', `可用 ${gigabytes(disk.workRoot)}`));
188
+ }
189
+ }
190
+ if (Number.isFinite(disk.pool) && disk.pool > 0 && !facts.pool?.repos) {
191
+ const enough = disk.pool >= POOL_FREE_BYTES;
192
+ add(
193
+ 'runtime',
194
+ item('disk-pool', '知识仓磁盘', enough ? 'ok' : 'warn', `可用 ${gigabytes(disk.pool)}${enough ? '' : ':下载知识仓至少需要 10 GB'}`),
195
+ );
196
+ }
197
+
198
+ // ---- 网络
199
+ const network = facts.network || {};
200
+ const probe = (id, title, result, { required, affects = [], fix = '', code = '' }) => {
201
+ if (!result) return;
202
+ if (result.skipped) add('network', item(id, title, 'info', result.detail));
203
+ else if (result.ok) add('network', item(id, title, 'ok', result.detail));
204
+ else add('network', item(id, title, required ? 'fail' : 'warn', result.detail, { affects: required ? affects : [], fix, code }));
205
+ };
206
+ probe('website', '网站', network.website, { required: true, affects: ALL_FEATURES, fix: '检查网络和代理设置(HTTPS_PROXY 等)', code: 'E2101' });
207
+ probe('gitcode', 'GitCode', network.gitcode, { required: true, affects: ALL_FEATURES, fix: '任务和 work-agent 仓库都要访问 GitCode:检查网络和代理设置' });
208
+ probe('registry', 'npm 注册表', network.registry, { required: false, fix: '只在安装或升级 Claude Code 时需要:检查网络,或在 config.json 的 mirrors.npmRegistry 设置镜像' });
209
+ if (network.proxy !== undefined) add('network', item('proxy', '代理', 'info', network.proxy || '未设置'));
210
+
211
+ // ---- 依赖
212
+ const tools = facts.tools || {};
213
+ for (const name of ['git', 'curl', 'python3', 'jq', 'sed', 'base64', 'rg']) {
214
+ const tool = tools[name];
215
+ if (!tool) continue;
216
+ const users = ALL_FEATURES.filter((feature) => FEATURE_TOOLS[feature].includes(name));
217
+ if (tool.ok) {
218
+ add('tools', item(name, name, 'ok', tool.version || '已安装'));
219
+ } else if (name === 'rg') {
220
+ add('tools', item(name, name, 'warn', '未安装:检索知识仓要用它(CANN 知识问答)', { affects: [], fix: 'work-agent-runner setup', code: 'E1201' }));
221
+ } else {
222
+ add('tools', item(name, name, 'fail', `未安装:${users.map((feature) => FEATURE_NAMES[feature]).join('、')}需要`, { affects: users, fix: 'work-agent-runner setup', code: 'E1201' }));
223
+ }
224
+ }
225
+ if (facts.packageManager !== undefined) {
226
+ add(
227
+ 'tools',
228
+ facts.packageManager
229
+ ? item('package-manager', '包管理器', 'ok', facts.packageManager)
230
+ : item('package-manager', '包管理器', 'warn', '没有识别出包管理器:缺少的软件只能手动安装'),
231
+ );
232
+ }
233
+ if (!facts.root && facts.sudo === false) add('tools', item('sudo', 'sudo', 'info', '没有 sudo:安装系统软件需要管理员'));
234
+
235
+ // ---- 沙箱
236
+ if (linux) {
237
+ for (const [name, label] of [['bwrap', 'bubblewrap'], ['socat', 'socat']]) {
238
+ const tool = tools[name];
239
+ if (!tool) continue;
240
+ add(
241
+ 'sandbox',
242
+ tool.ok
243
+ ? item(name, label, 'ok', '已安装')
244
+ : item(name, label, 'fail', '未安装:沙箱需要', { affects: ALL_FEATURES, fix: 'work-agent-runner setup', code: 'E1201' }),
245
+ );
246
+ }
247
+ const userns = facts.userns || {};
248
+ if (userns.max === 0 || userns.clone === 0) {
249
+ add('sandbox', item('userns', 'user namespace', 'fail', '系统关闭了非特权 user namespace', { affects: ALL_FEATURES, code: 'E4101' }));
250
+ } else if (facts.apparmor?.restrict === true && facts.sandbox?.ok) {
251
+ // Restricted, yet the sandbox runs (a profile lets bubblewrap through): worth knowing, nothing to do.
252
+ add('sandbox', item('apparmor', 'AppArmor', 'info', '限制了非特权 user namespace,但沙箱可以运行'));
253
+ }
254
+ }
255
+ if (facts.sandbox) {
256
+ if (facts.sandbox.ok) add('sandbox', item('probe', '沙箱实测', 'ok', '沙箱里的命令可以运行'));
257
+ else if (!facts.claude?.version) add('sandbox', item('probe', '沙箱实测', 'skip', '没有可用的 claude,无法检测'));
258
+ else {
259
+ // Claude Code's own words when runDoctor() put a plainer reason in front of them.
260
+ const problem = sandboxProblem({ reason: facts.sandbox.raw || facts.sandbox.reason, platform: facts.platform, apparmor: facts.apparmor, userns: facts.userns });
261
+ add(
262
+ 'sandbox',
263
+ item('probe', '沙箱实测', 'fail', problem.detail, { notes: problem.notes, affects: ALL_FEATURES, code: problem.code, fix: problem.fix, docs: SANDBOX_DOCS }),
264
+ );
265
+ }
266
+ }
267
+
268
+ // ---- Claude Code
269
+ const claude = facts.claude || {};
270
+ if (!claude.path) {
271
+ add('claude', item('claude', 'claude', 'fail', '未安装', { affects: ALL_FEATURES, code: 'E1301', fix: 'work-agent-runner setup' }));
272
+ } else if (!claude.version) {
273
+ add('claude', item('claude', 'claude', 'fail', `无法运行(${claude.path})`, { affects: ALL_FEATURES, code: 'E1301', fix: 'work-agent-runner setup 重新安装' }));
274
+ } else {
275
+ const source = { managed: '程序安装', external: '自行安装' }[claude.source] || '';
276
+ const where = `${claude.version}${source ? `(${source})` : ''} · ${claude.path}`;
277
+ if (claude.minVersion && compareVersions(claude.version, claude.minVersion) < 0) {
278
+ add(
279
+ 'claude',
280
+ item('claude', 'claude', 'fail', `${where}:低于网站要求的 ${claude.minVersion}`, {
281
+ affects: ALL_FEATURES,
282
+ code: 'E1301',
283
+ fix: 'work-agent-runner setup',
284
+ }),
285
+ );
286
+ } else {
287
+ add('claude', item('claude', 'claude', 'ok', where));
288
+ }
289
+ if (claude.verifiedVersion) {
290
+ add(
291
+ 'claude',
292
+ claude.version === claude.verifiedVersion
293
+ ? item('claude-verified', '已验证版本', 'ok', `${claude.verifiedVersion}:本程序用它测试过沙箱边界`)
294
+ : item('claude-verified', '已验证版本', 'info', `本程序测试过的是 ${claude.verifiedVersion},本机是 ${claude.version}`, {
295
+ fix: `需要时可以运行 work-agent-runner setup --claude-version ${claude.verifiedVersion}`,
296
+ }),
297
+ );
298
+ }
299
+ }
300
+
301
+ // ---- 仓库
302
+ const repo = facts.repo || {};
303
+ if (repo.ok) {
304
+ add('repos', item('work-agent', 'work-agent 仓库', 'ok', `${String(repo.commit || '').slice(0, 7)}${repo.committedAt ? `(${repo.committedAt.slice(0, 10)})` : ''}`));
305
+ } else if (repo.reason) {
306
+ add(
307
+ 'repos',
308
+ item('work-agent', 'work-agent 仓库', 'fail', repo.reason, {
309
+ affects: ALL_FEATURES,
310
+ code: repo.foreign ? 'E1115' : 'E5101',
311
+ fix: repo.foreign ? '在 config.json 里把 workAgentRepoDir 改成一个不存在或空的目录' : 'work-agent-runner update',
312
+ }),
313
+ );
314
+ }
315
+ const pool = facts.pool;
316
+ if (pool) {
317
+ if (pool.incomplete?.length) {
318
+ add('repos', item('pool', '知识仓', 'warn', `${pool.incomplete.join('、')} 不完整`, { fix: '删除这些目录后运行 work-agent-runner setup' }));
319
+ } else if (pool.repos) {
320
+ add('repos', item('pool', '知识仓', 'ok', `${pool.repos} 个仓${pool.ascend ? '(含 AscendC 两仓)' : ',缺 AscendC 两仓'}`));
321
+ } else {
322
+ add('repos', item('pool', '知识仓', 'warn', '未初始化:CANN 知识问答不能运行,代码检视不查 CANN / AscendC 文档(可选)', { fix: 'work-agent-runner setup' }));
323
+ }
324
+ }
325
+
326
+ // ---- 服务
327
+ const service = facts.service;
328
+ if (service) {
329
+ if (!service.installed) add('service', item('service', '后台服务', 'info', '未安装:程序只在前台运行时接任务', { fix: 'work-agent-runner service install' }));
330
+ else if (service.state === 'active' || service.state === 'running') add('service', item('service', '后台服务', 'ok', `${service.name} 运行中`));
331
+ else add('service', item('service', '后台服务', 'warn', `${service.name}:${service.state || '未运行'}`, { fix: 'work-agent-runner service start' }));
332
+ if (service.installed && service.linger === false) {
333
+ add(
334
+ 'service',
335
+ item('linger', 'linger', 'warn', '没有开启:退出登录后后台服务会停止', { fix: `让管理员执行 sudo loginctl enable-linger ${facts.user || '<用户名>'}` }),
336
+ );
337
+ }
338
+ }
339
+ if (facts.instance) add('service', item('instance', '程序', 'ok', `正在运行(pid ${facts.instance.pid},${facts.instance.version})`));
340
+ else if (facts.instance === null) add('service', item('instance', '程序', 'info', '没有在运行'));
341
+
342
+ // ---- 网站
343
+ const website = facts.website || {};
344
+ if (!website.token) {
345
+ add('website', item('token', '接入令牌', 'fail', '还没有接入令牌', { affects: ALL_FEATURES, code: 'E2201', fix: 'work-agent-runner login' }));
346
+ } else if (website.valid === false) {
347
+ add('website', item('token', '接入令牌', 'fail', website.note || '令牌无效或已删除', { affects: ALL_FEATURES, code: 'E2201', fix: '在网页上新建令牌后运行 work-agent-runner login' }));
348
+ } else if (website.blocked) {
349
+ add('website', item('token', '接入令牌', 'fail', '这台机器已在网页上被封禁', { affects: ALL_FEATURES, code: 'E2202', fix: '在网页上解除封禁' }));
350
+ } else if (website.valid) {
351
+ add('website', item('token', '接入令牌', 'ok', '有效'));
352
+ if (website.confirmed === false) {
353
+ add(
354
+ 'website',
355
+ item('confirmed', '确认', 'fail', '这台机器还没有在网页上确认,确认后才会收到任务', {
356
+ affects: ALL_FEATURES,
357
+ fix: '在网页「在线 Agent → 模型配置 → 执行机器」里核对后点「确认」',
358
+ }),
359
+ );
360
+ } else if (website.confirmed) {
361
+ add('website', item('confirmed', '确认', 'ok', '已确认'));
362
+ }
363
+ for (const [feature, verdict] of Object.entries(website.features || {})) {
364
+ if (!Object.hasOwn(FEATURE_NAMES, feature)) continue;
365
+ if (verdict?.ok) add('website', item(feature, FEATURE_NAMES[feature], 'ok', '可以运行'));
366
+ else {
367
+ // Without the pool CANN Q&A cannot run: optional, so a warning.
368
+ const optional = feature === 'cann-knowledge' && /知识仓/.test(verdict?.reason || '');
369
+ add(
370
+ 'website',
371
+ item(feature, FEATURE_NAMES[feature], optional ? 'warn' : 'fail', `网站判定不能运行:${verdict?.reason || '原因未知'}`, {
372
+ affects: optional ? [] : [feature],
373
+ }),
374
+ );
375
+ }
376
+ }
377
+ } else if (website.note) {
378
+ add('website', item('token', '接入令牌', 'skip', website.note));
379
+ }
380
+
381
+ const list = CHECK_GROUPS.map(([id]) => groups[id]).filter((group) => group.items.length);
382
+ const blocked = [...new Set(list.flatMap((group) => group.items.filter((entry) => entry.status === 'fail').flatMap((entry) => entry.affects)))];
383
+ const exitCode = blocked.length >= ALL_FEATURES.length ? 2 : blocked.length ? 1 : 0;
384
+ const counts = { fail: 0, warn: 0 };
385
+ for (const group of list) for (const entry of group.items) if (entry.status in counts) counts[entry.status] += 1;
386
+ let summary;
387
+ if (exitCode === 2) summary = `${counts.fail} 项问题:所有功能都不能运行`;
388
+ else if (exitCode === 1) summary = `${counts.fail} 项问题:不能运行 ${blocked.map((feature) => FEATURE_NAMES[feature]).join('、')}`;
389
+ else summary = counts.warn ? `可以运行;有 ${counts.warn} 项提醒` : '全部就绪';
390
+ return { groups: list, blocked, exitCode, summary };
391
+ }
@@ -6,6 +6,14 @@
6
6
  // importing must have no side effects.
7
7
 
8
8
  // Every tool a job may use.
9
+ // The Claude Code version this program was tested with: the real-claude
10
+ // boundary tests (tests/work-agent-runner-claude-boundaries.test.js) passed
11
+ // on it. `setup` installs it unless told otherwise; the website shows it as
12
+ // the recommended version. Raise it only after those tests pass on the new one
13
+ // (2.1.330, the stable channel on 2026-12-01: installed by lib/claude-install.mjs
14
+ // from registry.npmjs.org and run through both boundary tests).
15
+ export const VERIFIED_CLAUDE_VERSION = '2.1.330';
16
+
9
17
  export const CLAUDE_TOOLS = 'Bash,Read,Glob,Grep,Edit,Write,Skill,Agent';
10
18
  // Pre-allowed: Bash (confined by the operating system sandbox), Skill and
11
19
  // Agent. The file tools are deliberately left out: pre-allowing them lets them
@@ -0,0 +1,221 @@
1
+ // Claude Code installed by this program (docs/remediation-and-install-plan.md
2
+ // 4.4, design 10.4): the platform package @anthropic-ai/claude-code-<platform>
3
+ // from the npm registry, without npm, sudo, a system Node or install scripts.
4
+ //
5
+ // 1. the package for this platform (linux x64/arm64, glibc or musl; macOS x64/arm64)
6
+ // 2. its metadata: dist.tarball and dist.integrity (sha512). From a mirror,
7
+ // the integrity is checked against registry.npmjs.org when that answers;
8
+ // a difference stops the install (E1302)
9
+ // 3. the tarball into claude/.download-*/, hashed while it arrives; a hash
10
+ // that differs from the integrity stops the install (E1302)
11
+ // 4. only package/claude is extracted (extractTarEntry), mode 0755
12
+ // 5. `claude --version` must print the version asked for
13
+ // 6. renamed to claude/<version>/claude; the newest two versions are kept
14
+ //
15
+ // The version is the one this program was tested with (VERIFIED_CLAUDE_VERSION)
16
+ // unless told otherwise (a version, or a dist-tag: latest / stable).
17
+ //
18
+ // Only node: built-ins and files in this directory.
19
+
20
+ import { spawnSync } from 'node:child_process';
21
+ import crypto from 'node:crypto';
22
+ import fs from 'node:fs';
23
+ import path from 'node:path';
24
+
25
+ import { VERIFIED_CLAUDE_VERSION } from './claude-cli.mjs';
26
+ import { removeTree } from './fs-safe.mjs';
27
+ import { extractTarEntry, httpGet, httpText } from './node-runtime.cjs';
28
+
29
+ export const OFFICIAL_REGISTRY = 'https://registry.npmjs.org';
30
+ export const MIRROR_REGISTRY = 'https://registry.npmmirror.com';
31
+ export const CLAUDE_TERMS = 'https://www.anthropic.com/legal/commercial-terms';
32
+ export const CLAUDE_PACKAGE_PAGE = 'https://www.npmjs.com/package/@anthropic-ai/claude-code';
33
+ const VERSION = /^\d+\.\d+\.\d+$/;
34
+ const TAGS = new Set(['latest', 'stable', 'next']);
35
+ const KEEP_VERSIONS = 2;
36
+
37
+ export class ClaudeInstallError extends Error {
38
+ /** `fatal`: a mirror disagrees with the official registry — no other source is tried. */
39
+ constructor(code, message, { fatal = false } = {}) {
40
+ super(message);
41
+ this.code = code;
42
+ this.fatal = fatal;
43
+ }
44
+ }
45
+
46
+ /** The platform package's suffix for this machine ('linux-x64', 'linux-arm64-musl', 'darwin-arm64'…), or '' when there is none. */
47
+ export function claudePlatform({ platform = process.platform, arch = process.arch, musl = null } = {}) {
48
+ if (!['x64', 'arm64'].includes(arch)) return '';
49
+ if (platform === 'darwin') return `darwin-${arch}`;
50
+ if (platform !== 'linux') return '';
51
+ const isMusl = musl ?? !process.report?.getReport?.()?.header?.glibcVersionRuntime;
52
+ return `linux-${arch}${isMusl ? '-musl' : ''}`;
53
+ }
54
+
55
+ function packageName(platformKey) {
56
+ return `@anthropic-ai/claude-code-${platformKey}`;
57
+ }
58
+
59
+ function metadataUrl(registry, name, versionOrTag) {
60
+ return `${registry.replace(/\/+$/, '')}/${name.replace('/', '%2f')}/${versionOrTag}`;
61
+ }
62
+
63
+ async function fetchJson(url, options) {
64
+ const text = await httpText(url, options);
65
+ try {
66
+ return JSON.parse(text);
67
+ } catch {
68
+ throw new Error(`${url} 返回的不是 JSON`);
69
+ }
70
+ }
71
+
72
+ /** A version for `spec` (x.y.z, or a dist-tag of @anthropic-ai/claude-code); '' default = the verified one. */
73
+ export async function resolveClaudeVersion(spec = '', { registry = OFFICIAL_REGISTRY, env = process.env } = {}) {
74
+ const wanted = String(spec || VERIFIED_CLAUDE_VERSION);
75
+ if (VERSION.test(wanted)) return wanted;
76
+ if (!TAGS.has(wanted)) throw new ClaudeInstallError('E1302', `版本写法不对:${wanted}(例如 2.1.330、latest、stable)`);
77
+ const manifest = await fetchJson(metadataUrl(registry, '@anthropic-ai/claude-code', wanted), { env });
78
+ if (!VERSION.test(String(manifest?.version || ''))) throw new ClaudeInstallError('E1302', `没有查到 ${wanted} 对应的版本`);
79
+ return manifest.version;
80
+ }
81
+
82
+ /** The platform package's { tarball, integrity } at `version`, from `registry`. */
83
+ async function distOf(registry, platformKey, version, env) {
84
+ const manifest = await fetchJson(metadataUrl(registry, packageName(platformKey), version), { env });
85
+ const tarball = String(manifest?.dist?.tarball || '');
86
+ const integrity = String(manifest?.dist?.integrity || '');
87
+ if (manifest?.version !== version || !tarball || !/^sha512-[A-Za-z0-9+/]+=*$/.test(integrity)) {
88
+ throw new ClaudeInstallError('E1302', `${registry} 上 ${packageName(platformKey)}@${version} 的元数据不完整`);
89
+ }
90
+ return { tarball, integrity, size: Number(manifest?.dist?.unpackedSize) || 0 };
91
+ }
92
+
93
+ /** Streams `url` into `file`, hashing it: resolves { integrity, size }. */
94
+ function download(url, file, { env, onProgress }) {
95
+ return httpGet(url, { env, timeoutMs: 120_000 }).then(
96
+ (response) =>
97
+ new Promise((resolve, reject) => {
98
+ const total = Number(response.headers['content-length']) || 0;
99
+ const hash = crypto.createHash('sha512');
100
+ let received = 0;
101
+ const out = fs.createWriteStream(file, { mode: 0o600 });
102
+ response.on('data', (chunk) => {
103
+ hash.update(chunk);
104
+ received += chunk.length;
105
+ onProgress?.(received, total);
106
+ });
107
+ response.on('error', (error) => {
108
+ out.destroy();
109
+ reject(error);
110
+ });
111
+ out.on('error', reject);
112
+ out.on('finish', () => {
113
+ if (total && received !== total) reject(new Error('下载不完整'));
114
+ else resolve({ integrity: `sha512-${hash.digest('base64')}`, size: received });
115
+ });
116
+ response.pipe(out);
117
+ }),
118
+ );
119
+ }
120
+
121
+ /** What `claude --version` prints first (x.y.z), '' when it does not run. */
122
+ function versionOf(file, env) {
123
+ const result = spawnSync(file, ['--version'], { encoding: 'utf8', timeout: 30_000, stdio: ['ignore', 'pipe', 'pipe'], env: { ...env, DISABLE_AUTOUPDATER: '1' } });
124
+ if (result.error || result.status !== 0) return '';
125
+ return /^(\d+\.\d+\.\d+)/m.exec(result.stdout || '')?.[1] || '';
126
+ }
127
+
128
+ function compareVersions(a, b) {
129
+ const x = a.split('.').map(Number);
130
+ const y = b.split('.').map(Number);
131
+ for (let index = 0; index < 3; index += 1) if (x[index] !== y[index]) return x[index] - y[index];
132
+ return 0;
133
+ }
134
+
135
+ /** The versions installed under `claudeDir`, newest first: [{ version, path }]. */
136
+ export function installedClaudes(claudeDir) {
137
+ let names = [];
138
+ try {
139
+ names = fs.readdirSync(claudeDir);
140
+ } catch {
141
+ return [];
142
+ }
143
+ return names
144
+ .filter((name) => VERSION.test(name) && fs.existsSync(path.join(claudeDir, name, 'claude')))
145
+ .sort((a, b) => compareVersions(b, a))
146
+ .map((name) => ({ version: name, path: path.join(claudeDir, name, 'claude') }));
147
+ }
148
+
149
+ /**
150
+ * Installs Claude Code `version` into `claudeDir`; resolves { version, path, source }.
151
+ * `registry` (a mirror, or a test's): its integrity is checked against
152
+ * `officialRegistry` when that is another one and answers. `keep`: a path
153
+ * never deleted while pruning (the claude in use). `say(text)` reports steps.
154
+ */
155
+ export async function installClaude({
156
+ claudeDir,
157
+ version,
158
+ platformKey = claudePlatform(),
159
+ registries = [OFFICIAL_REGISTRY, MIRROR_REGISTRY],
160
+ officialRegistry = OFFICIAL_REGISTRY,
161
+ env = process.env,
162
+ keep = '',
163
+ say = () => {},
164
+ onProgress = null,
165
+ }) {
166
+ if (!platformKey) throw new ClaudeInstallError('E1302', `没有适用于 ${process.platform}/${process.arch} 的 Claude Code 平台包,请自行安装 claude`);
167
+ if (!VERSION.test(String(version))) throw new ClaudeInstallError('E1302', `版本写法不对:${version}`);
168
+ fs.mkdirSync(claudeDir, { recursive: true, mode: 0o700 });
169
+ // What an interrupted download left behind.
170
+ for (const name of fs.readdirSync(claudeDir)) if (name.startsWith('.download-')) removeTree(path.join(claudeDir, name));
171
+ const problems = [];
172
+ for (const registry of registries) {
173
+ const host = new URL(registry).host;
174
+ const work = fs.mkdtempSync(path.join(claudeDir, '.download-'));
175
+ try {
176
+ let dist = await distOf(registry, platformKey, version, env);
177
+ if (registry !== officialRegistry) {
178
+ let official = null;
179
+ try {
180
+ official = await distOf(officialRegistry, platformKey, version, env);
181
+ } catch {
182
+ say(`无法访问 ${new URL(officialRegistry).host} 核对校验值,使用 ${host} 提供的校验值`);
183
+ }
184
+ if (official && official.integrity !== dist.integrity) {
185
+ throw new ClaudeInstallError('E1302', `${host} 的校验值与 ${new URL(officialRegistry).host} 不一致,已停止`, { fatal: true });
186
+ }
187
+ }
188
+ say(`下载 ${packageName(platformKey)}@${version}(${host}${dist.size ? `,解开后约 ${Math.round(dist.size / 1048576)} MB` : ''})`);
189
+ const archive = path.join(work, 'claude.tgz');
190
+ const got = await download(dist.tarball, archive, { env, onProgress });
191
+ if (got.integrity !== dist.integrity) throw new ClaudeInstallError('E1302', '下载的文件与注册表的校验值(sha512)不一致,已丢弃');
192
+ say('✓ 校验通过(sha512)');
193
+ const staged = path.join(work, version);
194
+ fs.mkdirSync(staged, { mode: 0o700 });
195
+ const binary = path.join(staged, 'claude');
196
+ if (!(await extractTarEntry(archive, 'package/claude', binary))) throw new ClaudeInstallError('E1302', '平台包里没有 package/claude:Claude Code 的发布方式可能变了,请改用 npm 安装');
197
+ fs.chmodSync(binary, 0o755);
198
+ const actual = versionOf(binary, env);
199
+ if (actual !== version) {
200
+ throw new ClaudeInstallError('E1301', actual ? `下载的 claude 是 ${actual},不是 ${version}` : '下载的 claude 无法在这台机器上运行');
201
+ }
202
+ fs.rmSync(archive, { force: true });
203
+ const final = path.join(claudeDir, version);
204
+ removeTree(final);
205
+ fs.renameSync(staged, final);
206
+ // The newest two stay (one to go back to), and the one in use.
207
+ const installed = installedClaudes(claudeDir);
208
+ for (const old of installed.slice(KEEP_VERSIONS)) {
209
+ if (old.path !== keep && old.version !== version) removeTree(path.dirname(old.path));
210
+ }
211
+ return { version, path: path.join(final, 'claude'), source: registry };
212
+ } catch (error) {
213
+ if (error.fatal) throw error;
214
+ problems.push(`${host}:${error.message}`);
215
+ if (registry !== registries.at(-1)) say(`${host} 下载失败(${error.message}),改用下一个来源`);
216
+ } finally {
217
+ removeTree(work);
218
+ }
219
+ }
220
+ throw new ClaudeInstallError('E1302', problems.join(';'));
221
+ }