@online-tools/work-agent-runner 0.0.5-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/bin/main.mjs CHANGED
@@ -3,11 +3,18 @@
3
3
  // supported Node runs it. This file owns every side effect — arguments, the
4
4
  // config file, the lock, signals, exit codes; ../lib does the work.
5
5
  //
6
+ // The running instance (`start`, in the foreground or as a service) is the
7
+ // one writer of this program home's state: terminal commands ask it through
8
+ // the local control interface (lib/control.mjs) when it runs — `status`,
9
+ // `jobs`, `update`, `setup`'s knowledge pool, `doctor` — and only act
10
+ // themselves when it does not.
11
+ //
6
12
  // Exit codes: 0 stopped normally, 1 error, 78 needs a person (no token, token
7
13
  // deleted, machine blocked, same config running twice, unsupported system,
8
14
  // root, another instance, the old gitcode-agent-runner still running, a
9
15
  // directory that is not this program's) — services do not restart on 78
10
- // (launchd: 0).
16
+ // (launchd: 0). `status`: 0 running and fine, 1 running with a problem, 2 not
17
+ // running or not connected.
11
18
 
12
19
  import { spawn, spawnSync } from 'node:child_process';
13
20
  import { once } from 'node:events';
@@ -21,11 +28,10 @@ import {
21
28
  ConfigError,
22
29
  DEFAULT_SERVER,
23
30
  LEGACY_NAME,
24
- POOL_UPDATE_MS,
25
- REPO_UPDATE_HOUR,
26
31
  WorkRootError,
27
32
  adoptLegacyState,
28
33
  configPaths,
34
+ effectiveSettings,
29
35
  legacyConfigPending,
30
36
  legacyLockFile,
31
37
  loadConfig,
@@ -36,13 +42,15 @@ import {
36
42
  withRepoPaths,
37
43
  } from '../lib/config.mjs';
38
44
  import { UPDATE_COMMAND, fatalFor, runConnection } from '../lib/connection.mjs';
45
+ import { ControlError, NotRunningError, controlDirectories, controlRequest, pingInstance, socketLocation, startControlServer } from '../lib/control.mjs';
39
46
  import { SANDBOX_DOCS, runDoctor, which } from '../lib/doctor.mjs';
40
- import { cleanRunsDir, retryTrash } from '../lib/fs-safe.mjs';
47
+ import { cleanRunsDir } from '../lib/fs-safe.mjs';
41
48
  import { ApiError, createClient, normalizeServerUrl, proxyMode } from '../lib/http.mjs';
42
49
  import { FEATURE_LABELS, JobManager } from '../lib/jobs.mjs';
43
50
  import { LockedError, acquireLock, isRunnerAlive, lockHolder } from '../lib/lock.mjs';
44
51
  import { NODE_REQUIREMENT, nodeSupported } from '../lib/node-runtime.cjs';
45
52
  import { createLogger } from '../lib/log.mjs';
53
+ import { Maintenance } from '../lib/maintenance.mjs';
46
54
  import { CancelledError, askText, askYesNo, isInteractive, readHidden, readStdin } from '../lib/prompt.mjs';
47
55
  import {
48
56
  EXIT_NEEDS_ATTENTION,
@@ -51,15 +59,17 @@ import {
51
59
  legacyServiceInstalled,
52
60
  removeLegacyService,
53
61
  serviceExitCode,
62
+ servicePaths,
54
63
  serviceStatus,
55
64
  uninstallService,
56
65
  } from '../lib/service.mjs';
57
66
  import { DEFAULT_REQUIRED_TOOLS, npmPrefixWritable, planSetup, runSetup } from '../lib/setup.mjs';
58
67
  import { prepareWorkAgentHome } from '../lib/sandbox.mjs';
68
+ import { StateStore, countResults, matchesRunId, readHistory, readStatus } from '../lib/state.mjs';
59
69
  import { collectSystemInfo, describeSystem } from '../lib/system-info.mjs';
70
+ import { jobDetailLines, jobsLines, pathsLines, statusLines } from '../lib/views.mjs';
60
71
  import {
61
72
  WorkAgent,
62
- clearPoolUpdateRequest,
63
73
  freeBytes,
64
74
  markPoolBusy,
65
75
  poolBusyInfo,
@@ -72,16 +82,10 @@ const ENTRY = fileURLToPath(new URL('./work-agent-runner.cjs', import.meta.url))
72
82
  const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
73
83
  const TOKEN_PATTERN = /^gcm_[A-Za-z0-9_-]{43}$/;
74
84
  const NAME_MAX_CHARS = 40; // the website's limit (normalizeMachineName)
75
- const DOCTOR_INTERVAL_MS = 60 * 60_000;
76
85
  const ATTENTION = EXIT_NEEDS_ATTENTION;
77
86
  const LEGACY_SERVICE_HINT = `旧版程序 ${LEGACY_NAME} 的后台服务还在:运行 work-agent-runner service install 会停止并替换它(service uninstall 只删除)`;
78
87
  // A terminal command waits this long for the service to be done with the clone.
79
88
  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;
85
89
 
86
90
  // Which tools each feature needs — for the messages here only; the website decides.
87
91
  const FEATURE_TOOLS = {
@@ -97,16 +101,25 @@ const USAGE = `GitCode Agent 执行机器 ${VERSION}
97
101
 
98
102
  命令:
99
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] 各个目录在哪里,以及有没有问题
100
112
  login [--new-id] [--token-stdin] [--name <名称>]
101
113
  输入接入令牌(校验通过才保存);--new-id 重新生成机器标识
102
114
  logout 清除本机保存的令牌(机器标识保留)
103
115
  setup [--yes] [--repos <仓名>|--no-repos]
104
116
  检查并安装缺少的依赖、下载 work-agent 仓库,并询问是否
105
117
  下载知识仓(work-agent 的必要仓清单;需在终端里运行)
106
- update 立即更新 work-agent 仓库和知识仓(后台程序在运行时,
107
- 知识仓交给它在没有任务时更新)
118
+ update 立即更新 work-agent 仓库和知识仓(程序在运行时由它来做,
119
+ 知识仓在没有任务时更新)
108
120
  doctor [--json] 检查依赖、沙箱和各功能是否可用
109
- status 显示网站、令牌、机器标识、各个目录、服务状态,并测试连接
121
+ cleanup [--yes] 清空 work-agent 的共享临时目录、删除 30 天前的日志(会先确认)
122
+ reload 让运行中的程序重新读取 config.json 里的维护时间、限额和隔离设置
110
123
  service install|uninstall|start|stop|restart|status
111
124
  后台服务:注册(开机自启)/ 删除 / 启动 / 停止 / 重启 / 查看
112
125
  version 显示版本
@@ -129,6 +142,7 @@ class ExitError extends Error {
129
142
 
130
143
  const say = (text = '') => process.stdout.write(`${text}\n`);
131
144
  const log = createLogger();
145
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
132
146
 
133
147
  function checkSystem() {
134
148
  if (!['linux', 'darwin'].includes(process.platform)) throw new ExitError(ATTENTION, '暂不支持此系统(只支持 Linux 和 macOS)');
@@ -175,6 +189,21 @@ function machineName(value) {
175
189
  return length >= 1 && length <= NAME_MAX_CHARS && !/\p{Cc}/u.test(name) ? name : '';
176
190
  }
177
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
+
178
207
  /**
179
208
  * First run after an older layout (0.0.1 kept the config under ~/.config and
180
209
  * ran jobs in /var/tmp; before 0.0.1-alpha-5 everything was named
@@ -350,14 +379,14 @@ function systemInfo(ctx) {
350
379
  }
351
380
 
352
381
  /** After /connect: what the machine is called there, and whether its owner confirmed it. */
353
- function sayRegistered(ctx, reply) {
354
- say(`✓ 已连接 ${ctx.server},本机登记为「${reply.name}」(令牌:${reply.tokenName})`);
382
+ function sayRegistered(ctx, reply, out = say) {
383
+ out(`✓ 已连接 ${ctx.server},本机登记为「${reply.name}」(令牌:${reply.tokenName})${reply.role === 'server' ? ',服务器执行机器' : ''}`);
355
384
  if (!reply.created && ctx.config.machineName && reply.name !== ctx.config.machineName) {
356
- say(` 这台机器之前已登记为「${reply.name}」,名称请在网页上修改`);
385
+ out(` 这台机器之前已登记为「${reply.name}」,名称请在网页上修改`);
357
386
  }
358
387
  if (reply.confirmed === false) {
359
- say('⚠ 这台机器还没有确认,确认后才会收到任务:请在网页「在线 Agent → 模型配置 → 执行机器」里核对主机名和 IP 后点「确认」');
360
- say(` ${ctx.server}/features#agent/config`);
388
+ out('⚠ 这台机器还没有确认,确认后才会收到任务:请在网页「在线 Agent → 模型配置 → 执行机器」里核对主机名和 IP 后点「确认」');
389
+ out(` ${ctx.server}/features#agent/config`);
361
390
  }
362
391
  }
363
392
 
@@ -383,13 +412,14 @@ function networkReason(error) {
383
412
  return error?.cause?.code || error?.cause?.message || error?.message || String(error);
384
413
  }
385
414
 
386
- /** doctor + remembering a claude found outside PATH. */
387
- 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 } = {}) {
388
417
  const result = await runDoctor({
389
418
  configuredClaude: ctx.config.claudePath || '',
390
419
  workRoot: ctx.workRoot,
391
420
  realHome: ctx.realHome,
392
421
  workAgent: ctx.workAgent,
422
+ probe,
393
423
  });
394
424
  const remembered = result.claude.viaNpmPrefix || result.claude.path === ctx.config.claudePath ? result.claude.path : '';
395
425
  if ((ctx.config.claudePath || '') !== remembered) {
@@ -402,6 +432,20 @@ async function doctorFor(ctx) {
402
432
  return result;
403
433
  }
404
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 || '' };
445
+ }
446
+ return result;
447
+ }
448
+
405
449
  function connectFailure(error, server) {
406
450
  if (error instanceof ApiError) {
407
451
  if (error.status === 403) return new ExitError(ATTENTION, error.message);
@@ -449,10 +493,14 @@ async function obtainToken(ctx, { fromStdin = false, capabilities }) {
449
493
  throw new ExitError(ATTENTION, '令牌 3 次都不正确,已退出');
450
494
  }
451
495
 
452
- /** POST /connect with the saved token; waits out network trouble (services must not give up). */
453
- async function connectSaved(ctx, client, capabilities) {
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 = () => {} } = {}) {
454
501
  let delay = 1000;
455
502
  for (;;) {
503
+ if (signal?.aborted) throw new ExitError(0, '');
456
504
  try {
457
505
  return await connect(ctx, client, capabilities);
458
506
  } catch (error) {
@@ -465,8 +513,16 @@ async function connectSaved(ctx, client, capabilities) {
465
513
  throw new ExitError(fatal.code, fatal.message);
466
514
  }
467
515
  if (error instanceof ApiError && error.status !== 429 && error.status < 500) throw connectFailure(error, ctx.server);
468
- log.warn(`无法连接 ${ctx.server}(${error instanceof ApiError ? error.message : networkReason(error)}),${Math.round(delay / 1000)} 秒后重试`);
469
- await new Promise((resolve) => setTimeout(resolve, error?.retryAfterMs || delay));
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
+ });
470
526
  delay = Math.min(60_000, delay * 2);
471
527
  }
472
528
  }
@@ -476,23 +532,6 @@ function toolLabel(name) {
476
532
  return name === 'bwrap' ? 'bubblewrap' : name;
477
533
  }
478
534
 
479
- /**
480
- * Updates every repository in the knowledge pool (in this process: jobs that
481
- * arrive meanwhile wait for it). Skipped while another process is downloading
482
- * or updating it. Never fatal.
483
- */
484
- async function updatePool(ctx) {
485
- if (!ctx.workAgent.mountablePool()) return;
486
- const busy = poolBusyInfo(ctx.paths);
487
- if (busy) {
488
- log.info(`知识仓正由另一个进程(pid ${busy.pid})${busy.kind === 'init' ? '下载' : '更新'},这次不更新`);
489
- return;
490
- }
491
- await ctx.workAgent
492
- .updatePool({ say: (line) => log.info(line) })
493
- .catch((error) => log.warn(`知识仓更新失败:${error.message}`));
494
- }
495
-
496
535
  /** Brings the clone up to date. Never fatal: the website shows the reason instead. */
497
536
  async function refreshWorkAgent(ctx, { say: out = say } = {}) {
498
537
  try {
@@ -511,16 +550,57 @@ function poolAge(fetchedAt) {
511
550
  }
512
551
 
513
552
  /** The Skill source and the knowledge pool, in two lines. */
514
- function printWorkAgent(state) {
515
- if (state.ok) say(`✓ work-agent ${state.commit.slice(0, 7)}${state.committedAt ? `(${state.committedAt.slice(0, 10)})` : ''}`);
516
- else say(`✗ work-agent 仓库不可用:${state.reason}`);
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}`);
517
556
  if (state.incomplete?.length) {
518
- say(` 知识仓 ${state.incomplete.join('、')} 不完整:请删除后重新运行 work-agent-runner setup`);
557
+ out(` 知识仓 ${state.incomplete.join('、')} 不完整:请删除后重新运行 work-agent-runner setup`);
519
558
  } else if (state.repos) {
520
559
  const what = state.ascend ? `${state.repos} 个仓(含 AscendC 两仓)` : `${state.repos} 个仓,缺 AscendC 两仓(代码检视的 AscendC 规范域不检查)`;
521
- say(` 知识仓:${what}${poolAge(state.poolFetchedAt)}`);
560
+ out(` 知识仓:${what}${poolAge(state.poolFetchedAt)}`);
522
561
  } else {
523
- say(' 知识仓:未初始化(可选;运行 work-agent-runner setup 下载)');
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;
524
604
  }
525
605
  }
526
606
 
@@ -529,16 +609,22 @@ async function ensureClone(ctx) {
529
609
  const state = ctx.workAgent.state();
530
610
  if (state.ok || state.foreign) return;
531
611
  say('重新下载 work-agent 仓库……');
532
- printWorkAgent(await refreshWorkAgent(ctx));
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));
533
615
  }
534
616
 
535
617
  const REPO_NAME = /^[A-Za-z0-9._-]{1,80}$/;
536
618
 
619
+ function validRepoName(name) {
620
+ return REPO_NAME.test(name) && !name.startsWith('.');
621
+ }
622
+
537
623
  /** `--repos a,b` → names, validated the way work-agent.py validates them. */
538
624
  function splitRepos(value) {
539
625
  const names = String(value).split(/[,\s]+/).filter(Boolean);
540
626
  for (const name of names) {
541
- if (!REPO_NAME.test(name) || name.startsWith('.')) throw new ExitError(1, `仓名不正确:${name}`);
627
+ if (!validRepoName(name)) throw new ExitError(1, `仓名不正确:${name}`);
542
628
  }
543
629
  if (!names.length) throw new ExitError(1, '--repos 需要至少一个仓名');
544
630
  return names;
@@ -548,9 +634,11 @@ function splitRepos(value) {
548
634
  * Offers the knowledge pool — the repositories of work-agent's own essential
549
635
  * list — in a terminal only. Never downloads anything without a yes: `--repos`
550
636
  * picks the repositories instead, `--no-repos` skips the question. A download
551
- * only adds repositories, so a running service keeps taking jobs meanwhile.
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).
552
640
  */
553
- async function offerPool(ctx, values) {
641
+ async function offerPool(ctx, values, { delegate = true } = {}) {
554
642
  if (values['no-repos']) return;
555
643
  const wanted = values.repos === undefined ? null : splitRepos(values.repos);
556
644
  const { poolDir, workAgentHome } = ctx.paths;
@@ -582,14 +670,27 @@ async function offerPool(ctx, values) {
582
670
  say('已跳过;以后随时可以再运行 work-agent-runner setup');
583
671
  return;
584
672
  }
585
- const done = markPoolBusy(ctx.paths, 'init');
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');
586
686
  try {
587
- await ctx.workAgent.initPool({ repos: wanted, say });
687
+ await withStopOnSignal(ctx, () => ctx.workAgent.initPool({ repos: wanted, say }));
588
688
  prepareWorkAgentHome(workAgentHome, { poolDir: ctx.workAgent.mountablePool(), link: ctx.paths.workAgentLink });
589
689
  } catch (error) {
690
+ if (error instanceof ExitError) throw error;
590
691
  say(`下载知识仓失败:${error.message}`);
591
692
  } finally {
592
- done();
693
+ finished();
593
694
  }
594
695
  }
595
696
 
@@ -600,37 +701,37 @@ function neededBy(tool) {
600
701
  return features.length === Object.keys(FEATURE_TOOLS).length ? '所有功能需要' : `${features.join('、')}需要`;
601
702
  }
602
703
 
603
- function printDoctor(result) {
704
+ function printDoctor(result, out = say) {
604
705
  const ready = [];
605
706
  const missing = [];
606
707
  for (const [name, info] of Object.entries(result.tools)) {
607
708
  if (info.ok) ready.push(`✓ ${toolLabel(name)}${info.version ? ` ${info.version.split('.').slice(0, 2).join('.')}` : ''}`);
608
709
  else missing.push(name);
609
710
  }
610
- if (ready.length) say(` ${ready.join(' ')}`);
611
- for (const name of missing) say(` ✗ ${toolLabel(name).padEnd(11)} ${neededBy(name)}`);
612
- if (!result.claude.path) say(` ✗ ${'claude'.padEnd(11)} 所有功能需要`);
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)} 所有功能需要`);
613
714
  else if (!result.claudeVersion) {
614
715
  // 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 重新安装`);
716
+ out(` ✗ ${'claude'.padEnd(11)} 无法运行(${result.claude.path}):请运行 work-agent-runner setup 重新安装`);
616
717
  } else {
617
- say(` ✓ claude ${result.claudeVersion}`);
618
- if (result.claude.viaNpmPrefix) say(` 提示:claude 在 ${path.dirname(result.claude.path)},建议把这个目录加入 PATH`);
718
+ out(` ✓ claude ${result.claudeVersion}`);
719
+ if (result.claude.viaNpmPrefix) out(` 提示:claude 在 ${path.dirname(result.claude.path)},建议把这个目录加入 PATH`);
619
720
  }
620
721
  const { sandbox } = result.capabilities;
621
- if (sandbox.ok) say('✓ 沙箱可用');
622
- else say(`✗ 沙箱不可用:${sandbox.reason}(说明:${SANDBOX_DOCS})`);
722
+ if (sandbox.ok) out('✓ 沙箱可用');
723
+ else out(`✗ 沙箱不可用:${sandbox.reason}(说明:${SANDBOX_DOCS})`);
623
724
  }
624
725
 
625
- function printFeatures(reply) {
726
+ function printFeatures(reply, out = say) {
626
727
  if (!reply?.features) return;
627
728
  const entries = Object.entries(reply.features);
628
729
  const ok = entries.filter(([, verdict]) => verdict.ok).map(([feature]) => FEATURE_LABELS[feature] || feature);
629
- say(ok.length ? `可运行:${ok.join('、')}` : '暂时没有可运行的功能');
730
+ out(ok.length ? `可运行:${ok.join('、')}` : '暂时没有可运行的功能');
630
731
  for (const [feature, verdict] of entries) {
631
- if (!verdict.ok) say(`不可运行:${FEATURE_LABELS[feature] || feature}(${verdict.reason})`);
732
+ if (!verdict.ok) out(`不可运行:${FEATURE_LABELS[feature] || feature}(${verdict.reason})`);
632
733
  }
633
- if (reply.outdated) say(`程序版本过低,请运行 ${UPDATE_COMMAND}`);
734
+ if (reply.outdated) out(`程序版本过低,请运行 ${UPDATE_COMMAND}`);
634
735
  }
635
736
 
636
737
  function setupPlan(result, reply, { poolWanted = false } = {}) {
@@ -662,7 +763,16 @@ function runningInstance(ctx) {
662
763
  return holder !== process.pid && isRunnerAlive(holder) ? holder : 0;
663
764
  }
664
765
 
665
- // ---- Commands ------------------------------------------------------------------
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
+ }
666
776
 
667
777
  async function start(values) {
668
778
  checkSystem();
@@ -686,6 +796,8 @@ async function start(values) {
686
796
  try {
687
797
  prepareRunDirs(ctx);
688
798
  applyPending(ctx);
799
+ // The instance's log also goes to logs/runner.log (`work-agent-runner logs`).
800
+ log.setFile(ctx.paths.logFile);
689
801
  say(`GitCode Agent 执行机器 ${VERSION}`);
690
802
  if (legacyServiceInstalled()) log.warn(LEGACY_SERVICE_HINT);
691
803
  // Whatever a previous run left behind (run directories r??????, probe
@@ -701,57 +813,88 @@ async function start(values) {
701
813
  if (!ctx.config.token && !interactive) {
702
814
  throw new ExitError(ATTENTION, '还没有接入令牌:请先在终端运行 work-agent-runner login');
703
815
  }
704
- say('检查 work-agent 仓库……');
705
- printWorkAgent(await refreshWorkAgent(ctx));
706
- // No job is running yet, so it is safe to empty $WORK_AGENT_HOME/tmp, drop
707
- // old logs (work-agent's own cleanup) and pull the knowledge pool — a
708
- // `git pull` must never replace files a running review is reading.
709
- await ctx.workAgent.cleanup({ say: (line) => log.info(line) }).catch(() => {});
710
- await updatePool(ctx);
711
- clearPoolUpdateRequest(ctx.paths); // just done
712
- say('检查依赖和沙箱……');
713
- let result = await doctorFor(ctx);
714
- let client;
715
- let reply;
716
- if (!ctx.config.token) {
717
- ({ client, reply } = await obtainToken(ctx, { capabilities: result.capabilities }));
718
- } else {
719
- client = clientFor(ctx);
720
- reply = await connectSaved(ctx, client, result.capabilities);
721
- sayRegistered(ctx, reply);
722
- }
723
- printDoctor(result);
724
- const firstRun = !ctx.config.setupDone && interactive;
725
- if (firstRun) {
726
- const outcome = await runSetup({
727
- plan: setupPlan(result, reply, { poolWanted: !values['no-repos'] }),
728
- interactive: true,
729
- confirm: (question) => askYesNo(question),
730
- say,
731
- });
732
- // Asked once: missing items stay visible in status and on the website.
733
- saveField(ctx, 'setupDone', true);
734
- if (outcome.ran) {
735
- say('重新检查……');
736
- result = await doctorFor(ctx);
737
- printDoctor(result);
738
- }
739
- // The first clone may have failed for want of git, which setup just installed.
740
- await ensureClone(ctx);
741
- // The same question `setup` asks, so a first run settles everything.
742
- await offerPool(ctx, values);
743
- result = await doctorFor(ctx);
744
- reply = await connectSaved(ctx, client, result.capabilities);
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 });
745
820
  }
746
- printFeatures(reply);
747
- say('等待任务……(Ctrl+C 退出;后台运行:work-agent-runner service install)');
748
- 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 });
749
826
  } finally {
750
827
  lock.release();
751
828
  }
752
829
  }
753
830
 
754
- async function serve(ctx, client, initial, reply) {
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
+
755
898
  const controller = new AbortController();
756
899
  let fatal = null;
757
900
  const onFatal = (error) => {
@@ -761,131 +904,331 @@ async function serve(ctx, client, initial, reply) {
761
904
  controller.abort();
762
905
  }
763
906
  };
764
- const jobs = new JobManager({
765
- client,
766
- workAgent: ctx.workAgent,
767
- workRoot: ctx.workRoot,
768
- claudePath: initial.claude.path,
769
- realHome: ctx.realHome,
770
- log,
771
- onFatal,
772
- });
773
- let capabilities = initial.capabilities;
774
- // One maintenance step at a time: a hung pull must not stack up another round.
775
- let checking = false;
776
- const exclusive = async (work) => {
777
- if (checking) return;
778
- checking = true;
779
- try {
780
- await work();
781
- } catch (error) {
782
- log.warn(`定期检查失败:${error.message}`);
783
- } finally {
784
- checking = false;
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 };
785
952
  }
953
+ publish();
786
954
  };
787
955
  const recheck = async () => {
788
956
  const fresh = await doctorFor(ctx);
789
957
  capabilities = fresh.capabilities;
790
958
  if (fresh.claude.path) jobs.claudePath = fresh.claude.path;
959
+ refreshDegraded();
960
+ return fresh;
791
961
  };
792
962
 
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;
963
+ jobs = new JobManager({
964
+ client,
965
+ workAgent: ctx.workAgent,
966
+ workRoot: ctx.workRoot,
967
+ claudePath: initial.claude.path,
968
+ realHome: ctx.realHome,
969
+ log,
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
+ }
811
984
  }
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
- });
828
- }, POOL_UPDATE_MS);
829
- doctorTimer.unref();
830
- // `work-agent-runner update` in a terminal leaves the pool to this program:
831
- // done as soon as no job runs.
832
- const requestTimer = setInterval(() => {
833
- if (!poolUpdateRequested(ctx.paths) || jobs.runningIds().length) return;
834
- exclusive(async () => {
835
- clearPoolUpdateRequest(ctx.paths);
836
- log.info('按终端里 work-agent-runner update 的请求更新知识仓');
837
- await updatePool(ctx);
838
- await recheck();
839
- });
840
- }, REQUEST_POLL_MS);
841
- requestTimer.unref();
842
- // Every day at 08:00 local time: the work-agent clone (the Skill source).
843
- let repoTimer = null;
844
- const scheduleRepoUpdate = () => {
845
- const next = new Date();
846
- next.setHours(REPO_UPDATE_HOUR, 0, 0, 0);
847
- if (next.getTime() <= Date.now()) next.setDate(next.getDate() + 1);
848
- repoTimer = setTimeout(async () => {
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
+ },
998
+ });
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');
849
1046
  try {
850
- printWorkAgent(await refreshWorkAgent(ctx, { say: (line) => log.info(line) }));
851
- await exclusive(recheck);
852
- scheduleCloneRetry();
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 };
853
1051
  } finally {
854
- // Re-armed each time, so it stays on 08:00 across a change of day length.
855
- scheduleRepoUpdate();
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);
1065
+ } catch (error) {
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];
856
1091
  }
857
- }, next.getTime() - Date.now());
858
- repoTimer.unref();
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
+ },
859
1104
  };
860
- scheduleRepoUpdate();
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
+
861
1114
  let stopping = false;
862
1115
  const onSignal = (signal) => {
863
- if (stopping) return;
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
+ }
864
1124
  stopping = true;
865
1125
  log.info(`收到 ${signal},正在停止(结束运行中的任务)……`);
866
1126
  controller.abort();
867
1127
  };
868
1128
  process.on('SIGINT', onSignal);
869
1129
  process.on('SIGTERM', onSignal);
870
- const result = await runConnection({
871
- client,
872
- jobs,
873
- log,
874
- version: VERSION,
875
- connect: () => connect(ctx, client, capabilities),
876
- capabilities: { current: () => capabilities },
877
- system: { current: () => systemInfo(ctx) },
878
- confirmed: reply.confirmed !== false,
879
- heartbeatMs: reply.heartbeatMs,
880
- 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');
881
1136
  });
882
- clearInterval(doctorTimer);
883
- clearInterval(requestTimer);
884
- clearTimeout(repoTimer);
885
- clearTimeout(cloneTimer);
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
+ }
886
1231
  const outcome = fatal || result;
887
- ctx.workAgent.stop();
888
- await jobs.stopAll(5000);
889
1232
  if (outcome.clearToken && !clearToken(ctx, ctx.config.token)) {
890
1233
  // `login` saved a new token while this one was in use: exit 1 so a service
891
1234
  // restarts and connects with it.
@@ -897,12 +1240,7 @@ async function serve(ctx, client, initial, reply) {
897
1240
  return outcome.code || 0;
898
1241
  }
899
1242
 
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
- }
1243
+ // ---- Terminal commands -------------------------------------------------------
906
1244
 
907
1245
  async function login(values) {
908
1246
  checkSystem();
@@ -947,8 +1285,12 @@ async function setup(values) {
947
1285
  if (restarted !== null) return restarted;
948
1286
  if (!isInteractive()) throw new ExitError(ATTENTION, 'setup 需要在终端里运行(安装前会请你确认)');
949
1287
  const ctx = loadContext(values);
1288
+ const instance = await pingInstance(ctx.paths);
950
1289
  say('检查 work-agent 仓库……');
951
- printWorkAgent(await refreshWorkAgent(ctx));
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));
952
1294
  say('检查依赖和沙箱……');
953
1295
  let result = await doctorFor(ctx);
954
1296
  let client = null;
@@ -956,7 +1298,8 @@ async function setup(values) {
956
1298
  if (ctx.config.token) {
957
1299
  client = clientFor(ctx);
958
1300
  try {
959
- reply = await connect(ctx, client, result.capabilities);
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);
960
1303
  } catch (error) {
961
1304
  say(`无法从网站读取要求(${error.message}),按默认要求检查`);
962
1305
  client = null;
@@ -981,21 +1324,41 @@ async function setup(values) {
981
1324
  await ensureClone(ctx);
982
1325
  // After the tools: the pool is searched with rg.
983
1326
  await offerPool(ctx, values);
984
- if (client) reply = await connect(ctx, client, (await doctorFor(ctx)).capabilities).catch(() => reply);
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
+ }
985
1334
  printFeatures(reply);
986
1335
  return outcome.failed.length ? 1 : 0;
987
1336
  }
988
1337
 
989
1338
  /**
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).
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.
993
1342
  */
994
1343
  async function update(values) {
995
1344
  checkSystem();
996
1345
  const restarted = await applyProxy();
997
1346
  if (restarted !== null) return restarted;
998
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
+ }
999
1362
  const running = runningInstance(ctx);
1000
1363
  let failed = false;
1001
1364
  try {
@@ -1005,6 +1368,7 @@ async function update(values) {
1005
1368
  if (ctx.workAgent.mountablePool()) {
1006
1369
  const busy = poolBusyInfo(ctx.paths);
1007
1370
  if (running) {
1371
+ // An older program without the control interface: it updates when idle.
1008
1372
  requestPoolUpdate(ctx.paths);
1009
1373
  const service = serviceStatus();
1010
1374
  say(`程序正在运行(pid ${running}):已请它在没有任务时更新知识仓${service.installed ? `(${service.logHint})` : ''}`);
@@ -1014,18 +1378,19 @@ async function update(values) {
1014
1378
  } else {
1015
1379
  const done = markPoolBusy(ctx.paths, 'update');
1016
1380
  try {
1017
- await ctx.workAgent.updatePool({ say });
1381
+ await withStopOnSignal(ctx, () => ctx.workAgent.updatePool({ say }));
1018
1382
  } finally {
1019
1383
  done();
1020
1384
  }
1021
1385
  }
1022
1386
  }
1023
1387
  } catch (error) {
1388
+ if (error instanceof ExitError) throw error;
1024
1389
  say(error.message);
1025
1390
  failed = true;
1026
1391
  }
1027
1392
  if (ctx.config.token) {
1028
- // So the website shows the new commit without waiting for the hourly check.
1393
+ // So the website shows the new commit without waiting for the next start.
1029
1394
  try {
1030
1395
  printFeatures(await connect(ctx, clientFor(ctx), (await doctorFor(ctx)).capabilities));
1031
1396
  } catch {
@@ -1040,6 +1405,23 @@ async function doctor(values) {
1040
1405
  const restarted = await applyProxy();
1041
1406
  if (restarted !== null) return restarted;
1042
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
+ }
1043
1425
  const result = await doctorFor(ctx);
1044
1426
  let reply = null;
1045
1427
  let note = '';
@@ -1067,60 +1449,289 @@ async function doctor(values) {
1067
1449
  return 0;
1068
1450
  }
1069
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
+
1070
1487
  async function status(values) {
1071
1488
  checkSystem();
1072
1489
  const restarted = await applyProxy();
1073
1490
  if (restarted !== null) return restarted;
1074
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
+ }
1075
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
+ }
1076
1505
  say(`网站:${ctx.server}`);
1077
1506
  say(`令牌:${config.token ? `${config.token.slice(0, 12)}…` : '未登录(运行 work-agent-runner login)'}`);
1078
1507
  say(`机器标识:${config.clientId}`);
1079
1508
  say(`登记名称:${config.machineName || `${os.hostname()}(主机名)`}`);
1080
- say(`程序目录:${ctx.paths.baseDir}`);
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')},程序每小时重试)`);
1090
- const repo = ctx.workAgent.state();
1091
- say(`work-agent 仓库:${repo.ok ? `${repo.commit.slice(0, 7)}(${ctx.workAgent.repoDir})` : repo.reason}`);
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 为准)` : ''}`);
1094
- const poolRepos = ctx.workAgent.poolRepos();
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}),等待程序在没有任务时执行`);
1100
- say(`系统:${describeSystem(systemInfo(ctx))}`);
1101
1509
  say(`配置文件:${ctx.paths.configFile}`);
1102
- const service = serviceStatus();
1103
1510
  say(`后台服务:${service.installed ? `${service.state}(${service.name};${service.logHint})` : '未安装'}`);
1104
1511
  if (legacyServiceInstalled()) say(LEGACY_SERVICE_HINT);
1105
- const holder = lockHolder(ctx.paths.lockFile);
1106
- say(`运行中的实例:${isRunnerAlive(holder) ? `pid ${holder}` : '无'}`);
1107
- if (!config.token) return 0;
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 = '';
1108
1656
  try {
1109
- // A request with no effect (it must not be /heartbeat: reporting no running
1110
- // jobs from a second process would make the website fail this machine's jobs).
1111
- await clientFor(ctx).request('GET', '/ping');
1112
- say('连接测试:正常');
1657
+ const where = socketLocation(paths);
1658
+ socket = where.socket;
1659
+ socketNote = `${exists(where.socket) ? '程序运行中' : '程序没有在运行'}${where.fallback ? ' · 程序目录的路径太长,放在这里' : ''}`;
1113
1660
  } catch (error) {
1114
- if (error instanceof ApiError) {
1115
- const text = {
1116
- 404: '网站版本过旧(没有 /ping),请联系管理员部署新版网站',
1117
- 401: '令牌无效或已删除(运行 work-agent-runner login)',
1118
- 403: '这台机器已被封禁',
1119
- 409: '令牌有效,这台机器尚未登记(运行 work-agent-runner 会自动登记,之后在网页上确认)',
1120
- }[error.status] || error.message;
1121
- say(`连接测试:${text}`);
1122
- } else say(`连接测试:失败(${networkReason(error)})`);
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
+ }
1123
1732
  }
1733
+ await withStopOnSignal(ctx, () => ctx.workAgent.cleanup({ say }));
1734
+ say('已清理');
1124
1735
  return 0;
1125
1736
  }
1126
1737
 
@@ -1187,6 +1798,12 @@ async function main(argv) {
1187
1798
  'token-stdin': { type: 'boolean' },
1188
1799
  repos: { type: 'string' },
1189
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' },
1190
1807
 
1191
1808
  yes: { type: 'boolean', short: 'y' },
1192
1809
  json: { type: 'boolean' },
@@ -1200,10 +1817,18 @@ async function main(argv) {
1200
1817
  const { values, positionals } = parsed;
1201
1818
  if (values.version) return say(VERSION) ?? 0;
1202
1819
  if (values.help) return say(USAGE) ?? 0;
1203
- const [command = 'start', action] = positionals;
1820
+ const [command = 'start', action, argument] = positionals;
1204
1821
  switch (command) {
1205
1822
  case 'start':
1206
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);
1207
1832
  case 'login':
1208
1833
  return login(values);
1209
1834
  case 'logout':
@@ -1214,8 +1839,10 @@ async function main(argv) {
1214
1839
  return update(values);
1215
1840
  case 'doctor':
1216
1841
  return doctor(values);
1217
- case 'status':
1218
- return status(values);
1842
+ case 'cleanup':
1843
+ return cleanupCommand(values);
1844
+ case 'reload':
1845
+ return reload(values);
1219
1846
  case 'service':
1220
1847
  return service(action, values);
1221
1848
  case 'version':