pi-better-background-tasks 0.20.1 → 0.20.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.20.1",
3
+ "version": "0.20.3",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"1a13882b3d93635543ba5ce23618d49d89a4dddd753e75b813c9717346da9066","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.1","contentId":"41b03fd7c1ec59d3a988425593df167293ff6733348e1e1ee2c26f5839255dec"},"sha256":"ae72e92a22c7d15b5252d0ffed543e576e31a944cdd801fde2f88563b27617c5"}
1
+ {"build":{"format":1,"sourceDigest":"b78be1be377cc0afb4c352a3e954b947cb04cd869a0a42c07708ca55b133a03b","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.3","contentId":"3b8745c8af3ac4e913fee90d9baedbd5b7ed792905931368caad01341ee7043c"},"sha256":"3ffac195708bbc8bdd02f492a1392d31d7e93d054f5d0e8d849dc4413a15045e"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"1a13882b3d93635543ba5ce23618d49d89a4dddd753e75b813c9717346da9066","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.1","contentId":"7fcd83a7e4ca03f06e2a17151c13ef7a39f674b098b61a096b8d191b3d609084"},"sha256":"3f33c2a9871efeac1de259d47133431805db6f78e6ec83dfc35a14c633b019e7"}
1
+ {"build":{"format":1,"sourceDigest":"b78be1be377cc0afb4c352a3e954b947cb04cd869a0a42c07708ca55b133a03b","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.3","contentId":"05136ac971dda53b91d7c54ecd0a335102a2f52fdad5a9b05343986bf1c7d4b8"},"sha256":"3a7082c42c7473b77190a61df5bfa22d2abd616c4fb1c6671dbbcc523584a1ae"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"1a13882b3d93635543ba5ce23618d49d89a4dddd753e75b813c9717346da9066","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.1","contentId":"974a599e19549eb47553301f8a2abf3f75f9ef49133835dd4feab13117aca209"},"sha256":"79dbfb51ab1495c873657db19815e6e23a2f22eb9fd00beec18bcdad20a3253f"}
1
+ {"build":{"format":1,"sourceDigest":"b78be1be377cc0afb4c352a3e954b947cb04cd869a0a42c07708ca55b133a03b","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.3","contentId":"cb3ab02b2fb7dbcfa0fc59ff3f5959aae5e45efb16eceb80b87d57484e4d95fb"},"sha256":"a0b4fcbff76d28eeb9434998996db14a27731524e784f8b81374b5d670e48e78"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"1a13882b3d93635543ba5ce23618d49d89a4dddd753e75b813c9717346da9066","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.1","contentId":"ae922b992761077c8ed0d6c548495ce4f7f00a78535ecdb4e202c4d3967cf3ae"},"sha256":"cb9c77c019e2ce62ffde1098fa2944f6fff6ca828c59a10fad3c07db38dffa5b"}
1
+ {"build":{"format":1,"sourceDigest":"b78be1be377cc0afb4c352a3e954b947cb04cd869a0a42c07708ca55b133a03b","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.7.3","contentId":"ef3defd899269476359a94bbf98294b7fbba879341878fbd6216887e19a0b70b"},"sha256":"7913c6f10e58c7becc75ad819eeedc368d509704aab00e0e39fc13b98f394b9b"}
@@ -4,6 +4,22 @@ import { join } from 'node:path';
4
4
  import { readAdmissionStartToken, readProcessStartTokenFresh } from './process-identity.js';
5
5
  const ordered = (value: any): any => value === null || typeof value !== 'object' ? value : Array.isArray(value) ? value.map(ordered) : Object.fromEntries(Object.keys(value).sort().map(key => [key, ordered(value[key])]));
6
6
  export const backgroundDigest = (value: unknown) => createHash('sha256').update(JSON.stringify(ordered(value))).digest('hex');
7
+
8
+ export const TASK_TIMEOUT_HELP = "Optional whole-task timeout in seconds. Command watchers default to 900 seconds when omitted; pass 0 to use the 24-hour maximum. Spawned processes also have a 24-hour maximum. 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.";
9
+ // Admission v1/v2 hashes the full schema. Preserve the 0.20.1 wire text
10
+ // for this annotation; all property names, validation rules and defaults remain in the digest.
11
+ const PUBLISHED_TIMEOUT_HELP = "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.";
12
+
13
+ export function backgroundParametersDigest(parameters: unknown): string {
14
+ const wire = JSON.stringify(ordered(parameters), (key, value) => {
15
+ if (key === 'timeout_seconds' && value?.description === TASK_TIMEOUT_HELP) {
16
+ return { ...value, description: PUBLISHED_TIMEOUT_HELP };
17
+ }
18
+ return value;
19
+ });
20
+ return createHash('sha256').update(wire).digest('hex');
21
+ }
22
+
7
23
  export function readBackgroundAuthority(root: string, instance: string, authority: any, requireLive = true): any {
8
24
  if (!authority || !/^[a-f0-9-]{36}$/.test(authority.id) || !/^[a-f0-9]{64}$/.test(authority.secret))
9
25
  throw new Error('background-authority-refused');
@@ -2,7 +2,7 @@ import { createHash, randomBytes, randomUUID } from 'node:crypto';
2
2
  import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { getAgentDir, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
5
- import { backgroundDigest } from './managed-authority.js';
5
+ import { backgroundDigest, backgroundParametersDigest } from './managed-authority.js';
6
6
  import { readAdmissionStartToken, readProcessStartTokenFresh } from './process-identity.js';
7
7
  import { currentForegroundSandboxPolicy, FOREGROUND_SANDBOX_POLICY_CHANNEL } from './sandbox.js';
8
8
  import { backgroundListNeedsHistory, backgroundObservation } from './work-observation.js';
@@ -48,7 +48,7 @@ export async function requestBackgroundTool(pi: ExtensionAPI, ctx: ExtensionCont
48
48
  const start = version === 2 ? readAdmissionStartToken(process.pid) : readProcessStartTokenFresh(process.pid);
49
49
  const record = { version, id, secretHash: createHash('sha256').update(secret).digest('hex'), instanceId: hello.instanceId,
50
50
  owner: { kind: 'parent-session', sessionId, workspace: realpathSync(ctx.cwd) }, branchIds, projectTrusted: ctx.isProjectTrusted(),
51
- pid: process.pid, start, key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundDigest(parameters), policy };
51
+ pid: process.pid, start, key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundParametersDigest(parameters), policy };
52
52
  const staged = `${path}.tmp`;
53
53
  writeFileSync(staged, JSON.stringify(record), { flag: 'wx', mode: 0o600 });
54
54
  renameSync(staged, path);
@@ -1,3 +1,4 @@
1
+ import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.ts";
1
2
  import { getObservedWaitHost, registerObservedWaitClient } from "./observed-wait-client.js";
2
3
  export { getObservedWaitHost, registerObservedWaitClient } from "./observed-wait-client.js";
3
4
  /**
@@ -865,14 +866,16 @@ function mapEvidence(
865
866
  /** Shared terminal publication contract for the host and fixed server cancel adapter. */
866
867
  export function supervisorTerminalPublication(operation: OperationRecord, inspection: SupervisorInspection, refs = evidenceFor(inspection)) {
867
868
  const status = inspection.status;
868
- const outcome = terminalOutcome(status);
869
+ const endedAt = inspection.result?.endedAt ?? inspection.lost?.recordedAt;
870
+ const expired = endedAt !== undefined && endedAt >= taskDeadline(Math.min(operation.createdAt, inspection.launch.createdAt));
871
+ const outcome = expired ? "failed" : terminalOutcome(status);
869
872
  return {
870
873
  operationId: operation.operationId,
871
874
  eventId: `${operation.taskId}:${inspection.result?.endedAt ?? inspection.lost?.recordedAt ?? inspection.observedAt}:${status}`,
872
875
  outcome, owner: operation.owner,
873
876
  evidence: refs.map(ref => ({ kind: ref.kind, ref: ref.ref, ...(ref.summary ? { summary: ref.summary } : {}), detailLost: ref.detailLost })),
874
877
  ...(outcome === "lost" ? { detailLost: true } : {}),
875
- reason: inspection.result ? `supervisor ${status} exit=${inspection.result.exitCode ?? "null"}` : "supervisor lost: no terminal evidence",
878
+ reason: expired ? "24-hour task lifetime exceeded" : inspection.result ? `supervisor ${status} exit=${inspection.result.exitCode ?? "null"}` : "supervisor lost: no terminal evidence",
876
879
  };
877
880
  }
878
881
 
@@ -3544,11 +3547,12 @@ export class ObservedWaitHost {
3544
3547
  if (this.resultHandoffs.has(operation.operationId) || this.store?.resultSupervision(operation.operationId)) return;
3545
3548
  const store = this.requireStore();
3546
3549
  const status = inspection.status;
3547
- const outcome = terminalOutcome(status);
3548
3550
  const refs = evidenceFor(inspection);
3551
+ const publication = supervisorTerminalPublication(operation, inspection, refs);
3552
+ const outcome = publication.outcome;
3549
3553
  let recorded;
3550
3554
  try {
3551
- recorded = store.recordTerminalOutcome(supervisorTerminalPublication(operation, inspection, refs));
3555
+ recorded = store.recordTerminalOutcome(publication);
3552
3556
  } catch (error) {
3553
3557
  // A timer and a tool call can observe the same terminal record. The store
3554
3558
  // keeps the first revision; a replay is never a second execution.
package/src/registry.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.ts";
1
2
  import { createHash } from "node:crypto";
2
3
  import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
4
  import { tmpdir } from "node:os";
@@ -137,6 +138,7 @@ export function inspectMeta(id: string): MetaInspection {
137
138
  metaCache.delete(id);
138
139
  return { id, found: true, readable: false, error: `invalid metadata: ${invalid}` };
139
140
  }
141
+ if (meta.status === "running") meta.deadlineAt = taskDeadline(meta.startedAt, meta.deadlineAt);
140
142
  metaCache.set(id, meta);
141
143
  return { id, meta, found: true, readable: true };
142
144
  } catch (error) {
package/src/runtime.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.ts";
1
2
  import { WATCH_FINGERPRINT_VERSION, watchOutcomeFingerprint } from "./watch-fingerprint.js";
2
3
  import { readFileSync, statSync } from "node:fs";
3
4
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
@@ -366,7 +367,7 @@ function spawnTask(
366
367
  status: "running",
367
368
  startedAt: now,
368
369
  lastProgressAt: now,
369
- deadlineAt: params.timeout_seconds ? now + params.timeout_seconds * 1000 : undefined,
370
+ deadlineAt: taskDeadline(now, params.timeout_seconds ? now + params.timeout_seconds * 1000 : undefined),
370
371
  logPath,
371
372
  callback: params.callback,
372
373
  callbackOrigin,
@@ -658,7 +659,7 @@ function startWatchTask(
658
659
  status: "running",
659
660
  startedAt: now,
660
661
  lastProgressAt: now,
661
- deadlineAt: timeoutSeconds ? now + timeoutSeconds * 1000 : undefined,
662
+ deadlineAt: taskDeadline(now, timeoutSeconds ? now + timeoutSeconds * 1000 : undefined),
662
663
  intervalMs: Math.max(1, params.interval_seconds ?? 30) * 1000,
663
664
  logPath: logPathFor(id),
664
665
  callback: params.callback,
@@ -0,0 +1,44 @@
1
+ // Generated from packages/operation-coordinator/src/expiry.ts. Do not edit directly.
2
+ import { bumpChangeRevision } from "./discovery.ts";
3
+ import { getOperation } from "./operations.ts";
4
+ import { columnNumber, columnText, getRows, run, type StoreContext } from "./sqlite.ts";
5
+ import { MAX_TASK_LIFETIME_MS } from "./task-lifetime.ts";
6
+ import { cancelGeneration } from "./waits.ts";
7
+
8
+ const reason = "24-hour task lifetime exceeded";
9
+ const batch = 8;
10
+
11
+ export function overdueOperations(ctx: StoreContext) {
12
+ return getRows(ctx, `SELECT operation_id FROM operations WHERE phase = 'running' AND terminal_revision = 0
13
+ AND created_at <= ? ORDER BY created_at LIMIT ?`, ctx.now() - MAX_TASK_LIFETIME_MS, batch)
14
+ .map(row => getOperation(ctx, columnText(row, "operation_id"))!)
15
+ .filter(operation => operation.phase === "running");
16
+ }
17
+
18
+ export function expireWaits(ctx: StoreContext): number {
19
+ const now = ctx.now();
20
+ const cutoff = now - MAX_TASK_LIFETIME_MS;
21
+ const waits = getRows(ctx, `SELECT wait_id, generation FROM waits WHERE phase NOT IN ('consumed', 'cancelled')
22
+ AND dispatch_disarmed = 0 AND created_at <= ? ORDER BY created_at LIMIT ?`, cutoff, batch);
23
+ const claims = getRows(ctx, `SELECT claim_id FROM resume_claims WHERE state IN ('claimed', 'published')
24
+ AND claimed_at <= ? ORDER BY claimed_at LIMIT ?`, cutoff, batch);
25
+ if (!waits.length && !claims.length) return 0;
26
+ return ctx.transaction(() => {
27
+ let changed = 0;
28
+ for (const row of waits) {
29
+ const id = columnText(row, "wait_id"), generation = columnNumber(row, "generation");
30
+ if (!ctx.db.prepare(`SELECT 1 FROM waits WHERE wait_id = ? AND generation = ?
31
+ AND phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed = 0 AND created_at <= ?`).get(id, generation, cutoff)) continue;
32
+ cancelGeneration(ctx, id, generation, reason);
33
+ changed++;
34
+ }
35
+ // Published claims can outlive consumed waits or a disarmed assignment.
36
+ for (const row of claims) {
37
+ changed += run(ctx, `UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
38
+ WHERE claim_id = ? AND state IN ('claimed', 'published') AND claimed_at <= ?`,
39
+ now, reason, columnText(row, "claim_id"), cutoff);
40
+ }
41
+ if (changed) bumpChangeRevision(ctx);
42
+ return changed;
43
+ });
44
+ }
@@ -62,6 +62,12 @@ const ASSIGNMENT_ATTEMPTS_DDL = `CREATE TABLE IF NOT EXISTS assignment_attempts
62
62
  assignment_id TEXT NOT NULL REFERENCES assignment_bindings (assignment_id)
63
63
  )`;
64
64
  const ASSIGNMENT_ATTEMPT_COLUMN = `assignment_attempt_id TEXT REFERENCES assignment_attempts (attempt_id)`;
65
+ const EXPIRY_INDEXES = [
66
+ "CREATE INDEX IF NOT EXISTS operations_expiry ON operations(created_at) WHERE phase = 'running' AND terminal_revision = 0",
67
+ "CREATE INDEX IF NOT EXISTS waits_expiry ON waits(created_at) WHERE phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed = 0",
68
+ "CREATE INDEX IF NOT EXISTS claims_expiry ON resume_claims(claimed_at) WHERE state IN ('claimed', 'published')",
69
+ ];
70
+
65
71
  const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignment_cleanup
66
72
  ON operations (operation_id, assignment_attempt_id)
67
73
  WHERE assignment_attempt_id IS NOT NULL`;
@@ -313,7 +319,7 @@ export function ensureSchema(ctx: StoreContext): void {
313
319
  );
314
320
  }
315
321
  ctx.transaction(() => {
316
- for (const statement of DDL) ctx.db.exec(statement);
322
+ for (const statement of [...DDL, ...EXPIRY_INDEXES]) ctx.db.exec(statement);
317
323
  run(ctx, "INSERT INTO schema_meta (key, value) VALUES (?, ?)", SCHEMA_VERSION_KEY, String(SCHEMA_VERSION));
318
324
  });
319
325
  return;
@@ -369,6 +375,7 @@ export function ensureSchema(ctx: StoreContext): void {
369
375
  }
370
376
 
371
377
  function ensureAssignmentCleanupSchema(ctx: StoreContext): void {
378
+ for (const statement of EXPIRY_INDEXES) ctx.db.exec(statement);
372
379
  const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
373
380
  if (hasColumn() && getRow(ctx, "SELECT 1 FROM sqlite_master WHERE name = 'operations_assignment_cleanup'")) return;
374
381
  ctx.transaction(() => {
@@ -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.ts";
10
11
  import { setUpgradeFence } from "./upgrade.ts";
11
12
  import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks, type ParentCallbackScope, type ParentCallbackPage, type RecentBackgroundTerminalPage } from './background-parent-callbacks.ts';
12
13
  import { BackgroundRequests } from "./background-requests.ts";
@@ -127,6 +128,8 @@ import {
127
128
  } from "./types.ts";
128
129
 
129
130
  export interface Store {
131
+ overdueOperations(): OperationRecord[];
132
+ expireWaits(): number;
130
133
  hasSubagentManagement(): boolean;
131
134
  resultSupervisionChanges(after?: Parameters<typeof resultSupervisionChanges>[1]): ReturnType<typeof resultSupervisionChanges>;
132
135
  subagentLaunchJournal(): SubagentLaunchJournal;
@@ -359,6 +362,8 @@ export function openStore(options: StoreOptions): Store {
359
362
  };
360
363
 
361
364
  const store: Store = {
365
+ overdueOperations() { alive(); return overdueOperations(ctx); },
366
+ expireWaits() { alive(); return expireWaits(ctx); },
362
367
  subagentLaunchJournal() { alive(); return new SubagentLaunchJournal(ctx, alive); },
363
368
  resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
364
369
  handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
@@ -0,0 +1,7 @@
1
+ // Generated from packages/operation-coordinator/src/task-lifetime.ts. 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
+
5
+ export function taskDeadline(startedAt: number, requestedDeadline?: number): number {
6
+ return Math.min(startedAt + MAX_TASK_LIFETIME_MS, requestedDeadline ?? Infinity);
7
+ }
@@ -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(
@@ -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
  }
@@ -35,6 +35,7 @@ const outputDir = process.argv[2] ? resolve(process.argv[2]) : join(here, "gener
35
35
 
36
36
  /** Runtime entry first; everything else is reachable from it. */
37
37
  const CLOSURE = [
38
+ { source: join(here, "..", "shared-operation-coordinator", "src", "task-lifetime.ts"), out: "task-lifetime.mjs" },
38
39
  { source: join(here, "runner.ts"), out: "runner.mjs" },
39
40
  { source: join(here, "store.ts"), out: "store.mjs" },
40
41
  { 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 by src/supervisor/emit-runner.mjs from the TypeScript source.
2
+ // Do not edit: change the source and re-run the emitter (a drift test enforces this).
3
+
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
  * 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;
package/src/tools.ts CHANGED
@@ -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) {