@online-tools/work-agent-runner 0.0.0-stage → 0.0.2-alpha-1

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/bin/main.mjs ADDED
@@ -0,0 +1,990 @@
1
+ // work-agent-runner: runs GitCode 在线工具's 在线 Agent jobs (PR 描述 /
2
+ // Issue, 代码检视) on this machine. Loaded by work-agent-runner.cjs once a
3
+ // supported Node runs it. This file owns every side effect — arguments, the
4
+ // config file, the lock, signals, exit codes; ../lib does the work.
5
+ //
6
+ // Exit codes: 0 stopped normally, 1 error, 78 needs a person (no token, token
7
+ // deleted, machine blocked, same config running twice, unsupported system,
8
+ // root, another instance, the old gitcode-agent-runner still running) —
9
+ // services do not restart on 78 (launchd: 0).
10
+
11
+ import { spawn, spawnSync } from 'node:child_process';
12
+ import { once } from 'node:events';
13
+ import fs from 'node:fs';
14
+ import os from 'node:os';
15
+ import path from 'node:path';
16
+ import { fileURLToPath } from 'node:url';
17
+ import { parseArgs } from 'node:util';
18
+
19
+ import {
20
+ ConfigError,
21
+ DEFAULT_SERVER,
22
+ LEGACY_NAME,
23
+ POOL_UPDATE_MS,
24
+ REPO_UPDATE_HOUR,
25
+ WorkRootError,
26
+ adoptLegacyState,
27
+ configPaths,
28
+ legacyConfigPending,
29
+ legacyLockFile,
30
+ loadConfig,
31
+ newClientId,
32
+ prepareWorkRoot,
33
+ saveConfig,
34
+ withRepoPaths,
35
+ } from '../lib/config.mjs';
36
+ import { UPDATE_COMMAND, fatalFor, runConnection } from '../lib/connection.mjs';
37
+ import { SANDBOX_DOCS, runDoctor, which } from '../lib/doctor.mjs';
38
+ import { ApiError, createClient, normalizeServerUrl, proxyMode } from '../lib/http.mjs';
39
+ import { FEATURE_LABELS, JobManager } from '../lib/jobs.mjs';
40
+ import { LockedError, acquireLock, isRunnerAlive, lockHolder } from '../lib/lock.mjs';
41
+ import { NODE_REQUIREMENT, nodeSupported } from '../lib/node-runtime.cjs';
42
+ import { createLogger } from '../lib/log.mjs';
43
+ import { CancelledError, askText, askYesNo, isInteractive, readHidden, readStdin } from '../lib/prompt.mjs';
44
+ import {
45
+ EXIT_NEEDS_ATTENTION,
46
+ installService,
47
+ legacyServiceInstalled,
48
+ removeLegacyService,
49
+ serviceExitCode,
50
+ serviceStatus,
51
+ uninstallService,
52
+ } from '../lib/service.mjs';
53
+ import { DEFAULT_REQUIRED_TOOLS, npmPrefixWritable, planSetup, runSetup } from '../lib/setup.mjs';
54
+ import { prepareWorkAgentHome } from '../lib/sandbox.mjs';
55
+ import { collectSystemInfo, describeSystem } from '../lib/system-info.mjs';
56
+ import { ASCEND_REPOS, WorkAgent } from '../lib/work-agent.mjs';
57
+
58
+ // The command's entry point (it checks the Node version, then loads this file).
59
+ const ENTRY = fileURLToPath(new URL('./work-agent-runner.cjs', import.meta.url));
60
+ const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
61
+ const TOKEN_PATTERN = /^gcm_[A-Za-z0-9_-]{43}$/;
62
+ const NAME_MAX_CHARS = 40; // the website's limit (normalizeMachineName)
63
+ const DOCTOR_INTERVAL_MS = 60 * 60_000;
64
+ const ATTENTION = EXIT_NEEDS_ATTENTION;
65
+ const LEGACY_SERVICE_HINT = `旧版程序 ${LEGACY_NAME} 的后台服务还在:运行 work-agent-runner service install 会停止并替换它(service uninstall 只删除)`;
66
+
67
+ // Which tools each feature needs — for the messages here only; the website decides.
68
+ const FEATURE_TOOLS = {
69
+ 'pr-desc-issue-gen': ['git', 'curl', 'python3'],
70
+ 'ascend-code-review': ['git', 'python3', 'curl', 'jq', 'sed'],
71
+ 'code-review-flash': ['python3', 'git', 'base64'],
72
+ };
73
+
74
+ const USAGE = `GitCode Agent 执行机器 ${VERSION}
75
+
76
+ 用法:work-agent-runner [命令] [选项]
77
+
78
+ 命令:
79
+ start 连接网站并等待任务(默认)
80
+ login [--new-id] [--token-stdin] [--name <名称>]
81
+ 输入接入令牌(校验通过才保存);--new-id 重新生成机器标识
82
+ logout 清除本机保存的令牌(机器标识保留)
83
+ setup [--yes] [--repos <仓名>|--no-repos]
84
+ 检查并安装缺少的依赖、下载 work-agent 仓库,并询问是否
85
+ 下载 AscendC 知识仓(需在终端里运行)
86
+ update 立即更新 work-agent 仓库和知识仓(平时由程序自己定时更新)
87
+ doctor [--json] 检查依赖、沙箱和各功能是否可用
88
+ status 显示网站、令牌、机器标识、工作目录、服务状态,并测试连接
89
+ service install|uninstall|status
90
+ 注册 / 删除 / 查看后台服务(开机自启)
91
+ version 显示版本
92
+
93
+ 选项:
94
+ --server <url> 网站地址(默认 ${DEFAULT_SERVER},会保存)
95
+ --work-dir <dir> 工作目录(不能在主目录之内,会保存)
96
+ --name <名称> 这台机器登记时用的名称(默认主机名,会保存;登记后在网页上修改)
97
+ --allow-root 允许以 root 运行(仅限容器等确有需要的场合)
98
+
99
+ work-agent 仓库(Skill 来源)由本程序自己克隆并跟随 main,网站不下发 Skill。`;
100
+
101
+ class ExitError extends Error {
102
+ constructor(code, message = '') {
103
+ super(message);
104
+ this.code = code;
105
+ }
106
+ }
107
+
108
+ const say = (text = '') => process.stdout.write(`${text}\n`);
109
+ const log = createLogger();
110
+
111
+ function checkSystem() {
112
+ if (!['linux', 'darwin'].includes(process.platform)) throw new ExitError(ATTENTION, '暂不支持此系统(只支持 Linux 和 macOS)');
113
+ // work-agent-runner.cjs already switched to a supported Node when it could.
114
+ if (!nodeSupported(process.versions.node)) throw new ExitError(ATTENTION, `需要 Node ${NODE_REQUIREMENT}(当前 ${process.versions.node})`);
115
+ }
116
+
117
+ /**
118
+ * Proxies for this program's own requests. Node before 24.14 / 25.4 reads
119
+ * NODE_USE_ENV_PROXY only at startup: run once more with it set and pass
120
+ * signals and the exit code through. Returns that exit code, or null.
121
+ */
122
+ async function applyProxy() {
123
+ if (proxyMode() !== 'restart') return null;
124
+ const child = spawn(process.execPath, [...process.execArgv, ENTRY, ...process.argv.slice(2)], {
125
+ stdio: 'inherit',
126
+ env: { ...process.env, NODE_USE_ENV_PROXY: '1', GC_RUNNER_REEXEC: '1' },
127
+ });
128
+ for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => child.kill(signal));
129
+ const [code, signal] = await once(child, 'exit');
130
+ return code ?? (signal ? 128 + (os.constants.signals[signal] || 0) : 1);
131
+ }
132
+
133
+ function realHome() {
134
+ try {
135
+ return fs.realpathSync(os.homedir());
136
+ } catch {
137
+ return path.resolve(os.homedir());
138
+ }
139
+ }
140
+
141
+ /** A name the website accepts: trimmed, 1–40 characters, no control characters; else ''. */
142
+ function machineName(value) {
143
+ const name = String(value ?? '').trim();
144
+ const length = [...name].length;
145
+ return length >= 1 && length <= NAME_MAX_CHARS && !/\p{Cc}/u.test(name) ? name : '';
146
+ }
147
+
148
+ /**
149
+ * First run after an older layout (0.0.1 kept the config under ~/.config and
150
+ * ran jobs in /var/tmp; before 0.0.1-alpha-5 everything was named
151
+ * gitcode-agent-runner): take over the config, so the token and the machine id
152
+ * stay — never while a program still runs with it. Before anything else writes
153
+ * a config here, which would get a new machine id.
154
+ */
155
+ function adoptLegacy(paths) {
156
+ const configFile = legacyConfigPending(paths);
157
+ if (configFile) {
158
+ const holder = lockHolder(legacyLockFile(configFile));
159
+ for (const name of ['work-agent-runner', LEGACY_NAME]) {
160
+ if (!isRunnerAlive(holder, name)) continue;
161
+ throw new ExitError(
162
+ ATTENTION,
163
+ `旧版程序(${name},pid ${holder})正在运行,停止后才能沿用它的令牌和机器标识。` +
164
+ '它是后台服务的话,运行 work-agent-runner service install 会停止并替换它(service uninstall 只删除);在前台运行的请按 Ctrl+C',
165
+ );
166
+ }
167
+ }
168
+ if (!configFile && fs.existsSync(paths.configFile)) return;
169
+ adoptLegacyState(paths, configFile);
170
+ if (configFile) {
171
+ // stderr: doctor --json prints JSON on stdout.
172
+ process.stderr.write(`已沿用旧版本的配置(接入令牌和机器标识不变):${configFile} → ${paths.configFile}\n`);
173
+ }
174
+ }
175
+
176
+ /** Config, server, client id and work root; --server / --work-dir / --name are saved. */
177
+ function loadContext(values, { workRoot: needWorkRoot = true } = {}) {
178
+ const defaults = configPaths();
179
+ adoptLegacy(defaults);
180
+ const config = loadConfig(defaults);
181
+ let changed = false;
182
+ if (!config.clientId) {
183
+ config.clientId = newClientId();
184
+ changed = true;
185
+ }
186
+ let server;
187
+ try {
188
+ server = normalizeServerUrl(values.server || config.server || DEFAULT_SERVER);
189
+ } catch (error) {
190
+ throw new ExitError(ATTENTION, error.message);
191
+ }
192
+ if (values.server && server !== config.server) {
193
+ config.server = server;
194
+ changed = true;
195
+ }
196
+ if (values.name !== undefined) {
197
+ const name = machineName(values.name);
198
+ if (!name) throw new ExitError(1, `名称需为 1–${NAME_MAX_CHARS} 个字符,不能包含控制字符`);
199
+ if (name !== config.machineName) {
200
+ config.machineName = name;
201
+ changed = true;
202
+ }
203
+ }
204
+ if (values['work-dir']) {
205
+ const dir = path.resolve(values['work-dir']);
206
+ if (dir !== config.workRoot) {
207
+ config.workRoot = dir;
208
+ changed = true;
209
+ }
210
+ }
211
+ // The work-agent clone and the knowledge pool: wherever the config file says.
212
+ let paths;
213
+ try {
214
+ const resolved = withRepoPaths(defaults, config);
215
+ paths = resolved.paths;
216
+ if (resolved.missing) {
217
+ // Write both into the config, so the file always shows where they are.
218
+ config.workAgentRepoDir = paths.repoDir;
219
+ config.ascendReposDir = paths.poolDir;
220
+ changed = true;
221
+ }
222
+ } catch (error) {
223
+ throw new ExitError(ATTENTION, error.message);
224
+ }
225
+ // runs/ lives in the program's home unless --work-dir moves it.
226
+ const workRoot = needWorkRoot ? prepareWorkRoot(config.workRoot || paths.runsRoot) : '';
227
+ if (changed) saveConfig(paths, config);
228
+ const workAgent = new WorkAgent({
229
+ paths,
230
+ log,
231
+ // A mirror of the work-agent repository: from this machine's own config, or
232
+ // from WORK_AGENT_REPO for development and tests (any scheme, so a local
233
+ // path works). Never from the website, and clone() logs where it went.
234
+ repoUrl: process.env.WORK_AGENT_REPO || config.workAgentRepo,
235
+ });
236
+ // The Skills' logs, scratch and deliverables, and the pool symlink when there
237
+ // is a pool; a job's HOME links to this directory.
238
+ if (needWorkRoot) prepareWorkAgentHome(paths.workAgentHome, workAgent.mountablePool());
239
+ return { paths, config, server, workRoot, realHome: realHome(), workAgent };
240
+ }
241
+
242
+ function save(ctx) {
243
+ saveConfig(ctx.paths, ctx.config);
244
+ }
245
+
246
+ function clientFor(ctx, token = ctx.config.token) {
247
+ return createClient({ server: ctx.server, token, clientId: ctx.config.clientId, version: VERSION });
248
+ }
249
+
250
+ /** POST /connect. `name` only names a machine the website does not know yet. */
251
+ function connect(ctx, client, capabilities) {
252
+ return client.request('POST', '/connect', {
253
+ hostname: os.hostname(),
254
+ name: ctx.config.machineName || '',
255
+ version: VERSION,
256
+ capabilities,
257
+ system: systemInfo(ctx),
258
+ });
259
+ }
260
+
261
+ function systemInfo(ctx) {
262
+ return collectSystemInfo({ workRoot: ctx.workRoot || ctx.config.workRoot || ctx.paths.runsRoot });
263
+ }
264
+
265
+ /** After /connect: what the machine is called there, and whether its owner confirmed it. */
266
+ function sayRegistered(ctx, reply) {
267
+ say(`✓ 已连接 ${ctx.server},本机登记为「${reply.name}」(令牌:${reply.tokenName})`);
268
+ if (!reply.created && ctx.config.machineName && reply.name !== ctx.config.machineName) {
269
+ say(` 这台机器之前已登记为「${reply.name}」,名称请在网页上修改`);
270
+ }
271
+ if (reply.confirmed === false) {
272
+ say('⚠ 这台机器还没有确认,确认后才会收到任务:请在网页「在线 Agent → 模型配置 → 执行机器」里核对主机名和 IP 后点「确认」');
273
+ say(` ${ctx.server}/features#agent/config`);
274
+ }
275
+ }
276
+
277
+ /** First login in a terminal: the name this machine registers with (Enter = hostname). */
278
+ async function askMachineName(ctx) {
279
+ const hostname = os.hostname();
280
+ for (;;) {
281
+ const answer = await askText(`给这台机器起个名字(回车使用主机名 ${hostname}):`);
282
+ if (!answer) {
283
+ ctx.config.machineName = machineName(hostname) || '';
284
+ return;
285
+ }
286
+ const name = machineName(answer);
287
+ if (name) {
288
+ ctx.config.machineName = name;
289
+ return;
290
+ }
291
+ say(`名称需为 1–${NAME_MAX_CHARS} 个字符,不能包含控制字符`);
292
+ }
293
+ }
294
+
295
+ function networkReason(error) {
296
+ return error?.cause?.code || error?.cause?.message || error?.message || String(error);
297
+ }
298
+
299
+ /** doctor + remembering a claude found outside PATH. */
300
+ async function doctorFor(ctx) {
301
+ const result = await runDoctor({
302
+ configuredClaude: ctx.config.claudePath || '',
303
+ workRoot: ctx.workRoot,
304
+ realHome: ctx.realHome,
305
+ workAgent: ctx.workAgent,
306
+ });
307
+ const remembered = result.claude.viaNpmPrefix || result.claude.path === ctx.config.claudePath ? result.claude.path : '';
308
+ if ((ctx.config.claudePath || '') !== remembered) {
309
+ ctx.config.claudePath = remembered;
310
+ save(ctx);
311
+ }
312
+ return result;
313
+ }
314
+
315
+ function connectFailure(error, server) {
316
+ if (error instanceof ApiError) {
317
+ if (error.status === 403) return new ExitError(ATTENTION, error.message);
318
+ if (error.status === 400) return new ExitError(1, `网站拒绝了连接:${error.message}`);
319
+ }
320
+ return new ExitError(1, `无法连接 ${server}:${networkReason(error)}`);
321
+ }
322
+
323
+ /**
324
+ * Asks for the token (or reads it from stdin), checks it with POST /connect
325
+ * and saves it only then. Up to 3 tries in a terminal.
326
+ */
327
+ async function obtainToken(ctx, { fromStdin = false, capabilities }) {
328
+ if (!fromStdin && !isInteractive()) throw new ExitError(ATTENTION, '还没有接入令牌:请先在终端运行 work-agent-runner login');
329
+ if (!fromStdin) say('请在「在线 Agent → 模型配置 → 接入令牌」复制令牌并粘贴(输入不显示):');
330
+ for (let attempt = 1; attempt <= 3; attempt += 1) {
331
+ const token = fromStdin ? await readStdin() : await readHidden('令牌:');
332
+ if (!TOKEN_PATTERN.test(token)) {
333
+ if (fromStdin) throw new ExitError(ATTENTION, '令牌格式不正确(应为 gcm_ 开头的 47 个字符)');
334
+ say('令牌格式不正确(应为 gcm_ 开头的 47 个字符),请重新粘贴');
335
+ continue;
336
+ }
337
+ if (!fromStdin && !ctx.config.machineName) await askMachineName(ctx);
338
+ const client = clientFor(ctx, token);
339
+ try {
340
+ const reply = await connect(ctx, client, capabilities);
341
+ ctx.config.token = token;
342
+ save(ctx);
343
+ sayRegistered(ctx, reply);
344
+ return { client, reply };
345
+ } catch (error) {
346
+ if (error instanceof ApiError && error.status === 401) {
347
+ if (fromStdin) throw new ExitError(ATTENTION, '令牌无效或已删除');
348
+ say('令牌无效或已删除,请重新粘贴');
349
+ continue;
350
+ }
351
+ if (error instanceof ApiError && error.status === 429) throw new ExitError(1, '请求过于频繁,请稍后再试');
352
+ throw connectFailure(error, ctx.server);
353
+ }
354
+ }
355
+ throw new ExitError(ATTENTION, '令牌 3 次都不正确,已退出');
356
+ }
357
+
358
+ /** POST /connect with the saved token; waits out network trouble (services must not give up). */
359
+ async function connectSaved(ctx, client, capabilities) {
360
+ let delay = 1000;
361
+ for (;;) {
362
+ try {
363
+ return await connect(ctx, client, capabilities);
364
+ } catch (error) {
365
+ const fatal = fatalFor(error);
366
+ if (fatal) {
367
+ if (fatal.clearToken) {
368
+ ctx.config.token = '';
369
+ save(ctx);
370
+ }
371
+ throw new ExitError(fatal.code, fatal.message);
372
+ }
373
+ if (error instanceof ApiError && error.status !== 429 && error.status < 500) throw connectFailure(error, ctx.server);
374
+ log.warn(`无法连接 ${ctx.server}(${error instanceof ApiError ? error.message : networkReason(error)}),${Math.round(delay / 1000)} 秒后重试`);
375
+ await new Promise((resolve) => setTimeout(resolve, error?.retryAfterMs || delay));
376
+ delay = Math.min(60_000, delay * 2);
377
+ }
378
+ }
379
+ }
380
+
381
+ function toolLabel(name) {
382
+ return name === 'bwrap' ? 'bubblewrap' : name;
383
+ }
384
+
385
+ /** Updates every repository in the knowledge pool. Never fatal. */
386
+ async function updatePool(ctx) {
387
+ if (!ctx.workAgent.mountablePool()) return;
388
+ await ctx.workAgent
389
+ .updatePool({ say: (line) => log.info(line) })
390
+ .catch((error) => log.warn(`知识仓更新失败:${error.message}`));
391
+ }
392
+
393
+ /** Brings the clone up to date. Never fatal: the website shows the reason instead. */
394
+ async function refreshWorkAgent(ctx, { say: out = say } = {}) {
395
+ try {
396
+ return await ctx.workAgent.refresh();
397
+ } catch (error) {
398
+ out(`work-agent 仓库检查失败:${error.message}`);
399
+ return ctx.workAgent.state();
400
+ }
401
+ }
402
+
403
+ /** ",3 天前更新" for the knowledge pool line ('' when it was never fetched). */
404
+ function poolAge(fetchedAt) {
405
+ if (!fetchedAt) return '';
406
+ const days = Math.floor((Date.now() - fetchedAt) / 86_400_000);
407
+ return `,${days <= 0 ? '今天' : `${days} 天前`}更新`;
408
+ }
409
+
410
+ /** The Skill source and the knowledge pool, in two lines. */
411
+ function printWorkAgent(state) {
412
+ if (state.ok) say(`✓ work-agent ${state.commit.slice(0, 7)}${state.committedAt ? `(${state.committedAt.slice(0, 10)})` : ''}`);
413
+ else say(`✗ work-agent 仓库不可用:${state.reason}`);
414
+ if (state.incomplete?.length) {
415
+ say(` 知识仓 ${state.incomplete.join('、')} 不完整:请删除后重新运行 work-agent-runner setup`);
416
+ } else if (state.repos) {
417
+ const what = state.ascend ? `${state.repos} 个仓(含 AscendC 两仓)` : `${state.repos} 个仓,缺 AscendC 两仓(代码检视的 AscendC 规范域不检查)`;
418
+ say(` 知识仓:${what}${poolAge(state.poolFetchedAt)}`);
419
+ } else {
420
+ say(' 知识仓:未初始化(可选,约 1.1 GB;运行 work-agent-runner setup 下载)');
421
+ }
422
+ }
423
+
424
+ const REPO_NAME = /^[A-Za-z0-9._-]{1,80}$/;
425
+
426
+ /** `--repos a,b` → names, validated the way work-agent.py validates them. */
427
+ function splitRepos(value) {
428
+ const names = String(value).split(/[,\s]+/).filter(Boolean);
429
+ for (const name of names) {
430
+ if (!REPO_NAME.test(name) || name.startsWith('.')) throw new ExitError(1, `仓名不正确:${name}`);
431
+ }
432
+ if (!names.length) throw new ExitError(1, '--repos 需要至少一个仓名');
433
+ return names;
434
+ }
435
+
436
+ /**
437
+ * Offers the AscendC knowledge pool (≈1.1 GB), in a terminal only. Never
438
+ * downloads anything without a yes: `--repos` picks the repos, `--no-repos`
439
+ * skips the question.
440
+ */
441
+ async function offerPool(ctx, values) {
442
+ if (values['no-repos']) return;
443
+ const wanted = values.repos === undefined ? ASCEND_REPOS : splitRepos(values.repos);
444
+ const pool = ctx.workAgent.poolState();
445
+ if (pool.incomplete.length) {
446
+ say(`知识仓 ${pool.incomplete.join('、')} 不完整:请先删除 ${ctx.workAgent.paths.poolDir} 下这些目录`);
447
+ return;
448
+ }
449
+ if (pool.ascend && values.repos === undefined) {
450
+ say(`知识仓已就绪(${ctx.workAgent.paths.poolDir},${pool.repos} 个仓)`);
451
+ return;
452
+ }
453
+ say(`AscendC 知识仓用于「代码检视」的 AscendC 规范域:${wanted.join('、')},约 1.1 GB,下载到 ${ctx.workAgent.paths.poolDir}`);
454
+ say('不下载也能用,只是那部分规范不检查。');
455
+ if (!values.yes && !(await askYesNo('是否现在下载?'))) {
456
+ say('已跳过;以后随时可以再运行 work-agent-runner setup');
457
+ return;
458
+ }
459
+ try {
460
+ await ctx.workAgent.initPool({ repos: wanted, say });
461
+ prepareWorkAgentHome(ctx.paths.workAgentHome, ctx.workAgent.mountablePool());
462
+ } catch (error) {
463
+ say(`下载知识仓失败:${error.message}`);
464
+ }
465
+ }
466
+
467
+ function neededBy(tool) {
468
+ if (tool === 'bwrap' || tool === 'socat') return '沙箱需要(所有功能)';
469
+ if (tool === 'rg') return '检索 AscendC 知识仓需要';
470
+ const features = Object.entries(FEATURE_TOOLS).filter(([, tools]) => tools.includes(tool)).map(([feature]) => FEATURE_LABELS[feature]);
471
+ return features.length === 3 ? '所有功能需要' : `${features.join('、')}需要`;
472
+ }
473
+
474
+ function printDoctor(result) {
475
+ const ready = [];
476
+ const missing = [];
477
+ for (const [name, info] of Object.entries(result.tools)) {
478
+ if (info.ok) ready.push(`✓ ${toolLabel(name)}${info.version ? ` ${info.version.split('.').slice(0, 2).join('.')}` : ''}`);
479
+ else missing.push(name);
480
+ }
481
+ if (ready.length) say(` ${ready.join(' ')}`);
482
+ for (const name of missing) say(` ✗ ${toolLabel(name).padEnd(11)} ${neededBy(name)}`);
483
+ if (!result.claude.path) say(` ✗ ${'claude'.padEnd(11)} 所有功能需要`);
484
+ else {
485
+ say(` ✓ claude ${result.claudeVersion || '(无法读取版本)'}`);
486
+ if (result.claude.viaNpmPrefix) say(` 提示:claude 在 ${path.dirname(result.claude.path)},建议把这个目录加入 PATH`);
487
+ }
488
+ const { sandbox } = result.capabilities;
489
+ if (sandbox.ok) say('✓ 沙箱可用');
490
+ else say(`✗ 沙箱不可用:${sandbox.reason}(说明:${SANDBOX_DOCS})`);
491
+ }
492
+
493
+ function printFeatures(reply) {
494
+ if (!reply?.features) return;
495
+ const entries = Object.entries(reply.features);
496
+ const ok = entries.filter(([, verdict]) => verdict.ok).map(([feature]) => FEATURE_LABELS[feature] || feature);
497
+ say(ok.length ? `可运行:${ok.join('、')}` : '暂时没有可运行的功能');
498
+ for (const [feature, verdict] of entries) {
499
+ if (!verdict.ok) say(`不可运行:${FEATURE_LABELS[feature] || feature}(${verdict.reason})`);
500
+ }
501
+ if (reply.outdated) say(`程序版本过低,请运行 ${UPDATE_COMMAND}`);
502
+ }
503
+
504
+ function setupPlan(result, reply, { poolWanted = false } = {}) {
505
+ const npm = which('npm');
506
+ let npmWritable = false;
507
+ if (npm) {
508
+ const prefix = spawnSync(npm, ['prefix', '-g'], { encoding: 'utf8', timeout: 20_000, stdio: ['ignore', 'pipe', 'ignore'] }).stdout?.trim();
509
+ npmWritable = prefix ? npmPrefixWritable(prefix) : false;
510
+ }
511
+ return planSetup({
512
+ platform: process.platform,
513
+ requiredTools: Array.isArray(reply?.requiredTools) ? reply.requiredTools : DEFAULT_REQUIRED_TOOLS,
514
+ // The website does not ask for rg; the knowledge pool needs it.
515
+ extraTools: poolWanted ? ['rg'] : [],
516
+ tools: result.tools,
517
+ claudeVersion: result.claudeVersion,
518
+ minClaudeVersion: reply?.minClaudeVersion || '',
519
+ manager: result.packageManager,
520
+ isRoot: process.getuid() === 0,
521
+ sudo: which('sudo'),
522
+ npm,
523
+ npmWritable,
524
+ });
525
+ }
526
+
527
+ // ---- Commands ------------------------------------------------------------------
528
+
529
+ async function start(values) {
530
+ checkSystem();
531
+ const restarted = await applyProxy();
532
+ if (restarted !== null) return restarted;
533
+ if (process.getuid() === 0) {
534
+ if (!values['allow-root']) {
535
+ throw new ExitError(ATTENTION, '不要以 root 运行:任务中的命令会拥有 root 权限。请用普通账号运行;容器等确有需要时加 --allow-root');
536
+ }
537
+ log.warn('正以 root 运行(--allow-root):沙箱内的命令拥有 root 权限,建议改用专用的低权限账号');
538
+ }
539
+ const ctx = loadContext(values);
540
+ let lock;
541
+ try {
542
+ lock = acquireLock(ctx.paths.lockFile);
543
+ } catch (error) {
544
+ if (error instanceof LockedError) throw new ExitError(ATTENTION, error.message);
545
+ throw error;
546
+ }
547
+ try {
548
+ say(`GitCode Agent 执行机器 ${VERSION}`);
549
+ if (legacyServiceInstalled()) log.warn(LEGACY_SERVICE_HINT);
550
+ // Whatever a previous run left behind (probe directories are runs/p******).
551
+ fs.rmSync(path.join(ctx.workRoot, 'runs'), { recursive: true, force: true });
552
+ const interactive = isInteractive() && !process.env.GC_RUNNER_SERVICE;
553
+ if (!ctx.config.token && !interactive) {
554
+ throw new ExitError(ATTENTION, '还没有接入令牌:请先在终端运行 work-agent-runner login');
555
+ }
556
+ say('检查 work-agent 仓库……');
557
+ printWorkAgent(await refreshWorkAgent(ctx));
558
+ // No job is running yet, so it is safe to empty $WORK_AGENT_HOME/tmp, drop
559
+ // old logs (work-agent's own cleanup) and pull the knowledge pool — a
560
+ // `git pull` must never replace files a running review is reading.
561
+ await ctx.workAgent.cleanup({ say: (line) => log.info(line) }).catch(() => {});
562
+ await updatePool(ctx);
563
+ say('检查依赖和沙箱……');
564
+ let result = await doctorFor(ctx);
565
+ let client;
566
+ let reply;
567
+ if (!ctx.config.token) {
568
+ ({ client, reply } = await obtainToken(ctx, { capabilities: result.capabilities }));
569
+ } else {
570
+ client = clientFor(ctx);
571
+ reply = await connectSaved(ctx, client, result.capabilities);
572
+ sayRegistered(ctx, reply);
573
+ }
574
+ printDoctor(result);
575
+ const firstRun = !ctx.config.setupDone && interactive;
576
+ if (firstRun) {
577
+ const outcome = await runSetup({
578
+ plan: setupPlan(result, reply, { poolWanted: !values['no-repos'] }),
579
+ interactive: true,
580
+ confirm: (question) => askYesNo(question),
581
+ say,
582
+ });
583
+ // Asked once: missing items stay visible in status and on the website.
584
+ ctx.config.setupDone = true;
585
+ save(ctx);
586
+ if (outcome.ran) {
587
+ say('重新检查……');
588
+ result = await doctorFor(ctx);
589
+ printDoctor(result);
590
+ }
591
+ // The same question `setup` asks, so a first run settles everything.
592
+ await offerPool(ctx, values);
593
+ result = await doctorFor(ctx);
594
+ reply = await connectSaved(ctx, client, result.capabilities);
595
+ }
596
+ printFeatures(reply);
597
+ say('等待任务……(Ctrl+C 退出;后台运行:work-agent-runner service install)');
598
+ return await serve(ctx, client, result, reply);
599
+ } finally {
600
+ lock.release();
601
+ }
602
+ }
603
+
604
+ async function serve(ctx, client, initial, reply) {
605
+ const controller = new AbortController();
606
+ let fatal = null;
607
+ const onFatal = (error) => {
608
+ const result = fatalFor(error);
609
+ if (result && !fatal) {
610
+ fatal = result;
611
+ controller.abort();
612
+ }
613
+ };
614
+ const jobs = new JobManager({
615
+ client,
616
+ workAgent: ctx.workAgent,
617
+ workRoot: ctx.workRoot,
618
+ claudePath: initial.claude.path,
619
+ realHome: ctx.realHome,
620
+ log,
621
+ onFatal,
622
+ });
623
+ let capabilities = initial.capabilities;
624
+ let checking = false;
625
+ // Every hour: the knowledge pool, then the dependency and sandbox check.
626
+ const doctorTimer = setInterval(async () => {
627
+ // A hung pull must not stack up another round.
628
+ if (checking) return;
629
+ checking = true;
630
+ try {
631
+ // Only between jobs: a pull would replace files under a running review.
632
+ if (!jobs.runningIds().length) await updatePool(ctx);
633
+ const fresh = await doctorFor(ctx);
634
+ capabilities = fresh.capabilities;
635
+ if (fresh.claude.path) jobs.claudePath = fresh.claude.path;
636
+ } catch (error) {
637
+ log.warn(`定期检查失败:${error.message}`);
638
+ } finally {
639
+ checking = false;
640
+ }
641
+ }, POOL_UPDATE_MS);
642
+ doctorTimer.unref();
643
+ // Every day at 08:00 local time: the work-agent clone (the Skill source).
644
+ let repoTimer = null;
645
+ const scheduleRepoUpdate = () => {
646
+ const next = new Date();
647
+ next.setHours(REPO_UPDATE_HOUR, 0, 0, 0);
648
+ if (next.getTime() <= Date.now()) next.setDate(next.getDate() + 1);
649
+ repoTimer = setTimeout(async () => {
650
+ printWorkAgent(await refreshWorkAgent(ctx, { say: (line) => log.info(line) }));
651
+ try {
652
+ capabilities = (await doctorFor(ctx)).capabilities;
653
+ } catch (error) {
654
+ log.warn(`定期检查失败:${error.message}`);
655
+ }
656
+ // Re-armed each time, so it stays on 08:00 across a change of day length.
657
+ scheduleRepoUpdate();
658
+ }, next.getTime() - Date.now());
659
+ repoTimer.unref();
660
+ };
661
+ scheduleRepoUpdate();
662
+ let stopping = false;
663
+ const onSignal = (signal) => {
664
+ if (stopping) return;
665
+ stopping = true;
666
+ log.info(`收到 ${signal},正在停止(结束运行中的任务)……`);
667
+ controller.abort();
668
+ };
669
+ process.on('SIGINT', onSignal);
670
+ process.on('SIGTERM', onSignal);
671
+ const result = await runConnection({
672
+ client,
673
+ jobs,
674
+ log,
675
+ version: VERSION,
676
+ connect: () => connect(ctx, client, capabilities),
677
+ capabilities: { current: () => capabilities },
678
+ system: { current: () => systemInfo(ctx) },
679
+ confirmed: reply.confirmed !== false,
680
+ heartbeatMs: reply.heartbeatMs,
681
+ signal: controller.signal,
682
+ });
683
+ clearInterval(doctorTimer);
684
+ clearTimeout(repoTimer);
685
+ const outcome = fatal || result;
686
+ ctx.workAgent.stop();
687
+ await jobs.stopAll(5000);
688
+ if (outcome.clearToken) {
689
+ ctx.config.token = '';
690
+ save(ctx);
691
+ }
692
+ if (outcome.code) log.error(outcome.message);
693
+ else log.info('已停止');
694
+ return outcome.code || 0;
695
+ }
696
+
697
+ async function login(values) {
698
+ checkSystem();
699
+ const restarted = await applyProxy();
700
+ if (restarted !== null) return restarted;
701
+ const ctx = loadContext(values);
702
+ if (values['new-id']) {
703
+ ctx.config.clientId = newClientId();
704
+ // A new machine on the website: ask for its name again (unless --name gave one).
705
+ if (values.name === undefined) ctx.config.machineName = '';
706
+ save(ctx);
707
+ say('已生成新的机器标识:这台机器在网页上会作为新机器出现,需要在网页上确认');
708
+ }
709
+ if (!values['token-stdin'] && !isInteractive()) throw new ExitError(ATTENTION, 'login 需要在终端里运行(脚本里请用 --token-stdin)');
710
+ say('检查依赖和沙箱……');
711
+ const result = await doctorFor(ctx);
712
+ await obtainToken(ctx, { fromStdin: Boolean(values['token-stdin']), capabilities: result.capabilities });
713
+ return 0;
714
+ }
715
+
716
+ function logout(values) {
717
+ const ctx = loadContext(values, { workRoot: false });
718
+ const had = Boolean(ctx.config.token);
719
+ ctx.config.token = '';
720
+ save(ctx);
721
+ say(had ? '已清除本机保存的令牌(机器标识保留)' : '本机没有保存令牌');
722
+ return 0;
723
+ }
724
+
725
+ async function setup(values) {
726
+ checkSystem();
727
+ const restarted = await applyProxy();
728
+ if (restarted !== null) return restarted;
729
+ if (!isInteractive()) throw new ExitError(ATTENTION, 'setup 需要在终端里运行(安装前会请你确认)');
730
+ const ctx = loadContext(values);
731
+ say('检查 work-agent 仓库……');
732
+ printWorkAgent(await refreshWorkAgent(ctx));
733
+ say('检查依赖和沙箱……');
734
+ let result = await doctorFor(ctx);
735
+ let client = null;
736
+ let reply = null;
737
+ if (ctx.config.token) {
738
+ client = clientFor(ctx);
739
+ try {
740
+ reply = await connect(ctx, client, result.capabilities);
741
+ } catch (error) {
742
+ say(`无法从网站读取要求(${error.message}),按默认要求检查`);
743
+ client = null;
744
+ }
745
+ }
746
+ printDoctor(result);
747
+ const poolWanted = !values['no-repos'];
748
+ const outcome = await runSetup({
749
+ plan: setupPlan(result, reply, { poolWanted }),
750
+ interactive: true,
751
+ yes: Boolean(values.yes),
752
+ confirm: (question) => askYesNo(question),
753
+ say,
754
+ });
755
+ ctx.config.setupDone = true;
756
+ save(ctx);
757
+ if (outcome.ran) {
758
+ say('重新检查……');
759
+ result = await doctorFor(ctx);
760
+ printDoctor(result);
761
+ }
762
+ // After the tools: the pool is searched with rg.
763
+ await offerPool(ctx, values);
764
+ if (client) reply = await connect(ctx, client, (await doctorFor(ctx)).capabilities).catch(() => reply);
765
+ printFeatures(reply);
766
+ return outcome.failed.length ? 1 : 0;
767
+ }
768
+
769
+ /** `update`: both repositories, now. */
770
+ async function update(values) {
771
+ checkSystem();
772
+ const restarted = await applyProxy();
773
+ if (restarted !== null) return restarted;
774
+ const ctx = loadContext(values);
775
+ let failed = false;
776
+ try {
777
+ const state = await ctx.workAgent.refresh();
778
+ printWorkAgent(state);
779
+ failed = !state.ok;
780
+ if (ctx.workAgent.mountablePool()) await ctx.workAgent.updatePool({ say });
781
+ } catch (error) {
782
+ say(error.message);
783
+ failed = true;
784
+ }
785
+ if (ctx.config.token) {
786
+ // So the website shows the new commit without waiting for the hourly check.
787
+ try {
788
+ printFeatures(await connect(ctx, clientFor(ctx), (await doctorFor(ctx)).capabilities));
789
+ } catch {
790
+ say('(没能把新状态报给网站,程序下次连接时会报)');
791
+ }
792
+ }
793
+ return failed ? 1 : 0;
794
+ }
795
+
796
+ async function doctor(values) {
797
+ checkSystem();
798
+ const restarted = await applyProxy();
799
+ if (restarted !== null) return restarted;
800
+ const ctx = loadContext(values);
801
+ const result = await doctorFor(ctx);
802
+ let reply = null;
803
+ let note = '';
804
+ if (ctx.config.token) {
805
+ try {
806
+ // Also brings the website's copy of this machine's capabilities up to date.
807
+ reply = await connect(ctx, clientFor(ctx), result.capabilities);
808
+ } catch (error) {
809
+ note = error instanceof ApiError && error.status === 401 ? '令牌无效或已删除' : `无法连接网站:${error instanceof ApiError ? error.message : networkReason(error)}`;
810
+ }
811
+ } else note = '还没有接入令牌,无法判断各功能(运行 work-agent-runner login)';
812
+ const system = systemInfo(ctx);
813
+ const repo = ctx.workAgent.state();
814
+ if (values.json) {
815
+ say(JSON.stringify({ version: VERSION, capabilities: result.capabilities, workAgent: repo, system, claudePath: result.claude.path, features: reply?.features || null, confirmed: reply?.confirmed ?? null, note }, null, 2));
816
+ return 0;
817
+ }
818
+ say(`GitCode Agent 执行机器 ${VERSION} · Node ${process.versions.node} · ${process.platform}/${process.arch}`);
819
+ say(`系统:${describeSystem(system)}`);
820
+ printWorkAgent(repo);
821
+ printDoctor(result);
822
+ printFeatures(reply);
823
+ if (reply?.confirmed === false) say('这台机器还没有在网页上确认,确认后才会收到任务(在线 Agent → 模型配置 → 执行机器)');
824
+ if (note) say(note);
825
+ return 0;
826
+ }
827
+
828
+ async function status(values) {
829
+ checkSystem();
830
+ const restarted = await applyProxy();
831
+ if (restarted !== null) return restarted;
832
+ const ctx = loadContext(values, { workRoot: false });
833
+ const { config } = ctx;
834
+ say(`网站:${ctx.server}`);
835
+ say(`令牌:${config.token ? `${config.token.slice(0, 12)}…` : '未登录(运行 work-agent-runner login)'}`);
836
+ say(`机器标识:${config.clientId}`);
837
+ say(`登记名称:${config.machineName || `${os.hostname()}(主机名)`}`);
838
+ say(`程序目录:${ctx.paths.baseDir}`);
839
+ say(`任务目录:${path.join(config.workRoot || ctx.paths.runsRoot, 'runs')}`);
840
+ const repo = ctx.workAgent.state();
841
+ say(`work-agent 仓库:${repo.ok ? `${repo.commit.slice(0, 7)}(${ctx.workAgent.repoDir})` : repo.reason}`);
842
+ say(`WORK_AGENT_HOME:${ctx.paths.workAgentHome}`);
843
+ say(`知识仓:${repo.ascend ? `${repo.repos} 个仓,含 AscendC 两仓` : repo.repos ? `${repo.repos} 个仓,缺 AscendC 两仓` : '未初始化'}(${ctx.paths.poolDir})`);
844
+ say(`系统:${describeSystem(systemInfo(ctx))}`);
845
+ say(`配置文件:${ctx.paths.configFile}`);
846
+ const service = serviceStatus();
847
+ say(`后台服务:${service.installed ? service.state : '未安装'}${service.installed ? `(${service.logHint})` : ''}`);
848
+ if (legacyServiceInstalled()) say(LEGACY_SERVICE_HINT);
849
+ const holder = lockHolder(ctx.paths.lockFile);
850
+ say(`运行中的实例:${isRunnerAlive(holder) ? `pid ${holder}` : '无'}`);
851
+ if (!config.token) return 0;
852
+ try {
853
+ // A request with no effect (it must not be /heartbeat: reporting no running
854
+ // jobs from a second process would make the website fail this machine's jobs).
855
+ await clientFor(ctx).request('GET', '/ping');
856
+ say('连接测试:正常');
857
+ } catch (error) {
858
+ if (error instanceof ApiError) {
859
+ const text = {
860
+ 404: '网站版本过旧(没有 /ping),请联系管理员部署新版网站',
861
+ 401: '令牌无效或已删除(运行 work-agent-runner login)',
862
+ 403: '这台机器已被封禁',
863
+ 409: '令牌有效,这台机器尚未登记(运行 work-agent-runner 会自动登记,之后在网页上确认)',
864
+ }[error.status] || error.message;
865
+ say(`连接测试:${text}`);
866
+ } else say(`连接测试:失败(${networkReason(error)})`);
867
+ }
868
+ return 0;
869
+ }
870
+
871
+ async function service(action, values) {
872
+ checkSystem();
873
+ if (action === 'install') {
874
+ // First, so that loadContext() can take over the old program's config.
875
+ removeLegacyService({ say });
876
+ const ctx = loadContext(values);
877
+ if (!ctx.config.token) {
878
+ if (!isInteractive()) throw new ExitError(ATTENTION, '还没有接入令牌:请先在终端运行 work-agent-runner login');
879
+ const restarted = await applyProxy();
880
+ if (restarted !== null) return restarted;
881
+ say('检查依赖和沙箱……');
882
+ const result = await doctorFor(ctx);
883
+ await obtainToken(ctx, { capabilities: result.capabilities });
884
+ }
885
+ const holder = lockHolder(ctx.paths.lockFile);
886
+ if (isRunnerAlive(holder) && !process.env.GC_RUNNER_SERVICE) {
887
+ say(`注意:已有实例在运行(pid ${holder})。如果是前台运行的程序,请先按 Ctrl+C 停止它,否则服务无法启动。`);
888
+ }
889
+ installService({
890
+ nodePath: process.execPath,
891
+ entry: fs.realpathSync(ENTRY),
892
+ args: ['start', ...(values['allow-root'] ? ['--allow-root'] : [])],
893
+ say,
894
+ });
895
+ return 0;
896
+ }
897
+ if (action === 'uninstall') {
898
+ uninstallService({ say });
899
+ return 0;
900
+ }
901
+ if (action === 'status') {
902
+ const state = serviceStatus();
903
+ say(state.installed ? `后台服务:${state.state}` : '后台服务:未安装');
904
+ say(state.logHint);
905
+ if (legacyServiceInstalled()) say(LEGACY_SERVICE_HINT);
906
+ return 0;
907
+ }
908
+ throw new ExitError(1, '用法:work-agent-runner service install | uninstall | status');
909
+ }
910
+
911
+ async function main(argv) {
912
+ let parsed;
913
+ try {
914
+ parsed = parseArgs({
915
+ args: argv,
916
+ allowPositionals: true,
917
+ options: {
918
+ server: { type: 'string' },
919
+ 'work-dir': { type: 'string' },
920
+ name: { type: 'string' },
921
+ 'allow-root': { type: 'boolean' },
922
+ 'new-id': { type: 'boolean' },
923
+ 'token-stdin': { type: 'boolean' },
924
+ repos: { type: 'string' },
925
+ 'no-repos': { type: 'boolean' },
926
+
927
+ yes: { type: 'boolean', short: 'y' },
928
+ json: { type: 'boolean' },
929
+ version: { type: 'boolean', short: 'v' },
930
+ help: { type: 'boolean', short: 'h' },
931
+ },
932
+ });
933
+ } catch (error) {
934
+ throw new ExitError(1, `${error.message}\n\n${USAGE}`);
935
+ }
936
+ const { values, positionals } = parsed;
937
+ if (values.version) return say(VERSION) ?? 0;
938
+ if (values.help) return say(USAGE) ?? 0;
939
+ const [command = 'start', action] = positionals;
940
+ switch (command) {
941
+ case 'start':
942
+ return start(values);
943
+ case 'login':
944
+ return login(values);
945
+ case 'logout':
946
+ return logout(values);
947
+ case 'setup':
948
+ return setup(values);
949
+ case 'update':
950
+ return update(values);
951
+ case 'doctor':
952
+ return doctor(values);
953
+ case 'status':
954
+ return status(values);
955
+ case 'service':
956
+ return service(action, values);
957
+ case 'version':
958
+ say(VERSION);
959
+ return 0;
960
+ case 'help':
961
+ say(USAGE);
962
+ return 0;
963
+ default:
964
+ throw new ExitError(1, `未知的命令:${command}\n\n${USAGE}`);
965
+ }
966
+ }
967
+
968
+ function finish(code) {
969
+ const exitCode = serviceExitCode(code);
970
+ // Let buffered output reach a pipe before exiting.
971
+ process.stdout.write('', () => process.exit(exitCode));
972
+ }
973
+
974
+ main(process.argv.slice(2)).then(
975
+ (code) => finish(Number.isInteger(code) ? code : 0),
976
+ (error) => {
977
+ if (error instanceof ExitError) {
978
+ if (error.message) process.stderr.write(`${error.message}\n`);
979
+ finish(error.code);
980
+ } else if (error instanceof CancelledError) {
981
+ finish(0);
982
+ } else if (error instanceof ConfigError || error instanceof WorkRootError) {
983
+ process.stderr.write(`${error.message}\n`);
984
+ finish(ATTENTION);
985
+ } else {
986
+ process.stderr.write(`出错:${error?.message || error}\n`);
987
+ finish(1);
988
+ }
989
+ },
990
+ );