pi-better-server 0.4.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 +8 -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 +87 -0
- package/scripts/event-publication/writer.mjs +6 -0
- package/scripts/measure-full-runtime/frontend.ts +24 -0
- package/scripts/measure-full-runtime/hosted-extension.ts +28 -0
- package/scripts/measure-full-runtime/probe.mjs +29 -0
- 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 +146 -0
- package/scripts/measure-shared-reads/probe.mjs +26 -2
- package/scripts/measure-shared-reads.mjs +44 -9
- package/scripts/private-runtime/package-lock.json +66 -4
- package/scripts/private-runtime/package.json +10 -2
- package/scripts/source-provenance.mjs +31 -0
- package/scripts/test-on-pi.sh +3 -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 +27 -0
- package/src/runtime/background-tools.ts +389 -0
- package/src/runtime/background.ts +410 -48
- 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 +71 -33
- 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 +89 -4
- package/src/runtime/domain/background/types.mjs +1 -0
- package/src/runtime/domain/background-service/adapter-contract.domain.mjs +83 -0
- package/src/runtime/domain/background-service/adapter-contract.ts +70 -0
- package/src/runtime/domain/background-service/batch.domain.mjs +91 -0
- package/src/runtime/domain/background-service/batch.ts +111 -0
- package/src/runtime/domain/background-service/conditions.domain.mjs +94 -0
- package/src/runtime/domain/background-service/conditions.ts +99 -0
- package/src/runtime/domain/background-service/delivery-observer.domain.mjs +37 -0
- package/src/runtime/domain/background-service/delivery-observer.ts +42 -0
- package/src/runtime/domain/background-service/failures.domain.mjs +209 -0
- package/src/runtime/domain/background-service/failures.ts +212 -0
- package/src/runtime/domain/background-service/goal-provider.domain.mjs +193 -0
- package/src/runtime/domain/background-service/goal-provider.ts +209 -0
- package/src/runtime/domain/background-service/index.domain.mjs +54 -0
- package/src/runtime/domain/background-service/index.ts +55 -0
- package/src/runtime/domain/background-service/logs.domain.mjs +129 -0
- package/src/runtime/domain/background-service/logs.ts +134 -0
- package/src/runtime/domain/background-service/maintenance.domain.mjs +95 -0
- package/src/runtime/domain/background-service/maintenance.ts +98 -0
- package/src/runtime/domain/background-service/managed-authority.domain.mjs +32 -0
- package/src/runtime/domain/background-service/managed-authority.ts +30 -0
- package/src/runtime/domain/background-service/managed-client.domain.mjs +79 -0
- package/src/runtime/domain/background-service/managed-client.ts +73 -0
- package/src/runtime/domain/background-service/managed-frontend.domain.mjs +225 -0
- package/src/runtime/domain/background-service/managed-frontend.ts +176 -0
- package/src/runtime/domain/background-service/navigator-provider.domain.mjs +492 -0
- package/src/runtime/domain/background-service/navigator-provider.ts +485 -0
- 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 +4080 -0
- package/src/runtime/domain/background-service/observed-waits.ts +4513 -0
- package/src/runtime/domain/background-service/output.domain.mjs +867 -0
- package/src/runtime/domain/background-service/output.ts +952 -0
- package/src/runtime/domain/background-service/process-identity.domain.mjs +129 -0
- package/src/runtime/domain/background-service/process-identity.ts +134 -0
- package/src/runtime/domain/background-service/process.domain.mjs +512 -0
- package/src/runtime/domain/background-service/process.ts +532 -0
- package/src/runtime/domain/background-service/prompt.domain.mjs +58 -0
- package/src/runtime/domain/background-service/prompt.ts +72 -0
- package/src/runtime/domain/background-service/registry.domain.mjs +460 -0
- package/src/runtime/domain/background-service/registry.ts +450 -0
- package/src/runtime/domain/background-service/remote-task-preset.domain.mjs +67 -0
- package/src/runtime/domain/background-service/remote-task-preset.ts +127 -0
- package/src/runtime/domain/background-service/runtime.domain.mjs +1511 -0
- package/src/runtime/domain/background-service/runtime.ts +1636 -0
- package/src/runtime/domain/background-service/sandbox.domain.mjs +735 -0
- package/src/runtime/domain/background-service/sandbox.ts +913 -0
- package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +777 -0
- package/src/runtime/domain/background-service/shared-callback-batcher.ts +956 -0
- package/src/runtime/domain/background-service/shared-execution-policy.domain.mjs +50 -0
- package/src/runtime/domain/background-service/shared-execution-policy.ts +61 -0
- package/src/runtime/domain/background-service/shared-failure-observations.domain.mjs +1078 -0
- package/src/runtime/domain/background-service/shared-failure-observations.ts +1166 -0
- package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +126 -0
- package/src/runtime/domain/background-service/shared-harness-settings.ts +116 -0
- package/src/runtime/domain/background-service/shared-log-utils.domain.mjs +1223 -0
- package/src/runtime/domain/background-service/shared-log-utils.ts +1492 -0
- package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +289 -0
- package/src/runtime/domain/background-service/shared-navigator-panels.ts +272 -0
- package/src/runtime/domain/background-service/shared-navigator.domain.mjs +1930 -0
- package/src/runtime/domain/background-service/shared-navigator.ts +1962 -0
- 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 +189 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/index.domain.mjs +51 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/index.ts +122 -0
- 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 +163 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +174 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +66 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +87 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +90 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +97 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +139 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/errors.domain.mjs +12 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/errors.ts +79 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +342 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +513 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +283 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +458 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/recovery.domain.mjs +52 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/recovery.ts +55 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +114 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +140 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +280 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +442 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +420 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +441 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/sqlite.domain.mjs +194 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/sqlite.ts +239 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +275 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +585 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +120 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +142 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-cancellation.domain.mjs +188 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-cancellation.ts +224 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +25 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +707 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/upgrade.domain.mjs +22 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/upgrade.ts +22 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/validate.domain.mjs +234 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/validate.ts +241 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.domain.mjs +851 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.ts +1424 -0
- package/src/runtime/domain/background-service/shared-permission-blocker.domain.mjs +40 -0
- package/src/runtime/domain/background-service/shared-permission-blocker.ts +48 -0
- package/src/runtime/domain/background-service/shared-render-scheduler.domain.mjs +41 -0
- package/src/runtime/domain/background-service/shared-render-scheduler.ts +47 -0
- package/src/runtime/domain/background-service/shared-sandbox-core.domain.mjs +1531 -0
- package/src/runtime/domain/background-service/shared-sandbox-core.ts +1757 -0
- package/src/runtime/domain/background-service/shared-sandbox-diagnostics.domain.mjs +591 -0
- package/src/runtime/domain/background-service/shared-sandbox-diagnostics.ts +491 -0
- package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +698 -0
- package/src/runtime/domain/background-service/shared-ssh-core/index.ts +979 -0
- package/src/runtime/domain/background-service/shared-stall-detector.domain.mjs +37 -0
- package/src/runtime/domain/background-service/shared-stall-detector.ts +69 -0
- package/src/runtime/domain/background-service/shared-work-client.mjs +303 -0
- package/src/runtime/domain/background-service/stall-attention.domain.mjs +29 -0
- package/src/runtime/domain/background-service/stall-attention.ts +31 -0
- package/src/runtime/domain/background-service/stall.domain.mjs +57 -0
- package/src/runtime/domain/background-service/stall.ts +57 -0
- package/src/runtime/domain/background-service/supervisor/README.md +111 -0
- package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +90 -0
- package/src/runtime/domain/background-service/supervisor/generated/conditions.mjs +96 -0
- package/src/runtime/domain/background-service/supervisor/generated/identity.mjs +95 -0
- package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +131 -0
- package/src/runtime/domain/background-service/supervisor/generated/process.mjs +514 -0
- package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +872 -0
- package/src/runtime/domain/background-service/supervisor/generated/store.mjs +609 -0
- package/src/runtime/domain/background-service/supervisor/generated/types.mjs +50 -0
- package/src/runtime/domain/background-service/supervisor/identity.domain.mjs +93 -0
- package/src/runtime/domain/background-service/supervisor/identity.ts +99 -0
- package/src/runtime/domain/background-service/supervisor/index.domain.mjs +22 -0
- package/src/runtime/domain/background-service/supervisor/index.ts +37 -0
- package/src/runtime/domain/background-service/supervisor/invocation.domain.mjs +30 -0
- package/src/runtime/domain/background-service/supervisor/invocation.ts +44 -0
- package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +870 -0
- package/src/runtime/domain/background-service/supervisor/runner.ts +982 -0
- package/src/runtime/domain/background-service/supervisor/store.domain.mjs +605 -0
- package/src/runtime/domain/background-service/supervisor/store.ts +651 -0
- package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +721 -0
- package/src/runtime/domain/background-service/supervisor/supervisor.ts +804 -0
- package/src/runtime/domain/background-service/supervisor/types.domain.mjs +48 -0
- package/src/runtime/domain/background-service/supervisor/types.ts +394 -0
- package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +60 -0
- package/src/runtime/domain/background-service/task-diagnostics.ts +71 -0
- package/src/runtime/domain/background-service/tools.domain.mjs +1050 -0
- package/src/runtime/domain/background-service/tools.ts +1142 -0
- package/src/runtime/domain/background-service/types.domain.mjs +5 -0
- package/src/runtime/domain/background-service/types.ts +236 -0
- package/src/runtime/domain/background-service/work-observation.domain.mjs +176 -0
- package/src/runtime/domain/background-service/work-observation.ts +144 -0
- 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-parent-callbacks.mjs +65 -0
- package/src/runtime/domain/coordinator/src/background-requests.mjs +86 -0
- 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 +73 -21
- package/src/runtime/domain/coordinator/src/store.mjs +32 -3
- package/src/runtime/domain/coordinator/src/subagent-launch.mjs +119 -0
- package/src/runtime/domain/coordinator/src/types.mjs +1 -1
- package/src/runtime/domain/coordinator/src/upgrade.mjs +22 -0
- 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 +633 -0
- package/src/runtime/domain/sandbox-policy/background-admission.domain.mjs +83 -0
- package/src/runtime/domain/sandbox-policy/background-admission.ts +75 -0
- package/src/runtime/domain/sandbox-policy/commands.domain.mjs +245 -0
- package/src/runtime/domain/sandbox-policy/commands.ts +336 -0
- package/src/runtime/domain/sandbox-policy/deny-rules.domain.mjs +440 -0
- package/src/runtime/domain/sandbox-policy/deny-rules.ts +620 -0
- package/src/runtime/domain/sandbox-policy/diagnostics-command.domain.mjs +30 -0
- package/src/runtime/domain/sandbox-policy/diagnostics-command.ts +27 -0
- package/src/runtime/domain/sandbox-policy/events.domain.mjs +49 -0
- package/src/runtime/domain/sandbox-policy/events.ts +85 -0
- package/src/runtime/domain/sandbox-policy/files.domain.mjs +153 -0
- package/src/runtime/domain/sandbox-policy/files.ts +224 -0
- package/src/runtime/domain/sandbox-policy/index.domain.mjs +289 -0
- package/src/runtime/domain/sandbox-policy/index.ts +386 -0
- package/src/runtime/domain/sandbox-policy/package.json +66 -0
- package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +36 -0
- package/src/runtime/domain/sandbox-policy/permission-settings.ts +46 -0
- package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +309 -0
- package/src/runtime/domain/sandbox-policy/permissions-page.ts +295 -0
- package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +98 -0
- package/src/runtime/domain/sandbox-policy/permissions.ts +125 -0
- package/src/runtime/domain/sandbox-policy/policy.domain.mjs +80 -0
- package/src/runtime/domain/sandbox-policy/policy.ts +102 -0
- package/src/runtime/domain/sandbox-policy/preferences.domain.mjs +55 -0
- package/src/runtime/domain/sandbox-policy/preferences.ts +82 -0
- package/src/runtime/domain/sandbox-policy/rules-page.domain.mjs +138 -0
- package/src/runtime/domain/sandbox-policy/rules-page.ts +176 -0
- package/src/runtime/domain/sandbox-policy/session-permissions.domain.mjs +22 -0
- package/src/runtime/domain/sandbox-policy/session-permissions.ts +24 -0
- package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +126 -0
- package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +116 -0
- package/src/runtime/domain/sandbox-policy/shared-permission-blocker.domain.mjs +40 -0
- package/src/runtime/domain/sandbox-policy/shared-permission-blocker.ts +48 -0
- package/src/runtime/domain/sandbox-policy/shared-sandbox-core.domain.mjs +1531 -0
- package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1757 -0
- package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.domain.mjs +591 -0
- package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.ts +491 -0
- package/src/runtime/domain/sandbox-policy/shared-task-application.domain.mjs +185 -0
- package/src/runtime/domain/sandbox-policy/shared-task-application.ts +185 -0
- package/src/runtime/domain/sandbox-policy/shared-task-apply-patch.domain.mjs +416 -0
- package/src/runtime/domain/sandbox-policy/shared-task-apply-patch.ts +409 -0
- package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +325 -0
- package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +335 -0
- package/src/runtime/domain/sandbox-policy/shared-task-files.domain.mjs +346 -0
- package/src/runtime/domain/sandbox-policy/shared-task-files.ts +342 -0
- 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 +220 -0
- package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +209 -0
- package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +227 -0
- package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +224 -0
- package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +92 -0
- package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +123 -0
- package/src/runtime/domain/sandbox-policy/shell.domain.mjs +93 -0
- package/src/runtime/domain/sandbox-policy/shell.ts +129 -0
- package/src/runtime/domain/sandbox-policy/state.domain.mjs +307 -0
- package/src/runtime/domain/sandbox-policy/state.ts +408 -0
- package/src/runtime/domain/sandbox-policy/status.domain.mjs +64 -0
- package/src/runtime/domain/sandbox-policy/status.ts +76 -0
- package/src/runtime/domain/sandbox-policy/subagent-admission.domain.mjs +69 -0
- package/src/runtime/domain/sandbox-policy/subagent-admission.ts +60 -0
- package/src/runtime/domain/subagents/CONTEXT.md +202 -0
- package/src/runtime/domain/subagents/PRODUCT.md +49 -0
- package/src/runtime/domain/subagents/README.md +201 -0
- package/src/runtime/domain/subagents/agent-catalog.mjs +64 -0
- package/src/runtime/domain/subagents/agent-commands.domain.mjs +822 -0
- package/src/runtime/domain/subagents/agent-commands.ts +905 -0
- package/src/runtime/domain/subagents/agent-inspection.domain.mjs +398 -0
- package/src/runtime/domain/subagents/agent-inspection.ts +574 -0
- package/src/runtime/domain/subagents/agent-operations.domain.mjs +40 -0
- package/src/runtime/domain/subagents/agent-operations.ts +61 -0
- package/src/runtime/domain/subagents/agent-session-settings.domain.mjs +112 -0
- package/src/runtime/domain/subagents/agent-session-settings.ts +118 -0
- package/src/runtime/domain/subagents/agents-catalog-tool.domain.mjs +84 -0
- package/src/runtime/domain/subagents/agents-catalog-tool.ts +118 -0
- package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +276 -0
- package/src/runtime/domain/subagents/assignment-outcomes.ts +212 -0
- package/src/runtime/domain/subagents/assignment-projection.mjs +261 -0
- package/src/runtime/domain/subagents/assignment-report.domain.mjs +174 -0
- package/src/runtime/domain/subagents/assignment-report.ts +156 -0
- package/src/runtime/domain/subagents/batch.mjs +275 -0
- package/src/runtime/domain/subagents/callback-fields.domain.mjs +72 -0
- package/src/runtime/domain/subagents/callback-fields.ts +95 -0
- package/src/runtime/domain/subagents/capacity.mjs +108 -0
- package/src/runtime/domain/subagents/catalog-editor.domain.mjs +98 -0
- package/src/runtime/domain/subagents/catalog-editor.ts +125 -0
- package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +104 -0
- package/src/runtime/domain/subagents/catalog-host-admission.ts +85 -0
- package/src/runtime/domain/subagents/catalog-identity.domain.mjs +222 -0
- package/src/runtime/domain/subagents/catalog-identity.ts +258 -0
- package/src/runtime/domain/subagents/catalog-overlay.domain.mjs +9 -0
- package/src/runtime/domain/subagents/catalog-overlay.ts +10 -0
- package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +164 -0
- package/src/runtime/domain/subagents/catalog-preferences.ts +139 -0
- package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +366 -0
- package/src/runtime/domain/subagents/catalog-resolver.ts +540 -0
- package/src/runtime/domain/subagents/catalog-runtime.domain.mjs +570 -0
- package/src/runtime/domain/subagents/catalog-runtime.ts +680 -0
- package/src/runtime/domain/subagents/catalog-schema.domain.mjs +1331 -0
- package/src/runtime/domain/subagents/catalog-schema.ts +1563 -0
- package/src/runtime/domain/subagents/catalog-skill-edits.domain.mjs +95 -0
- package/src/runtime/domain/subagents/catalog-skill-edits.ts +116 -0
- package/src/runtime/domain/subagents/catalog-store.domain.mjs +808 -0
- package/src/runtime/domain/subagents/catalog-store.ts +1006 -0
- package/src/runtime/domain/subagents/catalog-ui.domain.mjs +651 -0
- package/src/runtime/domain/subagents/catalog-ui.ts +611 -0
- 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-codemode.domain.mjs +16 -0
- package/src/runtime/domain/subagents/child-codemode.ts +17 -0
- package/src/runtime/domain/subagents/child-dependencies.mjs +193 -0
- package/src/runtime/domain/subagents/child-incidents.domain.mjs +170 -0
- package/src/runtime/domain/subagents/child-incidents.ts +169 -0
- package/src/runtime/domain/subagents/child-operations.domain.mjs +986 -0
- package/src/runtime/domain/subagents/child-operations.ts +1191 -0
- package/src/runtime/domain/subagents/child-ownership.domain.mjs +205 -0
- package/src/runtime/domain/subagents/child-ownership.ts +160 -0
- package/src/runtime/domain/subagents/child-preflight.mjs +38 -0
- 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/child-runtime.mjs +67 -0
- package/src/runtime/domain/subagents/child-steer.domain.mjs +109 -0
- package/src/runtime/domain/subagents/child-steer.ts +102 -0
- package/src/runtime/domain/subagents/cleanup.domain.mjs +818 -0
- package/src/runtime/domain/subagents/cleanup.ts +1017 -0
- package/src/runtime/domain/subagents/codex-import.domain.mjs +575 -0
- package/src/runtime/domain/subagents/codex-import.ts +717 -0
- package/src/runtime/domain/subagents/completion.domain.mjs +6 -0
- package/src/runtime/domain/subagents/completion.mjs +152 -0
- package/src/runtime/domain/subagents/completion.ts +11 -0
- package/src/runtime/domain/subagents/config.domain.mjs +248 -0
- package/src/runtime/domain/subagents/config.json +15 -0
- package/src/runtime/domain/subagents/config.ts +328 -0
- package/src/runtime/domain/subagents/continuation-authority.domain.mjs +38 -0
- package/src/runtime/domain/subagents/continuation-authority.ts +31 -0
- 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 +942 -0
- package/src/runtime/domain/subagents/continuation.ts +1051 -0
- package/src/runtime/domain/subagents/delegation.domain.mjs +19 -0
- package/src/runtime/domain/subagents/delegation.ts +24 -0
- package/src/runtime/domain/subagents/effective-settings.domain.mjs +130 -0
- package/src/runtime/domain/subagents/effective-settings.ts +184 -0
- package/src/runtime/domain/subagents/extensions.domain.mjs +6 -0
- package/src/runtime/domain/subagents/extensions.mjs +164 -0
- package/src/runtime/domain/subagents/extensions.ts +19 -0
- package/src/runtime/domain/subagents/failures.domain.mjs +362 -0
- package/src/runtime/domain/subagents/failures.ts +319 -0
- package/src/runtime/domain/subagents/finalization.domain.mjs +168 -0
- package/src/runtime/domain/subagents/finalization.ts +218 -0
- package/src/runtime/domain/subagents/git-remotes.domain.mjs +351 -0
- package/src/runtime/domain/subagents/git-remotes.ts +413 -0
- package/src/runtime/domain/subagents/git-workspace.domain.mjs +337 -0
- package/src/runtime/domain/subagents/git-workspace.ts +430 -0
- package/src/runtime/domain/subagents/goal-provider.domain.mjs +125 -0
- package/src/runtime/domain/subagents/goal-provider.ts +132 -0
- package/src/runtime/domain/subagents/health-observation.domain.mjs +617 -0
- package/src/runtime/domain/subagents/health-observation.ts +818 -0
- package/src/runtime/domain/subagents/health-surface.mjs +284 -0
- package/src/runtime/domain/subagents/health.domain.mjs +261 -0
- package/src/runtime/domain/subagents/health.ts +343 -0
- package/src/runtime/domain/subagents/historical-attention.domain.mjs +37 -0
- package/src/runtime/domain/subagents/historical-attention.ts +35 -0
- package/src/runtime/domain/subagents/incident-model.domain.mjs +322 -0
- package/src/runtime/domain/subagents/incident-model.ts +358 -0
- package/src/runtime/domain/subagents/index.domain.mjs +4731 -0
- package/src/runtime/domain/subagents/index.ts +4781 -0
- package/src/runtime/domain/subagents/launch-abort.domain.mjs +13 -0
- package/src/runtime/domain/subagents/launch-abort.ts +21 -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/lifecycle.domain.mjs +265 -0
- package/src/runtime/domain/subagents/lifecycle.ts +360 -0
- package/src/runtime/domain/subagents/list.domain.mjs +2 -0
- package/src/runtime/domain/subagents/list.mjs +152 -0
- package/src/runtime/domain/subagents/list.ts +19 -0
- package/src/runtime/domain/subagents/log-cursor.domain.mjs +217 -0
- package/src/runtime/domain/subagents/log-cursor.ts +268 -0
- package/src/runtime/domain/subagents/managed-background-capability.domain.mjs +10 -0
- package/src/runtime/domain/subagents/managed-background-capability.ts +9 -0
- package/src/runtime/domain/subagents/managed-failure-worker.mjs +36 -0
- package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +48 -0
- package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +75 -0
- package/src/runtime/domain/subagents/managed-launch-client.ts +59 -0
- package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +627 -0
- package/src/runtime/domain/subagents/managed-launch-host.ts +504 -0
- package/src/runtime/domain/subagents/managed-launch-journal.mjs +17 -0
- package/src/runtime/domain/subagents/managed-launch-ownership.domain.mjs +29 -0
- package/src/runtime/domain/subagents/managed-launch-ownership.ts +22 -0
- package/src/runtime/domain/subagents/managed-launch-port.domain.mjs +2 -0
- package/src/runtime/domain/subagents/managed-launch-port.ts +25 -0
- package/src/runtime/domain/subagents/managed-launch-recovery.domain.mjs +29 -0
- package/src/runtime/domain/subagents/managed-launch-recovery.ts +45 -0
- package/src/runtime/domain/subagents/managed-worker-bridge.domain.mjs +63 -0
- package/src/runtime/domain/subagents/managed-worker-bridge.ts +48 -0
- package/src/runtime/domain/subagents/managed-worker.mjs +13 -0
- package/src/runtime/domain/subagents/model-resolution-core.domain.mjs +822 -0
- package/src/runtime/domain/subagents/model-resolution-core.ts +1074 -0
- package/src/runtime/domain/subagents/model-resolution.domain.mjs +22 -0
- package/src/runtime/domain/subagents/model-resolution.ts +32 -0
- package/src/runtime/domain/subagents/navigator.domain.mjs +6 -0
- package/src/runtime/domain/subagents/navigator.mjs +1233 -0
- package/src/runtime/domain/subagents/navigator.ts +39 -0
- package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +1012 -0
- package/src/runtime/domain/subagents/operation-bridge-types.ts +1156 -0
- package/src/runtime/domain/subagents/outage-observations.domain.mjs +84 -0
- package/src/runtime/domain/subagents/outage-observations.ts +73 -0
- package/src/runtime/domain/subagents/output-payload.domain.mjs +767 -0
- package/src/runtime/domain/subagents/output-payload.ts +987 -0
- 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 +86 -0
- package/src/runtime/domain/subagents/park-checkpoint.domain.mjs +55 -0
- package/src/runtime/domain/subagents/park-checkpoint.ts +61 -0
- package/src/runtime/domain/subagents/parse.domain.mjs +1218 -0
- package/src/runtime/domain/subagents/parse.ts +1451 -0
- package/src/runtime/domain/subagents/permission-policy.domain.mjs +232 -0
- package/src/runtime/domain/subagents/permission-policy.ts +291 -0
- package/src/runtime/domain/subagents/process-identity.mjs +33 -0
- package/src/runtime/domain/subagents/registry.domain.mjs +1584 -0
- package/src/runtime/domain/subagents/registry.ts +1904 -0
- package/src/runtime/domain/subagents/role-assignment.domain.mjs +104 -0
- package/src/runtime/domain/subagents/role-assignment.ts +141 -0
- package/src/runtime/domain/subagents/roles/role.architect.md +13 -0
- package/src/runtime/domain/subagents/roles/role.developer.md +16 -0
- package/src/runtime/domain/subagents/roles/role.explorer.md +13 -0
- package/src/runtime/domain/subagents/roles/role.product-manager.md +13 -0
- package/src/runtime/domain/subagents/roles/role.researcher.md +13 -0
- package/src/runtime/domain/subagents/roles/role.reviewer.md +13 -0
- package/src/runtime/domain/subagents/roles/role.writer.md +12 -0
- package/src/runtime/domain/subagents/sandbox.domain.mjs +64 -0
- package/src/runtime/domain/subagents/sandbox.ts +92 -0
- package/src/runtime/domain/subagents/session-selection.domain.mjs +32 -0
- package/src/runtime/domain/subagents/session-selection.ts +35 -0
- package/src/runtime/domain/subagents/session-store.domain.mjs +489 -0
- package/src/runtime/domain/subagents/session-store.ts +468 -0
- package/src/runtime/domain/subagents/settings-page.domain.mjs +313 -0
- package/src/runtime/domain/subagents/settings-page.ts +363 -0
- package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +777 -0
- package/src/runtime/domain/subagents/shared-callback-batcher.ts +956 -0
- package/src/runtime/domain/subagents/shared-catalog.domain.mjs +70 -0
- package/src/runtime/domain/subagents/shared-catalog.ts +61 -0
- package/src/runtime/domain/subagents/shared-execution-policy.domain.mjs +50 -0
- package/src/runtime/domain/subagents/shared-execution-policy.ts +61 -0
- package/src/runtime/domain/subagents/shared-failure-observations.domain.mjs +1078 -0
- package/src/runtime/domain/subagents/shared-failure-observations.ts +1166 -0
- package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +126 -0
- package/src/runtime/domain/subagents/shared-harness-settings.ts +116 -0
- package/src/runtime/domain/subagents/shared-log-utils.domain.mjs +1223 -0
- package/src/runtime/domain/subagents/shared-log-utils.ts +1492 -0
- package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +289 -0
- package/src/runtime/domain/subagents/shared-navigator-panels.ts +272 -0
- package/src/runtime/domain/subagents/shared-navigator.domain.mjs +1930 -0
- package/src/runtime/domain/subagents/shared-navigator.ts +1962 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +189 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/index.domain.mjs +51 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/index.ts +122 -0
- 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 +163 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +174 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +66 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +87 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +90 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +97 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +139 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/errors.domain.mjs +12 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/errors.ts +79 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +342 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +513 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +283 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +458 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/recovery.domain.mjs +52 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/recovery.ts +55 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +114 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +140 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +280 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +442 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +420 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +441 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/sqlite.domain.mjs +194 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/sqlite.ts +239 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +275 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +585 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +120 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +142 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-cancellation.domain.mjs +188 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-cancellation.ts +224 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +25 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +707 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/upgrade.domain.mjs +22 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/upgrade.ts +22 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/validate.domain.mjs +234 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/validate.ts +241 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.domain.mjs +851 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.ts +1424 -0
- package/src/runtime/domain/subagents/shared-permission-blocker.domain.mjs +40 -0
- package/src/runtime/domain/subagents/shared-permission-blocker.ts +48 -0
- package/src/runtime/domain/subagents/shared-render-scheduler.domain.mjs +41 -0
- package/src/runtime/domain/subagents/shared-render-scheduler.ts +47 -0
- package/src/runtime/domain/subagents/shared-sandbox-core.domain.mjs +1531 -0
- package/src/runtime/domain/subagents/shared-sandbox-core.ts +1757 -0
- package/src/runtime/domain/subagents/shared-sandbox-diagnostics.domain.mjs +591 -0
- package/src/runtime/domain/subagents/shared-sandbox-diagnostics.ts +491 -0
- package/src/runtime/domain/subagents/shared-stall-detector.domain.mjs +37 -0
- package/src/runtime/domain/subagents/shared-stall-detector.ts +69 -0
- package/src/runtime/domain/subagents/shared-task-application.domain.mjs +185 -0
- package/src/runtime/domain/subagents/shared-task-application.ts +185 -0
- package/src/runtime/domain/subagents/shared-task-apply-patch.domain.mjs +416 -0
- package/src/runtime/domain/subagents/shared-task-apply-patch.ts +409 -0
- package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +325 -0
- package/src/runtime/domain/subagents/shared-task-exec.ts +335 -0
- package/src/runtime/domain/subagents/shared-task-files.domain.mjs +346 -0
- package/src/runtime/domain/subagents/shared-task-files.ts +342 -0
- 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 +220 -0
- package/src/runtime/domain/subagents/shared-task-process-list.ts +209 -0
- package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +227 -0
- package/src/runtime/domain/subagents/shared-task-sandbox.ts +224 -0
- package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +92 -0
- package/src/runtime/domain/subagents/shared-task-tools.ts +123 -0
- package/src/runtime/domain/subagents/shared-work-client.mjs +303 -0
- package/src/runtime/domain/subagents/shared-worktree-context.domain.mjs +142 -0
- package/src/runtime/domain/subagents/shared-worktree-context.ts +158 -0
- package/src/runtime/domain/subagents/skill-picker.domain.mjs +316 -0
- package/src/runtime/domain/subagents/skill-picker.ts +353 -0
- package/src/runtime/domain/subagents/skills.domain.mjs +138 -0
- package/src/runtime/domain/subagents/skills.ts +183 -0
- package/src/runtime/domain/subagents/spawn.domain.mjs +72 -0
- package/src/runtime/domain/subagents/spawn.ts +80 -0
- package/src/runtime/domain/subagents/stop.domain.mjs +184 -0
- package/src/runtime/domain/subagents/stop.ts +217 -0
- package/src/runtime/domain/subagents/subagent-tools.domain.mjs +101 -0
- package/src/runtime/domain/subagents/subagent-tools.ts +137 -0
- package/src/runtime/domain/subagents/task-guard.domain.mjs +163 -0
- package/src/runtime/domain/subagents/task-guard.ts +144 -0
- package/src/runtime/domain/subagents/task-policy.domain.mjs +201 -0
- package/src/runtime/domain/subagents/task-policy.ts +236 -0
- package/src/runtime/domain/subagents/task-runtime.mjs +53 -0
- package/src/runtime/domain/subagents/task-tool-owner.domain.mjs +18 -0
- package/src/runtime/domain/subagents/task-tool-owner.ts +21 -0
- package/src/runtime/domain/subagents/thinking.domain.mjs +22 -0
- package/src/runtime/domain/subagents/thinking.ts +28 -0
- package/src/runtime/domain/subagents/tier-policy.domain.mjs +75 -0
- package/src/runtime/domain/subagents/tier-policy.ts +126 -0
- package/src/runtime/domain/subagents/timing-notifications.domain.mjs +51 -0
- package/src/runtime/domain/subagents/timing-notifications.ts +37 -0
- package/src/runtime/domain/subagents/timing.domain.mjs +487 -0
- package/src/runtime/domain/subagents/timing.ts +634 -0
- package/src/runtime/domain/subagents/tools.domain.mjs +558 -0
- package/src/runtime/domain/subagents/tools.ts +629 -0
- package/src/runtime/domain/subagents/widget.domain.mjs +6 -0
- package/src/runtime/domain/subagents/widget.mjs +246 -0
- package/src/runtime/domain/subagents/widget.ts +30 -0
- package/src/runtime/domain/subagents/work-observation.domain.mjs +316 -0
- package/src/runtime/domain/subagents/work-observation.ts +248 -0
- package/src/runtime/domain/subagents/worker-catalog.domain.mjs +120 -0
- package/src/runtime/domain/subagents/worker-catalog.ts +162 -0
- package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +1009 -0
- package/src/runtime/domain/subagents/worker-operations-host.ts +1238 -0
- package/src/runtime/domain/subagents/worker-waits.domain.mjs +2336 -0
- package/src/runtime/domain/subagents/worker-waits.ts +2878 -0
- package/src/runtime/domain/subagents/workspace-scope.domain.mjs +52 -0
- package/src/runtime/domain/subagents/workspace-scope.ts +50 -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 +27 -3
- package/src/runtime/query-executor.ts +178 -34
- package/src/runtime/query-worker.mjs +119 -22
- package/src/runtime/read-model.ts +939 -113
- 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 +73 -0
- 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 +185 -22
- package/src/session-activity.ts +26 -4
- package/src/version.ts +1 -1
|
@@ -0,0 +1,4080 @@
|
|
|
1
|
+
// Generated fixed launch domain from packages/pi-better-background-tasks/src/observed-waits.ts. Do not edit directly.
|
|
2
|
+
import { getObservedWaitHost, registerObservedWaitClient } from "./observed-wait-client.domain.mjs";
|
|
3
|
+
export { getObservedWaitHost, registerObservedWaitClient } from "./observed-wait-client.domain.mjs";
|
|
4
|
+
/**
|
|
5
|
+
* Parent-side observed waits: the integration between background tasks, the
|
|
6
|
+
* detached local supervisor and the durable operation coordinator.
|
|
7
|
+
*
|
|
8
|
+
* Scope of this module:
|
|
9
|
+
*
|
|
10
|
+
* - launch local processes and command watches through the supervisor after the
|
|
11
|
+
* normal Background / worker sandbox admission has already admitted them;
|
|
12
|
+
* - register the durable operation *before* the runner starts, using the
|
|
13
|
+
* token-derived `bgs_…` task id;
|
|
14
|
+
* - reconcile terminal supervisor evidence into the coordinator store without
|
|
15
|
+
* re-running an ambiguous launch;
|
|
16
|
+
* - register all-settled waits, dispatch ready deliveries to the owner, and
|
|
17
|
+
* require an exact evidence read before an acknowledgement consumes a wait;
|
|
18
|
+
* - expose a versioned, in-process service for the Subagents bridge. The bridge
|
|
19
|
+
* owns its transport; this module owns authorization and the durable records.
|
|
20
|
+
*
|
|
21
|
+
* What it deliberately does not own: SSH/remote launches, a bridge socket, model
|
|
22
|
+
* continuation, goal/workflow completion, or any permission decision beyond
|
|
23
|
+
* calling the existing `resolve*SandboxPlan` helpers.
|
|
24
|
+
*/
|
|
25
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
26
|
+
import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, watch } from "node:fs";
|
|
27
|
+
import { homedir } from "node:os";
|
|
28
|
+
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
29
|
+
import { validateCondition } from "./conditions.domain.mjs";
|
|
30
|
+
import { STEP_GATE_COMMAND_ENV, commandExecution, parseStepGateFailure, processExists, stepGateScript, validateCommandSpec, } from "./process.domain.mjs";
|
|
31
|
+
import { currentProcessStartToken, readProcessStartToken } from "./process-identity.domain.mjs";
|
|
32
|
+
import { assertBackgroundExecutionAllowed, backgroundExecutionLimits, confineCommandSpec, resolveForegroundSandboxPlan, currentForegroundSandboxPolicy, resolveWorkerSandboxPlan, sandboxProvenance, } from "./sandbox.domain.mjs";
|
|
33
|
+
import { openStore, cancellationCredential, } from "./shared-operation-coordinator/index.domain.mjs";
|
|
34
|
+
import { createLocalSupervisor, defaultSupervisorDirectory, supervisorPaths, supervisorTaskIdForToken, } from "./supervisor/index.domain.mjs";
|
|
35
|
+
import { processGroupAlive } from "./supervisor/identity.domain.mjs";
|
|
36
|
+
import { readStopRequest } from "./supervisor/store.domain.mjs";
|
|
37
|
+
export const OBSERVED_WAITS_SERVICE_VERSION = 2;
|
|
38
|
+
export const OBSERVED_WAITS_SERVICE_CHANNEL = "pi-better-background-tasks:observed-waits-service";
|
|
39
|
+
export const OBSERVED_WAITS_SERVICE_REQUEST_CHANNEL = "pi-better-background-tasks:observed-waits-service-request";
|
|
40
|
+
/**
|
|
41
|
+
* Request/reply compatibility surface used by the Subagents coordinator. The
|
|
42
|
+
* object service above is the richer in-process API; this channel is the
|
|
43
|
+
* versioned wire contract that lets a standalone Subagents build register runs,
|
|
44
|
+
* execute worker tools, admit parks, and drive resume claims without importing
|
|
45
|
+
* this package.
|
|
46
|
+
*/
|
|
47
|
+
export const OBSERVED_WAITS_RPC_CHANNEL = "pi-better-background-tasks:observed-waits";
|
|
48
|
+
export const OBSERVED_WAITS_READY_CHANNEL = "pi-better-background-tasks:observed-waits-ready";
|
|
49
|
+
export const OBSERVED_WAITS_RPC_VERSION = 1;
|
|
50
|
+
const OBSERVER = Object.freeze({ kind: "local-supervisor", version: "1" });
|
|
51
|
+
/**
|
|
52
|
+
* Process-wide host-instance ordering shared across module copies. A stale host
|
|
53
|
+
* must never take over a newer same-process host's callback claim, while the
|
|
54
|
+
* newer host may still recover an older instance's claim after a reload.
|
|
55
|
+
*/
|
|
56
|
+
const HOST_INSTANCE_STATE = (() => {
|
|
57
|
+
const key = Symbol.for("pi-better-background-tasks:observed-waits-host-instances");
|
|
58
|
+
const global = globalThis;
|
|
59
|
+
return global[key] ??= { next: 0, generations: new Map(), closed: new Set() };
|
|
60
|
+
})();
|
|
61
|
+
const LOCAL_DURABLE_ID = /^bgs_[0-9a-f]{20}$/;
|
|
62
|
+
const DEFAULT_POLL_MS = 250;
|
|
63
|
+
/**
|
|
64
|
+
* A cached projection survives unchanged renders. Host notifications invalidate
|
|
65
|
+
* it immediately; this bound only recovers changes whose notification was lost
|
|
66
|
+
* or came from a process this host never observed. It is not a render cadence.
|
|
67
|
+
*/
|
|
68
|
+
const DURABLE_PROJECTION_CACHE_MS = 5_000;
|
|
69
|
+
function normalizeRunPolicy(value) {
|
|
70
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
71
|
+
throw new Error("register-run requires a policy object.");
|
|
72
|
+
const policy = value;
|
|
73
|
+
if (policy.version !== 1)
|
|
74
|
+
throw new Error("register-run requires policy version 1.");
|
|
75
|
+
if (typeof policy.workspace !== "string" || !policy.workspace)
|
|
76
|
+
throw new Error("register-run policy.workspace is required.");
|
|
77
|
+
if (typeof policy.authorityReference !== "string" || !policy.authorityReference) {
|
|
78
|
+
throw new Error("register-run policy.authorityReference is required.");
|
|
79
|
+
}
|
|
80
|
+
const sandbox = policy.sandbox === null || policy.sandbox === undefined
|
|
81
|
+
? null
|
|
82
|
+
: policy.sandbox;
|
|
83
|
+
if (sandbox !== null && (typeof sandbox !== "object" || typeof sandbox.root !== "string")) {
|
|
84
|
+
throw new Error("register-run policy.sandbox must be null or a worker sandbox authority.");
|
|
85
|
+
}
|
|
86
|
+
const tools = Array.isArray(policy.tools)
|
|
87
|
+
? policy.tools.filter((tool) => typeof tool === "string")
|
|
88
|
+
: [];
|
|
89
|
+
return Object.freeze({
|
|
90
|
+
version: 1,
|
|
91
|
+
sandbox,
|
|
92
|
+
tools: Object.freeze(tools),
|
|
93
|
+
clean: policy.clean === true,
|
|
94
|
+
deadlineAt: typeof policy.deadlineAt === "number" && Number.isFinite(policy.deadlineAt) ? policy.deadlineAt : null,
|
|
95
|
+
authorityReference: policy.authorityReference,
|
|
96
|
+
workspace: policy.workspace,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
function normalizeRpcOwner(value, fallback) {
|
|
100
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
101
|
+
return fallback;
|
|
102
|
+
const owner = value;
|
|
103
|
+
if (typeof owner.sessionId !== "string" || typeof owner.workspace !== "string")
|
|
104
|
+
return fallback;
|
|
105
|
+
return {
|
|
106
|
+
kind: "worker-conversation",
|
|
107
|
+
sessionId: owner.sessionId,
|
|
108
|
+
workspace: owner.workspace,
|
|
109
|
+
branchId: typeof owner.branchId === "string" ? owner.branchId : null,
|
|
110
|
+
goalId: typeof owner.goalId === "string" ? owner.goalId : null,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function rpcCode(error) {
|
|
114
|
+
const code = error?.code;
|
|
115
|
+
return typeof code === "string" && code.length > 0 ? code : "refused";
|
|
116
|
+
}
|
|
117
|
+
function eventBusOf(pi) {
|
|
118
|
+
const events = pi?.events;
|
|
119
|
+
if (!events || typeof events !== "object")
|
|
120
|
+
return undefined;
|
|
121
|
+
const candidate = events;
|
|
122
|
+
if (typeof candidate.on !== "function" || typeof candidate.emit !== "function")
|
|
123
|
+
return undefined;
|
|
124
|
+
return candidate;
|
|
125
|
+
}
|
|
126
|
+
function isService(value) {
|
|
127
|
+
return !!value && typeof value === "object"
|
|
128
|
+
&& value.version === OBSERVED_WAITS_SERVICE_VERSION
|
|
129
|
+
&& value.available === true
|
|
130
|
+
&& typeof value.launchForWorker === "function";
|
|
131
|
+
}
|
|
132
|
+
const serviceMirrors = new WeakMap();
|
|
133
|
+
const serviceErrors = new WeakMap();
|
|
134
|
+
function observeServiceChannel(pi) {
|
|
135
|
+
const events = eventBusOf(pi);
|
|
136
|
+
if (!events || serviceMirrors.has(events))
|
|
137
|
+
return events;
|
|
138
|
+
serviceMirrors.set(events, undefined);
|
|
139
|
+
events.on(OBSERVED_WAITS_SERVICE_CHANNEL, (data) => {
|
|
140
|
+
if (isService(data)) {
|
|
141
|
+
serviceMirrors.set(events, data);
|
|
142
|
+
serviceErrors.delete(events);
|
|
143
|
+
}
|
|
144
|
+
else if (data && typeof data === "object"
|
|
145
|
+
&& data.version === OBSERVED_WAITS_SERVICE_VERSION
|
|
146
|
+
&& data.available === false) {
|
|
147
|
+
serviceMirrors.set(events, undefined);
|
|
148
|
+
const reason = data.reason;
|
|
149
|
+
serviceErrors.set(events, typeof reason === "string" ? reason : "observed waits are unavailable");
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
return events;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Ask for the Background operation service. Pi's bus dispatches synchronously,
|
|
156
|
+
* so a host that is already running answers before this returns. Returns
|
|
157
|
+
* `undefined` when this package is installed alone or the host is closed.
|
|
158
|
+
*/
|
|
159
|
+
export function getObservedWaitService(pi) {
|
|
160
|
+
const events = observeServiceChannel(pi);
|
|
161
|
+
if (!events)
|
|
162
|
+
return undefined;
|
|
163
|
+
events.emit(OBSERVED_WAITS_SERVICE_REQUEST_CHANNEL, { version: OBSERVED_WAITS_SERVICE_VERSION });
|
|
164
|
+
return serviceMirrors.get(events);
|
|
165
|
+
}
|
|
166
|
+
/** Why a service request returned nothing, when a host refused to open. */
|
|
167
|
+
export function observedWaitServiceUnavailableReason(pi) {
|
|
168
|
+
observeServiceChannel(pi);
|
|
169
|
+
const events = eventBusOf(pi);
|
|
170
|
+
return events ? serviceErrors.get(events) : undefined;
|
|
171
|
+
}
|
|
172
|
+
export function createObservedWaitHost(pi, options = {}) {
|
|
173
|
+
const existing = getObservedWaitHost(pi);
|
|
174
|
+
if (existing && existing !== undefined)
|
|
175
|
+
existing.close();
|
|
176
|
+
const host = new ObservedWaitHost(pi, options);
|
|
177
|
+
registerObservedWaitClient(pi, host);
|
|
178
|
+
return host;
|
|
179
|
+
}
|
|
180
|
+
function branchIdsOf(ctx) {
|
|
181
|
+
try {
|
|
182
|
+
const branch = ctx.sessionManager?.getBranch?.();
|
|
183
|
+
if (!branch)
|
|
184
|
+
return [];
|
|
185
|
+
return branch.map((entry) => entry?.id).filter((id) => typeof id === "string");
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
return [];
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
function startTokenDigest(token) {
|
|
192
|
+
return token ? createHash("sha256").update(token, "utf8").digest("hex").slice(0, 16) : "unknown";
|
|
193
|
+
}
|
|
194
|
+
function parseHostIdentity(hostId) {
|
|
195
|
+
const parts = hostId.split(":");
|
|
196
|
+
const pid = Number(parts[0]);
|
|
197
|
+
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
198
|
+
return {};
|
|
199
|
+
// New format: pid:startTokenDigest:instance. A legacy pid:instance claim has
|
|
200
|
+
// no process-instance identity and is therefore treated as unknown, not dead.
|
|
201
|
+
if (parts.length < 3)
|
|
202
|
+
return { pid };
|
|
203
|
+
let digest = parts[1] || undefined;
|
|
204
|
+
if (digest === "unknown")
|
|
205
|
+
return { pid };
|
|
206
|
+
if (digest && !/^[0-9a-f]{16}$/.test(digest)) {
|
|
207
|
+
// Tolerate an older/raw URL-encoded token form without putting its spaces or
|
|
208
|
+
// percent escapes into a durable ID field.
|
|
209
|
+
try {
|
|
210
|
+
digest = startTokenDigest(decodeURIComponent(digest));
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
digest = undefined;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return { pid, ...(digest ? { startTokenDigest: digest } : {}) };
|
|
217
|
+
}
|
|
218
|
+
function oneLine(value, max = 300) {
|
|
219
|
+
const text = String(value).replace(/\s+/g, " ").trim();
|
|
220
|
+
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
221
|
+
}
|
|
222
|
+
function ownerKey(owner) {
|
|
223
|
+
return [owner.kind, owner.sessionId, owner.workspace, owner.branchId ?? "", owner.goalId ?? ""].join("\u0000");
|
|
224
|
+
}
|
|
225
|
+
function sameOwner(a, b) {
|
|
226
|
+
return ownerKey(a) === ownerKey(b);
|
|
227
|
+
}
|
|
228
|
+
function ownerMatchesOperation(operation, owner) {
|
|
229
|
+
// The execution identity is the session (or conversation) plus workspace. The
|
|
230
|
+
// branch anchor decides which continuation may resume; it must not hide a
|
|
231
|
+
// task from its own session after the branch advances.
|
|
232
|
+
return operation.owner.kind === owner.kind
|
|
233
|
+
&& operation.owner.sessionId === owner.sessionId
|
|
234
|
+
&& operation.owner.workspace === owner.workspace;
|
|
235
|
+
}
|
|
236
|
+
function authorityReference(seed) {
|
|
237
|
+
return `authority:local:${createHash("sha256").update(seed, "utf8").digest("hex").slice(0, 32)}`;
|
|
238
|
+
}
|
|
239
|
+
function defaultStorePath() {
|
|
240
|
+
const agentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
|
|
241
|
+
return join(agentDir, "operation-coordinator.sqlite");
|
|
242
|
+
}
|
|
243
|
+
function tail(path, maxBytes = 64 * 1024) {
|
|
244
|
+
let fd;
|
|
245
|
+
try {
|
|
246
|
+
if (!existsSync(path))
|
|
247
|
+
return { text: "", truncated: false };
|
|
248
|
+
fd = openSync(path, "r");
|
|
249
|
+
const size = fstatSync(fd).size;
|
|
250
|
+
const start = Math.max(0, size - maxBytes);
|
|
251
|
+
const length = Math.min(maxBytes, size - start);
|
|
252
|
+
const buffer = Buffer.alloc(length);
|
|
253
|
+
if (length > 0)
|
|
254
|
+
readSync(fd, buffer, 0, length, start);
|
|
255
|
+
return { text: buffer.toString("utf8"), truncated: start > 0 };
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
return { text: "", truncated: false };
|
|
259
|
+
}
|
|
260
|
+
finally {
|
|
261
|
+
if (fd !== undefined) {
|
|
262
|
+
try {
|
|
263
|
+
closeSync(fd);
|
|
264
|
+
}
|
|
265
|
+
catch { /* already closed */ }
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
function lastLines(text, lines) {
|
|
270
|
+
if (lines <= 0)
|
|
271
|
+
return "";
|
|
272
|
+
const split = text.split(/\r?\n/);
|
|
273
|
+
if (split.length > 0 && split[split.length - 1] === "")
|
|
274
|
+
split.pop();
|
|
275
|
+
return split.slice(-lines).join("\n");
|
|
276
|
+
}
|
|
277
|
+
function terminalOutcome(status) {
|
|
278
|
+
switch (status) {
|
|
279
|
+
case "succeeded": return "succeeded";
|
|
280
|
+
case "cancelled": return "cancelled";
|
|
281
|
+
case "lost": return "lost";
|
|
282
|
+
default: return "failed";
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
function supervisionReasonFields(inspection) {
|
|
286
|
+
const reason = inspection?.result?.reason ?? inspection?.lost?.reason;
|
|
287
|
+
const cleanup = inspection?.result?.groupCleanup === "unproven"
|
|
288
|
+
? "Process-group cleanup is unproven; descendants may remain running."
|
|
289
|
+
: undefined;
|
|
290
|
+
const text = [reason, cleanup].filter(Boolean).join("; ");
|
|
291
|
+
return text ? { reason: oneLine(text) } : {};
|
|
292
|
+
}
|
|
293
|
+
function evidenceFor(inspection) {
|
|
294
|
+
const paths = inspection.logs;
|
|
295
|
+
const evidence = [];
|
|
296
|
+
const result = inspection.result;
|
|
297
|
+
const lost = inspection.lost;
|
|
298
|
+
const terminalRef = result ? "result.json" : "lost.json";
|
|
299
|
+
const summary = result
|
|
300
|
+
? `status=${result.status} exit=${result.exitCode ?? "null"} timedOut=${result.timedOut ? "true" : "false"}${result.groupCleanup ? ` groupCleanup=${result.groupCleanup}` : ""}`
|
|
301
|
+
: `status=lost detailLost=true`;
|
|
302
|
+
evidence.push({
|
|
303
|
+
operationId: "",
|
|
304
|
+
terminalRevision: 0,
|
|
305
|
+
kind: "terminal-record",
|
|
306
|
+
ref: terminalRef,
|
|
307
|
+
summary,
|
|
308
|
+
detailLost: !result,
|
|
309
|
+
});
|
|
310
|
+
for (const [label, path] of [["stdout", paths.stdout], ["stderr", paths.stderr]]) {
|
|
311
|
+
try {
|
|
312
|
+
const size = existsSync(path) ? statSync(path).size : 0;
|
|
313
|
+
if (size <= 0)
|
|
314
|
+
continue;
|
|
315
|
+
evidence.push({
|
|
316
|
+
operationId: "",
|
|
317
|
+
terminalRevision: 0,
|
|
318
|
+
kind: "log",
|
|
319
|
+
ref: path,
|
|
320
|
+
summary: `${label} retained (${size} bytes)`,
|
|
321
|
+
detailLost: false,
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
catch { /* a reclaimed log costs detail, never the outcome */ }
|
|
325
|
+
}
|
|
326
|
+
return evidence;
|
|
327
|
+
}
|
|
328
|
+
function mapEvidence(operationId, taskId, records, revision) {
|
|
329
|
+
return records.map((entry) => ({
|
|
330
|
+
operationId: "operationId" in entry ? entry.operationId || operationId : operationId,
|
|
331
|
+
...(taskId ? { taskId } : {}),
|
|
332
|
+
terminalRevision: "terminalRevision" in entry ? entry.terminalRevision || revision : revision,
|
|
333
|
+
kind: entry.kind,
|
|
334
|
+
ref: entry.ref,
|
|
335
|
+
...(entry.summary ? { summary: entry.summary } : {}),
|
|
336
|
+
detailLost: entry.detailLost,
|
|
337
|
+
}));
|
|
338
|
+
}
|
|
339
|
+
/** Shared terminal publication contract for the host and fixed server cancel adapter. */
|
|
340
|
+
export function supervisorTerminalPublication(operation, inspection, refs = evidenceFor(inspection)) {
|
|
341
|
+
const status = inspection.status;
|
|
342
|
+
const outcome = terminalOutcome(status);
|
|
343
|
+
return {
|
|
344
|
+
operationId: operation.operationId,
|
|
345
|
+
eventId: `${operation.taskId}:${inspection.result?.endedAt ?? inspection.lost?.recordedAt ?? inspection.observedAt}:${status}`,
|
|
346
|
+
outcome, owner: operation.owner,
|
|
347
|
+
evidence: refs.map(ref => ({ kind: ref.kind, ref: ref.ref, ...(ref.summary ? { summary: ref.summary } : {}), detailLost: ref.detailLost })),
|
|
348
|
+
...(outcome === "lost" ? { detailLost: true } : {}),
|
|
349
|
+
reason: inspection.result ? `supervisor ${status} exit=${inspection.result.exitCode ?? "null"}` : "supervisor lost: no terminal evidence",
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
export class ObservedWaitHost {
|
|
353
|
+
pi;
|
|
354
|
+
service;
|
|
355
|
+
store;
|
|
356
|
+
supervisor;
|
|
357
|
+
directory;
|
|
358
|
+
storePath;
|
|
359
|
+
discoveryScope;
|
|
360
|
+
pollMs;
|
|
361
|
+
options;
|
|
362
|
+
timer;
|
|
363
|
+
changeWatcher;
|
|
364
|
+
changeRepair;
|
|
365
|
+
changePosition;
|
|
366
|
+
changeScheduled = false;
|
|
367
|
+
managedDirty = false;
|
|
368
|
+
managedAfter = 0;
|
|
369
|
+
observeManagedChanges() {
|
|
370
|
+
const schedule = () => {
|
|
371
|
+
if (this.closed || this.changeScheduled)
|
|
372
|
+
return;
|
|
373
|
+
this.changeScheduled = true;
|
|
374
|
+
setImmediate(() => {
|
|
375
|
+
this.changeScheduled = false;
|
|
376
|
+
if (this.closed || !this.store)
|
|
377
|
+
return;
|
|
378
|
+
try {
|
|
379
|
+
const page = this.store.resultSupervisionChanges(this.changePosition);
|
|
380
|
+
const changed = page.reset || page.seq !== this.changePosition?.seq;
|
|
381
|
+
this.changePosition = { generation: page.generation, seq: page.seq };
|
|
382
|
+
this.managedDirty ||= changed;
|
|
383
|
+
if (this.managedDirty && Date.now() >= this.managedAfter) {
|
|
384
|
+
this.managedDirty = false;
|
|
385
|
+
this.managedAfter = Date.now() + 1000;
|
|
386
|
+
void this.reconcileNow();
|
|
387
|
+
}
|
|
388
|
+
if (page.more)
|
|
389
|
+
schedule();
|
|
390
|
+
}
|
|
391
|
+
catch { /* Existing authority remains unchanged; the bounded feed repair retries. */ }
|
|
392
|
+
});
|
|
393
|
+
};
|
|
394
|
+
this.changeWatcher = watch(dirname(this.storePath), (_event, file) => {
|
|
395
|
+
if (!file || String(file).startsWith("operation-coordinator.sqlite"))
|
|
396
|
+
schedule();
|
|
397
|
+
});
|
|
398
|
+
this.changeWatcher.on("error", () => { this.changeWatcher?.close(); this.changeWatcher = undefined; });
|
|
399
|
+
const repair = () => {
|
|
400
|
+
if (this.closed)
|
|
401
|
+
return;
|
|
402
|
+
schedule();
|
|
403
|
+
this.changeRepair = setTimeout(repair, 1000);
|
|
404
|
+
this.changeRepair.unref();
|
|
405
|
+
};
|
|
406
|
+
repair();
|
|
407
|
+
}
|
|
408
|
+
closed = false;
|
|
409
|
+
activationAttempted = false;
|
|
410
|
+
unavailableReason;
|
|
411
|
+
parentOrigin;
|
|
412
|
+
activeOrigin;
|
|
413
|
+
/**
|
|
414
|
+
* The live extension context for the active session. Branch eligibility is
|
|
415
|
+
* read from this context on every check; the SDK can settle/reload session
|
|
416
|
+
* history after session_start, so a start-time branch snapshot is stale.
|
|
417
|
+
*/
|
|
418
|
+
activeContext;
|
|
419
|
+
/** A new session/workspace context needs one seed scan of terminal callbacks. */
|
|
420
|
+
terminalRecoveryNeeded = false;
|
|
421
|
+
/** Terminal callbacks awaiting their exact batcher handoff. */
|
|
422
|
+
pendingTerminalCallbacks = new Set();
|
|
423
|
+
/** Running operations this host observed; a transition out of running can need recovery. */
|
|
424
|
+
watchedRunningTasks = new Set();
|
|
425
|
+
/** Durable sidecars discovered in this supervisor directory. */
|
|
426
|
+
discoveredTaskSidecars = new Set();
|
|
427
|
+
durableProjectionCache;
|
|
428
|
+
projectionMetrics = {
|
|
429
|
+
listCalls: 0,
|
|
430
|
+
queries: 0,
|
|
431
|
+
rowsRead: 0,
|
|
432
|
+
projectionsBuilt: 0,
|
|
433
|
+
cacheHits: 0,
|
|
434
|
+
};
|
|
435
|
+
continuation;
|
|
436
|
+
continuationError;
|
|
437
|
+
launches = new Map();
|
|
438
|
+
localCancels = new Set();
|
|
439
|
+
assignmentCleanupCursor;
|
|
440
|
+
resultHandoffs = new Set();
|
|
441
|
+
rpcRuns = new Map();
|
|
442
|
+
waitOwners = new Map();
|
|
443
|
+
stagedCheckpoints = new Map();
|
|
444
|
+
branchAnchors = new Map();
|
|
445
|
+
durableChangeListeners = new Set();
|
|
446
|
+
serviceId = `bg-observed-${randomUUID()}`;
|
|
447
|
+
/** Opaque, validation-safe process-instance identity: pid + hashed start token. */
|
|
448
|
+
hostStartDigest = startTokenDigest(currentProcessStartToken());
|
|
449
|
+
hostId = `${process.pid}:${this.hostStartDigest}:${randomUUID()}`;
|
|
450
|
+
hostGeneration = ++HOST_INSTANCE_STATE.next;
|
|
451
|
+
discoveryToken;
|
|
452
|
+
discoveryRole;
|
|
453
|
+
reconcileInFlight;
|
|
454
|
+
reconcileScope;
|
|
455
|
+
authorityPassCache;
|
|
456
|
+
/** Running operations this follower is currently assigned to supervise. */
|
|
457
|
+
followerRunningTasks = new Set();
|
|
458
|
+
unscopedCallbackRecovery = { revision: -1, branch: "", delivery: undefined, claims: undefined };
|
|
459
|
+
callbackRecoveryScopes = new Map();
|
|
460
|
+
recoveryScopeState() {
|
|
461
|
+
if (!this.activeOrigin)
|
|
462
|
+
return this.unscopedCallbackRecovery;
|
|
463
|
+
// Concurrent foregrounds can retain different branch snapshots of one session.
|
|
464
|
+
const key = JSON.stringify([this.activeOrigin.cwd, this.activeOrigin.sessionId, branchIdsOf(this.activeContext)]);
|
|
465
|
+
let state = this.callbackRecoveryScopes.get(key);
|
|
466
|
+
if (!state) {
|
|
467
|
+
if (this.callbackRecoveryScopes.size >= 128)
|
|
468
|
+
this.callbackRecoveryScopes.delete(this.callbackRecoveryScopes.keys().next().value);
|
|
469
|
+
state = { revision: -1, branch: "" };
|
|
470
|
+
this.callbackRecoveryScopes.set(key, state);
|
|
471
|
+
}
|
|
472
|
+
return state;
|
|
473
|
+
}
|
|
474
|
+
get lastChangeRevision() { return this.recoveryScopeState().revision; }
|
|
475
|
+
set lastChangeRevision(value) { this.recoveryScopeState().revision = value; }
|
|
476
|
+
get pendingCallbackCursor() { return this.recoveryScopeState().delivery; }
|
|
477
|
+
set pendingCallbackCursor(value) { this.recoveryScopeState().delivery = value; }
|
|
478
|
+
get pendingClaimCursor() { return this.recoveryScopeState().claims; }
|
|
479
|
+
set pendingClaimCursor(value) { this.recoveryScopeState().claims = value; }
|
|
480
|
+
get activeBranchSignature() { return this.recoveryScopeState().branch; }
|
|
481
|
+
set activeBranchSignature(value) { this.recoveryScopeState().branch = value; }
|
|
482
|
+
lastOwnedTerminalAt = 0;
|
|
483
|
+
constructor(pi, options = {}) {
|
|
484
|
+
this.pi = pi;
|
|
485
|
+
this.options = options;
|
|
486
|
+
this.directory = options.supervisorDirectory ?? defaultSupervisorDirectory();
|
|
487
|
+
this.storePath = options.storePath ?? defaultStorePath();
|
|
488
|
+
this.discoveryScope = createHash("sha256")
|
|
489
|
+
.update(`${resolve(this.storePath)}\0${resolve(this.directory)}`)
|
|
490
|
+
.digest("hex");
|
|
491
|
+
this.supervisor = options.supervisor ?? createLocalSupervisor({ directory: this.directory });
|
|
492
|
+
this.pollMs = options.pollMs ?? DEFAULT_POLL_MS;
|
|
493
|
+
const base = {
|
|
494
|
+
assignmentContinuation: 1,
|
|
495
|
+
outageReconciliation: 1,
|
|
496
|
+
version: OBSERVED_WAITS_SERVICE_VERSION,
|
|
497
|
+
serviceId: this.serviceId,
|
|
498
|
+
available: true,
|
|
499
|
+
ownsTask: (run, taskId) => this.ownsTask(run, taskId),
|
|
500
|
+
launchForWorker: (run, input) => this.launchForWorker(run, input),
|
|
501
|
+
statusForWorker: (run, taskId) => this.statusForWorker(run, taskId),
|
|
502
|
+
logForWorker: (run, taskId, logOptions) => this.logForWorker(run, taskId, logOptions),
|
|
503
|
+
stopForWorker: (run, taskId) => this.stopForWorker(run, taskId),
|
|
504
|
+
registerWorkerWait: (run, input) => this.registerWorkerWait(run, input),
|
|
505
|
+
checkpointWorkerWait: (run, input) => this.checkpointWorkerWait(run, input),
|
|
506
|
+
failWorkerPark: (run, input) => this.failWorkerPark(run, input),
|
|
507
|
+
readEvidence: (run, input) => this.readEvidence(run, input),
|
|
508
|
+
acknowledgeForWorker: (run, input) => this.acknowledgeForWorker(run, input),
|
|
509
|
+
claimResumeForWorker: (run, input) => this.claimResumeForWorker(run, input),
|
|
510
|
+
publishResumeForWorker: (run, input) => this.publishResumeForWorker(run, input),
|
|
511
|
+
releaseResumeForWorker: (run, input) => this.releaseResumeForWorker(run, input),
|
|
512
|
+
holdFailedResumeForWorker: (run, input) => this.holdFailedResumeForWorker(run, input),
|
|
513
|
+
repairFailedResumeForWorker: (run, input) => {
|
|
514
|
+
this.ownedWait(this.workerOwner(run), input.waitId, input.generation);
|
|
515
|
+
return this.requireStore().repairFailedResume(input);
|
|
516
|
+
},
|
|
517
|
+
listWorkerWaits: (run, listOptions) => this.listWorkerWaits(run, listOptions),
|
|
518
|
+
cancelWorkerWait: (run, input) => this.cancelWorkerWait(run, input),
|
|
519
|
+
registerContinuationAdapter: (adapter) => this.registerContinuationAdapter(adapter),
|
|
520
|
+
unregisterContinuationAdapter: (id) => this.unregisterContinuationAdapter(id),
|
|
521
|
+
};
|
|
522
|
+
Object.defineProperty(base, "continuationReady", {
|
|
523
|
+
enumerable: true,
|
|
524
|
+
get: () => this.continuation !== undefined || this.rpcRuns.size > 0,
|
|
525
|
+
});
|
|
526
|
+
HOST_INSTANCE_STATE.generations.set(this.hostId, this.hostGeneration);
|
|
527
|
+
this.service = Object.freeze(base);
|
|
528
|
+
this.listenForServiceRequests();
|
|
529
|
+
this.listenForWorkerRequests();
|
|
530
|
+
// Announce the capability object at extension load so a Subagents probe does
|
|
531
|
+
// not depend on handler order. The store opens on session activation or on
|
|
532
|
+
// the first operation, and a failure replaces this with an unavailable
|
|
533
|
+
// capability instead of pretending to be durable.
|
|
534
|
+
this.announce();
|
|
535
|
+
}
|
|
536
|
+
get available() {
|
|
537
|
+
return this.store !== undefined && !this.closed;
|
|
538
|
+
}
|
|
539
|
+
get usesServerResults() { return this.options.serverOwnedResults === true; }
|
|
540
|
+
get hasActivated() { return this.activationAttempted; }
|
|
541
|
+
/** Ready worker continuations can advance; held decisions and unread results cannot. */
|
|
542
|
+
advancingWaits() {
|
|
543
|
+
if (!this.store || !this.continuation)
|
|
544
|
+
return [];
|
|
545
|
+
return this.store.listWaits({ phase: ["ready", "resuming"], pendingOnly: true })
|
|
546
|
+
.filter(wait => wait.owner.kind === "worker-conversation")
|
|
547
|
+
.map(wait => ({ kind: "advancing-wait", id: wait.waitId, generation: wait.generation, owner: wait.owner,
|
|
548
|
+
lastProgressAt: wait.updatedAt, nextDeadline: wait.updatedAt + (this.options.verificationMs ?? 30000), recovery: "captured-worker-continuation" }))
|
|
549
|
+
.filter(wait => wait.nextDeadline > Date.now());
|
|
550
|
+
}
|
|
551
|
+
get reason() {
|
|
552
|
+
return this.unavailableReason;
|
|
553
|
+
}
|
|
554
|
+
/** Open the durable store and begin bounded reconciliation. */
|
|
555
|
+
start(ctx) {
|
|
556
|
+
this.activationAttempted = true;
|
|
557
|
+
if (ctx)
|
|
558
|
+
this.setActiveOrigin(ctx);
|
|
559
|
+
if (this.store) {
|
|
560
|
+
// The same host instance can be activated for another session without a
|
|
561
|
+
// reload. Re-evaluate pending deliveries against the new active origin.
|
|
562
|
+
this.recoverAbandonedDeliveries();
|
|
563
|
+
void this.reconcileNow();
|
|
564
|
+
this.recoverTerminalNotifications();
|
|
565
|
+
this.terminalRecoveryNeeded = false;
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
// session_before_switch closes the store, and the same extension instance
|
|
569
|
+
// handles the next session_start. A real unload is followed by no start.
|
|
570
|
+
this.closed = false;
|
|
571
|
+
this.unavailableReason = undefined;
|
|
572
|
+
try {
|
|
573
|
+
this.store = this.options.sharedStore ?? openStore({
|
|
574
|
+
path: this.storePath,
|
|
575
|
+
...(this.options.now ? { now: this.options.now } : {}),
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
catch (error) {
|
|
579
|
+
this.unavailableReason = oneLine(error instanceof Error ? error.message : String(error), 300);
|
|
580
|
+
this.announceUnavailable(this.unavailableReason);
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
if (HOST_INSTANCE_STATE.closed.delete(this.hostId)) {
|
|
584
|
+
// Reactivation is newer than instances created while this host was closed.
|
|
585
|
+
this.hostGeneration = ++HOST_INSTANCE_STATE.next;
|
|
586
|
+
HOST_INSTANCE_STATE.generations.set(this.hostId, this.hostGeneration);
|
|
587
|
+
}
|
|
588
|
+
this.announce();
|
|
589
|
+
this.writeHostDebug();
|
|
590
|
+
this.recoverAbandonedDeliveries();
|
|
591
|
+
void this.reconcileNow();
|
|
592
|
+
this.recoverTerminalNotifications();
|
|
593
|
+
this.terminalRecoveryNeeded = false;
|
|
594
|
+
if (this.options.serverOwnedResults && this.options.sharedStore) {
|
|
595
|
+
this.observeManagedChanges();
|
|
596
|
+
}
|
|
597
|
+
else if (this.pollMs > 0) {
|
|
598
|
+
this.timer = setInterval(() => { void this.reconcileNow(); }, this.pollMs);
|
|
599
|
+
this.timer.unref?.();
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
close() {
|
|
603
|
+
if (this.closed)
|
|
604
|
+
return;
|
|
605
|
+
this.closed = true;
|
|
606
|
+
HOST_INSTANCE_STATE.closed.add(this.hostId);
|
|
607
|
+
if (this.timer)
|
|
608
|
+
clearInterval(this.timer);
|
|
609
|
+
this.changeWatcher?.close();
|
|
610
|
+
this.changeWatcher = undefined;
|
|
611
|
+
if (this.changeRepair)
|
|
612
|
+
clearTimeout(this.changeRepair);
|
|
613
|
+
this.changeRepair = undefined;
|
|
614
|
+
this.changePosition = undefined;
|
|
615
|
+
this.timer = undefined;
|
|
616
|
+
this.releaseDiscoveryAuthority();
|
|
617
|
+
this.releaseSupervisionAuthority();
|
|
618
|
+
try {
|
|
619
|
+
if (!this.options.sharedStore)
|
|
620
|
+
this.store?.close();
|
|
621
|
+
}
|
|
622
|
+
catch { /* already closed */ }
|
|
623
|
+
this.store = undefined;
|
|
624
|
+
this.launches.clear();
|
|
625
|
+
this.rpcRuns.clear();
|
|
626
|
+
this.waitOwners.clear();
|
|
627
|
+
this.stagedCheckpoints.clear();
|
|
628
|
+
this.branchAnchors.clear();
|
|
629
|
+
this.activeOrigin = undefined;
|
|
630
|
+
this.activeContext = undefined;
|
|
631
|
+
this.terminalRecoveryNeeded = false;
|
|
632
|
+
this.pendingTerminalCallbacks.clear();
|
|
633
|
+
this.callbackRecoveryScopes.clear();
|
|
634
|
+
this.watchedRunningTasks.clear();
|
|
635
|
+
this.discoveredTaskSidecars.clear();
|
|
636
|
+
this.durableProjectionCache = undefined;
|
|
637
|
+
this.writeHostDebug();
|
|
638
|
+
this.announceUnavailable("the Background operation host closed");
|
|
639
|
+
}
|
|
640
|
+
/** Recover a callback a previous host recorded terminal but never delivered. */
|
|
641
|
+
recoverTerminalNotifications() {
|
|
642
|
+
if (!this.store)
|
|
643
|
+
return;
|
|
644
|
+
for (const operation of this.activeParentTerminalOperations()) {
|
|
645
|
+
if (operation.terminalOutcome === null)
|
|
646
|
+
continue;
|
|
647
|
+
this.attemptTerminalCallback(operation, this.statusOf(operation.operationId), operation.terminalOutcome, []);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
activeParentTerminalOperations(claims = false) {
|
|
651
|
+
const origin = this.activeOrigin;
|
|
652
|
+
if (!this.store || !origin?.sessionId)
|
|
653
|
+
return [];
|
|
654
|
+
const page = this.store.listPendingParentCallbacks({ sessionId: origin.sessionId, workspace: origin.cwd }, { after: claims ? this.pendingClaimCursor : this.pendingCallbackCursor, limit: 256 });
|
|
655
|
+
const next = page.length === 256 ? page.at(-1).operationId : undefined;
|
|
656
|
+
if (claims)
|
|
657
|
+
this.pendingClaimCursor = next;
|
|
658
|
+
else
|
|
659
|
+
this.pendingCallbackCursor = next;
|
|
660
|
+
return page;
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* Discover durable tasks launched by any host sharing this supervisor
|
|
664
|
+
* directory. A host that started before a task was registered never saw it in
|
|
665
|
+
* the running set; terminal discovery must not depend on that observation.
|
|
666
|
+
* This is a bounded directory listing plus new-sidecar lookup, not a scan of
|
|
667
|
+
* historical terminal rows on every tick.
|
|
668
|
+
*/
|
|
669
|
+
discoverObservedTasks() {
|
|
670
|
+
const store = this.store;
|
|
671
|
+
if (!store)
|
|
672
|
+
return;
|
|
673
|
+
let names;
|
|
674
|
+
try {
|
|
675
|
+
names = readdirSync(join(this.directory, "observed"));
|
|
676
|
+
}
|
|
677
|
+
catch {
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
let visibleOwner;
|
|
681
|
+
for (const name of names) {
|
|
682
|
+
if (!name.endsWith(".json") || name === "host.json")
|
|
683
|
+
continue;
|
|
684
|
+
const taskId = name.slice(0, -5);
|
|
685
|
+
if (!LOCAL_DURABLE_ID.test(taskId) || this.discoveredTaskSidecars.has(taskId))
|
|
686
|
+
continue;
|
|
687
|
+
const operation = this.operationForTask(taskId);
|
|
688
|
+
if (!operation)
|
|
689
|
+
continue; // registration may land on the next tick
|
|
690
|
+
this.discoveredTaskSidecars.add(taskId);
|
|
691
|
+
if (this.activeOwnerRelation(operation.owner) === "match")
|
|
692
|
+
visibleOwner = operation.owner;
|
|
693
|
+
if (operation.terminalRevision > 0) {
|
|
694
|
+
this.attemptTerminalCallback(operation, this.statusOf(operation.operationId), operation.terminalOutcome ?? "failed", [], { pendingWithoutContext: true });
|
|
695
|
+
}
|
|
696
|
+
else {
|
|
697
|
+
this.watchedRunningTasks.add(taskId);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
// A task launched by another Pi process became visible in this host's
|
|
701
|
+
// supervisor directory. The navigator must refresh without waiting for a
|
|
702
|
+
// render to rediscover it, and its cached projections are now stale.
|
|
703
|
+
if (visibleOwner)
|
|
704
|
+
this.emitDurableTaskChange(visibleOwner);
|
|
705
|
+
}
|
|
706
|
+
/**
|
|
707
|
+
* Retry only terminal callbacks that are still awaiting an exact handoff. The
|
|
708
|
+
* pending set is seeded once at activation and by each terminal attempt; it is
|
|
709
|
+
* not a scan of the historical terminal table on every 250 ms tick.
|
|
710
|
+
*/
|
|
711
|
+
hasPendingParentCallbackRecovery() { return this.lastChangeRevision < 0 || this.pendingCallbackCursor !== undefined || this.pendingClaimCursor !== undefined; }
|
|
712
|
+
rememberPendingCallback(taskId) {
|
|
713
|
+
if (!this.pendingTerminalCallbacks.has(taskId) && this.pendingTerminalCallbacks.size >= 256)
|
|
714
|
+
this.pendingTerminalCallbacks.delete(this.pendingTerminalCallbacks.values().next().value);
|
|
715
|
+
this.pendingTerminalCallbacks.add(taskId);
|
|
716
|
+
}
|
|
717
|
+
retryPendingTerminalCallbacks() {
|
|
718
|
+
if (!this.store || this.pendingTerminalCallbacks.size === 0)
|
|
719
|
+
return;
|
|
720
|
+
for (const taskId of [...this.pendingTerminalCallbacks].slice(0, 64)) {
|
|
721
|
+
this.pendingTerminalCallbacks.delete(taskId);
|
|
722
|
+
this.rememberPendingCallback(taskId);
|
|
723
|
+
const operation = this.operationForTask(taskId);
|
|
724
|
+
if (!operation || operation.terminalRevision === 0) {
|
|
725
|
+
this.pendingTerminalCallbacks.delete(taskId);
|
|
726
|
+
continue;
|
|
727
|
+
}
|
|
728
|
+
const context = this.launchContext(taskId);
|
|
729
|
+
if (!context || context.callback === false || context.callbackDeliveredAt !== undefined || !this.options.notifyParent) {
|
|
730
|
+
this.pendingTerminalCallbacks.delete(taskId);
|
|
731
|
+
continue;
|
|
732
|
+
}
|
|
733
|
+
if (!this.activeContext)
|
|
734
|
+
continue; // wait for an exact active owner
|
|
735
|
+
const relation = this.activeOwnerRelation(operation.owner);
|
|
736
|
+
if (relation === "unknown")
|
|
737
|
+
continue; // keep pending; never guess
|
|
738
|
+
if (relation === "foreign") {
|
|
739
|
+
this.pendingTerminalCallbacks.delete(taskId);
|
|
740
|
+
continue;
|
|
741
|
+
}
|
|
742
|
+
const waitPending = this.store.listWaits({ owner: operation.owner, pendingOnly: true })
|
|
743
|
+
.some((wait) => wait.dependencies.some((dep) => dep.operationId === operation.operationId));
|
|
744
|
+
if (waitPending) {
|
|
745
|
+
this.pendingTerminalCallbacks.delete(taskId);
|
|
746
|
+
continue;
|
|
747
|
+
}
|
|
748
|
+
this.attemptTerminalCallback(operation, this.statusOf(operation.operationId), operation.terminalOutcome ?? "failed", []);
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
/** A deterministic, awaitable reconciliation pass for tests and session activation. */
|
|
752
|
+
async reconcileNow() {
|
|
753
|
+
const scope = this.recoveryScopeState();
|
|
754
|
+
if (this.reconcileInFlight) {
|
|
755
|
+
const sameScope = this.reconcileScope === scope;
|
|
756
|
+
await this.reconcileInFlight;
|
|
757
|
+
// Startup or another foreground's pass cannot verify this scope's recovery.
|
|
758
|
+
if (!sameScope)
|
|
759
|
+
return this.reconcileNow();
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
const release = this.options.enterControl?.();
|
|
763
|
+
if (this.options.enterControl && !release) {
|
|
764
|
+
this.managedDirty = true;
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
this.reconcileScope = scope;
|
|
768
|
+
const pass = this.reconcilePass().finally(() => release?.());
|
|
769
|
+
this.reconcileInFlight = pass;
|
|
770
|
+
try {
|
|
771
|
+
await pass;
|
|
772
|
+
}
|
|
773
|
+
finally {
|
|
774
|
+
if (this.reconcileInFlight === pass) {
|
|
775
|
+
this.reconcileInFlight = undefined;
|
|
776
|
+
this.reconcileScope = undefined;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
async reconcilePass() {
|
|
781
|
+
if (!this.store || this.closed)
|
|
782
|
+
return;
|
|
783
|
+
this.authorityPassCache = new Map();
|
|
784
|
+
try {
|
|
785
|
+
const discovery = this.options.serverOwnedResults ? undefined : this.store.readDiscoveryState(this.discoveryScope);
|
|
786
|
+
if (this.options.serverOwnedResults || discovery?.managed) {
|
|
787
|
+
this.releaseDiscoveryAuthority();
|
|
788
|
+
if (!this.options.serverOwnedResults)
|
|
789
|
+
this.reconcileFollowerRunning();
|
|
790
|
+
this.reconcileOwnerChanges();
|
|
791
|
+
this.retryPendingTerminalCallbacks();
|
|
792
|
+
await this.dispatchOutbox();
|
|
793
|
+
return;
|
|
794
|
+
}
|
|
795
|
+
const role = this.refreshDiscoveryAuthority(discovery.claim);
|
|
796
|
+
this.noteDiscoveryRole(role);
|
|
797
|
+
if (role === "holder") {
|
|
798
|
+
this.discoverObservedTasks();
|
|
799
|
+
this.reconcileGlobalRunning();
|
|
800
|
+
if (discovery.hasAssignmentTasks)
|
|
801
|
+
await this.reconcileAssignmentCleanup();
|
|
802
|
+
}
|
|
803
|
+
else {
|
|
804
|
+
this.reconcileFollowerRunning();
|
|
805
|
+
this.reconcileOwnerChanges();
|
|
806
|
+
}
|
|
807
|
+
this.retryPendingTerminalCallbacks();
|
|
808
|
+
await this.dispatchOutbox();
|
|
809
|
+
}
|
|
810
|
+
finally {
|
|
811
|
+
this.authorityPassCache = undefined;
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
async reconcileAssignmentCleanup() {
|
|
815
|
+
const store = this.requireStore();
|
|
816
|
+
const [candidate] = store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor);
|
|
817
|
+
this.assignmentCleanupCursor = candidate?.operationId;
|
|
818
|
+
if (!candidate || candidate.resultManaged || this.supervisionAuthority(candidate) !== "self")
|
|
819
|
+
return;
|
|
820
|
+
const { taskId, launchToken } = candidate;
|
|
821
|
+
try {
|
|
822
|
+
const inspection = this.supervisor.snapshot(taskId);
|
|
823
|
+
const stop = readStopRequest(this.directory, taskId);
|
|
824
|
+
if (inspection?.token !== launchToken || (stop && stop.token !== launchToken))
|
|
825
|
+
return;
|
|
826
|
+
if (inspection.terminal) {
|
|
827
|
+
if (inspection.status !== "lost" && inspection.result?.groupCleanup !== "unproven")
|
|
828
|
+
return;
|
|
829
|
+
const pgid = inspection.command?.pgid ?? inspection.command?.pid;
|
|
830
|
+
if (inspection.cleanup?.groupEmpty === true || (pgid && !processGroupAlive(pgid))) {
|
|
831
|
+
store.verifyAssignmentCleanup(candidate.operationId, launchToken, candidate.terminalRevision);
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
if (!pgid)
|
|
835
|
+
return;
|
|
836
|
+
}
|
|
837
|
+
if (!this.localCancels.has(taskId)) {
|
|
838
|
+
this.localCancels.add(taskId);
|
|
839
|
+
try {
|
|
840
|
+
await this.supervisor.stop(taskId, { token: launchToken, reason: "owning assignment ended" });
|
|
841
|
+
}
|
|
842
|
+
finally {
|
|
843
|
+
this.localCancels.delete(taskId);
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
catch (error) {
|
|
848
|
+
this.options.logger?.(`Assignment cleanup for ${taskId}: ${String(error)}`);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
reconcileGlobalRunning() {
|
|
852
|
+
const store = this.store;
|
|
853
|
+
if (!store)
|
|
854
|
+
return;
|
|
855
|
+
const running = store.listOperations({ phase: "running" });
|
|
856
|
+
const runningIds = new Set(running.map((operation) => operation.taskId));
|
|
857
|
+
let changedOwner;
|
|
858
|
+
for (const taskId of [...this.watchedRunningTasks]) {
|
|
859
|
+
if (runningIds.has(taskId))
|
|
860
|
+
continue;
|
|
861
|
+
this.watchedRunningTasks.delete(taskId);
|
|
862
|
+
const operation = this.operationForTask(taskId);
|
|
863
|
+
if (operation && operation.terminalRevision > 0) {
|
|
864
|
+
if (this.activeOwnerRelation(operation.owner) === "match")
|
|
865
|
+
changedOwner = operation.owner;
|
|
866
|
+
// Another host may have recorded the terminal result without a live
|
|
867
|
+
// owner context. This host watched the operation, so recover its callback
|
|
868
|
+
// now that the active branch/identity can authorize the handoff.
|
|
869
|
+
this.attemptTerminalCallback(operation, this.statusOf(operation.operationId), operation.terminalOutcome ?? "failed", [], { pendingWithoutContext: true });
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
if (changedOwner)
|
|
873
|
+
this.emitDurableTaskChange(changedOwner);
|
|
874
|
+
for (const operation of running) {
|
|
875
|
+
this.watchedRunningTasks.add(operation.taskId);
|
|
876
|
+
this.reconcileOperation(operation);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
reconcileFollowerRunning() {
|
|
880
|
+
const store = this.store;
|
|
881
|
+
if (!store)
|
|
882
|
+
return;
|
|
883
|
+
const running = store.listRunningSupervisedBy(this.hostId);
|
|
884
|
+
const runningIds = new Set(running.map((operation) => operation.taskId));
|
|
885
|
+
for (const taskId of [...this.followerRunningTasks]) {
|
|
886
|
+
if (!runningIds.has(taskId))
|
|
887
|
+
this.followerRunningTasks.delete(taskId);
|
|
888
|
+
}
|
|
889
|
+
for (const operation of running) {
|
|
890
|
+
this.followerRunningTasks.add(operation.taskId);
|
|
891
|
+
this.reconcileOperation(operation);
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* A follower does not scan foreign operations. It refreshes the exact active
|
|
896
|
+
* owner's terminal records only when the shared change revision advances, so
|
|
897
|
+
* callback recovery stays correct without multiplying the running-set scan.
|
|
898
|
+
*/
|
|
899
|
+
reconcileOwnerChanges() {
|
|
900
|
+
const store = this.store;
|
|
901
|
+
const ctx = this.activeContext;
|
|
902
|
+
if (!store || !ctx)
|
|
903
|
+
return;
|
|
904
|
+
const sessionId = this.sessionIdIfAvailable(ctx);
|
|
905
|
+
if (!sessionId)
|
|
906
|
+
return;
|
|
907
|
+
let revision;
|
|
908
|
+
try {
|
|
909
|
+
revision = store.getChangeRevision();
|
|
910
|
+
}
|
|
911
|
+
catch {
|
|
912
|
+
return;
|
|
913
|
+
}
|
|
914
|
+
if (revision === this.lastChangeRevision && !this.pendingCallbackCursor)
|
|
915
|
+
return;
|
|
916
|
+
this.lastChangeRevision = revision;
|
|
917
|
+
let operations;
|
|
918
|
+
try {
|
|
919
|
+
operations = this.activeParentTerminalOperations();
|
|
920
|
+
}
|
|
921
|
+
catch {
|
|
922
|
+
return;
|
|
923
|
+
}
|
|
924
|
+
let newest = this.lastOwnedTerminalAt;
|
|
925
|
+
let visibleOwner;
|
|
926
|
+
for (const operation of operations) {
|
|
927
|
+
newest = Math.max(newest, operation.terminalAt ?? operation.updatedAt);
|
|
928
|
+
if (this.activeOwnerRelation(operation.owner) === "match")
|
|
929
|
+
visibleOwner ??= operation.owner;
|
|
930
|
+
this.attemptTerminalCallback(operation, this.statusOf(operation.operationId), operation.terminalOutcome ?? "failed", [], { pendingWithoutContext: true });
|
|
931
|
+
}
|
|
932
|
+
if (newest > this.lastOwnedTerminalAt) {
|
|
933
|
+
this.lastOwnedTerminalAt = newest;
|
|
934
|
+
if (visibleOwner)
|
|
935
|
+
this.emitDurableTaskChange(visibleOwner);
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
noteDiscoveryRole(role) {
|
|
939
|
+
if (this.discoveryRole === role)
|
|
940
|
+
return;
|
|
941
|
+
this.discoveryRole = role;
|
|
942
|
+
this.followerRunningTasks.clear();
|
|
943
|
+
if (role === "holder") {
|
|
944
|
+
this.watchedRunningTasks.clear();
|
|
945
|
+
this.discoveredTaskSidecars.clear();
|
|
946
|
+
}
|
|
947
|
+
this.lastChangeRevision = -1;
|
|
948
|
+
}
|
|
949
|
+
/**
|
|
950
|
+
* Acquire or confirm the one shared discovery claim. Process identity and
|
|
951
|
+
* explicit close evidence decide replacement; elapsed time is not a lease.
|
|
952
|
+
*/
|
|
953
|
+
refreshDiscoveryAuthority(claim) {
|
|
954
|
+
const store = this.store;
|
|
955
|
+
if (!store)
|
|
956
|
+
return "follower";
|
|
957
|
+
if (claim?.hostId === this.hostId) {
|
|
958
|
+
this.discoveryToken = claim.token;
|
|
959
|
+
return "holder";
|
|
960
|
+
}
|
|
961
|
+
if (claim) {
|
|
962
|
+
const state = this.discoveryHolderState(claim.hostId);
|
|
963
|
+
if (state === "live" || state === "unknown") {
|
|
964
|
+
this.discoveryToken = undefined;
|
|
965
|
+
return "follower";
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
const token = `discovery_${randomUUID()}`;
|
|
969
|
+
try {
|
|
970
|
+
const claimed = store.tryClaimDiscovery({
|
|
971
|
+
scope: this.discoveryScope,
|
|
972
|
+
expected: claim ? { hostId: claim.hostId, token: claim.token } : null,
|
|
973
|
+
hostId: this.hostId,
|
|
974
|
+
token,
|
|
975
|
+
});
|
|
976
|
+
if (claimed) {
|
|
977
|
+
this.discoveryToken = claimed.token;
|
|
978
|
+
return "holder";
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
catch {
|
|
982
|
+
// A busy store or a lost race defers discovery to a later pass.
|
|
983
|
+
}
|
|
984
|
+
this.discoveryToken = undefined;
|
|
985
|
+
return "follower";
|
|
986
|
+
}
|
|
987
|
+
discoveryHolderState(hostId) {
|
|
988
|
+
if (hostId === this.hostId)
|
|
989
|
+
return "live";
|
|
990
|
+
return this.supervisionHolderState(hostId);
|
|
991
|
+
}
|
|
992
|
+
isDurableTask(taskId) {
|
|
993
|
+
if (!LOCAL_DURABLE_ID.test(taskId))
|
|
994
|
+
return false;
|
|
995
|
+
if (this.store)
|
|
996
|
+
return this.operationForTask(taskId) !== undefined;
|
|
997
|
+
return existsSync(supervisorPaths(this.directory, taskId).dir);
|
|
998
|
+
}
|
|
999
|
+
// ---- parent launches -------------------------------------------------
|
|
1000
|
+
async launchParent(input) {
|
|
1001
|
+
const store = this.requireStore();
|
|
1002
|
+
this.requireStarted(input.ctx);
|
|
1003
|
+
if (input.params.ssh) {
|
|
1004
|
+
throw new Error("Structured SSH is not supervised by the durable local host; use the legacy remote task route.");
|
|
1005
|
+
}
|
|
1006
|
+
const owner = this.ownerFor(input.ctx);
|
|
1007
|
+
const prepared = this.prepareLaunch(input.kind, input.params, "bg_task_spawn", owner, undefined);
|
|
1008
|
+
if (this.options.serverOwnedResults) {
|
|
1009
|
+
this.assertManagedResultAdmission(prepared.provenance);
|
|
1010
|
+
const client = await this.resultSupervisionClient();
|
|
1011
|
+
client.close();
|
|
1012
|
+
}
|
|
1013
|
+
const operationId = `op_${randomUUID()}`;
|
|
1014
|
+
const token = `launch_${randomUUID()}`;
|
|
1015
|
+
const taskId = supervisorTaskIdForToken(token);
|
|
1016
|
+
this.options.assertAdmission?.();
|
|
1017
|
+
this.options.beforeParentOperation?.({ operationId, taskId, token });
|
|
1018
|
+
store.registerOperation({
|
|
1019
|
+
operationId,
|
|
1020
|
+
taskId,
|
|
1021
|
+
launchToken: token,
|
|
1022
|
+
owner,
|
|
1023
|
+
observer: OBSERVER,
|
|
1024
|
+
supervision: this.supervision(),
|
|
1025
|
+
authorityRef: this.parentAuthority(owner, prepared.plan),
|
|
1026
|
+
intentRef: typeof input.params.operation_id === "string" ? input.params.operation_id : null,
|
|
1027
|
+
});
|
|
1028
|
+
const launchContext = {
|
|
1029
|
+
kind: input.kind,
|
|
1030
|
+
parentOrigin: this.parentOrigin,
|
|
1031
|
+
gated: prepared.gated,
|
|
1032
|
+
callback: input.params.callback !== false,
|
|
1033
|
+
...(typeof input.params.name === "string" ? { name: input.params.name } : {}),
|
|
1034
|
+
...(typeof input.params.command === "string" ? { command: input.params.command } : {}),
|
|
1035
|
+
...(prepared.spec.argv ? { argv: [...prepared.spec.argv] } : {}),
|
|
1036
|
+
cwd: prepared.cwd,
|
|
1037
|
+
sandbox: prepared.provenance,
|
|
1038
|
+
supervisionPolicy: prepared.plan,
|
|
1039
|
+
branchId: owner.branchId ?? null,
|
|
1040
|
+
};
|
|
1041
|
+
// Persist supervision metadata outside the task execution record so a
|
|
1042
|
+
// replacement host can still notify the right parent and never re-route a
|
|
1043
|
+
// worker-owned operation to the parent's callback.
|
|
1044
|
+
this.writeLaunchContext(taskId, launchContext);
|
|
1045
|
+
this.launches.set(taskId, launchContext);
|
|
1046
|
+
if (this.options.serverOwnedResults)
|
|
1047
|
+
await this.handoffResults([store.getOperation(operationId)], true);
|
|
1048
|
+
const started = await this.startSupervisor({
|
|
1049
|
+
token, taskId, kind: input.kind, params: input.params, prepared, operationId,
|
|
1050
|
+
});
|
|
1051
|
+
this.launches.set(taskId, launchContext);
|
|
1052
|
+
this.emitDurableTaskChange(owner);
|
|
1053
|
+
const launch = {
|
|
1054
|
+
id: taskId,
|
|
1055
|
+
operationId,
|
|
1056
|
+
kind: input.kind,
|
|
1057
|
+
status: "running",
|
|
1058
|
+
...(typeof input.params.name === "string" ? { name: input.params.name } : {}),
|
|
1059
|
+
cwd: prepared.cwd,
|
|
1060
|
+
...(typeof input.params.command === "string" ? { command: input.params.command } : {}),
|
|
1061
|
+
...(prepared.spec.argv ? { argv: prepared.spec.argv } : {}),
|
|
1062
|
+
shell: prepared.spec.shell !== false,
|
|
1063
|
+
owner,
|
|
1064
|
+
started: started.started,
|
|
1065
|
+
claimed: started.claimed,
|
|
1066
|
+
notices: prepared.notices,
|
|
1067
|
+
};
|
|
1068
|
+
if (input.kind === "watch" && input.waitForFirstCheck !== false) {
|
|
1069
|
+
const check = await this.firstCheck(taskId);
|
|
1070
|
+
return { ...launch, ...(check ? { firstCheck: check } : {}) };
|
|
1071
|
+
}
|
|
1072
|
+
return launch;
|
|
1073
|
+
}
|
|
1074
|
+
formatLaunch(launch) {
|
|
1075
|
+
const lines = [
|
|
1076
|
+
`Started durable background ${launch.kind === "watch" ? "watch" : "process"} ${launch.id} (operation ${launch.operationId}).`,
|
|
1077
|
+
`Owner: ${launch.owner.kind} ${launch.owner.sessionId}.${launch.owner.branchId ? ` branch ${launch.owner.branchId}` : ""}`.trim(),
|
|
1078
|
+
`Status: ${launch.status}; supervisor ${launch.started ? "started" : "reported the existing execution"}${launch.claimed ? ", runner claimed" : ", runner claim pending"}.`,
|
|
1079
|
+
`Inspect with bg_task_status ${launch.id}; read output with bg_task_log ${launch.id}; stop with bg_task_stop ${launch.id}.`,
|
|
1080
|
+
"Never poll in the foreground. Register wait_for_operations when no independent work remains.",
|
|
1081
|
+
];
|
|
1082
|
+
if (launch.firstCheck) {
|
|
1083
|
+
lines.push(`First check: exit=${launch.firstCheck.exitCode ?? "null"}${launch.firstCheck.signal ? ` signal=${launch.firstCheck.signal}` : ""}.`);
|
|
1084
|
+
if (launch.firstCheck.stdout.trim())
|
|
1085
|
+
lines.push(`stdout: ${tailText(launch.firstCheck.stdout, 10)}`);
|
|
1086
|
+
if (launch.firstCheck.stderr.trim())
|
|
1087
|
+
lines.push(`stderr: ${tailText(launch.firstCheck.stderr, 10)}`);
|
|
1088
|
+
}
|
|
1089
|
+
for (const notice of launch.notices)
|
|
1090
|
+
lines.push(`Notice: ${notice}`);
|
|
1091
|
+
return lines.join("\n");
|
|
1092
|
+
}
|
|
1093
|
+
/**
|
|
1094
|
+
* Bounded first-check observation, mirroring the legacy watch launch. A watch
|
|
1095
|
+
* whose first check is still running returns the retained tails and says so;
|
|
1096
|
+
* it never invents an exit code. A check that ends without a terminal record
|
|
1097
|
+
* is given a short grace for the runner to publish the next attempt.
|
|
1098
|
+
*/
|
|
1099
|
+
async firstCheck(taskId) {
|
|
1100
|
+
const deadline = Date.now() + 15_000;
|
|
1101
|
+
const tails = (attempt) => {
|
|
1102
|
+
const inspection = this.supervisor.inspect(taskId);
|
|
1103
|
+
if (!inspection)
|
|
1104
|
+
return undefined;
|
|
1105
|
+
const paths = inspection.logs;
|
|
1106
|
+
return {
|
|
1107
|
+
attempt,
|
|
1108
|
+
exitCode: null,
|
|
1109
|
+
signal: null,
|
|
1110
|
+
stdout: lastLines(tail(paths.stdout).text, 10),
|
|
1111
|
+
stderr: lastLines(tail(paths.stderr).text, 10),
|
|
1112
|
+
};
|
|
1113
|
+
};
|
|
1114
|
+
let endedAt;
|
|
1115
|
+
while (Date.now() < deadline) {
|
|
1116
|
+
const inspection = this.supervisor.inspect(taskId);
|
|
1117
|
+
if (inspection?.result) {
|
|
1118
|
+
const last = inspection.result.lastCheck;
|
|
1119
|
+
return {
|
|
1120
|
+
attempt: inspection.result.checks ?? 1,
|
|
1121
|
+
exitCode: last?.exitCode ?? inspection.result.exitCode,
|
|
1122
|
+
signal: last?.signal ?? inspection.result.signal,
|
|
1123
|
+
stdout: last?.stdout ?? inspection.result.lastOutput?.stdout ?? "",
|
|
1124
|
+
stderr: last?.stderr ?? inspection.result.lastOutput?.stderr ?? "",
|
|
1125
|
+
};
|
|
1126
|
+
}
|
|
1127
|
+
const command = inspection?.command;
|
|
1128
|
+
if (command) {
|
|
1129
|
+
if (command.alive) {
|
|
1130
|
+
endedAt = undefined;
|
|
1131
|
+
}
|
|
1132
|
+
else if (endedAt === undefined) {
|
|
1133
|
+
endedAt = Date.now();
|
|
1134
|
+
}
|
|
1135
|
+
else if (Date.now() - endedAt >= 250) {
|
|
1136
|
+
return tails(command.attempt);
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
1140
|
+
}
|
|
1141
|
+
// Still running after the legacy first-check window: report what the logs hold.
|
|
1142
|
+
const inspection = this.supervisor.inspect(taskId);
|
|
1143
|
+
return inspection?.command ? tails(inspection.command.attempt) : undefined;
|
|
1144
|
+
}
|
|
1145
|
+
// ---- status / log / stop --------------------------------------------
|
|
1146
|
+
statusForParent(ctx, taskId) {
|
|
1147
|
+
this.noteParentContext(ctx);
|
|
1148
|
+
return this.status(taskId, this.ownerFor(ctx));
|
|
1149
|
+
}
|
|
1150
|
+
logForParent(ctx, taskId, options) {
|
|
1151
|
+
this.noteParentContext(ctx);
|
|
1152
|
+
return this.log(taskId, this.ownerFor(ctx), options);
|
|
1153
|
+
}
|
|
1154
|
+
async stopForParent(ctx, taskId, requestId) {
|
|
1155
|
+
this.noteParentContext(ctx);
|
|
1156
|
+
if (requestId) {
|
|
1157
|
+
try {
|
|
1158
|
+
return await this.stopThroughRuntime(ctx, taskId, requestId);
|
|
1159
|
+
}
|
|
1160
|
+
catch (error) {
|
|
1161
|
+
if (/not_accepted|accepted:|outcome_unknown/.test(String(error)))
|
|
1162
|
+
throw error;
|
|
1163
|
+
throw new Error(`not_accepted: ${String(error)}`);
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
return this.stop(taskId, this.ownerFor(ctx));
|
|
1167
|
+
}
|
|
1168
|
+
/** Called from an actual admitted parent tool context, not a wire owner claim. */
|
|
1169
|
+
authorizeCancellationForParent(ctx, taskId, requestId) {
|
|
1170
|
+
if (this.localCancels.has(taskId))
|
|
1171
|
+
throw new Error("not_accepted: old cancellation admission is still draining");
|
|
1172
|
+
const requester = this.ownerFor(ctx), operation = this.operationForTask(taskId);
|
|
1173
|
+
if (!operation)
|
|
1174
|
+
throw new Error(`Unknown task ${taskId}`);
|
|
1175
|
+
const admission = this.options.authorizeParentCancellation?.({ requester, operation, requestId });
|
|
1176
|
+
if (!ownerMatchesOperation(operation, requester) && !admission)
|
|
1177
|
+
throw new Error(`Task ${taskId} belongs to another execution owner.`);
|
|
1178
|
+
requestId = admission?.requestId ?? requestId;
|
|
1179
|
+
const managed = this.requireStore().resultSupervision(operation.operationId);
|
|
1180
|
+
if (this.supervisionAuthority(operation) === "foreign" && !(managed?.launchToken === operation.launchToken && managed.hostId === operation.supervision?.hostId))
|
|
1181
|
+
throw new Error("permission-unavailable: live legacy or unknown supervisor prevents cancellation handoff");
|
|
1182
|
+
const proof = cancellationCredential();
|
|
1183
|
+
const previous = this.requireStore().getTaskCancellation({ owner: operation.owner, idempotencyKey: requestId });
|
|
1184
|
+
if (previous && previous.operationId !== operation.operationId)
|
|
1185
|
+
throw new Error("not_accepted: request-conflict: cancellation key belongs to another task");
|
|
1186
|
+
this.requireStore().admitTaskCancellation({ credentialHash: proof.hash, directory: this.directory, request: previous ?? {
|
|
1187
|
+
owner: operation.owner, idempotencyKey: requestId, operationId: operation.operationId,
|
|
1188
|
+
expectedLaunchToken: operation.launchToken, expectedTerminalRevision: operation.terminalRevision,
|
|
1189
|
+
expectedHostId: operation.supervision?.hostId ?? "unavailable", reason: admission?.reason ?? "explicit stop",
|
|
1190
|
+
} });
|
|
1191
|
+
return proof.credential;
|
|
1192
|
+
}
|
|
1193
|
+
async stopThroughRuntime(ctx, taskId, requestId) {
|
|
1194
|
+
const root = realpathSync(dirname(this.storePath));
|
|
1195
|
+
const registrationPath = join(root, "server-registration-v1.json");
|
|
1196
|
+
if (!existsSync(registrationPath)) {
|
|
1197
|
+
const installer = "../runtime-client/src/runtime/client.mjs";
|
|
1198
|
+
await (await import(installer)).ensureRuntime({ agentDir: root });
|
|
1199
|
+
}
|
|
1200
|
+
const registration = JSON.parse(readFileSync(registrationPath, "utf8"));
|
|
1201
|
+
if (registration.agentDir !== root || registration.version !== 1)
|
|
1202
|
+
throw new Error("not_accepted: invalid canonical runtime registration");
|
|
1203
|
+
const module = "./shared-work-client.mjs";
|
|
1204
|
+
const { WorkClient } = await import(module);
|
|
1205
|
+
const client = new WorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-cancellation-v1"]);
|
|
1206
|
+
let submitted = false;
|
|
1207
|
+
try {
|
|
1208
|
+
await client.ready;
|
|
1209
|
+
await client.request("runtime_cancellation_status");
|
|
1210
|
+
const credential = this.authorizeCancellationForParent(ctx, taskId, requestId);
|
|
1211
|
+
const previous = await client.request("runtime_query_cancellation", { credential });
|
|
1212
|
+
let receipt = previous;
|
|
1213
|
+
if (previous.state === "not_accepted") {
|
|
1214
|
+
submitted = true;
|
|
1215
|
+
receipt = await client.request("runtime_cancel_task", { credential });
|
|
1216
|
+
}
|
|
1217
|
+
if (receipt.state === "outcome_unknown" || !receipt.result)
|
|
1218
|
+
throw new Error(`${receipt.state}: cancellation ${requestId}; query the same request before retrying`);
|
|
1219
|
+
// The credential above authorizes this exact recorded owner/token. Keep
|
|
1220
|
+
// the requester context intact even when its explicit all:true grant won.
|
|
1221
|
+
const operation = this.requireStore().getOperation(receipt.operationId);
|
|
1222
|
+
if (!operation || operation.taskId !== taskId || operation.launchToken !== receipt.expectedLaunchToken
|
|
1223
|
+
|| !sameOwner(operation.owner, receipt.owner))
|
|
1224
|
+
throw new Error('outcome_unknown: cancellation target identity changed');
|
|
1225
|
+
return this.statusForOperation(operation, this.ownerFor(ctx));
|
|
1226
|
+
}
|
|
1227
|
+
catch (error) {
|
|
1228
|
+
const message = String(error);
|
|
1229
|
+
if (/not_accepted|accepted:|outcome_unknown/.test(message))
|
|
1230
|
+
throw error;
|
|
1231
|
+
if (!submitted)
|
|
1232
|
+
throw new Error(`not_accepted: cancellation ${requestId}: ${message}`);
|
|
1233
|
+
throw new Error(`outcome_unknown: cancellation ${requestId}; reconnect and query the same request before retrying: ${message}`);
|
|
1234
|
+
}
|
|
1235
|
+
finally {
|
|
1236
|
+
client.close();
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
// ---- read-only projections for list, navigator and Goal -----------------
|
|
1240
|
+
/**
|
|
1241
|
+
* Durable operations owned by exactly this parent origin, newest first. This
|
|
1242
|
+
* never writes a legacy registry meta and never reconciles; it projects the
|
|
1243
|
+
* canonical operation store plus the supervisor's durable records.
|
|
1244
|
+
*/
|
|
1245
|
+
listDurableTasks(origin, options = {}) {
|
|
1246
|
+
const store = this.store;
|
|
1247
|
+
if (!store || this.closed)
|
|
1248
|
+
return [];
|
|
1249
|
+
if (!origin.sessionId)
|
|
1250
|
+
return [];
|
|
1251
|
+
this.projectionMetrics.listCalls += 1;
|
|
1252
|
+
const now = this.options.now?.() ?? Date.now();
|
|
1253
|
+
const originKey = `${origin.cwd}\0${origin.sessionId}`;
|
|
1254
|
+
const cacheKey = `${originKey}\0${options.retentionMs ?? ""}\0${options.includeDismissed === true ? 1 : 0}`;
|
|
1255
|
+
const cached = this.durableProjectionCache;
|
|
1256
|
+
if (!options.fresh && cached && cached.key === cacheKey && now >= cached.at && now - cached.at < DURABLE_PROJECTION_CACHE_MS) {
|
|
1257
|
+
this.projectionMetrics.cacheHits += 1;
|
|
1258
|
+
if (options.retentionMs === undefined)
|
|
1259
|
+
return cached.list;
|
|
1260
|
+
const live = cached.list.filter((projection) => !this.expiredProjection(projection, options, now));
|
|
1261
|
+
return live.length === cached.list.length ? cached.list : live;
|
|
1262
|
+
}
|
|
1263
|
+
const projections = [];
|
|
1264
|
+
const operations = store.listOperations({
|
|
1265
|
+
ownerScope: { kind: "parent-session", sessionId: origin.sessionId, workspace: origin.cwd },
|
|
1266
|
+
});
|
|
1267
|
+
this.projectionMetrics.queries += 1;
|
|
1268
|
+
this.projectionMetrics.rowsRead += operations.length;
|
|
1269
|
+
for (const operation of operations) {
|
|
1270
|
+
if (!this.belongsToParentOrigin(operation, origin))
|
|
1271
|
+
continue;
|
|
1272
|
+
this.projectionMetrics.projectionsBuilt += 1;
|
|
1273
|
+
const projection = this.projectDurable(operation, now);
|
|
1274
|
+
if (!projection)
|
|
1275
|
+
continue;
|
|
1276
|
+
if (projection.dismissedAt !== undefined && options.includeDismissed !== true)
|
|
1277
|
+
continue;
|
|
1278
|
+
if (projection.terminal && options.retentionMs !== undefined) {
|
|
1279
|
+
const endedAt = projection.endedAt ?? now;
|
|
1280
|
+
if (now - endedAt >= options.retentionMs)
|
|
1281
|
+
continue;
|
|
1282
|
+
}
|
|
1283
|
+
projections.push(projection);
|
|
1284
|
+
}
|
|
1285
|
+
projections.sort((a, b) => b.startedAt - a.startedAt);
|
|
1286
|
+
this.durableProjectionCache = {
|
|
1287
|
+
originKey,
|
|
1288
|
+
key: cacheKey,
|
|
1289
|
+
at: now,
|
|
1290
|
+
list: projections,
|
|
1291
|
+
byTask: new Map(projections.map((projection) => [projection.id, projection])),
|
|
1292
|
+
};
|
|
1293
|
+
const live = projections.filter((projection) => !this.expiredProjection(projection, options, now));
|
|
1294
|
+
return live.length === projections.length ? projections : live;
|
|
1295
|
+
}
|
|
1296
|
+
readDurableTask(origin, taskId) {
|
|
1297
|
+
const now = this.options.now?.() ?? Date.now();
|
|
1298
|
+
const cached = this.durableProjectionCache;
|
|
1299
|
+
if (cached && cached.originKey === `${origin.cwd}\0${origin.sessionId ?? ""}`
|
|
1300
|
+
&& now >= cached.at && now - cached.at < DURABLE_PROJECTION_CACHE_MS) {
|
|
1301
|
+
const projection = cached.byTask.get(taskId);
|
|
1302
|
+
if (projection)
|
|
1303
|
+
return projection;
|
|
1304
|
+
}
|
|
1305
|
+
const operation = this.operationForTask(taskId);
|
|
1306
|
+
if (!operation || !this.belongsToParentOrigin(operation, origin))
|
|
1307
|
+
return undefined;
|
|
1308
|
+
this.projectionMetrics.projectionsBuilt += 1;
|
|
1309
|
+
return this.projectDurable(operation, now);
|
|
1310
|
+
}
|
|
1311
|
+
/** Accumulated projection work, for performance regression proof. */
|
|
1312
|
+
getDurableProjectionMetrics() {
|
|
1313
|
+
return { ...this.projectionMetrics };
|
|
1314
|
+
}
|
|
1315
|
+
resetDurableProjectionMetrics() {
|
|
1316
|
+
this.projectionMetrics = { listCalls: 0, queries: 0, rowsRead: 0, projectionsBuilt: 0, cacheHits: 0 };
|
|
1317
|
+
}
|
|
1318
|
+
expiredProjection(projection, options, now) {
|
|
1319
|
+
if (!projection.terminal || options.retentionMs === undefined)
|
|
1320
|
+
return false;
|
|
1321
|
+
const endedAt = projection.endedAt ?? now;
|
|
1322
|
+
return now - endedAt >= options.retentionMs;
|
|
1323
|
+
}
|
|
1324
|
+
/**
|
|
1325
|
+
* True only when this host's **currently active** parent session/workspace
|
|
1326
|
+
* owns the durable operation. The adapter contract uses this to admit a local
|
|
1327
|
+
* stop/clear as a registry operation; it is not a regex and cannot authorize a
|
|
1328
|
+
* foreign session or a worker-owned operation.
|
|
1329
|
+
*/
|
|
1330
|
+
ownsDurableTask(taskId) {
|
|
1331
|
+
const origin = this.activeOrigin;
|
|
1332
|
+
if (!origin)
|
|
1333
|
+
return false;
|
|
1334
|
+
return this.readDurableTask(origin, taskId) !== undefined;
|
|
1335
|
+
}
|
|
1336
|
+
/** Read-only log tails. Unlike status/log tools, this records no evidence read. */
|
|
1337
|
+
readDurableTaskLog(origin, taskId, lines = 40) {
|
|
1338
|
+
const projection = this.readDurableTask(origin, taskId);
|
|
1339
|
+
if (!projection)
|
|
1340
|
+
return undefined;
|
|
1341
|
+
const count = Math.max(1, Math.floor(lines));
|
|
1342
|
+
const stdout = tail(projection.logPaths.stdout);
|
|
1343
|
+
const stderr = tail(projection.logPaths.stderr);
|
|
1344
|
+
return {
|
|
1345
|
+
taskId,
|
|
1346
|
+
status: projection.status,
|
|
1347
|
+
stdout: lastLines(stdout.text, count),
|
|
1348
|
+
stderr: lastLines(stderr.text, count),
|
|
1349
|
+
events: lastLines(tail(projection.logPaths.events).text, Math.min(count, 20)),
|
|
1350
|
+
truncated: stdout.truncated || stderr.truncated,
|
|
1351
|
+
};
|
|
1352
|
+
}
|
|
1353
|
+
/** Stop a durable task through the supervisor. Foreign ids are refused. */
|
|
1354
|
+
async stopDurableTask(origin, taskId) {
|
|
1355
|
+
const operation = this.operationForTask(taskId);
|
|
1356
|
+
if (!operation || !this.belongsToParentOrigin(operation, origin))
|
|
1357
|
+
return undefined;
|
|
1358
|
+
await this.stop(taskId, operation.owner);
|
|
1359
|
+
this.invalidateDurableProjection(operation.owner);
|
|
1360
|
+
return this.projectDurable(operation, this.options.now?.() ?? Date.now());
|
|
1361
|
+
}
|
|
1362
|
+
/** Dismiss one terminal durable task from list/navigator/Goal. Evidence stays readable. */
|
|
1363
|
+
dismissDurableTask(origin, taskId) {
|
|
1364
|
+
const operation = this.operationForTask(taskId);
|
|
1365
|
+
if (!operation || !this.belongsToParentOrigin(operation, origin))
|
|
1366
|
+
return false;
|
|
1367
|
+
const projection = this.projectDurable(operation, this.options.now?.() ?? Date.now());
|
|
1368
|
+
if (!projection || !projection.terminal)
|
|
1369
|
+
return false;
|
|
1370
|
+
const context = this.currentLaunchContext(taskId) ?? {
|
|
1371
|
+
kind: projection.kind,
|
|
1372
|
+
gated: projection.stepGateFailure !== undefined,
|
|
1373
|
+
callback: false,
|
|
1374
|
+
...(projection.name ? { name: projection.name } : {}),
|
|
1375
|
+
...(projection.command ? { command: projection.command } : {}),
|
|
1376
|
+
...(projection.argv ? { argv: [...projection.argv] } : {}),
|
|
1377
|
+
cwd: projection.cwd,
|
|
1378
|
+
};
|
|
1379
|
+
context.dismissedAt = Date.now();
|
|
1380
|
+
this.launches.set(taskId, context);
|
|
1381
|
+
this.writeLaunchContext(taskId, context);
|
|
1382
|
+
this.emitDurableTaskChange(operation.owner);
|
|
1383
|
+
return true;
|
|
1384
|
+
}
|
|
1385
|
+
onDurableTaskChange(listener) {
|
|
1386
|
+
this.durableChangeListeners.add(listener);
|
|
1387
|
+
return () => { this.durableChangeListeners.delete(listener); };
|
|
1388
|
+
}
|
|
1389
|
+
emitDurableTaskChange(owner) {
|
|
1390
|
+
// Navigators and Goal activity only show the active parent session. A
|
|
1391
|
+
// worker, another session, or another workspace must not evict its cache or
|
|
1392
|
+
// request a repaint.
|
|
1393
|
+
if (owner.kind !== "parent-session" || this.activeOwnerRelation(owner) !== "match")
|
|
1394
|
+
return;
|
|
1395
|
+
this.invalidateDurableProjection(owner);
|
|
1396
|
+
const change = { sessionId: owner.sessionId, workspace: owner.workspace, branchId: owner.branchId ?? null };
|
|
1397
|
+
for (const listener of [...this.durableChangeListeners]) {
|
|
1398
|
+
try {
|
|
1399
|
+
listener(change);
|
|
1400
|
+
}
|
|
1401
|
+
catch { /* a projection listener cannot break supervision */ }
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
invalidateDurableProjection(owner) {
|
|
1405
|
+
if (owner && (owner.kind !== "parent-session" || this.activeOwnerRelation(owner) !== "match"))
|
|
1406
|
+
return;
|
|
1407
|
+
this.durableProjectionCache = undefined;
|
|
1408
|
+
}
|
|
1409
|
+
belongsToParentOrigin(operation, origin) {
|
|
1410
|
+
if (operation.owner.kind !== "parent-session")
|
|
1411
|
+
return false;
|
|
1412
|
+
if (operation.owner.workspace !== origin.cwd)
|
|
1413
|
+
return false;
|
|
1414
|
+
if (origin.sessionId || operation.owner.sessionId)
|
|
1415
|
+
return operation.owner.sessionId === origin.sessionId;
|
|
1416
|
+
return true;
|
|
1417
|
+
}
|
|
1418
|
+
projectDurable(operation, now) {
|
|
1419
|
+
const context = this.launchContext(operation.taskId);
|
|
1420
|
+
// Projection is the rendering path: a snapshot reads the durable records
|
|
1421
|
+
// without taking the cross-process fence or spawning `ps`.
|
|
1422
|
+
const inspection = LOCAL_DURABLE_ID.test(operation.taskId)
|
|
1423
|
+
? (() => { try {
|
|
1424
|
+
return this.supervisor.snapshot(operation.taskId);
|
|
1425
|
+
}
|
|
1426
|
+
catch {
|
|
1427
|
+
return undefined;
|
|
1428
|
+
} })()
|
|
1429
|
+
: undefined;
|
|
1430
|
+
const storeStatus = operation.terminalRevision > 0 ? this.statusOf(operation.operationId) : undefined;
|
|
1431
|
+
const status = inspection?.terminal ? inspection.status : storeStatus ?? inspection?.status ?? "running";
|
|
1432
|
+
const terminal = inspection?.terminal === true || operation.terminalRevision > 0;
|
|
1433
|
+
const active = !terminal && (status === "running" || status === "starting");
|
|
1434
|
+
const startedAt = inspection?.result?.startedAt ?? inspection?.launch?.createdAt ?? operation.createdAt;
|
|
1435
|
+
const endedAt = inspection?.result?.endedAt ?? inspection?.lost?.recordedAt ?? operation.terminalAt ?? undefined;
|
|
1436
|
+
const pathSet = inspection?.logs ?? supervisorPaths(this.directory, operation.taskId);
|
|
1437
|
+
const result = inspection?.result;
|
|
1438
|
+
const lost = inspection?.lost;
|
|
1439
|
+
const waits = (this.store?.listWaits({ owner: operation.owner, pendingOnly: true }) ?? [])
|
|
1440
|
+
.filter((wait) => wait.dependencies.some((dep) => dep.operationId === operation.operationId))
|
|
1441
|
+
.map((wait) => this.waitView(wait));
|
|
1442
|
+
const stepGate = result && context?.gated
|
|
1443
|
+
? parseStepGateFailure(tail(pathSet.stderr).text, operation.taskId)
|
|
1444
|
+
: undefined;
|
|
1445
|
+
const timeoutSeconds = inspection?.launch.timeoutSeconds;
|
|
1446
|
+
return {
|
|
1447
|
+
id: operation.taskId,
|
|
1448
|
+
operationId: operation.operationId,
|
|
1449
|
+
kind: (context?.kind ?? inspection?.launch.kind) === "watch" ? "watch" : "process",
|
|
1450
|
+
status,
|
|
1451
|
+
active,
|
|
1452
|
+
terminal,
|
|
1453
|
+
attention: terminal && status !== "succeeded",
|
|
1454
|
+
...(context?.name ?? inspection?.launch.name ? { name: context?.name ?? inspection?.launch.name } : {}),
|
|
1455
|
+
cwd: inspection?.launch.cwd ?? context?.cwd ?? operation.owner.workspace,
|
|
1456
|
+
...(context?.command ? { command: context.command } : {}),
|
|
1457
|
+
...(context?.argv ? { argv: context.argv } : {}),
|
|
1458
|
+
startedAt,
|
|
1459
|
+
...(endedAt !== undefined ? { endedAt } : {}),
|
|
1460
|
+
exitCode: result?.exitCode ?? null,
|
|
1461
|
+
signal: result?.signal ?? null,
|
|
1462
|
+
...supervisionReasonFields(inspection),
|
|
1463
|
+
...(result?.matchedCondition ? { matchedCondition: result.matchedCondition } : {}),
|
|
1464
|
+
...(result?.lastOutput ? { lastOutput: result.lastOutput } : {}),
|
|
1465
|
+
...(stepGate ? { stepGateFailure: stepGate } : {}),
|
|
1466
|
+
terminalRevision: operation.terminalRevision,
|
|
1467
|
+
terminalOutcome: operation.terminalOutcome,
|
|
1468
|
+
detailLost: lost !== undefined || operation.terminalDetailLost,
|
|
1469
|
+
...(context?.dismissedAt !== undefined ? { dismissedAt: context.dismissedAt } : {}),
|
|
1470
|
+
...(result ? { logDiscardedBytes: result.stdoutDiscardedBytes + result.stderrDiscardedBytes } : {}),
|
|
1471
|
+
...(inspection?.launch.intervalSeconds !== undefined ? { intervalSeconds: inspection.launch.intervalSeconds } : {}),
|
|
1472
|
+
...(timeoutSeconds !== undefined && timeoutSeconds > 0 ? { deadlineAt: startedAt + timeoutSeconds * 1000 } : {}),
|
|
1473
|
+
logPaths: { stdout: pathSet.stdout, stderr: pathSet.stderr, events: pathSet.events },
|
|
1474
|
+
waits,
|
|
1475
|
+
...(context?.sandbox ? { sandbox: context.sandbox } : {}),
|
|
1476
|
+
owner: { sessionId: operation.owner.sessionId, workspace: operation.owner.workspace, branchId: operation.owner.branchId ?? null },
|
|
1477
|
+
};
|
|
1478
|
+
}
|
|
1479
|
+
status(taskId, owner) {
|
|
1480
|
+
return this.statusForOperation(this.ownedOperation(taskId, owner), owner);
|
|
1481
|
+
}
|
|
1482
|
+
statusForOperation(operation, owner) {
|
|
1483
|
+
const store = this.requireStore(), taskId = operation.taskId;
|
|
1484
|
+
const inspection = this.inspect(taskId);
|
|
1485
|
+
this.reconcileInspection(operation, inspection);
|
|
1486
|
+
const current = store.getOperation(operation.operationId) ?? operation;
|
|
1487
|
+
if (this.watchedRunningTasks.delete(taskId) && current.terminalRevision > 0) {
|
|
1488
|
+
this.attemptTerminalCallback(current, this.statusOf(current.operationId), current.terminalOutcome ?? "failed", [], { pendingWithoutContext: true });
|
|
1489
|
+
}
|
|
1490
|
+
if (current.terminalRevision > 0) {
|
|
1491
|
+
// Status is an explicit owner read of this exact terminal operation. It is
|
|
1492
|
+
// the natural recovery point when another host recorded terminal first.
|
|
1493
|
+
this.attemptTerminalCallback(current, this.statusOf(current.operationId), current.terminalOutcome ?? "failed", [], { pendingWithoutContext: true });
|
|
1494
|
+
}
|
|
1495
|
+
this.recordReadsForTask(owner, current);
|
|
1496
|
+
const paths = supervisorPaths(this.directory, taskId);
|
|
1497
|
+
const gateText = inspection ? `${tail(paths.stderr).text}` : "";
|
|
1498
|
+
const waits = store.listWaits({ pendingOnly: true })
|
|
1499
|
+
.filter((wait) => sameOwner(wait.owner, owner))
|
|
1500
|
+
.filter((wait) => wait.dependencies.some((dep) => dep.operationId === current.operationId))
|
|
1501
|
+
.map((wait) => this.waitView(wait));
|
|
1502
|
+
const result = inspection?.result;
|
|
1503
|
+
const launched = this.launchContext(taskId);
|
|
1504
|
+
const stepGate = result && launched?.gated ? parseStepGateFailure(gateText, taskId) : undefined;
|
|
1505
|
+
const kind = inspection?.kind ?? launched?.kind ?? "process";
|
|
1506
|
+
return {
|
|
1507
|
+
taskId,
|
|
1508
|
+
operationId: current.operationId,
|
|
1509
|
+
kind: kind === "watch" ? "watch" : "process",
|
|
1510
|
+
status: inspection?.status ?? this.statusOf(current.operationId),
|
|
1511
|
+
phase: current.phase,
|
|
1512
|
+
exitCode: result?.exitCode ?? null,
|
|
1513
|
+
signal: result?.signal ?? null,
|
|
1514
|
+
...supervisionReasonFields(inspection),
|
|
1515
|
+
terminalRevision: current.terminalRevision,
|
|
1516
|
+
terminalOutcome: current.terminalOutcome,
|
|
1517
|
+
...(result ? { startedAt: result.startedAt, endedAt: result.endedAt } : {}),
|
|
1518
|
+
...(result?.checks !== undefined ? { checks: result.checks } : {}),
|
|
1519
|
+
...(result?.matchedCondition ? { matchedCondition: result.matchedCondition } : {}),
|
|
1520
|
+
...(result?.lastOutput ? { lastOutput: result.lastOutput } : {}),
|
|
1521
|
+
...(stepGate ? { stepGateFailure: stepGate } : {}),
|
|
1522
|
+
waits,
|
|
1523
|
+
...(launched?.sandbox ? { sandbox: launched.sandbox } : {}),
|
|
1524
|
+
};
|
|
1525
|
+
}
|
|
1526
|
+
log(taskId, owner, options = {}) {
|
|
1527
|
+
const store = this.requireStore();
|
|
1528
|
+
const operation = this.ownedOperation(taskId, owner);
|
|
1529
|
+
const inspection = this.inspect(taskId);
|
|
1530
|
+
this.reconcileInspection(operation, inspection);
|
|
1531
|
+
this.recordReadsForTask(owner, store.getOperation(operation.operationId) ?? operation);
|
|
1532
|
+
const paths = supervisorPaths(this.directory, taskId);
|
|
1533
|
+
const lines = Math.max(1, Math.floor(options.lines ?? 40));
|
|
1534
|
+
const stdout = tail(paths.stdout);
|
|
1535
|
+
const stderr = tail(paths.stderr);
|
|
1536
|
+
return {
|
|
1537
|
+
taskId,
|
|
1538
|
+
status: inspection?.status ?? "running",
|
|
1539
|
+
stdout: lastLines(stdout.text, lines),
|
|
1540
|
+
stderr: lastLines(stderr.text, lines),
|
|
1541
|
+
events: lastLines(tail(paths.events).text, Math.min(lines, 20)),
|
|
1542
|
+
truncated: stdout.truncated || stderr.truncated,
|
|
1543
|
+
};
|
|
1544
|
+
}
|
|
1545
|
+
async stop(taskId, owner) {
|
|
1546
|
+
const store = this.requireStore();
|
|
1547
|
+
const operation = this.ownedOperation(taskId, owner);
|
|
1548
|
+
if (store.taskCancellationManaged(operation.operationId))
|
|
1549
|
+
throw new Error("not_accepted: cancellation admission transferred to server; use the registered stop tool with the original request_id");
|
|
1550
|
+
if (this.localCancels.has(taskId))
|
|
1551
|
+
throw new Error("not_accepted: old cancellation is already in flight");
|
|
1552
|
+
this.localCancels.add(taskId);
|
|
1553
|
+
try {
|
|
1554
|
+
const result = await this.supervisor.stop(taskId, { token: operation.launchToken });
|
|
1555
|
+
const inspection = result?.inspection ?? this.supervisor.inspect(taskId);
|
|
1556
|
+
this.reconcileInspection(operation, inspection);
|
|
1557
|
+
const current = store.getOperation(operation.operationId) ?? operation;
|
|
1558
|
+
if (current.terminalRevision === 0 && inspection?.terminal) {
|
|
1559
|
+
this.recordTerminal(current, inspection);
|
|
1560
|
+
}
|
|
1561
|
+
return this.status(taskId, owner);
|
|
1562
|
+
}
|
|
1563
|
+
finally {
|
|
1564
|
+
this.localCancels.delete(taskId);
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
formatStatus(view) {
|
|
1568
|
+
const lines = [
|
|
1569
|
+
`${view.taskId} ${view.kind}: ${view.status} (${view.phase})`,
|
|
1570
|
+
`operation: ${view.operationId}; terminal revision: ${view.terminalRevision}${view.terminalOutcome ? ` (${view.terminalOutcome})` : ""}`,
|
|
1571
|
+
];
|
|
1572
|
+
if (view.sandbox) {
|
|
1573
|
+
lines.push(`sandbox: ${view.sandbox.confinement}${view.sandbox.backend ? `; ${oneLine(view.sandbox.backend, 40)}` : ""}; source: ${oneLine(view.sandbox.policySource, 80)}; later changes do not affect this task.`);
|
|
1574
|
+
}
|
|
1575
|
+
if (view.exitCode !== null || view.signal)
|
|
1576
|
+
lines.push(`exit=${view.exitCode ?? "null"}${view.signal ? ` signal=${view.signal}` : ""}${view.stepGateFailure ? " (step gate)" : ""}`);
|
|
1577
|
+
if (view.startedAt)
|
|
1578
|
+
lines.push(`started: ${new Date(view.startedAt).toISOString()}${view.endedAt ? `; ended: ${new Date(view.endedAt).toISOString()}` : ""}`);
|
|
1579
|
+
if (view.checks !== undefined)
|
|
1580
|
+
lines.push(`checks: ${view.checks}`);
|
|
1581
|
+
if (view.matchedCondition)
|
|
1582
|
+
lines.push(`matched: ${oneLine(JSON.stringify(view.matchedCondition))}`);
|
|
1583
|
+
if (view.reason)
|
|
1584
|
+
lines.push(`reason: ${view.reason}`);
|
|
1585
|
+
if (view.stepGateFailure)
|
|
1586
|
+
lines.push(`failing step: ${view.stepGateFailure.command}`);
|
|
1587
|
+
if (view.waits.length) {
|
|
1588
|
+
for (const wait of view.waits) {
|
|
1589
|
+
lines.push(`wait: ${wait.waitId} generation ${wait.generation} ${wait.phase}${wait.settled ? " (settled)" : ""}`);
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
else {
|
|
1593
|
+
lines.push("wait: none pending for this owner");
|
|
1594
|
+
}
|
|
1595
|
+
lines.push("Read the terminal evidence with bg_task_log before acknowledging a wait.");
|
|
1596
|
+
return lines.join("\n");
|
|
1597
|
+
}
|
|
1598
|
+
formatLog(view) {
|
|
1599
|
+
const parts = [`${view.taskId} ${view.status}`, "stdout:", view.stdout || "(empty)"];
|
|
1600
|
+
if (view.stderr.trim())
|
|
1601
|
+
parts.push("stderr:", view.stderr);
|
|
1602
|
+
parts.push("events:", view.events || "(empty)");
|
|
1603
|
+
if (view.truncated)
|
|
1604
|
+
parts.push("Retention removed older output; the terminal outcome is preserved.");
|
|
1605
|
+
return parts.join("\n");
|
|
1606
|
+
}
|
|
1607
|
+
// ---- parent waits ----------------------------------------------------
|
|
1608
|
+
waitForParent(ctx, taskIds, continuationNote) {
|
|
1609
|
+
this.noteParentContext(ctx);
|
|
1610
|
+
const store = this.requireStore();
|
|
1611
|
+
const owner = this.ownerFor(ctx);
|
|
1612
|
+
const operations = this.operationsForTaskIds(owner, taskIds);
|
|
1613
|
+
for (const operation of operations)
|
|
1614
|
+
this.reconcileOperation(operation);
|
|
1615
|
+
const result = store.registerWait({
|
|
1616
|
+
owner,
|
|
1617
|
+
dependencies: operations.map((operation) => ({ operationId: operation.operationId })),
|
|
1618
|
+
continuationNote,
|
|
1619
|
+
origin: { taskIds: [...taskIds] },
|
|
1620
|
+
});
|
|
1621
|
+
void this.dispatchOutbox();
|
|
1622
|
+
return this.waitView(store.getWait({ waitId: result.wait.waitId }) ?? result.wait);
|
|
1623
|
+
}
|
|
1624
|
+
async resultSupervisionClient() {
|
|
1625
|
+
const root = realpathSync(dirname(this.storePath));
|
|
1626
|
+
const ports = globalThis[Symbol.for("pi-better-server:result-supervision-ports-v1")];
|
|
1627
|
+
const port = ports?.get(root);
|
|
1628
|
+
if (port)
|
|
1629
|
+
return { request: async (type) => {
|
|
1630
|
+
if (type !== "runtime_result_supervision")
|
|
1631
|
+
throw new Error("not_accepted: unsupported in-process supervision operation");
|
|
1632
|
+
return port.status();
|
|
1633
|
+
}, close() { } };
|
|
1634
|
+
// @ts-expect-error Generated standalone lightweight socket client.
|
|
1635
|
+
const { WorkClient } = await import("./shared-work-client.mjs");
|
|
1636
|
+
const connect = async () => {
|
|
1637
|
+
const registration = JSON.parse(readFileSync(join(root, "server-registration-v1.json"), "utf8"));
|
|
1638
|
+
if (registration.version !== 1 || registration.agentDir !== root)
|
|
1639
|
+
throw new Error("Invalid canonical runtime registration");
|
|
1640
|
+
const connection = new WorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-result-supervision-v1"]);
|
|
1641
|
+
try {
|
|
1642
|
+
await connection.ready;
|
|
1643
|
+
return connection;
|
|
1644
|
+
}
|
|
1645
|
+
catch (error) {
|
|
1646
|
+
connection.close();
|
|
1647
|
+
throw error;
|
|
1648
|
+
}
|
|
1649
|
+
};
|
|
1650
|
+
let client;
|
|
1651
|
+
try {
|
|
1652
|
+
client = await connect();
|
|
1653
|
+
}
|
|
1654
|
+
catch (error) {
|
|
1655
|
+
if (!["ENOENT", "ECONNREFUSED"].includes(error.code ?? ""))
|
|
1656
|
+
throw error;
|
|
1657
|
+
// The packaged canonical client owns artifact verification, owner checks and startup.
|
|
1658
|
+
// @ts-expect-error Generated by sync-runtime-client during package preparation.
|
|
1659
|
+
const { ensureRuntime } = await import("../runtime-client/src/runtime/client.mjs");
|
|
1660
|
+
await ensureRuntime({ agentDir: root, serverDir: process.env.PI_SERVER_DIR });
|
|
1661
|
+
client = await connect();
|
|
1662
|
+
}
|
|
1663
|
+
return client;
|
|
1664
|
+
}
|
|
1665
|
+
async refreshManagedResults() {
|
|
1666
|
+
if (!this.options.serverOwnedResults || !this.store || this.closed)
|
|
1667
|
+
return;
|
|
1668
|
+
const client = await this.resultSupervisionClient();
|
|
1669
|
+
try {
|
|
1670
|
+
await client.request("runtime_result_supervision");
|
|
1671
|
+
}
|
|
1672
|
+
finally {
|
|
1673
|
+
client.close();
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
/** A runner may finish between the server pass and this session's inspection. */
|
|
1677
|
+
async settledStatusForParent(ctx, taskId) {
|
|
1678
|
+
const observed = this.statusForParent(ctx, taskId);
|
|
1679
|
+
if (!this.options.serverOwnedResults || observed.terminalRevision > 0 || ["running", "starting"].includes(observed.status))
|
|
1680
|
+
return observed;
|
|
1681
|
+
await this.refreshManagedResults();
|
|
1682
|
+
const imported = this.statusForParent(ctx, taskId);
|
|
1683
|
+
if (imported.terminalRevision === 0)
|
|
1684
|
+
throw new Error("Terminal runner evidence is awaiting authoritative server import; supervision is unavailable.");
|
|
1685
|
+
return imported;
|
|
1686
|
+
}
|
|
1687
|
+
assertManagedResultAdmission(captured) {
|
|
1688
|
+
if (captured.policySource !== "no-publisher" && !currentForegroundSandboxPolicy(this.pi)) {
|
|
1689
|
+
throw new Error("permission-unavailable: expected current Background permission source is unavailable");
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
assertResultAdmission(captured, transferring = new Set()) {
|
|
1693
|
+
const discovery = this.requireStore().readDiscoveryClaim(this.discoveryScope);
|
|
1694
|
+
if (discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
|
|
1695
|
+
throw new Error("permission-unavailable: live or unknown original discovery holder prevents scope handoff");
|
|
1696
|
+
}
|
|
1697
|
+
if (captured.policySource !== "no-publisher" && !currentForegroundSandboxPolicy(this.pi)) {
|
|
1698
|
+
throw new Error("permission-unavailable: expected current Background permission source is unavailable");
|
|
1699
|
+
}
|
|
1700
|
+
for (const operation of this.requireStore().listOperations({ phase: "running" })) {
|
|
1701
|
+
if (!existsSync(this.sidecarPath(operation.taskId)) || this.requireStore().resultSupervision(operation.operationId))
|
|
1702
|
+
continue;
|
|
1703
|
+
// A compatible peer may be between registration and its grant transaction.
|
|
1704
|
+
// It cannot start a runner until that grant commits and never discovers globally.
|
|
1705
|
+
if (operation.supervision?.resultAdapter === 1)
|
|
1706
|
+
continue;
|
|
1707
|
+
if (this.supervisionAuthority(operation) === "foreign") {
|
|
1708
|
+
throw new Error("permission-unavailable: a live or unknown legacy operation holder prevents scope handoff");
|
|
1709
|
+
}
|
|
1710
|
+
// A dead holder is not itself a grant. Fencing discovery for a different
|
|
1711
|
+
// task would strand this runner: the server only imports explicit grants.
|
|
1712
|
+
if (!transferring.has(operation.operationId)) {
|
|
1713
|
+
throw new Error("permission-unavailable: an untransferred legacy operation prevents scope handoff; explicitly supervise its wait first");
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
async handoffResults(operations, newManaged = false) {
|
|
1718
|
+
const client = await this.resultSupervisionClient();
|
|
1719
|
+
try {
|
|
1720
|
+
const manager = await client.request("runtime_result_supervision");
|
|
1721
|
+
// Already granted dependencies need no discovery scope transfer. Legacy
|
|
1722
|
+
// holders may keep supervising unrelated work beside server-owned tasks.
|
|
1723
|
+
if (operations.every(operation => this.requireStore().resultSupervision(operation.operationId)))
|
|
1724
|
+
return;
|
|
1725
|
+
const discovery = this.requireStore().readDiscoveryClaim(this.discoveryScope);
|
|
1726
|
+
if (!newManaged && discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
|
|
1727
|
+
throw new Error("permission-unavailable: live or unknown original discovery holder prevents scope handoff");
|
|
1728
|
+
}
|
|
1729
|
+
const transfers = [];
|
|
1730
|
+
const transferring = new Set(operations.map(operation => operation.operationId));
|
|
1731
|
+
for (const operation of operations) {
|
|
1732
|
+
if (this.requireStore().resultSupervision(operation.operationId))
|
|
1733
|
+
continue;
|
|
1734
|
+
if (this.supervisionAuthority(operation) === "foreign" || this.localCancels.has(operation.taskId)) {
|
|
1735
|
+
throw new Error("permission-unavailable: original supervision owner is live, unknown or draining");
|
|
1736
|
+
}
|
|
1737
|
+
const context = this.launchContext(operation.taskId);
|
|
1738
|
+
if (!context?.sandbox || !context.supervisionPolicy || !operation.authorityRef)
|
|
1739
|
+
throw new Error("permission-unavailable: captured Background authority is unavailable");
|
|
1740
|
+
if (newManaged)
|
|
1741
|
+
this.assertManagedResultAdmission(context.sandbox);
|
|
1742
|
+
else
|
|
1743
|
+
this.assertResultAdmission(context.sandbox, transferring);
|
|
1744
|
+
const current = currentForegroundSandboxPolicy(this.pi);
|
|
1745
|
+
if (context.sandbox.policySource !== "no-publisher" && !current)
|
|
1746
|
+
throw new Error("permission-unavailable: expected current Background permission source is unavailable");
|
|
1747
|
+
transfers.push({ operationId: operation.operationId,
|
|
1748
|
+
expectedHostId: operation.supervision?.hostId ?? "unavailable", directory: this.directory, hostId: manager.hostId, epoch: manager.epoch,
|
|
1749
|
+
capability: { adapter: "background-results-v1", captured: { provenance: context.sandbox, policy: context.supervisionPolicy }, current: current ?? { state: "legacy-unconfined", policySource: "no-publisher" } } });
|
|
1750
|
+
}
|
|
1751
|
+
// Validate the whole batch, then stop admission before the durable CAS.
|
|
1752
|
+
for (const transfer of transfers)
|
|
1753
|
+
this.resultHandoffs.add(transfer.operationId);
|
|
1754
|
+
try {
|
|
1755
|
+
if (newManaged) {
|
|
1756
|
+
// New work grants only its own results; legacy discovery remains live.
|
|
1757
|
+
this.requireStore().handoffResultSupervisions(transfers);
|
|
1758
|
+
}
|
|
1759
|
+
else {
|
|
1760
|
+
this.requireStore().handoffResultScope({ scope: this.discoveryScope,
|
|
1761
|
+
expectedDiscovery: discovery ? { hostId: discovery.hostId, token: discovery.token } : null, grants: transfers });
|
|
1762
|
+
this.discoveryToken = undefined;
|
|
1763
|
+
this.discoveryRole = "follower";
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
catch (error) {
|
|
1767
|
+
// The transaction rolled back; only these uncommitted local fences may reopen.
|
|
1768
|
+
for (const transfer of transfers)
|
|
1769
|
+
this.resultHandoffs.delete(transfer.operationId);
|
|
1770
|
+
throw error;
|
|
1771
|
+
}
|
|
1772
|
+
await client.request("runtime_result_supervision");
|
|
1773
|
+
}
|
|
1774
|
+
finally {
|
|
1775
|
+
client.close();
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
async superviseParentWait(ctx, taskIds, note) {
|
|
1779
|
+
this.noteParentContext(ctx);
|
|
1780
|
+
const operations = this.operationsForTaskIds(this.ownerFor(ctx), taskIds);
|
|
1781
|
+
await this.handoffResults(operations);
|
|
1782
|
+
return this.waitForParent(ctx, taskIds, note);
|
|
1783
|
+
}
|
|
1784
|
+
waitViewForParent(ctx, waitId, generation) {
|
|
1785
|
+
const store = this.requireStore();
|
|
1786
|
+
const wait = store.getWait({ waitId, ...(generation ? { generation } : {}) });
|
|
1787
|
+
return wait && sameOwner(wait.owner, this.ownerFor(ctx)) ? this.waitView(wait) : undefined;
|
|
1788
|
+
}
|
|
1789
|
+
listWaitsForParent(ctx, options = {}) {
|
|
1790
|
+
this.noteParentContext(ctx);
|
|
1791
|
+
const store = this.requireStore();
|
|
1792
|
+
const owner = this.ownerFor(ctx);
|
|
1793
|
+
return store.listWaits({ owner, ...(options.pendingOnly ? { pendingOnly: true } : {}) }).map((wait) => this.waitView(wait));
|
|
1794
|
+
}
|
|
1795
|
+
cancelWaitForParent(ctx, waitId, generation, reason) {
|
|
1796
|
+
this.noteParentContext(ctx);
|
|
1797
|
+
return this.cancelWait(this.ownerFor(ctx), waitId, generation, reason);
|
|
1798
|
+
}
|
|
1799
|
+
acknowledgeForParent(ctx, input) {
|
|
1800
|
+
this.noteParentContext(ctx);
|
|
1801
|
+
return this.acknowledge(this.ownerFor(ctx), input);
|
|
1802
|
+
}
|
|
1803
|
+
// ---- worker service --------------------------------------------------
|
|
1804
|
+
ownsTask(run, taskId) {
|
|
1805
|
+
const operation = this.operationForTask(taskId);
|
|
1806
|
+
return !!operation && ownerMatchesOperation(operation, this.workerOwner(run));
|
|
1807
|
+
}
|
|
1808
|
+
async launchForWorker(run, input) {
|
|
1809
|
+
const store = this.requireStore();
|
|
1810
|
+
if (input.params.ssh)
|
|
1811
|
+
throw new Error("Worker background launches are local-only; structured SSH is unavailable through this service.");
|
|
1812
|
+
const owner = this.workerOwner(run);
|
|
1813
|
+
if (this.options.serverOwnedResults) {
|
|
1814
|
+
const client = await this.resultSupervisionClient();
|
|
1815
|
+
client.close();
|
|
1816
|
+
}
|
|
1817
|
+
const assertWorkerPolicy = this.options.prepareWorkerPolicy?.(run);
|
|
1818
|
+
const prepared = this.prepareLaunch(input.kind, input.params, input.kind === "watch" ? "bg_task_watch" : "bg_task_spawn", owner, input.policy, run.workspace);
|
|
1819
|
+
if (this.options.serverOwnedResults)
|
|
1820
|
+
this.assertManagedResultAdmission(prepared.provenance);
|
|
1821
|
+
const operationId = `op_${randomUUID()}`;
|
|
1822
|
+
const token = `launch_${randomUUID()}`;
|
|
1823
|
+
const taskId = supervisorTaskIdForToken(token);
|
|
1824
|
+
store.registerOperation({
|
|
1825
|
+
operationId,
|
|
1826
|
+
taskId,
|
|
1827
|
+
launchToken: token,
|
|
1828
|
+
owner,
|
|
1829
|
+
observer: OBSERVER,
|
|
1830
|
+
supervision: this.supervision(),
|
|
1831
|
+
authorityRef: authorityReference(`worker:${run.authorityReference}`),
|
|
1832
|
+
intentRef: typeof input.params.operation_id === "string" ? input.params.operation_id : null,
|
|
1833
|
+
...(run.assignmentAttemptId ? { assignmentAttemptId: run.assignmentAttemptId } : {}),
|
|
1834
|
+
});
|
|
1835
|
+
const launchContext = {
|
|
1836
|
+
workerAttemptId: run.runId,
|
|
1837
|
+
kind: input.kind,
|
|
1838
|
+
parentOrigin: this.parentOrigin,
|
|
1839
|
+
gated: prepared.gated,
|
|
1840
|
+
callback: false,
|
|
1841
|
+
...(typeof input.params.name === "string" ? { name: input.params.name } : {}),
|
|
1842
|
+
...(typeof input.params.command === "string" ? { command: input.params.command } : {}),
|
|
1843
|
+
...(prepared.spec.argv ? { argv: [...prepared.spec.argv] } : {}),
|
|
1844
|
+
cwd: prepared.cwd,
|
|
1845
|
+
sandbox: prepared.provenance,
|
|
1846
|
+
supervisionPolicy: prepared.plan,
|
|
1847
|
+
branchId: owner.branchId ?? null,
|
|
1848
|
+
};
|
|
1849
|
+
this.writeLaunchContext(taskId, launchContext);
|
|
1850
|
+
this.launches.set(taskId, launchContext);
|
|
1851
|
+
if (this.options.serverOwnedResults)
|
|
1852
|
+
await this.handoffResults([store.getOperation(operationId)], true);
|
|
1853
|
+
const started = await this.startSupervisor({
|
|
1854
|
+
token, taskId, kind: input.kind, params: input.params, prepared, operationId, assertDispatch: assertWorkerPolicy,
|
|
1855
|
+
});
|
|
1856
|
+
this.launches.set(taskId, launchContext);
|
|
1857
|
+
this.emitDurableTaskChange(owner);
|
|
1858
|
+
return {
|
|
1859
|
+
id: taskId,
|
|
1860
|
+
operationId,
|
|
1861
|
+
kind: input.kind,
|
|
1862
|
+
status: "running",
|
|
1863
|
+
...(typeof input.params.name === "string" ? { name: input.params.name } : {}),
|
|
1864
|
+
cwd: prepared.cwd,
|
|
1865
|
+
...(typeof input.params.command === "string" ? { command: input.params.command } : {}),
|
|
1866
|
+
...(prepared.spec.argv ? { argv: prepared.spec.argv } : {}),
|
|
1867
|
+
shell: prepared.spec.shell !== false,
|
|
1868
|
+
owner,
|
|
1869
|
+
started: started.started,
|
|
1870
|
+
claimed: started.claimed,
|
|
1871
|
+
notices: prepared.notices,
|
|
1872
|
+
};
|
|
1873
|
+
}
|
|
1874
|
+
statusForWorker(run, taskId) {
|
|
1875
|
+
return this.status(taskId, this.workerOwner(run));
|
|
1876
|
+
}
|
|
1877
|
+
logForWorker(run, taskId, options) {
|
|
1878
|
+
return this.log(taskId, this.workerOwner(run), options);
|
|
1879
|
+
}
|
|
1880
|
+
async stopForWorker(run, taskId) {
|
|
1881
|
+
return this.stop(taskId, this.workerOwner(run));
|
|
1882
|
+
}
|
|
1883
|
+
registerWorkerWait(run, input) {
|
|
1884
|
+
const store = this.requireStore();
|
|
1885
|
+
if (!this.continuation && this.rpcRuns.size === 0) {
|
|
1886
|
+
throw new Error("Worker parking requires a verified continuation adapter; start Subagents' coordinator before registering a park wait. The operation was not parked.");
|
|
1887
|
+
}
|
|
1888
|
+
const owner = this.workerOwner(run);
|
|
1889
|
+
const operations = this.operationsForTaskIds(owner, input.taskIds);
|
|
1890
|
+
const registered = store.registerWait({
|
|
1891
|
+
owner,
|
|
1892
|
+
dependencies: operations.map((operation) => ({ operationId: operation.operationId })),
|
|
1893
|
+
continuationNote: input.continuationNote,
|
|
1894
|
+
park: {
|
|
1895
|
+
attemptId: input.attemptId,
|
|
1896
|
+
checkpointId: input.checkpointId,
|
|
1897
|
+
...(input.writerLeaseId ? { writerLeaseId: input.writerLeaseId } : {}),
|
|
1898
|
+
},
|
|
1899
|
+
origin: { taskIds: [...input.taskIds], attemptId: input.attemptId },
|
|
1900
|
+
});
|
|
1901
|
+
const parking = store.transitionWaitPhase({
|
|
1902
|
+
waitId: registered.wait.waitId,
|
|
1903
|
+
generation: registered.wait.generation,
|
|
1904
|
+
from: "registering",
|
|
1905
|
+
to: "parking",
|
|
1906
|
+
reason: "waiting for the parked worker checkpoint",
|
|
1907
|
+
});
|
|
1908
|
+
return this.waitView(parking.wait);
|
|
1909
|
+
}
|
|
1910
|
+
async checkpointWorkerWait(run, input) {
|
|
1911
|
+
const store = this.requireStore();
|
|
1912
|
+
const owner = this.workerOwner(run);
|
|
1913
|
+
const wait = this.ownedWait(owner, input.waitId, input.generation);
|
|
1914
|
+
// A replacement host may replay the post-exit finalization. Once the
|
|
1915
|
+
// generation has left parking, the checkpoint is already proven.
|
|
1916
|
+
if (wait.phase === "waiting" || wait.phase === "ready" || wait.phase === "resuming" || wait.phase === "consumed") {
|
|
1917
|
+
return this.waitView(wait);
|
|
1918
|
+
}
|
|
1919
|
+
if (wait.phase !== "parking")
|
|
1920
|
+
throw new Error(`Wait ${wait.waitId} generation ${wait.generation} is ${wait.phase}, not parking.`);
|
|
1921
|
+
const proof = input.proof;
|
|
1922
|
+
if (!proof?.checkpointRecorded || !proof.writerLeaseReleased || !proof.writerPidGone) {
|
|
1923
|
+
throw new Error("A parked worker wait needs proven checkpoint commit, writer-lease release and original writer process exit before it can leave parking.");
|
|
1924
|
+
}
|
|
1925
|
+
const transitioned = store.transitionWaitPhase({
|
|
1926
|
+
waitId: wait.waitId,
|
|
1927
|
+
generation: wait.generation,
|
|
1928
|
+
from: "parking",
|
|
1929
|
+
to: "waiting",
|
|
1930
|
+
proof,
|
|
1931
|
+
reason: "checkpoint committed and the original writer exited",
|
|
1932
|
+
});
|
|
1933
|
+
await this.dispatchOutbox();
|
|
1934
|
+
return this.waitView(transitioned.wait);
|
|
1935
|
+
}
|
|
1936
|
+
/**
|
|
1937
|
+
* Record that the attempt could not become safely parked. A checkpoint that
|
|
1938
|
+
* was never committed must never look parked; if this store version cannot
|
|
1939
|
+
* hold an unproven generation, the generation is cancelled with the failure
|
|
1940
|
+
* reason instead of being left to block every future wait.
|
|
1941
|
+
*/
|
|
1942
|
+
failWorkerPark(run, input) {
|
|
1943
|
+
const store = this.requireStore();
|
|
1944
|
+
const owner = this.workerOwner(run);
|
|
1945
|
+
const wait = this.ownedWait(owner, input.waitId, input.generation);
|
|
1946
|
+
try {
|
|
1947
|
+
const transitioned = store.transitionWaitPhase({
|
|
1948
|
+
waitId: input.waitId,
|
|
1949
|
+
generation: input.generation,
|
|
1950
|
+
from: wait.phase,
|
|
1951
|
+
to: "held",
|
|
1952
|
+
reason: input.reason,
|
|
1953
|
+
});
|
|
1954
|
+
return this.waitView(transitioned.wait);
|
|
1955
|
+
}
|
|
1956
|
+
catch (error) {
|
|
1957
|
+
const code = error.code;
|
|
1958
|
+
if (code !== "checkpoint-proof" && code !== "wait-phase")
|
|
1959
|
+
throw error;
|
|
1960
|
+
return this.cancelWait(owner, input.waitId, input.generation, `park failed: ${input.reason}`);
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
readEvidence(run, input) {
|
|
1964
|
+
return this.readEvidenceForOwner(this.workerOwner(run), input.waitId, input.generation, input.taskId);
|
|
1965
|
+
}
|
|
1966
|
+
acknowledgeForWorker(run, input) {
|
|
1967
|
+
return this.acknowledge(this.workerOwner(run), input);
|
|
1968
|
+
}
|
|
1969
|
+
claimResumeForWorker(run, input) {
|
|
1970
|
+
const owner = this.workerOwner(run);
|
|
1971
|
+
this.ownedWait(owner, input.waitId, input.generation);
|
|
1972
|
+
const result = this.requireStore().claimResume({
|
|
1973
|
+
waitId: input.waitId,
|
|
1974
|
+
generation: input.generation,
|
|
1975
|
+
expectedCancelEpoch: input.expectedCancelEpoch,
|
|
1976
|
+
lease: {
|
|
1977
|
+
ownerId: input.lease.ownerId,
|
|
1978
|
+
...(input.lease.pid !== undefined ? { pid: input.lease.pid } : {}),
|
|
1979
|
+
...(input.lease.processStartToken !== undefined ? { processStartToken: input.lease.processStartToken } : {}),
|
|
1980
|
+
},
|
|
1981
|
+
reservedCheckpointId: input.reservedCheckpointId,
|
|
1982
|
+
});
|
|
1983
|
+
return {
|
|
1984
|
+
claimId: result.claim.claimId,
|
|
1985
|
+
claimToken: result.claim.claimToken,
|
|
1986
|
+
state: result.claim.state,
|
|
1987
|
+
attemptId: result.claim.attemptId,
|
|
1988
|
+
phase: result.wait.phase,
|
|
1989
|
+
cancelEpoch: result.wait.cancelEpoch,
|
|
1990
|
+
};
|
|
1991
|
+
}
|
|
1992
|
+
publishResumeForWorker(run, input) {
|
|
1993
|
+
this.ownedWait(this.workerOwner(run), input.waitId, input.generation);
|
|
1994
|
+
const result = this.requireStore().publishResumeAttempt({
|
|
1995
|
+
waitId: input.waitId,
|
|
1996
|
+
generation: input.generation,
|
|
1997
|
+
claimId: input.claimId,
|
|
1998
|
+
claimToken: input.claimToken,
|
|
1999
|
+
attemptId: input.attemptId,
|
|
2000
|
+
launchToken: input.launchToken,
|
|
2001
|
+
});
|
|
2002
|
+
return {
|
|
2003
|
+
claimId: result.claim.claimId,
|
|
2004
|
+
claimToken: result.claim.claimToken,
|
|
2005
|
+
state: result.claim.state,
|
|
2006
|
+
attemptId: result.claim.attemptId,
|
|
2007
|
+
phase: result.wait.phase,
|
|
2008
|
+
cancelEpoch: result.wait.cancelEpoch,
|
|
2009
|
+
};
|
|
2010
|
+
}
|
|
2011
|
+
releaseResumeForWorker(run, input) {
|
|
2012
|
+
this.ownedWait(this.workerOwner(run), input.waitId, input.generation);
|
|
2013
|
+
const result = this.requireStore().releaseResumeClaim({
|
|
2014
|
+
waitId: input.waitId,
|
|
2015
|
+
generation: input.generation,
|
|
2016
|
+
claimId: input.claimId,
|
|
2017
|
+
claimToken: input.claimToken,
|
|
2018
|
+
outcome: input.outcome,
|
|
2019
|
+
reason: input.reason,
|
|
2020
|
+
});
|
|
2021
|
+
return {
|
|
2022
|
+
claimId: result.claim.claimId,
|
|
2023
|
+
claimToken: result.claim.claimToken,
|
|
2024
|
+
state: result.claim.state,
|
|
2025
|
+
attemptId: result.claim.attemptId,
|
|
2026
|
+
phase: result.wait.phase,
|
|
2027
|
+
cancelEpoch: result.wait.cancelEpoch,
|
|
2028
|
+
};
|
|
2029
|
+
}
|
|
2030
|
+
listWorkerWaits(run, options = {}) {
|
|
2031
|
+
const store = this.requireStore();
|
|
2032
|
+
return store.listWaits({ owner: this.workerOwner(run), ...(options.pendingOnly ? { pendingOnly: true } : {}) })
|
|
2033
|
+
.map((wait) => this.waitView(wait));
|
|
2034
|
+
}
|
|
2035
|
+
cancelWorkerWait(run, input) {
|
|
2036
|
+
return this.cancelWait(this.workerOwner(run), input.waitId, input.generation, input.reason);
|
|
2037
|
+
}
|
|
2038
|
+
/**
|
|
2039
|
+
* A published continuation exited without interpreting its wait.
|
|
2040
|
+
*
|
|
2041
|
+
* This is not a cancellation: the epoch and evidence pins survive and the
|
|
2042
|
+
* generation becomes `held` with the failure reason. The claim is invalidated so
|
|
2043
|
+
* a second automatic attempt can never be published. Only a proven exit is
|
|
2044
|
+
* accepted; an ambiguous identity is refused and stays with its live writer.
|
|
2045
|
+
*/
|
|
2046
|
+
holdFailedResumeForWorker(run, input) {
|
|
2047
|
+
const owner = this.workerOwner(run);
|
|
2048
|
+
this.ownedWait(owner, input.waitId, input.generation);
|
|
2049
|
+
const result = this.requireStore().holdFailedResume({
|
|
2050
|
+
waitId: input.waitId,
|
|
2051
|
+
generation: input.generation,
|
|
2052
|
+
claimId: input.claimId,
|
|
2053
|
+
claimToken: input.claimToken,
|
|
2054
|
+
attemptId: input.attemptId,
|
|
2055
|
+
launchToken: input.launchToken,
|
|
2056
|
+
proof: { writerPidGone: input.proof?.writerPidGone === true, writerLeaseReleased: input.proof?.writerLeaseReleased === true },
|
|
2057
|
+
reason: input.reason,
|
|
2058
|
+
});
|
|
2059
|
+
return {
|
|
2060
|
+
waitId: input.waitId,
|
|
2061
|
+
generation: input.generation,
|
|
2062
|
+
phase: result.wait.phase,
|
|
2063
|
+
applied: result.applied,
|
|
2064
|
+
claim: {
|
|
2065
|
+
claimId: result.claim.claimId,
|
|
2066
|
+
state: result.claim.state,
|
|
2067
|
+
attemptId: result.claim.attemptId,
|
|
2068
|
+
...(result.claim.reason ? { reason: result.claim.reason } : {}),
|
|
2069
|
+
},
|
|
2070
|
+
};
|
|
2071
|
+
}
|
|
2072
|
+
registerContinuationAdapter(adapter) {
|
|
2073
|
+
if (!adapter || adapter.version !== 1 || typeof adapter.onWaitReady !== "function" || !adapter.id) {
|
|
2074
|
+
throw new Error("A version-1 continuation adapter is required.");
|
|
2075
|
+
}
|
|
2076
|
+
this.continuation = adapter;
|
|
2077
|
+
this.continuationError = undefined;
|
|
2078
|
+
this.announce();
|
|
2079
|
+
void this.dispatchOutbox();
|
|
2080
|
+
}
|
|
2081
|
+
unregisterContinuationAdapter(id) {
|
|
2082
|
+
if (this.continuation?.id === id)
|
|
2083
|
+
this.continuation = undefined;
|
|
2084
|
+
this.announce();
|
|
2085
|
+
}
|
|
2086
|
+
// ---- Subagents request/reply compatibility surface -------------------
|
|
2087
|
+
/** Answer the versioned request/reply channel the Subagents coordinator uses. */
|
|
2088
|
+
listenForWorkerRequests() {
|
|
2089
|
+
const events = eventBusOf(this.pi);
|
|
2090
|
+
if (!events)
|
|
2091
|
+
return;
|
|
2092
|
+
events.on(OBSERVED_WAITS_RPC_CHANNEL, (data) => {
|
|
2093
|
+
void this.handleWorkerRequest(data);
|
|
2094
|
+
});
|
|
2095
|
+
}
|
|
2096
|
+
async handleWorkerRequest(data) {
|
|
2097
|
+
if (!data || typeof data !== "object")
|
|
2098
|
+
return;
|
|
2099
|
+
const request = data;
|
|
2100
|
+
if (request.version !== OBSERVED_WAITS_RPC_VERSION || typeof request.method !== "string" ||
|
|
2101
|
+
typeof request.reply !== "function")
|
|
2102
|
+
return;
|
|
2103
|
+
const reply = request.reply;
|
|
2104
|
+
let answered = false;
|
|
2105
|
+
const answer = (value) => {
|
|
2106
|
+
if (answered)
|
|
2107
|
+
return;
|
|
2108
|
+
answered = true;
|
|
2109
|
+
try {
|
|
2110
|
+
reply(value);
|
|
2111
|
+
}
|
|
2112
|
+
catch { /* the requester timed out */ }
|
|
2113
|
+
};
|
|
2114
|
+
const params = request.params && typeof request.params === "object" && !Array.isArray(request.params)
|
|
2115
|
+
? request.params
|
|
2116
|
+
: {};
|
|
2117
|
+
if (!this.available && !this.closed) {
|
|
2118
|
+
// A capability probe may arrive before the session_start handler that
|
|
2119
|
+
// normally opens the store. Worker operations are parent-owned, so the
|
|
2120
|
+
// store can open now; the next parent context supplies its origin.
|
|
2121
|
+
this.start();
|
|
2122
|
+
}
|
|
2123
|
+
if (!this.available) {
|
|
2124
|
+
answer({ ok: false, code: "unavailable", reason: this.unavailableReason ?? "Observed waits are unavailable." });
|
|
2125
|
+
return;
|
|
2126
|
+
}
|
|
2127
|
+
try {
|
|
2128
|
+
answer({ ok: true, value: await this.dispatchWorkerRequest(request.method, params) });
|
|
2129
|
+
}
|
|
2130
|
+
catch (error) {
|
|
2131
|
+
answer({
|
|
2132
|
+
ok: false,
|
|
2133
|
+
code: rpcCode(error),
|
|
2134
|
+
reason: oneLine(error instanceof Error ? error.message : String(error), 500),
|
|
2135
|
+
});
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
async dispatchWorkerRequest(method, params) {
|
|
2139
|
+
switch (method) {
|
|
2140
|
+
case "status":
|
|
2141
|
+
return { version: OBSERVED_WAITS_RPC_VERSION, workerOperations: true, runs: this.rpcRuns.size };
|
|
2142
|
+
case "register-run":
|
|
2143
|
+
return this.rpcRegisterRun(params);
|
|
2144
|
+
case "release-run":
|
|
2145
|
+
return this.rpcReleaseRun(params);
|
|
2146
|
+
case "execute-tool":
|
|
2147
|
+
return this.rpcExecuteTool(params);
|
|
2148
|
+
case "wait-admission":
|
|
2149
|
+
return this.rpcWaitAdmission(params);
|
|
2150
|
+
case "checkpoint":
|
|
2151
|
+
return this.rpcCheckpoint(params);
|
|
2152
|
+
case "park-failed":
|
|
2153
|
+
return this.rpcParkFailed(params);
|
|
2154
|
+
case "acknowledge":
|
|
2155
|
+
return this.rpcAcknowledge(params);
|
|
2156
|
+
case "wait-snapshot":
|
|
2157
|
+
return this.rpcWaitSnapshot(params);
|
|
2158
|
+
case "claim-resume":
|
|
2159
|
+
return this.rpcClaimResume(params);
|
|
2160
|
+
case "publish-resume":
|
|
2161
|
+
return this.rpcPublishResume(params);
|
|
2162
|
+
case "release-resume":
|
|
2163
|
+
return this.rpcReleaseResume(params);
|
|
2164
|
+
case "hold-resume":
|
|
2165
|
+
return this.rpcHoldResume(params);
|
|
2166
|
+
case "cancel-wait":
|
|
2167
|
+
return this.rpcCancelWait(params);
|
|
2168
|
+
default:
|
|
2169
|
+
throw new Error(`Unsupported observed-waits method ${JSON.stringify(method)}.`);
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
2172
|
+
rpcRegisterRun(params) {
|
|
2173
|
+
if (params.assignmentOutcomesVersion !== undefined && params.assignmentOutcomesVersion !== 1)
|
|
2174
|
+
throw new Error("Unsupported assignment outcome capability; this host supports version 1.");
|
|
2175
|
+
const runId = requireRpcString(params, "runId");
|
|
2176
|
+
const conversationId = requireRpcString(params, "conversationId");
|
|
2177
|
+
const workspace = requireRpcString(params, "workspace");
|
|
2178
|
+
const authorityReference = requireRpcString(params, "authorityReference");
|
|
2179
|
+
const policy = normalizeRunPolicy(params.policy);
|
|
2180
|
+
if (policy.workspace !== workspace)
|
|
2181
|
+
throw new Error("register-run policy.workspace does not match the registered workspace.");
|
|
2182
|
+
const attemptId = typeof params.attemptId === "string" && params.attemptId ? params.attemptId : runId;
|
|
2183
|
+
const owner = normalizeRpcOwner(params.owner, {
|
|
2184
|
+
kind: "worker-conversation",
|
|
2185
|
+
sessionId: conversationId,
|
|
2186
|
+
workspace,
|
|
2187
|
+
branchId: null,
|
|
2188
|
+
goalId: null,
|
|
2189
|
+
});
|
|
2190
|
+
if (owner.sessionId !== conversationId || owner.workspace !== workspace) {
|
|
2191
|
+
throw new Error("register-run owner does not match the conversation and workspace.");
|
|
2192
|
+
}
|
|
2193
|
+
const tools = new Set(Array.isArray(params.tools)
|
|
2194
|
+
? params.tools.filter((tool) => typeof tool === "string")
|
|
2195
|
+
: policy.tools);
|
|
2196
|
+
const capabilities = params.capabilities && typeof params.capabilities === "object" && !Array.isArray(params.capabilities)
|
|
2197
|
+
? params.capabilities
|
|
2198
|
+
: {};
|
|
2199
|
+
this.rpcRuns.set(runId, Object.freeze({
|
|
2200
|
+
runId,
|
|
2201
|
+
assignmentTaskOwnership: params.assignmentTaskOwnership === true,
|
|
2202
|
+
conversationId,
|
|
2203
|
+
attemptId,
|
|
2204
|
+
workspace,
|
|
2205
|
+
authorityReference,
|
|
2206
|
+
policy,
|
|
2207
|
+
owner,
|
|
2208
|
+
tools,
|
|
2209
|
+
capabilities,
|
|
2210
|
+
...(typeof params.writerPid === "number" && params.writerPid > 0 ? { writerPid: params.writerPid } : {}),
|
|
2211
|
+
...(typeof params.writerLeaseId === "string" ? { writerLeaseId: params.writerLeaseId } : {}),
|
|
2212
|
+
}));
|
|
2213
|
+
return { runId, conversationId, workspace, attemptId, workerOperations: true, assignmentOutcomesVersion: 1 };
|
|
2214
|
+
}
|
|
2215
|
+
rpcReleaseRun(params) {
|
|
2216
|
+
const runId = requireRpcString(params, "runId");
|
|
2217
|
+
this.rpcRuns.delete(runId);
|
|
2218
|
+
if (this.rpcRuns.size === 0)
|
|
2219
|
+
this.waitOwners.clear();
|
|
2220
|
+
return { runId, released: true };
|
|
2221
|
+
}
|
|
2222
|
+
async rpcExecuteTool(params) {
|
|
2223
|
+
const binding = this.requireRpcRun(params);
|
|
2224
|
+
const tool = requireRpcString(params, "tool");
|
|
2225
|
+
const toolParams = params.params && typeof params.params === "object" && !Array.isArray(params.params)
|
|
2226
|
+
? params.params
|
|
2227
|
+
: {};
|
|
2228
|
+
if (!binding.tools.has(tool)) {
|
|
2229
|
+
throw new Error(`Tool ${tool} is not in this run's captured tool allowlist.`);
|
|
2230
|
+
}
|
|
2231
|
+
const run = this.rpcScope(binding);
|
|
2232
|
+
const deadlineParams = this.withAssignmentDeadline(binding, toolParams);
|
|
2233
|
+
switch (tool) {
|
|
2234
|
+
case "bg_task_spawn":
|
|
2235
|
+
case "bg_task_watch": {
|
|
2236
|
+
const launch = await this.launchForWorker(run, {
|
|
2237
|
+
kind: tool === "bg_task_watch" ? "watch" : "process",
|
|
2238
|
+
params: deadlineParams,
|
|
2239
|
+
policy: binding.policy.sandbox,
|
|
2240
|
+
});
|
|
2241
|
+
return {
|
|
2242
|
+
id: launch.id,
|
|
2243
|
+
taskId: launch.id,
|
|
2244
|
+
operationId: launch.operationId,
|
|
2245
|
+
kind: launch.kind,
|
|
2246
|
+
status: launch.status,
|
|
2247
|
+
name: launch.name,
|
|
2248
|
+
cwd: launch.cwd,
|
|
2249
|
+
owner: launch.owner,
|
|
2250
|
+
durable: true,
|
|
2251
|
+
started: launch.started,
|
|
2252
|
+
claimed: launch.claimed,
|
|
2253
|
+
notices: launch.notices,
|
|
2254
|
+
...(launch.firstCheck ? { firstCheck: launch.firstCheck } : {}),
|
|
2255
|
+
};
|
|
2256
|
+
}
|
|
2257
|
+
case "bg_task_status": {
|
|
2258
|
+
const taskId = this.requireOwnedRpcTask(binding, toolParams);
|
|
2259
|
+
return this.statusForWorker(run, taskId);
|
|
2260
|
+
}
|
|
2261
|
+
case "bg_task_log": {
|
|
2262
|
+
const taskId = this.requireOwnedRpcTask(binding, toolParams);
|
|
2263
|
+
return this.logForWorker(run, taskId, {
|
|
2264
|
+
...(typeof toolParams.lines === "number" ? { lines: toolParams.lines } : {}),
|
|
2265
|
+
});
|
|
2266
|
+
}
|
|
2267
|
+
case "bg_task_stop": {
|
|
2268
|
+
const taskId = this.requireOwnedRpcTask(binding, toolParams);
|
|
2269
|
+
return await this.stopForWorker(run, taskId);
|
|
2270
|
+
}
|
|
2271
|
+
default:
|
|
2272
|
+
throw new Error(`Tool ${tool} is not supported by the observed-waits execute-tool surface.`);
|
|
2273
|
+
}
|
|
2274
|
+
}
|
|
2275
|
+
rpcWaitAdmission(params) {
|
|
2276
|
+
const binding = this.requireRpcRun(params);
|
|
2277
|
+
const taskIds = Array.isArray(params.taskIds)
|
|
2278
|
+
? params.taskIds.filter((taskId) => typeof taskId === "string")
|
|
2279
|
+
: Array.isArray(params.task_ids)
|
|
2280
|
+
? params.task_ids.filter((taskId) => typeof taskId === "string")
|
|
2281
|
+
: [];
|
|
2282
|
+
if (taskIds.length === 0)
|
|
2283
|
+
throw new Error("wait-admission needs at least one task id.");
|
|
2284
|
+
for (const taskId of taskIds)
|
|
2285
|
+
this.requireOwnedRpcTask(binding, { id: taskId });
|
|
2286
|
+
const note = typeof params.continuationNote === "string" ? params.continuationNote
|
|
2287
|
+
: typeof params.continuation_note === "string" ? params.continuation_note : "";
|
|
2288
|
+
if (!note.trim())
|
|
2289
|
+
throw new Error("wait-admission needs a continuation note.");
|
|
2290
|
+
const owner = normalizeRpcOwner(params.owner, binding.owner);
|
|
2291
|
+
if (owner.sessionId !== binding.conversationId || owner.workspace !== binding.workspace) {
|
|
2292
|
+
throw new Error("wait-admission owner does not match the registered conversation and workspace.");
|
|
2293
|
+
}
|
|
2294
|
+
const attemptId = typeof params.attemptId === "string" && params.attemptId ? params.attemptId : binding.attemptId;
|
|
2295
|
+
const run = {
|
|
2296
|
+
runId: binding.runId,
|
|
2297
|
+
conversationId: binding.conversationId,
|
|
2298
|
+
workspace: binding.workspace,
|
|
2299
|
+
authorityReference: binding.authorityReference,
|
|
2300
|
+
branchId: owner.branchId ?? null,
|
|
2301
|
+
goalId: owner.goalId ?? null,
|
|
2302
|
+
};
|
|
2303
|
+
const wait = this.registerWorkerWait(run, {
|
|
2304
|
+
taskIds,
|
|
2305
|
+
continuationNote: note,
|
|
2306
|
+
attemptId,
|
|
2307
|
+
checkpointId: `park:${attemptId}`,
|
|
2308
|
+
...(binding.writerLeaseId ? { writerLeaseId: binding.writerLeaseId } : {}),
|
|
2309
|
+
});
|
|
2310
|
+
this.waitOwners.set(waitKey(wait.waitId, wait.generation), this.workerOwner(run));
|
|
2311
|
+
return { ...wait, park: true };
|
|
2312
|
+
}
|
|
2313
|
+
rpcCheckpoint(params) {
|
|
2314
|
+
const binding = this.requireRpcRun(params);
|
|
2315
|
+
const waitId = requireRpcString(params, "waitId");
|
|
2316
|
+
const generation = requireRpcCounter(params, "generation");
|
|
2317
|
+
const { wait, owner } = this.ownedRpcWait(binding, waitId, generation);
|
|
2318
|
+
if (wait.phase === "waiting" || wait.phase === "ready" || wait.phase === "resuming") {
|
|
2319
|
+
return { checkpointed: true, phase: wait.phase, staged: false };
|
|
2320
|
+
}
|
|
2321
|
+
if (wait.phase !== "parking") {
|
|
2322
|
+
throw new Error(`Wait ${waitId} generation ${generation} is ${wait.phase}; a checkpoint can only be recorded while parking.`);
|
|
2323
|
+
}
|
|
2324
|
+
const key = waitKey(waitId, generation);
|
|
2325
|
+
const evidence = params.evidence && typeof params.evidence === "object" && !Array.isArray(params.evidence)
|
|
2326
|
+
? params.evidence
|
|
2327
|
+
: undefined;
|
|
2328
|
+
const staged = this.stagedCheckpoints.get(key);
|
|
2329
|
+
if (!evidence && !staged)
|
|
2330
|
+
throw new Error("A park checkpoint needs the verified native checkpoint evidence.");
|
|
2331
|
+
if (evidence) {
|
|
2332
|
+
this.stagedCheckpoints.set(key, {
|
|
2333
|
+
evidence,
|
|
2334
|
+
toolCallId: typeof params.toolCallId === "string" ? params.toolCallId
|
|
2335
|
+
: typeof params.tool_call_id === "string" ? params.tool_call_id : "",
|
|
2336
|
+
checkpointRecorded: true,
|
|
2337
|
+
});
|
|
2338
|
+
}
|
|
2339
|
+
const proofParam = params.proof && typeof params.proof === "object" && !Array.isArray(params.proof)
|
|
2340
|
+
? params.proof
|
|
2341
|
+
: undefined;
|
|
2342
|
+
const writerLeaseReleased = params.writerLeaseReleased === true || proofParam?.writerLeaseReleased === true;
|
|
2343
|
+
const writerPidGone = params.writerPidGone === true || proofParam?.writerPidGone === true
|
|
2344
|
+
|| (binding.writerPid !== undefined && !processExists(binding.writerPid));
|
|
2345
|
+
if (!writerLeaseReleased || !writerPidGone) {
|
|
2346
|
+
// Staged while the child is alive. The trusted writer-exit observation
|
|
2347
|
+
// must make a second call; the wait never looks parked before that.
|
|
2348
|
+
return { checkpointed: true, phase: "parking", staged: true };
|
|
2349
|
+
}
|
|
2350
|
+
const transitioned = this.requireStore().transitionWaitPhase({
|
|
2351
|
+
waitId,
|
|
2352
|
+
generation,
|
|
2353
|
+
from: "parking",
|
|
2354
|
+
to: "waiting",
|
|
2355
|
+
proof: { checkpointRecorded: true, writerLeaseReleased: true, writerPidGone: true },
|
|
2356
|
+
reason: "trusted park checkpoint and writer process exit",
|
|
2357
|
+
});
|
|
2358
|
+
this.stagedCheckpoints.delete(key);
|
|
2359
|
+
void this.dispatchOutbox();
|
|
2360
|
+
return { checkpointed: true, phase: transitioned.wait.phase, staged: false };
|
|
2361
|
+
}
|
|
2362
|
+
rpcParkFailed(params) {
|
|
2363
|
+
const binding = this.requireRpcRun(params);
|
|
2364
|
+
const waitId = requireRpcString(params, "waitId");
|
|
2365
|
+
const generation = requireRpcCounter(params, "generation");
|
|
2366
|
+
const reason = requireRpcString(params, "reason");
|
|
2367
|
+
const { wait, owner } = this.ownedRpcWait(binding, waitId, generation);
|
|
2368
|
+
const run = {
|
|
2369
|
+
runId: binding.runId,
|
|
2370
|
+
conversationId: binding.conversationId,
|
|
2371
|
+
workspace: binding.workspace,
|
|
2372
|
+
authorityReference: binding.authorityReference,
|
|
2373
|
+
branchId: owner.branchId ?? null,
|
|
2374
|
+
goalId: owner.goalId ?? null,
|
|
2375
|
+
};
|
|
2376
|
+
const failed = this.failWorkerPark(run, { waitId, generation, reason });
|
|
2377
|
+
this.stagedCheckpoints.delete(waitKey(waitId, generation));
|
|
2378
|
+
return { waitId, generation, phase: failed.phase, held: failed.phase === "held" };
|
|
2379
|
+
}
|
|
2380
|
+
rpcAcknowledge(params) {
|
|
2381
|
+
const binding = this.requireRpcRun(params);
|
|
2382
|
+
const waitId = requireRpcString(params, "waitId" in params ? "waitId" : "wait_id");
|
|
2383
|
+
const generation = requireRpcCounter(params, "generation");
|
|
2384
|
+
const { owner } = this.ownedRpcWait(binding, waitId, generation);
|
|
2385
|
+
const disposition = params.disposition;
|
|
2386
|
+
if (disposition !== "continue" && disposition !== "blocked" && disposition !== "assignment-complete") {
|
|
2387
|
+
throw new Error("acknowledge disposition must be continue, blocked or assignment-complete.");
|
|
2388
|
+
}
|
|
2389
|
+
const note = typeof params.note === "string" ? params.note : "";
|
|
2390
|
+
const ack = this.acknowledge(owner, {
|
|
2391
|
+
waitId,
|
|
2392
|
+
generation,
|
|
2393
|
+
terminalRevisions: params.terminal_revisions ?? params.terminalRevisions,
|
|
2394
|
+
disposition,
|
|
2395
|
+
note,
|
|
2396
|
+
});
|
|
2397
|
+
return ack;
|
|
2398
|
+
}
|
|
2399
|
+
rpcWaitSnapshot(params) {
|
|
2400
|
+
const waitId = requireRpcString(params, "waitId");
|
|
2401
|
+
const generation = requireRpcCounter(params, "generation");
|
|
2402
|
+
const wait = this.requireStore().getWait({ waitId, generation });
|
|
2403
|
+
if (!wait)
|
|
2404
|
+
throw new Error(`Unknown wait ${waitId} generation ${generation}.`);
|
|
2405
|
+
if (wait.owner.kind !== "worker-conversation")
|
|
2406
|
+
throw new Error(`Wait ${waitId} does not belong to a worker conversation.`);
|
|
2407
|
+
const registered = [...this.rpcRuns.values()].some((run) => run.conversationId === wait.owner.sessionId && run.workspace === wait.owner.workspace);
|
|
2408
|
+
if (!registered)
|
|
2409
|
+
throw new Error(`Wait ${waitId} belongs to a conversation with no registered worker run.`);
|
|
2410
|
+
const claims = this.requireStore().listResumeClaims({ waitId, generation });
|
|
2411
|
+
const active = claims.find((claim) => claim.state === "claimed" || claim.state === "published");
|
|
2412
|
+
const view = this.waitView(wait);
|
|
2413
|
+
return {
|
|
2414
|
+
...view,
|
|
2415
|
+
cancelEpoch: wait.cancelEpoch,
|
|
2416
|
+
claim: active ? {
|
|
2417
|
+
claimId: active.claimId,
|
|
2418
|
+
state: active.state,
|
|
2419
|
+
attemptId: active.attemptId,
|
|
2420
|
+
reservedCheckpointId: active.reservedCheckpointId,
|
|
2421
|
+
} : null,
|
|
2422
|
+
};
|
|
2423
|
+
}
|
|
2424
|
+
rpcClaimResume(params) {
|
|
2425
|
+
const binding = this.requireRpcRun(params);
|
|
2426
|
+
const waitId = requireRpcString(params, "waitId");
|
|
2427
|
+
const generation = requireRpcCounter(params, "generation");
|
|
2428
|
+
const { owner } = this.ownedRpcWait(binding, waitId, generation);
|
|
2429
|
+
const lease = params.lease && typeof params.lease === "object" && !Array.isArray(params.lease)
|
|
2430
|
+
? params.lease
|
|
2431
|
+
: undefined;
|
|
2432
|
+
if (!lease || typeof lease.ownerId !== "string" || !lease.ownerId)
|
|
2433
|
+
throw new Error("claim-resume requires a lease ownerId.");
|
|
2434
|
+
const result = this.requireStore().claimResume({
|
|
2435
|
+
waitId,
|
|
2436
|
+
generation,
|
|
2437
|
+
expectedCancelEpoch: requireRpcCounter(params, "expectedCancelEpoch"),
|
|
2438
|
+
lease: {
|
|
2439
|
+
ownerId: lease.ownerId,
|
|
2440
|
+
...(typeof lease.pid === "number" ? { pid: lease.pid } : {}),
|
|
2441
|
+
...(typeof lease.processStartToken === "string" ? { processStartToken: lease.processStartToken } : {}),
|
|
2442
|
+
},
|
|
2443
|
+
reservedCheckpointId: requireRpcString(params, "reservedCheckpointId"),
|
|
2444
|
+
});
|
|
2445
|
+
void owner;
|
|
2446
|
+
return {
|
|
2447
|
+
claimId: result.claim.claimId,
|
|
2448
|
+
claimToken: result.claim.claimToken,
|
|
2449
|
+
waitId,
|
|
2450
|
+
generation,
|
|
2451
|
+
phase: result.wait.phase,
|
|
2452
|
+
cancelEpoch: result.wait.cancelEpoch,
|
|
2453
|
+
};
|
|
2454
|
+
}
|
|
2455
|
+
rpcPublishResume(params) {
|
|
2456
|
+
const binding = this.requireRpcRun(params);
|
|
2457
|
+
const waitId = requireRpcString(params, "waitId");
|
|
2458
|
+
const generation = requireRpcCounter(params, "generation");
|
|
2459
|
+
this.ownedRpcWait(binding, waitId, generation);
|
|
2460
|
+
const result = this.requireStore().publishResumeAttempt({
|
|
2461
|
+
waitId,
|
|
2462
|
+
generation,
|
|
2463
|
+
claimId: requireRpcString(params, "claimId"),
|
|
2464
|
+
claimToken: requireRpcString(params, "claimToken"),
|
|
2465
|
+
attemptId: requireRpcString(params, "attemptId"),
|
|
2466
|
+
launchToken: requireRpcString(params, "launchToken"),
|
|
2467
|
+
});
|
|
2468
|
+
return {
|
|
2469
|
+
claimId: result.claim.claimId,
|
|
2470
|
+
state: result.claim.state,
|
|
2471
|
+
attemptId: result.claim.attemptId,
|
|
2472
|
+
published: result.published,
|
|
2473
|
+
phase: result.wait.phase,
|
|
2474
|
+
};
|
|
2475
|
+
}
|
|
2476
|
+
rpcReleaseResume(params) {
|
|
2477
|
+
const binding = this.requireRpcRun(params);
|
|
2478
|
+
const waitId = requireRpcString(params, "waitId");
|
|
2479
|
+
const generation = requireRpcCounter(params, "generation");
|
|
2480
|
+
this.ownedRpcWait(binding, waitId, generation);
|
|
2481
|
+
const outcome = params.outcome;
|
|
2482
|
+
if (outcome !== "ready" && outcome !== "held")
|
|
2483
|
+
throw new Error("release-resume outcome must be ready or held.");
|
|
2484
|
+
const result = this.requireStore().releaseResumeClaim({
|
|
2485
|
+
waitId,
|
|
2486
|
+
generation,
|
|
2487
|
+
claimId: requireRpcString(params, "claimId"),
|
|
2488
|
+
claimToken: requireRpcString(params, "claimToken"),
|
|
2489
|
+
outcome,
|
|
2490
|
+
reason: requireRpcString(params, "reason"),
|
|
2491
|
+
});
|
|
2492
|
+
return { claimId: result.claim.claimId, state: result.claim.state, phase: result.wait.phase };
|
|
2493
|
+
}
|
|
2494
|
+
rpcHoldResume(params) {
|
|
2495
|
+
const binding = this.requireRpcRun(params);
|
|
2496
|
+
const waitId = requireRpcString(params, "waitId");
|
|
2497
|
+
const generation = requireRpcCounter(params, "generation");
|
|
2498
|
+
this.ownedRpcWait(binding, waitId, generation);
|
|
2499
|
+
const owner = this.workerOwner(this.rpcScope(binding));
|
|
2500
|
+
const proof = params.proof && typeof params.proof === "object" && !Array.isArray(params.proof)
|
|
2501
|
+
? params.proof
|
|
2502
|
+
: {};
|
|
2503
|
+
const result = this.holdFailedResumeForWorker(this.rpcScope(binding), {
|
|
2504
|
+
waitId,
|
|
2505
|
+
generation,
|
|
2506
|
+
claimId: requireRpcString(params, "claimId"),
|
|
2507
|
+
claimToken: requireRpcString(params, "claimToken"),
|
|
2508
|
+
attemptId: requireRpcString(params, "attemptId"),
|
|
2509
|
+
launchToken: requireRpcString(params, "launchToken"),
|
|
2510
|
+
proof: {
|
|
2511
|
+
writerPidGone: proof.writerPidGone === true,
|
|
2512
|
+
writerLeaseReleased: proof.writerLeaseReleased === true,
|
|
2513
|
+
},
|
|
2514
|
+
reason: requireRpcString(params, "reason"),
|
|
2515
|
+
});
|
|
2516
|
+
void owner;
|
|
2517
|
+
return result;
|
|
2518
|
+
}
|
|
2519
|
+
rpcCancelWait(params) {
|
|
2520
|
+
const binding = this.requireRpcRun(params);
|
|
2521
|
+
const waitId = requireRpcString(params, "waitId");
|
|
2522
|
+
const generation = requireRpcCounter(params, "generation");
|
|
2523
|
+
const { wait } = this.ownedRpcWait(binding, waitId, generation);
|
|
2524
|
+
const reason = requireRpcString(params, "reason");
|
|
2525
|
+
const expected = typeof params.expectedCancelEpoch === "number"
|
|
2526
|
+
? params.expectedCancelEpoch
|
|
2527
|
+
: wait.cancelEpoch;
|
|
2528
|
+
const result = this.requireStore().cancelWait({
|
|
2529
|
+
waitId,
|
|
2530
|
+
generation,
|
|
2531
|
+
expectedCancelEpoch: expected,
|
|
2532
|
+
owner: wait.owner,
|
|
2533
|
+
reason,
|
|
2534
|
+
});
|
|
2535
|
+
this.stagedCheckpoints.delete(waitKey(waitId, generation));
|
|
2536
|
+
try {
|
|
2537
|
+
void Promise.resolve(this.continuation?.onWaitCancelled?.({ waitId, generation, reason })).catch(() => { });
|
|
2538
|
+
}
|
|
2539
|
+
catch { /* persisted cancellation stands */ }
|
|
2540
|
+
return { waitId, generation, phase: result.wait.phase, cancelEpoch: result.wait.cancelEpoch };
|
|
2541
|
+
}
|
|
2542
|
+
requireRpcRun(params) {
|
|
2543
|
+
const runId = requireRpcString(params, "runId");
|
|
2544
|
+
const binding = this.rpcRuns.get(runId);
|
|
2545
|
+
if (!binding)
|
|
2546
|
+
throw new Error(`Run ${runId} is not registered with the Background observed-waits service.`);
|
|
2547
|
+
if (typeof params.conversationId === "string" && params.conversationId !== binding.conversationId) {
|
|
2548
|
+
throw new Error(`Run ${runId} belongs to a different conversation.`);
|
|
2549
|
+
}
|
|
2550
|
+
return binding;
|
|
2551
|
+
}
|
|
2552
|
+
rpcScope(binding) {
|
|
2553
|
+
return {
|
|
2554
|
+
runId: binding.runId,
|
|
2555
|
+
...(binding.assignmentTaskOwnership ? { assignmentAttemptId: binding.attemptId } : {}),
|
|
2556
|
+
conversationId: binding.conversationId,
|
|
2557
|
+
workspace: binding.workspace,
|
|
2558
|
+
authorityReference: binding.authorityReference,
|
|
2559
|
+
branchId: binding.owner.branchId ?? null,
|
|
2560
|
+
goalId: binding.owner.goalId ?? null,
|
|
2561
|
+
};
|
|
2562
|
+
}
|
|
2563
|
+
requireOwnedRpcTask(binding, params) {
|
|
2564
|
+
const taskId = requireRpcString(params, "id");
|
|
2565
|
+
if (!LOCAL_DURABLE_ID.test(taskId))
|
|
2566
|
+
throw new Error(`Task ${taskId} is not a durable local operation.`);
|
|
2567
|
+
const operation = this.operationForTask(taskId);
|
|
2568
|
+
if (!operation)
|
|
2569
|
+
throw new Error(`Unknown durable task ${taskId}.`);
|
|
2570
|
+
if (operation.owner.kind !== "worker-conversation" ||
|
|
2571
|
+
operation.owner.sessionId !== binding.conversationId ||
|
|
2572
|
+
operation.owner.workspace !== binding.workspace) {
|
|
2573
|
+
throw new Error(`Task ${taskId} is not owned by this worker conversation.`);
|
|
2574
|
+
}
|
|
2575
|
+
return taskId;
|
|
2576
|
+
}
|
|
2577
|
+
ownedRpcWait(binding, waitId, generation) {
|
|
2578
|
+
const wait = this.requireStore().getWait({ waitId, generation });
|
|
2579
|
+
if (!wait)
|
|
2580
|
+
throw new Error(`Unknown wait ${waitId} generation ${generation}.`);
|
|
2581
|
+
if (wait.owner.kind !== "worker-conversation" ||
|
|
2582
|
+
wait.owner.sessionId !== binding.conversationId ||
|
|
2583
|
+
wait.owner.workspace !== binding.workspace) {
|
|
2584
|
+
throw new Error(`Wait ${waitId} is not owned by this worker conversation.`);
|
|
2585
|
+
}
|
|
2586
|
+
return { wait, owner: wait.owner };
|
|
2587
|
+
}
|
|
2588
|
+
withAssignmentDeadline(binding, params) {
|
|
2589
|
+
const deadlineAt = binding.policy.deadlineAt;
|
|
2590
|
+
if (deadlineAt === null)
|
|
2591
|
+
return params;
|
|
2592
|
+
const remaining = (deadlineAt - (this.options.now?.() ?? Date.now())) / 1000;
|
|
2593
|
+
if (!(remaining > 0))
|
|
2594
|
+
throw new Error("The assignment deadline has expired; no background task was launched.");
|
|
2595
|
+
const requested = typeof params.timeout_seconds === "number" ? params.timeout_seconds : undefined;
|
|
2596
|
+
const timeout = requested === undefined || requested === 0
|
|
2597
|
+
? remaining
|
|
2598
|
+
: Math.min(requested, remaining);
|
|
2599
|
+
return { ...params, timeout_seconds: timeout };
|
|
2600
|
+
}
|
|
2601
|
+
// ---- launch preparation and admission --------------------------------
|
|
2602
|
+
prepareLaunch(kind, params, tool, owner, workerPolicy, workerWorkspace) {
|
|
2603
|
+
const cwd = workerWorkspace !== undefined
|
|
2604
|
+
? this.resolveWorkerCwd(workerWorkspace, params.cwd)
|
|
2605
|
+
: typeof params.cwd === "string" && params.cwd.length > 0
|
|
2606
|
+
? params.cwd
|
|
2607
|
+
: this.parentOrigin?.cwd ?? owner.workspace;
|
|
2608
|
+
const spec = {
|
|
2609
|
+
...(typeof params.command === "string" ? { command: params.command } : {}),
|
|
2610
|
+
...(Array.isArray(params.argv) && params.argv.every((entry) => typeof entry === "string") ? { argv: params.argv } : {}),
|
|
2611
|
+
shell: params.shell !== false,
|
|
2612
|
+
...(typeof params.loginShell === "boolean" ? { loginShell: params.loginShell } : {}),
|
|
2613
|
+
cwd,
|
|
2614
|
+
...(params.env && typeof params.env === "object" && !Array.isArray(params.env)
|
|
2615
|
+
? { env: params.env } : {}),
|
|
2616
|
+
};
|
|
2617
|
+
validateCommandSpec(spec);
|
|
2618
|
+
if (kind === "watch") {
|
|
2619
|
+
if (!params.success_when)
|
|
2620
|
+
throw new Error("Invalid parameters: watch requires success_when.");
|
|
2621
|
+
for (const [name, condition] of [["success_when", params.success_when], ["failure_when", params.failure_when]]) {
|
|
2622
|
+
const error = condition && validateCondition(condition);
|
|
2623
|
+
if (error)
|
|
2624
|
+
throw new Error(`${name}: ${error}`);
|
|
2625
|
+
}
|
|
2626
|
+
if (params.require_successful_steps === true) {
|
|
2627
|
+
throw new Error("Invalid step gate: require_successful_steps is for a spawned shell command; a watch poll reports its own exit code as the outcome. The task was not started.");
|
|
2628
|
+
}
|
|
2629
|
+
}
|
|
2630
|
+
const plan = workerPolicy !== undefined || owner.kind === "worker-conversation"
|
|
2631
|
+
? resolveWorkerSandboxPlan(this.pi, workerPolicy, params, tool)
|
|
2632
|
+
: resolveForegroundSandboxPlan(this.pi, false, params, tool);
|
|
2633
|
+
assertBackgroundExecutionAllowed(spec, plan, { remote: false, cwd });
|
|
2634
|
+
const limits = backgroundExecutionLimits(plan);
|
|
2635
|
+
const gated = kind === "process" && params.require_successful_steps === true;
|
|
2636
|
+
if (gated) {
|
|
2637
|
+
if (spec.shell === false) {
|
|
2638
|
+
throw new Error("Invalid step gate: require_successful_steps needs a shell command; argv with shell:false already reports the real exit code. The task was not started.");
|
|
2639
|
+
}
|
|
2640
|
+
if (!spec.command || spec.command.trim().length === 0) {
|
|
2641
|
+
throw new Error("Invalid step gate: require_successful_steps needs a non-empty shell command. The task was not started.");
|
|
2642
|
+
}
|
|
2643
|
+
}
|
|
2644
|
+
return {
|
|
2645
|
+
plan,
|
|
2646
|
+
spec,
|
|
2647
|
+
cwd,
|
|
2648
|
+
...(spec.env ? { env: spec.env } : {}),
|
|
2649
|
+
notices: [],
|
|
2650
|
+
gated,
|
|
2651
|
+
provenance: sandboxProvenance(plan, false),
|
|
2652
|
+
...(limits.commandTimeoutSeconds !== undefined ? { commandTimeoutSeconds: limits.commandTimeoutSeconds } : {}),
|
|
2653
|
+
};
|
|
2654
|
+
}
|
|
2655
|
+
async startSupervisor(input) {
|
|
2656
|
+
const { token, taskId, kind, params, prepared, operationId } = input;
|
|
2657
|
+
const profilePath = join(supervisorPaths(this.directory, taskId).dir, "sandbox.sb");
|
|
2658
|
+
let spec = prepared.spec;
|
|
2659
|
+
if (prepared.gated) {
|
|
2660
|
+
spec = {
|
|
2661
|
+
...spec,
|
|
2662
|
+
command: stepGateScript(taskId),
|
|
2663
|
+
env: { ...spec.env, [STEP_GATE_COMMAND_ENV]: prepared.spec.command },
|
|
2664
|
+
};
|
|
2665
|
+
}
|
|
2666
|
+
const notices = [];
|
|
2667
|
+
const confined = confineCommandSpec(spec, prepared.plan, profilePath, {}, (line) => notices.push(line));
|
|
2668
|
+
prepared.notices.push(...notices);
|
|
2669
|
+
const { execPath, execArgs } = commandExecution(confined);
|
|
2670
|
+
const options = {
|
|
2671
|
+
token,
|
|
2672
|
+
argv: [execPath, ...execArgs],
|
|
2673
|
+
cwd: confined.cwd ?? prepared.cwd,
|
|
2674
|
+
kind: kind === "watch" ? "watch" : "process",
|
|
2675
|
+
...(typeof params.name === "string" ? { name: params.name } : {}),
|
|
2676
|
+
operationId,
|
|
2677
|
+
...(prepared.commandTimeoutSeconds !== undefined ? { commandTimeoutSeconds: prepared.commandTimeoutSeconds } : {}),
|
|
2678
|
+
...(confined.env ? { env: confined.env } : prepared.env ? { env: prepared.env } : {}),
|
|
2679
|
+
...(typeof params.max_log_bytes === "number" ? { maxLogBytes: params.max_log_bytes } : {}),
|
|
2680
|
+
...(kind === "watch" ? this.watchOptions(params) : this.processTimeout(params)),
|
|
2681
|
+
};
|
|
2682
|
+
try {
|
|
2683
|
+
this.options.assertAdmission?.();
|
|
2684
|
+
input.assertDispatch?.();
|
|
2685
|
+
}
|
|
2686
|
+
catch (error) {
|
|
2687
|
+
const operation = this.requireStore().getOperation(operationId);
|
|
2688
|
+
if (operation && operation.terminalRevision === 0)
|
|
2689
|
+
this.requireStore().recordTerminalOutcome({
|
|
2690
|
+
operationId, eventId: `admission_refused_${randomUUID()}`, owner: operation.owner,
|
|
2691
|
+
outcome: "failed", evidence: [], reason: `External dispatch refused before spawn: ${String(error)}`,
|
|
2692
|
+
});
|
|
2693
|
+
throw error;
|
|
2694
|
+
}
|
|
2695
|
+
const started = await this.supervisor.start(options);
|
|
2696
|
+
return { started: started.started, claimed: started.claimed };
|
|
2697
|
+
}
|
|
2698
|
+
processTimeout(params) {
|
|
2699
|
+
return typeof params.timeout_seconds === "number" ? { timeoutSeconds: params.timeout_seconds } : {};
|
|
2700
|
+
}
|
|
2701
|
+
watchOptions(params) {
|
|
2702
|
+
return {
|
|
2703
|
+
intervalSeconds: Math.max(0.001, typeof params.interval_seconds === "number" ? params.interval_seconds : 30),
|
|
2704
|
+
timeoutSeconds: typeof params.timeout_seconds === "number" ? params.timeout_seconds : 900,
|
|
2705
|
+
successWhen: params.success_when,
|
|
2706
|
+
...(params.failure_when ? { failureWhen: params.failure_when } : {}),
|
|
2707
|
+
};
|
|
2708
|
+
}
|
|
2709
|
+
/**
|
|
2710
|
+
* Resolve a worker launch directory against the **registered worker
|
|
2711
|
+
* workspace**, never the parent's current directory. Omitted cwd means the
|
|
2712
|
+
* workspace itself; a relative path and symlinks are resolved before the
|
|
2713
|
+
* containment check so the policy and the executed command see one absolute
|
|
2714
|
+
* path.
|
|
2715
|
+
*/
|
|
2716
|
+
resolveWorkerCwd(workspace, requested) {
|
|
2717
|
+
const base = resolve(workspace);
|
|
2718
|
+
let workspaceReal = base;
|
|
2719
|
+
try {
|
|
2720
|
+
workspaceReal = realpathSync.native(base);
|
|
2721
|
+
}
|
|
2722
|
+
catch { /* the bridge already validated existence */ }
|
|
2723
|
+
const raw = typeof requested === "string" && requested.trim().length > 0 ? requested : ".";
|
|
2724
|
+
let candidate = resolve(base, raw);
|
|
2725
|
+
try {
|
|
2726
|
+
candidate = realpathSync.native(candidate);
|
|
2727
|
+
}
|
|
2728
|
+
catch { /* a missing cwd fails at supervisor start */ }
|
|
2729
|
+
const inside = relative(workspaceReal, candidate);
|
|
2730
|
+
if (inside.startsWith("..") || isAbsolute(inside)) {
|
|
2731
|
+
throw new Error("Worker launch cwd is outside the registered workspace.");
|
|
2732
|
+
}
|
|
2733
|
+
return candidate;
|
|
2734
|
+
}
|
|
2735
|
+
// ---- reconciliation --------------------------------------------------
|
|
2736
|
+
reconcileOperation(operation) {
|
|
2737
|
+
if (operation.terminalRevision > 0)
|
|
2738
|
+
return;
|
|
2739
|
+
if (this.resultHandoffs.has(operation.operationId) || (operation.resultManaged ?? !!this.store?.resultSupervision(operation.operationId)))
|
|
2740
|
+
return;
|
|
2741
|
+
if (this.options.serverOwnedResults)
|
|
2742
|
+
return;
|
|
2743
|
+
const authority = this.supervisionAuthority(operation);
|
|
2744
|
+
if (authority === "foreign")
|
|
2745
|
+
return;
|
|
2746
|
+
let claimed = false;
|
|
2747
|
+
if (authority === "replace") {
|
|
2748
|
+
try {
|
|
2749
|
+
this.store?.recordSupervision({
|
|
2750
|
+
operationId: operation.operationId,
|
|
2751
|
+
owner: operation.owner,
|
|
2752
|
+
expectedHostId: operation.supervision?.hostId ?? null,
|
|
2753
|
+
supervision: this.supervision(),
|
|
2754
|
+
health: "active",
|
|
2755
|
+
});
|
|
2756
|
+
claimed = true;
|
|
2757
|
+
}
|
|
2758
|
+
catch (error) {
|
|
2759
|
+
// Another host can hold the write lock, or it can take over between the
|
|
2760
|
+
// snapshot and this write. Leave the observed record alone and let the
|
|
2761
|
+
// next reconciliation tick re-read it.
|
|
2762
|
+
if (rpcCode(error) === "store-busy" || rpcCode(error) === "supervision-conflict")
|
|
2763
|
+
return;
|
|
2764
|
+
throw error;
|
|
2765
|
+
}
|
|
2766
|
+
}
|
|
2767
|
+
const inspection = this.inspect(operation.taskId);
|
|
2768
|
+
if (!inspection) {
|
|
2769
|
+
const now = this.options.now?.() ?? Date.now();
|
|
2770
|
+
if (now - operation.createdAt >= 30_000) {
|
|
2771
|
+
// The supervisor writes its launch record before spawning. No record
|
|
2772
|
+
// after the claim grace means no execution can be witnessed; this is
|
|
2773
|
+
// `lost`, never a success and never a silent retry.
|
|
2774
|
+
try {
|
|
2775
|
+
this.requireStore().recordTerminalOutcome({
|
|
2776
|
+
operationId: operation.operationId,
|
|
2777
|
+
eventId: `${operation.taskId}:missing:lost`,
|
|
2778
|
+
outcome: "lost",
|
|
2779
|
+
owner: operation.owner,
|
|
2780
|
+
evidence: [{
|
|
2781
|
+
kind: "summary",
|
|
2782
|
+
ref: "lost.json",
|
|
2783
|
+
summary: "status=lost detailLost=true",
|
|
2784
|
+
detailLost: true,
|
|
2785
|
+
}],
|
|
2786
|
+
detailLost: true,
|
|
2787
|
+
reason: "launch produced no durable supervisor record",
|
|
2788
|
+
});
|
|
2789
|
+
}
|
|
2790
|
+
catch { /* a concurrent terminal record wins */ }
|
|
2791
|
+
void this.dispatchOutbox();
|
|
2792
|
+
return;
|
|
2793
|
+
}
|
|
2794
|
+
try {
|
|
2795
|
+
if (claimed || operation.health !== "unmonitored" || operation.healthReason !== "no durable supervisor record exists for this operation") {
|
|
2796
|
+
this.store?.recordSupervision({
|
|
2797
|
+
operationId: operation.operationId,
|
|
2798
|
+
owner: operation.owner,
|
|
2799
|
+
expectedHostId: this.hostId,
|
|
2800
|
+
health: "unmonitored",
|
|
2801
|
+
reason: "no durable supervisor record exists for this operation",
|
|
2802
|
+
});
|
|
2803
|
+
}
|
|
2804
|
+
}
|
|
2805
|
+
catch { /* the owner may have been superseded; health is observational */ }
|
|
2806
|
+
return;
|
|
2807
|
+
}
|
|
2808
|
+
if (inspection.terminal) {
|
|
2809
|
+
this.recordTerminal(operation, inspection);
|
|
2810
|
+
return;
|
|
2811
|
+
}
|
|
2812
|
+
if (!claimed && (operation.health !== "active" || operation.supervision?.hostId !== this.hostId)) {
|
|
2813
|
+
// Health is observational; write it only when the supervising host or the
|
|
2814
|
+
// reported health actually changed. A 250 ms tick must not churn SQLite.
|
|
2815
|
+
try {
|
|
2816
|
+
this.store?.recordSupervision({
|
|
2817
|
+
operationId: operation.operationId,
|
|
2818
|
+
owner: operation.owner,
|
|
2819
|
+
expectedHostId: this.hostId,
|
|
2820
|
+
supervision: this.supervision(),
|
|
2821
|
+
health: "active",
|
|
2822
|
+
});
|
|
2823
|
+
}
|
|
2824
|
+
catch (error) {
|
|
2825
|
+
// Another host can hold the write lock or have taken over. Leave health
|
|
2826
|
+
// unchanged and let the next tick re-read the operation.
|
|
2827
|
+
if (rpcCode(error) !== "store-busy" && rpcCode(error) !== "supervision-conflict")
|
|
2828
|
+
throw error;
|
|
2829
|
+
}
|
|
2830
|
+
}
|
|
2831
|
+
}
|
|
2832
|
+
/**
|
|
2833
|
+
* Whether this host may inspect the operation. The recorded `supervision`
|
|
2834
|
+
* identity is the cross-process authority marker: a live holder keeps it, and
|
|
2835
|
+
* only a closed or dead holder is replaced. Process identity is checked before
|
|
2836
|
+
* elapsed time, and an unprovable holder is never stolen from.
|
|
2837
|
+
*/
|
|
2838
|
+
supervisionAuthority(operation) {
|
|
2839
|
+
const hostId = operation.supervision?.hostId;
|
|
2840
|
+
if (!hostId)
|
|
2841
|
+
return "replace";
|
|
2842
|
+
if (hostId === this.hostId)
|
|
2843
|
+
return "self";
|
|
2844
|
+
if (HOST_INSTANCE_STATE.closed.has(hostId))
|
|
2845
|
+
return "replace";
|
|
2846
|
+
const cached = this.authorityPassCache?.get(hostId);
|
|
2847
|
+
const state = cached ?? this.supervisionHolderState(hostId);
|
|
2848
|
+
if (cached === undefined)
|
|
2849
|
+
this.authorityPassCache?.set(hostId, state);
|
|
2850
|
+
return state === "live" || state === "unknown" ? "foreign" : "replace";
|
|
2851
|
+
}
|
|
2852
|
+
/** Process-identity check for a recorded holder, cached per pass by callers. */
|
|
2853
|
+
supervisionHolderState(hostId) {
|
|
2854
|
+
const { pid, startTokenDigest: claimedDigest } = parseHostIdentity(hostId);
|
|
2855
|
+
if (!pid)
|
|
2856
|
+
return "unknown";
|
|
2857
|
+
if (pid === process.pid) {
|
|
2858
|
+
const generation = HOST_INSTANCE_STATE.generations.get(hostId);
|
|
2859
|
+
// Another instance in this process still owns its record. Creation order
|
|
2860
|
+
// alone is not death: a reload predecessor is marked closed above.
|
|
2861
|
+
return generation === undefined ? "dead" : "live";
|
|
2862
|
+
}
|
|
2863
|
+
if (!processExists(pid))
|
|
2864
|
+
return "dead";
|
|
2865
|
+
if (!claimedDigest)
|
|
2866
|
+
return "unknown";
|
|
2867
|
+
const current = readProcessStartToken(pid);
|
|
2868
|
+
if (!current)
|
|
2869
|
+
return "unknown";
|
|
2870
|
+
return startTokenDigest(current) === claimedDigest ? "live" : "dead";
|
|
2871
|
+
}
|
|
2872
|
+
/**
|
|
2873
|
+
* A graceful close releases only this host's running authority. A crash leaves
|
|
2874
|
+
* the same record for the next host to replace after process identity proves it
|
|
2875
|
+
* dead; a newer holder is never cleared by a late close.
|
|
2876
|
+
*/
|
|
2877
|
+
releaseSupervisionAuthority() {
|
|
2878
|
+
const store = this.store;
|
|
2879
|
+
if (!store)
|
|
2880
|
+
return;
|
|
2881
|
+
let running;
|
|
2882
|
+
try {
|
|
2883
|
+
running = store.listOperations({ phase: "running" });
|
|
2884
|
+
}
|
|
2885
|
+
catch {
|
|
2886
|
+
return;
|
|
2887
|
+
}
|
|
2888
|
+
for (const operation of running) {
|
|
2889
|
+
if (operation.supervision?.hostId !== this.hostId)
|
|
2890
|
+
continue;
|
|
2891
|
+
try {
|
|
2892
|
+
store.releaseSupervision({
|
|
2893
|
+
operationId: operation.operationId,
|
|
2894
|
+
owner: operation.owner,
|
|
2895
|
+
hostId: this.hostId,
|
|
2896
|
+
reason: "the supervising host closed; another host may take over",
|
|
2897
|
+
});
|
|
2898
|
+
}
|
|
2899
|
+
catch {
|
|
2900
|
+
// Closing must not fail on a busy or already replaced record.
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2903
|
+
}
|
|
2904
|
+
/** Release only this host's exact discovery claim; a successor keeps its own. */
|
|
2905
|
+
releaseDiscoveryAuthority() {
|
|
2906
|
+
const store = this.store;
|
|
2907
|
+
const token = this.discoveryToken;
|
|
2908
|
+
this.discoveryToken = undefined;
|
|
2909
|
+
this.discoveryRole = undefined;
|
|
2910
|
+
if (!store || !token)
|
|
2911
|
+
return;
|
|
2912
|
+
try {
|
|
2913
|
+
store.releaseDiscoveryClaim({ scope: this.discoveryScope, hostId: this.hostId, token });
|
|
2914
|
+
}
|
|
2915
|
+
catch {
|
|
2916
|
+
// Closing must not fail on a busy or already replaced claim.
|
|
2917
|
+
}
|
|
2918
|
+
}
|
|
2919
|
+
reconcileInspection(operation, inspection) {
|
|
2920
|
+
if (inspection?.terminal && operation.terminalRevision === 0)
|
|
2921
|
+
this.recordTerminal(operation, inspection);
|
|
2922
|
+
}
|
|
2923
|
+
recordTerminal(operation, inspection) {
|
|
2924
|
+
if (this.options.serverOwnedResults)
|
|
2925
|
+
return;
|
|
2926
|
+
if (this.resultHandoffs.has(operation.operationId) || this.store?.resultSupervision(operation.operationId))
|
|
2927
|
+
return;
|
|
2928
|
+
const store = this.requireStore();
|
|
2929
|
+
const status = inspection.status;
|
|
2930
|
+
const outcome = terminalOutcome(status);
|
|
2931
|
+
const refs = evidenceFor(inspection);
|
|
2932
|
+
let recorded;
|
|
2933
|
+
try {
|
|
2934
|
+
recorded = store.recordTerminalOutcome(supervisorTerminalPublication(operation, inspection, refs));
|
|
2935
|
+
}
|
|
2936
|
+
catch (error) {
|
|
2937
|
+
// A timer and a tool call can observe the same terminal record. The store
|
|
2938
|
+
// keeps the first revision; a replay is never a second execution.
|
|
2939
|
+
this.options.logger?.(`observed waits: terminal replay for ${operation.taskId}: ${oneLine(String(error), 160)}`);
|
|
2940
|
+
return;
|
|
2941
|
+
}
|
|
2942
|
+
const recordContext = this.currentLaunchContext(operation.taskId);
|
|
2943
|
+
if (recordContext) {
|
|
2944
|
+
if (recorded.recorded) {
|
|
2945
|
+
recordContext.terminalRecordedBy = this.hostId;
|
|
2946
|
+
recordContext.terminalRecordedAt = Date.now();
|
|
2947
|
+
recordContext.terminalRecordedWithContext = !!this.activeContext;
|
|
2948
|
+
recordContext.terminalActiveSessionId = this.activeContext ? this.sessionId(this.activeContext) : undefined;
|
|
2949
|
+
recordContext.terminalActiveBranchIds = this.activeContext ? branchIdsOf(this.activeContext) : [];
|
|
2950
|
+
}
|
|
2951
|
+
else {
|
|
2952
|
+
recordContext.terminalReplayObservedBy = this.hostId;
|
|
2953
|
+
}
|
|
2954
|
+
this.launches.set(operation.taskId, recordContext);
|
|
2955
|
+
this.writeLaunchContext(operation.taskId, recordContext);
|
|
2956
|
+
}
|
|
2957
|
+
if (!recorded.recorded) {
|
|
2958
|
+
// A concurrent host recorded this terminal revision. This host may still be
|
|
2959
|
+
// the one with the live owner context; evaluate the callback against it.
|
|
2960
|
+
this.attemptTerminalCallback(recorded.operation, status, outcome, refs, { pendingWithoutContext: true });
|
|
2961
|
+
// The local projection cache may still show this operation as running even
|
|
2962
|
+
// though another process committed its terminal revision. Invalidate and
|
|
2963
|
+
// notify so the navigator repaints on this reconcile pass.
|
|
2964
|
+
this.emitDurableTaskChange(recorded.operation.owner);
|
|
2965
|
+
return;
|
|
2966
|
+
}
|
|
2967
|
+
this.options.logger?.(`observed waits: ${operation.taskId} ${status} (revision ${recorded.operation.terminalRevision})`);
|
|
2968
|
+
this.attemptTerminalCallback(operation, status, outcome, refs, { pendingWithoutContext: true });
|
|
2969
|
+
this.emitDurableTaskChange(operation.owner);
|
|
2970
|
+
// The parent callback is independent from the worker's wait: a worker may be
|
|
2971
|
+
// parked, while the parent session still learns that the supervised task ended.
|
|
2972
|
+
void this.dispatchOutbox();
|
|
2973
|
+
}
|
|
2974
|
+
/**
|
|
2975
|
+
* A parent-owned launch with callbacks on is notified once at its terminal
|
|
2976
|
+
* revision. A registered wait carries the same information and is delivered by
|
|
2977
|
+
* the outbox, so the two paths do not double-notify. A callback is only
|
|
2978
|
+
* receipted after the batcher's real handoff; returning from `notifyParent`
|
|
2979
|
+
* leaves it pending, and a replacement host recovers it.
|
|
2980
|
+
*/
|
|
2981
|
+
attemptTerminalCallback(operation, status, outcome, refs, options = {}) {
|
|
2982
|
+
const context = this.currentLaunchContext(operation.taskId);
|
|
2983
|
+
const skip = (reason) => {
|
|
2984
|
+
if (!context)
|
|
2985
|
+
return;
|
|
2986
|
+
if (context.callbackSkipReason === reason && context.callbackAttemptedAt !== undefined)
|
|
2987
|
+
return;
|
|
2988
|
+
context.callbackAttemptedAt = Date.now();
|
|
2989
|
+
context.callbackSkipReason = oneLine(reason, 200);
|
|
2990
|
+
this.launches.set(operation.taskId, context);
|
|
2991
|
+
this.writeLaunchContext(operation.taskId, context);
|
|
2992
|
+
};
|
|
2993
|
+
if (!this.options.notifyParent)
|
|
2994
|
+
return;
|
|
2995
|
+
if (operation.owner.kind !== "parent-session")
|
|
2996
|
+
return;
|
|
2997
|
+
if (!context)
|
|
2998
|
+
return;
|
|
2999
|
+
if (context.callback === false) {
|
|
3000
|
+
this.store?.setParentCallbackPending(operation.taskId, false);
|
|
3001
|
+
return;
|
|
3002
|
+
}
|
|
3003
|
+
// Never write any journal field while a newer or unprovable other host owns
|
|
3004
|
+
// the claim. In particular, a stale host's reconcile must not rewrite its
|
|
3005
|
+
// cached claim token over the current shared one.
|
|
3006
|
+
const claim = this.claimState(context.callbackClaimedBy);
|
|
3007
|
+
if (claim === "live" || claim === "unknown")
|
|
3008
|
+
return;
|
|
3009
|
+
if (context.callbackDeliveredAt !== undefined) {
|
|
3010
|
+
this.store?.setParentCallbackPending(operation.taskId, false);
|
|
3011
|
+
this.pendingTerminalCallbacks.delete(operation.taskId);
|
|
3012
|
+
skip("already delivered");
|
|
3013
|
+
return;
|
|
3014
|
+
}
|
|
3015
|
+
const waitPending = this.store?.listWaits({ owner: operation.owner, pendingOnly: true })
|
|
3016
|
+
.some((wait) => wait.dependencies.some((dep) => dep.operationId === operation.operationId)) ?? false;
|
|
3017
|
+
if (waitPending) {
|
|
3018
|
+
this.pendingTerminalCallbacks.delete(operation.taskId);
|
|
3019
|
+
skip("a registered wait owns delivery");
|
|
3020
|
+
return;
|
|
3021
|
+
}
|
|
3022
|
+
if (claim === "self")
|
|
3023
|
+
return; // this host's event is already in flight
|
|
3024
|
+
if (!this.activeContext) {
|
|
3025
|
+
// This host recorded terminal before a session context was restored. Keep
|
|
3026
|
+
// the callback pending so the next activation/tool call can hand it off;
|
|
3027
|
+
// never notify without an exact active owner.
|
|
3028
|
+
skip("no active context; pending");
|
|
3029
|
+
if (options.pendingWithoutContext)
|
|
3030
|
+
this.markCallbackPending(operation.taskId, context);
|
|
3031
|
+
return;
|
|
3032
|
+
}
|
|
3033
|
+
// A shared coordinator store can contain other sessions' operations. They are
|
|
3034
|
+
// never this host's callback work, even when they are terminal. An active
|
|
3035
|
+
// context without a readable session identity is unknown, so keep pending.
|
|
3036
|
+
const relation = this.activeOwnerRelation(operation.owner);
|
|
3037
|
+
if (relation === "unknown") {
|
|
3038
|
+
skip("active session identity is unavailable; pending");
|
|
3039
|
+
if (options.pendingWithoutContext)
|
|
3040
|
+
this.markCallbackPending(operation.taskId, context);
|
|
3041
|
+
return;
|
|
3042
|
+
}
|
|
3043
|
+
if (relation === "foreign") {
|
|
3044
|
+
// Another session owns this operation. This host may have recorded the
|
|
3045
|
+
// terminal revision while reconciling the shared store, but it must not
|
|
3046
|
+
// write callback journal state or clear the owner's pending work.
|
|
3047
|
+
this.pendingTerminalCallbacks.delete(operation.taskId);
|
|
3048
|
+
return;
|
|
3049
|
+
}
|
|
3050
|
+
// A terminal result can become eligible later: the live session may have
|
|
3051
|
+
// been settling when the record was produced, or the owner may navigate
|
|
3052
|
+
// back to an eligible descendant branch. Keep retrying only this id.
|
|
3053
|
+
this.rememberPendingCallback(operation.taskId);
|
|
3054
|
+
const origin = context.parentOrigin ?? { cwd: operation.owner.workspace, sessionId: operation.owner.sessionId };
|
|
3055
|
+
const branchId = context.branchId ?? operation.owner.branchId;
|
|
3056
|
+
if (!this.isParentOriginActive(origin, branchId)) {
|
|
3057
|
+
skip("recorded branch anchor is not on the active branch; pending");
|
|
3058
|
+
this.markCallbackPending(operation.taskId, context);
|
|
3059
|
+
return;
|
|
3060
|
+
}
|
|
3061
|
+
context.callbackAttemptedAt = Date.now();
|
|
3062
|
+
context.callbackSkipReason = undefined;
|
|
3063
|
+
context.callbackPendingAt ??= Date.now();
|
|
3064
|
+
context.callbackClaimedBy = this.hostId;
|
|
3065
|
+
context.callbackClaimedAt = Date.now();
|
|
3066
|
+
context.callbackClaimToken = randomUUID();
|
|
3067
|
+
context.callbackDeferredReason = undefined;
|
|
3068
|
+
this.launches.set(operation.taskId, context);
|
|
3069
|
+
this.writeLaunchContext(operation.taskId, context);
|
|
3070
|
+
const claimToken = context.callbackClaimToken;
|
|
3071
|
+
let settled = false;
|
|
3072
|
+
const delivery = {
|
|
3073
|
+
receiptId: `background-terminal:${operation.operationId}`,
|
|
3074
|
+
delivered: () => {
|
|
3075
|
+
if (settled)
|
|
3076
|
+
return;
|
|
3077
|
+
settled = true;
|
|
3078
|
+
this.completeTerminalCallback(operation.taskId, claimToken);
|
|
3079
|
+
},
|
|
3080
|
+
defer: (reason) => {
|
|
3081
|
+
if (settled)
|
|
3082
|
+
return;
|
|
3083
|
+
settled = true;
|
|
3084
|
+
this.deferTerminalCallback(operation.taskId, reason, true, claimToken);
|
|
3085
|
+
},
|
|
3086
|
+
};
|
|
3087
|
+
try {
|
|
3088
|
+
this.options.notifyParent({
|
|
3089
|
+
taskId: operation.taskId,
|
|
3090
|
+
origin,
|
|
3091
|
+
branchId,
|
|
3092
|
+
operationId: operation.operationId,
|
|
3093
|
+
status,
|
|
3094
|
+
outcome,
|
|
3095
|
+
summary: refs[0]?.summary ?? `terminal revision ${operation.terminalRevision}`,
|
|
3096
|
+
evidence: refs.map((ref) => ({
|
|
3097
|
+
...ref,
|
|
3098
|
+
operationId: operation.operationId,
|
|
3099
|
+
taskId: operation.taskId,
|
|
3100
|
+
terminalRevision: operation.terminalRevision,
|
|
3101
|
+
})),
|
|
3102
|
+
}, delivery);
|
|
3103
|
+
}
|
|
3104
|
+
catch (error) {
|
|
3105
|
+
// A notifier that threw synchronously must not spin the microtask retry.
|
|
3106
|
+
this.deferTerminalCallback(operation.taskId, error instanceof Error ? error.message : String(error), false, claimToken);
|
|
3107
|
+
}
|
|
3108
|
+
}
|
|
3109
|
+
/**
|
|
3110
|
+
* Exact owner relation for the live context. An active context without a
|
|
3111
|
+
* readable session identity is `unknown`, never `foreign`: a terminal result
|
|
3112
|
+
* stays pending until the real session identity is restored.
|
|
3113
|
+
*/
|
|
3114
|
+
activeOwnerRelation(owner) {
|
|
3115
|
+
const ctx = this.activeContext;
|
|
3116
|
+
if (!ctx)
|
|
3117
|
+
return "unknown";
|
|
3118
|
+
let cwd;
|
|
3119
|
+
try {
|
|
3120
|
+
cwd = ctx.cwd;
|
|
3121
|
+
}
|
|
3122
|
+
catch {
|
|
3123
|
+
return "unknown";
|
|
3124
|
+
}
|
|
3125
|
+
if (cwd !== owner.workspace)
|
|
3126
|
+
return "foreign";
|
|
3127
|
+
const known = this.sessionIdIfAvailable(ctx);
|
|
3128
|
+
if (known)
|
|
3129
|
+
return owner.sessionId === known ? "match" : "foreign";
|
|
3130
|
+
const fallback = this.sessionId(ctx);
|
|
3131
|
+
if (owner.sessionId === fallback)
|
|
3132
|
+
return "match";
|
|
3133
|
+
// A real owner and an anonymous active context cannot prove each other.
|
|
3134
|
+
return owner.sessionId.startsWith("anonymous:") ? "foreign" : "unknown";
|
|
3135
|
+
}
|
|
3136
|
+
markCallbackPending(taskId, context = this.currentLaunchContext(taskId)) {
|
|
3137
|
+
if (!context || context.callbackDeliveredAt !== undefined)
|
|
3138
|
+
return;
|
|
3139
|
+
const claim = this.claimState(context.callbackClaimedBy);
|
|
3140
|
+
if (claim === "live" || claim === "unknown") {
|
|
3141
|
+
this.rememberPendingCallback(taskId);
|
|
3142
|
+
return; // preserve the current owner's claim without any write
|
|
3143
|
+
}
|
|
3144
|
+
context.callbackPendingAt ??= Date.now();
|
|
3145
|
+
this.launches.set(taskId, context);
|
|
3146
|
+
this.writeLaunchContext(taskId, context);
|
|
3147
|
+
this.rememberPendingCallback(taskId);
|
|
3148
|
+
}
|
|
3149
|
+
completeTerminalCallback(taskId, claimToken) {
|
|
3150
|
+
// The sidecar is shared across hosts and is authoritative for the claim.
|
|
3151
|
+
// Never validate a stale delivery against this host's cached launch object.
|
|
3152
|
+
const context = this.currentLaunchContext(taskId);
|
|
3153
|
+
if (!context)
|
|
3154
|
+
return;
|
|
3155
|
+
// A stale handoff from an older attempt must not receipt a newer attempt.
|
|
3156
|
+
if (claimToken !== undefined && context.callbackClaimToken !== claimToken)
|
|
3157
|
+
return;
|
|
3158
|
+
this.pendingTerminalCallbacks.delete(taskId);
|
|
3159
|
+
context.callbackDeliveredAt ??= Date.now();
|
|
3160
|
+
context.callbackAttemptedAt = Date.now();
|
|
3161
|
+
delete context.callbackSkipReason;
|
|
3162
|
+
delete context.callbackPendingAt;
|
|
3163
|
+
delete context.callbackClaimedBy;
|
|
3164
|
+
delete context.callbackClaimedAt;
|
|
3165
|
+
delete context.callbackClaimToken;
|
|
3166
|
+
delete context.callbackDeferredReason;
|
|
3167
|
+
this.launches.set(taskId, context);
|
|
3168
|
+
this.writeLaunchContext(taskId, context);
|
|
3169
|
+
const operation = this.operationForTask(taskId);
|
|
3170
|
+
if (operation)
|
|
3171
|
+
this.emitDurableTaskChange(operation.owner);
|
|
3172
|
+
}
|
|
3173
|
+
deferTerminalCallback(taskId, reason, retry = true, claimToken) {
|
|
3174
|
+
const context = this.currentLaunchContext(taskId);
|
|
3175
|
+
if (!context || context.callbackDeliveredAt !== undefined)
|
|
3176
|
+
return;
|
|
3177
|
+
// A stale suppression must not clear the claim of a newer attempt.
|
|
3178
|
+
if (claimToken !== undefined && context.callbackClaimToken !== claimToken)
|
|
3179
|
+
return;
|
|
3180
|
+
this.rememberPendingCallback(taskId);
|
|
3181
|
+
context.callbackDeferredReason = oneLine(reason, 200);
|
|
3182
|
+
context.callbackAttemptedAt = Date.now();
|
|
3183
|
+
context.callbackSkipReason = `deferred: ${oneLine(reason, 160)}`;
|
|
3184
|
+
delete context.callbackClaimedBy;
|
|
3185
|
+
delete context.callbackClaimedAt;
|
|
3186
|
+
delete context.callbackClaimToken;
|
|
3187
|
+
this.launches.set(taskId, context);
|
|
3188
|
+
this.writeLaunchContext(taskId, context);
|
|
3189
|
+
if (retry) {
|
|
3190
|
+
// A batcher suppression can land after a session_tree retry already saw
|
|
3191
|
+
// the old claim. Re-evaluate the live branch after the claim is cleared.
|
|
3192
|
+
queueMicrotask(() => {
|
|
3193
|
+
if (!this.closed)
|
|
3194
|
+
this.retryPendingTerminalCallbacks();
|
|
3195
|
+
});
|
|
3196
|
+
}
|
|
3197
|
+
}
|
|
3198
|
+
outboxHandoffProof(taskId, event) {
|
|
3199
|
+
const proof = this.currentLaunchContext(taskId)?.outboxDelivered?.[event.eventId];
|
|
3200
|
+
return !!proof && proof.waitId === event.waitId && proof.generation === event.generation
|
|
3201
|
+
&& proof.terminalRevision === event.terminalRevision;
|
|
3202
|
+
}
|
|
3203
|
+
recordOutboxHandoffProof(taskId, event) {
|
|
3204
|
+
const context = this.currentLaunchContext(taskId);
|
|
3205
|
+
if (!context)
|
|
3206
|
+
return;
|
|
3207
|
+
const map = { ...(context.outboxDelivered ?? {}) };
|
|
3208
|
+
const at = this.options.now?.() ?? Date.now();
|
|
3209
|
+
map[event.eventId] = {
|
|
3210
|
+
waitId: event.waitId,
|
|
3211
|
+
generation: event.generation,
|
|
3212
|
+
terminalRevision: event.terminalRevision,
|
|
3213
|
+
deliveredAt: at,
|
|
3214
|
+
};
|
|
3215
|
+
const kept = Object.entries(map)
|
|
3216
|
+
.sort((a, b) => b[1].deliveredAt - a[1].deliveredAt)
|
|
3217
|
+
.slice(0, 20);
|
|
3218
|
+
context.outboxDelivered = Object.fromEntries(kept);
|
|
3219
|
+
this.launches.set(taskId, context);
|
|
3220
|
+
this.writeLaunchContext(taskId, context);
|
|
3221
|
+
}
|
|
3222
|
+
clearOutboxHandoffProof(taskId, eventId) {
|
|
3223
|
+
const context = this.currentLaunchContext(taskId);
|
|
3224
|
+
if (!context?.outboxDelivered || !(eventId in context.outboxDelivered))
|
|
3225
|
+
return;
|
|
3226
|
+
const map = { ...context.outboxDelivered };
|
|
3227
|
+
delete map[eventId];
|
|
3228
|
+
context.outboxDelivered = map;
|
|
3229
|
+
this.launches.set(taskId, context);
|
|
3230
|
+
this.writeLaunchContext(taskId, context);
|
|
3231
|
+
}
|
|
3232
|
+
/**
|
|
3233
|
+
* Identity of a claiming host. Liveness uses the process start token, not
|
|
3234
|
+
* elapsed time. `unknown` is held: an unprovable owner is never stolen from.
|
|
3235
|
+
*/
|
|
3236
|
+
claimState(hostId) {
|
|
3237
|
+
if (!hostId)
|
|
3238
|
+
return "none";
|
|
3239
|
+
if (hostId === this.hostId)
|
|
3240
|
+
return "self";
|
|
3241
|
+
const { pid, startTokenDigest: claimedDigest } = parseHostIdentity(hostId);
|
|
3242
|
+
if (!pid)
|
|
3243
|
+
return "unknown";
|
|
3244
|
+
if (HOST_INSTANCE_STATE.closed.has(hostId))
|
|
3245
|
+
return "dead";
|
|
3246
|
+
const generation = HOST_INSTANCE_STATE.generations.get(hostId);
|
|
3247
|
+
if (generation !== undefined) {
|
|
3248
|
+
if (pid === process.pid) {
|
|
3249
|
+
// A newer live instance owns the claim; an older one is a reload
|
|
3250
|
+
// predecessor whose claim this host may recover.
|
|
3251
|
+
return generation > this.hostGeneration ? "live" : "dead";
|
|
3252
|
+
}
|
|
3253
|
+
}
|
|
3254
|
+
// A different instance with this process's pid is a previous instance in the
|
|
3255
|
+
// same process (a reload) or a host this process cannot prove is current.
|
|
3256
|
+
if (pid === process.pid)
|
|
3257
|
+
return "dead";
|
|
3258
|
+
if (!processExists(pid))
|
|
3259
|
+
return "dead";
|
|
3260
|
+
if (!claimedDigest)
|
|
3261
|
+
return "unknown";
|
|
3262
|
+
const current = readProcessStartToken(pid);
|
|
3263
|
+
if (!current)
|
|
3264
|
+
return "unknown";
|
|
3265
|
+
return startTokenDigest(current) === claimedDigest ? "live" : "dead";
|
|
3266
|
+
}
|
|
3267
|
+
/**
|
|
3268
|
+
* Recover deliveries whose claiming host disappeared (reload, crash, or a
|
|
3269
|
+
* session switch). A claim owned by a live or unprovable host is left alone.
|
|
3270
|
+
*/
|
|
3271
|
+
recoverAbandonedDeliveries() {
|
|
3272
|
+
const store = this.store;
|
|
3273
|
+
if (!store)
|
|
3274
|
+
return;
|
|
3275
|
+
for (const event of store.listOutbox({ state: "claimed" })) {
|
|
3276
|
+
const claim = event.dispatchClaim;
|
|
3277
|
+
if (!claim || claim.claimedBy === this.hostId)
|
|
3278
|
+
continue;
|
|
3279
|
+
if (this.claimState(claim.claimedBy) !== "dead")
|
|
3280
|
+
continue;
|
|
3281
|
+
try {
|
|
3282
|
+
store.releaseOutbox({
|
|
3283
|
+
eventId: event.eventId,
|
|
3284
|
+
claimToken: claim.token,
|
|
3285
|
+
reason: "abandoned callback delivery claim recovered",
|
|
3286
|
+
});
|
|
3287
|
+
}
|
|
3288
|
+
catch { /* another host already recovered it */ }
|
|
3289
|
+
}
|
|
3290
|
+
for (const operation of this.activeParentTerminalOperations(true)) {
|
|
3291
|
+
const context = this.currentLaunchContext(operation.taskId);
|
|
3292
|
+
if (!context?.callbackClaimedBy || context.callbackClaimedBy === this.hostId)
|
|
3293
|
+
continue;
|
|
3294
|
+
if (this.claimState(context.callbackClaimedBy) !== "dead")
|
|
3295
|
+
continue;
|
|
3296
|
+
delete context.callbackClaimedBy;
|
|
3297
|
+
delete context.callbackClaimedAt;
|
|
3298
|
+
delete context.callbackClaimToken;
|
|
3299
|
+
this.launches.set(operation.taskId, context);
|
|
3300
|
+
this.writeLaunchContext(operation.taskId, context);
|
|
3301
|
+
}
|
|
3302
|
+
}
|
|
3303
|
+
inspect(taskId) {
|
|
3304
|
+
if (!LOCAL_DURABLE_ID.test(taskId))
|
|
3305
|
+
return undefined;
|
|
3306
|
+
try {
|
|
3307
|
+
return this.supervisor.inspect(taskId, { recordLost: true });
|
|
3308
|
+
}
|
|
3309
|
+
catch {
|
|
3310
|
+
return undefined;
|
|
3311
|
+
}
|
|
3312
|
+
}
|
|
3313
|
+
async dispatchOutbox() {
|
|
3314
|
+
const store = this.store;
|
|
3315
|
+
if (!store || this.closed)
|
|
3316
|
+
return;
|
|
3317
|
+
const pending = store.listDispatchableOutboxRecipients();
|
|
3318
|
+
if (pending.length === 0)
|
|
3319
|
+
return;
|
|
3320
|
+
for (const { recipient: owner, count } of pending) {
|
|
3321
|
+
// Foreign parents cannot receive a handoff here. Leave their events pending
|
|
3322
|
+
// without taking a write lock on every reconciliation pass.
|
|
3323
|
+
if (owner.kind === "parent-session") {
|
|
3324
|
+
const origin = { cwd: owner.workspace, sessionId: owner.sessionId };
|
|
3325
|
+
if (!this.options.notifyParent || !this.isParentOriginActive(origin, owner.branchId))
|
|
3326
|
+
continue;
|
|
3327
|
+
}
|
|
3328
|
+
if (owner.kind === "worker-conversation" && !this.continuation && this.rpcRuns.size === 0)
|
|
3329
|
+
continue;
|
|
3330
|
+
const claimToken = `dispatch_${randomUUID()}`;
|
|
3331
|
+
let claimed;
|
|
3332
|
+
try {
|
|
3333
|
+
claimed = store.claimOutbox({
|
|
3334
|
+
type: "dependency-ready",
|
|
3335
|
+
recipient: owner,
|
|
3336
|
+
claimToken,
|
|
3337
|
+
claimedBy: this.hostId,
|
|
3338
|
+
limit: Math.min(count, 20),
|
|
3339
|
+
});
|
|
3340
|
+
}
|
|
3341
|
+
catch (error) {
|
|
3342
|
+
this.options.logger?.(`observed waits: outbox claim failed: ${oneLine(String(error), 160)}`);
|
|
3343
|
+
continue;
|
|
3344
|
+
}
|
|
3345
|
+
for (const event of claimed) {
|
|
3346
|
+
const operation = store.getOperation(event.operationId);
|
|
3347
|
+
const taskId = operation?.taskId;
|
|
3348
|
+
const evidence = mapEvidence(event.operationId, taskId, event.evidence.map((pin) => ({
|
|
3349
|
+
operationId: pin.operationId,
|
|
3350
|
+
...(taskId ? { taskId } : {}),
|
|
3351
|
+
terminalRevision: pin.terminalRevision,
|
|
3352
|
+
kind: pin.kind,
|
|
3353
|
+
ref: pin.ref,
|
|
3354
|
+
...(pin.summary ? { summary: pin.summary } : {}),
|
|
3355
|
+
detailLost: pin.detailLost,
|
|
3356
|
+
})), event.terminalRevision);
|
|
3357
|
+
try {
|
|
3358
|
+
if (owner.kind === "worker-conversation" && this.continuation) {
|
|
3359
|
+
const adapter = this.continuation;
|
|
3360
|
+
const wait = store.getWait({ waitId: event.waitId, generation: event.generation });
|
|
3361
|
+
const outcome = await adapter.onWaitReady({
|
|
3362
|
+
waitId: event.waitId,
|
|
3363
|
+
generation: event.generation,
|
|
3364
|
+
...(wait?.park?.attemptId ? { parkedAttemptId: wait.park.attemptId } : {}),
|
|
3365
|
+
owner,
|
|
3366
|
+
...(taskId && this.launches.get(taskId)?.parentOrigin
|
|
3367
|
+
? { parentOrigin: this.launches.get(taskId).parentOrigin }
|
|
3368
|
+
: {}),
|
|
3369
|
+
taskIds: wait ? this.waitTaskIds(wait) : [],
|
|
3370
|
+
continuationNote: wait?.continuationNote ?? "",
|
|
3371
|
+
evidence,
|
|
3372
|
+
});
|
|
3373
|
+
if (outcome === "deferred") {
|
|
3374
|
+
store.releaseOutbox({ eventId: event.eventId, claimToken, reason: "continuation owner is inactive; delivery deferred" });
|
|
3375
|
+
continue;
|
|
3376
|
+
}
|
|
3377
|
+
}
|
|
3378
|
+
else if (owner.kind === "worker-conversation") {
|
|
3379
|
+
const wait = store.getWait({ waitId: event.waitId, generation: event.generation });
|
|
3380
|
+
eventBusOf(this.pi)?.emit(OBSERVED_WAITS_READY_CHANNEL, {
|
|
3381
|
+
version: OBSERVED_WAITS_RPC_VERSION,
|
|
3382
|
+
waitId: event.waitId,
|
|
3383
|
+
generation: event.generation,
|
|
3384
|
+
owner,
|
|
3385
|
+
taskIds: wait ? this.waitTaskIds(wait) : [],
|
|
3386
|
+
continuationNote: wait?.continuationNote ?? "",
|
|
3387
|
+
});
|
|
3388
|
+
}
|
|
3389
|
+
else {
|
|
3390
|
+
if (!this.options.notifyParent) {
|
|
3391
|
+
store.releaseOutbox({ eventId: event.eventId, claimToken, reason: "no parent notification channel is available" });
|
|
3392
|
+
continue;
|
|
3393
|
+
}
|
|
3394
|
+
const context = taskId ? this.launchContext(taskId) : undefined;
|
|
3395
|
+
// A handoff that landed just as the store closed is recorded against
|
|
3396
|
+
// this exact event, wait generation and terminal revision. A task-wide
|
|
3397
|
+
// standalone callback receipt is never proof for a later wait.
|
|
3398
|
+
if (taskId && this.outboxHandoffProof(taskId, event)) {
|
|
3399
|
+
try {
|
|
3400
|
+
store.markOutboxDelivered({ eventId: event.eventId, claimToken });
|
|
3401
|
+
}
|
|
3402
|
+
catch { /* already receipted */ }
|
|
3403
|
+
this.clearOutboxHandoffProof(taskId, event.eventId);
|
|
3404
|
+
continue;
|
|
3405
|
+
}
|
|
3406
|
+
const origin = context?.parentOrigin ?? { cwd: owner.workspace, sessionId: owner.sessionId };
|
|
3407
|
+
const branchId = context?.branchId ?? owner.branchId ?? null;
|
|
3408
|
+
if (!this.isParentOriginActive(origin, branchId)) {
|
|
3409
|
+
// Keep the durable delivery pending: the owning session may activate
|
|
3410
|
+
// (or regain the eligible branch) later. Never route it to whoever is
|
|
3411
|
+
// currently in front of the UI.
|
|
3412
|
+
store.releaseOutbox({
|
|
3413
|
+
eventId: event.eventId,
|
|
3414
|
+
claimToken,
|
|
3415
|
+
reason: "owning session or branch is not active",
|
|
3416
|
+
});
|
|
3417
|
+
continue;
|
|
3418
|
+
}
|
|
3419
|
+
let settled = false;
|
|
3420
|
+
const delivery = {
|
|
3421
|
+
receiptId: event.eventId,
|
|
3422
|
+
delivered: () => {
|
|
3423
|
+
if (settled)
|
|
3424
|
+
return;
|
|
3425
|
+
settled = true;
|
|
3426
|
+
let receipted = false;
|
|
3427
|
+
try {
|
|
3428
|
+
store.markOutboxDelivered({ eventId: event.eventId, claimToken });
|
|
3429
|
+
receipted = true;
|
|
3430
|
+
}
|
|
3431
|
+
catch { /* the store closed between handoff and receipt */ }
|
|
3432
|
+
// Key the recovered receipt to this exact event. Never use the
|
|
3433
|
+
// standalone task callback's receipt as proof for a wait.
|
|
3434
|
+
if (!receipted && taskId)
|
|
3435
|
+
this.recordOutboxHandoffProof(taskId, event);
|
|
3436
|
+
},
|
|
3437
|
+
defer: (reason) => {
|
|
3438
|
+
if (settled)
|
|
3439
|
+
return;
|
|
3440
|
+
settled = true;
|
|
3441
|
+
try {
|
|
3442
|
+
store.releaseOutbox({
|
|
3443
|
+
eventId: event.eventId,
|
|
3444
|
+
claimToken,
|
|
3445
|
+
reason: oneLine(reason, 200) || "callback delivery deferred",
|
|
3446
|
+
});
|
|
3447
|
+
}
|
|
3448
|
+
catch { /* another host recovered it */ }
|
|
3449
|
+
if (taskId)
|
|
3450
|
+
this.markCallbackPending(taskId);
|
|
3451
|
+
},
|
|
3452
|
+
};
|
|
3453
|
+
try {
|
|
3454
|
+
this.options.notifyParent({
|
|
3455
|
+
taskId: taskId ?? event.operationId,
|
|
3456
|
+
origin,
|
|
3457
|
+
branchId,
|
|
3458
|
+
operationId: event.operationId,
|
|
3459
|
+
waitId: event.waitId,
|
|
3460
|
+
generation: event.generation,
|
|
3461
|
+
status: this.statusOf(event.operationId),
|
|
3462
|
+
outcome: operation?.terminalOutcome ?? "failed",
|
|
3463
|
+
summary: evidence[0]?.summary ?? "terminal evidence is available",
|
|
3464
|
+
evidence,
|
|
3465
|
+
}, delivery);
|
|
3466
|
+
}
|
|
3467
|
+
catch (error) {
|
|
3468
|
+
delivery.defer(error instanceof Error ? error.message : String(error));
|
|
3469
|
+
}
|
|
3470
|
+
// The callback remains claimed until the batcher's actual handoff
|
|
3471
|
+
// calls `delivered()`; a reload recovers the abandoned claim.
|
|
3472
|
+
continue;
|
|
3473
|
+
}
|
|
3474
|
+
store.markOutboxDelivered({ eventId: event.eventId, claimToken });
|
|
3475
|
+
}
|
|
3476
|
+
catch (error) {
|
|
3477
|
+
if (this.closed)
|
|
3478
|
+
return;
|
|
3479
|
+
try {
|
|
3480
|
+
store.releaseOutbox({
|
|
3481
|
+
eventId: event.eventId,
|
|
3482
|
+
claimToken,
|
|
3483
|
+
reason: oneLine(error instanceof Error ? error.message : String(error), 200) || "delivery failed",
|
|
3484
|
+
});
|
|
3485
|
+
}
|
|
3486
|
+
catch { /* the store closed while the delivery was in flight */ }
|
|
3487
|
+
}
|
|
3488
|
+
}
|
|
3489
|
+
}
|
|
3490
|
+
}
|
|
3491
|
+
statusOf(operationId) {
|
|
3492
|
+
const operation = this.store?.getOperation(operationId);
|
|
3493
|
+
if (!operation)
|
|
3494
|
+
return "lost";
|
|
3495
|
+
if (operation.terminalRevision === 0)
|
|
3496
|
+
return "running";
|
|
3497
|
+
switch (operation.terminalOutcome) {
|
|
3498
|
+
case "succeeded": return "succeeded";
|
|
3499
|
+
case "cancelled": return "cancelled";
|
|
3500
|
+
case "lost": return "lost";
|
|
3501
|
+
default: return "failed";
|
|
3502
|
+
}
|
|
3503
|
+
}
|
|
3504
|
+
// ---- wait helpers ----------------------------------------------------
|
|
3505
|
+
waitView(wait) {
|
|
3506
|
+
const store = this.requireStore();
|
|
3507
|
+
const dependencies = wait.dependencies.map((dep) => {
|
|
3508
|
+
const operation = store.getOperation(dep.operationId);
|
|
3509
|
+
return {
|
|
3510
|
+
...(operation?.taskId ? { taskId: operation.taskId } : {}),
|
|
3511
|
+
operationId: dep.operationId,
|
|
3512
|
+
terminalRevision: dep.terminalRevision,
|
|
3513
|
+
terminalOutcome: dep.terminalOutcome,
|
|
3514
|
+
};
|
|
3515
|
+
});
|
|
3516
|
+
const evidence = [];
|
|
3517
|
+
for (const dep of wait.dependencies) {
|
|
3518
|
+
if (dep.terminalRevision <= 0)
|
|
3519
|
+
continue;
|
|
3520
|
+
const operation = store.getOperation(dep.operationId);
|
|
3521
|
+
evidence.push(...mapEvidence(dep.operationId, operation?.taskId, store.listOperationEvidence(dep.operationId, dep.terminalRevision), dep.terminalRevision));
|
|
3522
|
+
}
|
|
3523
|
+
return {
|
|
3524
|
+
waitId: wait.waitId,
|
|
3525
|
+
generation: wait.generation,
|
|
3526
|
+
phase: wait.phase,
|
|
3527
|
+
settled: wait.settled,
|
|
3528
|
+
park: wait.park !== null,
|
|
3529
|
+
cancelEpoch: wait.cancelEpoch,
|
|
3530
|
+
publishedClaimId: store.listResumeClaims({ waitId: wait.waitId, generation: wait.generation, state: "published" })[0]?.claimId ?? null,
|
|
3531
|
+
ownerKind: wait.owner.kind,
|
|
3532
|
+
continuationNote: wait.continuationNote,
|
|
3533
|
+
taskIds: dependencies
|
|
3534
|
+
.map((dep) => dep.taskId)
|
|
3535
|
+
.filter((taskId) => typeof taskId === "string"),
|
|
3536
|
+
dependencies,
|
|
3537
|
+
evidence,
|
|
3538
|
+
};
|
|
3539
|
+
}
|
|
3540
|
+
waitTaskIds(wait) {
|
|
3541
|
+
return wait.dependencies
|
|
3542
|
+
.map((dep) => this.store?.getOperation(dep.operationId)?.taskId)
|
|
3543
|
+
.filter((taskId) => typeof taskId === "string");
|
|
3544
|
+
}
|
|
3545
|
+
readEvidenceForOwner(owner, waitId, generation, taskId) {
|
|
3546
|
+
const store = this.requireStore();
|
|
3547
|
+
const wait = this.ownedWait(owner, waitId, generation);
|
|
3548
|
+
const reads = [];
|
|
3549
|
+
for (const dep of wait.dependencies) {
|
|
3550
|
+
if (dep.terminalRevision <= 0)
|
|
3551
|
+
continue;
|
|
3552
|
+
const operation = store.getOperation(dep.operationId);
|
|
3553
|
+
if (!operation)
|
|
3554
|
+
continue;
|
|
3555
|
+
if (taskId && operation.taskId !== taskId)
|
|
3556
|
+
continue;
|
|
3557
|
+
store.recordEvidenceRead({
|
|
3558
|
+
waitId,
|
|
3559
|
+
generation,
|
|
3560
|
+
owner,
|
|
3561
|
+
operationId: dep.operationId,
|
|
3562
|
+
terminalRevision: dep.terminalRevision,
|
|
3563
|
+
});
|
|
3564
|
+
reads.push(...mapEvidence(dep.operationId, operation.taskId, store.listOperationEvidence(dep.operationId, dep.terminalRevision), dep.terminalRevision));
|
|
3565
|
+
}
|
|
3566
|
+
return reads;
|
|
3567
|
+
}
|
|
3568
|
+
/** A status/log read is the evidence read the acknowledgement requires. */
|
|
3569
|
+
recordReadsForTask(owner, operation) {
|
|
3570
|
+
const store = this.store;
|
|
3571
|
+
if (!store || operation.terminalRevision <= 0)
|
|
3572
|
+
return;
|
|
3573
|
+
for (const wait of store.listWaits({ owner, pendingOnly: true })) {
|
|
3574
|
+
const dep = wait.dependencies.find((entry) => entry.operationId === operation.operationId);
|
|
3575
|
+
if (!dep || dep.terminalRevision <= 0)
|
|
3576
|
+
continue;
|
|
3577
|
+
try {
|
|
3578
|
+
store.recordEvidenceRead({
|
|
3579
|
+
waitId: wait.waitId,
|
|
3580
|
+
generation: wait.generation,
|
|
3581
|
+
owner,
|
|
3582
|
+
operationId: operation.operationId,
|
|
3583
|
+
terminalRevision: dep.terminalRevision,
|
|
3584
|
+
});
|
|
3585
|
+
}
|
|
3586
|
+
catch { /* a consumed or foreign generation is not this read's business */ }
|
|
3587
|
+
}
|
|
3588
|
+
}
|
|
3589
|
+
cancelWait(owner, waitId, generation, reason) {
|
|
3590
|
+
const store = this.requireStore();
|
|
3591
|
+
const wait = this.ownedWait(owner, waitId, generation);
|
|
3592
|
+
const cancelled = store.cancelWait({
|
|
3593
|
+
waitId,
|
|
3594
|
+
generation,
|
|
3595
|
+
expectedCancelEpoch: wait.cancelEpoch,
|
|
3596
|
+
owner,
|
|
3597
|
+
reason,
|
|
3598
|
+
});
|
|
3599
|
+
try {
|
|
3600
|
+
void Promise.resolve(this.continuation?.onWaitCancelled?.({ waitId, generation, reason })).catch(() => { });
|
|
3601
|
+
}
|
|
3602
|
+
catch { /* a continuation adapter failure cannot undo a persisted cancellation */ }
|
|
3603
|
+
return this.waitView(cancelled.wait);
|
|
3604
|
+
}
|
|
3605
|
+
acknowledge(owner, input) {
|
|
3606
|
+
const store = this.requireStore();
|
|
3607
|
+
const wait = this.ownedWait(owner, input.waitId, input.generation);
|
|
3608
|
+
const revisions = this.normalizeRevisions(wait, input.terminalRevisions);
|
|
3609
|
+
const result = store.acknowledgeResult({
|
|
3610
|
+
waitId: wait.waitId,
|
|
3611
|
+
generation: wait.generation,
|
|
3612
|
+
owner,
|
|
3613
|
+
disposition: input.disposition,
|
|
3614
|
+
note: input.note,
|
|
3615
|
+
terminalRevisions: revisions,
|
|
3616
|
+
});
|
|
3617
|
+
return {
|
|
3618
|
+
waitId: result.wait.waitId,
|
|
3619
|
+
generation: result.wait.generation,
|
|
3620
|
+
disposition: input.disposition,
|
|
3621
|
+
acknowledgedOutboxIds: result.acknowledgedOutboxIds,
|
|
3622
|
+
releasedPinIds: result.releasedPinIds,
|
|
3623
|
+
phase: result.wait.phase,
|
|
3624
|
+
};
|
|
3625
|
+
}
|
|
3626
|
+
normalizeRevisions(wait, input) {
|
|
3627
|
+
const store = this.requireStore();
|
|
3628
|
+
const resolved = [];
|
|
3629
|
+
const add = (operationId, taskId, revision) => {
|
|
3630
|
+
if (typeof revision !== "number" || !Number.isSafeInteger(revision) || revision < 1) {
|
|
3631
|
+
throw new Error("terminal_revisions must carry positive integer revisions.");
|
|
3632
|
+
}
|
|
3633
|
+
let operationIdValue = typeof operationId === "string" ? operationId : undefined;
|
|
3634
|
+
if (!operationIdValue && typeof taskId === "string") {
|
|
3635
|
+
operationIdValue = this.operationForTask(taskId)?.operationId;
|
|
3636
|
+
}
|
|
3637
|
+
if (!operationIdValue)
|
|
3638
|
+
throw new Error("terminal_revisions must name an operation_id (or a known task_id).");
|
|
3639
|
+
const dependency = wait.dependencies.find((dep) => dep.operationId === operationIdValue);
|
|
3640
|
+
if (!dependency)
|
|
3641
|
+
throw new Error(`Operation ${operationIdValue} is not a dependency of wait ${wait.waitId}.`);
|
|
3642
|
+
if (dependency.terminalRevision !== revision) {
|
|
3643
|
+
throw new Error(`Operation ${operationIdValue} is at terminal revision ${dependency.terminalRevision}, not ${revision}.`);
|
|
3644
|
+
}
|
|
3645
|
+
resolved.push({ operationId: operationIdValue, revision });
|
|
3646
|
+
};
|
|
3647
|
+
if (Array.isArray(input)) {
|
|
3648
|
+
for (const entry of input) {
|
|
3649
|
+
if (!entry || typeof entry !== "object")
|
|
3650
|
+
throw new Error("terminal_revisions entries must be objects.");
|
|
3651
|
+
const record = entry;
|
|
3652
|
+
add(record.operation_id ?? record.operationId, record.task_id ?? record.taskId, record.revision);
|
|
3653
|
+
}
|
|
3654
|
+
}
|
|
3655
|
+
else if (input && typeof input === "object") {
|
|
3656
|
+
for (const [key, revision] of Object.entries(input)) {
|
|
3657
|
+
const operation = store.getOperation(key) ? key : this.operationForTask(key)?.operationId;
|
|
3658
|
+
add(operation, key, revision);
|
|
3659
|
+
}
|
|
3660
|
+
}
|
|
3661
|
+
else {
|
|
3662
|
+
throw new Error("terminal_revisions is required.");
|
|
3663
|
+
}
|
|
3664
|
+
const unique = new Map(resolved.map((entry) => [entry.operationId, entry.revision]));
|
|
3665
|
+
if (unique.size === 0)
|
|
3666
|
+
throw new Error("terminal_revisions is empty.");
|
|
3667
|
+
return [...unique].map(([operationId, revision]) => ({ operationId, revision }));
|
|
3668
|
+
}
|
|
3669
|
+
// ---- identity and ownership -----------------------------------------
|
|
3670
|
+
sessionId(ctx) {
|
|
3671
|
+
try {
|
|
3672
|
+
const id = ctx.sessionManager?.getSessionId();
|
|
3673
|
+
if (typeof id === "string" && id.length > 0)
|
|
3674
|
+
return id;
|
|
3675
|
+
}
|
|
3676
|
+
catch { /* unavailable */ }
|
|
3677
|
+
return this.fallbackSessionId();
|
|
3678
|
+
}
|
|
3679
|
+
fallbackSessionId() {
|
|
3680
|
+
// A synthetic id keeps one host's launches owned by that host; it is stable
|
|
3681
|
+
// only for this process, which matches the missing-session contract.
|
|
3682
|
+
return `anonymous:${this.hostId}`;
|
|
3683
|
+
}
|
|
3684
|
+
ownerFor(ctx) {
|
|
3685
|
+
const sessionId = this.sessionId(ctx);
|
|
3686
|
+
const workspace = ctx.cwd;
|
|
3687
|
+
const key = `${sessionId}\u0000${workspace}`;
|
|
3688
|
+
let branchId = this.branchAnchors.get(key);
|
|
3689
|
+
if (branchId === undefined) {
|
|
3690
|
+
branchId = this.latestBranchId(ctx);
|
|
3691
|
+
// Reuse a pending wait's anchor after a reload so the store owner matches
|
|
3692
|
+
// the anchor recorded in the previous process.
|
|
3693
|
+
const existing = this.store?.listWaits({ pendingOnly: true })
|
|
3694
|
+
.find((wait) => wait.owner.kind === "parent-session"
|
|
3695
|
+
&& wait.owner.sessionId === sessionId && wait.owner.workspace === workspace);
|
|
3696
|
+
if (existing)
|
|
3697
|
+
branchId = existing.owner.branchId ?? null;
|
|
3698
|
+
this.branchAnchors.set(key, branchId);
|
|
3699
|
+
}
|
|
3700
|
+
return {
|
|
3701
|
+
kind: "parent-session",
|
|
3702
|
+
sessionId,
|
|
3703
|
+
workspace,
|
|
3704
|
+
branchId,
|
|
3705
|
+
goalId: null,
|
|
3706
|
+
};
|
|
3707
|
+
}
|
|
3708
|
+
latestBranchId(ctx) {
|
|
3709
|
+
try {
|
|
3710
|
+
const branch = ctx.sessionManager?.getBranch?.();
|
|
3711
|
+
if (!branch || branch.length === 0)
|
|
3712
|
+
return null;
|
|
3713
|
+
const id = branch[branch.length - 1]?.id;
|
|
3714
|
+
return typeof id === "string" && id.length > 0 ? id : null;
|
|
3715
|
+
}
|
|
3716
|
+
catch {
|
|
3717
|
+
return null;
|
|
3718
|
+
}
|
|
3719
|
+
}
|
|
3720
|
+
workerOwner(run) {
|
|
3721
|
+
return {
|
|
3722
|
+
kind: "worker-conversation",
|
|
3723
|
+
sessionId: run.conversationId,
|
|
3724
|
+
workspace: run.workspace,
|
|
3725
|
+
branchId: run.branchId ?? null,
|
|
3726
|
+
goalId: run.goalId ?? null,
|
|
3727
|
+
};
|
|
3728
|
+
}
|
|
3729
|
+
/**
|
|
3730
|
+
* Refresh the active session/branch snapshot. Called at start, at launch and
|
|
3731
|
+
* on every session_tree/branch navigation. Branch changes must be visible to
|
|
3732
|
+
* a queued callback *before* the batcher decides whether to deliver it.
|
|
3733
|
+
*/
|
|
3734
|
+
noteParentContext(ctx, options = {}) {
|
|
3735
|
+
this.setActiveOrigin(ctx, options.recover !== false);
|
|
3736
|
+
if (options.recover === false)
|
|
3737
|
+
return;
|
|
3738
|
+
if (!this.store)
|
|
3739
|
+
return;
|
|
3740
|
+
this.recoverAbandonedDeliveries();
|
|
3741
|
+
if (this.terminalRecoveryNeeded) {
|
|
3742
|
+
this.terminalRecoveryNeeded = false;
|
|
3743
|
+
this.recoverTerminalNotifications();
|
|
3744
|
+
}
|
|
3745
|
+
void this.dispatchOutbox();
|
|
3746
|
+
this.retryPendingTerminalCallbacks();
|
|
3747
|
+
this.writeHostDebug();
|
|
3748
|
+
}
|
|
3749
|
+
setActiveOrigin(ctx, debug = true) {
|
|
3750
|
+
const previous = this.activeContext;
|
|
3751
|
+
const previousKey = previous ? this.contextKey(previous) : undefined;
|
|
3752
|
+
const nextSessionId = this.sessionIdIfAvailable(ctx);
|
|
3753
|
+
const previousSessionId = previous ? this.sessionIdIfAvailable(previous) : undefined;
|
|
3754
|
+
// A partial tool/event context (no readable session identity) must not
|
|
3755
|
+
// replace a context that still proves the real session.
|
|
3756
|
+
if (!nextSessionId && previousSessionId)
|
|
3757
|
+
return;
|
|
3758
|
+
const origin = { cwd: ctx.cwd, sessionId: nextSessionId ?? this.sessionId(ctx) };
|
|
3759
|
+
const nextKey = this.contextKey(ctx);
|
|
3760
|
+
this.parentOrigin = origin;
|
|
3761
|
+
this.activeOrigin = origin;
|
|
3762
|
+
this.activeContext = ctx;
|
|
3763
|
+
// A tool call or activation for a different session/workspace must seed the
|
|
3764
|
+
// terminal callback journal once. Same-session calls keep the live context
|
|
3765
|
+
// current without rescanning historical terminal records.
|
|
3766
|
+
const branchSignature = JSON.stringify(branchIdsOf(ctx));
|
|
3767
|
+
const branchChanged = branchSignature !== this.activeBranchSignature;
|
|
3768
|
+
if (!previous || previousKey !== nextKey || branchChanged)
|
|
3769
|
+
this.terminalRecoveryNeeded = true;
|
|
3770
|
+
if (branchChanged) {
|
|
3771
|
+
this.lastChangeRevision = -1;
|
|
3772
|
+
this.pendingCallbackCursor = undefined;
|
|
3773
|
+
this.pendingClaimCursor = undefined;
|
|
3774
|
+
}
|
|
3775
|
+
this.activeBranchSignature = branchSignature;
|
|
3776
|
+
if (debug)
|
|
3777
|
+
this.writeHostDebug();
|
|
3778
|
+
}
|
|
3779
|
+
contextKey(ctx) {
|
|
3780
|
+
try {
|
|
3781
|
+
return `${this.sessionId(ctx)}\u0000${ctx.cwd}`;
|
|
3782
|
+
}
|
|
3783
|
+
catch {
|
|
3784
|
+
return undefined;
|
|
3785
|
+
}
|
|
3786
|
+
}
|
|
3787
|
+
/**
|
|
3788
|
+
* Exact session/workspace match plus an eligible branch anchor. A descendant
|
|
3789
|
+
* branch contains the recorded anchor; an abandoned fork does not.
|
|
3790
|
+
*/
|
|
3791
|
+
isParentOriginActive(origin, branchId) {
|
|
3792
|
+
const ctx = this.activeContext;
|
|
3793
|
+
if (!ctx || !origin)
|
|
3794
|
+
return false;
|
|
3795
|
+
let cwd;
|
|
3796
|
+
try {
|
|
3797
|
+
cwd = ctx.cwd;
|
|
3798
|
+
}
|
|
3799
|
+
catch {
|
|
3800
|
+
return false;
|
|
3801
|
+
}
|
|
3802
|
+
if (cwd !== origin.cwd)
|
|
3803
|
+
return false;
|
|
3804
|
+
const sessionId = this.sessionId(ctx);
|
|
3805
|
+
if (origin.sessionId || sessionId) {
|
|
3806
|
+
if (origin.sessionId !== sessionId)
|
|
3807
|
+
return false;
|
|
3808
|
+
}
|
|
3809
|
+
if (!branchId)
|
|
3810
|
+
return true;
|
|
3811
|
+
// Read the branch live: the SDK may settle reload history after session_start.
|
|
3812
|
+
return branchIdsOf(ctx).includes(branchId);
|
|
3813
|
+
}
|
|
3814
|
+
get parentSessionOrigin() {
|
|
3815
|
+
return this.parentOrigin;
|
|
3816
|
+
}
|
|
3817
|
+
requireStarted(ctx) {
|
|
3818
|
+
if (!ctx)
|
|
3819
|
+
return;
|
|
3820
|
+
this.noteParentContext(ctx);
|
|
3821
|
+
}
|
|
3822
|
+
/** Bounded host-level diagnostics for root reload investigations. */
|
|
3823
|
+
writeHostDebug() {
|
|
3824
|
+
if (process.env.PI_BG_OBSERVED_WAITS_DEBUG !== "1")
|
|
3825
|
+
return;
|
|
3826
|
+
try {
|
|
3827
|
+
const dir = join(this.directory, "observed");
|
|
3828
|
+
mkdirSync(dir, { recursive: true });
|
|
3829
|
+
const ctx = this.activeContext;
|
|
3830
|
+
writeFileSync(join(dir, "host.json"), JSON.stringify({
|
|
3831
|
+
hostId: this.hostId,
|
|
3832
|
+
storeOpen: !!this.store,
|
|
3833
|
+
closed: this.closed,
|
|
3834
|
+
managementMode: this.options.serverOwnedResults ? "server-client" : "legacy",
|
|
3835
|
+
activeContext: !!ctx,
|
|
3836
|
+
activeSessionId: ctx ? this.sessionIdIfAvailable(ctx) ?? this.sessionId(ctx) : undefined,
|
|
3837
|
+
activeCwd: ctx ? ctx.cwd : undefined,
|
|
3838
|
+
activeBranchIds: ctx ? branchIdsOf(ctx) : [],
|
|
3839
|
+
terminalRecoveryNeeded: this.terminalRecoveryNeeded,
|
|
3840
|
+
pendingTerminalCallbacks: [...this.pendingTerminalCallbacks],
|
|
3841
|
+
writtenAt: Date.now(),
|
|
3842
|
+
}), { mode: 0o600 });
|
|
3843
|
+
}
|
|
3844
|
+
catch { /* diagnostics only */ }
|
|
3845
|
+
}
|
|
3846
|
+
sessionIdIfAvailable(ctx) {
|
|
3847
|
+
try {
|
|
3848
|
+
const id = ctx.sessionManager?.getSessionId();
|
|
3849
|
+
return typeof id === "string" && id.length > 0 ? id : undefined;
|
|
3850
|
+
}
|
|
3851
|
+
catch {
|
|
3852
|
+
return undefined;
|
|
3853
|
+
}
|
|
3854
|
+
}
|
|
3855
|
+
sidecarPath(taskId) {
|
|
3856
|
+
return join(this.directory, "observed", `${taskId}.json`);
|
|
3857
|
+
}
|
|
3858
|
+
writeLaunchContext(taskId, context) {
|
|
3859
|
+
try {
|
|
3860
|
+
const operation = this.operationForTask(taskId);
|
|
3861
|
+
const parent = operation?.owner.kind === "parent-session";
|
|
3862
|
+
const outboxDelivered = operation && Object.values(context.outboxDelivered ?? {}).some(proof => proof.terminalRevision === operation.terminalRevision);
|
|
3863
|
+
const pending = context.callback !== false && context.callbackDeliveredAt === undefined && !outboxDelivered;
|
|
3864
|
+
// Publish the obligation before the sidecar: a crash may leave a pending
|
|
3865
|
+
// candidate, but cannot hide an accepted callback. Retire only after the
|
|
3866
|
+
// delivered/disabled sidecar is durable, so replay can prove suppression.
|
|
3867
|
+
if (parent && pending)
|
|
3868
|
+
this.store?.setParentCallbackPending(taskId, true);
|
|
3869
|
+
const path = this.sidecarPath(taskId);
|
|
3870
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
3871
|
+
const staged = `${path}.${randomUUID()}.tmp`;
|
|
3872
|
+
try {
|
|
3873
|
+
writeFileSync(staged, JSON.stringify(context), { mode: 0o600, flag: "wx" });
|
|
3874
|
+
renameSync(staged, path);
|
|
3875
|
+
}
|
|
3876
|
+
finally {
|
|
3877
|
+
rmSync(staged, { force: true });
|
|
3878
|
+
}
|
|
3879
|
+
if (parent && !pending)
|
|
3880
|
+
this.store?.setParentCallbackPending(taskId, false);
|
|
3881
|
+
}
|
|
3882
|
+
catch { /* retain an obligation if the exact sidecar cannot be persisted */ }
|
|
3883
|
+
}
|
|
3884
|
+
readLaunchContext(taskId) {
|
|
3885
|
+
try {
|
|
3886
|
+
const value = JSON.parse(readFileSync(this.sidecarPath(taskId), "utf8"));
|
|
3887
|
+
if (value.kind !== "process" && value.kind !== "watch")
|
|
3888
|
+
return undefined;
|
|
3889
|
+
return {
|
|
3890
|
+
kind: value.kind,
|
|
3891
|
+
...(value.parentOrigin && typeof value.parentOrigin === "object"
|
|
3892
|
+
? { parentOrigin: value.parentOrigin } : {}),
|
|
3893
|
+
gated: value.gated === true,
|
|
3894
|
+
callback: value.callback !== false,
|
|
3895
|
+
...(typeof value.name === "string" ? { name: value.name } : {}),
|
|
3896
|
+
...(typeof value.command === "string" ? { command: value.command } : {}),
|
|
3897
|
+
...(Array.isArray(value.argv) && value.argv.every((entry) => typeof entry === "string")
|
|
3898
|
+
? { argv: value.argv } : {}),
|
|
3899
|
+
...(typeof value.cwd === "string" ? { cwd: value.cwd } : {}),
|
|
3900
|
+
...(value.sandbox && typeof value.sandbox === "object" && !Array.isArray(value.sandbox)
|
|
3901
|
+
? { sandbox: value.sandbox } : {}),
|
|
3902
|
+
...(value.supervisionPolicy && typeof value.supervisionPolicy === "object"
|
|
3903
|
+
? { supervisionPolicy: value.supervisionPolicy } : {}),
|
|
3904
|
+
...(typeof value.branchId === "string" || value.branchId === null ? { branchId: value.branchId } : {}),
|
|
3905
|
+
...(typeof value.callbackPendingAt === "number" ? { callbackPendingAt: value.callbackPendingAt } : {}),
|
|
3906
|
+
...(typeof value.callbackDeliveredAt === "number" ? { callbackDeliveredAt: value.callbackDeliveredAt }
|
|
3907
|
+
: typeof value.callbackNotifiedAt === "number"
|
|
3908
|
+
? { callbackDeliveredAt: value.callbackNotifiedAt }
|
|
3909
|
+
: {}),
|
|
3910
|
+
...(typeof value.callbackDeferredReason === "string" ? { callbackDeferredReason: value.callbackDeferredReason } : {}),
|
|
3911
|
+
...(typeof value.callbackClaimedBy === "string" ? { callbackClaimedBy: value.callbackClaimedBy } : {}),
|
|
3912
|
+
...(typeof value.callbackClaimedAt === "number" ? { callbackClaimedAt: value.callbackClaimedAt } : {}),
|
|
3913
|
+
...(typeof value.callbackClaimToken === "string" ? { callbackClaimToken: value.callbackClaimToken } : {}),
|
|
3914
|
+
...(typeof value.callbackAttemptedAt === "number" ? { callbackAttemptedAt: value.callbackAttemptedAt } : {}),
|
|
3915
|
+
...(typeof value.callbackSkipReason === "string" ? { callbackSkipReason: value.callbackSkipReason } : {}),
|
|
3916
|
+
...(typeof value.terminalRecordedBy === "string" ? { terminalRecordedBy: value.terminalRecordedBy } : {}),
|
|
3917
|
+
...(typeof value.terminalRecordedAt === "number" ? { terminalRecordedAt: value.terminalRecordedAt } : {}),
|
|
3918
|
+
...(typeof value.terminalRecordedWithContext === "boolean" ? { terminalRecordedWithContext: value.terminalRecordedWithContext } : {}),
|
|
3919
|
+
...(typeof value.terminalActiveSessionId === "string" ? { terminalActiveSessionId: value.terminalActiveSessionId } : {}),
|
|
3920
|
+
...(Array.isArray(value.terminalActiveBranchIds) ? { terminalActiveBranchIds: value.terminalActiveBranchIds } : {}),
|
|
3921
|
+
...(typeof value.terminalReplayObservedBy === "string" ? { terminalReplayObservedBy: value.terminalReplayObservedBy } : {}),
|
|
3922
|
+
...(value.outboxDelivered && typeof value.outboxDelivered === "object" && !Array.isArray(value.outboxDelivered)
|
|
3923
|
+
? { outboxDelivered: value.outboxDelivered } : {}),
|
|
3924
|
+
...(typeof value.dismissedAt === "number" ? { dismissedAt: value.dismissedAt } : {}),
|
|
3925
|
+
};
|
|
3926
|
+
}
|
|
3927
|
+
catch {
|
|
3928
|
+
return undefined;
|
|
3929
|
+
}
|
|
3930
|
+
}
|
|
3931
|
+
launchContext(taskId) {
|
|
3932
|
+
return this.launches.get(taskId) ?? this.readLaunchContext(taskId);
|
|
3933
|
+
}
|
|
3934
|
+
/**
|
|
3935
|
+
* The shared sidecar is authoritative for callback claims. Every callback
|
|
3936
|
+
* mutation and diagnostic write uses this fresh copy, never a cached object
|
|
3937
|
+
* that another host may have already superseded.
|
|
3938
|
+
*/
|
|
3939
|
+
currentLaunchContext(taskId) {
|
|
3940
|
+
const persisted = this.readLaunchContext(taskId);
|
|
3941
|
+
if (persisted) {
|
|
3942
|
+
this.launches.set(taskId, persisted);
|
|
3943
|
+
return persisted;
|
|
3944
|
+
}
|
|
3945
|
+
// An unreadable journal cannot establish ownership of a delivery claim.
|
|
3946
|
+
this.launches.delete(taskId);
|
|
3947
|
+
return undefined;
|
|
3948
|
+
}
|
|
3949
|
+
requireStore() {
|
|
3950
|
+
if (!this.store && !this.closed)
|
|
3951
|
+
this.start();
|
|
3952
|
+
if (!this.store || this.closed) {
|
|
3953
|
+
throw new Error(this.unavailableReason ?? "Observed waits are unavailable; the durable store is not open.");
|
|
3954
|
+
}
|
|
3955
|
+
return this.store;
|
|
3956
|
+
}
|
|
3957
|
+
operationsForTaskIds(owner, taskIds) {
|
|
3958
|
+
if (!Array.isArray(taskIds) || taskIds.length === 0)
|
|
3959
|
+
throw new Error("At least one task id is required.");
|
|
3960
|
+
const operations = [];
|
|
3961
|
+
for (const taskId of taskIds) {
|
|
3962
|
+
if (typeof taskId !== "string" || !LOCAL_DURABLE_ID.test(taskId)) {
|
|
3963
|
+
throw new Error(`Task ${String(taskId)} is not a durable local operation; results are observed only for supervised local tasks.`);
|
|
3964
|
+
}
|
|
3965
|
+
const operation = this.operationForTask(taskId);
|
|
3966
|
+
if (!operation)
|
|
3967
|
+
throw new Error(`Unknown durable task ${taskId}.`);
|
|
3968
|
+
if (!ownerMatchesOperation(operation, owner)) {
|
|
3969
|
+
throw new Error(`Task ${taskId} belongs to another execution owner; a wait may only depend on an owned operation.`);
|
|
3970
|
+
}
|
|
3971
|
+
if (operations.some((entry) => entry.operationId === operation.operationId))
|
|
3972
|
+
continue;
|
|
3973
|
+
operations.push(operation);
|
|
3974
|
+
}
|
|
3975
|
+
return operations;
|
|
3976
|
+
}
|
|
3977
|
+
operationForTask(taskId) {
|
|
3978
|
+
return this.store?.listOperations({ taskId })[0];
|
|
3979
|
+
}
|
|
3980
|
+
ownedOperation(taskId, owner) {
|
|
3981
|
+
const operation = this.operationForTask(taskId);
|
|
3982
|
+
if (!operation)
|
|
3983
|
+
throw new Error(`Unknown durable task ${taskId}.`);
|
|
3984
|
+
if (!ownerMatchesOperation(operation, owner)) {
|
|
3985
|
+
throw new Error(`Task ${taskId} belongs to another execution owner (${operation.owner.kind} ${operation.owner.sessionId}).`);
|
|
3986
|
+
}
|
|
3987
|
+
return operation;
|
|
3988
|
+
}
|
|
3989
|
+
ownedWait(owner, waitId, generation) {
|
|
3990
|
+
const wait = this.requireStore().getWait({ waitId, generation });
|
|
3991
|
+
if (!wait)
|
|
3992
|
+
throw new Error(`Unknown wait ${waitId} generation ${generation}.`);
|
|
3993
|
+
if (!sameOwner(wait.owner, owner))
|
|
3994
|
+
throw new Error(`Wait ${waitId} belongs to another execution owner.`);
|
|
3995
|
+
return wait;
|
|
3996
|
+
}
|
|
3997
|
+
supervision() {
|
|
3998
|
+
return { hostId: this.hostId, runnerId: null, processStartToken: null, resultScope: this.discoveryScope,
|
|
3999
|
+
...(this.options.serverOwnedResults ? { resultAdapter: 1 } : {}) };
|
|
4000
|
+
}
|
|
4001
|
+
parentAuthority(owner, plan) {
|
|
4002
|
+
const levels = plan.confined && plan.permissions
|
|
4003
|
+
? `${plan.permissions.projectFiles}/${plan.permissions.outsideProject}/${plan.permissions.storedCredentials}/${plan.permissions.commands ? "commands" : "no-commands"}/${plan.permissions.network ? "network" : "no-network"}`
|
|
4004
|
+
: plan.confined ? "write-confinement" : "unconfined";
|
|
4005
|
+
return authorityReference(`parent:${owner.sessionId}:${levels}`);
|
|
4006
|
+
}
|
|
4007
|
+
announce() {
|
|
4008
|
+
const events = eventBusOf(this.pi);
|
|
4009
|
+
if (!events)
|
|
4010
|
+
return;
|
|
4011
|
+
events.emit(OBSERVED_WAITS_SERVICE_CHANNEL, this.service);
|
|
4012
|
+
}
|
|
4013
|
+
announceUnavailable(reason) {
|
|
4014
|
+
const events = eventBusOf(this.pi);
|
|
4015
|
+
if (!events)
|
|
4016
|
+
return;
|
|
4017
|
+
events.emit(OBSERVED_WAITS_SERVICE_CHANNEL, {
|
|
4018
|
+
version: OBSERVED_WAITS_SERVICE_VERSION,
|
|
4019
|
+
available: false,
|
|
4020
|
+
reason: oneLine(reason, 300),
|
|
4021
|
+
});
|
|
4022
|
+
}
|
|
4023
|
+
/** Answer a late service request without requiring the requester to know the host. */
|
|
4024
|
+
listenForServiceRequests() {
|
|
4025
|
+
const events = eventBusOf(this.pi);
|
|
4026
|
+
if (!events)
|
|
4027
|
+
return;
|
|
4028
|
+
events.on(OBSERVED_WAITS_SERVICE_REQUEST_CHANNEL, () => {
|
|
4029
|
+
if (this.closed) {
|
|
4030
|
+
this.announceUnavailable(this.unavailableReason ?? "the Background operation host closed");
|
|
4031
|
+
}
|
|
4032
|
+
else if (this.store || this.unavailableReason === undefined) {
|
|
4033
|
+
// A load-order probe may arrive before session_start. The capability
|
|
4034
|
+
// object exists; its methods open the store on first use.
|
|
4035
|
+
this.announce();
|
|
4036
|
+
}
|
|
4037
|
+
else {
|
|
4038
|
+
this.announceUnavailable(this.unavailableReason);
|
|
4039
|
+
}
|
|
4040
|
+
});
|
|
4041
|
+
}
|
|
4042
|
+
}
|
|
4043
|
+
function tailText(text, lines) {
|
|
4044
|
+
return lastLines(text, lines).replace(/\n+/g, " ⏎ ").slice(0, 400);
|
|
4045
|
+
}
|
|
4046
|
+
function requireRpcString(params, key) {
|
|
4047
|
+
const value = params[key];
|
|
4048
|
+
if (typeof value !== "string" || value.length === 0)
|
|
4049
|
+
throw new Error(`${key} is required.`);
|
|
4050
|
+
return value;
|
|
4051
|
+
}
|
|
4052
|
+
function requireRpcCounter(params, key) {
|
|
4053
|
+
const value = params[key];
|
|
4054
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0)
|
|
4055
|
+
throw new Error(`${key} must be a non-negative integer.`);
|
|
4056
|
+
return value;
|
|
4057
|
+
}
|
|
4058
|
+
function waitKey(waitId, generation) {
|
|
4059
|
+
return `${waitId}:${generation}`;
|
|
4060
|
+
}
|
|
4061
|
+
/** Model-facing summary of one wait generation. */
|
|
4062
|
+
export function formatWaitView(view) {
|
|
4063
|
+
const lines = [
|
|
4064
|
+
`${view.waitId} generation ${view.generation}: ${view.phase}${view.settled ? " (all dependencies settled)" : " (waiting)"}`,
|
|
4065
|
+
`owner: ${view.ownerKind}`,
|
|
4066
|
+
];
|
|
4067
|
+
for (const dep of view.dependencies) {
|
|
4068
|
+
lines.push(`- ${dep.taskId ?? dep.operationId}: revision ${dep.terminalRevision}${dep.terminalOutcome ? ` ${dep.terminalOutcome}` : " unsettled"}`);
|
|
4069
|
+
}
|
|
4070
|
+
if (view.evidence.length) {
|
|
4071
|
+
lines.push(`evidence: ${view.evidence.map((entry) => `${entry.kind}:${entry.ref}`).join(", ")}`);
|
|
4072
|
+
}
|
|
4073
|
+
lines.push(view.park
|
|
4074
|
+
? "Parked worker wait: resumption belongs to the registered continuation adapter."
|
|
4075
|
+
: "The parent stays responsive; this registration never blocks the model.");
|
|
4076
|
+
if (view.settled) {
|
|
4077
|
+
lines.push("Read the terminal evidence with bg_task_status and bg_task_log, then call acknowledge_operation_result with the exact revisions.");
|
|
4078
|
+
}
|
|
4079
|
+
return lines.join("\n");
|
|
4080
|
+
}
|