pi-better-server 0.5.0 → 0.6.0
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 +4 -1
- package/scripts/copy-pi-test-providers.mjs +10 -0
- package/scripts/event-publication/README.md +26 -0
- package/scripts/event-publication/commit.mjs +21 -0
- package/scripts/event-publication/measure.mjs +37 -5
- package/scripts/event-publication/writer.mjs +3 -8
- package/scripts/measure-full-runtime/probe.mjs +4 -2
- package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
- package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
- package/scripts/measure-shared-reads.mjs +2 -1
- package/scripts/private-runtime/package-lock.json +18 -0
- package/scripts/private-runtime/package.json +4 -1
- package/scripts/source-provenance.mjs +2 -2
- package/scripts/test-on-pi.sh +2 -9
- package/src/handshake.ts +1 -1
- package/src/hosted-session.ts +32 -4
- package/src/maintenance.ts +35 -7
- package/src/registry.ts +28 -4
- package/src/runtime/attempt-invalidation.ts +54 -0
- package/src/runtime/background-history.ts +151 -45
- package/src/runtime/background-policy.ts +9 -4
- package/src/runtime/background-tools.ts +131 -23
- package/src/runtime/background.ts +351 -68
- package/src/runtime/cancellation.ts +28 -7
- package/src/runtime/catalog-sources.ts +199 -0
- package/src/runtime/catalog.ts +53 -21
- package/src/runtime/client.ts +22 -2
- package/src/runtime/domain/assignment-inbox.mjs +119 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -1
- package/src/runtime/domain/assignment-observation.mjs +43 -35
- package/src/runtime/domain/background/process-identity.mjs +20 -2
- package/src/runtime/domain/background/process.mjs +3 -3
- package/src/runtime/domain/background/registry.mjs +61 -3
- package/src/runtime/domain/background/types.mjs +1 -0
- package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
- package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
- package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
- package/src/runtime/domain/background-service/goal-provider.ts +31 -16
- package/src/runtime/domain/background-service/index.domain.mjs +6 -9
- package/src/runtime/domain/background-service/index.ts +6 -9
- package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
- package/src/runtime/domain/background-service/managed-authority.ts +5 -3
- package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
- package/src/runtime/domain/background-service/managed-client.ts +20 -7
- package/src/runtime/domain/background-service/managed-frontend.domain.mjs +75 -17
- package/src/runtime/domain/background-service/managed-frontend.ts +62 -17
- package/src/runtime/domain/background-service/navigator-provider.domain.mjs +16 -5
- package/src/runtime/domain/background-service/navigator-provider.ts +15 -5
- package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
- package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
- package/src/runtime/domain/background-service/observed-waits.domain.mjs +170 -27
- package/src/runtime/domain/background-service/observed-waits.ts +154 -30
- package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
- package/src/runtime/domain/background-service/process-identity.ts +18 -2
- package/src/runtime/domain/background-service/process.domain.mjs +3 -3
- package/src/runtime/domain/background-service/process.ts +3 -3
- package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
- package/src/runtime/domain/background-service/registry.ts +53 -5
- package/src/runtime/domain/background-service/runtime.domain.mjs +32 -16
- package/src/runtime/domain/background-service/runtime.ts +19 -9
- package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
- package/src/runtime/domain/background-service/sandbox.ts +14 -11
- package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
- package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
- package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
- package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
- package/src/runtime/domain/background-service/shared-navigator.domain.mjs +218 -13
- package/src/runtime/domain/background-service/shared-navigator.ts +197 -14
- package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +21 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +34 -8
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
- package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
- package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
- package/src/runtime/domain/background-service/supervisor/generated/process.mjs +3 -3
- package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
- package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
- package/src/runtime/domain/background-service/tools.domain.mjs +31 -24
- package/src/runtime/domain/background-service/tools.ts +41 -38
- package/src/runtime/domain/background-service/types.domain.mjs +1 -0
- package/src/runtime/domain/background-service/types.ts +3 -1
- package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
- package/src/runtime/domain/background-service/work-observation.ts +46 -19
- package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
- package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
- package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
- package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
- package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
- package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
- package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
- package/src/runtime/domain/coordinator/src/store.mjs +21 -3
- package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
- package/src/runtime/domain/coordinator/src/types.mjs +1 -1
- package/src/runtime/domain/health-observation.d.mts +3 -1
- package/src/runtime/domain/health-observation.mjs +189 -190
- package/src/runtime/domain/log-cursor.d.mts +2 -0
- package/src/runtime/domain/log-cursor.mjs +85 -16
- package/src/runtime/domain/parse.d.mts +4 -1
- package/src/runtime/domain/parse.mjs +50 -5
- package/src/runtime/domain/sandbox-policy/README.md +61 -63
- package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
- package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
- package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
- package/src/runtime/domain/sandbox-policy/index.ts +52 -9
- package/src/runtime/domain/sandbox-policy/package.json +1 -1
- package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
- package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
- package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
- package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
- package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
- package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
- package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
- package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
- package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
- package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
- package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
- package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
- package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
- package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
- package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
- package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
- package/src/runtime/domain/subagents/README.md +1 -1
- package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +12 -6
- package/src/runtime/domain/subagents/assignment-outcomes.ts +11 -5
- package/src/runtime/domain/subagents/assignment-report.domain.mjs +87 -24
- package/src/runtime/domain/subagents/assignment-report.ts +83 -19
- package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
- package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
- package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
- package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
- package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
- package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
- package/src/runtime/domain/subagents/catalog-store.ts +27 -20
- package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
- package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
- package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
- package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
- package/src/runtime/domain/subagents/child-operations.ts +80 -1
- package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
- package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
- package/src/runtime/domain/subagents/child-process-list.ts +8 -0
- package/src/runtime/domain/subagents/config.domain.mjs +49 -2
- package/src/runtime/domain/subagents/config.ts +46 -2
- package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
- package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
- package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
- package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
- package/src/runtime/domain/subagents/extensions.mjs +11 -13
- package/src/runtime/domain/subagents/finalization.domain.mjs +12 -0
- package/src/runtime/domain/subagents/finalization.ts +15 -0
- package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
- package/src/runtime/domain/subagents/goal-provider.ts +44 -2
- package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
- package/src/runtime/domain/subagents/health-observation.ts +43 -48
- package/src/runtime/domain/subagents/index.domain.mjs +296 -123
- package/src/runtime/domain/subagents/index.ts +257 -98
- package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
- package/src/runtime/domain/subagents/launch-context.ts +23 -0
- package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
- package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
- package/src/runtime/domain/subagents/log-cursor.ts +91 -15
- package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
- package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +6 -3
- package/src/runtime/domain/subagents/managed-launch-client.ts +6 -3
- package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
- package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
- package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
- package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
- package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
- package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
- package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
- package/src/runtime/domain/subagents/owned-exit.ts +12 -0
- package/src/runtime/domain/subagents/package.json +1 -1
- package/src/runtime/domain/subagents/parse.domain.mjs +50 -5
- package/src/runtime/domain/subagents/parse.ts +48 -6
- package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
- package/src/runtime/domain/subagents/permission-policy.ts +41 -8
- package/src/runtime/domain/subagents/process-identity.mjs +33 -0
- package/src/runtime/domain/subagents/registry.domain.mjs +47 -33
- package/src/runtime/domain/subagents/registry.ts +54 -33
- package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
- package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
- package/src/runtime/domain/subagents/shared-catalog.domain.mjs +6 -23
- package/src/runtime/domain/subagents/shared-catalog.ts +6 -14
- package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
- package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
- package/src/runtime/domain/subagents/shared-navigator.domain.mjs +218 -13
- package/src/runtime/domain/subagents/shared-navigator.ts +197 -14
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +21 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +34 -8
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
- package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
- package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
- package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
- package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
- package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
- package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
- package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
- package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
- package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
- package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
- package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
- package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
- package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
- package/src/runtime/domain/subagents/task-policy.domain.mjs +1 -1
- package/src/runtime/domain/subagents/task-policy.ts +3 -1
- package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
- package/src/runtime/domain/subagents/timing.ts +10 -1
- package/src/runtime/domain/subagents/work-observation.domain.mjs +77 -16
- package/src/runtime/domain/subagents/work-observation.ts +71 -16
- package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
- package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
- package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
- package/src/runtime/domain/subagents/worker-waits.ts +93 -34
- package/src/runtime/health-config.ts +27 -11
- package/src/runtime/log-checkpoints.ts +117 -0
- package/src/runtime/mutation-store.ts +5 -4
- package/src/runtime/queries.ts +25 -2
- package/src/runtime/query-executor.ts +149 -28
- package/src/runtime/query-worker.mjs +106 -21
- package/src/runtime/read-model.ts +846 -120
- package/src/runtime/read-watchdog-probe.ts +4 -0
- package/src/runtime/result-supervision.ts +188 -16
- package/src/runtime/source-watch.ts +175 -0
- package/src/runtime/subagent-launch.ts +11 -4
- package/src/runtime/work-budget.ts +130 -0
- package/src/runtime/work-client.d.mts +8 -0
- package/src/runtime/work-client.mjs +150 -7
- package/src/server.ts +104 -23
- package/src/session-activity.ts +26 -4
- package/src/version.ts +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash, timingSafeEqual } from "node:crypto";
|
|
2
|
-
import { lstatSync, readFileSync, realpathSync } from "node:fs";
|
|
2
|
+
import { lstatSync, mkdirSync, readFileSync, realpathSync, statSync, watch, type FSWatcher } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
import { createAgentSession, DefaultResourceLoader, SessionManager, SettingsManager, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
@@ -9,7 +9,7 @@ import extension from "./index.ts";
|
|
|
9
9
|
import { bindRuntimeOutcomeStore } from "./assignment-outcomes.ts";
|
|
10
10
|
import { catalogSnapshotFromWire } from "./catalog-store.ts";
|
|
11
11
|
import { openLaunchJournal, launchDigest } from "./managed-launch-journal.mjs";
|
|
12
|
-
import { nextRunId, processStartToken, listMetas, writeMeta, listActiveMetasForParent, effectiveStatus, readMeta, readParkRecord, updateParkRecord } from "./registry.ts";
|
|
12
|
+
import { baseDir, nextRunId, processStartToken, listMetas, writeMeta, listActiveMetasForParent, effectiveStatus, readMeta, readParkRecord, updateParkRecord } from "./registry.ts";
|
|
13
13
|
import { recoverLaunchMetadata } from "./managed-launch-recovery.ts";
|
|
14
14
|
import { assertSubagentHandoff } from "./managed-launch-ownership.ts";
|
|
15
15
|
import { createOwnerCapacityGates } from "./capacity.mjs";
|
|
@@ -37,19 +37,127 @@ export class ManagedSubagentHost {
|
|
|
37
37
|
private closeJournal: () => void;
|
|
38
38
|
private epoch: number;
|
|
39
39
|
private pending = 0;
|
|
40
|
+
private requestSequence = 0;
|
|
41
|
+
private requestRecords = new Map<number, any>();
|
|
42
|
+
private foldRecord?: { kind: string; ids: readonly string[]; lastProgressAt: number; nextDeadline: number; recovery: string };
|
|
43
|
+
private acceptedRequestLive = false;
|
|
40
44
|
private continuationWindow = { started: 0, admitted: 0 };
|
|
41
45
|
private continuationFailures = new Map<string, { failures: number; retryAt: number; reason: string }>();
|
|
42
|
-
private workerHost?: { start(ctx?: unknown): void; close(): void; service: { continuationReady: boolean } };
|
|
46
|
+
private workerHost?: { start(ctx?: unknown): void; close(): void; advancingWaits?(): any[]; service: { continuationReady: boolean } };
|
|
43
47
|
private path: string;
|
|
48
|
+
private known = new Map<string, any>();
|
|
49
|
+
private healthClose?: () => void;
|
|
50
|
+
private healthChanged?: (id: string) => void;
|
|
51
|
+
private lifecycleMetrics = { passes: 0, entities: 0, deadlineLatenessMs: 0 };
|
|
52
|
+
private healthDue = new Map<string, number>();
|
|
53
|
+
private writerProofs = new Map<string, { verified: boolean; checkedAt: number; unknownSince: number }>();
|
|
54
|
+
lifecycleReasons() {
|
|
55
|
+
const now = Date.now();
|
|
56
|
+
const writers = [...this.known.values()].filter(meta => ["running", "orphaned"].includes(meta.status)).flatMap(meta => {
|
|
57
|
+
const proof = this.writerProofs.get(meta.id);
|
|
58
|
+
if (!proof || !proof.verified && now >= proof.unknownSince + this.verificationMs) return [];
|
|
59
|
+
return [{
|
|
60
|
+
kind: proof.verified ? "worker" : "verification", id: meta.id, owner: meta.callbackOrigin, writer: { pid: meta.pid, start: meta.pidStartTime },
|
|
61
|
+
management: meta.management, lastProgressAt: meta.timing?.lastProgressAt ?? meta.startedAt,
|
|
62
|
+
nextDeadline: proof.verified ? this.healthDue.get(meta.id) ?? null : proof.unknownSince + this.verificationMs,
|
|
63
|
+
recovery: proof.verified ? "current-managed-writer-supervision" : "writer-unverified-no-takeover",
|
|
64
|
+
}]; });
|
|
65
|
+
return [...this.requestRecords.values(), ...(this.foldRecord ? [{ ...this.foldRecord }] : []),
|
|
66
|
+
...(this.acceptedRequestLive ? this.journal.lifecycleReasons(this.current.ownerKey, this.current.key) : []).map(reason => ({ ...reason,
|
|
67
|
+
management: { ...reason.management, instance: this.instance }, writerFence: 'current-managed-launch-epoch' })),
|
|
68
|
+
...writers, ...(this.workerHost?.advancingWaits?.() ?? [])];
|
|
69
|
+
}
|
|
70
|
+
private observeHealth(reconcile: (ids: readonly string[]) => void) {
|
|
71
|
+
this.healthClose?.();
|
|
72
|
+
let closed = false, scheduled = false;
|
|
73
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
74
|
+
const watchers: FSWatcher[] = [], dirty = new Set(this.known.keys()), signatures = new Map<string, string>();
|
|
75
|
+
const signature = (meta: any) => {
|
|
76
|
+
let log = "missing";
|
|
77
|
+
try { const info = statSync(meta.logPath, { bigint: true }); log = `${info.ino}:${info.size}:${info.mtimeNs}`; } catch { /* No log yet. */ }
|
|
78
|
+
return JSON.stringify(meta) + log;
|
|
79
|
+
};
|
|
80
|
+
const schedule = () => {
|
|
81
|
+
if (closed || scheduled) return;
|
|
82
|
+
scheduled = true;
|
|
83
|
+
setImmediate(() => { scheduled = false; if (!closed) pass(); });
|
|
84
|
+
};
|
|
85
|
+
const hint = (id: string) => {
|
|
86
|
+
const meta = readMeta(id);
|
|
87
|
+
if (meta?.management?.root === this.root && meta.management.instance === this.instance && meta.management.epoch === this.epoch) {
|
|
88
|
+
if (signatures.get(id) === signature(meta)) return;
|
|
89
|
+
if (!this.writerProofs.has(id)) this.writerProofs.set(id, { verified: false, checkedAt: Date.now(), unknownSince: Date.now() });
|
|
90
|
+
this.known.set(id, meta); dirty.add(id); schedule();
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
this.healthChanged = hint;
|
|
94
|
+
const pass = () => {
|
|
95
|
+
const now = Date.now();
|
|
96
|
+
for (const [id, due] of this.healthDue) if (due <= now) dirty.add(id);
|
|
97
|
+
const ids = [...dirty].slice(0, 32);
|
|
98
|
+
ids.forEach(id => dirty.delete(id));
|
|
99
|
+
if (ids.length) {
|
|
100
|
+
const release = this.enterControl?.();
|
|
101
|
+
if (this.enterControl && !release) {
|
|
102
|
+
ids.forEach(id => dirty.add(id));
|
|
103
|
+
timer = setTimeout(schedule, 1000); timer.unref(); return;
|
|
104
|
+
}
|
|
105
|
+
this.lifecycleMetrics.passes++; this.lifecycleMetrics.entities += ids.length;
|
|
106
|
+
for (const id of ids) this.lifecycleMetrics.deadlineLatenessMs = Math.max(this.lifecycleMetrics.deadlineLatenessMs, now - (this.healthDue.get(id) ?? now));
|
|
107
|
+
try { reconcile(ids); } finally { release?.(); }
|
|
108
|
+
for (const id of ids) {
|
|
109
|
+
const meta = readMeta(id);
|
|
110
|
+
if (meta) this.known.set(id, meta); else this.known.delete(id);
|
|
111
|
+
if (meta) signatures.set(id, signature(meta));
|
|
112
|
+
this.healthDue.delete(id);
|
|
113
|
+
if (!meta || !["running", "orphaned"].includes(meta.status)) {
|
|
114
|
+
this.writerProofs.delete(id);
|
|
115
|
+
if (meta?.completionCallbackPendingAt && !meta.completionCallbackSentAt && !meta.completionCallbackSuppressedAt) this.healthDue.set(id, now + 15000);
|
|
116
|
+
else { this.known.delete(id); signatures.delete(id); }
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const verified = Boolean(meta.pidStartTime && processStartToken(meta.pid) === meta.pidStartTime && processExists(meta.pid));
|
|
120
|
+
const prior = this.writerProofs.get(id);
|
|
121
|
+
this.writerProofs.set(id, { verified, checkedAt: now, unknownSince: verified ? now : prior?.unknownSince ?? now });
|
|
122
|
+
const timing = meta.timing;
|
|
123
|
+
const deadlines = [now + 15000, timing?.ceilingAt,
|
|
124
|
+
!timing?.deadlineWakeSentAt ? timing?.deadlineAt : undefined,
|
|
125
|
+
timing?.steerDeliveredAt ? timing.steerDeliveredAt + timing.graceMs : undefined]
|
|
126
|
+
.filter((value): value is number => typeof value === "number" && value > now);
|
|
127
|
+
this.healthDue.set(id, Math.min(...deadlines));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (dirty.size) schedule();
|
|
131
|
+
if (timer) clearTimeout(timer);
|
|
132
|
+
if (this.healthDue.size) {
|
|
133
|
+
const next = [...this.healthDue.values()].reduce((a, b) => Math.min(a, b), Infinity);
|
|
134
|
+
timer = setTimeout(schedule, Math.max(1, next - Date.now())); timer.unref();
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
try {
|
|
138
|
+
mkdirSync(join(baseDir(), "runs"), { recursive: true });
|
|
139
|
+
const watcher = watch(join(baseDir(), "runs"), { recursive: true }, (_event, file) => {
|
|
140
|
+
const id = file && String(file).split(/[/\\]/)[0];
|
|
141
|
+
if (id && /^[A-Za-z0-9_-]+$/.test(id)) hint(id);
|
|
142
|
+
});
|
|
143
|
+
watcher.on("error", () => watcher.close()); watchers.push(watcher);
|
|
144
|
+
} catch { /* Known active writers still have independent liveness deadlines. */ }
|
|
145
|
+
schedule();
|
|
146
|
+
return this.healthClose = () => {
|
|
147
|
+
closed = true; if (timer) clearTimeout(timer); watchers.forEach(watcher => watcher.close());
|
|
148
|
+
this.healthChanged = undefined; this.healthDue.clear();
|
|
149
|
+
};
|
|
150
|
+
}
|
|
44
151
|
private capacityFor = createOwnerCapacityGates(({ pid, start }: { pid: number; start: string }) =>
|
|
45
152
|
listActiveMetasForParent(pid).filter(meta => meta.spawnPidStartTime === start && effectiveStatus(meta) === "running").length
|
|
46
153
|
+ this.journal.unresolvedAttempts().filter((attempt: any) => attempt.capacityOwner?.pid === pid && attempt.capacityOwner?.start === start && !readMeta(attempt.id)).length);
|
|
47
154
|
get busy() { return this.pending > 0 || Boolean(this.failureResponse); }
|
|
48
155
|
status() {
|
|
49
156
|
return { owner: "server", instanceId: this.instance, runtimeEpoch: this.epoch,
|
|
157
|
+
lifecycle: { ...this.lifecycleMetrics, activeDeadlines: this.healthDue.size },
|
|
50
158
|
inFlight: this.pending, failureFold: { worker: Boolean(this.failureWorker), inFlight: Boolean(this.failureResponse) }, continuationReady: this.workerHost?.service.continuationReady ?? false, continuationUnavailable: [...this.continuationFailures].map(([key, value]) => ({ key, ...value })), unresolvedAttempts: this.journal.unresolvedAttempts().filter((attempt: any) => !readMeta(attempt.id)).length };
|
|
51
159
|
}
|
|
52
|
-
constructor(private root: string, private instance: string, private catalog: any, sharedStore?: unknown, private createWorkerHost?: (pi: ExtensionAPI) => NonNullable<ManagedSubagentHost["workerHost"]>, private readPermissions?: () => unknown) {
|
|
160
|
+
constructor(private root: string, private instance: string, private catalog: any, sharedStore?: unknown, private createWorkerHost?: (pi: ExtensionAPI) => NonNullable<ManagedSubagentHost["workerHost"]>, private readPermissions?: () => unknown, private verificationMs = 30000, private enterControl?: () => (() => void) | undefined) {
|
|
53
161
|
this.current = { pid: process.pid, start: processStartToken(process.pid), owner: { workspace: root, sessionId: "runtime-recovery" } };
|
|
54
162
|
this.path = join(root, "operation-coordinator.sqlite");
|
|
55
163
|
const active = listMetas({ includeArchived: false });
|
|
@@ -125,6 +233,10 @@ export class ManagedSubagentHost {
|
|
|
125
233
|
}
|
|
126
234
|
}
|
|
127
235
|
async recover() {
|
|
236
|
+
for (const meta of listMetas({ includeArchived: false })) if (meta.management?.root === this.root) {
|
|
237
|
+
this.known.set(meta.id, meta);
|
|
238
|
+
this.writerProofs.set(meta.id, { verified: false, checkedAt: Date.now(), unknownSince: Date.now() });
|
|
239
|
+
}
|
|
128
240
|
if (listMetas({ includeArchived: false }).some(meta => meta.management?.root === this.root)) await this.initialize();
|
|
129
241
|
}
|
|
130
242
|
private grant(authority: any) {
|
|
@@ -152,12 +264,14 @@ export class ManagedSubagentHost {
|
|
|
152
264
|
return this.initializing ??= (async () => {
|
|
153
265
|
const host = this;
|
|
154
266
|
const port: ManagedLaunchPort = {
|
|
267
|
+
observeHealth: reconcile => host.observeHealth(reconcile),
|
|
268
|
+
activeProviders: () => host.current.activeProviders ?? {},
|
|
155
269
|
backgroundTools: () => host.current.background?.available === true ? host.current.background.tools : [],
|
|
156
270
|
get owner() { return { pid: host.current.pid, start: host.current.start }; },
|
|
157
271
|
get identity() { return { root: host.root, instance: host.instance, epoch: host.epoch }; },
|
|
158
272
|
continuationContext: () => host.executionContext(host.current),
|
|
159
273
|
dispatchContinuation: (park, run) => host.dispatchContinuation(park, run),
|
|
160
|
-
supervised: () =>
|
|
274
|
+
supervised: () => [...host.known.values()].filter(meta => port.owns(meta)),
|
|
161
275
|
owns: meta => meta.management?.root === host.root && meta.management?.instance === host.instance && meta.management?.epoch === host.epoch,
|
|
162
276
|
assertCurrent: () => host.journal.current(host.epoch),
|
|
163
277
|
capacity: () => host.capacityFor(host.current),
|
|
@@ -167,7 +281,7 @@ export class ManagedSubagentHost {
|
|
|
167
281
|
const command = host.catalog.connection();
|
|
168
282
|
command({ type: "runtime_register_catalog", cwd: host.current.owner.workspace,
|
|
169
283
|
sessionId: host.current.owner.sessionId, authority: host.current.catalogAuthority });
|
|
170
|
-
return catalogSnapshotFromWire(command({ type: "runtime_get_catalog", overlay: configuration.getSessionSettings?.() ?? configuration.sessionSettings }));
|
|
284
|
+
return catalogSnapshotFromWire(command({ type: "runtime_get_catalog", fresh: true, overlay: configuration.getSessionSettings?.() ?? configuration.sessionSettings }));
|
|
171
285
|
},
|
|
172
286
|
beforeSpawn: input => {
|
|
173
287
|
assertSubagentHandoff(listMetas({ includeArchived: false }), host.root);
|
|
@@ -185,11 +299,11 @@ export class ManagedSubagentHost {
|
|
|
185
299
|
const policyDigest = input.policyPath ? launchDigest(JSON.parse(readFileSync(input.policyPath, "utf8"))) : undefined;
|
|
186
300
|
const attempt = host.journal.prepare(host.current.ownerKey, host.current.key, host.epoch, { ...input, preflightDigest, policyDigest,
|
|
187
301
|
capacityOwner: { pid: host.current.pid, start: host.current.start },
|
|
188
|
-
launchAuthority: host.current.launchAuthority ?? { owner: host.current.owner, pid: host.current.pid, start: host.current.start, settings: host.current.settings, model: host.current.model, projectTrusted: host.current.projectTrusted, background: host.current.background, permissions: host.current.permissions } });
|
|
302
|
+
launchAuthority: host.current.launchAuthority ?? { owner: host.current.owner, pid: host.current.pid, start: host.current.start, settings: host.current.settings, model: host.current.model, projectTrusted: host.current.projectTrusted, background: host.current.background, activeProviders: host.current.activeProviders, permissions: host.current.permissions } });
|
|
189
303
|
return { PI_MANAGED_SUBAGENT: JSON.stringify({ path: host.path, owner: host.current.ownerKey,
|
|
190
304
|
key: host.current.key, epoch: host.epoch, id: input.id, token: attempt.token }) };
|
|
191
305
|
},
|
|
192
|
-
spawned: (id, pid) => host.journal.spawned(host.current.ownerKey, host.current.key, host.epoch, id, pid, processStartToken(pid)),
|
|
306
|
+
spawned: (id, pid) => { host.journal.spawned(host.current.ownerKey, host.current.key, host.epoch, id, pid, processStartToken(pid)); setImmediate(() => host.healthChanged?.(id)); },
|
|
193
307
|
};
|
|
194
308
|
const cwd = this.root;
|
|
195
309
|
const settingsManager = SettingsManager.inMemory({});
|
|
@@ -235,6 +349,11 @@ export class ManagedSubagentHost {
|
|
|
235
349
|
if (failure && Date.now() < failure.retryAt) return Promise.resolve("skipped" as const);
|
|
236
350
|
this.continuationWindow.admitted++;
|
|
237
351
|
this.pending++;
|
|
352
|
+
const requestId = ++this.requestSequence;
|
|
353
|
+
this.requestRecords.set(requestId, { kind: 'continuation-request', id: requestId, waitId: park.waitId, runId: park.runId,
|
|
354
|
+
generation: park.generation, lastProgressAt: now, executionDeadline: null, nextDeadline: null,
|
|
355
|
+
recovery: 'captured-continuation-serialized-by-current-launch-journal-owner' });
|
|
356
|
+
let dispatched = false;
|
|
238
357
|
const result = this.tail.catch(() => undefined).then(async () => {
|
|
239
358
|
const saved = this.journal.attempt(park.runId)?.launchAuthority;
|
|
240
359
|
if (!saved) throw new Error("Captured continuation launch authority unavailable");
|
|
@@ -244,7 +363,9 @@ export class ManagedSubagentHost {
|
|
|
244
363
|
capturedPermissions: saved.permissions, permissions,
|
|
245
364
|
ownerKey: JSON.stringify([saved.owner.workspace, saved.owner.sessionId]),
|
|
246
365
|
digest: launchDigest({ key, runId: park.runId }) };
|
|
366
|
+
this.acceptedRequestLive = true;
|
|
247
367
|
this.api.events.emit("pi-better-sandbox:policy", { state: "enabled", ...permissions });
|
|
368
|
+
dispatched = true;
|
|
248
369
|
const outcome = await run();
|
|
249
370
|
if (outcome === "resumed") this.journal.finish(this.current.ownerKey, this.current.key, this.epoch, { status: outcome });
|
|
250
371
|
this.continuationFailures.delete(retryKey);
|
|
@@ -253,8 +374,11 @@ export class ManagedSubagentHost {
|
|
|
253
374
|
const failures = Math.min(6, (this.continuationFailures.get(retryKey)?.failures ?? 0) + 1);
|
|
254
375
|
if (this.continuationFailures.size >= 128 && !this.continuationFailures.has(retryKey)) this.continuationFailures.delete(this.continuationFailures.keys().next().value!);
|
|
255
376
|
this.continuationFailures.set(retryKey, { failures, retryAt: Date.now() + Math.min(30000, 1000 * 2 ** (failures - 1)), reason: String(error).slice(0, 500) });
|
|
377
|
+
// Let orchestration persist its existing pre-spawn hold. A skipped
|
|
378
|
+
// result would leave this exact generation ready despite refusal.
|
|
379
|
+
if (!dispatched) throw error;
|
|
256
380
|
return "skipped" as const;
|
|
257
|
-
}).finally(() => { this.pending--; });
|
|
381
|
+
}).finally(() => { this.requestRecords.delete(requestId); this.acceptedRequestLive = false; this.pending--; });
|
|
258
382
|
this.tail = result;
|
|
259
383
|
return result;
|
|
260
384
|
}
|
|
@@ -266,21 +390,29 @@ export class ManagedSubagentHost {
|
|
|
266
390
|
runId: meta.id, sessionId: meta.sessionId, status: meta.status,
|
|
267
391
|
})) }, content: [{ type: "text", text: `Original launch ${status}; no replacement attempt was dispatched.` }] };
|
|
268
392
|
}
|
|
269
|
-
handle(command: Record<string, unknown
|
|
393
|
+
handle(command: Record<string, unknown>, onAccepted?: (id: string) => void) {
|
|
270
394
|
if (Object.keys(command).some(key => !["id", "type", "authority"].includes(key))) return Promise.reject(new Error("unsupported launch field"));
|
|
271
395
|
this.pending++;
|
|
396
|
+
const requestId = ++this.requestSequence;
|
|
397
|
+
this.requestRecords.set(requestId, { kind: 'launch-request', id: requestId, phase: 'queued-unaccepted',
|
|
398
|
+
lastProgressAt: Date.now(), executionDeadline: null, nextDeadline: null,
|
|
399
|
+
recovery: 'validate-captured-native-authority-before-admission-no-detached-execution-lease' });
|
|
272
400
|
const result = this.tail.catch(() => undefined).then(async () => {
|
|
273
401
|
const record = this.grant(command.authority);
|
|
274
402
|
// A retried tool call keeps its accepted recipient even after Goal/branch edits.
|
|
275
403
|
const ownerKey = JSON.stringify([record.owner.workspace, record.owner.sessionId]);
|
|
276
404
|
const digest = launchDigest({ tool: record.tool, params: record.params });
|
|
277
405
|
const intent = this.journal.accept(ownerKey, record.key, digest, this.epoch);
|
|
406
|
+
onAccepted?.(`launch-progress:${launchDigest([ownerKey, record.key])}`);
|
|
407
|
+
this.requestRecords.set(requestId, { ...this.requestRecords.get(requestId), phase: 'accepted',
|
|
408
|
+
operation: `launch-progress:${launchDigest([ownerKey, record.key])}`, lastProgressAt: Date.now() });
|
|
278
409
|
if (intent.prior) {
|
|
279
410
|
if (intent.result) return JSON.parse(intent.result);
|
|
280
411
|
return this.recoveredResult(intent);
|
|
281
412
|
}
|
|
282
413
|
try {
|
|
283
414
|
this.current = { ...record, authority: command.authority, ownerKey, grantDigest: launchDigest(record) };
|
|
415
|
+
this.acceptedRequestLive = true;
|
|
284
416
|
await this.initialize();
|
|
285
417
|
this.api.events.emit("pi-better-sandbox:policy", { state: "enabled", ...record.permissions });
|
|
286
418
|
const context = this.executionContext(record);
|
|
@@ -296,13 +428,17 @@ export class ManagedSubagentHost {
|
|
|
296
428
|
}
|
|
297
429
|
throw error;
|
|
298
430
|
}
|
|
299
|
-
}).finally(() => { this.pending--; });
|
|
431
|
+
}).finally(() => { this.requestRecords.delete(requestId); this.acceptedRequestLive = false; this.pending--; });
|
|
300
432
|
this.tail = result;
|
|
301
433
|
return result;
|
|
302
434
|
}
|
|
303
435
|
/** One root mechanical worker; no coordinator connection or query mutations. */
|
|
304
436
|
foldTerminalFailures(ids: readonly string[]): Promise<void> {
|
|
437
|
+
let release: (() => void) | undefined;
|
|
438
|
+
let physicalExit: Promise<number> | undefined;
|
|
305
439
|
const result = this.tail.catch(() => undefined).then(async () => {
|
|
440
|
+
release = this.enterControl?.();
|
|
441
|
+
if (this.enterControl && !release) throw new Error("runtime-overloaded: failure fold source capacity");
|
|
306
442
|
this.journal.current(this.epoch);
|
|
307
443
|
if (Atomics.load(this.foldRevocation, 0)) throw new Error("failure-fold-owner-revoked");
|
|
308
444
|
if (this.failureWorkerError) throw this.failureWorkerError;
|
|
@@ -323,15 +459,32 @@ export class ManagedSubagentHost {
|
|
|
323
459
|
worker.on("exit", code => fail(new Error(`failure-fold-worker-exited: ${code}`)));
|
|
324
460
|
worker.unref();
|
|
325
461
|
}
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
462
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
463
|
+
try {
|
|
464
|
+
await new Promise<void>((resolve, reject) => {
|
|
465
|
+
this.failureResponse = { resolve, reject };
|
|
466
|
+
this.foldRecord = { kind: 'failure-fold', ids: [...ids], lastProgressAt: Date.now(), nextDeadline: Date.now() + this.verificationMs,
|
|
467
|
+
recovery: 'revoke-unacknowledged-fold-generation-at-existing-verification-deadline' };
|
|
468
|
+
timer = setTimeout(() => {
|
|
469
|
+
const error = new Error("failure-fold-verification-deadline: source worker did not acknowledge");
|
|
470
|
+
Atomics.store(this.foldRevocation, 0, 1);
|
|
471
|
+
this.failureWorkerError = error;
|
|
472
|
+
this.failureResponse = undefined;
|
|
473
|
+
physicalExit = this.failureWorker?.terminate();
|
|
474
|
+
reject(error);
|
|
475
|
+
}, this.verificationMs);
|
|
476
|
+
this.failureWorker!.postMessage({ ids });
|
|
477
|
+
});
|
|
478
|
+
} finally { this.foldRecord = undefined; if (timer) clearTimeout(timer); }
|
|
479
|
+
}).finally(() => {
|
|
480
|
+
if (physicalExit) void physicalExit.then(() => release?.(), () => undefined);
|
|
481
|
+
else release?.();
|
|
330
482
|
});
|
|
331
483
|
this.tail = result;
|
|
332
484
|
return result;
|
|
333
485
|
}
|
|
334
486
|
async close() {
|
|
487
|
+
this.healthClose?.();
|
|
335
488
|
Atomics.store(this.foldRevocation, 0, 1);
|
|
336
489
|
await this.tail.catch(() => undefined);
|
|
337
490
|
await this.failureWorker?.terminate(); this.failureWorker = undefined;
|
|
@@ -1,10 +1,6 @@
|
|
|
1
1
|
// Generated fixed launch domain from packages/pi-better-subagents/managed-launch-journal.mjs. Do not edit directly.
|
|
2
|
-
import { createHash } from "node:crypto";
|
|
3
2
|
import { openStore } from "./shared-operation-coordinator/index.domain.mjs";
|
|
4
|
-
|
|
5
|
-
: Array.isArray(value) ? value.map(ordered)
|
|
6
|
-
: Object.fromEntries(Object.keys(value).sort().map(key => [key, ordered(value[key])]));
|
|
7
|
-
export const launchDigest = value => createHash("sha256").update(JSON.stringify(ordered(value))).digest("hex");
|
|
3
|
+
export { launchDigest } from "./launch-digest.mjs";
|
|
8
4
|
/** Standalone callers own a store; server callers pass their shared mutation lease. */
|
|
9
5
|
export function openLaunchJournal(path, sharedStore) {
|
|
10
6
|
const store = sharedStore ?? openStore({ path });
|
|
@@ -4,6 +4,8 @@ import type { RunMeta } from "./registry.ts";
|
|
|
4
4
|
|
|
5
5
|
/** Fixed server adapter port; never deserialized from a socket request. */
|
|
6
6
|
export interface ManagedLaunchPort {
|
|
7
|
+
observeHealth?(reconcile: (ids: readonly string[]) => void): () => void;
|
|
8
|
+
activeProviders?(): Record<string, string>;
|
|
7
9
|
backgroundTools(): readonly string[];
|
|
8
10
|
readonly owner: { pid: number; start?: string };
|
|
9
11
|
readonly identity: { root: string; instance: string; epoch: number };
|
|
@@ -18,4 +20,6 @@ export interface ManagedLaunchPort {
|
|
|
18
20
|
workerCommand(args: string[]): { file: string; fileArgs: string[] };
|
|
19
21
|
beforeSpawn(input: { id: string; sessionId: string; lease: string; leasePath: string; preflightPath: string; policyPath?: string; permissions: unknown; recoveryMeta: RunMeta; recipe: NonNullable<RunMeta["recipe"]> }): Record<string, string>;
|
|
20
22
|
spawned(id: string, pid: number): void;
|
|
23
|
+
/** Private fixture/owner observation, never a serialized execution capability. */
|
|
24
|
+
observeExit?(id: string, completion: Promise<void>): void;
|
|
21
25
|
}
|
|
@@ -24,6 +24,7 @@ export const OPERATIONS_CONVERSATION_ID_ENV = "PI_BETTER_OPERATIONS_CONVERSATION
|
|
|
24
24
|
export const OPERATIONS_ATTEMPT_ID_ENV = "PI_BETTER_OPERATIONS_ATTEMPT_ID";
|
|
25
25
|
export const OPERATIONS_WRITER_LEASE_ID_ENV = "PI_BETTER_OPERATIONS_WRITER_LEASE_ID";
|
|
26
26
|
export const OPERATIONS_CHILD_ID_ENV = "PI_BETTER_OPERATIONS_CHILD_ID";
|
|
27
|
+
export const OPERATIONS_DEADLINE_AT_ENV = "PI_BETTER_OPERATIONS_DEADLINE_AT";
|
|
27
28
|
/**
|
|
28
29
|
* Parent-provided bridge environment. A launched background task must not
|
|
29
30
|
* inherit any of these names: the token authorizes this child, not a shell it
|
|
@@ -39,6 +40,7 @@ export const OPERATION_BRIDGE_ENV_KEYS = Object.freeze([
|
|
|
39
40
|
OPERATIONS_ATTEMPT_ID_ENV,
|
|
40
41
|
OPERATIONS_WRITER_LEASE_ID_ENV,
|
|
41
42
|
OPERATIONS_CHILD_ID_ENV,
|
|
43
|
+
OPERATIONS_DEADLINE_AT_ENV,
|
|
42
44
|
]);
|
|
43
45
|
const BRIDGE_ENV_KEY_SET = new Set(OPERATION_BRIDGE_ENV_KEYS);
|
|
44
46
|
export function findBridgeEnvironmentKey(value, seen = new Set()) {
|
|
@@ -516,9 +518,19 @@ export function canonicalToolSchema(name) {
|
|
|
516
518
|
properties: {
|
|
517
519
|
status: { type: "string", enum: ["complete", "incomplete"] },
|
|
518
520
|
reason: { type: "string", minLength: 1, maxLength: 2048 },
|
|
521
|
+
remaining_work: { type: "array", minItems: 1, maxItems: 8, items: { type: "string", minLength: 1, maxLength: 1024 }, description: "For incomplete work, list the concrete steps still required." },
|
|
522
|
+
blocker: { type: "object", additionalProperties: false, required: ["kind", "reason"], properties: {
|
|
523
|
+
kind: { type: "string", enum: ["permission", "external-input"] },
|
|
524
|
+
reason: { type: "string", minLength: 1, maxLength: 1024 },
|
|
525
|
+
}, description: "Use only for an actual permission or external-input blocker that prevents further local work." },
|
|
519
526
|
evidence: { type: "array", minItems: 1, maxItems: 4, items: {
|
|
520
527
|
type: "object", additionalProperties: false, required: ["path", "explanation"],
|
|
521
|
-
properties: {
|
|
528
|
+
properties: {
|
|
529
|
+
path: { type: "string", minLength: 1, maxLength: 1024, description: "An existing workspace file. Foreign paths and credential files are refused." },
|
|
530
|
+
explanation: { type: "string", minLength: 1, maxLength: 1024 },
|
|
531
|
+
offset: { type: "integer", minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description: "Zero-based byte offset, inclusive. Requires max_bytes." },
|
|
532
|
+
max_bytes: { type: "integer", minimum: 1, maximum: 65536, description: "Retain at most this many bytes from offset (default zero), ending at EOF if earlier. Required for files larger than 65536 bytes." },
|
|
533
|
+
},
|
|
522
534
|
} },
|
|
523
535
|
},
|
|
524
536
|
};
|
|
@@ -537,7 +549,7 @@ const TOOL_LABELS = {
|
|
|
537
549
|
acknowledge_operation_result: "Acknowledge Operation Result",
|
|
538
550
|
};
|
|
539
551
|
const TOOL_DESCRIPTIONS = {
|
|
540
|
-
report_assignment_result: "Record your complete or incomplete assignment judgment with retained workspace
|
|
552
|
+
report_assignment_result: "Record your complete or incomplete assignment judgment with retained workspace file evidence before your final answer. Each retained file or explicit byte excerpt is limited to 65536 bytes; use offset and max_bytes for larger source files. A refused report may be corrected and retried. Once retained, only identical retries are allowed. Reporting does not terminalize the assignment, interpret waits or record parent acceptance.",
|
|
541
553
|
bg_task_spawn: "Start one long-running background operation through the trusted parent supervisor. Returns immediately. The operation is owned by the parent, not by this worker process.",
|
|
542
554
|
bg_task_watch: "Start one background command watch through the trusted parent supervisor. Returns immediately. The operation is owned by the parent, not by this worker process.",
|
|
543
555
|
bg_task_status: "Inspect one operation owned by this worker conversation. Only task ids accepted by the parent ownership check are readable.",
|
|
@@ -546,6 +558,7 @@ const TOOL_DESCRIPTIONS = {
|
|
|
546
558
|
acknowledge_operation_result: "Interpret the exact terminal evidence of a registered wait and mark that wait generation consumed. The disposition does not complete the assignment by itself.",
|
|
547
559
|
};
|
|
548
560
|
const TOOL_GUIDELINES = {
|
|
561
|
+
report_assignment_result: ["Continue available local work until the assignment is complete or a concrete blocker prevents progress. For incomplete work, provide remaining_work and any actual permission or external-input blocker. If evidence is refused, correct the path or excerpt range and retry before returning."],
|
|
549
562
|
bg_task_spawn: ["Use bg_task_spawn for established long commands; do not emulate background execution with polling, sleep loops, nohup or shell detachment."],
|
|
550
563
|
bg_task_watch: ["Use bg_task_watch for repeated observation. Do not run a foreground poll loop."],
|
|
551
564
|
wait_for_operations: ["Call wait_for_operations only when no independent work remains. A final answer that says you are waiting is not a park request."],
|
|
@@ -581,6 +594,7 @@ export function descriptorsForCapabilities(capabilities) {
|
|
|
581
594
|
* failure, not a reason to expose an extra tool.
|
|
582
595
|
*/
|
|
583
596
|
export function normalizeToolDescriptors(tools, capabilities) {
|
|
597
|
+
assertWaitToolDependencies(capabilities, tools.map(tool => tool.name));
|
|
584
598
|
const seen = new Set();
|
|
585
599
|
const normalized = [];
|
|
586
600
|
for (const tool of tools) {
|
|
@@ -604,6 +618,17 @@ export function normalizeToolDescriptors(tools, capabilities) {
|
|
|
604
618
|
}
|
|
605
619
|
return deepFreeze(normalized.sort((a, b) => a.name.localeCompare(b.name)));
|
|
606
620
|
}
|
|
621
|
+
/** A parked conversation must be able to read and interpret its terminal evidence. */
|
|
622
|
+
export function assertWaitToolDependencies(capabilities, names) {
|
|
623
|
+
if (!capabilities.wait && !capabilities.parking && !names.includes(WAIT_OPERATIONS_TOOL))
|
|
624
|
+
return;
|
|
625
|
+
if (!capabilities.wait || !capabilities.parking || !names.includes(WAIT_OPERATIONS_TOOL)
|
|
626
|
+
|| !capabilities.acknowledge || !names.includes(ACKNOWLEDGE_OPERATION_TOOL)
|
|
627
|
+
|| !((capabilities.background.status && names.includes("bg_task_status"))
|
|
628
|
+
|| (capabilities.background.log && names.includes("bg_task_log")))) {
|
|
629
|
+
throw new OperationBridgeError("invalid-request", "wait_for_operations requires parking, acknowledge_operation_result and at least one terminal evidence reader (bg_task_status or bg_task_log) in the final authorized tools list. Add the missing tools explicitly or remove wait_for_operations.");
|
|
630
|
+
}
|
|
631
|
+
}
|
|
607
632
|
export function capabilityForTool(name, capabilities) {
|
|
608
633
|
switch (name) {
|
|
609
634
|
case "report_assignment_result": return capabilities.reportAssignment === true;
|
|
@@ -25,6 +25,7 @@ export const OPERATIONS_CONVERSATION_ID_ENV = "PI_BETTER_OPERATIONS_CONVERSATION
|
|
|
25
25
|
export const OPERATIONS_ATTEMPT_ID_ENV = "PI_BETTER_OPERATIONS_ATTEMPT_ID";
|
|
26
26
|
export const OPERATIONS_WRITER_LEASE_ID_ENV = "PI_BETTER_OPERATIONS_WRITER_LEASE_ID";
|
|
27
27
|
export const OPERATIONS_CHILD_ID_ENV = "PI_BETTER_OPERATIONS_CHILD_ID";
|
|
28
|
+
export const OPERATIONS_DEADLINE_AT_ENV = "PI_BETTER_OPERATIONS_DEADLINE_AT";
|
|
28
29
|
|
|
29
30
|
/**
|
|
30
31
|
* Parent-provided bridge environment. A launched background task must not
|
|
@@ -41,6 +42,7 @@ export const OPERATION_BRIDGE_ENV_KEYS: readonly string[] = Object.freeze([
|
|
|
41
42
|
OPERATIONS_ATTEMPT_ID_ENV,
|
|
42
43
|
OPERATIONS_WRITER_LEASE_ID_ENV,
|
|
43
44
|
OPERATIONS_CHILD_ID_ENV,
|
|
45
|
+
OPERATIONS_DEADLINE_AT_ENV,
|
|
44
46
|
]);
|
|
45
47
|
|
|
46
48
|
const BRIDGE_ENV_KEY_SET = new Set(OPERATION_BRIDGE_ENV_KEYS);
|
|
@@ -635,9 +637,19 @@ export function canonicalToolSchema(name: OperationBridgeToolName): JsonRecord {
|
|
|
635
637
|
properties: {
|
|
636
638
|
status: { type: "string", enum: ["complete", "incomplete"] },
|
|
637
639
|
reason: { type: "string", minLength: 1, maxLength: 2048 },
|
|
640
|
+
remaining_work: { type: "array", minItems: 1, maxItems: 8, items: { type: "string", minLength: 1, maxLength: 1024 }, description: "For incomplete work, list the concrete steps still required." },
|
|
641
|
+
blocker: { type: "object", additionalProperties: false, required: ["kind", "reason"], properties: {
|
|
642
|
+
kind: { type: "string", enum: ["permission", "external-input"] },
|
|
643
|
+
reason: { type: "string", minLength: 1, maxLength: 1024 },
|
|
644
|
+
}, description: "Use only for an actual permission or external-input blocker that prevents further local work." },
|
|
638
645
|
evidence: { type: "array", minItems: 1, maxItems: 4, items: {
|
|
639
646
|
type: "object", additionalProperties: false, required: ["path", "explanation"],
|
|
640
|
-
properties: {
|
|
647
|
+
properties: {
|
|
648
|
+
path: { type: "string", minLength: 1, maxLength: 1024, description: "An existing workspace file. Foreign paths and credential files are refused." },
|
|
649
|
+
explanation: { type: "string", minLength: 1, maxLength: 1024 },
|
|
650
|
+
offset: { type: "integer", minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description: "Zero-based byte offset, inclusive. Requires max_bytes." },
|
|
651
|
+
max_bytes: { type: "integer", minimum: 1, maximum: 65536, description: "Retain at most this many bytes from offset (default zero), ending at EOF if earlier. Required for files larger than 65536 bytes." },
|
|
652
|
+
},
|
|
641
653
|
} },
|
|
642
654
|
},
|
|
643
655
|
};
|
|
@@ -658,7 +670,7 @@ const TOOL_LABELS: Record<OperationBridgeToolName, string> = {
|
|
|
658
670
|
};
|
|
659
671
|
|
|
660
672
|
const TOOL_DESCRIPTIONS: Record<OperationBridgeToolName, string> = {
|
|
661
|
-
report_assignment_result: "Record your complete or incomplete assignment judgment with retained workspace
|
|
673
|
+
report_assignment_result: "Record your complete or incomplete assignment judgment with retained workspace file evidence before your final answer. Each retained file or explicit byte excerpt is limited to 65536 bytes; use offset and max_bytes for larger source files. A refused report may be corrected and retried. Once retained, only identical retries are allowed. Reporting does not terminalize the assignment, interpret waits or record parent acceptance.",
|
|
662
674
|
bg_task_spawn: "Start one long-running background operation through the trusted parent supervisor. Returns immediately. The operation is owned by the parent, not by this worker process.",
|
|
663
675
|
bg_task_watch: "Start one background command watch through the trusted parent supervisor. Returns immediately. The operation is owned by the parent, not by this worker process.",
|
|
664
676
|
bg_task_status: "Inspect one operation owned by this worker conversation. Only task ids accepted by the parent ownership check are readable.",
|
|
@@ -668,6 +680,7 @@ const TOOL_DESCRIPTIONS: Record<OperationBridgeToolName, string> = {
|
|
|
668
680
|
};
|
|
669
681
|
|
|
670
682
|
const TOOL_GUIDELINES: Partial<Record<OperationBridgeToolName, readonly string[]>> = {
|
|
683
|
+
report_assignment_result: ["Continue available local work until the assignment is complete or a concrete blocker prevents progress. For incomplete work, provide remaining_work and any actual permission or external-input blocker. If evidence is refused, correct the path or excerpt range and retry before returning."],
|
|
671
684
|
bg_task_spawn: ["Use bg_task_spawn for established long commands; do not emulate background execution with polling, sleep loops, nohup or shell detachment."],
|
|
672
685
|
bg_task_watch: ["Use bg_task_watch for repeated observation. Do not run a foreground poll loop."],
|
|
673
686
|
wait_for_operations: ["Call wait_for_operations only when no independent work remains. A final answer that says you are waiting is not a park request."],
|
|
@@ -712,6 +725,7 @@ export function normalizeToolDescriptors(
|
|
|
712
725
|
tools: readonly OperationToolDescriptor[],
|
|
713
726
|
capabilities: OperationBridgeCapabilities,
|
|
714
727
|
): readonly OperationToolDescriptor[] {
|
|
728
|
+
assertWaitToolDependencies(capabilities, tools.map(tool => tool.name));
|
|
715
729
|
const seen = new Set<string>();
|
|
716
730
|
const normalized: OperationToolDescriptor[] = [];
|
|
717
731
|
for (const tool of tools) {
|
|
@@ -734,6 +748,17 @@ export function normalizeToolDescriptors(
|
|
|
734
748
|
return deepFreeze(normalized.sort((a, b) => a.name.localeCompare(b.name)));
|
|
735
749
|
}
|
|
736
750
|
|
|
751
|
+
/** A parked conversation must be able to read and interpret its terminal evidence. */
|
|
752
|
+
export function assertWaitToolDependencies(capabilities: OperationBridgeCapabilities, names: readonly string[]): void {
|
|
753
|
+
if (!capabilities.wait && !capabilities.parking && !names.includes(WAIT_OPERATIONS_TOOL)) return;
|
|
754
|
+
if (!capabilities.wait || !capabilities.parking || !names.includes(WAIT_OPERATIONS_TOOL)
|
|
755
|
+
|| !capabilities.acknowledge || !names.includes(ACKNOWLEDGE_OPERATION_TOOL)
|
|
756
|
+
|| !((capabilities.background.status && names.includes("bg_task_status"))
|
|
757
|
+
|| (capabilities.background.log && names.includes("bg_task_log")))) {
|
|
758
|
+
throw new OperationBridgeError("invalid-request", "wait_for_operations requires parking, acknowledge_operation_result and at least one terminal evidence reader (bg_task_status or bg_task_log) in the final authorized tools list. Add the missing tools explicitly or remove wait_for_operations.");
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
|
|
737
762
|
export function capabilityForTool(name: OperationBridgeToolName, capabilities: OperationBridgeCapabilities): boolean {
|
|
738
763
|
switch (name) {
|
|
739
764
|
case "report_assignment_result": return capabilities.reportAssignment === true;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Generated fixed launch domain from packages/pi-better-subagents/owned-exit.ts. Do not edit directly.
|
|
2
|
+
/** Private owner acknowledgement; metadata and released leases are not this barrier. */
|
|
3
|
+
export async function completeOwnedExit(exit, finalize, release, settle) {
|
|
4
|
+
const code = await exit;
|
|
5
|
+
try {
|
|
6
|
+
finalize(code);
|
|
7
|
+
}
|
|
8
|
+
finally {
|
|
9
|
+
release();
|
|
10
|
+
}
|
|
11
|
+
await settle();
|
|
12
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Private owner acknowledgement; metadata and released leases are not this barrier. */
|
|
2
|
+
export async function completeOwnedExit(
|
|
3
|
+
exit: Promise<number | null>,
|
|
4
|
+
finalize: (code: number | null) => void,
|
|
5
|
+
release: () => void,
|
|
6
|
+
settle: () => Promise<void>,
|
|
7
|
+
): Promise<void> {
|
|
8
|
+
const code = await exit;
|
|
9
|
+
try { finalize(code); }
|
|
10
|
+
finally { release(); }
|
|
11
|
+
await settle();
|
|
12
|
+
}
|