pi-better-server 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +4 -1
- package/scripts/copy-pi-test-providers.mjs +10 -0
- package/scripts/event-publication/README.md +26 -0
- package/scripts/event-publication/commit.mjs +21 -0
- package/scripts/event-publication/measure.mjs +37 -5
- package/scripts/event-publication/writer.mjs +3 -8
- package/scripts/measure-full-runtime/probe.mjs +4 -2
- package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
- package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
- package/scripts/measure-shared-reads.mjs +2 -1
- package/scripts/private-runtime/package-lock.json +18 -0
- package/scripts/private-runtime/package.json +4 -1
- package/scripts/source-provenance.mjs +2 -2
- package/scripts/test-on-pi.sh +2 -9
- package/src/handshake.ts +1 -1
- package/src/hosted-session.ts +32 -4
- package/src/maintenance.ts +35 -7
- package/src/registry.ts +28 -4
- package/src/runtime/attempt-invalidation.ts +54 -0
- package/src/runtime/background-history.ts +151 -45
- package/src/runtime/background-policy.ts +9 -4
- package/src/runtime/background-tools.ts +131 -23
- package/src/runtime/background.ts +351 -68
- package/src/runtime/cancellation.ts +28 -7
- package/src/runtime/catalog-sources.ts +199 -0
- package/src/runtime/catalog.ts +53 -21
- package/src/runtime/client.ts +22 -2
- package/src/runtime/domain/assignment-inbox.mjs +119 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -1
- package/src/runtime/domain/assignment-observation.mjs +43 -35
- package/src/runtime/domain/background/process-identity.mjs +20 -2
- package/src/runtime/domain/background/process.mjs +3 -3
- package/src/runtime/domain/background/registry.mjs +61 -3
- package/src/runtime/domain/background/types.mjs +1 -0
- package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
- package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
- package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
- package/src/runtime/domain/background-service/goal-provider.ts +31 -16
- package/src/runtime/domain/background-service/index.domain.mjs +6 -9
- package/src/runtime/domain/background-service/index.ts +6 -9
- package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
- package/src/runtime/domain/background-service/managed-authority.ts +5 -3
- package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
- package/src/runtime/domain/background-service/managed-client.ts +20 -7
- package/src/runtime/domain/background-service/managed-frontend.domain.mjs +75 -17
- package/src/runtime/domain/background-service/managed-frontend.ts +62 -17
- package/src/runtime/domain/background-service/navigator-provider.domain.mjs +16 -5
- package/src/runtime/domain/background-service/navigator-provider.ts +15 -5
- package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
- package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
- package/src/runtime/domain/background-service/observed-waits.domain.mjs +170 -27
- package/src/runtime/domain/background-service/observed-waits.ts +154 -30
- package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
- package/src/runtime/domain/background-service/process-identity.ts +18 -2
- package/src/runtime/domain/background-service/process.domain.mjs +3 -3
- package/src/runtime/domain/background-service/process.ts +3 -3
- package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
- package/src/runtime/domain/background-service/registry.ts +53 -5
- package/src/runtime/domain/background-service/runtime.domain.mjs +32 -16
- package/src/runtime/domain/background-service/runtime.ts +19 -9
- package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
- package/src/runtime/domain/background-service/sandbox.ts +14 -11
- package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
- package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
- package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
- package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
- package/src/runtime/domain/background-service/shared-navigator.domain.mjs +218 -13
- package/src/runtime/domain/background-service/shared-navigator.ts +197 -14
- package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +21 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +34 -8
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
- package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
- package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
- package/src/runtime/domain/background-service/supervisor/generated/process.mjs +3 -3
- package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
- package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
- package/src/runtime/domain/background-service/tools.domain.mjs +31 -24
- package/src/runtime/domain/background-service/tools.ts +41 -38
- package/src/runtime/domain/background-service/types.domain.mjs +1 -0
- package/src/runtime/domain/background-service/types.ts +3 -1
- package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
- package/src/runtime/domain/background-service/work-observation.ts +46 -19
- package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
- package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
- package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
- package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
- package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
- package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
- package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
- package/src/runtime/domain/coordinator/src/store.mjs +21 -3
- package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
- package/src/runtime/domain/coordinator/src/types.mjs +1 -1
- package/src/runtime/domain/health-observation.d.mts +3 -1
- package/src/runtime/domain/health-observation.mjs +189 -190
- package/src/runtime/domain/log-cursor.d.mts +2 -0
- package/src/runtime/domain/log-cursor.mjs +85 -16
- package/src/runtime/domain/parse.d.mts +4 -1
- package/src/runtime/domain/parse.mjs +50 -5
- package/src/runtime/domain/sandbox-policy/README.md +61 -63
- package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
- package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
- package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
- package/src/runtime/domain/sandbox-policy/index.ts +52 -9
- package/src/runtime/domain/sandbox-policy/package.json +1 -1
- package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
- package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
- package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
- package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
- package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
- package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
- package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
- package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
- package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
- package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
- package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
- package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
- package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
- package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
- package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
- package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
- package/src/runtime/domain/subagents/README.md +1 -1
- package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +12 -6
- package/src/runtime/domain/subagents/assignment-outcomes.ts +11 -5
- package/src/runtime/domain/subagents/assignment-report.domain.mjs +87 -24
- package/src/runtime/domain/subagents/assignment-report.ts +83 -19
- package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
- package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
- package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
- package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
- package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
- package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
- package/src/runtime/domain/subagents/catalog-store.ts +27 -20
- package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
- package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
- package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
- package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
- package/src/runtime/domain/subagents/child-operations.ts +80 -1
- package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
- package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
- package/src/runtime/domain/subagents/child-process-list.ts +8 -0
- package/src/runtime/domain/subagents/config.domain.mjs +49 -2
- package/src/runtime/domain/subagents/config.ts +46 -2
- package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
- package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
- package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
- package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
- package/src/runtime/domain/subagents/extensions.mjs +11 -13
- package/src/runtime/domain/subagents/finalization.domain.mjs +12 -0
- package/src/runtime/domain/subagents/finalization.ts +15 -0
- package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
- package/src/runtime/domain/subagents/goal-provider.ts +44 -2
- package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
- package/src/runtime/domain/subagents/health-observation.ts +43 -48
- package/src/runtime/domain/subagents/index.domain.mjs +296 -123
- package/src/runtime/domain/subagents/index.ts +257 -98
- package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
- package/src/runtime/domain/subagents/launch-context.ts +23 -0
- package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
- package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
- package/src/runtime/domain/subagents/log-cursor.ts +91 -15
- package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
- package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +6 -3
- package/src/runtime/domain/subagents/managed-launch-client.ts +6 -3
- package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
- package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
- package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
- package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
- package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
- package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
- package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
- package/src/runtime/domain/subagents/owned-exit.ts +12 -0
- package/src/runtime/domain/subagents/package.json +1 -1
- package/src/runtime/domain/subagents/parse.domain.mjs +50 -5
- package/src/runtime/domain/subagents/parse.ts +48 -6
- package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
- package/src/runtime/domain/subagents/permission-policy.ts +41 -8
- package/src/runtime/domain/subagents/process-identity.mjs +33 -0
- package/src/runtime/domain/subagents/registry.domain.mjs +47 -33
- package/src/runtime/domain/subagents/registry.ts +54 -33
- package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
- package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
- package/src/runtime/domain/subagents/shared-catalog.domain.mjs +6 -23
- package/src/runtime/domain/subagents/shared-catalog.ts +6 -14
- package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
- package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
- package/src/runtime/domain/subagents/shared-navigator.domain.mjs +218 -13
- package/src/runtime/domain/subagents/shared-navigator.ts +197 -14
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +21 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +34 -8
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
- package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
- package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
- package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
- package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
- package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
- package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
- package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
- package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
- package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
- package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
- package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
- package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
- package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
- package/src/runtime/domain/subagents/task-policy.domain.mjs +1 -1
- package/src/runtime/domain/subagents/task-policy.ts +3 -1
- package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
- package/src/runtime/domain/subagents/timing.ts +10 -1
- package/src/runtime/domain/subagents/work-observation.domain.mjs +77 -16
- package/src/runtime/domain/subagents/work-observation.ts +71 -16
- package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
- package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
- package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
- package/src/runtime/domain/subagents/worker-waits.ts +93 -34
- package/src/runtime/health-config.ts +27 -11
- package/src/runtime/log-checkpoints.ts +117 -0
- package/src/runtime/mutation-store.ts +5 -4
- package/src/runtime/queries.ts +25 -2
- package/src/runtime/query-executor.ts +149 -28
- package/src/runtime/query-worker.mjs +106 -21
- package/src/runtime/read-model.ts +846 -120
- package/src/runtime/read-watchdog-probe.ts +4 -0
- package/src/runtime/result-supervision.ts +188 -16
- package/src/runtime/source-watch.ts +175 -0
- package/src/runtime/subagent-launch.ts +11 -4
- package/src/runtime/work-budget.ts +130 -0
- package/src/runtime/work-client.d.mts +8 -0
- package/src/runtime/work-client.mjs +150 -7
- package/src/server.ts +104 -23
- package/src/session-activity.ts +26 -4
- package/src/version.ts +1 -1
|
@@ -1,5 +1,17 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
1
2
|
import { connect } from "node:net";
|
|
2
3
|
import { performance } from "node:perf_hooks";
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
5
|
+
|
|
6
|
+
/** A persisted session can own work even when its selected branch is empty. */
|
|
7
|
+
export function shouldRestoreWorkObservation(event, session) {
|
|
8
|
+
if (event?.piBetterObserveWork) return true;
|
|
9
|
+
const reason = event?.reason;
|
|
10
|
+
if (reason === "new") return false;
|
|
11
|
+
if (reason !== "startup" || typeof session?.getSessionFile !== "function") return true;
|
|
12
|
+
const file = session.getSessionFile();
|
|
13
|
+
return file ? existsSync(file) : Boolean(session.getLeafId?.());
|
|
14
|
+
}
|
|
3
15
|
|
|
4
16
|
/** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
|
|
5
17
|
export class WorkClient {
|
|
@@ -12,6 +24,11 @@ export class WorkClient {
|
|
|
12
24
|
scope;
|
|
13
25
|
buffer = "";
|
|
14
26
|
closed = false;
|
|
27
|
+
recoveryTimer;
|
|
28
|
+
recoveryActive = false;
|
|
29
|
+
recoveryAgain = false;
|
|
30
|
+
recoveryDelay = 100;
|
|
31
|
+
scopeGeneration = 0;
|
|
15
32
|
|
|
16
33
|
constructor(socketPath, agentDir, requiredCapabilities = []) {
|
|
17
34
|
this.socket = typeof socketPath === "string" ? connect(socketPath) : socketPath;
|
|
@@ -26,8 +43,8 @@ export class WorkClient {
|
|
|
26
43
|
const message = JSON.parse(line);
|
|
27
44
|
if (message.type === "event") {
|
|
28
45
|
if (message.event.type === "runtime_catalog_snapshot") { for (const listener of this.catalogListeners) listener(message.event.snapshot); continue; }
|
|
29
|
-
if (message.event.type === "resync_required") { this.degrade(message.event.reason);
|
|
30
|
-
else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot);
|
|
46
|
+
if (message.event.type === "resync_required") { this.degrade(message.event.reason); this.scheduleRecovery(); }
|
|
47
|
+
else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot, message.event.previousSeq);
|
|
31
48
|
} else {
|
|
32
49
|
const request = this.pending.get(message.id);
|
|
33
50
|
if (!request) continue;
|
|
@@ -37,7 +54,9 @@ export class WorkClient {
|
|
|
37
54
|
} catch (error) { this.fail(error); }
|
|
38
55
|
}
|
|
39
56
|
});
|
|
40
|
-
this.socket.on("error", error => this.fail(error)
|
|
57
|
+
this.socket.on("error", error => this.fail(["ECONNRESET", "EPIPE"].includes(error.code)
|
|
58
|
+
? Object.assign(new Error(`runtime-unavailable: disconnected (${error.code}); resync required`, { cause: error }), { code: error.code })
|
|
59
|
+
: error));
|
|
41
60
|
this.socket.on("close", () => this.fail(new Error("runtime-unavailable: disconnected; resync required")));
|
|
42
61
|
this.ready = this.request("hello", { protocolVersion: 1, runtimeRoot: agentDir, requiredCapabilities: ["runtime-state-v1", "runtime-subscriptions-v1", ...requiredCapabilities] })
|
|
43
62
|
.then(async hello => { if (typeof socketPath === "string" && hello.capabilities?.includes("runtime-client-retention-v1")) await this.request("runtime_register_client", { clientId: `work-${process.pid}` }); return hello; });
|
|
@@ -59,27 +78,63 @@ export class WorkClient {
|
|
|
59
78
|
this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
|
|
60
79
|
this.notify();
|
|
61
80
|
}
|
|
62
|
-
accept(snapshot) {
|
|
81
|
+
accept(snapshot, previousSeq) {
|
|
63
82
|
if (this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
|
|
64
83
|
if (this.snapshot?.instanceId && this.snapshot.instanceId !== snapshot.instanceId) {
|
|
65
84
|
this.degrade("instance-changed: resync required");
|
|
66
85
|
snapshot = { ...snapshot, resyncRequired: true, resyncReason: "instance-changed" };
|
|
67
|
-
} else if (this.snapshot?.seq !== undefined &&
|
|
86
|
+
} else if (this.snapshot?.seq !== undefined && Number.isSafeInteger(previousSeq) && previousSeq > this.snapshot.seq) {
|
|
68
87
|
this.degrade("sequence-gap: replacing with a full authoritative snapshot");
|
|
69
88
|
snapshot = { ...snapshot, resyncRequired: true, resyncReason: "sequence-gap" };
|
|
70
89
|
}
|
|
71
|
-
//
|
|
90
|
+
// Global seq may skip unrelated changes; only a missing subscription
|
|
91
|
+
// predecessor indicates loss. The received snapshot is still complete.
|
|
72
92
|
this.snapshot = Object.freeze(snapshot); this.notify();
|
|
73
93
|
}
|
|
94
|
+
scheduleRecovery(delay = 0) {
|
|
95
|
+
if (this.closed) return;
|
|
96
|
+
if (this.recoveryActive) { this.recoveryAgain = true; return; }
|
|
97
|
+
if (this.recoveryTimer) return;
|
|
98
|
+
this.recoveryTimer = setTimeout(() => {
|
|
99
|
+
this.recoveryTimer = undefined;
|
|
100
|
+
void this.recover();
|
|
101
|
+
}, delay);
|
|
102
|
+
this.recoveryTimer.unref?.();
|
|
103
|
+
}
|
|
104
|
+
async recover() {
|
|
105
|
+
const generation = this.scopeGeneration;
|
|
106
|
+
this.recoveryActive = true;
|
|
107
|
+
let retry = false;
|
|
108
|
+
try { await this.resync(); this.recoveryDelay = 100; }
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (!this.closed && generation === this.scopeGeneration) {
|
|
111
|
+
this.degrade(String(error));
|
|
112
|
+
retry = /runtime-(?:timeout|overloaded|unhealthy)/.test(String(error));
|
|
113
|
+
}
|
|
114
|
+
} finally {
|
|
115
|
+
this.recoveryActive = false;
|
|
116
|
+
const again = this.recoveryAgain;
|
|
117
|
+
this.recoveryAgain = false;
|
|
118
|
+
if (!this.closed && (again || retry && generation === this.scopeGeneration)) {
|
|
119
|
+
this.scheduleRecovery(again ? 0 : this.recoveryDelay);
|
|
120
|
+
this.recoveryDelay = Math.min(1000, this.recoveryDelay * 2);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
74
124
|
async subscribe(scope) {
|
|
75
125
|
await this.ready;
|
|
126
|
+
this.scopeGeneration++;
|
|
127
|
+
clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
|
|
128
|
+
this.recoveryAgain = false; this.recoveryDelay = 100;
|
|
76
129
|
this.scope = scope;
|
|
77
130
|
const snapshot = await this.request("runtime_subscribe", { scope });
|
|
78
131
|
this.accept(snapshot); return snapshot;
|
|
79
132
|
}
|
|
80
133
|
async resync() {
|
|
134
|
+
const generation = this.scopeGeneration;
|
|
81
135
|
const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
|
|
82
|
-
this.accept(snapshot);
|
|
136
|
+
if (!this.closed && generation === this.scopeGeneration) this.accept(snapshot);
|
|
137
|
+
return snapshot;
|
|
83
138
|
}
|
|
84
139
|
async get(scope) {
|
|
85
140
|
await this.ready;
|
|
@@ -94,9 +149,97 @@ export class WorkClient {
|
|
|
94
149
|
fail(error) {
|
|
95
150
|
if (this.closed) return;
|
|
96
151
|
this.closed = true;
|
|
152
|
+
this.scopeGeneration++;
|
|
153
|
+
clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
|
|
97
154
|
for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
|
|
98
155
|
this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
|
|
99
156
|
for (const listener of this.catalogListeners) listener({ status: "revoked" });
|
|
100
157
|
}
|
|
101
158
|
close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); this.catalogListeners.clear(); }
|
|
102
159
|
}
|
|
160
|
+
|
|
161
|
+
// Shared across the standalone extension copies, but never across agent roots.
|
|
162
|
+
const recoveryKey = Symbol.for("pi-better-runtime.connection-recovery.v2");
|
|
163
|
+
const recoveries = globalThis[recoveryKey] ??= new Map();
|
|
164
|
+
const connectionDemands = globalThis[Symbol.for("pi-better-runtime.connection-demand.v2")] ??= new Map();
|
|
165
|
+
|
|
166
|
+
/** Establish a transport only. Never replay an application request after dispatch. */
|
|
167
|
+
export async function connectWorkClient(socketPath, agentDir, capabilities = [], options = {}) {
|
|
168
|
+
const timeoutMs = options.timeoutMs ?? 60000;
|
|
169
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("Invalid connection timeout");
|
|
170
|
+
const deadline = performance.now() + timeoutMs;
|
|
171
|
+
const started = performance.now();
|
|
172
|
+
let backoff = 100, recovered = false, lastError, recoveryError, ownedRecovery;
|
|
173
|
+
const remaining = () => Math.max(1, deadline - performance.now());
|
|
174
|
+
const key = JSON.stringify([agentDir, socketPath]);
|
|
175
|
+
connectionDemands.set(key, (connectionDemands.get(key) ?? 0) + 1);
|
|
176
|
+
try {
|
|
177
|
+
while (performance.now() < deadline) {
|
|
178
|
+
options.signal?.throwIfAborted();
|
|
179
|
+
const client = new WorkClient(socketPath, agentDir, capabilities);
|
|
180
|
+
const abort = () => client.close();
|
|
181
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
182
|
+
const timer = setTimeout(() => client.close(), remaining());
|
|
183
|
+
try {
|
|
184
|
+
await client.ready;
|
|
185
|
+
options.signal?.throwIfAborted();
|
|
186
|
+
return client;
|
|
187
|
+
} catch (error) {
|
|
188
|
+
client.close();
|
|
189
|
+
options.signal?.throwIfAborted();
|
|
190
|
+
lastError = error;
|
|
191
|
+
if (recoveryError) throw recoveryError;
|
|
192
|
+
if (!["ENOENT", "ECONNREFUSED", "ECONNRESET", "EPIPE"].includes(error?.code)
|
|
193
|
+
&& !/runtime-unavailable: (?:disconnected|server closed)/.test(String(error))) throw error;
|
|
194
|
+
} finally {
|
|
195
|
+
clearTimeout(timer);
|
|
196
|
+
options.signal?.removeEventListener("abort", abort);
|
|
197
|
+
}
|
|
198
|
+
// Most replacement gaps need only a reconnect. Startup remains owner-safe.
|
|
199
|
+
if (!recovered && options.recover && performance.now() - started >= 250 && performance.now() < deadline) {
|
|
200
|
+
recovered = true;
|
|
201
|
+
let recovery = recoveries.get(key);
|
|
202
|
+
if (!recovery) {
|
|
203
|
+
const controller = new AbortController();
|
|
204
|
+
const budget = Math.ceil(remaining());
|
|
205
|
+
const timer = setTimeout(() => {
|
|
206
|
+
controller.abort(new Error("runtime-unavailable: reconnect deadline exceeded during recovery"));
|
|
207
|
+
}, budget);
|
|
208
|
+
const promise = waitForRecovery(Promise.resolve().then(() => options.recover({ timeoutMs: budget, signal: controller.signal })), controller.signal)
|
|
209
|
+
.finally(() => clearTimeout(timer));
|
|
210
|
+
recovery = { promise, controller, key };
|
|
211
|
+
recoveries.set(key, recovery);
|
|
212
|
+
void recovery.promise.finally(() => { if (recoveries.get(key) === recovery) recoveries.delete(key); }).catch(() => {});
|
|
213
|
+
}
|
|
214
|
+
// A caller can cancel its wait without cancelling another caller's recovery.
|
|
215
|
+
// Keep trying the transport while the owner-safe installer waits.
|
|
216
|
+
// A replacement can accept compatible clients before the pinned
|
|
217
|
+
// installer finishes; waiting for it would stall all subscribers.
|
|
218
|
+
ownedRecovery = recovery;
|
|
219
|
+
void recovery.promise.catch(error => { recoveryError = error; });
|
|
220
|
+
}
|
|
221
|
+
if (performance.now() >= deadline) break;
|
|
222
|
+
await delay(Math.min(backoff, remaining()), undefined, { signal: options.signal });
|
|
223
|
+
backoff = Math.min(1000, backoff * 2);
|
|
224
|
+
}
|
|
225
|
+
throw new Error("runtime-unavailable: reconnect deadline exceeded; task state is unknown, retry after recovery", { cause: lastError });
|
|
226
|
+
} finally {
|
|
227
|
+
const remainingDemand = connectionDemands.get(key) - 1;
|
|
228
|
+
if (remainingDemand) connectionDemands.set(key, remainingDemand);
|
|
229
|
+
else {
|
|
230
|
+
connectionDemands.delete(key);
|
|
231
|
+
const recovery = recoveries.get(key) ?? ownedRecovery;
|
|
232
|
+
if (recovery) { recoveries.delete(key); recovery.controller.abort(); }
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function waitForRecovery(recovery, signal) {
|
|
238
|
+
return new Promise((resolve, reject) => {
|
|
239
|
+
const finish = (callback, value) => { signal.removeEventListener("abort", abort); callback(value); };
|
|
240
|
+
const abort = () => finish(reject, signal.reason);
|
|
241
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
242
|
+
recovery.then(value => finish(resolve, value), error => finish(reject, error));
|
|
243
|
+
if (signal.aborted) abort();
|
|
244
|
+
});
|
|
245
|
+
}
|
package/src/server.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createBackgroundTools
|
|
1
|
+
import { createBackgroundTools } from "./runtime/background-tools.ts";
|
|
2
2
|
import { createLocalWorkClient } from "./runtime/local-client.ts";
|
|
3
3
|
import { chmodSync, existsSync, realpathSync, unlinkSync, writeFileSync, renameSync } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
@@ -20,12 +20,12 @@ import type { IdleSessionsLease, UpgradeRequest } from "./startup/managed-types.
|
|
|
20
20
|
import { HostedSession } from "./hosted-session.ts";
|
|
21
21
|
import { readLifecycleConfig, type LifecycleConfig } from "./lifecycle-config.ts";
|
|
22
22
|
import { runtimeRoot } from "./runtime/root.ts";
|
|
23
|
-
import { RuntimeCancellation
|
|
24
|
-
import { RuntimeResultSupervision
|
|
23
|
+
import { RuntimeCancellation } from "./runtime/cancellation.ts";
|
|
24
|
+
import { RuntimeResultSupervision } from "./runtime/result-supervision.ts";
|
|
25
25
|
import { SharedCatalog } from "./runtime/catalog.ts";
|
|
26
26
|
import { acquireMutationStore, mutationStoreMetrics } from "./runtime/mutation-store.ts";
|
|
27
27
|
import { WorkQueryExecutor } from "./runtime/query-executor.ts";
|
|
28
|
-
import { createSubagentLaunch
|
|
28
|
+
import { createSubagentLaunch } from "./runtime/subagent-launch.ts";
|
|
29
29
|
|
|
30
30
|
export interface DaemonOptions extends Partial<LifecycleConfig> {
|
|
31
31
|
/** Defaults to `~/.pi/agent/server` (or `$PI_SERVER_DIR`). */
|
|
@@ -44,6 +44,8 @@ export interface DaemonOptions extends Partial<LifecycleConfig> {
|
|
|
44
44
|
onDraining?: () => void;
|
|
45
45
|
/** Trusted fault-injection seam; never exposed through the socket protocol. */
|
|
46
46
|
cancellationFault?: (stage: import("./runtime/cancellation.ts").CancellationStage) => void;
|
|
47
|
+
/** Private fixture hook; no protocol command, parameters or authority are passed. */
|
|
48
|
+
rpcEvidence?: { bind(read: () => unknown): void; event(plane: string, slot: number, phase: string): void };
|
|
47
49
|
}
|
|
48
50
|
|
|
49
51
|
export interface Daemon {
|
|
@@ -97,16 +99,24 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
97
99
|
let launchInitialization: ReturnType<typeof createSubagentLaunch> | undefined;
|
|
98
100
|
let backgroundInitialization: ReturnType<typeof createBackgroundTools> | undefined;
|
|
99
101
|
let backgroundTools: Awaited<ReturnType<typeof createBackgroundTools>> | undefined;
|
|
100
|
-
const initializeBackground = () => backgroundInitialization ??=
|
|
102
|
+
const initializeBackground = () => backgroundInitialization ??= (() => {
|
|
103
|
+
options.rpcEvidence?.event('background', 0, 'init-pending');
|
|
104
|
+
return createBackgroundTools(realpathSync(getAgentDir()), instanceId!, () => Boolean(pendingUpgrade), scope => work().snapshot(scope), config.runtimeIdleMs,
|
|
105
|
+
options.rpcEvidence ? (slot, phase) => options.rpcEvidence!.event('adapter', slot, phase) : undefined)
|
|
106
|
+
.then(host => { options.rpcEvidence?.event('background', 0, 'init-returned'); return backgroundTools = host; })
|
|
107
|
+
.catch(error => { options.rpcEvidence?.event('background', 0, 'init-failed'); backgroundInitialization = undefined; throw error; });
|
|
108
|
+
})();
|
|
101
109
|
let cancellations: RuntimeCancellation | undefined;
|
|
110
|
+
const controlStore = acquireMutationStore(realpathSync(getAgentDir()));
|
|
102
111
|
let resultSupervision: RuntimeResultSupervision | undefined;
|
|
103
112
|
const resultPortKey = Symbol.for("pi-better-server:result-supervision-ports-v1");
|
|
104
113
|
const resultPorts: Map<string, any> = (globalThis as any)[resultPortKey] ??= new Map();
|
|
105
114
|
const resultRoot = realpathSync(getAgentDir());
|
|
106
115
|
const resultPort = { status() {
|
|
107
|
-
resultSupervision ??= new RuntimeResultSupervision(resultRoot, instanceId
|
|
116
|
+
resultSupervision ??= new RuntimeResultSupervision(resultRoot, instanceId!, config.runtimeIdleMs);
|
|
108
117
|
resultSupervision.reconcile();
|
|
109
|
-
return { hostId: resultSupervision.hostId, epoch: resultSupervision.epoch, reason: resultSupervision.reason
|
|
118
|
+
return { hostId: resultSupervision.hostId, epoch: resultSupervision.epoch, reason: resultSupervision.reason,
|
|
119
|
+
obligations: resultSupervision.livenessReasons(), metrics: resultSupervision.metrics };
|
|
110
120
|
} };
|
|
111
121
|
let workModel: WorkQueryExecutor | undefined;
|
|
112
122
|
let registry!: SessionRegistry;
|
|
@@ -116,6 +126,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
116
126
|
try { await cancellations?.close(); }
|
|
117
127
|
finally {
|
|
118
128
|
resultSupervision?.close();
|
|
129
|
+
controlStore.release();
|
|
119
130
|
if (resultPorts.get(resultRoot) === resultPort) resultPorts.delete(resultRoot);
|
|
120
131
|
try { await (await launchInitialization?.catch(() => undefined))?.close();
|
|
121
132
|
await (await backgroundInitialization?.catch(() => undefined))?.close(); }
|
|
@@ -123,13 +134,15 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
123
134
|
}
|
|
124
135
|
}
|
|
125
136
|
};
|
|
126
|
-
if (
|
|
137
|
+
if (controlStore.store.resultSupervisions(true).length || controlStore.store.listAssignmentCleanupOperations(1).length) {
|
|
138
|
+
resultSupervision = new RuntimeResultSupervision(resultRoot, instanceId!, config.runtimeIdleMs);
|
|
139
|
+
}
|
|
127
140
|
resultPorts.set(resultRoot, resultPort);
|
|
128
|
-
if (
|
|
141
|
+
if (controlStore.store.pendingTaskCancellations().length) cancellations = new RuntimeCancellation(realpathSync(getAgentDir()), instanceId!, options.cancellationFault);
|
|
129
142
|
const catalog = new SharedCatalog(realpathSync(getAgentDir()), instanceId!);
|
|
130
143
|
const initializeLaunch = () => {
|
|
131
144
|
if (!launchInitialization) {
|
|
132
|
-
const pending = createSubagentLaunch(realpathSync(getAgentDir()), instanceId!, catalog);
|
|
145
|
+
const pending = createSubagentLaunch(realpathSync(getAgentDir()), instanceId!, catalog, config.runtimeIdleMs);
|
|
133
146
|
launchInitialization = pending;
|
|
134
147
|
void pending.then(host => { launches = host; }, () => {
|
|
135
148
|
// The factory releases partial resources before rejection. A later
|
|
@@ -139,14 +152,16 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
139
152
|
}
|
|
140
153
|
return launchInitialization;
|
|
141
154
|
};
|
|
142
|
-
if (hasSubagentManagement(
|
|
155
|
+
if (controlStore.store.hasSubagentManagement()) {
|
|
143
156
|
void initializeLaunch().catch(error => log(`Subagent supervision unavailable: ${String(error)}`));
|
|
144
157
|
}
|
|
145
158
|
const work = () => {
|
|
146
159
|
if (!workModel) {
|
|
147
160
|
workModel = new WorkQueryExecutor(realpathSync(getAgentDir()), instanceId!, {
|
|
161
|
+
logWatchdog: log,
|
|
162
|
+
budgetBuffer: controlStore.budget.buffer,
|
|
148
163
|
onTerminalLogsChanged: async ids => {
|
|
149
|
-
if (!launchInitialization && !hasSubagentManagement(
|
|
164
|
+
if (!launchInitialization && !controlStore.store.hasSubagentManagement()) return;
|
|
150
165
|
const host = await initializeLaunch();
|
|
151
166
|
await host.foldTerminalFailures(ids);
|
|
152
167
|
},
|
|
@@ -160,13 +175,14 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
160
175
|
// Structural port permits independent integration with the shared maintenance owner.
|
|
161
176
|
const sessionMaintenance = (registry as SessionRegistry & { maintenance?: {
|
|
162
177
|
readonly busy: boolean;
|
|
178
|
+
lifecycleReasons(): unknown[];
|
|
163
179
|
enterSessionOperation(): () => void;
|
|
164
180
|
withIdleSessions<T>(purpose: "upgrade", run: (live: HostedSession[], lease: IdleSessionsLease) => Promise<T>): Promise<T>;
|
|
165
181
|
} }).maintenance;
|
|
166
182
|
const safeUpgrade = !!(build && instanceId && sessionMaintenance
|
|
167
183
|
&& typeof sessionMaintenance.withIdleSessions === "function" && "publishRuntimeEvent" in HostedSession.prototype);
|
|
168
184
|
let pendingUpgrade: UpgradeRequest | undefined;
|
|
169
|
-
if(
|
|
185
|
+
if(controlStore.store.backgroundRequests().hasPending()) void initializeBackground().catch(error => log(`Background request recovery unavailable: ${String(error)}`));
|
|
170
186
|
const reconnectControllers = new Map<ConnectionControl, boolean>();
|
|
171
187
|
const setUpgradeFence = (epoch: string | null) => {
|
|
172
188
|
const lease = acquireMutationStore(realpathSync(getAgentDir()));
|
|
@@ -189,8 +205,13 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
189
205
|
const sockets = new Set<Socket>();
|
|
190
206
|
const dispatches = new Set<Promise<void>>();
|
|
191
207
|
let inFlight = 0;
|
|
208
|
+
let requestCounter = 0, connectionCounter = 0;
|
|
209
|
+
const requests = new Map<number, { kind: string; id: number; connection: number; operation?: { kind: string; id: string }; lastProgressAt: number; nextDeadline: null; executionDeadline: null; recovery: string }>();
|
|
210
|
+
options.rpcEvidence?.bind(() => ({ lanes: controlStore.budget.metrics().lanes,
|
|
211
|
+
read: workModel?.metrics().executor, observation: workModel?.observation().status }));
|
|
192
212
|
let draining = false;
|
|
193
213
|
let idleStopping = false;
|
|
214
|
+
let idleEvidence: unknown;
|
|
194
215
|
const runtimeClients = new Map<Socket, string>();
|
|
195
216
|
let guardianBinding: { socket: Socket; identity: import("./daemon-owner.ts").DaemonOwnerIdentity } | undefined;
|
|
196
217
|
let observationUnavailable = false;
|
|
@@ -199,6 +220,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
199
220
|
let zeroSince: number | undefined = registry.activeCount === 0 ? now() : undefined;
|
|
200
221
|
let startupUntil = 0;
|
|
201
222
|
const server: Server = createServer((socket) => {
|
|
223
|
+
const connection = ++connectionCounter;
|
|
202
224
|
sockets.add(socket);
|
|
203
225
|
const send = (message: ServerMessage): void => {
|
|
204
226
|
if (!socket.destroyed) socket.write(encodeLine(message));
|
|
@@ -233,6 +255,19 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
233
255
|
return;
|
|
234
256
|
}
|
|
235
257
|
inFlight++;
|
|
258
|
+
const request = ++requestCounter;
|
|
259
|
+
const evidencePlane = type === 'runtime_background_tool' ? 'background'
|
|
260
|
+
: ['runtime_cancel_task', 'runtime_query_cancellation', 'runtime_cancellation_status'].includes(type) ? 'cancel'
|
|
261
|
+
: ['runtime_get_snapshot', 'runtime_subscribe', 'runtime_get_metrics'].includes(type) ? 'read' : undefined;
|
|
262
|
+
if (evidencePlane) options.rpcEvidence?.event(evidencePlane, request, 'request-pending');
|
|
263
|
+
requests.set(request, { kind: 'transport-request', id: request, connection, lastProgressAt: now(),
|
|
264
|
+
nextDeadline: null, executionDeadline: null,
|
|
265
|
+
recovery: 'dispatch-drains-to-settlement-read-waiters-use-existing-caller-cancellation-accepted-effects-use-durable-owner' });
|
|
266
|
+
const accepted = (kind: string) => (operationId: string) => {
|
|
267
|
+
const record = requests.get(request);
|
|
268
|
+
if (record) { record.operation = { kind, id: operationId }; record.lastProgressAt = now(); }
|
|
269
|
+
};
|
|
270
|
+
let evidenceFailed = false;
|
|
236
271
|
try {
|
|
237
272
|
if (!type) {
|
|
238
273
|
send(failure(id, "unknown", "Missing command type"));
|
|
@@ -258,12 +293,22 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
258
293
|
capabilities: ["runtime-status-v1"], hostedSessions: registry.activeCount, lifecycle: config,
|
|
259
294
|
subagentManagement: launches?.status() ?? null,
|
|
260
295
|
backgroundManagement: backgroundTools?.metrics() ?? null,
|
|
296
|
+
resultSupervision: resultSupervision ? { reason: resultSupervision.reason, metrics: resultSupervision.metrics } : null,
|
|
297
|
+
workBudget: controlStore.budget.metrics(),
|
|
261
298
|
guardianBinding: guardianBinding?.identity ?? null,
|
|
262
299
|
workObservation: observation ? { status: observation.status, reason: observation.reason, observedAt: observation.observedAt } : null,
|
|
263
300
|
livenessReasons: [...[...runtimeClients.values()].map(id => ({ kind: "connection", id })),
|
|
264
|
-
...
|
|
265
|
-
...(
|
|
301
|
+
...requests.values(),
|
|
302
|
+
...registry.lifecycleReasons(),
|
|
303
|
+
...(resultSupervision?.livenessReasons() ?? []),
|
|
304
|
+
...(launches?.lifecycleReasons() ?? []),
|
|
305
|
+
...(backgroundTools?.lifecycleReasons() ?? []),
|
|
306
|
+
...(cancellations?.lifecycleReasons() ?? []),
|
|
307
|
+
...(sessionMaintenance?.lifecycleReasons() ?? []),
|
|
308
|
+
...(observation?.reasons ?? []).filter((reason: any) => !resultSupervision?.manages(reason.operationId))],
|
|
266
309
|
livenessObservation: observation ?? { status: "unobserved", reasons: [], observedAt: null },
|
|
310
|
+
readRequests: workModel?.requestReasons() ?? [],
|
|
311
|
+
transportRequests: [...requests.values()].map(reason => ({ ...reason })),
|
|
267
312
|
nextIdleDeadline: runtimeClients.size > 0 || registry.activeCount > 0 ? null
|
|
268
313
|
: hostedUsed ? config.daemonIdleMs === 0 || zeroSince === undefined ? null : zeroSince + config.daemonIdleMs
|
|
269
314
|
: runtimeZeroSince === undefined ? null : runtimeZeroSince + config.runtimeIdleMs } });
|
|
@@ -278,10 +323,12 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
278
323
|
if (runtimeInFlight >= 32) throw new Error("not_accepted: too many in-flight runtime requests");
|
|
279
324
|
if (socket.writableLength > 4 * 1024 * 1024) { socket.destroy(); return; }
|
|
280
325
|
runtimeInFlight++;
|
|
326
|
+
const releaseControl = controlStore.budget.enter("control");
|
|
281
327
|
try {
|
|
328
|
+
if (!releaseControl) throw new Error("runtime-overloaded: control source capacity");
|
|
282
329
|
cancellations ??= new RuntimeCancellation(realpathSync(getAgentDir()), instanceId!, options.cancellationFault);
|
|
283
|
-
return reply({ data: await cancellations.handle(command) });
|
|
284
|
-
} finally { runtimeInFlight--; }
|
|
330
|
+
return reply({ data: await cancellations.handle(command, accepted('cancellation'), releaseControl) });
|
|
331
|
+
} finally { releaseControl?.(); runtimeInFlight--; }
|
|
285
332
|
}
|
|
286
333
|
if (type === "runtime_bind_catalog_host") {
|
|
287
334
|
if (!greeted) throw new Error(`${type} requires hello`);
|
|
@@ -293,7 +340,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
293
340
|
if (socket.writableLength > 4 * 1024 * 1024) { socket.destroy(); return; }
|
|
294
341
|
if (runtimeInFlight >= 32) throw new Error("runtime-overloaded");
|
|
295
342
|
runtimeInFlight++;
|
|
296
|
-
try { return reply({data: await (await initializeBackground()).handle(command)}); } finally { runtimeInFlight--; }
|
|
343
|
+
try { return reply({data: await (await initializeBackground()).handle(command, accepted('background-request'))}); } finally { runtimeInFlight--; }
|
|
297
344
|
}
|
|
298
345
|
if (type === "runtime_launch_subagent") {
|
|
299
346
|
if (!greeted) throw new Error("not_accepted: launch requires hello");
|
|
@@ -302,7 +349,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
302
349
|
runtimeInFlight++;
|
|
303
350
|
try {
|
|
304
351
|
launches = await initializeLaunch();
|
|
305
|
-
const data = await launches.handle(command);
|
|
352
|
+
const data = await launches.handle(command, accepted('managed-launch'));
|
|
306
353
|
// The durable launch receipt must not fail because derived reads
|
|
307
354
|
// are rebuilding or overloaded. Refresh independently.
|
|
308
355
|
void work().livenessReasons().catch(error => log(`Launch snapshot refresh unavailable: ${String(error)}`));
|
|
@@ -357,7 +404,9 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
357
404
|
workQueries ??= work().connect(socket);
|
|
358
405
|
const data = await workQueries.handle(command);
|
|
359
406
|
if (type === "runtime_get_metrics") {
|
|
360
|
-
return reply({ data: { ...JSON.parse(data.json), mutationSqlite: mutationStoreMetrics(getAgentDir())
|
|
407
|
+
return reply({ data: { ...JSON.parse(data.json), mutationSqlite: mutationStoreMetrics(getAgentDir()),
|
|
408
|
+
workBudget: controlStore.budget.metrics(), resultSupervision: resultSupervision?.metrics,
|
|
409
|
+
subagentLifecycle: launches?.status().lifecycle } });
|
|
361
410
|
}
|
|
362
411
|
if (socket.writableLength > 4 * 1024 * 1024) { socket.destroy(); return; }
|
|
363
412
|
// Snapshot JSON is encoded in the worker; only the small envelope runs here.
|
|
@@ -454,7 +503,15 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
454
503
|
await nativeHost.reload(sessionId);
|
|
455
504
|
return reply({ sessionId });
|
|
456
505
|
}
|
|
457
|
-
if (type === "client_snapshot")
|
|
506
|
+
if (type === "client_snapshot") {
|
|
507
|
+
if (socket.destroyed) return;
|
|
508
|
+
const data = await new Promise<unknown>((resolve, reject) => {
|
|
509
|
+
const closed = () => reject(new Error('Read caller disconnected'));
|
|
510
|
+
socket.once('close', closed);
|
|
511
|
+
void hosted.clientSnapshot().then(resolve, reject).finally(() => socket.off('close', closed));
|
|
512
|
+
});
|
|
513
|
+
return reply({ sessionId, data });
|
|
514
|
+
}
|
|
458
515
|
if (type === "clear_queue") return reply({ sessionId, data: hosted.session.clearQueue() });
|
|
459
516
|
if (type === "abort_compaction") {
|
|
460
517
|
hosted.session.abortCompaction();
|
|
@@ -464,10 +521,16 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
464
521
|
const response = await hosted.handle(rpc as RpcCommand);
|
|
465
522
|
send({ ...response, sessionId } as ServerMessage);
|
|
466
523
|
} catch (error) {
|
|
524
|
+
evidenceFailed = true;
|
|
467
525
|
send(failure(id, type || "unknown", error instanceof Error ? error.message : String(error)));
|
|
468
526
|
} finally {
|
|
527
|
+
if (evidencePlane) {
|
|
528
|
+
options.rpcEvidence?.event(evidencePlane, request, evidenceFailed ? 'request-failed' : 'request-returned');
|
|
529
|
+
options.rpcEvidence?.event(evidencePlane, request, 'settled');
|
|
530
|
+
}
|
|
469
531
|
releaseSessionOperation?.();
|
|
470
532
|
inFlight--;
|
|
533
|
+
requests.delete(request);
|
|
471
534
|
if (registry.activeCount > 0) { zeroSince = undefined; hostedUsed = true; }
|
|
472
535
|
else zeroSince ??= now();
|
|
473
536
|
}
|
|
@@ -508,6 +571,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
508
571
|
await (await launchInitialization?.catch(() => undefined))?.close();
|
|
509
572
|
await (await backgroundInitialization?.catch(() => undefined))?.close();
|
|
510
573
|
resultSupervision?.close();
|
|
574
|
+
controlStore.release();
|
|
511
575
|
if (resultPorts.get(resultRoot) === resultPort) resultPorts.delete(resultRoot);
|
|
512
576
|
await workModel?.close();
|
|
513
577
|
for (const socket of sockets) socket.destroy();
|
|
@@ -591,11 +655,25 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
591
655
|
: (now() - runtimeZeroSince < config.runtimeIdleMs || now() < startupUntil)) return;
|
|
592
656
|
// Recheck durable activity before fencing admission; observation never adopts a writer.
|
|
593
657
|
if (draining) return;
|
|
658
|
+
resultSupervision?.reconcile();
|
|
659
|
+
if (resultSupervision?.livenessReasons().length) {
|
|
660
|
+
runtimeZeroSince = undefined;
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
if (launches?.lifecycleReasons().length) { runtimeZeroSince = undefined; return; }
|
|
664
|
+
if (backgroundTools?.lifecycleReasons().length) { runtimeZeroSince = undefined; return; }
|
|
594
665
|
try {
|
|
595
|
-
|
|
666
|
+
// Control never waits for a queued/rebuilding/wedged read worker.
|
|
667
|
+
// Legacy passive evidence is usable only within its existing idle
|
|
668
|
+
// verification window; it cannot renew itself through a probe RPC.
|
|
669
|
+
const observation = workModel?.observation();
|
|
670
|
+
const fresh = observation?.observedAt !== null && observation?.observedAt !== undefined
|
|
671
|
+
&& now() < observation.observedAt + config.runtimeIdleMs;
|
|
672
|
+
if (fresh && observation.reasons.some((reason: any) => !resultSupervision?.manages(reason.operationId))) {
|
|
596
673
|
runtimeZeroSince = undefined;
|
|
597
674
|
return;
|
|
598
675
|
}
|
|
676
|
+
if (observation && (!fresh || observation.status !== "ready")) observationUnavailable = true;
|
|
599
677
|
} catch (error) {
|
|
600
678
|
// The executor already bounds query deadlines and terminates failed workers.
|
|
601
679
|
// Unknown obligations cannot keep an otherwise detached runtime alive forever.
|
|
@@ -607,6 +685,8 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
607
685
|
if (runtimeClients.size > 0 || registry.activeCount > 0 || inFlight > 0 || launches?.busy || backgroundTools?.busy || cancellations?.busy || sessionMaintenance?.busy || nativeHost.busy || registry.hasPendingOperations) return;
|
|
608
686
|
draining = true;
|
|
609
687
|
idleStopping = true;
|
|
688
|
+
idleEvidence = { at: now(), deadline: hostedUsed ? zeroSince! + config.daemonIdleMs : runtimeZeroSince! + config.runtimeIdleMs,
|
|
689
|
+
lifecycle: config, obligations: [], budget: controlStore.budget.metrics() };
|
|
610
690
|
log("idle timeout with no active sessions; shutting down");
|
|
611
691
|
})().finally(() => { maintenance = undefined; });
|
|
612
692
|
return maintenance.then(() => draining ? daemon.stop() : undefined);
|
|
@@ -637,13 +717,14 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
637
717
|
await (await launchInitialization?.catch(() => undefined))?.close();
|
|
638
718
|
await (await backgroundInitialization?.catch(() => undefined))?.close();
|
|
639
719
|
resultSupervision?.close();
|
|
720
|
+
controlStore.release();
|
|
640
721
|
if (resultPorts.get(resultRoot) === resultPort) resultPorts.delete(resultRoot);
|
|
641
722
|
await workModel?.close();
|
|
642
723
|
await registry.shutdown();
|
|
643
724
|
await Promise.allSettled([...dispatches]);
|
|
644
725
|
if (existsSync(socketPath)) unlinkSync(socketPath);
|
|
645
726
|
const checkpoint = join(serverDir, `clean-stop-${instanceId}.tmp`);
|
|
646
|
-
writeFileSync(checkpoint, JSON.stringify({ pid: process.pid, token: instanceId, reason: "clean-stop", observation: observationUnavailable ? "unavailable" : "verified" }), { mode: 0o600 });
|
|
727
|
+
writeFileSync(checkpoint, JSON.stringify({ pid: process.pid, token: instanceId, reason: "clean-stop", observation: observationUnavailable ? "unavailable" : "verified", idleEvidence }), { mode: 0o600 });
|
|
647
728
|
renameSync(checkpoint, join(serverDir, "clean-stop.json"));
|
|
648
729
|
releaseOwner();
|
|
649
730
|
finishClosed();
|
package/src/session-activity.ts
CHANGED
|
@@ -10,6 +10,18 @@ interface ActivityProvider {
|
|
|
10
10
|
|
|
11
11
|
/** One bus per hosted session; legacy providers may conservatively report process-wide work. */
|
|
12
12
|
export class SessionActivity {
|
|
13
|
+
private recordCounter = 0;
|
|
14
|
+
private handlerRecords = new Map<number, number>();
|
|
15
|
+
private providerRecords = new Map<string, { lastProgressAt: number; state: string }>();
|
|
16
|
+
private refreshStartedAt: number | undefined;
|
|
17
|
+
lifecycleReasons() {
|
|
18
|
+
return [
|
|
19
|
+
...[...this.handlerRecords].map(([id, lastProgressAt]) => ({ kind: 'hosted-handler', id, lastProgressAt })),
|
|
20
|
+
...[...this.providerRecords].map(([id, record]) => ({ kind: 'hosted-provider', id, ...record })),
|
|
21
|
+
...(this.refreshStartedAt === undefined ? [] : [{ kind: 'hosted-observation', id: 'provider-refresh', lastProgressAt: this.refreshStartedAt }]),
|
|
22
|
+
...(this.unobservable ? [{ kind: 'hosted-retention', id: 'caller-owned-loader', lastProgressAt: null, recovery: 'caller-owned-loader-cannot-prove-background-idleness' }] : []),
|
|
23
|
+
].map(record => ({ executionDeadline: null, nextDeadline: null, recovery: 'existing-hosted-session-idle-and-admission-policy', ...record }));
|
|
24
|
+
}
|
|
13
25
|
readonly events = createEventBus();
|
|
14
26
|
private readonly runtimeUnsubscribers = new Set<() => void>();
|
|
15
27
|
/** Extensions share the host bus, but their subscriptions end at each loader reload. */
|
|
@@ -27,16 +39,18 @@ export class SessionActivity {
|
|
|
27
39
|
// An emit already in progress can still hold a removed listener.
|
|
28
40
|
if (!this.runtimeUnsubscribers.has(release) || this.runtimeRevoked) return;
|
|
29
41
|
this.pendingHandlers++;
|
|
42
|
+
const record = ++this.recordCounter;
|
|
43
|
+
this.handlerRecords.set(record, Date.now());
|
|
30
44
|
let asynchronous = false;
|
|
31
45
|
try {
|
|
32
46
|
const result = handler(data) as unknown as void | Promise<void>;
|
|
33
47
|
if (result && typeof result.then === "function") {
|
|
34
48
|
asynchronous = true;
|
|
35
49
|
this.changed();
|
|
36
|
-
return Promise.resolve(result).finally(() => { this.pendingHandlers--; this.changed(); });
|
|
50
|
+
return Promise.resolve(result).finally(() => { this.pendingHandlers--; this.handlerRecords.delete(record); this.changed(); });
|
|
37
51
|
}
|
|
38
52
|
return result;
|
|
39
|
-
} finally { if (!asynchronous) this.pendingHandlers--; }
|
|
53
|
+
} finally { if (!asynchronous) { this.pendingHandlers--; this.handlerRecords.delete(record); } }
|
|
40
54
|
});
|
|
41
55
|
const release = () => {
|
|
42
56
|
this.runtimeUnsubscribers.delete(release);
|
|
@@ -124,6 +138,7 @@ export class SessionActivity {
|
|
|
124
138
|
this.unsubscribers.clear();
|
|
125
139
|
for (const unsubscribe of this.runtimeUnsubscribers) unsubscribe();
|
|
126
140
|
this.providers.clear();
|
|
141
|
+
this.providerRecords.clear();
|
|
127
142
|
this.active = false;
|
|
128
143
|
this.revision++;
|
|
129
144
|
}
|
|
@@ -153,6 +168,7 @@ export class SessionActivity {
|
|
|
153
168
|
refresh(): Promise<void> {
|
|
154
169
|
if (this.disposed || !this.session) return Promise.resolve();
|
|
155
170
|
if (this.refreshing) return this.refreshing;
|
|
171
|
+
this.refreshStartedAt = Date.now();
|
|
156
172
|
// Defer collection so the guard is installed before invoking arbitrary provider code.
|
|
157
173
|
const run = Promise.resolve().then(async () => {
|
|
158
174
|
let observed: number;
|
|
@@ -161,18 +177,24 @@ export class SessionActivity {
|
|
|
161
177
|
let active = false;
|
|
162
178
|
try {
|
|
163
179
|
const ctx = this.session!.extensionRunner.createContext();
|
|
180
|
+
this.providerRecords.delete('@context');
|
|
164
181
|
for (const provider of this.providers.values()) {
|
|
165
182
|
try {
|
|
166
183
|
const snapshot = await provider.getActivity(ctx);
|
|
167
|
-
|
|
184
|
+
const busy = snapshot.items.some((item) => item.active);
|
|
185
|
+
if (busy && !this.providerRecords.has(provider.id)) this.providerRecords.set(provider.id, { lastProgressAt: Date.now(), state: 'active' });
|
|
186
|
+
if (!busy) this.providerRecords.delete(provider.id);
|
|
187
|
+
active ||= busy;
|
|
168
188
|
} catch (error) {
|
|
169
189
|
// An unavailable owned-work observation cannot establish that work finished.
|
|
170
190
|
active = true;
|
|
191
|
+
if (!this.providerRecords.has(provider.id)) this.providerRecords.set(provider.id, { lastProgressAt: Date.now(), state: 'observation-unavailable' });
|
|
171
192
|
this.log(`session activity provider ${provider.id} failed: ${String(error)}`);
|
|
172
193
|
}
|
|
173
194
|
}
|
|
174
195
|
} catch (error) {
|
|
175
196
|
active = true;
|
|
197
|
+
if (!this.providerRecords.has('@context')) this.providerRecords.set('@context', { lastProgressAt: Date.now(), state: 'context-observation-unavailable' });
|
|
176
198
|
this.log(`session activity observation failed: ${String(error)}`);
|
|
177
199
|
}
|
|
178
200
|
if (this.disposed) return;
|
|
@@ -181,7 +203,7 @@ export class SessionActivity {
|
|
|
181
203
|
if (this.busy !== wasBusy) this.changed();
|
|
182
204
|
} while (observed !== this.revision);
|
|
183
205
|
});
|
|
184
|
-
this.refreshing = run.finally(() => { this.refreshing = undefined; });
|
|
206
|
+
this.refreshing = run.finally(() => { this.refreshing = undefined; this.refreshStartedAt = undefined; });
|
|
185
207
|
return this.refreshing;
|
|
186
208
|
}
|
|
187
209
|
|
package/src/version.ts
CHANGED