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