@online-tools/work-agent-runner 0.0.5-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.
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,24 @@ 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 }; 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).
288
+ * runMode() { isolation: 'shared' | 'per-run', keep: 'merge' | 'archive' | 'none' }:
289
+ * how the job sees work-agent's home, and what becomes of the logs and
290
+ * deliverables a per-run job leaves (docs/design.md 2.6).
264
291
  */
265
292
  export class JobManager {
266
293
  constructor({
@@ -274,6 +301,13 @@ export class JobManager {
274
301
  log,
275
302
  onFatal = () => {},
276
303
  jobWaitMs = JOB_WAIT_MS,
304
+ minFreeBytes = MIN_FREE_BYTES,
305
+ gate = null,
306
+ runMode = () => ({ isolation: 'shared', keep: 'none' }),
307
+ onChange = () => {},
308
+ onFinished = () => {},
309
+ freeBytes = diskFreeBytes,
310
+ controlDirs = [],
277
311
  }) {
278
312
  this.client = client;
279
313
  this.workAgent = workAgent;
@@ -281,7 +315,15 @@ export class JobManager {
281
315
  this.runsDir = path.join(workRoot, 'runs');
282
316
  // Same filesystem as runs/: a run directory that cannot be deleted is renamed here.
283
317
  this.trashDir = path.join(workRoot, 'trash');
318
+ this.archiveDir = path.join(workRoot, 'archive');
284
319
  this.jobWaitMs = jobWaitMs;
320
+ this.minFreeBytes = minFreeBytes;
321
+ this.gate = gate || ((options) => this.poolGate(options));
322
+ this.runMode = runMode;
323
+ this.onChange = onChange;
324
+ this.onFinished = onFinished;
325
+ this.freeBytes = freeBytes;
326
+ this.controlDirs = controlDirs;
285
327
  this.claudePath = claudePath;
286
328
  this.realHome = realHome;
287
329
  this.env = env;
@@ -297,16 +339,65 @@ export class JobManager {
297
339
  return [...this.jobs.keys()];
298
340
  }
299
341
 
342
+ /** The jobs here now, for status: run id, feature, phase and since when (every phase's time), timeout. */
343
+ snapshot() {
344
+ return [...this.jobs.values()].map((entry) => ({
345
+ runId: entry.runId,
346
+ feature: Object.hasOwn(FEATURE_LABELS, entry.job?.feature) ? entry.job.feature : '',
347
+ interactive: entry.job?.interactive === true,
348
+ phase: entry.phase,
349
+ phaseSince: entry.at[entry.phase] || '',
350
+ receivedAt: entry.at.received,
351
+ at: { ...entry.at },
352
+ timeoutAt: entry.timeoutAt || '',
353
+ isolation: entry.isolation || '',
354
+ workAgentCommit: entry.commit || '',
355
+ }));
356
+ }
357
+
358
+ changed() {
359
+ try {
360
+ this.onChange();
361
+ } catch (error) {
362
+ this.log.warn(`更新状态失败:${error.message}`);
363
+ }
364
+ }
365
+
366
+ setPhase(entry, phase) {
367
+ entry.phase = phase;
368
+ entry.at[phase] = new Date().toISOString();
369
+ this.changed();
370
+ }
371
+
300
372
  /** A `job` event from the control channel. Repeats of a running job are ignored. */
301
373
  handle(job) {
302
374
  if (this.closed) return;
303
375
  const runId = typeof job?.runId === 'string' && job.runId.length <= 100 ? job.runId : '';
304
376
  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 };
377
+ const entry = {
378
+ runId,
379
+ job,
380
+ child: null,
381
+ interaction: null,
382
+ cancelled: false,
383
+ timedOut: false,
384
+ failure: '',
385
+ gone: false,
386
+ done: null,
387
+ phase: 'received',
388
+ at: { received: new Date().toISOString() },
389
+ };
306
390
  this.jobs.set(runId, entry);
391
+ this.changed();
307
392
  entry.done = this.run(entry)
308
- .catch((error) => this.log.error(`任务 ${runId} 异常:${error?.message || error}`))
309
- .finally(() => this.jobs.delete(runId));
393
+ .catch((error) => {
394
+ this.log.error(`任务 ${runId} 异常:${error?.message || error}`);
395
+ this.record(entry, { result: 'failed', message: String(error?.message || error) });
396
+ })
397
+ .finally(() => {
398
+ this.jobs.delete(runId);
399
+ this.changed();
400
+ });
310
401
  }
311
402
 
312
403
  /**
@@ -324,13 +415,24 @@ export class JobManager {
324
415
  return result;
325
416
  }
326
417
 
327
- /** Stops a job (website cancel, heartbeat reconciliation). */
328
- cancel(runId) {
418
+ /**
419
+ * Stops a job (website cancel, heartbeat reconciliation, `work-agent-runner
420
+ * jobs cancel`). `by`: who, when it was not the website — the website is
421
+ * then told why the job ended.
422
+ */
423
+ cancel(runId, { by = '' } = {}) {
329
424
  const entry = this.jobs.get(runId);
330
- if (!entry || entry.cancelled) return;
425
+ if (!entry || entry.cancelled) return false;
331
426
  entry.cancelled = true;
332
- this.log.info(`任务 ${runId} 被取消`);
427
+ entry.cancelledBy = by;
428
+ this.log.info(`任务 ${runId} 被取消${by ? `(${by})` : ''}`);
333
429
  this.terminate(entry);
430
+ return true;
431
+ }
432
+
433
+ /** What the website is told about a job stopped on this machine ('' when the website stopped it). */
434
+ cancelReason(entry) {
435
+ return entry.cancelled && entry.cancelledBy && !entry.gone ? `任务在执行机器上被取消(${entry.cancelledBy})` : '';
334
436
  }
335
437
 
336
438
  terminate(entry) {
@@ -341,11 +443,21 @@ export class JobManager {
341
443
  setTimeout(() => killGroup(pid, 'SIGKILL'), KILL_GRACE_MS).unref();
342
444
  }
343
445
 
446
+ /** A second Ctrl+C: every job's process group gets SIGKILL at once (no grace, nothing reported). */
447
+ killAll() {
448
+ this.closed = true;
449
+ for (const entry of this.jobs.values()) {
450
+ entry.cancelled = true;
451
+ killGroup(entry.child?.pid, 'SIGKILL');
452
+ }
453
+ }
454
+
344
455
  /** Stops every job and waits (≤ timeoutMs) for their exits to be reported. */
345
456
  async stopAll(timeoutMs = 5000) {
346
457
  this.closed = true;
347
458
  const entries = [...this.jobs.values()];
348
459
  for (const entry of entries) {
460
+ if (!entry.cancelled) entry.cancelledBy = '执行机器上的程序正在停止';
349
461
  entry.cancelled = true;
350
462
  this.terminate(entry);
351
463
  }
@@ -394,6 +506,90 @@ export class JobManager {
394
506
  }
395
507
  }
396
508
 
509
+ /** Not run: tells the website why (with the code, after the status lines sent so far) and records it. */
510
+ async fail(entry, code, message) {
511
+ await entry.uploader?.drain();
512
+ if (!entry.gone) await this.reportExit(entry, { seq: entry.uploader?.lastSeq || 0, error: withCode(code, message) });
513
+ this.record(entry, { result: 'failed', code, message });
514
+ }
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
+
555
+ /** The job's one history record (once): what happened, never what it was asked or given. */
556
+ record(entry, { result, code = '', message = '', exit = null }) {
557
+ if (entry.recorded) return;
558
+ entry.recorded = true;
559
+ this.setPhase(entry, 'done');
560
+ const { at } = entry;
561
+ const waitedMs = at.waiting && at.preparing ? Math.max(0, Date.parse(at.preparing) - Date.parse(at.waiting)) : 0;
562
+ try {
563
+ this.onFinished({
564
+ runId: entry.runId,
565
+ feature: Object.hasOwn(FEATURE_LABELS, entry.job?.feature) ? entry.job.feature : '',
566
+ interactive: entry.job?.interactive === true,
567
+ isolation: entry.isolation || '',
568
+ at: { ...at },
569
+ waitedMs,
570
+ result,
571
+ exit,
572
+ error: { code, message: String(message || '').slice(0, 300) },
573
+ workAgentCommit: entry.commit || '',
574
+ outputBytes: entry.uploader?.totalBytes || 0,
575
+ });
576
+ } catch (error) {
577
+ this.log.warn(`无法记录任务 ${entry.runId}:${error.message}`);
578
+ }
579
+ }
580
+
581
+ /** The default gate: no knowledge-pool update in progress (bounded wait). */
582
+ async poolGate({ isCancelled, timeoutMs, onWait }) {
583
+ if (typeof this.workAgent?.waitForPoolIdle !== 'function') return { ok: true };
584
+ const idle = await this.workAgent.waitForPoolIdle({ timeoutMs, isCancelled, onWait: () => onWait('waiting_pool_update', '等待知识仓更新完成后开始') });
585
+ if (idle || isCancelled()) return { ok: true };
586
+ return {
587
+ ok: false,
588
+ code: 'E3201',
589
+ message: `执行机器正在更新知识仓,等待超过 ${Math.round(timeoutMs / 60_000)} 分钟,任务未执行,请稍后重试`,
590
+ };
591
+ }
592
+
397
593
  async run(entry) {
398
594
  const { runId, job } = entry;
399
595
  const started = Date.now();
@@ -401,94 +597,173 @@ export class JobManager {
401
597
  // Acknowledge first so the website does not wait for the accept timeout.
402
598
  if (!(await this.accept(entry))) {
403
599
  this.log.warn(`任务 ${runId} 已在网站上失效,未执行`);
600
+ this.record(entry, { result: 'not_accepted', message: '网站上已失效,未执行' });
404
601
  return;
405
602
  }
603
+ this.setPhase(entry, 'accepted');
604
+ entry.uploader = this.uploaderFor(entry);
406
605
  if (invalid) {
407
606
  this.log.warn(`任务 ${runId} 参数不合法(${invalid}),未执行`);
408
- await this.reportExit(entry, { error: `任务参数不合法:${invalid}` });
607
+ await this.fail(entry, 'E3101', `任务参数不合法:${invalid}`);
409
608
  return;
410
609
  }
411
610
  const label = FEATURE_LABELS[job.feature];
412
611
  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({
612
+ // Never in a log line, whatever prints them.
613
+ const secrets = [job.apiKey, job.env.GITCODE_CRED];
614
+ for (const secret of secrets) addSecret(secret);
615
+ let runDir = '';
616
+ try {
617
+ this.setPhase(entry, 'waiting');
618
+ const gate = await this.gate({
619
+ isCancelled: () => entry.cancelled || entry.gone,
418
620
  timeoutMs: this.jobWaitMs,
419
- isCancelled: () => entry.cancelled,
420
- onWait: () => this.log.info(`任务 ${runId} 等待知识仓更新完成后开始`),
621
+ onWait: (code, why) => {
622
+ this.log.info(`任务 ${runId} ${why}`);
623
+ this.status(entry, code);
624
+ },
421
625
  });
422
- if (!idle && !entry.cancelled) {
423
- this.log.warn(`任务 ${runId} 等待知识仓更新超时,未执行`);
424
- await this.reportExit(entry, { error: `执行机器正在更新知识仓,等待超过 ${Math.round(this.jobWaitMs / 60_000)} 分钟,任务未执行,请稍后重试` });
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) });
629
+ this.record(entry, { result: 'cancelled' });
630
+ return;
631
+ }
632
+ if (!gate.ok) {
633
+ this.log.warn(`任务 ${runId} 未执行:${gate.message}`);
634
+ await this.fail(entry, gate.code, gate.message);
425
635
  return;
426
636
  }
427
- }
428
-
429
- if (entry.cancelled) {
430
- await this.reportExit(entry, { signal: 'SIGTERM' });
431
- return;
432
- }
433
637
 
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
- }
638
+ this.setPhase(entry, 'preparing');
639
+ const waitedMs = Date.parse(entry.at.preparing) - Date.parse(entry.at.waiting);
640
+ this.status(entry, 'preparing', waitedMs);
641
+ // A code review clones the repository it reviews: no room, no start.
642
+ const free = this.freeBytes(this.runsDir);
643
+ if (free && free < this.minFreeBytes) {
644
+ const message = `执行机器的工作目录磁盘只剩 ${gigabytes(free)} GB(至少要 ${gigabytes(this.minFreeBytes)} GB),任务未执行`;
645
+ this.log.warn(`任务 ${runId} ${message}`);
646
+ await this.fail(entry, 'E3301', message);
647
+ return;
648
+ }
649
+ const mode = this.runMode();
650
+ // A short directory name, not the run id: see socketPathProblem().
651
+ let layout;
652
+ try {
653
+ runDir = newRunDir(this.runsDir, 'r');
654
+ layout = createRunLayout(runDir, {
655
+ workAgentHome: this.paths?.workAgentHome || '',
656
+ isolation: mode.isolation,
657
+ pool: this.workAgent.mountablePool(),
658
+ });
659
+ entry.isolation = layout.isolation;
660
+ const tooLong = socketPathProblem(layout.tmpDir, this.platform);
661
+ if (tooLong) throw new Error(tooLong);
662
+ } catch (error) {
663
+ await this.fail(entry, 'E3401', `准备运行目录失败:${error?.message || error}`);
664
+ return;
665
+ }
447
666
 
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, {
667
+ // A copy of this machine's work-agent clone as the working directory (the
668
+ // Skills' logs pointed at the job's $WORK_AGENT_HOME/logs, their scratch at
669
+ // the run's own), and the knowledge pool read-only if there is one: the
670
+ // settings name every path the job may reach (sandbox.mjs).
671
+ try {
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
+ );
678
+ entry.commit = commit;
679
+ const pool = this.workAgent.mountablePool();
680
+ writeSandboxSettings(layout.settingsFile, {
681
+ workDir: fs.realpathSync(layout.workDir),
462
682
  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
- }
683
+ ...runAllowances(layout, {
684
+ realHome: this.realHome,
685
+ pathEnv: this.env.PATH || '',
686
+ caPaths: caPaths(this.env),
687
+ pool,
688
+ paths: this.paths,
689
+ // A server execution machine: what other users' jobs left is not this one's.
690
+ denySharedWork: layout.isolation === 'per-run' && mode.keep !== 'merge',
691
+ controlDirs: this.controlDirs,
692
+ // Other jobs' archived outputs, what could not be deleted, and the
693
+ // program's status, history and log.
694
+ privateDirs: [this.archiveDir, this.trashDir, ...(this.paths?.stateDir ? [this.paths.stateDir, this.paths.logsDir] : [])],
695
+ }),
696
+ });
697
+ this.log.info(
698
+ `任务 ${runId} 使用 work-agent ${commit.slice(0, 7)}${pool ? ',已挂载知识仓' : ''}${layout.isolation === 'per-run' ? ',WORK_AGENT_HOME 独立' : ''}`,
699
+ );
700
+ } catch (error) {
701
+ await this.fail(entry, 'E3401', `准备 Skill 失败:${error?.message || error}`);
702
+ return;
703
+ }
475
704
 
476
- try {
477
- const result = await this.spawnClaude(entry, layout);
705
+ const result = await this.spawnClaude(entry, layout, waitedMs);
706
+ const failure = result.error || entry.failure;
707
+ const failureCode = result.error ? 'E1301' : entry.failure ? 'E3501' : '';
708
+ await entry.uploader.drain();
478
709
  if (!entry.gone) {
479
710
  await this.reportExit(entry, {
480
711
  seq: entry.uploader.lastSeq,
481
712
  code: result.code,
482
713
  signal: result.signal,
483
714
  timedOut: entry.timedOut,
484
- error: result.error || entry.failure,
715
+ error: failure ? withCode(failureCode, failure) : this.cancelReason(entry),
485
716
  });
486
717
  }
487
718
  const seconds = Math.round((Date.now() - started) / 1000);
488
719
  const outcome = entry.timedOut ? '超时' : entry.cancelled ? '已取消' : result.error ? result.error : `退出码 ${result.code ?? result.signal}`;
489
720
  this.log.info(`任务 ${runId} 结束(${label}):${outcome},用时 ${seconds} 秒`);
721
+
722
+ let kind = 'failed';
723
+ if (entry.timedOut) kind = 'timeout';
724
+ else if (entry.cancelled || entry.gone) kind = 'cancelled';
725
+ else if (!failure && result.code === 0) kind = 'ok';
726
+ this.setPhase(entry, 'cleaning');
727
+ this.keepOutputs(entry, layout, mode, kind);
728
+ this.record(entry, {
729
+ result: kind,
730
+ code: kind === 'failed' ? failureCode : '',
731
+ message: failure || (kind === 'failed' ? `claude 退出码 ${result.code ?? result.signal}` : ''),
732
+ exit: { code: result.code, signal: result.signal, timedOut: entry.timedOut },
733
+ });
490
734
  } finally {
491
- this.removeRunDir(runDir);
735
+ for (const secret of secrets) removeSecret(secret);
736
+ if (runDir) this.removeRunDir(runDir);
737
+ }
738
+ }
739
+
740
+ /**
741
+ * What a per-run job left in its own WORK_AGENT_HOME (logs/ and docs/, at
742
+ * most 50 MiB): merged into the shared ones (a user's machine; a name that
743
+ * is taken gets the run id's last 8 characters), archived under
744
+ * archive/<runId>/ with meta.json (a server execution machine that keeps
745
+ * them), or dropped with the run.
746
+ */
747
+ keepOutputs(entry, layout, mode, result = '') {
748
+ if (layout?.isolation !== 'per-run' || !['merge', 'archive'].includes(mode.keep)) return;
749
+ const wah = layout.workAgentHome;
750
+ const archive = mode.keep === 'archive';
751
+ const into = archive ? path.join(this.archiveDir, entry.runId) : layout.sharedWorkAgentHome;
752
+ const budget = { left: MERGE_MAX_BYTES, skipped: 0 };
753
+ try {
754
+ for (const name of ['logs', 'docs']) mergeTree(path.join(wah, name), path.join(into, name), entry.runId.slice(-8), budget);
755
+ if (archive) {
756
+ fs.mkdirSync(into, { recursive: true, mode: 0o700 });
757
+ writeJsonAtomic(path.join(into, 'meta.json'), {
758
+ runId: entry.runId,
759
+ feature: entry.job?.feature || '',
760
+ result,
761
+ finishedAt: new Date().toISOString(),
762
+ });
763
+ }
764
+ if (budget.skipped) this.log.warn(`任务 ${entry.runId} 留下的文件超过 ${MERGE_MAX_BYTES / 1048576} MB,${budget.skipped} 个没有放进 ${into}`);
765
+ } catch (error) {
766
+ this.log.warn(`任务 ${entry.runId} 的日志和交付件没能保留:${error.message}`);
492
767
  }
493
768
  }
494
769
 
@@ -505,11 +780,10 @@ export class JobManager {
505
780
  else this.log.warn(`运行目录 ${runDir} 删不掉(${why}),下次启动时再试`);
506
781
  }
507
782
 
508
- spawnClaude(entry, layout) {
783
+ spawnClaude(entry, layout, waitedMs = 0) {
509
784
  const { job } = entry;
510
785
  return new Promise((resolve) => {
511
786
  if (!this.claudePath) {
512
- entry.uploader = { lastSeq: 0 };
513
787
  resolve({ code: null, signal: null, error: '无法启动 claude:未安装' });
514
788
  return;
515
789
  }
@@ -531,36 +805,27 @@ export class JobManager {
531
805
  model: job.model,
532
806
  extra: {
533
807
  ...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,
808
+ // The job's work-agent home (the shared one, or its own per-run
809
+ // one); the job's HOME links to it, so `~/.work-agent/...` in a
810
+ // Skill is the same directory.
811
+ WORK_AGENT_HOME: layout.workAgentHome || this.paths.workAgentHome,
537
812
  GITCODE_CRED: job.env.GITCODE_CRED,
538
813
  },
539
814
  }),
540
815
  });
541
816
  } catch (error) {
542
- entry.uploader = { lastSeq: 0 };
543
817
  resolve({ code: null, signal: null, error: `无法启动 claude:${error.code || error.message}` });
544
818
  return;
545
819
  }
546
820
  entry.child = child;
547
- const uploader = new OutputUploader({
548
- client: this.client,
549
- runId: entry.runId,
550
- onGone: () => {
551
- entry.gone = true;
552
- this.terminate(entry);
553
- },
554
- onFailure: (reason) => {
555
- entry.failure = reason;
556
- this.terminate(entry);
557
- },
558
- onFatal: (error) => {
559
- this.terminate(entry);
560
- this.onFatal(error);
561
- },
562
- });
563
- entry.uploader = uploader;
821
+ const { uploader } = entry;
822
+ if (child.pid) {
823
+ entry.timeoutAt = new Date(Date.now() + job.timeoutMs).toISOString();
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(() => {});
828
+ }
564
829
  if (interactive) {
565
830
  entry.interaction = createClaudeInteraction({
566
831
  write: (message) => {
@@ -606,12 +871,14 @@ export class JobManager {
606
871
  clearTimeout(timeout);
607
872
  clearTimeout(closeWait);
608
873
  killGroup(child.pid, 'SIGKILL'); // whatever the job left behind
874
+ if (entry.phase === 'running') this.setPhase(entry, 'finishing');
609
875
  // Open questions are reported closed before the exit.
610
876
  entry.interaction?.dispose();
611
877
  await uploader.drain();
612
878
  resolve(result);
613
879
  };
614
880
  child.once('exit', () => {
881
+ if (entry.phase === 'running') this.setPhase(entry, 'finishing');
615
882
  // Background descendants may keep the pipes open: end them shortly after.
616
883
  closeWait = setTimeout(() => killGroup(child.pid, 'SIGKILL'), CLOSE_WAIT_MS);
617
884
  closeWait.unref();
@@ -630,6 +897,76 @@ export class JobManager {
630
897
  }
631
898
  }
632
899
 
900
+ const GIB = 1024 ** 3;
901
+
902
+ function gigabytes(bytes) {
903
+ return (bytes / GIB).toFixed(1);
904
+ }
905
+
906
+ /** Free bytes where `dir` lives (0 = unknown, never a reason to refuse). */
907
+ function diskFreeBytes(dir) {
908
+ try {
909
+ const stat = fs.statfsSync(dir);
910
+ return Number(stat.bavail) * Number(stat.bsize);
911
+ } catch {
912
+ return 0;
913
+ }
914
+ }
915
+
916
+ /** A name in `dir` that is not taken: `name`, else `stem-suffix.ext`, `stem-suffix-2.ext`… */
917
+ function freeName(dir, name, suffix) {
918
+ if (!fs.existsSync(path.join(dir, name))) return path.join(dir, name);
919
+ const ext = path.extname(name);
920
+ const stem = path.basename(name, ext);
921
+ for (let index = 1; ; index += 1) {
922
+ const candidate = path.join(dir, `${stem}-${suffix}${index > 1 ? `-${index}` : ''}${ext}`);
923
+ if (!fs.existsSync(candidate)) return candidate;
924
+ }
925
+ }
926
+
927
+ /**
928
+ * Moves the regular files under `source` into `target` (same layout), never
929
+ * over an existing file and never more than `budget.left` bytes; symlinks and
930
+ * special files stay behind. Across filesystems: copy, then delete.
931
+ */
932
+ function mergeTree(source, target, suffix, budget) {
933
+ let names;
934
+ try {
935
+ names = fs.readdirSync(source);
936
+ } catch {
937
+ return;
938
+ }
939
+ if (!names.length) return;
940
+ fs.mkdirSync(target, { recursive: true, mode: 0o700 });
941
+ for (const name of names) {
942
+ const from = path.join(source, name);
943
+ let stat;
944
+ try {
945
+ stat = fs.lstatSync(from);
946
+ } catch {
947
+ continue;
948
+ }
949
+ if (stat.isDirectory()) {
950
+ mergeTree(from, path.join(target, name), suffix, budget);
951
+ continue;
952
+ }
953
+ if (!stat.isFile()) continue;
954
+ if (stat.size > budget.left) {
955
+ budget.skipped += 1;
956
+ continue;
957
+ }
958
+ const to = freeName(target, name, suffix);
959
+ try {
960
+ fs.renameSync(from, to);
961
+ } catch (error) {
962
+ if (error.code !== 'EXDEV') throw error;
963
+ fs.copyFileSync(from, to, fs.constants.COPYFILE_EXCL);
964
+ fs.rmSync(from, { force: true });
965
+ }
966
+ budget.left -= stat.size;
967
+ }
968
+ }
969
+
633
970
  /**
634
971
  * Splits decoded text into lines for `onLine` (without the newline); end()
635
972
  * flushes the last line even when it has no newline.