@caupulican/pi-adaptative 0.85.4 → 0.86.1
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/CHANGELOG.md +65 -0
- package/dist/bun/cli.d.ts +1 -1
- package/dist/bun/cli.d.ts.map +1 -1
- package/dist/bun/cli.js +1 -0
- package/dist/bun/cli.js.map +1 -1
- package/dist/core/agent-paths.d.ts +3 -3
- package/dist/core/agent-paths.d.ts.map +1 -1
- package/dist/core/agent-paths.js +3 -3
- package/dist/core/agent-paths.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +1 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +1 -1
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session.d.ts +11 -5
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +14 -3
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts +2 -2
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +2 -2
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
- package/dist/core/autonomy/bounded-completion.js +19 -8
- package/dist/core/autonomy/bounded-completion.js.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.d.ts +11 -5
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.js +34 -8
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
- package/dist/core/autonomy/subagent-prompt.d.ts +3 -3
- package/dist/core/autonomy/subagent-prompt.js +9 -9
- package/dist/core/autonomy/subagent-prompt.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +10 -8
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +23 -13
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/bash-execution-controller.d.ts +4 -0
- package/dist/core/bash-execution-controller.d.ts.map +1 -1
- package/dist/core/bash-execution-controller.js +11 -4
- package/dist/core/bash-execution-controller.js.map +1 -1
- package/dist/core/bash-executor.d.ts +2 -0
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +4 -3
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/billing-failover-controller.d.ts +2 -2
- package/dist/core/billing-failover-controller.d.ts.map +1 -1
- package/dist/core/billing-failover-controller.js +1 -1
- package/dist/core/billing-failover-controller.js.map +1 -1
- package/dist/core/capability-contract.d.ts +1 -1
- package/dist/core/capability-contract.d.ts.map +1 -1
- package/dist/core/capability-contract.js +0 -1
- package/dist/core/capability-contract.js.map +1 -1
- package/dist/core/compaction-controller.d.ts +8 -2
- package/dist/core/compaction-controller.d.ts.map +1 -1
- package/dist/core/compaction-controller.js +73 -3
- package/dist/core/compaction-controller.js.map +1 -1
- package/dist/core/compaction-support.d.ts +2 -2
- package/dist/core/compaction-support.d.ts.map +1 -1
- package/dist/core/compaction-support.js +9 -1
- package/dist/core/compaction-support.js.map +1 -1
- package/dist/core/context/artifact-retrieval.d.ts +1 -1
- package/dist/core/context/artifact-retrieval.d.ts.map +1 -1
- package/dist/core/context/artifact-retrieval.js +1 -1
- package/dist/core/context/artifact-retrieval.js.map +1 -1
- package/dist/core/context/context-artifacts.d.ts +6 -6
- package/dist/core/context/context-artifacts.d.ts.map +1 -1
- package/dist/core/context/context-artifacts.js +151 -63
- package/dist/core/context/context-artifacts.js.map +1 -1
- package/dist/core/context/context-composition.js +1 -1
- package/dist/core/context/context-composition.js.map +1 -1
- package/dist/core/context/context-store-retention.d.ts.map +1 -1
- package/dist/core/context/context-store-retention.js +5 -2
- package/dist/core/context/context-store-retention.js.map +1 -1
- package/dist/core/context/file-store-memory-provider.js +1 -1
- package/dist/core/context/file-store-memory-provider.js.map +1 -1
- package/dist/core/context/tool-output-packer.d.ts +1 -1
- package/dist/core/context/tool-output-packer.d.ts.map +1 -1
- package/dist/core/context/tool-output-packer.js +1 -1
- package/dist/core/context/tool-output-packer.js.map +1 -1
- package/dist/core/context-gc.d.ts.map +1 -1
- package/dist/core/context-gc.js +7 -5
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/context-pipeline.d.ts +2 -2
- package/dist/core/context-pipeline.d.ts.map +1 -1
- package/dist/core/context-pipeline.js +8 -4
- package/dist/core/context-pipeline.js.map +1 -1
- package/dist/core/cost/cost-summary.d.ts +1 -1
- package/dist/core/cost/cost-summary.d.ts.map +1 -1
- package/dist/core/cost/cost-summary.js +1 -1
- package/dist/core/cost/cost-summary.js.map +1 -1
- package/dist/core/cost/daily-usage.d.ts +1 -1
- package/dist/core/cost/daily-usage.d.ts.map +1 -1
- package/dist/core/cost/daily-usage.js +2 -2
- package/dist/core/cost/daily-usage.js.map +1 -1
- package/dist/core/cost/session-usage.d.ts +1 -1
- package/dist/core/cost/session-usage.d.ts.map +1 -1
- package/dist/core/cost/session-usage.js +1 -1
- package/dist/core/cost/session-usage.js.map +1 -1
- package/dist/core/default-tool-surface.d.ts +1 -0
- package/dist/core/default-tool-surface.d.ts.map +1 -1
- package/dist/core/default-tool-surface.js +3 -2
- package/dist/core/default-tool-surface.js.map +1 -1
- package/dist/core/delegation/worker-actions.js +1 -1
- package/dist/core/delegation/worker-actions.js.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.d.ts +27 -8
- package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.js +191 -33
- package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-agent-control.d.ts +45 -6
- package/dist/core/delegation/worker-agent-control.d.ts.map +1 -1
- package/dist/core/delegation/worker-agent-control.js +110 -13
- package/dist/core/delegation/worker-agent-control.js.map +1 -1
- package/dist/core/delegation/worker-attempt-executor.d.ts +1 -1
- package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
- package/dist/core/delegation/worker-attempt-executor.js +180 -160
- package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
- package/dist/core/delegation/worker-authority-resolver.d.ts +23 -0
- package/dist/core/delegation/worker-authority-resolver.d.ts.map +1 -0
- package/dist/core/delegation/worker-authority-resolver.js +128 -0
- package/dist/core/delegation/worker-authority-resolver.js.map +1 -0
- package/dist/core/delegation/worker-conversation-store.d.ts +2 -1
- package/dist/core/delegation/worker-conversation-store.d.ts.map +1 -1
- package/dist/core/delegation/worker-conversation-store.js +4 -3
- package/dist/core/delegation/worker-conversation-store.js.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.d.ts +7 -1
- package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.js +260 -87
- package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
- package/dist/core/delegation/worker-delegation-request.d.ts +25 -4
- package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -1
- package/dist/core/delegation/worker-delegation-request.js +90 -1
- package/dist/core/delegation/worker-delegation-request.js.map +1 -1
- package/dist/core/delegation/worker-execution-policy.d.ts +2 -0
- package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
- package/dist/core/delegation/worker-execution-policy.js +22 -12
- package/dist/core/delegation/worker-execution-policy.js.map +1 -1
- package/dist/core/delegation/worker-lifecycle.d.ts +1 -0
- package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -1
- package/dist/core/delegation/worker-lifecycle.js +4 -2
- package/dist/core/delegation/worker-lifecycle.js.map +1 -1
- package/dist/core/delegation/worker-profile-resolver.d.ts +0 -2
- package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -1
- package/dist/core/delegation/worker-profile-resolver.js +8 -35
- package/dist/core/delegation/worker-profile-resolver.js.map +1 -1
- package/dist/core/delegation/worker-recovery-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-recovery-coordinator.js +1 -0
- package/dist/core/delegation/worker-recovery-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-runner.d.ts +6 -1
- package/dist/core/delegation/worker-runner.d.ts.map +1 -1
- package/dist/core/delegation/worker-runner.js +20 -6
- package/dist/core/delegation/worker-runner.js.map +1 -1
- package/dist/core/delegation/worker-tree-budget-coordinator.d.ts +47 -0
- package/dist/core/delegation/worker-tree-budget-coordinator.d.ts.map +1 -0
- package/dist/core/delegation/worker-tree-budget-coordinator.js +210 -0
- package/dist/core/delegation/worker-tree-budget-coordinator.js.map +1 -0
- package/dist/core/extensions/builtin.d.ts +2 -2
- package/dist/core/extensions/builtin.d.ts.map +1 -1
- package/dist/core/extensions/builtin.js +2 -2
- package/dist/core/extensions/builtin.js.map +1 -1
- package/dist/core/extensions/bundled-virtual-modules.d.ts +2 -0
- package/dist/core/extensions/bundled-virtual-modules.d.ts.map +1 -0
- package/dist/core/extensions/bundled-virtual-modules.js +129 -0
- package/dist/core/extensions/bundled-virtual-modules.js.map +1 -0
- package/dist/core/extensions/factory-runtime.d.ts +22 -0
- package/dist/core/extensions/factory-runtime.d.ts.map +1 -0
- package/dist/core/extensions/factory-runtime.js +334 -0
- package/dist/core/extensions/factory-runtime.js.map +1 -0
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/lifecycle.d.ts +13 -0
- package/dist/core/extensions/lifecycle.d.ts.map +1 -0
- package/dist/core/extensions/lifecycle.js +52 -0
- package/dist/core/extensions/lifecycle.js.map +1 -0
- package/dist/core/extensions/loader.d.ts +3 -24
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +21 -531
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/virtual-modules.d.ts +51 -0
- package/dist/core/extensions/virtual-modules.d.ts.map +1 -0
- package/dist/core/extensions/virtual-modules.js +59 -0
- package/dist/core/extensions/virtual-modules.js.map +1 -0
- package/dist/core/foreground-recovery-controller.d.ts +2 -1
- package/dist/core/foreground-recovery-controller.d.ts.map +1 -1
- package/dist/core/foreground-recovery-controller.js +3 -3
- package/dist/core/foreground-recovery-controller.js.map +1 -1
- package/dist/core/goal-loop-controller.js +1 -1
- package/dist/core/goal-loop-controller.js.map +1 -1
- package/dist/core/goals/compact-goal-context.d.ts +1 -1
- package/dist/core/goals/compact-goal-context.d.ts.map +1 -1
- package/dist/core/goals/compact-goal-context.js +1 -1
- package/dist/core/goals/compact-goal-context.js.map +1 -1
- package/dist/core/goals/goal-auto-continue-controller.js +1 -1
- package/dist/core/goals/goal-auto-continue-controller.js.map +1 -1
- package/dist/core/goals/goal-session-controller.d.ts +1 -1
- package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-session-controller.js +1 -1
- package/dist/core/goals/goal-session-controller.js.map +1 -1
- package/dist/core/http-dispatcher.d.ts +1 -1
- package/dist/core/http-dispatcher.d.ts.map +1 -1
- package/dist/core/http-dispatcher.js +1 -1
- package/dist/core/http-dispatcher.js.map +1 -1
- package/dist/core/index.d.ts +3 -2
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +2 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/memory/providers/file-store.d.ts.map +1 -1
- package/dist/core/memory/providers/file-store.js +1 -1
- package/dist/core/memory/providers/file-store.js.map +1 -1
- package/dist/core/memory/providers/user-memory-archive.js +1 -1
- package/dist/core/memory/providers/user-memory-archive.js.map +1 -1
- package/dist/core/model-registry.d.ts +2 -1
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +4 -1
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-router-controller.js +1 -1
- package/dist/core/model-router-controller.js.map +1 -1
- package/dist/core/model-selection-controller.js +1 -1
- package/dist/core/model-selection-controller.js.map +1 -1
- package/dist/core/model-tool-protocol.d.ts +1 -1
- package/dist/core/model-tool-protocol.d.ts.map +1 -1
- package/dist/core/model-tool-protocol.js +1 -1
- package/dist/core/model-tool-protocol.js.map +1 -1
- package/dist/core/models/llamacpp-runtime.d.ts +7 -0
- package/dist/core/models/llamacpp-runtime.d.ts.map +1 -1
- package/dist/core/models/llamacpp-runtime.js +8 -3
- package/dist/core/models/llamacpp-runtime.js.map +1 -1
- package/dist/core/models/local-runtime.js +1 -1
- package/dist/core/models/local-runtime.js.map +1 -1
- package/dist/core/models/runtime-process.d.ts.map +1 -1
- package/dist/core/models/runtime-process.js +5 -18
- package/dist/core/models/runtime-process.js.map +1 -1
- package/dist/core/orchestration/bounded-string-array.d.ts +11 -0
- package/dist/core/orchestration/bounded-string-array.d.ts.map +1 -0
- package/dist/core/orchestration/bounded-string-array.js +17 -0
- package/dist/core/orchestration/bounded-string-array.js.map +1 -0
- package/dist/core/orchestration/capability-gateway.d.ts +16 -0
- package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
- package/dist/core/orchestration/capability-gateway.js +38 -0
- package/dist/core/orchestration/capability-gateway.js.map +1 -1
- package/dist/core/orchestration/contracts.d.ts +11 -3
- package/dist/core/orchestration/contracts.d.ts.map +1 -1
- package/dist/core/orchestration/contracts.js +0 -1
- package/dist/core/orchestration/contracts.js.map +1 -1
- package/dist/core/orchestration/delegation-ledger.d.ts +1 -0
- package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -1
- package/dist/core/orchestration/delegation-ledger.js +3 -0
- package/dist/core/orchestration/delegation-ledger.js.map +1 -1
- package/dist/core/orchestration/event-store.d.ts +12 -10
- package/dist/core/orchestration/event-store.d.ts.map +1 -1
- package/dist/core/orchestration/event-store.js +94 -104
- package/dist/core/orchestration/event-store.js.map +1 -1
- package/dist/core/orchestration/lane-tool-manifests.d.ts +2 -2
- package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -1
- package/dist/core/orchestration/lane-tool-manifests.js +4 -1
- package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
- package/dist/core/orchestration/model-binding.d.ts +1 -1
- package/dist/core/orchestration/model-binding.d.ts.map +1 -1
- package/dist/core/orchestration/model-binding.js +1 -1
- package/dist/core/orchestration/model-binding.js.map +1 -1
- package/dist/core/orchestration/policy-compiler.d.ts.map +1 -1
- package/dist/core/orchestration/policy-compiler.js +8 -9
- package/dist/core/orchestration/policy-compiler.js.map +1 -1
- package/dist/core/orchestration/profile-registry.d.ts.map +1 -1
- package/dist/core/orchestration/profile-registry.js +4 -10
- package/dist/core/orchestration/profile-registry.js.map +1 -1
- package/dist/core/orchestration/task-profile-writer.js +1 -1
- package/dist/core/orchestration/task-profile-writer.js.map +1 -1
- package/dist/core/orchestration/task-runtime.d.ts +1 -0
- package/dist/core/orchestration/task-runtime.d.ts.map +1 -1
- package/dist/core/orchestration/task-runtime.js +58 -3
- package/dist/core/orchestration/task-runtime.js.map +1 -1
- package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -1
- package/dist/core/orchestration/worker-execution-contract.js +10 -17
- package/dist/core/orchestration/worker-execution-contract.js.map +1 -1
- package/dist/core/process-matrix/runtime.d.ts +15 -1
- package/dist/core/process-matrix/runtime.d.ts.map +1 -1
- package/dist/core/process-matrix/runtime.js +55 -34
- package/dist/core/process-matrix/runtime.js.map +1 -1
- package/dist/core/reflection-controller.d.ts +4 -3
- package/dist/core/reflection-controller.d.ts.map +1 -1
- package/dist/core/reflection-controller.js +2 -2
- package/dist/core/reflection-controller.js.map +1 -1
- package/dist/core/research/model-fitness-controller.js +1 -1
- package/dist/core/research/model-fitness-controller.js.map +1 -1
- package/dist/core/research/research-lane-controller.d.ts +2 -2
- package/dist/core/research/research-lane-controller.d.ts.map +1 -1
- package/dist/core/research/research-lane-controller.js +1 -1
- package/dist/core/research/research-lane-controller.js.map +1 -1
- package/dist/core/resource-loader.d.ts +10 -19
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +8 -70
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/risk-classifier.js +3 -3
- package/dist/core/risk-classifier.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +4 -1
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +47 -18
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/scout-controller.d.ts +1 -1
- package/dist/core/scout-controller.d.ts.map +1 -1
- package/dist/core/scout-controller.js +1 -1
- package/dist/core/scout-controller.js.map +1 -1
- package/dist/core/sdk.d.ts +2 -2
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -3
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/secrets/bitwarden-credential-storage.d.ts +51 -0
- package/dist/core/secrets/bitwarden-credential-storage.d.ts.map +1 -0
- package/dist/core/secrets/bitwarden-credential-storage.js +345 -0
- package/dist/core/secrets/bitwarden-credential-storage.js.map +1 -0
- package/dist/core/secrets/credential-exposure-guard.d.ts +8 -4
- package/dist/core/secrets/credential-exposure-guard.d.ts.map +1 -1
- package/dist/core/secrets/credential-exposure-guard.js +31 -29
- package/dist/core/secrets/credential-exposure-guard.js.map +1 -1
- package/dist/core/secrets/credential-manager.d.ts +109 -0
- package/dist/core/secrets/credential-manager.d.ts.map +1 -0
- package/dist/core/secrets/credential-manager.js +384 -0
- package/dist/core/secrets/credential-manager.js.map +1 -0
- package/dist/core/secrets/credential-project.d.ts +4 -0
- package/dist/core/secrets/credential-project.d.ts.map +1 -0
- package/dist/core/secrets/credential-project.js +145 -0
- package/dist/core/secrets/credential-project.js.map +1 -0
- package/dist/core/secrets/secret-dotenv.d.ts +1 -1
- package/dist/core/secrets/secret-dotenv.js +1 -1
- package/dist/core/secrets/secret-dotenv.js.map +1 -1
- package/dist/core/security/context-threat-scanner.d.ts +14 -0
- package/dist/core/security/context-threat-scanner.d.ts.map +1 -0
- package/dist/core/security/context-threat-scanner.js +71 -0
- package/dist/core/security/context-threat-scanner.js.map +1 -0
- package/dist/core/session-supervision-runtime.d.ts +4 -1
- package/dist/core/session-supervision-runtime.d.ts.map +1 -1
- package/dist/core/session-supervision-runtime.js +49 -11
- package/dist/core/session-supervision-runtime.js.map +1 -1
- package/dist/core/settings-manager.d.ts +4 -2
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +10 -6
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +1 -0
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/system-prompt.js +1 -1
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tool-capability-policy.js +2 -2
- package/dist/core/tool-capability-policy.js.map +1 -1
- package/dist/core/tool-recovery-logger.js +1 -1
- package/dist/core/tool-recovery-logger.js.map +1 -1
- package/dist/core/tools/artifact-retrieve.js +1 -1
- package/dist/core/tools/artifact-retrieve.js.map +1 -1
- package/dist/core/tools/bash.d.ts +2 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +16 -4
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/delegate.d.ts +29 -1
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +179 -28
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/extensionify-runtime.d.ts +44 -0
- package/dist/core/tools/extensionify-runtime.d.ts.map +1 -0
- package/dist/core/tools/extensionify-runtime.js +115 -0
- package/dist/core/tools/extensionify-runtime.js.map +1 -0
- package/dist/core/tools/extensionify.d.ts +9 -30
- package/dist/core/tools/extensionify.d.ts.map +1 -1
- package/dist/core/tools/extensionify.js +10 -140
- package/dist/core/tools/extensionify.js.map +1 -1
- package/dist/core/tools/find.d.ts +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +1 -1
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/git-filter.d.ts +1 -0
- package/dist/core/tools/git-filter.d.ts.map +1 -1
- package/dist/core/tools/git-filter.js +1 -1
- package/dist/core/tools/git-filter.js.map +1 -1
- package/dist/core/tools/index.d.ts +2 -4
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +7 -43
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/ls.d.ts +1 -1
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +1 -1
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +1 -1
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +1 -1
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/profile-writer.js +3 -3
- package/dist/core/tools/profile-writer.js.map +1 -1
- package/dist/core/tools/python.d.ts +2 -0
- package/dist/core/tools/python.d.ts.map +1 -1
- package/dist/core/tools/python.js +17 -12
- package/dist/core/tools/python.js.map +1 -1
- package/dist/core/tools/render-utils.js +1 -1
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/tools/run-process.d.ts +2 -0
- package/dist/core/tools/run-process.d.ts.map +1 -1
- package/dist/core/tools/run-process.js +7 -3
- package/dist/core/tools/run-process.js.map +1 -1
- package/dist/core/tools/search-command-guard.d.ts +8 -0
- package/dist/core/tools/search-command-guard.d.ts.map +1 -1
- package/dist/core/tools/search-command-guard.js +54 -0
- package/dist/core/tools/search-command-guard.js.map +1 -1
- package/dist/core/tools/secret-store.d.ts +8 -18
- package/dist/core/tools/secret-store.d.ts.map +1 -1
- package/dist/core/tools/secret-store.js +83 -348
- package/dist/core/tools/secret-store.js.map +1 -1
- package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
- package/dist/core/tools/shell-contract-router.js +9 -4
- package/dist/core/tools/shell-contract-router.js.map +1 -1
- package/dist/core/tools/shell-session.d.ts.map +1 -1
- package/dist/core/tools/shell-session.js +6 -4
- package/dist/core/tools/shell-session.js.map +1 -1
- package/dist/core/tools/tool-definition-factory.d.ts +32 -0
- package/dist/core/tools/tool-definition-factory.d.ts.map +1 -0
- package/dist/core/tools/tool-definition-factory.js +55 -0
- package/dist/core/tools/tool-definition-factory.js.map +1 -0
- package/dist/core/util/atomic-file.d.ts.map +1 -1
- package/dist/core/util/atomic-file.js +79 -32
- package/dist/core/util/atomic-file.js.map +1 -1
- package/dist/index.d.ts +5 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -2
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts +2 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +24 -18
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/auto-learn-controller.js +1 -1
- package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +35 -14
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +1 -1
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-event-controller.js +1 -1
- package/dist/modes/interactive/interactive-event-controller.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +27 -4
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/secret-menu-controller.d.ts +21 -0
- package/dist/modes/interactive/secret-menu-controller.d.ts.map +1 -0
- package/dist/modes/interactive/secret-menu-controller.js +276 -0
- package/dist/modes/interactive/secret-menu-controller.js.map +1 -0
- package/dist/utils/child-process.js +1 -1
- package/dist/utils/child-process.js.map +1 -1
- package/dist/utils/tools-manager.d.ts +2 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +43 -48
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/zip-extractor.d.ts +8 -0
- package/dist/utils/zip-extractor.d.ts.map +1 -0
- package/dist/utils/zip-extractor.js +275 -0
- package/dist/utils/zip-extractor.js.map +1 -0
- package/docs/harness-architecture.md +34 -22
- package/docs/index.md +1 -1
- package/docs/resources.md +1 -1
- package/docs/settings.md +39 -103
- package/docs/usage.md +7 -5
- package/docs/worker-profiles.md +9 -7
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +7 -5
- package/dist/core/secrets/secret-vault-format.d.ts +0 -112
- package/dist/core/secrets/secret-vault-format.d.ts.map +0 -1
- package/dist/core/secrets/secret-vault-format.js +0 -396
- package/dist/core/secrets/secret-vault-format.js.map +0 -1
- package/dist/core/secrets/secret-vault.d.ts +0 -72
- package/dist/core/secrets/secret-vault.d.ts.map +0 -1
- package/dist/core/secrets/secret-vault.js +0 -663
- package/dist/core/secrets/secret-vault.js.map +0 -1
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Api, Model } from "@caupulican/pi-ai";
|
|
2
|
+
import type { ModelRegistry } from "../model-registry.ts";
|
|
3
|
+
import type { WorkerDelegationAuthorityRequest } from "./worker-delegation-request.ts";
|
|
4
|
+
import type { ResolvedWorkerProfile } from "./worker-profile-resolver.ts";
|
|
5
|
+
export interface WorkerAuthorityResolutionInput {
|
|
6
|
+
authority?: WorkerDelegationAuthorityRequest;
|
|
7
|
+
base?: ResolvedWorkerProfile;
|
|
8
|
+
foregroundModel?: Model<Api>;
|
|
9
|
+
modelRegistry: ModelRegistry;
|
|
10
|
+
isModelExhausted(model: Model<Api>): boolean;
|
|
11
|
+
}
|
|
12
|
+
export type WorkerAuthorityResolution = {
|
|
13
|
+
ok: true;
|
|
14
|
+
shipment: ResolvedWorkerProfile;
|
|
15
|
+
requestedReadPaths?: readonly string[];
|
|
16
|
+
requestedWritePaths?: readonly string[];
|
|
17
|
+
} | {
|
|
18
|
+
ok: false;
|
|
19
|
+
reason: string;
|
|
20
|
+
};
|
|
21
|
+
/** Materialize free-form model choices as one immutable profile-shaped execution snapshot. */
|
|
22
|
+
export declare function resolveWorkerAuthority(input: WorkerAuthorityResolutionInput): WorkerAuthorityResolution;
|
|
23
|
+
//# sourceMappingURL=worker-authority-resolver.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker-authority-resolver.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-authority-resolver.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAGpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAU1D,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AACvF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AA0B1E,MAAM,WAAW,8BAA8B;IAC9C,SAAS,CAAC,EAAE,gCAAgC,CAAC;IAC7C,IAAI,CAAC,EAAE,qBAAqB,CAAC;IAC7B,eAAe,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IAC7B,aAAa,EAAE,aAAa,CAAC;IAC7B,gBAAgB,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC;CAC7C;AAED,MAAM,MAAM,yBAAyB,GAClC;IACA,EAAE,EAAE,IAAI,CAAC;IACT,QAAQ,EAAE,qBAAqB,CAAC;IAChC,kBAAkB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACvC,mBAAmB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACvC,GACD;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AA6BjC,8FAA8F;AAC9F,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,8BAA8B,GAAG,yBAAyB,CA6EvG"}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { resolveModelThinkingLevel } from "@caupulican/pi-ai/models";
|
|
3
|
+
import { mapToolNamesForPlatform, STABLE_SHELL_TOOL_NAME } from "../default-tool-surface.js";
|
|
4
|
+
import { ORCHESTRATION_SCHEMA_VERSION, } from "../orchestration/contracts.js";
|
|
5
|
+
import { CLASSIFIED_LANE_TOOL_NAMES } from "../orchestration/lane-tool-manifests.js";
|
|
6
|
+
import { resolvePinnedOrchestrationModel } from "../orchestration/model-binding.js";
|
|
7
|
+
import { getToolCapabilityPolicy } from "../tool-capability-policy.js";
|
|
8
|
+
const DEFAULT_TOOL_NAMES = [
|
|
9
|
+
"read",
|
|
10
|
+
"grep",
|
|
11
|
+
"find",
|
|
12
|
+
"ls",
|
|
13
|
+
"write",
|
|
14
|
+
"edit",
|
|
15
|
+
"memory",
|
|
16
|
+
STABLE_SHELL_TOOL_NAME,
|
|
17
|
+
"delegate",
|
|
18
|
+
];
|
|
19
|
+
const AVAILABLE_TOOL_NAMES = new Set([...CLASSIFIED_LANE_TOOL_NAMES, "delegate"]);
|
|
20
|
+
const DEFAULT_CAPABILITIES = [
|
|
21
|
+
"filesystem.read",
|
|
22
|
+
"filesystem.write",
|
|
23
|
+
"worktree.read",
|
|
24
|
+
"worktree.mutate",
|
|
25
|
+
"process.exec",
|
|
26
|
+
"network.http",
|
|
27
|
+
"service.mcp",
|
|
28
|
+
"memory.query",
|
|
29
|
+
"workflow.delegate",
|
|
30
|
+
];
|
|
31
|
+
function selectModelBinding(authority, base, foregroundModel, modelRegistry) {
|
|
32
|
+
const provider = authority?.model?.provider ?? base?.modelBinding.provider ?? foregroundModel?.provider;
|
|
33
|
+
const modelId = authority?.model?.modelId ?? base?.modelBinding.modelId ?? foregroundModel?.id;
|
|
34
|
+
if (!provider || !modelId)
|
|
35
|
+
return undefined;
|
|
36
|
+
const sameAsBase = provider === base?.modelBinding.provider && modelId === base.modelBinding.modelId;
|
|
37
|
+
const selectedModel = modelRegistry.find(provider, modelId);
|
|
38
|
+
const thinkingLevel = authority?.thinkingLevel ??
|
|
39
|
+
(sameAsBase
|
|
40
|
+
? base.modelBinding.thinkingLevel
|
|
41
|
+
: foregroundModel && provider === foregroundModel.provider && modelId === foregroundModel.id
|
|
42
|
+
? resolveModelThinkingLevel(foregroundModel, undefined)
|
|
43
|
+
: selectedModel
|
|
44
|
+
? resolveModelThinkingLevel(selectedModel, undefined)
|
|
45
|
+
: "off");
|
|
46
|
+
return { provider, modelId, thinkingLevel };
|
|
47
|
+
}
|
|
48
|
+
function adaptiveProfileId(value) {
|
|
49
|
+
return `adaptive-${createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 32)}`;
|
|
50
|
+
}
|
|
51
|
+
/** Materialize free-form model choices as one immutable profile-shaped execution snapshot. */
|
|
52
|
+
export function resolveWorkerAuthority(input) {
|
|
53
|
+
if (!input.authority && input.base)
|
|
54
|
+
return { ok: true, shipment: input.base };
|
|
55
|
+
const binding = selectModelBinding(input.authority, input.base, input.foregroundModel, input.modelRegistry);
|
|
56
|
+
if (!binding)
|
|
57
|
+
return { ok: false, reason: "orchestration_model_required" };
|
|
58
|
+
const resolvedModel = resolvePinnedOrchestrationModel(binding, input.modelRegistry, input.isModelExhausted);
|
|
59
|
+
if (!resolvedModel)
|
|
60
|
+
return { ok: false, reason: "orchestration_model_unavailable" };
|
|
61
|
+
const requestedToolNames = mapToolNamesForPlatform(input.authority?.toolNames ?? input.base?.profile.toolNames ?? DEFAULT_TOOL_NAMES);
|
|
62
|
+
const uniqueToolNames = [...new Set(requestedToolNames)];
|
|
63
|
+
const unavailableTools = uniqueToolNames.filter((toolName) => !AVAILABLE_TOOL_NAMES.has(toolName));
|
|
64
|
+
if (unavailableTools.length > 0) {
|
|
65
|
+
return { ok: false, reason: `orchestration_tool_unavailable:${unavailableTools.join(",")}` };
|
|
66
|
+
}
|
|
67
|
+
const capabilities = new Set(input.authority?.capabilities ?? input.base?.profile.capabilityCeiling ?? DEFAULT_CAPABILITIES);
|
|
68
|
+
const toolNames = [];
|
|
69
|
+
for (const toolName of uniqueToolNames) {
|
|
70
|
+
const policy = getToolCapabilityPolicy(toolName);
|
|
71
|
+
if (!policy)
|
|
72
|
+
return { ok: false, reason: `orchestration_tool_unclassified:${toolName}` };
|
|
73
|
+
if (policy.capabilityCandidates.some((capability) => capabilities.has(capability))) {
|
|
74
|
+
toolNames.push(toolName);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (input.authority?.toolNames !== undefined) {
|
|
78
|
+
return { ok: false, reason: `orchestration_tool_capability_missing:${toolName}` };
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const budget = structuredClone(input.authority?.budget ?? input.base?.profile.budget ?? {});
|
|
82
|
+
const role = input.authority?.role ?? input.base?.profile.role ?? "orchestrator";
|
|
83
|
+
const now = new Date().toISOString();
|
|
84
|
+
const descriptor = {
|
|
85
|
+
role,
|
|
86
|
+
binding: resolvedModel.binding,
|
|
87
|
+
capabilities: [...capabilities],
|
|
88
|
+
toolNames,
|
|
89
|
+
budget,
|
|
90
|
+
resourceProfileNames: input.base?.profile.resourceProfileNames ?? [],
|
|
91
|
+
};
|
|
92
|
+
const maxWallClockMs = budget.maxWallClockMs ?? 0;
|
|
93
|
+
const wallClockLeaseTtlMs = maxWallClockMs > Number.MAX_SAFE_INTEGER - 30_000 ? Number.MAX_SAFE_INTEGER : maxWallClockMs + 30_000;
|
|
94
|
+
const profile = {
|
|
95
|
+
schemaVersion: ORCHESTRATION_SCHEMA_VERSION,
|
|
96
|
+
profileId: adaptiveProfileId(descriptor),
|
|
97
|
+
description: "Admission-time adaptive agent authority",
|
|
98
|
+
role,
|
|
99
|
+
modelPolicy: { mode: "fixed", candidates: [resolvedModel.binding] },
|
|
100
|
+
capabilityCeiling: [...capabilities],
|
|
101
|
+
toolNames,
|
|
102
|
+
resourceProfileNames: [...(input.base?.profile.resourceProfileNames ?? [])],
|
|
103
|
+
dispatchProfileIds: [],
|
|
104
|
+
...(input.base?.profile.executionPolicy ? { executionPolicy: input.base.profile.executionPolicy } : {}),
|
|
105
|
+
budget,
|
|
106
|
+
maxConcurrent: Number.MAX_SAFE_INTEGER,
|
|
107
|
+
leaseTtlMs: Math.max(input.base?.profile.leaseTtlMs ?? 0, wallClockLeaseTtlMs, 90_000),
|
|
108
|
+
requireIndependentVerification: input.base?.profile.requireIndependentVerification ?? false,
|
|
109
|
+
...(input.base?.profile.verificationProfileId
|
|
110
|
+
? { verificationProfileId: input.base.profile.verificationProfileId }
|
|
111
|
+
: {}),
|
|
112
|
+
createdAt: now,
|
|
113
|
+
updatedAt: now,
|
|
114
|
+
};
|
|
115
|
+
return {
|
|
116
|
+
ok: true,
|
|
117
|
+
shipment: {
|
|
118
|
+
model: resolvedModel.model,
|
|
119
|
+
modelBinding: resolvedModel.binding,
|
|
120
|
+
profile,
|
|
121
|
+
resourcePointers: structuredClone(input.base?.resourcePointers ?? []),
|
|
122
|
+
...(input.base?.soul ? { soul: input.base.soul } : {}),
|
|
123
|
+
},
|
|
124
|
+
...(input.authority?.readPaths ? { requestedReadPaths: [...input.authority.readPaths] } : {}),
|
|
125
|
+
...(input.authority?.writePaths ? { requestedWritePaths: [...input.authority.writePaths] } : {}),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
//# sourceMappingURL=worker-authority-resolver.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker-authority-resolver.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-authority-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAA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G,CAAC,KAAK,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC,CAAC,EAAE,kBAAkB,EAAE,CAAC,GAAG,KAAK,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7F,GAAG,CAAC,KAAK,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC,EAAE,mBAAmB,EAAE,CAAC,GAAG,KAAK,CAAC,SAAS,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAChG,CAAC;AACH,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { Api, Model } from \"@caupulican/pi-ai\";\nimport { resolveModelThinkingLevel } from \"@caupulican/pi-ai/models\";\nimport { mapToolNamesForPlatform, STABLE_SHELL_TOOL_NAME } from \"../default-tool-surface.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport {\n\ttype HarnessCapability,\n\tORCHESTRATION_SCHEMA_VERSION,\n\ttype OrchestrationModelBinding,\n\ttype OrchestrationProfile,\n} from \"../orchestration/contracts.ts\";\nimport { CLASSIFIED_LANE_TOOL_NAMES } from \"../orchestration/lane-tool-manifests.ts\";\nimport { resolvePinnedOrchestrationModel } from \"../orchestration/model-binding.ts\";\nimport { getToolCapabilityPolicy } from \"../tool-capability-policy.ts\";\nimport type { WorkerDelegationAuthorityRequest } from \"./worker-delegation-request.ts\";\nimport type { ResolvedWorkerProfile } from \"./worker-profile-resolver.ts\";\n\nconst DEFAULT_TOOL_NAMES = [\n\t\"read\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n\t\"write\",\n\t\"edit\",\n\t\"memory\",\n\tSTABLE_SHELL_TOOL_NAME,\n\t\"delegate\",\n] as const;\nconst AVAILABLE_TOOL_NAMES: ReadonlySet<string> = new Set([...CLASSIFIED_LANE_TOOL_NAMES, \"delegate\"]);\nconst DEFAULT_CAPABILITIES: readonly HarnessCapability[] = [\n\t\"filesystem.read\",\n\t\"filesystem.write\",\n\t\"worktree.read\",\n\t\"worktree.mutate\",\n\t\"process.exec\",\n\t\"network.http\",\n\t\"service.mcp\",\n\t\"memory.query\",\n\t\"workflow.delegate\",\n];\n\nexport interface WorkerAuthorityResolutionInput {\n\tauthority?: WorkerDelegationAuthorityRequest;\n\tbase?: ResolvedWorkerProfile;\n\tforegroundModel?: Model<Api>;\n\tmodelRegistry: ModelRegistry;\n\tisModelExhausted(model: Model<Api>): boolean;\n}\n\nexport type WorkerAuthorityResolution =\n\t| {\n\t\t\tok: true;\n\t\t\tshipment: ResolvedWorkerProfile;\n\t\t\trequestedReadPaths?: readonly string[];\n\t\t\trequestedWritePaths?: readonly string[];\n\t }\n\t| { ok: false; reason: string };\n\nfunction selectModelBinding(\n\tauthority: WorkerDelegationAuthorityRequest | undefined,\n\tbase: ResolvedWorkerProfile | undefined,\n\tforegroundModel: Model<Api> | undefined,\n\tmodelRegistry: ModelRegistry,\n): OrchestrationModelBinding | undefined {\n\tconst provider = authority?.model?.provider ?? base?.modelBinding.provider ?? foregroundModel?.provider;\n\tconst modelId = authority?.model?.modelId ?? base?.modelBinding.modelId ?? foregroundModel?.id;\n\tif (!provider || !modelId) return undefined;\n\tconst sameAsBase = provider === base?.modelBinding.provider && modelId === base.modelBinding.modelId;\n\tconst selectedModel = modelRegistry.find(provider, modelId);\n\tconst thinkingLevel =\n\t\tauthority?.thinkingLevel ??\n\t\t(sameAsBase\n\t\t\t? base.modelBinding.thinkingLevel\n\t\t\t: foregroundModel && provider === foregroundModel.provider && modelId === foregroundModel.id\n\t\t\t\t? resolveModelThinkingLevel(foregroundModel, undefined)\n\t\t\t\t: selectedModel\n\t\t\t\t\t? resolveModelThinkingLevel(selectedModel, undefined)\n\t\t\t\t\t: \"off\");\n\treturn { provider, modelId, thinkingLevel };\n}\n\nfunction adaptiveProfileId(value: object): string {\n\treturn `adaptive-${createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\").slice(0, 32)}`;\n}\n\n/** Materialize free-form model choices as one immutable profile-shaped execution snapshot. */\nexport function resolveWorkerAuthority(input: WorkerAuthorityResolutionInput): WorkerAuthorityResolution {\n\tif (!input.authority && input.base) return { ok: true, shipment: input.base };\n\tconst binding = selectModelBinding(input.authority, input.base, input.foregroundModel, input.modelRegistry);\n\tif (!binding) return { ok: false, reason: \"orchestration_model_required\" };\n\tconst resolvedModel = resolvePinnedOrchestrationModel(binding, input.modelRegistry, input.isModelExhausted);\n\tif (!resolvedModel) return { ok: false, reason: \"orchestration_model_unavailable\" };\n\n\tconst requestedToolNames = mapToolNamesForPlatform(\n\t\tinput.authority?.toolNames ?? input.base?.profile.toolNames ?? DEFAULT_TOOL_NAMES,\n\t);\n\tconst uniqueToolNames = [...new Set(requestedToolNames)];\n\tconst unavailableTools = uniqueToolNames.filter((toolName) => !AVAILABLE_TOOL_NAMES.has(toolName));\n\tif (unavailableTools.length > 0) {\n\t\treturn { ok: false, reason: `orchestration_tool_unavailable:${unavailableTools.join(\",\")}` };\n\t}\n\tconst capabilities = new Set<HarnessCapability>(\n\t\tinput.authority?.capabilities ?? input.base?.profile.capabilityCeiling ?? DEFAULT_CAPABILITIES,\n\t);\n\tconst toolNames: string[] = [];\n\tfor (const toolName of uniqueToolNames) {\n\t\tconst policy = getToolCapabilityPolicy(toolName);\n\t\tif (!policy) return { ok: false, reason: `orchestration_tool_unclassified:${toolName}` };\n\t\tif (policy.capabilityCandidates.some((capability) => capabilities.has(capability))) {\n\t\t\ttoolNames.push(toolName);\n\t\t\tcontinue;\n\t\t}\n\t\tif (input.authority?.toolNames !== undefined) {\n\t\t\treturn { ok: false, reason: `orchestration_tool_capability_missing:${toolName}` };\n\t\t}\n\t}\n\tconst budget = structuredClone(input.authority?.budget ?? input.base?.profile.budget ?? {});\n\tconst role = input.authority?.role ?? input.base?.profile.role ?? \"orchestrator\";\n\tconst now = new Date().toISOString();\n\tconst descriptor = {\n\t\trole,\n\t\tbinding: resolvedModel.binding,\n\t\tcapabilities: [...capabilities],\n\t\ttoolNames,\n\t\tbudget,\n\t\tresourceProfileNames: input.base?.profile.resourceProfileNames ?? [],\n\t};\n\tconst maxWallClockMs = budget.maxWallClockMs ?? 0;\n\tconst wallClockLeaseTtlMs =\n\t\tmaxWallClockMs > Number.MAX_SAFE_INTEGER - 30_000 ? Number.MAX_SAFE_INTEGER : maxWallClockMs + 30_000;\n\tconst profile: OrchestrationProfile = {\n\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\tprofileId: adaptiveProfileId(descriptor),\n\t\tdescription: \"Admission-time adaptive agent authority\",\n\t\trole,\n\t\tmodelPolicy: { mode: \"fixed\", candidates: [resolvedModel.binding] },\n\t\tcapabilityCeiling: [...capabilities],\n\t\ttoolNames,\n\t\tresourceProfileNames: [...(input.base?.profile.resourceProfileNames ?? [])],\n\t\tdispatchProfileIds: [],\n\t\t...(input.base?.profile.executionPolicy ? { executionPolicy: input.base.profile.executionPolicy } : {}),\n\t\tbudget,\n\t\tmaxConcurrent: Number.MAX_SAFE_INTEGER,\n\t\tleaseTtlMs: Math.max(input.base?.profile.leaseTtlMs ?? 0, wallClockLeaseTtlMs, 90_000),\n\t\trequireIndependentVerification: input.base?.profile.requireIndependentVerification ?? false,\n\t\t...(input.base?.profile.verificationProfileId\n\t\t\t? { verificationProfileId: input.base.profile.verificationProfileId }\n\t\t\t: {}),\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t};\n\treturn {\n\t\tok: true,\n\t\tshipment: {\n\t\t\tmodel: resolvedModel.model,\n\t\t\tmodelBinding: resolvedModel.binding,\n\t\t\tprofile,\n\t\t\tresourcePointers: structuredClone(input.base?.resourcePointers ?? []),\n\t\t\t...(input.base?.soul ? { soul: input.base.soul } : {}),\n\t\t},\n\t\t...(input.authority?.readPaths ? { requestedReadPaths: [...input.authority.readPaths] } : {}),\n\t\t...(input.authority?.writePaths ? { requestedWritePaths: [...input.authority.writePaths] } : {}),\n\t};\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { type CompactionPreparation, type CompactionResult, estimateContextTokens
|
|
1
|
+
import { type CompactionPreparation, type CompactionResult, estimateContextTokens } from "@caupulican/pi-agent-core/compaction/compaction";
|
|
2
|
+
import { type SessionContext, SessionManager } from "@caupulican/pi-agent-core/session";
|
|
2
3
|
import type { Message, Usage } from "@caupulican/pi-ai";
|
|
3
4
|
import type { AgentResumeContext, AttemptUsageSnapshot, ResourcePointer } from "../orchestration/contracts.ts";
|
|
4
5
|
export interface CreateWorkerConversationOptions {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-conversation-store.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-conversation-store.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"worker-conversation-store.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-conversation-store.ts"],"names":[],"mappings":"AAIA,OAAO,EACN,KAAK,qBAAqB,EAC1B,KAAK,gBAAgB,EAErB,qBAAqB,EAErB,MAAM,iDAAiD,CAAC;AAEzD,OAAO,EAAwB,KAAK,cAAc,EAAE,cAAc,EAAE,MAAM,mCAAmC,CAAC;AAC9G,OAAO,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAIxD,OAAO,KAAK,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAY/G,MAAM,WAAW,+BAA+B;IAC/C,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe,EAAE,MAAM,CAAC;IACxB,8FAA8F;IAC9F,cAAc,EAAE,MAAM,CAAC;IACvB,GAAG,EAAE,MAAM,CAAC;IACZ,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,oBAAoB,EAAE,SAAS,MAAM,EAAE,CAAC;IACxC,eAAe,EAAE,SAAS,eAAe,EAAE,CAAC;CAC5C;AAED,MAAM,WAAW,6BAA6B;IAC7C,QAAQ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;IAED;;;;OAIG;IACH,oCAAoC,CAAC,iBAAiB,EAAE,SAAS,MAAM,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC,CAmBtF;IAED;;;;OAIG;IACG,sBAAsB,CAC3B,MAAM,EAAE,iCAAiC,EACzC,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,kCAAkC,CAAC,CAwD7C;IAED,gFAAgF;IAChF,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAEtC;IAED;;;;;OAKG;IACH,gBAAgB,CAAC,UAAU,EAAE,SAAS,OAAO,EAAE,GAAG,MAAM,CAiBvD;IAED,uFAAuF;IACvF,gBAAgB,IAAI,kBAAkB,CAErC;CACD;AA0BD,4FAA4F;AAC5F,qBAAa,uBAAuB;IACnC,MAAM,CAAC,OAAO,EAAE,+BAA+B,GAAG,kBAAkB,CAInE;IAED,OAAO,CAAC,YAAY;IAsCpB,sGAAsG;IACtG,MAAM,CAAC,OAAO,EAAE,+BAA+B,GAAG,kBAAkB,CAWnE;IAED,IAAI,CAAC,OAAO,EAAE,6BAA6B,GAAG,kBAAkB,CAoC/D;CACD"}
|
|
@@ -2,8 +2,9 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { existsSync } from "node:fs";
|
|
3
3
|
import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
|
|
4
4
|
import { isDeepStrictEqual } from "node:util";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
5
|
+
import { createDeterministicCompaction, estimateContextTokens, prepareCompaction, } from "@caupulican/pi-agent-core/compaction/compaction";
|
|
6
|
+
import { convertToLlm } from "@caupulican/pi-agent-core/messages";
|
|
7
|
+
import { assertValidSessionId, SessionManager } from "@caupulican/pi-agent-core/session";
|
|
7
8
|
import { orchestrationSessionsDir, workerConversationSessionsDir } from "../agent-paths.js";
|
|
8
9
|
import { sameAgentResumeIdentity } from "../orchestration/agent-resume.js";
|
|
9
10
|
import { validateAttemptUsageSnapshot } from "../orchestration/attempt-usage.js";
|
|
@@ -233,7 +234,7 @@ export class WorkerConversation {
|
|
|
233
234
|
if (entry.type !== "message" || entry.message.role !== "user" || typeof entry.message.content !== "string") {
|
|
234
235
|
continue;
|
|
235
236
|
}
|
|
236
|
-
const messageId = /^\[Worker control (worker-message-[^\]]+)
|
|
237
|
+
const messageId = /^\[Worker control (worker-message-[^\]\s]+)(?: [^\]]+)?\]\n/.exec(entry.message.content)?.[1];
|
|
237
238
|
if (!messageId || !unresolved.delete(messageId))
|
|
238
239
|
continue;
|
|
239
240
|
delivered.add(messageId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-conversation-store.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-conversation-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC7E,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EACN,oBAAoB,EAGpB,6BAA6B,EAC7B,qBAAqB,EACrB,iBAAiB,EAEjB,cAAc,GACd,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAAE,wBAAwB,EAAE,6BAA6B,EAAE,MAAM,mBAAmB,CAAC;AAC5F,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC;AAC3E,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AAEjF,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC/E,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EACN,qCAAqC,EACrC,8BAA8B,EAC9B,0CAA0C,GAC1C,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,CAAC,CAAC;QACxC,IAAI,OAAO,CAAC,UAAU,IAAI,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,KAAK,UAAU,EAAE,CAAC;YACtE,MAAM,IAAI,KAAK,CACd,kGAAkG,CAClG,CAAC;QACH,CAAC;QAED,MAAM,cAAc,GAAG,cAAc,CAAC,IAAI,CAAC,WAAW,EAAE,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;QACtF,IAAI,cAAc,CAAC,YAAY,EAAE,KAAK,OAAO,CAAC,SAAS,EAAE,CAAC;YACzD,MAAM,IAAI,KAAK,CAAC,qFAAqF,CAAC,CAAC;QACxG,CAAC;QACD,IAAI,cAAc,CAAC,MAAM,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;YACtD,MAAM,IAAI,KAAK,CAAC,4FAA4F,CAAC,CAAC;QAC/G,CAAC;QACD,+BAA+B,CAC9B,8BAA8B,CAAC,WAAW,CAAC,EAC3C,OAAO,EACP,OAAO,CAAC,sBAAsB,CAC9B,CAAC;QAEF,OAAO,IAAI,kBAAkB,CAAC,cAAc,EAAE;YAC7C,GAAG,OAAO;YACV,UAAU;YACV,WAAW;YACX,GAAG,EAAE,cAAc,CAAC,MAAM,EAAE;SAC5B,CAAC,CAAC;IACJ,CAAC;CACD;AAED,SAAS,qBAAqB,CAAC,UAAkB,EAAE,SAAiB;IACnE,OAAO,OAAO,CAAC,UAAU,EAAE,GAAG,SAAS,QAAQ,CAAC,CAAC;AAClD,CAAC;AAED,SAAS,8BAA8B,CAAC,WAAmB;IAC1D,OAAO,GAAG,WAAW,cAAc,CAAC;AACrC,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, relative, resolve } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { convertToLlm } from \"@caupulican/pi-agent-core\";\nimport {\n\tassertValidSessionId,\n\ttype CompactionPreparation,\n\ttype CompactionResult,\n\tcreateDeterministicCompaction,\n\testimateContextTokens,\n\tprepareCompaction,\n\ttype SessionContext,\n\tSessionManager,\n} from \"@caupulican/pi-agent-core/node\";\nimport type { Message, Usage } from \"@caupulican/pi-ai\";\nimport { orchestrationSessionsDir, workerConversationSessionsDir } from \"../agent-paths.ts\";\nimport { sameAgentResumeIdentity } from \"../orchestration/agent-resume.ts\";\nimport { validateAttemptUsageSnapshot } from \"../orchestration/attempt-usage.ts\";\nimport type { AgentResumeContext, AttemptUsageSnapshot, ResourcePointer } from \"../orchestration/contracts.ts\";\nimport { withFileLockSync, writeFileAtomicSync } from \"../util/atomic-file.ts\";\nimport { readBoundedTextFileSync } from \"../util/bounded-file.ts\";\nimport {\n\tcollectBoundedWorkerClaimChangedFiles,\n\tMAX_WORKER_CLAIM_CHANGED_FILES,\n\tMAX_WORKER_CLAIM_TERMINAL_ATTEMPT_ID_CHARS,\n} from \"./worker-claim.ts\";\n\nconst MAX_WORKER_CONVERSATION_METADATA_BYTES = 256 * 1024;\nconst WORKER_CHANGED_FILE_CUSTOM_TYPE = \"worker-changed-file\";\n\nexport interface CreateWorkerConversationOptions {\n\tagentDir: string;\n\tparentSessionId: string;\n\t/** Durable logical identity for the worker/lane. It never becomes a path segment directly. */\n\tlogicalAgentId: string;\n\tcwd: string;\n\torchestrationProfileId?: string;\n\tmodelRef?: string;\n\tresourceProfileNames: readonly string[];\n\tcontextPointers: readonly ResourcePointer[];\n}\n\nexport interface OpenWorkerConversationOptions {\n\tagentDir: string;\n\tresumeContext: AgentResumeContext;\n\texpectedLogicalAgentId?: string;\n}\n\n/**\n * Explicit, token-based retention for a durable worker transcript.\n *\n * This deliberately has no default: the worker model/context policy belongs to orchestration, not\n * the transcript store. Call only at a safe worker turn boundary, after all messages from that turn\n * have been durably committed. The execution controller provides `generateVerifiedCompaction`\n * through the shared model-aware pipeline; this store owns only preparation, append-only apply,\n * and its deterministic verified fallback.\n */\nexport interface WorkerConversationRetentionPolicy {\n\t/** Maximum provider-visible context tokens after a checkpoint is applied. */\n\tmaxContextTokens: number;\n\t/** Shared compaction's retained recent-context target. Must be lower than the maximum. */\n\tkeepRecentTokens: number;\n\t/**\n\t * Generate a verified shared compaction result. Failures, malformed results, and omitted\n\t * generators fall back to `createDeterministicCompaction`; raw transcript entries are never\n\t * replaced or removed.\n\t */\n\tgenerateVerifiedCompaction?: (preparation: CompactionPreparation) => Promise<CompactionResult>;\n\t/**\n\t * Cumulative provider usage spent by the current verified generation if it failed before it\n\t * could return a CompactionResult. This usage is attached to the deterministic checkpoint so\n\t * recovery never loses rejected-summary spend.\n\t */\n\tgetFailedCompactionUsage?: () => Usage | undefined;\n}\n\nexport interface WorkerConversationRetentionOutcome {\n\tstatus: \"within_limit\" | \"compacted_verified\" | \"compacted_deterministic\" | \"cannot_compact\";\n\tcontext: SessionContext;\n\tcontextUsage: ReturnType<typeof estimateContextTokens>;\n}\n\ninterface WorkerConversationMetadata {\n\tlogicalAgentId: string;\n\tresumeContext: AgentResumeContext;\n}\n\nfunction stableWorkerSessionId(parentSessionId: string, logicalAgentId: string): string {\n\tconst normalizedAgentId = logicalAgentId.trim();\n\tif (!normalizedAgentId) throw new TypeError(\"A logical worker agent id is required.\");\n\tconst digest = createHash(\"sha256\")\n\t\t.update(\"pi-worker-conversation-v1\")\n\t\t.update(\"\\0\")\n\t\t.update(parentSessionId)\n\t\t.update(\"\\0\")\n\t\t.update(normalizedAgentId)\n\t\t.digest(\"hex\")\n\t\t.slice(0, 32);\n\treturn `worker-${digest}`;\n}\n\nfunction cloneResumeContext(context: AgentResumeContext): AgentResumeContext {\n\treturn structuredClone(context);\n}\n\nfunction expectedResumeContext(options: CreateWorkerConversationOptions): AgentResumeContext {\n\tconst sessionDir = workerConversationSessionsDir(options.agentDir, options.parentSessionId);\n\tconst sessionId = stableWorkerSessionId(options.parentSessionId, options.logicalAgentId);\n\tassertValidSessionId(sessionId);\n\tif (!options.cwd.trim()) throw new TypeError(\"A worker conversation working directory is required.\");\n\treturn {\n\t\tprovider: \"pi\",\n\t\tsessionId,\n\t\tsessionDir,\n\t\tsessionFile: joinWorkerSessionFile(sessionDir, sessionId),\n\t\tcwd: resolve(options.cwd),\n\t\t...(options.orchestrationProfileId ? { orchestrationProfileId: options.orchestrationProfileId } : {}),\n\t\t...(options.modelRef ? { modelRef: options.modelRef } : {}),\n\t\tresourceProfileNames: [...options.resourceProfileNames],\n\t\tcontextPointers: structuredClone(options.contextPointers),\n\t};\n}\n\nfunction metadataFromFile(metadataFile: string): WorkerConversationMetadata {\n\tlet metadata: unknown;\n\ttry {\n\t\tmetadata = JSON.parse(\n\t\t\treadBoundedTextFileSync(\n\t\t\t\tmetadataFile,\n\t\t\t\tMAX_WORKER_CONVERSATION_METADATA_BYTES,\n\t\t\t\t\"Worker conversation metadata durable size bound\",\n\t\t\t),\n\t\t);\n\t} catch {\n\t\tthrow new Error(\n\t\t\texistsSync(metadataFile)\n\t\t\t\t? \"Worker conversation metadata is invalid or exceeds its durable size bound.\"\n\t\t\t\t: \"Worker conversation metadata is missing or invalid.\",\n\t\t);\n\t}\n\tif (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata)) {\n\t\tthrow new Error(\"Worker conversation metadata is invalid.\");\n\t}\n\tconst logicalAgentId = (metadata as { logicalAgentId?: unknown }).logicalAgentId;\n\tconst resumeContext = (metadata as { resumeContext?: unknown }).resumeContext;\n\tif (typeof logicalAgentId !== \"string\" || !logicalAgentId.trim() || !resumeContext) {\n\t\tthrow new Error(\"Worker conversation metadata is invalid.\");\n\t}\n\treturn { logicalAgentId, resumeContext: cloneResumeContext(resumeContext as AgentResumeContext) };\n}\n\nfunction assertExactConversationMetadata(\n\tmetadataFile: string,\n\texpected: AgentResumeContext,\n\tlogicalAgentId?: string,\n): void {\n\tconst metadata = metadataFromFile(metadataFile);\n\tif (logicalAgentId && metadata.logicalAgentId !== logicalAgentId) {\n\t\tthrow new Error(\"Worker conversation logical agent identity conflicts with the persisted transcript.\");\n\t}\n\tif (!sameAgentResumeIdentity(metadata.resumeContext, expected)) {\n\t\tthrow new Error(\"Worker conversation resume context conflicts with the persisted transcript.\");\n\t}\n}\n\nfunction assertWorkerConversationFile(agentDir: string, sessionFile: string, sessionId: string): string {\n\tconst workersRoot = resolve(orchestrationSessionsDir(agentDir));\n\tconst resolvedFile = resolve(sessionFile);\n\tconst fileRelativeToWorkersRoot = relative(workersRoot, resolvedFile);\n\tif (\n\t\tfileRelativeToWorkersRoot === \"\" ||\n\t\tfileRelativeToWorkersRoot.startsWith(\"..\") ||\n\t\tisAbsolute(fileRelativeToWorkersRoot)\n\t) {\n\t\tthrow new Error(\"Worker conversation session file must remain under the canonical worker sessions directory.\");\n\t}\n\tconst segments = fileRelativeToWorkersRoot.split(/[\\\\/]/);\n\tif (segments.length !== 3 || segments[1] !== \"worker-conversations\") {\n\t\tthrow new Error(\"Worker conversation session file must remain under the canonical worker sessions directory.\");\n\t}\n\tif (basename(resolvedFile) !== `${sessionId}.jsonl`) {\n\t\tthrow new Error(\"Worker conversation session file does not match its durable session id.\");\n\t}\n\treturn resolvedFile;\n}\n\n/**\n * Durable SessionManager-backed transcript for exactly one logical worker lane.\n *\n * Single-writer invariant: orchestration must ensure that no two live processes append to the same\n * conversation. This store deliberately does not merge branches or lock competing writers; a\n * complete child transcript is committed only after it proves the current provider-visible context\n * is its exact prefix.\n */\nexport class WorkerConversation {\n\tprivate readonly sessionManager: SessionManager;\n\tprivate readonly resumeContext: AgentResumeContext;\n\n\tconstructor(sessionManager: SessionManager, resumeContext: AgentResumeContext) {\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.resumeContext = cloneResumeContext(resumeContext);\n\t}\n\n\t/** Resolve current provider-visible messages lazily through SessionManager. */\n\tgetProviderContext(): SessionContext {\n\t\treturn this.sessionManager.buildSessionContext();\n\t}\n\n\t/** Convert the current compacted projection at its transcript owner, never at each consumer. */\n\tgetProviderMessages(): Message[] {\n\t\treturn convertToLlm(this.getProviderContext().messages);\n\t}\n\n\t/** True when provider context is a compacted projection rather than the raw transcript prefix. */\n\thasProviderCompaction(): boolean {\n\t\treturn this.sessionManager.getBranch().some((entry) => entry.type === \"compaction\");\n\t}\n\n\t/**\n\t * The immutable, append-only raw worker messages, including messages compacted out of provider\n\t * context. This is recovery/audit data; it is never loaded into a provider request implicitly.\n\t */\n\tgetRawTranscript(): Message[] {\n\t\tconst messages: Message[] = [];\n\t\tfor (const entry of this.sessionManager.getEntries()) {\n\t\t\tif (\n\t\t\t\tentry.type === \"message\" &&\n\t\t\t\t(entry.message.role === \"user\" || entry.message.role === \"assistant\" || entry.message.role === \"toolResult\")\n\t\t\t) {\n\t\t\t\tmessages.push(structuredClone(entry.message));\n\t\t\t}\n\t\t}\n\t\treturn messages;\n\t}\n\n\t/** Durable host-observed mutation progress. Custom entries never enter provider context. */\n\trecordChangedFile(attemptId: string, filePath: string): void {\n\t\tif (!attemptId.trim() || attemptId.length > MAX_WORKER_CLAIM_TERMINAL_ATTEMPT_ID_CHARS) {\n\t\t\tthrow new TypeError(\"Worker changed-file progress attempt id is invalid or exceeds its durable bound.\");\n\t\t}\n\t\tconst candidate = collectBoundedWorkerClaimChangedFiles([filePath]);\n\t\tif (candidate.overflowed || candidate.values.length !== 1) {\n\t\t\tthrow new TypeError(\"Worker changed-file progress path is invalid or exceeds its durable bound.\");\n\t\t}\n\t\tconst path = candidate.values[0]!;\n\t\tconst existing = this.getChangedFiles(attemptId);\n\t\tif (existing.includes(path)) return;\n\t\tif (existing.length >= MAX_WORKER_CLAIM_CHANGED_FILES) {\n\t\t\tthrow new Error(\"Worker changed-file progress exceeds its durable entry bound.\");\n\t\t}\n\t\tthis.sessionManager.appendCustomEntry(WORKER_CHANGED_FILE_CUSTOM_TYPE, { attemptId, path });\n\t}\n\n\t/** Rehydrate the bounded mutation set across owner-session disposal and worker resume. */\n\tgetChangedFiles(attemptId: string): string[] {\n\t\tconst paths: string[] = [];\n\t\tfor (const entry of this.sessionManager.getEntries()) {\n\t\t\tif (entry.type !== \"custom\" || entry.customType !== WORKER_CHANGED_FILE_CUSTOM_TYPE) continue;\n\t\t\tconst data = entry.data;\n\t\t\tif (!data || typeof data !== \"object\" || Array.isArray(data)) continue;\n\t\t\tconst attemptDescriptor = Object.getOwnPropertyDescriptor(data, \"attemptId\");\n\t\t\tconst pathDescriptor = Object.getOwnPropertyDescriptor(data, \"path\");\n\t\t\tif (\n\t\t\t\tattemptDescriptor &&\n\t\t\t\t\"value\" in attemptDescriptor &&\n\t\t\t\tattemptDescriptor.value === attemptId &&\n\t\t\t\tpathDescriptor &&\n\t\t\t\t\"value\" in pathDescriptor &&\n\t\t\t\ttypeof pathDescriptor.value === \"string\"\n\t\t\t) {\n\t\t\t\tpaths.push(pathDescriptor.value);\n\t\t\t}\n\t\t}\n\t\treturn collectBoundedWorkerClaimChangedFiles(paths).values;\n\t}\n\n\t/**\n\t * Recover cumulative accounting from raw entry metadata without cloning or resolving message\n\t * payloads that compaction deliberately moved out of the provider-visible working set.\n\t */\n\tgetRawTranscriptUsage(): AttemptUsageSnapshot {\n\t\tconst usage: AttemptUsageSnapshot = {\n\t\t\ttoolCalls: 0,\n\t\t\tinputTokens: 0,\n\t\t\toutputTokens: 0,\n\t\t\tcacheReadTokens: 0,\n\t\t\tcacheWriteTokens: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcostUsd: 0,\n\t\t\tactiveWallClockMs: 0,\n\t\t};\n\t\tfor (const entry of this.sessionManager.getEntries()) {\n\t\t\tif (entry.type === \"compaction\" && entry.usage) {\n\t\t\t\tusage.inputTokens += entry.usage.input;\n\t\t\t\tusage.outputTokens += entry.usage.output;\n\t\t\t\tusage.cacheReadTokens += entry.usage.cacheRead;\n\t\t\t\tusage.cacheWriteTokens += entry.usage.cacheWrite;\n\t\t\t\tusage.totalTokens += entry.usage.totalTokens;\n\t\t\t\tusage.costUsd += entry.usage.cost.total;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entry.type !== \"message\") continue;\n\t\t\tif (entry.message.role === \"toolResult\") {\n\t\t\t\tusage.toolCalls += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entry.message.role !== \"assistant\") continue;\n\t\t\tusage.inputTokens += entry.message.usage.input;\n\t\t\tusage.outputTokens += entry.message.usage.output;\n\t\t\tusage.cacheReadTokens += entry.message.usage.cacheRead;\n\t\t\tusage.cacheWriteTokens += entry.message.usage.cacheWrite;\n\t\t\tusage.totalTokens += entry.message.usage.totalTokens;\n\t\t\tusage.costUsd += entry.message.usage.cost.total;\n\t\t}\n\t\treturn validateAttemptUsageSnapshot(usage, \"legacy worker transcript usage\");\n\t}\n\n\t/**\n\t * Locate a bounded set of durable mailbox delivery commits without materializing or cloning the\n\t * complete raw transcript. Recovery uses this only to close the narrow crash window after a\n\t * control message was appended but before its mailbox acknowledgement was persisted.\n\t */\n\tfindDeliveredWorkerControlMessageIds(pendingMessageIds: readonly string[]): Set<string> {\n\t\tconst unresolved = new Set(pendingMessageIds);\n\t\tconst delivered = new Set<string>();\n\t\tif (unresolved.size === 0) return delivered;\n\t\tconst entries = this.sessionManager.getEntries();\n\t\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\t\tconst entry = entries[index];\n\t\t\tif (!entry) continue;\n\t\t\tif (entry.type !== \"message\" || entry.message.role !== \"user\" || typeof entry.message.content !== \"string\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst messageId = /^\\[Worker control (worker-message-[^\\]]+)\\]\\n/.exec(entry.message.content)?.[1];\n\t\t\tif (!messageId || !unresolved.delete(messageId)) continue;\n\t\t\tdelivered.add(messageId);\n\t\t\tif (unresolved.size === 0) break;\n\t\t}\n\t\treturn delivered;\n\t}\n\n\t/**\n\t * Append one shared-compaction checkpoint when the current provider-visible context exceeds the\n\t * explicit worker policy. The source transcript remains append-only; only the projection sent to\n\t * the next provider call changes. The method is idempotent while no new messages are appended.\n\t */\n\tasync compactProviderContext(\n\t\tpolicy: WorkerConversationRetentionPolicy,\n\t\tsignal?: AbortSignal,\n\t): Promise<WorkerConversationRetentionOutcome> {\n\t\tassertRetentionPolicy(policy);\n\t\tsignal?.throwIfAborted();\n\t\tconst before = this.getProviderContext();\n\t\tconst beforeUsage = estimateContextTokens(before.messages);\n\t\tif (beforeUsage.tokens <= policy.maxContextTokens) {\n\t\t\treturn { status: \"within_limit\", context: before, contextUsage: beforeUsage };\n\t\t}\n\n\t\tconst preparation = prepareCompaction(this.sessionManager.getBranch(), {\n\t\t\tenabled: true,\n\t\t\t// The store does not choose a model or invoke a provider. This is only the shared cut-point\n\t\t\t// input required by deterministic fallback; a controller-provided verified generator owns\n\t\t\t// the model-specific reserve and retry policy.\n\t\t\treserveTokens: Math.max(1, Math.floor(policy.maxContextTokens / 4)),\n\t\t\tkeepRecentTokens: policy.keepRecentTokens,\n\t\t\ttriggerPercent: 0,\n\t\t});\n\t\tif (!preparation) {\n\t\t\treturn { status: \"cannot_compact\", context: before, contextUsage: beforeUsage };\n\t\t}\n\n\t\tlet result: CompactionResult;\n\t\tlet status: WorkerConversationRetentionOutcome[\"status\"] = \"compacted_deterministic\";\n\t\tif (policy.generateVerifiedCompaction) {\n\t\t\ttry {\n\t\t\t\tconst verified = await policy.generateVerifiedCompaction(preparation);\n\t\t\t\tsignal?.throwIfAborted();\n\t\t\t\tassertApplicableCompactionResult(verified, preparation);\n\t\t\t\tresult = verified;\n\t\t\t\tstatus = \"compacted_verified\";\n\t\t\t} catch {\n\t\t\t\t// Cancellation/suspension transfers transcript ownership. The retiring owner must\n\t\t\t\t// not append a fallback after its execution fence has been released.\n\t\t\t\tsignal?.throwIfAborted();\n\t\t\t\tconst failedUsage = policy.getFailedCompactionUsage?.();\n\t\t\t\tresult = {\n\t\t\t\t\t...createDeterministicCompaction(preparation),\n\t\t\t\t\t...(failedUsage ? { usage: structuredClone(failedUsage) } : {}),\n\t\t\t\t};\n\t\t\t}\n\t\t} else {\n\t\t\tresult = createDeterministicCompaction(preparation);\n\t\t}\n\n\t\tsignal?.throwIfAborted();\n\t\tthis.sessionManager.appendCompaction(\n\t\t\tresult.summary,\n\t\t\tresult.firstKeptEntryId,\n\t\t\tresult.tokensBefore,\n\t\t\tresult.details,\n\t\t\tfalse,\n\t\t\tresult.usage,\n\t\t);\n\t\tconst context = this.getProviderContext();\n\t\treturn { status, context, contextUsage: estimateContextTokens(context.messages) };\n\t}\n\n\t/** Append one already-authorized worker message to the canonical transcript. */\n\tappendMessage(message: Message): string {\n\t\treturn this.sessionManager.appendMessage(structuredClone(message));\n\t}\n\n\t/**\n\t * Commit one complete child-owned transcript without replaying its persisted prefix.\n\t *\n\t * Any mismatch is a divergence: appending would duplicate or reorder provider context, so the\n\t * caller must resolve it rather than silently branching this logical worker conversation.\n\t */\n\tcommitTranscript(transcript: readonly Message[]): number {\n\t\t// Compare against the append-only source transcript, not the provider projection: once a\n\t\t// compaction checkpoint exists, buildSessionContext() begins with its synthetic summary and is\n\t\t// intentionally no longer an exact prefix of the child loop's raw message sequence.\n\t\tconst persisted = this.getRawTranscript();\n\t\tif (transcript.length < persisted.length) {\n\t\t\tthrow new Error(\"Worker conversation transcript is shorter than its persisted raw context.\");\n\t\t}\n\t\tfor (let index = 0; index < persisted.length; index++) {\n\t\t\tif (!isDeepStrictEqual(persisted[index], transcript[index])) {\n\t\t\t\tthrow new Error(`Worker conversation transcript diverges from persisted context at message ${index}.`);\n\t\t\t}\n\t\t}\n\t\tfor (const message of transcript.slice(persisted.length)) {\n\t\t\tthis.appendMessage(message);\n\t\t}\n\t\treturn transcript.length - persisted.length;\n\t}\n\n\t/** Return an isolated copy suitable for durable orchestration/process-resume state. */\n\tgetResumeContext(): AgentResumeContext {\n\t\treturn cloneResumeContext(this.resumeContext);\n\t}\n}\n\nfunction assertRetentionPolicy(policy: WorkerConversationRetentionPolicy): void {\n\tif (!Number.isSafeInteger(policy.maxContextTokens) || policy.maxContextTokens < 2) {\n\t\tthrow new TypeError(\"Worker conversation maximum context tokens must be an integer of at least 2.\");\n\t}\n\tif (\n\t\t!Number.isSafeInteger(policy.keepRecentTokens) ||\n\t\tpolicy.keepRecentTokens < 1 ||\n\t\tpolicy.keepRecentTokens >= policy.maxContextTokens\n\t) {\n\t\tthrow new TypeError(\"Worker conversation retained context tokens must be an integer below the maximum.\");\n\t}\n}\n\nfunction assertApplicableCompactionResult(result: CompactionResult, preparation: CompactionPreparation): void {\n\tif (\n\t\t!result ||\n\t\ttypeof result.summary !== \"string\" ||\n\t\tresult.firstKeptEntryId !== preparation.firstKeptEntryId ||\n\t\tresult.tokensBefore !== preparation.tokensBefore\n\t) {\n\t\tthrow new Error(\"Worker verified compaction result does not match the prepared durable transcript.\");\n\t}\n}\n\n/** Creates and reopens canonical SessionManager transcripts for logical Pi worker lanes. */\nexport class WorkerConversationStore {\n\tcreate(options: CreateWorkerConversationOptions): WorkerConversation {\n\t\tconst resumeContext = expectedResumeContext(options);\n\t\tconst sessionFile = resumeContext.sessionFile!;\n\t\treturn withFileLockSync(sessionFile, () => this.createLocked(options, resumeContext));\n\t}\n\n\tprivate createLocked(\n\t\toptions: CreateWorkerConversationOptions,\n\t\tresumeContext: AgentResumeContext,\n\t): WorkerConversation {\n\t\tconst sessionDir = resumeContext.sessionDir!;\n\t\tconst sessionFile = resumeContext.sessionFile!;\n\t\tconst metadataFile = workerConversationMetadataFile(sessionFile);\n\t\tif (existsSync(sessionFile)) {\n\t\t\tthrow new Error(`Worker conversation already exists for logical agent '${options.logicalAgentId}'.`);\n\t\t}\n\n\t\t// SessionManager intentionally defers a brand-new header until its first assistant message.\n\t\t// A worker must be resumable after its first user/tool message, so atomically seed the exact\n\t\t// SessionManager header and immediately reopen it through SessionManager for all later writes.\n\t\tconst seed = SessionManager.create(resumeContext.cwd, options.agentDir, sessionDir, {\n\t\t\tid: resumeContext.sessionId,\n\t\t});\n\t\tconst header = seed.getHeader();\n\t\tif (!header) throw new Error(\"Unable to create a worker conversation session header.\");\n\t\tif (existsSync(metadataFile)) {\n\t\t\tassertExactConversationMetadata(metadataFile, resumeContext, options.logicalAgentId);\n\t\t} else {\n\t\t\t// Metadata lands first: a crash leaves no visible conversation until the ordinary session\n\t\t\t// header is atomically published, while a later ensure can validate the exact intended identity.\n\t\t\twriteFileAtomicSync(\n\t\t\t\tmetadataFile,\n\t\t\t\t`${JSON.stringify({ logicalAgentId: options.logicalAgentId, resumeContext })}\\n`,\n\t\t\t);\n\t\t}\n\t\twriteFileAtomicSync(sessionFile, `${JSON.stringify(header)}\\n`);\n\n\t\treturn this.open({\n\t\t\tagentDir: options.agentDir,\n\t\t\tresumeContext,\n\t\t\texpectedLogicalAgentId: options.logicalAgentId,\n\t\t});\n\t}\n\n\t/** Open the one canonical transcript or atomically create it with the exact same durable identity. */\n\tensure(options: CreateWorkerConversationOptions): WorkerConversation {\n\t\tconst resumeContext = expectedResumeContext(options);\n\t\tconst sessionFile = resumeContext.sessionFile!;\n\t\treturn withFileLockSync(sessionFile, () => {\n\t\t\tif (!existsSync(sessionFile)) return this.createLocked(options, resumeContext);\n\t\t\treturn this.open({\n\t\t\t\tagentDir: options.agentDir,\n\t\t\t\tresumeContext,\n\t\t\t\texpectedLogicalAgentId: options.logicalAgentId,\n\t\t\t});\n\t\t});\n\t}\n\n\topen(options: OpenWorkerConversationOptions): WorkerConversation {\n\t\tconst context = cloneResumeContext(options.resumeContext);\n\t\tif (context.provider !== \"pi\") throw new TypeError(\"Only Pi worker conversations can be reopened.\");\n\t\tif (!context.sessionFile)\n\t\t\tthrow new TypeError(\"A persisted worker session file is required to reopen a conversation.\");\n\t\tif (!context.cwd.trim()) throw new TypeError(\"A worker conversation working directory is required.\");\n\t\tassertValidSessionId(context.sessionId);\n\n\t\tconst sessionFile = assertWorkerConversationFile(options.agentDir, context.sessionFile, context.sessionId);\n\t\tif (!existsSync(sessionFile)) throw new Error(`Worker conversation session file does not exist: ${sessionFile}`);\n\t\tconst sessionDir = dirname(sessionFile);\n\t\tif (context.sessionDir && resolve(context.sessionDir) !== sessionDir) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Worker conversation resume context has a session directory that disagrees with its session file.\",\n\t\t\t);\n\t\t}\n\n\t\tconst sessionManager = SessionManager.open(sessionFile, options.agentDir, sessionDir);\n\t\tif (sessionManager.getSessionId() !== context.sessionId) {\n\t\t\tthrow new Error(\"Worker conversation session file does not contain the requested durable session id.\");\n\t\t}\n\t\tif (sessionManager.getCwd() !== resolve(context.cwd)) {\n\t\t\tthrow new Error(\"Worker conversation resume context working directory disagrees with the persisted session.\");\n\t\t}\n\t\tassertExactConversationMetadata(\n\t\t\tworkerConversationMetadataFile(sessionFile),\n\t\t\tcontext,\n\t\t\toptions.expectedLogicalAgentId,\n\t\t);\n\n\t\treturn new WorkerConversation(sessionManager, {\n\t\t\t...context,\n\t\t\tsessionDir,\n\t\t\tsessionFile,\n\t\t\tcwd: sessionManager.getCwd(),\n\t\t});\n\t}\n}\n\nfunction joinWorkerSessionFile(sessionDir: string, sessionId: string): string {\n\treturn resolve(sessionDir, `${sessionId}.jsonl`);\n}\n\nfunction workerConversationMetadataFile(sessionFile: string): string {\n\treturn `${sessionFile}.worker.json`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"worker-conversation-store.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-conversation-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC7E,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAGN,6BAA6B,EAC7B,qBAAqB,EACrB,iBAAiB,GACjB,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAClE,OAAO,EAAE,oBAAoB,EAAuB,cAAc,EAAE,MAAM,mCAAmC,CAAC;AAE9G,OAAO,EA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AC,UAAU,EAAE,GAAG,SAAS,QAAQ,CAAC,CAAC;AAClD,CAAC;AAED,SAAS,8BAA8B,CAAC,WAAmB;IAC1D,OAAO,GAAG,WAAW,cAAc,CAAC;AACrC,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, relative, resolve } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport {\n\ttype CompactionPreparation,\n\ttype CompactionResult,\n\tcreateDeterministicCompaction,\n\testimateContextTokens,\n\tprepareCompaction,\n} from \"@caupulican/pi-agent-core/compaction/compaction\";\nimport { convertToLlm } from \"@caupulican/pi-agent-core/messages\";\nimport { assertValidSessionId, type SessionContext, SessionManager } from \"@caupulican/pi-agent-core/session\";\nimport type { Message, Usage } from \"@caupulican/pi-ai\";\nimport { orchestrationSessionsDir, workerConversationSessionsDir } from \"../agent-paths.ts\";\nimport { sameAgentResumeIdentity } from \"../orchestration/agent-resume.ts\";\nimport { validateAttemptUsageSnapshot } from \"../orchestration/attempt-usage.ts\";\nimport type { AgentResumeContext, AttemptUsageSnapshot, ResourcePointer } from \"../orchestration/contracts.ts\";\nimport { withFileLockSync, writeFileAtomicSync } from \"../util/atomic-file.ts\";\nimport { readBoundedTextFileSync } from \"../util/bounded-file.ts\";\nimport {\n\tcollectBoundedWorkerClaimChangedFiles,\n\tMAX_WORKER_CLAIM_CHANGED_FILES,\n\tMAX_WORKER_CLAIM_TERMINAL_ATTEMPT_ID_CHARS,\n} from \"./worker-claim.ts\";\n\nconst MAX_WORKER_CONVERSATION_METADATA_BYTES = 256 * 1024;\nconst WORKER_CHANGED_FILE_CUSTOM_TYPE = \"worker-changed-file\";\n\nexport interface CreateWorkerConversationOptions {\n\tagentDir: string;\n\tparentSessionId: string;\n\t/** Durable logical identity for the worker/lane. It never becomes a path segment directly. */\n\tlogicalAgentId: string;\n\tcwd: string;\n\torchestrationProfileId?: string;\n\tmodelRef?: string;\n\tresourceProfileNames: readonly string[];\n\tcontextPointers: readonly ResourcePointer[];\n}\n\nexport interface OpenWorkerConversationOptions {\n\tagentDir: string;\n\tresumeContext: AgentResumeContext;\n\texpectedLogicalAgentId?: string;\n}\n\n/**\n * Explicit, token-based retention for a durable worker transcript.\n *\n * This deliberately has no default: the worker model/context policy belongs to orchestration, not\n * the transcript store. Call only at a safe worker turn boundary, after all messages from that turn\n * have been durably committed. The execution controller provides `generateVerifiedCompaction`\n * through the shared model-aware pipeline; this store owns only preparation, append-only apply,\n * and its deterministic verified fallback.\n */\nexport interface WorkerConversationRetentionPolicy {\n\t/** Maximum provider-visible context tokens after a checkpoint is applied. */\n\tmaxContextTokens: number;\n\t/** Shared compaction's retained recent-context target. Must be lower than the maximum. */\n\tkeepRecentTokens: number;\n\t/**\n\t * Generate a verified shared compaction result. Failures, malformed results, and omitted\n\t * generators fall back to `createDeterministicCompaction`; raw transcript entries are never\n\t * replaced or removed.\n\t */\n\tgenerateVerifiedCompaction?: (preparation: CompactionPreparation) => Promise<CompactionResult>;\n\t/**\n\t * Cumulative provider usage spent by the current verified generation if it failed before it\n\t * could return a CompactionResult. This usage is attached to the deterministic checkpoint so\n\t * recovery never loses rejected-summary spend.\n\t */\n\tgetFailedCompactionUsage?: () => Usage | undefined;\n}\n\nexport interface WorkerConversationRetentionOutcome {\n\tstatus: \"within_limit\" | \"compacted_verified\" | \"compacted_deterministic\" | \"cannot_compact\";\n\tcontext: SessionContext;\n\tcontextUsage: ReturnType<typeof estimateContextTokens>;\n}\n\ninterface WorkerConversationMetadata {\n\tlogicalAgentId: string;\n\tresumeContext: AgentResumeContext;\n}\n\nfunction stableWorkerSessionId(parentSessionId: string, logicalAgentId: string): string {\n\tconst normalizedAgentId = logicalAgentId.trim();\n\tif (!normalizedAgentId) throw new TypeError(\"A logical worker agent id is required.\");\n\tconst digest = createHash(\"sha256\")\n\t\t.update(\"pi-worker-conversation-v1\")\n\t\t.update(\"\\0\")\n\t\t.update(parentSessionId)\n\t\t.update(\"\\0\")\n\t\t.update(normalizedAgentId)\n\t\t.digest(\"hex\")\n\t\t.slice(0, 32);\n\treturn `worker-${digest}`;\n}\n\nfunction cloneResumeContext(context: AgentResumeContext): AgentResumeContext {\n\treturn structuredClone(context);\n}\n\nfunction expectedResumeContext(options: CreateWorkerConversationOptions): AgentResumeContext {\n\tconst sessionDir = workerConversationSessionsDir(options.agentDir, options.parentSessionId);\n\tconst sessionId = stableWorkerSessionId(options.parentSessionId, options.logicalAgentId);\n\tassertValidSessionId(sessionId);\n\tif (!options.cwd.trim()) throw new TypeError(\"A worker conversation working directory is required.\");\n\treturn {\n\t\tprovider: \"pi\",\n\t\tsessionId,\n\t\tsessionDir,\n\t\tsessionFile: joinWorkerSessionFile(sessionDir, sessionId),\n\t\tcwd: resolve(options.cwd),\n\t\t...(options.orchestrationProfileId ? { orchestrationProfileId: options.orchestrationProfileId } : {}),\n\t\t...(options.modelRef ? { modelRef: options.modelRef } : {}),\n\t\tresourceProfileNames: [...options.resourceProfileNames],\n\t\tcontextPointers: structuredClone(options.contextPointers),\n\t};\n}\n\nfunction metadataFromFile(metadataFile: string): WorkerConversationMetadata {\n\tlet metadata: unknown;\n\ttry {\n\t\tmetadata = JSON.parse(\n\t\t\treadBoundedTextFileSync(\n\t\t\t\tmetadataFile,\n\t\t\t\tMAX_WORKER_CONVERSATION_METADATA_BYTES,\n\t\t\t\t\"Worker conversation metadata durable size bound\",\n\t\t\t),\n\t\t);\n\t} catch {\n\t\tthrow new Error(\n\t\t\texistsSync(metadataFile)\n\t\t\t\t? \"Worker conversation metadata is invalid or exceeds its durable size bound.\"\n\t\t\t\t: \"Worker conversation metadata is missing or invalid.\",\n\t\t);\n\t}\n\tif (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata)) {\n\t\tthrow new Error(\"Worker conversation metadata is invalid.\");\n\t}\n\tconst logicalAgentId = (metadata as { logicalAgentId?: unknown }).logicalAgentId;\n\tconst resumeContext = (metadata as { resumeContext?: unknown }).resumeContext;\n\tif (typeof logicalAgentId !== \"string\" || !logicalAgentId.trim() || !resumeContext) {\n\t\tthrow new Error(\"Worker conversation metadata is invalid.\");\n\t}\n\treturn { logicalAgentId, resumeContext: cloneResumeContext(resumeContext as AgentResumeContext) };\n}\n\nfunction assertExactConversationMetadata(\n\tmetadataFile: string,\n\texpected: AgentResumeContext,\n\tlogicalAgentId?: string,\n): void {\n\tconst metadata = metadataFromFile(metadataFile);\n\tif (logicalAgentId && metadata.logicalAgentId !== logicalAgentId) {\n\t\tthrow new Error(\"Worker conversation logical agent identity conflicts with the persisted transcript.\");\n\t}\n\tif (!sameAgentResumeIdentity(metadata.resumeContext, expected)) {\n\t\tthrow new Error(\"Worker conversation resume context conflicts with the persisted transcript.\");\n\t}\n}\n\nfunction assertWorkerConversationFile(agentDir: string, sessionFile: string, sessionId: string): string {\n\tconst workersRoot = resolve(orchestrationSessionsDir(agentDir));\n\tconst resolvedFile = resolve(sessionFile);\n\tconst fileRelativeToWorkersRoot = relative(workersRoot, resolvedFile);\n\tif (\n\t\tfileRelativeToWorkersRoot === \"\" ||\n\t\tfileRelativeToWorkersRoot.startsWith(\"..\") ||\n\t\tisAbsolute(fileRelativeToWorkersRoot)\n\t) {\n\t\tthrow new Error(\"Worker conversation session file must remain under the canonical worker sessions directory.\");\n\t}\n\tconst segments = fileRelativeToWorkersRoot.split(/[\\\\/]/);\n\tif (segments.length !== 3 || segments[1] !== \"worker-conversations\") {\n\t\tthrow new Error(\"Worker conversation session file must remain under the canonical worker sessions directory.\");\n\t}\n\tif (basename(resolvedFile) !== `${sessionId}.jsonl`) {\n\t\tthrow new Error(\"Worker conversation session file does not match its durable session id.\");\n\t}\n\treturn resolvedFile;\n}\n\n/**\n * Durable SessionManager-backed transcript for exactly one logical worker lane.\n *\n * Single-writer invariant: orchestration must ensure that no two live processes append to the same\n * conversation. This store deliberately does not merge branches or lock competing writers; a\n * complete child transcript is committed only after it proves the current provider-visible context\n * is its exact prefix.\n */\nexport class WorkerConversation {\n\tprivate readonly sessionManager: SessionManager;\n\tprivate readonly resumeContext: AgentResumeContext;\n\n\tconstructor(sessionManager: SessionManager, resumeContext: AgentResumeContext) {\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.resumeContext = cloneResumeContext(resumeContext);\n\t}\n\n\t/** Resolve current provider-visible messages lazily through SessionManager. */\n\tgetProviderContext(): SessionContext {\n\t\treturn this.sessionManager.buildSessionContext();\n\t}\n\n\t/** Convert the current compacted projection at its transcript owner, never at each consumer. */\n\tgetProviderMessages(): Message[] {\n\t\treturn convertToLlm(this.getProviderContext().messages);\n\t}\n\n\t/** True when provider context is a compacted projection rather than the raw transcript prefix. */\n\thasProviderCompaction(): boolean {\n\t\treturn this.sessionManager.getBranch().some((entry) => entry.type === \"compaction\");\n\t}\n\n\t/**\n\t * The immutable, append-only raw worker messages, including messages compacted out of provider\n\t * context. This is recovery/audit data; it is never loaded into a provider request implicitly.\n\t */\n\tgetRawTranscript(): Message[] {\n\t\tconst messages: Message[] = [];\n\t\tfor (const entry of this.sessionManager.getEntries()) {\n\t\t\tif (\n\t\t\t\tentry.type === \"message\" &&\n\t\t\t\t(entry.message.role === \"user\" || entry.message.role === \"assistant\" || entry.message.role === \"toolResult\")\n\t\t\t) {\n\t\t\t\tmessages.push(structuredClone(entry.message));\n\t\t\t}\n\t\t}\n\t\treturn messages;\n\t}\n\n\t/** Durable host-observed mutation progress. Custom entries never enter provider context. */\n\trecordChangedFile(attemptId: string, filePath: string): void {\n\t\tif (!attemptId.trim() || attemptId.length > MAX_WORKER_CLAIM_TERMINAL_ATTEMPT_ID_CHARS) {\n\t\t\tthrow new TypeError(\"Worker changed-file progress attempt id is invalid or exceeds its durable bound.\");\n\t\t}\n\t\tconst candidate = collectBoundedWorkerClaimChangedFiles([filePath]);\n\t\tif (candidate.overflowed || candidate.values.length !== 1) {\n\t\t\tthrow new TypeError(\"Worker changed-file progress path is invalid or exceeds its durable bound.\");\n\t\t}\n\t\tconst path = candidate.values[0]!;\n\t\tconst existing = this.getChangedFiles(attemptId);\n\t\tif (existing.includes(path)) return;\n\t\tif (existing.length >= MAX_WORKER_CLAIM_CHANGED_FILES) {\n\t\t\tthrow new Error(\"Worker changed-file progress exceeds its durable entry bound.\");\n\t\t}\n\t\tthis.sessionManager.appendCustomEntry(WORKER_CHANGED_FILE_CUSTOM_TYPE, { attemptId, path });\n\t}\n\n\t/** Rehydrate the bounded mutation set across owner-session disposal and worker resume. */\n\tgetChangedFiles(attemptId: string): string[] {\n\t\tconst paths: string[] = [];\n\t\tfor (const entry of this.sessionManager.getEntries()) {\n\t\t\tif (entry.type !== \"custom\" || entry.customType !== WORKER_CHANGED_FILE_CUSTOM_TYPE) continue;\n\t\t\tconst data = entry.data;\n\t\t\tif (!data || typeof data !== \"object\" || Array.isArray(data)) continue;\n\t\t\tconst attemptDescriptor = Object.getOwnPropertyDescriptor(data, \"attemptId\");\n\t\t\tconst pathDescriptor = Object.getOwnPropertyDescriptor(data, \"path\");\n\t\t\tif (\n\t\t\t\tattemptDescriptor &&\n\t\t\t\t\"value\" in attemptDescriptor &&\n\t\t\t\tattemptDescriptor.value === attemptId &&\n\t\t\t\tpathDescriptor &&\n\t\t\t\t\"value\" in pathDescriptor &&\n\t\t\t\ttypeof pathDescriptor.value === \"string\"\n\t\t\t) {\n\t\t\t\tpaths.push(pathDescriptor.value);\n\t\t\t}\n\t\t}\n\t\treturn collectBoundedWorkerClaimChangedFiles(paths).values;\n\t}\n\n\t/**\n\t * Recover cumulative accounting from raw entry metadata without cloning or resolving message\n\t * payloads that compaction deliberately moved out of the provider-visible working set.\n\t */\n\tgetRawTranscriptUsage(): AttemptUsageSnapshot {\n\t\tconst usage: AttemptUsageSnapshot = {\n\t\t\ttoolCalls: 0,\n\t\t\tinputTokens: 0,\n\t\t\toutputTokens: 0,\n\t\t\tcacheReadTokens: 0,\n\t\t\tcacheWriteTokens: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcostUsd: 0,\n\t\t\tactiveWallClockMs: 0,\n\t\t};\n\t\tfor (const entry of this.sessionManager.getEntries()) {\n\t\t\tif (entry.type === \"compaction\" && entry.usage) {\n\t\t\t\tusage.inputTokens += entry.usage.input;\n\t\t\t\tusage.outputTokens += entry.usage.output;\n\t\t\t\tusage.cacheReadTokens += entry.usage.cacheRead;\n\t\t\t\tusage.cacheWriteTokens += entry.usage.cacheWrite;\n\t\t\t\tusage.totalTokens += entry.usage.totalTokens;\n\t\t\t\tusage.costUsd += entry.usage.cost.total;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entry.type !== \"message\") continue;\n\t\t\tif (entry.message.role === \"toolResult\") {\n\t\t\t\tusage.toolCalls += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entry.message.role !== \"assistant\") continue;\n\t\t\tusage.inputTokens += entry.message.usage.input;\n\t\t\tusage.outputTokens += entry.message.usage.output;\n\t\t\tusage.cacheReadTokens += entry.message.usage.cacheRead;\n\t\t\tusage.cacheWriteTokens += entry.message.usage.cacheWrite;\n\t\t\tusage.totalTokens += entry.message.usage.totalTokens;\n\t\t\tusage.costUsd += entry.message.usage.cost.total;\n\t\t}\n\t\treturn validateAttemptUsageSnapshot(usage, \"legacy worker transcript usage\");\n\t}\n\n\t/**\n\t * Locate a bounded set of durable mailbox delivery commits without materializing or cloning the\n\t * complete raw transcript. Recovery uses this only to close the narrow crash window after a\n\t * control message was appended but before its mailbox acknowledgement was persisted.\n\t */\n\tfindDeliveredWorkerControlMessageIds(pendingMessageIds: readonly string[]): Set<string> {\n\t\tconst unresolved = new Set(pendingMessageIds);\n\t\tconst delivered = new Set<string>();\n\t\tif (unresolved.size === 0) return delivered;\n\t\tconst entries = this.sessionManager.getEntries();\n\t\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\t\tconst entry = entries[index];\n\t\t\tif (!entry) continue;\n\t\t\tif (entry.type !== \"message\" || entry.message.role !== \"user\" || typeof entry.message.content !== \"string\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst messageId = /^\\[Worker control (worker-message-[^\\]\\s]+)(?: [^\\]]+)?\\]\\n/.exec(\n\t\t\t\tentry.message.content,\n\t\t\t)?.[1];\n\t\t\tif (!messageId || !unresolved.delete(messageId)) continue;\n\t\t\tdelivered.add(messageId);\n\t\t\tif (unresolved.size === 0) break;\n\t\t}\n\t\treturn delivered;\n\t}\n\n\t/**\n\t * Append one shared-compaction checkpoint when the current provider-visible context exceeds the\n\t * explicit worker policy. The source transcript remains append-only; only the projection sent to\n\t * the next provider call changes. The method is idempotent while no new messages are appended.\n\t */\n\tasync compactProviderContext(\n\t\tpolicy: WorkerConversationRetentionPolicy,\n\t\tsignal?: AbortSignal,\n\t): Promise<WorkerConversationRetentionOutcome> {\n\t\tassertRetentionPolicy(policy);\n\t\tsignal?.throwIfAborted();\n\t\tconst before = this.getProviderContext();\n\t\tconst beforeUsage = estimateContextTokens(before.messages);\n\t\tif (beforeUsage.tokens <= policy.maxContextTokens) {\n\t\t\treturn { status: \"within_limit\", context: before, contextUsage: beforeUsage };\n\t\t}\n\n\t\tconst preparation = prepareCompaction(this.sessionManager.getBranch(), {\n\t\t\tenabled: true,\n\t\t\t// The store does not choose a model or invoke a provider. This is only the shared cut-point\n\t\t\t// input required by deterministic fallback; a controller-provided verified generator owns\n\t\t\t// the model-specific reserve and retry policy.\n\t\t\treserveTokens: Math.max(1, Math.floor(policy.maxContextTokens / 4)),\n\t\t\tkeepRecentTokens: policy.keepRecentTokens,\n\t\t\ttriggerPercent: 0,\n\t\t});\n\t\tif (!preparation) {\n\t\t\treturn { status: \"cannot_compact\", context: before, contextUsage: beforeUsage };\n\t\t}\n\n\t\tlet result: CompactionResult;\n\t\tlet status: WorkerConversationRetentionOutcome[\"status\"] = \"compacted_deterministic\";\n\t\tif (policy.generateVerifiedCompaction) {\n\t\t\ttry {\n\t\t\t\tconst verified = await policy.generateVerifiedCompaction(preparation);\n\t\t\t\tsignal?.throwIfAborted();\n\t\t\t\tassertApplicableCompactionResult(verified, preparation);\n\t\t\t\tresult = verified;\n\t\t\t\tstatus = \"compacted_verified\";\n\t\t\t} catch {\n\t\t\t\t// Cancellation/suspension transfers transcript ownership. The retiring owner must\n\t\t\t\t// not append a fallback after its execution fence has been released.\n\t\t\t\tsignal?.throwIfAborted();\n\t\t\t\tconst failedUsage = policy.getFailedCompactionUsage?.();\n\t\t\t\tresult = {\n\t\t\t\t\t...createDeterministicCompaction(preparation),\n\t\t\t\t\t...(failedUsage ? { usage: structuredClone(failedUsage) } : {}),\n\t\t\t\t};\n\t\t\t}\n\t\t} else {\n\t\t\tresult = createDeterministicCompaction(preparation);\n\t\t}\n\n\t\tsignal?.throwIfAborted();\n\t\tthis.sessionManager.appendCompaction(\n\t\t\tresult.summary,\n\t\t\tresult.firstKeptEntryId,\n\t\t\tresult.tokensBefore,\n\t\t\tresult.details,\n\t\t\tfalse,\n\t\t\tresult.usage,\n\t\t);\n\t\tconst context = this.getProviderContext();\n\t\treturn { status, context, contextUsage: estimateContextTokens(context.messages) };\n\t}\n\n\t/** Append one already-authorized worker message to the canonical transcript. */\n\tappendMessage(message: Message): string {\n\t\treturn this.sessionManager.appendMessage(structuredClone(message));\n\t}\n\n\t/**\n\t * Commit one complete child-owned transcript without replaying its persisted prefix.\n\t *\n\t * Any mismatch is a divergence: appending would duplicate or reorder provider context, so the\n\t * caller must resolve it rather than silently branching this logical worker conversation.\n\t */\n\tcommitTranscript(transcript: readonly Message[]): number {\n\t\t// Compare against the append-only source transcript, not the provider projection: once a\n\t\t// compaction checkpoint exists, buildSessionContext() begins with its synthetic summary and is\n\t\t// intentionally no longer an exact prefix of the child loop's raw message sequence.\n\t\tconst persisted = this.getRawTranscript();\n\t\tif (transcript.length < persisted.length) {\n\t\t\tthrow new Error(\"Worker conversation transcript is shorter than its persisted raw context.\");\n\t\t}\n\t\tfor (let index = 0; index < persisted.length; index++) {\n\t\t\tif (!isDeepStrictEqual(persisted[index], transcript[index])) {\n\t\t\t\tthrow new Error(`Worker conversation transcript diverges from persisted context at message ${index}.`);\n\t\t\t}\n\t\t}\n\t\tfor (const message of transcript.slice(persisted.length)) {\n\t\t\tthis.appendMessage(message);\n\t\t}\n\t\treturn transcript.length - persisted.length;\n\t}\n\n\t/** Return an isolated copy suitable for durable orchestration/process-resume state. */\n\tgetResumeContext(): AgentResumeContext {\n\t\treturn cloneResumeContext(this.resumeContext);\n\t}\n}\n\nfunction assertRetentionPolicy(policy: WorkerConversationRetentionPolicy): void {\n\tif (!Number.isSafeInteger(policy.maxContextTokens) || policy.maxContextTokens < 2) {\n\t\tthrow new TypeError(\"Worker conversation maximum context tokens must be an integer of at least 2.\");\n\t}\n\tif (\n\t\t!Number.isSafeInteger(policy.keepRecentTokens) ||\n\t\tpolicy.keepRecentTokens < 1 ||\n\t\tpolicy.keepRecentTokens >= policy.maxContextTokens\n\t) {\n\t\tthrow new TypeError(\"Worker conversation retained context tokens must be an integer below the maximum.\");\n\t}\n}\n\nfunction assertApplicableCompactionResult(result: CompactionResult, preparation: CompactionPreparation): void {\n\tif (\n\t\t!result ||\n\t\ttypeof result.summary !== \"string\" ||\n\t\tresult.firstKeptEntryId !== preparation.firstKeptEntryId ||\n\t\tresult.tokensBefore !== preparation.tokensBefore\n\t) {\n\t\tthrow new Error(\"Worker verified compaction result does not match the prepared durable transcript.\");\n\t}\n}\n\n/** Creates and reopens canonical SessionManager transcripts for logical Pi worker lanes. */\nexport class WorkerConversationStore {\n\tcreate(options: CreateWorkerConversationOptions): WorkerConversation {\n\t\tconst resumeContext = expectedResumeContext(options);\n\t\tconst sessionFile = resumeContext.sessionFile!;\n\t\treturn withFileLockSync(sessionFile, () => this.createLocked(options, resumeContext));\n\t}\n\n\tprivate createLocked(\n\t\toptions: CreateWorkerConversationOptions,\n\t\tresumeContext: AgentResumeContext,\n\t): WorkerConversation {\n\t\tconst sessionDir = resumeContext.sessionDir!;\n\t\tconst sessionFile = resumeContext.sessionFile!;\n\t\tconst metadataFile = workerConversationMetadataFile(sessionFile);\n\t\tif (existsSync(sessionFile)) {\n\t\t\tthrow new Error(`Worker conversation already exists for logical agent '${options.logicalAgentId}'.`);\n\t\t}\n\n\t\t// SessionManager intentionally defers a brand-new header until its first assistant message.\n\t\t// A worker must be resumable after its first user/tool message, so atomically seed the exact\n\t\t// SessionManager header and immediately reopen it through SessionManager for all later writes.\n\t\tconst seed = SessionManager.create(resumeContext.cwd, options.agentDir, sessionDir, {\n\t\t\tid: resumeContext.sessionId,\n\t\t});\n\t\tconst header = seed.getHeader();\n\t\tif (!header) throw new Error(\"Unable to create a worker conversation session header.\");\n\t\tif (existsSync(metadataFile)) {\n\t\t\tassertExactConversationMetadata(metadataFile, resumeContext, options.logicalAgentId);\n\t\t} else {\n\t\t\t// Metadata lands first: a crash leaves no visible conversation until the ordinary session\n\t\t\t// header is atomically published, while a later ensure can validate the exact intended identity.\n\t\t\twriteFileAtomicSync(\n\t\t\t\tmetadataFile,\n\t\t\t\t`${JSON.stringify({ logicalAgentId: options.logicalAgentId, resumeContext })}\\n`,\n\t\t\t);\n\t\t}\n\t\twriteFileAtomicSync(sessionFile, `${JSON.stringify(header)}\\n`);\n\n\t\treturn this.open({\n\t\t\tagentDir: options.agentDir,\n\t\t\tresumeContext,\n\t\t\texpectedLogicalAgentId: options.logicalAgentId,\n\t\t});\n\t}\n\n\t/** Open the one canonical transcript or atomically create it with the exact same durable identity. */\n\tensure(options: CreateWorkerConversationOptions): WorkerConversation {\n\t\tconst resumeContext = expectedResumeContext(options);\n\t\tconst sessionFile = resumeContext.sessionFile!;\n\t\treturn withFileLockSync(sessionFile, () => {\n\t\t\tif (!existsSync(sessionFile)) return this.createLocked(options, resumeContext);\n\t\t\treturn this.open({\n\t\t\t\tagentDir: options.agentDir,\n\t\t\t\tresumeContext,\n\t\t\t\texpectedLogicalAgentId: options.logicalAgentId,\n\t\t\t});\n\t\t});\n\t}\n\n\topen(options: OpenWorkerConversationOptions): WorkerConversation {\n\t\tconst context = cloneResumeContext(options.resumeContext);\n\t\tif (context.provider !== \"pi\") throw new TypeError(\"Only Pi worker conversations can be reopened.\");\n\t\tif (!context.sessionFile)\n\t\t\tthrow new TypeError(\"A persisted worker session file is required to reopen a conversation.\");\n\t\tif (!context.cwd.trim()) throw new TypeError(\"A worker conversation working directory is required.\");\n\t\tassertValidSessionId(context.sessionId);\n\n\t\tconst sessionFile = assertWorkerConversationFile(options.agentDir, context.sessionFile, context.sessionId);\n\t\tif (!existsSync(sessionFile)) throw new Error(`Worker conversation session file does not exist: ${sessionFile}`);\n\t\tconst sessionDir = dirname(sessionFile);\n\t\tif (context.sessionDir && resolve(context.sessionDir) !== sessionDir) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Worker conversation resume context has a session directory that disagrees with its session file.\",\n\t\t\t);\n\t\t}\n\n\t\tconst sessionManager = SessionManager.open(sessionFile, options.agentDir, sessionDir);\n\t\tif (sessionManager.getSessionId() !== context.sessionId) {\n\t\t\tthrow new Error(\"Worker conversation session file does not contain the requested durable session id.\");\n\t\t}\n\t\tif (sessionManager.getCwd() !== resolve(context.cwd)) {\n\t\t\tthrow new Error(\"Worker conversation resume context working directory disagrees with the persisted session.\");\n\t\t}\n\t\tassertExactConversationMetadata(\n\t\t\tworkerConversationMetadataFile(sessionFile),\n\t\t\tcontext,\n\t\t\toptions.expectedLogicalAgentId,\n\t\t);\n\n\t\treturn new WorkerConversation(sessionManager, {\n\t\t\t...context,\n\t\t\tsessionDir,\n\t\t\tsessionFile,\n\t\t\tcwd: sessionManager.getCwd(),\n\t\t});\n\t}\n}\n\nfunction joinWorkerSessionFile(sessionDir: string, sessionId: string): string {\n\treturn resolve(sessionDir, `${sessionId}.jsonl`);\n}\n\nfunction workerConversationMetadataFile(sessionFile: string): string {\n\treturn `${sessionFile}.worker.json`;\n}\n"]}
|
|
@@ -12,7 +12,7 @@ import type { TaskRuntimeProjection } from "../orchestration/task-runtime.ts";
|
|
|
12
12
|
import type { ResourceLoader } from "../resource-loader.ts";
|
|
13
13
|
import type { SettingsManager } from "../settings-manager.ts";
|
|
14
14
|
import type { WorkerAgentControlPort } from "./worker-agent-control.ts";
|
|
15
|
-
import type
|
|
15
|
+
import { type WorkerDelegationRequest } from "./worker-delegation-request.ts";
|
|
16
16
|
import type { WorkerLifecycle } from "./worker-lifecycle.ts";
|
|
17
17
|
import type { WorkerNotificationCoordinator } from "./worker-notification-coordinator.ts";
|
|
18
18
|
export declare function isLocalExecutionModel(model: Pick<Model<Api>, "provider" | "baseUrl">): boolean;
|
|
@@ -63,10 +63,13 @@ export declare class WorkerDelegationController {
|
|
|
63
63
|
private readonly notifications;
|
|
64
64
|
private readonly scheduler;
|
|
65
65
|
private readonly laneAbortControllers;
|
|
66
|
+
private readonly shellSessionKeys;
|
|
66
67
|
/** Sole logical-agent control/mailbox owner; execution only calls its narrow delivery hooks. */
|
|
67
68
|
private readonly agentControl;
|
|
68
69
|
private readonly publishedTerminalAttemptIds;
|
|
70
|
+
private readonly yieldedCapacityAttemptIds;
|
|
69
71
|
private readonly conversations;
|
|
72
|
+
private readonly treeBudgets;
|
|
70
73
|
private readonly writeReservations;
|
|
71
74
|
private readonly inFlightLedgers;
|
|
72
75
|
constructor(deps: WorkerDelegationControllerDeps, notifications: WorkerNotificationCoordinator, lifecycle: WorkerLifecycle);
|
|
@@ -101,6 +104,7 @@ export declare class WorkerDelegationController {
|
|
|
101
104
|
createTaskProfile(input: TaskProfileCreateInput): TaskProfileCreateResult;
|
|
102
105
|
private resolveWorkerShipment;
|
|
103
106
|
private resolveRequiredVerifier;
|
|
107
|
+
private hasExactRecursiveCycle;
|
|
104
108
|
/** Single admission contract shared by enqueue, scheduler revalidation, and execution. */
|
|
105
109
|
private resolveWorkerAdmission;
|
|
106
110
|
private buildVerifierRequest;
|
|
@@ -113,10 +117,12 @@ export declare class WorkerDelegationController {
|
|
|
113
117
|
*/
|
|
114
118
|
private cancelAndPublish;
|
|
115
119
|
private hasWorkerCapacity;
|
|
120
|
+
private yieldWorkerCapacity;
|
|
116
121
|
private workerDispatchAdmission;
|
|
117
122
|
private buildWorkerExecutionPlan;
|
|
118
123
|
/** One durable preparation path for queued, immediate, and recovered execution. */
|
|
119
124
|
private prepareWorkerAttempt;
|
|
125
|
+
private ensurePreparedAgent;
|
|
120
126
|
start(request: WorkerDelegationRequest): {
|
|
121
127
|
started: false;
|
|
122
128
|
skipReason: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-delegation-controller.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-delegation-controller.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,KAAK,EACX,iBAAiB,EACjB,yBAAyB,EACzB,wBAAwB,EACxB,0BAA0B,EAC1B,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAG/F,OAAO,KAAK,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAElF,OAAO,EAAkC,KAAK,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;
|
|
1
|
+
{"version":3,"file":"worker-delegation-controller.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-delegation-controller.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,KAAK,EACX,iBAAiB,EACjB,yBAAyB,EACzB,wBAAwB,EACxB,0BAA0B,EAC1B,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAG/F,OAAO,KAAK,EAAE,UAAU,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