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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-better-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Daemon that hosts Pi agent sessions behind a local Unix socket with session-addressed Pi RPC.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -59,6 +59,9 @@
|
|
|
59
59
|
"engines": {
|
|
60
60
|
"node": ">=22.0.0"
|
|
61
61
|
},
|
|
62
|
+
"optionalDependencies": {
|
|
63
|
+
"fsevents": "~2.3.3"
|
|
64
|
+
},
|
|
62
65
|
"dependencies": {
|
|
63
66
|
"proper-lockfile": "^4.1.2",
|
|
64
67
|
"shell-quote": "1.12.0",
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { cpSync } from "node:fs";
|
|
2
|
+
import { basename, join } from "node:path";
|
|
3
|
+
|
|
4
|
+
const [root, prefix] = process.argv.slice(2);
|
|
5
|
+
if (!root || !prefix) throw new Error("Usage: copy-pi-test-providers.mjs <workspace> <prefix>");
|
|
6
|
+
for (const name of ["pi-better-subagents", "pi-better-background-tasks", "pi-better-sandbox", "operation-coordinator", "pi-better-goal"]) {
|
|
7
|
+
cpSync(join(root, "packages", name), join(prefix, "packages", name), {
|
|
8
|
+
recursive: true, filter: path => !["node_modules", ".work", ".pi-compat"].includes(basename(path)),
|
|
9
|
+
});
|
|
10
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Source Commit Visibility
|
|
2
|
+
|
|
3
|
+
The writer stages a unique marker and atomically renames its metadata file. The
|
|
4
|
+
measurement accepts only a ready subscription event containing that task and marker;
|
|
5
|
+
neither a polling query nor the writer's IPC acknowledgement counts as visibility.
|
|
6
|
+
|
|
7
|
+
The rename occurs between `commitStartedNs` and `committedNs`. A concurrent reader can
|
|
8
|
+
receive the renamed content before the writer is scheduled to record `committedNs`.
|
|
9
|
+
Subtracting that post-rename timestamp from event receipt therefore can be negative
|
|
10
|
+
even though the event contains fresh, committed content.
|
|
11
|
+
|
|
12
|
+
`latencyMs` is the conservative upper bound from immediately before rename to receipt.
|
|
13
|
+
The one-second healthy publication budget and nonnegative-latency gates are unchanged.
|
|
14
|
+
The measurement also rejects any receipt preceding `commitStartedNs` and retains the
|
|
15
|
+
signed `completionDeltaMs` alongside both timestamps. A negative completion delta
|
|
16
|
+
exposes the scheduling interval rather than being clamped or discarded. This bound
|
|
17
|
+
includes rename duration and can overestimate, never underestimate, commit latency.
|
|
18
|
+
|
|
19
|
+
`event-publication-clock.test.ts` deterministically holds an external writer after its
|
|
20
|
+
rename until 1/5/10 real Unix socket subscribers have received the exact marker. It uses
|
|
21
|
+
the production read model and subscription encoder without daemon identity admission.
|
|
22
|
+
It reproduces the old negative-delta assertion, verifies the timestamp bracket, checks
|
|
23
|
+
the fresh snapshot and retains per-recipient values and changed-source read counts.
|
|
24
|
+
The production writer does not wait for subscribers. Workload concurrency, resource
|
|
25
|
+
windows and shared-read budgets are unchanged. Full daemon/resource acceptance still
|
|
26
|
+
belongs to the qualifying resource CI lane.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, renameSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
export async function commitMetadata(path, marker, afterRename) {
|
|
4
|
+
const meta = JSON.parse(readFileSync(path, 'utf8'));
|
|
5
|
+
const staged = `${path}.${process.pid}.latency.tmp`;
|
|
6
|
+
writeFileSync(staged, JSON.stringify({ ...meta, name: marker }));
|
|
7
|
+
const commitStartedNs = process.hrtime.bigint().toString();
|
|
8
|
+
renameSync(staged, path);
|
|
9
|
+
if (afterRename) await afterRename();
|
|
10
|
+
const committedNs = process.hrtime.bigint().toString();
|
|
11
|
+
return { marker, commitStartedNs, committedNs };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function publicationObservation(commit, recipient) {
|
|
15
|
+
const visible = BigInt(recipient.visibleNs), started = BigInt(commit.commitStartedNs), completed = BigInt(commit.committedNs);
|
|
16
|
+
if (completed < started || visible < started) throw new Error(`Invalid source commit/visibility ordering: ${JSON.stringify({ commit, recipient })}`);
|
|
17
|
+
// Matching the unique renamed marker proves causality. A writer can be descheduled
|
|
18
|
+
// after rename, so its return timestamp is only an upper bound on commit time.
|
|
19
|
+
return { ...recipient, latencyMs: Number(visible - started) / 1e6,
|
|
20
|
+
completionDeltaMs: Number(visible - completed) / 1e6 };
|
|
21
|
+
}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { fork } from 'node:child_process';
|
|
2
2
|
import { once } from 'node:events';
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
4
5
|
import { WorkClient } from '../../src/runtime/work-client.mjs';
|
|
6
|
+
import { publicationObservation } from './commit.mjs';
|
|
5
7
|
|
|
6
8
|
export function distribution(values) {
|
|
7
9
|
const sorted = [...values].sort((a, b) => a - b);
|
|
@@ -14,8 +16,15 @@ function deadline(promise, label) {
|
|
|
14
16
|
timer = setTimeout(() => reject(new Error(`Event publication timeout: ${label}`)), 10000);
|
|
15
17
|
})]).finally(() => clearTimeout(timer));
|
|
16
18
|
}
|
|
19
|
+
|
|
20
|
+
/** Observe a delivered violation after timing ends; never poll or repair it. */
|
|
21
|
+
export async function publicationBudgetDiagnostic(observation, diagnostics) {
|
|
22
|
+
if (!observation.recipients.some(recipient => recipient.latencyMs > 1000)) return;
|
|
23
|
+
try { return { component: await diagnostics?.() }; }
|
|
24
|
+
catch (error) { return { diagnosticError: String(error) }; }
|
|
25
|
+
}
|
|
17
26
|
/** No snapshot polling or RPC response is counted as event visibility. */
|
|
18
|
-
export async function measureEventPublication({ socketPath, agentDir, scope, metaPath, taskId, subscribers, commits = 5 }) {
|
|
27
|
+
export async function measureEventPublication({ socketPath, agentDir, scope, metaPath, taskId, subscribers, commits = 5, phase, diagnostics }) {
|
|
19
28
|
const clients = [], observations = [];
|
|
20
29
|
const writer = fork(new URL('./writer.mjs', import.meta.url), [metaPath], { execArgv: [], stdio: ['ignore', 'ignore', 'inherit', 'ipc'] });
|
|
21
30
|
try {
|
|
@@ -37,16 +46,39 @@ export async function measureEventPublication({ socketPath, agentDir, scope, met
|
|
|
37
46
|
resolve({ subscriber, visibleNs: process.hrtime.bigint().toString(), seq: snapshot.seq, instanceId: snapshot.instanceId });
|
|
38
47
|
}));
|
|
39
48
|
}));
|
|
49
|
+
let acknowledgement;
|
|
40
50
|
try {
|
|
41
51
|
const committed = once(writer, 'message');
|
|
42
52
|
writer.send({ marker });
|
|
43
|
-
const [message, visible] = await deadline(Promise.all([committed.then(([value]) => value), Promise.all(visibility)]), 'committed change through subscription');
|
|
44
|
-
|
|
45
|
-
|
|
53
|
+
const [message, visible] = await deadline(Promise.all([committed.then(([value]) => { acknowledgement = value; return value; }), Promise.all(visibility)]), 'committed change through subscription');
|
|
54
|
+
if (message.marker !== marker) throw new Error('External writer acknowledged a different source commit');
|
|
55
|
+
const observation = { commit, marker, commitStartedNs: message.commitStartedNs, committedNs: message.committedNs,
|
|
56
|
+
recipients: visible.map(value => publicationObservation(message, value)) };
|
|
57
|
+
observations.push(observation);
|
|
58
|
+
const failure = await publicationBudgetDiagnostic(observation, diagnostics);
|
|
59
|
+
if (failure) {
|
|
60
|
+
observation.failure = failure;
|
|
61
|
+
console.error(`Event publication budget failure: ${JSON.stringify({ phase, ...observation }).slice(0, 32768)}`);
|
|
62
|
+
}
|
|
63
|
+
} catch (error) {
|
|
64
|
+
// Capture only after failure; RPC responses never satisfy the visibility assertion.
|
|
65
|
+
const row = value => ({ status: value?.status, reason: value?.reason, seq: value?.seq, scopeRevision: value?.scopeRevision,
|
|
66
|
+
row: value?.rows?.find(row => row.meta?.id === taskId) });
|
|
67
|
+
const report = { phase, commit, marker, acknowledgement, subscriptions: clients.map(client => row(client.snapshot)) };
|
|
68
|
+
try {
|
|
69
|
+
const info = statSync(metaPath, { bigint: true });
|
|
70
|
+
const meta = JSON.parse(readFileSync(metaPath, 'utf8'));
|
|
71
|
+
report.file = { id: meta.id, name: meta.name, identity: `${info.dev}:${info.ino}`, size: String(info.size), mtimeNs: String(info.mtimeNs) };
|
|
72
|
+
report.freshQuery = row(await clients[0].get(scope));
|
|
73
|
+
report.component = await diagnostics?.();
|
|
74
|
+
} catch (diagnosticError) { report.diagnosticError = String(diagnosticError); }
|
|
75
|
+
console.error(`Event publication failure: ${JSON.stringify(report).slice(0, 32768)}`);
|
|
76
|
+
throw error;
|
|
46
77
|
} finally { removers.forEach(remove => remove()); }
|
|
47
78
|
}
|
|
48
79
|
const values = observations.flatMap(item => item.recipients.map(value => value.latencyMs));
|
|
49
|
-
return { boundary: 'external atomic metadata commit to matching real Unix subscription event',
|
|
80
|
+
return { boundary: 'external atomic metadata commit to matching real Unix subscription event',
|
|
81
|
+
latencyBound: 'conservative upper bound from immediately before atomic rename; completionDeltaMs retains the signed post-rename timestamp delta', subscribers, commits,
|
|
50
82
|
healthyBudgetMs: 1000, ms: distribution(values), observations };
|
|
51
83
|
} finally {
|
|
52
84
|
clients.forEach(client => client.close());
|
|
@@ -1,11 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { commitMetadata } from './commit.mjs';
|
|
2
2
|
const path = process.argv[2];
|
|
3
|
-
process.on('message', ({ marker }) => {
|
|
4
|
-
|
|
5
|
-
const staged = `${path}.${process.pid}.latency.tmp`;
|
|
6
|
-
writeFileSync(staged, JSON.stringify({ ...meta, name: marker }));
|
|
7
|
-
renameSync(staged, path);
|
|
8
|
-
// Same-host monotonic clock; timestamp after the atomic source commit.
|
|
9
|
-
process.send({ marker, committedNs: process.hrtime.bigint().toString() });
|
|
3
|
+
process.on('message', async ({ marker }) => {
|
|
4
|
+
process.send(await commitMetadata(path, marker));
|
|
10
5
|
});
|
|
11
6
|
process.send({ ready: true });
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { isMainThread } from 'node:worker_threads';
|
|
2
|
-
import { createRequire } from 'node:module';
|
|
2
|
+
import { createRequire, register } from 'node:module';
|
|
3
3
|
import { readFileSync, writeFileSync, renameSync } from 'node:fs';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { monitorEventLoopDelay } from 'node:perf_hooks';
|
|
6
6
|
import { currentOwnerIdentity } from '../../src/daemon-owner.ts';
|
|
7
|
+
import { recoveryTraceSnapshot } from './recovery-trace.mjs';
|
|
7
8
|
if (isMainThread && process.env.PI_RESOURCE_REPORT_DIR) {
|
|
9
|
+
register(new URL('./recovery-trace-loader.mjs', import.meta.url));
|
|
8
10
|
const identity = currentOwnerIdentity();
|
|
9
11
|
const sqlite = createRequire(import.meta.url)('node:sqlite'), Original = sqlite.DatabaseSync;
|
|
10
12
|
const connections = { coordinator: 0, derived: 0, other: 0 };
|
|
@@ -19,7 +21,7 @@ if (isMainThread && process.env.PI_RESOURCE_REPORT_DIR) {
|
|
|
19
21
|
let next = ''; try { next = readFileSync(join(process.env.PI_RESOURCE_REPORT_DIR, 'generation'), 'utf8'); } catch {}
|
|
20
22
|
if (next !== generation) { generation = next; lag.reset(); }
|
|
21
23
|
const target=join(process.env.PI_RESOURCE_REPORT_DIR, `${process.pid}.json`), temporary=`${target}.tmp`;
|
|
22
|
-
writeFileSync(temporary, JSON.stringify({ identity, generation, at: Date.now(), cpu: process.cpuUsage(), usage: process.resourceUsage(), rss: process.memoryUsage().rss, connections,
|
|
24
|
+
writeFileSync(temporary, JSON.stringify({ identity, generation, at: Date.now(), cpu: process.cpuUsage(), usage: process.resourceUsage(), rss: process.memoryUsage().rss, connections, backgroundRecoveryTrace: recoveryTraceSnapshot(),
|
|
23
25
|
lagMs: { p50: lag.percentile(50)/1e6, p95: lag.percentile(95)/1e6, p99: lag.percentile(99)/1e6 } }));
|
|
24
26
|
renameSync(temporary,target);
|
|
25
27
|
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import ts from 'typescript';
|
|
3
|
+
|
|
4
|
+
const target = new URL('../../src/runtime/background-tools.ts', import.meta.url).href;
|
|
5
|
+
const recorder = new URL('./recovery-trace.mjs', import.meta.url).href;
|
|
6
|
+
|
|
7
|
+
export function instrumentRecoveryTrace(source) {
|
|
8
|
+
const replace = (from, to) => {
|
|
9
|
+
if (source.split(from).length !== 2) throw new Error(`Resource trace source anchor changed: ${from}`);
|
|
10
|
+
source = source.replace(from, to);
|
|
11
|
+
};
|
|
12
|
+
replace('service.noteParentContext(ctx, { recover: false });', `
|
|
13
|
+
const traceRecoveryState = () => {
|
|
14
|
+
const state = service.activeOrigin ? service.callbackRecoveryScopes.get(JSON.stringify([service.activeOrigin.cwd, service.activeOrigin.sessionId, service.activeContext.sessionManager.getBranch().map(entry => entry.id).filter(id => typeof id === 'string')])) : service.unscopedCallbackRecovery;
|
|
15
|
+
return state ? { ...state } : null;
|
|
16
|
+
};
|
|
17
|
+
const traceBeforeContext = { owner: service.activeOrigin, state: traceRecoveryState() };
|
|
18
|
+
service.noteParentContext(ctx, { recover: false });`);
|
|
19
|
+
replace('const recoveryVersion = authority.backgroundDigest([lease.store.getChangeRevision(), record.branchIds]);', `
|
|
20
|
+
const traceCoordinatorRevision = lease.store.getChangeRevision();
|
|
21
|
+
const recoveryVersion = authority.backgroundDigest([traceCoordinatorRevision, record.branchIds]);`);
|
|
22
|
+
replace('metrics.reconciles++;', `
|
|
23
|
+
const traceAfterContext = traceRecoveryState();
|
|
24
|
+
recordRecoveryTrace({ event: 'reconcile', owner: record.owner, branchDigest: authority.backgroundDigest(record.branchIds),
|
|
25
|
+
coordinatorRevision: traceCoordinatorRevision, cachedRecoveryDigest: recoveryVersions.get(viewKey) ?? null,
|
|
26
|
+
recoveryDigest: recoveryVersion, pending: !traceAfterContext || traceAfterContext.revision < 0 || traceAfterContext.delivery !== undefined || traceAfterContext.claims !== undefined,
|
|
27
|
+
beforeContext: traceBeforeContext, afterContext: traceAfterContext });
|
|
28
|
+
metrics.reconciles++;`);
|
|
29
|
+
replace('metrics.scopeRefreshes++;', `
|
|
30
|
+
recordRecoveryTrace({ event: 'projection', owner: record.owner, branchDigest: authority.backgroundDigest(record.branchIds),
|
|
31
|
+
previousRevision: projection?.revision ?? null, revision, scopeRevision: snapshot.scopeRevision, snapshotSequence: snapshot.seq });
|
|
32
|
+
metrics.scopeRefreshes++;`);
|
|
33
|
+
replace("item.delivery.defer('Native delivery lease expired');", `
|
|
34
|
+
recordRecoveryTrace({ event: 'invalidate', owner: item.scope.owner, reason: 'delivery-lease-expired' });
|
|
35
|
+
item.delivery.defer('Native delivery lease expired');`);
|
|
36
|
+
replace('deliveries.delete(record.params.token);', `
|
|
37
|
+
recordRecoveryTrace({ event: 'invalidate', owner: record.owner, reason: record.params.delivered === true ? 'receipt-delivered' : 'receipt-deferred' });
|
|
38
|
+
deliveries.delete(record.params.token);`);
|
|
39
|
+
replace('scopes.delete(oldest); forgetOwner(oldest);', `
|
|
40
|
+
recordRecoveryTrace({ event: 'invalidate', ownerKey: oldest, reason: 'scope-evicted' });
|
|
41
|
+
scopes.delete(oldest); forgetOwner(oldest);`);
|
|
42
|
+
return `import { recordRecoveryTrace } from ${JSON.stringify(recorder)};\n${source}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function load(url, context, nextLoad) {
|
|
46
|
+
if (url !== target) return nextLoad(url, context);
|
|
47
|
+
const source = instrumentRecoveryTrace(readFileSync(new URL(url), 'utf8'));
|
|
48
|
+
return { format: 'module', shortCircuit: true, source: ts.transpileModule(source, {
|
|
49
|
+
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },
|
|
50
|
+
}).outputText };
|
|
51
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const LIMIT = 128;
|
|
2
|
+
const records = [];
|
|
3
|
+
let sequence = 0;
|
|
4
|
+
|
|
5
|
+
// This recorder is imported only by the resource fixture and its loader.
|
|
6
|
+
export function recordRecoveryTrace(record) {
|
|
7
|
+
const bounded = JSON.parse(JSON.stringify(record, (_key, value) => typeof value === 'string' ? value.slice(0, 256) : value));
|
|
8
|
+
const entry = { sequence: ++sequence, at: Date.now(), ...bounded };
|
|
9
|
+
if (Buffer.byteLength(JSON.stringify(entry)) > 4096) throw new Error('Resource recovery trace entry exceeds its test-only bound');
|
|
10
|
+
records.push(entry);
|
|
11
|
+
if (records.length > LIMIT) records.shift();
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function recoveryTraceSnapshot() {
|
|
15
|
+
return { total: sequence, dropped: sequence - records.length, records: [...records] };
|
|
16
|
+
}
|
|
@@ -179,7 +179,8 @@ try {
|
|
|
179
179
|
phase('event-publication', history, count);
|
|
180
180
|
entry.eventPublication = await measureEventPublication({ socketPath: ready.socket, agentDir: agent,
|
|
181
181
|
scope: { cwd: root, sessionId, active: true }, metaPath: join(runs, 'sa_resource_active_0', 'meta.json'),
|
|
182
|
-
taskId: 'sa_resource_active_0', subscribers: count }
|
|
182
|
+
taskId: 'sa_resource_active_0', subscribers: count, phase: { history, clients: count },
|
|
183
|
+
diagnostics: () => control.request('runtime_get_metrics') });
|
|
183
184
|
assert.ok(entry.eventPublication.ms.max <= 1000, `Committed changes must reach healthy subscribers within 1s: ${JSON.stringify(entry.eventPublication.ms)}`);
|
|
184
185
|
assert.ok(entry.eventPublication.ms.p50 >= 0, 'Event visibility must follow the source commit');
|
|
185
186
|
console.log(JSON.stringify(entry));
|
|
@@ -11,11 +11,15 @@
|
|
|
11
11
|
"@earendil-works/pi-ai": "1.4.0",
|
|
12
12
|
"@earendil-works/pi-coding-agent": "1.4.0",
|
|
13
13
|
"@earendil-works/pi-tui": "1.4.0",
|
|
14
|
+
"fsevents": "2.3.3",
|
|
14
15
|
"proper-lockfile": "4.1.2",
|
|
15
16
|
"shell-quote": "1.12.0",
|
|
16
17
|
"smol-toml": "1.9.0",
|
|
17
18
|
"typebox": "1.3.27",
|
|
18
19
|
"yaml": "2.9.1"
|
|
20
|
+
},
|
|
21
|
+
"optionalDependencies": {
|
|
22
|
+
"fsevents": "2.3.3"
|
|
19
23
|
}
|
|
20
24
|
},
|
|
21
25
|
"node_modules/@anthropic-ai/sdk": {
|
|
@@ -929,6 +933,20 @@
|
|
|
929
933
|
"node": ">=12.20.0"
|
|
930
934
|
}
|
|
931
935
|
},
|
|
936
|
+
"node_modules/fsevents": {
|
|
937
|
+
"version": "2.3.3",
|
|
938
|
+
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
|
939
|
+
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
|
|
940
|
+
"hasInstallScript": true,
|
|
941
|
+
"license": "MIT",
|
|
942
|
+
"optional": true,
|
|
943
|
+
"os": [
|
|
944
|
+
"darwin"
|
|
945
|
+
],
|
|
946
|
+
"engines": {
|
|
947
|
+
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
|
948
|
+
}
|
|
949
|
+
},
|
|
932
950
|
"node_modules/gaxios": {
|
|
933
951
|
"version": "7.3.1",
|
|
934
952
|
"resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.3.1.tgz",
|
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
"private": true,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"dependencies": {
|
|
7
|
-
"@earendil-works/pi-coding-agent": "1.4.0",
|
|
8
7
|
"@earendil-works/pi-ai": "1.4.0",
|
|
8
|
+
"@earendil-works/pi-coding-agent": "1.4.0",
|
|
9
9
|
"@earendil-works/pi-tui": "1.4.0",
|
|
10
10
|
"proper-lockfile": "4.1.2",
|
|
11
11
|
"shell-quote": "1.12.0",
|
|
@@ -18,5 +18,8 @@
|
|
|
18
18
|
"@earendil-works/pi-mcp": "1.4.0",
|
|
19
19
|
"@earendil-works/pi-codemode": "1.4.0",
|
|
20
20
|
"@earendil-works/pi-telemetry": "1.4.0"
|
|
21
|
+
},
|
|
22
|
+
"optionalDependencies": {
|
|
23
|
+
"fsevents": "2.3.3"
|
|
21
24
|
}
|
|
22
25
|
}
|
|
@@ -16,7 +16,7 @@ export function sourceProvenance(workspace) {
|
|
|
16
16
|
const files = [];
|
|
17
17
|
const walk = relative => {
|
|
18
18
|
for (const entry of readdirSync(join(workspace, relative), { withFileTypes: true })) {
|
|
19
|
-
if (['node_modules', '.git', 'dist', 'coverage'].includes(entry.name)) continue;
|
|
19
|
+
if (['node_modules', '.git', '.work', 'dist', 'coverage'].includes(entry.name)) continue;
|
|
20
20
|
const path = `${relative}/${entry.name}`;
|
|
21
21
|
if (entry.isDirectory()) walk(path);
|
|
22
22
|
else if (entry.isFile()) files.push(path);
|
|
@@ -26,6 +26,6 @@ export function sourceProvenance(workspace) {
|
|
|
26
26
|
for (const file of ['package.json', 'package-lock.json']) if (existsSync(join(workspace, file))) files.push(file);
|
|
27
27
|
const manifest = files.sort().map(path => ({ path, sha256: createHash('sha256').update(readFileSync(join(workspace, path))).digest('hex') }));
|
|
28
28
|
return { head, dirty, kind: head ? 'git-checkout' : 'source-copy-without-git',
|
|
29
|
-
manifest: { algorithm: 'sha256', scope: 'packages and scripts excluding node_modules/dist/coverage, plus root package manifests',
|
|
29
|
+
manifest: { algorithm: 'sha256', scope: 'packages and scripts excluding .git/.work/node_modules/dist/coverage, plus root package manifests',
|
|
30
30
|
files: manifest.length, sha256: createHash('sha256').update(JSON.stringify(manifest)).digest('hex') } };
|
|
31
31
|
}
|
package/scripts/test-on-pi.sh
CHANGED
|
@@ -26,21 +26,14 @@ cp "$ROOT_DIR/scripts/isolate-registry.mjs" "$PREFIX/scripts/"
|
|
|
26
26
|
cp -R "$PKG_DIR/src" "$PKG_DIR/test" "$PKG_DIR/scripts" "$PKG_DIR/package.json" "$PKG_DIR/tsconfig.json" "$PREFIX/packages/pi-better-server/"
|
|
27
27
|
[ -d "$PKG_DIR/codex-plugin" ] && cp -R "$PKG_DIR/codex-plugin" "$PREFIX/packages/pi-better-server/"
|
|
28
28
|
# Activity and permission regressions load the real sibling providers against this SDK.
|
|
29
|
-
node
|
|
30
|
-
import { cpSync } from "node:fs";
|
|
31
|
-
import { basename, join } from "node:path";
|
|
32
|
-
for (const name of ["pi-better-subagents", "pi-better-background-tasks", "pi-better-sandbox", "operation-coordinator"]) {
|
|
33
|
-
cpSync(join(process.argv[2], "packages", name), join(process.argv[3], "packages", name), {
|
|
34
|
-
recursive: true, filter: path => !["node_modules", ".work", ".pi-compat"].includes(basename(path)),
|
|
35
|
-
});
|
|
36
|
-
}
|
|
37
|
-
NODE
|
|
29
|
+
node "$PKG_DIR/scripts/copy-pi-test-providers.mjs" "$ROOT_DIR" "$PREFIX"
|
|
38
30
|
# Install the consumer's declared runtime closure, not just the host's transitives.
|
|
39
31
|
# Its host-provided peers must keep resolving to the requested Pi above.
|
|
40
32
|
(cd "$PREFIX/packages/pi-better-server" && npm install --omit=dev --ignore-scripts --legacy-peer-deps --package-lock=false --no-audit --no-fund)
|
|
41
33
|
(cd "$PREFIX/packages/pi-better-subagents" && npm install --omit=dev --ignore-scripts --legacy-peer-deps --package-lock=false --no-audit --no-fund)
|
|
42
34
|
(cd "$PREFIX/packages/pi-better-background-tasks" && npm install --omit=dev --ignore-scripts --legacy-peer-deps --package-lock=false --no-audit --no-fund)
|
|
43
35
|
(cd "$PREFIX/packages/pi-better-sandbox" && npm install --omit=dev --ignore-scripts --legacy-peer-deps --package-lock=false --no-audit --no-fund)
|
|
36
|
+
(cd "$PREFIX/packages/pi-better-goal" && npm install --omit=dev --ignore-scripts --legacy-peer-deps --package-lock=false --no-audit --no-fund)
|
|
44
37
|
|
|
45
38
|
cd "$PREFIX/packages/pi-better-server"
|
|
46
39
|
installed="$(node -p "require('$PREFIX/node_modules/@earendil-works/pi-coding-agent/package.json').version")"
|
package/src/handshake.ts
CHANGED
|
@@ -12,7 +12,7 @@ export function serverHello(identity: HelloIdentity = {}): HelloData {
|
|
|
12
12
|
return { protocolVersion: PROTOCOL_VERSION, piVersion: PI_VERSION, extensionVersions: { ...SERVER_EXTENSION_VERSIONS },
|
|
13
13
|
...(identity.agentDir ? { agentDir: identity.agentDir, nodeVersion: process.versions.node } : {}),
|
|
14
14
|
...(build ? { build } : {}), ...(identity.instanceId ? { instanceId: identity.instanceId } : {}),
|
|
15
|
-
capabilities: [...(identity.runtimeLifecycle ? ["runtime-client-retention-v1"] : []),...(identity.agentDir ? ["runtime-status-v1", "runtime-state-v1", "runtime-subscriptions-v1", "runtime-background-state-v1", "runtime-background-execution-v1", "runtime-cancellation-v1", "runtime-result-supervision-v1", "runtime-catalog-v1", "runtime-subagent-launch-v1"] : []), "native-client-v1", "package-sync-v1", "global-package-sync-v1", "session-browser-v1", "folder-browser-v1", "session-transfer-v1", "compressed-bundle-v1", "remote-reload-v1",
|
|
15
|
+
capabilities: [...(identity.runtimeLifecycle ? ["runtime-client-retention-v1"] : []),...(identity.agentDir ? ["runtime-status-v1", "runtime-state-v1", "runtime-subscriptions-v1", "runtime-background-state-v1", "runtime-background-execution-v1", "runtime-background-admission-v2", "runtime-cancellation-v1", "runtime-result-supervision-v1", "runtime-catalog-v1", "runtime-subagent-launch-v1"] : []), "native-client-v1", "package-sync-v1", "global-package-sync-v1", "session-browser-v1", "folder-browser-v1", "session-transfer-v1", "compressed-bundle-v1", "remote-reload-v1",
|
|
16
16
|
...(identity.safeUpgrade && build && identity.instanceId ? ["safe-upgrade-v1"] : [])] };
|
|
17
17
|
}
|
|
18
18
|
|
package/src/hosted-session.ts
CHANGED
|
@@ -3,12 +3,12 @@ import type { AgentSession, AgentSessionEvent, RpcCommand, RpcResponse, RpcSessi
|
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
4
|
import type { EventLog, LoggedEvent, Replay } from "./event-log.ts";
|
|
5
5
|
import { UNSUPPORTED_SESSION_COMMANDS } from "./protocol.ts";
|
|
6
|
-
import { assertHostedAdmission, fenceHostedSession, reloadHostedSession } from "./maintenance.ts";
|
|
6
|
+
import { assertHostedAdmission, fenceHostedSession, reloadHostedSession, hostedCacheReasons } from "./maintenance.ts";
|
|
7
7
|
import type { SessionActivity } from "./session-activity.ts";
|
|
8
8
|
import { UiBridge, type PendingDialog } from "./ui-bridge.ts";
|
|
9
9
|
|
|
10
10
|
type Listener = (logged: LoggedEvent) => void;
|
|
11
|
-
type CommandWork = { kind: string; dialogs: number };
|
|
11
|
+
type CommandWork = { kind: string; dialogs: number; id: number; startedAt: number };
|
|
12
12
|
|
|
13
13
|
function ok(id: string | undefined, command: string, data?: unknown): RpcResponse {
|
|
14
14
|
return { ...(id !== undefined ? { id } : {}), type: "response", command, success: true, ...(data !== undefined ? { data } : {}) } as RpcResponse;
|
|
@@ -60,6 +60,29 @@ export class HostedSession {
|
|
|
60
60
|
private runtimeReleased = false;
|
|
61
61
|
private operations = 0;
|
|
62
62
|
private readonly commandsInFlight = new Set<CommandWork>();
|
|
63
|
+
private operationCounter = 0;
|
|
64
|
+
private progressAt = Date.now();
|
|
65
|
+
private operationRecords = new Map<number, { source: string; lastProgressAt: number }>();
|
|
66
|
+
lifecycleReasons() {
|
|
67
|
+
const dialogs = [...this.dialogWork.values()];
|
|
68
|
+
const modelBlocked = dialogs.some(work => work.toolCallId || !work.command || ['prompt','steer','follow_up'].includes(work.command.kind));
|
|
69
|
+
const compactBlocked = dialogs.some(work => !work.toolCallId && (!work.command || work.command.kind === 'compact'));
|
|
70
|
+
const bashBlocked = dialogs.some(work => !work.toolCallId && (!work.command || work.command.kind === 'bash'));
|
|
71
|
+
const blockedTools = new Set(dialogs.map(work => work.toolCallId));
|
|
72
|
+
const base = { owner: this.session.sessionId, generation: this.generation, lastProgressAt: this.progressAt,
|
|
73
|
+
executionDeadline: null, nextDeadline: null, recovery: 'existing-hosted-idle-and-admission-policy' };
|
|
74
|
+
return [
|
|
75
|
+
...[...this.operationRecords].map(([id, record]) => ({ ...base, kind: 'hosted-operation', id, ...record, retainsExecution: false })),
|
|
76
|
+
...[...this.commandsInFlight].map(work => ({ ...base, kind: 'hosted-command', id: work.id, source: work.kind, lastProgressAt: work.startedAt, retainsExecution: work.dialogs === 0 })),
|
|
77
|
+
...[...this.activeTools.keys()].map(id => ({ ...base, kind: 'hosted-tool', id, retainsExecution: !blockedTools.has(id) })),
|
|
78
|
+
...[...this.dialogWork.keys()].map(id => ({ ...base, kind: 'hosted-dialog', id, retainsExecution: false })),
|
|
79
|
+
...(this.turnActive ? [{ ...base, kind: 'hosted-turn', id: this.generation, retainsExecution: !modelBlocked }] : []),
|
|
80
|
+
...(this.session.isCompacting ? [{ ...base, kind: 'hosted-compaction', id: this.generation, retainsExecution: !compactBlocked }] : []),
|
|
81
|
+
...(this.session.isBashRunning ? [{ ...base, kind: 'hosted-bash', id: this.generation, retainsExecution: !bashBlocked }] : []),
|
|
82
|
+
...(this.activity?.lifecycleReasons() ?? []).map(record => ({ ...base, ...record, retainsExecution: record.kind !== 'hosted-observation' })),
|
|
83
|
+
...hostedCacheReasons(this.session),
|
|
84
|
+
];
|
|
85
|
+
}
|
|
63
86
|
private readonly workContext = new AsyncLocalStorage<CommandWork>();
|
|
64
87
|
private readonly dialogWork = new Map<string, { command?: CommandWork; toolCallId?: string }>();
|
|
65
88
|
/**
|
|
@@ -136,8 +159,10 @@ export class HostedSession {
|
|
|
136
159
|
async clientSnapshot(): Promise<Record<string, unknown>> {
|
|
137
160
|
if (this.disposed) throw new Error("Session runtime is closed; explicitly reopen the session");
|
|
138
161
|
this.operations++;
|
|
162
|
+
const record = ++this.operationCounter;
|
|
163
|
+
this.operationRecords.set(record, { source: 'client-snapshot', lastProgressAt: Date.now() });
|
|
139
164
|
try { return await this.readClientSnapshot(); }
|
|
140
|
-
finally { this.operations--; }
|
|
165
|
+
finally { this.operations--; this.operationRecords.delete(record); }
|
|
141
166
|
}
|
|
142
167
|
|
|
143
168
|
private async readClientSnapshot(): Promise<Record<string, unknown>> {
|
|
@@ -219,6 +244,7 @@ export class HostedSession {
|
|
|
219
244
|
publishRuntimeEvent(event: unknown): void { this.publish(event); }
|
|
220
245
|
|
|
221
246
|
private publish(event: unknown): void {
|
|
247
|
+
this.progressAt = Date.now();
|
|
222
248
|
if (this.runtimeReleased) return;
|
|
223
249
|
const logged = this.log.append(event);
|
|
224
250
|
for (const listener of this.listeners) listener(logged);
|
|
@@ -418,7 +444,8 @@ export class HostedSession {
|
|
|
418
444
|
try { if (!command.type.startsWith("get_")) assertHostedAdmission(this.session, command.type === "set_session_name"); }
|
|
419
445
|
catch (error) { return fail(command.id, command.type, String(error)); }
|
|
420
446
|
this.operations++;
|
|
421
|
-
const work: CommandWork = { kind: command.type, dialogs: 0 };
|
|
447
|
+
const work: CommandWork = { kind: command.type, dialogs: 0, id: ++this.operationCounter, startedAt: Date.now() };
|
|
448
|
+
this.operationRecords.set(work.id, { source: passive ? 'passive-rpc' : 'command-rpc', lastProgressAt: work.startedAt });
|
|
422
449
|
if (!passive) {
|
|
423
450
|
// Installed synchronously, before dispatch can reach provider/preflight awaits.
|
|
424
451
|
this.commandsInFlight.add(work);
|
|
@@ -428,6 +455,7 @@ export class HostedSession {
|
|
|
428
455
|
try { return await this.workContext.run(work, () => this.dispatch(command)); }
|
|
429
456
|
finally {
|
|
430
457
|
this.operations--;
|
|
458
|
+
this.operationRecords.delete(work.id);
|
|
431
459
|
if (!passive) {
|
|
432
460
|
this.commandsInFlight.delete(work);
|
|
433
461
|
this.onActivity("work");
|
package/src/maintenance.ts
CHANGED
|
@@ -16,7 +16,7 @@ export class MaintenanceBusyError extends Error {
|
|
|
16
16
|
}
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
-
type Admission = { gate: HostMaintenance; closed: boolean; calls: number; persistenceSafe: boolean; reloadEntry: boolean };
|
|
19
|
+
type Admission = { gate: HostMaintenance; manager?: SessionManager; closed: boolean; calls: number; persistenceSafe: boolean; reloadEntry: boolean };
|
|
20
20
|
type Method = (this: any, ...args: any[]) => any;
|
|
21
21
|
type WarmGuard = { state: Admission; methods: Map<string, Method> };
|
|
22
22
|
type GuardState = { managers: WeakMap<object, Admission>; installed: WeakSet<object>; supported: WeakSet<object>; tools: WeakSet<object>; warmers?: WeakMap<object, WarmGuard> };
|
|
@@ -41,12 +41,14 @@ function tracked(state: Admission | undefined, original: Method, receiver: unkno
|
|
|
41
41
|
throw error;
|
|
42
42
|
}
|
|
43
43
|
state.calls++;
|
|
44
|
+
const finishRecord = state.gate.trackOperation(`sdk:${original.name || 'call'}`, state.manager?.getSessionId());
|
|
44
45
|
try {
|
|
45
46
|
const result = Reflect.apply(original, receiver, args);
|
|
46
|
-
if (result && typeof result.then === "function") return Promise.resolve(result).finally(() => { state.calls--; });
|
|
47
|
+
if (result && typeof result.then === "function") return Promise.resolve(result).finally(() => { state.calls--; finishRecord(); });
|
|
47
48
|
state.calls--;
|
|
49
|
+
finishRecord();
|
|
48
50
|
return result;
|
|
49
|
-
} catch (error) { state.calls--; throw error; }
|
|
51
|
+
} catch (error) { state.calls--; finishRecord(); throw error; }
|
|
50
52
|
}
|
|
51
53
|
|
|
52
54
|
function wrap(proto: object, name: string, invoke: (original: Method, receiver: any, args: any[]) => any): boolean {
|
|
@@ -195,6 +197,20 @@ export function assertHostedAdmission(session: AgentSession, metadata = false):
|
|
|
195
197
|
}
|
|
196
198
|
|
|
197
199
|
export function hostedSdkCalls(session: AgentSession): number { return guards.managers.get(session.sessionManager)?.calls ?? 0; }
|
|
200
|
+
const warmingRuns = new WeakMap<object, number>();
|
|
201
|
+
let warmingRunCounter = 0;
|
|
202
|
+
export function hostedCacheReasons(session: AgentSession) {
|
|
203
|
+
const warmer = (session as unknown as { _cacheWarmer?: { run?: unknown } })._cacheWarmer;
|
|
204
|
+
const run = warmer?.run;
|
|
205
|
+
if (cacheWarmingState(session) === 'idle') return [];
|
|
206
|
+
let id: number | null = null;
|
|
207
|
+
if (run && typeof run === 'object') {
|
|
208
|
+
id = warmingRuns.get(run) ?? ++warmingRunCounter; warmingRuns.set(run, id);
|
|
209
|
+
}
|
|
210
|
+
return [{ kind: 'hosted-cache-work', owner: session.sessionId, id, state: run === undefined ? 'unsupported-observation' : 'queued-or-running',
|
|
211
|
+
lastProgressAt: null, executionDeadline: null, nextDeadline: null, retainsExecution: false,
|
|
212
|
+
recovery: 'existing-sdk-cache-warmer-must-retire-run-before-maintenance-no-new-runtime-lease' }];
|
|
213
|
+
}
|
|
198
214
|
|
|
199
215
|
export async function reloadHostedSession(session: AgentSession): Promise<void> {
|
|
200
216
|
const state = guards.managers.get(session.sessionManager);
|
|
@@ -205,6 +221,15 @@ export async function reloadHostedSession(session: AgentSession): Promise<void>
|
|
|
205
221
|
|
|
206
222
|
/** The registry, native reload/package host and upgrade activation share this one gate. */
|
|
207
223
|
export class HostMaintenance {
|
|
224
|
+
private recordCounter = 0;
|
|
225
|
+
private records = new Map<number, { kind: string; id: number; source: string; sessionId?: string; lastProgressAt: number; executionDeadline: null; nextDeadline: null; recovery: string }>();
|
|
226
|
+
lifecycleReasons() { return [...this.records.values()].map(record => ({ ...record })); }
|
|
227
|
+
trackOperation(source: string, sessionId?: string): () => void {
|
|
228
|
+
const id = ++this.recordCounter;
|
|
229
|
+
this.records.set(id, { kind: 'host-operation', id, source, sessionId, lastProgressAt: Date.now(),
|
|
230
|
+
executionDeadline: null, nextDeadline: null, recovery: 'drain-admitted-host-operation-until-settlement' });
|
|
231
|
+
return () => { this.records.delete(id); };
|
|
232
|
+
}
|
|
208
233
|
private purpose: MaintenancePurpose | undefined;
|
|
209
234
|
private operations = 0;
|
|
210
235
|
private stopped = false;
|
|
@@ -225,7 +250,7 @@ export class HostMaintenance {
|
|
|
225
250
|
const proto = SessionManager.prototype as unknown as Record<string, unknown>;
|
|
226
251
|
const sessionProto = AgentSession.prototype as unknown as Record<string, unknown>;
|
|
227
252
|
guards.managers.set(manager, {
|
|
228
|
-
gate: this, closed: false, calls: 0, reloadEntry: false,
|
|
253
|
+
gate: this, manager, closed: false, calls: 0, reloadEntry: false,
|
|
229
254
|
persistenceSafe: /^(0\.82|1\.2)\./.test(VERSION) && guards.supported.has(AgentSession.prototype) && guards.supported.has(SessionManager.prototype) &&
|
|
230
255
|
["_persist", "_rewriteFile"].every(name => typeof proto[name] === "function" && !Object.hasOwn(manager, name)) &&
|
|
231
256
|
["_buildRuntime", "_refreshToolRegistry", "prompt", "compact", "executeBash"].every(name => typeof sessionProto[name] === "function"),
|
|
@@ -241,15 +266,17 @@ export class HostMaintenance {
|
|
|
241
266
|
const state = guards.managers.get(manager)!;
|
|
242
267
|
assertAdmission(state);
|
|
243
268
|
state.calls++;
|
|
269
|
+
const finishRecord = this.trackOperation('hosted-tool', manager.getSessionId());
|
|
244
270
|
let released = false;
|
|
245
|
-
return () => { if (!released) { released = true; state.calls--; } };
|
|
271
|
+
return () => { if (!released) { released = true; state.calls--; finishRecord(); } };
|
|
246
272
|
}
|
|
247
273
|
|
|
248
274
|
enterSessionOperation(): () => void {
|
|
249
275
|
this.assertAdmission();
|
|
250
276
|
this.operations++;
|
|
277
|
+
const finishRecord = this.trackOperation('session-operation');
|
|
251
278
|
let released = false;
|
|
252
|
-
return () => { if (!released) { released = true; this.operations--; } };
|
|
279
|
+
return () => { if (!released) { released = true; this.operations--; finishRecord(); } };
|
|
253
280
|
}
|
|
254
281
|
|
|
255
282
|
async withIdleSessions<T>(purpose: MaintenancePurpose, run: (sessions: HostedSession[], lease: IdleSessionsLease) => Promise<T>): Promise<T> {
|
|
@@ -311,7 +338,8 @@ export class HostMaintenance {
|
|
|
311
338
|
for (const session of sessions) session.fence();
|
|
312
339
|
},
|
|
313
340
|
};
|
|
341
|
+
const finishRecord = this.trackOperation(purpose);
|
|
314
342
|
try { await lease.refreshIdle(); return await run(sessions, lease); }
|
|
315
|
-
finally { valid = false; if (!this.stopped && held) this.purpose = undefined; }
|
|
343
|
+
finally { finishRecord(); valid = false; if (!this.stopped && held) this.purpose = undefined; }
|
|
316
344
|
}
|
|
317
345
|
}
|