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.ts";
17
18
  import { randomUUID } from "node:crypto";
18
19
  import { StoreError } from "./errors.ts";
19
20
  import {
@@ -606,41 +607,46 @@ export function cancelWait(ctx: StoreContext, input: CancelWaitInput): CancelWai
606
607
  );
607
608
  }
608
609
  assertExpectedEpoch(wait, expectedCancelEpoch);
609
- const at = ctx.now();
610
- run(
611
- ctx,
612
- "UPDATE waits SET phase = 'cancelled', phase_reason = ?, cancel_epoch = cancel_epoch + 1, updated_at = ? WHERE wait_id = ? AND generation = ?",
613
- reason,
614
- at,
615
- waitId,
616
- generation,
617
- );
618
- const activeClaimRows = getRows(
619
- ctx,
620
- "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')",
621
- waitId,
622
- generation,
623
- );
624
- const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
625
- run(
626
- ctx,
627
- `UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
628
- WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`,
629
- at,
630
- reason,
631
- waitId,
632
- generation,
633
- );
634
- const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
635
- releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
636
- return {
637
- wait: requireWait(ctx, waitId, generation),
638
- invalidatedClaimIds,
639
- voidedOutboxIds,
640
- };
610
+ return cancelGeneration(ctx, waitId, generation, reason);
641
611
  });
642
612
  }
643
613
 
614
+ /** Caller holds the write transaction and has selected a nonterminal generation. */
615
+ export function cancelGeneration(ctx: StoreContext, waitId: string, generation: number, reason: string): CancelWaitResult {
616
+ const at = ctx.now();
617
+ run(
618
+ ctx,
619
+ "UPDATE waits SET phase = 'cancelled', phase_reason = ?, cancel_epoch = cancel_epoch + 1, updated_at = ? WHERE wait_id = ? AND generation = ?",
620
+ reason,
621
+ at,
622
+ waitId,
623
+ generation,
624
+ );
625
+ const activeClaimRows = getRows(
626
+ ctx,
627
+ "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')",
628
+ waitId,
629
+ generation,
630
+ );
631
+ const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
632
+ run(
633
+ ctx,
634
+ `UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
635
+ WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`,
636
+ at,
637
+ reason,
638
+ waitId,
639
+ generation,
640
+ );
641
+ const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
642
+ releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
643
+ return {
644
+ wait: requireWait(ctx, waitId, generation),
645
+ invalidatedClaimIds,
646
+ voidedOutboxIds,
647
+ };
648
+ }
649
+
644
650
  // ---- resume claims ------------------------------------------------------
645
651
 
646
652
  export function claimResume(ctx: StoreContext, input: ClaimResumeInput): ResumeClaimResult {
@@ -653,6 +659,7 @@ export function claimResume(ctx: StoreContext, input: ClaimResumeInput): ResumeC
653
659
  return ctx.transaction(() => {
654
660
  assertCurrentGeneration(ctx, waitId, generation);
655
661
  const wait = requireWait(ctx, waitId, generation);
662
+ if (ctx.now() >= taskDeadline(wait.createdAt)) throw new StoreError("wait-phase", "The 24-hour wait lifetime has expired.");
656
663
  const active = getRows(
657
664
  ctx,
658
665
  "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')",
@@ -735,6 +742,7 @@ export function publishResumeAttempt(
735
742
  return ctx.transaction(() => {
736
743
  assertCurrentGeneration(ctx, waitId, generation);
737
744
  const wait = requireWait(ctx, waitId, generation);
745
+ if (ctx.now() >= taskDeadline(wait.createdAt)) throw new StoreError("wait-phase", "The 24-hour wait lifetime has expired.");
738
746
  const claim = requireClaim(ctx, claimId);
739
747
  if (claim.waitId !== waitId || claim.generation !== generation) {
740
748
  throw new StoreError(
@@ -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,6 +32,7 @@ const here = dirname(fileURLToPath(import.meta.url));
32
32
  const outputDir = process.argv[2] ? resolve(process.argv[2]) : join(here, "generated");
33
33
  /** Runtime entry first; everything else is reachable from it. */
34
34
  const CLOSURE = [
35
+ { source: join(here, "..", "shared-operation-coordinator", "src", "task-lifetime.ts"), out: "task-lifetime.mjs" },
35
36
  { source: join(here, "runner.ts"), out: "runner.mjs" },
36
37
  { source: join(here, "store.ts"), out: "store.mjs" },
37
38
  { source: join(here, "types.ts"), out: "types.mjs" },
@@ -30,6 +30,7 @@
30
30
  * - a stop or timeout is not published until the group is proven empty (or the
31
31
  * cleanup deadline discloses it as unproven).
32
32
  */
33
+ import { taskDeadline } from "./task-lifetime.mjs";
33
34
  import { spawn } from "node:child_process";
34
35
  import { closeSync, openSync, realpathSync } from "node:fs";
35
36
  import { join, resolve } from "node:path";
@@ -590,20 +591,20 @@ async function waitForNextCheck(ctx, delayMs) {
590
591
  }
591
592
  async function runWatch(ctx) {
592
593
  const intervalMs = ctx.launch.intervalMs ?? DEFAULT_WATCH_INTERVAL_MS;
593
- const deadlineAt = ctx.launch.taskTimeoutMs === undefined ? undefined : ctx.startedAt + ctx.launch.taskTimeoutMs;
594
+ const deadlineAt = taskDeadline(ctx.launch.createdAt, ctx.launch.taskTimeoutMs === undefined ? undefined : ctx.startedAt + ctx.launch.taskTimeoutMs);
594
595
  while (!ctx.finalized) {
595
596
  if (observeStop(ctx)) {
596
597
  finalize(ctx, cancelledTerminal("stopped by request", "none"));
597
598
  return;
598
599
  }
599
- if (deadlineAt !== undefined && Date.now() >= deadlineAt) {
600
+ if (Date.now() >= deadlineAt) {
600
601
  finalize(ctx, { status: "timed_out", reason: "timeout", exitCode: null, signal: null, timedOut: true, groupCleanup: "none" });
601
602
  return;
602
603
  }
603
- const remaining = deadlineAt === undefined ? undefined : Math.max(1, deadlineAt - Date.now());
604
+ const remaining = Math.max(1, deadlineAt - Date.now());
604
605
  const capMs = ctx.launch.commandTimeoutMs;
605
- const pollTimeoutMs = capMs === undefined ? remaining : remaining === undefined ? capMs : Math.min(remaining, capMs);
606
- const capBound = capMs !== undefined && (remaining === undefined || capMs < remaining);
606
+ const pollTimeoutMs = capMs === undefined ? remaining : Math.min(remaining, capMs);
607
+ const capBound = capMs !== undefined && capMs < remaining;
607
608
  const checkStartedAt = Date.now();
608
609
  const outcome = await runChild(ctx, {
609
610
  argv: ctx.launch.command.argv,
@@ -735,9 +736,13 @@ async function runWatch(ctx) {
735
736
  }
736
737
  async function runProcess(ctx) {
737
738
  const { argv, cwd } = ctx.launch.command;
738
- const deadlineAt = ctx.launch.taskTimeoutMs === undefined ? undefined : ctx.startedAt + ctx.launch.taskTimeoutMs;
739
+ const deadlineAt = taskDeadline(ctx.launch.createdAt, ctx.launch.taskTimeoutMs === undefined ? undefined : ctx.startedAt + ctx.launch.taskTimeoutMs);
740
+ if (Date.now() >= deadlineAt) {
741
+ finalize(ctx, { status: "timed_out", reason: "timeout", exitCode: null, signal: null, timedOut: true, groupCleanup: "none" });
742
+ return;
743
+ }
739
744
  const capAt = ctx.launch.commandTimeoutMs === undefined ? undefined : ctx.startedAt + ctx.launch.commandTimeoutMs;
740
- const capBound = capAt !== undefined && (deadlineAt === undefined || capAt <= deadlineAt);
745
+ const capBound = capAt !== undefined && capAt <= deadlineAt;
741
746
  const killAt = capBound ? capAt : deadlineAt;
742
747
  const outcome = await runChild(ctx, {
743
748
  argv,
@@ -0,0 +1,9 @@
1
+ // Generated fixed launch domain from packages/pi-better-background-tasks/src/supervisor/generated/task-lifetime.mjs. Do not edit directly.
2
+ // Generated by src/supervisor/emit-runner.mjs from the TypeScript source.
3
+ // Do not edit: change the source and re-run the emitter (a drift test enforces this).
4
+ // Generated from packages/operation-coordinator/src/task-lifetime.ts. Do not edit directly.
5
+ /** Absolute wall-clock limit, including time spent waiting for a runner. */
6
+ export const MAX_TASK_LIFETIME_MS = 24 * 60 * 60 * 1000;
7
+ export function taskDeadline(startedAt, requestedDeadline) {
8
+ return Math.min(startedAt + MAX_TASK_LIFETIME_MS, requestedDeadline ?? Infinity);
9
+ }
@@ -28,6 +28,7 @@
28
28
  * - a stop or timeout is not published until the group is proven empty (or the
29
29
  * cleanup deadline discloses it as unproven).
30
30
  */
31
+ import { taskDeadline } from "../shared-operation-coordinator/src/task-lifetime.domain.mjs";
31
32
  import { spawn } from "node:child_process";
32
33
  import { closeSync, openSync, realpathSync } from "node:fs";
33
34
  import { join, resolve } from "node:path";
@@ -588,20 +589,20 @@ async function waitForNextCheck(ctx, delayMs) {
588
589
  }
589
590
  async function runWatch(ctx) {
590
591
  const intervalMs = ctx.launch.intervalMs ?? DEFAULT_WATCH_INTERVAL_MS;
591
- const deadlineAt = ctx.launch.taskTimeoutMs === undefined ? undefined : ctx.startedAt + ctx.launch.taskTimeoutMs;
592
+ const deadlineAt = taskDeadline(ctx.launch.createdAt, ctx.launch.taskTimeoutMs === undefined ? undefined : ctx.startedAt + ctx.launch.taskTimeoutMs);
592
593
  while (!ctx.finalized) {
593
594
  if (observeStop(ctx)) {
594
595
  finalize(ctx, cancelledTerminal("stopped by request", "none"));
595
596
  return;
596
597
  }
597
- if (deadlineAt !== undefined && Date.now() >= deadlineAt) {
598
+ if (Date.now() >= deadlineAt) {
598
599
  finalize(ctx, { status: "timed_out", reason: "timeout", exitCode: null, signal: null, timedOut: true, groupCleanup: "none" });
599
600
  return;
600
601
  }
601
- const remaining = deadlineAt === undefined ? undefined : Math.max(1, deadlineAt - Date.now());
602
+ const remaining = Math.max(1, deadlineAt - Date.now());
602
603
  const capMs = ctx.launch.commandTimeoutMs;
603
- const pollTimeoutMs = capMs === undefined ? remaining : remaining === undefined ? capMs : Math.min(remaining, capMs);
604
- const capBound = capMs !== undefined && (remaining === undefined || capMs < remaining);
604
+ const pollTimeoutMs = capMs === undefined ? remaining : Math.min(remaining, capMs);
605
+ const capBound = capMs !== undefined && capMs < remaining;
605
606
  const checkStartedAt = Date.now();
606
607
  const outcome = await runChild(ctx, {
607
608
  argv: ctx.launch.command.argv,
@@ -733,9 +734,13 @@ async function runWatch(ctx) {
733
734
  }
734
735
  async function runProcess(ctx) {
735
736
  const { argv, cwd } = ctx.launch.command;
736
- const deadlineAt = ctx.launch.taskTimeoutMs === undefined ? undefined : ctx.startedAt + ctx.launch.taskTimeoutMs;
737
+ const deadlineAt = taskDeadline(ctx.launch.createdAt, ctx.launch.taskTimeoutMs === undefined ? undefined : ctx.startedAt + ctx.launch.taskTimeoutMs);
738
+ if (Date.now() >= deadlineAt) {
739
+ finalize(ctx, { status: "timed_out", reason: "timeout", exitCode: null, signal: null, timedOut: true, groupCleanup: "none" });
740
+ return;
741
+ }
737
742
  const capAt = ctx.launch.commandTimeoutMs === undefined ? undefined : ctx.startedAt + ctx.launch.commandTimeoutMs;
738
- const capBound = capAt !== undefined && (deadlineAt === undefined || capAt <= deadlineAt);
743
+ const capBound = capAt !== undefined && capAt <= deadlineAt;
739
744
  const killAt = capBound ? capAt : deadlineAt;
740
745
  const outcome = await runChild(ctx, {
741
746
  argv,
@@ -28,6 +28,7 @@
28
28
  * cleanup deadline discloses it as unproven).
29
29
  */
30
30
 
31
+ import { taskDeadline } from "../shared-operation-coordinator/src/task-lifetime.ts";
31
32
  import { spawn } from "node:child_process";
32
33
  import { closeSync, openSync, realpathSync } from "node:fs";
33
34
  import { join, resolve } from "node:path";
@@ -692,20 +693,20 @@ async function waitForNextCheck(ctx: RunnerContext, delayMs: number): Promise<bo
692
693
 
693
694
  async function runWatch(ctx: RunnerContext): Promise<void> {
694
695
  const intervalMs = ctx.launch.intervalMs ?? DEFAULT_WATCH_INTERVAL_MS;
695
- const deadlineAt = ctx.launch.taskTimeoutMs === undefined ? undefined : ctx.startedAt + ctx.launch.taskTimeoutMs;
696
+ const deadlineAt = taskDeadline(ctx.launch.createdAt, ctx.launch.taskTimeoutMs === undefined ? undefined : ctx.startedAt + ctx.launch.taskTimeoutMs);
696
697
  while (!ctx.finalized) {
697
698
  if (observeStop(ctx)) {
698
699
  finalize(ctx, cancelledTerminal("stopped by request", "none"));
699
700
  return;
700
701
  }
701
- if (deadlineAt !== undefined && Date.now() >= deadlineAt) {
702
+ if (Date.now() >= deadlineAt) {
702
703
  finalize(ctx, { status: "timed_out", reason: "timeout", exitCode: null, signal: null, timedOut: true, groupCleanup: "none" });
703
704
  return;
704
705
  }
705
- const remaining = deadlineAt === undefined ? undefined : Math.max(1, deadlineAt - Date.now());
706
+ const remaining = Math.max(1, deadlineAt - Date.now());
706
707
  const capMs = ctx.launch.commandTimeoutMs;
707
- const pollTimeoutMs = capMs === undefined ? remaining : remaining === undefined ? capMs : Math.min(remaining, capMs);
708
- const capBound = capMs !== undefined && (remaining === undefined || capMs < remaining);
708
+ const pollTimeoutMs = capMs === undefined ? remaining : Math.min(remaining, capMs);
709
+ const capBound = capMs !== undefined && capMs < remaining;
709
710
  const checkStartedAt = Date.now();
710
711
  const outcome = await runChild(ctx, {
711
712
  argv: ctx.launch.command.argv,
@@ -838,9 +839,13 @@ async function runWatch(ctx: RunnerContext): Promise<void> {
838
839
 
839
840
  async function runProcess(ctx: RunnerContext): Promise<void> {
840
841
  const { argv, cwd } = ctx.launch.command;
841
- const deadlineAt = ctx.launch.taskTimeoutMs === undefined ? undefined : ctx.startedAt + ctx.launch.taskTimeoutMs;
842
+ const deadlineAt = taskDeadline(ctx.launch.createdAt, ctx.launch.taskTimeoutMs === undefined ? undefined : ctx.startedAt + ctx.launch.taskTimeoutMs);
843
+ if (Date.now() >= deadlineAt) {
844
+ finalize(ctx, { status: "timed_out", reason: "timeout", exitCode: null, signal: null, timedOut: true, groupCleanup: "none" });
845
+ return;
846
+ }
842
847
  const capAt = ctx.launch.commandTimeoutMs === undefined ? undefined : ctx.startedAt + ctx.launch.commandTimeoutMs;
843
- const capBound = capAt !== undefined && (deadlineAt === undefined || capAt <= deadlineAt);
848
+ const capBound = capAt !== undefined && capAt <= deadlineAt;
844
849
  const killAt = capBound ? capAt : deadlineAt;
845
850
 
846
851
  const outcome = await runChild(ctx, {
@@ -306,7 +306,7 @@ export interface SupervisorStartOptions {
306
306
  operationId?: string;
307
307
  /** Per-command cap; a watch applies it to every check. */
308
308
  commandTimeoutSeconds?: number;
309
- /** Whole-task deadline; `0` means none. A watch defaults to 15 minutes. */
309
+ /** Whole-task deadline; `0` uses the 24-hour maximum. A watch defaults to 15 minutes. */
310
310
  timeoutSeconds?: number;
311
311
  /** Watch cadence. Watch only; fractional values are allowed for tight checks. */
312
312
  intervalSeconds?: number;
@@ -1,4 +1,5 @@
1
1
  // Generated fixed launch domain from packages/pi-better-background-tasks/src/tools.ts. Do not edit directly.
2
+ import { TASK_TIMEOUT_HELP } from "./managed-authority.domain.mjs";
2
3
  import { Type } from "typebox";
3
4
  import { truncateToWidth as piTruncateToWidth, visibleWidth as piVisibleWidth, wrapTextWithAnsi as piWrapTextWithAnsi, } from "@earendil-works/pi-tui";
4
5
  import { advertiseBackgroundAdapter } from "./adapter-contract.domain.mjs";
@@ -68,7 +69,7 @@ const CommandFields = {
68
69
  env: Type.Optional(StringMap("Extra environment variables.")),
69
70
  max_log_bytes: Type.Optional(Type.Number({ description: "Maximum retained raw-log bytes. Default 4194304 (4 MiB). Older output is compacted while the task runs." })),
70
71
  callback: Type.Optional(Type.Boolean({ description: "Queue a follow-up when the task reaches a terminal state. Default true." })),
71
- timeout_seconds: Type.Optional(Type.Number({ description: "Optional whole-task timeout in seconds. Command watchers default to 900 seconds when omitted; pass 0 to disable. Spawned processes have no default timeout. When the Background tasks sandbox profile sets a command time limit, that cap applies to each actual command (and each watch check) independently: a smaller timeout_seconds still wins, and 0 does not disable the policy cap." })),
72
+ timeout_seconds: Type.Optional(Type.Number({ description: TASK_TIMEOUT_HELP })),
72
73
  ssh: Type.Optional(SshSchema),
73
74
  remote: Type.Optional(RemoteSchema),
74
75
  ...IntentFields,
@@ -327,7 +328,7 @@ export function registerTools(pi, runtime, refreshNavigator = refreshBackgroundT
327
328
  register({
328
329
  name: "bg_task_watch",
329
330
  label: "BG Watch",
330
- description: `Poll a command in the background until success_when, failure_when, or timeout matches. For remote work, prefer structured ssh: pass ssh:{host,user} and provide the remote command in command; each interval opens a direct one-shot SSH poll without tmux installation. For short synchronous remote commands that should return output now, use remote_bash from pi-better-ssh. Returns its task id once the first check finishes. ${WATCH_CHECK_GUIDANCE} Default timeout 900 seconds; pass timeout_seconds:0 to disable.`,
331
+ description: `Poll a command in the background until success_when, failure_when, or timeout matches. For remote work, prefer structured ssh: pass ssh:{host,user} and provide the remote command in command; each interval opens a direct one-shot SSH poll without tmux installation. For short synchronous remote commands that should return output now, use remote_bash from pi-better-ssh. Returns its task id once the first check finishes. ${WATCH_CHECK_GUIDANCE} Default timeout 900 seconds; pass timeout_seconds:0 to use the 24-hour maximum.`,
331
332
  promptGuidelines: BACKGROUND_ORCHESTRATION_GUIDELINES,
332
333
  parameters: WatchParams,
333
334
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
@@ -1,3 +1,4 @@
1
+ import { TASK_TIMEOUT_HELP } from "./managed-authority.js";
1
2
  import { Type } from "typebox";
2
3
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
4
  import {
@@ -96,7 +97,7 @@ const CommandFields = {
96
97
  env: Type.Optional(StringMap("Extra environment variables.")),
97
98
  max_log_bytes: Type.Optional(Type.Number({ description: "Maximum retained raw-log bytes. Default 4194304 (4 MiB). Older output is compacted while the task runs." })),
98
99
  callback: Type.Optional(Type.Boolean({ description: "Queue a follow-up when the task reaches a terminal state. Default true." })),
99
- timeout_seconds: Type.Optional(Type.Number({ description: "Optional whole-task timeout in seconds. Command watchers default to 900 seconds when omitted; pass 0 to disable. Spawned processes have no default timeout. When the Background tasks sandbox profile sets a command time limit, that cap applies to each actual command (and each watch check) independently: a smaller timeout_seconds still wins, and 0 does not disable the policy cap." })),
100
+ timeout_seconds: Type.Optional(Type.Number({ description: TASK_TIMEOUT_HELP })),
100
101
  ssh: Type.Optional(SshSchema),
101
102
  remote: Type.Optional(RemoteSchema),
102
103
  ...IntentFields,
@@ -383,7 +384,7 @@ export function registerTools(pi: ExtensionAPI, runtime?: ToolRuntime, refreshNa
383
384
  register({
384
385
  name: "bg_task_watch",
385
386
  label: "BG Watch",
386
- description: `Poll a command in the background until success_when, failure_when, or timeout matches. For remote work, prefer structured ssh: pass ssh:{host,user} and provide the remote command in command; each interval opens a direct one-shot SSH poll without tmux installation. For short synchronous remote commands that should return output now, use remote_bash from pi-better-ssh. Returns its task id once the first check finishes. ${WATCH_CHECK_GUIDANCE} Default timeout 900 seconds; pass timeout_seconds:0 to disable.`,
387
+ description: `Poll a command in the background until success_when, failure_when, or timeout matches. For remote work, prefer structured ssh: pass ssh:{host,user} and provide the remote command in command; each interval opens a direct one-shot SSH poll without tmux installation. For short synchronous remote commands that should return output now, use remote_bash from pi-better-ssh. Returns its task id once the first check finishes. ${WATCH_CHECK_GUIDANCE} Default timeout 900 seconds; pass timeout_seconds:0 to use the 24-hour maximum.`,
387
388
  promptGuidelines: BACKGROUND_ORCHESTRATION_GUIDELINES,
388
389
  parameters: WatchParams,
389
390
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
@@ -0,0 +1,43 @@
1
+ // Generated canonical coordinator. Do not edit directly.
2
+ import { bumpChangeRevision } from "./discovery.mjs";
3
+ import { getOperation } from "./operations.mjs";
4
+ import { columnNumber, columnText, getRows, run } from "./sqlite.mjs";
5
+ import { MAX_TASK_LIFETIME_MS } from "./task-lifetime.mjs";
6
+ import { cancelGeneration } from "./waits.mjs";
7
+ const reason = "24-hour task lifetime exceeded";
8
+ const batch = 8;
9
+ export function overdueOperations(ctx) {
10
+ return getRows(ctx, `SELECT operation_id FROM operations WHERE phase = 'running' AND terminal_revision = 0
11
+ AND created_at <= ? ORDER BY created_at LIMIT ?`, ctx.now() - MAX_TASK_LIFETIME_MS, batch)
12
+ .map(row => getOperation(ctx, columnText(row, "operation_id")))
13
+ .filter(operation => operation.phase === "running");
14
+ }
15
+ export function expireWaits(ctx) {
16
+ const now = ctx.now();
17
+ const cutoff = now - MAX_TASK_LIFETIME_MS;
18
+ const waits = getRows(ctx, `SELECT wait_id, generation FROM waits WHERE phase NOT IN ('consumed', 'cancelled')
19
+ AND dispatch_disarmed = 0 AND created_at <= ? ORDER BY created_at LIMIT ?`, cutoff, batch);
20
+ const claims = getRows(ctx, `SELECT claim_id FROM resume_claims WHERE state IN ('claimed', 'published')
21
+ AND claimed_at <= ? ORDER BY claimed_at LIMIT ?`, cutoff, batch);
22
+ if (!waits.length && !claims.length)
23
+ return 0;
24
+ return ctx.transaction(() => {
25
+ let changed = 0;
26
+ for (const row of waits) {
27
+ const id = columnText(row, "wait_id"), generation = columnNumber(row, "generation");
28
+ if (!ctx.db.prepare(`SELECT 1 FROM waits WHERE wait_id = ? AND generation = ?
29
+ AND phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed = 0 AND created_at <= ?`).get(id, generation, cutoff))
30
+ continue;
31
+ cancelGeneration(ctx, id, generation, reason);
32
+ changed++;
33
+ }
34
+ // Published claims can outlive consumed waits or a disarmed assignment.
35
+ for (const row of claims) {
36
+ changed += run(ctx, `UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
37
+ WHERE claim_id = ? AND state IN ('claimed', 'published') AND claimed_at <= ?`, now, reason, columnText(row, "claim_id"), cutoff);
38
+ }
39
+ if (changed)
40
+ bumpChangeRevision(ctx);
41
+ return changed;
42
+ });
43
+ }
@@ -59,6 +59,11 @@ const ASSIGNMENT_ATTEMPTS_DDL = `CREATE TABLE IF NOT EXISTS assignment_attempts
59
59
  assignment_id TEXT NOT NULL REFERENCES assignment_bindings (assignment_id)
60
60
  )`;
61
61
  const ASSIGNMENT_ATTEMPT_COLUMN = `assignment_attempt_id TEXT REFERENCES assignment_attempts (attempt_id)`;
62
+ const EXPIRY_INDEXES = [
63
+ "CREATE INDEX IF NOT EXISTS operations_expiry ON operations(created_at) WHERE phase = 'running' AND terminal_revision = 0",
64
+ "CREATE INDEX IF NOT EXISTS waits_expiry ON waits(created_at) WHERE phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed = 0",
65
+ "CREATE INDEX IF NOT EXISTS claims_expiry ON resume_claims(claimed_at) WHERE state IN ('claimed', 'published')",
66
+ ];
62
67
  const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignment_cleanup
63
68
  ON operations (operation_id, assignment_attempt_id)
64
69
  WHERE assignment_attempt_id IS NOT NULL`;
@@ -300,7 +305,7 @@ export function ensureSchema(ctx) {
300
305
  throw new StoreError("schema-version", `The database at this path holds tables (${tables.join(", ")}) but no ${SCHEMA_VERSION_KEY}. It was not written by the operation coordinator; refusing to reuse or clear it.`);
301
306
  }
302
307
  ctx.transaction(() => {
303
- for (const statement of DDL)
308
+ for (const statement of [...DDL, ...EXPIRY_INDEXES])
304
309
  ctx.db.exec(statement);
305
310
  run(ctx, "INSERT INTO schema_meta (key, value) VALUES (?, ?)", SCHEMA_VERSION_KEY, String(SCHEMA_VERSION));
306
311
  });
@@ -350,6 +355,8 @@ export function ensureSchema(ctx) {
350
355
  ensureAssignmentCleanupSchema(ctx);
351
356
  }
352
357
  function ensureAssignmentCleanupSchema(ctx) {
358
+ for (const statement of EXPIRY_INDEXES)
359
+ ctx.db.exec(statement);
353
360
  const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
354
361
  if (hasColumn() && getRow(ctx, "SELECT 1 FROM sqlite_master WHERE name = 'operations_assignment_cleanup'"))
355
362
  return;
@@ -7,6 +7,7 @@
7
7
  * synchronous and transactional; a refusal throws `StoreError` with a typed code
8
8
  * and leaves no partial record.
9
9
  */
10
+ import { expireWaits, overdueOperations } from "./expiry.mjs";
10
11
  import { setUpgradeFence } from "./upgrade.mjs";
11
12
  import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks } from './background-parent-callbacks.mjs';
12
13
  import { BackgroundRequests } from "./background-requests.mjs";
@@ -50,6 +51,8 @@ export function openStore(options) {
50
51
  }
51
52
  };
52
53
  const store = {
54
+ overdueOperations() { alive(); return overdueOperations(ctx); },
55
+ expireWaits() { alive(); return expireWaits(ctx); },
53
56
  subagentLaunchJournal() { alive(); return new SubagentLaunchJournal(ctx, alive); },
54
57
  resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
55
58
  handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
@@ -0,0 +1,6 @@
1
+ // Generated canonical coordinator. Do not edit directly.
2
+ /** Absolute wall-clock limit, including time spent waiting for a runner. */
3
+ export const MAX_TASK_LIFETIME_MS = 24 * 60 * 60 * 1000;
4
+ export function taskDeadline(startedAt, requestedDeadline) {
5
+ return Math.min(startedAt + MAX_TASK_LIFETIME_MS, requestedDeadline ?? Infinity);
6
+ }