@online-tools/work-agent-runner 0.0.4-alpha-1 → 0.0.5-alpha-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/main.mjs CHANGED
@@ -5,8 +5,9 @@
5
5
  //
6
6
  // Exit codes: 0 stopped normally, 1 error, 78 needs a person (no token, token
7
7
  // deleted, machine blocked, same config running twice, unsupported system,
8
- // root, another instance, the old gitcode-agent-runner still running) —
9
- // services do not restart on 78 (launchd: 0).
8
+ // root, another instance, the old gitcode-agent-runner still running, a
9
+ // directory that is not this program's) — services do not restart on 78
10
+ // (launchd: 0).
10
11
 
11
12
  import { spawn, spawnSync } from 'node:child_process';
12
13
  import { once } from 'node:events';
@@ -29,12 +30,14 @@ import {
29
30
  legacyLockFile,
30
31
  loadConfig,
31
32
  newClientId,
33
+ prepareProgramHome,
32
34
  prepareWorkRoot,
33
- saveConfig,
35
+ updateConfig,
34
36
  withRepoPaths,
35
37
  } from '../lib/config.mjs';
36
38
  import { UPDATE_COMMAND, fatalFor, runConnection } from '../lib/connection.mjs';
37
39
  import { SANDBOX_DOCS, runDoctor, which } from '../lib/doctor.mjs';
40
+ import { cleanRunsDir, retryTrash } from '../lib/fs-safe.mjs';
38
41
  import { ApiError, createClient, normalizeServerUrl, proxyMode } from '../lib/http.mjs';
39
42
  import { FEATURE_LABELS, JobManager } from '../lib/jobs.mjs';
40
43
  import { LockedError, acquireLock, isRunnerAlive, lockHolder } from '../lib/lock.mjs';
@@ -43,6 +46,7 @@ import { createLogger } from '../lib/log.mjs';
43
46
  import { CancelledError, askText, askYesNo, isInteractive, readHidden, readStdin } from '../lib/prompt.mjs';
44
47
  import {
45
48
  EXIT_NEEDS_ATTENTION,
49
+ controlService,
46
50
  installService,
47
51
  legacyServiceInstalled,
48
52
  removeLegacyService,
@@ -53,7 +57,15 @@ import {
53
57
  import { DEFAULT_REQUIRED_TOOLS, npmPrefixWritable, planSetup, runSetup } from '../lib/setup.mjs';
54
58
  import { prepareWorkAgentHome } from '../lib/sandbox.mjs';
55
59
  import { collectSystemInfo, describeSystem } from '../lib/system-info.mjs';
56
- import { WorkAgent, freeBytes } from '../lib/work-agent.mjs';
60
+ import {
61
+ WorkAgent,
62
+ clearPoolUpdateRequest,
63
+ freeBytes,
64
+ markPoolBusy,
65
+ poolBusyInfo,
66
+ poolUpdateRequested,
67
+ requestPoolUpdate,
68
+ } from '../lib/work-agent.mjs';
57
69
 
58
70
  // The command's entry point (it checks the Node version, then loads this file).
59
71
  const ENTRY = fileURLToPath(new URL('./work-agent-runner.cjs', import.meta.url));
@@ -63,6 +75,13 @@ const NAME_MAX_CHARS = 40; // the website's limit (normalizeMachineName)
63
75
  const DOCTOR_INTERVAL_MS = 60 * 60_000;
64
76
  const ATTENTION = EXIT_NEEDS_ATTENTION;
65
77
  const LEGACY_SERVICE_HINT = `旧版程序 ${LEGACY_NAME} 的后台服务还在:运行 work-agent-runner service install 会停止并替换它(service uninstall 只删除)`;
78
+ // A terminal command waits this long for the service to be done with the clone.
79
+ const TERMINAL_LOCK_WAIT_MS = 2 * 60_000;
80
+ // A missing or broken clone is tried again: 1 minute, doubling, at most 30.
81
+ const CLONE_RETRY_START_MS = 60_000;
82
+ const CLONE_RETRY_MAX_MS = 30 * 60_000;
83
+ // How often the service looks for a knowledge-pool update a terminal asked for.
84
+ const REQUEST_POLL_MS = 30_000;
66
85
 
67
86
  // Which tools each feature needs — for the messages here only; the website decides.
68
87
  const FEATURE_TOOLS = {
@@ -84,16 +103,18 @@ const USAGE = `GitCode Agent 执行机器 ${VERSION}
84
103
  setup [--yes] [--repos <仓名>|--no-repos]
85
104
  检查并安装缺少的依赖、下载 work-agent 仓库,并询问是否
86
105
  下载知识仓(work-agent 的必要仓清单;需在终端里运行)
87
- update 立即更新 work-agent 仓库和知识仓(平时由程序自己定时更新)
106
+ update 立即更新 work-agent 仓库和知识仓(后台程序在运行时,
107
+ 知识仓交给它在没有任务时更新)
88
108
  doctor [--json] 检查依赖、沙箱和各功能是否可用
89
- status 显示网站、令牌、机器标识、工作目录、服务状态,并测试连接
90
- service install|uninstall|status
91
- 注册 / 删除 / 查看后台服务(开机自启)
109
+ status 显示网站、令牌、机器标识、各个目录、服务状态,并测试连接
110
+ service install|uninstall|start|stop|restart|status
111
+ 后台服务:注册(开机自启)/ 删除 / 启动 / 停止 / 重启 / 查看
92
112
  version 显示版本
93
113
 
94
114
  选项:
95
115
  --server <url> 网站地址(默认 ${DEFAULT_SERVER},会保存)
96
- --work-dir <dir> 工作目录(不能在主目录之内,会保存)
116
+ --work-dir <dir> 任务目录放在哪里(会保存):新目录、空目录或本程序用过的目录;
117
+ 已有其他内容的目录会改用其下的 work-agent-runner/,原有内容不动
97
118
  --name <名称> 这台机器登记时用的名称(默认主机名,会保存;登记后在网页上修改)
98
119
  --allow-root 允许以 root 运行(仅限容器等确有需要的场合)
99
120
 
@@ -126,7 +147,7 @@ async function applyProxy() {
126
147
  stdio: 'inherit',
127
148
  env: { ...process.env, NODE_USE_ENV_PROXY: '1', GC_RUNNER_REEXEC: '1' },
128
149
  });
129
- for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => child.kill(signal));
150
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => child.kill(signal));
130
151
  const [code, signal] = await once(child, 'exit');
131
152
  return code ?? (signal ? 128 + (os.constants.signals[signal] || 0) : 1);
132
153
  }
@@ -139,6 +160,14 @@ function realHome() {
139
160
  }
140
161
  }
141
162
 
163
+ function realpathOr(value) {
164
+ try {
165
+ return fs.realpathSync(value);
166
+ } catch {
167
+ return path.resolve(value);
168
+ }
169
+ }
170
+
142
171
  /** A name the website accepts: trimmed, 1–40 characters, no control characters; else ''. */
143
172
  function machineName(value) {
144
173
  const name = String(value ?? '').trim();
@@ -174,58 +203,52 @@ function adoptLegacy(paths) {
174
203
  }
175
204
  }
176
205
 
177
- /** Config, server, client id and work root; --server / --work-dir / --name are saved. */
178
- function loadContext(values, { workRoot: needWorkRoot = true } = {}) {
206
+ /**
207
+ * Config, server, client id and paths. What --server / --work-dir / --name
208
+ * change, a missing client id and the directories config.json does not name
209
+ * yet are `pending` until applyPending() writes them: right away for a
210
+ * terminal command (`persist`), only once `start` holds the instance lock.
211
+ * `workRoot`: also prepare the work root and work-agent's home.
212
+ */
213
+ function loadContext(values, { workRoot: needWorkRoot = true, persist = true, instance = false } = {}) {
179
214
  const defaults = configPaths();
215
+ // Before anything is written into it: a WORK_AGENT_RUNNER_HOME pointed at a
216
+ // directory of the user's is refused, not taken over.
217
+ prepareProgramHome(defaults.baseDir);
180
218
  adoptLegacy(defaults);
181
219
  const config = loadConfig(defaults);
182
- let changed = false;
183
- if (!config.clientId) {
184
- config.clientId = newClientId();
185
- changed = true;
186
- }
220
+ const pending = {};
221
+ if (!config.clientId) pending.clientId = newClientId();
187
222
  let server;
188
223
  try {
189
224
  server = normalizeServerUrl(values.server || config.server || DEFAULT_SERVER);
190
225
  } catch (error) {
191
226
  throw new ExitError(ATTENTION, error.message);
192
227
  }
193
- if (values.server && server !== config.server) {
194
- config.server = server;
195
- changed = true;
196
- }
228
+ if (values.server && server !== config.server) pending.server = server;
197
229
  if (values.name !== undefined) {
198
230
  const name = machineName(values.name);
199
231
  if (!name) throw new ExitError(1, `名称需为 1–${NAME_MAX_CHARS} 个字符,不能包含控制字符`);
200
- if (name !== config.machineName) {
201
- config.machineName = name;
202
- changed = true;
203
- }
232
+ if (name !== config.machineName) pending.machineName = name;
204
233
  }
205
- if (values['work-dir']) {
234
+ // A --work-dir is only taken once prepareRunDirs() has accepted it (status
235
+ // and logout do not prepare one, so they ignore it).
236
+ if (values['work-dir'] && (needWorkRoot || !persist)) {
206
237
  const dir = path.resolve(values['work-dir']);
207
- if (dir !== config.workRoot) {
208
- config.workRoot = dir;
209
- changed = true;
210
- }
238
+ if (dir !== config.workRoot) pending.workRoot = dir;
211
239
  }
212
- // The work-agent clone and the knowledge pool: wherever the config file says.
240
+ // work-agent's home and the two repositories: wherever the config file says.
213
241
  let paths;
214
242
  try {
215
- const resolved = withRepoPaths(defaults, config);
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
- }
243
+ paths = withRepoPaths(defaults, config).paths;
223
244
  } catch (error) {
224
245
  throw new ExitError(ATTENTION, error.message);
225
246
  }
226
- // runs/ lives in the program's home unless --work-dir moves it.
227
- const workRoot = needWorkRoot ? prepareWorkRoot(config.workRoot || paths.runsRoot) : '';
228
- if (changed) saveConfig(paths, config);
247
+ // Written into the config, so the file always shows where they are.
248
+ if (!config.workAgentHome) pending.workAgentHome = paths.workAgentHome;
249
+ if (!config.workAgentRepoDir) pending.workAgentRepoDir = paths.repoDir;
250
+ if (!config.ascendReposDir) pending.ascendReposDir = paths.poolDir;
251
+ Object.assign(config, pending);
229
252
  const workAgent = new WorkAgent({
230
253
  paths,
231
254
  log,
@@ -233,17 +256,78 @@ function loadContext(values, { workRoot: needWorkRoot = true } = {}) {
233
256
  // from WORK_AGENT_REPO for development and tests (any scheme, so a local
234
257
  // path works). Never from the website, and clone() logs where it went.
235
258
  repoUrl: process.env.WORK_AGENT_REPO || config.workAgentRepo,
259
+ // Jobs wait long for a terminal `update`; a terminal command waits less for the service.
260
+ ...(instance ? {} : { lockWaitMs: TERMINAL_LOCK_WAIT_MS }),
261
+ });
262
+ const ctx = { paths, config, pending, server, workRoot: '', realHome: realHome(), workAgent };
263
+ // The work root is checked before anything is saved: a refused --work-dir
264
+ // must not end up in the config.
265
+ if (needWorkRoot) prepareRunDirs(ctx);
266
+ if (persist) applyPending(ctx);
267
+ return ctx;
268
+ }
269
+
270
+ /** Writes what loadContext() left pending, field by field (another process may have written meanwhile). */
271
+ function applyPending(ctx) {
272
+ const { pending } = ctx;
273
+ if (!Object.keys(pending).length) return;
274
+ const written = updateConfig(ctx.paths, (config) => {
275
+ for (const [key, value] of Object.entries(pending)) {
276
+ // Defaults only fill what is still empty; the options given now win.
277
+ if (['clientId', 'workAgentHome', 'workAgentRepoDir', 'ascendReposDir'].includes(key) && config[key]) continue;
278
+ config[key] = value;
279
+ }
236
280
  });
281
+ for (const key of Object.keys(pending)) if (written[key] !== undefined) ctx.config[key] = written[key];
282
+ ctx.pending = {};
283
+ }
284
+
285
+ /**
286
+ * The work root (runs/ and trash/): the program's home, or the --work-dir,
287
+ * which is only used as it is when it is new, empty or this program's — else
288
+ * its work-agent-runner/ subdirectory, which then goes into the config
289
+ * (pending: applyPending() saves it). Then work-agent's home (logs/ tmp/
290
+ * docs/, the pool link).
291
+ */
292
+ function prepareRunDirs(ctx) {
293
+ const requested = ctx.config.workRoot || ctx.paths.runsRoot;
294
+ const workRoot = prepareWorkRoot(requested, { programHome: ctx.paths.baseDir });
295
+ if (ctx.config.workRoot && realpathOr(ctx.config.workRoot) !== workRoot) {
296
+ log.info(`${ctx.config.workRoot} 里已有其他内容,任务目录改放在 ${workRoot}(不会改动 ${ctx.config.workRoot} 里原有的东西)`);
297
+ ctx.config.workRoot = workRoot;
298
+ ctx.pending.workRoot = workRoot;
299
+ }
300
+ ctx.workRoot = workRoot;
237
301
  // The Skills' logs, scratch and deliverables, and the pool symlink when there
238
302
  // is a pool; a job's HOME links to this directory.
239
- if (needWorkRoot) {
240
- prepareWorkAgentHome(paths.workAgentHome, { poolDir: workAgent.mountablePool(), link: paths.workAgentLink });
241
- }
242
- return { paths, config, server, workRoot, realHome: realHome(), workAgent };
303
+ prepareWorkAgentHome(ctx.paths.workAgentHome, { poolDir: ctx.workAgent.mountablePool(), link: ctx.paths.workAgentLink });
243
304
  }
244
305
 
245
- function save(ctx) {
246
- saveConfig(ctx.paths, ctx.config);
306
+ /** Saves a field of the config without writing back anything stale. */
307
+ function saveField(ctx, key, value) {
308
+ updateConfig(ctx.paths, (config) => {
309
+ if (value === '' || value === undefined) delete config[key];
310
+ else config[key] = value;
311
+ });
312
+ ctx.config[key] = value;
313
+ }
314
+
315
+ /**
316
+ * The website no longer accepts `failedToken`: clear it from the config —
317
+ * unless the file holds another one by now (a `login` in a terminal while this
318
+ * ran). Returns true when the file is left without a token.
319
+ */
320
+ function clearToken(ctx, failedToken) {
321
+ try {
322
+ const written = updateConfig(ctx.paths, (config) => {
323
+ if (config.token === failedToken) config.token = '';
324
+ });
325
+ ctx.config.token = written.token;
326
+ return !written.token;
327
+ } catch (error) {
328
+ log.warn(`无法清除本机保存的令牌:${error.message}`);
329
+ return true;
330
+ }
247
331
  }
248
332
 
249
333
  function clientFor(ctx, token = ctx.config.token) {
@@ -309,8 +393,11 @@ async function doctorFor(ctx) {
309
393
  });
310
394
  const remembered = result.claude.viaNpmPrefix || result.claude.path === ctx.config.claudePath ? result.claude.path : '';
311
395
  if ((ctx.config.claudePath || '') !== remembered) {
312
- ctx.config.claudePath = remembered;
313
- save(ctx);
396
+ try {
397
+ saveField(ctx, 'claudePath', remembered);
398
+ } catch (error) {
399
+ log.warn(`无法保存 claude 的位置:${error.message}`);
400
+ }
314
401
  }
315
402
  return result;
316
403
  }
@@ -341,8 +428,12 @@ async function obtainToken(ctx, { fromStdin = false, capabilities }) {
341
428
  const client = clientFor(ctx, token);
342
429
  try {
343
430
  const reply = await connect(ctx, client, capabilities);
431
+ const name = ctx.config.machineName;
432
+ updateConfig(ctx.paths, (config) => {
433
+ config.token = token;
434
+ if (name) config.machineName = name;
435
+ });
344
436
  ctx.config.token = token;
345
- save(ctx);
346
437
  sayRegistered(ctx, reply);
347
438
  return { client, reply };
348
439
  } catch (error) {
@@ -367,9 +458,9 @@ async function connectSaved(ctx, client, capabilities) {
367
458
  } catch (error) {
368
459
  const fatal = fatalFor(error);
369
460
  if (fatal) {
370
- if (fatal.clearToken) {
371
- ctx.config.token = '';
372
- save(ctx);
461
+ if (fatal.clearToken && !clearToken(ctx, ctx.config.token)) {
462
+ // A `login` saved a new token meanwhile: a restart uses it (exit 1, so services restart).
463
+ throw new ExitError(1, '保存的令牌已失效,但配置文件里已经是新的令牌:重新启动后使用它');
373
464
  }
374
465
  throw new ExitError(fatal.code, fatal.message);
375
466
  }
@@ -385,9 +476,18 @@ function toolLabel(name) {
385
476
  return name === 'bwrap' ? 'bubblewrap' : name;
386
477
  }
387
478
 
388
- /** Updates every repository in the knowledge pool. Never fatal. */
479
+ /**
480
+ * Updates every repository in the knowledge pool (in this process: jobs that
481
+ * arrive meanwhile wait for it). Skipped while another process is downloading
482
+ * or updating it. Never fatal.
483
+ */
389
484
  async function updatePool(ctx) {
390
485
  if (!ctx.workAgent.mountablePool()) return;
486
+ const busy = poolBusyInfo(ctx.paths);
487
+ if (busy) {
488
+ log.info(`知识仓正由另一个进程(pid ${busy.pid})${busy.kind === 'init' ? '下载' : '更新'},这次不更新`);
489
+ return;
490
+ }
391
491
  await ctx.workAgent
392
492
  .updatePool({ say: (line) => log.info(line) })
393
493
  .catch((error) => log.warn(`知识仓更新失败:${error.message}`));
@@ -424,6 +524,14 @@ function printWorkAgent(state) {
424
524
  }
425
525
  }
426
526
 
527
+ /** After `setup` installed tools: a clone that failed for want of git is made now. */
528
+ async function ensureClone(ctx) {
529
+ const state = ctx.workAgent.state();
530
+ if (state.ok || state.foreign) return;
531
+ say('重新下载 work-agent 仓库……');
532
+ printWorkAgent(await refreshWorkAgent(ctx));
533
+ }
534
+
427
535
  const REPO_NAME = /^[A-Za-z0-9._-]{1,80}$/;
428
536
 
429
537
  /** `--repos a,b` → names, validated the way work-agent.py validates them. */
@@ -439,7 +547,8 @@ function splitRepos(value) {
439
547
  /**
440
548
  * Offers the knowledge pool — the repositories of work-agent's own essential
441
549
  * list — in a terminal only. Never downloads anything without a yes: `--repos`
442
- * picks the repositories instead, `--no-repos` skips the question.
550
+ * picks the repositories instead, `--no-repos` skips the question. A download
551
+ * only adds repositories, so a running service keeps taking jobs meanwhile.
443
552
  */
444
553
  async function offerPool(ctx, values) {
445
554
  if (values['no-repos']) return;
@@ -454,6 +563,11 @@ async function offerPool(ctx, values) {
454
563
  say(`知识仓已就绪(${poolDir},${pool.repos} 个仓)`);
455
564
  return;
456
565
  }
566
+ const busy = poolBusyInfo(ctx.paths);
567
+ if (busy) {
568
+ say(`另一个进程(pid ${busy.pid})正在${busy.kind === 'init' ? '下载' : '更新'}知识仓,请等它结束后再运行 work-agent-runner setup`);
569
+ return;
570
+ }
457
571
  if (wanted) say(`将下载到 ${poolDir}:${wanted.join('、')}`);
458
572
  else {
459
573
  say(`知识仓用于「代码检视」查 CANN / AscendC 的权威文档,下载到 ${poolDir}`);
@@ -468,11 +582,14 @@ async function offerPool(ctx, values) {
468
582
  say('已跳过;以后随时可以再运行 work-agent-runner setup');
469
583
  return;
470
584
  }
585
+ const done = markPoolBusy(ctx.paths, 'init');
471
586
  try {
472
587
  await ctx.workAgent.initPool({ repos: wanted, say });
473
588
  prepareWorkAgentHome(workAgentHome, { poolDir: ctx.workAgent.mountablePool(), link: ctx.paths.workAgentLink });
474
589
  } catch (error) {
475
590
  say(`下载知识仓失败:${error.message}`);
591
+ } finally {
592
+ done();
476
593
  }
477
594
  }
478
595
 
@@ -493,8 +610,11 @@ function printDoctor(result) {
493
610
  if (ready.length) say(` ${ready.join(' ')}`);
494
611
  for (const name of missing) say(` ✗ ${toolLabel(name).padEnd(11)} ${neededBy(name)}`);
495
612
  if (!result.claude.path) say(` ✗ ${'claude'.padEnd(11)} 所有功能需要`);
496
- else {
497
- say(` ✓ claude ${result.claudeVersion || '(无法读取版本)'}`);
613
+ else if (!result.claudeVersion) {
614
+ // There, but `claude --version` does not run (a broken install, a too-old Node behind it…).
615
+ say(` ✗ ${'claude'.padEnd(11)} 无法运行(${result.claude.path}):请运行 work-agent-runner setup 重新安装`);
616
+ } else {
617
+ say(` ✓ claude ${result.claudeVersion}`);
498
618
  if (result.claude.viaNpmPrefix) say(` 提示:claude 在 ${path.dirname(result.claude.path)},建议把这个目录加入 PATH`);
499
619
  }
500
620
  const { sandbox } = result.capabilities;
@@ -536,6 +656,12 @@ function setupPlan(result, reply, { poolWanted = false } = {}) {
536
656
  });
537
657
  }
538
658
 
659
+ /** The pid of a running instance of this program home other than this process, or 0. */
660
+ function runningInstance(ctx) {
661
+ const holder = lockHolder(ctx.paths.lockFile);
662
+ return holder !== process.pid && isRunnerAlive(holder) ? holder : 0;
663
+ }
664
+
539
665
  // ---- Commands ------------------------------------------------------------------
540
666
 
541
667
  async function start(values) {
@@ -548,7 +674,8 @@ async function start(values) {
548
674
  }
549
675
  log.warn('正以 root 运行(--allow-root):沙箱内的命令拥有 root 权限,建议改用专用的低权限账号');
550
676
  }
551
- const ctx = loadContext(values);
677
+ // Nothing is written before the lock: another instance may be running.
678
+ const ctx = loadContext(values, { workRoot: false, persist: false, instance: true });
552
679
  let lock;
553
680
  try {
554
681
  lock = acquireLock(ctx.paths.lockFile);
@@ -557,10 +684,19 @@ async function start(values) {
557
684
  throw error;
558
685
  }
559
686
  try {
687
+ prepareRunDirs(ctx);
688
+ applyPending(ctx);
560
689
  say(`GitCode Agent 执行机器 ${VERSION}`);
561
690
  if (legacyServiceInstalled()) log.warn(LEGACY_SERVICE_HINT);
562
- // Whatever a previous run left behind (probe directories are runs/p******).
563
- fs.rmSync(path.join(ctx.workRoot, 'runs'), { recursive: true, force: true });
691
+ // Whatever a previous run left behind (run directories r??????, probe
692
+ // directories p??????) — by name only, and never fatal: a directory a job
693
+ // made undeletable goes to trash/ and is retried every hour.
694
+ const cleaned = cleanRunsDir(path.join(ctx.workRoot, 'runs'), { trashDir: path.join(ctx.workRoot, 'trash') });
695
+ const stuck = cleaned.trashed.length + cleaned.failed.length;
696
+ if (stuck) log.warn(`有 ${stuck} 个任务目录删不掉,留在 ${path.join(ctx.workRoot, 'trash')},稍后再试;不影响接收任务`);
697
+ if (cleaned.unknown.length) {
698
+ log.warn(`${path.join(ctx.workRoot, 'runs')} 里有不是本程序的内容(${cleaned.unknown.slice(0, 3).join('、')}),没有删除`);
699
+ }
564
700
  const interactive = isInteractive() && !process.env.GC_RUNNER_SERVICE;
565
701
  if (!ctx.config.token && !interactive) {
566
702
  throw new ExitError(ATTENTION, '还没有接入令牌:请先在终端运行 work-agent-runner login');
@@ -572,6 +708,7 @@ async function start(values) {
572
708
  // `git pull` must never replace files a running review is reading.
573
709
  await ctx.workAgent.cleanup({ say: (line) => log.info(line) }).catch(() => {});
574
710
  await updatePool(ctx);
711
+ clearPoolUpdateRequest(ctx.paths); // just done
575
712
  say('检查依赖和沙箱……');
576
713
  let result = await doctorFor(ctx);
577
714
  let client;
@@ -593,13 +730,14 @@ async function start(values) {
593
730
  say,
594
731
  });
595
732
  // Asked once: missing items stay visible in status and on the website.
596
- ctx.config.setupDone = true;
597
- save(ctx);
733
+ saveField(ctx, 'setupDone', true);
598
734
  if (outcome.ran) {
599
735
  say('重新检查……');
600
736
  result = await doctorFor(ctx);
601
737
  printDoctor(result);
602
738
  }
739
+ // The first clone may have failed for want of git, which setup just installed.
740
+ await ensureClone(ctx);
603
741
  // The same question `setup` asks, so a first run settles everything.
604
742
  await offerPool(ctx, values);
605
743
  result = await doctorFor(ctx);
@@ -633,25 +771,74 @@ async function serve(ctx, client, initial, reply) {
633
771
  onFatal,
634
772
  });
635
773
  let capabilities = initial.capabilities;
774
+ // One maintenance step at a time: a hung pull must not stack up another round.
636
775
  let checking = false;
637
- // Every hour: the knowledge pool, then the dependency and sandbox check.
638
- const doctorTimer = setInterval(async () => {
639
- // A hung pull must not stack up another round.
776
+ const exclusive = async (work) => {
640
777
  if (checking) return;
641
778
  checking = true;
642
779
  try {
643
- // Only between jobs: a pull would replace files under a running review.
644
- if (!jobs.runningIds().length) await updatePool(ctx);
645
- const fresh = await doctorFor(ctx);
646
- capabilities = fresh.capabilities;
647
- if (fresh.claude.path) jobs.claudePath = fresh.claude.path;
780
+ await work();
648
781
  } catch (error) {
649
782
  log.warn(`定期检查失败:${error.message}`);
650
783
  } finally {
651
784
  checking = false;
652
785
  }
786
+ };
787
+ const recheck = async () => {
788
+ const fresh = await doctorFor(ctx);
789
+ capabilities = fresh.capabilities;
790
+ if (fresh.claude.path) jobs.claudePath = fresh.claude.path;
791
+ };
792
+
793
+ // A missing or broken clone (gitcode.com was unreachable, a re-clone failed)
794
+ // is tried again soon, not only at the next 08:00.
795
+ let cloneTimer = null;
796
+ let cloneDelay = CLONE_RETRY_START_MS;
797
+ const scheduleCloneRetry = () => {
798
+ clearTimeout(cloneTimer);
799
+ const state = ctx.workAgent.state();
800
+ if (state.ok || state.foreign) {
801
+ cloneDelay = CLONE_RETRY_START_MS;
802
+ return;
803
+ }
804
+ cloneTimer = setTimeout(async () => {
805
+ const fresh = await refreshWorkAgent(ctx, { say: (line) => log.warn(line) });
806
+ if (fresh.ok) {
807
+ log.info(`✓ work-agent 仓库就绪:${fresh.commit.slice(0, 7)}`);
808
+ cloneDelay = CLONE_RETRY_START_MS;
809
+ await exclusive(recheck);
810
+ return;
811
+ }
812
+ cloneDelay = Math.min(CLONE_RETRY_MAX_MS, cloneDelay * 2);
813
+ log.warn(`work-agent 仓库仍不可用(${fresh.reason}),${Math.round(cloneDelay / 60_000)} 分钟后再试`);
814
+ scheduleCloneRetry();
815
+ }, cloneDelay);
816
+ cloneTimer.unref();
817
+ };
818
+ scheduleCloneRetry();
819
+
820
+ // Every hour: the knowledge pool, then the dependency and sandbox check.
821
+ const doctorTimer = setInterval(() => {
822
+ exclusive(async () => {
823
+ // Only between jobs: a pull would replace files under a running review.
824
+ if (!jobs.runningIds().length) await updatePool(ctx);
825
+ clearTrash(ctx);
826
+ await recheck();
827
+ });
653
828
  }, POOL_UPDATE_MS);
654
829
  doctorTimer.unref();
830
+ // `work-agent-runner update` in a terminal leaves the pool to this program:
831
+ // done as soon as no job runs.
832
+ const requestTimer = setInterval(() => {
833
+ if (!poolUpdateRequested(ctx.paths) || jobs.runningIds().length) return;
834
+ exclusive(async () => {
835
+ clearPoolUpdateRequest(ctx.paths);
836
+ log.info('按终端里 work-agent-runner update 的请求更新知识仓');
837
+ await updatePool(ctx);
838
+ await recheck();
839
+ });
840
+ }, REQUEST_POLL_MS);
841
+ requestTimer.unref();
655
842
  // Every day at 08:00 local time: the work-agent clone (the Skill source).
656
843
  let repoTimer = null;
657
844
  const scheduleRepoUpdate = () => {
@@ -659,14 +846,14 @@ async function serve(ctx, client, initial, reply) {
659
846
  next.setHours(REPO_UPDATE_HOUR, 0, 0, 0);
660
847
  if (next.getTime() <= Date.now()) next.setDate(next.getDate() + 1);
661
848
  repoTimer = setTimeout(async () => {
662
- printWorkAgent(await refreshWorkAgent(ctx, { say: (line) => log.info(line) }));
663
849
  try {
664
- capabilities = (await doctorFor(ctx)).capabilities;
665
- } catch (error) {
666
- log.warn(`定期检查失败:${error.message}`);
850
+ printWorkAgent(await refreshWorkAgent(ctx, { say: (line) => log.info(line) }));
851
+ await exclusive(recheck);
852
+ scheduleCloneRetry();
853
+ } finally {
854
+ // Re-armed each time, so it stays on 08:00 across a change of day length.
855
+ scheduleRepoUpdate();
667
856
  }
668
- // Re-armed each time, so it stays on 08:00 across a change of day length.
669
- scheduleRepoUpdate();
670
857
  }, next.getTime() - Date.now());
671
858
  repoTimer.unref();
672
859
  };
@@ -693,43 +880,63 @@ async function serve(ctx, client, initial, reply) {
693
880
  signal: controller.signal,
694
881
  });
695
882
  clearInterval(doctorTimer);
883
+ clearInterval(requestTimer);
696
884
  clearTimeout(repoTimer);
885
+ clearTimeout(cloneTimer);
697
886
  const outcome = fatal || result;
698
887
  ctx.workAgent.stop();
699
888
  await jobs.stopAll(5000);
700
- if (outcome.clearToken) {
701
- ctx.config.token = '';
702
- save(ctx);
889
+ if (outcome.clearToken && !clearToken(ctx, ctx.config.token)) {
890
+ // `login` saved a new token while this one was in use: exit 1 so a service
891
+ // restarts and connects with it.
892
+ log.warn('使用中的令牌已失效,配置文件里已经是新的令牌:重新启动后使用它');
893
+ return 1;
703
894
  }
704
895
  if (outcome.code) log.error(outcome.message);
705
896
  else log.info('已停止');
706
897
  return outcome.code || 0;
707
898
  }
708
899
 
900
+ /** Tries again to delete what earlier jobs left undeletable; reports what is still there. */
901
+ function clearTrash(ctx) {
902
+ const trashDir = path.join(ctx.workRoot, 'trash');
903
+ const left = retryTrash(trashDir);
904
+ if (left.length) log.warn(`${trashDir} 里有 ${left.length} 个目录还删不掉(可能是任务改了权限),需要时请手动删除`);
905
+ }
906
+
709
907
  async function login(values) {
710
908
  checkSystem();
711
909
  const restarted = await applyProxy();
712
910
  if (restarted !== null) return restarted;
713
911
  const ctx = loadContext(values);
714
912
  if (values['new-id']) {
715
- ctx.config.clientId = newClientId();
913
+ const clientId = newClientId();
716
914
  // A new machine on the website: ask for its name again (unless --name gave one).
717
- if (values.name === undefined) ctx.config.machineName = '';
718
- save(ctx);
915
+ const forgetName = values.name === undefined;
916
+ updateConfig(ctx.paths, (config) => {
917
+ config.clientId = clientId;
918
+ if (forgetName) delete config.machineName;
919
+ });
920
+ ctx.config.clientId = clientId;
921
+ if (forgetName) ctx.config.machineName = '';
719
922
  say('已生成新的机器标识:这台机器在网页上会作为新机器出现,需要在网页上确认');
720
923
  }
721
924
  if (!values['token-stdin'] && !isInteractive()) throw new ExitError(ATTENTION, 'login 需要在终端里运行(脚本里请用 --token-stdin)');
722
925
  say('检查依赖和沙箱……');
723
926
  const result = await doctorFor(ctx);
724
927
  await obtainToken(ctx, { fromStdin: Boolean(values['token-stdin']), capabilities: result.capabilities });
928
+ const running = runningInstance(ctx);
929
+ if (running) say(`注意:正在运行的程序(pid ${running})还在用原来的令牌;运行 work-agent-runner service restart(或重新启动前台程序)改用新令牌`);
725
930
  return 0;
726
931
  }
727
932
 
728
933
  function logout(values) {
729
934
  const ctx = loadContext(values, { workRoot: false });
730
- const had = Boolean(ctx.config.token);
731
- ctx.config.token = '';
732
- save(ctx);
935
+ let had = false;
936
+ updateConfig(ctx.paths, (config) => {
937
+ had = Boolean(config.token);
938
+ config.token = '';
939
+ });
733
940
  say(had ? '已清除本机保存的令牌(机器标识保留)' : '本机没有保存令牌');
734
941
  return 0;
735
942
  }
@@ -764,13 +971,14 @@ async function setup(values) {
764
971
  confirm: (question) => askYesNo(question),
765
972
  say,
766
973
  });
767
- ctx.config.setupDone = true;
768
- save(ctx);
974
+ saveField(ctx, 'setupDone', true);
769
975
  if (outcome.ran) {
770
976
  say('重新检查……');
771
977
  result = await doctorFor(ctx);
772
978
  printDoctor(result);
773
979
  }
980
+ // A clone that failed for want of git is made now that setup installed it.
981
+ await ensureClone(ctx);
774
982
  // After the tools: the pool is searched with rg.
775
983
  await offerPool(ctx, values);
776
984
  if (client) reply = await connect(ctx, client, (await doctorFor(ctx)).capabilities).catch(() => reply);
@@ -778,18 +986,40 @@ async function setup(values) {
778
986
  return outcome.failed.length ? 1 : 0;
779
987
  }
780
988
 
781
- /** `update`: both repositories, now. */
989
+ /**
990
+ * `update`: both repositories, now. With the program running, the knowledge
991
+ * pool is left to it (it updates as soon as no job runs: a `git pull` must not
992
+ * replace files a job is reading).
993
+ */
782
994
  async function update(values) {
783
995
  checkSystem();
784
996
  const restarted = await applyProxy();
785
997
  if (restarted !== null) return restarted;
786
998
  const ctx = loadContext(values);
999
+ const running = runningInstance(ctx);
787
1000
  let failed = false;
788
1001
  try {
789
1002
  const state = await ctx.workAgent.refresh();
790
1003
  printWorkAgent(state);
791
1004
  failed = !state.ok;
792
- if (ctx.workAgent.mountablePool()) await ctx.workAgent.updatePool({ say });
1005
+ if (ctx.workAgent.mountablePool()) {
1006
+ const busy = poolBusyInfo(ctx.paths);
1007
+ if (running) {
1008
+ requestPoolUpdate(ctx.paths);
1009
+ const service = serviceStatus();
1010
+ say(`程序正在运行(pid ${running}):已请它在没有任务时更新知识仓${service.installed ? `(${service.logHint})` : ''}`);
1011
+ } else if (busy) {
1012
+ say(`另一个进程(pid ${busy.pid})正在${busy.kind === 'init' ? '下载' : '更新'}知识仓,请等它结束后再试`);
1013
+ failed = true;
1014
+ } else {
1015
+ const done = markPoolBusy(ctx.paths, 'update');
1016
+ try {
1017
+ await ctx.workAgent.updatePool({ say });
1018
+ } finally {
1019
+ done();
1020
+ }
1021
+ }
1022
+ }
793
1023
  } catch (error) {
794
1024
  say(error.message);
795
1025
  failed = true;
@@ -848,16 +1078,29 @@ async function status(values) {
848
1078
  say(`机器标识:${config.clientId}`);
849
1079
  say(`登记名称:${config.machineName || `${os.hostname()}(主机名)`}`);
850
1080
  say(`程序目录:${ctx.paths.baseDir}`);
851
- say(`任务目录:${path.join(config.workRoot || ctx.paths.runsRoot, 'runs')}`);
1081
+ const workRoot = config.workRoot || ctx.paths.runsRoot;
1082
+ say(`任务目录:${path.join(workRoot, 'runs')}`);
1083
+ let trashed = 0;
1084
+ try {
1085
+ trashed = fs.readdirSync(path.join(workRoot, 'trash')).length;
1086
+ } catch {
1087
+ // None.
1088
+ }
1089
+ if (trashed) say(` 回收站:${trashed} 个删不掉的任务目录(${path.join(workRoot, 'trash')},程序每小时重试)`);
852
1090
  const repo = ctx.workAgent.state();
853
1091
  say(`work-agent 仓库:${repo.ok ? `${repo.commit.slice(0, 7)}(${ctx.workAgent.repoDir})` : repo.reason}`);
854
- say(`WORK_AGENT_HOME:${ctx.paths.workAgentHome}`);
1092
+ const envHome = process.env.WORK_AGENT_HOME ? path.resolve(process.env.WORK_AGENT_HOME) : '';
1093
+ say(`WORK_AGENT_HOME:${ctx.paths.workAgentHome}${envHome && envHome !== ctx.paths.workAgentHome ? `(环境变量是 ${envHome},以 config.json 为准)` : ''}`);
855
1094
  const poolRepos = ctx.workAgent.poolRepos();
856
1095
  say(`知识仓:${poolRepos.length ? `${poolRepos.length} 个仓(${poolRepos.join('、')})` : '未初始化'}(${ctx.paths.poolDir})`);
1096
+ const busy = poolBusyInfo(ctx.paths);
1097
+ if (busy) say(` 进程 ${busy.pid} 正在${busy.kind === 'init' ? '下载' : '更新'}知识仓(${busy.startedAt} 开始)`);
1098
+ const requested = poolUpdateRequested(ctx.paths);
1099
+ if (requested) say(` 已请求更新知识仓(${requested}),等待程序在没有任务时执行`);
857
1100
  say(`系统:${describeSystem(systemInfo(ctx))}`);
858
1101
  say(`配置文件:${ctx.paths.configFile}`);
859
1102
  const service = serviceStatus();
860
- say(`后台服务:${service.installed ? service.state : '未安装'}${service.installed ? `(${service.logHint})` : ''}`);
1103
+ say(`后台服务:${service.installed ? `${service.state}(${service.name};${service.logHint})` : '未安装'}`);
861
1104
  if (legacyServiceInstalled()) say(LEGACY_SERVICE_HINT);
862
1105
  const holder = lockHolder(ctx.paths.lockFile);
863
1106
  say(`运行中的实例:${isRunnerAlive(holder) ? `pid ${holder}` : '无'}`);
@@ -911,14 +1154,22 @@ async function service(action, values) {
911
1154
  uninstallService({ say });
912
1155
  return 0;
913
1156
  }
1157
+ if (['start', 'stop', 'restart'].includes(action)) {
1158
+ try {
1159
+ controlService(action, { say });
1160
+ } catch (error) {
1161
+ throw new ExitError(1, error.message);
1162
+ }
1163
+ return 0;
1164
+ }
914
1165
  if (action === 'status') {
915
1166
  const state = serviceStatus();
916
- say(state.installed ? `后台服务:${state.state}` : '后台服务:未安装');
1167
+ say(state.installed ? `后台服务:${state.state}(${state.name})` : '后台服务:未安装');
917
1168
  say(state.logHint);
918
1169
  if (legacyServiceInstalled()) say(LEGACY_SERVICE_HINT);
919
1170
  return 0;
920
1171
  }
921
- throw new ExitError(1, '用法:work-agent-runner service install | uninstall | status');
1172
+ throw new ExitError(1, '用法:work-agent-runner service install | uninstall | start | stop | restart | status');
922
1173
  }
923
1174
 
924
1175
  async function main(argv) {