pi-better-server 0.5.0 → 0.7.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 +7 -3
- 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/frontend.ts +10 -2
- 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-full-runtime.mjs +2 -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 +181 -27
- package/src/runtime/background.ts +365 -70
- 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 +52 -14
- package/src/runtime/domain/background/registry.mjs +61 -3
- package/src/runtime/domain/background/supervisor/store.mjs +3 -3
- package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -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 +25 -9
- package/src/runtime/domain/background-service/index.ts +25 -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 +159 -19
- package/src/runtime/domain/background-service/managed-frontend.ts +135 -19
- package/src/runtime/domain/background-service/navigator-provider.domain.mjs +21 -5
- package/src/runtime/domain/background-service/navigator-provider.ts +19 -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 +372 -57
- package/src/runtime/domain/background-service/observed-waits.ts +321 -53
- 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 +52 -14
- package/src/runtime/domain/background-service/process.ts +48 -14
- 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/review-settings.domain.mjs +16 -0
- package/src/runtime/domain/background-service/review-settings.ts +18 -0
- package/src/runtime/domain/background-service/runtime.domain.mjs +40 -86
- package/src/runtime/domain/background-service/runtime.ts +27 -82
- 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 +273 -41
- package/src/runtime/domain/background-service/shared-navigator.ts +244 -40
- 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/outbox.domain.mjs +7 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
- 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 +26 -4
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +40 -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/stall.domain.mjs +5 -3
- package/src/runtime/domain/background-service/stall.ts +7 -4
- package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
- package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
- package/src/runtime/domain/background-service/supervisor/README.md +1 -4
- package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
- package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
- package/src/runtime/domain/background-service/supervisor/generated/process.mjs +52 -14
- package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
- package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
- package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
- package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
- package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
- package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
- package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
- package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
- package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -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 +53 -40
- package/src/runtime/domain/background-service/tools.ts +67 -54
- package/src/runtime/domain/background-service/types.domain.mjs +1 -0
- package/src/runtime/domain/background-service/types.ts +7 -3
- package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
- package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
- 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/outbox.mjs +7 -0
- 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 +26 -4
- 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/log-paths.mjs +8 -1
- package/src/runtime/domain/parse.d.mts +4 -1
- package/src/runtime/domain/parse.mjs +58 -9
- package/src/runtime/domain/sandbox-policy/README.md +63 -65
- 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/session-store.mjs +7 -0
- package/src/runtime/domain/subagents/README.md +13 -11
- package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +10 -7
- package/src/runtime/domain/subagents/assignment-outcomes.ts +9 -6
- package/src/runtime/domain/subagents/assignment-report.domain.mjs +109 -24
- package/src/runtime/domain/subagents/assignment-report.ts +103 -19
- package/src/runtime/domain/subagents/batch.mjs +13 -5
- 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/cleanup.domain.mjs +11 -2
- package/src/runtime/domain/subagents/cleanup.ts +10 -2
- package/src/runtime/domain/subagents/config.domain.mjs +54 -2
- package/src/runtime/domain/subagents/config.ts +53 -3
- 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/continuation.domain.mjs +4 -2
- package/src/runtime/domain/subagents/continuation.ts +4 -2
- package/src/runtime/domain/subagents/extensions.mjs +11 -13
- package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
- package/src/runtime/domain/subagents/failures.ts +10 -2
- package/src/runtime/domain/subagents/finalization.domain.mjs +16 -1
- package/src/runtime/domain/subagents/finalization.ts +21 -1
- 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 +457 -182
- package/src/runtime/domain/subagents/index.ts +417 -155
- package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +515 -0
- package/src/runtime/domain/subagents/isolated-workspace.ts +557 -0
- 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/list.mjs +2 -2
- 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 +27 -7
- package/src/runtime/domain/subagents/managed-launch-client.ts +28 -8
- 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/output-payload.domain.mjs +24 -9
- package/src/runtime/domain/subagents/output-payload.ts +26 -12
- 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 +4 -2
- package/src/runtime/domain/subagents/parse.domain.mjs +58 -9
- package/src/runtime/domain/subagents/parse.ts +57 -10
- 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 +71 -51
- package/src/runtime/domain/subagents/registry.ts +77 -38
- package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
- package/src/runtime/domain/subagents/retained-result.ts +65 -0
- package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
- package/src/runtime/domain/subagents/session-selection.ts +2 -1
- package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
- package/src/runtime/domain/subagents/session-store.ts +9 -0
- package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
- package/src/runtime/domain/subagents/settings-page.ts +147 -108
- 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 +28 -29
- package/src/runtime/domain/subagents/shared-catalog.ts +29 -21
- 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 +273 -41
- package/src/runtime/domain/subagents/shared-navigator.ts +244 -40
- 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/outbox.domain.mjs +7 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
- 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 +26 -4
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +40 -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-guard.domain.mjs +14 -1
- package/src/runtime/domain/subagents/task-guard.ts +13 -1
- package/src/runtime/domain/subagents/task-policy.domain.mjs +3 -2
- package/src/runtime/domain/subagents/task-policy.ts +8 -2
- package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
- package/src/runtime/domain/subagents/timing.ts +10 -1
- package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
- package/src/runtime/domain/subagents/tools.ts +4 -7
- package/src/runtime/domain/subagents/work-observation.domain.mjs +102 -17
- package/src/runtime/domain/subagents/work-observation.ts +91 -17
- 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/domain/subagents/workspace-files.domain.mjs +103 -0
- package/src/runtime/domain/subagents/workspace-files.ts +114 -0
- package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
- package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
- package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
- package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
- package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
- 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 +849 -121
- package/src/runtime/read-watchdog-probe.ts +4 -0
- package/src/runtime/result-supervision.ts +188 -16
- package/src/runtime/root.ts +5 -2
- 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
|
@@ -3,24 +3,49 @@ import { Check } from 'typebox/value';
|
|
|
3
3
|
import { setImmediate as yieldTurn } from 'node:timers/promises';
|
|
4
4
|
import { randomUUID } from 'node:crypto';
|
|
5
5
|
import { join } from 'node:path';
|
|
6
|
-
import { existsSync } from 'node:fs';
|
|
6
|
+
import { existsSync, openSync, closeSync, readSync, fstatSync } from 'node:fs';
|
|
7
7
|
import { createAgentSession, DefaultResourceLoader, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
|
|
8
8
|
import { acquireMutationStore } from './mutation-store.ts';
|
|
9
9
|
/** Fixed canonical adapter. It never owns a native parent transcript. */
|
|
10
|
-
export async function createBackgroundTools(root: string, instance: string, draining: () => boolean = () => false, observe?: (scope: Record<string, unknown>) => Promise<any
|
|
10
|
+
export async function createBackgroundTools(root: string, instance: string, draining: () => boolean = () => false, observe?: (scope: Record<string, unknown>) => Promise<any>, verificationMs = 30000,
|
|
11
|
+
trace?: (slot: number, phase: 'queued' | 'executing' | 'recovery' | 'read-pending' | 'read-returned' | 'tool-pending' | 'tool-returned' | 'settled') => void) {
|
|
11
12
|
const load = (file: string) => import(`./domain/background-service/${file}.domain.mjs`);
|
|
12
|
-
const [{ createObservedWaitHost }, { registerTools }, { createBackgroundTaskRuntime }, sandbox, authority, permissions, registry, navigator, failures] = await Promise.all([
|
|
13
|
+
const [{ createObservedWaitHost }, { registerTools }, { createBackgroundTaskRuntime }, sandbox, authority, permissions, registry, navigator, failures, reviewSettings] = await Promise.all([
|
|
13
14
|
load('observed-waits'), load('tools'), load('runtime'), load('sandbox'), load('managed-authority'),
|
|
14
|
-
import(String('./domain/sandbox-policy/permission-settings.domain.mjs')), load('registry'), load('navigator-provider'), load('failures'),
|
|
15
|
+
import(String('./domain/sandbox-policy/permission-settings.domain.mjs')), load('registry'), load('navigator-provider'), load('failures'), load('review-settings'),
|
|
15
16
|
]);
|
|
17
|
+
const identity = await load('process-identity');
|
|
16
18
|
const lease = acquireMutationStore(root);
|
|
19
|
+
const unknownWriters = new Map<string, number>();
|
|
17
20
|
let journal: ReturnType<typeof lease.store.backgroundRequests>;
|
|
18
21
|
let pi: any, service: any, session: any, runtime: any, current: any;
|
|
19
22
|
let tail: Promise<unknown> = Promise.resolve(), pending = 0;
|
|
23
|
+
let traceSlot = 0;
|
|
20
24
|
const projections = new Map<string, any>(), metrics = { scopeRefreshes: 0, exactDetailReads: 0, reconciles: 0 };
|
|
21
25
|
const recoveryVersions = new Map<string, string>();
|
|
22
26
|
const scopes = new Map<string, any>(), deliveries = new Map<string, any>();
|
|
27
|
+
const traceSeen = new Set<string>();
|
|
28
|
+
const traceHandoff = (stage: string, facts: Record<string, unknown>) => {
|
|
29
|
+
if (process.env.PI_BG_OBSERVED_WAITS_DEBUG !== '1') return;
|
|
30
|
+
const full = JSON.stringify({ stage, ...facts });
|
|
31
|
+
const line = full.length <= 4096 ? full : JSON.stringify({ stage, truncated: true });
|
|
32
|
+
if (traceSeen.has(line) || traceSeen.size >= 128) return;
|
|
33
|
+
const output = traceSeen.size === 127 ? JSON.stringify({ stage: 'capture-limit', limit: 128 }) : line;
|
|
34
|
+
traceSeen.add(line);
|
|
35
|
+
try { console.error('[background-handoff-server]', output); } catch { /* diagnostics never own delivery */ }
|
|
36
|
+
};
|
|
37
|
+
const isAttentionDelivery = (item: any) => {
|
|
38
|
+
const type = item.notification.event?.customType;
|
|
39
|
+
return type === 'background-task-stall' || type === 'background-wait-review';
|
|
40
|
+
};
|
|
41
|
+
const sameNativeHost = (item: any, record: any) => item.scope.pid === record.pid && item.scope.start === record.start;
|
|
42
|
+
const deliveryLeaseMs = 30000;
|
|
23
43
|
const ownerKey = (owner: any) => JSON.stringify([owner.workspace, owner.sessionId]);
|
|
44
|
+
const forgetView = (view: string) => { projections.delete(view); recoveryVersions.delete(view); };
|
|
45
|
+
const forgetOwner = (key: string) => {
|
|
46
|
+
for (const view of new Set([...projections.keys(), ...recoveryVersions.keys()]))
|
|
47
|
+
if (JSON.parse(view)[0] === key) forgetView(view);
|
|
48
|
+
};
|
|
24
49
|
const effectivePolicy = (record: any) => effectiveBackgroundPolicy(record.policy, permissions.readPermissionSettings({ agentDir: () => root }).background, record.owner.workspace);
|
|
25
50
|
const assertAdmission = () => {
|
|
26
51
|
if (!current)
|
|
@@ -31,16 +56,21 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
31
56
|
};
|
|
32
57
|
const notifyParent = (notification: any, delivery: any) => {
|
|
33
58
|
const owner = { workspace: notification.origin?.cwd, sessionId: notification.origin?.sessionId }, scope = scopes.get(ownerKey(owner));
|
|
59
|
+
const facts = { taskId: notification.taskId, receiptId: delivery.receiptId, sessionId: owner.sessionId, urgent: notification.urgent === true };
|
|
60
|
+
traceHandoff('notify', facts);
|
|
34
61
|
if (!scope || deliveries.size >= 256) {
|
|
62
|
+
traceHandoff('defer', { ...facts, scopeKnown: Boolean(scope), backlog: deliveries.size });
|
|
35
63
|
delivery.defer('Native recipient unavailable or delivery backlog full');
|
|
36
64
|
return;
|
|
37
65
|
}
|
|
38
66
|
if ([...deliveries.values()].some(item => item.receiptId === delivery.receiptId && ownerKey(item.scope.owner) === ownerKey(owner))) {
|
|
67
|
+
traceHandoff('duplicate', facts);
|
|
39
68
|
delivery.defer('Delivery already pending');
|
|
40
69
|
return;
|
|
41
70
|
}
|
|
42
71
|
const token = randomUUID();
|
|
43
72
|
deliveries.set(token, { token, notification, receiptId: delivery.receiptId ?? `background-terminal:${notification.operationId}`, delivery, scope, createdAt: Date.now() });
|
|
73
|
+
traceHandoff('enqueued', facts);
|
|
44
74
|
};
|
|
45
75
|
try {
|
|
46
76
|
journal = lease.store.backgroundRequests();
|
|
@@ -64,8 +94,14 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
64
94
|
pi = new Proxy(api, { get(target, key) { if (key === 'sendMessage')
|
|
65
95
|
return () => { throw new Error('Native parent transcript delivery requires authenticated frontend'); }; const value = Reflect.get(target, key); return typeof value === 'function' ? value.bind(target) : value; } });
|
|
66
96
|
runtime = createBackgroundTaskRuntime(failures.createFailureAttention((origin:any,event:any)=>new Promise<boolean>(resolve=>notifyParent({origin,taskId:event.inspectId??event.id,status:event.status,urgent:true,event:{...event,isDelivered:undefined,getSuppressionReason:undefined,onDelivered:undefined}},
|
|
67
|
-
{receiptId:event.receiptId,delivered:()=>{event.onDelivered?.(Date.now());resolve(true);},defer:()=>resolve(false)}))), (origin: any, event: any) => notifyParent({ origin, taskId: event.id, status: event.status, outcome: event.outcome, event: { ...event, isDelivered: undefined, getSuppressionReason: undefined, onDelivered: undefined, onSuppressed: undefined } }, { receiptId: event.receiptId, delivered: () => event.onDelivered?.(Date.now()), defer: () => undefined }), { assert: assertAdmission,
|
|
97
|
+
{receiptId:event.receiptId,delivered:()=>{event.onDelivered?.(Date.now());resolve(true);},defer:()=>resolve(false)}))), (origin: any, event: any) => notifyParent({ origin, taskId: event.id, status: event.status, outcome: event.outcome, event: { ...event, isDelivered: undefined, getSuppressionReason: undefined, onDelivered: undefined, onSuppressed: undefined } }, { receiptId: event.receiptId, delivered: () => event.onDelivered?.(Date.now()), defer: () => undefined }), { assert: assertAdmission,
|
|
98
|
+
prepared: (id: string) => journal.operation(current.ownerKey, current.record.key, { operationId: `legacy:${id}`, taskId: id, token: current.record.key }) },
|
|
99
|
+
(kind: string, id: string, work: () => unknown, dueAt?: number) => {
|
|
100
|
+
const origin = registry.readMeta(id)?.callbackOrigin;
|
|
101
|
+
return lease.budget.scheduleSource(`legacy-${kind}`, id, work, JSON.stringify([origin?.cwd ?? root, origin?.sessionId ?? null]), dueAt);
|
|
102
|
+
});
|
|
68
103
|
service = createObservedWaitHost(pi, { sharedStore: lease.store, storePath: join(root, 'operation-coordinator.sqlite'), serverOwnedResults: true, pollMs: 0,
|
|
104
|
+
enterControl: () => lease.budget.enter('control'),
|
|
69
105
|
notifyParent, assertAdmission,
|
|
70
106
|
authorizeParentCancellation: ({requester, operation, requestId}: any) => {
|
|
71
107
|
assertAdmission();
|
|
@@ -107,21 +143,49 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
107
143
|
}
|
|
108
144
|
return {
|
|
109
145
|
get busy() { return pending > 0; },
|
|
146
|
+
lifecycleReasons() {
|
|
147
|
+
const now = Date.now(), reasons: any[] = journal.lifecycleReasons().map((reason: any) => ({ ...reason,
|
|
148
|
+
management: { instance } }));
|
|
149
|
+
for (const scope of scopes.values()) for (const meta of registry.listActiveMetasForOrigin({ cwd: scope.owner.workspace, sessionId: scope.owner.sessionId })) {
|
|
150
|
+
if (meta.status !== 'running') continue;
|
|
151
|
+
const watch = meta.kind === 'command_watch' || Boolean(meta.remote);
|
|
152
|
+
const verified = meta.pid && meta.pidStartTime && identity.readProcessStartToken(meta.pid) === meta.pidStartTime;
|
|
153
|
+
if (!watch && !verified) {
|
|
154
|
+
if (!unknownWriters.has(meta.id)) unknownWriters.set(meta.id, now);
|
|
155
|
+
const since = unknownWriters.get(meta.id)!;
|
|
156
|
+
if (now >= since + verificationMs) continue;
|
|
157
|
+
reasons.push({ kind: 'verification', id: meta.id, owner: scope.owner, lastProgressAt: since,
|
|
158
|
+
nextDeadline: since + verificationMs, recovery: 'legacy-writer-unverified-no-takeover' });
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
unknownWriters.delete(meta.id);
|
|
162
|
+
reasons.push({ kind: watch ? 'task' : 'runner', id: meta.id, owner: scope.owner,
|
|
163
|
+
writer: { pid: meta.pid, start: meta.pidStartTime }, lastProgressAt: meta.lastProgressAt ?? meta.startedAt,
|
|
164
|
+
nextDeadline: meta.deadlineAt ?? (watch ? (meta.lastCheckedAt ?? meta.startedAt) + (meta.intervalMs ?? 1000) : now + 1000),
|
|
165
|
+
recovery: watch ? 'captured-legacy-watch' : 'captured-legacy-command' });
|
|
166
|
+
}
|
|
167
|
+
return reasons;
|
|
168
|
+
},
|
|
110
169
|
metrics() { return { ...metrics, registry: registry.getRegistryIoMetrics(), cachedScopes: projections.size }; },
|
|
111
|
-
handle(command: any) {
|
|
170
|
+
handle(command: any, onAccepted?: (id: string) => void) {
|
|
112
171
|
if (Object.keys(command).some(key => !['id', 'type', 'authority'].includes(key)))
|
|
113
172
|
return Promise.reject(new Error('unsupported Background request field'));
|
|
114
173
|
if (pending >= 64)
|
|
115
174
|
return Promise.reject(new Error('runtime-overloaded: Background request capacity'));
|
|
116
175
|
pending++;
|
|
176
|
+
const slot = ++traceSlot;
|
|
177
|
+
trace?.(slot, 'queued');
|
|
117
178
|
const request = tail.catch(() => undefined).then(async () => {
|
|
179
|
+
trace?.(slot, 'executing');
|
|
118
180
|
const record = authority.readBackgroundAuthority(root, instance, command.authority), key = ownerKey(record.owner);
|
|
181
|
+
// A warmed branch view must not overwrite another foreground's progress.
|
|
182
|
+
const viewKey = JSON.stringify([key, authority.backgroundDigest(record.branchIds)]);
|
|
119
183
|
const policy = effectivePolicy(record);
|
|
120
184
|
current = { record, authority: command.authority, ownerKey: key, digest: authority.backgroundDigest(record), policy, policyDigest: authority.backgroundDigest(policy ?? null) };
|
|
121
185
|
if (scopes.size >= 128 && !scopes.has(key)) {
|
|
122
186
|
const oldest = [...scopes.keys()].find(candidate => ![...deliveries.values()].some(item => ownerKey(item.scope.owner) === candidate));
|
|
123
187
|
if (oldest) {
|
|
124
|
-
scopes.delete(oldest);
|
|
188
|
+
scopes.delete(oldest); forgetOwner(oldest);
|
|
125
189
|
}
|
|
126
190
|
else
|
|
127
191
|
throw new Error('runtime-overloaded: Background scope capacity');
|
|
@@ -135,15 +199,16 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
135
199
|
sessionManager: { getSessionId: () => record.owner.sessionId, getBranch: () => branch, getEntries: () => branch, getLeafId: () => record.branchIds.at(-1), getSessionFile: () => undefined } };
|
|
136
200
|
service.noteParentContext(ctx, { recover: false });
|
|
137
201
|
for (const [token, item] of deliveries)
|
|
138
|
-
if (Date.now() - item.createdAt
|
|
202
|
+
if (Date.now() - item.createdAt >= deliveryLeaseMs) {
|
|
139
203
|
item.delivery.defer('Native delivery lease expired');
|
|
140
|
-
|
|
141
|
-
recoveryVersions.delete(ownerKey(item.scope.owner));
|
|
204
|
+
forgetOwner(ownerKey(item.scope.owner));
|
|
142
205
|
deliveries.delete(token);
|
|
143
206
|
}
|
|
144
207
|
if (record.tool === '__background_receipt') {
|
|
145
208
|
const item = deliveries.get(record.params.token);
|
|
146
|
-
|
|
209
|
+
traceHandoff('receipt', { sessionId: record.owner.sessionId, taskId: item?.notification.taskId,
|
|
210
|
+
receiptId: item?.receiptId, found: Boolean(item), delivered: record.params.delivered === true });
|
|
211
|
+
if (!item || ownerKey(item.scope.owner) !== key || isAttentionDelivery(item) && !sameNativeHost(item, record))
|
|
147
212
|
throw new Error('delivery-receipt-refused');
|
|
148
213
|
if (record.params.delivered === true && !service.isParentOriginActive(item.notification.origin, item.notification.branchId))
|
|
149
214
|
throw new Error('delivery-recipient-inactive');
|
|
@@ -151,42 +216,104 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
151
216
|
item.delivery.delivered();
|
|
152
217
|
else {
|
|
153
218
|
item.delivery.defer(String(record.params.reason ?? 'Native handoff deferred'));
|
|
154
|
-
projections.delete(key);
|
|
155
219
|
}
|
|
156
220
|
deliveries.delete(record.params.token);
|
|
157
|
-
|
|
158
|
-
recoveryVersions.delete(key);
|
|
221
|
+
forgetOwner(key);
|
|
159
222
|
return { receipted: record.params.delivered === true };
|
|
160
223
|
}
|
|
161
224
|
if (record.tool === '__background_poll') {
|
|
225
|
+
traceHandoff('poll-enter', { sessionId: record.owner.sessionId });
|
|
162
226
|
if (!observe)
|
|
163
227
|
throw new Error('Shared Background observation unavailable');
|
|
164
228
|
// Recovery is indexed and bounded independently of display readiness.
|
|
165
229
|
const recoveryVersion = authority.backgroundDigest([lease.store.getChangeRevision(), record.branchIds]);
|
|
166
|
-
if (recoveryVersions.get(
|
|
230
|
+
if (recoveryVersions.get(viewKey) !== recoveryVersion || service.hasPendingParentCallbackRecovery()) {
|
|
167
231
|
metrics.reconciles++;
|
|
168
232
|
service.noteParentContext(ctx);
|
|
233
|
+
trace?.(slot, 'recovery');
|
|
169
234
|
await service.reconcileNow();
|
|
170
|
-
recoveryVersions.
|
|
235
|
+
if (!recoveryVersions.has(viewKey) && recoveryVersions.size >= 128) forgetView(recoveryVersions.keys().next().value!);
|
|
236
|
+
recoveryVersions.set(viewKey, recoveryVersion);
|
|
171
237
|
}
|
|
238
|
+
trace?.(slot, 'read-pending');
|
|
172
239
|
const snapshot = await observe({ background: true, cwd: record.owner.workspace, sessionId: record.owner.sessionId });
|
|
240
|
+
trace?.(slot, 'read-returned');
|
|
173
241
|
if (snapshot.status !== 'ready')
|
|
174
242
|
throw new Error(snapshot.reason ?? 'Shared Background observation unverified');
|
|
243
|
+
// Callback pointers carry a delivery obligation but no navigator detail.
|
|
244
|
+
const visibleRows = snapshot.rows.filter(({ meta }: any) => !meta.callbackPending
|
|
245
|
+
&& (!meta.parentRecipient?.branchId || record.branchIds.includes(meta.parentRecipient.branchId)));
|
|
175
246
|
const revision = authority.backgroundDigest([snapshot.scopeRevision, record.branchIds]);
|
|
176
|
-
let projection = projections.get(
|
|
247
|
+
let projection = projections.get(viewKey);
|
|
177
248
|
if (projection?.revision !== revision) {
|
|
178
249
|
metrics.scopeRefreshes++;
|
|
179
|
-
const legacy =
|
|
250
|
+
const legacy = visibleRows.filter((row: any) => !row.meta.durable).map((row: any) => row.meta);
|
|
180
251
|
const recovery=new Map([...legacy,...registry.listPendingCallbackMetasForOrigin({cwd:record.owner.workspace,sessionId:record.owner.sessionId})].map((meta:any)=>[meta.id,meta]));
|
|
181
252
|
for (const meta of recovery.values())
|
|
182
253
|
if (meta.status === 'running' || meta.callback !== false && !meta.callbackSentAt && !meta.callbackSuppressedAt)
|
|
183
254
|
runtime.resumeRunningTask(pi, meta, () => ({ cwd: record.owner.workspace, sessionId: record.owner.sessionId }));
|
|
184
|
-
projection = { revision, tasks:
|
|
185
|
-
if (projections.size >= 128 && !projections.has(
|
|
186
|
-
|
|
187
|
-
projections.set(
|
|
255
|
+
projection = { revision, tasks: visibleRows.filter((row: any) => row.meta.durable).map((row: any) => row.meta), legacyRows: legacy.filter((meta: any) => !meta.dismissedAt).map((meta: any) => navigator.rowFromMeta(meta, Date.now())) };
|
|
256
|
+
if (projections.size >= 128 && !projections.has(viewKey))
|
|
257
|
+
forgetView(projections.keys().next().value!);
|
|
258
|
+
projections.set(viewKey, projection);
|
|
259
|
+
}
|
|
260
|
+
// A task may finish while the client is disconnected, then
|
|
261
|
+
// age out of the recent index before reconnect. Resolve only
|
|
262
|
+
// the client's bounded, previously active IDs in this owner.
|
|
263
|
+
const tasks = [...projection.tasks];
|
|
264
|
+
const present = new Set(tasks.map((task: any) => task.id));
|
|
265
|
+
if (Array.isArray(record.params.knownActiveIds)) {
|
|
266
|
+
for (const id of new Set(record.params.knownActiveIds.slice(0, 200))) {
|
|
267
|
+
if (typeof id !== 'string' || present.has(id)) continue;
|
|
268
|
+
let task = service.readDurableTask({cwd: record.owner.workspace, sessionId: record.owner.sessionId}, id);
|
|
269
|
+
if (!task) {
|
|
270
|
+
const exact = await observe({background: true, cwd: record.owner.workspace, sessionId: record.owner.sessionId, id});
|
|
271
|
+
task = exact.rows.find((row: any) => row.meta.id === id && !row.meta.callbackPending)?.meta;
|
|
272
|
+
}
|
|
273
|
+
if (task && task.dismissedAt === undefined && (!task.parentRecipient?.branchId || record.branchIds.includes(task.parentRecipient.branchId))) { tasks.push(task); present.add(id); }
|
|
274
|
+
}
|
|
188
275
|
}
|
|
189
|
-
|
|
276
|
+
const origin = { cwd: record.owner.workspace, sessionId: record.owner.sessionId };
|
|
277
|
+
const liveAlerts = new Map<string, any>();
|
|
278
|
+
const reviewTasks = tasks.filter(task => task.active && task.progress && task.callback && task.owner.kind === 'parent-session');
|
|
279
|
+
let intervalMinutes = reviewSettings.DEFAULT_BACKGROUND_REVIEW_INTERVAL_MINUTES;
|
|
280
|
+
if (reviewTasks.some(task => task.waits.length)) {
|
|
281
|
+
try { intervalMinutes = reviewSettings.readBackgroundReviewInterval({ agentDir: () => root }); }
|
|
282
|
+
catch { /* An unreadable settings file must not interrupt Background delivery. */ }
|
|
283
|
+
}
|
|
284
|
+
let nextReviewAt = Infinity;
|
|
285
|
+
for (const task of reviewTasks) {
|
|
286
|
+
const stall = task.progress.alertDue ? service.pendingStallAlert(origin, task.id, task.waits) : undefined;
|
|
287
|
+
const review = task.waits.length ? service.backgroundWaitReview(origin, task.id, task.waits, intervalMinutes * 60_000) : undefined;
|
|
288
|
+
for (const alert of [stall, review?.alert]) {
|
|
289
|
+
if (!alert) continue;
|
|
290
|
+
liveAlerts.set(alert.delivery.receiptId, alert.notification);
|
|
291
|
+
notifyParent(alert.notification, alert.delivery);
|
|
292
|
+
}
|
|
293
|
+
if (review && !review.alert) nextReviewAt = Math.min(nextReviewAt, review.dueAt);
|
|
294
|
+
}
|
|
295
|
+
const outgoing = [];
|
|
296
|
+
let retryAfterMs = Number.isFinite(nextReviewAt) ? Math.max(1, nextReviewAt - Date.now()) : undefined;
|
|
297
|
+
if (liveAlerts.size && deliveries.size >= 256) retryAfterMs = Math.min(retryAfterMs ?? 1000, 1000);
|
|
298
|
+
for (const [token, item] of deliveries) {
|
|
299
|
+
if (ownerKey(item.scope.owner) !== key) continue;
|
|
300
|
+
let notification = item.notification;
|
|
301
|
+
if (isAttentionDelivery(item)) {
|
|
302
|
+
if (item.notification.branchId && !record.branchIds.includes(item.notification.branchId)) continue;
|
|
303
|
+
notification = liveAlerts.get(item.receiptId);
|
|
304
|
+
if (!notification) { deliveries.delete(token); continue; }
|
|
305
|
+
// Two frontends can share a session and branch. Only the holder may hand off
|
|
306
|
+
// each alert. A survivor polls again at lease expiry if no receipt arrives.
|
|
307
|
+
if (!sameNativeHost(item, record)) {
|
|
308
|
+
const remaining = Math.max(1, item.createdAt + deliveryLeaseMs - Date.now());
|
|
309
|
+
retryAfterMs = Math.min(retryAfterMs ?? remaining, remaining);
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
outgoing.push({ token, notification, receiptId: item.receiptId });
|
|
314
|
+
}
|
|
315
|
+
traceHandoff('poll-return', { sessionId: record.owner.sessionId, total: outgoing.length, deliveries: outgoing.slice(0, 8).map(item => ({ taskId: item.notification.taskId, receiptId: item.receiptId })) });
|
|
316
|
+
return { ...projection, tasks, retryAfterMs, recoveryPending: service.hasPendingParentCallbackRecovery(), deliveries: outgoing };
|
|
190
317
|
}
|
|
191
318
|
const origin = { cwd: record.owner.workspace, sessionId: record.owner.sessionId };
|
|
192
319
|
if (record.tool === '__background_detail' || record.tool === '__background_action') {
|
|
@@ -209,8 +336,28 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
209
336
|
registry.writeMeta(meta);
|
|
210
337
|
return true;
|
|
211
338
|
}
|
|
212
|
-
if (record.tool === '__background_log')
|
|
213
|
-
|
|
339
|
+
if (record.tool === '__background_log') {
|
|
340
|
+
const owned = service.readDurableTaskLog(origin, record.params.id, record.params.lines);
|
|
341
|
+
if (owned) return owned;
|
|
342
|
+
const snapshot = await observe?.({background: true, ...origin, id: record.params.id});
|
|
343
|
+
if (snapshot?.status !== 'ready') throw new Error('Background task observation unavailable; retry after recovery');
|
|
344
|
+
const task = snapshot.rows.find((row: any) => row.meta.id === record.params.id)?.meta;
|
|
345
|
+
if (!task?.readOnly || task.parentRecipient?.branchId && !record.branchIds.includes(task.parentRecipient.branchId))
|
|
346
|
+
throw new Error('Background task is outside the captured scope');
|
|
347
|
+
const count = Math.max(1, Math.min(200, Number(record.params.lines) || 40));
|
|
348
|
+
let truncated = false;
|
|
349
|
+
const tail = (path: string) => {
|
|
350
|
+
const fd = openSync(path, 'r');
|
|
351
|
+
try {
|
|
352
|
+
const size = fstatSync(fd).size, bytes = Math.min(size, 65536);
|
|
353
|
+
truncated ||= size > bytes;
|
|
354
|
+
const buffer = Buffer.alloc(bytes); const read = readSync(fd, buffer, 0, bytes, size - bytes);
|
|
355
|
+
return buffer.subarray(0, read).toString('utf8').split('\n').slice(-count).join('\n');
|
|
356
|
+
} finally { closeSync(fd); }
|
|
357
|
+
};
|
|
358
|
+
return {taskId: task.id, status: task.status, stdout: tail(task.logPaths.stdout),
|
|
359
|
+
stderr: tail(task.logPaths.stderr), events: tail(task.logPaths.events), truncated};
|
|
360
|
+
}
|
|
214
361
|
if (record.tool === '__background_stop')
|
|
215
362
|
return service.stopDurableTask(origin, record.params.id);
|
|
216
363
|
if (record.tool === '__background_dismiss')
|
|
@@ -226,15 +373,19 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
226
373
|
if (admission && draining() && !prior)
|
|
227
374
|
throw new Error('runtime-draining: new Background execution deferred for upgrade');
|
|
228
375
|
if (mutation) {
|
|
229
|
-
const accepted = journal.accept(key, record.key, authority.backgroundDigest({ tool: record.tool, params: record.params })
|
|
376
|
+
const accepted = journal.accept(key, record.key, authority.backgroundDigest({ tool: record.tool, params: record.params }),
|
|
377
|
+
{ instance, pid: record.pid, start: record.start });
|
|
230
378
|
if (accepted.prior)
|
|
231
379
|
return accepted.record.result ?? { content: [{ type: 'text', text: 'Accepted Background request has an uncertain outcome; inspect its exact operations before issuing new work.' }], details: { status: 'outcome_unknown', operations: accepted.record.operations } };
|
|
232
380
|
journal.dispatch(key, record.key);
|
|
381
|
+
onAccepted?.(`background-request-v1:${authority.backgroundDigest([key, record.key])}`);
|
|
233
382
|
}
|
|
234
383
|
assertAdmission();
|
|
235
384
|
let result;
|
|
236
385
|
try {
|
|
386
|
+
trace?.(slot, 'tool-pending');
|
|
237
387
|
result = await tool.execute(record.key, record.params, undefined, undefined, ctx);
|
|
388
|
+
trace?.(slot, 'tool-returned');
|
|
238
389
|
}
|
|
239
390
|
catch (error) {
|
|
240
391
|
if (mutation)
|
|
@@ -253,7 +404,10 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
253
404
|
if (mutation)
|
|
254
405
|
journal.finish(key, record.key, result);
|
|
255
406
|
return result;
|
|
256
|
-
}).
|
|
407
|
+
}).catch(error => {
|
|
408
|
+
traceHandoff('request-error', { tool: current?.record.tool, sessionId: current?.record.owner.sessionId, error: String(error).slice(0, 256) });
|
|
409
|
+
throw error;
|
|
410
|
+
}).finally(() => { pending--; trace?.(slot, 'settled'); });
|
|
257
411
|
tail = request;
|
|
258
412
|
return request;
|
|
259
413
|
},
|