@caupulican/pi-adaptative 0.85.3 → 0.85.8
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 +60 -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-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-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +2 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +12 -8
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +82 -88
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-guidance.d.ts.map +1 -1
- package/dist/core/auth-guidance.js +3 -0
- package/dist/core/auth-guidance.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/lane-tool-surface.d.ts +2 -0
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.js +4 -3
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +4 -0
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +2 -0
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/background-tool-task-controller.d.ts +12 -7
- package/dist/core/background-tool-task-controller.d.ts.map +1 -1
- package/dist/core/background-tool-task-controller.js +55 -19
- package/dist/core/background-tool-task-controller.js.map +1 -1
- package/dist/core/bash-executor.js +2 -2
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/bedrock-scope.d.ts +26 -0
- package/dist/core/bedrock-scope.d.ts.map +1 -0
- package/dist/core/bedrock-scope.js +178 -0
- package/dist/core/bedrock-scope.js.map +1 -0
- 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/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/delegation/worker-actions.js +1 -1
- package/dist/core/delegation/worker-actions.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 +3 -2
- package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
- 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 +3 -2
- package/dist/core/delegation/worker-conversation-store.js.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.js +6 -0
- package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
- 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 -528
- 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 +26 -2
- package/dist/core/foreground-recovery-controller.d.ts.map +1 -1
- package/dist/core/foreground-recovery-controller.js +112 -3
- package/dist/core/foreground-recovery-controller.js.map +1 -1
- package/dist/core/foreground-terminal-handoff-controller.d.ts +27 -0
- package/dist/core/foreground-terminal-handoff-controller.d.ts.map +1 -0
- package/dist/core/foreground-terminal-handoff-controller.js +56 -0
- package/dist/core/foreground-terminal-handoff-controller.js.map +1 -0
- package/dist/core/goal-loop-controller.d.ts.map +1 -1
- package/dist/core/goal-loop-controller.js +5 -0
- 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.d.ts +3 -0
- package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-auto-continue-controller.js +28 -7
- 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/human-input-controller.d.ts +9 -0
- package/dist/core/human-input-controller.d.ts.map +1 -1
- package/dist/core/human-input-controller.js +60 -5
- package/dist/core/human-input-controller.js.map +1 -1
- package/dist/core/human-input.d.ts +12 -0
- package/dist/core/human-input.d.ts.map +1 -1
- package/dist/core/human-input.js +59 -12
- package/dist/core/human-input.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/local-runtime-controller.d.ts.map +1 -1
- package/dist/core/local-runtime-controller.js +15 -9
- package/dist/core/local-runtime-controller.js.map +1 -1
- package/dist/core/memory/providers/file-store.d.ts +1 -0
- package/dist/core/memory/providers/file-store.d.ts.map +1 -1
- package/dist/core/memory/providers/file-store.js +253 -126
- 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-capability.d.ts +15 -1
- package/dist/core/model-capability.d.ts.map +1 -1
- package/dist/core/model-capability.js +24 -1
- package/dist/core/model-capability.js.map +1 -1
- package/dist/core/model-registry.d.ts +7 -1
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +22 -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.d.ts +6 -6
- package/dist/core/model-router-controller.d.ts.map +1 -1
- package/dist/core/model-router-controller.js +6 -6
- 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/context-sizing.d.ts +1 -0
- package/dist/core/models/context-sizing.d.ts.map +1 -1
- package/dist/core/models/context-sizing.js +4 -1
- package/dist/core/models/context-sizing.js.map +1 -1
- package/dist/core/models/default-model-suggestions.d.ts.map +1 -1
- package/dist/core/models/default-model-suggestions.js +20 -10
- package/dist/core/models/default-model-suggestions.js.map +1 -1
- package/dist/core/models/llamacpp-runtime.d.ts +39 -11
- package/dist/core/models/llamacpp-runtime.d.ts.map +1 -1
- package/dist/core/models/llamacpp-runtime.js +87 -31
- package/dist/core/models/llamacpp-runtime.js.map +1 -1
- package/dist/core/models/local-execution-planner.d.ts +24 -0
- package/dist/core/models/local-execution-planner.d.ts.map +1 -0
- package/dist/core/models/local-execution-planner.js +119 -0
- package/dist/core/models/local-execution-planner.js.map +1 -0
- package/dist/core/models/local-inference-profile.d.ts +34 -0
- package/dist/core/models/local-inference-profile.d.ts.map +1 -0
- package/dist/core/models/local-inference-profile.js +74 -0
- package/dist/core/models/local-inference-profile.js.map +1 -0
- package/dist/core/models/local-runtime.d.ts +23 -4
- package/dist/core/models/local-runtime.d.ts.map +1 -1
- package/dist/core/models/local-runtime.js +12 -9
- package/dist/core/models/local-runtime.js.map +1 -1
- package/dist/core/models/managed-ollama-model.d.ts +26 -0
- package/dist/core/models/managed-ollama-model.d.ts.map +1 -0
- package/dist/core/models/managed-ollama-model.js +59 -0
- package/dist/core/models/managed-ollama-model.js.map +1 -0
- package/dist/core/models/model-ref.js +11 -11
- package/dist/core/models/model-ref.js.map +1 -1
- package/dist/core/models/prism-llamacpp-lifecycle.d.ts +10 -20
- package/dist/core/models/prism-llamacpp-lifecycle.d.ts.map +1 -1
- package/dist/core/models/prism-llamacpp-lifecycle.js +11 -31
- package/dist/core/models/prism-llamacpp-lifecycle.js.map +1 -1
- package/dist/core/models/prism-llamacpp-server-probe.d.ts +10 -0
- package/dist/core/models/prism-llamacpp-server-probe.d.ts.map +1 -0
- package/dist/core/models/prism-llamacpp-server-probe.js +36 -0
- package/dist/core/models/prism-llamacpp-server-probe.js.map +1 -0
- package/dist/core/models/runtime-arbiter.d.ts +3 -0
- package/dist/core/models/runtime-arbiter.d.ts.map +1 -1
- package/dist/core/models/runtime-arbiter.js +2 -1
- package/dist/core/models/runtime-arbiter.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/task-profile-writer.js +1 -1
- package/dist/core/orchestration/task-profile-writer.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 +15 -6
- 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/runtime-builder.d.ts +5 -1
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +50 -7
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/scout-controller.d.ts +4 -3
- package/dist/core/scout-controller.d.ts.map +1 -1
- package/dist/core/scout-controller.js +2 -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 +13 -11
- package/dist/core/sdk.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 +13 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +60 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt-builder.d.ts +5 -2
- package/dist/core/system-prompt-builder.d.ts.map +1 -1
- package/dist/core/system-prompt-builder.js +22 -10
- package/dist/core/system-prompt-builder.js.map +1 -1
- package/dist/core/system-prompt.d.ts +3 -0
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +181 -55
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tool-protocol-controller.d.ts.map +1 -1
- package/dist/core/tool-protocol-controller.js +5 -3
- package/dist/core/tool-protocol-controller.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/edit-diff.d.ts +2 -0
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +9 -1
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts +5 -8
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +88 -55
- package/dist/core/tools/edit.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/file-mutation-intent.d.ts +42 -15
- package/dist/core/tools/file-mutation-intent.d.ts.map +1 -1
- package/dist/core/tools/file-mutation-intent.js +271 -77
- package/dist/core/tools/file-mutation-intent.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/index.d.ts +3 -5
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +8 -44
- 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/render-utils.js +1 -1
- package/dist/core/tools/render-utils.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/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/tools/write.d.ts +5 -10
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +92 -73
- package/dist/core/tools/write.js.map +1 -1
- 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 +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -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/auth-dialogs-controller.d.ts +6 -0
- package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -1
- package/dist/modes/interactive/auth-dialogs-controller.js +59 -12
- package/dist/modes/interactive/auth-dialogs-controller.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/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.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +1 -1
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/local-model-commands.d.ts +1 -1
- package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
- package/dist/modes/interactive/local-model-commands.js +51 -8
- package/dist/modes/interactive/local-model-commands.js.map +1 -1
- package/dist/utils/child-process.js +1 -1
- package/dist/utils/child-process.js.map +1 -1
- package/docs/providers.md +34 -10
- package/docs/tool-boundary-performance-roadmap-2026-08-02.md +21 -18
- package/examples/extensions/built-in-tool-renderer.ts +1 -1
- 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/minimal-mode.ts +1 -1
- package/examples/extensions/prompt-customizer.ts +2 -2
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/ssh.ts +17 -0
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +240 -260
- package/package.json +9 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reflection-controller.js","sourceRoot":"","sources":["../../src/core/reflection-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAKN,YAAY,EACZ,yBAAyB,GAEzB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAKN,yBAAyB,GAIzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACN,sBAAsB,EACtB,0BAA0B,GA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AG,cAAc,IAAI,kBAAkB,eAAe,4HAA4H,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC;YAC/M,aAAa,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;YACtC,OAAO,IAAI,CAAC;QACb,CAAC;QAAC,MAAM,CAAC;YACR,oCAAoC;YACpC,OAAO,KAAK,CAAC;QACd,CAAC;IACF,CAAC;CACD","sourcesContent":["/**\n * Native reflection + learning-write controller.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the end-of-loop reflection\n * pass (R2), the isolated-completion primitive it runs on, and the learning-apply/rollback path that\n * turns reflection writes into gated, audited durable memory/skill changes. It mutates NO session\n * fields — every durable effect goes through the bundled memory tool, the session log (via deps), or\n * the skills dir; the whole pass is best-effort and never throws into the turn loop. Reads live\n * session state (model/agent/registry/memory/settings) through narrow deps accessors rather than the\n * whole AgentSession.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n\ttype Agent,\n\ttype AgentContext,\n\ttype AgentLoopConfig,\n\ttype AgentMessage,\n\trunAgentLoop,\n\tstartAgentProviderRequest,\n\ttype ThinkingLevel,\n} from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport {\n\ttype Api,\n\ttype AssistantMessage,\n\ttype Message,\n\ttype Model,\n\tresolveModelThinkingLevel,\n\ttype SimpleStreamOptions,\n\ttype TextContent,\n\ttype Usage,\n} from \"@caupulican/pi-ai\";\nimport {\n\tcomputeLaneAffinityKey,\n\tDEFAULT_ISOLATED_LANE_KIND,\n\ttype IsolatedCompletionOptions,\n\ttype IsolatedCompletionResult,\n} from \"./agent-session-contracts.ts\";\nimport type { LearningDecision } from \"./autonomy/contracts.ts\";\nimport { AUTONOMY_TELEMETRY_EVENT_TYPES, type AutonomyTelemetryEvent } from \"./autonomy/telemetry-events.ts\";\nimport {\n\tAPPLY_WRITE_REFUSED_REASON_CODE,\n\tappendLearningAuditSnapshot,\n\tcontradictionsForReflectionWrite,\n\tgetLearningAuditSnapshots,\n\ttype LearningAuditRecord,\n\tproposalFromReflectionWrite,\n\trollbackPlanForReflectionWrite,\n} from \"./learning/learning-audit.ts\";\nimport { evaluateLearningDecision } from \"./learning/learning-gate.ts\";\nimport { ObservationStore, observationKey } from \"./learning/observation-store.ts\";\nimport {\n\ttype DemandSignals,\n\tdecideDemand,\n\tReflectionEngine,\n\ttype ReflectionResult,\n\ttype ReflectionWrite,\n} from \"./learning/reflection-engine.ts\";\nimport {\n\tanalyzeReflectionTurn,\n\tboundReflectionSemanticText,\n\ttype ReflectionTurnAnalysis,\n\treflectionTriggerPriority,\n} from \"./learning/reflection-turn-analysis.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { registerInFlightWork } from \"./reload-blockers.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { runSkillAudit } from \"./tools/skill-audit.ts\";\n\nexport interface ReflectionControllerDeps {\n\t/** Current session model (fallback for an isolated call that omits its own model). */\n\tgetModel(): Model<Api> | undefined;\n\t/** The underlying agent — its `streamFn` runs the isolated completion. */\n\tgetAgent(): Agent;\n\t/** True when the session's stream fn is the raw `streamSimple` provider (auth must be injected). */\n\tisRawStreamSimple(): boolean;\n\t/** Model registry for API-key/header resolution on the raw-provider path. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** Memory subsystem — the bundled `memory` tool applies durable writes; fresh block feeds reflection. */\n\tgetMemoryManager(): MemoryManager;\n\t/** Settings — the learning-apply policy (gate thresholds, auto-apply layers) is read here. */\n\tgetSettingsManager(): SettingsManager;\n\t/** Session log — audit snapshots and learning-audit reads go through this. */\n\tgetSessionManager(): SessionManager;\n\t/** Agent dir — reflection-promoted skills are written under `<agentDir>/skills/`. */\n\tgetAgentDir(): string;\n\t/** Child sessions must not learn — the pass returns null for them. */\n\tisChildSession(): boolean;\n\t/** Disposal short-circuits: no completion, no writes against a dead session. */\n\tisDisposed(): boolean;\n\t/** Session-lifetime abort signal — aborts an in-flight reflection completion on dispose. */\n\tgetReflectionSignal(): AbortSignal;\n\t/** Archive a promoted skill (rollback of a `promote_skill` write). */\n\tarchivePromotedSkill(name: string): boolean;\n\t/** G3/G8 autonomy telemetry sink for learning-gate outcomes and approval requests. */\n\temitAutonomyTelemetry(event: AutonomyTelemetryEvent): void;\n\t/** Account the reflection pass's token spend into the cost roll-up (idempotent on reportId). */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts?: { label?: string; sourceSessionId?: string; reportId?: string },\n\t): string | undefined;\n\t/** Persist a learning-gate decision snapshot to the session log. */\n\tsaveLearningDecisionSnapshot(decision: LearningDecision): string;\n\t/** Resolve text-tool fallback for the selected isolated model, not the foreground model. */\n\tresolveTextToolCallProtocol(model: Model<Api>): SimpleStreamOptions[\"textToolCallProtocol\"];\n\t/** Ensure a managed-local model is running/resident before any isolated lane calls it. */\n\tensureModelReady(model: Model<Api>): Promise<void>;\n\t/**\n\t * Session working directory — feeds the skill-overlap audit's project-local skill discovery, the\n\t * same `cwd` the model-invoked `skillify`/`skill_audit` tools already receive (tools/index.ts).\n\t * Optional so a host that has not wired it yet still resolves (falls back to `process.cwd()`,\n\t * mirroring the existing profile-resolution fallback in settings-manager.ts).\n\t */\n\tgetCwd?(): string;\n}\n\n// reasonCode when an automatic skill promotion is blocked by an overlap with an existing skill\n// (skill_audit's similarity threshold) and routed to a consolidation proposal instead of a blind write.\nexport const SKILL_OVERLAP_CONSOLIDATION_REASON_CODE = \"skill_overlap_consolidation_proposed\";\n// reasonCode when the overlap audit itself fails — the promotion is held (not written unaudited)\n// rather than silently skipping the check.\nexport const SKILL_AUDIT_UNAVAILABLE_REASON_CODE = \"skill_audit_unavailable\";\n\nconst REFLECTION_MIN_INTERVAL_MS = 45_000;\nconst REFLECTION_PENDING_MAX_CHARS = 12_000;\nconst REFLECTION_DIGEST_HISTORY_SIZE = 64;\n\nexport class ReflectionController {\n\tprivate readonly deps: ReflectionControllerDeps;\n\tprivate readonly pendingTurns: Array<{ analysis: ReflectionTurnAnalysis; contextHeadroomPct: number }> = [];\n\tprivate readonly scheduledDigests = new Set<string>();\n\tprivate activeScheduledPass: Promise<void> | undefined;\n\tprivate scheduledTimer: NodeJS.Timeout | undefined;\n\tprivate lastScheduledPassAt = 0;\n\n\tconstructor(deps: ReflectionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** Analyze once, schedule bounded background reflection when warranted, and return filtered turn text for sync hooks. */\n\tscheduleFromTurn(messages: AgentMessage[], contextHeadroomPct: number): ReflectionTurnAnalysis {\n\t\tconst settings = this.deps.getSettingsManager().getAutoLearnSettings();\n\t\tconst analysis = analyzeReflectionTurn(messages, settings.complexTaskToolCalls ?? 12);\n\t\tconst enabled =\n\t\t\tsettings.enabled !== false &&\n\t\t\tsettings.reflectionReview !== false &&\n\t\t\tprocess.env.PI_NATIVE_REFLECTION !== \"0\" &&\n\t\t\tprocess.env.PI_AUTO_LEARN_CHILD !== \"1\" &&\n\t\t\t!this.deps.isChildSession() &&\n\t\t\t!this.deps.isDisposed();\n\t\tif (!enabled || analysis.trigger === \"none\" || this.scheduledDigests.has(analysis.digest)) return analysis;\n\n\t\tthis.scheduledDigests.add(analysis.digest);\n\t\twhile (this.scheduledDigests.size > REFLECTION_DIGEST_HISTORY_SIZE) {\n\t\t\tconst oldest = this.scheduledDigests.values().next().value;\n\t\t\tif (typeof oldest !== \"string\") break;\n\t\t\tthis.scheduledDigests.delete(oldest);\n\t\t}\n\t\tthis.pendingTurns.push({ analysis, contextHeadroomPct });\n\t\tlet pendingChars = this.pendingTurns.reduce((total, turn) => total + turn.analysis.recentTurnText.length, 0);\n\t\twhile (this.pendingTurns.length > 1 && pendingChars > REFLECTION_PENDING_MAX_CHARS) {\n\t\t\tpendingChars -= this.pendingTurns.shift()?.analysis.recentTurnText.length ?? 0;\n\t\t}\n\t\tthis.schedulePendingPass();\n\t\treturn analysis;\n\t}\n\n\tprivate schedulePendingPass(): void {\n\t\tif (this.activeScheduledPass || this.scheduledTimer || this.pendingTurns.length === 0 || this.deps.isDisposed()) {\n\t\t\treturn;\n\t\t}\n\t\tconst delay = Math.max(0, REFLECTION_MIN_INTERVAL_MS - (Date.now() - this.lastScheduledPassAt));\n\t\tif (delay > 0) {\n\t\t\tthis.scheduledTimer = setTimeout(() => {\n\t\t\t\tthis.scheduledTimer = undefined;\n\t\t\t\tthis.startPendingPass();\n\t\t\t}, delay);\n\t\t\tthis.scheduledTimer.unref?.();\n\t\t\treturn;\n\t\t}\n\t\tthis.startPendingPass();\n\t}\n\n\tprivate startPendingPass(): void {\n\t\tif (this.activeScheduledPass || this.pendingTurns.length === 0 || this.deps.isDisposed()) return;\n\t\tconst turns = this.pendingTurns.splice(0);\n\t\tconst trigger = turns.reduce<DemandSignals[\"trigger\"]>(\n\t\t\t(selected, turn) =>\n\t\t\t\treflectionTriggerPriority(turn.analysis.trigger) > reflectionTriggerPriority(selected)\n\t\t\t\t\t? turn.analysis.trigger\n\t\t\t\t\t: selected,\n\t\t\t\"none\",\n\t\t);\n\t\tconst recentTurnText = boundReflectionSemanticText(\n\t\t\tturns.map((turn) => turn.analysis.recentTurnText).join(\"\\n---\\n\"),\n\t\t\tREFLECTION_PENDING_MAX_CHARS,\n\t\t);\n\t\tconst reportDigest = createHash(\"sha256\")\n\t\t\t.update(turns.map((turn) => turn.analysis.digest).join(\"\\0\"))\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 24);\n\t\tconst settings = this.deps.getSettingsManager().getAutoLearnSettings();\n\t\tlet model: Model<Api> | undefined;\n\t\tif (settings.model && settings.model !== \"active\") {\n\t\t\tconst resolved = resolveCliModel({ cliModel: settings.model, modelRegistry: this.deps.getModelRegistry() });\n\t\t\tif (resolved.model && this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) model = resolved.model;\n\t\t}\n\t\tconst toolCallCount = turns.reduce((total, turn) => total + turn.analysis.toolCallCount, 0);\n\t\tconst contextHeadroomPct = Math.min(...turns.map((turn) => turn.contextHeadroomPct));\n\t\tthis.lastScheduledPassAt = Date.now();\n\t\tthis.activeScheduledPass = (async () => {\n\t\t\ttry {\n\t\t\t\tawait this.runReflectionPass({\n\t\t\t\t\tsignals: {\n\t\t\t\t\t\ttrigger,\n\t\t\t\t\t\ttoolCallCount,\n\t\t\t\t\t\thadCorrection: turns.some((turn) => turn.analysis.hadCorrection),\n\t\t\t\t\t\tcontextHeadroomPct,\n\t\t\t\t\t\tusefulLately: 0,\n\t\t\t\t\t},\n\t\t\t\t\trecentTurnText,\n\t\t\t\t\treportId: `reflection:${reportDigest}`,\n\t\t\t\t\tmodel,\n\t\t\t\t\tthinkingLevel: settings.thinkingLevel ?? \"low\",\n\t\t\t\t\texplicitUserMemoryInstruction: turns.every((turn) => turn.analysis.explicitUserMemoryInstruction),\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\t// Best-effort background learning must never disrupt the foreground turn.\n\t\t\t} finally {\n\t\t\t\tthis.activeScheduledPass = undefined;\n\t\t\t\tthis.schedulePendingPass();\n\t\t\t}\n\t\t})();\n\t}\n\n\tcancelScheduled(): void {\n\t\tif (this.scheduledTimer) clearTimeout(this.scheduledTimer);\n\t\tthis.scheduledTimer = undefined;\n\t\tthis.pendingTurns.length = 0;\n\t}\n\n\tasync waitForActivePass(): Promise<void> {\n\t\twhile (this.activeScheduledPass) await this.activeScheduledPass;\n\t}\n\n\t/**\n\t * Run an LLM completion fully ISOLATED from the main session — the load-bearing primitive for\n\t * reflection and bounded child lanes (adaptive-agent design §6c/§7).\n\t *\n\t * Isolation invariants (audited by codex): builds fresh context (no main history), defaults to no\n\t * tools, and passes **no real `sessionId`** — only a deterministic SYNTHETIC cache-affinity key\n\t * (see {@link computeLaneAffinityKey}) derived from `(laneKind, model, systemPrompt)`, which can never\n\t * equal or embed the real session id. A tool-enabled call receives only caller-owned tools and hooks,\n\t * and applies a turn bound only when its owner explicitly supplies one. It cannot mutate `agent.state.messages`, append session entries, or touch the\n\t * foreground tool registry. Mirrors `generateSummary()`'s one-shot mechanics otherwise.\n\t *\n\t * Returns the result even on an error/aborted stop reason (callers — e.g. a background reflection\n\t * microtask — decide whether to act); it does not throw on a model-level error.\n\t */\n\tasync runIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult> {\n\t\tif (opts.maxTurns !== undefined && (!Number.isSafeInteger(opts.maxTurns) || opts.maxTurns <= 0)) {\n\t\t\tthrow new Error(\"runIsolatedCompletion: maxTurns must be a positive safe integer when provided\");\n\t\t}\n\t\tconst model = opts.model ?? this.deps.getModel();\n\t\tif (!model) {\n\t\t\tthrow new Error(\"runIsolatedCompletion: no model available\");\n\t\t}\n\t\tawait this.deps.ensureModelReady(model);\n\t\tconst thinkingLevel = resolveModelThinkingLevel(model, opts.thinkingLevel, \"off\");\n\n\t\t// Registered for the full isolated-completion call (one-shot or child-loop) so the\n\t\t// reload gate waits it out — this is the SINGLE choke point every isolated completion in the\n\t\t// codebase runs through (reflection, research/worker/fitness lanes, context-pipeline curation,\n\t\t// model-router judge calls). registerInFlightWork is a pure sync map op (cannot throw), so\n\t\t// placing it as the last statement before `try` still guarantees the matching finally always\n\t\t// runs, on every return path below and on any thrown error.\n\t\tconst deregisterInFlight = registerInFlightWork(\n\t\t\tthis.deps.getAgentDir(),\n\t\t\t\"isolated-completion\",\n\t\t\topts.laneKind ?? DEFAULT_ISOLATED_LANE_KIND,\n\t\t);\n\t\ttry {\n\t\t\t// Fresh, isolated context: explicit messages, caller-owned tools only, nothing from the main session.\n\t\t\tconst history = opts.history ?? [];\n\t\t\tconst context: AgentContext = {\n\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\tmessages: [...history, ...opts.messages],\n\t\t\t\ttools: opts.tools ?? [],\n\t\t\t};\n\n\t\t\t// Isolate the prompt cache from the main session by DELIBERATELY never sending the real\n\t\t\t// sessionId. In its place, a deterministic SYNTHETIC affinity key lets providers with\n\t\t\t// session-affinity headers / prompt_cache_key route repeat calls from the SAME lane (same\n\t\t\t// laneKind+model+systemPrompt) to the same cache-warm backend, without entangling this call\n\t\t\t// with — or leaking any identity of — the main session.\n\t\t\tconst affinityKey = computeLaneAffinityKey(\n\t\t\t\topts.laneKind ?? DEFAULT_ISOLATED_LANE_KIND,\n\t\t\t\tmodel,\n\t\t\t\topts.systemPrompt,\n\t\t\t);\n\t\t\tconst options: SimpleStreamOptions = {\n\t\t\t\tmaxTokens: opts.maxTokens,\n\t\t\t\tsignal: opts.signal,\n\t\t\t\tinteractionMode: \"background\",\n\t\t\t\tcacheRetention: opts.cacheRetention,\n\t\t\t\treasoning: thinkingLevel,\n\t\t\t\tsessionId: affinityKey,\n\t\t\t};\n\n\t\t\t// When streamFn is the raw streamSimple (e.g. in tests), auth must be injected explicitly.\n\t\t\t// Throw only when auth genuinely fails — providers that authenticate without an API key\n\t\t\t// (OAuth, local no-key) legitimately return ok with an undefined apiKey.\n\t\t\tif (this.deps.isRawStreamSimple()) {\n\t\t\t\tconst auth = await this.deps.getModelRegistry().getApiKeyAndHeaders(model);\n\t\t\t\tif (!auth.ok) {\n\t\t\t\t\tthrow new Error(auth.error);\n\t\t\t\t}\n\t\t\t\toptions.apiKey = auth.apiKey;\n\t\t\t\toptions.headers = auth.headers;\n\t\t\t}\n\t\t\tconst agent = this.deps.getAgent();\n\t\t\tconst foregroundModel = agent.state.model;\n\t\t\tconst usesForegroundModel = foregroundModel?.provider === model.provider && foregroundModel.id === model.id;\n\t\t\tconst textToolCallProtocol = this.deps.resolveTextToolCallProtocol(model);\n\t\t\tconst maxTurns = opts.maxTurns;\n\t\t\tlet completedTurns = 0;\n\t\t\tconst loopConfig: AgentLoopConfig = {\n\t\t\t\tmodel,\n\t\t\t\tinteractionMode: \"background\",\n\t\t\t\tmaxTokens: opts.maxTokens,\n\t\t\t\tcacheRetention: opts.cacheRetention,\n\t\t\t\treasoning: thinkingLevel,\n\t\t\t\t// Same synthetic per-lane affinity key as the one-shot path above — never the real sessionId.\n\t\t\t\tsessionId: affinityKey,\n\t\t\t\t...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n\t\t\t\t...(options.headers !== undefined ? { headers: options.headers } : {}),\n\t\t\t\tgetApiKey: agent.getApiKey,\n\t\t\t\tresolveRequestReasoning: agent.resolveRequestReasoning,\n\t\t\t\ttemperature: textToolCallProtocol ? 0 : undefined,\n\t\t\t\ttextToolCallProtocol,\n\t\t\t\tonTextToolProtocolParse: usesForegroundModel ? agent.onTextToolProtocolParse : undefined,\n\t\t\t\ttransport: agent.transport,\n\t\t\t\tthinkingBudgets: agent.thinkingBudgets,\n\t\t\t\tmaxRetryDelayMs: agent.maxRetryDelayMs,\n\t\t\t\t// This remains independent from an owner-provided turn budget: it stops only repeated\n\t\t\t\t// identical tool calls, so legitimate long-running work can continue until completion.\n\t\t\t\tmaxStallTurns: agent.maxStallTurns,\n\t\t\t\tonRunawayStop: usesForegroundModel ? agent.onRunawayStop : undefined,\n\t\t\t\ttoolExecution: \"sequential\",\n\t\t\t\ttoolArgumentTeachEnabled: agent.toolArgumentTeachEnabled,\n\t\t\t\tonToolArgumentValidation: usesForegroundModel ? agent.onToolArgumentValidation : undefined,\n\t\t\t\ttoolValidationEscalationThreshold: agent.toolValidationEscalationThreshold,\n\t\t\t\tonToolValidationEscalation: usesForegroundModel ? agent.onToolValidationEscalation : undefined,\n\t\t\t\tbeforeToolCall: opts.beforeToolCall,\n\t\t\t\tafterToolCall: opts.afterToolCall,\n\t\t\t\tgetSteeringMessages: opts.getSteeringMessages,\n\t\t\t\tgetFollowUpMessages: opts.getFollowUpMessages,\n\t\t\t\ttransformContext: opts.transformContext,\n\t\t\t\trequestPreflight: opts.requestPreflight,\n\t\t\t\t...(maxTurns === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tshouldStopAfterTurn: () => {\n\t\t\t\t\t\t\t\tcompletedTurns += 1;\n\t\t\t\t\t\t\t\treturn completedTurns >= maxTurns;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\tconvertToLlm: agent.convertToLlm,\n\t\t\t};\n\n\t\t\t// An explicitly supplied surface owns a child tool loop even when it is empty: a model may\n\t\t\t// hallucinate an unavailable tool and must receive the bounded unknown-tool result so it can\n\t\t\t// repair. Only an omitted tools option selects the one-shot completion path.\n\t\t\tif (opts.tools !== undefined) {\n\t\t\t\tconst childContext: AgentContext = {\n\t\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\t\tmessages: [...history],\n\t\t\t\t\ttools: [...opts.tools],\n\t\t\t\t};\n\t\t\t\tconst messages = await runAgentLoop(\n\t\t\t\t\topts.messages,\n\t\t\t\t\tchildContext,\n\t\t\t\t\tloopConfig,\n\t\t\t\t\tasync (event) => {\n\t\t\t\t\t\tif (event.type === \"message_end\") await opts.onMessage?.(event.message as Message);\n\t\t\t\t\t},\n\t\t\t\t\topts.signal,\n\t\t\t\t\tagent.streamFn,\n\t\t\t\t);\n\t\t\t\tconst assistantMessages = messages.filter(\n\t\t\t\t\t(message): message is AssistantMessage => message.role === \"assistant\",\n\t\t\t\t);\n\t\t\t\tlet finalAssistant = assistantMessages.at(-1);\n\t\t\t\tif (!finalAssistant) {\n\t\t\t\t\tthrow new Error(\"runIsolatedCompletion: child loop produced no assistant message\");\n\t\t\t\t}\n\n\t\t\t\tconst hasFinalText = finalAssistant.content.some(\n\t\t\t\t\t(content) => content.type === \"text\" && content.text.trim().length > 0,\n\t\t\t\t);\n\t\t\t\tconst endedOnToolCall = finalAssistant.content.some((content) => content.type === \"toolCall\");\n\t\t\t\tif (opts.finalTextPrompt && !hasFinalText && endedOnToolCall && !opts.signal?.aborted) {\n\t\t\t\t\t// A hard turn bound may stop immediately after successful tool execution. Preserve that bound,\n\t\t\t\t\t// then allow exactly one tool-free synthesis call so the gathered work is not thrown away.\n\t\t\t\t\tconst finalizationPrompt: Message = {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: opts.finalTextPrompt,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t};\n\t\t\t\t\tawait opts.onMessage?.(finalizationPrompt);\n\t\t\t\t\tconst finalizationContext: AgentContext = {\n\t\t\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\t\t\tmessages: [...history, ...messages, finalizationPrompt],\n\t\t\t\t\t\ttools: [],\n\t\t\t\t\t};\n\t\t\t\t\tconst finalizationStream = await startAgentProviderRequest(\n\t\t\t\t\t\tfinalizationContext,\n\t\t\t\t\t\tloopConfig,\n\t\t\t\t\t\topts.signal,\n\t\t\t\t\t\tagent.streamFn,\n\t\t\t\t\t);\n\t\t\t\t\tfinalAssistant = await finalizationStream.result();\n\t\t\t\t\tawait opts.onMessage?.(finalAssistant);\n\t\t\t\t\tassistantMessages.push(finalAssistant);\n\t\t\t\t\tmessages.push(finalizationPrompt, finalAssistant);\n\t\t\t\t}\n\n\t\t\t\tconst usage = assistantMessages.reduce<Usage>(\n\t\t\t\t\t(total, message) => ({\n\t\t\t\t\t\tinput: total.input + message.usage.input,\n\t\t\t\t\t\toutput: total.output + message.usage.output,\n\t\t\t\t\t\tcacheRead: total.cacheRead + message.usage.cacheRead,\n\t\t\t\t\t\tcacheWrite: total.cacheWrite + message.usage.cacheWrite,\n\t\t\t\t\t\ttotalTokens: total.totalTokens + message.usage.totalTokens,\n\t\t\t\t\t\tcost: {\n\t\t\t\t\t\t\tinput: total.cost.input + message.usage.cost.input,\n\t\t\t\t\t\t\toutput: total.cost.output + message.usage.cost.output,\n\t\t\t\t\t\t\tcacheRead: total.cost.cacheRead + message.usage.cost.cacheRead,\n\t\t\t\t\t\t\tcacheWrite: total.cost.cacheWrite + message.usage.cost.cacheWrite,\n\t\t\t\t\t\t\ttotal: total.cost.total + message.usage.cost.total,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t\t{\n\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tconst text = finalAssistant.content\n\t\t\t\t\t.filter((content): content is TextContent => content.type === \"text\")\n\t\t\t\t\t.map((content) => content.text)\n\t\t\t\t\t.join(\"\");\n\t\t\t\t// Isolated inputs are Message values and this loop only adds assistant/tool-result messages,\n\t\t\t\t// so the child transcript is safely representable by the public Message[] contract.\n\t\t\t\treturn {\n\t\t\t\t\ttext,\n\t\t\t\t\tusage,\n\t\t\t\t\tstopReason: finalAssistant.stopReason,\n\t\t\t\t\tmessages: [...history, ...(messages as Message[])],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tfor (const message of opts.messages) await opts.onMessage?.(message);\n\t\t\tconst stream = await startAgentProviderRequest(context, loopConfig, opts.signal, agent.streamFn);\n\t\t\tconst result = await stream.result();\n\t\t\tawait opts.onMessage?.(result);\n\t\t\tconst text = result.content\n\t\t\t\t.filter((c): c is TextContent => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\");\n\t\t\tconst usage: Usage = result.usage ?? {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t};\n\t\t\treturn { text, usage, stopReason: result.stopReason, messages: [...history, ...opts.messages, result] };\n\t\t} finally {\n\t\t\tderegisterInFlight();\n\t\t}\n\t}\n\n\t/**\n\t * Native end-of-loop reflection pass (R2). Demand-gates (zero-I/O), and when warranted runs the\n\t * {@link ReflectionEngine} via an isolated completion ({@link runIsolatedCompletion}), applies the\n\t * resulting memory writes through the bundled `memory` tool, and accounts the reflection's token\n\t * cost via the cost-aggregation surface so it stays visible and net-negative-auditable.\n\t *\n\t * Returns `null` when the gate skips (or in a child session, which must not learn). The whole pass\n\t * is best-effort: a model/parse error yields no writes, never throws into the caller.\n\t */\n\tasync runReflectionPass(input: {\n\t\tsignals: DemandSignals;\n\t\trecentTurnText: string;\n\t\tmodel?: Model<Api>;\n\t\tthinkingLevel?: ThinkingLevel;\n\t\tsignal?: AbortSignal;\n\t\t/** Stable id so a duplicate scheduling/retry of the same pass can't double-count its cost. */\n\t\treportId?: string;\n\t\t/** True only when every turn in this pass explicitly asked Pi to remember durable information. */\n\t\texplicitUserMemoryInstruction?: boolean;\n\t}): Promise<ReflectionResult | null> {\n\t\tif (this.deps.isChildSession() || this.deps.isDisposed()) return null;\n\t\tconst plan = decideDemand(input.signals);\n\t\tif (plan.act === \"skip\") return null;\n\n\t\t// Bug #21: tie this background pass to the session lifetime. Disposing the session aborts the\n\t\t// in-flight completion (input.signal can add a more specific abort).\n\t\tconst signal = input.signal\n\t\t\t? AbortSignal.any([input.signal, this.deps.getReflectionSignal()])\n\t\t\t: this.deps.getReflectionSignal();\n\n\t\tconst complete = (systemPrompt: string, userPrompt: string) =>\n\t\t\tthis.runIsolatedCompletion({\n\t\t\t\tsystemPrompt,\n\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\tmodel: input.model,\n\t\t\t\tthinkingLevel: input.thinkingLevel ?? \"low\",\n\t\t\t\tmaxTokens: plan.tokenBudget,\n\t\t\t\tsignal,\n\t\t\t\t// The reflection system prompt is static (#33) — let the provider cache the prefix so\n\t\t\t\t// repeated passes only pay for the variable tail.\n\t\t\t\tcacheRetention: \"short\",\n\t\t\t\tlaneKind: \"reflection\",\n\t\t\t});\n\n\t\tconst result = await new ReflectionEngine().reflect({\n\t\t\trecentTurnText: input.recentTurnText,\n\t\t\t// Read memory FRESH (not the prefix-cache-frozen system-prompt block) so confront-before-write\n\t\t\t// sees writes made earlier this session.\n\t\t\texistingMemory: this.deps.getMemoryManager().buildSystemPromptBlockFresh() || \"\",\n\t\t\tplan,\n\t\t\tcomplete,\n\t\t});\n\n\t\t// Bug #21: if the session was disposed while the completion was in flight, do NOT write memory\n\t\t// or skills against the dead session.\n\t\tif (this.deps.isDisposed()) return result;\n\n\t\t// Learning apply policy: every durable write is converted to a proposal, decided by the\n\t\t// learning gate, and audited with a rollback plan. When the policy is explicitly disabled,\n\t\t// legacy direct-apply behavior is preserved — but now leaves audit records with rollback info.\n\t\tconst policy = this.deps.getSettingsManager().getLearningPolicySettings();\n\t\t// The audit id sequence counts STORED snapshots only: it reseeds from the stored count on\n\t\t// every pass, so advancing it for a no-op (which stores nothing) would make later passes\n\t\t// reuse ids — and rollback keys on the id, so a collision blocks or misdirects rollback.\n\t\tlet auditSequence = getLearningAuditSnapshots(this.deps.getSessionManager().getEntries()).length;\n\t\t// G6 evidence strength: durable proposals accumulate observation counts across passes/sessions\n\t\t// so the gate can distinguish a one-off cue from a repeatedly-confirmed lesson. Built once per\n\t\t// pass; every increment is best-effort (store IO must never break reflection).\n\t\tconst observationStore = ObservationStore.forAgentDir(this.deps.getAgentDir());\n\t\tlet writeIndex = 0;\n\t\tfor (const write of result.writes) {\n\t\t\twriteIndex += 1;\n\t\t\tconst proposalId = `${input.reportId ?? \"reflection\"}-w${writeIndex}`;\n\t\t\tconst proposal = proposalFromReflectionWrite(write, proposalId);\n\t\t\tconst rollback = rollbackPlanForReflectionWrite(write);\n\t\t\tlet observations = 1;\n\t\t\tif (policy.enabled) {\n\t\t\t\ttry {\n\t\t\t\t\tobservations = observationStore.increment(observationKey(proposal.layer, proposal.summary));\n\t\t\t\t} catch {\n\t\t\t\t\t// A store read/write failure falls back to a fresh count of 1, which keeps the gate\n\t\t\t\t\t// proposal-first (never spuriously auto-applies) rather than crashing the pass.\n\t\t\t\t\tobservations = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst explicitUserMemoryWrite =\n\t\t\t\tinput.explicitUserMemoryInstruction === true &&\n\t\t\t\t(write.kind === \"memory_add\" || write.kind === \"memory_replace\");\n\t\t\tconst decision: LearningDecision = explicitUserMemoryWrite\n\t\t\t\t? {\n\t\t\t\t\t\tkind: \"apply\",\n\t\t\t\t\t\treasonCode: \"explicit_user_memory_instruction\",\n\t\t\t\t\t\tconfidence: 100,\n\t\t\t\t\t\tsummary: proposal.summary,\n\t\t\t\t\t\trequiresApproval: false,\n\t\t\t\t\t}\n\t\t\t\t: policy.enabled\n\t\t\t\t\t? evaluateLearningDecision({\n\t\t\t\t\t\t\tproposal,\n\t\t\t\t\t\t\tconfidence: policy.reflectionSourceConfidence,\n\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t// A replace/remove supersedes an existing durable fact — the reflection engine's\n\t\t\t\t\t\t\t// confront-before-write conflict signal — so it routes through approval instead of\n\t\t\t\t\t\t\t// silently overwriting prior memory. Additive writes contradict nothing.\n\t\t\t\t\t\t\tcontradictions: contradictionsForReflectionWrite(write),\n\t\t\t\t\t\t\tsettings: {\n\t\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\t\tautoApplyEnabled: policy.autoApplyEnabled,\n\t\t\t\t\t\t\t\tconfidenceThreshold: policy.confidenceThreshold,\n\t\t\t\t\t\t\t\tminObservations: policy.minObservations,\n\t\t\t\t\t\t\t\tallowedAutoApplyLayers: policy.allowedAutoApplyLayers,\n\t\t\t\t\t\t\t\trequireRollbackPlan: policy.requireRollbackPlan,\n\t\t\t\t\t\t\t\tautoApplySupersessions: policy.autoApplySupersessions,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t})\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tkind: \"apply\",\n\t\t\t\t\t\t\treasonCode: \"learning_policy_disabled_legacy_apply\",\n\t\t\t\t\t\t\tconfidence: 0,\n\t\t\t\t\t\t\tsummary: proposal.summary,\n\t\t\t\t\t\t\trequiresApproval: false,\n\t\t\t\t\t\t};\n\n\t\t\tthis.deps.saveLearningDecisionSnapshot(decision);\n\t\t\t// G3: learning-gate outcome. Codes/numbers only — never the proposal summary/memory text.\n\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.learningDecision,\n\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\tpayload: {\n\t\t\t\t\tkind: decision.kind,\n\t\t\t\t\treasonCode: decision.reasonCode,\n\t\t\t\t\tlayer: proposal.layer,\n\t\t\t\t\tconfidence: decision.confidence,\n\t\t\t\t\trequiresApproval: decision.requiresApproval,\n\t\t\t\t},\n\t\t\t});\n\t\t\t// G8: a proposal that needs human sign-off is an approval REQUEST. Codes/layer only —\n\t\t\t// never the proposal summary/memory text (those live only in the audit snapshot).\n\t\t\tif (decision.requiresApproval) {\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.approvalRequest,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tkind: decision.kind,\n\t\t\t\t\t\treasonCode: decision.reasonCode,\n\t\t\t\t\t\tlayer: proposal.layer,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\t// An automatic skill promotion the gate would otherwise apply must still clear the same\n\t\t\t// skill_audit overlap check the model-invoked `skillify` tool enforces — otherwise reflection\n\t\t\t// can silently write a near-duplicate SKILL.md. A non-overlapping skill is unaffected\n\t\t\t// (skillPromotionBlock stays undefined) and promotes exactly as before.\n\t\t\tconst skillPromotionBlock =\n\t\t\t\twrite.kind === \"promote_skill\" && decision.kind === \"apply\"\n\t\t\t\t\t? this._checkSkillPromotionOverlap(write)\n\t\t\t\t\t: undefined;\n\n\t\t\t// The gate's decision and the write's actual outcome are two different questions: the memory\n\t\t\t// tool can refuse a write (budget exceeded, drift, threat) via details.success:false without\n\t\t\t// throwing. Capture that outcome instead of assuming \"decision.kind === apply\" means it landed\n\t\t\t// — otherwise a refused write leaves a phantom \"apply\" audit whose rollback later fails\n\t\t\t// not-found (or, worse, misfires against whatever now occupies that text).\n\t\t\tconst applied =\n\t\t\t\tdecision.kind === \"apply\" && !skillPromotionBlock ? await this._applyReflectionWrite(write, signal) : false;\n\t\t\tconst writeFailed = decision.kind === \"apply\" && !skillPromotionBlock && !applied;\n\t\t\tif (decision.kind !== \"no-op\") {\n\t\t\t\tauditSequence += 1;\n\t\t\t\tappendLearningAuditSnapshot(this.deps.getSessionManager(), {\n\t\t\t\t\tid: `audit-${auditSequence}`,\n\t\t\t\t\tproposalId,\n\t\t\t\t\tlayer: proposal.layer,\n\t\t\t\t\taction: skillPromotionBlock\n\t\t\t\t\t\t? \"propose\"\n\t\t\t\t\t\t: writeFailed\n\t\t\t\t\t\t\t? \"apply_failed\"\n\t\t\t\t\t\t\t: decision.kind === \"apply\"\n\t\t\t\t\t\t\t\t? \"apply\"\n\t\t\t\t\t\t\t\t: \"propose\",\n\t\t\t\t\tsummary: skillPromotionBlock ? `${proposal.summary} — ${skillPromotionBlock.note}` : proposal.summary,\n\t\t\t\t\treasonCode: skillPromotionBlock\n\t\t\t\t\t\t? skillPromotionBlock.reasonCode\n\t\t\t\t\t\t: writeFailed\n\t\t\t\t\t\t\t? APPLY_WRITE_REFUSED_REASON_CODE\n\t\t\t\t\t\t\t: decision.reasonCode,\n\t\t\t\t\tdecision,\n\t\t\t\t\t// No rollback plan on a failed apply or a held/proposed promotion — nothing durable\n\t\t\t\t\t// landed in either case, so there is nothing to undo.\n\t\t\t\t\trollback: skillPromotionBlock || writeFailed ? undefined : rollback,\n\t\t\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Account the reflection's spend so it surfaces in the footer roll-up (net-token visibility).\n\t\t// Idempotent on reportId so a retried/duplicated pass cannot double-count.\n\t\tif (result.usage.cost.total > 0 || result.usage.totalTokens > 0) {\n\t\t\tthis.deps.addSpawnedUsage(result.usage, { label: \"reflection\", reportId: input.reportId });\n\t\t}\n\t\treturn result;\n\t}\n\n\tgetLearningAuditRecords(): LearningAuditRecord[] {\n\t\treturn getLearningAuditSnapshots(this.deps.getSessionManager().getEntries());\n\t}\n\n\t/**\n\t * Roll back one applied durable learning change by executing the inverse operation recorded in\n\t * its audit record (memory ops run through the same bundled memory-tool path as the original\n\t * apply; promoted skills are archived). Appends a linked \"rollback\" audit record on success so\n\t * the change history stays complete and a change cannot be rolled back twice.\n\t */\n\tasync rollbackLearningWrite(auditId: string): Promise<{ ok: boolean; reason: string }> {\n\t\tif (this.deps.isDisposed()) return { ok: false, reason: \"session_disposed\" };\n\n\t\tconst audits = this.getLearningAuditRecords();\n\t\tconst audit = audits.find((record) => record.id === auditId);\n\t\tif (!audit) return { ok: false, reason: \"audit_not_found\" };\n\t\tif (audit.action !== \"apply\") return { ok: false, reason: \"not_an_applied_change\" };\n\t\tif (audits.some((record) => record.action === \"rollback\" && record.rollbackOf === auditId)) {\n\t\t\treturn { ok: false, reason: \"already_rolled_back\" };\n\t\t}\n\t\tconst rollback = audit.rollback;\n\t\tif (!rollback) return { ok: false, reason: \"no_rollback_plan\" };\n\n\t\t// Every inverse must be VERIFIED-applied before the rollback audit is appended: a silently\n\t\t// failed inverse that still recorded \"rollback\" would permanently self-lock the change\n\t\t// behind already_rolled_back while the durable write is in fact still live.\n\t\tswitch (rollback.kind) {\n\t\t\tcase \"memory_remove\": {\n\t\t\t\tif (!rollback.target) return { ok: false, reason: \"missing_rollback_target\" };\n\t\t\t\tif (!(await this._applyReflectionWrite({ kind: \"memory_remove\", target: rollback.target }))) {\n\t\t\t\t\treturn { ok: false, reason: \"rollback_apply_failed\" };\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"memory_restore\": {\n\t\t\t\tif (!rollback.target || rollback.previous === undefined) {\n\t\t\t\t\treturn { ok: false, reason: \"missing_rollback_target\" };\n\t\t\t\t}\n\t\t\t\tconst applied = await this._applyReflectionWrite({\n\t\t\t\t\tkind: \"memory_replace\",\n\t\t\t\t\ttarget: rollback.target,\n\t\t\t\t\ttext: rollback.previous,\n\t\t\t\t});\n\t\t\t\tif (!applied) return { ok: false, reason: \"rollback_apply_failed\" };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"memory_add\": {\n\t\t\t\tif (rollback.previous === undefined) return { ok: false, reason: \"missing_rollback_target\" };\n\t\t\t\tconst applied = await this._applyReflectionWrite({\n\t\t\t\t\tkind: \"memory_add\",\n\t\t\t\t\tsection: \"MEMORY\",\n\t\t\t\t\ttext: rollback.previous,\n\t\t\t\t});\n\t\t\t\tif (!applied) return { ok: false, reason: \"rollback_apply_failed\" };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"archive_skill\": {\n\t\t\t\tif (!rollback.target) return { ok: false, reason: \"missing_rollback_target\" };\n\t\t\t\tif (!this.deps.archivePromotedSkill(rollback.target)) {\n\t\t\t\t\treturn { ok: false, reason: \"skill_archive_failed\" };\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tappendLearningAuditSnapshot(this.deps.getSessionManager(), {\n\t\t\tid: `${audit.id}-rollback`,\n\t\t\tproposalId: audit.proposalId,\n\t\t\tlayer: audit.layer,\n\t\t\taction: \"rollback\",\n\t\t\tsummary: `Rolled back: ${audit.summary}`,\n\t\t\treasonCode: \"user_requested_rollback\",\n\t\t\tdecision: audit.decision,\n\t\t\trollbackOf: audit.id,\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t});\n\t\treturn { ok: true, reason: \"rollback_applied\" };\n\t}\n\n\t/**\n\t * Apply one reflection write through the bundled `memory` tool. `memory_replace`/`memory_remove`\n\t * don't carry a target file, so we try MEMORY.md first and fall back to USER.md when the substring\n\t * isn't found there. Never throws (reflection must never break a turn); returns whether the write\n\t * actually applied so callers that MUST know — rollback's once-only accounting — can react instead\n\t * of recording a success that never happened.\n\t */\n\tprivate async _applyReflectionWrite(write: ReflectionWrite, signal?: AbortSignal): Promise<boolean> {\n\t\t// R7 memory-to-behavior: a recurring procedure is compiled into an executable skill file rather\n\t\t// than stored as a flat fact. Written under the agent skills dir so it loads like any user skill.\n\t\tif (write.kind === \"promote_skill\") {\n\t\t\treturn this._promoteReflectionSkill(write.name, write.description, write.body);\n\t\t}\n\n\t\ttype MemResult = { details?: { success?: boolean; error?: string } };\n\t\ttype MemExec = (\n\t\t\ttoolCallId: string,\n\t\t\tparams: { action: string; target: string; content?: string; oldContent?: string },\n\t\t\tsignal: AbortSignal | undefined,\n\t\t\tonUpdate: undefined,\n\t\t\tctx: undefined,\n\t\t) => Promise<MemResult>;\n\t\tconst memTool = this.deps\n\t\t\t.getMemoryManager()\n\t\t\t.getToolDefinitions()\n\t\t\t.find((t) => t.name === \"memory\");\n\t\tconst exec = memTool?.execute as unknown as MemExec | undefined;\n\t\tif (!exec) return false;\n\n\t\tconst run = (params: Parameters<MemExec>[1]) => exec(\"reflection\", params, signal, undefined, undefined);\n\n\t\tif (write.kind === \"memory_add\") {\n\t\t\ttry {\n\t\t\t\tconst res = await run({\n\t\t\t\t\taction: \"add\",\n\t\t\t\t\ttarget: write.section === \"USER\" ? \"user\" : \"memory\",\n\t\t\t\t\tcontent: write.text,\n\t\t\t\t});\n\t\t\t\treturn res?.details?.success === true;\n\t\t\t} catch {\n\t\t\t\t// best-effort; reflection writes must never throw into the turn loop\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t// replace / remove carry no target file — try MEMORY.md, then USER.md. The memory tool reports\n\t\t// outcomes via `details.success` (it catches its own errors rather than throwing). Only a\n\t\t// genuine \"not found in the file\" justifies trying the other file; a real failure for a file\n\t\t// (budget exceeded / drift) must NOT fall through and mutate the wrong target.\n\t\tfor (const target of [\"memory\", \"user\"] as const) {\n\t\t\ttry {\n\t\t\t\tconst params =\n\t\t\t\t\twrite.kind === \"memory_replace\"\n\t\t\t\t\t\t? { action: \"replace\", target, oldContent: write.target, content: write.text }\n\t\t\t\t\t\t: { action: \"remove\", target, oldContent: write.target };\n\t\t\t\tconst res = await run(params);\n\t\t\t\tif (res?.details?.success === true) return true; // applied\n\t\t\t\tif (!/not found/i.test(String(res?.details?.error ?? \"\"))) return false; // real failure — don't misapply\n\t\t\t\t// substring simply absent from this file — try the next target\n\t\t\t} catch {\n\t\t\t\t// defensive: if the tool ever does throw, try the next target\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * The same skill_audit overlap check the model-invoked `skillify` tool enforces\n\t * (tools/skillify.ts → tools/skill-audit.ts's `runSkillAudit`), run before an AUTOMATIC promotion\n\t * so the reflection engine can never silently write a near-duplicate SKILL.md. Reuses the audit\n\t * seam unchanged (never duplicated) against the same already-loaded skills universe skillify\n\t * compares a draft against. Returns a block reason when the draft overlaps an existing skill above\n\t * the audit's own similarity threshold, or when the audit itself fails (the promotion is held, not\n\t * written unaudited); undefined when clear to promote. Never throws — mirrors every other\n\t * best-effort check in this file.\n\t */\n\tprivate _checkSkillPromotionOverlap(write: {\n\t\tname: string;\n\t\tdescription: string;\n\t\tbody: string;\n\t}): { reasonCode: string; note: string } | undefined {\n\t\ttry {\n\t\t\tconst cwd = this.deps.getCwd?.() ?? process.cwd();\n\t\t\tconst audit = runSkillAudit(cwd, write);\n\t\t\tconst overlap = audit.nearDuplicates.find((d) => d.a === \"[draft]\" || d.b === \"[draft]\");\n\t\t\tif (!overlap) return undefined;\n\t\t\tconst otherPath = overlap.a === \"[draft]\" ? overlap.b : overlap.a;\n\t\t\t// Every skill file is named \"SKILL.md\" — unlike skillify's own display formatter (which takes\n\t\t\t// the path's last segment and always shows that literal filename), look up the declared\n\t\t\t// frontmatter name so the proposal actually names the skill it overlaps with.\n\t\t\tconst otherName = audit.skills.find((s) => s.path === otherPath)?.name ?? otherPath;\n\t\t\treturn {\n\t\t\t\treasonCode: SKILL_OVERLAP_CONSOLIDATION_REASON_CODE,\n\t\t\t\tnote: `overlaps existing skill \"${otherName}\" (${(overlap.similarity * 100).toFixed(0)}% similar) — consolidation proposed instead of a duplicate write`,\n\t\t\t};\n\t\t} catch {\n\t\t\t// Bounded, observable degradation via the promote path's existing error-reporting shape: an\n\t\t\t// audit failure must never throw into the reflection pass, but it also must not silently\n\t\t\t// fall through to an unaudited write — hold the promotion and record why.\n\t\t\treturn {\n\t\t\t\treasonCode: SKILL_AUDIT_UNAVAILABLE_REASON_CODE,\n\t\t\t\tnote: \"skill overlap audit failed; promotion held rather than written unaudited\",\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * R7: write a reflection-promoted skill as `<agentDir>/skills/<name>/SKILL.md` so it loads like any\n\t * user skill. Best-effort; never clobbers an existing (hand-authored) skill of the same name. The\n\t * overlap audit runs at the call site in {@link runReflectionPass} — a write only reaches here\n\t * once the draft has already cleared it.\n\t */\n\tprivate _promoteReflectionSkill(rawName: string, description: string, body: string): boolean {\n\t\tconst name = rawName\n\t\t\t.trim()\n\t\t\t.toLowerCase()\n\t\t\t.replace(/[^a-z0-9-]+/g, \"-\")\n\t\t\t.replace(/^-+|-+$/g, \"\")\n\t\t\t.slice(0, 64);\n\t\tif (!name || !body.trim()) return false;\n\t\ttry {\n\t\t\tconst dir = join(this.deps.getAgentDir(), \"skills\", name);\n\t\t\tconst file = join(dir, \"SKILL.md\");\n\t\t\tif (existsSync(file)) return false; // do not overwrite an existing skill\n\t\t\tmkdirSync(dir, { recursive: true });\n\t\t\tconst safeDescription = description.replace(/[\\r\\n]+/g, \" \").trim();\n\t\t\t// `promoted: true` marks this as reflection-generated so the curator (#32) can lifecycle-manage\n\t\t\t// it (archive/consolidate) WITHOUT ever touching hand-authored user skills.\n\t\t\tconst content = `---\\nname: ${name}\\ndescription: ${safeDescription}\\npromoted: true\\n---\\n\\n<!-- Auto-generated by the reflection engine (R7 memory-to-behavior). Review and refine. -->\\n\\n${body.trim()}\\n`;\n\t\t\twriteFileSync(file, content, \"utf-8\");\n\t\t\treturn true;\n\t\t} catch {\n\t\t\t// promotion must never break a turn\n\t\t\treturn false;\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"reflection-controller.js","sourceRoot":"","sources":["../../src/core/reflection-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,YAAY,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AAG/F,OAAO,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AAUrE,OAAO,EACN,sBAAsB,EACtB,0BAA0B,GAG1B,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,8BAA8B,EAA+B,MAAM,gCAAgC,CAAC;AAC7G,OAAO,EACN,+BAA+B,EAC/B,2BAA2B,EAC3B,gCAAgC,EAChC,yBAAyB,EAEzB,2BAA2B,EAC3B,8BAA8B,GAC9B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,EAEN,YAAY,EACZ,gBAAgB,GAGhB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACN,qBAAqB,EACrB,2BAA2B,EAE3B,yBAAyB,GACzB,MAAM,wCAAwC,CAAC;AAGhD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAE5D,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAiDvD,+FAA+F;AAC/F,wGAAwG;AACxG,MAAM,CAAC,MAAM,uCA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IAAI,CAAC,IAAI,EAAE;YAAE,OAAO,KAAK,CAAC;QACxC,IAAI,CAAC;YACJ,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC;YAC1D,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC;YACnC,IAAI,UAAU,CAAC,IAAI,CAAC;gBAAE,OAAO,KAAK,CAAC,CAAC,qCAAqC;YACzE,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YACpC,MAAM,eAAe,GAAG,WAAW,CAAC,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;YACpE,gGAAgG;YAChG,4EAA4E;YAC5E,MAAM,OAAO,GAAG,cAAc,IAAI,kBAAkB,eAAe,4HAA4H,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC;YAC/M,aAAa,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;YACtC,OAAO,IAAI,CAAC;QACb,CAAC;QAAC,MAAM,CAAC;YACR,oCAAoC;YACpC,OAAO,KAAK,CAAC;QACd,CAAC;IACF,CAAC;CACD","sourcesContent":["/**\n * Native reflection + learning-write controller.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the end-of-loop reflection\n * pass (R2), the isolated-completion primitive it runs on, and the learning-apply/rollback path that\n * turns reflection writes into gated, audited durable memory/skill changes. It mutates NO session\n * fields — every durable effect goes through the bundled memory tool, the session log (via deps), or\n * the skills dir; the whole pass is best-effort and never throws into the turn loop. Reads live\n * session state (model/agent/registry/memory/settings) through narrow deps accessors rather than the\n * whole AgentSession.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Agent } from \"@caupulican/pi-agent-core/agent\";\nimport { runAgentLoop, startAgentProviderRequest } from \"@caupulican/pi-agent-core/agent-loop\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/session\";\nimport type { AgentContext, AgentLoopConfig, AgentMessage, ThinkingLevel } from \"@caupulican/pi-agent-core/types\";\nimport { resolveModelThinkingLevel } from \"@caupulican/pi-ai/models\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\n\tUsage,\n} from \"@caupulican/pi-ai/types\";\nimport {\n\tcomputeLaneAffinityKey,\n\tDEFAULT_ISOLATED_LANE_KIND,\n\ttype IsolatedCompletionOptions,\n\ttype IsolatedCompletionResult,\n} from \"./agent-session-contracts.ts\";\nimport type { LearningDecision } from \"./autonomy/contracts.ts\";\nimport { AUTONOMY_TELEMETRY_EVENT_TYPES, type AutonomyTelemetryEvent } from \"./autonomy/telemetry-events.ts\";\nimport {\n\tAPPLY_WRITE_REFUSED_REASON_CODE,\n\tappendLearningAuditSnapshot,\n\tcontradictionsForReflectionWrite,\n\tgetLearningAuditSnapshots,\n\ttype LearningAuditRecord,\n\tproposalFromReflectionWrite,\n\trollbackPlanForReflectionWrite,\n} from \"./learning/learning-audit.ts\";\nimport { evaluateLearningDecision } from \"./learning/learning-gate.ts\";\nimport { ObservationStore, observationKey } from \"./learning/observation-store.ts\";\nimport {\n\ttype DemandSignals,\n\tdecideDemand,\n\tReflectionEngine,\n\ttype ReflectionResult,\n\ttype ReflectionWrite,\n} from \"./learning/reflection-engine.ts\";\nimport {\n\tanalyzeReflectionTurn,\n\tboundReflectionSemanticText,\n\ttype ReflectionTurnAnalysis,\n\treflectionTriggerPriority,\n} from \"./learning/reflection-turn-analysis.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { registerInFlightWork } from \"./reload-blockers.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { runSkillAudit } from \"./tools/skill-audit.ts\";\n\nexport interface ReflectionControllerDeps {\n\t/** Current session model (fallback for an isolated call that omits its own model). */\n\tgetModel(): Model<Api> | undefined;\n\t/** The underlying agent — its `streamFn` runs the isolated completion. */\n\tgetAgent(): Agent;\n\t/** True when the session's stream fn is the raw `streamSimple` provider (auth must be injected). */\n\tisRawStreamSimple(): boolean;\n\t/** Model registry for API-key/header resolution on the raw-provider path. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** Memory subsystem — the bundled `memory` tool applies durable writes; fresh block feeds reflection. */\n\tgetMemoryManager(): MemoryManager;\n\t/** Settings — the learning-apply policy (gate thresholds, auto-apply layers) is read here. */\n\tgetSettingsManager(): SettingsManager;\n\t/** Session log — audit snapshots and learning-audit reads go through this. */\n\tgetSessionManager(): SessionManager;\n\t/** Agent dir — reflection-promoted skills are written under `<agentDir>/skills/`. */\n\tgetAgentDir(): string;\n\t/** Child sessions must not learn — the pass returns null for them. */\n\tisChildSession(): boolean;\n\t/** Disposal short-circuits: no completion, no writes against a dead session. */\n\tisDisposed(): boolean;\n\t/** Session-lifetime abort signal — aborts an in-flight reflection completion on dispose. */\n\tgetReflectionSignal(): AbortSignal;\n\t/** Archive a promoted skill (rollback of a `promote_skill` write). */\n\tarchivePromotedSkill(name: string): boolean;\n\t/** G3/G8 autonomy telemetry sink for learning-gate outcomes and approval requests. */\n\temitAutonomyTelemetry(event: AutonomyTelemetryEvent): void;\n\t/** Account the reflection pass's token spend into the cost roll-up (idempotent on reportId). */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts?: { label?: string; sourceSessionId?: string; reportId?: string },\n\t): string | undefined;\n\t/** Persist a learning-gate decision snapshot to the session log. */\n\tsaveLearningDecisionSnapshot(decision: LearningDecision): string;\n\t/** Resolve text-tool fallback for the selected isolated model, not the foreground model. */\n\tresolveTextToolCallProtocol(model: Model<Api>): SimpleStreamOptions[\"textToolCallProtocol\"];\n\t/** Ensure a managed-local model is running/resident before any isolated lane calls it. */\n\tensureModelReady(model: Model<Api>): Promise<void>;\n\t/**\n\t * Session working directory — feeds the skill-overlap audit's project-local skill discovery, the\n\t * same `cwd` the model-invoked `skillify`/`skill_audit` tools already receive (tools/index.ts).\n\t * Optional so a host that has not wired it yet still resolves (falls back to `process.cwd()`,\n\t * mirroring the existing profile-resolution fallback in settings-manager.ts).\n\t */\n\tgetCwd?(): string;\n}\n\n// reasonCode when an automatic skill promotion is blocked by an overlap with an existing skill\n// (skill_audit's similarity threshold) and routed to a consolidation proposal instead of a blind write.\nexport const SKILL_OVERLAP_CONSOLIDATION_REASON_CODE = \"skill_overlap_consolidation_proposed\";\n// reasonCode when the overlap audit itself fails — the promotion is held (not written unaudited)\n// rather than silently skipping the check.\nexport const SKILL_AUDIT_UNAVAILABLE_REASON_CODE = \"skill_audit_unavailable\";\n\nconst REFLECTION_MIN_INTERVAL_MS = 45_000;\nconst REFLECTION_PENDING_MAX_CHARS = 12_000;\nconst REFLECTION_DIGEST_HISTORY_SIZE = 64;\n\nexport class ReflectionController {\n\tprivate readonly deps: ReflectionControllerDeps;\n\tprivate readonly pendingTurns: Array<{ analysis: ReflectionTurnAnalysis; contextHeadroomPct: number }> = [];\n\tprivate readonly scheduledDigests = new Set<string>();\n\tprivate activeScheduledPass: Promise<void> | undefined;\n\tprivate scheduledTimer: NodeJS.Timeout | undefined;\n\tprivate lastScheduledPassAt = 0;\n\n\tconstructor(deps: ReflectionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** Analyze once, schedule bounded background reflection when warranted, and return filtered turn text for sync hooks. */\n\tscheduleFromTurn(messages: AgentMessage[], contextHeadroomPct: number): ReflectionTurnAnalysis {\n\t\tconst settings = this.deps.getSettingsManager().getAutoLearnSettings();\n\t\tconst analysis = analyzeReflectionTurn(messages, settings.complexTaskToolCalls ?? 12);\n\t\tconst enabled =\n\t\t\tsettings.enabled !== false &&\n\t\t\tsettings.reflectionReview !== false &&\n\t\t\tprocess.env.PI_NATIVE_REFLECTION !== \"0\" &&\n\t\t\tprocess.env.PI_AUTO_LEARN_CHILD !== \"1\" &&\n\t\t\t!this.deps.isChildSession() &&\n\t\t\t!this.deps.isDisposed();\n\t\tif (!enabled || analysis.trigger === \"none\" || this.scheduledDigests.has(analysis.digest)) return analysis;\n\n\t\tthis.scheduledDigests.add(analysis.digest);\n\t\twhile (this.scheduledDigests.size > REFLECTION_DIGEST_HISTORY_SIZE) {\n\t\t\tconst oldest = this.scheduledDigests.values().next().value;\n\t\t\tif (typeof oldest !== \"string\") break;\n\t\t\tthis.scheduledDigests.delete(oldest);\n\t\t}\n\t\tthis.pendingTurns.push({ analysis, contextHeadroomPct });\n\t\tlet pendingChars = this.pendingTurns.reduce((total, turn) => total + turn.analysis.recentTurnText.length, 0);\n\t\twhile (this.pendingTurns.length > 1 && pendingChars > REFLECTION_PENDING_MAX_CHARS) {\n\t\t\tpendingChars -= this.pendingTurns.shift()?.analysis.recentTurnText.length ?? 0;\n\t\t}\n\t\tthis.schedulePendingPass();\n\t\treturn analysis;\n\t}\n\n\tprivate schedulePendingPass(): void {\n\t\tif (this.activeScheduledPass || this.scheduledTimer || this.pendingTurns.length === 0 || this.deps.isDisposed()) {\n\t\t\treturn;\n\t\t}\n\t\tconst delay = Math.max(0, REFLECTION_MIN_INTERVAL_MS - (Date.now() - this.lastScheduledPassAt));\n\t\tif (delay > 0) {\n\t\t\tthis.scheduledTimer = setTimeout(() => {\n\t\t\t\tthis.scheduledTimer = undefined;\n\t\t\t\tthis.startPendingPass();\n\t\t\t}, delay);\n\t\t\tthis.scheduledTimer.unref?.();\n\t\t\treturn;\n\t\t}\n\t\tthis.startPendingPass();\n\t}\n\n\tprivate startPendingPass(): void {\n\t\tif (this.activeScheduledPass || this.pendingTurns.length === 0 || this.deps.isDisposed()) return;\n\t\tconst turns = this.pendingTurns.splice(0);\n\t\tconst trigger = turns.reduce<DemandSignals[\"trigger\"]>(\n\t\t\t(selected, turn) =>\n\t\t\t\treflectionTriggerPriority(turn.analysis.trigger) > reflectionTriggerPriority(selected)\n\t\t\t\t\t? turn.analysis.trigger\n\t\t\t\t\t: selected,\n\t\t\t\"none\",\n\t\t);\n\t\tconst recentTurnText = boundReflectionSemanticText(\n\t\t\tturns.map((turn) => turn.analysis.recentTurnText).join(\"\\n---\\n\"),\n\t\t\tREFLECTION_PENDING_MAX_CHARS,\n\t\t);\n\t\tconst reportDigest = createHash(\"sha256\")\n\t\t\t.update(turns.map((turn) => turn.analysis.digest).join(\"\\0\"))\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 24);\n\t\tconst settings = this.deps.getSettingsManager().getAutoLearnSettings();\n\t\tlet model: Model<Api> | undefined;\n\t\tif (settings.model && settings.model !== \"active\") {\n\t\t\tconst resolved = resolveCliModel({ cliModel: settings.model, modelRegistry: this.deps.getModelRegistry() });\n\t\t\tif (resolved.model && this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) model = resolved.model;\n\t\t}\n\t\tconst toolCallCount = turns.reduce((total, turn) => total + turn.analysis.toolCallCount, 0);\n\t\tconst contextHeadroomPct = Math.min(...turns.map((turn) => turn.contextHeadroomPct));\n\t\tthis.lastScheduledPassAt = Date.now();\n\t\tthis.activeScheduledPass = (async () => {\n\t\t\ttry {\n\t\t\t\tawait this.runReflectionPass({\n\t\t\t\t\tsignals: {\n\t\t\t\t\t\ttrigger,\n\t\t\t\t\t\ttoolCallCount,\n\t\t\t\t\t\thadCorrection: turns.some((turn) => turn.analysis.hadCorrection),\n\t\t\t\t\t\tcontextHeadroomPct,\n\t\t\t\t\t\tusefulLately: 0,\n\t\t\t\t\t},\n\t\t\t\t\trecentTurnText,\n\t\t\t\t\treportId: `reflection:${reportDigest}`,\n\t\t\t\t\tmodel,\n\t\t\t\t\tthinkingLevel: settings.thinkingLevel ?? \"low\",\n\t\t\t\t\texplicitUserMemoryInstruction: turns.every((turn) => turn.analysis.explicitUserMemoryInstruction),\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\t// Best-effort background learning must never disrupt the foreground turn.\n\t\t\t} finally {\n\t\t\t\tthis.activeScheduledPass = undefined;\n\t\t\t\tthis.schedulePendingPass();\n\t\t\t}\n\t\t})();\n\t}\n\n\tcancelScheduled(): void {\n\t\tif (this.scheduledTimer) clearTimeout(this.scheduledTimer);\n\t\tthis.scheduledTimer = undefined;\n\t\tthis.pendingTurns.length = 0;\n\t}\n\n\tasync waitForActivePass(): Promise<void> {\n\t\twhile (this.activeScheduledPass) await this.activeScheduledPass;\n\t}\n\n\t/**\n\t * Run an LLM completion fully ISOLATED from the main session — the load-bearing primitive for\n\t * reflection and bounded child lanes (adaptive-agent design §6c/§7).\n\t *\n\t * Isolation invariants (audited by codex): builds fresh context (no main history), defaults to no\n\t * tools, and passes **no real `sessionId`** — only a deterministic SYNTHETIC cache-affinity key\n\t * (see {@link computeLaneAffinityKey}) derived from `(laneKind, model, systemPrompt)`, which can never\n\t * equal or embed the real session id. A tool-enabled call receives only caller-owned tools and hooks,\n\t * and applies a turn bound only when its owner explicitly supplies one. It cannot mutate `agent.state.messages`, append session entries, or touch the\n\t * foreground tool registry. Mirrors `generateSummary()`'s one-shot mechanics otherwise.\n\t *\n\t * Returns the result even on an error/aborted stop reason (callers — e.g. a background reflection\n\t * microtask — decide whether to act); it does not throw on a model-level error.\n\t */\n\tasync runIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult> {\n\t\tif (opts.maxTurns !== undefined && (!Number.isSafeInteger(opts.maxTurns) || opts.maxTurns <= 0)) {\n\t\t\tthrow new Error(\"runIsolatedCompletion: maxTurns must be a positive safe integer when provided\");\n\t\t}\n\t\tconst model = opts.model ?? this.deps.getModel();\n\t\tif (!model) {\n\t\t\tthrow new Error(\"runIsolatedCompletion: no model available\");\n\t\t}\n\t\tawait this.deps.ensureModelReady(model);\n\t\tconst thinkingLevel = resolveModelThinkingLevel(model, opts.thinkingLevel, \"off\");\n\n\t\t// Registered for the full isolated-completion call (one-shot or child-loop) so the\n\t\t// reload gate waits it out — this is the SINGLE choke point every isolated completion in the\n\t\t// codebase runs through (reflection, research/worker/fitness lanes, context-pipeline curation,\n\t\t// model-router judge calls). registerInFlightWork is a pure sync map op (cannot throw), so\n\t\t// placing it as the last statement before `try` still guarantees the matching finally always\n\t\t// runs, on every return path below and on any thrown error.\n\t\tconst deregisterInFlight = registerInFlightWork(\n\t\t\tthis.deps.getAgentDir(),\n\t\t\t\"isolated-completion\",\n\t\t\topts.laneKind ?? DEFAULT_ISOLATED_LANE_KIND,\n\t\t);\n\t\ttry {\n\t\t\t// Fresh, isolated context: explicit messages, caller-owned tools only, nothing from the main session.\n\t\t\tconst history = opts.history ?? [];\n\t\t\tconst context: AgentContext = {\n\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\tmessages: [...history, ...opts.messages],\n\t\t\t\ttools: opts.tools ?? [],\n\t\t\t};\n\n\t\t\t// Isolate the prompt cache from the main session by DELIBERATELY never sending the real\n\t\t\t// sessionId. In its place, a deterministic SYNTHETIC affinity key lets providers with\n\t\t\t// session-affinity headers / prompt_cache_key route repeat calls from the SAME lane (same\n\t\t\t// laneKind+model+systemPrompt) to the same cache-warm backend, without entangling this call\n\t\t\t// with — or leaking any identity of — the main session.\n\t\t\tconst affinityKey = computeLaneAffinityKey(\n\t\t\t\topts.laneKind ?? DEFAULT_ISOLATED_LANE_KIND,\n\t\t\t\tmodel,\n\t\t\t\topts.systemPrompt,\n\t\t\t);\n\t\t\tconst options: SimpleStreamOptions = {\n\t\t\t\tmaxTokens: opts.maxTokens,\n\t\t\t\tsignal: opts.signal,\n\t\t\t\tinteractionMode: \"background\",\n\t\t\t\tcacheRetention: opts.cacheRetention,\n\t\t\t\treasoning: thinkingLevel,\n\t\t\t\tsessionId: affinityKey,\n\t\t\t};\n\n\t\t\t// When streamFn is the raw streamSimple (e.g. in tests), auth must be injected explicitly.\n\t\t\t// Throw only when auth genuinely fails — providers that authenticate without an API key\n\t\t\t// (OAuth, local no-key) legitimately return ok with an undefined apiKey.\n\t\t\tif (this.deps.isRawStreamSimple()) {\n\t\t\t\tconst auth = await this.deps.getModelRegistry().getApiKeyAndHeaders(model);\n\t\t\t\tif (!auth.ok) {\n\t\t\t\t\tthrow new Error(auth.error);\n\t\t\t\t}\n\t\t\t\toptions.apiKey = auth.apiKey;\n\t\t\t\toptions.headers = auth.headers;\n\t\t\t}\n\t\t\tconst agent = this.deps.getAgent();\n\t\t\tconst foregroundModel = agent.state.model;\n\t\t\tconst usesForegroundModel = foregroundModel?.provider === model.provider && foregroundModel.id === model.id;\n\t\t\tconst textToolCallProtocol = this.deps.resolveTextToolCallProtocol(model);\n\t\t\tconst maxTurns = opts.maxTurns;\n\t\t\tlet completedTurns = 0;\n\t\t\tconst loopConfig: AgentLoopConfig = {\n\t\t\t\tmodel,\n\t\t\t\tinteractionMode: \"background\",\n\t\t\t\tmaxTokens: opts.maxTokens,\n\t\t\t\tcacheRetention: opts.cacheRetention,\n\t\t\t\treasoning: thinkingLevel,\n\t\t\t\t// Same synthetic per-lane affinity key as the one-shot path above — never the real sessionId.\n\t\t\t\tsessionId: affinityKey,\n\t\t\t\t...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n\t\t\t\t...(options.headers !== undefined ? { headers: options.headers } : {}),\n\t\t\t\tgetApiKey: agent.getApiKey,\n\t\t\t\tresolveRequestReasoning: agent.resolveRequestReasoning,\n\t\t\t\ttemperature: textToolCallProtocol ? 0 : undefined,\n\t\t\t\ttextToolCallProtocol,\n\t\t\t\tonTextToolProtocolParse: usesForegroundModel ? agent.onTextToolProtocolParse : undefined,\n\t\t\t\ttransport: agent.transport,\n\t\t\t\tthinkingBudgets: agent.thinkingBudgets,\n\t\t\t\tmaxRetryDelayMs: agent.maxRetryDelayMs,\n\t\t\t\t// This remains independent from an owner-provided turn budget: it stops only repeated\n\t\t\t\t// identical tool calls, so legitimate long-running work can continue until completion.\n\t\t\t\tmaxStallTurns: agent.maxStallTurns,\n\t\t\t\tonRunawayStop: usesForegroundModel ? agent.onRunawayStop : undefined,\n\t\t\t\ttoolExecution: \"sequential\",\n\t\t\t\ttoolArgumentTeachEnabled: agent.toolArgumentTeachEnabled,\n\t\t\t\tonToolArgumentValidation: usesForegroundModel ? agent.onToolArgumentValidation : undefined,\n\t\t\t\ttoolValidationEscalationThreshold: agent.toolValidationEscalationThreshold,\n\t\t\t\tonToolValidationEscalation: usesForegroundModel ? agent.onToolValidationEscalation : undefined,\n\t\t\t\tbeforeToolCall: opts.beforeToolCall,\n\t\t\t\tafterToolCall: opts.afterToolCall,\n\t\t\t\tgetSteeringMessages: opts.getSteeringMessages,\n\t\t\t\tgetFollowUpMessages: opts.getFollowUpMessages,\n\t\t\t\ttransformContext: opts.transformContext,\n\t\t\t\trequestPreflight: opts.requestPreflight,\n\t\t\t\t...(maxTurns === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tshouldStopAfterTurn: () => {\n\t\t\t\t\t\t\t\tcompletedTurns += 1;\n\t\t\t\t\t\t\t\treturn completedTurns >= maxTurns;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\tconvertToLlm: agent.convertToLlm,\n\t\t\t};\n\n\t\t\t// An explicitly supplied surface owns a child tool loop even when it is empty: a model may\n\t\t\t// hallucinate an unavailable tool and must receive the bounded unknown-tool result so it can\n\t\t\t// repair. Only an omitted tools option selects the one-shot completion path.\n\t\t\tif (opts.tools !== undefined) {\n\t\t\t\tconst childContext: AgentContext = {\n\t\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\t\tmessages: [...history],\n\t\t\t\t\ttools: [...opts.tools],\n\t\t\t\t};\n\t\t\t\tconst messages = await runAgentLoop(\n\t\t\t\t\topts.messages,\n\t\t\t\t\tchildContext,\n\t\t\t\t\tloopConfig,\n\t\t\t\t\tasync (event) => {\n\t\t\t\t\t\tif (event.type === \"message_end\") await opts.onMessage?.(event.message as Message);\n\t\t\t\t\t},\n\t\t\t\t\topts.signal,\n\t\t\t\t\tagent.streamFn,\n\t\t\t\t);\n\t\t\t\tconst assistantMessages = messages.filter(\n\t\t\t\t\t(message): message is AssistantMessage => message.role === \"assistant\",\n\t\t\t\t);\n\t\t\t\tlet finalAssistant = assistantMessages.at(-1);\n\t\t\t\tif (!finalAssistant) {\n\t\t\t\t\tthrow new Error(\"runIsolatedCompletion: child loop produced no assistant message\");\n\t\t\t\t}\n\n\t\t\t\tconst hasFinalText = finalAssistant.content.some(\n\t\t\t\t\t(content) => content.type === \"text\" && content.text.trim().length > 0,\n\t\t\t\t);\n\t\t\t\tconst endedOnToolCall = finalAssistant.content.some((content) => content.type === \"toolCall\");\n\t\t\t\tif (opts.finalTextPrompt && !hasFinalText && endedOnToolCall && !opts.signal?.aborted) {\n\t\t\t\t\t// A hard turn bound may stop immediately after successful tool execution. Preserve that bound,\n\t\t\t\t\t// then allow exactly one tool-free synthesis call so the gathered work is not thrown away.\n\t\t\t\t\tconst finalizationPrompt: Message = {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: opts.finalTextPrompt,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t};\n\t\t\t\t\tawait opts.onMessage?.(finalizationPrompt);\n\t\t\t\t\tconst finalizationContext: AgentContext = {\n\t\t\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\t\t\tmessages: [...history, ...messages, finalizationPrompt],\n\t\t\t\t\t\ttools: [],\n\t\t\t\t\t};\n\t\t\t\t\tconst finalizationStream = await startAgentProviderRequest(\n\t\t\t\t\t\tfinalizationContext,\n\t\t\t\t\t\tloopConfig,\n\t\t\t\t\t\topts.signal,\n\t\t\t\t\t\tagent.streamFn,\n\t\t\t\t\t);\n\t\t\t\t\tfinalAssistant = await finalizationStream.result();\n\t\t\t\t\tawait opts.onMessage?.(finalAssistant);\n\t\t\t\t\tassistantMessages.push(finalAssistant);\n\t\t\t\t\tmessages.push(finalizationPrompt, finalAssistant);\n\t\t\t\t}\n\n\t\t\t\tconst usage = assistantMessages.reduce<Usage>(\n\t\t\t\t\t(total, message) => ({\n\t\t\t\t\t\tinput: total.input + message.usage.input,\n\t\t\t\t\t\toutput: total.output + message.usage.output,\n\t\t\t\t\t\tcacheRead: total.cacheRead + message.usage.cacheRead,\n\t\t\t\t\t\tcacheWrite: total.cacheWrite + message.usage.cacheWrite,\n\t\t\t\t\t\ttotalTokens: total.totalTokens + message.usage.totalTokens,\n\t\t\t\t\t\tcost: {\n\t\t\t\t\t\t\tinput: total.cost.input + message.usage.cost.input,\n\t\t\t\t\t\t\toutput: total.cost.output + message.usage.cost.output,\n\t\t\t\t\t\t\tcacheRead: total.cost.cacheRead + message.usage.cost.cacheRead,\n\t\t\t\t\t\t\tcacheWrite: total.cost.cacheWrite + message.usage.cost.cacheWrite,\n\t\t\t\t\t\t\ttotal: total.cost.total + message.usage.cost.total,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t\t{\n\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tconst text = finalAssistant.content\n\t\t\t\t\t.filter((content): content is TextContent => content.type === \"text\")\n\t\t\t\t\t.map((content) => content.text)\n\t\t\t\t\t.join(\"\");\n\t\t\t\t// Isolated inputs are Message values and this loop only adds assistant/tool-result messages,\n\t\t\t\t// so the child transcript is safely representable by the public Message[] contract.\n\t\t\t\treturn {\n\t\t\t\t\ttext,\n\t\t\t\t\tusage,\n\t\t\t\t\tstopReason: finalAssistant.stopReason,\n\t\t\t\t\tmessages: [...history, ...(messages as Message[])],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tfor (const message of opts.messages) await opts.onMessage?.(message);\n\t\t\tconst stream = await startAgentProviderRequest(context, loopConfig, opts.signal, agent.streamFn);\n\t\t\tconst result = await stream.result();\n\t\t\tawait opts.onMessage?.(result);\n\t\t\tconst text = result.content\n\t\t\t\t.filter((c): c is TextContent => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\");\n\t\t\tconst usage: Usage = result.usage ?? {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t};\n\t\t\treturn { text, usage, stopReason: result.stopReason, messages: [...history, ...opts.messages, result] };\n\t\t} finally {\n\t\t\tderegisterInFlight();\n\t\t}\n\t}\n\n\t/**\n\t * Native end-of-loop reflection pass (R2). Demand-gates (zero-I/O), and when warranted runs the\n\t * {@link ReflectionEngine} via an isolated completion ({@link runIsolatedCompletion}), applies the\n\t * resulting memory writes through the bundled `memory` tool, and accounts the reflection's token\n\t * cost via the cost-aggregation surface so it stays visible and net-negative-auditable.\n\t *\n\t * Returns `null` when the gate skips (or in a child session, which must not learn). The whole pass\n\t * is best-effort: a model/parse error yields no writes, never throws into the caller.\n\t */\n\tasync runReflectionPass(input: {\n\t\tsignals: DemandSignals;\n\t\trecentTurnText: string;\n\t\tmodel?: Model<Api>;\n\t\tthinkingLevel?: ThinkingLevel;\n\t\tsignal?: AbortSignal;\n\t\t/** Stable id so a duplicate scheduling/retry of the same pass can't double-count its cost. */\n\t\treportId?: string;\n\t\t/** True only when every turn in this pass explicitly asked Pi to remember durable information. */\n\t\texplicitUserMemoryInstruction?: boolean;\n\t}): Promise<ReflectionResult | null> {\n\t\tif (this.deps.isChildSession() || this.deps.isDisposed()) return null;\n\t\tconst plan = decideDemand(input.signals);\n\t\tif (plan.act === \"skip\") return null;\n\n\t\t// Bug #21: tie this background pass to the session lifetime. Disposing the session aborts the\n\t\t// in-flight completion (input.signal can add a more specific abort).\n\t\tconst signal = input.signal\n\t\t\t? AbortSignal.any([input.signal, this.deps.getReflectionSignal()])\n\t\t\t: this.deps.getReflectionSignal();\n\n\t\tconst complete = (systemPrompt: string, userPrompt: string) =>\n\t\t\tthis.runIsolatedCompletion({\n\t\t\t\tsystemPrompt,\n\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\tmodel: input.model,\n\t\t\t\tthinkingLevel: input.thinkingLevel ?? \"low\",\n\t\t\t\tmaxTokens: plan.tokenBudget,\n\t\t\t\tsignal,\n\t\t\t\t// The reflection system prompt is static (#33) — let the provider cache the prefix so\n\t\t\t\t// repeated passes only pay for the variable tail.\n\t\t\t\tcacheRetention: \"short\",\n\t\t\t\tlaneKind: \"reflection\",\n\t\t\t});\n\n\t\tconst result = await new ReflectionEngine().reflect({\n\t\t\trecentTurnText: input.recentTurnText,\n\t\t\t// Read memory FRESH (not the prefix-cache-frozen system-prompt block) so confront-before-write\n\t\t\t// sees writes made earlier this session.\n\t\t\texistingMemory: this.deps.getMemoryManager().buildSystemPromptBlockFresh() || \"\",\n\t\t\tplan,\n\t\t\tcomplete,\n\t\t});\n\n\t\t// Bug #21: if the session was disposed while the completion was in flight, do NOT write memory\n\t\t// or skills against the dead session.\n\t\tif (this.deps.isDisposed()) return result;\n\n\t\t// Learning apply policy: every durable write is converted to a proposal, decided by the\n\t\t// learning gate, and audited with a rollback plan. When the policy is explicitly disabled,\n\t\t// legacy direct-apply behavior is preserved — but now leaves audit records with rollback info.\n\t\tconst policy = this.deps.getSettingsManager().getLearningPolicySettings();\n\t\t// The audit id sequence counts STORED snapshots only: it reseeds from the stored count on\n\t\t// every pass, so advancing it for a no-op (which stores nothing) would make later passes\n\t\t// reuse ids — and rollback keys on the id, so a collision blocks or misdirects rollback.\n\t\tlet auditSequence = getLearningAuditSnapshots(this.deps.getSessionManager().getEntries()).length;\n\t\t// G6 evidence strength: durable proposals accumulate observation counts across passes/sessions\n\t\t// so the gate can distinguish a one-off cue from a repeatedly-confirmed lesson. Built once per\n\t\t// pass; every increment is best-effort (store IO must never break reflection).\n\t\tconst observationStore = ObservationStore.forAgentDir(this.deps.getAgentDir());\n\t\tlet writeIndex = 0;\n\t\tfor (const write of result.writes) {\n\t\t\twriteIndex += 1;\n\t\t\tconst proposalId = `${input.reportId ?? \"reflection\"}-w${writeIndex}`;\n\t\t\tconst proposal = proposalFromReflectionWrite(write, proposalId);\n\t\t\tconst rollback = rollbackPlanForReflectionWrite(write);\n\t\t\tlet observations = 1;\n\t\t\tif (policy.enabled) {\n\t\t\t\ttry {\n\t\t\t\t\tobservations = observationStore.increment(observationKey(proposal.layer, proposal.summary));\n\t\t\t\t} catch {\n\t\t\t\t\t// A store read/write failure falls back to a fresh count of 1, which keeps the gate\n\t\t\t\t\t// proposal-first (never spuriously auto-applies) rather than crashing the pass.\n\t\t\t\t\tobservations = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst explicitUserMemoryWrite =\n\t\t\t\tinput.explicitUserMemoryInstruction === true &&\n\t\t\t\t(write.kind === \"memory_add\" || write.kind === \"memory_replace\");\n\t\t\tconst decision: LearningDecision = explicitUserMemoryWrite\n\t\t\t\t? {\n\t\t\t\t\t\tkind: \"apply\",\n\t\t\t\t\t\treasonCode: \"explicit_user_memory_instruction\",\n\t\t\t\t\t\tconfidence: 100,\n\t\t\t\t\t\tsummary: proposal.summary,\n\t\t\t\t\t\trequiresApproval: false,\n\t\t\t\t\t}\n\t\t\t\t: policy.enabled\n\t\t\t\t\t? evaluateLearningDecision({\n\t\t\t\t\t\t\tproposal,\n\t\t\t\t\t\t\tconfidence: policy.reflectionSourceConfidence,\n\t\t\t\t\t\t\tobservations,\n\t\t\t\t\t\t\t// A replace/remove supersedes an existing durable fact — the reflection engine's\n\t\t\t\t\t\t\t// confront-before-write conflict signal — so it routes through approval instead of\n\t\t\t\t\t\t\t// silently overwriting prior memory. Additive writes contradict nothing.\n\t\t\t\t\t\t\tcontradictions: contradictionsForReflectionWrite(write),\n\t\t\t\t\t\t\tsettings: {\n\t\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\t\tautoApplyEnabled: policy.autoApplyEnabled,\n\t\t\t\t\t\t\t\tconfidenceThreshold: policy.confidenceThreshold,\n\t\t\t\t\t\t\t\tminObservations: policy.minObservations,\n\t\t\t\t\t\t\t\tallowedAutoApplyLayers: policy.allowedAutoApplyLayers,\n\t\t\t\t\t\t\t\trequireRollbackPlan: policy.requireRollbackPlan,\n\t\t\t\t\t\t\t\tautoApplySupersessions: policy.autoApplySupersessions,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t})\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tkind: \"apply\",\n\t\t\t\t\t\t\treasonCode: \"learning_policy_disabled_legacy_apply\",\n\t\t\t\t\t\t\tconfidence: 0,\n\t\t\t\t\t\t\tsummary: proposal.summary,\n\t\t\t\t\t\t\trequiresApproval: false,\n\t\t\t\t\t\t};\n\n\t\t\tthis.deps.saveLearningDecisionSnapshot(decision);\n\t\t\t// G3: learning-gate outcome. Codes/numbers only — never the proposal summary/memory text.\n\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.learningDecision,\n\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\tpayload: {\n\t\t\t\t\tkind: decision.kind,\n\t\t\t\t\treasonCode: decision.reasonCode,\n\t\t\t\t\tlayer: proposal.layer,\n\t\t\t\t\tconfidence: decision.confidence,\n\t\t\t\t\trequiresApproval: decision.requiresApproval,\n\t\t\t\t},\n\t\t\t});\n\t\t\t// G8: a proposal that needs human sign-off is an approval REQUEST. Codes/layer only —\n\t\t\t// never the proposal summary/memory text (those live only in the audit snapshot).\n\t\t\tif (decision.requiresApproval) {\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.approvalRequest,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tkind: decision.kind,\n\t\t\t\t\t\treasonCode: decision.reasonCode,\n\t\t\t\t\t\tlayer: proposal.layer,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\t// An automatic skill promotion the gate would otherwise apply must still clear the same\n\t\t\t// skill_audit overlap check the model-invoked `skillify` tool enforces — otherwise reflection\n\t\t\t// can silently write a near-duplicate SKILL.md. A non-overlapping skill is unaffected\n\t\t\t// (skillPromotionBlock stays undefined) and promotes exactly as before.\n\t\t\tconst skillPromotionBlock =\n\t\t\t\twrite.kind === \"promote_skill\" && decision.kind === \"apply\"\n\t\t\t\t\t? this._checkSkillPromotionOverlap(write)\n\t\t\t\t\t: undefined;\n\n\t\t\t// The gate's decision and the write's actual outcome are two different questions: the memory\n\t\t\t// tool can refuse a write (budget exceeded, drift, threat) via details.success:false without\n\t\t\t// throwing. Capture that outcome instead of assuming \"decision.kind === apply\" means it landed\n\t\t\t// — otherwise a refused write leaves a phantom \"apply\" audit whose rollback later fails\n\t\t\t// not-found (or, worse, misfires against whatever now occupies that text).\n\t\t\tconst applied =\n\t\t\t\tdecision.kind === \"apply\" && !skillPromotionBlock ? await this._applyReflectionWrite(write, signal) : false;\n\t\t\tconst writeFailed = decision.kind === \"apply\" && !skillPromotionBlock && !applied;\n\t\t\tif (decision.kind !== \"no-op\") {\n\t\t\t\tauditSequence += 1;\n\t\t\t\tappendLearningAuditSnapshot(this.deps.getSessionManager(), {\n\t\t\t\t\tid: `audit-${auditSequence}`,\n\t\t\t\t\tproposalId,\n\t\t\t\t\tlayer: proposal.layer,\n\t\t\t\t\taction: skillPromotionBlock\n\t\t\t\t\t\t? \"propose\"\n\t\t\t\t\t\t: writeFailed\n\t\t\t\t\t\t\t? \"apply_failed\"\n\t\t\t\t\t\t\t: decision.kind === \"apply\"\n\t\t\t\t\t\t\t\t? \"apply\"\n\t\t\t\t\t\t\t\t: \"propose\",\n\t\t\t\t\tsummary: skillPromotionBlock ? `${proposal.summary} — ${skillPromotionBlock.note}` : proposal.summary,\n\t\t\t\t\treasonCode: skillPromotionBlock\n\t\t\t\t\t\t? skillPromotionBlock.reasonCode\n\t\t\t\t\t\t: writeFailed\n\t\t\t\t\t\t\t? APPLY_WRITE_REFUSED_REASON_CODE\n\t\t\t\t\t\t\t: decision.reasonCode,\n\t\t\t\t\tdecision,\n\t\t\t\t\t// No rollback plan on a failed apply or a held/proposed promotion — nothing durable\n\t\t\t\t\t// landed in either case, so there is nothing to undo.\n\t\t\t\t\trollback: skillPromotionBlock || writeFailed ? undefined : rollback,\n\t\t\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Account the reflection's spend so it surfaces in the footer roll-up (net-token visibility).\n\t\t// Idempotent on reportId so a retried/duplicated pass cannot double-count.\n\t\tif (result.usage.cost.total > 0 || result.usage.totalTokens > 0) {\n\t\t\tthis.deps.addSpawnedUsage(result.usage, { label: \"reflection\", reportId: input.reportId });\n\t\t}\n\t\treturn result;\n\t}\n\n\tgetLearningAuditRecords(): LearningAuditRecord[] {\n\t\treturn getLearningAuditSnapshots(this.deps.getSessionManager().getEntries());\n\t}\n\n\t/**\n\t * Roll back one applied durable learning change by executing the inverse operation recorded in\n\t * its audit record (memory ops run through the same bundled memory-tool path as the original\n\t * apply; promoted skills are archived). Appends a linked \"rollback\" audit record on success so\n\t * the change history stays complete and a change cannot be rolled back twice.\n\t */\n\tasync rollbackLearningWrite(auditId: string): Promise<{ ok: boolean; reason: string }> {\n\t\tif (this.deps.isDisposed()) return { ok: false, reason: \"session_disposed\" };\n\n\t\tconst audits = this.getLearningAuditRecords();\n\t\tconst audit = audits.find((record) => record.id === auditId);\n\t\tif (!audit) return { ok: false, reason: \"audit_not_found\" };\n\t\tif (audit.action !== \"apply\") return { ok: false, reason: \"not_an_applied_change\" };\n\t\tif (audits.some((record) => record.action === \"rollback\" && record.rollbackOf === auditId)) {\n\t\t\treturn { ok: false, reason: \"already_rolled_back\" };\n\t\t}\n\t\tconst rollback = audit.rollback;\n\t\tif (!rollback) return { ok: false, reason: \"no_rollback_plan\" };\n\n\t\t// Every inverse must be VERIFIED-applied before the rollback audit is appended: a silently\n\t\t// failed inverse that still recorded \"rollback\" would permanently self-lock the change\n\t\t// behind already_rolled_back while the durable write is in fact still live.\n\t\tswitch (rollback.kind) {\n\t\t\tcase \"memory_remove\": {\n\t\t\t\tif (!rollback.target) return { ok: false, reason: \"missing_rollback_target\" };\n\t\t\t\tif (!(await this._applyReflectionWrite({ kind: \"memory_remove\", target: rollback.target }))) {\n\t\t\t\t\treturn { ok: false, reason: \"rollback_apply_failed\" };\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"memory_restore\": {\n\t\t\t\tif (!rollback.target || rollback.previous === undefined) {\n\t\t\t\t\treturn { ok: false, reason: \"missing_rollback_target\" };\n\t\t\t\t}\n\t\t\t\tconst applied = await this._applyReflectionWrite({\n\t\t\t\t\tkind: \"memory_replace\",\n\t\t\t\t\ttarget: rollback.target,\n\t\t\t\t\ttext: rollback.previous,\n\t\t\t\t});\n\t\t\t\tif (!applied) return { ok: false, reason: \"rollback_apply_failed\" };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"memory_add\": {\n\t\t\t\tif (rollback.previous === undefined) return { ok: false, reason: \"missing_rollback_target\" };\n\t\t\t\tconst applied = await this._applyReflectionWrite({\n\t\t\t\t\tkind: \"memory_add\",\n\t\t\t\t\tsection: \"MEMORY\",\n\t\t\t\t\ttext: rollback.previous,\n\t\t\t\t});\n\t\t\t\tif (!applied) return { ok: false, reason: \"rollback_apply_failed\" };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"archive_skill\": {\n\t\t\t\tif (!rollback.target) return { ok: false, reason: \"missing_rollback_target\" };\n\t\t\t\tif (!this.deps.archivePromotedSkill(rollback.target)) {\n\t\t\t\t\treturn { ok: false, reason: \"skill_archive_failed\" };\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tappendLearningAuditSnapshot(this.deps.getSessionManager(), {\n\t\t\tid: `${audit.id}-rollback`,\n\t\t\tproposalId: audit.proposalId,\n\t\t\tlayer: audit.layer,\n\t\t\taction: \"rollback\",\n\t\t\tsummary: `Rolled back: ${audit.summary}`,\n\t\t\treasonCode: \"user_requested_rollback\",\n\t\t\tdecision: audit.decision,\n\t\t\trollbackOf: audit.id,\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t});\n\t\treturn { ok: true, reason: \"rollback_applied\" };\n\t}\n\n\t/**\n\t * Apply one reflection write through the bundled `memory` tool. `memory_replace`/`memory_remove`\n\t * don't carry a target file, so we try MEMORY.md first and fall back to USER.md when the substring\n\t * isn't found there. Never throws (reflection must never break a turn); returns whether the write\n\t * actually applied so callers that MUST know — rollback's once-only accounting — can react instead\n\t * of recording a success that never happened.\n\t */\n\tprivate async _applyReflectionWrite(write: ReflectionWrite, signal?: AbortSignal): Promise<boolean> {\n\t\t// R7 memory-to-behavior: a recurring procedure is compiled into an executable skill file rather\n\t\t// than stored as a flat fact. Written under the agent skills dir so it loads like any user skill.\n\t\tif (write.kind === \"promote_skill\") {\n\t\t\treturn this._promoteReflectionSkill(write.name, write.description, write.body);\n\t\t}\n\n\t\ttype MemResult = { details?: { success?: boolean; error?: string } };\n\t\ttype MemExec = (\n\t\t\ttoolCallId: string,\n\t\t\tparams: { action: string; target: string; content?: string; oldContent?: string },\n\t\t\tsignal: AbortSignal | undefined,\n\t\t\tonUpdate: undefined,\n\t\t\tctx: undefined,\n\t\t) => Promise<MemResult>;\n\t\tconst memTool = this.deps\n\t\t\t.getMemoryManager()\n\t\t\t.getToolDefinitions()\n\t\t\t.find((t) => t.name === \"memory\");\n\t\tconst exec = memTool?.execute as unknown as MemExec | undefined;\n\t\tif (!exec) return false;\n\n\t\tconst run = (params: Parameters<MemExec>[1]) => exec(\"reflection\", params, signal, undefined, undefined);\n\n\t\tif (write.kind === \"memory_add\") {\n\t\t\ttry {\n\t\t\t\tconst res = await run({\n\t\t\t\t\taction: \"add\",\n\t\t\t\t\ttarget: write.section === \"USER\" ? \"user\" : \"memory\",\n\t\t\t\t\tcontent: write.text,\n\t\t\t\t});\n\t\t\t\treturn res?.details?.success === true;\n\t\t\t} catch {\n\t\t\t\t// best-effort; reflection writes must never throw into the turn loop\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t// replace / remove carry no target file — try MEMORY.md, then USER.md. The memory tool reports\n\t\t// outcomes via `details.success` (it catches its own errors rather than throwing). Only a\n\t\t// genuine \"not found in the file\" justifies trying the other file; a real failure for a file\n\t\t// (budget exceeded / drift) must NOT fall through and mutate the wrong target.\n\t\tfor (const target of [\"memory\", \"user\"] as const) {\n\t\t\ttry {\n\t\t\t\tconst params =\n\t\t\t\t\twrite.kind === \"memory_replace\"\n\t\t\t\t\t\t? { action: \"replace\", target, oldContent: write.target, content: write.text }\n\t\t\t\t\t\t: { action: \"remove\", target, oldContent: write.target };\n\t\t\t\tconst res = await run(params);\n\t\t\t\tif (res?.details?.success === true) return true; // applied\n\t\t\t\tif (!/not found/i.test(String(res?.details?.error ?? \"\"))) return false; // real failure — don't misapply\n\t\t\t\t// substring simply absent from this file — try the next target\n\t\t\t} catch {\n\t\t\t\t// defensive: if the tool ever does throw, try the next target\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * The same skill_audit overlap check the model-invoked `skillify` tool enforces\n\t * (tools/skillify.ts → tools/skill-audit.ts's `runSkillAudit`), run before an AUTOMATIC promotion\n\t * so the reflection engine can never silently write a near-duplicate SKILL.md. Reuses the audit\n\t * seam unchanged (never duplicated) against the same already-loaded skills universe skillify\n\t * compares a draft against. Returns a block reason when the draft overlaps an existing skill above\n\t * the audit's own similarity threshold, or when the audit itself fails (the promotion is held, not\n\t * written unaudited); undefined when clear to promote. Never throws — mirrors every other\n\t * best-effort check in this file.\n\t */\n\tprivate _checkSkillPromotionOverlap(write: {\n\t\tname: string;\n\t\tdescription: string;\n\t\tbody: string;\n\t}): { reasonCode: string; note: string } | undefined {\n\t\ttry {\n\t\t\tconst cwd = this.deps.getCwd?.() ?? process.cwd();\n\t\t\tconst audit = runSkillAudit(cwd, write);\n\t\t\tconst overlap = audit.nearDuplicates.find((d) => d.a === \"[draft]\" || d.b === \"[draft]\");\n\t\t\tif (!overlap) return undefined;\n\t\t\tconst otherPath = overlap.a === \"[draft]\" ? overlap.b : overlap.a;\n\t\t\t// Every skill file is named \"SKILL.md\" — unlike skillify's own display formatter (which takes\n\t\t\t// the path's last segment and always shows that literal filename), look up the declared\n\t\t\t// frontmatter name so the proposal actually names the skill it overlaps with.\n\t\t\tconst otherName = audit.skills.find((s) => s.path === otherPath)?.name ?? otherPath;\n\t\t\treturn {\n\t\t\t\treasonCode: SKILL_OVERLAP_CONSOLIDATION_REASON_CODE,\n\t\t\t\tnote: `overlaps existing skill \"${otherName}\" (${(overlap.similarity * 100).toFixed(0)}% similar) — consolidation proposed instead of a duplicate write`,\n\t\t\t};\n\t\t} catch {\n\t\t\t// Bounded, observable degradation via the promote path's existing error-reporting shape: an\n\t\t\t// audit failure must never throw into the reflection pass, but it also must not silently\n\t\t\t// fall through to an unaudited write — hold the promotion and record why.\n\t\t\treturn {\n\t\t\t\treasonCode: SKILL_AUDIT_UNAVAILABLE_REASON_CODE,\n\t\t\t\tnote: \"skill overlap audit failed; promotion held rather than written unaudited\",\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * R7: write a reflection-promoted skill as `<agentDir>/skills/<name>/SKILL.md` so it loads like any\n\t * user skill. Best-effort; never clobbers an existing (hand-authored) skill of the same name. The\n\t * overlap audit runs at the call site in {@link runReflectionPass} — a write only reaches here\n\t * once the draft has already cleared it.\n\t */\n\tprivate _promoteReflectionSkill(rawName: string, description: string, body: string): boolean {\n\t\tconst name = rawName\n\t\t\t.trim()\n\t\t\t.toLowerCase()\n\t\t\t.replace(/[^a-z0-9-]+/g, \"-\")\n\t\t\t.replace(/^-+|-+$/g, \"\")\n\t\t\t.slice(0, 64);\n\t\tif (!name || !body.trim()) return false;\n\t\ttry {\n\t\t\tconst dir = join(this.deps.getAgentDir(), \"skills\", name);\n\t\t\tconst file = join(dir, \"SKILL.md\");\n\t\t\tif (existsSync(file)) return false; // do not overwrite an existing skill\n\t\t\tmkdirSync(dir, { recursive: true });\n\t\t\tconst safeDescription = description.replace(/[\\r\\n]+/g, \" \").trim();\n\t\t\t// `promoted: true` marks this as reflection-generated so the curator (#32) can lifecycle-manage\n\t\t\t// it (archive/consolidate) WITHOUT ever touching hand-authored user skills.\n\t\t\tconst content = `---\\nname: ${name}\\ndescription: ${safeDescription}\\npromoted: true\\n---\\n\\n<!-- Auto-generated by the reflection engine (R7 memory-to-behavior). Review and refine. -->\\n\\n${body.trim()}\\n`;\n\t\t\twriteFileSync(file, content, \"utf-8\");\n\t\t\treturn true;\n\t\t} catch {\n\t\t\t// promotion must never break a turn\n\t\t\treturn false;\n\t\t}\n\t}\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { addUsage, createEmptyUsage } from "@caupulican/pi-agent-core";
|
|
1
|
+
import { addUsage, createEmptyUsage } from "@caupulican/pi-agent-core/usage";
|
|
2
2
|
import { runIsolatedTextCompletion } from "../isolated-text-completion.js";
|
|
3
3
|
import { FitnessStore } from "../models/fitness-store.js";
|
|
4
4
|
import { registerInFlightWork } from "../reload-blockers.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-fitness-controller.js","sourceRoot":"","sources":["../../../src/core/research/model-fitness-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"model-fitness-controller.js","sourceRoot":"","sources":["../../../src/core/research/model-fitness-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAA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I,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,CAAC;gBAC7B,MAAM,QAAQ,GAAG,IAAI,CAAC,UAAU;oBAC/B,CAAC,CAAC,YAAY,IAAI,CAAC,UAAU,EAAE;oBAC/B,CAAC,CAAC,GAAG,QAAQ,IAAI,IAAI,CAAC,MAAM,IAAI,SAAS,EAAE,CAAC;gBAC7C,kBAAkB,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE;oBACpC,IAAI,EAAE,eAAe;oBACrB,KAAK,EAAE,eAAe;oBACtB,SAAS,EAAE,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE;oBACnC,QAAQ;iBACR,CAAC,CAAC;YACJ,CAAC;YACD,IAAI,CAAC;gBACJ,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE;oBAAE,YAAY,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;YACvG,CAAC;YAAC,MAAM,CAAC;gBACR,mDAAmD;YACpD,CAAC;YACD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC;QACnD,CAAC;gBAAS,CAAC;YACV,kBAAkB,EAAE,CAAC;QACtB,CAAC;IACF,CAAC;IAED,gBAAgB;QACf,IAAI,CAAC;YACJ,OAAO,YAAY,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,UAAU,EAAE,CAAC;QACvE,CAAC;QAAC,MAAM,CAAC;YACR,OAAO,EAAE,CAAC;QACX,CAAC;IACF,CAAC;CACD","sourcesContent":["import { addUsage, createEmptyUsage } from \"@caupulican/pi-agent-core/usage\";\nimport type { Usage } from \"@caupulican/pi-ai\";\nimport type { IsolatedCompletionOptions, IsolatedCompletionResult } from \"../agent-session.ts\";\nimport { runIsolatedTextCompletion } from \"../isolated-text-completion.ts\";\nimport { FitnessStore, type StoredFitnessReport } from \"../models/fitness-store.ts\";\nimport { registerInFlightWork } from \"../reload-blockers.ts\";\nimport { reportSpawnedUsage } from \"../spawned-usage.ts\";\nimport type { LaneModelResolver } from \"./lane-model-resolver.ts\";\nimport { type ModelFitnessReport, runModelFitnessProbe } from \"./model-fitness.ts\";\n\nexport interface ModelFitnessControllerDeps {\n\tisDisposed(): boolean;\n\tgetSessionId(): string;\n\tgetAgentDir(): string;\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts: { label?: string; sourceSessionId?: string; reportId: string },\n\t): string | undefined;\n\trunIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n}\n\n/** Owns model-fitness execution, cancellation, accounting, and host-keyed persistence. */\nexport class ModelFitnessController {\n\tprivate readonly abortController = new AbortController();\n\tprivate readonly deps: ModelFitnessControllerDeps;\n\tprivate readonly models: LaneModelResolver;\n\n\tconstructor(deps: ModelFitnessControllerDeps, models: LaneModelResolver) {\n\t\tthis.deps = deps;\n\t\tthis.models = models;\n\t}\n\n\tabort(): void {\n\t\tthis.abortController.abort();\n\t}\n\n\tasync run(args: {\n\t\tmodel: string;\n\t\ttrials?: number;\n\t\ttoolCallId?: string;\n\t}): Promise<{ started: true; model: string; report: ModelFitnessReport } | { started: false; skipReason: string }> {\n\t\tif (this.deps.isDisposed()) return { started: false, skipReason: \"session_disposed\" };\n\t\tconst resolved = this.models.resolveModel(args.model.trim() || undefined);\n\t\tif (!resolved) return { started: false, skipReason: \"model_unresolved_or_unauthenticated\" };\n\t\tconst capability = this.models.capabilityProfile(resolved);\n\t\tconst deregisterInFlight = registerInFlightWork(\n\t\t\tthis.deps.getAgentDir(),\n\t\t\t\"lane\",\n\t\t\t`fitness:${resolved.provider}/${resolved.id}`,\n\t\t);\n\t\ttry {\n\t\t\tconst spent = createEmptyUsage();\n\t\t\tconst report = await runModelFitnessProbe({\n\t\t\t\ttrials: args.trials,\n\t\t\t\tsignal: this.abortController.signal,\n\t\t\t\tcapacityProbe:\n\t\t\t\t\tresolved.provider === \"ollama\" && resolved.contextWindow > 0\n\t\t\t\t\t\t? { registeredContextWindow: resolved.contextWindow }\n\t\t\t\t\t\t: undefined,\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tconst callStarted = Date.now();\n\t\t\t\t\tconst completion = await runIsolatedTextCompletion(this.deps, {\n\t\t\t\t\t\tsystemPrompt,\n\t\t\t\t\t\tuserPrompt,\n\t\t\t\t\t\tmodel: resolved,\n\t\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\t\tmaxTokens: capability.laneMaxOutputTokens,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t\tlaneKind: \"fitness\",\n\t\t\t\t\t});\n\t\t\t\t\tconst callMs = Date.now() - callStarted;\n\t\t\t\t\taddUsage(spent, completion.usage);\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\tcostUsd: completion.costUsd,\n\t\t\t\t\t\tstopReason: completion.stopReason,\n\t\t\t\t\t\toutputTokens: completion.usage.output,\n\t\t\t\t\t\tevalMs: callMs,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\t\t\tconst modelRef = `${resolved.provider}/${resolved.id}`;\n\t\t\tif (!this.deps.isDisposed()) {\n\t\t\t\tconst identity = args.toolCallId\n\t\t\t\t\t? `toolcall:${args.toolCallId}`\n\t\t\t\t\t: `${modelRef} ${args.trials ?? \"default\"}`;\n\t\t\t\treportSpawnedUsage(this.deps, spent, {\n\t\t\t\t\tkind: \"model-fitness\",\n\t\t\t\t\tlabel: \"model-fitness\",\n\t\t\t\t\tsessionId: this.deps.getSessionId(),\n\t\t\t\t\tidentity,\n\t\t\t\t});\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tif (!this.deps.isDisposed()) FitnessStore.forAgentDir(this.deps.getAgentDir()).save(modelRef, report);\n\t\t\t} catch {\n\t\t\t\t// Best-effort persistence must not fail the probe.\n\t\t\t}\n\t\t\treturn { started: true, model: modelRef, report };\n\t\t} finally {\n\t\t\tderegisterInFlight();\n\t\t}\n\t}\n\n\tgetStoredReports(): StoredFitnessReport[] {\n\t\ttry {\n\t\t\treturn FitnessStore.forAgentDir(this.deps.getAgentDir()).getForHost();\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { SessionManager } from "@caupulican/pi-agent-core/
|
|
2
|
-
import {
|
|
1
|
+
import type { SessionManager } from "@caupulican/pi-agent-core/session";
|
|
2
|
+
import type { Usage } from "@caupulican/pi-ai/types";
|
|
3
3
|
import type { AgentSessionEvent, IsolatedCompletionOptions, IsolatedCompletionResult, ResearchLaneRunOutcome } from "../agent-session.ts";
|
|
4
4
|
import type { CapabilityEnvelope, EvidenceBundle } from "../autonomy/contracts.ts";
|
|
5
5
|
import type { LaneTracker } from "../autonomy/lane-tracker.ts";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"research-lane-controller.d.ts","sourceRoot":"","sources":["../../../src/core/research/research-lane-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"research-lane-controller.d.ts","sourceRoot":"","sources":["../../../src/core/research/research-lane-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mCAAmC,CAAC;AAExE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,yBAAyB,CAAC;AACrD,OAAO,KAAK,EACX,iBAAiB,EACjB,yBAAyB,EACzB,wBAAwB,EACxB,sBAAsB,EACtB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAGnF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM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OAAO,CAAC,MAAM,CAA4C;IAC1D,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,eAAe,CAAqB;IAC5C,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,kBAAkB,CAAK;IAC/B,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAyB;IACzD,OAAO,CAAC,QAAQ,CAAC,uBAAuB,CAAqB;IAC7D,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA6B;IAClD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAc;IACpC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAoB;IAE3C,YAAY,IAAI,EAAE,0BAA0B,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,iBAAiB,EAI1F;IAED,WAAW,IAAI,IAAI,CAMlB;IAED,iBAAiB,IAAI,MAAM,GAAG,SAAS,CAEtC;IAED,KAAK,IAAI,IAAI,CAGZ;IAED,UAAU,IAAI,IAAI,CAKjB;IAED,gBAAgB,IAAI,IAAI,CAsCvB;IAEK,OAAO,CAAC,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAsI9G;IAED,OAAO,CAAC,WAAW;YA2BL,YAAY;IAa1B,OAAO,CAAC,aAAa;IAkBrB,OAAO,CAAC,qBAAqB;IAW7B,OAAO,CAAC,qBAAqB;CAc7B"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { resolveModelThinkingLevel } from "@caupulican/pi-ai";
|
|
1
|
+
import { resolveModelThinkingLevel } from "@caupulican/pi-ai/models";
|
|
2
2
|
import { getPrivateLaneDeniedPaths } from "../autonomy/lane-private-paths.js";
|
|
3
3
|
import { createLaneToolSurface } from "../autonomy/lane-tool-surface.js";
|
|
4
4
|
import { appendLaneRecordSnapshot, getLaneRecordSnapshots } from "../autonomy/session-lane-record.js";
|
|
@@ -107,6 +107,7 @@ export class ResearchLaneController {
|
|
|
107
107
|
const startedRecord = this.lanes.start({ type: "research", goalId: demand.goalId });
|
|
108
108
|
this._persistedRunCount++;
|
|
109
109
|
const deregisterInFlight = registerInFlightWork(this.deps.getAgentDir(), "lane", `research:${startedRecord.laneId}`);
|
|
110
|
+
let toolSurface;
|
|
110
111
|
try {
|
|
111
112
|
let spentUsage;
|
|
112
113
|
const workspaceSources = await this.deps.collectWorkspaceSources({
|
|
@@ -115,17 +116,18 @@ export class ResearchLaneController {
|
|
|
115
116
|
maxSources: settings.maxSources,
|
|
116
117
|
});
|
|
117
118
|
const maxUsd = clampLaneMaxUsd(settings.maxUsd, this.deps.getCapabilityEnvelope()?.maxEstimatedUsd);
|
|
118
|
-
const
|
|
119
|
+
const activeToolSurface = createLaneToolSurface({
|
|
119
120
|
cwd: this.deps.getCwd(),
|
|
120
121
|
profile: laneProfile,
|
|
121
122
|
deniedPaths: getPrivateLaneDeniedPaths(this.deps.getCwd(), this.deps.getAgentDir()),
|
|
122
123
|
});
|
|
123
|
-
|
|
124
|
+
toolSurface = activeToolSurface;
|
|
125
|
+
this.warnUnboundToolGrants(laneProfile, activeToolSurface);
|
|
124
126
|
const result = await runResearch({
|
|
125
127
|
query: demand.query,
|
|
126
128
|
context: demand.context,
|
|
127
129
|
sources: workspaceSources,
|
|
128
|
-
envelope: this.buildEnvelope(maxUsd, laneProfile,
|
|
130
|
+
envelope: this.buildEnvelope(maxUsd, laneProfile, activeToolSurface),
|
|
129
131
|
maxUsd,
|
|
130
132
|
maxSources: settings.maxSources,
|
|
131
133
|
maxFindings: settings.maxFindings,
|
|
@@ -142,9 +144,9 @@ export class ResearchLaneController {
|
|
|
142
144
|
model,
|
|
143
145
|
thinkingLevel: resolveModelThinkingLevel(model, laneProfile?.thinking),
|
|
144
146
|
maxTokens: laneCapability.laneMaxOutputTokens,
|
|
145
|
-
tools:
|
|
147
|
+
tools: activeToolSurface.tools,
|
|
146
148
|
maxTurns: 6,
|
|
147
|
-
beforeToolCall:
|
|
149
|
+
beforeToolCall: activeToolSurface.beforeToolCall,
|
|
148
150
|
signal,
|
|
149
151
|
cacheRetention: "short",
|
|
150
152
|
laneKind: "research",
|
|
@@ -199,6 +201,13 @@ export class ResearchLaneController {
|
|
|
199
201
|
return { started: true, record };
|
|
200
202
|
}
|
|
201
203
|
finally {
|
|
204
|
+
try {
|
|
205
|
+
await toolSurface?.dispose();
|
|
206
|
+
}
|
|
207
|
+
catch (error) {
|
|
208
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
209
|
+
this.deps.emit({ type: "warning", message: `Research lane payload cleanup failed: ${message}` });
|
|
210
|
+
}
|
|
202
211
|
this._isRunning = false;
|
|
203
212
|
deregisterInFlight();
|
|
204
213
|
}
|