@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/lib/jobs.mjs CHANGED
@@ -19,9 +19,11 @@ import path from 'node:path';
19
19
  import { StringDecoder } from 'node:string_decoder';
20
20
 
21
21
  import { claudeArgs, claudeEnv } from './claude-cli.mjs';
22
- import { removeTree } from './fs-safe.mjs';
22
+ import { withCode } from './errors.mjs';
23
+ import { removeTree, writeJsonAtomic } from './fs-safe.mjs';
23
24
  import { ApiError } from './http.mjs';
24
25
  import { createClaudeInteraction } from './interaction.mjs';
26
+ import { addSecret, removeSecret } from './log.mjs';
25
27
  import {
26
28
  caPaths,
27
29
  createRunLayout,
@@ -46,6 +48,11 @@ const CLOSE_WAIT_MS = 2000;
46
48
  // How long an accepted job waits for a knowledge-pool update to finish before
47
49
  // it starts (its own timeout only starts with claude).
48
50
  export const JOB_WAIT_MS = 15 * 60_000;
51
+ // A job does not start with less than this free where runs/ lives (config: limits.minFreeBytes).
52
+ export const MIN_FREE_BYTES = 1024 ** 3;
53
+ // What a per-run job may leave behind: merged into the shared logs/ and docs/
54
+ // (user machines) or archived (server machines).
55
+ const MERGE_MAX_BYTES = 50 * 1024 * 1024;
49
56
 
50
57
  const BATCH_DELAY_MS = 200;
51
58
  const BATCH_BYTES = 64 * 1024;
@@ -119,6 +126,7 @@ export class OutputUploader {
119
126
  this.pendingBytes = 0;
120
127
  this.pendingSince = 0;
121
128
  this.lastSeq = 0; // last seq acknowledged
129
+ this.totalBytes = 0; // everything pushed, for the job's history
122
130
  this.dead = false;
123
131
  this.pump = null;
124
132
  this.timer = null;
@@ -127,6 +135,7 @@ export class OutputUploader {
127
135
 
128
136
  push(stream, data) {
129
137
  if (this.dead || !data) return;
138
+ this.totalBytes += Buffer.byteLength(data);
130
139
  const last = this.pending.at(-1);
131
140
  if (last && last.stream === stream) last.data += data;
132
141
  else this.pending.push({ stream, data });
@@ -261,6 +270,18 @@ function killGroup(pid, signal) {
261
270
  * `workAgent`: WorkAgent (the Skill source and the knowledge pool);
262
271
  * `onFatal(error)`: the token or machine is no longer accepted (stop
263
272
  * everything).
273
+ *
274
+ * Every job goes through phases (docs/design.md 6.1) — received, accepted,
275
+ * waiting, preparing, running, finishing, cleaning, done — each reported with
276
+ * `onChange()`; a job that is done becomes one record for `onFinished(record)`
277
+ * (the history: phase times, result, exit, error code — never the task, a
278
+ * key or an answer).
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).
282
+ * runMode() { isolation: 'shared' | 'per-run', keep: 'merge' | 'archive' | 'none' }:
283
+ * how the job sees work-agent's home, and what becomes of the logs and
284
+ * deliverables a per-run job leaves (docs/design.md 2.6).
264
285
  */
265
286
  export class JobManager {
266
287
  constructor({
@@ -274,6 +295,13 @@ export class JobManager {
274
295
  log,
275
296
  onFatal = () => {},
276
297
  jobWaitMs = JOB_WAIT_MS,
298
+ minFreeBytes = MIN_FREE_BYTES,
299
+ gate = null,
300
+ runMode = () => ({ isolation: 'shared', keep: 'none' }),
301
+ onChange = () => {},
302
+ onFinished = () => {},
303
+ freeBytes = diskFreeBytes,
304
+ controlDirs = [],
277
305
  }) {
278
306
  this.client = client;
279
307
  this.workAgent = workAgent;
@@ -281,7 +309,15 @@ export class JobManager {
281
309
  this.runsDir = path.join(workRoot, 'runs');
282
310
  // Same filesystem as runs/: a run directory that cannot be deleted is renamed here.
283
311
  this.trashDir = path.join(workRoot, 'trash');
312
+ this.archiveDir = path.join(workRoot, 'archive');
284
313
  this.jobWaitMs = jobWaitMs;
314
+ this.minFreeBytes = minFreeBytes;
315
+ this.gate = gate || ((options) => this.poolGate(options));
316
+ this.runMode = runMode;
317
+ this.onChange = onChange;
318
+ this.onFinished = onFinished;
319
+ this.freeBytes = freeBytes;
320
+ this.controlDirs = controlDirs;
285
321
  this.claudePath = claudePath;
286
322
  this.realHome = realHome;
287
323
  this.env = env;
@@ -297,16 +333,65 @@ export class JobManager {
297
333
  return [...this.jobs.keys()];
298
334
  }
299
335
 
336
+ /** The jobs here now, for status: run id, feature, phase and since when (every phase's time), timeout. */
337
+ snapshot() {
338
+ return [...this.jobs.values()].map((entry) => ({
339
+ runId: entry.runId,
340
+ feature: Object.hasOwn(FEATURE_LABELS, entry.job?.feature) ? entry.job.feature : '',
341
+ interactive: entry.job?.interactive === true,
342
+ phase: entry.phase,
343
+ phaseSince: entry.at[entry.phase] || '',
344
+ receivedAt: entry.at.received,
345
+ at: { ...entry.at },
346
+ timeoutAt: entry.timeoutAt || '',
347
+ isolation: entry.isolation || '',
348
+ workAgentCommit: entry.commit || '',
349
+ }));
350
+ }
351
+
352
+ changed() {
353
+ try {
354
+ this.onChange();
355
+ } catch (error) {
356
+ this.log.warn(`更新状态失败:${error.message}`);
357
+ }
358
+ }
359
+
360
+ setPhase(entry, phase) {
361
+ entry.phase = phase;
362
+ entry.at[phase] = new Date().toISOString();
363
+ this.changed();
364
+ }
365
+
300
366
  /** A `job` event from the control channel. Repeats of a running job are ignored. */
301
367
  handle(job) {
302
368
  if (this.closed) return;
303
369
  const runId = typeof job?.runId === 'string' && job.runId.length <= 100 ? job.runId : '';
304
370
  if (!runId || this.jobs.has(runId)) return;
305
- const entry = { runId, job, child: null, interaction: null, cancelled: false, timedOut: false, failure: '', gone: false, done: null };
371
+ const entry = {
372
+ runId,
373
+ job,
374
+ child: null,
375
+ interaction: null,
376
+ cancelled: false,
377
+ timedOut: false,
378
+ failure: '',
379
+ gone: false,
380
+ done: null,
381
+ phase: 'received',
382
+ at: { received: new Date().toISOString() },
383
+ };
306
384
  this.jobs.set(runId, entry);
385
+ this.changed();
307
386
  entry.done = this.run(entry)
308
- .catch((error) => this.log.error(`任务 ${runId} 异常:${error?.message || error}`))
309
- .finally(() => this.jobs.delete(runId));
387
+ .catch((error) => {
388
+ this.log.error(`任务 ${runId} 异常:${error?.message || error}`);
389
+ this.record(entry, { result: 'failed', message: String(error?.message || error) });
390
+ })
391
+ .finally(() => {
392
+ this.jobs.delete(runId);
393
+ this.changed();
394
+ });
310
395
  }
311
396
 
312
397
  /**
@@ -324,13 +409,24 @@ export class JobManager {
324
409
  return result;
325
410
  }
326
411
 
327
- /** Stops a job (website cancel, heartbeat reconciliation). */
328
- cancel(runId) {
412
+ /**
413
+ * Stops a job (website cancel, heartbeat reconciliation, `work-agent-runner
414
+ * jobs cancel`). `by`: who, when it was not the website — the website is
415
+ * then told why the job ended.
416
+ */
417
+ cancel(runId, { by = '' } = {}) {
329
418
  const entry = this.jobs.get(runId);
330
- if (!entry || entry.cancelled) return;
419
+ if (!entry || entry.cancelled) return false;
331
420
  entry.cancelled = true;
332
- this.log.info(`任务 ${runId} 被取消`);
421
+ entry.cancelledBy = by;
422
+ this.log.info(`任务 ${runId} 被取消${by ? `(${by})` : ''}`);
333
423
  this.terminate(entry);
424
+ return true;
425
+ }
426
+
427
+ /** What the website is told about a job stopped on this machine ('' when the website stopped it). */
428
+ cancelReason(entry) {
429
+ return entry.cancelled && entry.cancelledBy && !entry.gone ? `任务在执行机器上被取消(${entry.cancelledBy})` : '';
334
430
  }
335
431
 
336
432
  terminate(entry) {
@@ -341,11 +437,21 @@ export class JobManager {
341
437
  setTimeout(() => killGroup(pid, 'SIGKILL'), KILL_GRACE_MS).unref();
342
438
  }
343
439
 
440
+ /** A second Ctrl+C: every job's process group gets SIGKILL at once (no grace, nothing reported). */
441
+ killAll() {
442
+ this.closed = true;
443
+ for (const entry of this.jobs.values()) {
444
+ entry.cancelled = true;
445
+ killGroup(entry.child?.pid, 'SIGKILL');
446
+ }
447
+ }
448
+
344
449
  /** Stops every job and waits (≤ timeoutMs) for their exits to be reported. */
345
450
  async stopAll(timeoutMs = 5000) {
346
451
  this.closed = true;
347
452
  const entries = [...this.jobs.values()];
348
453
  for (const entry of entries) {
454
+ if (!entry.cancelled) entry.cancelledBy = '执行机器上的程序正在停止';
349
455
  entry.cancelled = true;
350
456
  this.terminate(entry);
351
457
  }
@@ -394,6 +500,50 @@ export class JobManager {
394
500
  }
395
501
  }
396
502
 
503
+ /** Not run: tells the website why (with the code) and records it. */
504
+ async fail(entry, code, message) {
505
+ await this.reportExit(entry, { error: withCode(code, message) });
506
+ this.record(entry, { result: 'failed', code, message });
507
+ }
508
+
509
+ /** The job's one history record (once): what happened, never what it was asked or given. */
510
+ record(entry, { result, code = '', message = '', exit = null }) {
511
+ if (entry.recorded) return;
512
+ entry.recorded = true;
513
+ this.setPhase(entry, 'done');
514
+ const { at } = entry;
515
+ const waitedMs = at.waiting && at.preparing ? Math.max(0, Date.parse(at.preparing) - Date.parse(at.waiting)) : 0;
516
+ try {
517
+ this.onFinished({
518
+ runId: entry.runId,
519
+ feature: Object.hasOwn(FEATURE_LABELS, entry.job?.feature) ? entry.job.feature : '',
520
+ interactive: entry.job?.interactive === true,
521
+ isolation: entry.isolation || '',
522
+ at: { ...at },
523
+ waitedMs,
524
+ result,
525
+ exit,
526
+ error: { code, message: String(message || '').slice(0, 300) },
527
+ workAgentCommit: entry.commit || '',
528
+ outputBytes: entry.uploader?.totalBytes || 0,
529
+ });
530
+ } catch (error) {
531
+ this.log.warn(`无法记录任务 ${entry.runId}:${error.message}`);
532
+ }
533
+ }
534
+
535
+ /** The default gate: no knowledge-pool update in progress (bounded wait). */
536
+ async poolGate({ isCancelled, timeoutMs, onWait }) {
537
+ if (typeof this.workAgent?.waitForPoolIdle !== 'function') return { ok: true };
538
+ const idle = await this.workAgent.waitForPoolIdle({ timeoutMs, isCancelled, onWait: () => onWait('等待知识仓更新完成后开始') });
539
+ if (idle || isCancelled()) return { ok: true };
540
+ return {
541
+ ok: false,
542
+ code: 'E3201',
543
+ message: `执行机器正在更新知识仓,等待超过 ${Math.round(timeoutMs / 60_000)} 分钟,任务未执行,请稍后重试`,
544
+ };
545
+ }
546
+
397
547
  async run(entry) {
398
548
  const { runId, job } = entry;
399
549
  const started = Date.now();
@@ -401,94 +551,163 @@ export class JobManager {
401
551
  // Acknowledge first so the website does not wait for the accept timeout.
402
552
  if (!(await this.accept(entry))) {
403
553
  this.log.warn(`任务 ${runId} 已在网站上失效,未执行`);
554
+ this.record(entry, { result: 'not_accepted', message: '网站上已失效,未执行' });
404
555
  return;
405
556
  }
557
+ this.setPhase(entry, 'accepted');
406
558
  if (invalid) {
407
559
  this.log.warn(`任务 ${runId} 参数不合法(${invalid}),未执行`);
408
- await this.reportExit(entry, { error: `任务参数不合法:${invalid}` });
560
+ await this.fail(entry, 'E3101', `任务参数不合法:${invalid}`);
409
561
  return;
410
562
  }
411
563
  const label = FEATURE_LABELS[job.feature];
412
564
  this.log.info(`开始任务 ${runId}(${label})`);
413
-
414
- // A `git pull` in the knowledge pool must not replace files under a running
415
- // job: wait for it (bounded) before anything starts.
416
- if (typeof this.workAgent?.waitForPoolIdle === 'function') {
417
- const idle = await this.workAgent.waitForPoolIdle({
418
- timeoutMs: this.jobWaitMs,
565
+ // Never in a log line, whatever prints them.
566
+ const secrets = [job.apiKey, job.env.GITCODE_CRED];
567
+ for (const secret of secrets) addSecret(secret);
568
+ let runDir = '';
569
+ try {
570
+ this.setPhase(entry, 'waiting');
571
+ const gate = await this.gate({
419
572
  isCancelled: () => entry.cancelled,
420
- onWait: () => this.log.info(`任务 ${runId} 等待知识仓更新完成后开始`),
573
+ timeoutMs: this.jobWaitMs,
574
+ onWait: (why) => this.log.info(`任务 ${runId} ${why}`),
421
575
  });
422
- if (!idle && !entry.cancelled) {
423
- this.log.warn(`任务 ${runId} 等待知识仓更新超时,未执行`);
424
- await this.reportExit(entry, { error: `执行机器正在更新知识仓,等待超过 ${Math.round(this.jobWaitMs / 60_000)} 分钟,任务未执行,请稍后重试` });
576
+ if (entry.cancelled) {
577
+ await this.reportExit(entry, { signal: 'SIGTERM', error: this.cancelReason(entry) });
578
+ this.record(entry, { result: 'cancelled' });
579
+ return;
580
+ }
581
+ if (!gate.ok) {
582
+ this.log.warn(`任务 ${runId} 未执行:${gate.message}`);
583
+ await this.fail(entry, gate.code, gate.message);
425
584
  return;
426
585
  }
427
- }
428
-
429
- if (entry.cancelled) {
430
- await this.reportExit(entry, { signal: 'SIGTERM' });
431
- return;
432
- }
433
586
 
434
- // A short directory name, not the run id: see socketPathProblem().
435
- let runDir = '';
436
- let layout;
437
- try {
438
- runDir = newRunDir(this.runsDir, 'r');
439
- layout = createRunLayout(runDir, { workAgentHome: this.paths?.workAgentHome || '' });
440
- const tooLong = socketPathProblem(layout.tmpDir, this.platform);
441
- if (tooLong) throw new Error(tooLong);
442
- } catch (error) {
443
- if (runDir) this.removeRunDir(runDir);
444
- await this.reportExit(entry, { error: `准备运行目录失败:${error?.message || error}` });
445
- return;
446
- }
587
+ this.setPhase(entry, 'preparing');
588
+ // A code review clones the repository it reviews: no room, no start.
589
+ const free = this.freeBytes(this.runsDir);
590
+ if (free && free < this.minFreeBytes) {
591
+ const message = `执行机器的工作目录磁盘只剩 ${gigabytes(free)} GB(至少要 ${gigabytes(this.minFreeBytes)} GB),任务未执行`;
592
+ this.log.warn(`任务 ${runId} ${message}`);
593
+ await this.fail(entry, 'E3301', message);
594
+ return;
595
+ }
596
+ const mode = this.runMode();
597
+ // A short directory name, not the run id: see socketPathProblem().
598
+ let layout;
599
+ try {
600
+ runDir = newRunDir(this.runsDir, 'r');
601
+ layout = createRunLayout(runDir, {
602
+ workAgentHome: this.paths?.workAgentHome || '',
603
+ isolation: mode.isolation,
604
+ pool: this.workAgent.mountablePool(),
605
+ });
606
+ entry.isolation = layout.isolation;
607
+ const tooLong = socketPathProblem(layout.tmpDir, this.platform);
608
+ if (tooLong) throw new Error(tooLong);
609
+ } catch (error) {
610
+ await this.fail(entry, 'E3401', `准备运行目录失败:${error?.message || error}`);
611
+ return;
612
+ }
447
613
 
448
- // A copy of this machine's work-agent clone as the working directory (the
449
- // Skills' logs pointed at $WORK_AGENT_HOME/logs, their scratch at the run's
450
- // own), and the knowledge pool read-only if there is one: the settings name
451
- // every path the job may reach (sandbox.mjs).
452
- try {
453
- const { commit } = await this.workAgent.copyRepoInto(layout.workDir, {
454
- logs: path.join(this.paths.workAgentHome, 'logs'),
455
- scratch: layout.scratchDir,
456
- });
457
- const pool = this.workAgent.mountablePool();
458
- writeSandboxSettings(layout.settingsFile, {
459
- workDir: fs.realpathSync(layout.workDir),
460
- realHome: this.realHome,
461
- ...runAllowances(layout, {
614
+ // A copy of this machine's work-agent clone as the working directory (the
615
+ // Skills' logs pointed at the job's $WORK_AGENT_HOME/logs, their scratch at
616
+ // the run's own), and the knowledge pool read-only if there is one: the
617
+ // settings name every path the job may reach (sandbox.mjs).
618
+ 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
+ });
623
+ entry.commit = commit;
624
+ const pool = this.workAgent.mountablePool();
625
+ writeSandboxSettings(layout.settingsFile, {
626
+ workDir: fs.realpathSync(layout.workDir),
462
627
  realHome: this.realHome,
463
- pathEnv: this.env.PATH || '',
464
- caPaths: caPaths(this.env),
465
- pool,
466
- paths: this.paths,
467
- }),
468
- });
469
- this.log.info(`任务 ${runId} 使用 work-agent ${commit.slice(0, 7)}${pool ? ',已挂载知识仓' : ''}`);
470
- } catch (error) {
471
- this.removeRunDir(runDir);
472
- await this.reportExit(entry, { error: `准备 Skill 失败:${error?.message || error}` });
473
- return;
474
- }
628
+ ...runAllowances(layout, {
629
+ realHome: this.realHome,
630
+ pathEnv: this.env.PATH || '',
631
+ caPaths: caPaths(this.env),
632
+ pool,
633
+ paths: this.paths,
634
+ // A server execution machine: what other users' jobs left is not this one's.
635
+ denySharedWork: layout.isolation === 'per-run' && mode.keep !== 'merge',
636
+ controlDirs: this.controlDirs,
637
+ // Other jobs' archived outputs, what could not be deleted, and the
638
+ // program's status, history and log.
639
+ privateDirs: [this.archiveDir, this.trashDir, ...(this.paths?.stateDir ? [this.paths.stateDir, this.paths.logsDir] : [])],
640
+ }),
641
+ });
642
+ this.log.info(
643
+ `任务 ${runId} 使用 work-agent ${commit.slice(0, 7)}${pool ? ',已挂载知识仓' : ''}${layout.isolation === 'per-run' ? ',WORK_AGENT_HOME 独立' : ''}`,
644
+ );
645
+ } catch (error) {
646
+ await this.fail(entry, 'E3401', `准备 Skill 失败:${error?.message || error}`);
647
+ return;
648
+ }
475
649
 
476
- try {
477
650
  const result = await this.spawnClaude(entry, layout);
651
+ const failure = result.error || entry.failure;
652
+ const failureCode = result.error ? 'E1301' : entry.failure ? 'E3501' : '';
478
653
  if (!entry.gone) {
479
654
  await this.reportExit(entry, {
480
655
  seq: entry.uploader.lastSeq,
481
656
  code: result.code,
482
657
  signal: result.signal,
483
658
  timedOut: entry.timedOut,
484
- error: result.error || entry.failure,
659
+ error: failure ? withCode(failureCode, failure) : this.cancelReason(entry),
485
660
  });
486
661
  }
487
662
  const seconds = Math.round((Date.now() - started) / 1000);
488
663
  const outcome = entry.timedOut ? '超时' : entry.cancelled ? '已取消' : result.error ? result.error : `退出码 ${result.code ?? result.signal}`;
489
664
  this.log.info(`任务 ${runId} 结束(${label}):${outcome},用时 ${seconds} 秒`);
665
+
666
+ let kind = 'failed';
667
+ if (entry.timedOut) kind = 'timeout';
668
+ else if (entry.cancelled || entry.gone) kind = 'cancelled';
669
+ else if (!failure && result.code === 0) kind = 'ok';
670
+ this.setPhase(entry, 'cleaning');
671
+ this.keepOutputs(entry, layout, mode, kind);
672
+ this.record(entry, {
673
+ result: kind,
674
+ code: kind === 'failed' ? failureCode : '',
675
+ message: failure || (kind === 'failed' ? `claude 退出码 ${result.code ?? result.signal}` : ''),
676
+ exit: { code: result.code, signal: result.signal, timedOut: entry.timedOut },
677
+ });
490
678
  } finally {
491
- this.removeRunDir(runDir);
679
+ for (const secret of secrets) removeSecret(secret);
680
+ if (runDir) this.removeRunDir(runDir);
681
+ }
682
+ }
683
+
684
+ /**
685
+ * What a per-run job left in its own WORK_AGENT_HOME (logs/ and docs/, at
686
+ * most 50 MiB): merged into the shared ones (a user's machine; a name that
687
+ * is taken gets the run id's last 8 characters), archived under
688
+ * archive/<runId>/ with meta.json (a server execution machine that keeps
689
+ * them), or dropped with the run.
690
+ */
691
+ keepOutputs(entry, layout, mode, result = '') {
692
+ if (layout?.isolation !== 'per-run' || !['merge', 'archive'].includes(mode.keep)) return;
693
+ const wah = layout.workAgentHome;
694
+ const archive = mode.keep === 'archive';
695
+ const into = archive ? path.join(this.archiveDir, entry.runId) : layout.sharedWorkAgentHome;
696
+ const budget = { left: MERGE_MAX_BYTES, skipped: 0 };
697
+ try {
698
+ for (const name of ['logs', 'docs']) mergeTree(path.join(wah, name), path.join(into, name), entry.runId.slice(-8), budget);
699
+ if (archive) {
700
+ fs.mkdirSync(into, { recursive: true, mode: 0o700 });
701
+ writeJsonAtomic(path.join(into, 'meta.json'), {
702
+ runId: entry.runId,
703
+ feature: entry.job?.feature || '',
704
+ result,
705
+ finishedAt: new Date().toISOString(),
706
+ });
707
+ }
708
+ if (budget.skipped) this.log.warn(`任务 ${entry.runId} 留下的文件超过 ${MERGE_MAX_BYTES / 1048576} MB,${budget.skipped} 个没有放进 ${into}`);
709
+ } catch (error) {
710
+ this.log.warn(`任务 ${entry.runId} 的日志和交付件没能保留:${error.message}`);
492
711
  }
493
712
  }
494
713
 
@@ -509,7 +728,7 @@ export class JobManager {
509
728
  const { job } = entry;
510
729
  return new Promise((resolve) => {
511
730
  if (!this.claudePath) {
512
- entry.uploader = { lastSeq: 0 };
731
+ entry.uploader = { lastSeq: 0, totalBytes: 0 };
513
732
  resolve({ code: null, signal: null, error: '无法启动 claude:未安装' });
514
733
  return;
515
734
  }
@@ -531,19 +750,24 @@ export class JobManager {
531
750
  model: job.model,
532
751
  extra: {
533
752
  ...passThroughEnv(this.env, this.platform),
534
- // The program's persistent workspace: the job's HOME links to it,
535
- // so `~/.work-agent/...` in a Skill is the same directory.
536
- WORK_AGENT_HOME: this.paths.workAgentHome,
753
+ // The job's work-agent home (the shared one, or its own per-run
754
+ // one); the job's HOME links to it, so `~/.work-agent/...` in a
755
+ // Skill is the same directory.
756
+ WORK_AGENT_HOME: layout.workAgentHome || this.paths.workAgentHome,
537
757
  GITCODE_CRED: job.env.GITCODE_CRED,
538
758
  },
539
759
  }),
540
760
  });
541
761
  } catch (error) {
542
- entry.uploader = { lastSeq: 0 };
762
+ entry.uploader = { lastSeq: 0, totalBytes: 0 };
543
763
  resolve({ code: null, signal: null, error: `无法启动 claude:${error.code || error.message}` });
544
764
  return;
545
765
  }
546
766
  entry.child = child;
767
+ if (child.pid) {
768
+ entry.timeoutAt = new Date(Date.now() + job.timeoutMs).toISOString();
769
+ this.setPhase(entry, 'running');
770
+ }
547
771
  const uploader = new OutputUploader({
548
772
  client: this.client,
549
773
  runId: entry.runId,
@@ -606,12 +830,14 @@ export class JobManager {
606
830
  clearTimeout(timeout);
607
831
  clearTimeout(closeWait);
608
832
  killGroup(child.pid, 'SIGKILL'); // whatever the job left behind
833
+ if (entry.phase === 'running') this.setPhase(entry, 'finishing');
609
834
  // Open questions are reported closed before the exit.
610
835
  entry.interaction?.dispose();
611
836
  await uploader.drain();
612
837
  resolve(result);
613
838
  };
614
839
  child.once('exit', () => {
840
+ if (entry.phase === 'running') this.setPhase(entry, 'finishing');
615
841
  // Background descendants may keep the pipes open: end them shortly after.
616
842
  closeWait = setTimeout(() => killGroup(child.pid, 'SIGKILL'), CLOSE_WAIT_MS);
617
843
  closeWait.unref();
@@ -630,6 +856,76 @@ export class JobManager {
630
856
  }
631
857
  }
632
858
 
859
+ const GIB = 1024 ** 3;
860
+
861
+ function gigabytes(bytes) {
862
+ return (bytes / GIB).toFixed(1);
863
+ }
864
+
865
+ /** Free bytes where `dir` lives (0 = unknown, never a reason to refuse). */
866
+ function diskFreeBytes(dir) {
867
+ try {
868
+ const stat = fs.statfsSync(dir);
869
+ return Number(stat.bavail) * Number(stat.bsize);
870
+ } catch {
871
+ return 0;
872
+ }
873
+ }
874
+
875
+ /** A name in `dir` that is not taken: `name`, else `stem-suffix.ext`, `stem-suffix-2.ext`… */
876
+ function freeName(dir, name, suffix) {
877
+ if (!fs.existsSync(path.join(dir, name))) return path.join(dir, name);
878
+ const ext = path.extname(name);
879
+ const stem = path.basename(name, ext);
880
+ for (let index = 1; ; index += 1) {
881
+ const candidate = path.join(dir, `${stem}-${suffix}${index > 1 ? `-${index}` : ''}${ext}`);
882
+ if (!fs.existsSync(candidate)) return candidate;
883
+ }
884
+ }
885
+
886
+ /**
887
+ * Moves the regular files under `source` into `target` (same layout), never
888
+ * over an existing file and never more than `budget.left` bytes; symlinks and
889
+ * special files stay behind. Across filesystems: copy, then delete.
890
+ */
891
+ function mergeTree(source, target, suffix, budget) {
892
+ let names;
893
+ try {
894
+ names = fs.readdirSync(source);
895
+ } catch {
896
+ return;
897
+ }
898
+ if (!names.length) return;
899
+ fs.mkdirSync(target, { recursive: true, mode: 0o700 });
900
+ for (const name of names) {
901
+ const from = path.join(source, name);
902
+ let stat;
903
+ try {
904
+ stat = fs.lstatSync(from);
905
+ } catch {
906
+ continue;
907
+ }
908
+ if (stat.isDirectory()) {
909
+ mergeTree(from, path.join(target, name), suffix, budget);
910
+ continue;
911
+ }
912
+ if (!stat.isFile()) continue;
913
+ if (stat.size > budget.left) {
914
+ budget.skipped += 1;
915
+ continue;
916
+ }
917
+ const to = freeName(target, name, suffix);
918
+ try {
919
+ fs.renameSync(from, to);
920
+ } catch (error) {
921
+ if (error.code !== 'EXDEV') throw error;
922
+ fs.copyFileSync(from, to, fs.constants.COPYFILE_EXCL);
923
+ fs.rmSync(from, { force: true });
924
+ }
925
+ budget.left -= stat.size;
926
+ }
927
+ }
928
+
633
929
  /**
634
930
  * Splits decoded text into lines for `onLine` (without the newline); end()
635
931
  * flushes the last line even when it has no newline.