@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/CHANGELOG.md +65 -0
- package/README.md +289 -116
- package/bin/main.mjs +1948 -436
- package/lib/check.mjs +391 -0
- package/lib/claude-cli.mjs +8 -0
- package/lib/claude-install.mjs +221 -0
- package/lib/config.mjs +48 -4
- package/lib/connection.mjs +87 -4
- package/lib/control.mjs +330 -0
- package/lib/diagnose.mjs +82 -0
- package/lib/doctor.mjs +19 -3
- package/lib/errors.mjs +43 -0
- package/lib/jobs.mjs +428 -91
- package/lib/log.mjs +100 -7
- package/lib/maintenance.mjs +394 -0
- package/lib/sandbox.mjs +55 -6
- package/lib/service.mjs +42 -6
- package/lib/setup-state.mjs +119 -0
- package/lib/setup.mjs +4 -1
- package/lib/state.mjs +145 -0
- package/lib/uninstall.mjs +122 -0
- package/lib/views.mjs +260 -0
- package/lib/work-agent.mjs +27 -6
- package/package.json +2 -2
package/bin/main.mjs
CHANGED
|
@@ -3,11 +3,18 @@
|
|
|
3
3
|
// supported Node runs it. This file owns every side effect — arguments, the
|
|
4
4
|
// config file, the lock, signals, exit codes; ../lib does the work.
|
|
5
5
|
//
|
|
6
|
+
// The running instance (`start`, in the foreground or as a service) is the
|
|
7
|
+
// one writer of this program home's state: terminal commands ask it through
|
|
8
|
+
// the local control interface (lib/control.mjs) when it runs — `status`,
|
|
9
|
+
// `jobs`, `update`, `setup`'s knowledge pool, `doctor` — and only act
|
|
10
|
+
// themselves when it does not.
|
|
11
|
+
//
|
|
6
12
|
// Exit codes: 0 stopped normally, 1 error, 78 needs a person (no token, token
|
|
7
13
|
// deleted, machine blocked, same config running twice, unsupported system,
|
|
8
14
|
// root, another instance, the old gitcode-agent-runner still running, a
|
|
9
15
|
// directory that is not this program's) — services do not restart on 78
|
|
10
|
-
// (launchd: 0).
|
|
16
|
+
// (launchd: 0). `status`: 0 running and fine, 1 running with a problem, 2 not
|
|
17
|
+
// running or not connected.
|
|
11
18
|
|
|
12
19
|
import { spawn, spawnSync } from 'node:child_process';
|
|
13
20
|
import { once } from 'node:events';
|
|
@@ -21,11 +28,11 @@ import {
|
|
|
21
28
|
ConfigError,
|
|
22
29
|
DEFAULT_SERVER,
|
|
23
30
|
LEGACY_NAME,
|
|
24
|
-
POOL_UPDATE_MS,
|
|
25
|
-
REPO_UPDATE_HOUR,
|
|
26
31
|
WorkRootError,
|
|
27
32
|
adoptLegacyState,
|
|
28
33
|
configPaths,
|
|
34
|
+
effectiveSettings,
|
|
35
|
+
isInside,
|
|
29
36
|
legacyConfigPending,
|
|
30
37
|
legacyLockFile,
|
|
31
38
|
loadConfig,
|
|
@@ -36,30 +43,49 @@ import {
|
|
|
36
43
|
withRepoPaths,
|
|
37
44
|
} from '../lib/config.mjs';
|
|
38
45
|
import { UPDATE_COMMAND, fatalFor, runConnection } from '../lib/connection.mjs';
|
|
46
|
+
import { ControlError, NotRunningError, controlDirectories, controlRequest, pingInstance, socketLocation, startControlServer } from '../lib/control.mjs';
|
|
47
|
+
import { FEATURE_TOOLS, assessCheck, readApparmor, readUserns, sandboxProblem } from '../lib/check.mjs';
|
|
48
|
+
import {
|
|
49
|
+
CLAUDE_PACKAGE_PAGE,
|
|
50
|
+
CLAUDE_TERMS,
|
|
51
|
+
MIRROR_REGISTRY,
|
|
52
|
+
OFFICIAL_REGISTRY,
|
|
53
|
+
claudePlatform,
|
|
54
|
+
installClaude,
|
|
55
|
+
resolveClaudeVersion,
|
|
56
|
+
} from '../lib/claude-install.mjs';
|
|
57
|
+
import { VERIFIED_CLAUDE_VERSION } from '../lib/claude-cli.mjs';
|
|
39
58
|
import { SANDBOX_DOCS, runDoctor, which } from '../lib/doctor.mjs';
|
|
40
|
-
import { cleanRunsDir
|
|
59
|
+
import { cleanRunsDir } from '../lib/fs-safe.mjs';
|
|
41
60
|
import { ApiError, createClient, normalizeServerUrl, proxyMode } from '../lib/http.mjs';
|
|
42
61
|
import { FEATURE_LABELS, JobManager } from '../lib/jobs.mjs';
|
|
43
62
|
import { LockedError, acquireLock, isRunnerAlive, lockHolder } from '../lib/lock.mjs';
|
|
44
63
|
import { NODE_REQUIREMENT, nodeSupported } from '../lib/node-runtime.cjs';
|
|
45
|
-
import { createLogger } from '../lib/log.mjs';
|
|
64
|
+
import { createLogger, redactUrl } from '../lib/log.mjs';
|
|
65
|
+
import { Maintenance } from '../lib/maintenance.mjs';
|
|
46
66
|
import { CancelledError, askText, askYesNo, isInteractive, readHidden, readStdin } from '../lib/prompt.mjs';
|
|
47
67
|
import {
|
|
48
68
|
EXIT_NEEDS_ATTENTION,
|
|
49
69
|
controlService,
|
|
50
70
|
installService,
|
|
51
71
|
legacyServiceInstalled,
|
|
72
|
+
lingerEnabled,
|
|
52
73
|
removeLegacyService,
|
|
53
74
|
serviceExitCode,
|
|
75
|
+
servicePaths,
|
|
54
76
|
serviceStatus,
|
|
55
77
|
uninstallService,
|
|
56
78
|
} from '../lib/service.mjs';
|
|
57
|
-
import { DEFAULT_REQUIRED_TOOLS, npmPrefixWritable, planSetup, runSetup } from '../lib/setup.mjs';
|
|
58
|
-
import {
|
|
59
|
-
import {
|
|
79
|
+
import { DEFAULT_REQUIRED_TOOLS, formatCommand, npmPrefixWritable, planSetup, runCommand, runSetup } from '../lib/setup.mjs';
|
|
80
|
+
import { SETUP_STEPS, SetupState, openSetupLog, stepLine } from '../lib/setup-state.mjs';
|
|
81
|
+
import { bundleFiles, configForBundle, lastLines, tarGz } from '../lib/diagnose.mjs';
|
|
82
|
+
import { performUninstall, uninstallPlan } from '../lib/uninstall.mjs';
|
|
83
|
+
import { PROXY_VARIABLES, prepareWorkAgentHome } from '../lib/sandbox.mjs';
|
|
84
|
+
import { StateStore, countResults, matchesRunId, readHistory, readStatus } from '../lib/state.mjs';
|
|
85
|
+
import { collectSystemInfo } from '../lib/system-info.mjs';
|
|
86
|
+
import { checkLines, jobDetailLines, jobsLines, pathsLines, statusLines } from '../lib/views.mjs';
|
|
60
87
|
import {
|
|
61
88
|
WorkAgent,
|
|
62
|
-
clearPoolUpdateRequest,
|
|
63
89
|
freeBytes,
|
|
64
90
|
markPoolBusy,
|
|
65
91
|
poolBusyInfo,
|
|
@@ -72,24 +98,11 @@ const ENTRY = fileURLToPath(new URL('./work-agent-runner.cjs', import.meta.url))
|
|
|
72
98
|
const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
73
99
|
const TOKEN_PATTERN = /^gcm_[A-Za-z0-9_-]{43}$/;
|
|
74
100
|
const NAME_MAX_CHARS = 40; // the website's limit (normalizeMachineName)
|
|
75
|
-
const DOCTOR_INTERVAL_MS = 60 * 60_000;
|
|
76
101
|
const ATTENTION = EXIT_NEEDS_ATTENTION;
|
|
77
102
|
const LEGACY_SERVICE_HINT = `旧版程序 ${LEGACY_NAME} 的后台服务还在:运行 work-agent-runner service install 会停止并替换它(service uninstall 只删除)`;
|
|
78
103
|
// A terminal command waits this long for the service to be done with the clone.
|
|
79
104
|
const TERMINAL_LOCK_WAIT_MS = 2 * 60_000;
|
|
80
|
-
|
|
81
|
-
const CLONE_RETRY_START_MS = 60_000;
|
|
82
|
-
const CLONE_RETRY_MAX_MS = 30 * 60_000;
|
|
83
|
-
// How often the service looks for a knowledge-pool update a terminal asked for.
|
|
84
|
-
const REQUEST_POLL_MS = 30_000;
|
|
85
|
-
|
|
86
|
-
// Which tools each feature needs — for the messages here only; the website decides.
|
|
87
|
-
const FEATURE_TOOLS = {
|
|
88
|
-
'pr-desc-issue-gen': ['git', 'curl', 'python3'],
|
|
89
|
-
'ascend-code-review': ['git', 'python3', 'curl', 'jq', 'sed'],
|
|
90
|
-
'code-review-flash': ['python3', 'git', 'base64'],
|
|
91
|
-
'cann-knowledge': ['rg'],
|
|
92
|
-
};
|
|
105
|
+
|
|
93
106
|
|
|
94
107
|
const USAGE = `GitCode Agent 执行机器 ${VERSION}
|
|
95
108
|
|
|
@@ -97,18 +110,41 @@ const USAGE = `GitCode Agent 执行机器 ${VERSION}
|
|
|
97
110
|
|
|
98
111
|
命令:
|
|
99
112
|
start 连接网站并等待任务(默认)
|
|
113
|
+
status [--json] [--watch] 本机状态:运行情况、连接、任务、维护和问题(--watch 每 2 秒刷新)
|
|
114
|
+
(退出码:0 正常,1 有问题,2 没有运行或没连上网站)
|
|
115
|
+
jobs [--failed] [--since 24h] [-n 20] [--json]
|
|
116
|
+
任务记录;jobs show <任务 ID> 查看一个任务的过程,
|
|
117
|
+
jobs cancel <任务 ID> 在本机取消运行中的任务
|
|
118
|
+
logs [-f] [-n 100] [--job <任务 ID>] [--since 1h]
|
|
119
|
+
程序日志(-f 跟随新内容)
|
|
120
|
+
paths [--json] 各个目录在哪里,以及有没有问题
|
|
100
121
|
login [--new-id] [--token-stdin] [--name <名称>]
|
|
101
122
|
输入接入令牌(校验通过才保存);--new-id 重新生成机器标识
|
|
102
123
|
logout 清除本机保存的令牌(机器标识保留)
|
|
103
|
-
setup [--yes] [--repos
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
124
|
+
setup [--yes] [--reset] [--repos essential|none|<仓名>] [--claude-version <版本|stable|latest>] [--service]
|
|
125
|
+
逐步完成设置:预检、令牌、依赖、Claude Code(由程序下载并校验)、
|
|
126
|
+
沙箱、work-agent 仓库、知识仓(可选)、后台服务(可选)。已完成的
|
|
127
|
+
步骤再运行时很快确认,失败的可以重试;--reset 从头询问
|
|
128
|
+
setup --unattended --token-file <文件|-> [--name <名称>] [--repos essential|none] [--service]
|
|
129
|
+
无人值守:不提问(按选项来),过程写到 stderr,结果以 JSON 输出到
|
|
130
|
+
stdout,有步骤失败时退出码为 1
|
|
131
|
+
update 立即更新 work-agent 仓库和知识仓(程序在运行时由它来做,
|
|
132
|
+
知识仓在没有任务时更新)
|
|
133
|
+
check [--json] 逐项检查系统、网络、依赖、沙箱、Claude Code、仓库、服务和网站,
|
|
134
|
+
给出影响和处理办法(退出码:0 全部可用,1 部分功能不可用,
|
|
135
|
+
2 都不能运行;doctor 是它的旧名字)
|
|
136
|
+
cleanup [--yes] 清空 work-agent 的共享临时目录、删除 30 天前的日志(会先确认)
|
|
137
|
+
reload 让运行中的程序重新读取 config.json 里的维护时间、限额和隔离设置
|
|
138
|
+
upgrade [--to <版本>] [--drain-timeout 30m]
|
|
139
|
+
升级本程序:运行中的程序先停止接新任务、等任务结束,装好后重启
|
|
140
|
+
服务并确认连上网站,失败时装回原版本
|
|
141
|
+
uninstall [--purge] [--yes]
|
|
142
|
+
卸载:删除后台服务、在网站上注销、删除程序的目录(默认保留
|
|
143
|
+
config.json,--purge 全删);work-agent 的家和知识仓不动
|
|
144
|
+
diagnose [-o <文件>] 生成脱敏的诊断包(.tar.gz),发给支持人员之前请先自己看一遍
|
|
145
|
+
service install|uninstall|start|stop|restart|status|logs
|
|
146
|
+
后台服务:注册(开机自启)/ 删除 / 启动 / 停止 / 重启 / 查看 /
|
|
147
|
+
看服务管理器记下的输出
|
|
112
148
|
version 显示版本
|
|
113
149
|
|
|
114
150
|
选项:
|
|
@@ -127,8 +163,23 @@ class ExitError extends Error {
|
|
|
127
163
|
}
|
|
128
164
|
}
|
|
129
165
|
|
|
130
|
-
|
|
166
|
+
// Where say() writes: stdout, or (while a setup step runs) the step's own
|
|
167
|
+
// output, indented and copied into the setup log.
|
|
168
|
+
let output = (text) => process.stdout.write(`${text}\n`);
|
|
169
|
+
const say = (text = '') => output(String(text));
|
|
170
|
+
|
|
171
|
+
/** Runs `work` with say() going to `sink`. */
|
|
172
|
+
async function sayingTo(sink, work) {
|
|
173
|
+
const saved = output;
|
|
174
|
+
output = sink;
|
|
175
|
+
try {
|
|
176
|
+
return await work();
|
|
177
|
+
} finally {
|
|
178
|
+
output = saved;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
131
181
|
const log = createLogger();
|
|
182
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
132
183
|
|
|
133
184
|
function checkSystem() {
|
|
134
185
|
if (!['linux', 'darwin'].includes(process.platform)) throw new ExitError(ATTENTION, '暂不支持此系统(只支持 Linux 和 macOS)');
|
|
@@ -175,6 +226,21 @@ function machineName(value) {
|
|
|
175
226
|
return length >= 1 && length <= NAME_MAX_CHARS && !/\p{Cc}/u.test(name) ? name : '';
|
|
176
227
|
}
|
|
177
228
|
|
|
229
|
+
/** "24h" / "30m" / "7d" → milliseconds; 0 for nothing. */
|
|
230
|
+
function parseSince(value) {
|
|
231
|
+
if (!value) return 0;
|
|
232
|
+
const match = /^(\d+)\s*(m|h|d)$/.exec(String(value).trim());
|
|
233
|
+
if (!match) throw new ExitError(1, `--since 的格式是 30m、24h 或 7d(收到 ${value})`);
|
|
234
|
+
return Number(match[1]) * { m: 60_000, h: 3_600_000, d: 86_400_000 }[match[2]];
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function parseCount(value, fallback) {
|
|
238
|
+
if (value === undefined) return fallback;
|
|
239
|
+
const count = Number(value);
|
|
240
|
+
if (!Number.isInteger(count) || count < 1 || count > 10_000) throw new ExitError(1, `-n 需要 1–10000 之间的整数(收到 ${value})`);
|
|
241
|
+
return count;
|
|
242
|
+
}
|
|
243
|
+
|
|
178
244
|
/**
|
|
179
245
|
* First run after an older layout (0.0.1 kept the config under ~/.config and
|
|
180
246
|
* ran jobs in /var/tmp; before 0.0.1-alpha-5 everything was named
|
|
@@ -350,14 +416,14 @@ function systemInfo(ctx) {
|
|
|
350
416
|
}
|
|
351
417
|
|
|
352
418
|
/** After /connect: what the machine is called there, and whether its owner confirmed it. */
|
|
353
|
-
function sayRegistered(ctx, reply) {
|
|
354
|
-
|
|
419
|
+
function sayRegistered(ctx, reply, out = say) {
|
|
420
|
+
out(`✓ 已连接 ${ctx.server},本机登记为「${reply.name}」(令牌:${reply.tokenName})${reply.role === 'server' ? ',服务器执行机器' : ''}`);
|
|
355
421
|
if (!reply.created && ctx.config.machineName && reply.name !== ctx.config.machineName) {
|
|
356
|
-
|
|
422
|
+
out(` 这台机器之前已登记为「${reply.name}」,名称请在网页上修改`);
|
|
357
423
|
}
|
|
358
424
|
if (reply.confirmed === false) {
|
|
359
|
-
|
|
360
|
-
|
|
425
|
+
out('⚠ 这台机器还没有确认,确认后才会收到任务:请在网页「在线 Agent → 模型配置 → 执行机器」里核对主机名和 IP 后点「确认」');
|
|
426
|
+
out(` ${ctx.server}/features#agent/config`);
|
|
361
427
|
}
|
|
362
428
|
}
|
|
363
429
|
|
|
@@ -383,13 +449,23 @@ function networkReason(error) {
|
|
|
383
449
|
return error?.cause?.code || error?.cause?.message || error?.message || String(error);
|
|
384
450
|
}
|
|
385
451
|
|
|
386
|
-
/** doctor + remembering a claude found outside PATH. */
|
|
387
|
-
async function doctorFor(ctx) {
|
|
452
|
+
/** doctor + remembering a claude found outside PATH. `probe: false`: no sandbox check (seconds faster). */
|
|
453
|
+
async function doctorFor(ctx, { probe = true } = {}) {
|
|
454
|
+
// From the file: `setup` may have installed claude since this program started.
|
|
455
|
+
let configured = ctx.config.claudePath || '';
|
|
456
|
+
try {
|
|
457
|
+
configured = loadConfig(ctx.paths).claudePath || '';
|
|
458
|
+
ctx.config.claudePath = configured;
|
|
459
|
+
} catch {
|
|
460
|
+
// An unreadable config: what this program read at start.
|
|
461
|
+
}
|
|
388
462
|
const result = await runDoctor({
|
|
389
|
-
configuredClaude:
|
|
463
|
+
configuredClaude: configured,
|
|
464
|
+
managedDir: ctx.paths.claudeDir,
|
|
390
465
|
workRoot: ctx.workRoot,
|
|
391
466
|
realHome: ctx.realHome,
|
|
392
467
|
workAgent: ctx.workAgent,
|
|
468
|
+
probe,
|
|
393
469
|
});
|
|
394
470
|
const remembered = result.claude.viaNpmPrefix || result.claude.path === ctx.config.claudePath ? result.claude.path : '';
|
|
395
471
|
if ((ctx.config.claudePath || '') !== remembered) {
|
|
@@ -402,6 +478,20 @@ async function doctorFor(ctx) {
|
|
|
402
478
|
return result;
|
|
403
479
|
}
|
|
404
480
|
|
|
481
|
+
/**
|
|
482
|
+
* What a start reports before the sandbox check has run: everything quick,
|
|
483
|
+
* and the sandbox verdict of the last run when claude has not changed since.
|
|
484
|
+
* The real check follows in the background; jobs wait for it.
|
|
485
|
+
*/
|
|
486
|
+
async function quickChecks(ctx) {
|
|
487
|
+
const result = await doctorFor(ctx, { probe: false });
|
|
488
|
+
const last = readStatus(ctx.paths.statusFile)?.capabilities;
|
|
489
|
+
if (last?.sandbox && last.claude && last.claude === result.capabilities.claude && last.os === result.capabilities.os) {
|
|
490
|
+
result.capabilities.sandbox = { ok: last.sandbox.ok === true, reason: last.sandbox.reason || '' };
|
|
491
|
+
}
|
|
492
|
+
return result;
|
|
493
|
+
}
|
|
494
|
+
|
|
405
495
|
function connectFailure(error, server) {
|
|
406
496
|
if (error instanceof ApiError) {
|
|
407
497
|
if (error.status === 403) return new ExitError(ATTENTION, error.message);
|
|
@@ -414,11 +504,13 @@ function connectFailure(error, server) {
|
|
|
414
504
|
* Asks for the token (or reads it from stdin), checks it with POST /connect
|
|
415
505
|
* and saves it only then. Up to 3 tries in a terminal.
|
|
416
506
|
*/
|
|
417
|
-
async function obtainToken(ctx, { fromStdin = false, capabilities }) {
|
|
507
|
+
async function obtainToken(ctx, { fromStdin = false, given = null, capabilities }) {
|
|
508
|
+
// `given`: from a file (setup --unattended --token-file) — checked like one from stdin.
|
|
509
|
+
if (given !== null) fromStdin = true;
|
|
418
510
|
if (!fromStdin && !isInteractive()) throw new ExitError(ATTENTION, '还没有接入令牌:请先在终端运行 work-agent-runner login');
|
|
419
511
|
if (!fromStdin) say('请在「在线 Agent → 模型配置 → 接入令牌」复制令牌并粘贴(输入不显示):');
|
|
420
512
|
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
|
421
|
-
const token = fromStdin ? await readStdin() : await readHidden('令牌:');
|
|
513
|
+
const token = given !== null ? given : fromStdin ? await readStdin() : await readHidden('令牌:');
|
|
422
514
|
if (!TOKEN_PATTERN.test(token)) {
|
|
423
515
|
if (fromStdin) throw new ExitError(ATTENTION, '令牌格式不正确(应为 gcm_ 开头的 47 个字符)');
|
|
424
516
|
say('令牌格式不正确(应为 gcm_ 开头的 47 个字符),请重新粘贴');
|
|
@@ -449,10 +541,14 @@ async function obtainToken(ctx, { fromStdin = false, capabilities }) {
|
|
|
449
541
|
throw new ExitError(ATTENTION, '令牌 3 次都不正确,已退出');
|
|
450
542
|
}
|
|
451
543
|
|
|
452
|
-
/**
|
|
453
|
-
|
|
544
|
+
/**
|
|
545
|
+
* POST /connect with the saved token; waits out network trouble (services must
|
|
546
|
+
* not give up). `signal` ends the wait (a stop while the network is down).
|
|
547
|
+
*/
|
|
548
|
+
async function connectSaved(ctx, client, capabilities, { signal = null, onRetry = () => {} } = {}) {
|
|
454
549
|
let delay = 1000;
|
|
455
550
|
for (;;) {
|
|
551
|
+
if (signal?.aborted) throw new ExitError(0, '');
|
|
456
552
|
try {
|
|
457
553
|
return await connect(ctx, client, capabilities);
|
|
458
554
|
} catch (error) {
|
|
@@ -465,8 +561,16 @@ async function connectSaved(ctx, client, capabilities) {
|
|
|
465
561
|
throw new ExitError(fatal.code, fatal.message);
|
|
466
562
|
}
|
|
467
563
|
if (error instanceof ApiError && error.status !== 429 && error.status < 500) throw connectFailure(error, ctx.server);
|
|
468
|
-
|
|
469
|
-
|
|
564
|
+
const reason = error instanceof ApiError ? error.message : networkReason(error);
|
|
565
|
+
onRetry(reason);
|
|
566
|
+
log.warn(`无法连接 ${ctx.server}(${reason}),${Math.round(delay / 1000)} 秒后重试`);
|
|
567
|
+
await new Promise((resolve) => {
|
|
568
|
+
const timer = setTimeout(resolve, error?.retryAfterMs || delay);
|
|
569
|
+
signal?.addEventListener('abort', () => {
|
|
570
|
+
clearTimeout(timer);
|
|
571
|
+
resolve();
|
|
572
|
+
}, { once: true });
|
|
573
|
+
});
|
|
470
574
|
delay = Math.min(60_000, delay * 2);
|
|
471
575
|
}
|
|
472
576
|
}
|
|
@@ -476,23 +580,6 @@ function toolLabel(name) {
|
|
|
476
580
|
return name === 'bwrap' ? 'bubblewrap' : name;
|
|
477
581
|
}
|
|
478
582
|
|
|
479
|
-
/**
|
|
480
|
-
* Updates every repository in the knowledge pool (in this process: jobs that
|
|
481
|
-
* arrive meanwhile wait for it). Skipped while another process is downloading
|
|
482
|
-
* or updating it. Never fatal.
|
|
483
|
-
*/
|
|
484
|
-
async function updatePool(ctx) {
|
|
485
|
-
if (!ctx.workAgent.mountablePool()) return;
|
|
486
|
-
const busy = poolBusyInfo(ctx.paths);
|
|
487
|
-
if (busy) {
|
|
488
|
-
log.info(`知识仓正由另一个进程(pid ${busy.pid})${busy.kind === 'init' ? '下载' : '更新'},这次不更新`);
|
|
489
|
-
return;
|
|
490
|
-
}
|
|
491
|
-
await ctx.workAgent
|
|
492
|
-
.updatePool({ say: (line) => log.info(line) })
|
|
493
|
-
.catch((error) => log.warn(`知识仓更新失败:${error.message}`));
|
|
494
|
-
}
|
|
495
|
-
|
|
496
583
|
/** Brings the clone up to date. Never fatal: the website shows the reason instead. */
|
|
497
584
|
async function refreshWorkAgent(ctx, { say: out = say } = {}) {
|
|
498
585
|
try {
|
|
@@ -511,16 +598,57 @@ function poolAge(fetchedAt) {
|
|
|
511
598
|
}
|
|
512
599
|
|
|
513
600
|
/** The Skill source and the knowledge pool, in two lines. */
|
|
514
|
-
function printWorkAgent(state) {
|
|
515
|
-
if (state.ok)
|
|
516
|
-
else
|
|
601
|
+
function printWorkAgent(state, out = say) {
|
|
602
|
+
if (state.ok) out(`✓ work-agent ${state.commit.slice(0, 7)}${state.committedAt ? `(${state.committedAt.slice(0, 10)})` : ''}`);
|
|
603
|
+
else out(`✗ work-agent 仓库不可用:${state.reason}`);
|
|
517
604
|
if (state.incomplete?.length) {
|
|
518
|
-
|
|
605
|
+
out(` 知识仓 ${state.incomplete.join('、')} 不完整:请删除后重新运行 work-agent-runner setup`);
|
|
519
606
|
} else if (state.repos) {
|
|
520
607
|
const what = state.ascend ? `${state.repos} 个仓(含 AscendC 两仓)` : `${state.repos} 个仓,缺 AscendC 两仓(代码检视的 AscendC 规范域不检查)`;
|
|
521
|
-
|
|
608
|
+
out(` 知识仓:${what}${poolAge(state.poolFetchedAt)}`);
|
|
522
609
|
} else {
|
|
523
|
-
|
|
610
|
+
out(' 知识仓:未初始化(可选;运行 work-agent-runner setup 下载)');
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* Runs `work` (a terminal's own work-agent.py: a pool update, a download, a
|
|
616
|
+
* cleanup); Ctrl+C or SIGTERM stops work-agent.py with it, which runs in its
|
|
617
|
+
* own process group and would otherwise go on alone. A second one exits at once.
|
|
618
|
+
*/
|
|
619
|
+
async function withStopOnSignal(ctx, work) {
|
|
620
|
+
let interrupted = '';
|
|
621
|
+
const onSignal = (signal) => {
|
|
622
|
+
if (interrupted) process.exit(130);
|
|
623
|
+
interrupted = signal;
|
|
624
|
+
say(`\n收到 ${signal},正在停止 work-agent.py……`);
|
|
625
|
+
ctx.workAgent.stop();
|
|
626
|
+
};
|
|
627
|
+
const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
|
|
628
|
+
for (const signal of signals) process.on(signal, onSignal);
|
|
629
|
+
try {
|
|
630
|
+
return await work();
|
|
631
|
+
} catch (error) {
|
|
632
|
+
if (interrupted) throw new ExitError(128 + (os.constants.signals[interrupted] || 0), '已停止');
|
|
633
|
+
throw error;
|
|
634
|
+
} finally {
|
|
635
|
+
for (const signal of signals) process.off(signal, onSignal);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/** A running instance's answer to `method`, printing its progress lines; null when none answers. */
|
|
640
|
+
async function askInstance(ctx, method, params = {}, { quiet = false } = {}) {
|
|
641
|
+
try {
|
|
642
|
+
return await controlRequest(ctx.paths, method, params, {
|
|
643
|
+
timeoutMs: 0,
|
|
644
|
+
onEvent: (event, data) => {
|
|
645
|
+
if (event === 'log' && !quiet) say(` ${data}`);
|
|
646
|
+
},
|
|
647
|
+
});
|
|
648
|
+
} catch (error) {
|
|
649
|
+
if (error instanceof NotRunningError) return null;
|
|
650
|
+
if (error instanceof ControlError) throw new ExitError(1, error.message);
|
|
651
|
+
throw error;
|
|
524
652
|
}
|
|
525
653
|
}
|
|
526
654
|
|
|
@@ -529,70 +657,27 @@ async function ensureClone(ctx) {
|
|
|
529
657
|
const state = ctx.workAgent.state();
|
|
530
658
|
if (state.ok || state.foreign) return;
|
|
531
659
|
say('重新下载 work-agent 仓库……');
|
|
532
|
-
|
|
660
|
+
const delegated = await askInstance(ctx, 'repo.refresh');
|
|
661
|
+
if (delegated) say(delegated.ok ? `✓ work-agent ${delegated.commit.slice(0, 7)}` : `✗ work-agent 仓库不可用:${delegated.reason}`);
|
|
662
|
+
else printWorkAgent(await refreshWorkAgent(ctx));
|
|
533
663
|
}
|
|
534
664
|
|
|
535
665
|
const REPO_NAME = /^[A-Za-z0-9._-]{1,80}$/;
|
|
536
666
|
|
|
667
|
+
function validRepoName(name) {
|
|
668
|
+
return REPO_NAME.test(name) && !name.startsWith('.');
|
|
669
|
+
}
|
|
670
|
+
|
|
537
671
|
/** `--repos a,b` → names, validated the way work-agent.py validates them. */
|
|
538
672
|
function splitRepos(value) {
|
|
539
673
|
const names = String(value).split(/[,\s]+/).filter(Boolean);
|
|
540
674
|
for (const name of names) {
|
|
541
|
-
if (!
|
|
675
|
+
if (!validRepoName(name)) throw new ExitError(1, `仓名不正确:${name}`);
|
|
542
676
|
}
|
|
543
677
|
if (!names.length) throw new ExitError(1, '--repos 需要至少一个仓名');
|
|
544
678
|
return names;
|
|
545
679
|
}
|
|
546
680
|
|
|
547
|
-
/**
|
|
548
|
-
* Offers the knowledge pool — the repositories of work-agent's own essential
|
|
549
|
-
* list — in a terminal only. Never downloads anything without a yes: `--repos`
|
|
550
|
-
* picks the repositories instead, `--no-repos` skips the question. A download
|
|
551
|
-
* only adds repositories, so a running service keeps taking jobs meanwhile.
|
|
552
|
-
*/
|
|
553
|
-
async function offerPool(ctx, values) {
|
|
554
|
-
if (values['no-repos']) return;
|
|
555
|
-
const wanted = values.repos === undefined ? null : splitRepos(values.repos);
|
|
556
|
-
const { poolDir, workAgentHome } = ctx.paths;
|
|
557
|
-
const pool = ctx.workAgent.poolState();
|
|
558
|
-
if (pool.incomplete.length) {
|
|
559
|
-
say(`知识仓 ${pool.incomplete.join('、')} 不完整:请先删除 ${poolDir} 下这些目录`);
|
|
560
|
-
return;
|
|
561
|
-
}
|
|
562
|
-
if (pool.repos && values.repos === undefined) {
|
|
563
|
-
say(`知识仓已就绪(${poolDir},${pool.repos} 个仓)`);
|
|
564
|
-
return;
|
|
565
|
-
}
|
|
566
|
-
const busy = poolBusyInfo(ctx.paths);
|
|
567
|
-
if (busy) {
|
|
568
|
-
say(`另一个进程(pid ${busy.pid})正在${busy.kind === 'init' ? '下载' : '更新'}知识仓,请等它结束后再运行 work-agent-runner setup`);
|
|
569
|
-
return;
|
|
570
|
-
}
|
|
571
|
-
if (wanted) say(`将下载到 ${poolDir}:${wanted.join('、')}`);
|
|
572
|
-
else {
|
|
573
|
-
say(`知识仓用于「代码检视」查 CANN / AscendC 的权威文档,下载到 ${poolDir}`);
|
|
574
|
-
// The list file only exists once work-agent.py has run init at least once.
|
|
575
|
-
const listed = ctx.workAgent.essentialRepos();
|
|
576
|
-
if (listed.length) say(`要下载的仓(${ctx.workAgent.essentialFile}):${listed.join('、')}`);
|
|
577
|
-
else say(`要下载的是 work-agent 的必要仓清单,首次初始化时会生成 ${ctx.workAgent.essentialFile},之后可以自己编辑再运行 setup`);
|
|
578
|
-
const free = freeBytes(poolDir);
|
|
579
|
-
say(`仓比较多,下载可能要很久;该磁盘当前可用 ${(free / 1073741824).toFixed(1)} GB。不下载也能用,只是相关规范不做检查。`);
|
|
580
|
-
}
|
|
581
|
-
if (!values.yes && !(await askYesNo('是否现在下载?'))) {
|
|
582
|
-
say('已跳过;以后随时可以再运行 work-agent-runner setup');
|
|
583
|
-
return;
|
|
584
|
-
}
|
|
585
|
-
const done = markPoolBusy(ctx.paths, 'init');
|
|
586
|
-
try {
|
|
587
|
-
await ctx.workAgent.initPool({ repos: wanted, say });
|
|
588
|
-
prepareWorkAgentHome(workAgentHome, { poolDir: ctx.workAgent.mountablePool(), link: ctx.paths.workAgentLink });
|
|
589
|
-
} catch (error) {
|
|
590
|
-
say(`下载知识仓失败:${error.message}`);
|
|
591
|
-
} finally {
|
|
592
|
-
done();
|
|
593
|
-
}
|
|
594
|
-
}
|
|
595
|
-
|
|
596
681
|
function neededBy(tool) {
|
|
597
682
|
if (tool === 'bwrap' || tool === 'socat') return '沙箱需要(所有功能)';
|
|
598
683
|
const features = Object.entries(FEATURE_TOOLS).filter(([, tools]) => tools.includes(tool)).map(([feature]) => FEATURE_LABELS[feature]);
|
|
@@ -600,37 +685,37 @@ function neededBy(tool) {
|
|
|
600
685
|
return features.length === Object.keys(FEATURE_TOOLS).length ? '所有功能需要' : `${features.join('、')}需要`;
|
|
601
686
|
}
|
|
602
687
|
|
|
603
|
-
function printDoctor(result) {
|
|
688
|
+
function printDoctor(result, out = say) {
|
|
604
689
|
const ready = [];
|
|
605
690
|
const missing = [];
|
|
606
691
|
for (const [name, info] of Object.entries(result.tools)) {
|
|
607
692
|
if (info.ok) ready.push(`✓ ${toolLabel(name)}${info.version ? ` ${info.version.split('.').slice(0, 2).join('.')}` : ''}`);
|
|
608
693
|
else missing.push(name);
|
|
609
694
|
}
|
|
610
|
-
if (ready.length)
|
|
611
|
-
for (const name of missing)
|
|
612
|
-
if (!result.claude.path)
|
|
695
|
+
if (ready.length) out(` ${ready.join(' ')}`);
|
|
696
|
+
for (const name of missing) out(` ✗ ${toolLabel(name).padEnd(11)} ${neededBy(name)}`);
|
|
697
|
+
if (!result.claude.path) out(` ✗ ${'claude'.padEnd(11)} 所有功能需要`);
|
|
613
698
|
else if (!result.claudeVersion) {
|
|
614
699
|
// There, but `claude --version` does not run (a broken install, a too-old Node behind it…).
|
|
615
|
-
|
|
700
|
+
out(` ✗ ${'claude'.padEnd(11)} 无法运行(${result.claude.path}):请运行 work-agent-runner setup 重新安装`);
|
|
616
701
|
} else {
|
|
617
|
-
|
|
618
|
-
if (result.claude.viaNpmPrefix)
|
|
702
|
+
out(` ✓ claude ${result.claudeVersion}`);
|
|
703
|
+
if (result.claude.viaNpmPrefix) out(` 提示:claude 在 ${path.dirname(result.claude.path)},建议把这个目录加入 PATH`);
|
|
619
704
|
}
|
|
620
705
|
const { sandbox } = result.capabilities;
|
|
621
|
-
if (sandbox.ok)
|
|
622
|
-
else
|
|
706
|
+
if (sandbox.ok) out('✓ 沙箱可用');
|
|
707
|
+
else out(`✗ 沙箱不可用:${sandbox.reason}(说明:${SANDBOX_DOCS})`);
|
|
623
708
|
}
|
|
624
709
|
|
|
625
|
-
function printFeatures(reply) {
|
|
710
|
+
function printFeatures(reply, out = say) {
|
|
626
711
|
if (!reply?.features) return;
|
|
627
712
|
const entries = Object.entries(reply.features);
|
|
628
713
|
const ok = entries.filter(([, verdict]) => verdict.ok).map(([feature]) => FEATURE_LABELS[feature] || feature);
|
|
629
|
-
|
|
714
|
+
out(ok.length ? `可运行:${ok.join('、')}` : '暂时没有可运行的功能');
|
|
630
715
|
for (const [feature, verdict] of entries) {
|
|
631
|
-
if (!verdict.ok)
|
|
716
|
+
if (!verdict.ok) out(`不可运行:${FEATURE_LABELS[feature] || feature}(${verdict.reason})`);
|
|
632
717
|
}
|
|
633
|
-
if (reply.outdated)
|
|
718
|
+
if (reply.outdated) out(`程序版本过低,请运行 ${UPDATE_COMMAND}`);
|
|
634
719
|
}
|
|
635
720
|
|
|
636
721
|
function setupPlan(result, reply, { poolWanted = false } = {}) {
|
|
@@ -653,16 +738,115 @@ function setupPlan(result, reply, { poolWanted = false } = {}) {
|
|
|
653
738
|
sudo: which('sudo'),
|
|
654
739
|
npm,
|
|
655
740
|
npmWritable,
|
|
741
|
+
// Installed by claudeStep() instead, where this program has a platform package.
|
|
742
|
+
managedClaude: Boolean(claudePlatform()),
|
|
656
743
|
});
|
|
657
744
|
}
|
|
658
745
|
|
|
746
|
+
function compareVersions(a, b) {
|
|
747
|
+
const parse = (value) => (/^(\d+)\.(\d+)\.(\d+)/.exec(String(value)) || [0, 0, 0, 0]).slice(1, 4).map(Number);
|
|
748
|
+
const [x, y] = [parse(a), parse(b)];
|
|
749
|
+
for (let index = 0; index < 3; index += 1) if (x[index] !== y[index]) return x[index] < y[index] ? -1 : 1;
|
|
750
|
+
return 0;
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/**
|
|
754
|
+
* Where Claude Code is downloaded from: WORK_AGENT_RUNNER_REGISTRY (tests;
|
|
755
|
+
* WORK_AGENT_RUNNER_OFFICIAL_REGISTRY stands for npmjs.org then), the
|
|
756
|
+
* config's mirrors.npmRegistry, else npmjs.org then npmmirror.com. A mirror's
|
|
757
|
+
* checksums are compared with the official registry's.
|
|
758
|
+
*/
|
|
759
|
+
function claudeSources(ctx) {
|
|
760
|
+
const env = process.env.WORK_AGENT_RUNNER_REGISTRY;
|
|
761
|
+
if (env) return { registries: [env.replace(/\/+$/, '')], officialRegistry: (process.env.WORK_AGENT_RUNNER_OFFICIAL_REGISTRY || env).replace(/\/+$/, '') };
|
|
762
|
+
const mirror = ctx.config.mirrors?.npmRegistry;
|
|
763
|
+
if (mirror) return { registries: [mirror], officialRegistry: OFFICIAL_REGISTRY };
|
|
764
|
+
return { registries: [OFFICIAL_REGISTRY, MIRROR_REGISTRY], officialRegistry: OFFICIAL_REGISTRY };
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/** Download progress on one terminal line (every 5 %). */
|
|
768
|
+
function progressLine() {
|
|
769
|
+
let shown = -1;
|
|
770
|
+
return (received, total) => {
|
|
771
|
+
if (!total || !process.stdout.isTTY) return;
|
|
772
|
+
const percent = Math.floor((received / total) * 20) * 5;
|
|
773
|
+
if (percent === shown) return;
|
|
774
|
+
shown = percent;
|
|
775
|
+
process.stdout.write(`\r ${percent}%(${Math.round(received / 1048576)} / ${Math.round(total / 1048576)} MB)${percent === 100 ? '\n' : ''}`);
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/**
|
|
780
|
+
* Claude Code installed by this program (lib/claude-install.mjs) when claude
|
|
781
|
+
* is missing, older than the website asks, or `--claude-version` names one.
|
|
782
|
+
* Shows Anthropic's terms and asks first (`yes` skips the question).
|
|
783
|
+
* Resolves 'installed' | 'skipped' | 'failed' | 'not-needed'.
|
|
784
|
+
*/
|
|
785
|
+
async function claudeStep(ctx, values, { result, minVersion = '', ask = (question) => askYesNo(question) }) {
|
|
786
|
+
const wanted = values['claude-version'] || '';
|
|
787
|
+
const current = result.claudeVersion;
|
|
788
|
+
if (!wanted && current && !(minVersion && compareVersions(current, minVersion) < 0)) return 'not-needed';
|
|
789
|
+
const platformKey = claudePlatform();
|
|
790
|
+
if (!platformKey) {
|
|
791
|
+
say(`这台机器(${process.platform}/${process.arch})没有 Claude Code 的平台包,请自行安装:npm install -g @anthropic-ai/claude-code`);
|
|
792
|
+
return 'failed';
|
|
793
|
+
}
|
|
794
|
+
const { registries, officialRegistry } = claudeSources(ctx);
|
|
795
|
+
let version;
|
|
796
|
+
try {
|
|
797
|
+
version = await resolveClaudeVersion(wanted, { registry: registries[0] });
|
|
798
|
+
} catch (error) {
|
|
799
|
+
say(`✗ 无法确定要安装的 Claude Code 版本:${error.message}`);
|
|
800
|
+
return 'failed';
|
|
801
|
+
}
|
|
802
|
+
if (current === version && result.claude.path && isInside(result.claude.path, ctx.paths.claudeDir)) {
|
|
803
|
+
say(`Claude Code ${version} 已经装好:${result.claude.path}`);
|
|
804
|
+
return 'not-needed';
|
|
805
|
+
}
|
|
806
|
+
const why = !current ? '没有找到 claude' : wanted ? `按 --claude-version ${wanted}` : `本机的 ${current} 低于网站要求的 ${minVersion}`;
|
|
807
|
+
say(`Claude Code:${why},将安装 ${version}${version === VERIFIED_CLAUDE_VERSION ? '(本程序测试过的版本)' : '(不是本程序测试过的版本)'}到 ${ctx.paths.claudeDir}`);
|
|
808
|
+
say(` Claude Code 是 Anthropic 的软件,使用须遵守 Anthropic 的条款:${CLAUDE_TERMS}(包:${CLAUDE_PACKAGE_PAGE})`);
|
|
809
|
+
if (!values.yes && !(await ask('是否下载并安装?'))) {
|
|
810
|
+
say('已跳过;也可以自己安装:npm install -g @anthropic-ai/claude-code');
|
|
811
|
+
return 'skipped';
|
|
812
|
+
}
|
|
813
|
+
try {
|
|
814
|
+
const installed = await installClaude({
|
|
815
|
+
claudeDir: ctx.paths.claudeDir,
|
|
816
|
+
version,
|
|
817
|
+
platformKey,
|
|
818
|
+
registries,
|
|
819
|
+
officialRegistry,
|
|
820
|
+
keep: ctx.config.claudePath || '',
|
|
821
|
+
say: (line) => say(` ${line}`),
|
|
822
|
+
onProgress: progressLine(),
|
|
823
|
+
});
|
|
824
|
+
saveField(ctx, 'claudePath', installed.path);
|
|
825
|
+
say(`✓ Claude Code ${version} 已安装:${installed.path}`);
|
|
826
|
+
return 'installed';
|
|
827
|
+
} catch (error) {
|
|
828
|
+
say(`✗ 安装 Claude Code 失败:${error.message}(${error.code || 'E1302'})`);
|
|
829
|
+
say(' 也可以自己安装:npm install -g @anthropic-ai/claude-code');
|
|
830
|
+
return 'failed';
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
|
|
659
834
|
/** The pid of a running instance of this program home other than this process, or 0. */
|
|
660
835
|
function runningInstance(ctx) {
|
|
661
836
|
const holder = lockHolder(ctx.paths.lockFile);
|
|
662
837
|
return holder !== process.pid && isRunnerAlive(holder) ? holder : 0;
|
|
663
838
|
}
|
|
664
839
|
|
|
665
|
-
// ----
|
|
840
|
+
// ---- The instance ------------------------------------------------------------
|
|
841
|
+
|
|
842
|
+
/** The newest failure with an error code among `records` (oldest first): { code, at }, or null. */
|
|
843
|
+
function lastErrorOf(records) {
|
|
844
|
+
for (let index = records.length - 1; index >= 0; index -= 1) {
|
|
845
|
+
const item = records[index];
|
|
846
|
+
if (item.result !== 'ok' && item.result !== 'cancelled' && item.error?.code) return { code: item.error.code, at: item.at?.done || '' };
|
|
847
|
+
}
|
|
848
|
+
return null;
|
|
849
|
+
}
|
|
666
850
|
|
|
667
851
|
async function start(values) {
|
|
668
852
|
checkSystem();
|
|
@@ -676,6 +860,7 @@ async function start(values) {
|
|
|
676
860
|
}
|
|
677
861
|
// Nothing is written before the lock: another instance may be running.
|
|
678
862
|
const ctx = loadContext(values, { workRoot: false, persist: false, instance: true });
|
|
863
|
+
let startService = false;
|
|
679
864
|
let lock;
|
|
680
865
|
try {
|
|
681
866
|
lock = acquireLock(ctx.paths.lockFile);
|
|
@@ -686,6 +871,8 @@ async function start(values) {
|
|
|
686
871
|
try {
|
|
687
872
|
prepareRunDirs(ctx);
|
|
688
873
|
applyPending(ctx);
|
|
874
|
+
// The instance's log also goes to logs/runner.log (`work-agent-runner logs`).
|
|
875
|
+
log.setFile(ctx.paths.logFile);
|
|
689
876
|
say(`GitCode Agent 执行机器 ${VERSION}`);
|
|
690
877
|
if (legacyServiceInstalled()) log.warn(LEGACY_SERVICE_HINT);
|
|
691
878
|
// Whatever a previous run left behind (run directories r??????, probe
|
|
@@ -701,57 +888,83 @@ async function start(values) {
|
|
|
701
888
|
if (!ctx.config.token && !interactive) {
|
|
702
889
|
throw new ExitError(ATTENTION, '还没有接入令牌:请先在终端运行 work-agent-runner login');
|
|
703
890
|
}
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
await updatePool(ctx);
|
|
711
|
-
clearPoolUpdateRequest(ctx.paths); // just done
|
|
712
|
-
say('检查依赖和沙箱……');
|
|
713
|
-
let result = await doctorFor(ctx);
|
|
714
|
-
let client;
|
|
715
|
-
let reply;
|
|
716
|
-
if (!ctx.config.token) {
|
|
717
|
-
({ client, reply } = await obtainToken(ctx, { capabilities: result.capabilities }));
|
|
891
|
+
if (!ctx.config.token || (!ctx.config.setupDone && interactive)) {
|
|
892
|
+
// A person is at the terminal for the first run: the setup steps, with
|
|
893
|
+
// the answers they need.
|
|
894
|
+
const outcome = await firstRun(ctx, values);
|
|
895
|
+
if (outcome !== 'service') return outcome;
|
|
896
|
+
startService = true;
|
|
718
897
|
} else {
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
const firstRun = !ctx.config.setupDone && interactive;
|
|
725
|
-
if (firstRun) {
|
|
726
|
-
const outcome = await runSetup({
|
|
727
|
-
plan: setupPlan(result, reply, { poolWanted: !values['no-repos'] }),
|
|
728
|
-
interactive: true,
|
|
729
|
-
confirm: (question) => askYesNo(question),
|
|
730
|
-
say,
|
|
731
|
-
});
|
|
732
|
-
// Asked once: missing items stay visible in status and on the website.
|
|
733
|
-
saveField(ctx, 'setupDone', true);
|
|
734
|
-
if (outcome.ran) {
|
|
735
|
-
say('重新检查……');
|
|
736
|
-
result = await doctorFor(ctx);
|
|
737
|
-
printDoctor(result);
|
|
738
|
-
}
|
|
739
|
-
// The first clone may have failed for want of git, which setup just installed.
|
|
740
|
-
await ensureClone(ctx);
|
|
741
|
-
// The same question `setup` asks, so a first run settles everything.
|
|
742
|
-
await offerPool(ctx, values);
|
|
743
|
-
result = await doctorFor(ctx);
|
|
744
|
-
reply = await connectSaved(ctx, client, result.capabilities);
|
|
898
|
+
// Known machine: online within seconds, the slow checks (sandbox, clone)
|
|
899
|
+
// follow in the background — jobs that arrive meanwhile wait for them.
|
|
900
|
+
say('检查依赖……');
|
|
901
|
+
const result = await quickChecks(ctx);
|
|
902
|
+
return await serve(ctx, { client: clientFor(ctx), initial: result, checksPending: true });
|
|
745
903
|
}
|
|
746
|
-
printFeatures(reply);
|
|
747
|
-
say('等待任务……(Ctrl+C 退出;后台运行:work-agent-runner service install)');
|
|
748
|
-
return await serve(ctx, client, result, reply);
|
|
749
904
|
} finally {
|
|
750
905
|
lock.release();
|
|
751
906
|
}
|
|
907
|
+
// The service the first run installed, now that this process let go of the lock.
|
|
908
|
+
try {
|
|
909
|
+
controlService('start', { say });
|
|
910
|
+
} catch (error) {
|
|
911
|
+
throw new ExitError(1, `${error.message};可以运行 work-agent-runner service start 重试`);
|
|
912
|
+
}
|
|
913
|
+
say('已转为后台服务运行。查看状态:work-agent-runner status');
|
|
914
|
+
return 0;
|
|
752
915
|
}
|
|
753
916
|
|
|
754
|
-
|
|
917
|
+
/**
|
|
918
|
+
* A person is at the terminal for the first run: the setup steps, then (unless
|
|
919
|
+
* they put it in the background as a service) this machine goes online here.
|
|
920
|
+
* Resolves 'service' when the service is to be started once this process has
|
|
921
|
+
* let go of the instance lock.
|
|
922
|
+
*/
|
|
923
|
+
async function firstRun(ctx, values) {
|
|
924
|
+
say('首次运行:逐项完成设置(以后随时可以再运行 work-agent-runner setup)');
|
|
925
|
+
const flow = setupFlow(ctx, values, { firstRun: true });
|
|
926
|
+
const finished = await runSetupSteps(ctx, flow);
|
|
927
|
+
// Asked once: what is still missing shows in check, status and on the website.
|
|
928
|
+
saveField(ctx, 'setupDone', true);
|
|
929
|
+
if (flow.log.file) say(`安装日志:${flow.log.file}`);
|
|
930
|
+
if (!ctx.config.token) throw new ExitError(ATTENTION, '还没有接入令牌:请运行 work-agent-runner login');
|
|
931
|
+
if (!finished) throw new ExitError(0, '已退出设置;准备好后运行 work-agent-runner setup 继续');
|
|
932
|
+
if (flow.serviceInstalled) return 'service';
|
|
933
|
+
return serve(ctx, { client: flow.client || clientFor(ctx), initial: flow.result?.capabilities?.sandbox ? flow.result : await doctorFor(ctx) });
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/**
|
|
937
|
+
* The running instance: status and history (lib/state.mjs), the control
|
|
938
|
+
* interface, maintenance, jobs and the connection, until a signal or a fatal
|
|
939
|
+
* answer from the website. `reply`: the /connect answer when the caller
|
|
940
|
+
* connected already; else this connects (and keeps trying). `checksPending`:
|
|
941
|
+
* the clone and the sandbox check still have to run (in the background).
|
|
942
|
+
*/
|
|
943
|
+
async function serve(ctx, { client, initial, reply = null, checksPending = false }) {
|
|
944
|
+
const startedAt = new Date().toISOString();
|
|
945
|
+
const settings = () => effectiveSettings(ctx.config);
|
|
946
|
+
const state = new StateStore({ statusFile: ctx.paths.statusFile, historyFile: ctx.paths.historyFile });
|
|
947
|
+
// How long a job may wait here before it starts: the website's backstop allows for it.
|
|
948
|
+
const withLimits = (caps) => ({ ...caps, jobWaitMaxMs: settings().limits.jobWaitMaxMinutes * 60_000 });
|
|
949
|
+
let capabilities = withLimits(initial.capabilities);
|
|
950
|
+
let role = reply?.role === 'server' ? 'server' : 'user';
|
|
951
|
+
let confirmed = reply ? reply.confirmed !== false : true;
|
|
952
|
+
let outdated = Boolean(reply?.outdated);
|
|
953
|
+
let registeredName = reply?.name || '';
|
|
954
|
+
let ready = !checksPending;
|
|
955
|
+
// `upgrade` drains: no new jobs, the running ones finish.
|
|
956
|
+
let draining = false;
|
|
957
|
+
let controlSocket = '';
|
|
958
|
+
let degraded = [];
|
|
959
|
+
const connection = { server: ctx.server, connected: false, since: '', lastHeartbeatAt: '', lastError: '' };
|
|
960
|
+
// The jobs of the last 24 hours, for status (oldest first).
|
|
961
|
+
let recent = readHistory(ctx.paths.historyFile, { since: Date.now() - 86_400_000, limit: 1000 }).reverse();
|
|
962
|
+
const lastDay = () => {
|
|
963
|
+
const cutoff = Date.now() - 86_400_000;
|
|
964
|
+
recent = recent.filter((record) => Date.parse(record.at?.done || '') >= cutoff);
|
|
965
|
+
return recent;
|
|
966
|
+
};
|
|
967
|
+
|
|
755
968
|
const controller = new AbortController();
|
|
756
969
|
let fatal = null;
|
|
757
970
|
const onFatal = (error) => {
|
|
@@ -761,7 +974,87 @@ async function serve(ctx, client, initial, reply) {
|
|
|
761
974
|
controller.abort();
|
|
762
975
|
}
|
|
763
976
|
};
|
|
764
|
-
|
|
977
|
+
|
|
978
|
+
// A server execution machine runs every user's jobs: each gets a
|
|
979
|
+
// WORK_AGENT_HOME of its own, and what it leaves is archived or dropped.
|
|
980
|
+
const runMode = () => {
|
|
981
|
+
if (role === 'server') return { isolation: 'per-run', keep: settings().limits.archiveDays > 0 ? 'archive' : 'none' };
|
|
982
|
+
return settings().isolation === 'per-run' ? { isolation: 'per-run', keep: 'merge' } : { isolation: 'shared', keep: 'none' };
|
|
983
|
+
};
|
|
984
|
+
// Whether this machine takes new jobs and why not — also told to the website
|
|
985
|
+
// with every heartbeat (it pauses dispatch for pool_update / disk_low).
|
|
986
|
+
const takingJobs = () => {
|
|
987
|
+
if (draining) return { accepting: false, reason: 'upgrade' };
|
|
988
|
+
if (!ready) return { accepting: false, reason: 'starting_checks' };
|
|
989
|
+
if (degraded.some((problem) => problem.code === 'E5101')) return { accepting: false, reason: 'clone_missing' };
|
|
990
|
+
// Here (maintenance marks it before the pull starts) or in a terminal.
|
|
991
|
+
if (ctx.workAgent.poolUpdating || maintenance?.pool.running || poolBusyInfo(ctx.paths)?.kind === 'update') {
|
|
992
|
+
return { accepting: false, reason: 'pool_update' };
|
|
993
|
+
}
|
|
994
|
+
const free = freeBytes(path.join(ctx.workRoot, 'runs'));
|
|
995
|
+
if (free && free < settings().limits.minFreeBytes) return { accepting: false, reason: 'disk_low' };
|
|
996
|
+
if (!confirmed) return { accepting: false, reason: 'unconfirmed' };
|
|
997
|
+
if (outdated) return { accepting: false, reason: 'outdated' };
|
|
998
|
+
return { accepting: true, reason: '' };
|
|
999
|
+
};
|
|
1000
|
+
const acceptingState = () => (connection.connected ? { name: 'online', ...takingJobs() } : { name: 'connecting', accepting: false, reason: '' });
|
|
1001
|
+
// A heartbeat at once when that changes, so the website stops (or resumes) sending jobs.
|
|
1002
|
+
let beatNow = () => {};
|
|
1003
|
+
let lastTaking = '';
|
|
1004
|
+
const selfReport = {
|
|
1005
|
+
current: () => ({
|
|
1006
|
+
state: {
|
|
1007
|
+
...takingJobs(),
|
|
1008
|
+
degraded: degraded.map((problem) => problem.code),
|
|
1009
|
+
diskFree: freeBytes(path.join(ctx.workRoot, 'runs')) || 0,
|
|
1010
|
+
},
|
|
1011
|
+
jobs: jobs.snapshot().map((job) => ({ runId: job.runId, phase: job.phase, since: job.phaseSince })),
|
|
1012
|
+
}),
|
|
1013
|
+
};
|
|
1014
|
+
let maintenance = null;
|
|
1015
|
+
let jobs = null;
|
|
1016
|
+
const publish = () => {
|
|
1017
|
+
if (!jobs) return;
|
|
1018
|
+
const taking = JSON.stringify(takingJobs());
|
|
1019
|
+
if (taking !== lastTaking) {
|
|
1020
|
+
lastTaking = taking;
|
|
1021
|
+
beatNow();
|
|
1022
|
+
}
|
|
1023
|
+
const info = systemInfo(ctx);
|
|
1024
|
+
state.set({
|
|
1025
|
+
instance: { pid: process.pid, startedAt, version: VERSION, node: process.versions.node, service: process.env.GC_RUNNER_SERVICE || 'foreground' },
|
|
1026
|
+
state: acceptingState(),
|
|
1027
|
+
connection: { ...connection },
|
|
1028
|
+
machine: { name: registeredName || ctx.config.machineName || os.hostname(), confirmed, role },
|
|
1029
|
+
capabilities,
|
|
1030
|
+
jobs: jobs.snapshot(),
|
|
1031
|
+
maintenance: maintenance ? maintenance.snapshot() : {},
|
|
1032
|
+
paths: { programHome: ctx.paths.baseDir, workRoot: ctx.workRoot, logFile: ctx.paths.logFile, controlSocket },
|
|
1033
|
+
resources: { workRootFree: info.diskAvailable, memAvailable: info.memAvailable, memTotal: info.memLimit || info.memTotal, loadAvg: info.loadAvg },
|
|
1034
|
+
degraded,
|
|
1035
|
+
last24h: { ...countResults(lastDay()), lastError: lastErrorOf(recent) },
|
|
1036
|
+
});
|
|
1037
|
+
};
|
|
1038
|
+
// What has gone wrong, and the clone / pool as the website should see them
|
|
1039
|
+
// (a daily refresh changes the commit; the next heartbeat reports it).
|
|
1040
|
+
const refreshDegraded = () => {
|
|
1041
|
+
if (maintenance) {
|
|
1042
|
+
degraded = maintenance.degraded();
|
|
1043
|
+
const repo = maintenance.repoState();
|
|
1044
|
+
const workAgent = { commit: repo.commit, committedAt: repo.committedAt, repos: repo.repos, ascend: repo.ascend };
|
|
1045
|
+
if (JSON.stringify(workAgent) !== JSON.stringify(capabilities.workAgent)) capabilities = { ...capabilities, workAgent };
|
|
1046
|
+
}
|
|
1047
|
+
publish();
|
|
1048
|
+
};
|
|
1049
|
+
const recheck = async () => {
|
|
1050
|
+
const fresh = await doctorFor(ctx);
|
|
1051
|
+
capabilities = withLimits(fresh.capabilities);
|
|
1052
|
+
if (fresh.claude.path) jobs.claudePath = fresh.claude.path;
|
|
1053
|
+
refreshDegraded();
|
|
1054
|
+
return fresh;
|
|
1055
|
+
};
|
|
1056
|
+
|
|
1057
|
+
jobs = new JobManager({
|
|
765
1058
|
client,
|
|
766
1059
|
workAgent: ctx.workAgent,
|
|
767
1060
|
workRoot: ctx.workRoot,
|
|
@@ -769,123 +1062,297 @@ async function serve(ctx, client, initial, reply) {
|
|
|
769
1062
|
realHome: ctx.realHome,
|
|
770
1063
|
log,
|
|
771
1064
|
onFatal,
|
|
1065
|
+
jobWaitMs: settings().limits.jobWaitMaxMinutes * 60_000,
|
|
1066
|
+
minFreeBytes: settings().limits.minFreeBytes,
|
|
1067
|
+
controlDirs: controlDirectories(ctx.paths),
|
|
1068
|
+
runMode,
|
|
1069
|
+
// A job starts once the start-up checks are done and no knowledge-pool update runs.
|
|
1070
|
+
gate: async ({ isCancelled, timeoutMs, onWait }) => {
|
|
1071
|
+
const deadline = Date.now() + timeoutMs;
|
|
1072
|
+
if (!ready) {
|
|
1073
|
+
onWait('waiting_starting', '等待启动检查完成后开始');
|
|
1074
|
+
while (!ready && !isCancelled() && Date.now() < deadline) await sleep(500);
|
|
1075
|
+
if (!ready && !isCancelled()) {
|
|
1076
|
+
return { ok: false, code: 'E3201', message: '执行机器的启动检查还没有完成,任务未执行,请稍后重试' };
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
// Sent before the check found otherwise (it reports to the website at once).
|
|
1080
|
+
// (Without claude at all, starting it fails with E1301 instead.)
|
|
1081
|
+
if (!isCancelled() && capabilities.claude && capabilities.sandbox?.ok === false) {
|
|
1082
|
+
return { ok: false, code: 'E4101', message: `执行机器的沙箱不可用(${capabilities.sandbox.reason || '原因未知'}),任务未执行` };
|
|
1083
|
+
}
|
|
1084
|
+
return jobs.poolGate({ isCancelled, timeoutMs: Math.max(1000, deadline - Date.now()), onWait });
|
|
1085
|
+
},
|
|
1086
|
+
onChange: publish,
|
|
1087
|
+
onFinished: (record) => {
|
|
1088
|
+
state.appendHistory(record);
|
|
1089
|
+
recent.push(record);
|
|
1090
|
+
publish();
|
|
1091
|
+
},
|
|
1092
|
+
});
|
|
1093
|
+
maintenance = new Maintenance({
|
|
1094
|
+
workAgent: ctx.workAgent,
|
|
1095
|
+
jobs,
|
|
1096
|
+
log,
|
|
1097
|
+
paths: ctx.paths,
|
|
1098
|
+
workRoot: ctx.workRoot,
|
|
1099
|
+
settings,
|
|
1100
|
+
recheck,
|
|
1101
|
+
onChange: refreshDegraded,
|
|
772
1102
|
});
|
|
773
|
-
let capabilities = initial.capabilities;
|
|
774
|
-
// One maintenance step at a time: a hung pull must not stack up another round.
|
|
775
|
-
let checking = false;
|
|
776
|
-
const exclusive = async (work) => {
|
|
777
|
-
if (checking) return;
|
|
778
|
-
checking = true;
|
|
779
|
-
try {
|
|
780
|
-
await work();
|
|
781
|
-
} catch (error) {
|
|
782
|
-
log.warn(`定期检查失败:${error.message}`);
|
|
783
|
-
} finally {
|
|
784
|
-
checking = false;
|
|
785
|
-
}
|
|
786
|
-
};
|
|
787
|
-
const recheck = async () => {
|
|
788
|
-
const fresh = await doctorFor(ctx);
|
|
789
|
-
capabilities = fresh.capabilities;
|
|
790
|
-
if (fresh.claude.path) jobs.claudePath = fresh.claude.path;
|
|
791
|
-
};
|
|
792
1103
|
|
|
793
|
-
//
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
},
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
doctorTimer.unref();
|
|
830
|
-
// `work-agent-runner update` in a terminal leaves the pool to this program:
|
|
831
|
-
// done as soon as no job runs.
|
|
832
|
-
const requestTimer = setInterval(() => {
|
|
833
|
-
if (!poolUpdateRequested(ctx.paths) || jobs.runningIds().length) return;
|
|
834
|
-
exclusive(async () => {
|
|
835
|
-
clearPoolUpdateRequest(ctx.paths);
|
|
836
|
-
log.info('按终端里 work-agent-runner update 的请求更新知识仓');
|
|
837
|
-
await updatePool(ctx);
|
|
838
|
-
await recheck();
|
|
839
|
-
});
|
|
840
|
-
}, REQUEST_POLL_MS);
|
|
841
|
-
requestTimer.unref();
|
|
842
|
-
// Every day at 08:00 local time: the work-agent clone (the Skill source).
|
|
843
|
-
let repoTimer = null;
|
|
844
|
-
const scheduleRepoUpdate = () => {
|
|
845
|
-
const next = new Date();
|
|
846
|
-
next.setHours(REPO_UPDATE_HOUR, 0, 0, 0);
|
|
847
|
-
if (next.getTime() <= Date.now()) next.setDate(next.getDate() + 1);
|
|
848
|
-
repoTimer = setTimeout(async () => {
|
|
1104
|
+
// The local control interface: what terminal commands ask this instance.
|
|
1105
|
+
const handlers = {
|
|
1106
|
+
ping: () => ({ pid: process.pid, version: VERSION, programHome: ctx.paths.baseDir, service: process.env.GC_RUNNER_SERVICE || 'foreground' }),
|
|
1107
|
+
status: () => {
|
|
1108
|
+
refreshDegraded();
|
|
1109
|
+
state.flush();
|
|
1110
|
+
return state.snapshot();
|
|
1111
|
+
},
|
|
1112
|
+
jobs: (params) => ({
|
|
1113
|
+
running: jobs.snapshot(),
|
|
1114
|
+
history: readHistory(ctx.paths.historyFile, {
|
|
1115
|
+
since: Number.isFinite(params.since) ? params.since : 0,
|
|
1116
|
+
limit: Number.isInteger(params.limit) ? Math.min(10_000, Math.max(1, params.limit)) : 20,
|
|
1117
|
+
failedOnly: params.failedOnly === true,
|
|
1118
|
+
runId: typeof params.runId === 'string' ? params.runId.slice(0, 100) : '',
|
|
1119
|
+
}),
|
|
1120
|
+
}),
|
|
1121
|
+
'job.cancel': (params) => {
|
|
1122
|
+
const matches = jobs.runningIds().filter((id) => matchesRunId(id, params.runId));
|
|
1123
|
+
if (matches.length > 1) throw new ControlError('E9009', `有 ${matches.length} 个运行中的任务都含有「${String(params.runId).slice(0, 40)}」,请给出完整的任务 ID`);
|
|
1124
|
+
if (!matches.length) return { runId: '', cancelled: false };
|
|
1125
|
+
return { runId: matches[0], cancelled: jobs.cancel(matches[0], { by: '本机 work-agent-runner jobs cancel' }) };
|
|
1126
|
+
},
|
|
1127
|
+
'repo.refresh': async () => {
|
|
1128
|
+
const fresh = await maintenance.refreshClone();
|
|
1129
|
+
await maintenance.runChecks().catch(() => {});
|
|
1130
|
+
return { ok: fresh.ok, commit: fresh.commit || '', reason: fresh.reason || '' };
|
|
1131
|
+
},
|
|
1132
|
+
// Now if no job runs, else queued for when none does ({ queued, reason }).
|
|
1133
|
+
'pool.update': (params, { send }) => maintenance.updatePool({ say: (line) => send('log', line) }),
|
|
1134
|
+
'pool.init': async (params, { send }) => {
|
|
1135
|
+
const repos = Array.isArray(params.repos) ? params.repos.map(String) : null;
|
|
1136
|
+
if (repos && (!repos.length || repos.length > 100 || !repos.every(validRepoName))) throw new ControlError('E9007', '仓名不正确');
|
|
1137
|
+
const busy = poolBusyInfo(ctx.paths);
|
|
1138
|
+
if (busy) throw new ControlError('E9008', `进程 ${busy.pid} 正在${busy.kind === 'init' ? '下载' : '更新'}知识仓`);
|
|
1139
|
+
const done = markPoolBusy(ctx.paths, 'init');
|
|
849
1140
|
try {
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
1141
|
+
const after = await ctx.workAgent.initPool({ repos, say: (line) => send('log', line) });
|
|
1142
|
+
prepareWorkAgentHome(ctx.paths.workAgentHome, { poolDir: ctx.workAgent.mountablePool(), link: ctx.paths.workAgentLink });
|
|
1143
|
+
await maintenance.runChecks().catch(() => {});
|
|
1144
|
+
return { repos: after.repos };
|
|
853
1145
|
} finally {
|
|
854
|
-
|
|
855
|
-
|
|
1146
|
+
done();
|
|
1147
|
+
}
|
|
1148
|
+
},
|
|
1149
|
+
// A terminal's doctor / setup: checked here, reported to the website from here (3.11).
|
|
1150
|
+
doctor: async () => {
|
|
1151
|
+
const fresh = await maintenance.runChecks();
|
|
1152
|
+
let answer = null;
|
|
1153
|
+
let note = '';
|
|
1154
|
+
try {
|
|
1155
|
+
answer = await connect(ctx, client, capabilities);
|
|
1156
|
+
registeredName = answer.name || registeredName;
|
|
1157
|
+
confirmed = answer.confirmed !== false;
|
|
1158
|
+
outdated = Boolean(answer.outdated);
|
|
1159
|
+
} catch (error) {
|
|
1160
|
+
if (fatalFor(error)) onFatal(error);
|
|
1161
|
+
note = `没能把结果报给网站(${error instanceof ApiError ? error.message : networkReason(error)}),下次心跳时再报`;
|
|
1162
|
+
}
|
|
1163
|
+
publish();
|
|
1164
|
+
return {
|
|
1165
|
+
capabilities: fresh.capabilities,
|
|
1166
|
+
tools: fresh.tools,
|
|
1167
|
+
claude: fresh.claude,
|
|
1168
|
+
claudeVersion: fresh.claudeVersion,
|
|
1169
|
+
workAgent: ctx.workAgent.state(),
|
|
1170
|
+
features: answer?.features || null,
|
|
1171
|
+
outdated: Boolean(answer?.outdated),
|
|
1172
|
+
confirmed: answer ? answer.confirmed !== false : null,
|
|
1173
|
+
minClaudeVersion: answer?.minClaudeVersion || '',
|
|
1174
|
+
note,
|
|
1175
|
+
};
|
|
1176
|
+
},
|
|
1177
|
+
// `upgrade`: stop taking jobs (the website is told at once), or take them again.
|
|
1178
|
+
drain: (params) => {
|
|
1179
|
+
draining = params.on !== false;
|
|
1180
|
+
log.info(draining ? '准备升级:暂停接新任务,等运行中的任务结束' : '恢复接新任务');
|
|
1181
|
+
publish();
|
|
1182
|
+
return { draining, running: jobs.runningIds().length };
|
|
1183
|
+
},
|
|
1184
|
+
// `uninstall`: stop as on SIGTERM (jobs ended and reported first).
|
|
1185
|
+
stop: () => {
|
|
1186
|
+
log.info('收到本机的停止请求(work-agent-runner uninstall)');
|
|
1187
|
+
setImmediate(() => onSignal('SIGTERM'));
|
|
1188
|
+
return { stopping: true };
|
|
1189
|
+
},
|
|
1190
|
+
// `reload`: what applies without a restart (the next job, the next schedule).
|
|
1191
|
+
'config.reload': () => {
|
|
1192
|
+
const fresh = loadConfig(ctx.paths);
|
|
1193
|
+
const changed = [];
|
|
1194
|
+
for (const key of ['isolation', 'maintenance', 'limits']) {
|
|
1195
|
+
if (JSON.stringify(fresh[key]) === JSON.stringify(ctx.config[key])) continue;
|
|
1196
|
+
changed.push(key);
|
|
1197
|
+
if (fresh[key] === undefined) delete ctx.config[key];
|
|
1198
|
+
else ctx.config[key] = fresh[key];
|
|
856
1199
|
}
|
|
857
|
-
|
|
858
|
-
|
|
1200
|
+
jobs.jobWaitMs = settings().limits.jobWaitMaxMinutes * 60_000;
|
|
1201
|
+
jobs.minFreeBytes = settings().limits.minFreeBytes;
|
|
1202
|
+
capabilities = withLimits(capabilities);
|
|
1203
|
+
if (changed.includes('maintenance')) {
|
|
1204
|
+
maintenance.scheduleRepo();
|
|
1205
|
+
maintenance.schedulePool();
|
|
1206
|
+
}
|
|
1207
|
+
const restartRequired = ['server', 'token', 'clientId', 'workRoot', 'workAgentHome', 'workAgentRepoDir', 'ascendReposDir', 'workAgentRepo'].filter(
|
|
1208
|
+
(key) => JSON.stringify(fresh[key] ?? '') !== JSON.stringify(ctx.config[key] ?? ''),
|
|
1209
|
+
);
|
|
1210
|
+
refreshDegraded();
|
|
1211
|
+
return { changed, restartRequired };
|
|
1212
|
+
},
|
|
859
1213
|
};
|
|
860
|
-
|
|
1214
|
+
let control = null;
|
|
1215
|
+
try {
|
|
1216
|
+
control = await startControlServer({ paths: ctx.paths, handlers, log });
|
|
1217
|
+
controlSocket = control.socket;
|
|
1218
|
+
} catch (error) {
|
|
1219
|
+
// The instance works without it; terminal commands then act themselves.
|
|
1220
|
+
log.warn(`本机管理接口没有启动(${error.message}):status、jobs、update 等命令只能读取记录`);
|
|
1221
|
+
}
|
|
1222
|
+
|
|
861
1223
|
let stopping = false;
|
|
862
1224
|
const onSignal = (signal) => {
|
|
863
|
-
if (stopping)
|
|
1225
|
+
if (stopping) {
|
|
1226
|
+
// A second Ctrl+C: no more waiting.
|
|
1227
|
+
log.warn(`再次收到 ${signal},立即退出`);
|
|
1228
|
+
jobs.killAll();
|
|
1229
|
+
ctx.workAgent.stop();
|
|
1230
|
+
state.flush();
|
|
1231
|
+
process.exit(130);
|
|
1232
|
+
}
|
|
864
1233
|
stopping = true;
|
|
865
1234
|
log.info(`收到 ${signal},正在停止(结束运行中的任务)……`);
|
|
866
1235
|
controller.abort();
|
|
867
1236
|
};
|
|
868
1237
|
process.on('SIGINT', onSignal);
|
|
869
1238
|
process.on('SIGTERM', onSignal);
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
1239
|
+
// SIGHUP: a service's reload (systemctl reload: config.json again, as
|
|
1240
|
+
// `work-agent-runner reload`); in the foreground, the terminal was closed —
|
|
1241
|
+
// stop the same way as SIGTERM (jobs run in process groups of their own and
|
|
1242
|
+
// would go on alone), with nowhere left to print to.
|
|
1243
|
+
process.on('SIGHUP', () => {
|
|
1244
|
+
if (process.env.GC_RUNNER_SERVICE) {
|
|
1245
|
+
try {
|
|
1246
|
+
const { changed, restartRequired } = handlers['config.reload']();
|
|
1247
|
+
log.info(`收到 SIGHUP,已重新读取配置${changed.length ? `:${changed.join('、')} 已生效` : '(可以直接生效的设置没有变化)'}`);
|
|
1248
|
+
if (restartRequired.length) log.warn(`${restartRequired.join('、')} 要重新启动程序才生效`);
|
|
1249
|
+
} catch (error) {
|
|
1250
|
+
log.warn(`重新读取配置失败:${error.message}`);
|
|
1251
|
+
}
|
|
1252
|
+
return;
|
|
1253
|
+
}
|
|
1254
|
+
for (const stream of [process.stdout, process.stderr]) stream.on('error', () => {});
|
|
1255
|
+
onSignal('SIGHUP');
|
|
881
1256
|
});
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
1257
|
+
|
|
1258
|
+
let result = { code: 0, message: '' };
|
|
1259
|
+
try {
|
|
1260
|
+
publish();
|
|
1261
|
+
if (!reply) {
|
|
1262
|
+
reply = await connectSaved(ctx, client, capabilities, {
|
|
1263
|
+
signal: controller.signal,
|
|
1264
|
+
onRetry: (reason) => {
|
|
1265
|
+
connection.lastError = reason;
|
|
1266
|
+
publish();
|
|
1267
|
+
},
|
|
1268
|
+
});
|
|
1269
|
+
sayRegistered(ctx, reply, (line) => log.info(line));
|
|
1270
|
+
// Before the checks every feature reads as unavailable: their result follows.
|
|
1271
|
+
if (checksPending) log.info('正在检查沙箱和 work-agent 仓库,检查完成前收到的任务会等待');
|
|
1272
|
+
else printFeatures(reply, (line) => log.info(line));
|
|
1273
|
+
registeredName = reply.name || registeredName;
|
|
1274
|
+
role = reply.role === 'server' ? 'server' : 'user';
|
|
1275
|
+
confirmed = reply.confirmed !== false;
|
|
1276
|
+
outdated = Boolean(reply.outdated);
|
|
1277
|
+
}
|
|
1278
|
+
maintenance.start();
|
|
1279
|
+
if (checksPending) {
|
|
1280
|
+
// The clone and the sandbox check, while the website already sees this
|
|
1281
|
+
// machine; then the result to the website at once (POST /connect is the
|
|
1282
|
+
// way to apply capabilities now), and its verdict per feature to the log.
|
|
1283
|
+
(async () => {
|
|
1284
|
+
let checked = null;
|
|
1285
|
+
try {
|
|
1286
|
+
await maintenance.refreshClone();
|
|
1287
|
+
checked = await maintenance.runChecks().catch((error) => {
|
|
1288
|
+
log.warn(`启动检查失败:${error.message}`);
|
|
1289
|
+
return null;
|
|
1290
|
+
});
|
|
1291
|
+
} finally {
|
|
1292
|
+
ready = true;
|
|
1293
|
+
publish();
|
|
1294
|
+
}
|
|
1295
|
+
const info = (line) => log.info(line);
|
|
1296
|
+
printWorkAgent(ctx.workAgent.state(), info);
|
|
1297
|
+
if (checked) printDoctor(checked, info);
|
|
1298
|
+
if (controller.signal.aborted) return;
|
|
1299
|
+
try {
|
|
1300
|
+
const fresh = await connect(ctx, client, capabilities);
|
|
1301
|
+
registeredName = fresh.name || registeredName;
|
|
1302
|
+
confirmed = fresh.confirmed !== false;
|
|
1303
|
+
outdated = Boolean(fresh.outdated);
|
|
1304
|
+
printFeatures(fresh, info);
|
|
1305
|
+
} catch (error) {
|
|
1306
|
+
if (fatalFor(error)) onFatal(error);
|
|
1307
|
+
else log.warn(`没能把检查结果报给网站(${error instanceof ApiError ? error.message : networkReason(error)}),下次心跳时再报`);
|
|
1308
|
+
}
|
|
1309
|
+
log.info('启动检查完成');
|
|
1310
|
+
publish();
|
|
1311
|
+
})();
|
|
1312
|
+
} else {
|
|
1313
|
+
refreshDegraded();
|
|
1314
|
+
}
|
|
1315
|
+
say('等待任务……(Ctrl+C 退出;后台运行:work-agent-runner service install;查看状态:work-agent-runner status)');
|
|
1316
|
+
result = await runConnection({
|
|
1317
|
+
client,
|
|
1318
|
+
jobs,
|
|
1319
|
+
log,
|
|
1320
|
+
version: VERSION,
|
|
1321
|
+
connect: () => connect(ctx, client, capabilities),
|
|
1322
|
+
capabilities: { current: () => capabilities },
|
|
1323
|
+
system: { current: () => systemInfo(ctx) },
|
|
1324
|
+
confirmed,
|
|
1325
|
+
heartbeatMs: reply.heartbeatMs,
|
|
1326
|
+
signal: controller.signal,
|
|
1327
|
+
selfReport,
|
|
1328
|
+
bindBeat: (beat) => {
|
|
1329
|
+
beatNow = beat;
|
|
1330
|
+
},
|
|
1331
|
+
// Connected = the control channel is open (jobs only come through it).
|
|
1332
|
+
onStatus: ({ confirmed: nowConfirmed, ...patch }) => {
|
|
1333
|
+
Object.assign(connection, patch);
|
|
1334
|
+
if (typeof nowConfirmed === 'boolean') confirmed = nowConfirmed;
|
|
1335
|
+
publish();
|
|
1336
|
+
},
|
|
1337
|
+
onReply: (fresh) => {
|
|
1338
|
+
if (fresh?.role) role = fresh.role === 'server' ? 'server' : 'user';
|
|
1339
|
+
if (typeof fresh?.name === 'string' && fresh.name) registeredName = fresh.name;
|
|
1340
|
+
if (typeof fresh?.confirmed === 'boolean') confirmed = fresh.confirmed;
|
|
1341
|
+
publish();
|
|
1342
|
+
},
|
|
1343
|
+
});
|
|
1344
|
+
} catch (error) {
|
|
1345
|
+
if (!(error instanceof ExitError) || error.code !== 0) throw error;
|
|
1346
|
+
} finally {
|
|
1347
|
+
maintenance.stop();
|
|
1348
|
+
ctx.workAgent.stop();
|
|
1349
|
+
await jobs.stopAll(5000);
|
|
1350
|
+
connection.connected = false;
|
|
1351
|
+
publish();
|
|
1352
|
+
state.flush();
|
|
1353
|
+
await control?.close();
|
|
1354
|
+
}
|
|
886
1355
|
const outcome = fatal || result;
|
|
887
|
-
ctx.workAgent.stop();
|
|
888
|
-
await jobs.stopAll(5000);
|
|
889
1356
|
if (outcome.clearToken && !clearToken(ctx, ctx.config.token)) {
|
|
890
1357
|
// `login` saved a new token while this one was in use: exit 1 so a service
|
|
891
1358
|
// restarts and connects with it.
|
|
@@ -897,12 +1364,7 @@ async function serve(ctx, client, initial, reply) {
|
|
|
897
1364
|
return outcome.code || 0;
|
|
898
1365
|
}
|
|
899
1366
|
|
|
900
|
-
|
|
901
|
-
function clearTrash(ctx) {
|
|
902
|
-
const trashDir = path.join(ctx.workRoot, 'trash');
|
|
903
|
-
const left = retryTrash(trashDir);
|
|
904
|
-
if (left.length) log.warn(`${trashDir} 里有 ${left.length} 个目录还删不掉(可能是任务改了权限),需要时请手动删除`);
|
|
905
|
-
}
|
|
1367
|
+
// ---- Terminal commands -------------------------------------------------------
|
|
906
1368
|
|
|
907
1369
|
async function login(values) {
|
|
908
1370
|
checkSystem();
|
|
@@ -941,130 +1403,670 @@ function logout(values) {
|
|
|
941
1403
|
return 0;
|
|
942
1404
|
}
|
|
943
1405
|
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
const ctx = loadContext(values);
|
|
950
|
-
say('检查 work-agent 仓库……');
|
|
951
|
-
printWorkAgent(await refreshWorkAgent(ctx));
|
|
952
|
-
say('检查依赖和沙箱……');
|
|
953
|
-
let result = await doctorFor(ctx);
|
|
954
|
-
let client = null;
|
|
955
|
-
let reply = null;
|
|
956
|
-
if (ctx.config.token) {
|
|
957
|
-
client = clientFor(ctx);
|
|
958
|
-
try {
|
|
959
|
-
reply = await connect(ctx, client, result.capabilities);
|
|
960
|
-
} catch (error) {
|
|
961
|
-
say(`无法从网站读取要求(${error.message}),按默认要求检查`);
|
|
962
|
-
client = null;
|
|
963
|
-
}
|
|
964
|
-
}
|
|
965
|
-
printDoctor(result);
|
|
966
|
-
const poolWanted = !values['no-repos'];
|
|
967
|
-
const outcome = await runSetup({
|
|
968
|
-
plan: setupPlan(result, reply, { poolWanted }),
|
|
969
|
-
interactive: true,
|
|
970
|
-
yes: Boolean(values.yes),
|
|
971
|
-
confirm: (question) => askYesNo(question),
|
|
972
|
-
say,
|
|
973
|
-
});
|
|
974
|
-
saveField(ctx, 'setupDone', true);
|
|
975
|
-
if (outcome.ran) {
|
|
976
|
-
say('重新检查……');
|
|
977
|
-
result = await doctorFor(ctx);
|
|
978
|
-
printDoctor(result);
|
|
979
|
-
}
|
|
980
|
-
// A clone that failed for want of git is made now that setup installed it.
|
|
981
|
-
await ensureClone(ctx);
|
|
982
|
-
// After the tools: the pool is searched with rg.
|
|
983
|
-
await offerPool(ctx, values);
|
|
984
|
-
if (client) reply = await connect(ctx, client, (await doctorFor(ctx)).capabilities).catch(() => reply);
|
|
985
|
-
printFeatures(reply);
|
|
986
|
-
return outcome.failed.length ? 1 : 0;
|
|
987
|
-
}
|
|
1406
|
+
// ---- setup, step by step (lib/setup-state.mjs) ------------------------------------
|
|
1407
|
+
|
|
1408
|
+
const stepDone = (detail = '') => ({ status: 'done', detail });
|
|
1409
|
+
const stepSkipped = (detail = '') => ({ status: 'skipped', detail });
|
|
1410
|
+
const stepFailed = (code, message, fix = '') => ({ status: 'failed', detail: message, error: { code, message, fix } });
|
|
988
1411
|
|
|
989
1412
|
/**
|
|
990
|
-
*
|
|
991
|
-
*
|
|
992
|
-
*
|
|
1413
|
+
* One setup run: the options, whether nobody answers questions (`unattended`:
|
|
1414
|
+
* the options decide; output on stderr, a JSON report on stdout), whether it
|
|
1415
|
+
* is a `start`'s first run (`firstRun`), the setup log, and what the steps
|
|
1416
|
+
* learn on the way (instance, client, reply, result).
|
|
993
1417
|
*/
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
const
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
const done = markPoolBusy(ctx.paths, 'update');
|
|
1016
|
-
try {
|
|
1017
|
-
await ctx.workAgent.updatePool({ say });
|
|
1018
|
-
} finally {
|
|
1019
|
-
done();
|
|
1020
|
-
}
|
|
1418
|
+
function setupFlow(ctx, values, { unattended = false, firstRun = false } = {}) {
|
|
1419
|
+
const log = openSetupLog(ctx.paths.logsDir);
|
|
1420
|
+
log.write(`work-agent-runner ${VERSION} setup${unattended ? ' --unattended' : ''}${firstRun ? '(首次运行)' : ''}`);
|
|
1421
|
+
const stream = unattended ? process.stderr : process.stdout;
|
|
1422
|
+
const flow = {
|
|
1423
|
+
values,
|
|
1424
|
+
unattended,
|
|
1425
|
+
firstRun,
|
|
1426
|
+
log,
|
|
1427
|
+
out: (line = '') => {
|
|
1428
|
+
log.write(line);
|
|
1429
|
+
stream.write(`${line}\n`);
|
|
1430
|
+
},
|
|
1431
|
+
beforeAsk: () => {},
|
|
1432
|
+
/** A yes/no question: unattended runs answer `answer`, --yes says yes, else the terminal. */
|
|
1433
|
+
ask: async (question, { answer = true, defaultYes = true } = {}) => {
|
|
1434
|
+
flow.beforeAsk();
|
|
1435
|
+
if (unattended || values.yes) {
|
|
1436
|
+
const given = unattended ? answer : true;
|
|
1437
|
+
log.write(`${question} → ${given ? '是' : '否'}(${unattended ? '无人值守' : '--yes'})`);
|
|
1438
|
+
return given;
|
|
1021
1439
|
}
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1440
|
+
const reply = await askYesNo(` ${question}`, { defaultYes });
|
|
1441
|
+
log.write(`${question} → ${reply ? '是' : '否'}`);
|
|
1442
|
+
return reply;
|
|
1443
|
+
},
|
|
1444
|
+
instance: null,
|
|
1445
|
+
client: null,
|
|
1446
|
+
reply: null,
|
|
1447
|
+
result: null,
|
|
1448
|
+
serviceInstalled: false,
|
|
1449
|
+
state: null,
|
|
1450
|
+
};
|
|
1451
|
+
return flow;
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
/** Whether this run is to download the knowledge pool (and so wants rg). */
|
|
1455
|
+
function poolWanted(flow) {
|
|
1456
|
+
const { values } = flow;
|
|
1457
|
+
if (values['no-repos'] || values.repos === 'none') return false;
|
|
1458
|
+
return !flow.unattended || values.repos !== undefined;
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
/** --repos: essential (work-agent's list) → null, none → [], else the names. */
|
|
1462
|
+
function reposOption(value) {
|
|
1463
|
+
if (value === undefined || value === 'essential') return null;
|
|
1464
|
+
if (value === 'none') return [];
|
|
1465
|
+
return splitRepos(value);
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
/** Linux user services stop at logout without linger: say so, and offer to turn it on (sudo). */
|
|
1469
|
+
async function lingerCheck(flow) {
|
|
1470
|
+
if (process.platform !== 'linux') return;
|
|
1471
|
+
const user = os.userInfo().username;
|
|
1472
|
+
if (lingerEnabled({ user }) !== false) return;
|
|
1473
|
+
say('linger 没有开启:退出登录后后台服务会停止');
|
|
1474
|
+
if (flow.unattended) {
|
|
1475
|
+
say(`需要时请让管理员执行:sudo loginctl enable-linger ${user}`);
|
|
1476
|
+
return;
|
|
1026
1477
|
}
|
|
1027
|
-
if (
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
printFeatures(await connect(ctx, clientFor(ctx), (await doctorFor(ctx)).capabilities));
|
|
1031
|
-
} catch {
|
|
1032
|
-
say('(没能把新状态报给网站,程序下次连接时会报)');
|
|
1033
|
-
}
|
|
1478
|
+
if (!(await flow.ask('是否现在开启 linger(需要 sudo)?'))) {
|
|
1479
|
+
say(`以后可以让管理员执行:sudo loginctl enable-linger ${user}`);
|
|
1480
|
+
return;
|
|
1034
1481
|
}
|
|
1035
|
-
|
|
1482
|
+
const command = process.getuid() === 0 ? ['loginctl', 'enable-linger', user] : [which('sudo') || 'sudo', 'loginctl', 'enable-linger', user];
|
|
1483
|
+
const code = await runCommand(command);
|
|
1484
|
+
say(code === 0 && lingerEnabled({ user }) ? '✓ 已开启 linger' : `没有开启成功(退出码 ${code}):请让管理员执行 sudo loginctl enable-linger ${user}`);
|
|
1036
1485
|
}
|
|
1037
1486
|
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1487
|
+
const SETUP_STEP_RUNNERS = {
|
|
1488
|
+
// What later steps cannot fix: the system, paths, disks, the network.
|
|
1489
|
+
async precheck(ctx) {
|
|
1490
|
+
const report = assessCheck(await baseCheckFacts(ctx));
|
|
1491
|
+
let noted = 0;
|
|
1492
|
+
for (const group of report.groups.filter((item) => ['system', 'runtime', 'network'].includes(item.id))) {
|
|
1493
|
+
for (const entry of group.items) {
|
|
1494
|
+
if (entry.status !== 'fail' && entry.status !== 'warn') continue;
|
|
1495
|
+
noted += 1;
|
|
1496
|
+
say(`${entry.status === 'fail' ? '✗' : '⚠'} ${entry.title}:${entry.detail}${entry.code ? `(${entry.code})` : ''}`);
|
|
1497
|
+
if (entry.fix) say(` 处理:${entry.fix}`);
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
return stepDone(noted ? `完成,${noted} 项要注意` : '完成');
|
|
1501
|
+
},
|
|
1502
|
+
|
|
1503
|
+
async token(ctx, flow) {
|
|
1504
|
+
const { values } = flow;
|
|
1505
|
+
flow.instance = await pingInstance(ctx.paths);
|
|
1506
|
+
const quick = async () => (await doctorFor(ctx, { probe: false })).capabilities;
|
|
1507
|
+
if (!ctx.config.token || values['token-file']) {
|
|
1508
|
+
if (!values['token-file'] && flow.unattended) return stepFailed('E2201', '没有接入令牌', '用 --token-file <文件>(- 为标准输入)提供令牌');
|
|
1509
|
+
let given = null;
|
|
1510
|
+
if (values['token-file']) {
|
|
1511
|
+
try {
|
|
1512
|
+
given = values['token-file'] === '-' ? await readStdin() : fs.readFileSync(values['token-file'], 'utf8').trim();
|
|
1513
|
+
} catch (error) {
|
|
1514
|
+
return stepFailed('E2201', `读不到令牌文件(${error.code || error.message})`, '检查 --token-file 的路径');
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
try {
|
|
1518
|
+
const { client, reply } = await obtainToken(ctx, { given, capabilities: await quick() });
|
|
1519
|
+
flow.client = client;
|
|
1520
|
+
flow.reply = reply;
|
|
1521
|
+
return stepDone(`登记为「${reply.name}」${reply.confirmed === false ? ',网页上还没有确认' : ''}`);
|
|
1522
|
+
} catch (error) {
|
|
1523
|
+
if (error instanceof ExitError) return stepFailed('E2201', error.message, '在网页上新建令牌后重试');
|
|
1524
|
+
throw error;
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
flow.client = clientFor(ctx);
|
|
1528
|
+
try {
|
|
1529
|
+
// With the program running, it reports this machine; this terminal only asks.
|
|
1530
|
+
flow.reply = flow.instance ? await flow.client.request('GET', '/ping') : await connect(ctx, flow.client, await quick());
|
|
1531
|
+
} catch (error) {
|
|
1532
|
+
if (error instanceof ApiError && error.status === 401) return stepFailed('E2201', '令牌无效或已删除', '在网页上新建令牌后运行 work-agent-runner login');
|
|
1533
|
+
if (error instanceof ApiError && error.code === 'machine_blocked') return stepFailed('E2202', '这台机器已在网页上被封禁', '在网页上解除封禁');
|
|
1534
|
+
return stepFailed('E2101', `无法连接 ${ctx.server}(${error instanceof ApiError ? error.message : networkReason(error)})`, '检查网络和代理设置');
|
|
1535
|
+
}
|
|
1536
|
+
const unconfirmed = flow.reply.confirmed === false ? ',网页上还没有确认' : '';
|
|
1537
|
+
if (flow.instance) return stepDone(`令牌有效(程序正在运行,pid ${flow.instance.pid})${unconfirmed}`);
|
|
1538
|
+
return stepDone(`已连接,登记为「${flow.reply.name}」${unconfirmed}`);
|
|
1539
|
+
},
|
|
1540
|
+
|
|
1541
|
+
async deps(ctx, flow) {
|
|
1542
|
+
flow.result = await doctorFor(ctx, { probe: false });
|
|
1543
|
+
const plan = setupPlan(flow.result, flow.reply, { poolWanted: poolWanted(flow) });
|
|
1544
|
+
if (!plan.missing.length && !plan.commands.length && !plan.manual.length) return stepDone('都已就绪');
|
|
1545
|
+
const outcome = await runSetup({
|
|
1546
|
+
plan,
|
|
1547
|
+
interactive: true,
|
|
1548
|
+
yes: flow.unattended || Boolean(flow.values.yes),
|
|
1549
|
+
confirm: (question) => flow.ask(question),
|
|
1550
|
+
say,
|
|
1551
|
+
});
|
|
1552
|
+
if (outcome.failed.length) return stepFailed('E1201', `${outcome.failed.length} 条安装命令失败`, '看上面的输出,修好后重新运行 work-agent-runner setup');
|
|
1553
|
+
if (!outcome.ran) {
|
|
1554
|
+
if (plan.commands.length) return stepSkipped(`没有安装:缺少 ${plan.missing.join('、')}`);
|
|
1555
|
+
if (plan.missing.length) return stepFailed('E1201', `缺少 ${plan.missing.join('、')}`, plan.manual.length ? '请管理员执行上面的命令' : '请手动安装');
|
|
1556
|
+
return stepDone('都已就绪');
|
|
1557
|
+
}
|
|
1558
|
+
flow.result = await doctorFor(ctx, { probe: false });
|
|
1559
|
+
const left = setupPlan(flow.result, flow.reply, { poolWanted: poolWanted(flow) }).missing;
|
|
1560
|
+
return left.length ? stepFailed('E1201', `安装后仍缺少 ${left.join('、')}`, '看上面的输出') : stepDone('已安装');
|
|
1561
|
+
},
|
|
1562
|
+
|
|
1563
|
+
async claude(ctx, flow) {
|
|
1564
|
+
if (!flow.result) flow.result = await doctorFor(ctx, { probe: false });
|
|
1565
|
+
const outcome = await claudeStep(ctx, flow.values, {
|
|
1566
|
+
result: flow.result,
|
|
1567
|
+
minVersion: flow.reply?.minClaudeVersion || '',
|
|
1568
|
+
ask: (question) => flow.ask(question),
|
|
1569
|
+
});
|
|
1570
|
+
if (outcome === 'failed') return stepFailed('E1302', '没有装好 Claude Code', '看上面的原因;也可以自己安装:npm install -g @anthropic-ai/claude-code');
|
|
1571
|
+
if (outcome === 'skipped') return stepSkipped('没有安装');
|
|
1572
|
+
if (outcome === 'installed') flow.result = await doctorFor(ctx, { probe: false });
|
|
1573
|
+
const { claude, claudeVersion: version } = flow.result;
|
|
1574
|
+
if (!version) return stepFailed('E1301', claude.path ? `claude 无法运行(${claude.path})` : '没有可用的 claude', 'work-agent-runner setup');
|
|
1575
|
+
return stepDone(`${version}${isInside(claude.path, ctx.paths.claudeDir) ? '(程序安装)' : ''}`);
|
|
1576
|
+
},
|
|
1577
|
+
|
|
1578
|
+
async prereq() {
|
|
1579
|
+
if (process.platform !== 'linux') return stepDone('macOS 用系统自带的 Seatbelt');
|
|
1580
|
+
const userns = readUserns();
|
|
1581
|
+
if (userns.max === 0 || userns.clone === 0) {
|
|
1582
|
+
return stepFailed('E4101', '系统关闭了非特权 user namespace,沙箱无法运行', '需要管理员打开(会改变本机的安全设置,请先评估)');
|
|
1583
|
+
}
|
|
1584
|
+
if (readApparmor().restrict) return stepDone('AppArmor 限制了非特权 user namespace,下一步的沙箱实测会确认是否受影响');
|
|
1585
|
+
return stepDone('user namespace 可用');
|
|
1586
|
+
},
|
|
1587
|
+
|
|
1588
|
+
async repo(ctx, flow) {
|
|
1589
|
+
if (flow.instance) {
|
|
1590
|
+
const repo = await askInstance(ctx, 'repo.refresh');
|
|
1591
|
+
return repo.ok ? stepDone(`${repo.commit.slice(0, 7)}(由运行中的程序更新)`) : stepFailed('E5101', repo.reason, '检查网络后运行 work-agent-runner update');
|
|
1592
|
+
}
|
|
1593
|
+
const state = await refreshWorkAgent(ctx);
|
|
1594
|
+
if (state.ok) return stepDone(`${state.commit.slice(0, 7)}${state.committedAt ? `(${state.committedAt.slice(0, 10)})` : ''}`);
|
|
1595
|
+
return stepFailed(
|
|
1596
|
+
state.foreign ? 'E1115' : 'E5101',
|
|
1597
|
+
state.reason,
|
|
1598
|
+
state.foreign ? '在 config.json 里把 workAgentRepoDir 改成一个不存在或空的目录' : '检查网络后运行 work-agent-runner update',
|
|
1599
|
+
);
|
|
1600
|
+
},
|
|
1601
|
+
|
|
1602
|
+
async sandbox(ctx, flow) {
|
|
1603
|
+
let sandbox;
|
|
1604
|
+
if (flow.instance) {
|
|
1605
|
+
// Its environment is the one jobs get.
|
|
1606
|
+
sandbox = (await askInstance(ctx, 'doctor', {}, { quiet: true })).capabilities.sandbox;
|
|
1607
|
+
} else {
|
|
1608
|
+
flow.result = await doctorFor(ctx);
|
|
1609
|
+
sandbox = flow.result.capabilities.sandbox;
|
|
1610
|
+
}
|
|
1611
|
+
if (sandbox.ok) return stepDone('沙箱里的命令可以运行');
|
|
1612
|
+
const problem = sandboxProblem({ reason: sandbox.raw || sandbox.reason, platform: process.platform, apparmor: readApparmor(), userns: readUserns() });
|
|
1613
|
+
for (const note of problem.notes) say(note);
|
|
1614
|
+
return stepFailed(problem.code, problem.detail, `${problem.fix}(说明:${SANDBOX_DOCS})`);
|
|
1615
|
+
},
|
|
1616
|
+
|
|
1617
|
+
async pool(ctx, flow) {
|
|
1618
|
+
const { values } = flow;
|
|
1619
|
+
const { poolDir, workAgentHome } = ctx.paths;
|
|
1620
|
+
const pool = ctx.workAgent.poolState();
|
|
1621
|
+
if (pool.incomplete.length) return stepFailed('E5201', `${pool.incomplete.join('、')} 不完整`, `删除 ${poolDir} 下这些目录后重新运行 setup`);
|
|
1622
|
+
const wanted = reposOption(values.repos);
|
|
1623
|
+
if (pool.repos && values.repos === undefined) return stepDone(`${pool.repos} 个仓`);
|
|
1624
|
+
if (values['no-repos'] || (Array.isArray(wanted) && !wanted.length)) return stepSkipped('不下载');
|
|
1625
|
+
if (flow.unattended && values.repos === undefined) return stepSkipped('没有要求下载(--repos essential)');
|
|
1626
|
+
const busy = poolBusyInfo(ctx.paths);
|
|
1627
|
+
if (busy) return stepFailed('E5201', `进程 ${busy.pid} 正在${busy.kind === 'init' ? '下载' : '更新'}知识仓`, '等它结束后重新运行 setup');
|
|
1628
|
+
if (wanted) say(`将下载到 ${poolDir}:${wanted.join('、')}`);
|
|
1629
|
+
else {
|
|
1630
|
+
say(`知识仓用于「代码检视」查 CANN / AscendC 的权威文档、「CANN 知识问答」作答,下载到 ${poolDir}`);
|
|
1631
|
+
// The list file only exists once work-agent.py has run init at least once.
|
|
1632
|
+
const listed = ctx.workAgent.essentialRepos();
|
|
1633
|
+
if (listed.length) say(`要下载的仓(${ctx.workAgent.essentialFile}):${listed.join('、')}`);
|
|
1634
|
+
else say(`要下载的是 work-agent 的必要仓清单,首次初始化时生成 ${ctx.workAgent.essentialFile},之后可以自己编辑再运行 setup`);
|
|
1635
|
+
say(`仓比较多,下载可能要很久;该磁盘当前可用 ${(freeBytes(poolDir) / 1073741824).toFixed(1)} GB。不下载也能用,只是相关规范不做检查。`);
|
|
1636
|
+
}
|
|
1637
|
+
if (!(await flow.ask('是否现在下载?', { defaultYes: false }))) return stepSkipped('以后可以再运行 work-agent-runner setup');
|
|
1638
|
+
if (flow.instance) {
|
|
1639
|
+
// The program downloads it (a Ctrl+C here does not stop it).
|
|
1640
|
+
try {
|
|
1641
|
+
const after = await askInstance(ctx, 'pool.init', { repos: wanted });
|
|
1642
|
+
return stepDone(`${after.repos} 个仓`);
|
|
1643
|
+
} catch (error) {
|
|
1644
|
+
return stepFailed('E5201', `下载知识仓失败:${error.message}`, '看上面的输出,修好后重新运行 setup');
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
const finished = markPoolBusy(ctx.paths, 'init');
|
|
1648
|
+
try {
|
|
1649
|
+
const after = await withStopOnSignal(ctx, () => ctx.workAgent.initPool({ repos: wanted, say }));
|
|
1650
|
+
prepareWorkAgentHome(workAgentHome, { poolDir: ctx.workAgent.mountablePool(), link: ctx.paths.workAgentLink });
|
|
1651
|
+
return stepDone(`${after.repos} 个仓`);
|
|
1652
|
+
} catch (error) {
|
|
1653
|
+
if (error instanceof ExitError) throw error;
|
|
1654
|
+
return stepFailed('E5201', `下载知识仓失败:${error.message}`, '看上面的输出,修好后重新运行 setup');
|
|
1655
|
+
} finally {
|
|
1656
|
+
finished();
|
|
1657
|
+
}
|
|
1658
|
+
},
|
|
1659
|
+
|
|
1660
|
+
async service(ctx, flow) {
|
|
1661
|
+
const { values } = flow;
|
|
1662
|
+
const status = serviceStatus();
|
|
1663
|
+
if (status.installed) {
|
|
1664
|
+
await lingerCheck(flow);
|
|
1665
|
+
return stepDone(`${status.name}:${status.state}`);
|
|
1666
|
+
}
|
|
1667
|
+
if (flow.unattended && !values.service) return stepSkipped('没有要求(--service)');
|
|
1668
|
+
if (!flow.unattended && !(await flow.ask('是否注册为后台服务(开机自启,关掉终端也保持在线)?'))) return stepSkipped('只在前台运行');
|
|
1669
|
+
if (process.getuid() === 0 && !values['allow-root']) {
|
|
1670
|
+
return stepFailed('E1103', '以 root 运行的服务需要 --allow-root', '改用普通账号运行,或加上 --allow-root 重新运行 setup');
|
|
1671
|
+
}
|
|
1672
|
+
if (flow.instance && flow.instance.service === 'foreground') {
|
|
1673
|
+
return stepFailed('', `程序正在前台运行(pid ${flow.instance.pid})`, '先在它的终端按 Ctrl+C 停止,再运行 work-agent-runner service install');
|
|
1674
|
+
}
|
|
1675
|
+
removeLegacyService({ say });
|
|
1676
|
+
installService({
|
|
1677
|
+
nodePath: process.execPath,
|
|
1678
|
+
entry: fs.realpathSync(ENTRY),
|
|
1679
|
+
args: ['start', ...(values['allow-root'] ? ['--allow-root'] : [])],
|
|
1680
|
+
say,
|
|
1681
|
+
// The first run holds the instance lock: the service starts once it lets go.
|
|
1682
|
+
start: !flow.firstRun,
|
|
1683
|
+
});
|
|
1684
|
+
flow.serviceInstalled = true;
|
|
1685
|
+
await lingerCheck(flow);
|
|
1686
|
+
return stepDone(flow.firstRun ? '已安装,设置完成后启动' : '已安装并启动');
|
|
1687
|
+
},
|
|
1688
|
+
};
|
|
1689
|
+
|
|
1690
|
+
/** Whether options ask for a step that was declined before (it is asked again). */
|
|
1691
|
+
function stepAskedFor(id, values) {
|
|
1692
|
+
if (id === 'claude') return Boolean(values['claude-version']);
|
|
1693
|
+
if (id === 'pool') return values.repos !== undefined;
|
|
1694
|
+
if (id === 'service') return Boolean(values.service);
|
|
1695
|
+
return false;
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
/**
|
|
1699
|
+
* The setup steps in order. Each is idempotent: one done before is checked
|
|
1700
|
+
* again quickly; one declined before stays declined (unless --reset or an
|
|
1701
|
+
* option asks for it). A failed step: retry, carry on or stop (in a
|
|
1702
|
+
* terminal); unattended runs carry on and report. False when stopped.
|
|
1703
|
+
*/
|
|
1704
|
+
async function runSetupSteps(ctx, flow) {
|
|
1705
|
+
const state = new SetupState(ctx.paths.setupFile, { version: VERSION });
|
|
1706
|
+
if (flow.values.reset) state.reset();
|
|
1707
|
+
flow.state = state;
|
|
1708
|
+
for (const [index, [id, title]] of SETUP_STEPS.entries()) {
|
|
1709
|
+
if (state.status(id) === 'skipped' && !stepAskedFor(id, flow.values)) {
|
|
1710
|
+
flow.out(stepLine(index, title, '- 之前跳过了(setup --reset 重新询问)'));
|
|
1711
|
+
continue;
|
|
1712
|
+
}
|
|
1713
|
+
for (;;) {
|
|
1714
|
+
let shown = false;
|
|
1715
|
+
const header = () => {
|
|
1716
|
+
if (shown) return;
|
|
1717
|
+
shown = true;
|
|
1718
|
+
flow.out(stepLine(index, title));
|
|
1719
|
+
};
|
|
1720
|
+
flow.beforeAsk = header;
|
|
1721
|
+
const started = Date.now();
|
|
1722
|
+
let outcome;
|
|
1723
|
+
try {
|
|
1724
|
+
outcome = await sayingTo((text) => {
|
|
1725
|
+
header();
|
|
1726
|
+
flow.out(` ${text}`);
|
|
1727
|
+
}, () => SETUP_STEP_RUNNERS[id](ctx, flow));
|
|
1728
|
+
} catch (error) {
|
|
1729
|
+
if (error instanceof CancelledError || (error instanceof ExitError && error.code >= 128)) throw error;
|
|
1730
|
+
outcome = stepFailed(error?.code && /^E\d{4}$/.test(error.code) ? error.code : '', error?.message || String(error));
|
|
1731
|
+
}
|
|
1732
|
+
const seconds = Math.round((Date.now() - started) / 1000);
|
|
1733
|
+
let mark;
|
|
1734
|
+
if (outcome.status === 'done') mark = `✓ ${outcome.detail || '完成'}${seconds >= 3 ? `(${seconds} 秒)` : ''}`;
|
|
1735
|
+
else if (outcome.status === 'skipped') mark = `- 跳过${outcome.detail ? `:${outcome.detail}` : ''}`;
|
|
1736
|
+
else mark = `✗ ${outcome.detail}${outcome.error?.code ? `(${outcome.error.code})` : ''}`;
|
|
1737
|
+
if (shown) flow.out(` ${mark}`);
|
|
1738
|
+
else flow.out(stepLine(index, title, mark));
|
|
1739
|
+
if (outcome.status === 'failed' && outcome.error?.fix) flow.out(` 处理:${outcome.error.fix}`);
|
|
1740
|
+
state.set(id, outcome.status, { detail: outcome.detail, error: outcome.error || null });
|
|
1741
|
+
if (outcome.status !== 'failed' || flow.unattended) break;
|
|
1742
|
+
const choice = String(await askText(' [r] 重试 [c] 继续 [q] 退出(回车 = 继续):')).trim().toLowerCase();
|
|
1743
|
+
flow.log.write(`选择:${choice || 'c'}`);
|
|
1744
|
+
if (choice === 'r') continue;
|
|
1745
|
+
if (choice === 'q') return false;
|
|
1746
|
+
break;
|
|
1747
|
+
}
|
|
1748
|
+
}
|
|
1749
|
+
return true;
|
|
1750
|
+
}
|
|
1751
|
+
|
|
1752
|
+
/** After the steps: the website's verdict — from the running program (it reports itself), else from here. */
|
|
1753
|
+
async function setupVerdict(ctx, flow) {
|
|
1754
|
+
if (flow.instance) return askInstance(ctx, 'doctor', {}, { quiet: true }).catch(() => null);
|
|
1755
|
+
if (!ctx.config.token) return null;
|
|
1756
|
+
try {
|
|
1757
|
+
const capabilities = (flow.result?.capabilities?.sandbox ? flow.result : await doctorFor(ctx)).capabilities;
|
|
1758
|
+
return await connect(ctx, flow.client || clientFor(ctx), capabilities);
|
|
1759
|
+
} catch {
|
|
1760
|
+
return null;
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
|
|
1764
|
+
/** `setup`: the steps in a terminal, or --unattended (options decide; JSON report). */
|
|
1765
|
+
async function setup(values) {
|
|
1766
|
+
checkSystem();
|
|
1767
|
+
const restarted = await applyProxy();
|
|
1768
|
+
if (restarted !== null) return restarted;
|
|
1769
|
+
const unattended = Boolean(values.unattended);
|
|
1770
|
+
if (!unattended && !isInteractive()) throw new ExitError(ATTENTION, 'setup 需要在终端里运行(安装前会请你确认);脚本里请用 setup --unattended');
|
|
1771
|
+
// stdout is for the JSON report alone.
|
|
1772
|
+
if (unattended) log.setOut(process.stderr);
|
|
1042
1773
|
const ctx = loadContext(values);
|
|
1043
|
-
const
|
|
1044
|
-
|
|
1045
|
-
|
|
1774
|
+
const flow = setupFlow(ctx, values, { unattended });
|
|
1775
|
+
flow.out(`GitCode Agent 执行机器 ${VERSION} · 设置`);
|
|
1776
|
+
const finished = await runSetupSteps(ctx, flow);
|
|
1777
|
+
saveField(ctx, 'setupDone', true);
|
|
1778
|
+
const verdict = await setupVerdict(ctx, flow);
|
|
1779
|
+
const failedSteps = SETUP_STEPS.filter(([id]) => flow.state.status(id) === 'failed').map(([id]) => id);
|
|
1780
|
+
if (unattended) {
|
|
1781
|
+
const report = {
|
|
1782
|
+
version: VERSION,
|
|
1783
|
+
ok: !failedSteps.length,
|
|
1784
|
+
steps: flow.state.toJSON(),
|
|
1785
|
+
features: verdict?.features || null,
|
|
1786
|
+
confirmed: verdict ? verdict.confirmed !== false : null,
|
|
1787
|
+
log: flow.log.file,
|
|
1788
|
+
};
|
|
1789
|
+
process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
1790
|
+
return failedSteps.length ? 1 : 0;
|
|
1791
|
+
}
|
|
1792
|
+
flow.out(finished ? '—— 完成 ——' : '—— 已退出 ——');
|
|
1793
|
+
printFeatures(verdict, flow.out);
|
|
1794
|
+
if (verdict?.confirmed === false) {
|
|
1795
|
+
flow.out('下一步:在网页「在线 Agent → 模型配置 → 执行机器」确认这台机器');
|
|
1796
|
+
flow.out(` ${ctx.server}/features#agent/config`);
|
|
1797
|
+
}
|
|
1798
|
+
if (flow.log.file) flow.out(`安装日志:${flow.log.file}`);
|
|
1799
|
+
return failedSteps.length || !finished ? 1 : 0;
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
/**
|
|
1803
|
+
* `update`: both repositories, now. With the program running, it does both
|
|
1804
|
+
* (the knowledge pool as soon as no job runs: a `git pull` must not replace
|
|
1805
|
+
* files a job is reading); otherwise this process does.
|
|
1806
|
+
*/
|
|
1807
|
+
async function update(values) {
|
|
1808
|
+
checkSystem();
|
|
1809
|
+
const restarted = await applyProxy();
|
|
1810
|
+
if (restarted !== null) return restarted;
|
|
1811
|
+
const ctx = loadContext(values);
|
|
1812
|
+
const instance = await pingInstance(ctx.paths);
|
|
1813
|
+
if (instance) {
|
|
1814
|
+
say(`程序正在运行(pid ${instance.pid}),由它来更新:`);
|
|
1815
|
+
const repo = await askInstance(ctx, 'repo.refresh');
|
|
1816
|
+
say(repo.ok ? `✓ work-agent ${repo.commit.slice(0, 7)}` : `✗ work-agent 仓库不可用:${repo.reason}`);
|
|
1817
|
+
if (ctx.workAgent.mountablePool()) {
|
|
1818
|
+
const pool = await askInstance(ctx, 'pool.update');
|
|
1819
|
+
if (pool?.queued) say(`知识仓:${pool.reason},已安排在任务结束后更新(work-agent-runner status 可以看到)`);
|
|
1820
|
+
else if (pool?.skipped) say(`知识仓:${pool.skipped}`);
|
|
1821
|
+
else say(pool?.result === 'ok' ? '✓ 知识仓已更新' : `✗ 知识仓更新失败:${pool?.error || '原因未知'}`);
|
|
1822
|
+
if (pool?.result === 'failed') return 1;
|
|
1823
|
+
}
|
|
1824
|
+
return repo.ok ? 0 : 1;
|
|
1825
|
+
}
|
|
1826
|
+
const running = runningInstance(ctx);
|
|
1827
|
+
let failed = false;
|
|
1828
|
+
try {
|
|
1829
|
+
const state = await ctx.workAgent.refresh();
|
|
1830
|
+
printWorkAgent(state);
|
|
1831
|
+
failed = !state.ok;
|
|
1832
|
+
if (ctx.workAgent.mountablePool()) {
|
|
1833
|
+
const busy = poolBusyInfo(ctx.paths);
|
|
1834
|
+
if (running) {
|
|
1835
|
+
// An older program without the control interface: it updates when idle.
|
|
1836
|
+
requestPoolUpdate(ctx.paths);
|
|
1837
|
+
const service = serviceStatus();
|
|
1838
|
+
say(`程序正在运行(pid ${running}):已请它在没有任务时更新知识仓${service.installed ? `(${service.logHint})` : ''}`);
|
|
1839
|
+
} else if (busy) {
|
|
1840
|
+
say(`另一个进程(pid ${busy.pid})正在${busy.kind === 'init' ? '下载' : '更新'}知识仓,请等它结束后再试`);
|
|
1841
|
+
failed = true;
|
|
1842
|
+
} else {
|
|
1843
|
+
const done = markPoolBusy(ctx.paths, 'update');
|
|
1844
|
+
try {
|
|
1845
|
+
await withStopOnSignal(ctx, () => ctx.workAgent.updatePool({ say }));
|
|
1846
|
+
} finally {
|
|
1847
|
+
done();
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
} catch (error) {
|
|
1852
|
+
if (error instanceof ExitError) throw error;
|
|
1853
|
+
say(error.message);
|
|
1854
|
+
failed = true;
|
|
1855
|
+
}
|
|
1046
1856
|
if (ctx.config.token) {
|
|
1857
|
+
// So the website shows the new commit without waiting for the next start.
|
|
1047
1858
|
try {
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
note = error instanceof ApiError && error.status === 401 ? '令牌无效或已删除' : `无法连接网站:${error instanceof ApiError ? error.message : networkReason(error)}`;
|
|
1859
|
+
printFeatures(await connect(ctx, clientFor(ctx), (await doctorFor(ctx)).capabilities));
|
|
1860
|
+
} catch {
|
|
1861
|
+
say('(没能把新状态报给网站,程序下次连接时会报)');
|
|
1052
1862
|
}
|
|
1053
|
-
}
|
|
1863
|
+
}
|
|
1864
|
+
return failed ? 1 : 0;
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
/** "glibc 2.43" / "musl" on Linux; null elsewhere. Managed Claude Code picks its platform package by it. */
|
|
1868
|
+
function libcInfo() {
|
|
1869
|
+
if (process.platform !== 'linux') return null;
|
|
1870
|
+
const glibc = process.report?.getReport?.()?.header?.glibcVersionRuntime;
|
|
1871
|
+
return glibc ? { family: 'glibc', version: glibc } : { family: 'musl', version: '' };
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
/** GET `url` within 10 s: { ok, detail } — any HTTP answer means the network and TLS work. */
|
|
1875
|
+
async function reach(url, { expect = null } = {}) {
|
|
1876
|
+
try {
|
|
1877
|
+
const response = await fetch(url, { method: 'GET', redirect: 'manual', signal: AbortSignal.timeout(10_000), headers: { 'User-Agent': `work-agent-runner/${VERSION}` } });
|
|
1878
|
+
await response.body?.cancel().catch(() => {});
|
|
1879
|
+
if (expect && !expect(response.status)) return { ok: false, detail: `${new URL(url).origin} 返回 HTTP ${response.status}` };
|
|
1880
|
+
return { ok: true, detail: `${new URL(url).origin} 可以连上` };
|
|
1881
|
+
} catch (error) {
|
|
1882
|
+
return { ok: false, detail: `无法连接 ${new URL(url).origin}(${error?.cause?.code || error?.name || error?.message})` };
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
|
|
1886
|
+
/** The npm registry Claude Code comes from: WORK_AGENT_RUNNER_REGISTRY (tests), config mirrors.npmRegistry, else npmjs. */
|
|
1887
|
+
function registryBase(ctx) {
|
|
1888
|
+
return (process.env.WORK_AGENT_RUNNER_REGISTRY || ctx.config.mirrors?.npmRegistry || 'https://registry.npmjs.org').replace(/\/+$/, '');
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1891
|
+
async function networkFacts(ctx) {
|
|
1892
|
+
// Tests and machines without outside access: say so instead of waiting for timeouts.
|
|
1893
|
+
if (process.env.WORK_AGENT_RUNNER_OFFLINE_CHECK === '1') {
|
|
1894
|
+
const skipped = { skipped: true, detail: '未检查(WORK_AGENT_RUNNER_OFFLINE_CHECK=1)' };
|
|
1895
|
+
return { website: skipped, gitcode: skipped, registry: skipped, proxy: '' };
|
|
1896
|
+
}
|
|
1897
|
+
const repoUrl = ctx.workAgent.repoUrl;
|
|
1898
|
+
const remote = /^https?:\/\//.test(repoUrl) ? new URL(repoUrl).origin : '';
|
|
1899
|
+
const [website, gitcode, registry] = await Promise.all([
|
|
1900
|
+
reach(`${ctx.server}/api/machine/v1/ping`),
|
|
1901
|
+
remote ? reach(`${remote}/`) : Promise.resolve({ skipped: true, detail: `work-agent 仓库来自 ${repoUrl}(不检查网络)` }),
|
|
1902
|
+
reach(`${registryBase(ctx)}/@anthropic-ai%2fclaude-code/latest`, { expect: (status) => status === 200 }),
|
|
1903
|
+
]);
|
|
1904
|
+
const proxy = PROXY_VARIABLES.filter((name) => process.env[name] && /^https?_proxy$/i.test(name))
|
|
1905
|
+
.map((name) => `${name}=${redactUrl(process.env[name])}`)
|
|
1906
|
+
.join(' ');
|
|
1907
|
+
return { website, gitcode, registry, proxy };
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
/** claude as `check` reports it: where, which version, who installed it, the verified and the required version. */
|
|
1911
|
+
function claudeFacts(ctx, file, version, minVersion = '') {
|
|
1912
|
+
const managed = Boolean(file) && isInside(file, ctx.paths.claudeDir);
|
|
1913
|
+
return { path: file || '', version: version || '', source: file ? (managed ? 'managed' : 'external') : '', verifiedVersion: VERIFIED_CLAUDE_VERSION, minVersion };
|
|
1914
|
+
}
|
|
1915
|
+
|
|
1916
|
+
/**
|
|
1917
|
+
* Everything `check` judges (lib/check.mjs). What only this terminal can see
|
|
1918
|
+
* — the system, paths, disks, network, AppArmor, the service — is read here;
|
|
1919
|
+
* tools, the sandbox, claude and the website's verdict come from the running
|
|
1920
|
+
* program when there is one (its environment is the one jobs get).
|
|
1921
|
+
*/
|
|
1922
|
+
async function collectCheckFacts(ctx) {
|
|
1923
|
+
const facts = await baseCheckFacts(ctx);
|
|
1924
|
+
return withProgramFacts(ctx, facts);
|
|
1925
|
+
}
|
|
1926
|
+
|
|
1927
|
+
/** What this terminal can tell by itself, quickly: system, paths, disks, network, AppArmor, the service. */
|
|
1928
|
+
async function baseCheckFacts(ctx) {
|
|
1929
|
+
const { paths, config } = ctx;
|
|
1054
1930
|
const system = systemInfo(ctx);
|
|
1931
|
+
const user = os.userInfo().username;
|
|
1932
|
+
let control;
|
|
1933
|
+
try {
|
|
1934
|
+
const where = socketLocation(paths);
|
|
1935
|
+
control = { socket: where.socket, fallback: where.fallback };
|
|
1936
|
+
} catch (error) {
|
|
1937
|
+
control = { error: error.message };
|
|
1938
|
+
}
|
|
1939
|
+
const instance = await pingInstance(paths);
|
|
1940
|
+
const service = serviceStatus();
|
|
1941
|
+
const facts = {
|
|
1942
|
+
platform: process.platform,
|
|
1943
|
+
arch: process.arch,
|
|
1944
|
+
osName: system.osName,
|
|
1945
|
+
libc: libcInfo(),
|
|
1946
|
+
root: process.getuid() === 0,
|
|
1947
|
+
user,
|
|
1948
|
+
container: system.container,
|
|
1949
|
+
workRoot: { path: ctx.workRoot, bytes: Buffer.byteLength(ctx.workRoot) },
|
|
1950
|
+
control,
|
|
1951
|
+
node: { version: process.versions.node, managed: Boolean(process.env.GC_RUNNER_NODE_SWITCHED) },
|
|
1952
|
+
disk: { workRoot: freeBytes(ctx.workRoot), pool: freeBytes(paths.poolDir), minFree: effectiveSettings(config).limits.minFreeBytes },
|
|
1953
|
+
network: await networkFacts(ctx),
|
|
1954
|
+
sudo: Boolean(which('sudo')),
|
|
1955
|
+
apparmor: readApparmor(),
|
|
1956
|
+
userns: readUserns(),
|
|
1957
|
+
service: { installed: service.installed, state: service.state, name: service.name, linger: service.installed ? lingerEnabled({ user }) : null },
|
|
1958
|
+
instance: instance ? { pid: instance.pid, version: instance.version } : null,
|
|
1959
|
+
};
|
|
1960
|
+
return facts;
|
|
1961
|
+
}
|
|
1962
|
+
|
|
1963
|
+
/** Tools, the sandbox, claude, the repositories and the website's verdict: by the running program when there is one. */
|
|
1964
|
+
async function withProgramFacts(ctx, facts) {
|
|
1965
|
+
const { config } = ctx;
|
|
1966
|
+
const delegated = facts.instance ? await askInstance(ctx, 'doctor', {}, { quiet: true }).catch(() => null) : null;
|
|
1967
|
+
if (delegated) {
|
|
1968
|
+
return Object.assign(facts, {
|
|
1969
|
+
viaInstance: true,
|
|
1970
|
+
capabilities: delegated.capabilities,
|
|
1971
|
+
tools: delegated.tools,
|
|
1972
|
+
packageManager: delegated.capabilities.packageManager || '',
|
|
1973
|
+
sandbox: delegated.capabilities.sandbox,
|
|
1974
|
+
claude: claudeFacts(ctx, delegated.claude.path, delegated.claudeVersion, delegated.minClaudeVersion),
|
|
1975
|
+
repo: delegated.workAgent,
|
|
1976
|
+
pool: delegated.workAgent,
|
|
1977
|
+
website: {
|
|
1978
|
+
token: Boolean(config.token),
|
|
1979
|
+
valid: delegated.features ? true : undefined,
|
|
1980
|
+
confirmed: delegated.confirmed ?? undefined,
|
|
1981
|
+
features: delegated.features,
|
|
1982
|
+
note: delegated.note,
|
|
1983
|
+
},
|
|
1984
|
+
});
|
|
1985
|
+
}
|
|
1986
|
+
const result = await doctorFor(ctx);
|
|
1055
1987
|
const repo = ctx.workAgent.state();
|
|
1988
|
+
const website = { token: Boolean(config.token) };
|
|
1989
|
+
let minVersion = '';
|
|
1990
|
+
if (config.token) {
|
|
1991
|
+
try {
|
|
1992
|
+
// Also brings the website's copy of this machine's capabilities up to date.
|
|
1993
|
+
const reply = await connect(ctx, clientFor(ctx), result.capabilities);
|
|
1994
|
+
Object.assign(website, { valid: true, confirmed: reply.confirmed !== false, features: reply.features });
|
|
1995
|
+
minVersion = reply.minClaudeVersion || '';
|
|
1996
|
+
} catch (error) {
|
|
1997
|
+
if (error instanceof ApiError && error.status === 401) Object.assign(website, { valid: false, note: '令牌无效或已删除' });
|
|
1998
|
+
else if (error instanceof ApiError && error.code === 'machine_blocked') website.blocked = true;
|
|
1999
|
+
else website.note = `无法连接网站,无法判断各功能(${error instanceof ApiError ? error.message : networkReason(error)})`;
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
return Object.assign(facts, {
|
|
2003
|
+
viaInstance: false,
|
|
2004
|
+
capabilities: result.capabilities,
|
|
2005
|
+
tools: result.tools,
|
|
2006
|
+
packageManager: result.packageManager || '',
|
|
2007
|
+
sandbox: result.capabilities.sandbox,
|
|
2008
|
+
claude: claudeFacts(ctx, result.claude.path, result.claudeVersion, minVersion),
|
|
2009
|
+
repo,
|
|
2010
|
+
pool: repo,
|
|
2011
|
+
website,
|
|
2012
|
+
});
|
|
2013
|
+
}
|
|
2014
|
+
|
|
2015
|
+
/**
|
|
2016
|
+
* `check` (and its old name `doctor`): group by group, what this machine
|
|
2017
|
+
* needs; exit 0 every feature can run, 1 some cannot, 2 none can.
|
|
2018
|
+
*/
|
|
2019
|
+
async function check(values) {
|
|
2020
|
+
checkSystem();
|
|
2021
|
+
const restarted = await applyProxy();
|
|
2022
|
+
if (restarted !== null) return restarted;
|
|
2023
|
+
const ctx = loadContext(values);
|
|
2024
|
+
if (!values.json) say(`GitCode Agent 执行机器 ${VERSION} · 检查中……`);
|
|
2025
|
+
const facts = await collectCheckFacts(ctx);
|
|
2026
|
+
const report = assessCheck(facts);
|
|
1056
2027
|
if (values.json) {
|
|
1057
|
-
say(JSON.stringify({ version: VERSION, capabilities:
|
|
1058
|
-
return
|
|
2028
|
+
say(JSON.stringify({ version: VERSION, ...report, capabilities: facts.capabilities, viaInstance: facts.viaInstance }, null, 2));
|
|
2029
|
+
return report.exitCode;
|
|
2030
|
+
}
|
|
2031
|
+
if (facts.viaInstance) say(`依赖、沙箱和 claude 由运行中的程序(pid ${facts.instance.pid})检查,结果由它报给网站`);
|
|
2032
|
+
say('');
|
|
2033
|
+
for (const line of checkLines(report)) say(line);
|
|
2034
|
+
return report.exitCode;
|
|
2035
|
+
}
|
|
2036
|
+
|
|
2037
|
+
/**
|
|
2038
|
+
* The instance's status: asked live, else its last status.json.
|
|
2039
|
+
* { snapshot, live, silent (why a running one did not answer), holder, alive }.
|
|
2040
|
+
*/
|
|
2041
|
+
async function currentStatus(ctx) {
|
|
2042
|
+
let snapshot = null;
|
|
2043
|
+
let live = false;
|
|
2044
|
+
let silent = '';
|
|
2045
|
+
try {
|
|
2046
|
+
snapshot = await controlRequest(ctx.paths, 'status', {}, { timeoutMs: 10_000 });
|
|
2047
|
+
live = true;
|
|
2048
|
+
} catch (error) {
|
|
2049
|
+
if (!(error instanceof NotRunningError)) silent = error.message;
|
|
2050
|
+
}
|
|
2051
|
+
if (!snapshot) snapshot = readStatus(ctx.paths.statusFile);
|
|
2052
|
+
const holder = lockHolder(ctx.paths.lockFile);
|
|
2053
|
+
return { snapshot, live, silent, holder, alive: isRunnerAlive(holder) };
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
/** `status --watch`: the live part, redrawn every 2 seconds until Ctrl+C. */
|
|
2057
|
+
async function watchStatus(ctx) {
|
|
2058
|
+
if (!process.stdout.isTTY) throw new ExitError(1, 'status --watch 需要在终端里运行(脚本里请用 status --json)');
|
|
2059
|
+
process.on('SIGINT', () => {
|
|
2060
|
+
process.stdout.write('\n');
|
|
2061
|
+
process.exit(0);
|
|
2062
|
+
});
|
|
2063
|
+
for (;;) {
|
|
2064
|
+
const { snapshot, live, silent, holder, alive } = await currentStatus(ctx);
|
|
2065
|
+
const silentPid = !live && alive ? holder : 0;
|
|
2066
|
+
const lines = snapshot ? statusLines(snapshot, { stale: !live, silentPid, silentReason: silent }) : ['程序没有在运行,也还没有状态记录'];
|
|
2067
|
+
process.stdout.write(`\x1b[H\x1b[2J${lines.join('\n')}\n\n每 2 秒刷新 · Ctrl+C 退出\n`);
|
|
2068
|
+
await sleep(2000);
|
|
1059
2069
|
}
|
|
1060
|
-
say(`GitCode Agent 执行机器 ${VERSION} · Node ${process.versions.node} · ${process.platform}/${process.arch}`);
|
|
1061
|
-
say(`系统:${describeSystem(system)}`);
|
|
1062
|
-
printWorkAgent(repo);
|
|
1063
|
-
printDoctor(result);
|
|
1064
|
-
printFeatures(reply);
|
|
1065
|
-
if (reply?.confirmed === false) say('这台机器还没有在网页上确认,确认后才会收到任务(在线 Agent → 模型配置 → 执行机器)');
|
|
1066
|
-
if (note) say(note);
|
|
1067
|
-
return 0;
|
|
1068
2070
|
}
|
|
1069
2071
|
|
|
1070
2072
|
async function status(values) {
|
|
@@ -1072,55 +2074,512 @@ async function status(values) {
|
|
|
1072
2074
|
const restarted = await applyProxy();
|
|
1073
2075
|
if (restarted !== null) return restarted;
|
|
1074
2076
|
const ctx = loadContext(values, { workRoot: false });
|
|
2077
|
+
if (values.watch) {
|
|
2078
|
+
if (values.json) throw new ExitError(1, '--watch 和 --json 不能一起用');
|
|
2079
|
+
return watchStatus(ctx);
|
|
2080
|
+
}
|
|
1075
2081
|
const { config } = ctx;
|
|
2082
|
+
const { snapshot, live, silent, holder, alive } = await currentStatus(ctx);
|
|
2083
|
+
const healthy = live && snapshot?.connection?.connected && snapshot?.state?.accepting && !(snapshot?.degraded || []).length;
|
|
2084
|
+
const code = !live || !snapshot?.connection?.connected ? 2 : healthy ? 0 : 1;
|
|
2085
|
+
const service = serviceStatus();
|
|
2086
|
+
if (values.json) {
|
|
2087
|
+
say(JSON.stringify({ running: live, pid: alive ? holder : 0, snapshot, service, configFile: ctx.paths.configFile }, null, 2));
|
|
2088
|
+
return code;
|
|
2089
|
+
}
|
|
1076
2090
|
say(`网站:${ctx.server}`);
|
|
1077
2091
|
say(`令牌:${config.token ? `${config.token.slice(0, 12)}…` : '未登录(运行 work-agent-runner login)'}`);
|
|
1078
2092
|
say(`机器标识:${config.clientId}`);
|
|
1079
2093
|
say(`登记名称:${config.machineName || `${os.hostname()}(主机名)`}`);
|
|
1080
|
-
say(
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
2094
|
+
say(`配置文件:${ctx.paths.configFile}`);
|
|
2095
|
+
say(`后台服务:${service.installed ? `${service.state}(${service.name};${service.logHint})` : '未安装'}`);
|
|
2096
|
+
if (legacyServiceInstalled()) say(LEGACY_SERVICE_HINT);
|
|
2097
|
+
say('');
|
|
2098
|
+
const silentPid = !live && alive ? holder : 0;
|
|
2099
|
+
if (snapshot) for (const line of statusLines(snapshot, { stale: !live, silentPid, silentReason: silent })) say(line);
|
|
2100
|
+
else if (silentPid) say(`程序在运行(pid ${holder}),但没有回应管理接口${silent ? `(${silent})` : '(0.0.5 及以前的版本没有这个接口)'}`);
|
|
2101
|
+
else say('程序没有在运行,也还没有状态记录');
|
|
2102
|
+
say('');
|
|
2103
|
+
say(`目录:程序目录 ${ctx.paths.baseDir} · 任务目录 ${path.join(config.workRoot || ctx.paths.runsRoot, 'runs')} · 日志 ${ctx.paths.logFile}(完整列表:work-agent-runner paths)`);
|
|
2104
|
+
const requested = poolUpdateRequested(ctx.paths);
|
|
2105
|
+
if (requested && !live) say(`已请求更新知识仓(${requested}),等待程序在没有任务时执行`);
|
|
2106
|
+
if (!live && config.token) {
|
|
2107
|
+
try {
|
|
2108
|
+
// A request with no effect (it must not be /heartbeat: reporting no running
|
|
2109
|
+
// jobs from a second process would make the website fail this machine's jobs).
|
|
2110
|
+
await clientFor(ctx).request('GET', '/ping');
|
|
2111
|
+
say('连接测试:令牌有效,网站可以连上');
|
|
2112
|
+
} catch (error) {
|
|
2113
|
+
if (error instanceof ApiError) {
|
|
2114
|
+
const text = {
|
|
2115
|
+
404: '网站版本过旧(没有 /ping),请联系管理员部署新版网站',
|
|
2116
|
+
401: '令牌无效或已删除(运行 work-agent-runner login)',
|
|
2117
|
+
403: '这台机器已被封禁',
|
|
2118
|
+
409: '令牌有效,这台机器尚未登记(运行 work-agent-runner 会自动登记,之后在网页上确认)',
|
|
2119
|
+
}[error.status] || error.message;
|
|
2120
|
+
say(`连接测试:${text}`);
|
|
2121
|
+
} else say(`连接测试:失败(${networkReason(error)})`);
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
return code;
|
|
2125
|
+
}
|
|
2126
|
+
|
|
2127
|
+
async function jobsCommand(values, action, runId) {
|
|
2128
|
+
checkSystem();
|
|
2129
|
+
const ctx = loadContext(values, { workRoot: false });
|
|
2130
|
+
if (action === 'cancel') {
|
|
2131
|
+
if (!runId) throw new ExitError(1, '用法:work-agent-runner jobs cancel <任务 ID>');
|
|
2132
|
+
const answer = await askInstance(ctx, 'job.cancel', { runId }, { quiet: true });
|
|
2133
|
+
if (!answer) throw new ExitError(2, '程序没有在运行');
|
|
2134
|
+
say(answer.cancelled ? `已取消任务 ${answer.runId}(网页上会显示为已取消)` : `没有找到运行中的任务 ${runId}`);
|
|
2135
|
+
return answer.cancelled ? 0 : 1;
|
|
2136
|
+
}
|
|
2137
|
+
if (action === 'show') {
|
|
2138
|
+
if (!runId) throw new ExitError(1, '用法:work-agent-runner jobs show <任务 ID>');
|
|
2139
|
+
const live = await askInstance(ctx, 'jobs', { runId, limit: 1 }, { quiet: true });
|
|
2140
|
+
const running = live?.running?.find((job) => matchesRunId(job.runId, runId));
|
|
2141
|
+
const record = running || (live?.history || readHistory(ctx.paths.historyFile, { runId, limit: 1 }))[0];
|
|
2142
|
+
if (values.json) {
|
|
2143
|
+
say(JSON.stringify(record || null, null, 2));
|
|
2144
|
+
return record ? 0 : 1;
|
|
2145
|
+
}
|
|
2146
|
+
if (!record) throw new ExitError(1, `没有找到任务 ${runId}(只保留最近 1000 个或 30 天内的任务)`);
|
|
2147
|
+
for (const line of jobDetailLines(record)) say(line);
|
|
2148
|
+
return 0;
|
|
2149
|
+
}
|
|
2150
|
+
if (action) throw new ExitError(1, '用法:work-agent-runner jobs [show|cancel <任务 ID>] [--failed] [--since 24h] [-n 20] [--json]');
|
|
2151
|
+
const since = parseSince(values.since);
|
|
2152
|
+
const params = { since: since ? Date.now() - since : 0, limit: parseCount(values.lines, 20), failedOnly: Boolean(values.failed) };
|
|
2153
|
+
const live = await askInstance(ctx, 'jobs', params, { quiet: true });
|
|
2154
|
+
const data = live || { running: [], history: readHistory(ctx.paths.historyFile, params) };
|
|
2155
|
+
if (values.json) {
|
|
2156
|
+
say(JSON.stringify({ running: data.running, history: data.history, live: Boolean(live) }, null, 2));
|
|
2157
|
+
return 0;
|
|
2158
|
+
}
|
|
2159
|
+
if (!live) say('(程序没有在运行,以下来自任务记录)');
|
|
2160
|
+
for (const line of jobsLines(data, { failedOnly: params.failedOnly })) say(line);
|
|
2161
|
+
return 0;
|
|
2162
|
+
}
|
|
2163
|
+
|
|
2164
|
+
/** "2026-12-01 10:12:03 …" → that time (ms), NaN for lines without one. */
|
|
2165
|
+
function lineTime(line) {
|
|
2166
|
+
const match = /^(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)/.exec(line);
|
|
2167
|
+
if (!match) return Number.NaN;
|
|
2168
|
+
const [, year, month, day, hour, minute, second] = match.map(Number);
|
|
2169
|
+
return new Date(year, month - 1, day, hour, minute, second).getTime();
|
|
2170
|
+
}
|
|
2171
|
+
|
|
2172
|
+
async function logs(values) {
|
|
2173
|
+
checkSystem();
|
|
2174
|
+
const ctx = loadContext(values, { workRoot: false });
|
|
2175
|
+
const file = ctx.paths.logFile;
|
|
2176
|
+
const count = parseCount(values.lines, 100);
|
|
2177
|
+
const since = parseSince(values.since);
|
|
2178
|
+
const from = since ? Date.now() - since : 0;
|
|
2179
|
+
const keep = (line) => line && (!values.job || line.includes(values.job)) && (!from || !(lineTime(line) < from));
|
|
2180
|
+
// Oldest file first: runner.log.4 … runner.log.1, runner.log.
|
|
2181
|
+
const files = [4, 3, 2, 1].map((index) => `${file}.${index}`).filter((name) => fs.existsSync(name));
|
|
2182
|
+
if (fs.existsSync(file)) files.push(file);
|
|
2183
|
+
if (!files.length) {
|
|
2184
|
+
say(`还没有日志(${file}):程序运行后才有${serviceStatus().installed ? `;后台服务的输出也可以看:${serviceStatus().logHint}` : ''}`);
|
|
2185
|
+
if (!values.follow) return 0;
|
|
2186
|
+
}
|
|
2187
|
+
let lines = [];
|
|
2188
|
+
for (const name of files) lines.push(...fs.readFileSync(name, 'utf8').split('\n').filter(keep));
|
|
2189
|
+
for (const line of lines.slice(-count)) say(line);
|
|
2190
|
+
lines = null;
|
|
2191
|
+
if (!values.follow) return 0;
|
|
2192
|
+
// Follow: new lines as they come, across a rotation.
|
|
2193
|
+
let offset = fs.existsSync(file) ? fs.statSync(file).size : 0;
|
|
2194
|
+
let rest = '';
|
|
2195
|
+
for (;;) {
|
|
2196
|
+
await sleep(500);
|
|
2197
|
+
let size = 0;
|
|
2198
|
+
try {
|
|
2199
|
+
size = fs.statSync(file).size;
|
|
2200
|
+
} catch {
|
|
2201
|
+
continue;
|
|
2202
|
+
}
|
|
2203
|
+
if (size < offset) offset = 0; // rotated
|
|
2204
|
+
if (size === offset) continue;
|
|
2205
|
+
const handle = fs.openSync(file, 'r');
|
|
2206
|
+
const chunk = Buffer.alloc(size - offset);
|
|
2207
|
+
fs.readSync(handle, chunk, 0, chunk.length, offset);
|
|
2208
|
+
fs.closeSync(handle);
|
|
2209
|
+
offset = size;
|
|
2210
|
+
const parts = (rest + chunk.toString('utf8')).split('\n');
|
|
2211
|
+
rest = parts.pop();
|
|
2212
|
+
for (const line of parts) if (keep(line)) say(line);
|
|
2213
|
+
}
|
|
2214
|
+
}
|
|
2215
|
+
|
|
2216
|
+
/** Every directory this program uses, and whether it is fine: [{ label, path, note, free }]. */
|
|
2217
|
+
function pathRows(ctx) {
|
|
2218
|
+
const { paths, config } = ctx;
|
|
2219
|
+
const uid = process.getuid();
|
|
2220
|
+
const exists = (target) => fs.existsSync(target);
|
|
2221
|
+
const owned = (target) => {
|
|
2222
|
+
try {
|
|
2223
|
+
const stat = fs.statSync(target);
|
|
2224
|
+
return `${stat.uid === uid ? '本人' : '属主不是当前用户'} · ${(stat.mode & 0o777).toString(8).padStart(4, '0')}`;
|
|
2225
|
+
} catch {
|
|
2226
|
+
return '不存在';
|
|
2227
|
+
}
|
|
2228
|
+
};
|
|
2229
|
+
const count = (dir) => {
|
|
2230
|
+
try {
|
|
2231
|
+
return fs.readdirSync(dir).length;
|
|
2232
|
+
} catch {
|
|
2233
|
+
return 0;
|
|
2234
|
+
}
|
|
2235
|
+
};
|
|
2236
|
+
const workRoot = config.workRoot || paths.runsRoot;
|
|
2237
|
+
let socket = '';
|
|
2238
|
+
let socketNote = '';
|
|
1084
2239
|
try {
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
2240
|
+
const where = socketLocation(paths);
|
|
2241
|
+
socket = where.socket;
|
|
2242
|
+
socketNote = `${exists(where.socket) ? '程序运行中' : '程序没有在运行'}${where.fallback ? ' · 程序目录的路径太长,放在这里' : ''}`;
|
|
2243
|
+
} catch (error) {
|
|
2244
|
+
socketNote = error.message;
|
|
1088
2245
|
}
|
|
1089
|
-
|
|
2246
|
+
const own = ctx.workAgent.ownership();
|
|
1090
2247
|
const repo = ctx.workAgent.state();
|
|
1091
|
-
say(`work-agent 仓库:${repo.ok ? `${repo.commit.slice(0, 7)}(${ctx.workAgent.repoDir})` : repo.reason}`);
|
|
1092
2248
|
const envHome = process.env.WORK_AGENT_HOME ? path.resolve(process.env.WORK_AGENT_HOME) : '';
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
2249
|
+
const poolLink = path.join(paths.workAgentHome, 'ascend-repos');
|
|
2250
|
+
let poolNote = `${ctx.workAgent.poolRepos().length} 个仓`;
|
|
2251
|
+
try {
|
|
2252
|
+
if (fs.lstatSync(poolLink).isSymbolicLink()) poolNote += ` · ${poolLink} → 此处`;
|
|
2253
|
+
} catch {
|
|
2254
|
+
// No link.
|
|
2255
|
+
}
|
|
2256
|
+
const service = servicePaths();
|
|
2257
|
+
const rows = [
|
|
2258
|
+
{ label: '程序目录', path: paths.baseDir, note: owned(paths.baseDir), free: freeBytes(paths.baseDir) },
|
|
2259
|
+
{ label: '配置文件', path: paths.configFile, note: owned(paths.configFile) },
|
|
2260
|
+
{ label: '程序日志', path: paths.logFile, note: exists(paths.logFile) ? '' : '还没有' },
|
|
2261
|
+
{ label: '状态与任务记录', path: paths.stateDir },
|
|
2262
|
+
{ label: '管理接口', path: socket, note: socketNote },
|
|
2263
|
+
{
|
|
2264
|
+
label: '工作目录',
|
|
2265
|
+
path: workRoot,
|
|
2266
|
+
note: workRoot === paths.runsRoot ? '就是程序目录' : exists(path.join(workRoot, '.work-agent-runner.json')) ? '本程序的(有标记)' : '没有标记',
|
|
2267
|
+
free: freeBytes(workRoot),
|
|
2268
|
+
},
|
|
2269
|
+
{ label: ' 任务目录', path: path.join(workRoot, 'runs'), note: `${count(path.join(workRoot, 'runs'))} 项` },
|
|
2270
|
+
{ label: ' 回收站', path: path.join(workRoot, 'trash'), note: count(path.join(workRoot, 'trash')) ? `${count(path.join(workRoot, 'trash'))} 个删不掉的目录` : '空' },
|
|
2271
|
+
{ label: ' 任务归档', path: path.join(workRoot, 'archive'), note: effectiveSettings(config).limits.archiveDays ? `${count(path.join(workRoot, 'archive'))} 项` : '未启用' },
|
|
2272
|
+
{
|
|
2273
|
+
label: 'work-agent 克隆',
|
|
2274
|
+
path: paths.repoDir,
|
|
2275
|
+
note: own.kind === 'foreign' ? '不是本程序创建的,程序不会改动它' : repo.ok ? `${repo.commit.slice(0, 7)} · 本程序的` : repo.reason,
|
|
2276
|
+
},
|
|
2277
|
+
{ label: 'work-agent 的家', path: paths.workAgentHome, note: envHome && envHome !== paths.workAgentHome ? `环境变量 WORK_AGENT_HOME 是 ${envHome},以 config.json 为准` : '' },
|
|
2278
|
+
{ label: '知识仓', path: paths.poolDir, note: poolNote, free: freeBytes(paths.poolDir) },
|
|
2279
|
+
{ label: '托管 Node', path: exists(paths.nodeDir) ? paths.nodeDir : '', note: exists(paths.nodeDir) ? fs.readdirSync(paths.nodeDir).filter((name) => name.startsWith('v')).join('、') : '不需要(系统 Node 满足要求)' },
|
|
2280
|
+
{ label: '后台服务定义', path: service.file, note: exists(service.file) ? '已安装' : '未安装' },
|
|
2281
|
+
];
|
|
2282
|
+
return rows;
|
|
2283
|
+
}
|
|
2284
|
+
|
|
2285
|
+
/** `paths`: every directory this program uses, and whether it is fine. */
|
|
2286
|
+
function pathsCommand(values) {
|
|
2287
|
+
checkSystem();
|
|
2288
|
+
const rows = pathRows(loadContext(values, { workRoot: false }));
|
|
2289
|
+
if (values.json) {
|
|
2290
|
+
say(JSON.stringify(rows, null, 2));
|
|
2291
|
+
return 0;
|
|
2292
|
+
}
|
|
2293
|
+
for (const line of pathsLines(rows)) say(line);
|
|
2294
|
+
return 0;
|
|
2295
|
+
}
|
|
2296
|
+
|
|
2297
|
+
/** `reload`: the running program applies what config.json says now (maintenance, limits, isolation). */
|
|
2298
|
+
async function reload(values) {
|
|
2299
|
+
checkSystem();
|
|
2300
|
+
const ctx = loadContext(values, { workRoot: false });
|
|
2301
|
+
const answer = await askInstance(ctx, 'config.reload', {}, { quiet: true });
|
|
2302
|
+
if (!answer) throw new ExitError(2, '程序没有在运行:下次启动时会使用 config.json 里的设置');
|
|
2303
|
+
say(answer.changed.length ? `已生效:${answer.changed.join('、')}` : 'config.json 里可以直接生效的设置没有变化');
|
|
2304
|
+
if (answer.restartRequired.length) say(`${answer.restartRequired.join('、')} 要重新启动程序才生效(work-agent-runner service restart)`);
|
|
2305
|
+
return 0;
|
|
2306
|
+
}
|
|
2307
|
+
|
|
2308
|
+
// ---- upgrade, uninstall, diagnose -------------------------------------------------
|
|
2309
|
+
|
|
2310
|
+
const PACKAGE_NAME = '@online-tools/work-agent-runner';
|
|
2311
|
+
|
|
2312
|
+
/** "30m" / "2h" / "90s" → milliseconds. */
|
|
2313
|
+
function parseDuration(value, fallback) {
|
|
2314
|
+
if (value === undefined) return fallback;
|
|
2315
|
+
const match = /^(\d+)\s*(s|m|h)$/.exec(String(value).trim());
|
|
2316
|
+
if (!match) throw new ExitError(1, `时长的格式是 90s、30m 或 2h(收到 ${value})`);
|
|
2317
|
+
return Number(match[1]) * { s: 1000, m: 60_000, h: 3_600_000 }[match[2]];
|
|
2318
|
+
}
|
|
2319
|
+
|
|
2320
|
+
/** The newest version: what the website advertises (with a token), else npm's latest. */
|
|
2321
|
+
async function newestVersion(ctx) {
|
|
2322
|
+
if (ctx.config.token) {
|
|
2323
|
+
try {
|
|
2324
|
+
const reply = await clientFor(ctx).request('GET', '/ping');
|
|
2325
|
+
if (reply?.latestVersion) return reply.latestVersion;
|
|
2326
|
+
} catch {
|
|
2327
|
+
// npm then.
|
|
2328
|
+
}
|
|
2329
|
+
}
|
|
2330
|
+
const npm = which('npm');
|
|
2331
|
+
if (!npm) return '';
|
|
2332
|
+
const result = spawnSync(npm, ['view', PACKAGE_NAME, 'version'], { encoding: 'utf8', timeout: 60_000, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
2333
|
+
return result.status === 0 ? result.stdout.trim() : '';
|
|
2334
|
+
}
|
|
2335
|
+
|
|
2336
|
+
/** `npm install -g <spec>` as this user, or with sudo (asked first) where the global directory is not theirs. */
|
|
2337
|
+
async function npmGlobalInstall(spec, { ask }) {
|
|
2338
|
+
const npm = which('npm');
|
|
2339
|
+
if (!npm) throw new ExitError(1, '没有找到 npm:请手动安装');
|
|
2340
|
+
const prefix = spawnSync(npm, ['prefix', '-g'], { encoding: 'utf8', timeout: 20_000, stdio: ['ignore', 'pipe', 'ignore'] }).stdout?.trim();
|
|
2341
|
+
let command = [npm, 'install', '-g', spec];
|
|
2342
|
+
if (process.getuid() !== 0 && !(prefix && npmPrefixWritable(prefix))) {
|
|
2343
|
+
const sudo = which('sudo');
|
|
2344
|
+
if (!sudo) throw new ExitError(1, `npm 的全局目录(${prefix || '未知'})不可写,也没有 sudo:请让管理员执行 ${formatCommand(command)}`);
|
|
2345
|
+
command = [sudo, ...command];
|
|
2346
|
+
if (!(await ask(`需要 sudo 执行:${formatCommand(command)},是否继续?`))) throw new ExitError(1, '已取消');
|
|
2347
|
+
}
|
|
2348
|
+
say(`执行:${formatCommand(command)}`);
|
|
2349
|
+
return runCommand(command);
|
|
2350
|
+
}
|
|
2351
|
+
|
|
2352
|
+
/** Until the running program has no job left (true), or `timeoutMs` passed (false). */
|
|
2353
|
+
async function waitUntilIdle(ctx, timeoutMs) {
|
|
2354
|
+
const deadline = Date.now() + timeoutMs;
|
|
2355
|
+
let toldAt = 0;
|
|
2356
|
+
for (;;) {
|
|
2357
|
+
const snapshot = await controlRequest(ctx.paths, 'status', {}, { timeoutMs: 10_000 }).catch(() => null);
|
|
2358
|
+
const running = snapshot?.jobs?.length || 0;
|
|
2359
|
+
if (!snapshot || !running) return true;
|
|
2360
|
+
if (Date.now() >= deadline) return false;
|
|
2361
|
+
if (Date.now() - toldAt >= 30_000) {
|
|
2362
|
+
toldAt = Date.now();
|
|
2363
|
+
say(`还有 ${running} 个任务在运行,等它们结束……`);
|
|
2364
|
+
}
|
|
2365
|
+
await sleep(2000);
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
|
|
2369
|
+
/** Within `timeoutMs`: the program answers as `version` and is connected to the website. */
|
|
2370
|
+
async function waitForVersion(ctx, version, timeoutMs) {
|
|
2371
|
+
const deadline = Date.now() + timeoutMs;
|
|
2372
|
+
while (Date.now() < deadline) {
|
|
2373
|
+
const snapshot = await controlRequest(ctx.paths, 'status', {}, { timeoutMs: 5000 }).catch(() => null);
|
|
2374
|
+
if (snapshot?.instance?.version === version && snapshot.connection?.connected) return true;
|
|
2375
|
+
await sleep(2000);
|
|
2376
|
+
}
|
|
2377
|
+
return false;
|
|
2378
|
+
}
|
|
2379
|
+
|
|
2380
|
+
/**
|
|
2381
|
+
* `upgrade [--to <version>] [--drain-timeout 30m]` (design 10.7): the running
|
|
2382
|
+
* program stops taking jobs and finishes the ones it has; npm installs the
|
|
2383
|
+
* new version; the service restarts and must answer as it, connected, within
|
|
2384
|
+
* 60 s — or the old version goes back on.
|
|
2385
|
+
*/
|
|
2386
|
+
async function upgrade(values) {
|
|
2387
|
+
checkSystem();
|
|
2388
|
+
const restarted = await applyProxy();
|
|
2389
|
+
if (restarted !== null) return restarted;
|
|
2390
|
+
const ctx = loadContext(values, { workRoot: false });
|
|
2391
|
+
const ask = (question) => (values.yes ? Promise.resolve(true) : isInteractive() ? askYesNo(question) : Promise.resolve(false));
|
|
2392
|
+
const target = values.to || (await newestVersion(ctx));
|
|
2393
|
+
if (!target) throw new ExitError(1, '查不到最新版本:请用 --to <版本> 指定');
|
|
2394
|
+
if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(target)) throw new ExitError(1, `版本写法不对:${target}`);
|
|
2395
|
+
if (target === VERSION) {
|
|
2396
|
+
say(`已经是 ${VERSION}`);
|
|
2397
|
+
return 0;
|
|
2398
|
+
}
|
|
2399
|
+
say(`将从 ${VERSION} 升级到 ${target}`);
|
|
2400
|
+
const instance = await pingInstance(ctx.paths);
|
|
2401
|
+
const drainMs = parseDuration(values['drain-timeout'], 30 * 60_000);
|
|
2402
|
+
const resume = async () => {
|
|
2403
|
+
if (instance) await askInstance(ctx, 'drain', { on: false }, { quiet: true }).catch(() => null);
|
|
2404
|
+
};
|
|
2405
|
+
if (instance) {
|
|
2406
|
+
await askInstance(ctx, 'drain', { on: true }, { quiet: true });
|
|
2407
|
+
say(`程序正在运行(pid ${instance.pid}):已暂停接新任务(网页上显示「正在升级程序」),等运行中的任务结束`);
|
|
2408
|
+
while (!(await waitUntilIdle(ctx, drainMs))) {
|
|
2409
|
+
const choice = isInteractive() ? String(await askText('还有任务在运行:[w] 继续等 [c] 取消这些任务 [q] 放弃升级(回车 = 放弃):')).trim().toLowerCase() : 'q';
|
|
2410
|
+
if (choice === 'w') continue;
|
|
2411
|
+
if (choice === 'c') {
|
|
2412
|
+
const live = await askInstance(ctx, 'jobs', { limit: 1 }, { quiet: true });
|
|
2413
|
+
for (const job of live?.running || []) await askInstance(ctx, 'job.cancel', { runId: job.runId }, { quiet: true }).catch(() => null);
|
|
2414
|
+
continue;
|
|
2415
|
+
}
|
|
2416
|
+
await resume();
|
|
2417
|
+
throw new ExitError(1, '已放弃升级,程序恢复接新任务');
|
|
2418
|
+
}
|
|
2419
|
+
}
|
|
2420
|
+
let code;
|
|
2421
|
+
try {
|
|
2422
|
+
code = await npmGlobalInstall(`${PACKAGE_NAME}@${target}`, { ask });
|
|
2423
|
+
} catch (error) {
|
|
2424
|
+
await resume();
|
|
2425
|
+
throw error;
|
|
2426
|
+
}
|
|
2427
|
+
if (code !== 0) {
|
|
2428
|
+
await resume();
|
|
2429
|
+
throw new ExitError(1, `安装失败(退出码 ${code}),仍在使用 ${VERSION}`);
|
|
2430
|
+
}
|
|
1102
2431
|
const service = serviceStatus();
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
2432
|
+
const asService = service.installed && (!instance || instance.service !== 'foreground');
|
|
2433
|
+
// The service through the version just installed: its `service install`
|
|
2434
|
+
// writes the definition from its own template (stop and reload settings
|
|
2435
|
+
// change between versions) and restarts the service.
|
|
2436
|
+
const reinstallService = () =>
|
|
2437
|
+
runCommand([process.execPath, fs.realpathSync(ENTRY), 'service', 'install', ...(process.getuid() === 0 ? ['--allow-root'] : [])]);
|
|
2438
|
+
if (asService) {
|
|
2439
|
+
await reinstallService();
|
|
2440
|
+
if (await waitForVersion(ctx, target, 60_000)) {
|
|
2441
|
+
say(`✓ 已升级到 ${target}:后台服务已按新版本重新安装、启动,并连上了网站`);
|
|
2442
|
+
return 0;
|
|
2443
|
+
}
|
|
2444
|
+
say(`✗ ${target} 没有在 60 秒内正常连上网站,装回 ${VERSION}……`);
|
|
2445
|
+
const back = await npmGlobalInstall(`${PACKAGE_NAME}@${VERSION}`, { ask: () => Promise.resolve(true) }).catch(() => 1);
|
|
2446
|
+
if (back === 0) await reinstallService();
|
|
2447
|
+
throw new ExitError(1, back === 0 ? `升级失败,已装回 ${VERSION}(work-agent-runner logs 查看原因)` : `升级失败,装回 ${VERSION} 也失败了:请手动执行 npm i -g ${PACKAGE_NAME}@${VERSION}`);
|
|
2448
|
+
}
|
|
2449
|
+
if (instance) {
|
|
2450
|
+
// A program in the foreground keeps the old code until restarted.
|
|
2451
|
+
await resume();
|
|
2452
|
+
say(`✓ 已安装 ${target}。前台运行的程序(pid ${instance.pid})还是 ${VERSION}:在它的终端按 Ctrl+C,再运行 work-agent-runner 即可`);
|
|
2453
|
+
return 0;
|
|
2454
|
+
}
|
|
2455
|
+
say(`✓ 已安装 ${target}`);
|
|
2456
|
+
return 0;
|
|
2457
|
+
}
|
|
2458
|
+
|
|
2459
|
+
/**
|
|
2460
|
+
* `uninstall [--purge]` (design 3.21): the service, a running program, the
|
|
2461
|
+
* website's record of this machine, then only what is this program's own.
|
|
2462
|
+
* work-agent's home and the knowledge pool stay.
|
|
2463
|
+
*/
|
|
2464
|
+
async function uninstall(values) {
|
|
2465
|
+
checkSystem();
|
|
2466
|
+
const ctx = loadContext(values, { workRoot: false });
|
|
2467
|
+
const workRoot = ctx.config.workRoot || ctx.paths.runsRoot;
|
|
2468
|
+
const plan = uninstallPlan({ paths: ctx.paths, workRoot, purge: Boolean(values.purge) });
|
|
2469
|
+
say('将要:');
|
|
2470
|
+
say(' · 停止并删除后台服务,停止正在运行的程序');
|
|
2471
|
+
if (ctx.config.token) say(' · 在网站上注销这台机器(网页「执行机器」里随之移除)');
|
|
2472
|
+
for (const item of plan.remove) say(` · 删除 ${item.path}(${item.what})`);
|
|
2473
|
+
for (const item of plan.removeIfEmpty) say(` · ${item.path}:${item.what}`);
|
|
2474
|
+
for (const item of plan.keep) say(` · 保留 ${item.path}(${item.what}${item.size ? `,约 ${(item.size / 1073741824).toFixed(1)} GB` : ''})`);
|
|
2475
|
+
if (!values.yes) {
|
|
2476
|
+
if (!isInteractive()) throw new ExitError(ATTENTION, 'uninstall 需要在终端里确认(脚本里加 --yes)');
|
|
2477
|
+
if (!(await askYesNo('是否继续?', { defaultYes: false }))) {
|
|
2478
|
+
say('已取消');
|
|
2479
|
+
return 0;
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
uninstallService({ say });
|
|
2483
|
+
const instance = await pingInstance(ctx.paths);
|
|
2484
|
+
if (instance) {
|
|
2485
|
+
say(`停止正在运行的程序(pid ${instance.pid},先结束运行中的任务)……`);
|
|
2486
|
+
await askInstance(ctx, 'stop', {}, { quiet: true }).catch(() => null);
|
|
2487
|
+
const deadline = Date.now() + 120_000;
|
|
2488
|
+
while (Date.now() < deadline && isRunnerAlive(lockHolder(ctx.paths.lockFile))) await sleep(500);
|
|
2489
|
+
if (isRunnerAlive(lockHolder(ctx.paths.lockFile))) throw new ExitError(1, '程序没有停下来:请先手动停止它,再运行 uninstall');
|
|
2490
|
+
}
|
|
2491
|
+
if (ctx.config.token) {
|
|
2492
|
+
try {
|
|
2493
|
+
await clientFor(ctx).request('POST', '/deregister', {});
|
|
2494
|
+
say('✓ 已在网站上注销这台机器');
|
|
2495
|
+
} catch (error) {
|
|
2496
|
+
const why =
|
|
2497
|
+
error instanceof ApiError
|
|
2498
|
+
? { 404: '网站还不支持注销', 409: '网站上这台机器还显示在线', 401: '令牌已失效' }[error.status] || error.message
|
|
2499
|
+
: networkReason(error);
|
|
2500
|
+
say(`没能在网站上注销(${why}):请到网页「在线 Agent → 模型配置 → 执行机器」移除这台机器`);
|
|
2501
|
+
}
|
|
2502
|
+
}
|
|
2503
|
+
const outcome = performUninstall(plan);
|
|
2504
|
+
for (const item of outcome.failed) say(`✗ 没能删除 ${item.path},请手动删除`);
|
|
2505
|
+
if (!values.purge && fs.existsSync(ctx.paths.configFile)) say(`配置留在 ${ctx.paths.configFile}(重装后沿用同一台机器);不需要了就删除它`);
|
|
2506
|
+
for (const item of plan.keep.filter((entry) => entry.path !== ctx.paths.configFile)) say(`保留了 ${item.path}:不需要的话手动删除(rm -rf ${item.path})`);
|
|
2507
|
+
say(`最后运行:npm rm -g ${PACKAGE_NAME}`);
|
|
2508
|
+
return outcome.failed.length ? 1 : 0;
|
|
2509
|
+
}
|
|
2510
|
+
|
|
2511
|
+
function readTextFile(file) {
|
|
2512
|
+
try {
|
|
2513
|
+
return fs.readFileSync(file, 'utf8');
|
|
2514
|
+
} catch {
|
|
2515
|
+
return null;
|
|
2516
|
+
}
|
|
2517
|
+
}
|
|
2518
|
+
|
|
2519
|
+
/** `diagnose [-o 文件]` (design 9.5): a redacted .tar.gz to look through and send for help. */
|
|
2520
|
+
async function diagnose(values) {
|
|
2521
|
+
checkSystem();
|
|
2522
|
+
const restarted = await applyProxy();
|
|
2523
|
+
if (restarted !== null) return restarted;
|
|
2524
|
+
const ctx = loadContext(values, { workRoot: false });
|
|
2525
|
+
say('收集中(含一次检查,可能要一会儿)……');
|
|
2526
|
+
const facts = await collectCheckFacts(ctx);
|
|
2527
|
+
const report = assessCheck(facts);
|
|
2528
|
+
const live = await controlRequest(ctx.paths, 'status', {}, { timeoutMs: 10_000 }).catch(() => null);
|
|
2529
|
+
const history = readHistory(ctx.paths.historyFile, { limit: 200 }).reverse();
|
|
2530
|
+
const setupLogs = (() => {
|
|
2531
|
+
try {
|
|
2532
|
+
return fs.readdirSync(ctx.paths.logsDir).filter((name) => /^setup-\d{8}-\d{6}\.log$/.test(name)).sort();
|
|
2533
|
+
} catch {
|
|
2534
|
+
return [];
|
|
2535
|
+
}
|
|
2536
|
+
})();
|
|
2537
|
+
const service = servicePaths();
|
|
2538
|
+
let config = null;
|
|
1108
2539
|
try {
|
|
1109
|
-
|
|
1110
|
-
// jobs from a second process would make the website fail this machine's jobs).
|
|
1111
|
-
await clientFor(ctx).request('GET', '/ping');
|
|
1112
|
-
say('连接测试:正常');
|
|
2540
|
+
config = configForBundle(loadConfig(ctx.paths));
|
|
1113
2541
|
} catch (error) {
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
2542
|
+
config = { error: error.message };
|
|
2543
|
+
}
|
|
2544
|
+
const { files, listing } = bundleFiles([
|
|
2545
|
+
{ name: 'version.txt', content: `work-agent-runner ${VERSION}\nnode ${process.versions.node}\n${process.platform}/${process.arch}\n` },
|
|
2546
|
+
{ name: 'check.json', content: { ...report, capabilities: facts.capabilities, viaInstance: facts.viaInstance } },
|
|
2547
|
+
{ name: 'status.json', content: live || readStatus(ctx.paths.statusFile) },
|
|
2548
|
+
{ name: 'paths.json', content: pathRows(ctx) },
|
|
2549
|
+
{ name: 'history.jsonl', content: history.map((item) => JSON.stringify(item)).join('\n') + (history.length ? '\n' : '') },
|
|
2550
|
+
{ name: 'runner.log', content: lastLines(readTextFile(ctx.paths.logFile), 5000) },
|
|
2551
|
+
{ name: 'setup.log', content: setupLogs.length ? readTextFile(path.join(ctx.paths.logsDir, setupLogs.at(-1))) : null },
|
|
2552
|
+
{ name: 'setup.json', content: readTextFile(ctx.paths.setupFile) },
|
|
2553
|
+
{ name: 'config.json', content: config },
|
|
2554
|
+
{ name: path.basename(service.file), content: readTextFile(service.file) },
|
|
2555
|
+
{ name: 'system.json', content: systemInfo(ctx) },
|
|
2556
|
+
]);
|
|
2557
|
+
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\..*$/, '').replace('T', '-');
|
|
2558
|
+
const file = path.resolve(values.output || `work-agent-runner-diag-${stamp}.tar.gz`);
|
|
2559
|
+
fs.writeFileSync(file, tarGz(files), { mode: 0o600 });
|
|
2560
|
+
say(`已生成 ${file},包含:`);
|
|
2561
|
+
for (const line of listing) say(` ${line}`);
|
|
2562
|
+
say('里面没有接入令牌、API Key 和代理密码;发出之前请自己再看一遍(tar -xzf 解开)。');
|
|
2563
|
+
return 0;
|
|
2564
|
+
}
|
|
2565
|
+
|
|
2566
|
+
async function cleanupCommand(values) {
|
|
2567
|
+
checkSystem();
|
|
2568
|
+
const ctx = loadContext(values, { workRoot: false });
|
|
2569
|
+
const home = ctx.paths.workAgentHome;
|
|
2570
|
+
const live = await askInstance(ctx, 'status', {}, { quiet: true }).catch(() => null);
|
|
2571
|
+
if (live?.jobs?.length) throw new ExitError(1, `程序正在运行 ${live.jobs.length} 个任务,请等它们结束后再清理`);
|
|
2572
|
+
say(`将清空 ${path.join(home, 'tmp')},并删除 ${path.join(home, 'logs')} 里 30 天前的日志。`);
|
|
2573
|
+
say('你手工使用 work-agent 时放在这里的文件也会被删除。');
|
|
2574
|
+
if (!values.yes) {
|
|
2575
|
+
if (!isInteractive()) throw new ExitError(ATTENTION, 'cleanup 需要在终端里确认(脚本里加 --yes)');
|
|
2576
|
+
if (!(await askYesNo('是否继续?', { defaultYes: false }))) {
|
|
2577
|
+
say('已取消');
|
|
2578
|
+
return 0;
|
|
2579
|
+
}
|
|
1123
2580
|
}
|
|
2581
|
+
await withStopOnSignal(ctx, () => ctx.workAgent.cleanup({ say }));
|
|
2582
|
+
say('已清理');
|
|
1124
2583
|
return 0;
|
|
1125
2584
|
}
|
|
1126
2585
|
|
|
@@ -1148,12 +2607,24 @@ async function service(action, values) {
|
|
|
1148
2607
|
args: ['start', ...(values['allow-root'] ? ['--allow-root'] : [])],
|
|
1149
2608
|
say,
|
|
1150
2609
|
});
|
|
2610
|
+
// A user service stops at logout without linger: offer to turn it on.
|
|
2611
|
+
await lingerCheck({ unattended: !isInteractive(), ask: (question) => askYesNo(question), beforeAsk: () => {} });
|
|
1151
2612
|
return 0;
|
|
1152
2613
|
}
|
|
1153
2614
|
if (action === 'uninstall') {
|
|
1154
2615
|
uninstallService({ say });
|
|
1155
2616
|
return 0;
|
|
1156
2617
|
}
|
|
2618
|
+
if (action === 'logs') {
|
|
2619
|
+
// What the service manager kept: also the lines before the program's own log starts.
|
|
2620
|
+
const paths = servicePaths();
|
|
2621
|
+
const [command, args] =
|
|
2622
|
+
paths.kind === 'launchd'
|
|
2623
|
+
? ['tail', ['-n', '100', '-f', paths.logFile]]
|
|
2624
|
+
: ['journalctl', ['--user', '-u', paths.name, '-n', '100', '-f', '--no-pager']];
|
|
2625
|
+
const code = await runCommand([command, ...args]);
|
|
2626
|
+
return code === 130 ? 0 : code;
|
|
2627
|
+
}
|
|
1157
2628
|
if (['start', 'stop', 'restart'].includes(action)) {
|
|
1158
2629
|
try {
|
|
1159
2630
|
controlService(action, { say });
|
|
@@ -1165,11 +2636,20 @@ async function service(action, values) {
|
|
|
1165
2636
|
if (action === 'status') {
|
|
1166
2637
|
const state = serviceStatus();
|
|
1167
2638
|
say(state.installed ? `后台服务:${state.state}(${state.name})` : '后台服务:未安装');
|
|
2639
|
+
if (state.installed && process.platform === 'linux' && lingerEnabled() === false) say('linger 没有开启:退出登录后服务会停止(sudo loginctl enable-linger $USER)');
|
|
1168
2640
|
say(state.logHint);
|
|
1169
2641
|
if (legacyServiceInstalled()) say(LEGACY_SERVICE_HINT);
|
|
2642
|
+
// And what the program itself says, when it answers.
|
|
2643
|
+
const ctx = loadContext(values, { workRoot: false });
|
|
2644
|
+
const snapshot = await controlRequest(ctx.paths, 'status', {}, { timeoutMs: 10_000 }).catch(() => null);
|
|
2645
|
+
if (snapshot) {
|
|
2646
|
+
say('');
|
|
2647
|
+
for (const line of statusLines(snapshot).slice(0, 3)) say(line);
|
|
2648
|
+
say('(完整状态:work-agent-runner status)');
|
|
2649
|
+
}
|
|
1170
2650
|
return 0;
|
|
1171
2651
|
}
|
|
1172
|
-
throw new ExitError(1, '用法:work-agent-runner service install | uninstall | start | stop | restart | status');
|
|
2652
|
+
throw new ExitError(1, '用法:work-agent-runner service install | uninstall | start | stop | restart | status | logs');
|
|
1173
2653
|
}
|
|
1174
2654
|
|
|
1175
2655
|
async function main(argv) {
|
|
@@ -1187,6 +2667,21 @@ async function main(argv) {
|
|
|
1187
2667
|
'token-stdin': { type: 'boolean' },
|
|
1188
2668
|
repos: { type: 'string' },
|
|
1189
2669
|
'no-repos': { type: 'boolean' },
|
|
2670
|
+
'claude-version': { type: 'string' },
|
|
2671
|
+
unattended: { type: 'boolean' },
|
|
2672
|
+
'token-file': { type: 'string' },
|
|
2673
|
+
service: { type: 'boolean' },
|
|
2674
|
+
reset: { type: 'boolean' },
|
|
2675
|
+
to: { type: 'string' },
|
|
2676
|
+
'drain-timeout': { type: 'string' },
|
|
2677
|
+
purge: { type: 'boolean' },
|
|
2678
|
+
output: { type: 'string', short: 'o' },
|
|
2679
|
+
follow: { type: 'boolean', short: 'f' },
|
|
2680
|
+
lines: { type: 'string', short: 'n' },
|
|
2681
|
+
since: { type: 'string' },
|
|
2682
|
+
job: { type: 'string' },
|
|
2683
|
+
failed: { type: 'boolean' },
|
|
2684
|
+
watch: { type: 'boolean', short: 'w' },
|
|
1190
2685
|
|
|
1191
2686
|
yes: { type: 'boolean', short: 'y' },
|
|
1192
2687
|
json: { type: 'boolean' },
|
|
@@ -1200,10 +2695,18 @@ async function main(argv) {
|
|
|
1200
2695
|
const { values, positionals } = parsed;
|
|
1201
2696
|
if (values.version) return say(VERSION) ?? 0;
|
|
1202
2697
|
if (values.help) return say(USAGE) ?? 0;
|
|
1203
|
-
const [command = 'start', action] = positionals;
|
|
2698
|
+
const [command = 'start', action, argument] = positionals;
|
|
1204
2699
|
switch (command) {
|
|
1205
2700
|
case 'start':
|
|
1206
2701
|
return start(values);
|
|
2702
|
+
case 'status':
|
|
2703
|
+
return status(values);
|
|
2704
|
+
case 'jobs':
|
|
2705
|
+
return jobsCommand(values, action, argument);
|
|
2706
|
+
case 'logs':
|
|
2707
|
+
return logs(values);
|
|
2708
|
+
case 'paths':
|
|
2709
|
+
return pathsCommand(values);
|
|
1207
2710
|
case 'login':
|
|
1208
2711
|
return login(values);
|
|
1209
2712
|
case 'logout':
|
|
@@ -1212,10 +2715,19 @@ async function main(argv) {
|
|
|
1212
2715
|
return setup(values);
|
|
1213
2716
|
case 'update':
|
|
1214
2717
|
return update(values);
|
|
2718
|
+
case 'check':
|
|
1215
2719
|
case 'doctor':
|
|
1216
|
-
return
|
|
1217
|
-
case '
|
|
1218
|
-
return
|
|
2720
|
+
return check(values);
|
|
2721
|
+
case 'cleanup':
|
|
2722
|
+
return cleanupCommand(values);
|
|
2723
|
+
case 'upgrade':
|
|
2724
|
+
return upgrade(values);
|
|
2725
|
+
case 'uninstall':
|
|
2726
|
+
return uninstall(values);
|
|
2727
|
+
case 'diagnose':
|
|
2728
|
+
return diagnose(values);
|
|
2729
|
+
case 'reload':
|
|
2730
|
+
return reload(values);
|
|
1219
2731
|
case 'service':
|
|
1220
2732
|
return service(action, values);
|
|
1221
2733
|
case 'version':
|