@online-tools/work-agent-runner 0.1.0-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 +251 -156
- package/bin/main.mjs +1124 -239
- package/lib/check.mjs +391 -0
- package/lib/claude-cli.mjs +8 -0
- package/lib/claude-install.mjs +221 -0
- package/lib/config.mjs +9 -0
- package/lib/connection.mjs +49 -3
- package/lib/diagnose.mjs +82 -0
- package/lib/doctor.mjs +19 -3
- package/lib/errors.mjs +9 -0
- package/lib/jobs.mjs +75 -34
- package/lib/log.mjs +6 -1
- package/lib/service.mjs +42 -6
- package/lib/setup-state.mjs +119 -0
- package/lib/setup.mjs +4 -1
- package/lib/uninstall.mjs +122 -0
- package/lib/views.mjs +26 -0
- package/lib/work-agent.mjs +10 -5
- package/package.json +2 -2
package/bin/main.mjs
CHANGED
|
@@ -32,6 +32,7 @@ import {
|
|
|
32
32
|
adoptLegacyState,
|
|
33
33
|
configPaths,
|
|
34
34
|
effectiveSettings,
|
|
35
|
+
isInside,
|
|
35
36
|
legacyConfigPending,
|
|
36
37
|
legacyLockFile,
|
|
37
38
|
loadConfig,
|
|
@@ -43,13 +44,24 @@ import {
|
|
|
43
44
|
} from '../lib/config.mjs';
|
|
44
45
|
import { UPDATE_COMMAND, fatalFor, runConnection } from '../lib/connection.mjs';
|
|
45
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';
|
|
46
58
|
import { SANDBOX_DOCS, runDoctor, which } from '../lib/doctor.mjs';
|
|
47
59
|
import { cleanRunsDir } from '../lib/fs-safe.mjs';
|
|
48
60
|
import { ApiError, createClient, normalizeServerUrl, proxyMode } from '../lib/http.mjs';
|
|
49
61
|
import { FEATURE_LABELS, JobManager } from '../lib/jobs.mjs';
|
|
50
62
|
import { LockedError, acquireLock, isRunnerAlive, lockHolder } from '../lib/lock.mjs';
|
|
51
63
|
import { NODE_REQUIREMENT, nodeSupported } from '../lib/node-runtime.cjs';
|
|
52
|
-
import { createLogger } from '../lib/log.mjs';
|
|
64
|
+
import { createLogger, redactUrl } from '../lib/log.mjs';
|
|
53
65
|
import { Maintenance } from '../lib/maintenance.mjs';
|
|
54
66
|
import { CancelledError, askText, askYesNo, isInteractive, readHidden, readStdin } from '../lib/prompt.mjs';
|
|
55
67
|
import {
|
|
@@ -57,17 +69,21 @@ import {
|
|
|
57
69
|
controlService,
|
|
58
70
|
installService,
|
|
59
71
|
legacyServiceInstalled,
|
|
72
|
+
lingerEnabled,
|
|
60
73
|
removeLegacyService,
|
|
61
74
|
serviceExitCode,
|
|
62
75
|
servicePaths,
|
|
63
76
|
serviceStatus,
|
|
64
77
|
uninstallService,
|
|
65
78
|
} from '../lib/service.mjs';
|
|
66
|
-
import { DEFAULT_REQUIRED_TOOLS, npmPrefixWritable, planSetup, runSetup } from '../lib/setup.mjs';
|
|
67
|
-
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';
|
|
68
84
|
import { StateStore, countResults, matchesRunId, readHistory, readStatus } from '../lib/state.mjs';
|
|
69
|
-
import { collectSystemInfo
|
|
70
|
-
import { jobDetailLines, jobsLines, pathsLines, statusLines } from '../lib/views.mjs';
|
|
85
|
+
import { collectSystemInfo } from '../lib/system-info.mjs';
|
|
86
|
+
import { checkLines, jobDetailLines, jobsLines, pathsLines, statusLines } from '../lib/views.mjs';
|
|
71
87
|
import {
|
|
72
88
|
WorkAgent,
|
|
73
89
|
freeBytes,
|
|
@@ -87,13 +103,6 @@ const LEGACY_SERVICE_HINT = `旧版程序 ${LEGACY_NAME} 的后台服务还在
|
|
|
87
103
|
// A terminal command waits this long for the service to be done with the clone.
|
|
88
104
|
const TERMINAL_LOCK_WAIT_MS = 2 * 60_000;
|
|
89
105
|
|
|
90
|
-
// Which tools each feature needs — for the messages here only; the website decides.
|
|
91
|
-
const FEATURE_TOOLS = {
|
|
92
|
-
'pr-desc-issue-gen': ['git', 'curl', 'python3'],
|
|
93
|
-
'ascend-code-review': ['git', 'python3', 'curl', 'jq', 'sed'],
|
|
94
|
-
'code-review-flash': ['python3', 'git', 'base64'],
|
|
95
|
-
'cann-knowledge': ['rg'],
|
|
96
|
-
};
|
|
97
106
|
|
|
98
107
|
const USAGE = `GitCode Agent 执行机器 ${VERSION}
|
|
99
108
|
|
|
@@ -112,16 +121,30 @@ const USAGE = `GitCode Agent 执行机器 ${VERSION}
|
|
|
112
121
|
login [--new-id] [--token-stdin] [--name <名称>]
|
|
113
122
|
输入接入令牌(校验通过才保存);--new-id 重新生成机器标识
|
|
114
123
|
logout 清除本机保存的令牌(机器标识保留)
|
|
115
|
-
setup [--yes] [--repos
|
|
116
|
-
|
|
117
|
-
|
|
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
|
|
118
131
|
update 立即更新 work-agent 仓库和知识仓(程序在运行时由它来做,
|
|
119
132
|
知识仓在没有任务时更新)
|
|
120
|
-
|
|
133
|
+
check [--json] 逐项检查系统、网络、依赖、沙箱、Claude Code、仓库、服务和网站,
|
|
134
|
+
给出影响和处理办法(退出码:0 全部可用,1 部分功能不可用,
|
|
135
|
+
2 都不能运行;doctor 是它的旧名字)
|
|
121
136
|
cleanup [--yes] 清空 work-agent 的共享临时目录、删除 30 天前的日志(会先确认)
|
|
122
137
|
reload 让运行中的程序重新读取 config.json 里的维护时间、限额和隔离设置
|
|
123
|
-
|
|
124
|
-
|
|
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
|
+
看服务管理器记下的输出
|
|
125
148
|
version 显示版本
|
|
126
149
|
|
|
127
150
|
选项:
|
|
@@ -140,7 +163,21 @@ class ExitError extends Error {
|
|
|
140
163
|
}
|
|
141
164
|
}
|
|
142
165
|
|
|
143
|
-
|
|
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
|
+
}
|
|
144
181
|
const log = createLogger();
|
|
145
182
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
146
183
|
|
|
@@ -414,8 +451,17 @@ function networkReason(error) {
|
|
|
414
451
|
|
|
415
452
|
/** doctor + remembering a claude found outside PATH. `probe: false`: no sandbox check (seconds faster). */
|
|
416
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
|
+
}
|
|
417
462
|
const result = await runDoctor({
|
|
418
|
-
configuredClaude:
|
|
463
|
+
configuredClaude: configured,
|
|
464
|
+
managedDir: ctx.paths.claudeDir,
|
|
419
465
|
workRoot: ctx.workRoot,
|
|
420
466
|
realHome: ctx.realHome,
|
|
421
467
|
workAgent: ctx.workAgent,
|
|
@@ -458,11 +504,13 @@ function connectFailure(error, server) {
|
|
|
458
504
|
* Asks for the token (or reads it from stdin), checks it with POST /connect
|
|
459
505
|
* and saves it only then. Up to 3 tries in a terminal.
|
|
460
506
|
*/
|
|
461
|
-
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;
|
|
462
510
|
if (!fromStdin && !isInteractive()) throw new ExitError(ATTENTION, '还没有接入令牌:请先在终端运行 work-agent-runner login');
|
|
463
511
|
if (!fromStdin) say('请在「在线 Agent → 模型配置 → 接入令牌」复制令牌并粘贴(输入不显示):');
|
|
464
512
|
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
|
465
|
-
const token = fromStdin ? await readStdin() : await readHidden('令牌:');
|
|
513
|
+
const token = given !== null ? given : fromStdin ? await readStdin() : await readHidden('令牌:');
|
|
466
514
|
if (!TOKEN_PATTERN.test(token)) {
|
|
467
515
|
if (fromStdin) throw new ExitError(ATTENTION, '令牌格式不正确(应为 gcm_ 开头的 47 个字符)');
|
|
468
516
|
say('令牌格式不正确(应为 gcm_ 开头的 47 个字符),请重新粘贴');
|
|
@@ -630,70 +678,6 @@ function splitRepos(value) {
|
|
|
630
678
|
return names;
|
|
631
679
|
}
|
|
632
680
|
|
|
633
|
-
/**
|
|
634
|
-
* Offers the knowledge pool — the repositories of work-agent's own essential
|
|
635
|
-
* list — in a terminal only. Never downloads anything without a yes: `--repos`
|
|
636
|
-
* picks the repositories instead, `--no-repos` skips the question. A download
|
|
637
|
-
* only adds repositories, so a running service keeps taking jobs meanwhile;
|
|
638
|
-
* with the program running, it does the download (and a Ctrl+C here does not
|
|
639
|
-
* stop it).
|
|
640
|
-
*/
|
|
641
|
-
async function offerPool(ctx, values, { delegate = true } = {}) {
|
|
642
|
-
if (values['no-repos']) return;
|
|
643
|
-
const wanted = values.repos === undefined ? null : splitRepos(values.repos);
|
|
644
|
-
const { poolDir, workAgentHome } = ctx.paths;
|
|
645
|
-
const pool = ctx.workAgent.poolState();
|
|
646
|
-
if (pool.incomplete.length) {
|
|
647
|
-
say(`知识仓 ${pool.incomplete.join('、')} 不完整:请先删除 ${poolDir} 下这些目录`);
|
|
648
|
-
return;
|
|
649
|
-
}
|
|
650
|
-
if (pool.repos && values.repos === undefined) {
|
|
651
|
-
say(`知识仓已就绪(${poolDir},${pool.repos} 个仓)`);
|
|
652
|
-
return;
|
|
653
|
-
}
|
|
654
|
-
const busy = poolBusyInfo(ctx.paths);
|
|
655
|
-
if (busy) {
|
|
656
|
-
say(`另一个进程(pid ${busy.pid})正在${busy.kind === 'init' ? '下载' : '更新'}知识仓,请等它结束后再运行 work-agent-runner setup`);
|
|
657
|
-
return;
|
|
658
|
-
}
|
|
659
|
-
if (wanted) say(`将下载到 ${poolDir}:${wanted.join('、')}`);
|
|
660
|
-
else {
|
|
661
|
-
say(`知识仓用于「代码检视」查 CANN / AscendC 的权威文档,下载到 ${poolDir}`);
|
|
662
|
-
// The list file only exists once work-agent.py has run init at least once.
|
|
663
|
-
const listed = ctx.workAgent.essentialRepos();
|
|
664
|
-
if (listed.length) say(`要下载的仓(${ctx.workAgent.essentialFile}):${listed.join('、')}`);
|
|
665
|
-
else say(`要下载的是 work-agent 的必要仓清单,首次初始化时会生成 ${ctx.workAgent.essentialFile},之后可以自己编辑再运行 setup`);
|
|
666
|
-
const free = freeBytes(poolDir);
|
|
667
|
-
say(`仓比较多,下载可能要很久;该磁盘当前可用 ${(free / 1073741824).toFixed(1)} GB。不下载也能用,只是相关规范不做检查。`);
|
|
668
|
-
}
|
|
669
|
-
if (!values.yes && !(await askYesNo('是否现在下载?'))) {
|
|
670
|
-
say('已跳过;以后随时可以再运行 work-agent-runner setup');
|
|
671
|
-
return;
|
|
672
|
-
}
|
|
673
|
-
if (delegate) {
|
|
674
|
-
try {
|
|
675
|
-
const done = await askInstance(ctx, 'pool.init', { repos: wanted });
|
|
676
|
-
if (done) {
|
|
677
|
-
say(`知识仓就绪(${done.repos} 个仓)`);
|
|
678
|
-
return;
|
|
679
|
-
}
|
|
680
|
-
} catch (error) {
|
|
681
|
-
say(`下载知识仓失败:${error.message}`);
|
|
682
|
-
return;
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
|
-
const finished = markPoolBusy(ctx.paths, 'init');
|
|
686
|
-
try {
|
|
687
|
-
await withStopOnSignal(ctx, () => ctx.workAgent.initPool({ repos: wanted, say }));
|
|
688
|
-
prepareWorkAgentHome(workAgentHome, { poolDir: ctx.workAgent.mountablePool(), link: ctx.paths.workAgentLink });
|
|
689
|
-
} catch (error) {
|
|
690
|
-
if (error instanceof ExitError) throw error;
|
|
691
|
-
say(`下载知识仓失败:${error.message}`);
|
|
692
|
-
} finally {
|
|
693
|
-
finished();
|
|
694
|
-
}
|
|
695
|
-
}
|
|
696
|
-
|
|
697
681
|
function neededBy(tool) {
|
|
698
682
|
if (tool === 'bwrap' || tool === 'socat') return '沙箱需要(所有功能)';
|
|
699
683
|
const features = Object.entries(FEATURE_TOOLS).filter(([, tools]) => tools.includes(tool)).map(([feature]) => FEATURE_LABELS[feature]);
|
|
@@ -754,9 +738,99 @@ function setupPlan(result, reply, { poolWanted = false } = {}) {
|
|
|
754
738
|
sudo: which('sudo'),
|
|
755
739
|
npm,
|
|
756
740
|
npmWritable,
|
|
741
|
+
// Installed by claudeStep() instead, where this program has a platform package.
|
|
742
|
+
managedClaude: Boolean(claudePlatform()),
|
|
757
743
|
});
|
|
758
744
|
}
|
|
759
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
|
+
|
|
760
834
|
/** The pid of a running instance of this program home other than this process, or 0. */
|
|
761
835
|
function runningInstance(ctx) {
|
|
762
836
|
const holder = lockHolder(ctx.paths.lockFile);
|
|
@@ -786,6 +860,7 @@ async function start(values) {
|
|
|
786
860
|
}
|
|
787
861
|
// Nothing is written before the lock: another instance may be running.
|
|
788
862
|
const ctx = loadContext(values, { workRoot: false, persist: false, instance: true });
|
|
863
|
+
let startService = false;
|
|
789
864
|
let lock;
|
|
790
865
|
try {
|
|
791
866
|
lock = acquireLock(ctx.paths.lockFile);
|
|
@@ -814,57 +889,48 @@ async function start(values) {
|
|
|
814
889
|
throw new ExitError(ATTENTION, '还没有接入令牌:请先在终端运行 work-agent-runner login');
|
|
815
890
|
}
|
|
816
891
|
if (!ctx.config.token || (!ctx.config.setupDone && interactive)) {
|
|
817
|
-
// A person is at the terminal for the first run:
|
|
818
|
-
//
|
|
819
|
-
|
|
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;
|
|
897
|
+
} else {
|
|
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 });
|
|
820
903
|
}
|
|
821
|
-
// Known machine: online within seconds, the slow checks (sandbox, clone)
|
|
822
|
-
// follow in the background — jobs that arrive meanwhile wait for them.
|
|
823
|
-
say('检查依赖……');
|
|
824
|
-
const result = await quickChecks(ctx);
|
|
825
|
-
return await serve(ctx, { client: clientFor(ctx), initial: result, checksPending: true });
|
|
826
904
|
} finally {
|
|
827
905
|
lock.release();
|
|
828
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;
|
|
829
915
|
}
|
|
830
916
|
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
if (
|
|
847
|
-
|
|
848
|
-
plan: setupPlan(result, reply, { poolWanted: !values['no-repos'] }),
|
|
849
|
-
interactive: true,
|
|
850
|
-
confirm: (question) => askYesNo(question),
|
|
851
|
-
say,
|
|
852
|
-
});
|
|
853
|
-
// Asked once: missing items stay visible in status and on the website.
|
|
854
|
-
saveField(ctx, 'setupDone', true);
|
|
855
|
-
if (outcome.ran) {
|
|
856
|
-
say('重新检查……');
|
|
857
|
-
result = await doctorFor(ctx);
|
|
858
|
-
printDoctor(result);
|
|
859
|
-
}
|
|
860
|
-
// The first clone may have failed for want of git, which setup just installed.
|
|
861
|
-
await ensureClone(ctx);
|
|
862
|
-
// The same question `setup` asks, so a first run settles everything.
|
|
863
|
-
await offerPool(ctx, values, { delegate: false });
|
|
864
|
-
result = await doctorFor(ctx);
|
|
865
|
-
reply = await connectSaved(ctx, client, result.capabilities);
|
|
866
|
-
}
|
|
867
|
-
return serve(ctx, { client, initial: result, reply });
|
|
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) });
|
|
868
934
|
}
|
|
869
935
|
|
|
870
936
|
/**
|
|
@@ -878,12 +944,16 @@ async function serve(ctx, { client, initial, reply = null, checksPending = false
|
|
|
878
944
|
const startedAt = new Date().toISOString();
|
|
879
945
|
const settings = () => effectiveSettings(ctx.config);
|
|
880
946
|
const state = new StateStore({ statusFile: ctx.paths.statusFile, historyFile: ctx.paths.historyFile });
|
|
881
|
-
|
|
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);
|
|
882
950
|
let role = reply?.role === 'server' ? 'server' : 'user';
|
|
883
951
|
let confirmed = reply ? reply.confirmed !== false : true;
|
|
884
952
|
let outdated = Boolean(reply?.outdated);
|
|
885
953
|
let registeredName = reply?.name || '';
|
|
886
954
|
let ready = !checksPending;
|
|
955
|
+
// `upgrade` drains: no new jobs, the running ones finish.
|
|
956
|
+
let draining = false;
|
|
887
957
|
let controlSocket = '';
|
|
888
958
|
let degraded = [];
|
|
889
959
|
const connection = { server: ctx.server, connected: false, since: '', lastHeartbeatAt: '', lastError: '' };
|
|
@@ -911,21 +981,45 @@ async function serve(ctx, { client, initial, reply = null, checksPending = false
|
|
|
911
981
|
if (role === 'server') return { isolation: 'per-run', keep: settings().limits.archiveDays > 0 ? 'archive' : 'none' };
|
|
912
982
|
return settings().isolation === 'per-run' ? { isolation: 'per-run', keep: 'merge' } : { isolation: 'shared', keep: 'none' };
|
|
913
983
|
};
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
if (
|
|
918
|
-
if (
|
|
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
|
+
}
|
|
919
994
|
const free = freeBytes(path.join(ctx.workRoot, 'runs'));
|
|
920
|
-
if (free && free < settings().limits.minFreeBytes) return {
|
|
921
|
-
if (!confirmed) return {
|
|
922
|
-
if (outdated) return {
|
|
923
|
-
return {
|
|
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
|
+
}),
|
|
924
1013
|
};
|
|
925
1014
|
let maintenance = null;
|
|
926
1015
|
let jobs = null;
|
|
927
1016
|
const publish = () => {
|
|
928
1017
|
if (!jobs) return;
|
|
1018
|
+
const taking = JSON.stringify(takingJobs());
|
|
1019
|
+
if (taking !== lastTaking) {
|
|
1020
|
+
lastTaking = taking;
|
|
1021
|
+
beatNow();
|
|
1022
|
+
}
|
|
929
1023
|
const info = systemInfo(ctx);
|
|
930
1024
|
state.set({
|
|
931
1025
|
instance: { pid: process.pid, startedAt, version: VERSION, node: process.versions.node, service: process.env.GC_RUNNER_SERVICE || 'foreground' },
|
|
@@ -954,7 +1048,7 @@ async function serve(ctx, { client, initial, reply = null, checksPending = false
|
|
|
954
1048
|
};
|
|
955
1049
|
const recheck = async () => {
|
|
956
1050
|
const fresh = await doctorFor(ctx);
|
|
957
|
-
capabilities = fresh.capabilities;
|
|
1051
|
+
capabilities = withLimits(fresh.capabilities);
|
|
958
1052
|
if (fresh.claude.path) jobs.claudePath = fresh.claude.path;
|
|
959
1053
|
refreshDegraded();
|
|
960
1054
|
return fresh;
|
|
@@ -976,7 +1070,7 @@ async function serve(ctx, { client, initial, reply = null, checksPending = false
|
|
|
976
1070
|
gate: async ({ isCancelled, timeoutMs, onWait }) => {
|
|
977
1071
|
const deadline = Date.now() + timeoutMs;
|
|
978
1072
|
if (!ready) {
|
|
979
|
-
onWait('等待启动检查完成后开始');
|
|
1073
|
+
onWait('waiting_starting', '等待启动检查完成后开始');
|
|
980
1074
|
while (!ready && !isCancelled() && Date.now() < deadline) await sleep(500);
|
|
981
1075
|
if (!ready && !isCancelled()) {
|
|
982
1076
|
return { ok: false, code: 'E3201', message: '执行机器的启动检查还没有完成,任务未执行,请稍后重试' };
|
|
@@ -1009,7 +1103,7 @@ async function serve(ctx, { client, initial, reply = null, checksPending = false
|
|
|
1009
1103
|
|
|
1010
1104
|
// The local control interface: what terminal commands ask this instance.
|
|
1011
1105
|
const handlers = {
|
|
1012
|
-
ping: () => ({ pid: process.pid, version: VERSION, programHome: ctx.paths.baseDir }),
|
|
1106
|
+
ping: () => ({ pid: process.pid, version: VERSION, programHome: ctx.paths.baseDir, service: process.env.GC_RUNNER_SERVICE || 'foreground' }),
|
|
1013
1107
|
status: () => {
|
|
1014
1108
|
refreshDegraded();
|
|
1015
1109
|
state.flush();
|
|
@@ -1076,9 +1170,23 @@ async function serve(ctx, { client, initial, reply = null, checksPending = false
|
|
|
1076
1170
|
features: answer?.features || null,
|
|
1077
1171
|
outdated: Boolean(answer?.outdated),
|
|
1078
1172
|
confirmed: answer ? answer.confirmed !== false : null,
|
|
1173
|
+
minClaudeVersion: answer?.minClaudeVersion || '',
|
|
1079
1174
|
note,
|
|
1080
1175
|
};
|
|
1081
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
|
+
},
|
|
1082
1190
|
// `reload`: what applies without a restart (the next job, the next schedule).
|
|
1083
1191
|
'config.reload': () => {
|
|
1084
1192
|
const fresh = loadConfig(ctx.paths);
|
|
@@ -1091,6 +1199,7 @@ async function serve(ctx, { client, initial, reply = null, checksPending = false
|
|
|
1091
1199
|
}
|
|
1092
1200
|
jobs.jobWaitMs = settings().limits.jobWaitMaxMinutes * 60_000;
|
|
1093
1201
|
jobs.minFreeBytes = settings().limits.minFreeBytes;
|
|
1202
|
+
capabilities = withLimits(capabilities);
|
|
1094
1203
|
if (changed.includes('maintenance')) {
|
|
1095
1204
|
maintenance.scheduleRepo();
|
|
1096
1205
|
maintenance.schedulePool();
|
|
@@ -1127,10 +1236,21 @@ async function serve(ctx, { client, initial, reply = null, checksPending = false
|
|
|
1127
1236
|
};
|
|
1128
1237
|
process.on('SIGINT', onSignal);
|
|
1129
1238
|
process.on('SIGTERM', onSignal);
|
|
1130
|
-
//
|
|
1131
|
-
//
|
|
1132
|
-
//
|
|
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.
|
|
1133
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
|
+
}
|
|
1134
1254
|
for (const stream of [process.stdout, process.stderr]) stream.on('error', () => {});
|
|
1135
1255
|
onSignal('SIGHUP');
|
|
1136
1256
|
});
|
|
@@ -1204,6 +1324,10 @@ async function serve(ctx, { client, initial, reply = null, checksPending = false
|
|
|
1204
1324
|
confirmed,
|
|
1205
1325
|
heartbeatMs: reply.heartbeatMs,
|
|
1206
1326
|
signal: controller.signal,
|
|
1327
|
+
selfReport,
|
|
1328
|
+
bindBeat: (beat) => {
|
|
1329
|
+
beatNow = beat;
|
|
1330
|
+
},
|
|
1207
1331
|
// Connected = the control channel is open (jobs only come through it).
|
|
1208
1332
|
onStatus: ({ confirmed: nowConfirmed, ...patch }) => {
|
|
1209
1333
|
Object.assign(connection, patch);
|
|
@@ -1279,60 +1403,400 @@ function logout(values) {
|
|
|
1279
1403
|
return 0;
|
|
1280
1404
|
}
|
|
1281
1405
|
|
|
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 } });
|
|
1411
|
+
|
|
1412
|
+
/**
|
|
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).
|
|
1417
|
+
*/
|
|
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;
|
|
1439
|
+
}
|
|
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;
|
|
1477
|
+
}
|
|
1478
|
+
if (!(await flow.ask('是否现在开启 linger(需要 sudo)?'))) {
|
|
1479
|
+
say(`以后可以让管理员执行:sudo loginctl enable-linger ${user}`);
|
|
1480
|
+
return;
|
|
1481
|
+
}
|
|
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}`);
|
|
1485
|
+
}
|
|
1486
|
+
|
|
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). */
|
|
1282
1765
|
async function setup(values) {
|
|
1283
1766
|
checkSystem();
|
|
1284
1767
|
const restarted = await applyProxy();
|
|
1285
1768
|
if (restarted !== null) return restarted;
|
|
1286
|
-
|
|
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);
|
|
1287
1773
|
const ctx = loadContext(values);
|
|
1288
|
-
const
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
const repo = await askInstance(ctx, 'repo.refresh');
|
|
1292
|
-
say(repo.ok ? `✓ work-agent ${repo.commit.slice(0, 7)}(由运行中的程序更新)` : `✗ work-agent 仓库不可用:${repo.reason}`);
|
|
1293
|
-
} else printWorkAgent(await refreshWorkAgent(ctx));
|
|
1294
|
-
say('检查依赖和沙箱……');
|
|
1295
|
-
let result = await doctorFor(ctx);
|
|
1296
|
-
let client = null;
|
|
1297
|
-
let reply = null;
|
|
1298
|
-
if (ctx.config.token) {
|
|
1299
|
-
client = clientFor(ctx);
|
|
1300
|
-
try {
|
|
1301
|
-
// The requirements; with the program running it reports this machine itself.
|
|
1302
|
-
reply = instance ? await client.request('GET', '/ping') : await connect(ctx, client, result.capabilities);
|
|
1303
|
-
} catch (error) {
|
|
1304
|
-
say(`无法从网站读取要求(${error.message}),按默认要求检查`);
|
|
1305
|
-
client = null;
|
|
1306
|
-
}
|
|
1307
|
-
}
|
|
1308
|
-
printDoctor(result);
|
|
1309
|
-
const poolWanted = !values['no-repos'];
|
|
1310
|
-
const outcome = await runSetup({
|
|
1311
|
-
plan: setupPlan(result, reply, { poolWanted }),
|
|
1312
|
-
interactive: true,
|
|
1313
|
-
yes: Boolean(values.yes),
|
|
1314
|
-
confirm: (question) => askYesNo(question),
|
|
1315
|
-
say,
|
|
1316
|
-
});
|
|
1774
|
+
const flow = setupFlow(ctx, values, { unattended });
|
|
1775
|
+
flow.out(`GitCode Agent 执行机器 ${VERSION} · 设置`);
|
|
1776
|
+
const finished = await runSetupSteps(ctx, flow);
|
|
1317
1777
|
saveField(ctx, 'setupDone', true);
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
}
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
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;
|
|
1336
1800
|
}
|
|
1337
1801
|
|
|
1338
1802
|
/**
|
|
@@ -1400,53 +1864,174 @@ async function update(values) {
|
|
|
1400
1864
|
return failed ? 1 : 0;
|
|
1401
1865
|
}
|
|
1402
1866
|
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
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;
|
|
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;
|
|
1409
1967
|
if (delegated) {
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
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
|
+
});
|
|
1424
1985
|
}
|
|
1425
1986
|
const result = await doctorFor(ctx);
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1987
|
+
const repo = ctx.workAgent.state();
|
|
1988
|
+
const website = { token: Boolean(config.token) };
|
|
1989
|
+
let minVersion = '';
|
|
1990
|
+
if (config.token) {
|
|
1429
1991
|
try {
|
|
1430
1992
|
// Also brings the website's copy of this machine's capabilities up to date.
|
|
1431
|
-
reply = await connect(ctx, clientFor(ctx), result.capabilities);
|
|
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 || '';
|
|
1432
1996
|
} catch (error) {
|
|
1433
|
-
|
|
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)})`;
|
|
1434
2000
|
}
|
|
1435
|
-
}
|
|
1436
|
-
|
|
1437
|
-
|
|
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);
|
|
1438
2027
|
if (values.json) {
|
|
1439
|
-
say(JSON.stringify({ version: VERSION, capabilities:
|
|
1440
|
-
return
|
|
2028
|
+
say(JSON.stringify({ version: VERSION, ...report, capabilities: facts.capabilities, viaInstance: facts.viaInstance }, null, 2));
|
|
2029
|
+
return report.exitCode;
|
|
1441
2030
|
}
|
|
1442
|
-
say(
|
|
1443
|
-
say(
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
printFeatures(reply);
|
|
1447
|
-
if (reply?.confirmed === false) say('这台机器还没有在网页上确认,确认后才会收到任务(在线 Agent → 模型配置 → 执行机器)');
|
|
1448
|
-
if (note) say(note);
|
|
1449
|
-
return 0;
|
|
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;
|
|
1450
2035
|
}
|
|
1451
2036
|
|
|
1452
2037
|
/**
|
|
@@ -1628,10 +2213,8 @@ async function logs(values) {
|
|
|
1628
2213
|
}
|
|
1629
2214
|
}
|
|
1630
2215
|
|
|
1631
|
-
/**
|
|
1632
|
-
function
|
|
1633
|
-
checkSystem();
|
|
1634
|
-
const ctx = loadContext(values, { workRoot: false });
|
|
2216
|
+
/** Every directory this program uses, and whether it is fine: [{ label, path, note, free }]. */
|
|
2217
|
+
function pathRows(ctx) {
|
|
1635
2218
|
const { paths, config } = ctx;
|
|
1636
2219
|
const uid = process.getuid();
|
|
1637
2220
|
const exists = (target) => fs.existsSync(target);
|
|
@@ -1696,6 +2279,13 @@ function pathsCommand(values) {
|
|
|
1696
2279
|
{ label: '托管 Node', path: exists(paths.nodeDir) ? paths.nodeDir : '', note: exists(paths.nodeDir) ? fs.readdirSync(paths.nodeDir).filter((name) => name.startsWith('v')).join('、') : '不需要(系统 Node 满足要求)' },
|
|
1697
2280
|
{ label: '后台服务定义', path: service.file, note: exists(service.file) ? '已安装' : '未安装' },
|
|
1698
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 }));
|
|
1699
2289
|
if (values.json) {
|
|
1700
2290
|
say(JSON.stringify(rows, null, 2));
|
|
1701
2291
|
return 0;
|
|
@@ -1715,6 +2305,264 @@ async function reload(values) {
|
|
|
1715
2305
|
return 0;
|
|
1716
2306
|
}
|
|
1717
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
|
+
}
|
|
2431
|
+
const service = serviceStatus();
|
|
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;
|
|
2539
|
+
try {
|
|
2540
|
+
config = configForBundle(loadConfig(ctx.paths));
|
|
2541
|
+
} catch (error) {
|
|
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
|
+
|
|
1718
2566
|
async function cleanupCommand(values) {
|
|
1719
2567
|
checkSystem();
|
|
1720
2568
|
const ctx = loadContext(values, { workRoot: false });
|
|
@@ -1759,12 +2607,24 @@ async function service(action, values) {
|
|
|
1759
2607
|
args: ['start', ...(values['allow-root'] ? ['--allow-root'] : [])],
|
|
1760
2608
|
say,
|
|
1761
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: () => {} });
|
|
1762
2612
|
return 0;
|
|
1763
2613
|
}
|
|
1764
2614
|
if (action === 'uninstall') {
|
|
1765
2615
|
uninstallService({ say });
|
|
1766
2616
|
return 0;
|
|
1767
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
|
+
}
|
|
1768
2628
|
if (['start', 'stop', 'restart'].includes(action)) {
|
|
1769
2629
|
try {
|
|
1770
2630
|
controlService(action, { say });
|
|
@@ -1776,11 +2636,20 @@ async function service(action, values) {
|
|
|
1776
2636
|
if (action === 'status') {
|
|
1777
2637
|
const state = serviceStatus();
|
|
1778
2638
|
say(state.installed ? `后台服务:${state.state}(${state.name})` : '后台服务:未安装');
|
|
2639
|
+
if (state.installed && process.platform === 'linux' && lingerEnabled() === false) say('linger 没有开启:退出登录后服务会停止(sudo loginctl enable-linger $USER)');
|
|
1779
2640
|
say(state.logHint);
|
|
1780
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
|
+
}
|
|
1781
2650
|
return 0;
|
|
1782
2651
|
}
|
|
1783
|
-
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');
|
|
1784
2653
|
}
|
|
1785
2654
|
|
|
1786
2655
|
async function main(argv) {
|
|
@@ -1798,6 +2667,15 @@ async function main(argv) {
|
|
|
1798
2667
|
'token-stdin': { type: 'boolean' },
|
|
1799
2668
|
repos: { type: 'string' },
|
|
1800
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' },
|
|
1801
2679
|
follow: { type: 'boolean', short: 'f' },
|
|
1802
2680
|
lines: { type: 'string', short: 'n' },
|
|
1803
2681
|
since: { type: 'string' },
|
|
@@ -1837,10 +2715,17 @@ async function main(argv) {
|
|
|
1837
2715
|
return setup(values);
|
|
1838
2716
|
case 'update':
|
|
1839
2717
|
return update(values);
|
|
2718
|
+
case 'check':
|
|
1840
2719
|
case 'doctor':
|
|
1841
|
-
return
|
|
2720
|
+
return check(values);
|
|
1842
2721
|
case 'cleanup':
|
|
1843
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);
|
|
1844
2729
|
case 'reload':
|
|
1845
2730
|
return reload(values);
|
|
1846
2731
|
case 'service':
|