@online-tools/work-agent-runner 0.1.0-alpha-1 → 0.1.0-alpha-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,6 +19,7 @@ const BACKOFF_MAX_MS = 60_000;
19
19
  const STABLE_MS = 60_000;
20
20
  const REPLACED_WINDOW_MS = 10 * 60_000;
21
21
  const REPLACED_LIMIT = 3;
22
+ const MIN_BEAT_GAP_MS = 2000;
22
23
 
23
24
  export const FATAL = {
24
25
  tokenDeleted: {
@@ -78,6 +79,10 @@ function jitter(ms) {
78
79
  * onStatus (optional) { connected, since, lastHeartbeatAt, lastError, confirmed }
79
80
  * as they change, for the instance's status
80
81
  * onReply (optional) the reply of a /connect made here (re-registration)
82
+ * selfReport (optional) { current(): { state, jobs } } — whether this machine takes
83
+ * jobs and why not, and its jobs' phases, with every heartbeat (0.1.0-alpha-2+)
84
+ * bindBeat (optional) receives beat(): send a heartbeat now (the machine stopped
85
+ * or resumed taking jobs), at most every MIN_BEAT_GAP_MS
81
86
  *
82
87
  * A heartbeat reply may carry capabilitiesDigest (the SHA-256 of the
83
88
  * capabilities the website last received, as JSON): when it is not this
@@ -97,10 +102,13 @@ export async function runConnection({
97
102
  signal,
98
103
  onStatus = () => {},
99
104
  onReply = () => {},
105
+ selfReport = null,
106
+ bindBeat = () => {},
100
107
  }) {
101
108
  const stopper = new AbortController();
102
109
  const stop = AbortSignal.any([signal || new AbortController().signal, stopper.signal]);
103
- const state = { result: null, heartbeatMs, replaced: [], sentCapabilities: '', warnedOutdated: false, toldLatest: '', confirmed };
110
+ // confirmedAt: when a `confirmed` event arrived — a heartbeat reply computed before it is stale.
111
+ const state = { result: null, heartbeatMs, replaced: [], sentCapabilities: '', warnedOutdated: false, toldLatest: '', confirmed, confirmedAt: 0 };
104
112
 
105
113
  const report = (patch) => {
106
114
  try {
@@ -161,6 +169,7 @@ export async function runConnection({
161
169
  jobs.handle(event.job);
162
170
  break;
163
171
  case 'confirmed':
172
+ state.confirmedAt = Date.now();
164
173
  noteConfirmed(true, typeof event.name === 'string' ? event.name.slice(0, 40) : '');
165
174
  break;
166
175
  case 'cancel':
@@ -186,11 +195,47 @@ export async function runConnection({
186
195
  }
187
196
  };
188
197
 
198
+ // The wait between heartbeats, cut short by beat(). A beat asked for while a
199
+ // heartbeat is on its way is sent right after it (pending).
200
+ let wake = null;
201
+ let pending = false;
202
+ let lastBeatAt = 0;
203
+ const untilAllowed = () => Math.max(0, MIN_BEAT_GAP_MS - (Date.now() - lastBeatAt));
204
+ const nap = (ms) =>
205
+ new Promise((resolve) => {
206
+ const done = () => {
207
+ clearTimeout(timer);
208
+ stop.removeEventListener('abort', done);
209
+ wake = null;
210
+ resolve();
211
+ };
212
+ // A pending beat goes as soon as allowed — never later than the regular one.
213
+ const timer = setTimeout(done, pending ? Math.min(ms, untilAllowed()) : ms);
214
+ stop.addEventListener('abort', done, { once: true });
215
+ wake = done;
216
+ });
217
+ bindBeat(() => {
218
+ pending = true;
219
+ if (!wake) return;
220
+ const wait = untilAllowed();
221
+ if (!wait) wake();
222
+ else setTimeout(() => (pending ? wake?.() : null), wait).unref?.();
223
+ });
224
+
189
225
  const heartbeats = (async () => {
190
226
  while (!stop.aborted) {
191
- await sleep(state.heartbeatMs, stop);
227
+ await nap(state.heartbeatMs);
192
228
  if (stop.aborted) break;
229
+ pending = false;
230
+ lastBeatAt = Date.now();
193
231
  const body = { version, running: jobs.runningIds().slice(0, 200) };
232
+ if (selfReport) {
233
+ try {
234
+ Object.assign(body, selfReport.current());
235
+ } catch (error) {
236
+ log.warn(`读取本机状态失败:${error.message}`);
237
+ }
238
+ }
194
239
  const current = JSON.stringify(capabilities.current());
195
240
  if (current !== state.sentCapabilities) body.capabilities = capabilities.current();
196
241
  if (system) {
@@ -214,7 +259,8 @@ export async function runConnection({
214
259
  // Answers the website has not seen arrive yet (the control channel may
215
260
  // have been down); repeats of one already given are dropped.
216
261
  for (const item of Array.isArray(reply?.answers) ? reply.answers : []) jobs.answer?.(item?.runId, item?.requestId, item?.answers);
217
- noteConfirmed(reply?.confirmed);
262
+ // A reply computed before the `confirmed` event that overtook it says nothing new.
263
+ if (!(reply?.confirmed === false && state.confirmedAt >= lastBeatAt)) noteConfirmed(reply?.confirmed);
218
264
  if (reply?.outdated && !state.warnedOutdated) {
219
265
  state.warnedOutdated = true;
220
266
  log.warn(`程序版本 ${version} 已低于网站要求的 ${reply.minVersion},请运行 ${UPDATE_COMMAND} 后重启`);
@@ -0,0 +1,82 @@
1
+ // `work-agent-runner diagnose` (design 9.5): a .tar.gz a person can look
2
+ // through and send to whoever helps them — version, check, status, paths,
3
+ // recent job history, the end of the program log, the latest setup log, the
4
+ // config without its token, the service definition, system details. Every
5
+ // text goes through redact() on the way in; the config's token is removed
6
+ // outright. The archive holds regular files only (a tar writer of its own,
7
+ // gzip from node:zlib).
8
+ //
9
+ // Only node: built-ins and files in this directory.
10
+
11
+ import zlib from 'node:zlib';
12
+
13
+ import { redact } from './log.mjs';
14
+
15
+ const BLOCK = 512;
16
+
17
+ function octal(value, length) {
18
+ return `${value.toString(8).padStart(length - 1, '0')}\0`;
19
+ }
20
+
21
+ /** One ustar header for a regular file `name` (≤ 100 bytes) of `size` bytes. */
22
+ function header(name, size, mtime) {
23
+ const block = Buffer.alloc(BLOCK, 0);
24
+ const write = (text, offset, length) => block.write(text, offset, length, 'utf8');
25
+ if (Buffer.byteLength(name) > 100) throw new Error(`文件名过长:${name}`);
26
+ write(name, 0, 100);
27
+ write(octal(0o644, 8), 100, 8); // mode
28
+ write(octal(0, 8), 108, 8); // uid
29
+ write(octal(0, 8), 116, 8); // gid
30
+ write(octal(size, 12), 124, 12);
31
+ write(octal(Math.floor(mtime / 1000), 12), 136, 12);
32
+ write(' ', 148, 8); // checksum: spaces while it is computed
33
+ write('0', 156, 1); // regular file
34
+ write('ustar\0', 257, 6);
35
+ write('00', 263, 2);
36
+ let sum = 0;
37
+ for (const byte of block) sum += byte;
38
+ write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 8);
39
+ return block;
40
+ }
41
+
42
+ /** A gzip'ed tar of `files` ([{ name, content }], regular files under one directory). */
43
+ export function tarGz(files, { mtime = Date.now() } = {}) {
44
+ const parts = [];
45
+ for (const { name, content } of files) {
46
+ const data = Buffer.isBuffer(content) ? content : Buffer.from(String(content), 'utf8');
47
+ parts.push(header(name, data.length, mtime), data);
48
+ const pad = (BLOCK - (data.length % BLOCK)) % BLOCK;
49
+ if (pad) parts.push(Buffer.alloc(pad, 0));
50
+ }
51
+ parts.push(Buffer.alloc(BLOCK * 2, 0));
52
+ return zlib.gzipSync(Buffer.concat(parts));
53
+ }
54
+
55
+ /** The config as it goes into a bundle: no token, every other value kept (and redacted like any text). */
56
+ export function configForBundle(config) {
57
+ const copy = { ...config };
58
+ if (copy.token) copy.token = '(已去掉)';
59
+ return copy;
60
+ }
61
+
62
+ /** The last `count` lines of `text`. */
63
+ export function lastLines(text, count) {
64
+ const lines = String(text || '').split('\n');
65
+ if (lines.at(-1) === '') lines.pop();
66
+ return lines.slice(-count).join('\n') + (lines.length ? '\n' : '');
67
+ }
68
+
69
+ /**
70
+ * The bundle's files, in order, every text redacted: `entries` is
71
+ * [{ name, content }] (strings or objects, written as JSON). Returns
72
+ * { files, listing } — what the archive holds, for the person to look at.
73
+ */
74
+ export function bundleFiles(entries, { folder = 'work-agent-runner-diag' } = {}) {
75
+ const files = [];
76
+ for (const { name, content } of entries) {
77
+ if (content === null || content === undefined) continue;
78
+ const text = typeof content === 'string' ? content : `${JSON.stringify(content, null, 2)}\n`;
79
+ files.push({ name: `${folder}/${name}`, content: redact(text) });
80
+ }
81
+ return { files, listing: files.map((file) => `${file.name}(${Buffer.byteLength(file.content)} 字节)`) };
82
+ }
package/lib/doctor.mjs CHANGED
@@ -8,7 +8,8 @@ import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import readline from 'node:readline';
10
10
 
11
- import { claudeArgs, claudeEnv } from './claude-cli.mjs';
11
+ import { readApparmor, readUserns, sandboxProblem } from './check.mjs';
12
+ import { VERIFIED_CLAUDE_VERSION, claudeArgs, claudeEnv } from './claude-cli.mjs';
12
13
  import { removeTree } from './fs-safe.mjs';
13
14
  import { SANDBOX_TOOLS, SKILL_TOOLS, detectPackageManager } from './packages.mjs';
14
15
  import { PROBE_MARKER, PROBE_TOOL_ID, startProbeModel } from './probe-model.mjs';
@@ -256,7 +257,8 @@ export async function probeSandbox({
256
257
  /**
257
258
  * Full check. `probe: false` skips the sandbox probe (it then reads as not
258
259
  * checked). `workAgent`: a WorkAgent, whose clone and pool are reported as
259
- * capabilities and mounted into the probe exactly as into a job. Returns
260
+ * capabilities and mounted into the probe exactly as into a job. `apparmorFacts`
261
+ * / `usernsFacts` read the system (injected by tests). Returns
260
262
  * { capabilities, tools, claude, claudeVersion, packageManager, workAgent }.
261
263
  */
262
264
  export async function runDoctor({
@@ -269,6 +271,9 @@ export async function runDoctor({
269
271
  workAgent = null,
270
272
  probe = true,
271
273
  probeTimeoutMs = PROBE_TIMEOUT_MS,
274
+ apparmorFacts = readApparmor,
275
+ usernsFacts = readUserns,
276
+ managedDir = '',
272
277
  }) {
273
278
  const pathEnv = env.PATH || '';
274
279
  const tools = checkTools({ platform, pathEnv });
@@ -291,9 +296,15 @@ export async function runDoctor({
291
296
  timeoutMs: probeTimeoutMs,
292
297
  });
293
298
  if (!sandbox.ok && platform === 'linux') {
294
- // The common case, in words the user can act on (setup installs them).
299
+ // The common cases, in words the user can act on: missing tools (setup
300
+ // installs them), AppArmor's user-namespace restriction (E1402, an
301
+ // administrator's call). Claude Code's own words stay in `raw` for `check`.
295
302
  const missing = SANDBOX_TOOLS.filter((name) => !tools[name]?.ok).map((name) => (name === 'bwrap' ? 'bubblewrap' : name));
296
303
  if (missing.length) sandbox = { ok: false, reason: `缺少 ${missing.join('、')}` };
304
+ else {
305
+ const problem = sandboxProblem({ reason: sandbox.reason, platform, apparmor: apparmorFacts(), userns: usernsFacts() });
306
+ if (problem.code === 'E1402') sandbox = { ok: false, reason: 'AppArmor 限制了非特权 user namespace(E1402,运行 work-agent-runner check 查看)', raw: sandbox.reason };
307
+ }
297
308
  }
298
309
  }
299
310
  return {
@@ -308,6 +319,11 @@ export async function runDoctor({
308
319
  // This program runs 交互执行 jobs (lib/interaction.mjs, since 0.0.3); the
309
320
  // website only sends `interactive: true` to machines that say so.
310
321
  interactive: true,
322
+ // Jobs report their phases (machine_status lines, POST …/started; 0.1.0-alpha-2).
323
+ jobPhases: true,
324
+ // Installed by this program (claude/<version>/claude) or by the user; the version it was tested with?
325
+ claudeSource: claude.path ? (managedDir && claude.path.startsWith(`${managedDir}${path.sep}`) ? 'managed' : 'external') : '',
326
+ claudeVerified: Boolean(version) && version === VERIFIED_CLAUDE_VERSION,
311
327
  workAgent: repo
312
328
  ? { commit: repo.commit, committedAt: repo.committedAt, repos: repo.repos, ascend: repo.ascend }
313
329
  : { commit: '', committedAt: '', repos: 0, ascend: false },
package/lib/errors.mjs CHANGED
@@ -4,8 +4,17 @@
4
4
  // far; the catalog grows with it.
5
5
 
6
6
  export const ERROR_CODES = {
7
+ E1103: '以 root 运行',
8
+ E1105: '工作目录路径过长(沙箱 socket)',
7
9
  E1112: '本机管理接口无法启动(socket 路径太长或目录不安全)',
10
+ E1115: 'work-agent 克隆目录不是本程序创建的',
11
+ E1201: '缺少依赖',
8
12
  E1301: 'Claude Code 未安装或无法运行',
13
+ E1302: 'Claude Code 下载或校验失败',
14
+ E1402: 'AppArmor 限制了非特权 user namespace',
15
+ E2101: '无法连接网站',
16
+ E2201: '接入令牌无效或已删除',
17
+ E2202: '机器已被封禁',
9
18
  E3101: '任务参数不合法',
10
19
  E3201: '等待执行条件超时',
11
20
  E3301: '工作目录磁盘空间不足',
package/lib/jobs.mjs CHANGED
@@ -277,8 +277,14 @@ function killGroup(pid, signal) {
277
277
  * (the history: phase times, result, exit, error code — never the task, a
278
278
  * key or an answer).
279
279
  * gate({ isCancelled, timeoutMs, onWait }) resolves { ok: true } once the job
280
- * may start, or { ok: false, code, message }. Default: no knowledge-pool
281
- * update is running (a `git pull` must not replace files under a job).
280
+ * may start, or { ok: false, code, message }; onWait(code, text) when it
281
+ * has to wait (code: waiting_starting / waiting_pool_update …). Default: no
282
+ * knowledge-pool update is running (a `git pull` must not replace files
283
+ * under a job).
284
+ * From acceptance on, the job's output stream carries `machine_status` lines
285
+ * (waiting, preparing, started) — the website shows its own text for their
286
+ * code — and POST …/started tells it when claude runs, so its backstop counts
287
+ * from there (capabilities.jobPhases).
282
288
  * runMode() { isolation: 'shared' | 'per-run', keep: 'merge' | 'archive' | 'none' }:
283
289
  * how the job sees work-agent's home, and what becomes of the logs and
284
290
  * deliverables a per-run job leaves (docs/design.md 2.6).
@@ -500,12 +506,52 @@ export class JobManager {
500
506
  }
501
507
  }
502
508
 
503
- /** Not run: tells the website why (with the code) and records it. */
509
+ /** Not run: tells the website why (with the code, after the status lines sent so far) and records it. */
504
510
  async fail(entry, code, message) {
505
- await this.reportExit(entry, { error: withCode(code, message) });
511
+ await entry.uploader?.drain();
512
+ if (!entry.gone) await this.reportExit(entry, { seq: entry.uploader?.lastSeq || 0, error: withCode(code, message) });
506
513
  this.record(entry, { result: 'failed', code, message });
507
514
  }
508
515
 
516
+ /** The job's output stream, from acceptance on (status lines first, then claude's output). */
517
+ uploaderFor(entry) {
518
+ return new OutputUploader({
519
+ client: this.client,
520
+ runId: entry.runId,
521
+ onGone: () => {
522
+ entry.gone = true;
523
+ this.terminate(entry);
524
+ },
525
+ onFailure: (reason) => {
526
+ entry.failure = reason;
527
+ this.terminate(entry);
528
+ },
529
+ onFatal: (error) => {
530
+ this.terminate(entry);
531
+ this.onFatal(error);
532
+ },
533
+ });
534
+ }
535
+
536
+ /** A `machine_status` line in the job's output: { code, waitedMs } (the website words it). */
537
+ status(entry, code, waitedMs = 0) {
538
+ entry.uploader?.push('stdout', `${JSON.stringify({ type: 'machine_status', code, waitedMs: Math.max(0, Math.round(waitedMs)) })}\n`);
539
+ }
540
+
541
+ /** POST …/started: claude runs now. A website without it answers 404: nothing to do. */
542
+ async reportStarted(entry, waitedMs) {
543
+ const url = `/jobs/${encodeURIComponent(entry.runId)}/started`;
544
+ for (let attempt = 0; attempt < 3; attempt += 1) {
545
+ try {
546
+ await this.client.request('POST', url, { waitedMs: Math.max(0, Math.round(waitedMs)) });
547
+ return;
548
+ } catch (error) {
549
+ if (error instanceof ApiError && error.status < 500 && error.status !== 429) return;
550
+ await sleep(error?.retryAfterMs || backoff(attempt));
551
+ }
552
+ }
553
+ }
554
+
509
555
  /** The job's one history record (once): what happened, never what it was asked or given. */
510
556
  record(entry, { result, code = '', message = '', exit = null }) {
511
557
  if (entry.recorded) return;
@@ -535,7 +581,7 @@ export class JobManager {
535
581
  /** The default gate: no knowledge-pool update in progress (bounded wait). */
536
582
  async poolGate({ isCancelled, timeoutMs, onWait }) {
537
583
  if (typeof this.workAgent?.waitForPoolIdle !== 'function') return { ok: true };
538
- const idle = await this.workAgent.waitForPoolIdle({ timeoutMs, isCancelled, onWait: () => onWait('等待知识仓更新完成后开始') });
584
+ const idle = await this.workAgent.waitForPoolIdle({ timeoutMs, isCancelled, onWait: () => onWait('waiting_pool_update', '等待知识仓更新完成后开始') });
539
585
  if (idle || isCancelled()) return { ok: true };
540
586
  return {
541
587
  ok: false,
@@ -555,6 +601,7 @@ export class JobManager {
555
601
  return;
556
602
  }
557
603
  this.setPhase(entry, 'accepted');
604
+ entry.uploader = this.uploaderFor(entry);
558
605
  if (invalid) {
559
606
  this.log.warn(`任务 ${runId} 参数不合法(${invalid}),未执行`);
560
607
  await this.fail(entry, 'E3101', `任务参数不合法:${invalid}`);
@@ -569,12 +616,16 @@ export class JobManager {
569
616
  try {
570
617
  this.setPhase(entry, 'waiting');
571
618
  const gate = await this.gate({
572
- isCancelled: () => entry.cancelled,
619
+ isCancelled: () => entry.cancelled || entry.gone,
573
620
  timeoutMs: this.jobWaitMs,
574
- onWait: (why) => this.log.info(`任务 ${runId} ${why}`),
621
+ onWait: (code, why) => {
622
+ this.log.info(`任务 ${runId} ${why}`);
623
+ this.status(entry, code);
624
+ },
575
625
  });
576
- if (entry.cancelled) {
577
- await this.reportExit(entry, { signal: 'SIGTERM', error: this.cancelReason(entry) });
626
+ if (entry.cancelled || entry.gone) {
627
+ await entry.uploader.drain();
628
+ if (!entry.gone) await this.reportExit(entry, { seq: entry.uploader.lastSeq, signal: 'SIGTERM', error: this.cancelReason(entry) });
578
629
  this.record(entry, { result: 'cancelled' });
579
630
  return;
580
631
  }
@@ -585,6 +636,8 @@ export class JobManager {
585
636
  }
586
637
 
587
638
  this.setPhase(entry, 'preparing');
639
+ const waitedMs = Date.parse(entry.at.preparing) - Date.parse(entry.at.waiting);
640
+ this.status(entry, 'preparing', waitedMs);
588
641
  // A code review clones the repository it reviews: no room, no start.
589
642
  const free = this.freeBytes(this.runsDir);
590
643
  if (free && free < this.minFreeBytes) {
@@ -616,10 +669,12 @@ export class JobManager {
616
669
  // the run's own), and the knowledge pool read-only if there is one: the
617
670
  // settings name every path the job may reach (sandbox.mjs).
618
671
  try {
619
- const { commit } = await this.workAgent.copyRepoInto(layout.workDir, {
620
- logs: path.join(layout.workAgentHome || this.paths.workAgentHome, 'logs'),
621
- scratch: layout.scratchDir,
622
- });
672
+ const { commit } = await this.workAgent.copyRepoInto(
673
+ layout.workDir,
674
+ { logs: path.join(layout.workAgentHome || this.paths.workAgentHome, 'logs'), scratch: layout.scratchDir },
675
+ // Another process (a terminal's update) holds the clone: say so on the page.
676
+ { onWait: () => this.status(entry, 'waiting_clone') },
677
+ );
623
678
  entry.commit = commit;
624
679
  const pool = this.workAgent.mountablePool();
625
680
  writeSandboxSettings(layout.settingsFile, {
@@ -647,9 +702,10 @@ export class JobManager {
647
702
  return;
648
703
  }
649
704
 
650
- const result = await this.spawnClaude(entry, layout);
705
+ const result = await this.spawnClaude(entry, layout, waitedMs);
651
706
  const failure = result.error || entry.failure;
652
707
  const failureCode = result.error ? 'E1301' : entry.failure ? 'E3501' : '';
708
+ await entry.uploader.drain();
653
709
  if (!entry.gone) {
654
710
  await this.reportExit(entry, {
655
711
  seq: entry.uploader.lastSeq,
@@ -724,11 +780,10 @@ export class JobManager {
724
780
  else this.log.warn(`运行目录 ${runDir} 删不掉(${why}),下次启动时再试`);
725
781
  }
726
782
 
727
- spawnClaude(entry, layout) {
783
+ spawnClaude(entry, layout, waitedMs = 0) {
728
784
  const { job } = entry;
729
785
  return new Promise((resolve) => {
730
786
  if (!this.claudePath) {
731
- entry.uploader = { lastSeq: 0, totalBytes: 0 };
732
787
  resolve({ code: null, signal: null, error: '无法启动 claude:未安装' });
733
788
  return;
734
789
  }
@@ -759,32 +814,18 @@ export class JobManager {
759
814
  }),
760
815
  });
761
816
  } catch (error) {
762
- entry.uploader = { lastSeq: 0, totalBytes: 0 };
763
817
  resolve({ code: null, signal: null, error: `无法启动 claude:${error.code || error.message}` });
764
818
  return;
765
819
  }
766
820
  entry.child = child;
821
+ const { uploader } = entry;
767
822
  if (child.pid) {
768
823
  entry.timeoutAt = new Date(Date.now() + job.timeoutMs).toISOString();
769
824
  this.setPhase(entry, 'running');
825
+ // Ahead of claude's first line; the website's backstop counts from here.
826
+ this.status(entry, 'started', waitedMs);
827
+ this.reportStarted(entry, waitedMs).catch(() => {});
770
828
  }
771
- const uploader = new OutputUploader({
772
- client: this.client,
773
- runId: entry.runId,
774
- onGone: () => {
775
- entry.gone = true;
776
- this.terminate(entry);
777
- },
778
- onFailure: (reason) => {
779
- entry.failure = reason;
780
- this.terminate(entry);
781
- },
782
- onFatal: (error) => {
783
- this.terminate(entry);
784
- this.onFatal(error);
785
- },
786
- });
787
- entry.uploader = uploader;
788
829
  if (interactive) {
789
830
  entry.interaction = createClaudeInteraction({
790
831
  write: (message) => {
package/lib/log.mjs CHANGED
@@ -64,6 +64,7 @@ function sizeOf(file) {
64
64
 
65
65
  export function createLogger({ out = process.stdout, err = process.stderr, file = '', maxBytes = LOG_MAX_BYTES, keep = LOG_KEEP } = {}) {
66
66
  let target = file;
67
+ let infoStream = out;
67
68
  let size = target ? sizeOf(target) : 0;
68
69
  const listeners = new Set();
69
70
  const toFile = (line) => {
@@ -87,7 +88,11 @@ export function createLogger({ out = process.stdout, err = process.stderr, file
87
88
  for (const listener of listeners) listener({ time, level, text });
88
89
  };
89
90
  return {
90
- info: (message) => write(out, 'INFO', '', message),
91
+ info: (message) => write(infoStream, 'INFO', '', message),
92
+ /** Info lines to another stream (setup --unattended keeps stdout for its JSON report). */
93
+ setOut(stream) {
94
+ infoStream = stream;
95
+ },
91
96
  warn: (message) => write(err, 'WARN', '警告:', message),
92
97
  error: (message) => write(err, 'ERROR', '错误:', message),
93
98
  /** From now on also into `next` (0600, its directory 0700); '' stops it. */
package/lib/service.mjs CHANGED
@@ -78,21 +78,30 @@ function systemdExecWord(value) {
78
78
  return systemdWord(value).replace(/\$/g, '$$$$');
79
79
  }
80
80
 
81
+ /**
82
+ * The systemd user unit (design 10.6). No network-online.target: it does
83
+ * nothing for user services; the program retries its connection itself.
84
+ * KillMode=mixed: stop sends SIGTERM to the program alone, which ends its
85
+ * jobs and reports their exits (claude runs in process groups of its own)
86
+ * before TimeoutStopSec kills what is left. Reload is SIGHUP: config.json's
87
+ * maintenance times, limits and isolation apply at once.
88
+ */
81
89
  export function systemdUnit({ nodePath, entry, args = ['start'], environment }) {
82
90
  const lines = [
83
91
  '[Unit]',
84
92
  'Description=work-agent-runner(GitCode 在线工具执行机器)',
85
- 'After=network-online.target',
86
- 'Wants=network-online.target',
87
93
  'StartLimitIntervalSec=300',
88
94
  'StartLimitBurst=10',
89
95
  '',
90
96
  '[Service]',
91
97
  'Type=simple',
92
98
  `ExecStart=${[nodePath, entry, ...args].map(systemdExecWord).join(' ')}`,
99
+ 'ExecReload=/bin/kill -HUP $MAINPID',
93
100
  'Restart=on-failure',
94
101
  'RestartSec=5',
95
102
  `RestartPreventExitStatus=${EXIT_NEEDS_ATTENTION}`,
103
+ 'KillMode=mixed',
104
+ 'TimeoutStopSec=90',
96
105
  ...Object.entries(environment).map(([name, value]) => `Environment=${systemdWord(`${name}=${value}`)}`),
97
106
  '',
98
107
  '[Install]',
@@ -132,6 +141,10 @@ ${variables}
132
141
  <key>SuccessfulExit</key>
133
142
  <false/>
134
143
  </dict>
144
+ <key>ProcessType</key>
145
+ <string>Background</string>
146
+ <key>ExitTimeOut</key>
147
+ <integer>90</integer>
135
148
  <key>StandardOutPath</key>
136
149
  <string>${xml(logFile)}</string>
137
150
  <key>StandardErrorPath</key>
@@ -178,7 +191,12 @@ function logHintFor(paths) {
178
191
  }
179
192
 
180
193
  /** Writes the definition (0600), loads it and (re)starts the service. */
181
- export function installService({ platform = process.platform, nodePath, entry, args, env = process.env, say }) {
194
+ /**
195
+ * Writes the definition (0600), loads it and (re)starts the service.
196
+ * `start: false`: written and enabled only — the first run starts it once
197
+ * its own process has let go of the instance lock (controlService('start')).
198
+ */
199
+ export function installService({ platform = process.platform, nodePath, entry, args, env = process.env, say, start = true }) {
182
200
  const paths = servicePaths({ platform, env });
183
201
  const environment = serviceEnvironment(env, paths.kind);
184
202
  say('服务将使用以下环境变量(来自当前终端):');
@@ -190,6 +208,10 @@ export function installService({ platform = process.platform, nodePath, entry, a
190
208
  fs.chmodSync(paths.file, 0o600);
191
209
  const domain = `gui/${process.getuid()}`;
192
210
  run('launchctl', ['bootout', `${domain}/${paths.name}`], { quiet: true }); // an older definition, if loaded
211
+ if (!start) {
212
+ say(`已安装后台服务(launchd,${paths.name}),稍后启动`);
213
+ return paths;
214
+ }
193
215
  const loaded = run('launchctl', ['bootstrap', domain, paths.file]);
194
216
  if (!loaded.ok) throw new Error('launchctl bootstrap 失败');
195
217
  say(`已安装并启动后台服务(launchd,${paths.name})。${logHintFor(paths)}`);
@@ -197,12 +219,13 @@ export function installService({ platform = process.platform, nodePath, entry, a
197
219
  }
198
220
  fs.writeFileSync(paths.file, systemdUnit({ nodePath, entry, args, environment }), { mode: 0o600 });
199
221
  fs.chmodSync(paths.file, 0o600);
200
- for (const command of [['daemon-reload'], ['enable', paths.name], ['restart', paths.name]]) {
222
+ const commands = [['daemon-reload'], ['enable', paths.name], ...(start ? [['restart', paths.name]] : [])];
223
+ for (const command of commands) {
201
224
  const result = run('systemctl', ['--user', ...command]);
202
225
  if (!result.ok) throw new Error(`systemctl --user ${command.join(' ')} 失败`);
203
226
  }
204
- say(`已安装并启动后台服务(systemd 用户服务 ${paths.name})。`);
205
- say('退出登录后服务会停止;要让它一直运行,请让管理员执行一次:loginctl enable-linger $USER');
227
+ say(start ? `已安装并启动后台服务(systemd 用户服务 ${paths.name})。` : `已安装后台服务(systemd 用户服务 ${paths.name}),稍后启动`);
228
+ if (lingerEnabled({ platform }) === false) say('退出登录后服务会停止;要让它一直运行,请让管理员执行一次:loginctl enable-linger $USER');
206
229
  say(`查看日志:journalctl --user -u ${paths.name} -f`);
207
230
  return paths;
208
231
  }
@@ -270,6 +293,19 @@ export function uninstallService({ platform = process.platform, env = process.en
270
293
  else if (!legacy) say('没有安装后台服务');
271
294
  }
272
295
 
296
+ /**
297
+ * Whether systemd keeps this user's services running after they log out
298
+ * (`loginctl enable-linger`): true / false, null when it cannot tell (macOS,
299
+ * no loginctl). A user service without it stops at logout.
300
+ */
301
+ export function lingerEnabled({ platform = process.platform, user = os.userInfo().username } = {}) {
302
+ if (platform !== 'linux') return null;
303
+ const result = run('loginctl', ['show-user', user, '-p', 'Linger', '--value'], { quiet: true });
304
+ if (!result.ok) return null;
305
+ const value = result.stdout.trim();
306
+ return value === 'yes' ? true : value === 'no' ? false : null;
307
+ }
308
+
273
309
  /** { installed, state, logHint, name } */
274
310
  export function serviceStatus({ platform = process.platform, env = process.env } = {}) {
275
311
  const paths = servicePaths({ platform, env });