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.
- package/package.json +1 -1
- package/src/runtime/background-tools.ts +2 -1
- package/src/runtime/domain/background/registry.mjs +3 -0
- package/src/runtime/domain/background/shared-operation-coordinator/src/task-lifetime.mjs +6 -0
- package/src/runtime/domain/background/terminal-publication.mjs +5 -2
- package/src/runtime/domain/background-service/managed-authority.domain.mjs +13 -0
- package/src/runtime/domain/background-service/managed-authority.ts +16 -0
- package/src/runtime/domain/background-service/managed-client.domain.mjs +2 -2
- package/src/runtime/domain/background-service/managed-client.ts +2 -2
- package/src/runtime/domain/background-service/observed-waits.domain.mjs +8 -4
- package/src/runtime/domain/background-service/observed-waits.ts +8 -4
- package/src/runtime/domain/background-service/registry.domain.mjs +3 -0
- package/src/runtime/domain/background-service/registry.ts +2 -0
- package/src/runtime/domain/background-service/runtime.domain.mjs +3 -2
- package/src/runtime/domain/background-service/runtime.ts +3 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/expiry.domain.mjs +44 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/expiry.ts +44 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +8 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +8 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +3 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +5 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-lifetime.domain.mjs +7 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-lifetime.ts +7 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.domain.mjs +22 -13
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.ts +40 -32
- package/src/runtime/domain/background-service/shared-sandbox-diagnostics.domain.mjs +12 -19
- package/src/runtime/domain/background-service/shared-sandbox-diagnostics.ts +12 -16
- package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
- package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +12 -7
- package/src/runtime/domain/background-service/supervisor/generated/task-lifetime.mjs +9 -0
- package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +12 -7
- package/src/runtime/domain/background-service/supervisor/runner.ts +12 -7
- package/src/runtime/domain/background-service/supervisor/types.ts +1 -1
- package/src/runtime/domain/background-service/tools.domain.mjs +3 -2
- package/src/runtime/domain/background-service/tools.ts +3 -2
- package/src/runtime/domain/coordinator/src/expiry.mjs +43 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +8 -1
- package/src/runtime/domain/coordinator/src/store.mjs +3 -0
- package/src/runtime/domain/coordinator/src/task-lifetime.mjs +6 -0
- package/src/runtime/domain/coordinator/src/waits.mjs +22 -13
- package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.domain.mjs +12 -19
- package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.ts +12 -16
- package/src/runtime/domain/subagents/README.md +2 -2
- package/src/runtime/domain/subagents/cleanup.domain.mjs +5 -2
- package/src/runtime/domain/subagents/cleanup.ts +4 -1
- package/src/runtime/domain/subagents/index.domain.mjs +47 -29
- package/src/runtime/domain/subagents/index.ts +46 -27
- package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +28 -2
- package/src/runtime/domain/subagents/managed-launch-host.ts +26 -2
- package/src/runtime/domain/subagents/managed-launch-port.ts +2 -0
- package/src/runtime/domain/subagents/output-payload.domain.mjs +3 -1
- package/src/runtime/domain/subagents/output-payload.ts +2 -0
- package/src/runtime/domain/subagents/package.json +1 -1
- package/src/runtime/domain/subagents/registry-cleanup-worker.mjs +24 -0
- package/src/runtime/domain/subagents/registry.domain.mjs +33 -7
- package/src/runtime/domain/subagents/registry.ts +18 -4
- package/src/runtime/domain/subagents/settings-page.domain.mjs +10 -10
- package/src/runtime/domain/subagents/settings-page.ts +10 -10
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/expiry.domain.mjs +44 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/expiry.ts +44 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +8 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +8 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +3 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +5 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-lifetime.domain.mjs +7 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-lifetime.ts +7 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.domain.mjs +22 -13
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.ts +40 -32
- package/src/runtime/domain/subagents/shared-sandbox-diagnostics.domain.mjs +12 -19
- package/src/runtime/domain/subagents/shared-sandbox-diagnostics.ts +12 -16
- package/src/runtime/domain/subagents/stop.domain.mjs +7 -5
- package/src/runtime/domain/subagents/stop.ts +7 -5
- package/src/runtime/domain/subagents/timing.domain.mjs +7 -3
- package/src/runtime/domain/subagents/timing.ts +11 -4
- package/src/runtime/domain/subagents/tools.domain.mjs +3 -2
- package/src/runtime/domain/subagents/tools.ts +3 -2
- package/src/runtime/domain/subagents/workflow-assignment.domain.mjs +25 -0
- package/src/runtime/domain/subagents/workflow-assignment.ts +35 -0
- package/src/runtime/domain/subagents/workspace-files.domain.mjs +6 -6
- package/src/runtime/domain/subagents/workspace-files.ts +6 -6
- package/src/runtime/query-executor.ts +11 -2
- package/src/runtime/task-expiry.ts +52 -0
- package/src/server.ts +4 -0
- package/src/version.ts +1 -1
package/package.json
CHANGED
|
@@ -363,7 +363,8 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
363
363
|
if (record.tool === '__background_dismiss')
|
|
364
364
|
return service.dismissDurableTask(origin, record.params.id);
|
|
365
365
|
const tool = session.extensionRunner.getToolDefinition(record.tool);
|
|
366
|
-
if (!tool || record.parametersDigest !== authority.
|
|
366
|
+
if (!tool || (record.parametersDigest !== authority.backgroundParametersDigest(tool.parameters)
|
|
367
|
+
&& record.parametersDigest !== authority.backgroundDigest(tool.parameters)))
|
|
367
368
|
throw new Error('capability-mismatch: Background tool schema');
|
|
368
369
|
if (!Check(tool.parameters, record.params))
|
|
369
370
|
throw new Error('Invalid Background tool parameters');
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.mjs";
|
|
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";
|
|
@@ -112,6 +113,8 @@ export function inspectMeta(id) {
|
|
|
112
113
|
metaCache.delete(id);
|
|
113
114
|
return { id, found: true, readable: false, error: `invalid metadata: ${invalid}` };
|
|
114
115
|
}
|
|
116
|
+
if (meta.status === "running")
|
|
117
|
+
meta.deadlineAt = taskDeadline(meta.startedAt, meta.deadlineAt);
|
|
115
118
|
metaCache.set(id, meta);
|
|
116
119
|
return { id, meta, found: true, readable: true };
|
|
117
120
|
}
|
|
@@ -0,0 +1,6 @@
|
|
|
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
|
+
export function taskDeadline(startedAt, requestedDeadline) {
|
|
5
|
+
return Math.min(startedAt + MAX_TASK_LIFETIME_MS, requestedDeadline ?? Infinity);
|
|
6
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Generated canonical terminal publication. Do not edit directly.
|
|
2
2
|
import { existsSync, statSync } from "node:fs";
|
|
3
|
+
import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.mjs";
|
|
3
4
|
function terminalOutcome(status) {
|
|
4
5
|
switch (status) {
|
|
5
6
|
case "succeeded": return "succeeded";
|
|
@@ -46,13 +47,15 @@ function evidenceFor(inspection) {
|
|
|
46
47
|
/** Shared terminal publication contract for the host and fixed server cancel adapter. */
|
|
47
48
|
export function supervisorTerminalPublication(operation, inspection, refs = evidenceFor(inspection)) {
|
|
48
49
|
const status = inspection.status;
|
|
49
|
-
const
|
|
50
|
+
const endedAt = inspection.result?.endedAt ?? inspection.lost?.recordedAt;
|
|
51
|
+
const expired = endedAt !== undefined && endedAt >= taskDeadline(Math.min(operation.createdAt, inspection.launch.createdAt));
|
|
52
|
+
const outcome = expired ? "failed" : terminalOutcome(status);
|
|
50
53
|
return {
|
|
51
54
|
operationId: operation.operationId,
|
|
52
55
|
eventId: `${operation.taskId}:${inspection.result?.endedAt ?? inspection.lost?.recordedAt ?? inspection.observedAt}:${status}`,
|
|
53
56
|
outcome, owner: operation.owner,
|
|
54
57
|
evidence: refs.map(ref => ({ kind: ref.kind, ref: ref.ref, ...(ref.summary ? { summary: ref.summary } : {}), detailLost: ref.detailLost })),
|
|
55
58
|
...(outcome === "lost" ? { detailLost: true } : {}),
|
|
56
|
-
reason: inspection.result ? `supervisor ${status} exit=${inspection.result.exitCode ?? "null"}` : "supervisor lost: no terminal evidence",
|
|
59
|
+
reason: expired ? "24-hour task lifetime exceeded" : inspection.result ? `supervisor ${status} exit=${inspection.result.exitCode ?? "null"}` : "supervisor lost: no terminal evidence",
|
|
57
60
|
};
|
|
58
61
|
}
|
|
@@ -5,6 +5,19 @@ import { join } from 'node:path';
|
|
|
5
5
|
import { readAdmissionStartToken, readProcessStartTokenFresh } from "./process-identity.domain.mjs";
|
|
6
6
|
const ordered = (value) => value === null || typeof value !== 'object' ? value : Array.isArray(value) ? value.map(ordered) : Object.fromEntries(Object.keys(value).sort().map(key => [key, ordered(value[key])]));
|
|
7
7
|
export const backgroundDigest = (value) => createHash('sha256').update(JSON.stringify(ordered(value))).digest('hex');
|
|
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
|
+
export function backgroundParametersDigest(parameters) {
|
|
13
|
+
const wire = JSON.stringify(ordered(parameters), (key, value) => {
|
|
14
|
+
if (key === 'timeout_seconds' && value?.description === TASK_TIMEOUT_HELP) {
|
|
15
|
+
return { ...value, description: PUBLISHED_TIMEOUT_HELP };
|
|
16
|
+
}
|
|
17
|
+
return value;
|
|
18
|
+
});
|
|
19
|
+
return createHash('sha256').update(wire).digest('hex');
|
|
20
|
+
}
|
|
8
21
|
export function readBackgroundAuthority(root, instance, authority, requireLive = true) {
|
|
9
22
|
if (!authority || !/^[a-f0-9-]{36}$/.test(authority.id) || !/^[a-f0-9]{64}$/.test(authority.secret))
|
|
10
23
|
throw new Error('background-authority-refused');
|
|
@@ -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');
|
|
@@ -3,7 +3,7 @@ import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
|
3
3
|
import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { getAgentDir } from '@earendil-works/pi-coding-agent';
|
|
6
|
-
import { backgroundDigest } from "./managed-authority.domain.mjs";
|
|
6
|
+
import { backgroundDigest, backgroundParametersDigest } from "./managed-authority.domain.mjs";
|
|
7
7
|
import { readAdmissionStartToken, readProcessStartTokenFresh } from "./process-identity.domain.mjs";
|
|
8
8
|
import { currentForegroundSandboxPolicy, FOREGROUND_SANDBOX_POLICY_CHANNEL } from "./sandbox.domain.mjs";
|
|
9
9
|
import { backgroundListNeedsHistory, backgroundObservation } from "./work-observation.domain.mjs";
|
|
@@ -50,7 +50,7 @@ export async function requestBackgroundTool(pi, ctx, key, tool, params, paramete
|
|
|
50
50
|
const start = version === 2 ? readAdmissionStartToken(process.pid) : readProcessStartTokenFresh(process.pid);
|
|
51
51
|
const record = { version, id, secretHash: createHash('sha256').update(secret).digest('hex'), instanceId: hello.instanceId,
|
|
52
52
|
owner: { kind: 'parent-session', sessionId, workspace: realpathSync(ctx.cwd) }, branchIds, projectTrusted: ctx.isProjectTrusted(),
|
|
53
|
-
pid: process.pid, start, key, tool, params, parametersDigest: parameters === undefined ? undefined :
|
|
53
|
+
pid: process.pid, start, key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundParametersDigest(parameters), policy };
|
|
54
54
|
const staged = `${path}.tmp`;
|
|
55
55
|
writeFileSync(staged, JSON.stringify(record), { flag: 'wx', mode: 0o600 });
|
|
56
56
|
renameSync(staged, path);
|
|
@@ -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 :
|
|
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,4 +1,5 @@
|
|
|
1
1
|
// Generated fixed launch domain from packages/pi-better-background-tasks/src/observed-waits.ts. Do not edit directly.
|
|
2
|
+
import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.domain.mjs";
|
|
2
3
|
import { getObservedWaitHost, registerObservedWaitClient } from "./observed-wait-client.domain.mjs";
|
|
3
4
|
export { getObservedWaitHost, registerObservedWaitClient } from "./observed-wait-client.domain.mjs";
|
|
4
5
|
/**
|
|
@@ -341,14 +342,16 @@ function mapEvidence(operationId, taskId, records, revision) {
|
|
|
341
342
|
/** Shared terminal publication contract for the host and fixed server cancel adapter. */
|
|
342
343
|
export function supervisorTerminalPublication(operation, inspection, refs = evidenceFor(inspection)) {
|
|
343
344
|
const status = inspection.status;
|
|
344
|
-
const
|
|
345
|
+
const endedAt = inspection.result?.endedAt ?? inspection.lost?.recordedAt;
|
|
346
|
+
const expired = endedAt !== undefined && endedAt >= taskDeadline(Math.min(operation.createdAt, inspection.launch.createdAt));
|
|
347
|
+
const outcome = expired ? "failed" : terminalOutcome(status);
|
|
345
348
|
return {
|
|
346
349
|
operationId: operation.operationId,
|
|
347
350
|
eventId: `${operation.taskId}:${inspection.result?.endedAt ?? inspection.lost?.recordedAt ?? inspection.observedAt}:${status}`,
|
|
348
351
|
outcome, owner: operation.owner,
|
|
349
352
|
evidence: refs.map(ref => ({ kind: ref.kind, ref: ref.ref, ...(ref.summary ? { summary: ref.summary } : {}), detailLost: ref.detailLost })),
|
|
350
353
|
...(outcome === "lost" ? { detailLost: true } : {}),
|
|
351
|
-
reason: inspection.result ? `supervisor ${status} exit=${inspection.result.exitCode ?? "null"}` : "supervisor lost: no terminal evidence",
|
|
354
|
+
reason: expired ? "24-hour task lifetime exceeded" : inspection.result ? `supervisor ${status} exit=${inspection.result.exitCode ?? "null"}` : "supervisor lost: no terminal evidence",
|
|
352
355
|
};
|
|
353
356
|
}
|
|
354
357
|
export class ObservedWaitHost {
|
|
@@ -3079,11 +3082,12 @@ export class ObservedWaitHost {
|
|
|
3079
3082
|
return;
|
|
3080
3083
|
const store = this.requireStore();
|
|
3081
3084
|
const status = inspection.status;
|
|
3082
|
-
const outcome = terminalOutcome(status);
|
|
3083
3085
|
const refs = evidenceFor(inspection);
|
|
3086
|
+
const publication = supervisorTerminalPublication(operation, inspection, refs);
|
|
3087
|
+
const outcome = publication.outcome;
|
|
3084
3088
|
let recorded;
|
|
3085
3089
|
try {
|
|
3086
|
-
recorded = store.recordTerminalOutcome(
|
|
3090
|
+
recorded = store.recordTerminalOutcome(publication);
|
|
3087
3091
|
}
|
|
3088
3092
|
catch (error) {
|
|
3089
3093
|
// A timer and a tool call can observe the same terminal record. The store
|
|
@@ -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
|
|
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(
|
|
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.
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// Generated fixed launch domain from packages/pi-better-background-tasks/src/registry.ts. Do not edit directly.
|
|
2
|
+
import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.domain.mjs";
|
|
2
3
|
import { createHash } from "node:crypto";
|
|
3
4
|
import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
5
|
import { tmpdir } from "node:os";
|
|
@@ -113,6 +114,8 @@ export function inspectMeta(id) {
|
|
|
113
114
|
metaCache.delete(id);
|
|
114
115
|
return { id, found: true, readable: false, error: `invalid metadata: ${invalid}` };
|
|
115
116
|
}
|
|
117
|
+
if (meta.status === "running")
|
|
118
|
+
meta.deadlineAt = taskDeadline(meta.startedAt, meta.deadlineAt);
|
|
116
119
|
metaCache.set(id, meta);
|
|
117
120
|
return { id, meta, found: true, readable: true };
|
|
118
121
|
}
|
|
@@ -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) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// Generated fixed launch domain from packages/pi-better-background-tasks/src/runtime.ts. Do not edit directly.
|
|
2
|
+
import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.domain.mjs";
|
|
2
3
|
import { WATCH_FINGERPRINT_VERSION, watchOutcomeFingerprint } from "./watch-fingerprint.domain.mjs";
|
|
3
4
|
import { readFileSync, statSync } from "node:fs";
|
|
4
5
|
import { appendLine, appendTaskOutput, appendWatchResult, retainLogTail, resolveMaxLogBytes } from "./logs.domain.mjs";
|
|
@@ -281,7 +282,7 @@ export function createBackgroundTaskRuntime(attention = createFailureAttention()
|
|
|
281
282
|
status: "running",
|
|
282
283
|
startedAt: now,
|
|
283
284
|
lastProgressAt: now,
|
|
284
|
-
deadlineAt: params.timeout_seconds ? now + params.timeout_seconds * 1000 : undefined,
|
|
285
|
+
deadlineAt: taskDeadline(now, params.timeout_seconds ? now + params.timeout_seconds * 1000 : undefined),
|
|
285
286
|
logPath,
|
|
286
287
|
callback: params.callback,
|
|
287
288
|
callbackOrigin,
|
|
@@ -565,7 +566,7 @@ export function createBackgroundTaskRuntime(attention = createFailureAttention()
|
|
|
565
566
|
status: "running",
|
|
566
567
|
startedAt: now,
|
|
567
568
|
lastProgressAt: now,
|
|
568
|
-
deadlineAt: timeoutSeconds ? now + timeoutSeconds * 1000 : undefined,
|
|
569
|
+
deadlineAt: taskDeadline(now, timeoutSeconds ? now + timeoutSeconds * 1000 : undefined),
|
|
569
570
|
intervalMs: Math.max(1, params.interval_seconds ?? 30) * 1000,
|
|
570
571
|
logPath: logPathFor(id),
|
|
571
572
|
callback: params.callback,
|
|
@@ -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,
|
package/src/runtime/domain/background-service/shared-operation-coordinator/src/expiry.domain.mjs
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Generated fixed launch domain from packages/pi-better-background-tasks/src/shared-operation-coordinator/src/expiry.ts. Do not edit directly.
|
|
2
|
+
// Generated from packages/operation-coordinator/src/expiry.ts. Do not edit directly.
|
|
3
|
+
import { bumpChangeRevision } from "./discovery.domain.mjs";
|
|
4
|
+
import { getOperation } from "./operations.domain.mjs";
|
|
5
|
+
import { columnNumber, columnText, getRows, run } from "./sqlite.domain.mjs";
|
|
6
|
+
import { MAX_TASK_LIFETIME_MS } from "./task-lifetime.domain.mjs";
|
|
7
|
+
import { cancelGeneration } from "./waits.domain.mjs";
|
|
8
|
+
const reason = "24-hour task lifetime exceeded";
|
|
9
|
+
const batch = 8;
|
|
10
|
+
export function overdueOperations(ctx) {
|
|
11
|
+
return getRows(ctx, `SELECT operation_id FROM operations WHERE phase = 'running' AND terminal_revision = 0
|
|
12
|
+
AND created_at <= ? ORDER BY created_at LIMIT ?`, ctx.now() - MAX_TASK_LIFETIME_MS, batch)
|
|
13
|
+
.map(row => getOperation(ctx, columnText(row, "operation_id")))
|
|
14
|
+
.filter(operation => operation.phase === "running");
|
|
15
|
+
}
|
|
16
|
+
export function expireWaits(ctx) {
|
|
17
|
+
const now = ctx.now();
|
|
18
|
+
const cutoff = now - MAX_TASK_LIFETIME_MS;
|
|
19
|
+
const waits = getRows(ctx, `SELECT wait_id, generation FROM waits WHERE phase NOT IN ('consumed', 'cancelled')
|
|
20
|
+
AND dispatch_disarmed = 0 AND created_at <= ? ORDER BY created_at LIMIT ?`, cutoff, batch);
|
|
21
|
+
const claims = getRows(ctx, `SELECT claim_id FROM resume_claims WHERE state IN ('claimed', 'published')
|
|
22
|
+
AND claimed_at <= ? ORDER BY claimed_at LIMIT ?`, cutoff, batch);
|
|
23
|
+
if (!waits.length && !claims.length)
|
|
24
|
+
return 0;
|
|
25
|
+
return ctx.transaction(() => {
|
|
26
|
+
let changed = 0;
|
|
27
|
+
for (const row of waits) {
|
|
28
|
+
const id = columnText(row, "wait_id"), generation = columnNumber(row, "generation");
|
|
29
|
+
if (!ctx.db.prepare(`SELECT 1 FROM waits WHERE wait_id = ? AND generation = ?
|
|
30
|
+
AND phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed = 0 AND created_at <= ?`).get(id, generation, cutoff))
|
|
31
|
+
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 <= ?`, now, reason, columnText(row, "claim_id"), cutoff);
|
|
39
|
+
}
|
|
40
|
+
if (changed)
|
|
41
|
+
bumpChangeRevision(ctx);
|
|
42
|
+
return changed;
|
|
43
|
+
});
|
|
44
|
+
}
|
|
@@ -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
|
+
}
|
package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs
CHANGED
|
@@ -60,6 +60,11 @@ const ASSIGNMENT_ATTEMPTS_DDL = `CREATE TABLE IF NOT EXISTS assignment_attempts
|
|
|
60
60
|
assignment_id TEXT NOT NULL REFERENCES assignment_bindings (assignment_id)
|
|
61
61
|
)`;
|
|
62
62
|
const ASSIGNMENT_ATTEMPT_COLUMN = `assignment_attempt_id TEXT REFERENCES assignment_attempts (attempt_id)`;
|
|
63
|
+
const EXPIRY_INDEXES = [
|
|
64
|
+
"CREATE INDEX IF NOT EXISTS operations_expiry ON operations(created_at) WHERE phase = 'running' AND terminal_revision = 0",
|
|
65
|
+
"CREATE INDEX IF NOT EXISTS waits_expiry ON waits(created_at) WHERE phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed = 0",
|
|
66
|
+
"CREATE INDEX IF NOT EXISTS claims_expiry ON resume_claims(claimed_at) WHERE state IN ('claimed', 'published')",
|
|
67
|
+
];
|
|
63
68
|
const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignment_cleanup
|
|
64
69
|
ON operations (operation_id, assignment_attempt_id)
|
|
65
70
|
WHERE assignment_attempt_id IS NOT NULL`;
|
|
@@ -301,7 +306,7 @@ export function ensureSchema(ctx) {
|
|
|
301
306
|
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.`);
|
|
302
307
|
}
|
|
303
308
|
ctx.transaction(() => {
|
|
304
|
-
for (const statement of DDL)
|
|
309
|
+
for (const statement of [...DDL, ...EXPIRY_INDEXES])
|
|
305
310
|
ctx.db.exec(statement);
|
|
306
311
|
run(ctx, "INSERT INTO schema_meta (key, value) VALUES (?, ?)", SCHEMA_VERSION_KEY, String(SCHEMA_VERSION));
|
|
307
312
|
});
|
|
@@ -351,6 +356,8 @@ export function ensureSchema(ctx) {
|
|
|
351
356
|
ensureAssignmentCleanupSchema(ctx);
|
|
352
357
|
}
|
|
353
358
|
function ensureAssignmentCleanupSchema(ctx) {
|
|
359
|
+
for (const statement of EXPIRY_INDEXES)
|
|
360
|
+
ctx.db.exec(statement);
|
|
354
361
|
const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
|
|
355
362
|
if (hasColumn() && getRow(ctx, "SELECT 1 FROM sqlite_master WHERE name = 'operations_assignment_cleanup'"))
|
|
356
363
|
return;
|
|
@@ -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(() => {
|
package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* synchronous and transactional; a refusal throws `StoreError` with a typed code
|
|
9
9
|
* and leaves no partial record.
|
|
10
10
|
*/
|
|
11
|
+
import { expireWaits, overdueOperations } from "./expiry.domain.mjs";
|
|
11
12
|
import { setUpgradeFence } from "./upgrade.domain.mjs";
|
|
12
13
|
import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks } from "./background-parent-callbacks.domain.mjs";
|
|
13
14
|
import { BackgroundRequests } from "./background-requests.domain.mjs";
|
|
@@ -51,6 +52,8 @@ export function openStore(options) {
|
|
|
51
52
|
}
|
|
52
53
|
};
|
|
53
54
|
const store = {
|
|
55
|
+
overdueOperations() { alive(); return overdueOperations(ctx); },
|
|
56
|
+
expireWaits() { alive(); return expireWaits(ctx); },
|
|
54
57
|
subagentLaunchJournal() { alive(); return new SubagentLaunchJournal(ctx, alive); },
|
|
55
58
|
resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
|
|
56
59
|
handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
|
|
@@ -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 fixed launch domain from packages/pi-better-background-tasks/src/shared-operation-coordinator/src/task-lifetime.ts. Do not edit directly.
|
|
2
|
+
// Generated from packages/operation-coordinator/src/task-lifetime.ts. Do not edit directly.
|
|
3
|
+
/** Absolute wall-clock limit, including time spent waiting for a runner. */
|
|
4
|
+
export const MAX_TASK_LIFETIME_MS = 24 * 60 * 60 * 1000;
|
|
5
|
+
export function taskDeadline(startedAt, requestedDeadline) {
|
|
6
|
+
return Math.min(startedAt + MAX_TASK_LIFETIME_MS, requestedDeadline ?? Infinity);
|
|
7
|
+
}
|
package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-lifetime.ts
ADDED
|
@@ -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
|
+
}
|
package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.domain.mjs
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* the cancellation epoch it observed. Cancellation invalidates the active resume
|
|
16
16
|
* claim, and a claim whose epoch no longer matches can never publish an attempt.
|
|
17
17
|
*/
|
|
18
|
+
import { taskDeadline } from "./task-lifetime.domain.mjs";
|
|
18
19
|
import { randomUUID } from "node:crypto";
|
|
19
20
|
import { StoreError } from "./errors.domain.mjs";
|
|
20
21
|
import { acknowledgeGenerationOutbox, enqueueReadyGeneration, releaseGenerationPins, voidGenerationOutbox, } from "./outbox.domain.mjs";
|
|
@@ -370,21 +371,25 @@ export function cancelWait(ctx, input) {
|
|
|
370
371
|
throw new StoreError("wait-phase", `Wait ${waitId} generation ${generation} is already ${wait.phase}; cancellation is recorded once and cannot be repeated or replaced.`);
|
|
371
372
|
}
|
|
372
373
|
assertExpectedEpoch(wait, expectedCancelEpoch);
|
|
373
|
-
|
|
374
|
-
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);
|
|
375
|
-
const activeClaimRows = getRows(ctx, "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')", waitId, generation);
|
|
376
|
-
const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
|
|
377
|
-
run(ctx, `UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
|
|
378
|
-
WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`, at, reason, waitId, generation);
|
|
379
|
-
const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
|
|
380
|
-
releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
|
|
381
|
-
return {
|
|
382
|
-
wait: requireWait(ctx, waitId, generation),
|
|
383
|
-
invalidatedClaimIds,
|
|
384
|
-
voidedOutboxIds,
|
|
385
|
-
};
|
|
374
|
+
return cancelGeneration(ctx, waitId, generation, reason);
|
|
386
375
|
});
|
|
387
376
|
}
|
|
377
|
+
/** Caller holds the write transaction and has selected a nonterminal generation. */
|
|
378
|
+
export function cancelGeneration(ctx, waitId, generation, reason) {
|
|
379
|
+
const at = ctx.now();
|
|
380
|
+
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);
|
|
381
|
+
const activeClaimRows = getRows(ctx, "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')", waitId, generation);
|
|
382
|
+
const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
|
|
383
|
+
run(ctx, `UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
|
|
384
|
+
WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`, at, reason, waitId, generation);
|
|
385
|
+
const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
|
|
386
|
+
releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
|
|
387
|
+
return {
|
|
388
|
+
wait: requireWait(ctx, waitId, generation),
|
|
389
|
+
invalidatedClaimIds,
|
|
390
|
+
voidedOutboxIds,
|
|
391
|
+
};
|
|
392
|
+
}
|
|
388
393
|
// ---- resume claims ------------------------------------------------------
|
|
389
394
|
export function claimResume(ctx, input) {
|
|
390
395
|
const waitId = requireId("waitId", input.waitId);
|
|
@@ -395,6 +400,8 @@ export function claimResume(ctx, input) {
|
|
|
395
400
|
return ctx.transaction(() => {
|
|
396
401
|
assertCurrentGeneration(ctx, waitId, generation);
|
|
397
402
|
const wait = requireWait(ctx, waitId, generation);
|
|
403
|
+
if (ctx.now() >= taskDeadline(wait.createdAt))
|
|
404
|
+
throw new StoreError("wait-phase", "The 24-hour wait lifetime has expired.");
|
|
398
405
|
const active = getRows(ctx, "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')", waitId, generation)[0];
|
|
399
406
|
if (active) {
|
|
400
407
|
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.`);
|
|
@@ -439,6 +446,8 @@ export function publishResumeAttempt(ctx, input) {
|
|
|
439
446
|
return ctx.transaction(() => {
|
|
440
447
|
assertCurrentGeneration(ctx, waitId, generation);
|
|
441
448
|
const wait = requireWait(ctx, waitId, generation);
|
|
449
|
+
if (ctx.now() >= taskDeadline(wait.createdAt))
|
|
450
|
+
throw new StoreError("wait-phase", "The 24-hour wait lifetime has expired.");
|
|
442
451
|
const claim = requireClaim(ctx, claimId);
|
|
443
452
|
if (claim.waitId !== waitId || claim.generation !== generation) {
|
|
444
453
|
throw new StoreError("claim-state", `Resume claim ${claimId} belongs to ${claim.waitId} generation ${claim.generation}, not ${waitId} generation ${generation}.`);
|