pi-better-server 0.7.1 → 0.7.3

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.
Files changed (84) hide show
  1. package/package.json +1 -1
  2. package/src/runtime/background-tools.ts +2 -1
  3. package/src/runtime/domain/background/registry.mjs +3 -0
  4. package/src/runtime/domain/background/shared-operation-coordinator/src/task-lifetime.mjs +6 -0
  5. package/src/runtime/domain/background/terminal-publication.mjs +5 -2
  6. package/src/runtime/domain/background-service/managed-authority.domain.mjs +13 -0
  7. package/src/runtime/domain/background-service/managed-authority.ts +16 -0
  8. package/src/runtime/domain/background-service/managed-client.domain.mjs +2 -2
  9. package/src/runtime/domain/background-service/managed-client.ts +2 -2
  10. package/src/runtime/domain/background-service/observed-waits.domain.mjs +8 -4
  11. package/src/runtime/domain/background-service/observed-waits.ts +8 -4
  12. package/src/runtime/domain/background-service/registry.domain.mjs +3 -0
  13. package/src/runtime/domain/background-service/registry.ts +2 -0
  14. package/src/runtime/domain/background-service/runtime.domain.mjs +3 -2
  15. package/src/runtime/domain/background-service/runtime.ts +3 -2
  16. package/src/runtime/domain/background-service/shared-operation-coordinator/src/expiry.domain.mjs +44 -0
  17. package/src/runtime/domain/background-service/shared-operation-coordinator/src/expiry.ts +44 -0
  18. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +8 -1
  19. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +8 -1
  20. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +3 -0
  21. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +5 -0
  22. package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-lifetime.domain.mjs +7 -0
  23. package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-lifetime.ts +7 -0
  24. package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.domain.mjs +22 -13
  25. package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.ts +40 -32
  26. package/src/runtime/domain/background-service/shared-sandbox-diagnostics.domain.mjs +12 -19
  27. package/src/runtime/domain/background-service/shared-sandbox-diagnostics.ts +12 -16
  28. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  29. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +12 -7
  30. package/src/runtime/domain/background-service/supervisor/generated/task-lifetime.mjs +9 -0
  31. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +12 -7
  32. package/src/runtime/domain/background-service/supervisor/runner.ts +12 -7
  33. package/src/runtime/domain/background-service/supervisor/types.ts +1 -1
  34. package/src/runtime/domain/background-service/tools.domain.mjs +3 -2
  35. package/src/runtime/domain/background-service/tools.ts +3 -2
  36. package/src/runtime/domain/coordinator/src/expiry.mjs +43 -0
  37. package/src/runtime/domain/coordinator/src/schema.mjs +8 -1
  38. package/src/runtime/domain/coordinator/src/store.mjs +3 -0
  39. package/src/runtime/domain/coordinator/src/task-lifetime.mjs +6 -0
  40. package/src/runtime/domain/coordinator/src/waits.mjs +22 -13
  41. package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.domain.mjs +12 -19
  42. package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.ts +12 -16
  43. package/src/runtime/domain/subagents/README.md +2 -2
  44. package/src/runtime/domain/subagents/cleanup.domain.mjs +5 -2
  45. package/src/runtime/domain/subagents/cleanup.ts +4 -1
  46. package/src/runtime/domain/subagents/index.domain.mjs +47 -29
  47. package/src/runtime/domain/subagents/index.ts +46 -27
  48. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +28 -2
  49. package/src/runtime/domain/subagents/managed-launch-host.ts +26 -2
  50. package/src/runtime/domain/subagents/managed-launch-port.ts +2 -0
  51. package/src/runtime/domain/subagents/output-payload.domain.mjs +3 -1
  52. package/src/runtime/domain/subagents/output-payload.ts +2 -0
  53. package/src/runtime/domain/subagents/package.json +1 -1
  54. package/src/runtime/domain/subagents/registry-cleanup-worker.mjs +24 -0
  55. package/src/runtime/domain/subagents/registry.domain.mjs +33 -7
  56. package/src/runtime/domain/subagents/registry.ts +18 -4
  57. package/src/runtime/domain/subagents/settings-page.domain.mjs +10 -10
  58. package/src/runtime/domain/subagents/settings-page.ts +10 -10
  59. package/src/runtime/domain/subagents/shared-operation-coordinator/src/expiry.domain.mjs +44 -0
  60. package/src/runtime/domain/subagents/shared-operation-coordinator/src/expiry.ts +44 -0
  61. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +8 -1
  62. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +8 -1
  63. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +3 -0
  64. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +5 -0
  65. package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-lifetime.domain.mjs +7 -0
  66. package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-lifetime.ts +7 -0
  67. package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.domain.mjs +22 -13
  68. package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.ts +40 -32
  69. package/src/runtime/domain/subagents/shared-sandbox-diagnostics.domain.mjs +12 -19
  70. package/src/runtime/domain/subagents/shared-sandbox-diagnostics.ts +12 -16
  71. package/src/runtime/domain/subagents/stop.domain.mjs +7 -5
  72. package/src/runtime/domain/subagents/stop.ts +7 -5
  73. package/src/runtime/domain/subagents/timing.domain.mjs +7 -3
  74. package/src/runtime/domain/subagents/timing.ts +11 -4
  75. package/src/runtime/domain/subagents/tools.domain.mjs +3 -2
  76. package/src/runtime/domain/subagents/tools.ts +3 -2
  77. package/src/runtime/domain/subagents/workflow-assignment.domain.mjs +25 -0
  78. package/src/runtime/domain/subagents/workflow-assignment.ts +35 -0
  79. package/src/runtime/domain/subagents/workspace-files.domain.mjs +6 -6
  80. package/src/runtime/domain/subagents/workspace-files.ts +6 -6
  81. package/src/runtime/query-executor.ts +11 -2
  82. package/src/runtime/task-expiry.ts +52 -0
  83. package/src/server.ts +4 -0
  84. package/src/version.ts +1 -1
@@ -14,6 +14,7 @@
14
14
  * the cancellation epoch it observed. Cancellation invalidates the active resume
15
15
  * claim, and a claim whose epoch no longer matches can never publish an attempt.
16
16
  */
17
+ import { taskDeadline } from "./task-lifetime.mjs";
17
18
  import { randomUUID } from "node:crypto";
18
19
  import { StoreError } from "./errors.mjs";
19
20
  import { acknowledgeGenerationOutbox, enqueueReadyGeneration, releaseGenerationPins, voidGenerationOutbox, } from "./outbox.mjs";
@@ -369,21 +370,25 @@ export function cancelWait(ctx, input) {
369
370
  throw new StoreError("wait-phase", `Wait ${waitId} generation ${generation} is already ${wait.phase}; cancellation is recorded once and cannot be repeated or replaced.`);
370
371
  }
371
372
  assertExpectedEpoch(wait, expectedCancelEpoch);
372
- const at = ctx.now();
373
- run(ctx, "UPDATE waits SET phase = 'cancelled', phase_reason = ?, cancel_epoch = cancel_epoch + 1, updated_at = ? WHERE wait_id = ? AND generation = ?", reason, at, waitId, generation);
374
- const activeClaimRows = getRows(ctx, "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')", waitId, generation);
375
- const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
376
- run(ctx, `UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
377
- WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`, at, reason, waitId, generation);
378
- const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
379
- releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
380
- return {
381
- wait: requireWait(ctx, waitId, generation),
382
- invalidatedClaimIds,
383
- voidedOutboxIds,
384
- };
373
+ return cancelGeneration(ctx, waitId, generation, reason);
385
374
  });
386
375
  }
376
+ /** Caller holds the write transaction and has selected a nonterminal generation. */
377
+ export function cancelGeneration(ctx, waitId, generation, reason) {
378
+ const at = ctx.now();
379
+ run(ctx, "UPDATE waits SET phase = 'cancelled', phase_reason = ?, cancel_epoch = cancel_epoch + 1, updated_at = ? WHERE wait_id = ? AND generation = ?", reason, at, waitId, generation);
380
+ const activeClaimRows = getRows(ctx, "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')", waitId, generation);
381
+ const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
382
+ run(ctx, `UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
383
+ WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`, at, reason, waitId, generation);
384
+ const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
385
+ releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
386
+ return {
387
+ wait: requireWait(ctx, waitId, generation),
388
+ invalidatedClaimIds,
389
+ voidedOutboxIds,
390
+ };
391
+ }
387
392
  // ---- resume claims ------------------------------------------------------
388
393
  export function claimResume(ctx, input) {
389
394
  const waitId = requireId("waitId", input.waitId);
@@ -394,6 +399,8 @@ export function claimResume(ctx, input) {
394
399
  return ctx.transaction(() => {
395
400
  assertCurrentGeneration(ctx, waitId, generation);
396
401
  const wait = requireWait(ctx, waitId, generation);
402
+ if (ctx.now() >= taskDeadline(wait.createdAt))
403
+ throw new StoreError("wait-phase", "The 24-hour wait lifetime has expired.");
397
404
  const active = getRows(ctx, "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')", waitId, generation)[0];
398
405
  if (active) {
399
406
  throw new StoreError("concurrent-claim", `Wait ${waitId} generation ${generation} already has an active resume claim (${columnText(active, "claim_id")}). One conversation admits one writer; release or invalidate that claim instead of claiming again.`);
@@ -438,6 +445,8 @@ export function publishResumeAttempt(ctx, input) {
438
445
  return ctx.transaction(() => {
439
446
  assertCurrentGeneration(ctx, waitId, generation);
440
447
  const wait = requireWait(ctx, waitId, generation);
448
+ if (ctx.now() >= taskDeadline(wait.createdAt))
449
+ throw new StoreError("wait-phase", "The 24-hour wait lifetime has expired.");
441
450
  const claim = requireClaim(ctx, claimId);
442
451
  if (claim.waitId !== waitId || claim.generation !== generation) {
443
452
  throw new StoreError("claim-state", `Resume claim ${claimId} belongs to ${claim.waitId} generation ${claim.generation}, not ${waitId} generation ${generation}.`);
@@ -273,7 +273,7 @@ function sameOperation(a, b) {
273
273
  function load(dir, key) {
274
274
  const path = join(dir, "events.jsonl");
275
275
  if (!stat(path))
276
- return { records: [], losses: emptyLosses() };
276
+ return { records: [], losses: emptyLosses(), needsRepair: false };
277
277
  chmodSync(path, 0o600);
278
278
  const raw = readSafe(path, MAX_BYTES);
279
279
  const lines = raw.split("\n");
@@ -304,7 +304,8 @@ function load(dir, key) {
304
304
  catch {
305
305
  losses.malformed++;
306
306
  }
307
- if (header && (header.count !== lines.length || header.digest !== digest(key, "journal", lines.join("\n"))))
307
+ const headerMatches = header && header.count === lines.length && header.digest === digest(key, "journal", lines.join("\n"));
308
+ if (header && !headerMatches)
308
309
  losses.tampered++;
309
310
  const records = [];
310
311
  const seen = new Set();
@@ -340,7 +341,7 @@ function load(dir, key) {
340
341
  seen.add(record.fingerprint);
341
342
  records.push(record);
342
343
  }
343
- return { records, losses };
344
+ return { records, losses, needsRepair: !headerMatches || records.length !== lines.length };
344
345
  }
345
346
  function encode(journal, key) {
346
347
  const lines = journal.records.map(record => JSON.stringify({ ...record, mac: digest(key, "event", JSON.stringify(record)) }));
@@ -460,31 +461,22 @@ export class SandboxDiagnostics {
460
461
  return;
461
462
  if (input.outcome === "succeeded" && !stat(join(dir, "events.jsonl")))
462
463
  return;
463
- locked(dir, () => {
464
+ const repaired = locked(dir, () => {
464
465
  const key = installationKey(dir, input.outcome === "denied");
465
466
  const journal = load(dir, key);
466
- const before = JSON.stringify(journal.losses);
467
467
  const pruned = retain(journal, key, now);
468
468
  const fingerprint = imported ? digest(key, "relay-event-identity", identity([imported.runIdentity, imported.value.idFingerprint])) :
469
469
  digest(key, "event-identity", randomBytes(32).toString("hex"));
470
470
  // Signed record identities survive parent reloads and full log rescans.
471
- if (imported && journal.records.some(r => r.fingerprint === fingerprint)) {
472
- if (pruned || journal.losses.malformed || journal.losses.tampered)
473
- atomic(join(dir, "events.jsonl"), encode(journal, key));
474
- if (issues(journal.losses).length)
475
- this.report(new Error("Diagnostics collection has gaps."));
476
- return;
477
- }
471
+ const duplicate = imported && journal.records.some(r => r.fingerprint === fingerprint);
478
472
  const operationFingerprint = digest(key, "operation", operation);
479
473
  const recovered = new Set(journal.records.flatMap(r => r.recoveryOf ? [r.recoveryOf] : []));
480
474
  const prior = [...journal.records].reverse().find(r => r.outcome === "denied" && r.context === this.options.context &&
481
475
  r.tool === tool && r.operationFingerprint === operationFingerprint && r.timestamp <= now);
482
- if (input.outcome === "succeeded" && (!prior || recovered.has(prior.fingerprint))) {
483
- if (pruned || issues(journal.losses).some(i => i !== "retention-loss"))
476
+ if (duplicate || (input.outcome === "succeeded" && (!prior || recovered.has(prior.fingerprint)))) {
477
+ if (pruned || journal.needsRepair)
484
478
  atomic(join(dir, "events.jsonl"), encode(journal, key));
485
- if (issues(journal.losses).length)
486
- this.report(new Error("Diagnostics collection has gaps."));
487
- return;
479
+ return journal.needsRepair;
488
480
  }
489
481
  const backend = imported?.value.backend ?? this.options.backend();
490
482
  const version = imported?.value.version ?? this.options.version;
@@ -505,9 +497,10 @@ export class SandboxDiagnostics {
505
497
  journal.records.push(record);
506
498
  retain(journal, key, now);
507
499
  atomic(join(dir, "events.jsonl"), encode(journal, key));
508
- if (before !== JSON.stringify(journal.losses) || journal.losses.malformed || journal.losses.tampered)
509
- this.report(new Error("Diagnostics collection has gaps."));
500
+ return journal.needsRepair;
510
501
  });
502
+ if (repaired)
503
+ this.report(new Error("Diagnostics collection has gaps."));
511
504
  }
512
505
  catch (error) {
513
506
  this.report(this.options.relay || imported ? new Error("Diagnostics collection has gaps.") : error);
@@ -249,9 +249,9 @@ function sameOperation(a: DiagnosticRecord, b: DiagnosticRecord): boolean {
249
249
  return a.context === b.context && a.tool === b.tool && a.operationFingerprint === b.operationFingerprint;
250
250
  }
251
251
  interface Journal { records: DiagnosticRecord[]; losses: DiagnosticLosses }
252
- function load(dir: string, key: Buffer): Journal {
252
+ function load(dir: string, key: Buffer): Journal & { needsRepair: boolean } {
253
253
  const path = join(dir, "events.jsonl");
254
- if (!stat(path)) return { records: [], losses: emptyLosses() };
254
+ if (!stat(path)) return { records: [], losses: emptyLosses(), needsRepair: false };
255
255
  chmodSync(path, 0o600);
256
256
  const raw = readSafe(path, MAX_BYTES);
257
257
  const lines = raw.split("\n");
@@ -273,7 +273,8 @@ function load(dir: string, key: Buffer): Journal {
273
273
  } else losses.tampered++;
274
274
  } else losses.malformed++;
275
275
  } catch { losses.malformed++; }
276
- if (header && (header.count !== lines.length || header.digest !== digest(key, "journal", lines.join("\n")))) losses.tampered++;
276
+ const headerMatches = header && header.count === lines.length && header.digest === digest(key, "journal", lines.join("\n"));
277
+ if (header && !headerMatches) losses.tampered++;
277
278
  const records: DiagnosticRecord[] = [];
278
279
  const seen = new Set<string>();
279
280
  const denied = new Map<string, DiagnosticRecord>();
@@ -293,7 +294,7 @@ function load(dir: string, key: Buffer): Journal {
293
294
  seen.add(record.fingerprint);
294
295
  records.push(record);
295
296
  }
296
- return { records, losses };
297
+ return { records, losses, needsRepair: !headerMatches || records.length !== lines.length };
297
298
  }
298
299
  function encode(journal: Journal, key: Buffer): string {
299
300
  const lines = journal.records.map(record => JSON.stringify({ ...record, mac: digest(key, "event", JSON.stringify(record)) }));
@@ -385,27 +386,21 @@ export class SandboxDiagnostics {
385
386
  const dir = directory(this.options, input.outcome === "denied");
386
387
  if (!dir) return;
387
388
  if (input.outcome === "succeeded" && !stat(join(dir, "events.jsonl"))) return;
388
- locked(dir, () => {
389
+ const repaired = locked(dir, () => {
389
390
  const key = installationKey(dir, input.outcome === "denied");
390
391
  const journal = load(dir, key);
391
- const before = JSON.stringify(journal.losses);
392
392
  const pruned = retain(journal, key, now);
393
393
  const fingerprint = imported ? digest(key, "relay-event-identity", identity([imported.runIdentity, imported.value.idFingerprint])) :
394
394
  digest(key, "event-identity", randomBytes(32).toString("hex"));
395
395
  // Signed record identities survive parent reloads and full log rescans.
396
- if (imported && journal.records.some(r => r.fingerprint === fingerprint)) {
397
- if (pruned || journal.losses.malformed || journal.losses.tampered) atomic(join(dir, "events.jsonl"), encode(journal, key));
398
- if (issues(journal.losses).length) this.report(new Error("Diagnostics collection has gaps."));
399
- return;
400
- }
396
+ const duplicate = imported && journal.records.some(r => r.fingerprint === fingerprint);
401
397
  const operationFingerprint = digest(key, "operation", operation);
402
398
  const recovered = new Set(journal.records.flatMap(r => r.recoveryOf ? [r.recoveryOf] : []));
403
399
  const prior = [...journal.records].reverse().find(r => r.outcome === "denied" && r.context === this.options.context &&
404
400
  r.tool === tool && r.operationFingerprint === operationFingerprint && r.timestamp <= now);
405
- if (input.outcome === "succeeded" && (!prior || recovered.has(prior.fingerprint))) {
406
- if (pruned || issues(journal.losses).some(i => i !== "retention-loss")) atomic(join(dir, "events.jsonl"), encode(journal, key));
407
- if (issues(journal.losses).length) this.report(new Error("Diagnostics collection has gaps."));
408
- return;
401
+ if (duplicate || (input.outcome === "succeeded" && (!prior || recovered.has(prior.fingerprint)))) {
402
+ if (pruned || journal.needsRepair) atomic(join(dir, "events.jsonl"), encode(journal, key));
403
+ return journal.needsRepair;
409
404
  }
410
405
  const backend = imported?.value.backend ?? this.options.backend();
411
406
  const version = imported?.value.version ?? this.options.version;
@@ -425,8 +420,9 @@ export class SandboxDiagnostics {
425
420
  journal.records.push(record);
426
421
  retain(journal, key, now);
427
422
  atomic(join(dir, "events.jsonl"), encode(journal, key));
428
- if (before !== JSON.stringify(journal.losses) || journal.losses.malformed || journal.losses.tampered) this.report(new Error("Diagnostics collection has gaps."));
423
+ return journal.needsRepair;
429
424
  });
425
+ if (repaired) this.report(new Error("Diagnostics collection has gaps."));
430
426
  } catch (error) { this.report(this.options.relay || imported ? new Error("Diagnostics collection has gaps.") : error); }
431
427
  }
432
428
  }
@@ -32,7 +32,7 @@ The API is `runtime-client/src/runtime/client.mjs`, exporting `ensureRuntime`.
32
32
  - Durable logs, result retrieval, and [failure observations](docs/failure-observations.md) independent of lifecycle status. A live child handles its own tool errors; the parent is woken only for actionable incidents, and children can classify handled failures with `failure_disposition`.
33
33
  - Live background-work navigator for active runs.
34
34
  - Git writers start in separate Clones by default. **Git workspace** in `/subagents settings` also offers Worktree. Results carry the working directory or a recoverable copy, including incomplete work. [Workspace recovery](docs/usage.md#git-workspaces)
35
- - Harness-owned run timing: every run gets independent factual alerts for a tool call left open (5 min) and for no progress (10 min), plus a 60-minute hard timeout. Choose a duration or **No limit** under **Run timeout** in `/subagents settings`. Soft deadlines remain opt-in. Configure per spawn with `deadline_minutes`, `grace_minutes`, `max_minutes`, `tool_wait_minutes`, `stuck_minutes`, globally in `config.json` / `PI_SUBAGENT_*_MINUTES`, or in `/subagents settings`. See [usage notes](docs/usage.md#run-timing-deadline-ceiling-tool-wait-stuck).
35
+ - Harness-owned run timing: every run gets independent factual alerts for a tool call left open (5 min) and for no progress (10 min), plus a 60-minute hard timeout. Choose a duration or **24 hours** under **Run timeout** in `/subagents settings`. Soft deadlines remain opt-in. Configure per spawn with `deadline_minutes`, `grace_minutes`, `max_minutes`, `tool_wait_minutes`, `stuck_minutes`, globally in `config.json` / `PI_SUBAGENT_*_MINUTES`, or in `/subagents settings`. See [usage notes](docs/usage.md#run-timing-deadline-ceiling-tool-wait-stuck).
36
36
 
37
37
  Every single or batch launch automatically joins one shared supervision watcher in the
38
38
  foreground Pi process. The last active run's exit or stop tears it down; a later
@@ -97,7 +97,7 @@ Linux confinement requires a usable `bubblewrap` backend and Pi SDK 0.82.1 or ne
97
97
  The user config sets `delegationMode` to `manual`, `adaptive` (default), or
98
98
  `coordinator`. `/subagents settings` (or `/subagents`) opens a settings page
99
99
  for delegation mode, the concurrent-subagent cap (default 6), and Git workspace
100
- (Clone or Worktree). Run timeout supports a duration or **No limit**. The
100
+ (Clone or Worktree). Run timeout supports a duration or **24 hours**. The
101
101
  tool-wait alert (default 5 minutes) and no-progress alert (default 10 minutes)
102
102
  have separate intervals. Enter `0` to turn an alert off. Skill exposure cycles between Discover automatically and No skill
103
103
  catalog. The Selected skills row opens the same searchable checkbox picker used
@@ -1,7 +1,7 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/cleanup.ts. Do not edit directly.
2
2
  import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, } from "node:fs";
3
3
  import { join, relative, sep } from "node:path";
4
- import { ABANDONED_LAUNCH_GRACE_MS, abandonedLaunchRecord, baseDir, listMetas, observeArchivePublication, ownedByThisParent, orphanedTaskRuntimeProvenance, processStartToken, purgeAbandonedLaunch, readMeta, removeMetaArtifacts, removeRunDirectory, removeTaskRuntimeProvenance, runDir, listPendingParkedRuns, } from "./registry.domain.mjs";
4
+ import { ABANDONED_LAUNCH_GRACE_MS, abandonedLaunchRecord, baseDir, launchAttemptInProgress, listMetas, observeArchivePublication, ownedByThisParent, orphanedTaskRuntimeProvenance, processStartToken, purgeAbandonedLaunch, readMeta, removeMetaArtifacts, removeRunDirectory, removeTaskRuntimeProvenance, runDir, listPendingParkedRuns, } from "./registry.domain.mjs";
5
5
  import { ConversationBusyError, ConversationLockUnavailableError, conversationLeaseDir, readConversationLease, readRetention, retainedRunIds, retainedSessionIds, withConversationMutation, } from "./continuation.domain.mjs";
6
6
  import { processExists } from "./spawn.domain.mjs";
7
7
  import { archiveCompletedAttempt, archivePublicationPending, listArchivedAttempts } from "./session-store.domain.mjs";
@@ -108,6 +108,9 @@ function safeStatMtime(path) {
108
108
  /** A metadata-less run directory, with its provenance record (#325). */
109
109
  function removeRun(id, errors) {
110
110
  try {
111
+ // A concurrent launch publishes its claim before metadata and drops it after publication.
112
+ if (launchAttemptInProgress(id) || readMeta(id))
113
+ return false;
111
114
  removeRunDirectory(id);
112
115
  return true;
113
116
  }
@@ -777,7 +780,7 @@ export function enforceRegistrySizeCapOnce(options = {}) {
777
780
  // the shortfall it reports stay honest.
778
781
  const keptBytes = plan.keptBytes + retainedBytes;
779
782
  try {
780
- writeCleanupState({ ...state, lastSizeSweepAt: now });
783
+ writeCleanupState({ ...state, lastSizeSweepAt: options.now ?? Date.now() });
781
784
  }
782
785
  catch (err) {
783
786
  errors.push(`${cleanupStatePath()}: ${err instanceof Error ? err.message : String(err)}`);
@@ -11,6 +11,7 @@ import { join, relative, sep } from "node:path";
11
11
  import { ABANDONED_LAUNCH_GRACE_MS,
12
12
  abandonedLaunchRecord,
13
13
  baseDir,
14
+ launchAttemptInProgress,
14
15
  listMetas,
15
16
  observeArchivePublication,
16
17
  ownedByThisParent,
@@ -236,6 +237,8 @@ function safeStatMtime(path: string): number | undefined {
236
237
  /** A metadata-less run directory, with its provenance record (#325). */
237
238
  function removeRun(id: string, errors: string[]): boolean {
238
239
  try {
240
+ // A concurrent launch publishes its claim before metadata and drops it after publication.
241
+ if (launchAttemptInProgress(id) || readMeta(id)) return false;
239
242
  removeRunDirectory(id);
240
243
  return true;
241
244
  } catch (err) {
@@ -977,7 +980,7 @@ export function enforceRegistrySizeCapOnce(options: SizeCapOptions = {}): SizeCa
977
980
  const keptBytes = plan.keptBytes + retainedBytes;
978
981
 
979
982
  try {
980
- writeCleanupState({ ...state, lastSizeSweepAt: now });
983
+ writeCleanupState({ ...state, lastSizeSweepAt: options.now ?? Date.now() });
981
984
  } catch (err) {
982
985
  errors.push(`${cleanupStatePath()}: ${err instanceof Error ? err.message : String(err)}`);
983
986
  }
@@ -1,4 +1,5 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/index.ts. Do not edit directly.
2
+ import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.domain.mjs";
2
3
  import { shouldRestoreWorkObservation } from "./shared-work-client.mjs";
3
4
  import { appendTimingWake, removeTimingReceipt, receiptTimingWake, timingWakeReceipt } from "./timing-notifications.domain.mjs";
4
5
  import { captureLaunchContext } from "./launch-context.domain.mjs";
@@ -44,8 +45,9 @@ import { ORDINARY_TOOL_PROVIDERS, activeChildProviders, ordinaryChildConfig, add
44
45
  import { createSubagentSettingsPage } from "./settings-page.domain.mjs";
45
46
  import { deliverSubagentPrompt, effectiveSubagentSettings, subagentSettingsTool } from "./effective-settings.domain.mjs";
46
47
  import { STEER_FILE_ENV, readSteerReceipt } from "./child-steer.domain.mjs";
47
- import { continuationTimingParams, decideTiming, describeTiming, DEFAULT_TIMING_MINUTES, emptyProgress, foldProgress, formatTimingLimits, isTimingMinutes, isProgressRelevantLine, resolveRunTiming, steerText, stuckAlertText, TIMING_ENV, timingParameterSchemas, toolWaitAlertText, validatedTimingMinutes, } from "./timing.domain.mjs";
48
+ import { continuationTimingParams, configuredMaxMinutes, decideTiming, describeTiming, DEFAULT_TIMING_MINUTES, emptyProgress, foldProgress, formatTimingLimits, isTimingMinutes, isProgressRelevantLine, resolveRunTiming, steerText, stuckAlertText, TIMING_ENV, timingParameterSchemas, toolWaitAlertText, validatedTimingMinutes, } from "./timing.domain.mjs";
48
49
  import { readAppendedLines } from "./log-cursor.domain.mjs";
50
+ import { launchWorkflowAssignment } from "./workflow-assignment.domain.mjs";
49
51
  import { DELEGATION_MODES, DELEGATION_MODE_REQUEST, isDelegationMode, normalizeDelegationMode } from "./delegation.domain.mjs";
50
52
  import { resolveExtensions, extensionArgs } from "./extensions.domain.mjs";
51
53
  import { prepareTaskRuntime, applyDirectApplicationLoadout, DEFAULT_TASK_PERMISSIONS, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.domain.mjs";
@@ -1156,7 +1158,12 @@ function stopForTiming(pi, id, reason, now) {
1156
1158
  */
1157
1159
  function enforceTiming(pi, meta, now) {
1158
1160
  const timing = meta.timing;
1159
- if (!timing || timing.stopReason)
1161
+ if (!timing)
1162
+ return false;
1163
+ if ((meta.status === "running" || meta.status === "orphaned") && now >= (timing.lifetimeAt ?? taskDeadline(meta.startedAt))) {
1164
+ return stopForTiming(pi, meta.id, "ceiling", now);
1165
+ }
1166
+ if (timing.stopReason)
1160
1167
  return false;
1161
1168
  // The ceiling also bounds an orphaned run (child gone, its process group still alive).
1162
1169
  if (meta.status === "orphaned") {
@@ -1656,10 +1663,7 @@ function navigatorCloseRun(id) {
1656
1663
  if (outcome.action === "dismissed" || outcome.action === "stopped-and-dismissed")
1657
1664
  pendingNavigatorDismissals.add(id);
1658
1665
  // A closed row is off the hot path: release its caches and retained events.
1659
- spendCache.delete(id);
1660
- healthLogCache.delete(id);
1661
- resetChildEventLogCursor(id);
1662
- resetParseRunCursor(id);
1666
+ forgetRunCaches(id);
1663
1667
  syncHealthTicker();
1664
1668
  // Close stops (or log-finalizes) the run, which is a terminal transition:
1665
1669
  // queue its one completion callback so no terminal state is silent (#624).
@@ -2038,6 +2042,12 @@ function resolvePiBinary() {
2038
2042
  }
2039
2043
  return cachedPi;
2040
2044
  }
2045
+ function forgetRunCaches(id) {
2046
+ spendCache.delete(id);
2047
+ healthLogCache.delete(id);
2048
+ resetChildEventLogCursor(id);
2049
+ resetParseRunCursor(id);
2050
+ }
2041
2051
  function prepareLaunchWorkspace(options, isolated) {
2042
2052
  const built = import.meta.url.endsWith(".domain.mjs");
2043
2053
  const entry = new URL("./workspace-prepare-worker.mjs", import.meta.url);
@@ -2488,13 +2498,13 @@ export default function (pi, managed) {
2488
2498
  const defaults = resolveRunTiming({ settings: cfg, env: process.env, startedAt: 0 });
2489
2499
  const minutes = (ms) => ms === undefined ? 0 : ms / 60_000;
2490
2500
  return {
2491
- maxMinutes: minutes(effective.ceilingAt),
2501
+ maxMinutes: configuredMaxMinutes(sessionTimeout, timingSettingsFor(cfg), process.env),
2492
2502
  toolWaitMinutes: minutes(effective.toolWaitMs),
2493
2503
  stuckMinutes: minutes(effective.stuckMs),
2494
2504
  timeoutSource: timeoutSource(),
2495
2505
  toolWaitSource: sourceFor("toolWaitMinutes"),
2496
2506
  stuckSource: sourceFor("stuckMinutes"),
2497
- defaultMaxMinutes: minutes(defaults.ceilingAt),
2507
+ defaultMaxMinutes: configuredMaxMinutes({}, cfg, process.env),
2498
2508
  defaultToolWaitMinutes: minutes(defaults.toolWaitMs),
2499
2509
  defaultStuckMinutes: minutes(defaults.stuckMs),
2500
2510
  };
@@ -2777,13 +2787,13 @@ export default function (pi, managed) {
2777
2787
  ctx = captureLaunchContext(ctx);
2778
2788
  restoreDelegationMode(ctx);
2779
2789
  await workerOperations.start();
2780
- return definition.execute(key, params, signal, onUpdate, ctx);
2790
+ return launchWorkflowAssignment(pi, ctx, key, params, args => definition.execute(key, args, signal, onUpdate, ctx));
2781
2791
  } } : { ...definition, async execute(key, params, signal, _onUpdate, ctx) {
2782
2792
  ctx = captureLaunchContext(ctx);
2783
2793
  catalogHostFrom(ctx);
2784
2794
  const { submitManagedLaunch } = await import("./managed-launch-client.domain.mjs");
2785
2795
  void activateWorkObservation();
2786
- return await observeNavigatorLaunch(ctx, "subagents", key, "Subagent launch", () => submitManagedLaunch(pi, ctx, key, definition.name, params, signal));
2796
+ return launchWorkflowAssignment(pi, ctx, key, params, async (args) => await observeNavigatorLaunch(ctx, "subagents", key, "Subagent launch", () => submitManagedLaunch(pi, ctx, key, definition.name, args, signal)));
2787
2797
  } });
2788
2798
  };
2789
2799
  announceExecutionAdapter(pi, {
@@ -2949,20 +2959,17 @@ export default function (pi, managed) {
2949
2959
  model = parsed.model;
2950
2960
  thinking = parsed.thinking;
2951
2961
  }
2952
- // Best-effort daily hygiene for durable tmp state. The marker makes
2953
- // this effectively free after the first subagent launch each day.
2954
- // Resume has already validated this history. Retiring it here would let
2955
- // native --session create an empty replacement before the child runs.
2956
- if (!resume)
2957
- runDailyCleanupOnce({ config: cfg });
2958
- // Age retires history; this bounds the peak one busy day can reach.
2959
- // Rate-limited inside cleanup.ts, and never on the UI hot path.
2960
- const capped = resume ? { removed: [] } : enforceRegistrySizeCapOnce({ config: cfg });
2961
- for (const id of capped.removed) {
2962
- spendCache.delete(id);
2963
- healthLogCache.delete(id);
2964
- resetChildEventLogCursor(id);
2965
- resetParseRunCursor(id);
2962
+ // Continuations revalidate and lease their saved history. Only fresh launches request maintenance.
2963
+ if (!resume) {
2964
+ if (managed) {
2965
+ const { cleanupTerminalRunRetentionMs, cleanupSessionRetentionMs, maxRegistryBytes } = cfg;
2966
+ managed.scheduleRegistryCleanup({ cleanupTerminalRunRetentionMs, cleanupSessionRetentionMs, maxRegistryBytes }, forgetRunCaches);
2967
+ }
2968
+ else {
2969
+ runDailyCleanupOnce({ config: cfg });
2970
+ for (const removed of enforceRegistrySizeCapOnce({ config: cfg }).removed)
2971
+ forgetRunCaches(removed);
2972
+ }
2966
2973
  }
2967
2974
  const callbackOrigin = internal?.parkOwner
2968
2975
  ? { cwd: internal.parkOwner.workspace, sessionId: internal.parkOwner.sessionId }
@@ -3505,6 +3512,11 @@ export default function (pi, managed) {
3505
3512
  trustedExtensions: resume?.recipe.trustedExtensions ?? taskTools?.trusted.map(({ name, package: owner, loadPath }) => ({ name, package: owner, loadPath })),
3506
3513
  });
3507
3514
  const startedAt = Date.now();
3515
+ const timing = resolveRunTiming({ params: launchTimingParams(p), settings: timingSettingsFor(cfg), env: process.env, startedAt });
3516
+ if (internal?.resumeWait && resume) {
3517
+ timing.lifetimeAt = resume.prior.timing?.lifetimeAt ?? taskDeadline(resume.prior.startedAt);
3518
+ timing.ceilingAt = Math.min(timing.lifetimeAt, resume.prior.timing?.ceilingAt ?? Infinity, timing.ceilingAt);
3519
+ }
3508
3520
  const meta = {
3509
3521
  assignment,
3510
3522
  outcomeSupport: { version: 1, available: Boolean(assignment), ...(!assignment ? { reason: "Legacy host has no verified parent session/transcript; durable assignment delivery is unavailable." } : {}) },
@@ -3554,9 +3566,12 @@ export default function (pi, managed) {
3554
3566
  tools: bridgePlan.tools,
3555
3567
  },
3556
3568
  } : {}),
3557
- timing: resolveRunTiming({ params: launchTimingParams(p), settings: timingSettingsFor(cfg), env: process.env, startedAt }),
3569
+ timing,
3558
3570
  };
3559
3571
  const dispatchGuard = await internal?.beforeSpawn?.({ runId: id, permissionPlan });
3572
+ if (internal?.resumeWait && Date.now() >= timing.ceilingAt) {
3573
+ throw new PreSpawnResumeError("The parked task reached its execution time limit before dispatch.");
3574
+ }
3560
3575
  if (isolated)
3561
3576
  markWorkspaceWriter(isolated, id);
3562
3577
  const managedEnv = managed?.beforeSpawn({ id, sessionId, lease: lease.token, leasePath: lease.path,
@@ -3723,7 +3738,7 @@ export default function (pi, managed) {
3723
3738
  if (!prior)
3724
3739
  throw new PreSpawnResumeError(`Cannot resume ${input.park.runId}: its run record is gone.`);
3725
3740
  const now = Date.now();
3726
- if (prior.timing?.deadlineAt !== undefined && now >= prior.timing.deadlineAt) {
3741
+ if (now >= taskDeadline(prior.startedAt, prior.timing?.ceilingAt) || (prior.timing?.deadlineAt !== undefined && now >= prior.timing.deadlineAt)) {
3727
3742
  throw new PreSpawnResumeError(`Cannot resume ${input.park.runId}: its assignment deadline passed while it was parked. The wait is held for the owner.`);
3728
3743
  }
3729
3744
  let plan;
@@ -3925,7 +3940,7 @@ export default function (pi, managed) {
3925
3940
  "The tools param is both the tool allowlist AND what determines which extensions load in the child (e.g. tools='read,bash,web_fetch' loads only the web-tools package). Ask for the tools the task needs and nothing more; clean:true gives a built-ins-only child. When the task already names its SKILL.md by path, pass skills with those absolute paths (or [] for none) so the child does not advertise the whole skills catalog. Without an agent or role, pick a model with the model param (e.g. 'xai/grok-4.5@high'); providerless model patterns are resolved by Pi, while provider/model is deterministic and loads mapped provider extensions.",
3926
3941
  ...CATALOG_GUIDELINES,
3927
3942
  "Subagent sandboxing defaults to off. Human settings in /sandbox control file, credential-file, command, and network permissions; sandbox:false cannot override an enabled human profile. Set sandbox:true to request kernel confinement, including without published settings. Set callback:false to finish quietly — then read the result on demand via subagent_result.",
3928
- "Every launch automatically joins one shared harness-owned watcher, including batch launches; it stops when the last active run ends. Do not start a separate heartbeat or background watcher for subagents. A tool call still open for tool_wait_minutes (default 5) or no progress for stuck_minutes (default 10) sends one factual alert; these alerts never stop, cancel, or restart the run. Hard timeouts default to 60 minutes; max_minutes overrides that default (0 disables). Soft deadlines remain opt-in for work with a real wall-clock bound: deadline_minutes steers the child to wrap up and later stops it after grace_minutes, while max_minutes stops it without grace. Do not set elapsed-time limits merely because a task may take a while; use them only when the work needs a real wall-clock bound.",
3943
+ "Every launch automatically joins one shared harness-owned watcher, including batch launches; it stops when the last active run ends. Do not start a separate heartbeat or background watcher for subagents. A tool call still open for tool_wait_minutes (default 5) or no progress for stuck_minutes (default 10) sends one factual alert; these alerts never stop, cancel, or restart the run. Hard timeouts default to 60 minutes; max_minutes overrides that default up to 24 hours (0 selects the maximum). Soft deadlines remain opt-in for work with a real wall-clock bound: deadline_minutes steers the child to wrap up and later stops it after grace_minutes, while max_minutes stops it without grace. Do not set elapsed-time limits merely because a task may take a while; use them only when the work needs a real wall-clock bound.",
3929
3944
  "Git writers receive separate checkouts by default. /subagents settings selects Clone or Worktree. isolation:false selects the live checkout. A sandboxed Worktree can return its files or explicitly continue in a verified Clone with recover_in_clone:true.",
3930
3945
  "Saved conversations persist automatically. To continue a completed or stopped worker in its own history, call subagent_spawn with session_id (the native session id reported for the saved conversation) and the new feedback as prompt. Omit session_id for a brand-new conversation.",
3931
3946
  "On a continuation, pass prompt, session_id, and only optional model, thinking, callback, or timing overrides. Launch-only options (name, agent, role, alias, tools, exclude_tools, skills, clean, sandbox, sandbox_dir, cwd, git_clone_workspace, approve, allow_nested) keep the saved recipe; repeat them only with the same value, otherwise the launch is refused.",
@@ -3933,6 +3948,9 @@ export default function (pi, managed) {
3933
3948
  ],
3934
3949
  parameters: Type.Object({
3935
3950
  prompt: Type.String({ description: "The task for the subagent. This is the only context it gets — be self-contained. On a continuation this is the next user turn; the original task and role stay in saved history." }),
3951
+ workflow: Type.Optional(Type.Object({
3952
+ runId: Type.String(), step: Type.String(),
3953
+ }, { description: "Bind this launch to a ready dynamic workflow item. Supply its selected role or agent and inherit catalog skills." })),
3936
3954
  session_name: Type.Optional(Type.String({ description: "Exact name of one saved conversation in the current folder and descendants. Alternative to session_id. Duplicate names report matching session ids instead of choosing a conversation." })),
3937
3955
  session_id: Type.Optional(Type.String({ description: "Native session id of a saved conversation to continue (reported for every launch and attempt). Omit to start a new conversation. A continuation gets a new run id but keeps this session id, history, workspace, and frozen launch recipe." })),
3938
3956
  name: Type.Optional(Type.String({ description: "Short label for the run (e.g. 'reviewer'). Ignored when agent or role is set, except as the direct-role alias when alias is omitted." })),
@@ -4461,7 +4479,7 @@ export default function (pi, managed) {
4461
4479
  : skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
4462
4480
  const timing = timingState();
4463
4481
  ctx.ui.notify(`Delegation mode: ${activeDelegationMode()}. Concurrent subagents: ${activeConcurrencyCap()}. ` +
4464
- `Run timeout: ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "No limit"}. Tool-wait alert: ${timing.toolWaitMinutes} min. ` +
4482
+ `Run timeout: ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "24 hours"}. Tool-wait alert: ${timing.toolWaitMinutes} min. ` +
4465
4483
  `No-progress alert: ${timing.stuckMinutes} min. Skills: ${skillChoice}. ` +
4466
4484
  `Use /subagents mode <mode>, cap <number>, tool-wait <minutes>, stuck <minutes>, or settings; /subagents save persists them.`, "info");
4467
4485
  }
@@ -4553,7 +4571,7 @@ export default function (pi, managed) {
4553
4571
  : skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
4554
4572
  const timing = timingState();
4555
4573
  if (ctx.hasUI && !(await ctx.ui.confirm("Save subagent defaults?", `Future sessions will start in ${activeDelegationMode()} with a cap of ${activeConcurrencyCap()}, ` +
4556
- `run timeout ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "No limit"}, tool-wait alert ${timing.toolWaitMinutes} min, ` +
4574
+ `run timeout ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "24 hours"}, tool-wait alert ${timing.toolWaitMinutes} min, ` +
4557
4575
  `no-progress alert ${timing.stuckMinutes} min, and ${skillChoice}.`))) {
4558
4576
  ctx.ui.notify("Subagent defaults unchanged.", "info");
4559
4577
  return;