@online-tools/work-agent-runner 0.0.4-alpha-1 → 0.1.0-alpha-1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +127 -25
- package/bin/main.mjs +1124 -246
- package/lib/config.mjs +250 -40
- package/lib/connection.mjs +38 -1
- package/lib/control.mjs +330 -0
- package/lib/doctor.mjs +3 -1
- package/lib/errors.mjs +34 -0
- package/lib/fs-safe.mjs +163 -0
- package/lib/jobs.mjs +402 -60
- package/lib/lock.mjs +114 -15
- package/lib/log.mjs +95 -7
- package/lib/maintenance.mjs +394 -0
- package/lib/sandbox.mjs +61 -9
- package/lib/service.mjs +85 -26
- package/lib/skill-tree.mjs +24 -6
- package/lib/state.mjs +145 -0
- package/lib/views.mjs +234 -0
- package/lib/work-agent.mjs +397 -77
- package/package.json +1 -1
package/bin/main.mjs
CHANGED
|
@@ -3,10 +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
|
-
// root, another instance, the old gitcode-agent-runner still running
|
|
9
|
-
// services do not restart on 78
|
|
14
|
+
// root, another instance, the old gitcode-agent-runner still running, a
|
|
15
|
+
// directory that is not this program's) — services do not restart on 78
|
|
16
|
+
// (launchd: 0). `status`: 0 running and fine, 1 running with a problem, 2 not
|
|
17
|
+
// running or not connected.
|
|
10
18
|
|
|
11
19
|
import { spawn, spawnSync } from 'node:child_process';
|
|
12
20
|
import { once } from 'node:events';
|
|
@@ -20,49 +28,64 @@ import {
|
|
|
20
28
|
ConfigError,
|
|
21
29
|
DEFAULT_SERVER,
|
|
22
30
|
LEGACY_NAME,
|
|
23
|
-
POOL_UPDATE_MS,
|
|
24
|
-
REPO_UPDATE_HOUR,
|
|
25
31
|
WorkRootError,
|
|
26
32
|
adoptLegacyState,
|
|
27
33
|
configPaths,
|
|
34
|
+
effectiveSettings,
|
|
28
35
|
legacyConfigPending,
|
|
29
36
|
legacyLockFile,
|
|
30
37
|
loadConfig,
|
|
31
38
|
newClientId,
|
|
39
|
+
prepareProgramHome,
|
|
32
40
|
prepareWorkRoot,
|
|
33
|
-
|
|
41
|
+
updateConfig,
|
|
34
42
|
withRepoPaths,
|
|
35
43
|
} from '../lib/config.mjs';
|
|
36
44
|
import { UPDATE_COMMAND, fatalFor, runConnection } from '../lib/connection.mjs';
|
|
45
|
+
import { ControlError, NotRunningError, controlDirectories, controlRequest, pingInstance, socketLocation, startControlServer } from '../lib/control.mjs';
|
|
37
46
|
import { SANDBOX_DOCS, runDoctor, which } from '../lib/doctor.mjs';
|
|
47
|
+
import { cleanRunsDir } from '../lib/fs-safe.mjs';
|
|
38
48
|
import { ApiError, createClient, normalizeServerUrl, proxyMode } from '../lib/http.mjs';
|
|
39
49
|
import { FEATURE_LABELS, JobManager } from '../lib/jobs.mjs';
|
|
40
50
|
import { LockedError, acquireLock, isRunnerAlive, lockHolder } from '../lib/lock.mjs';
|
|
41
51
|
import { NODE_REQUIREMENT, nodeSupported } from '../lib/node-runtime.cjs';
|
|
42
52
|
import { createLogger } from '../lib/log.mjs';
|
|
53
|
+
import { Maintenance } from '../lib/maintenance.mjs';
|
|
43
54
|
import { CancelledError, askText, askYesNo, isInteractive, readHidden, readStdin } from '../lib/prompt.mjs';
|
|
44
55
|
import {
|
|
45
56
|
EXIT_NEEDS_ATTENTION,
|
|
57
|
+
controlService,
|
|
46
58
|
installService,
|
|
47
59
|
legacyServiceInstalled,
|
|
48
60
|
removeLegacyService,
|
|
49
61
|
serviceExitCode,
|
|
62
|
+
servicePaths,
|
|
50
63
|
serviceStatus,
|
|
51
64
|
uninstallService,
|
|
52
65
|
} from '../lib/service.mjs';
|
|
53
66
|
import { DEFAULT_REQUIRED_TOOLS, npmPrefixWritable, planSetup, runSetup } from '../lib/setup.mjs';
|
|
54
67
|
import { prepareWorkAgentHome } from '../lib/sandbox.mjs';
|
|
68
|
+
import { StateStore, countResults, matchesRunId, readHistory, readStatus } from '../lib/state.mjs';
|
|
55
69
|
import { collectSystemInfo, describeSystem } from '../lib/system-info.mjs';
|
|
56
|
-
import {
|
|
70
|
+
import { jobDetailLines, jobsLines, pathsLines, statusLines } from '../lib/views.mjs';
|
|
71
|
+
import {
|
|
72
|
+
WorkAgent,
|
|
73
|
+
freeBytes,
|
|
74
|
+
markPoolBusy,
|
|
75
|
+
poolBusyInfo,
|
|
76
|
+
poolUpdateRequested,
|
|
77
|
+
requestPoolUpdate,
|
|
78
|
+
} from '../lib/work-agent.mjs';
|
|
57
79
|
|
|
58
80
|
// The command's entry point (it checks the Node version, then loads this file).
|
|
59
81
|
const ENTRY = fileURLToPath(new URL('./work-agent-runner.cjs', import.meta.url));
|
|
60
82
|
const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
61
83
|
const TOKEN_PATTERN = /^gcm_[A-Za-z0-9_-]{43}$/;
|
|
62
84
|
const NAME_MAX_CHARS = 40; // the website's limit (normalizeMachineName)
|
|
63
|
-
const DOCTOR_INTERVAL_MS = 60 * 60_000;
|
|
64
85
|
const ATTENTION = EXIT_NEEDS_ATTENTION;
|
|
65
86
|
const LEGACY_SERVICE_HINT = `旧版程序 ${LEGACY_NAME} 的后台服务还在:运行 work-agent-runner service install 会停止并替换它(service uninstall 只删除)`;
|
|
87
|
+
// A terminal command waits this long for the service to be done with the clone.
|
|
88
|
+
const TERMINAL_LOCK_WAIT_MS = 2 * 60_000;
|
|
66
89
|
|
|
67
90
|
// Which tools each feature needs — for the messages here only; the website decides.
|
|
68
91
|
const FEATURE_TOOLS = {
|
|
@@ -78,22 +101,33 @@ const USAGE = `GitCode Agent 执行机器 ${VERSION}
|
|
|
78
101
|
|
|
79
102
|
命令:
|
|
80
103
|
start 连接网站并等待任务(默认)
|
|
104
|
+
status [--json] [--watch] 本机状态:运行情况、连接、任务、维护和问题(--watch 每 2 秒刷新)
|
|
105
|
+
(退出码:0 正常,1 有问题,2 没有运行或没连上网站)
|
|
106
|
+
jobs [--failed] [--since 24h] [-n 20] [--json]
|
|
107
|
+
任务记录;jobs show <任务 ID> 查看一个任务的过程,
|
|
108
|
+
jobs cancel <任务 ID> 在本机取消运行中的任务
|
|
109
|
+
logs [-f] [-n 100] [--job <任务 ID>] [--since 1h]
|
|
110
|
+
程序日志(-f 跟随新内容)
|
|
111
|
+
paths [--json] 各个目录在哪里,以及有没有问题
|
|
81
112
|
login [--new-id] [--token-stdin] [--name <名称>]
|
|
82
113
|
输入接入令牌(校验通过才保存);--new-id 重新生成机器标识
|
|
83
114
|
logout 清除本机保存的令牌(机器标识保留)
|
|
84
115
|
setup [--yes] [--repos <仓名>|--no-repos]
|
|
85
116
|
检查并安装缺少的依赖、下载 work-agent 仓库,并询问是否
|
|
86
117
|
下载知识仓(work-agent 的必要仓清单;需在终端里运行)
|
|
87
|
-
update 立即更新 work-agent
|
|
118
|
+
update 立即更新 work-agent 仓库和知识仓(程序在运行时由它来做,
|
|
119
|
+
知识仓在没有任务时更新)
|
|
88
120
|
doctor [--json] 检查依赖、沙箱和各功能是否可用
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
121
|
+
cleanup [--yes] 清空 work-agent 的共享临时目录、删除 30 天前的日志(会先确认)
|
|
122
|
+
reload 让运行中的程序重新读取 config.json 里的维护时间、限额和隔离设置
|
|
123
|
+
service install|uninstall|start|stop|restart|status
|
|
124
|
+
后台服务:注册(开机自启)/ 删除 / 启动 / 停止 / 重启 / 查看
|
|
92
125
|
version 显示版本
|
|
93
126
|
|
|
94
127
|
选项:
|
|
95
128
|
--server <url> 网站地址(默认 ${DEFAULT_SERVER},会保存)
|
|
96
|
-
--work-dir <dir>
|
|
129
|
+
--work-dir <dir> 任务目录放在哪里(会保存):新目录、空目录或本程序用过的目录;
|
|
130
|
+
已有其他内容的目录会改用其下的 work-agent-runner/,原有内容不动
|
|
97
131
|
--name <名称> 这台机器登记时用的名称(默认主机名,会保存;登记后在网页上修改)
|
|
98
132
|
--allow-root 允许以 root 运行(仅限容器等确有需要的场合)
|
|
99
133
|
|
|
@@ -108,6 +142,7 @@ class ExitError extends Error {
|
|
|
108
142
|
|
|
109
143
|
const say = (text = '') => process.stdout.write(`${text}\n`);
|
|
110
144
|
const log = createLogger();
|
|
145
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
111
146
|
|
|
112
147
|
function checkSystem() {
|
|
113
148
|
if (!['linux', 'darwin'].includes(process.platform)) throw new ExitError(ATTENTION, '暂不支持此系统(只支持 Linux 和 macOS)');
|
|
@@ -126,7 +161,7 @@ async function applyProxy() {
|
|
|
126
161
|
stdio: 'inherit',
|
|
127
162
|
env: { ...process.env, NODE_USE_ENV_PROXY: '1', GC_RUNNER_REEXEC: '1' },
|
|
128
163
|
});
|
|
129
|
-
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => child.kill(signal));
|
|
164
|
+
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => child.kill(signal));
|
|
130
165
|
const [code, signal] = await once(child, 'exit');
|
|
131
166
|
return code ?? (signal ? 128 + (os.constants.signals[signal] || 0) : 1);
|
|
132
167
|
}
|
|
@@ -139,6 +174,14 @@ function realHome() {
|
|
|
139
174
|
}
|
|
140
175
|
}
|
|
141
176
|
|
|
177
|
+
function realpathOr(value) {
|
|
178
|
+
try {
|
|
179
|
+
return fs.realpathSync(value);
|
|
180
|
+
} catch {
|
|
181
|
+
return path.resolve(value);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
142
185
|
/** A name the website accepts: trimmed, 1–40 characters, no control characters; else ''. */
|
|
143
186
|
function machineName(value) {
|
|
144
187
|
const name = String(value ?? '').trim();
|
|
@@ -146,6 +189,21 @@ function machineName(value) {
|
|
|
146
189
|
return length >= 1 && length <= NAME_MAX_CHARS && !/\p{Cc}/u.test(name) ? name : '';
|
|
147
190
|
}
|
|
148
191
|
|
|
192
|
+
/** "24h" / "30m" / "7d" → milliseconds; 0 for nothing. */
|
|
193
|
+
function parseSince(value) {
|
|
194
|
+
if (!value) return 0;
|
|
195
|
+
const match = /^(\d+)\s*(m|h|d)$/.exec(String(value).trim());
|
|
196
|
+
if (!match) throw new ExitError(1, `--since 的格式是 30m、24h 或 7d(收到 ${value})`);
|
|
197
|
+
return Number(match[1]) * { m: 60_000, h: 3_600_000, d: 86_400_000 }[match[2]];
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function parseCount(value, fallback) {
|
|
201
|
+
if (value === undefined) return fallback;
|
|
202
|
+
const count = Number(value);
|
|
203
|
+
if (!Number.isInteger(count) || count < 1 || count > 10_000) throw new ExitError(1, `-n 需要 1–10000 之间的整数(收到 ${value})`);
|
|
204
|
+
return count;
|
|
205
|
+
}
|
|
206
|
+
|
|
149
207
|
/**
|
|
150
208
|
* First run after an older layout (0.0.1 kept the config under ~/.config and
|
|
151
209
|
* ran jobs in /var/tmp; before 0.0.1-alpha-5 everything was named
|
|
@@ -174,58 +232,52 @@ function adoptLegacy(paths) {
|
|
|
174
232
|
}
|
|
175
233
|
}
|
|
176
234
|
|
|
177
|
-
/**
|
|
178
|
-
|
|
235
|
+
/**
|
|
236
|
+
* Config, server, client id and paths. What --server / --work-dir / --name
|
|
237
|
+
* change, a missing client id and the directories config.json does not name
|
|
238
|
+
* yet are `pending` until applyPending() writes them: right away for a
|
|
239
|
+
* terminal command (`persist`), only once `start` holds the instance lock.
|
|
240
|
+
* `workRoot`: also prepare the work root and work-agent's home.
|
|
241
|
+
*/
|
|
242
|
+
function loadContext(values, { workRoot: needWorkRoot = true, persist = true, instance = false } = {}) {
|
|
179
243
|
const defaults = configPaths();
|
|
244
|
+
// Before anything is written into it: a WORK_AGENT_RUNNER_HOME pointed at a
|
|
245
|
+
// directory of the user's is refused, not taken over.
|
|
246
|
+
prepareProgramHome(defaults.baseDir);
|
|
180
247
|
adoptLegacy(defaults);
|
|
181
248
|
const config = loadConfig(defaults);
|
|
182
|
-
|
|
183
|
-
if (!config.clientId)
|
|
184
|
-
config.clientId = newClientId();
|
|
185
|
-
changed = true;
|
|
186
|
-
}
|
|
249
|
+
const pending = {};
|
|
250
|
+
if (!config.clientId) pending.clientId = newClientId();
|
|
187
251
|
let server;
|
|
188
252
|
try {
|
|
189
253
|
server = normalizeServerUrl(values.server || config.server || DEFAULT_SERVER);
|
|
190
254
|
} catch (error) {
|
|
191
255
|
throw new ExitError(ATTENTION, error.message);
|
|
192
256
|
}
|
|
193
|
-
if (values.server && server !== config.server)
|
|
194
|
-
config.server = server;
|
|
195
|
-
changed = true;
|
|
196
|
-
}
|
|
257
|
+
if (values.server && server !== config.server) pending.server = server;
|
|
197
258
|
if (values.name !== undefined) {
|
|
198
259
|
const name = machineName(values.name);
|
|
199
260
|
if (!name) throw new ExitError(1, `名称需为 1–${NAME_MAX_CHARS} 个字符,不能包含控制字符`);
|
|
200
|
-
if (name !== config.machineName)
|
|
201
|
-
config.machineName = name;
|
|
202
|
-
changed = true;
|
|
203
|
-
}
|
|
261
|
+
if (name !== config.machineName) pending.machineName = name;
|
|
204
262
|
}
|
|
205
|
-
|
|
263
|
+
// A --work-dir is only taken once prepareRunDirs() has accepted it (status
|
|
264
|
+
// and logout do not prepare one, so they ignore it).
|
|
265
|
+
if (values['work-dir'] && (needWorkRoot || !persist)) {
|
|
206
266
|
const dir = path.resolve(values['work-dir']);
|
|
207
|
-
if (dir !== config.workRoot)
|
|
208
|
-
config.workRoot = dir;
|
|
209
|
-
changed = true;
|
|
210
|
-
}
|
|
267
|
+
if (dir !== config.workRoot) pending.workRoot = dir;
|
|
211
268
|
}
|
|
212
|
-
//
|
|
269
|
+
// work-agent's home and the two repositories: wherever the config file says.
|
|
213
270
|
let paths;
|
|
214
271
|
try {
|
|
215
|
-
|
|
216
|
-
paths = resolved.paths;
|
|
217
|
-
if (resolved.missing) {
|
|
218
|
-
// Write both into the config, so the file always shows where they are.
|
|
219
|
-
config.workAgentRepoDir = paths.repoDir;
|
|
220
|
-
config.ascendReposDir = paths.poolDir;
|
|
221
|
-
changed = true;
|
|
222
|
-
}
|
|
272
|
+
paths = withRepoPaths(defaults, config).paths;
|
|
223
273
|
} catch (error) {
|
|
224
274
|
throw new ExitError(ATTENTION, error.message);
|
|
225
275
|
}
|
|
226
|
-
//
|
|
227
|
-
|
|
228
|
-
if (
|
|
276
|
+
// Written into the config, so the file always shows where they are.
|
|
277
|
+
if (!config.workAgentHome) pending.workAgentHome = paths.workAgentHome;
|
|
278
|
+
if (!config.workAgentRepoDir) pending.workAgentRepoDir = paths.repoDir;
|
|
279
|
+
if (!config.ascendReposDir) pending.ascendReposDir = paths.poolDir;
|
|
280
|
+
Object.assign(config, pending);
|
|
229
281
|
const workAgent = new WorkAgent({
|
|
230
282
|
paths,
|
|
231
283
|
log,
|
|
@@ -233,17 +285,78 @@ function loadContext(values, { workRoot: needWorkRoot = true } = {}) {
|
|
|
233
285
|
// from WORK_AGENT_REPO for development and tests (any scheme, so a local
|
|
234
286
|
// path works). Never from the website, and clone() logs where it went.
|
|
235
287
|
repoUrl: process.env.WORK_AGENT_REPO || config.workAgentRepo,
|
|
288
|
+
// Jobs wait long for a terminal `update`; a terminal command waits less for the service.
|
|
289
|
+
...(instance ? {} : { lockWaitMs: TERMINAL_LOCK_WAIT_MS }),
|
|
236
290
|
});
|
|
291
|
+
const ctx = { paths, config, pending, server, workRoot: '', realHome: realHome(), workAgent };
|
|
292
|
+
// The work root is checked before anything is saved: a refused --work-dir
|
|
293
|
+
// must not end up in the config.
|
|
294
|
+
if (needWorkRoot) prepareRunDirs(ctx);
|
|
295
|
+
if (persist) applyPending(ctx);
|
|
296
|
+
return ctx;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Writes what loadContext() left pending, field by field (another process may have written meanwhile). */
|
|
300
|
+
function applyPending(ctx) {
|
|
301
|
+
const { pending } = ctx;
|
|
302
|
+
if (!Object.keys(pending).length) return;
|
|
303
|
+
const written = updateConfig(ctx.paths, (config) => {
|
|
304
|
+
for (const [key, value] of Object.entries(pending)) {
|
|
305
|
+
// Defaults only fill what is still empty; the options given now win.
|
|
306
|
+
if (['clientId', 'workAgentHome', 'workAgentRepoDir', 'ascendReposDir'].includes(key) && config[key]) continue;
|
|
307
|
+
config[key] = value;
|
|
308
|
+
}
|
|
309
|
+
});
|
|
310
|
+
for (const key of Object.keys(pending)) if (written[key] !== undefined) ctx.config[key] = written[key];
|
|
311
|
+
ctx.pending = {};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* The work root (runs/ and trash/): the program's home, or the --work-dir,
|
|
316
|
+
* which is only used as it is when it is new, empty or this program's — else
|
|
317
|
+
* its work-agent-runner/ subdirectory, which then goes into the config
|
|
318
|
+
* (pending: applyPending() saves it). Then work-agent's home (logs/ tmp/
|
|
319
|
+
* docs/, the pool link).
|
|
320
|
+
*/
|
|
321
|
+
function prepareRunDirs(ctx) {
|
|
322
|
+
const requested = ctx.config.workRoot || ctx.paths.runsRoot;
|
|
323
|
+
const workRoot = prepareWorkRoot(requested, { programHome: ctx.paths.baseDir });
|
|
324
|
+
if (ctx.config.workRoot && realpathOr(ctx.config.workRoot) !== workRoot) {
|
|
325
|
+
log.info(`${ctx.config.workRoot} 里已有其他内容,任务目录改放在 ${workRoot}(不会改动 ${ctx.config.workRoot} 里原有的东西)`);
|
|
326
|
+
ctx.config.workRoot = workRoot;
|
|
327
|
+
ctx.pending.workRoot = workRoot;
|
|
328
|
+
}
|
|
329
|
+
ctx.workRoot = workRoot;
|
|
237
330
|
// The Skills' logs, scratch and deliverables, and the pool symlink when there
|
|
238
331
|
// is a pool; a job's HOME links to this directory.
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
332
|
+
prepareWorkAgentHome(ctx.paths.workAgentHome, { poolDir: ctx.workAgent.mountablePool(), link: ctx.paths.workAgentLink });
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** Saves a field of the config without writing back anything stale. */
|
|
336
|
+
function saveField(ctx, key, value) {
|
|
337
|
+
updateConfig(ctx.paths, (config) => {
|
|
338
|
+
if (value === '' || value === undefined) delete config[key];
|
|
339
|
+
else config[key] = value;
|
|
340
|
+
});
|
|
341
|
+
ctx.config[key] = value;
|
|
243
342
|
}
|
|
244
343
|
|
|
245
|
-
|
|
246
|
-
|
|
344
|
+
/**
|
|
345
|
+
* The website no longer accepts `failedToken`: clear it from the config —
|
|
346
|
+
* unless the file holds another one by now (a `login` in a terminal while this
|
|
347
|
+
* ran). Returns true when the file is left without a token.
|
|
348
|
+
*/
|
|
349
|
+
function clearToken(ctx, failedToken) {
|
|
350
|
+
try {
|
|
351
|
+
const written = updateConfig(ctx.paths, (config) => {
|
|
352
|
+
if (config.token === failedToken) config.token = '';
|
|
353
|
+
});
|
|
354
|
+
ctx.config.token = written.token;
|
|
355
|
+
return !written.token;
|
|
356
|
+
} catch (error) {
|
|
357
|
+
log.warn(`无法清除本机保存的令牌:${error.message}`);
|
|
358
|
+
return true;
|
|
359
|
+
}
|
|
247
360
|
}
|
|
248
361
|
|
|
249
362
|
function clientFor(ctx, token = ctx.config.token) {
|
|
@@ -266,14 +379,14 @@ function systemInfo(ctx) {
|
|
|
266
379
|
}
|
|
267
380
|
|
|
268
381
|
/** After /connect: what the machine is called there, and whether its owner confirmed it. */
|
|
269
|
-
function sayRegistered(ctx, reply) {
|
|
270
|
-
|
|
382
|
+
function sayRegistered(ctx, reply, out = say) {
|
|
383
|
+
out(`✓ 已连接 ${ctx.server},本机登记为「${reply.name}」(令牌:${reply.tokenName})${reply.role === 'server' ? ',服务器执行机器' : ''}`);
|
|
271
384
|
if (!reply.created && ctx.config.machineName && reply.name !== ctx.config.machineName) {
|
|
272
|
-
|
|
385
|
+
out(` 这台机器之前已登记为「${reply.name}」,名称请在网页上修改`);
|
|
273
386
|
}
|
|
274
387
|
if (reply.confirmed === false) {
|
|
275
|
-
|
|
276
|
-
|
|
388
|
+
out('⚠ 这台机器还没有确认,确认后才会收到任务:请在网页「在线 Agent → 模型配置 → 执行机器」里核对主机名和 IP 后点「确认」');
|
|
389
|
+
out(` ${ctx.server}/features#agent/config`);
|
|
277
390
|
}
|
|
278
391
|
}
|
|
279
392
|
|
|
@@ -299,18 +412,36 @@ function networkReason(error) {
|
|
|
299
412
|
return error?.cause?.code || error?.cause?.message || error?.message || String(error);
|
|
300
413
|
}
|
|
301
414
|
|
|
302
|
-
/** doctor + remembering a claude found outside PATH. */
|
|
303
|
-
async function doctorFor(ctx) {
|
|
415
|
+
/** doctor + remembering a claude found outside PATH. `probe: false`: no sandbox check (seconds faster). */
|
|
416
|
+
async function doctorFor(ctx, { probe = true } = {}) {
|
|
304
417
|
const result = await runDoctor({
|
|
305
418
|
configuredClaude: ctx.config.claudePath || '',
|
|
306
419
|
workRoot: ctx.workRoot,
|
|
307
420
|
realHome: ctx.realHome,
|
|
308
421
|
workAgent: ctx.workAgent,
|
|
422
|
+
probe,
|
|
309
423
|
});
|
|
310
424
|
const remembered = result.claude.viaNpmPrefix || result.claude.path === ctx.config.claudePath ? result.claude.path : '';
|
|
311
425
|
if ((ctx.config.claudePath || '') !== remembered) {
|
|
312
|
-
|
|
313
|
-
|
|
426
|
+
try {
|
|
427
|
+
saveField(ctx, 'claudePath', remembered);
|
|
428
|
+
} catch (error) {
|
|
429
|
+
log.warn(`无法保存 claude 的位置:${error.message}`);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
return result;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* What a start reports before the sandbox check has run: everything quick,
|
|
437
|
+
* and the sandbox verdict of the last run when claude has not changed since.
|
|
438
|
+
* The real check follows in the background; jobs wait for it.
|
|
439
|
+
*/
|
|
440
|
+
async function quickChecks(ctx) {
|
|
441
|
+
const result = await doctorFor(ctx, { probe: false });
|
|
442
|
+
const last = readStatus(ctx.paths.statusFile)?.capabilities;
|
|
443
|
+
if (last?.sandbox && last.claude && last.claude === result.capabilities.claude && last.os === result.capabilities.os) {
|
|
444
|
+
result.capabilities.sandbox = { ok: last.sandbox.ok === true, reason: last.sandbox.reason || '' };
|
|
314
445
|
}
|
|
315
446
|
return result;
|
|
316
447
|
}
|
|
@@ -341,8 +472,12 @@ async function obtainToken(ctx, { fromStdin = false, capabilities }) {
|
|
|
341
472
|
const client = clientFor(ctx, token);
|
|
342
473
|
try {
|
|
343
474
|
const reply = await connect(ctx, client, capabilities);
|
|
475
|
+
const name = ctx.config.machineName;
|
|
476
|
+
updateConfig(ctx.paths, (config) => {
|
|
477
|
+
config.token = token;
|
|
478
|
+
if (name) config.machineName = name;
|
|
479
|
+
});
|
|
344
480
|
ctx.config.token = token;
|
|
345
|
-
save(ctx);
|
|
346
481
|
sayRegistered(ctx, reply);
|
|
347
482
|
return { client, reply };
|
|
348
483
|
} catch (error) {
|
|
@@ -358,24 +493,36 @@ async function obtainToken(ctx, { fromStdin = false, capabilities }) {
|
|
|
358
493
|
throw new ExitError(ATTENTION, '令牌 3 次都不正确,已退出');
|
|
359
494
|
}
|
|
360
495
|
|
|
361
|
-
/**
|
|
362
|
-
|
|
496
|
+
/**
|
|
497
|
+
* POST /connect with the saved token; waits out network trouble (services must
|
|
498
|
+
* not give up). `signal` ends the wait (a stop while the network is down).
|
|
499
|
+
*/
|
|
500
|
+
async function connectSaved(ctx, client, capabilities, { signal = null, onRetry = () => {} } = {}) {
|
|
363
501
|
let delay = 1000;
|
|
364
502
|
for (;;) {
|
|
503
|
+
if (signal?.aborted) throw new ExitError(0, '');
|
|
365
504
|
try {
|
|
366
505
|
return await connect(ctx, client, capabilities);
|
|
367
506
|
} catch (error) {
|
|
368
507
|
const fatal = fatalFor(error);
|
|
369
508
|
if (fatal) {
|
|
370
|
-
if (fatal.clearToken) {
|
|
371
|
-
|
|
372
|
-
|
|
509
|
+
if (fatal.clearToken && !clearToken(ctx, ctx.config.token)) {
|
|
510
|
+
// A `login` saved a new token meanwhile: a restart uses it (exit 1, so services restart).
|
|
511
|
+
throw new ExitError(1, '保存的令牌已失效,但配置文件里已经是新的令牌:重新启动后使用它');
|
|
373
512
|
}
|
|
374
513
|
throw new ExitError(fatal.code, fatal.message);
|
|
375
514
|
}
|
|
376
515
|
if (error instanceof ApiError && error.status !== 429 && error.status < 500) throw connectFailure(error, ctx.server);
|
|
377
|
-
|
|
378
|
-
|
|
516
|
+
const reason = error instanceof ApiError ? error.message : networkReason(error);
|
|
517
|
+
onRetry(reason);
|
|
518
|
+
log.warn(`无法连接 ${ctx.server}(${reason}),${Math.round(delay / 1000)} 秒后重试`);
|
|
519
|
+
await new Promise((resolve) => {
|
|
520
|
+
const timer = setTimeout(resolve, error?.retryAfterMs || delay);
|
|
521
|
+
signal?.addEventListener('abort', () => {
|
|
522
|
+
clearTimeout(timer);
|
|
523
|
+
resolve();
|
|
524
|
+
}, { once: true });
|
|
525
|
+
});
|
|
379
526
|
delay = Math.min(60_000, delay * 2);
|
|
380
527
|
}
|
|
381
528
|
}
|
|
@@ -385,14 +532,6 @@ function toolLabel(name) {
|
|
|
385
532
|
return name === 'bwrap' ? 'bubblewrap' : name;
|
|
386
533
|
}
|
|
387
534
|
|
|
388
|
-
/** Updates every repository in the knowledge pool. Never fatal. */
|
|
389
|
-
async function updatePool(ctx) {
|
|
390
|
-
if (!ctx.workAgent.mountablePool()) return;
|
|
391
|
-
await ctx.workAgent
|
|
392
|
-
.updatePool({ say: (line) => log.info(line) })
|
|
393
|
-
.catch((error) => log.warn(`知识仓更新失败:${error.message}`));
|
|
394
|
-
}
|
|
395
|
-
|
|
396
535
|
/** Brings the clone up to date. Never fatal: the website shows the reason instead. */
|
|
397
536
|
async function refreshWorkAgent(ctx, { say: out = say } = {}) {
|
|
398
537
|
try {
|
|
@@ -411,26 +550,81 @@ function poolAge(fetchedAt) {
|
|
|
411
550
|
}
|
|
412
551
|
|
|
413
552
|
/** The Skill source and the knowledge pool, in two lines. */
|
|
414
|
-
function printWorkAgent(state) {
|
|
415
|
-
if (state.ok)
|
|
416
|
-
else
|
|
553
|
+
function printWorkAgent(state, out = say) {
|
|
554
|
+
if (state.ok) out(`✓ work-agent ${state.commit.slice(0, 7)}${state.committedAt ? `(${state.committedAt.slice(0, 10)})` : ''}`);
|
|
555
|
+
else out(`✗ work-agent 仓库不可用:${state.reason}`);
|
|
417
556
|
if (state.incomplete?.length) {
|
|
418
|
-
|
|
557
|
+
out(` 知识仓 ${state.incomplete.join('、')} 不完整:请删除后重新运行 work-agent-runner setup`);
|
|
419
558
|
} else if (state.repos) {
|
|
420
559
|
const what = state.ascend ? `${state.repos} 个仓(含 AscendC 两仓)` : `${state.repos} 个仓,缺 AscendC 两仓(代码检视的 AscendC 规范域不检查)`;
|
|
421
|
-
|
|
560
|
+
out(` 知识仓:${what}${poolAge(state.poolFetchedAt)}`);
|
|
422
561
|
} else {
|
|
423
|
-
|
|
562
|
+
out(' 知识仓:未初始化(可选;运行 work-agent-runner setup 下载)');
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* Runs `work` (a terminal's own work-agent.py: a pool update, a download, a
|
|
568
|
+
* cleanup); Ctrl+C or SIGTERM stops work-agent.py with it, which runs in its
|
|
569
|
+
* own process group and would otherwise go on alone. A second one exits at once.
|
|
570
|
+
*/
|
|
571
|
+
async function withStopOnSignal(ctx, work) {
|
|
572
|
+
let interrupted = '';
|
|
573
|
+
const onSignal = (signal) => {
|
|
574
|
+
if (interrupted) process.exit(130);
|
|
575
|
+
interrupted = signal;
|
|
576
|
+
say(`\n收到 ${signal},正在停止 work-agent.py……`);
|
|
577
|
+
ctx.workAgent.stop();
|
|
578
|
+
};
|
|
579
|
+
const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
|
|
580
|
+
for (const signal of signals) process.on(signal, onSignal);
|
|
581
|
+
try {
|
|
582
|
+
return await work();
|
|
583
|
+
} catch (error) {
|
|
584
|
+
if (interrupted) throw new ExitError(128 + (os.constants.signals[interrupted] || 0), '已停止');
|
|
585
|
+
throw error;
|
|
586
|
+
} finally {
|
|
587
|
+
for (const signal of signals) process.off(signal, onSignal);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/** A running instance's answer to `method`, printing its progress lines; null when none answers. */
|
|
592
|
+
async function askInstance(ctx, method, params = {}, { quiet = false } = {}) {
|
|
593
|
+
try {
|
|
594
|
+
return await controlRequest(ctx.paths, method, params, {
|
|
595
|
+
timeoutMs: 0,
|
|
596
|
+
onEvent: (event, data) => {
|
|
597
|
+
if (event === 'log' && !quiet) say(` ${data}`);
|
|
598
|
+
},
|
|
599
|
+
});
|
|
600
|
+
} catch (error) {
|
|
601
|
+
if (error instanceof NotRunningError) return null;
|
|
602
|
+
if (error instanceof ControlError) throw new ExitError(1, error.message);
|
|
603
|
+
throw error;
|
|
424
604
|
}
|
|
425
605
|
}
|
|
426
606
|
|
|
607
|
+
/** After `setup` installed tools: a clone that failed for want of git is made now. */
|
|
608
|
+
async function ensureClone(ctx) {
|
|
609
|
+
const state = ctx.workAgent.state();
|
|
610
|
+
if (state.ok || state.foreign) return;
|
|
611
|
+
say('重新下载 work-agent 仓库……');
|
|
612
|
+
const delegated = await askInstance(ctx, 'repo.refresh');
|
|
613
|
+
if (delegated) say(delegated.ok ? `✓ work-agent ${delegated.commit.slice(0, 7)}` : `✗ work-agent 仓库不可用:${delegated.reason}`);
|
|
614
|
+
else printWorkAgent(await refreshWorkAgent(ctx));
|
|
615
|
+
}
|
|
616
|
+
|
|
427
617
|
const REPO_NAME = /^[A-Za-z0-9._-]{1,80}$/;
|
|
428
618
|
|
|
619
|
+
function validRepoName(name) {
|
|
620
|
+
return REPO_NAME.test(name) && !name.startsWith('.');
|
|
621
|
+
}
|
|
622
|
+
|
|
429
623
|
/** `--repos a,b` → names, validated the way work-agent.py validates them. */
|
|
430
624
|
function splitRepos(value) {
|
|
431
625
|
const names = String(value).split(/[,\s]+/).filter(Boolean);
|
|
432
626
|
for (const name of names) {
|
|
433
|
-
if (!
|
|
627
|
+
if (!validRepoName(name)) throw new ExitError(1, `仓名不正确:${name}`);
|
|
434
628
|
}
|
|
435
629
|
if (!names.length) throw new ExitError(1, '--repos 需要至少一个仓名');
|
|
436
630
|
return names;
|
|
@@ -439,9 +633,12 @@ function splitRepos(value) {
|
|
|
439
633
|
/**
|
|
440
634
|
* Offers the knowledge pool — the repositories of work-agent's own essential
|
|
441
635
|
* list — in a terminal only. Never downloads anything without a yes: `--repos`
|
|
442
|
-
* picks the repositories instead, `--no-repos` skips the question.
|
|
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).
|
|
443
640
|
*/
|
|
444
|
-
async function offerPool(ctx, values) {
|
|
641
|
+
async function offerPool(ctx, values, { delegate = true } = {}) {
|
|
445
642
|
if (values['no-repos']) return;
|
|
446
643
|
const wanted = values.repos === undefined ? null : splitRepos(values.repos);
|
|
447
644
|
const { poolDir, workAgentHome } = ctx.paths;
|
|
@@ -454,6 +651,11 @@ async function offerPool(ctx, values) {
|
|
|
454
651
|
say(`知识仓已就绪(${poolDir},${pool.repos} 个仓)`);
|
|
455
652
|
return;
|
|
456
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
|
+
}
|
|
457
659
|
if (wanted) say(`将下载到 ${poolDir}:${wanted.join('、')}`);
|
|
458
660
|
else {
|
|
459
661
|
say(`知识仓用于「代码检视」查 CANN / AscendC 的权威文档,下载到 ${poolDir}`);
|
|
@@ -468,11 +670,27 @@ async function offerPool(ctx, values) {
|
|
|
468
670
|
say('已跳过;以后随时可以再运行 work-agent-runner setup');
|
|
469
671
|
return;
|
|
470
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');
|
|
471
686
|
try {
|
|
472
|
-
await ctx.workAgent.initPool({ repos: wanted, say });
|
|
687
|
+
await withStopOnSignal(ctx, () => ctx.workAgent.initPool({ repos: wanted, say }));
|
|
473
688
|
prepareWorkAgentHome(workAgentHome, { poolDir: ctx.workAgent.mountablePool(), link: ctx.paths.workAgentLink });
|
|
474
689
|
} catch (error) {
|
|
690
|
+
if (error instanceof ExitError) throw error;
|
|
475
691
|
say(`下载知识仓失败:${error.message}`);
|
|
692
|
+
} finally {
|
|
693
|
+
finished();
|
|
476
694
|
}
|
|
477
695
|
}
|
|
478
696
|
|
|
@@ -483,34 +701,37 @@ function neededBy(tool) {
|
|
|
483
701
|
return features.length === Object.keys(FEATURE_TOOLS).length ? '所有功能需要' : `${features.join('、')}需要`;
|
|
484
702
|
}
|
|
485
703
|
|
|
486
|
-
function printDoctor(result) {
|
|
704
|
+
function printDoctor(result, out = say) {
|
|
487
705
|
const ready = [];
|
|
488
706
|
const missing = [];
|
|
489
707
|
for (const [name, info] of Object.entries(result.tools)) {
|
|
490
708
|
if (info.ok) ready.push(`✓ ${toolLabel(name)}${info.version ? ` ${info.version.split('.').slice(0, 2).join('.')}` : ''}`);
|
|
491
709
|
else missing.push(name);
|
|
492
710
|
}
|
|
493
|
-
if (ready.length)
|
|
494
|
-
for (const name of missing)
|
|
495
|
-
if (!result.claude.path)
|
|
496
|
-
else {
|
|
497
|
-
|
|
498
|
-
|
|
711
|
+
if (ready.length) out(` ${ready.join(' ')}`);
|
|
712
|
+
for (const name of missing) out(` ✗ ${toolLabel(name).padEnd(11)} ${neededBy(name)}`);
|
|
713
|
+
if (!result.claude.path) out(` ✗ ${'claude'.padEnd(11)} 所有功能需要`);
|
|
714
|
+
else if (!result.claudeVersion) {
|
|
715
|
+
// There, but `claude --version` does not run (a broken install, a too-old Node behind it…).
|
|
716
|
+
out(` ✗ ${'claude'.padEnd(11)} 无法运行(${result.claude.path}):请运行 work-agent-runner setup 重新安装`);
|
|
717
|
+
} else {
|
|
718
|
+
out(` ✓ claude ${result.claudeVersion}`);
|
|
719
|
+
if (result.claude.viaNpmPrefix) out(` 提示:claude 在 ${path.dirname(result.claude.path)},建议把这个目录加入 PATH`);
|
|
499
720
|
}
|
|
500
721
|
const { sandbox } = result.capabilities;
|
|
501
|
-
if (sandbox.ok)
|
|
502
|
-
else
|
|
722
|
+
if (sandbox.ok) out('✓ 沙箱可用');
|
|
723
|
+
else out(`✗ 沙箱不可用:${sandbox.reason}(说明:${SANDBOX_DOCS})`);
|
|
503
724
|
}
|
|
504
725
|
|
|
505
|
-
function printFeatures(reply) {
|
|
726
|
+
function printFeatures(reply, out = say) {
|
|
506
727
|
if (!reply?.features) return;
|
|
507
728
|
const entries = Object.entries(reply.features);
|
|
508
729
|
const ok = entries.filter(([, verdict]) => verdict.ok).map(([feature]) => FEATURE_LABELS[feature] || feature);
|
|
509
|
-
|
|
730
|
+
out(ok.length ? `可运行:${ok.join('、')}` : '暂时没有可运行的功能');
|
|
510
731
|
for (const [feature, verdict] of entries) {
|
|
511
|
-
if (!verdict.ok)
|
|
732
|
+
if (!verdict.ok) out(`不可运行:${FEATURE_LABELS[feature] || feature}(${verdict.reason})`);
|
|
512
733
|
}
|
|
513
|
-
if (reply.outdated)
|
|
734
|
+
if (reply.outdated) out(`程序版本过低,请运行 ${UPDATE_COMMAND}`);
|
|
514
735
|
}
|
|
515
736
|
|
|
516
737
|
function setupPlan(result, reply, { poolWanted = false } = {}) {
|
|
@@ -536,7 +757,22 @@ function setupPlan(result, reply, { poolWanted = false } = {}) {
|
|
|
536
757
|
});
|
|
537
758
|
}
|
|
538
759
|
|
|
539
|
-
|
|
760
|
+
/** The pid of a running instance of this program home other than this process, or 0. */
|
|
761
|
+
function runningInstance(ctx) {
|
|
762
|
+
const holder = lockHolder(ctx.paths.lockFile);
|
|
763
|
+
return holder !== process.pid && isRunnerAlive(holder) ? holder : 0;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
// ---- The instance ------------------------------------------------------------
|
|
767
|
+
|
|
768
|
+
/** The newest failure with an error code among `records` (oldest first): { code, at }, or null. */
|
|
769
|
+
function lastErrorOf(records) {
|
|
770
|
+
for (let index = records.length - 1; index >= 0; index -= 1) {
|
|
771
|
+
const item = records[index];
|
|
772
|
+
if (item.result !== 'ok' && item.result !== 'cancelled' && item.error?.code) return { code: item.error.code, at: item.at?.done || '' };
|
|
773
|
+
}
|
|
774
|
+
return null;
|
|
775
|
+
}
|
|
540
776
|
|
|
541
777
|
async function start(values) {
|
|
542
778
|
checkSystem();
|
|
@@ -548,7 +784,8 @@ async function start(values) {
|
|
|
548
784
|
}
|
|
549
785
|
log.warn('正以 root 运行(--allow-root):沙箱内的命令拥有 root 权限,建议改用专用的低权限账号');
|
|
550
786
|
}
|
|
551
|
-
|
|
787
|
+
// Nothing is written before the lock: another instance may be running.
|
|
788
|
+
const ctx = loadContext(values, { workRoot: false, persist: false, instance: true });
|
|
552
789
|
let lock;
|
|
553
790
|
try {
|
|
554
791
|
lock = acquireLock(ctx.paths.lockFile);
|
|
@@ -557,63 +794,107 @@ async function start(values) {
|
|
|
557
794
|
throw error;
|
|
558
795
|
}
|
|
559
796
|
try {
|
|
797
|
+
prepareRunDirs(ctx);
|
|
798
|
+
applyPending(ctx);
|
|
799
|
+
// The instance's log also goes to logs/runner.log (`work-agent-runner logs`).
|
|
800
|
+
log.setFile(ctx.paths.logFile);
|
|
560
801
|
say(`GitCode Agent 执行机器 ${VERSION}`);
|
|
561
802
|
if (legacyServiceInstalled()) log.warn(LEGACY_SERVICE_HINT);
|
|
562
|
-
// Whatever a previous run left behind (
|
|
563
|
-
|
|
803
|
+
// Whatever a previous run left behind (run directories r??????, probe
|
|
804
|
+
// directories p??????) — by name only, and never fatal: a directory a job
|
|
805
|
+
// made undeletable goes to trash/ and is retried every hour.
|
|
806
|
+
const cleaned = cleanRunsDir(path.join(ctx.workRoot, 'runs'), { trashDir: path.join(ctx.workRoot, 'trash') });
|
|
807
|
+
const stuck = cleaned.trashed.length + cleaned.failed.length;
|
|
808
|
+
if (stuck) log.warn(`有 ${stuck} 个任务目录删不掉,留在 ${path.join(ctx.workRoot, 'trash')},稍后再试;不影响接收任务`);
|
|
809
|
+
if (cleaned.unknown.length) {
|
|
810
|
+
log.warn(`${path.join(ctx.workRoot, 'runs')} 里有不是本程序的内容(${cleaned.unknown.slice(0, 3).join('、')}),没有删除`);
|
|
811
|
+
}
|
|
564
812
|
const interactive = isInteractive() && !process.env.GC_RUNNER_SERVICE;
|
|
565
813
|
if (!ctx.config.token && !interactive) {
|
|
566
814
|
throw new ExitError(ATTENTION, '还没有接入令牌:请先在终端运行 work-agent-runner login');
|
|
567
815
|
}
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
// `git pull` must never replace files a running review is reading.
|
|
573
|
-
await ctx.workAgent.cleanup({ say: (line) => log.info(line) }).catch(() => {});
|
|
574
|
-
await updatePool(ctx);
|
|
575
|
-
say('检查依赖和沙箱……');
|
|
576
|
-
let result = await doctorFor(ctx);
|
|
577
|
-
let client;
|
|
578
|
-
let reply;
|
|
579
|
-
if (!ctx.config.token) {
|
|
580
|
-
({ client, reply } = await obtainToken(ctx, { capabilities: result.capabilities }));
|
|
581
|
-
} else {
|
|
582
|
-
client = clientFor(ctx);
|
|
583
|
-
reply = await connectSaved(ctx, client, result.capabilities);
|
|
584
|
-
sayRegistered(ctx, reply);
|
|
816
|
+
if (!ctx.config.token || (!ctx.config.setupDone && interactive)) {
|
|
817
|
+
// A person is at the terminal for the first run: everything in order,
|
|
818
|
+
// with the answers it needs.
|
|
819
|
+
return await firstRun(ctx, values, { interactive });
|
|
585
820
|
}
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
interactive: true,
|
|
592
|
-
confirm: (question) => askYesNo(question),
|
|
593
|
-
say,
|
|
594
|
-
});
|
|
595
|
-
// Asked once: missing items stay visible in status and on the website.
|
|
596
|
-
ctx.config.setupDone = true;
|
|
597
|
-
save(ctx);
|
|
598
|
-
if (outcome.ran) {
|
|
599
|
-
say('重新检查……');
|
|
600
|
-
result = await doctorFor(ctx);
|
|
601
|
-
printDoctor(result);
|
|
602
|
-
}
|
|
603
|
-
// The same question `setup` asks, so a first run settles everything.
|
|
604
|
-
await offerPool(ctx, values);
|
|
605
|
-
result = await doctorFor(ctx);
|
|
606
|
-
reply = await connectSaved(ctx, client, result.capabilities);
|
|
607
|
-
}
|
|
608
|
-
printFeatures(reply);
|
|
609
|
-
say('等待任务……(Ctrl+C 退出;后台运行:work-agent-runner service install)');
|
|
610
|
-
return await serve(ctx, client, result, reply);
|
|
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 });
|
|
611
826
|
} finally {
|
|
612
827
|
lock.release();
|
|
613
828
|
}
|
|
614
829
|
}
|
|
615
830
|
|
|
616
|
-
async function
|
|
831
|
+
async function firstRun(ctx, values, { interactive }) {
|
|
832
|
+
say('检查 work-agent 仓库……');
|
|
833
|
+
printWorkAgent(await refreshWorkAgent(ctx));
|
|
834
|
+
say('检查依赖和沙箱……');
|
|
835
|
+
let result = await doctorFor(ctx);
|
|
836
|
+
let client;
|
|
837
|
+
let reply;
|
|
838
|
+
if (!ctx.config.token) {
|
|
839
|
+
({ client, reply } = await obtainToken(ctx, { capabilities: result.capabilities }));
|
|
840
|
+
} else {
|
|
841
|
+
client = clientFor(ctx);
|
|
842
|
+
reply = await connectSaved(ctx, client, result.capabilities);
|
|
843
|
+
sayRegistered(ctx, reply);
|
|
844
|
+
}
|
|
845
|
+
printDoctor(result);
|
|
846
|
+
if (!ctx.config.setupDone && interactive) {
|
|
847
|
+
const outcome = await runSetup({
|
|
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 });
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
/**
|
|
871
|
+
* The running instance: status and history (lib/state.mjs), the control
|
|
872
|
+
* interface, maintenance, jobs and the connection, until a signal or a fatal
|
|
873
|
+
* answer from the website. `reply`: the /connect answer when the caller
|
|
874
|
+
* connected already; else this connects (and keeps trying). `checksPending`:
|
|
875
|
+
* the clone and the sandbox check still have to run (in the background).
|
|
876
|
+
*/
|
|
877
|
+
async function serve(ctx, { client, initial, reply = null, checksPending = false }) {
|
|
878
|
+
const startedAt = new Date().toISOString();
|
|
879
|
+
const settings = () => effectiveSettings(ctx.config);
|
|
880
|
+
const state = new StateStore({ statusFile: ctx.paths.statusFile, historyFile: ctx.paths.historyFile });
|
|
881
|
+
let capabilities = initial.capabilities;
|
|
882
|
+
let role = reply?.role === 'server' ? 'server' : 'user';
|
|
883
|
+
let confirmed = reply ? reply.confirmed !== false : true;
|
|
884
|
+
let outdated = Boolean(reply?.outdated);
|
|
885
|
+
let registeredName = reply?.name || '';
|
|
886
|
+
let ready = !checksPending;
|
|
887
|
+
let controlSocket = '';
|
|
888
|
+
let degraded = [];
|
|
889
|
+
const connection = { server: ctx.server, connected: false, since: '', lastHeartbeatAt: '', lastError: '' };
|
|
890
|
+
// The jobs of the last 24 hours, for status (oldest first).
|
|
891
|
+
let recent = readHistory(ctx.paths.historyFile, { since: Date.now() - 86_400_000, limit: 1000 }).reverse();
|
|
892
|
+
const lastDay = () => {
|
|
893
|
+
const cutoff = Date.now() - 86_400_000;
|
|
894
|
+
recent = recent.filter((record) => Date.parse(record.at?.done || '') >= cutoff);
|
|
895
|
+
return recent;
|
|
896
|
+
};
|
|
897
|
+
|
|
617
898
|
const controller = new AbortController();
|
|
618
899
|
let fatal = null;
|
|
619
900
|
const onFatal = (error) => {
|
|
@@ -623,7 +904,63 @@ async function serve(ctx, client, initial, reply) {
|
|
|
623
904
|
controller.abort();
|
|
624
905
|
}
|
|
625
906
|
};
|
|
626
|
-
|
|
907
|
+
|
|
908
|
+
// A server execution machine runs every user's jobs: each gets a
|
|
909
|
+
// WORK_AGENT_HOME of its own, and what it leaves is archived or dropped.
|
|
910
|
+
const runMode = () => {
|
|
911
|
+
if (role === 'server') return { isolation: 'per-run', keep: settings().limits.archiveDays > 0 ? 'archive' : 'none' };
|
|
912
|
+
return settings().isolation === 'per-run' ? { isolation: 'per-run', keep: 'merge' } : { isolation: 'shared', keep: 'none' };
|
|
913
|
+
};
|
|
914
|
+
const acceptingState = () => {
|
|
915
|
+
if (!connection.connected) return { name: 'connecting', accepting: false, reason: '' };
|
|
916
|
+
if (!ready) return { name: 'online', accepting: false, reason: 'starting_checks' };
|
|
917
|
+
if (degraded.some((problem) => problem.code === 'E5101')) return { name: 'online', accepting: false, reason: 'clone_missing' };
|
|
918
|
+
if (ctx.workAgent.poolUpdating) return { name: 'online', accepting: false, reason: 'pool_update' };
|
|
919
|
+
const free = freeBytes(path.join(ctx.workRoot, 'runs'));
|
|
920
|
+
if (free && free < settings().limits.minFreeBytes) return { name: 'online', accepting: false, reason: 'disk_low' };
|
|
921
|
+
if (!confirmed) return { name: 'online', accepting: false, reason: 'unconfirmed' };
|
|
922
|
+
if (outdated) return { name: 'online', accepting: false, reason: 'outdated' };
|
|
923
|
+
return { name: 'online', accepting: true, reason: '' };
|
|
924
|
+
};
|
|
925
|
+
let maintenance = null;
|
|
926
|
+
let jobs = null;
|
|
927
|
+
const publish = () => {
|
|
928
|
+
if (!jobs) return;
|
|
929
|
+
const info = systemInfo(ctx);
|
|
930
|
+
state.set({
|
|
931
|
+
instance: { pid: process.pid, startedAt, version: VERSION, node: process.versions.node, service: process.env.GC_RUNNER_SERVICE || 'foreground' },
|
|
932
|
+
state: acceptingState(),
|
|
933
|
+
connection: { ...connection },
|
|
934
|
+
machine: { name: registeredName || ctx.config.machineName || os.hostname(), confirmed, role },
|
|
935
|
+
capabilities,
|
|
936
|
+
jobs: jobs.snapshot(),
|
|
937
|
+
maintenance: maintenance ? maintenance.snapshot() : {},
|
|
938
|
+
paths: { programHome: ctx.paths.baseDir, workRoot: ctx.workRoot, logFile: ctx.paths.logFile, controlSocket },
|
|
939
|
+
resources: { workRootFree: info.diskAvailable, memAvailable: info.memAvailable, memTotal: info.memLimit || info.memTotal, loadAvg: info.loadAvg },
|
|
940
|
+
degraded,
|
|
941
|
+
last24h: { ...countResults(lastDay()), lastError: lastErrorOf(recent) },
|
|
942
|
+
});
|
|
943
|
+
};
|
|
944
|
+
// What has gone wrong, and the clone / pool as the website should see them
|
|
945
|
+
// (a daily refresh changes the commit; the next heartbeat reports it).
|
|
946
|
+
const refreshDegraded = () => {
|
|
947
|
+
if (maintenance) {
|
|
948
|
+
degraded = maintenance.degraded();
|
|
949
|
+
const repo = maintenance.repoState();
|
|
950
|
+
const workAgent = { commit: repo.commit, committedAt: repo.committedAt, repos: repo.repos, ascend: repo.ascend };
|
|
951
|
+
if (JSON.stringify(workAgent) !== JSON.stringify(capabilities.workAgent)) capabilities = { ...capabilities, workAgent };
|
|
952
|
+
}
|
|
953
|
+
publish();
|
|
954
|
+
};
|
|
955
|
+
const recheck = async () => {
|
|
956
|
+
const fresh = await doctorFor(ctx);
|
|
957
|
+
capabilities = fresh.capabilities;
|
|
958
|
+
if (fresh.claude.path) jobs.claudePath = fresh.claude.path;
|
|
959
|
+
refreshDegraded();
|
|
960
|
+
return fresh;
|
|
961
|
+
};
|
|
962
|
+
|
|
963
|
+
jobs = new JobManager({
|
|
627
964
|
client,
|
|
628
965
|
workAgent: ctx.workAgent,
|
|
629
966
|
workRoot: ctx.workRoot,
|
|
@@ -631,105 +968,313 @@ async function serve(ctx, client, initial, reply) {
|
|
|
631
968
|
realHome: ctx.realHome,
|
|
632
969
|
log,
|
|
633
970
|
onFatal,
|
|
971
|
+
jobWaitMs: settings().limits.jobWaitMaxMinutes * 60_000,
|
|
972
|
+
minFreeBytes: settings().limits.minFreeBytes,
|
|
973
|
+
controlDirs: controlDirectories(ctx.paths),
|
|
974
|
+
runMode,
|
|
975
|
+
// A job starts once the start-up checks are done and no knowledge-pool update runs.
|
|
976
|
+
gate: async ({ isCancelled, timeoutMs, onWait }) => {
|
|
977
|
+
const deadline = Date.now() + timeoutMs;
|
|
978
|
+
if (!ready) {
|
|
979
|
+
onWait('等待启动检查完成后开始');
|
|
980
|
+
while (!ready && !isCancelled() && Date.now() < deadline) await sleep(500);
|
|
981
|
+
if (!ready && !isCancelled()) {
|
|
982
|
+
return { ok: false, code: 'E3201', message: '执行机器的启动检查还没有完成,任务未执行,请稍后重试' };
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
// Sent before the check found otherwise (it reports to the website at once).
|
|
986
|
+
// (Without claude at all, starting it fails with E1301 instead.)
|
|
987
|
+
if (!isCancelled() && capabilities.claude && capabilities.sandbox?.ok === false) {
|
|
988
|
+
return { ok: false, code: 'E4101', message: `执行机器的沙箱不可用(${capabilities.sandbox.reason || '原因未知'}),任务未执行` };
|
|
989
|
+
}
|
|
990
|
+
return jobs.poolGate({ isCancelled, timeoutMs: Math.max(1000, deadline - Date.now()), onWait });
|
|
991
|
+
},
|
|
992
|
+
onChange: publish,
|
|
993
|
+
onFinished: (record) => {
|
|
994
|
+
state.appendHistory(record);
|
|
995
|
+
recent.push(record);
|
|
996
|
+
publish();
|
|
997
|
+
},
|
|
634
998
|
});
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
999
|
+
maintenance = new Maintenance({
|
|
1000
|
+
workAgent: ctx.workAgent,
|
|
1001
|
+
jobs,
|
|
1002
|
+
log,
|
|
1003
|
+
paths: ctx.paths,
|
|
1004
|
+
workRoot: ctx.workRoot,
|
|
1005
|
+
settings,
|
|
1006
|
+
recheck,
|
|
1007
|
+
onChange: refreshDegraded,
|
|
1008
|
+
});
|
|
1009
|
+
|
|
1010
|
+
// The local control interface: what terminal commands ask this instance.
|
|
1011
|
+
const handlers = {
|
|
1012
|
+
ping: () => ({ pid: process.pid, version: VERSION, programHome: ctx.paths.baseDir }),
|
|
1013
|
+
status: () => {
|
|
1014
|
+
refreshDegraded();
|
|
1015
|
+
state.flush();
|
|
1016
|
+
return state.snapshot();
|
|
1017
|
+
},
|
|
1018
|
+
jobs: (params) => ({
|
|
1019
|
+
running: jobs.snapshot(),
|
|
1020
|
+
history: readHistory(ctx.paths.historyFile, {
|
|
1021
|
+
since: Number.isFinite(params.since) ? params.since : 0,
|
|
1022
|
+
limit: Number.isInteger(params.limit) ? Math.min(10_000, Math.max(1, params.limit)) : 20,
|
|
1023
|
+
failedOnly: params.failedOnly === true,
|
|
1024
|
+
runId: typeof params.runId === 'string' ? params.runId.slice(0, 100) : '',
|
|
1025
|
+
}),
|
|
1026
|
+
}),
|
|
1027
|
+
'job.cancel': (params) => {
|
|
1028
|
+
const matches = jobs.runningIds().filter((id) => matchesRunId(id, params.runId));
|
|
1029
|
+
if (matches.length > 1) throw new ControlError('E9009', `有 ${matches.length} 个运行中的任务都含有「${String(params.runId).slice(0, 40)}」,请给出完整的任务 ID`);
|
|
1030
|
+
if (!matches.length) return { runId: '', cancelled: false };
|
|
1031
|
+
return { runId: matches[0], cancelled: jobs.cancel(matches[0], { by: '本机 work-agent-runner jobs cancel' }) };
|
|
1032
|
+
},
|
|
1033
|
+
'repo.refresh': async () => {
|
|
1034
|
+
const fresh = await maintenance.refreshClone();
|
|
1035
|
+
await maintenance.runChecks().catch(() => {});
|
|
1036
|
+
return { ok: fresh.ok, commit: fresh.commit || '', reason: fresh.reason || '' };
|
|
1037
|
+
},
|
|
1038
|
+
// Now if no job runs, else queued for when none does ({ queued, reason }).
|
|
1039
|
+
'pool.update': (params, { send }) => maintenance.updatePool({ say: (line) => send('log', line) }),
|
|
1040
|
+
'pool.init': async (params, { send }) => {
|
|
1041
|
+
const repos = Array.isArray(params.repos) ? params.repos.map(String) : null;
|
|
1042
|
+
if (repos && (!repos.length || repos.length > 100 || !repos.every(validRepoName))) throw new ControlError('E9007', '仓名不正确');
|
|
1043
|
+
const busy = poolBusyInfo(ctx.paths);
|
|
1044
|
+
if (busy) throw new ControlError('E9008', `进程 ${busy.pid} 正在${busy.kind === 'init' ? '下载' : '更新'}知识仓`);
|
|
1045
|
+
const done = markPoolBusy(ctx.paths, 'init');
|
|
663
1046
|
try {
|
|
664
|
-
|
|
1047
|
+
const after = await ctx.workAgent.initPool({ repos, say: (line) => send('log', line) });
|
|
1048
|
+
prepareWorkAgentHome(ctx.paths.workAgentHome, { poolDir: ctx.workAgent.mountablePool(), link: ctx.paths.workAgentLink });
|
|
1049
|
+
await maintenance.runChecks().catch(() => {});
|
|
1050
|
+
return { repos: after.repos };
|
|
1051
|
+
} finally {
|
|
1052
|
+
done();
|
|
1053
|
+
}
|
|
1054
|
+
},
|
|
1055
|
+
// A terminal's doctor / setup: checked here, reported to the website from here (3.11).
|
|
1056
|
+
doctor: async () => {
|
|
1057
|
+
const fresh = await maintenance.runChecks();
|
|
1058
|
+
let answer = null;
|
|
1059
|
+
let note = '';
|
|
1060
|
+
try {
|
|
1061
|
+
answer = await connect(ctx, client, capabilities);
|
|
1062
|
+
registeredName = answer.name || registeredName;
|
|
1063
|
+
confirmed = answer.confirmed !== false;
|
|
1064
|
+
outdated = Boolean(answer.outdated);
|
|
665
1065
|
} catch (error) {
|
|
666
|
-
|
|
1066
|
+
if (fatalFor(error)) onFatal(error);
|
|
1067
|
+
note = `没能把结果报给网站(${error instanceof ApiError ? error.message : networkReason(error)}),下次心跳时再报`;
|
|
1068
|
+
}
|
|
1069
|
+
publish();
|
|
1070
|
+
return {
|
|
1071
|
+
capabilities: fresh.capabilities,
|
|
1072
|
+
tools: fresh.tools,
|
|
1073
|
+
claude: fresh.claude,
|
|
1074
|
+
claudeVersion: fresh.claudeVersion,
|
|
1075
|
+
workAgent: ctx.workAgent.state(),
|
|
1076
|
+
features: answer?.features || null,
|
|
1077
|
+
outdated: Boolean(answer?.outdated),
|
|
1078
|
+
confirmed: answer ? answer.confirmed !== false : null,
|
|
1079
|
+
note,
|
|
1080
|
+
};
|
|
1081
|
+
},
|
|
1082
|
+
// `reload`: what applies without a restart (the next job, the next schedule).
|
|
1083
|
+
'config.reload': () => {
|
|
1084
|
+
const fresh = loadConfig(ctx.paths);
|
|
1085
|
+
const changed = [];
|
|
1086
|
+
for (const key of ['isolation', 'maintenance', 'limits']) {
|
|
1087
|
+
if (JSON.stringify(fresh[key]) === JSON.stringify(ctx.config[key])) continue;
|
|
1088
|
+
changed.push(key);
|
|
1089
|
+
if (fresh[key] === undefined) delete ctx.config[key];
|
|
1090
|
+
else ctx.config[key] = fresh[key];
|
|
667
1091
|
}
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
1092
|
+
jobs.jobWaitMs = settings().limits.jobWaitMaxMinutes * 60_000;
|
|
1093
|
+
jobs.minFreeBytes = settings().limits.minFreeBytes;
|
|
1094
|
+
if (changed.includes('maintenance')) {
|
|
1095
|
+
maintenance.scheduleRepo();
|
|
1096
|
+
maintenance.schedulePool();
|
|
1097
|
+
}
|
|
1098
|
+
const restartRequired = ['server', 'token', 'clientId', 'workRoot', 'workAgentHome', 'workAgentRepoDir', 'ascendReposDir', 'workAgentRepo'].filter(
|
|
1099
|
+
(key) => JSON.stringify(fresh[key] ?? '') !== JSON.stringify(ctx.config[key] ?? ''),
|
|
1100
|
+
);
|
|
1101
|
+
refreshDegraded();
|
|
1102
|
+
return { changed, restartRequired };
|
|
1103
|
+
},
|
|
672
1104
|
};
|
|
673
|
-
|
|
1105
|
+
let control = null;
|
|
1106
|
+
try {
|
|
1107
|
+
control = await startControlServer({ paths: ctx.paths, handlers, log });
|
|
1108
|
+
controlSocket = control.socket;
|
|
1109
|
+
} catch (error) {
|
|
1110
|
+
// The instance works without it; terminal commands then act themselves.
|
|
1111
|
+
log.warn(`本机管理接口没有启动(${error.message}):status、jobs、update 等命令只能读取记录`);
|
|
1112
|
+
}
|
|
1113
|
+
|
|
674
1114
|
let stopping = false;
|
|
675
1115
|
const onSignal = (signal) => {
|
|
676
|
-
if (stopping)
|
|
1116
|
+
if (stopping) {
|
|
1117
|
+
// A second Ctrl+C: no more waiting.
|
|
1118
|
+
log.warn(`再次收到 ${signal},立即退出`);
|
|
1119
|
+
jobs.killAll();
|
|
1120
|
+
ctx.workAgent.stop();
|
|
1121
|
+
state.flush();
|
|
1122
|
+
process.exit(130);
|
|
1123
|
+
}
|
|
677
1124
|
stopping = true;
|
|
678
1125
|
log.info(`收到 ${signal},正在停止(结束运行中的任务)……`);
|
|
679
1126
|
controller.abort();
|
|
680
1127
|
};
|
|
681
1128
|
process.on('SIGINT', onSignal);
|
|
682
1129
|
process.on('SIGTERM', onSignal);
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
capabilities: { current: () => capabilities },
|
|
690
|
-
system: { current: () => systemInfo(ctx) },
|
|
691
|
-
confirmed: reply.confirmed !== false,
|
|
692
|
-
heartbeatMs: reply.heartbeatMs,
|
|
693
|
-
signal: controller.signal,
|
|
1130
|
+
// The terminal of a foreground program was closed: stop the same way (jobs
|
|
1131
|
+
// run in process groups of their own and would go on alone), with nowhere
|
|
1132
|
+
// left to print to.
|
|
1133
|
+
process.on('SIGHUP', () => {
|
|
1134
|
+
for (const stream of [process.stdout, process.stderr]) stream.on('error', () => {});
|
|
1135
|
+
onSignal('SIGHUP');
|
|
694
1136
|
});
|
|
695
|
-
|
|
696
|
-
|
|
1137
|
+
|
|
1138
|
+
let result = { code: 0, message: '' };
|
|
1139
|
+
try {
|
|
1140
|
+
publish();
|
|
1141
|
+
if (!reply) {
|
|
1142
|
+
reply = await connectSaved(ctx, client, capabilities, {
|
|
1143
|
+
signal: controller.signal,
|
|
1144
|
+
onRetry: (reason) => {
|
|
1145
|
+
connection.lastError = reason;
|
|
1146
|
+
publish();
|
|
1147
|
+
},
|
|
1148
|
+
});
|
|
1149
|
+
sayRegistered(ctx, reply, (line) => log.info(line));
|
|
1150
|
+
// Before the checks every feature reads as unavailable: their result follows.
|
|
1151
|
+
if (checksPending) log.info('正在检查沙箱和 work-agent 仓库,检查完成前收到的任务会等待');
|
|
1152
|
+
else printFeatures(reply, (line) => log.info(line));
|
|
1153
|
+
registeredName = reply.name || registeredName;
|
|
1154
|
+
role = reply.role === 'server' ? 'server' : 'user';
|
|
1155
|
+
confirmed = reply.confirmed !== false;
|
|
1156
|
+
outdated = Boolean(reply.outdated);
|
|
1157
|
+
}
|
|
1158
|
+
maintenance.start();
|
|
1159
|
+
if (checksPending) {
|
|
1160
|
+
// The clone and the sandbox check, while the website already sees this
|
|
1161
|
+
// machine; then the result to the website at once (POST /connect is the
|
|
1162
|
+
// way to apply capabilities now), and its verdict per feature to the log.
|
|
1163
|
+
(async () => {
|
|
1164
|
+
let checked = null;
|
|
1165
|
+
try {
|
|
1166
|
+
await maintenance.refreshClone();
|
|
1167
|
+
checked = await maintenance.runChecks().catch((error) => {
|
|
1168
|
+
log.warn(`启动检查失败:${error.message}`);
|
|
1169
|
+
return null;
|
|
1170
|
+
});
|
|
1171
|
+
} finally {
|
|
1172
|
+
ready = true;
|
|
1173
|
+
publish();
|
|
1174
|
+
}
|
|
1175
|
+
const info = (line) => log.info(line);
|
|
1176
|
+
printWorkAgent(ctx.workAgent.state(), info);
|
|
1177
|
+
if (checked) printDoctor(checked, info);
|
|
1178
|
+
if (controller.signal.aborted) return;
|
|
1179
|
+
try {
|
|
1180
|
+
const fresh = await connect(ctx, client, capabilities);
|
|
1181
|
+
registeredName = fresh.name || registeredName;
|
|
1182
|
+
confirmed = fresh.confirmed !== false;
|
|
1183
|
+
outdated = Boolean(fresh.outdated);
|
|
1184
|
+
printFeatures(fresh, info);
|
|
1185
|
+
} catch (error) {
|
|
1186
|
+
if (fatalFor(error)) onFatal(error);
|
|
1187
|
+
else log.warn(`没能把检查结果报给网站(${error instanceof ApiError ? error.message : networkReason(error)}),下次心跳时再报`);
|
|
1188
|
+
}
|
|
1189
|
+
log.info('启动检查完成');
|
|
1190
|
+
publish();
|
|
1191
|
+
})();
|
|
1192
|
+
} else {
|
|
1193
|
+
refreshDegraded();
|
|
1194
|
+
}
|
|
1195
|
+
say('等待任务……(Ctrl+C 退出;后台运行:work-agent-runner service install;查看状态:work-agent-runner status)');
|
|
1196
|
+
result = await runConnection({
|
|
1197
|
+
client,
|
|
1198
|
+
jobs,
|
|
1199
|
+
log,
|
|
1200
|
+
version: VERSION,
|
|
1201
|
+
connect: () => connect(ctx, client, capabilities),
|
|
1202
|
+
capabilities: { current: () => capabilities },
|
|
1203
|
+
system: { current: () => systemInfo(ctx) },
|
|
1204
|
+
confirmed,
|
|
1205
|
+
heartbeatMs: reply.heartbeatMs,
|
|
1206
|
+
signal: controller.signal,
|
|
1207
|
+
// Connected = the control channel is open (jobs only come through it).
|
|
1208
|
+
onStatus: ({ confirmed: nowConfirmed, ...patch }) => {
|
|
1209
|
+
Object.assign(connection, patch);
|
|
1210
|
+
if (typeof nowConfirmed === 'boolean') confirmed = nowConfirmed;
|
|
1211
|
+
publish();
|
|
1212
|
+
},
|
|
1213
|
+
onReply: (fresh) => {
|
|
1214
|
+
if (fresh?.role) role = fresh.role === 'server' ? 'server' : 'user';
|
|
1215
|
+
if (typeof fresh?.name === 'string' && fresh.name) registeredName = fresh.name;
|
|
1216
|
+
if (typeof fresh?.confirmed === 'boolean') confirmed = fresh.confirmed;
|
|
1217
|
+
publish();
|
|
1218
|
+
},
|
|
1219
|
+
});
|
|
1220
|
+
} catch (error) {
|
|
1221
|
+
if (!(error instanceof ExitError) || error.code !== 0) throw error;
|
|
1222
|
+
} finally {
|
|
1223
|
+
maintenance.stop();
|
|
1224
|
+
ctx.workAgent.stop();
|
|
1225
|
+
await jobs.stopAll(5000);
|
|
1226
|
+
connection.connected = false;
|
|
1227
|
+
publish();
|
|
1228
|
+
state.flush();
|
|
1229
|
+
await control?.close();
|
|
1230
|
+
}
|
|
697
1231
|
const outcome = fatal || result;
|
|
698
|
-
ctx.
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
1232
|
+
if (outcome.clearToken && !clearToken(ctx, ctx.config.token)) {
|
|
1233
|
+
// `login` saved a new token while this one was in use: exit 1 so a service
|
|
1234
|
+
// restarts and connects with it.
|
|
1235
|
+
log.warn('使用中的令牌已失效,配置文件里已经是新的令牌:重新启动后使用它');
|
|
1236
|
+
return 1;
|
|
703
1237
|
}
|
|
704
1238
|
if (outcome.code) log.error(outcome.message);
|
|
705
1239
|
else log.info('已停止');
|
|
706
1240
|
return outcome.code || 0;
|
|
707
1241
|
}
|
|
708
1242
|
|
|
1243
|
+
// ---- Terminal commands -------------------------------------------------------
|
|
1244
|
+
|
|
709
1245
|
async function login(values) {
|
|
710
1246
|
checkSystem();
|
|
711
1247
|
const restarted = await applyProxy();
|
|
712
1248
|
if (restarted !== null) return restarted;
|
|
713
1249
|
const ctx = loadContext(values);
|
|
714
1250
|
if (values['new-id']) {
|
|
715
|
-
|
|
1251
|
+
const clientId = newClientId();
|
|
716
1252
|
// A new machine on the website: ask for its name again (unless --name gave one).
|
|
717
|
-
|
|
718
|
-
|
|
1253
|
+
const forgetName = values.name === undefined;
|
|
1254
|
+
updateConfig(ctx.paths, (config) => {
|
|
1255
|
+
config.clientId = clientId;
|
|
1256
|
+
if (forgetName) delete config.machineName;
|
|
1257
|
+
});
|
|
1258
|
+
ctx.config.clientId = clientId;
|
|
1259
|
+
if (forgetName) ctx.config.machineName = '';
|
|
719
1260
|
say('已生成新的机器标识:这台机器在网页上会作为新机器出现,需要在网页上确认');
|
|
720
1261
|
}
|
|
721
1262
|
if (!values['token-stdin'] && !isInteractive()) throw new ExitError(ATTENTION, 'login 需要在终端里运行(脚本里请用 --token-stdin)');
|
|
722
1263
|
say('检查依赖和沙箱……');
|
|
723
1264
|
const result = await doctorFor(ctx);
|
|
724
1265
|
await obtainToken(ctx, { fromStdin: Boolean(values['token-stdin']), capabilities: result.capabilities });
|
|
1266
|
+
const running = runningInstance(ctx);
|
|
1267
|
+
if (running) say(`注意:正在运行的程序(pid ${running})还在用原来的令牌;运行 work-agent-runner service restart(或重新启动前台程序)改用新令牌`);
|
|
725
1268
|
return 0;
|
|
726
1269
|
}
|
|
727
1270
|
|
|
728
1271
|
function logout(values) {
|
|
729
1272
|
const ctx = loadContext(values, { workRoot: false });
|
|
730
|
-
|
|
731
|
-
ctx.config
|
|
732
|
-
|
|
1273
|
+
let had = false;
|
|
1274
|
+
updateConfig(ctx.paths, (config) => {
|
|
1275
|
+
had = Boolean(config.token);
|
|
1276
|
+
config.token = '';
|
|
1277
|
+
});
|
|
733
1278
|
say(had ? '已清除本机保存的令牌(机器标识保留)' : '本机没有保存令牌');
|
|
734
1279
|
return 0;
|
|
735
1280
|
}
|
|
@@ -740,8 +1285,12 @@ async function setup(values) {
|
|
|
740
1285
|
if (restarted !== null) return restarted;
|
|
741
1286
|
if (!isInteractive()) throw new ExitError(ATTENTION, 'setup 需要在终端里运行(安装前会请你确认)');
|
|
742
1287
|
const ctx = loadContext(values);
|
|
1288
|
+
const instance = await pingInstance(ctx.paths);
|
|
743
1289
|
say('检查 work-agent 仓库……');
|
|
744
|
-
|
|
1290
|
+
if (instance) {
|
|
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));
|
|
745
1294
|
say('检查依赖和沙箱……');
|
|
746
1295
|
let result = await doctorFor(ctx);
|
|
747
1296
|
let client = null;
|
|
@@ -749,7 +1298,8 @@ async function setup(values) {
|
|
|
749
1298
|
if (ctx.config.token) {
|
|
750
1299
|
client = clientFor(ctx);
|
|
751
1300
|
try {
|
|
752
|
-
|
|
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);
|
|
753
1303
|
} catch (error) {
|
|
754
1304
|
say(`无法从网站读取要求(${error.message}),按默认要求检查`);
|
|
755
1305
|
client = null;
|
|
@@ -764,38 +1314,83 @@ async function setup(values) {
|
|
|
764
1314
|
confirm: (question) => askYesNo(question),
|
|
765
1315
|
say,
|
|
766
1316
|
});
|
|
767
|
-
ctx
|
|
768
|
-
save(ctx);
|
|
1317
|
+
saveField(ctx, 'setupDone', true);
|
|
769
1318
|
if (outcome.ran) {
|
|
770
1319
|
say('重新检查……');
|
|
771
1320
|
result = await doctorFor(ctx);
|
|
772
1321
|
printDoctor(result);
|
|
773
1322
|
}
|
|
1323
|
+
// A clone that failed for want of git is made now that setup installed it.
|
|
1324
|
+
await ensureClone(ctx);
|
|
774
1325
|
// After the tools: the pool is searched with rg.
|
|
775
1326
|
await offerPool(ctx, values);
|
|
776
|
-
if (
|
|
1327
|
+
if (instance) {
|
|
1328
|
+
// The program checks again and reports this machine to the website itself.
|
|
1329
|
+
const checked = await askInstance(ctx, 'doctor', {}, { quiet: true }).catch(() => null);
|
|
1330
|
+
if (checked?.features) reply = checked;
|
|
1331
|
+
} else if (client) {
|
|
1332
|
+
reply = await connect(ctx, client, (await doctorFor(ctx)).capabilities).catch(() => reply);
|
|
1333
|
+
}
|
|
777
1334
|
printFeatures(reply);
|
|
778
1335
|
return outcome.failed.length ? 1 : 0;
|
|
779
1336
|
}
|
|
780
1337
|
|
|
781
|
-
/**
|
|
1338
|
+
/**
|
|
1339
|
+
* `update`: both repositories, now. With the program running, it does both
|
|
1340
|
+
* (the knowledge pool as soon as no job runs: a `git pull` must not replace
|
|
1341
|
+
* files a job is reading); otherwise this process does.
|
|
1342
|
+
*/
|
|
782
1343
|
async function update(values) {
|
|
783
1344
|
checkSystem();
|
|
784
1345
|
const restarted = await applyProxy();
|
|
785
1346
|
if (restarted !== null) return restarted;
|
|
786
1347
|
const ctx = loadContext(values);
|
|
1348
|
+
const instance = await pingInstance(ctx.paths);
|
|
1349
|
+
if (instance) {
|
|
1350
|
+
say(`程序正在运行(pid ${instance.pid}),由它来更新:`);
|
|
1351
|
+
const repo = await askInstance(ctx, 'repo.refresh');
|
|
1352
|
+
say(repo.ok ? `✓ work-agent ${repo.commit.slice(0, 7)}` : `✗ work-agent 仓库不可用:${repo.reason}`);
|
|
1353
|
+
if (ctx.workAgent.mountablePool()) {
|
|
1354
|
+
const pool = await askInstance(ctx, 'pool.update');
|
|
1355
|
+
if (pool?.queued) say(`知识仓:${pool.reason},已安排在任务结束后更新(work-agent-runner status 可以看到)`);
|
|
1356
|
+
else if (pool?.skipped) say(`知识仓:${pool.skipped}`);
|
|
1357
|
+
else say(pool?.result === 'ok' ? '✓ 知识仓已更新' : `✗ 知识仓更新失败:${pool?.error || '原因未知'}`);
|
|
1358
|
+
if (pool?.result === 'failed') return 1;
|
|
1359
|
+
}
|
|
1360
|
+
return repo.ok ? 0 : 1;
|
|
1361
|
+
}
|
|
1362
|
+
const running = runningInstance(ctx);
|
|
787
1363
|
let failed = false;
|
|
788
1364
|
try {
|
|
789
1365
|
const state = await ctx.workAgent.refresh();
|
|
790
1366
|
printWorkAgent(state);
|
|
791
1367
|
failed = !state.ok;
|
|
792
|
-
if (ctx.workAgent.mountablePool())
|
|
1368
|
+
if (ctx.workAgent.mountablePool()) {
|
|
1369
|
+
const busy = poolBusyInfo(ctx.paths);
|
|
1370
|
+
if (running) {
|
|
1371
|
+
// An older program without the control interface: it updates when idle.
|
|
1372
|
+
requestPoolUpdate(ctx.paths);
|
|
1373
|
+
const service = serviceStatus();
|
|
1374
|
+
say(`程序正在运行(pid ${running}):已请它在没有任务时更新知识仓${service.installed ? `(${service.logHint})` : ''}`);
|
|
1375
|
+
} else if (busy) {
|
|
1376
|
+
say(`另一个进程(pid ${busy.pid})正在${busy.kind === 'init' ? '下载' : '更新'}知识仓,请等它结束后再试`);
|
|
1377
|
+
failed = true;
|
|
1378
|
+
} else {
|
|
1379
|
+
const done = markPoolBusy(ctx.paths, 'update');
|
|
1380
|
+
try {
|
|
1381
|
+
await withStopOnSignal(ctx, () => ctx.workAgent.updatePool({ say }));
|
|
1382
|
+
} finally {
|
|
1383
|
+
done();
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
793
1387
|
} catch (error) {
|
|
1388
|
+
if (error instanceof ExitError) throw error;
|
|
794
1389
|
say(error.message);
|
|
795
1390
|
failed = true;
|
|
796
1391
|
}
|
|
797
1392
|
if (ctx.config.token) {
|
|
798
|
-
// So the website shows the new commit without waiting for the
|
|
1393
|
+
// So the website shows the new commit without waiting for the next start.
|
|
799
1394
|
try {
|
|
800
1395
|
printFeatures(await connect(ctx, clientFor(ctx), (await doctorFor(ctx)).capabilities));
|
|
801
1396
|
} catch {
|
|
@@ -810,6 +1405,23 @@ async function doctor(values) {
|
|
|
810
1405
|
const restarted = await applyProxy();
|
|
811
1406
|
if (restarted !== null) return restarted;
|
|
812
1407
|
const ctx = loadContext(values);
|
|
1408
|
+
const delegated = await askInstance(ctx, 'doctor', {}, { quiet: true });
|
|
1409
|
+
if (delegated) {
|
|
1410
|
+
// The running program checked its own environment and reported it to the
|
|
1411
|
+
// website itself; nothing is sent from this terminal.
|
|
1412
|
+
if (values.json) {
|
|
1413
|
+
const { capabilities, workAgent, claude, features, confirmed, note } = delegated;
|
|
1414
|
+
say(JSON.stringify({ version: VERSION, capabilities, workAgent, claudePath: claude.path, features, confirmed, note, viaInstance: true }, null, 2));
|
|
1415
|
+
return 0;
|
|
1416
|
+
}
|
|
1417
|
+
say(`GitCode Agent 执行机器 ${VERSION} · 由运行中的程序检查,结果由它报给网站`);
|
|
1418
|
+
printWorkAgent(delegated.workAgent);
|
|
1419
|
+
printDoctor(delegated);
|
|
1420
|
+
printFeatures(delegated);
|
|
1421
|
+
if (delegated.confirmed === false) say('这台机器还没有在网页上确认,确认后才会收到任务(在线 Agent → 模型配置 → 执行机器)');
|
|
1422
|
+
if (delegated.note) say(delegated.note);
|
|
1423
|
+
return 0;
|
|
1424
|
+
}
|
|
813
1425
|
const result = await doctorFor(ctx);
|
|
814
1426
|
let reply = null;
|
|
815
1427
|
let note = '';
|
|
@@ -837,47 +1449,289 @@ async function doctor(values) {
|
|
|
837
1449
|
return 0;
|
|
838
1450
|
}
|
|
839
1451
|
|
|
1452
|
+
/**
|
|
1453
|
+
* The instance's status: asked live, else its last status.json.
|
|
1454
|
+
* { snapshot, live, silent (why a running one did not answer), holder, alive }.
|
|
1455
|
+
*/
|
|
1456
|
+
async function currentStatus(ctx) {
|
|
1457
|
+
let snapshot = null;
|
|
1458
|
+
let live = false;
|
|
1459
|
+
let silent = '';
|
|
1460
|
+
try {
|
|
1461
|
+
snapshot = await controlRequest(ctx.paths, 'status', {}, { timeoutMs: 10_000 });
|
|
1462
|
+
live = true;
|
|
1463
|
+
} catch (error) {
|
|
1464
|
+
if (!(error instanceof NotRunningError)) silent = error.message;
|
|
1465
|
+
}
|
|
1466
|
+
if (!snapshot) snapshot = readStatus(ctx.paths.statusFile);
|
|
1467
|
+
const holder = lockHolder(ctx.paths.lockFile);
|
|
1468
|
+
return { snapshot, live, silent, holder, alive: isRunnerAlive(holder) };
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
/** `status --watch`: the live part, redrawn every 2 seconds until Ctrl+C. */
|
|
1472
|
+
async function watchStatus(ctx) {
|
|
1473
|
+
if (!process.stdout.isTTY) throw new ExitError(1, 'status --watch 需要在终端里运行(脚本里请用 status --json)');
|
|
1474
|
+
process.on('SIGINT', () => {
|
|
1475
|
+
process.stdout.write('\n');
|
|
1476
|
+
process.exit(0);
|
|
1477
|
+
});
|
|
1478
|
+
for (;;) {
|
|
1479
|
+
const { snapshot, live, silent, holder, alive } = await currentStatus(ctx);
|
|
1480
|
+
const silentPid = !live && alive ? holder : 0;
|
|
1481
|
+
const lines = snapshot ? statusLines(snapshot, { stale: !live, silentPid, silentReason: silent }) : ['程序没有在运行,也还没有状态记录'];
|
|
1482
|
+
process.stdout.write(`\x1b[H\x1b[2J${lines.join('\n')}\n\n每 2 秒刷新 · Ctrl+C 退出\n`);
|
|
1483
|
+
await sleep(2000);
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
|
|
840
1487
|
async function status(values) {
|
|
841
1488
|
checkSystem();
|
|
842
1489
|
const restarted = await applyProxy();
|
|
843
1490
|
if (restarted !== null) return restarted;
|
|
844
1491
|
const ctx = loadContext(values, { workRoot: false });
|
|
1492
|
+
if (values.watch) {
|
|
1493
|
+
if (values.json) throw new ExitError(1, '--watch 和 --json 不能一起用');
|
|
1494
|
+
return watchStatus(ctx);
|
|
1495
|
+
}
|
|
845
1496
|
const { config } = ctx;
|
|
1497
|
+
const { snapshot, live, silent, holder, alive } = await currentStatus(ctx);
|
|
1498
|
+
const healthy = live && snapshot?.connection?.connected && snapshot?.state?.accepting && !(snapshot?.degraded || []).length;
|
|
1499
|
+
const code = !live || !snapshot?.connection?.connected ? 2 : healthy ? 0 : 1;
|
|
1500
|
+
const service = serviceStatus();
|
|
1501
|
+
if (values.json) {
|
|
1502
|
+
say(JSON.stringify({ running: live, pid: alive ? holder : 0, snapshot, service, configFile: ctx.paths.configFile }, null, 2));
|
|
1503
|
+
return code;
|
|
1504
|
+
}
|
|
846
1505
|
say(`网站:${ctx.server}`);
|
|
847
1506
|
say(`令牌:${config.token ? `${config.token.slice(0, 12)}…` : '未登录(运行 work-agent-runner login)'}`);
|
|
848
1507
|
say(`机器标识:${config.clientId}`);
|
|
849
1508
|
say(`登记名称:${config.machineName || `${os.hostname()}(主机名)`}`);
|
|
850
|
-
say(`程序目录:${ctx.paths.baseDir}`);
|
|
851
|
-
say(`任务目录:${path.join(config.workRoot || ctx.paths.runsRoot, 'runs')}`);
|
|
852
|
-
const repo = ctx.workAgent.state();
|
|
853
|
-
say(`work-agent 仓库:${repo.ok ? `${repo.commit.slice(0, 7)}(${ctx.workAgent.repoDir})` : repo.reason}`);
|
|
854
|
-
say(`WORK_AGENT_HOME:${ctx.paths.workAgentHome}`);
|
|
855
|
-
const poolRepos = ctx.workAgent.poolRepos();
|
|
856
|
-
say(`知识仓:${poolRepos.length ? `${poolRepos.length} 个仓(${poolRepos.join('、')})` : '未初始化'}(${ctx.paths.poolDir})`);
|
|
857
|
-
say(`系统:${describeSystem(systemInfo(ctx))}`);
|
|
858
1509
|
say(`配置文件:${ctx.paths.configFile}`);
|
|
859
|
-
|
|
860
|
-
say(`后台服务:${service.installed ? service.state : '未安装'}${service.installed ? `(${service.logHint})` : ''}`);
|
|
1510
|
+
say(`后台服务:${service.installed ? `${service.state}(${service.name};${service.logHint})` : '未安装'}`);
|
|
861
1511
|
if (legacyServiceInstalled()) say(LEGACY_SERVICE_HINT);
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
if (!
|
|
1512
|
+
say('');
|
|
1513
|
+
const silentPid = !live && alive ? holder : 0;
|
|
1514
|
+
if (snapshot) for (const line of statusLines(snapshot, { stale: !live, silentPid, silentReason: silent })) say(line);
|
|
1515
|
+
else if (silentPid) say(`程序在运行(pid ${holder}),但没有回应管理接口${silent ? `(${silent})` : '(0.0.5 及以前的版本没有这个接口)'}`);
|
|
1516
|
+
else say('程序没有在运行,也还没有状态记录');
|
|
1517
|
+
say('');
|
|
1518
|
+
say(`目录:程序目录 ${ctx.paths.baseDir} · 任务目录 ${path.join(config.workRoot || ctx.paths.runsRoot, 'runs')} · 日志 ${ctx.paths.logFile}(完整列表:work-agent-runner paths)`);
|
|
1519
|
+
const requested = poolUpdateRequested(ctx.paths);
|
|
1520
|
+
if (requested && !live) say(`已请求更新知识仓(${requested}),等待程序在没有任务时执行`);
|
|
1521
|
+
if (!live && config.token) {
|
|
1522
|
+
try {
|
|
1523
|
+
// A request with no effect (it must not be /heartbeat: reporting no running
|
|
1524
|
+
// jobs from a second process would make the website fail this machine's jobs).
|
|
1525
|
+
await clientFor(ctx).request('GET', '/ping');
|
|
1526
|
+
say('连接测试:令牌有效,网站可以连上');
|
|
1527
|
+
} catch (error) {
|
|
1528
|
+
if (error instanceof ApiError) {
|
|
1529
|
+
const text = {
|
|
1530
|
+
404: '网站版本过旧(没有 /ping),请联系管理员部署新版网站',
|
|
1531
|
+
401: '令牌无效或已删除(运行 work-agent-runner login)',
|
|
1532
|
+
403: '这台机器已被封禁',
|
|
1533
|
+
409: '令牌有效,这台机器尚未登记(运行 work-agent-runner 会自动登记,之后在网页上确认)',
|
|
1534
|
+
}[error.status] || error.message;
|
|
1535
|
+
say(`连接测试:${text}`);
|
|
1536
|
+
} else say(`连接测试:失败(${networkReason(error)})`);
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
return code;
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
async function jobsCommand(values, action, runId) {
|
|
1543
|
+
checkSystem();
|
|
1544
|
+
const ctx = loadContext(values, { workRoot: false });
|
|
1545
|
+
if (action === 'cancel') {
|
|
1546
|
+
if (!runId) throw new ExitError(1, '用法:work-agent-runner jobs cancel <任务 ID>');
|
|
1547
|
+
const answer = await askInstance(ctx, 'job.cancel', { runId }, { quiet: true });
|
|
1548
|
+
if (!answer) throw new ExitError(2, '程序没有在运行');
|
|
1549
|
+
say(answer.cancelled ? `已取消任务 ${answer.runId}(网页上会显示为已取消)` : `没有找到运行中的任务 ${runId}`);
|
|
1550
|
+
return answer.cancelled ? 0 : 1;
|
|
1551
|
+
}
|
|
1552
|
+
if (action === 'show') {
|
|
1553
|
+
if (!runId) throw new ExitError(1, '用法:work-agent-runner jobs show <任务 ID>');
|
|
1554
|
+
const live = await askInstance(ctx, 'jobs', { runId, limit: 1 }, { quiet: true });
|
|
1555
|
+
const running = live?.running?.find((job) => matchesRunId(job.runId, runId));
|
|
1556
|
+
const record = running || (live?.history || readHistory(ctx.paths.historyFile, { runId, limit: 1 }))[0];
|
|
1557
|
+
if (values.json) {
|
|
1558
|
+
say(JSON.stringify(record || null, null, 2));
|
|
1559
|
+
return record ? 0 : 1;
|
|
1560
|
+
}
|
|
1561
|
+
if (!record) throw new ExitError(1, `没有找到任务 ${runId}(只保留最近 1000 个或 30 天内的任务)`);
|
|
1562
|
+
for (const line of jobDetailLines(record)) say(line);
|
|
1563
|
+
return 0;
|
|
1564
|
+
}
|
|
1565
|
+
if (action) throw new ExitError(1, '用法:work-agent-runner jobs [show|cancel <任务 ID>] [--failed] [--since 24h] [-n 20] [--json]');
|
|
1566
|
+
const since = parseSince(values.since);
|
|
1567
|
+
const params = { since: since ? Date.now() - since : 0, limit: parseCount(values.lines, 20), failedOnly: Boolean(values.failed) };
|
|
1568
|
+
const live = await askInstance(ctx, 'jobs', params, { quiet: true });
|
|
1569
|
+
const data = live || { running: [], history: readHistory(ctx.paths.historyFile, params) };
|
|
1570
|
+
if (values.json) {
|
|
1571
|
+
say(JSON.stringify({ running: data.running, history: data.history, live: Boolean(live) }, null, 2));
|
|
1572
|
+
return 0;
|
|
1573
|
+
}
|
|
1574
|
+
if (!live) say('(程序没有在运行,以下来自任务记录)');
|
|
1575
|
+
for (const line of jobsLines(data, { failedOnly: params.failedOnly })) say(line);
|
|
1576
|
+
return 0;
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
/** "2026-12-01 10:12:03 …" → that time (ms), NaN for lines without one. */
|
|
1580
|
+
function lineTime(line) {
|
|
1581
|
+
const match = /^(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)/.exec(line);
|
|
1582
|
+
if (!match) return Number.NaN;
|
|
1583
|
+
const [, year, month, day, hour, minute, second] = match.map(Number);
|
|
1584
|
+
return new Date(year, month - 1, day, hour, minute, second).getTime();
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
async function logs(values) {
|
|
1588
|
+
checkSystem();
|
|
1589
|
+
const ctx = loadContext(values, { workRoot: false });
|
|
1590
|
+
const file = ctx.paths.logFile;
|
|
1591
|
+
const count = parseCount(values.lines, 100);
|
|
1592
|
+
const since = parseSince(values.since);
|
|
1593
|
+
const from = since ? Date.now() - since : 0;
|
|
1594
|
+
const keep = (line) => line && (!values.job || line.includes(values.job)) && (!from || !(lineTime(line) < from));
|
|
1595
|
+
// Oldest file first: runner.log.4 … runner.log.1, runner.log.
|
|
1596
|
+
const files = [4, 3, 2, 1].map((index) => `${file}.${index}`).filter((name) => fs.existsSync(name));
|
|
1597
|
+
if (fs.existsSync(file)) files.push(file);
|
|
1598
|
+
if (!files.length) {
|
|
1599
|
+
say(`还没有日志(${file}):程序运行后才有${serviceStatus().installed ? `;后台服务的输出也可以看:${serviceStatus().logHint}` : ''}`);
|
|
1600
|
+
if (!values.follow) return 0;
|
|
1601
|
+
}
|
|
1602
|
+
let lines = [];
|
|
1603
|
+
for (const name of files) lines.push(...fs.readFileSync(name, 'utf8').split('\n').filter(keep));
|
|
1604
|
+
for (const line of lines.slice(-count)) say(line);
|
|
1605
|
+
lines = null;
|
|
1606
|
+
if (!values.follow) return 0;
|
|
1607
|
+
// Follow: new lines as they come, across a rotation.
|
|
1608
|
+
let offset = fs.existsSync(file) ? fs.statSync(file).size : 0;
|
|
1609
|
+
let rest = '';
|
|
1610
|
+
for (;;) {
|
|
1611
|
+
await sleep(500);
|
|
1612
|
+
let size = 0;
|
|
1613
|
+
try {
|
|
1614
|
+
size = fs.statSync(file).size;
|
|
1615
|
+
} catch {
|
|
1616
|
+
continue;
|
|
1617
|
+
}
|
|
1618
|
+
if (size < offset) offset = 0; // rotated
|
|
1619
|
+
if (size === offset) continue;
|
|
1620
|
+
const handle = fs.openSync(file, 'r');
|
|
1621
|
+
const chunk = Buffer.alloc(size - offset);
|
|
1622
|
+
fs.readSync(handle, chunk, 0, chunk.length, offset);
|
|
1623
|
+
fs.closeSync(handle);
|
|
1624
|
+
offset = size;
|
|
1625
|
+
const parts = (rest + chunk.toString('utf8')).split('\n');
|
|
1626
|
+
rest = parts.pop();
|
|
1627
|
+
for (const line of parts) if (keep(line)) say(line);
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
|
|
1631
|
+
/** `paths`: every directory this program uses, and whether it is fine. */
|
|
1632
|
+
function pathsCommand(values) {
|
|
1633
|
+
checkSystem();
|
|
1634
|
+
const ctx = loadContext(values, { workRoot: false });
|
|
1635
|
+
const { paths, config } = ctx;
|
|
1636
|
+
const uid = process.getuid();
|
|
1637
|
+
const exists = (target) => fs.existsSync(target);
|
|
1638
|
+
const owned = (target) => {
|
|
1639
|
+
try {
|
|
1640
|
+
const stat = fs.statSync(target);
|
|
1641
|
+
return `${stat.uid === uid ? '本人' : '属主不是当前用户'} · ${(stat.mode & 0o777).toString(8).padStart(4, '0')}`;
|
|
1642
|
+
} catch {
|
|
1643
|
+
return '不存在';
|
|
1644
|
+
}
|
|
1645
|
+
};
|
|
1646
|
+
const count = (dir) => {
|
|
1647
|
+
try {
|
|
1648
|
+
return fs.readdirSync(dir).length;
|
|
1649
|
+
} catch {
|
|
1650
|
+
return 0;
|
|
1651
|
+
}
|
|
1652
|
+
};
|
|
1653
|
+
const workRoot = config.workRoot || paths.runsRoot;
|
|
1654
|
+
let socket = '';
|
|
1655
|
+
let socketNote = '';
|
|
865
1656
|
try {
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
say('连接测试:正常');
|
|
1657
|
+
const where = socketLocation(paths);
|
|
1658
|
+
socket = where.socket;
|
|
1659
|
+
socketNote = `${exists(where.socket) ? '程序运行中' : '程序没有在运行'}${where.fallback ? ' · 程序目录的路径太长,放在这里' : ''}`;
|
|
870
1660
|
} catch (error) {
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
1661
|
+
socketNote = error.message;
|
|
1662
|
+
}
|
|
1663
|
+
const own = ctx.workAgent.ownership();
|
|
1664
|
+
const repo = ctx.workAgent.state();
|
|
1665
|
+
const envHome = process.env.WORK_AGENT_HOME ? path.resolve(process.env.WORK_AGENT_HOME) : '';
|
|
1666
|
+
const poolLink = path.join(paths.workAgentHome, 'ascend-repos');
|
|
1667
|
+
let poolNote = `${ctx.workAgent.poolRepos().length} 个仓`;
|
|
1668
|
+
try {
|
|
1669
|
+
if (fs.lstatSync(poolLink).isSymbolicLink()) poolNote += ` · ${poolLink} → 此处`;
|
|
1670
|
+
} catch {
|
|
1671
|
+
// No link.
|
|
1672
|
+
}
|
|
1673
|
+
const service = servicePaths();
|
|
1674
|
+
const rows = [
|
|
1675
|
+
{ label: '程序目录', path: paths.baseDir, note: owned(paths.baseDir), free: freeBytes(paths.baseDir) },
|
|
1676
|
+
{ label: '配置文件', path: paths.configFile, note: owned(paths.configFile) },
|
|
1677
|
+
{ label: '程序日志', path: paths.logFile, note: exists(paths.logFile) ? '' : '还没有' },
|
|
1678
|
+
{ label: '状态与任务记录', path: paths.stateDir },
|
|
1679
|
+
{ label: '管理接口', path: socket, note: socketNote },
|
|
1680
|
+
{
|
|
1681
|
+
label: '工作目录',
|
|
1682
|
+
path: workRoot,
|
|
1683
|
+
note: workRoot === paths.runsRoot ? '就是程序目录' : exists(path.join(workRoot, '.work-agent-runner.json')) ? '本程序的(有标记)' : '没有标记',
|
|
1684
|
+
free: freeBytes(workRoot),
|
|
1685
|
+
},
|
|
1686
|
+
{ label: ' 任务目录', path: path.join(workRoot, 'runs'), note: `${count(path.join(workRoot, 'runs'))} 项` },
|
|
1687
|
+
{ label: ' 回收站', path: path.join(workRoot, 'trash'), note: count(path.join(workRoot, 'trash')) ? `${count(path.join(workRoot, 'trash'))} 个删不掉的目录` : '空' },
|
|
1688
|
+
{ label: ' 任务归档', path: path.join(workRoot, 'archive'), note: effectiveSettings(config).limits.archiveDays ? `${count(path.join(workRoot, 'archive'))} 项` : '未启用' },
|
|
1689
|
+
{
|
|
1690
|
+
label: 'work-agent 克隆',
|
|
1691
|
+
path: paths.repoDir,
|
|
1692
|
+
note: own.kind === 'foreign' ? '不是本程序创建的,程序不会改动它' : repo.ok ? `${repo.commit.slice(0, 7)} · 本程序的` : repo.reason,
|
|
1693
|
+
},
|
|
1694
|
+
{ label: 'work-agent 的家', path: paths.workAgentHome, note: envHome && envHome !== paths.workAgentHome ? `环境变量 WORK_AGENT_HOME 是 ${envHome},以 config.json 为准` : '' },
|
|
1695
|
+
{ label: '知识仓', path: paths.poolDir, note: poolNote, free: freeBytes(paths.poolDir) },
|
|
1696
|
+
{ label: '托管 Node', path: exists(paths.nodeDir) ? paths.nodeDir : '', note: exists(paths.nodeDir) ? fs.readdirSync(paths.nodeDir).filter((name) => name.startsWith('v')).join('、') : '不需要(系统 Node 满足要求)' },
|
|
1697
|
+
{ label: '后台服务定义', path: service.file, note: exists(service.file) ? '已安装' : '未安装' },
|
|
1698
|
+
];
|
|
1699
|
+
if (values.json) {
|
|
1700
|
+
say(JSON.stringify(rows, null, 2));
|
|
1701
|
+
return 0;
|
|
1702
|
+
}
|
|
1703
|
+
for (const line of pathsLines(rows)) say(line);
|
|
1704
|
+
return 0;
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
/** `reload`: the running program applies what config.json says now (maintenance, limits, isolation). */
|
|
1708
|
+
async function reload(values) {
|
|
1709
|
+
checkSystem();
|
|
1710
|
+
const ctx = loadContext(values, { workRoot: false });
|
|
1711
|
+
const answer = await askInstance(ctx, 'config.reload', {}, { quiet: true });
|
|
1712
|
+
if (!answer) throw new ExitError(2, '程序没有在运行:下次启动时会使用 config.json 里的设置');
|
|
1713
|
+
say(answer.changed.length ? `已生效:${answer.changed.join('、')}` : 'config.json 里可以直接生效的设置没有变化');
|
|
1714
|
+
if (answer.restartRequired.length) say(`${answer.restartRequired.join('、')} 要重新启动程序才生效(work-agent-runner service restart)`);
|
|
1715
|
+
return 0;
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
async function cleanupCommand(values) {
|
|
1719
|
+
checkSystem();
|
|
1720
|
+
const ctx = loadContext(values, { workRoot: false });
|
|
1721
|
+
const home = ctx.paths.workAgentHome;
|
|
1722
|
+
const live = await askInstance(ctx, 'status', {}, { quiet: true }).catch(() => null);
|
|
1723
|
+
if (live?.jobs?.length) throw new ExitError(1, `程序正在运行 ${live.jobs.length} 个任务,请等它们结束后再清理`);
|
|
1724
|
+
say(`将清空 ${path.join(home, 'tmp')},并删除 ${path.join(home, 'logs')} 里 30 天前的日志。`);
|
|
1725
|
+
say('你手工使用 work-agent 时放在这里的文件也会被删除。');
|
|
1726
|
+
if (!values.yes) {
|
|
1727
|
+
if (!isInteractive()) throw new ExitError(ATTENTION, 'cleanup 需要在终端里确认(脚本里加 --yes)');
|
|
1728
|
+
if (!(await askYesNo('是否继续?', { defaultYes: false }))) {
|
|
1729
|
+
say('已取消');
|
|
1730
|
+
return 0;
|
|
1731
|
+
}
|
|
880
1732
|
}
|
|
1733
|
+
await withStopOnSignal(ctx, () => ctx.workAgent.cleanup({ say }));
|
|
1734
|
+
say('已清理');
|
|
881
1735
|
return 0;
|
|
882
1736
|
}
|
|
883
1737
|
|
|
@@ -911,14 +1765,22 @@ async function service(action, values) {
|
|
|
911
1765
|
uninstallService({ say });
|
|
912
1766
|
return 0;
|
|
913
1767
|
}
|
|
1768
|
+
if (['start', 'stop', 'restart'].includes(action)) {
|
|
1769
|
+
try {
|
|
1770
|
+
controlService(action, { say });
|
|
1771
|
+
} catch (error) {
|
|
1772
|
+
throw new ExitError(1, error.message);
|
|
1773
|
+
}
|
|
1774
|
+
return 0;
|
|
1775
|
+
}
|
|
914
1776
|
if (action === 'status') {
|
|
915
1777
|
const state = serviceStatus();
|
|
916
|
-
say(state.installed ? `后台服务:${state.state}
|
|
1778
|
+
say(state.installed ? `后台服务:${state.state}(${state.name})` : '后台服务:未安装');
|
|
917
1779
|
say(state.logHint);
|
|
918
1780
|
if (legacyServiceInstalled()) say(LEGACY_SERVICE_HINT);
|
|
919
1781
|
return 0;
|
|
920
1782
|
}
|
|
921
|
-
throw new ExitError(1, '用法:work-agent-runner service install | uninstall | status');
|
|
1783
|
+
throw new ExitError(1, '用法:work-agent-runner service install | uninstall | start | stop | restart | status');
|
|
922
1784
|
}
|
|
923
1785
|
|
|
924
1786
|
async function main(argv) {
|
|
@@ -936,6 +1798,12 @@ async function main(argv) {
|
|
|
936
1798
|
'token-stdin': { type: 'boolean' },
|
|
937
1799
|
repos: { type: 'string' },
|
|
938
1800
|
'no-repos': { type: 'boolean' },
|
|
1801
|
+
follow: { type: 'boolean', short: 'f' },
|
|
1802
|
+
lines: { type: 'string', short: 'n' },
|
|
1803
|
+
since: { type: 'string' },
|
|
1804
|
+
job: { type: 'string' },
|
|
1805
|
+
failed: { type: 'boolean' },
|
|
1806
|
+
watch: { type: 'boolean', short: 'w' },
|
|
939
1807
|
|
|
940
1808
|
yes: { type: 'boolean', short: 'y' },
|
|
941
1809
|
json: { type: 'boolean' },
|
|
@@ -949,10 +1817,18 @@ async function main(argv) {
|
|
|
949
1817
|
const { values, positionals } = parsed;
|
|
950
1818
|
if (values.version) return say(VERSION) ?? 0;
|
|
951
1819
|
if (values.help) return say(USAGE) ?? 0;
|
|
952
|
-
const [command = 'start', action] = positionals;
|
|
1820
|
+
const [command = 'start', action, argument] = positionals;
|
|
953
1821
|
switch (command) {
|
|
954
1822
|
case 'start':
|
|
955
1823
|
return start(values);
|
|
1824
|
+
case 'status':
|
|
1825
|
+
return status(values);
|
|
1826
|
+
case 'jobs':
|
|
1827
|
+
return jobsCommand(values, action, argument);
|
|
1828
|
+
case 'logs':
|
|
1829
|
+
return logs(values);
|
|
1830
|
+
case 'paths':
|
|
1831
|
+
return pathsCommand(values);
|
|
956
1832
|
case 'login':
|
|
957
1833
|
return login(values);
|
|
958
1834
|
case 'logout':
|
|
@@ -963,8 +1839,10 @@ async function main(argv) {
|
|
|
963
1839
|
return update(values);
|
|
964
1840
|
case 'doctor':
|
|
965
1841
|
return doctor(values);
|
|
966
|
-
case '
|
|
967
|
-
return
|
|
1842
|
+
case 'cleanup':
|
|
1843
|
+
return cleanupCommand(values);
|
|
1844
|
+
case 'reload':
|
|
1845
|
+
return reload(values);
|
|
968
1846
|
case 'service':
|
|
969
1847
|
return service(action, values);
|
|
970
1848
|
case 'version':
|