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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/jobs.mjs CHANGED
@@ -19,8 +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 { withCode } from './errors.mjs';
23
+ import { removeTree, writeJsonAtomic } from './fs-safe.mjs';
22
24
  import { ApiError } from './http.mjs';
23
25
  import { createClaudeInteraction } from './interaction.mjs';
26
+ import { addSecret, removeSecret } from './log.mjs';
24
27
  import {
25
28
  caPaths,
26
29
  createRunLayout,
@@ -42,6 +45,14 @@ const RUN_ID = /^(skill|review)_\d+_[0-9a-f]{8}$/;
42
45
  const TASK_MAX_BYTES = 64 * 1024;
43
46
  const KILL_GRACE_MS = 5000;
44
47
  const CLOSE_WAIT_MS = 2000;
48
+ // How long an accepted job waits for a knowledge-pool update to finish before
49
+ // it starts (its own timeout only starts with claude).
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;
45
56
 
46
57
  const BATCH_DELAY_MS = 200;
47
58
  const BATCH_BYTES = 64 * 1024;
@@ -115,6 +126,7 @@ export class OutputUploader {
115
126
  this.pendingBytes = 0;
116
127
  this.pendingSince = 0;
117
128
  this.lastSeq = 0; // last seq acknowledged
129
+ this.totalBytes = 0; // everything pushed, for the job's history
118
130
  this.dead = false;
119
131
  this.pump = null;
120
132
  this.timer = null;
@@ -123,6 +135,7 @@ export class OutputUploader {
123
135
 
124
136
  push(stream, data) {
125
137
  if (this.dead || !data) return;
138
+ this.totalBytes += Buffer.byteLength(data);
126
139
  const last = this.pending.at(-1);
127
140
  if (last && last.stream === stream) last.data += data;
128
141
  else this.pending.push({ stream, data });
@@ -257,13 +270,54 @@ function killGroup(pid, signal) {
257
270
  * `workAgent`: WorkAgent (the Skill source and the knowledge pool);
258
271
  * `onFatal(error)`: the token or machine is no longer accepted (stop
259
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).
260
285
  */
261
286
  export class JobManager {
262
- constructor({ client, workAgent, workRoot, claudePath, realHome, env = process.env, platform = process.platform, log, onFatal = () => {} }) {
287
+ constructor({
288
+ client,
289
+ workAgent,
290
+ workRoot,
291
+ claudePath,
292
+ realHome,
293
+ env = process.env,
294
+ platform = process.platform,
295
+ log,
296
+ onFatal = () => {},
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 = [],
305
+ }) {
263
306
  this.client = client;
264
307
  this.workAgent = workAgent;
265
308
  this.paths = workAgent?.paths || null;
266
309
  this.runsDir = path.join(workRoot, 'runs');
310
+ // Same filesystem as runs/: a run directory that cannot be deleted is renamed here.
311
+ this.trashDir = path.join(workRoot, 'trash');
312
+ this.archiveDir = path.join(workRoot, 'archive');
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;
267
321
  this.claudePath = claudePath;
268
322
  this.realHome = realHome;
269
323
  this.env = env;
@@ -279,16 +333,65 @@ export class JobManager {
279
333
  return [...this.jobs.keys()];
280
334
  }
281
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
+
282
366
  /** A `job` event from the control channel. Repeats of a running job are ignored. */
283
367
  handle(job) {
284
368
  if (this.closed) return;
285
369
  const runId = typeof job?.runId === 'string' && job.runId.length <= 100 ? job.runId : '';
286
370
  if (!runId || this.jobs.has(runId)) return;
287
- 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
+ };
288
384
  this.jobs.set(runId, entry);
385
+ this.changed();
289
386
  entry.done = this.run(entry)
290
- .catch((error) => this.log.error(`任务 ${runId} 异常:${error?.message || error}`))
291
- .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
+ });
292
395
  }
293
396
 
294
397
  /**
@@ -306,13 +409,24 @@ export class JobManager {
306
409
  return result;
307
410
  }
308
411
 
309
- /** Stops a job (website cancel, heartbeat reconciliation). */
310
- 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 = '' } = {}) {
311
418
  const entry = this.jobs.get(runId);
312
- if (!entry || entry.cancelled) return;
419
+ if (!entry || entry.cancelled) return false;
313
420
  entry.cancelled = true;
314
- this.log.info(`任务 ${runId} 被取消`);
421
+ entry.cancelledBy = by;
422
+ this.log.info(`任务 ${runId} 被取消${by ? `(${by})` : ''}`);
315
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})` : '';
316
430
  }
317
431
 
318
432
  terminate(entry) {
@@ -323,11 +437,21 @@ export class JobManager {
323
437
  setTimeout(() => killGroup(pid, 'SIGKILL'), KILL_GRACE_MS).unref();
324
438
  }
325
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
+
326
449
  /** Stops every job and waits (≤ timeoutMs) for their exits to be reported. */
327
450
  async stopAll(timeoutMs = 5000) {
328
451
  this.closed = true;
329
452
  const entries = [...this.jobs.values()];
330
453
  for (const entry of entries) {
454
+ if (!entry.cancelled) entry.cancelledBy = '执行机器上的程序正在停止';
331
455
  entry.cancelled = true;
332
456
  this.terminate(entry);
333
457
  }
@@ -376,6 +500,50 @@ export class JobManager {
376
500
  }
377
501
  }
378
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
+
379
547
  async run(entry) {
380
548
  const { runId, job } = entry;
381
549
  const started = Date.now();
@@ -383,87 +551,184 @@ export class JobManager {
383
551
  // Acknowledge first so the website does not wait for the accept timeout.
384
552
  if (!(await this.accept(entry))) {
385
553
  this.log.warn(`任务 ${runId} 已在网站上失效,未执行`);
554
+ this.record(entry, { result: 'not_accepted', message: '网站上已失效,未执行' });
386
555
  return;
387
556
  }
557
+ this.setPhase(entry, 'accepted');
388
558
  if (invalid) {
389
559
  this.log.warn(`任务 ${runId} 参数不合法(${invalid}),未执行`);
390
- await this.reportExit(entry, { error: `任务参数不合法:${invalid}` });
560
+ await this.fail(entry, 'E3101', `任务参数不合法:${invalid}`);
391
561
  return;
392
562
  }
393
563
  const label = FEATURE_LABELS[job.feature];
394
564
  this.log.info(`开始任务 ${runId}(${label})`);
395
-
396
- if (entry.cancelled) {
397
- await this.reportExit(entry, { signal: 'SIGTERM' });
398
- return;
399
- }
400
-
401
- // A short directory name, not the run id: see socketPathProblem().
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);
402
568
  let runDir = '';
403
- let layout;
404
569
  try {
405
- runDir = newRunDir(this.runsDir, 'r');
406
- layout = createRunLayout(runDir, { workAgentHome: this.paths?.workAgentHome || '' });
407
- const tooLong = socketPathProblem(layout.tmpDir, this.platform);
408
- if (tooLong) throw new Error(tooLong);
409
- } catch (error) {
410
- if (runDir) fs.rmSync(runDir, { recursive: true, force: true });
411
- await this.reportExit(entry, { error: `准备运行目录失败:${error?.message || error}` });
412
- return;
413
- }
414
-
415
- // A copy of this machine's work-agent clone as the working directory (the
416
- // Skills' logs pointed at $WORK_AGENT_HOME/logs, their scratch at the run's
417
- // own), and the knowledge pool read-only if there is one: the settings name
418
- // every path the job may reach (sandbox.mjs).
419
- try {
420
- const { commit } = await this.workAgent.copyRepoInto(layout.workDir, {
421
- logs: path.join(this.paths.workAgentHome, 'logs'),
422
- scratch: layout.scratchDir,
570
+ this.setPhase(entry, 'waiting');
571
+ const gate = await this.gate({
572
+ isCancelled: () => entry.cancelled,
573
+ timeoutMs: this.jobWaitMs,
574
+ onWait: (why) => this.log.info(`任务 ${runId} ${why}`),
423
575
  });
424
- const pool = this.workAgent.mountablePool();
425
- writeSandboxSettings(layout.settingsFile, {
426
- workDir: fs.realpathSync(layout.workDir),
427
- realHome: this.realHome,
428
- ...runAllowances(layout, {
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);
584
+ return;
585
+ }
586
+
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
+ }
613
+
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),
429
627
  realHome: this.realHome,
430
- pathEnv: this.env.PATH || '',
431
- caPaths: caPaths(this.env),
432
- pool,
433
- paths: this.paths,
434
- }),
435
- });
436
- this.log.info(`任务 ${runId} 使用 work-agent ${commit.slice(0, 7)}${pool ? ',已挂载知识仓' : ''}`);
437
- } catch (error) {
438
- fs.rmSync(runDir, { recursive: true, force: true });
439
- await this.reportExit(entry, { error: `准备 Skill 失败:${error?.message || error}` });
440
- return;
441
- }
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
+ }
442
649
 
443
- try {
444
650
  const result = await this.spawnClaude(entry, layout);
651
+ const failure = result.error || entry.failure;
652
+ const failureCode = result.error ? 'E1301' : entry.failure ? 'E3501' : '';
445
653
  if (!entry.gone) {
446
654
  await this.reportExit(entry, {
447
655
  seq: entry.uploader.lastSeq,
448
656
  code: result.code,
449
657
  signal: result.signal,
450
658
  timedOut: entry.timedOut,
451
- error: result.error || entry.failure,
659
+ error: failure ? withCode(failureCode, failure) : this.cancelReason(entry),
452
660
  });
453
661
  }
454
662
  const seconds = Math.round((Date.now() - started) / 1000);
455
663
  const outcome = entry.timedOut ? '超时' : entry.cancelled ? '已取消' : result.error ? result.error : `退出码 ${result.code ?? result.signal}`;
456
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
+ });
457
678
  } finally {
458
- fs.rmSync(runDir, { recursive: true, force: true });
679
+ for (const secret of secrets) removeSecret(secret);
680
+ if (runDir) this.removeRunDir(runDir);
459
681
  }
460
682
  }
461
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}`);
711
+ }
712
+ }
713
+
714
+ /**
715
+ * Deletes a run directory; never throws. What a job made undeletable (a
716
+ * read-only directory) goes to trash/, retried at the next start and every
717
+ * hour — it must never stop the program.
718
+ */
719
+ removeRunDir(runDir) {
720
+ const outcome = removeTree(runDir, { trashDir: this.trashDir });
721
+ if (outcome.removed) return;
722
+ const why = outcome.error?.code || outcome.error?.message || String(outcome.error);
723
+ if (outcome.trashed) this.log.warn(`运行目录 ${runDir} 删不掉(${why}),已移到 ${outcome.trashed},稍后再试`);
724
+ else this.log.warn(`运行目录 ${runDir} 删不掉(${why}),下次启动时再试`);
725
+ }
726
+
462
727
  spawnClaude(entry, layout) {
463
728
  const { job } = entry;
464
729
  return new Promise((resolve) => {
465
730
  if (!this.claudePath) {
466
- entry.uploader = { lastSeq: 0 };
731
+ entry.uploader = { lastSeq: 0, totalBytes: 0 };
467
732
  resolve({ code: null, signal: null, error: '无法启动 claude:未安装' });
468
733
  return;
469
734
  }
@@ -485,19 +750,24 @@ export class JobManager {
485
750
  model: job.model,
486
751
  extra: {
487
752
  ...passThroughEnv(this.env, this.platform),
488
- // The program's persistent workspace: the job's HOME links to it,
489
- // so `~/.work-agent/...` in a Skill is the same directory.
490
- 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,
491
757
  GITCODE_CRED: job.env.GITCODE_CRED,
492
758
  },
493
759
  }),
494
760
  });
495
761
  } catch (error) {
496
- entry.uploader = { lastSeq: 0 };
762
+ entry.uploader = { lastSeq: 0, totalBytes: 0 };
497
763
  resolve({ code: null, signal: null, error: `无法启动 claude:${error.code || error.message}` });
498
764
  return;
499
765
  }
500
766
  entry.child = child;
767
+ if (child.pid) {
768
+ entry.timeoutAt = new Date(Date.now() + job.timeoutMs).toISOString();
769
+ this.setPhase(entry, 'running');
770
+ }
501
771
  const uploader = new OutputUploader({
502
772
  client: this.client,
503
773
  runId: entry.runId,
@@ -560,12 +830,14 @@ export class JobManager {
560
830
  clearTimeout(timeout);
561
831
  clearTimeout(closeWait);
562
832
  killGroup(child.pid, 'SIGKILL'); // whatever the job left behind
833
+ if (entry.phase === 'running') this.setPhase(entry, 'finishing');
563
834
  // Open questions are reported closed before the exit.
564
835
  entry.interaction?.dispose();
565
836
  await uploader.drain();
566
837
  resolve(result);
567
838
  };
568
839
  child.once('exit', () => {
840
+ if (entry.phase === 'running') this.setPhase(entry, 'finishing');
569
841
  // Background descendants may keep the pipes open: end them shortly after.
570
842
  closeWait = setTimeout(() => killGroup(child.pid, 'SIGKILL'), CLOSE_WAIT_MS);
571
843
  closeWait.unref();
@@ -584,6 +856,76 @@ export class JobManager {
584
856
  }
585
857
  }
586
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
+
587
929
  /**
588
930
  * Splits decoded text into lines for `onLine` (without the newline); end()
589
931
  * flushes the last line even when it has no newline.