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
|
@@ -5,6 +5,7 @@ import { homedir } from "node:os";
|
|
|
5
5
|
import { runDir, writeMeta, type RunMeta } from "./registry.ts";
|
|
6
6
|
import { credentialFilePaths } from "./shared-sandbox-core.ts";
|
|
7
7
|
import type { PermissionSnapshot, PermissionProfile } from "./permission-policy.ts";
|
|
8
|
+
import { OperationBridgeError, redactSecret } from "./operation-bridge-types.ts";
|
|
8
9
|
|
|
9
10
|
const hash = (bytes: string | Buffer) => createHash("sha256").update(bytes).digest("hex");
|
|
10
11
|
const inside = (root: string, path: string) => { const rel = relative(root, path); return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)); };
|
|
@@ -20,15 +21,47 @@ function retainedBytes(path: string, limit: number): Buffer {
|
|
|
20
21
|
}
|
|
21
22
|
export interface AssignmentReport {
|
|
22
23
|
version: 1; assignmentId: string; attemptId: string; requestDigest: string; status: "complete" | "incomplete"; reason: string;
|
|
23
|
-
|
|
24
|
+
remainingWork?: string[];
|
|
25
|
+
blocker?: { kind: "permission" | "external-input"; reason: string };
|
|
26
|
+
evidence: Array<{ path: string; digest: string; source: string; explanation: string; range?: { offset: number; bytes: number; sourceBytes: number } }>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface ReportInput {
|
|
30
|
+
status: string; reason: string;
|
|
31
|
+
remaining_work?: string[];
|
|
32
|
+
blocker?: AssignmentReport["blocker"];
|
|
33
|
+
evidence: Array<{ path: string; explanation: string; offset?: number; max_bytes?: number }>;
|
|
24
34
|
}
|
|
25
35
|
|
|
26
36
|
/** Runs synchronously under the authenticated handler: no yield between authority and persistence. */
|
|
27
37
|
export function recordAssignmentReport(id: string, input: unknown, assertAuthority: () => RunMeta, current?: PermissionSnapshot) {
|
|
28
38
|
const meta = assertAuthority();
|
|
29
|
-
|
|
39
|
+
try { return retainAssignmentReport(id, input, meta, assertAuthority, current); }
|
|
40
|
+
catch (error) {
|
|
41
|
+
// Refused input is not a committed report: the same writer may correct it.
|
|
42
|
+
// Recheck the live writer before retaining even diagnostic metadata.
|
|
43
|
+
recordAssignmentReportRejection(error instanceof Error ? error.message : String(error), assertAuthority);
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Also used for authenticated bridge refusals that never enter the report handler. */
|
|
49
|
+
export function recordAssignmentReportRejection(reason: string, assertAuthority: () => RunMeta): void {
|
|
50
|
+
const latest = assertAuthority();
|
|
51
|
+
if (!latest.assignmentReport) writeMeta({ ...latest, assignmentReportRejection: {
|
|
52
|
+
reason: redactSecret(reason), rejectedAt: Date.now(),
|
|
53
|
+
} });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function retainAssignmentReport(id: string, input: unknown, meta: RunMeta, assertAuthority: () => RunMeta, current?: PermissionSnapshot) {
|
|
57
|
+
const report = input as ReportInput;
|
|
30
58
|
if (!["complete", "incomplete"].includes(report.status) || !report.reason?.trim() || report.reason.length > 2048
|
|
31
59
|
|| !Array.isArray(report.evidence) || report.evidence.length < 1 || report.evidence.length > 4) throw new Error("Invalid assignment report.");
|
|
60
|
+
if (report.remaining_work !== undefined && (!Array.isArray(report.remaining_work) || report.remaining_work.length < 1 || report.remaining_work.length > 8
|
|
61
|
+
|| report.remaining_work.some((item) => typeof item !== "string" || !item.trim() || item.length > 1024))) throw new Error("Remaining work needs 1 to 8 bounded descriptions.");
|
|
62
|
+
if (report.blocker && (!["permission", "external-input"].includes(report.blocker.kind) || !report.blocker.reason?.trim()
|
|
63
|
+
|| report.blocker.reason.length > 1024)) throw new Error("A blocker needs its permission or external-input kind and a concrete reason.");
|
|
64
|
+
if (report.status === "complete" && (report.remaining_work || report.blocker)) throw new Error("A complete assignment cannot have remaining work or a blocker.");
|
|
32
65
|
const root = realpathSync(meta.cwd);
|
|
33
66
|
const directory = join(runDir(id), "assignment-report-v1");
|
|
34
67
|
const captured = (meta.operations?.policy.sandbox as { permissions?: Partial<PermissionProfile> } | null)?.permissions;
|
|
@@ -37,28 +70,22 @@ export function recordAssignmentReport(id: string, input: unknown, assertAuthori
|
|
|
37
70
|
if (policy?.enabled && policy.projectFiles !== "read" && policy.projectFiles !== "read-write") throw new Error("Current assignment evidence read permission refused.");
|
|
38
71
|
}
|
|
39
72
|
if (meta.operations?.policy.sandbox && !current?.permissions) throw new Error("Current assignment evidence read authority unavailable.");
|
|
40
|
-
|
|
73
|
+
// Keep the legacy digest for whole-file reports without the additive fields.
|
|
74
|
+
const request: unknown[] = [report.status, report.reason, report.evidence.map((e) => e.offset === undefined && e.max_bytes === undefined
|
|
75
|
+
? [e.path, e.explanation] : [e.path, e.explanation, e.offset ?? 0, e.max_bytes])];
|
|
76
|
+
if (report.remaining_work || report.blocker) request.push([report.remaining_work ?? null,
|
|
77
|
+
report.blocker ? [report.blocker.kind, report.blocker.reason] : null]);
|
|
78
|
+
const requestDigest = hash(JSON.stringify(request));
|
|
41
79
|
if (meta.assignmentReport) {
|
|
42
80
|
const accepted = readAssignmentReport(meta)!;
|
|
43
81
|
if (accepted.requestDigest !== requestDigest) throw new Error("Conflicting assignment report refused.");
|
|
44
82
|
return { reportId: meta.assignmentReport.digest, status: accepted.status, note: "Report retained. Assignment terminalization after exit and exact parent disposition remain separate." };
|
|
45
83
|
}
|
|
46
|
-
const snapshots = report.evidence.map((e) =>
|
|
47
|
-
if (!e.path || !e.explanation?.trim() || e.explanation.length > 1024) throw new Error("Evidence needs a bounded explanation.");
|
|
48
|
-
const source = realpathSync(resolve(root, e.path));
|
|
49
|
-
if (!inside(root, source) || credentialFilePaths(homedir()).some((p) => inside(p, source))) throw new Error("Foreign or credential assignment evidence refused.");
|
|
50
|
-
const fd = openSync(source, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
51
|
-
try {
|
|
52
|
-
const stat = fstatSync(fd);
|
|
53
|
-
if (!stat.isFile() || stat.size > 65536) throw new Error("Assignment evidence must be a file of at most 65536 bytes.");
|
|
54
|
-
const bytes = Buffer.alloc(stat.size);
|
|
55
|
-
if (readSync(fd, bytes, 0, bytes.length, 0) !== bytes.length) throw new Error("Assignment evidence changed during capture.");
|
|
56
|
-
return { bytes, digest: hash(bytes), source, explanation: e.explanation };
|
|
57
|
-
} finally { closeSync(fd); }
|
|
58
|
-
});
|
|
84
|
+
const snapshots = report.evidence.map((e) => captureEvidence(root, e));
|
|
59
85
|
const retained: AssignmentReport = { version: 1, assignmentId: meta.assignment!.assignmentId, attemptId: id, requestDigest,
|
|
60
86
|
status: report.status as AssignmentReport["status"], reason: report.reason,
|
|
61
|
-
|
|
87
|
+
...(report.remaining_work ? { remainingWork: report.remaining_work } : {}), ...(report.blocker ? { blocker: report.blocker } : {}),
|
|
88
|
+
evidence: snapshots.map(({ digest, source, explanation, range }) => ({ path: join(directory, digest), digest, source, explanation, ...(range ? { range } : {}) })) };
|
|
62
89
|
const text = JSON.stringify(retained);
|
|
63
90
|
if (Buffer.byteLength(text) > 65536) throw new Error("Assignment report exceeds its retained metadata bound.");
|
|
64
91
|
const digest = hash(text);
|
|
@@ -71,11 +98,44 @@ export function recordAssignmentReport(id: string, input: unknown, assertAuthori
|
|
|
71
98
|
for (const snapshot of snapshots) writeFileSync(join(directory, snapshot.digest), snapshot.bytes, { mode: 0o600 });
|
|
72
99
|
const path = join(directory, `${digest}.json`);
|
|
73
100
|
writeFileSync(path, text, { mode: 0o600 });
|
|
74
|
-
|
|
101
|
+
const updated = { ...latest, assignmentReport: { version: 1 as const, assignmentId: retained.assignmentId, attemptId: id, digest, path } };
|
|
102
|
+
delete updated.assignmentReportRejection;
|
|
103
|
+
writeMeta(updated);
|
|
75
104
|
}
|
|
76
105
|
return { reportId: digest, status: report.status, note: "Report retained. Assignment terminalization after exit and exact parent disposition remain separate." };
|
|
77
106
|
}
|
|
78
107
|
|
|
108
|
+
function captureEvidence(root: string, e: ReportInput["evidence"][number]) {
|
|
109
|
+
try {
|
|
110
|
+
if (!e.path || !e.explanation?.trim() || e.explanation.length > 1024) throw new Error("Evidence needs a bounded explanation.");
|
|
111
|
+
const source = realpathSync(resolve(root, e.path));
|
|
112
|
+
if (credentialFilePaths(homedir()).some((p) => inside(p, source))) throw new Error("Foreign or credential assignment evidence refused.");
|
|
113
|
+
if (!inside(root, source)) throw new Error(`Foreign assignment evidence refused: the source must resolve inside the assigned workspace ${JSON.stringify(root)}. A sibling directory is outside this boundary. Use an existing workspace file or place the reportable artifact inside the workspace, then retry.`);
|
|
114
|
+
const fd = openSync(source, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
115
|
+
try {
|
|
116
|
+
const stat = fstatSync(fd);
|
|
117
|
+
if (!stat.isFile()) throw new Error(`Assignment evidence ${JSON.stringify(e.path)} must be a regular file.`);
|
|
118
|
+
const offset = e.offset ?? 0;
|
|
119
|
+
if (!Number.isSafeInteger(offset) || offset < 0 || offset > stat.size || (offset === stat.size && offset !== 0)
|
|
120
|
+
|| (e.offset !== undefined && e.max_bytes === undefined)
|
|
121
|
+
|| (e.max_bytes !== undefined && (!Number.isSafeInteger(e.max_bytes) || e.max_bytes < 1 || e.max_bytes > 65536))) {
|
|
122
|
+
throw new Error(`Invalid assignment evidence range for ${JSON.stringify(e.path)} (${stat.size} bytes). Use offset within the file and max_bytes from 1 through 65536.`);
|
|
123
|
+
}
|
|
124
|
+
if (e.max_bytes === undefined && stat.size > 65536) {
|
|
125
|
+
throw new Error(`Assignment evidence ${JSON.stringify(e.path)} is ${stat.size} bytes; the retained limit is 65536 bytes. Retry with offset and max_bytes (at most 65536) for the relevant excerpt.`);
|
|
126
|
+
}
|
|
127
|
+
const bytes = Buffer.alloc(Math.min(stat.size - offset, e.max_bytes ?? stat.size));
|
|
128
|
+
if (readSync(fd, bytes, 0, bytes.length, offset) !== bytes.length) throw new Error("Assignment evidence changed during capture.");
|
|
129
|
+
const after = fstatSync(fd);
|
|
130
|
+
if (after.size !== stat.size || after.mtimeMs !== stat.mtimeMs || after.ctimeMs !== stat.ctimeMs) throw new Error("Assignment evidence changed during capture.");
|
|
131
|
+
return { bytes, digest: hash(bytes), source, explanation: e.explanation,
|
|
132
|
+
...(e.max_bytes === undefined ? {} : { range: { offset, bytes: bytes.length, sourceBytes: stat.size } }) };
|
|
133
|
+
} finally { closeSync(fd); }
|
|
134
|
+
} catch (error) {
|
|
135
|
+
throw new OperationBridgeError("tool-error", error instanceof Error ? error.message : String(error), true);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
79
139
|
export function readAssignmentReport(meta: RunMeta): AssignmentReport | null {
|
|
80
140
|
const ref = meta.assignmentReport;
|
|
81
141
|
if (!ref) return null;
|
|
@@ -86,7 +146,11 @@ export function readAssignmentReport(meta: RunMeta): AssignmentReport | null {
|
|
|
86
146
|
const report = JSON.parse(text) as AssignmentReport;
|
|
87
147
|
if (report.version !== 1 || report.assignmentId !== ref.assignmentId || report.attemptId !== meta.id) throw new Error("Foreign assignment report.");
|
|
88
148
|
for (const e of report.evidence) {
|
|
89
|
-
if (!/^[a-f0-9]{64}$/.test(e.digest) || e.path !== join(runDir(meta.id), "assignment-report-v1", e.digest)
|
|
149
|
+
if (!/^[a-f0-9]{64}$/.test(e.digest) || e.path !== join(runDir(meta.id), "assignment-report-v1", e.digest)) throw new Error("Retained assignment evidence changed.");
|
|
150
|
+
const bytes = retainedBytes(e.path, 65536);
|
|
151
|
+
if (hash(bytes) !== e.digest || (e.range && (!Number.isSafeInteger(e.range.offset) || e.range.offset < 0
|
|
152
|
+
|| !Number.isSafeInteger(e.range.sourceBytes) || e.range.sourceBytes < 0 || e.range.bytes !== bytes.length
|
|
153
|
+
|| e.range.offset + e.range.bytes > e.range.sourceBytes))) throw new Error("Retained assignment evidence changed.");
|
|
90
154
|
}
|
|
91
155
|
return report;
|
|
92
156
|
}
|
|
@@ -3,7 +3,7 @@ import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
|
3
3
|
import { lstatSync, mkdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { processStartToken } from "./registry.domain.mjs";
|
|
6
|
-
import {
|
|
6
|
+
import { connectWorkClient } from "./shared-work-client.mjs";
|
|
7
7
|
import { overlayDigest } from "./catalog-overlay.domain.mjs";
|
|
8
8
|
export { overlayDigest } from "./catalog-overlay.domain.mjs";
|
|
9
9
|
export function createCatalogHostAdapter() {
|
|
@@ -11,6 +11,8 @@ export function createCatalogHostAdapter() {
|
|
|
11
11
|
let live;
|
|
12
12
|
let timer;
|
|
13
13
|
let epoch = 0;
|
|
14
|
+
let pendingConnection;
|
|
15
|
+
let refreshPending = false;
|
|
14
16
|
let admitting = Promise.resolve(undefined);
|
|
15
17
|
/** Fixed Pi adapter only. Never exposed as a tool or socket issuance operation. */
|
|
16
18
|
function noteCatalogHostContext(ctx, overlay) {
|
|
@@ -18,6 +20,8 @@ export function createCatalogHostAdapter() {
|
|
|
18
20
|
}
|
|
19
21
|
function closeCatalogHost() {
|
|
20
22
|
epoch++;
|
|
23
|
+
pendingConnection?.abort();
|
|
24
|
+
pendingConnection = undefined;
|
|
21
25
|
clearInterval(timer);
|
|
22
26
|
timer = undefined;
|
|
23
27
|
if (live) {
|
|
@@ -55,9 +59,15 @@ export function createCatalogHostAdapter() {
|
|
|
55
59
|
const id = randomUUID(), secret = randomBytes(32).toString("hex"), generation = randomUUID();
|
|
56
60
|
const path = join(root, `${id}.json`), staging = join(root, `.${id}`);
|
|
57
61
|
const authority = { id, secret, generation, cwd: scope.cwd, sessionId: scope.sessionId, branchId: scope.branchId };
|
|
58
|
-
const
|
|
62
|
+
const controller = new AbortController();
|
|
63
|
+
pendingConnection = controller;
|
|
64
|
+
const client = await connectWorkClient(socketPath, agentDir, ["runtime-catalog-v1"], { signal: controller.signal })
|
|
65
|
+
.finally(() => { if (pendingConnection === controller)
|
|
66
|
+
pendingConnection = undefined; });
|
|
59
67
|
try {
|
|
60
68
|
const hello = await client.ready;
|
|
69
|
+
if (epoch !== admittedEpoch || !current)
|
|
70
|
+
throw new Error("catalog-host-revoked");
|
|
61
71
|
const pidStartTime = processStartToken(process.pid);
|
|
62
72
|
if (!pidStartTime)
|
|
63
73
|
throw new Error("catalog-host-identity-unavailable");
|
|
@@ -68,7 +78,15 @@ export function createCatalogHostAdapter() {
|
|
|
68
78
|
throw new Error("catalog-host-revoked");
|
|
69
79
|
live = { client, path, key, authority };
|
|
70
80
|
if (!timer) {
|
|
71
|
-
timer = setInterval(() => {
|
|
81
|
+
timer = setInterval(() => {
|
|
82
|
+
if (refreshPending)
|
|
83
|
+
return;
|
|
84
|
+
refreshPending = true;
|
|
85
|
+
void catalogHostAuthority(agentDir, current?.ctx.cwd ?? cwd, socketPath)
|
|
86
|
+
.catch(() => { if (epoch === admittedEpoch)
|
|
87
|
+
closeCatalogHost(); })
|
|
88
|
+
.finally(() => { refreshPending = false; });
|
|
89
|
+
}, 500);
|
|
72
90
|
timer.unref();
|
|
73
91
|
}
|
|
74
92
|
return authority;
|
|
@@ -2,7 +2,7 @@ import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
|
2
2
|
import { lstatSync, mkdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { processStartToken } from "./registry.ts";
|
|
5
|
-
import { WorkClient } from "./shared-work-client.mjs";
|
|
5
|
+
import { WorkClient, connectWorkClient } from "./shared-work-client.mjs";
|
|
6
6
|
import type { AgentSessionOverrides } from "./agent-session-settings.ts";
|
|
7
7
|
import { overlayDigest } from "./catalog-overlay.ts";
|
|
8
8
|
export { overlayDigest } from "./catalog-overlay.ts";
|
|
@@ -13,6 +13,8 @@ export function createCatalogHostAdapter() {
|
|
|
13
13
|
let live: { client: WorkClient; path: string; key: string; authority: Record<string, unknown> } | undefined;
|
|
14
14
|
let timer: ReturnType<typeof setInterval> | undefined;
|
|
15
15
|
let epoch = 0;
|
|
16
|
+
let pendingConnection: AbortController | undefined;
|
|
17
|
+
let refreshPending = false;
|
|
16
18
|
let admitting: Promise<Record<string, unknown> | undefined> = Promise.resolve(undefined);
|
|
17
19
|
|
|
18
20
|
/** Fixed Pi adapter only. Never exposed as a tool or socket issuance operation. */
|
|
@@ -22,6 +24,7 @@ export function createCatalogHostAdapter() {
|
|
|
22
24
|
|
|
23
25
|
function closeCatalogHost() {
|
|
24
26
|
epoch++;
|
|
27
|
+
pendingConnection?.abort(); pendingConnection = undefined;
|
|
25
28
|
clearInterval(timer); timer = undefined;
|
|
26
29
|
if (live) { live.client.close(); rmSync(live.path, { force: true }); live = undefined; }
|
|
27
30
|
current = undefined;
|
|
@@ -48,9 +51,13 @@ export function createCatalogHostAdapter() {
|
|
|
48
51
|
const id = randomUUID(), secret = randomBytes(32).toString("hex"), generation = randomUUID();
|
|
49
52
|
const path = join(root, `${id}.json`), staging = join(root, `.${id}`);
|
|
50
53
|
const authority = { id, secret, generation, cwd: scope.cwd, sessionId: scope.sessionId, branchId: scope.branchId };
|
|
51
|
-
const
|
|
54
|
+
const controller = new AbortController();
|
|
55
|
+
pendingConnection = controller;
|
|
56
|
+
const client = await connectWorkClient(socketPath, agentDir, ["runtime-catalog-v1"], { signal: controller.signal })
|
|
57
|
+
.finally(() => { if (pendingConnection === controller) pendingConnection = undefined; });
|
|
52
58
|
try {
|
|
53
59
|
const hello = await client.ready;
|
|
60
|
+
if (epoch !== admittedEpoch || !current) throw new Error("catalog-host-revoked");
|
|
54
61
|
const pidStartTime = processStartToken(process.pid);
|
|
55
62
|
if (!pidStartTime) throw new Error("catalog-host-identity-unavailable");
|
|
56
63
|
writeFileSync(staging, JSON.stringify({ version: 1, id, generation, serverInstance: hello.instanceId, pid: process.pid, pidStartTime, secretHash: hash(secret), ...scope }), { mode: 0o600, flag: "wx" });
|
|
@@ -58,7 +65,16 @@ export function createCatalogHostAdapter() {
|
|
|
58
65
|
await client.request("runtime_bind_catalog_host", { authority });
|
|
59
66
|
if (epoch !== admittedEpoch || !current) throw new Error("catalog-host-revoked");
|
|
60
67
|
live = { client, path, key, authority };
|
|
61
|
-
if (!timer) {
|
|
68
|
+
if (!timer) {
|
|
69
|
+
timer = setInterval(() => {
|
|
70
|
+
if (refreshPending) return;
|
|
71
|
+
refreshPending = true;
|
|
72
|
+
void catalogHostAuthority(agentDir, current?.ctx.cwd ?? cwd, socketPath)
|
|
73
|
+
.catch(() => { if (epoch === admittedEpoch) closeCatalogHost(); })
|
|
74
|
+
.finally(() => { refreshPending = false; });
|
|
75
|
+
}, 500);
|
|
76
|
+
timer.unref();
|
|
77
|
+
}
|
|
62
78
|
return authority;
|
|
63
79
|
} catch (error) { client.close(); rmSync(path, { force: true }); rmSync(staging, { force: true }); throw error; }
|
|
64
80
|
}
|
|
@@ -32,7 +32,7 @@ function preferences(id: string, value: unknown): CatalogPreference {
|
|
|
32
32
|
}
|
|
33
33
|
|
|
34
34
|
function snapshot(values: CatalogPreferences): { settings: CatalogPreferences; digest: string } {
|
|
35
|
-
const settings = Object.freeze(Object.fromEntries(Object.keys(values).sort().map(id => [id, values[id]])));
|
|
35
|
+
const settings = Object.freeze(Object.fromEntries(Object.keys(values).sort().map(id => [id, values[id]!])));
|
|
36
36
|
return { settings, digest: createHash("sha256").update(JSON.stringify(settings)).digest("hex") };
|
|
37
37
|
}
|
|
38
38
|
|
|
@@ -99,7 +99,41 @@ export function inspectCatalog(snapshot, id) {
|
|
|
99
99
|
snapshotDigest: snapshot.digest,
|
|
100
100
|
};
|
|
101
101
|
}
|
|
102
|
+
export const catalogResolutionMetrics = { assemblies: 0, hits: 0 };
|
|
103
|
+
const resolutions = new Map();
|
|
104
|
+
function resolveCached(snapshot, id, compute) {
|
|
105
|
+
const entry = findEntry(snapshot, id);
|
|
106
|
+
if (!entry)
|
|
107
|
+
return compute();
|
|
108
|
+
const roleId = entry.definition?.kind === "agent" ? entry.definition.roleId : undefined;
|
|
109
|
+
const role = roleId ? findEntry(snapshot, roleId) : undefined;
|
|
110
|
+
// Only the selected definition, its base role and their own preferences contribute.
|
|
111
|
+
const key = JSON.stringify([{ ...entry, unused: undefined }, role && { ...role, unused: undefined }, snapshot.savedSettings?.[id], roleId && snapshot.savedSettings?.[roleId],
|
|
112
|
+
snapshot.sessionSettings?.[id], roleId && snapshot.sessionSettings?.[roleId]]);
|
|
113
|
+
const cached = resolutions.get(key);
|
|
114
|
+
if (cached) {
|
|
115
|
+
catalogResolutionMetrics.hits++;
|
|
116
|
+
const result = structuredClone(cached);
|
|
117
|
+
result.entry = entry;
|
|
118
|
+
if (result.effective)
|
|
119
|
+
result.effective.snapshotDigest = snapshot.digest;
|
|
120
|
+
return result;
|
|
121
|
+
}
|
|
122
|
+
catalogResolutionMetrics.assemblies++;
|
|
123
|
+
const result = compute();
|
|
124
|
+
if (new TextEncoder().encode(key).byteLength <= 64 * 1024)
|
|
125
|
+
resolutions.set(key, structuredClone(result));
|
|
126
|
+
if (resolutions.size > 512)
|
|
127
|
+
resolutions.delete(resolutions.keys().next().value);
|
|
128
|
+
return result;
|
|
129
|
+
}
|
|
102
130
|
function resolveRole(snapshot, roleId) {
|
|
131
|
+
return resolveCached(snapshot, roleId, () => resolveRoleUncached(snapshot, roleId));
|
|
132
|
+
}
|
|
133
|
+
function resolveAgent(snapshot, agentId) {
|
|
134
|
+
return resolveCached(snapshot, agentId, () => resolveAgentUncached(snapshot, agentId));
|
|
135
|
+
}
|
|
136
|
+
function resolveRoleUncached(snapshot, roleId) {
|
|
103
137
|
const entry = findEntry(snapshot, roleId);
|
|
104
138
|
if (!entry || entry.kind !== "role") {
|
|
105
139
|
return {
|
|
@@ -142,7 +176,7 @@ function resolveRole(snapshot, roleId) {
|
|
|
142
176
|
},
|
|
143
177
|
};
|
|
144
178
|
}
|
|
145
|
-
function
|
|
179
|
+
function resolveAgentUncached(snapshot, agentId) {
|
|
146
180
|
const entry = findEntry(snapshot, agentId);
|
|
147
181
|
if (!entry || entry.kind !== "agent") {
|
|
148
182
|
return {
|
|
@@ -218,7 +218,41 @@ export function inspectCatalog(snapshot: CatalogSnapshot, id: string): CatalogIn
|
|
|
218
218
|
};
|
|
219
219
|
}
|
|
220
220
|
|
|
221
|
+
export const catalogResolutionMetrics = { assemblies: 0, hits: 0 };
|
|
222
|
+
const resolutions = new Map<string, Resolution>();
|
|
223
|
+
|
|
224
|
+
function resolveCached(snapshot: CatalogSnapshot, id: string, compute: () => Resolution): Resolution {
|
|
225
|
+
const entry = findEntry(snapshot, id);
|
|
226
|
+
if (!entry) return compute();
|
|
227
|
+
const roleId = entry.definition?.kind === "agent" ? entry.definition.roleId : undefined;
|
|
228
|
+
const role = roleId ? findEntry(snapshot, roleId) : undefined;
|
|
229
|
+
// Only the selected definition, its base role and their own preferences contribute.
|
|
230
|
+
const key = JSON.stringify([{ ...entry, unused: undefined }, role && { ...role, unused: undefined }, snapshot.savedSettings?.[id], roleId && snapshot.savedSettings?.[roleId],
|
|
231
|
+
snapshot.sessionSettings?.[id], roleId && snapshot.sessionSettings?.[roleId]]);
|
|
232
|
+
const cached = resolutions.get(key);
|
|
233
|
+
if (cached) {
|
|
234
|
+
catalogResolutionMetrics.hits++;
|
|
235
|
+
const result = structuredClone(cached);
|
|
236
|
+
result.entry = entry;
|
|
237
|
+
if (result.effective) result.effective.snapshotDigest = snapshot.digest;
|
|
238
|
+
return result;
|
|
239
|
+
}
|
|
240
|
+
catalogResolutionMetrics.assemblies++;
|
|
241
|
+
const result = compute();
|
|
242
|
+
if (new TextEncoder().encode(key).byteLength <= 64 * 1024) resolutions.set(key, structuredClone(result));
|
|
243
|
+
if (resolutions.size > 512) resolutions.delete(resolutions.keys().next().value!);
|
|
244
|
+
return result;
|
|
245
|
+
}
|
|
246
|
+
|
|
221
247
|
function resolveRole(snapshot: CatalogSnapshot, roleId: string): Resolution {
|
|
248
|
+
return resolveCached(snapshot, roleId, () => resolveRoleUncached(snapshot, roleId));
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function resolveAgent(snapshot: CatalogSnapshot, agentId: string): Resolution {
|
|
252
|
+
return resolveCached(snapshot, agentId, () => resolveAgentUncached(snapshot, agentId));
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function resolveRoleUncached(snapshot: CatalogSnapshot, roleId: string): Resolution {
|
|
222
256
|
const entry = findEntry(snapshot, roleId);
|
|
223
257
|
if (!entry || entry.kind !== "role") {
|
|
224
258
|
return {
|
|
@@ -268,7 +302,7 @@ function resolveRole(snapshot: CatalogSnapshot, roleId: string): Resolution {
|
|
|
268
302
|
};
|
|
269
303
|
}
|
|
270
304
|
|
|
271
|
-
function
|
|
305
|
+
function resolveAgentUncached(snapshot: CatalogSnapshot, agentId: string): Resolution {
|
|
272
306
|
const entry = findEntry(snapshot, agentId);
|
|
273
307
|
if (!entry || entry.kind !== "agent") {
|
|
274
308
|
return {
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* Filesystem catalog: project, personal, and bundled sources.
|
|
4
4
|
*
|
|
5
|
-
* Discovery is deterministic
|
|
6
|
-
*
|
|
5
|
+
* Discovery is deterministic. Direct callers read disk on every call; the server
|
|
6
|
+
* can supply bounded source reuse after admission. Callers launching a batch retain the snapshot
|
|
7
7
|
* and reuse that object for every job.
|
|
8
8
|
*
|
|
9
9
|
* Project files are read only when `projectTrusted` is true. Pass Pi's
|
|
@@ -69,12 +69,12 @@ export function listScopedAgents(input, scope) {
|
|
|
69
69
|
throw new Error("Unsafe project config directory");
|
|
70
70
|
const directory = scope === "project" ? projectCatalogPaths(input.cwd, config).agents : userCatalogPaths(input.userRoot).agents;
|
|
71
71
|
const occurrences = new Map();
|
|
72
|
-
collectDirectory(directory, scope, "agent", occurrences, diagnostics);
|
|
72
|
+
collectDirectory(directory, scope, "agent", occurrences, diagnostics, input.sources);
|
|
73
73
|
const agents = [...occurrences.values()].flat().flatMap(item => item.parse.definition?.kind === "agent"
|
|
74
74
|
? [{ path: item.path, definition: item.parse.definition }] : []);
|
|
75
75
|
return { agents, diagnostics };
|
|
76
76
|
}
|
|
77
|
-
/**
|
|
77
|
+
/** Discover authorized sources. Identical bytes produce the same content digest. */
|
|
78
78
|
export function loadCatalog(input) {
|
|
79
79
|
const loadedAt = new Date().toISOString();
|
|
80
80
|
const diagnostics = [];
|
|
@@ -91,8 +91,8 @@ export function loadCatalog(input) {
|
|
|
91
91
|
groups.set(scope, new Map());
|
|
92
92
|
if (input.projectTrusted) {
|
|
93
93
|
const project = projectCatalogPaths(input.cwd, configDirName);
|
|
94
|
-
collectDirectory(project.roles, "project", "role", groups.get("project"), diagnostics);
|
|
95
|
-
collectDirectory(project.agents, "project", "agent", groups.get("project"), diagnostics);
|
|
94
|
+
collectDirectory(project.roles, "project", "role", groups.get("project"), diagnostics, input.sources);
|
|
95
|
+
collectDirectory(project.agents, "project", "agent", groups.get("project"), diagnostics, input.sources);
|
|
96
96
|
}
|
|
97
97
|
else {
|
|
98
98
|
const project = projectCatalogPaths(input.cwd, configDirName);
|
|
@@ -101,8 +101,8 @@ export function loadCatalog(input) {
|
|
|
101
101
|
}
|
|
102
102
|
}
|
|
103
103
|
const user = userCatalogPaths(input.userRoot);
|
|
104
|
-
collectDirectory(user.roles, "user", "role", groups.get("user"), diagnostics);
|
|
105
|
-
collectDirectory(user.agents, "user", "agent", groups.get("user"), diagnostics);
|
|
104
|
+
collectDirectory(user.roles, "user", "role", groups.get("user"), diagnostics, input.sources);
|
|
105
|
+
collectDirectory(user.agents, "user", "agent", groups.get("user"), diagnostics, input.sources);
|
|
106
106
|
const bundledRoles = input.bundledRoot ?? bundledRolesRoot();
|
|
107
107
|
if (!existsSync(bundledRoles)) {
|
|
108
108
|
diagnostics.push(diagnostic(DiagnosticCodes.bundledMissing, `Bundled role directory ${bundledRoles} is missing.`, {
|
|
@@ -114,23 +114,21 @@ export function loadCatalog(input) {
|
|
|
114
114
|
}));
|
|
115
115
|
}
|
|
116
116
|
else {
|
|
117
|
-
collectDirectory(bundledRoles, "bundled", "role", groups.get("bundled"), diagnostics);
|
|
117
|
+
collectDirectory(bundledRoles, "bundled", "role", groups.get("bundled"), diagnostics, input.sources);
|
|
118
118
|
}
|
|
119
119
|
if (input.bundledAgentsRoot) {
|
|
120
|
-
collectDirectory(input.bundledAgentsRoot, "bundled", "agent", groups.get("bundled"), diagnostics);
|
|
120
|
+
collectDirectory(input.bundledAgentsRoot, "bundled", "agent", groups.get("bundled"), diagnostics, input.sources);
|
|
121
121
|
}
|
|
122
122
|
const { entries, blocked } = selectIdentities(groups, diagnostics);
|
|
123
123
|
const savedSettings = {};
|
|
124
124
|
const preferenceSources = {};
|
|
125
|
-
const preferenceDigests = [];
|
|
126
125
|
const scopes = [
|
|
127
126
|
{ scope: "user", root: user.root },
|
|
128
127
|
...(input.projectTrusted ? [{ scope: "project", root: projectCatalogPaths(input.cwd, configDirName).root }] : []),
|
|
129
128
|
];
|
|
130
129
|
for (const { scope, root } of scopes) {
|
|
131
130
|
try {
|
|
132
|
-
const preferences = readCatalogPreferences(root);
|
|
133
|
-
preferenceDigests.push(preferences.digest);
|
|
131
|
+
const preferences = input.sources?.preferences?.(root) ?? readCatalogPreferences(root);
|
|
134
132
|
for (const entry of entries) {
|
|
135
133
|
if (scope === "user" && entry.scope === "project")
|
|
136
134
|
continue;
|
|
@@ -141,8 +139,8 @@ export function loadCatalog(input) {
|
|
|
141
139
|
if (own.bundled) {
|
|
142
140
|
const fallbacks = entry.scope === "bundled" ? [entry] : entry.unused.filter(source => source.scope === "bundled");
|
|
143
141
|
const fallback = fallbacks.length === 1 ? fallbacks[0] : undefined;
|
|
144
|
-
const raw = fallback ? readFileSync(fallback.path, "utf8") : undefined;
|
|
145
|
-
const parsed = raw === undefined ? undefined : parseDefinition(raw, fallback.path);
|
|
142
|
+
const raw = fallback ? (input.sources?.read(fallback.path) ?? readFileSync(fallback.path, "utf8")) : undefined;
|
|
143
|
+
const parsed = raw === undefined ? undefined : (input.sources?.parse(raw, fallback.path) ?? parseDefinition(raw, fallback.path));
|
|
146
144
|
if (!fallback || !parsed?.ok || parsed.definition?.id !== entry.id || parsed.diagnostics.some(item => item.blocking)
|
|
147
145
|
|| contentDigest(raw) !== fallback.contentDigest) {
|
|
148
146
|
const failure = diagnostic("catalog-preferences", `Cannot inherit bundled runtime defaults for ${entry.id}: a single valid bundled definition is required.`, {
|
|
@@ -182,8 +180,8 @@ export function loadCatalog(input) {
|
|
|
182
180
|
}
|
|
183
181
|
}
|
|
184
182
|
}
|
|
185
|
-
const snapshot = finishSnapshot(entries, blocked, diagnostics, loadedAt);
|
|
186
|
-
const digest = contentDigest(JSON.stringify([snapshot.digest,
|
|
183
|
+
const snapshot = finishSnapshot(entries, blocked, diagnostics, loadedAt, input.sources);
|
|
184
|
+
const digest = contentDigest(JSON.stringify([snapshot.digest, savedSettings, preferenceSources]));
|
|
187
185
|
return deepFreeze({ ...snapshot, digest, revision: digest, savedSettings, preferenceSources });
|
|
188
186
|
}
|
|
189
187
|
export function refreshCatalog(input) {
|
|
@@ -372,7 +370,7 @@ export function saveDefinition(input) {
|
|
|
372
370
|
export function isSafeConfigDirName(name) {
|
|
373
371
|
return /^\.[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name) || /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name);
|
|
374
372
|
}
|
|
375
|
-
function collectDirectory(directory, scope, directoryKind, into, diagnostics) {
|
|
373
|
+
function collectDirectory(directory, scope, directoryKind, into, diagnostics, sources) {
|
|
376
374
|
let stats;
|
|
377
375
|
try {
|
|
378
376
|
stats = lstatSync(directory);
|
|
@@ -449,7 +447,7 @@ function collectDirectory(directory, scope, directoryKind, into, diagnostics) {
|
|
|
449
447
|
continue;
|
|
450
448
|
let raw;
|
|
451
449
|
try {
|
|
452
|
-
raw = readFileSync(path, "utf8");
|
|
450
|
+
raw = sources?.read(path) ?? readFileSync(path, "utf8");
|
|
453
451
|
}
|
|
454
452
|
catch (error) {
|
|
455
453
|
diagnostics.push(diagnostic(DiagnosticCodes.ioError, `Could not read ${path}: ${error.message}`, {
|
|
@@ -462,7 +460,7 @@ function collectDirectory(directory, scope, directoryKind, into, diagnostics) {
|
|
|
462
460
|
}
|
|
463
461
|
let parse;
|
|
464
462
|
try {
|
|
465
|
-
parse = parseDefinition(raw, path);
|
|
463
|
+
parse = sources?.parse(raw, path) ?? parseDefinition(raw, path);
|
|
466
464
|
}
|
|
467
465
|
catch (error) {
|
|
468
466
|
const detail = error instanceof Error ? error.message : String(error);
|
|
@@ -586,11 +584,11 @@ function unusedSource(occurrence, reason) {
|
|
|
586
584
|
reason,
|
|
587
585
|
};
|
|
588
586
|
}
|
|
589
|
-
function finishSnapshot(entries, blocked, diagnostics, loadedAt) {
|
|
587
|
+
function finishSnapshot(entries, blocked, diagnostics, loadedAt, sources) {
|
|
590
588
|
const roleEntries = [];
|
|
591
589
|
const agentEntries = [];
|
|
592
590
|
for (const entry of entries) {
|
|
593
|
-
const frozen = deepFreeze(cloneEntry(entry));
|
|
591
|
+
const frozen = sources?.entry?.(entry) ?? deepFreeze(cloneEntry(entry));
|
|
594
592
|
if (frozen.kind === "role")
|
|
595
593
|
roleEntries.push([frozen.id, frozen]);
|
|
596
594
|
else
|