@caupulican/pi-adaptative 0.81.39 → 0.81.41
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 +77 -0
- package/README.md +2 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts +2 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts.map +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js +3 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js.map +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.ts +4 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +9 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +290 -107
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +357 -122
- package/dist/bundled-resources/skills/tool-call-repair/references/repair-catalogue.md +2 -2
- package/dist/cli/args.d.ts +4 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +31 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-directory-layout.d.ts +15 -0
- package/dist/core/agent-directory-layout.d.ts.map +1 -0
- package/dist/core/agent-directory-layout.js +72 -0
- package/dist/core/agent-directory-layout.js.map +1 -0
- package/dist/core/agent-paths.d.ts +25 -2
- package/dist/core/agent-paths.d.ts.map +1 -1
- package/dist/core/agent-paths.js +79 -4
- package/dist/core/agent-paths.js.map +1 -1
- package/dist/core/agent-session-contracts.d.ts +293 -0
- package/dist/core/agent-session-contracts.d.ts.map +1 -0
- package/dist/core/agent-session-contracts.js +26 -0
- package/dist/core/agent-session-contracts.js.map +1 -0
- package/dist/core/agent-session-runtime.d.ts +52 -8
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +400 -79
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +1 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +1 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +74 -518
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +370 -1432
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +3 -1
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/autonomy/approval-gate.d.ts +3 -2
- package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
- package/dist/core/autonomy/approval-gate.js +6 -28
- package/dist/core/autonomy/approval-gate.js.map +1 -1
- package/dist/core/autonomy/bounded-completion.d.ts +1 -1
- package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
- package/dist/core/autonomy/bounded-completion.js +1 -1
- package/dist/core/autonomy/bounded-completion.js.map +1 -1
- package/dist/core/autonomy/contracts.d.ts +20 -12
- package/dist/core/autonomy/contracts.d.ts.map +1 -1
- package/dist/core/autonomy/contracts.js.map +1 -1
- package/dist/core/autonomy/foreground-envelope.d.ts +8 -2
- package/dist/core/autonomy/foreground-envelope.d.ts.map +1 -1
- package/dist/core/autonomy/foreground-envelope.js +8 -25
- package/dist/core/autonomy/foreground-envelope.js.map +1 -1
- package/dist/core/autonomy/gates.d.ts.map +1 -1
- package/dist/core/autonomy/gates.js +8 -10
- package/dist/core/autonomy/gates.js.map +1 -1
- package/dist/core/autonomy/lane-private-paths.d.ts +2 -0
- package/dist/core/autonomy/lane-private-paths.d.ts.map +1 -0
- package/dist/core/autonomy/lane-private-paths.js +16 -0
- package/dist/core/autonomy/lane-private-paths.js.map +1 -0
- package/dist/core/autonomy/lane-tool-surface.d.ts +10 -0
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.js +48 -9
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
- package/dist/core/autonomy/lane-tracker.d.ts +14 -0
- package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tracker.js +38 -0
- package/dist/core/autonomy/lane-tracker.js.map +1 -1
- package/dist/core/autonomy/risk-assessment.d.ts +1 -2
- package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
- package/dist/core/autonomy/risk-assessment.js +1 -123
- package/dist/core/autonomy/risk-assessment.js.map +1 -1
- package/dist/core/autonomy/session-lane-record.d.ts +4 -4
- package/dist/core/autonomy/session-lane-record.d.ts.map +1 -1
- package/dist/core/autonomy/session-lane-record.js +16 -29
- package/dist/core/autonomy/session-lane-record.js.map +1 -1
- package/dist/core/autonomy/telemetry-events.d.ts +1 -1
- package/dist/core/autonomy/telemetry-events.d.ts.map +1 -1
- package/dist/core/autonomy/telemetry-events.js +1 -1
- package/dist/core/autonomy/telemetry-events.js.map +1 -1
- package/dist/core/autonomy-telemetry.d.ts +7 -7
- package/dist/core/autonomy-telemetry.d.ts.map +1 -1
- package/dist/core/autonomy-telemetry.js +9 -9
- package/dist/core/autonomy-telemetry.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +56 -236
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +141 -1273
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/bedrock-sso-login.d.ts +16 -0
- package/dist/core/bedrock-sso-login.d.ts.map +1 -0
- package/dist/core/bedrock-sso-login.js +98 -0
- package/dist/core/bedrock-sso-login.js.map +1 -0
- package/dist/core/capability-contract.d.ts +4 -0
- package/dist/core/capability-contract.d.ts.map +1 -0
- package/dist/core/capability-contract.js +28 -0
- package/dist/core/capability-contract.js.map +1 -0
- package/dist/core/compaction-controller.d.ts +90 -0
- package/dist/core/compaction-controller.d.ts.map +1 -0
- package/dist/core/compaction-controller.js +452 -0
- package/dist/core/compaction-controller.js.map +1 -0
- package/dist/core/compaction-support.d.ts +13 -17
- package/dist/core/compaction-support.d.ts.map +1 -1
- package/dist/core/compaction-support.js +3 -3
- package/dist/core/compaction-support.js.map +1 -1
- package/dist/core/context/context-artifacts.d.ts +6 -2
- package/dist/core/context/context-artifacts.d.ts.map +1 -1
- package/dist/core/context/context-artifacts.js +34 -2
- package/dist/core/context/context-artifacts.js.map +1 -1
- package/dist/core/context/context-store-retention.d.ts +8 -2
- package/dist/core/context/context-store-retention.d.ts.map +1 -1
- package/dist/core/context/context-store-retention.js +158 -35
- package/dist/core/context/context-store-retention.js.map +1 -1
- package/dist/core/context/okf-memory.d.ts.map +1 -1
- package/dist/core/context/okf-memory.js +9 -11
- package/dist/core/context/okf-memory.js.map +1 -1
- package/dist/core/context/sqlite-runtime-index.d.ts.map +1 -1
- package/dist/core/context/sqlite-runtime-index.js +6 -8
- package/dist/core/context/sqlite-runtime-index.js.map +1 -1
- package/dist/core/context-gc.d.ts +3 -0
- package/dist/core/context-gc.d.ts.map +1 -1
- package/dist/core/context-gc.js +10 -5
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/context-pipeline.d.ts +1 -1
- package/dist/core/context-pipeline.d.ts.map +1 -1
- package/dist/core/context-pipeline.js +16 -37
- package/dist/core/context-pipeline.js.map +1 -1
- package/dist/core/cost/cost-summary.d.ts.map +1 -1
- package/dist/core/cost/cost-summary.js +5 -3
- package/dist/core/cost/cost-summary.js.map +1 -1
- package/dist/core/cost/daily-usage.d.ts.map +1 -1
- package/dist/core/cost/daily-usage.js +4 -5
- package/dist/core/cost/daily-usage.js.map +1 -1
- package/dist/core/default-tool-surface.d.ts.map +1 -1
- package/dist/core/default-tool-surface.js +2 -0
- package/dist/core/default-tool-surface.js.map +1 -1
- package/dist/core/delegation/managed-lane-controller.d.ts +34 -0
- package/dist/core/delegation/managed-lane-controller.d.ts.map +1 -0
- package/dist/core/delegation/managed-lane-controller.js +217 -0
- package/dist/core/delegation/managed-lane-controller.js.map +1 -0
- package/dist/core/delegation/session-worker-claim.d.ts +44 -0
- package/dist/core/delegation/session-worker-claim.d.ts.map +1 -0
- package/dist/core/delegation/session-worker-claim.js +98 -0
- package/dist/core/delegation/session-worker-claim.js.map +1 -0
- package/dist/core/delegation/worker-actions.d.ts +7 -5
- package/dist/core/delegation/worker-actions.d.ts.map +1 -1
- package/dist/core/delegation/worker-actions.js +20 -4
- package/dist/core/delegation/worker-actions.js.map +1 -1
- package/dist/core/delegation/{worker-result.d.ts → worker-claim.d.ts} +13 -13
- package/dist/core/delegation/worker-claim.d.ts.map +1 -0
- package/dist/core/delegation/{worker-result.js → worker-claim.js} +61 -51
- package/dist/core/delegation/worker-claim.js.map +1 -0
- package/dist/core/delegation/worker-delegation-controller.d.ts +110 -0
- package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -0
- package/dist/core/delegation/worker-delegation-controller.js +861 -0
- package/dist/core/delegation/worker-delegation-controller.js.map +1 -0
- package/dist/core/delegation/worker-delegation-request.d.ts +11 -0
- package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -0
- package/dist/core/delegation/worker-delegation-request.js +2 -0
- package/dist/core/delegation/worker-delegation-request.js.map +1 -0
- package/dist/core/delegation/worker-dispatch-scheduler.d.ts +40 -0
- package/dist/core/delegation/worker-dispatch-scheduler.d.ts.map +1 -0
- package/dist/core/delegation/worker-dispatch-scheduler.js +93 -0
- package/dist/core/delegation/worker-dispatch-scheduler.js.map +1 -0
- package/dist/core/delegation/worker-execution-policy.d.ts +62 -0
- package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -0
- package/dist/core/delegation/worker-execution-policy.js +160 -0
- package/dist/core/delegation/worker-execution-policy.js.map +1 -0
- package/dist/core/delegation/worker-lane-projection.d.ts +14 -0
- package/dist/core/delegation/worker-lane-projection.d.ts.map +1 -0
- package/dist/core/delegation/worker-lane-projection.js +100 -0
- package/dist/core/delegation/worker-lane-projection.js.map +1 -0
- package/dist/core/delegation/worker-lifecycle.d.ts +97 -0
- package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -0
- package/dist/core/delegation/worker-lifecycle.js +339 -0
- package/dist/core/delegation/worker-lifecycle.js.map +1 -0
- package/dist/core/delegation/worker-notification-coordinator.d.ts +36 -0
- package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -0
- package/dist/core/delegation/worker-notification-coordinator.js +90 -0
- package/dist/core/delegation/worker-notification-coordinator.js.map +1 -0
- package/dist/core/delegation/worker-profile-resolver.d.ts +55 -0
- package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -0
- package/dist/core/delegation/worker-profile-resolver.js +113 -0
- package/dist/core/delegation/worker-profile-resolver.js.map +1 -0
- package/dist/core/delegation/worker-runner.d.ts +25 -14
- package/dist/core/delegation/worker-runner.d.ts.map +1 -1
- package/dist/core/delegation/worker-runner.js +122 -53
- package/dist/core/delegation/worker-runner.js.map +1 -1
- package/dist/core/delegation/worker-task-label.d.ts +3 -0
- package/dist/core/delegation/worker-task-label.d.ts.map +1 -0
- package/dist/core/delegation/worker-task-label.js +11 -0
- package/dist/core/delegation/worker-task-label.js.map +1 -0
- package/dist/core/doctor.d.ts +8 -0
- package/dist/core/doctor.d.ts.map +1 -1
- package/dist/core/doctor.js +32 -1
- package/dist/core/doctor.js.map +1 -1
- package/dist/core/extension-import-authority.d.ts +6 -0
- package/dist/core/extension-import-authority.d.ts.map +1 -0
- package/dist/core/extension-import-authority.js +10 -0
- package/dist/core/extension-import-authority.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.map +1 -1
- package/dist/core/extensions/loader.d.ts +5 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +52 -18
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +3 -0
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +20 -5
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/stale-context.d.ts +2 -0
- package/dist/core/extensions/stale-context.d.ts.map +1 -0
- package/dist/core/extensions/stale-context.js +2 -0
- package/dist/core/extensions/stale-context.js.map +1 -0
- package/dist/core/extensions/storage.d.ts +8 -0
- package/dist/core/extensions/storage.d.ts.map +1 -0
- package/dist/core/extensions/storage.js +28 -0
- package/dist/core/extensions/storage.js.map +1 -0
- package/dist/core/extensions/types.d.ts +78 -21
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/failure-corpus.d.ts +1 -15
- package/dist/core/failure-corpus.d.ts.map +1 -1
- package/dist/core/failure-corpus.js +9 -37
- package/dist/core/failure-corpus.js.map +1 -1
- package/dist/core/foreground-recovery-controller.d.ts +53 -0
- package/dist/core/foreground-recovery-controller.d.ts.map +1 -0
- package/dist/core/foreground-recovery-controller.js +111 -0
- package/dist/core/foreground-recovery-controller.js.map +1 -0
- package/dist/core/gateways/channel-provider.d.ts +3 -0
- package/dist/core/gateways/channel-provider.d.ts.map +1 -1
- package/dist/core/gateways/channel-provider.js +31 -6
- package/dist/core/gateways/channel-provider.js.map +1 -1
- package/dist/core/goal-loop-controller.d.ts +14 -9
- package/dist/core/goal-loop-controller.d.ts.map +1 -1
- package/dist/core/goal-loop-controller.js +47 -75
- package/dist/core/goal-loop-controller.js.map +1 -1
- package/dist/core/goals/compact-goal-context.d.ts +11 -0
- package/dist/core/goals/compact-goal-context.d.ts.map +1 -0
- package/dist/core/goals/compact-goal-context.js +59 -0
- package/dist/core/goals/compact-goal-context.js.map +1 -0
- package/dist/core/goals/goal-acceptance.d.ts +11 -0
- package/dist/core/goals/goal-acceptance.d.ts.map +1 -0
- package/dist/core/goals/goal-acceptance.js +27 -0
- package/dist/core/goals/goal-acceptance.js.map +1 -0
- package/dist/core/goals/goal-auto-continue-controller.d.ts +28 -0
- package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -0
- package/dist/core/goals/goal-auto-continue-controller.js +90 -0
- package/dist/core/goals/goal-auto-continue-controller.js.map +1 -0
- package/dist/core/goals/goal-continuation-controller.d.ts +2 -2
- package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-continuation-controller.js +52 -11
- package/dist/core/goals/goal-continuation-controller.js.map +1 -1
- package/dist/core/goals/goal-continuation-defaults.d.ts +4 -29
- package/dist/core/goals/goal-continuation-defaults.d.ts.map +1 -1
- package/dist/core/goals/goal-continuation-defaults.js +4 -32
- package/dist/core/goals/goal-continuation-defaults.js.map +1 -1
- package/dist/core/goals/goal-continuation-prompt.d.ts +8 -18
- package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
- package/dist/core/goals/goal-continuation-prompt.js +9 -179
- package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
- package/dist/core/goals/goal-lifecycle.d.ts +43 -0
- package/dist/core/goals/goal-lifecycle.d.ts.map +1 -0
- package/dist/core/goals/goal-lifecycle.js +102 -0
- package/dist/core/goals/goal-lifecycle.js.map +1 -0
- package/dist/core/goals/goal-record.d.ts +17 -0
- package/dist/core/goals/goal-record.d.ts.map +1 -0
- package/dist/core/goals/goal-record.js +31 -0
- package/dist/core/goals/goal-record.js.map +1 -0
- package/dist/core/goals/goal-runtime-snapshot.d.ts +11 -9
- package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
- package/dist/core/goals/goal-runtime-snapshot.js +10 -8
- package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
- package/dist/core/goals/goal-session-controller.d.ts +42 -0
- package/dist/core/goals/goal-session-controller.d.ts.map +1 -0
- package/dist/core/goals/goal-session-controller.js +128 -0
- package/dist/core/goals/goal-session-controller.js.map +1 -0
- package/dist/core/goals/goal-state.d.ts +46 -25
- package/dist/core/goals/goal-state.d.ts.map +1 -1
- package/dist/core/goals/goal-state.js +91 -24
- package/dist/core/goals/goal-state.js.map +1 -1
- package/dist/core/goals/goal-tool-core.d.ts +9 -10
- package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
- package/dist/core/goals/goal-tool-core.js +60 -75
- package/dist/core/goals/goal-tool-core.js.map +1 -1
- package/dist/core/goals/session-goal-state.d.ts +20 -12
- package/dist/core/goals/session-goal-state.d.ts.map +1 -1
- package/dist/core/goals/session-goal-state.js +133 -33
- package/dist/core/goals/session-goal-state.js.map +1 -1
- package/dist/core/human-input-controller.d.ts +47 -0
- package/dist/core/human-input-controller.d.ts.map +1 -0
- package/dist/core/human-input-controller.js +181 -0
- package/dist/core/human-input-controller.js.map +1 -0
- package/dist/core/human-input.d.ts +100 -0
- package/dist/core/human-input.d.ts.map +1 -0
- package/dist/core/human-input.js +362 -0
- package/dist/core/human-input.js.map +1 -0
- package/dist/core/index.d.ts +9 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +9 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/{telemetry.d.ts → install-telemetry.d.ts} +1 -1
- package/dist/core/install-telemetry.d.ts.map +1 -0
- package/dist/core/{telemetry.js → install-telemetry.js} +1 -1
- package/dist/core/install-telemetry.js.map +1 -0
- package/dist/core/keybindings.d.ts +17 -1
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +24 -6
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/learning/learning-audit.d.ts +2 -4
- package/dist/core/learning/learning-audit.d.ts.map +1 -1
- package/dist/core/learning/learning-audit.js +9 -29
- package/dist/core/learning/learning-audit.js.map +1 -1
- package/dist/core/learning/learning-gate.d.ts.map +1 -1
- package/dist/core/learning/learning-gate.js +1 -6
- package/dist/core/learning/learning-gate.js.map +1 -1
- package/dist/core/learning/session-learning-decision.d.ts +2 -4
- package/dist/core/learning/session-learning-decision.d.ts.map +1 -1
- package/dist/core/learning/session-learning-decision.js +9 -29
- package/dist/core/learning/session-learning-decision.js.map +1 -1
- package/dist/core/local-runtime-controller.d.ts +1 -1
- package/dist/core/local-runtime-controller.d.ts.map +1 -1
- package/dist/core/local-runtime-controller.js.map +1 -1
- package/dist/core/memory-controller.d.ts.map +1 -1
- package/dist/core/memory-controller.js +4 -4
- package/dist/core/memory-controller.js.map +1 -1
- package/dist/core/model-capability.d.ts +0 -19
- package/dist/core/model-capability.d.ts.map +1 -1
- package/dist/core/model-capability.js +1 -19
- package/dist/core/model-capability.js.map +1 -1
- package/dist/core/model-registry.d.ts +6 -1
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +13 -5
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts +17 -2
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +38 -25
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-router/intent-classifier.d.ts +1 -4
- package/dist/core/model-router/intent-classifier.d.ts.map +1 -1
- package/dist/core/model-router/intent-classifier.js +1 -156
- package/dist/core/model-router/intent-classifier.js.map +1 -1
- package/dist/core/model-router-controller.d.ts +1 -1
- package/dist/core/model-router-controller.d.ts.map +1 -1
- package/dist/core/model-router-controller.js +2 -2
- package/dist/core/model-router-controller.js.map +1 -1
- package/dist/core/model-selection-controller.d.ts +5 -5
- package/dist/core/model-selection-controller.d.ts.map +1 -1
- package/dist/core/model-selection-controller.js.map +1 -1
- package/dist/core/model-tool-protocol.d.ts +23 -0
- package/dist/core/model-tool-protocol.d.ts.map +1 -0
- package/dist/core/model-tool-protocol.js +43 -0
- package/dist/core/model-tool-protocol.js.map +1 -0
- package/dist/core/models/adaptation-store.d.ts +4 -6
- package/dist/core/models/adaptation-store.d.ts.map +1 -1
- package/dist/core/models/adaptation-store.js +95 -83
- package/dist/core/models/adaptation-store.js.map +1 -1
- package/dist/core/models/fitness-store.d.ts +2 -12
- package/dist/core/models/fitness-store.d.ts.map +1 -1
- package/dist/core/models/fitness-store.js +84 -57
- package/dist/core/models/fitness-store.js.map +1 -1
- package/dist/core/models/host-state-store.d.ts +34 -0
- package/dist/core/models/host-state-store.d.ts.map +1 -0
- package/dist/core/models/host-state-store.js +86 -0
- package/dist/core/models/host-state-store.js.map +1 -0
- package/dist/core/orchestration/agent-resume.d.ts +24 -0
- package/dist/core/orchestration/agent-resume.d.ts.map +1 -0
- package/dist/core/orchestration/agent-resume.js +90 -0
- package/dist/core/orchestration/agent-resume.js.map +1 -0
- package/dist/core/orchestration/capability-gateway.d.ts +61 -0
- package/dist/core/orchestration/capability-gateway.d.ts.map +1 -0
- package/dist/core/orchestration/capability-gateway.js +152 -0
- package/dist/core/orchestration/capability-gateway.js.map +1 -0
- package/dist/core/orchestration/contracts.d.ts +343 -0
- package/dist/core/orchestration/contracts.d.ts.map +1 -0
- package/dist/core/orchestration/contracts.js +135 -0
- package/dist/core/orchestration/contracts.js.map +1 -0
- package/dist/core/orchestration/delegation-ledger.d.ts +56 -0
- package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -0
- package/dist/core/orchestration/delegation-ledger.js +200 -0
- package/dist/core/orchestration/delegation-ledger.js.map +1 -0
- package/dist/core/orchestration/event-store.d.ts +83 -0
- package/dist/core/orchestration/event-store.d.ts.map +1 -0
- package/dist/core/orchestration/event-store.js +560 -0
- package/dist/core/orchestration/event-store.js.map +1 -0
- package/dist/core/orchestration/lane-tool-manifests.d.ts +9 -0
- package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -0
- package/dist/core/orchestration/lane-tool-manifests.js +37 -0
- package/dist/core/orchestration/lane-tool-manifests.js.map +1 -0
- package/dist/core/orchestration/model-binding.d.ts +15 -0
- package/dist/core/orchestration/model-binding.d.ts.map +1 -0
- package/dist/core/orchestration/model-binding.js +29 -0
- package/dist/core/orchestration/model-binding.js.map +1 -0
- package/dist/core/orchestration/policy-compiler.d.ts +49 -0
- package/dist/core/orchestration/policy-compiler.d.ts.map +1 -0
- package/dist/core/orchestration/policy-compiler.js +191 -0
- package/dist/core/orchestration/policy-compiler.js.map +1 -0
- package/dist/core/orchestration/policy-gate.d.ts +18 -0
- package/dist/core/orchestration/policy-gate.d.ts.map +1 -0
- package/dist/core/orchestration/policy-gate.js +24 -0
- package/dist/core/orchestration/policy-gate.js.map +1 -0
- package/dist/core/orchestration/profile-registry.d.ts +51 -0
- package/dist/core/orchestration/profile-registry.d.ts.map +1 -0
- package/dist/core/orchestration/profile-registry.js +393 -0
- package/dist/core/orchestration/profile-registry.js.map +1 -0
- package/dist/core/orchestration/profile-store.d.ts +31 -0
- package/dist/core/orchestration/profile-store.d.ts.map +1 -0
- package/dist/core/orchestration/profile-store.js +136 -0
- package/dist/core/orchestration/profile-store.js.map +1 -0
- package/dist/core/orchestration/risk-budget.d.ts +9 -0
- package/dist/core/orchestration/risk-budget.d.ts.map +1 -0
- package/dist/core/orchestration/risk-budget.js +48 -0
- package/dist/core/orchestration/risk-budget.js.map +1 -0
- package/dist/core/orchestration/task-runtime.d.ts +168 -0
- package/dist/core/orchestration/task-runtime.d.ts.map +1 -0
- package/dist/core/orchestration/task-runtime.js +1600 -0
- package/dist/core/orchestration/task-runtime.js.map +1 -0
- package/dist/core/orchestration/work-state-projection.d.ts +32 -0
- package/dist/core/orchestration/work-state-projection.d.ts.map +1 -0
- package/dist/core/orchestration/work-state-projection.js +116 -0
- package/dist/core/orchestration/work-state-projection.js.map +1 -0
- package/dist/core/orchestration/worker-execution-contract.d.ts +21 -0
- package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -0
- package/dist/core/orchestration/worker-execution-contract.js +179 -0
- package/dist/core/orchestration/worker-execution-contract.js.map +1 -0
- package/dist/core/orchestration/worker-result-adapter.d.ts +21 -0
- package/dist/core/orchestration/worker-result-adapter.d.ts.map +1 -0
- package/dist/core/orchestration/worker-result-adapter.js +109 -0
- package/dist/core/orchestration/worker-result-adapter.js.map +1 -0
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +20 -3
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/process-identity.d.ts +11 -0
- package/dist/core/process-identity.d.ts.map +1 -0
- package/dist/core/process-identity.js +26 -0
- package/dist/core/process-identity.js.map +1 -0
- package/dist/core/process-matrix/codes.d.ts +14 -3
- package/dist/core/process-matrix/codes.d.ts.map +1 -1
- package/dist/core/process-matrix/codes.js.map +1 -1
- package/dist/core/process-matrix/resume-launcher.d.ts +26 -0
- package/dist/core/process-matrix/resume-launcher.d.ts.map +1 -0
- package/dist/core/process-matrix/resume-launcher.js +62 -0
- package/dist/core/process-matrix/resume-launcher.js.map +1 -0
- package/dist/core/process-matrix/runtime.d.ts +37 -22
- package/dist/core/process-matrix/runtime.d.ts.map +1 -1
- package/dist/core/process-matrix/runtime.js +399 -76
- package/dist/core/process-matrix/runtime.js.map +1 -1
- package/dist/core/process-matrix/store.d.ts +5 -2
- package/dist/core/process-matrix/store.d.ts.map +1 -1
- package/dist/core/process-matrix/store.js +123 -14
- package/dist/core/process-matrix/store.js.map +1 -1
- package/dist/core/process-matrix/supervisor.d.ts +10 -7
- package/dist/core/process-matrix/supervisor.d.ts.map +1 -1
- package/dist/core/process-matrix/supervisor.js +45 -14
- package/dist/core/process-matrix/supervisor.js.map +1 -1
- package/dist/core/profile-filter-controller.d.ts +8 -1
- package/dist/core/profile-filter-controller.d.ts.map +1 -1
- package/dist/core/profile-filter-controller.js +23 -5
- package/dist/core/profile-filter-controller.js.map +1 -1
- package/dist/core/profile-registry.d.ts.map +1 -1
- package/dist/core/profile-registry.js +6 -8
- package/dist/core/profile-registry.js.map +1 -1
- package/dist/core/prompt-templates.d.ts +1 -0
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +18 -29
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/reflection-controller.d.ts +5 -5
- package/dist/core/reflection-controller.d.ts.map +1 -1
- package/dist/core/reflection-controller.js +5 -2
- package/dist/core/reflection-controller.js.map +1 -1
- package/dist/core/reload-blockers.d.ts.map +1 -1
- package/dist/core/reload-blockers.js +6 -8
- package/dist/core/reload-blockers.js.map +1 -1
- package/dist/core/request-auth.d.ts +7 -0
- package/dist/core/request-auth.d.ts.map +1 -0
- package/dist/core/request-auth.js +8 -0
- package/dist/core/request-auth.js.map +1 -0
- package/dist/core/research/evidence-bundle.d.ts.map +1 -1
- package/dist/core/research/evidence-bundle.js +1 -6
- package/dist/core/research/evidence-bundle.js.map +1 -1
- package/dist/core/research/lane-model-resolver.d.ts +33 -0
- package/dist/core/research/lane-model-resolver.d.ts.map +1 -0
- package/dist/core/research/lane-model-resolver.js +65 -0
- package/dist/core/research/lane-model-resolver.js.map +1 -0
- package/dist/core/research/model-fitness-controller.d.ts +38 -0
- package/dist/core/research/model-fitness-controller.d.ts.map +1 -0
- package/dist/core/research/model-fitness-controller.js +106 -0
- package/dist/core/research/model-fitness-controller.js.map +1 -0
- package/dist/core/research/model-fitness.d.ts +1 -1
- package/dist/core/research/model-fitness.d.ts.map +1 -1
- package/dist/core/research/model-fitness.js +4 -4
- package/dist/core/research/model-fitness.js.map +1 -1
- package/dist/core/research/research-gate.d.ts.map +1 -1
- package/dist/core/research/research-gate.js +7 -7
- package/dist/core/research/research-gate.js.map +1 -1
- package/dist/core/research/research-lane-controller.d.ts +62 -0
- package/dist/core/research/research-lane-controller.d.ts.map +1 -0
- package/dist/core/research/research-lane-controller.js +292 -0
- package/dist/core/research/research-lane-controller.js.map +1 -0
- package/dist/core/research/session-evidence-bundle.d.ts +2 -4
- package/dist/core/research/session-evidence-bundle.d.ts.map +1 -1
- package/dist/core/research/session-evidence-bundle.js +10 -46
- package/dist/core/research/session-evidence-bundle.js.map +1 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +23 -8
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/risk-classifier.d.ts +6 -0
- package/dist/core/risk-classifier.d.ts.map +1 -0
- package/dist/core/risk-classifier.js +233 -0
- package/dist/core/risk-classifier.js.map +1 -0
- package/dist/core/runtime-builder.d.ts +41 -23
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +365 -253
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/sdk.d.ts +6 -3
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +68 -25
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/secrets/credential-exposure-guard.d.ts +9 -0
- package/dist/core/secrets/credential-exposure-guard.d.ts.map +1 -0
- package/dist/core/secrets/credential-exposure-guard.js +241 -0
- package/dist/core/secrets/credential-exposure-guard.js.map +1 -0
- package/dist/core/secrets/secret-dotenv.d.ts +27 -0
- package/dist/core/secrets/secret-dotenv.d.ts.map +1 -0
- package/dist/core/secrets/secret-dotenv.js +183 -0
- package/dist/core/secrets/secret-dotenv.js.map +1 -0
- package/dist/core/secrets/secret-vault-format.d.ts +112 -0
- package/dist/core/secrets/secret-vault-format.d.ts.map +1 -0
- package/dist/core/secrets/secret-vault-format.js +397 -0
- package/dist/core/secrets/secret-vault-format.js.map +1 -0
- package/dist/core/secrets/secret-vault.d.ts +72 -0
- package/dist/core/secrets/secret-vault.d.ts.map +1 -0
- package/dist/core/secrets/secret-vault.js +671 -0
- package/dist/core/secrets/secret-vault.js.map +1 -0
- package/dist/core/session-analytics.d.ts +4 -23
- package/dist/core/session-analytics.d.ts.map +1 -1
- package/dist/core/session-analytics.js +67 -70
- package/dist/core/session-analytics.js.map +1 -1
- package/dist/core/session-image-store.d.ts +33 -0
- package/dist/core/session-image-store.d.ts.map +1 -0
- package/dist/core/session-image-store.js +283 -0
- package/dist/core/session-image-store.js.map +1 -0
- package/dist/core/session-role.d.ts +11 -4
- package/dist/core/session-role.d.ts.map +1 -1
- package/dist/core/session-role.js +24 -5
- package/dist/core/session-role.js.map +1 -1
- package/dist/core/session-snapshot.d.ts +34 -0
- package/dist/core/session-snapshot.d.ts.map +1 -0
- package/dist/core/session-snapshot.js +68 -0
- package/dist/core/session-snapshot.js.map +1 -0
- package/dist/core/session-supervision-runtime.d.ts +31 -0
- package/dist/core/session-supervision-runtime.d.ts.map +1 -0
- package/dist/core/session-supervision-runtime.js +97 -0
- package/dist/core/session-supervision-runtime.js.map +1 -0
- package/dist/core/session-tree-navigator.d.ts +4 -6
- package/dist/core/session-tree-navigator.d.ts.map +1 -1
- package/dist/core/session-tree-navigator.js +4 -1
- package/dist/core/session-tree-navigator.js.map +1 -1
- package/dist/core/settings-manager.d.ts +10 -5
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +81 -29
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +2 -2
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/tasks/session-task-state.d.ts +2 -4
- package/dist/core/tasks/session-task-state.d.ts.map +1 -1
- package/dist/core/tasks/session-task-state.js +10 -28
- package/dist/core/tasks/session-task-state.js.map +1 -1
- package/dist/core/tasks/task-projection.d.ts +20 -0
- package/dist/core/tasks/task-projection.d.ts.map +1 -0
- package/dist/core/tasks/task-projection.js +47 -0
- package/dist/core/tasks/task-projection.js.map +1 -0
- package/dist/core/tasks/task-state.d.ts +4 -0
- package/dist/core/tasks/task-state.d.ts.map +1 -1
- package/dist/core/tasks/task-state.js +28 -11
- package/dist/core/tasks/task-state.js.map +1 -1
- package/dist/core/tool-capability-policy.d.ts +13 -0
- package/dist/core/tool-capability-policy.d.ts.map +1 -0
- package/dist/core/tool-capability-policy.js +86 -0
- package/dist/core/tool-capability-policy.js.map +1 -0
- package/dist/core/tool-gate-controller.d.ts.map +1 -1
- package/dist/core/tool-gate-controller.js +8 -2
- package/dist/core/tool-gate-controller.js.map +1 -1
- package/dist/core/tool-protocol-controller.d.ts +89 -0
- package/dist/core/tool-protocol-controller.d.ts.map +1 -0
- package/dist/core/tool-protocol-controller.js +512 -0
- package/dist/core/tool-protocol-controller.js.map +1 -0
- package/dist/core/tool-recovery-log-records.d.ts +2 -3
- package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
- package/dist/core/tool-recovery-log-records.js +9 -35
- package/dist/core/tool-recovery-log-records.js.map +1 -1
- package/dist/core/tool-recovery-stats.d.ts +21 -1
- package/dist/core/tool-recovery-stats.d.ts.map +1 -1
- package/dist/core/tool-recovery-stats.js.map +1 -1
- package/dist/core/tool-selection/tool-performance-store.d.ts +3 -7
- package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -1
- package/dist/core/tool-selection/tool-performance-store.js +97 -138
- package/dist/core/tool-selection/tool-performance-store.js.map +1 -1
- package/dist/core/tools/ask-question.d.ts +124 -0
- package/dist/core/tools/ask-question.d.ts.map +1 -0
- package/dist/core/tools/ask-question.js +693 -0
- package/dist/core/tools/ask-question.js.map +1 -0
- package/dist/core/tools/bash.d.ts +5 -0
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +59 -5
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/delegate-status.d.ts +31 -3
- package/dist/core/tools/delegate-status.d.ts.map +1 -1
- package/dist/core/tools/delegate-status.js +148 -29
- package/dist/core/tools/delegate-status.js.map +1 -1
- package/dist/core/tools/delegate.d.ts +15 -13
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +106 -23
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/extensionify.d.ts.map +1 -1
- package/dist/core/tools/extensionify.js +1 -0
- package/dist/core/tools/extensionify.js.map +1 -1
- package/dist/core/tools/git-filter.d.ts +1 -8
- package/dist/core/tools/git-filter.d.ts.map +1 -1
- package/dist/core/tools/git-filter.js +2 -63
- package/dist/core/tools/git-filter.js.map +1 -1
- package/dist/core/tools/goal.d.ts +10 -8
- package/dist/core/tools/goal.d.ts.map +1 -1
- package/dist/core/tools/goal.js +106 -28
- package/dist/core/tools/goal.js.map +1 -1
- package/dist/core/tools/index.d.ts +1 -0
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +1 -0
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/model-fitness.d.ts.map +1 -1
- package/dist/core/tools/model-fitness.js +2 -2
- package/dist/core/tools/model-fitness.js.map +1 -1
- package/dist/core/tools/orchestration-panel.d.ts +40 -0
- package/dist/core/tools/orchestration-panel.d.ts.map +1 -0
- package/dist/core/tools/orchestration-panel.js +124 -0
- package/dist/core/tools/orchestration-panel.js.map +1 -0
- package/dist/core/tools/output-accumulator.d.ts +11 -0
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +36 -3
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/python.d.ts +2 -0
- package/dist/core/tools/python.d.ts.map +1 -1
- package/dist/core/tools/python.js +3 -1
- package/dist/core/tools/python.js.map +1 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +1 -1
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/run-process.d.ts +26 -0
- package/dist/core/tools/run-process.d.ts.map +1 -0
- package/dist/core/tools/run-process.js +138 -0
- package/dist/core/tools/run-process.js.map +1 -0
- package/dist/core/tools/search-command-guard.d.ts +14 -0
- package/dist/core/tools/search-command-guard.d.ts.map +1 -0
- package/dist/core/tools/search-command-guard.js +333 -0
- package/dist/core/tools/search-command-guard.js.map +1 -0
- package/dist/core/tools/secret-store.d.ts +38 -0
- package/dist/core/tools/secret-store.d.ts.map +1 -0
- package/dist/core/tools/secret-store.js +412 -0
- package/dist/core/tools/secret-store.js.map +1 -0
- package/dist/core/tools/shell-command-parser.d.ts +16 -0
- package/dist/core/tools/shell-command-parser.d.ts.map +1 -0
- package/dist/core/tools/shell-command-parser.js +113 -0
- package/dist/core/tools/shell-command-parser.js.map +1 -0
- package/dist/core/tools/task-steps.d.ts +2 -0
- package/dist/core/tools/task-steps.d.ts.map +1 -1
- package/dist/core/tools/task-steps.js +99 -0
- package/dist/core/tools/task-steps.js.map +1 -1
- package/dist/core/tools/tmux-dispatch.d.ts +3 -5
- package/dist/core/tools/tmux-dispatch.d.ts.map +1 -1
- package/dist/core/tools/tmux-dispatch.js +4 -4
- package/dist/core/tools/tmux-dispatch.js.map +1 -1
- package/dist/core/tools/windows-shell-engine.d.ts.map +1 -1
- package/dist/core/tools/windows-shell-engine.js +4 -6
- package/dist/core/tools/windows-shell-engine.js.map +1 -1
- package/dist/core/util/atomic-file.d.ts +6 -2
- package/dist/core/util/atomic-file.d.ts.map +1 -1
- package/dist/core/util/atomic-file.js +4 -4
- package/dist/core/util/atomic-file.js.map +1 -1
- package/dist/core/util/bounded-jsonl.d.ts +10 -0
- package/dist/core/util/bounded-jsonl.d.ts.map +1 -0
- package/dist/core/util/bounded-jsonl.js +75 -0
- package/dist/core/util/bounded-jsonl.js.map +1 -0
- package/dist/core/util/value-guards.d.ts +5 -0
- package/dist/core/util/value-guards.d.ts.map +1 -0
- package/dist/core/util/value-guards.js +12 -0
- package/dist/core/util/value-guards.js.map +1 -0
- package/dist/core/worktree-sync/store.d.ts +3 -3
- package/dist/core/worktree-sync/store.d.ts.map +1 -1
- package/dist/core/worktree-sync/store.js +10 -5
- package/dist/core/worktree-sync/store.js.map +1 -1
- package/dist/index.d.ts +15 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +14 -3
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +149 -51
- package/dist/main.js.map +1 -1
- package/dist/migrations.d.ts +4 -6
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +186 -28
- package/dist/migrations.js.map +1 -1
- package/dist/modes/interactive/auth-dialogs-controller.d.ts +4 -0
- package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -1
- package/dist/modes/interactive/auth-dialogs-controller.js +60 -1
- package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -1
- package/dist/modes/interactive/clipboard-input.d.ts +7 -1
- package/dist/modes/interactive/clipboard-input.d.ts.map +1 -1
- package/dist/modes/interactive/clipboard-input.js +44 -6
- package/dist/modes/interactive/clipboard-input.js.map +1 -1
- package/dist/modes/interactive/components/activity-lane.d.ts +55 -0
- package/dist/modes/interactive/components/activity-lane.d.ts.map +1 -0
- package/dist/modes/interactive/components/activity-lane.js +304 -0
- package/dist/modes/interactive/components/activity-lane.js.map +1 -0
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +19 -10
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/expandable-text.d.ts +12 -0
- package/dist/modes/interactive/components/expandable-text.d.ts.map +1 -0
- package/dist/modes/interactive/components/expandable-text.js +17 -0
- package/dist/modes/interactive/components/expandable-text.js.map +1 -0
- package/dist/modes/interactive/components/extension-editor.d.ts +15 -1
- package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-editor.js +30 -21
- package/dist/modes/interactive/components/extension-editor.js.map +1 -1
- package/dist/modes/interactive/components/extension-input.d.ts +1 -0
- package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-input.js +6 -1
- package/dist/modes/interactive/components/extension-input.js.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts +2 -2
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +23 -14
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +6 -6
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +19 -11
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +53 -20
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tool-group.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-group.js +3 -0
- package/dist/modes/interactive/components/tool-group.js.map +1 -1
- package/dist/modes/interactive/components/usage-action-selector.d.ts +16 -0
- package/dist/modes/interactive/components/usage-action-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/usage-action-selector.js +46 -0
- package/dist/modes/interactive/components/usage-action-selector.js.map +1 -0
- package/dist/modes/interactive/config-backup.d.ts.map +1 -1
- package/dist/modes/interactive/config-backup.js +5 -4
- package/dist/modes/interactive/config-backup.js.map +1 -1
- package/dist/modes/interactive/extension-ui-host.d.ts +14 -0
- package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -1
- package/dist/modes/interactive/extension-ui-host.js +77 -15
- package/dist/modes/interactive/extension-ui-host.js.map +1 -1
- package/dist/modes/interactive/external-editor.d.ts +15 -0
- package/dist/modes/interactive/external-editor.d.ts.map +1 -1
- package/dist/modes/interactive/external-editor.js +27 -19
- package/dist/modes/interactive/external-editor.js.map +1 -1
- package/dist/modes/interactive/history-reload-math.d.ts +6 -2
- package/dist/modes/interactive/history-reload-math.d.ts.map +1 -1
- package/dist/modes/interactive/history-reload-math.js +10 -5
- package/dist/modes/interactive/history-reload-math.js.map +1 -1
- package/dist/modes/interactive/interactive-event-controller.d.ts +74 -0
- package/dist/modes/interactive/interactive-event-controller.d.ts.map +1 -0
- package/dist/modes/interactive/interactive-event-controller.js +328 -0
- package/dist/modes/interactive/interactive-event-controller.js.map +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts +22 -24
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +245 -595
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/key-handlers.d.ts.map +1 -1
- package/dist/modes/interactive/key-handlers.js +1 -1
- package/dist/modes/interactive/key-handlers.js.map +1 -1
- package/dist/modes/interactive/loaded-resources-view.d.ts +20 -0
- package/dist/modes/interactive/loaded-resources-view.d.ts.map +1 -0
- package/dist/modes/interactive/loaded-resources-view.js +147 -0
- package/dist/modes/interactive/loaded-resources-view.js.map +1 -0
- package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
- package/dist/modes/interactive/profile-menu-controller.js +7 -7
- package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
- package/dist/modes/interactive/report-commands.d.ts.map +1 -1
- package/dist/modes/interactive/report-commands.js +21 -0
- package/dist/modes/interactive/report-commands.js.map +1 -1
- package/dist/modes/interactive/resource-display.d.ts.map +1 -1
- package/dist/modes/interactive/resource-display.js +8 -2
- package/dist/modes/interactive/resource-display.js.map +1 -1
- package/dist/modes/interactive/resource-shell-commands.d.ts +1 -5
- package/dist/modes/interactive/resource-shell-commands.d.ts.map +1 -1
- package/dist/modes/interactive/resource-shell-commands.js +0 -5
- package/dist/modes/interactive/resource-shell-commands.js.map +1 -1
- package/dist/modes/interactive/session-flow-commands.d.ts +27 -8
- package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
- package/dist/modes/interactive/session-flow-commands.js +150 -64
- package/dist/modes/interactive/session-flow-commands.js.map +1 -1
- package/dist/modes/interactive/session-io-commands.d.ts.map +1 -1
- package/dist/modes/interactive/session-io-commands.js +16 -6
- package/dist/modes/interactive/session-io-commands.js.map +1 -1
- package/dist/modes/interactive/session-replacement-errors.d.ts +7 -0
- package/dist/modes/interactive/session-replacement-errors.d.ts.map +1 -0
- package/dist/modes/interactive/session-replacement-errors.js +15 -0
- package/dist/modes/interactive/session-replacement-errors.js.map +1 -0
- package/dist/modes/interactive/startup-checks.d.ts.map +1 -1
- package/dist/modes/interactive/startup-checks.js +1 -1
- package/dist/modes/interactive/startup-checks.js.map +1 -1
- package/dist/modes/interactive/usage-commands.d.ts +34 -0
- package/dist/modes/interactive/usage-commands.d.ts.map +1 -0
- package/dist/modes/interactive/usage-commands.js +225 -0
- package/dist/modes/interactive/usage-commands.js.map +1 -0
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +82 -23
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +15 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js +138 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +2 -13
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/clipboard-native.d.ts +1 -0
- package/dist/utils/clipboard-native.d.ts.map +1 -1
- package/dist/utils/clipboard-native.js.map +1 -1
- package/dist/utils/clipboard.d.ts +1 -0
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +52 -1
- package/dist/utils/clipboard.js.map +1 -1
- package/dist/utils/platform.d.ts +3 -0
- package/dist/utils/platform.d.ts.map +1 -0
- package/dist/utils/platform.js +8 -0
- package/dist/utils/platform.js.map +1 -0
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +5 -3
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/version-check.d.ts.map +1 -1
- package/dist/utils/version-check.js +3 -1
- package/dist/utils/version-check.js.map +1 -1
- package/dist/utils/work-directory.d.ts +11 -0
- package/dist/utils/work-directory.d.ts.map +1 -1
- package/dist/utils/work-directory.js +30 -9
- package/dist/utils/work-directory.js.map +1 -1
- package/docs/UI_POLISH_ORCHESTRATION.md +38 -0
- package/docs/UI_QUALITY_ORCHESTRATION.md +28 -0
- package/docs/docs.json +4 -0
- package/docs/extensions.md +62 -2
- package/docs/harness-architecture.md +156 -0
- package/docs/keybindings.md +11 -1
- package/docs/process-matrix.md +59 -26
- package/docs/providers.md +9 -1
- package/docs/rpc.md +45 -2
- package/docs/sessions.md +15 -0
- package/docs/settings.md +125 -11
- package/docs/task-steps.md +8 -0
- package/docs/telemetry.md +19 -0
- package/docs/tmux-agent-manager.md +10 -3
- package/docs/ui-reference/README.md +9 -0
- package/docs/ui-reference/orchestration-after.txt +14 -0
- package/docs/ui-reference/orchestration-before.txt +13 -0
- package/docs/ui-reference/orchestration-reference.txt +16 -0
- package/docs/usage.md +22 -2
- package/docs/work-directory.md +19 -8
- 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/question.ts +34 -245
- package/examples/extensions/questionnaire.ts +41 -407
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +13 -13
- package/package.json +4 -4
- package/dist/core/delegation/session-worker-result.d.ts +0 -46
- package/dist/core/delegation/session-worker-result.d.ts.map +0 -1
- package/dist/core/delegation/session-worker-result.js +0 -113
- package/dist/core/delegation/session-worker-result.js.map +0 -1
- package/dist/core/delegation/worker-result.d.ts.map +0 -1
- package/dist/core/delegation/worker-result.js.map +0 -1
- package/dist/core/telemetry.d.ts.map +0 -1
- package/dist/core/telemetry.js.map +0 -1
|
@@ -12,7 +12,8 @@
|
|
|
12
12
|
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
13
13
|
import { join } from "node:path";
|
|
14
14
|
import { runAgentLoop, } from "@caupulican/pi-agent-core";
|
|
15
|
-
import {
|
|
15
|
+
import { resolveModelThinkingLevel, } from "@caupulican/pi-ai";
|
|
16
|
+
import { computeLaneAffinityKey, DEFAULT_ISOLATED_LANE_KIND, } from "./agent-session-contracts.js";
|
|
16
17
|
import { AUTONOMY_TELEMETRY_EVENT_TYPES } from "./autonomy/telemetry-events.js";
|
|
17
18
|
import { APPLY_WRITE_REFUSED_REASON_CODE, appendLearningAuditSnapshot, contradictionsForReflectionWrite, getLearningAuditSnapshots, proposalFromReflectionWrite, rollbackPlanForReflectionWrite, } from "./learning/learning-audit.js";
|
|
18
19
|
import { evaluateLearningDecision } from "./learning/learning-gate.js";
|
|
@@ -51,7 +52,7 @@ export class ReflectionController {
|
|
|
51
52
|
throw new Error("runIsolatedCompletion: no model available");
|
|
52
53
|
}
|
|
53
54
|
await this.deps.ensureModelReady(model);
|
|
54
|
-
const thinkingLevel = opts.thinkingLevel
|
|
55
|
+
const thinkingLevel = resolveModelThinkingLevel(model, opts.thinkingLevel, "off");
|
|
55
56
|
// Registered for the full isolated-completion call (one-shot or child-loop) so the
|
|
56
57
|
// reload gate waits it out — this is the SINGLE choke point every isolated completion in the
|
|
57
58
|
// codebase runs through (reflection, research/worker/fitness lanes, context-pipeline curation,
|
|
@@ -75,6 +76,7 @@ export class ReflectionController {
|
|
|
75
76
|
const options = {
|
|
76
77
|
maxTokens: opts.maxTokens,
|
|
77
78
|
signal: opts.signal,
|
|
79
|
+
interactionMode: "background",
|
|
78
80
|
cacheRetention: opts.cacheRetention,
|
|
79
81
|
reasoning: thinkingLevel,
|
|
80
82
|
sessionId: affinityKey,
|
|
@@ -105,6 +107,7 @@ export class ReflectionController {
|
|
|
105
107
|
};
|
|
106
108
|
const loopConfig = {
|
|
107
109
|
model,
|
|
110
|
+
interactionMode: "background",
|
|
108
111
|
maxTokens: opts.maxTokens,
|
|
109
112
|
cacheRetention: opts.cacheRetention,
|
|
110
113
|
reasoning: thinkingLevel,
|
|
@@ -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,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAIN,YAAY,GAEZ,MAAM,2BAA2B,CAAC;AAGnC,OAAO,EACN,sBAAsB,EACtB,0BAA0B,GAG1B,MAAM,oBAAoB,CAAC;AAE5B,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,CA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C,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;IAAA,CACD;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 { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n\ttype Agent,\n\ttype AgentContext,\n\ttype AgentLoopConfig,\n\trunAgentLoop,\n\ttype ThinkingLevel,\n} from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Api, AssistantMessage, Context, Model, SimpleStreamOptions, TextContent, Usage } from \"@caupulican/pi-ai\";\nimport {\n\tcomputeLaneAffinityKey,\n\tDEFAULT_ISOLATED_LANE_KIND,\n\ttype IsolatedCompletionOptions,\n\ttype IsolatedCompletionResult,\n} from \"./agent-session.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 type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { ModelRegistry } from \"./model-registry.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<any> | 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<any>): 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\nexport class ReflectionController {\n\tprivate readonly deps: ReflectionControllerDeps;\n\n\tconstructor(deps: ReflectionControllerDeps) {\n\t\tthis.deps = deps;\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 is turn-bounded. 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\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 = 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 context: Context = {\n\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\tmessages: 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\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\n\t\t\tif (opts.tools && opts.tools.length > 0) {\n\t\t\t\tconst agent = this.deps.getAgent();\n\t\t\t\tconst foregroundModel = agent.state.model;\n\t\t\t\tconst usesForegroundModel = foregroundModel?.provider === model.provider && foregroundModel.id === model.id;\n\t\t\t\tconst textToolCallProtocol = this.deps.resolveTextToolCallProtocol(model);\n\t\t\t\tconst requestedMaxTurns =\n\t\t\t\t\ttypeof opts.maxTurns === \"number\" && Number.isFinite(opts.maxTurns) ? Math.floor(opts.maxTurns) : 6;\n\t\t\t\tconst maxTurns = Math.max(1, Math.min(12, requestedMaxTurns));\n\t\t\t\tlet completedTurns = 0;\n\t\t\t\tconst childContext: AgentContext = {\n\t\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\t\tmessages: [],\n\t\t\t\t\ttools: [...opts.tools],\n\t\t\t\t};\n\t\t\t\tconst loopConfig: AgentLoopConfig = {\n\t\t\t\t\tmodel,\n\t\t\t\t\tmaxTokens: opts.maxTokens,\n\t\t\t\t\tcacheRetention: opts.cacheRetention,\n\t\t\t\t\treasoning: thinkingLevel,\n\t\t\t\t\t// Same synthetic per-lane affinity key as the one-shot path above — never the real sessionId.\n\t\t\t\t\tsessionId: affinityKey,\n\t\t\t\t\t...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n\t\t\t\t\t...(options.headers !== undefined ? { headers: options.headers } : {}),\n\t\t\t\t\ttemperature: textToolCallProtocol ? 0 : undefined,\n\t\t\t\t\ttextToolCallProtocol,\n\t\t\t\t\tonTextToolProtocolParse: usesForegroundModel ? agent.onTextToolProtocolParse : undefined,\n\t\t\t\t\ttransport: agent.transport,\n\t\t\t\t\tthinkingBudgets: agent.thinkingBudgets,\n\t\t\t\t\tmaxRetryDelayMs: agent.maxRetryDelayMs,\n\t\t\t\t\tmaxStallTurns: Math.max(2, Math.min(maxTurns, agent.maxStallTurns ?? maxTurns)),\n\t\t\t\t\tonRunawayStop: usesForegroundModel ? agent.onRunawayStop : undefined,\n\t\t\t\t\ttoolExecution: \"sequential\",\n\t\t\t\t\ttoolArgumentTeachEnabled: agent.toolArgumentTeachEnabled,\n\t\t\t\t\tonToolArgumentValidation: usesForegroundModel ? agent.onToolArgumentValidation : undefined,\n\t\t\t\t\ttoolValidationEscalationThreshold: agent.toolValidationEscalationThreshold,\n\t\t\t\t\tonToolValidationEscalation: usesForegroundModel ? agent.onToolValidationEscalation : undefined,\n\t\t\t\t\tbeforeToolCall: opts.beforeToolCall,\n\t\t\t\t\tafterToolCall: opts.afterToolCall,\n\t\t\t\t\tshouldStopAfterTurn: () => {\n\t\t\t\t\t\tcompletedTurns += 1;\n\t\t\t\t\t\treturn completedTurns >= maxTurns;\n\t\t\t\t\t},\n\t\t\t\t\tconvertToLlm: agent.convertToLlm,\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\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 finalizationMessages = await agent.convertToLlm(messages);\n\t\t\t\t\tconst finalizationStream = await agent.streamFn(\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\t\t\t\tmessages: [\n\t\t\t\t\t\t\t\t...finalizationMessages,\n\t\t\t\t\t\t\t\t{ role: \"user\", content: opts.finalTextPrompt, timestamp: Date.now() },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\ttools: [],\n\t\t\t\t\t\t},\n\t\t\t\t\t\toptions,\n\t\t\t\t\t);\n\t\t\t\t\tfinalAssistant = await finalizationStream.result();\n\t\t\t\t\tassistantMessages.push(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\treturn { text, usage, stopReason: finalAssistant.stopReason };\n\t\t\t}\n\n\t\t\tconst stream = await this.deps.getAgent().streamFn(model, context, options);\n\t\t\tconst result = await stream.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 };\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<any>;\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}): 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. With the policy disabled (default) the\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 decision: LearningDecision = policy.enabled\n\t\t\t\t? evaluateLearningDecision({\n\t\t\t\t\t\tproposal,\n\t\t\t\t\t\tconfidence: policy.reflectionSourceConfidence,\n\t\t\t\t\t\tobservations,\n\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// confront-before-write conflict signal — so it routes through approval instead of\n\t\t\t\t\t\t// silently overwriting prior memory. Additive writes contradict nothing.\n\t\t\t\t\t\tcontradictions: contradictionsForReflectionWrite(write),\n\t\t\t\t\t\tsettings: {\n\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\tautoApplyEnabled: policy.autoApplyEnabled,\n\t\t\t\t\t\t\tconfidenceThreshold: policy.confidenceThreshold,\n\t\t\t\t\t\t\tminObservations: policy.minObservations,\n\t\t\t\t\t\t\tallowedAutoApplyLayers: policy.allowedAutoApplyLayers,\n\t\t\t\t\t\t\trequireRollbackPlan: policy.requireRollbackPlan,\n\t\t\t\t\t\t\tautoApplySupersessions: policy.autoApplySupersessions,\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t: {\n\t\t\t\t\t\tkind: \"apply\",\n\t\t\t\t\t\treasonCode: \"learning_policy_disabled_legacy_apply\",\n\t\t\t\t\t\tconfidence: 0,\n\t\t\t\t\t\tsummary: proposal.summary,\n\t\t\t\t\t\trequiresApproval: false,\n\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","sour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,EAAE,IAAY,EAAW;QAC5F,MAAM,IAAI,GAAG,OAAO;aAClB,IAAI,EAAE;aACN,WAAW,EAAE;aACb,OAAO,CAAC,cAAc,EAAE,GAAG,CAAC;aAC5B,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;aACvB,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,IAAI,CAAC,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;IAAA,CACD;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 { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n\ttype Agent,\n\ttype AgentContext,\n\ttype AgentLoopConfig,\n\trunAgentLoop,\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 Context,\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 type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { ModelRegistry } from \"./model-registry.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\nexport class ReflectionController {\n\tprivate readonly deps: ReflectionControllerDeps;\n\n\tconstructor(deps: ReflectionControllerDeps) {\n\t\tthis.deps = deps;\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 is turn-bounded. 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\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 context: Context = {\n\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\tmessages: 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\n\t\t\tif (opts.tools && opts.tools.length > 0) {\n\t\t\t\tconst agent = this.deps.getAgent();\n\t\t\t\tconst foregroundModel = agent.state.model;\n\t\t\t\tconst usesForegroundModel = foregroundModel?.provider === model.provider && foregroundModel.id === model.id;\n\t\t\t\tconst textToolCallProtocol = this.deps.resolveTextToolCallProtocol(model);\n\t\t\t\tconst requestedMaxTurns =\n\t\t\t\t\ttypeof opts.maxTurns === \"number\" && Number.isFinite(opts.maxTurns) ? Math.floor(opts.maxTurns) : 6;\n\t\t\t\tconst maxTurns = Math.max(1, Math.min(12, requestedMaxTurns));\n\t\t\t\tlet completedTurns = 0;\n\t\t\t\tconst childContext: AgentContext = {\n\t\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\t\tmessages: [],\n\t\t\t\t\ttools: [...opts.tools],\n\t\t\t\t};\n\t\t\t\tconst loopConfig: AgentLoopConfig = {\n\t\t\t\t\tmodel,\n\t\t\t\t\tinteractionMode: \"background\",\n\t\t\t\t\tmaxTokens: opts.maxTokens,\n\t\t\t\t\tcacheRetention: opts.cacheRetention,\n\t\t\t\t\treasoning: thinkingLevel,\n\t\t\t\t\t// Same synthetic per-lane affinity key as the one-shot path above — never the real sessionId.\n\t\t\t\t\tsessionId: affinityKey,\n\t\t\t\t\t...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n\t\t\t\t\t...(options.headers !== undefined ? { headers: options.headers } : {}),\n\t\t\t\t\ttemperature: textToolCallProtocol ? 0 : undefined,\n\t\t\t\t\ttextToolCallProtocol,\n\t\t\t\t\tonTextToolProtocolParse: usesForegroundModel ? agent.onTextToolProtocolParse : undefined,\n\t\t\t\t\ttransport: agent.transport,\n\t\t\t\t\tthinkingBudgets: agent.thinkingBudgets,\n\t\t\t\t\tmaxRetryDelayMs: agent.maxRetryDelayMs,\n\t\t\t\t\tmaxStallTurns: Math.max(2, Math.min(maxTurns, agent.maxStallTurns ?? maxTurns)),\n\t\t\t\t\tonRunawayStop: usesForegroundModel ? agent.onRunawayStop : undefined,\n\t\t\t\t\ttoolExecution: \"sequential\",\n\t\t\t\t\ttoolArgumentTeachEnabled: agent.toolArgumentTeachEnabled,\n\t\t\t\t\tonToolArgumentValidation: usesForegroundModel ? agent.onToolArgumentValidation : undefined,\n\t\t\t\t\ttoolValidationEscalationThreshold: agent.toolValidationEscalationThreshold,\n\t\t\t\t\tonToolValidationEscalation: usesForegroundModel ? agent.onToolValidationEscalation : undefined,\n\t\t\t\t\tbeforeToolCall: opts.beforeToolCall,\n\t\t\t\t\tafterToolCall: opts.afterToolCall,\n\t\t\t\t\tshouldStopAfterTurn: () => {\n\t\t\t\t\t\tcompletedTurns += 1;\n\t\t\t\t\t\treturn completedTurns >= maxTurns;\n\t\t\t\t\t},\n\t\t\t\t\tconvertToLlm: agent.convertToLlm,\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\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 finalizationMessages = await agent.convertToLlm(messages);\n\t\t\t\t\tconst finalizationStream = await agent.streamFn(\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsystemPrompt: opts.systemPrompt,\n\t\t\t\t\t\t\tmessages: [\n\t\t\t\t\t\t\t\t...finalizationMessages,\n\t\t\t\t\t\t\t\t{ role: \"user\", content: opts.finalTextPrompt, timestamp: Date.now() },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\ttools: [],\n\t\t\t\t\t\t},\n\t\t\t\t\t\toptions,\n\t\t\t\t\t);\n\t\t\t\t\tfinalAssistant = await finalizationStream.result();\n\t\t\t\t\tassistantMessages.push(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\treturn { text, usage, stopReason: finalAssistant.stopReason };\n\t\t\t}\n\n\t\t\tconst stream = await this.deps.getAgent().streamFn(model, context, options);\n\t\t\tconst result = await stream.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 };\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}): 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. With the policy disabled (default) the\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 decision: LearningDecision = policy.enabled\n\t\t\t\t? evaluateLearningDecision({\n\t\t\t\t\t\tproposal,\n\t\t\t\t\t\tconfidence: policy.reflectionSourceConfidence,\n\t\t\t\t\t\tobservations,\n\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// confront-before-write conflict signal — so it routes through approval instead of\n\t\t\t\t\t\t// silently overwriting prior memory. Additive writes contradict nothing.\n\t\t\t\t\t\tcontradictions: contradictionsForReflectionWrite(write),\n\t\t\t\t\t\tsettings: {\n\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\tautoApplyEnabled: policy.autoApplyEnabled,\n\t\t\t\t\t\t\tconfidenceThreshold: policy.confidenceThreshold,\n\t\t\t\t\t\t\tminObservations: policy.minObservations,\n\t\t\t\t\t\t\tallowedAutoApplyLayers: policy.allowedAutoApplyLayers,\n\t\t\t\t\t\t\trequireRollbackPlan: policy.requireRollbackPlan,\n\t\t\t\t\t\t\tautoApplySupersessions: policy.autoApplySupersessions,\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t: {\n\t\t\t\t\t\tkind: \"apply\",\n\t\t\t\t\t\treasonCode: \"learning_policy_disabled_legacy_apply\",\n\t\t\t\t\t\tconfidence: 0,\n\t\t\t\t\t\tsummary: proposal.summary,\n\t\t\t\t\t\trequiresApproval: false,\n\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reload-blockers.d.ts","sourceRoot":"","sources":["../../src/core/reload-blockers.ts"],"names":[],"mappings":"AAYA,eAAO,MAAM,kBAAkB,QAAa,CAAC;AAC7C,eAAO,MAAM,8BAA8B,QAAc,CAAC;AAE1D,wBAAgB,wBAAwB,CAAC,QAAQ,GAAE,MAAsB,GAAG,MAAM,CAEjF;AAED,MAAM,WAAW,mBAAmB;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,aAAa,GAAG,aAAa,CAAC;IACtC,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,GAAG,CAAC,E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M,WAAW,gBAAgB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,gBAAgB,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,YAAY,EAAE,MAAM,CAAC;CACrB;AAKD,oGAAoG;AACpG,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,IAAI,CAgBxG;AAED,2FAA2F;AAC3F,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,GAAG,gBAAgB,EAAE,CAGzE;AAED,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,gBAAgB,GAAG,MAAM,CAEvE;AAED;;;GAGG;AACH,wBAAgB,iCAAiC,IAAI,IAAI,CAExD","sourcesContent":["/**\n * Reload/live-op blocker sources for THIS process's reload gate (`RuntimeBuilder`, see\n * runtime-builder.ts): cross-process peer/coordinator sessions (file-backed, below) AND the\n * in-process quiesce registry (`registerInFlightWork`/`getInFlightWorkUnits`) that tracks background\n * lanes, context-scout runs, and isolated completions running in THIS process. The gate reads both;\n * `getPendingReloadBlockers` (cross-process) also backs the `/autonomy` status text.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getAgentDir } from \"../config.ts\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\n\nexport const ACTIVE_TURN_TTL_MS = 5 * 60_000;\nexport const AUTO_RELOAD_COORDINATOR_TTL_MS = 10 * 60_000;\n\nexport function getReloadCoordinationDir(agentDir: string = getAgentDir()): string {\n\treturn getProcessWorkRun(agentDir, \"coordination\", \"reload\", \"state\").path;\n}\n\nexport interface ReloadSessionRecord {\n\tkey: string;\n\tsource: \"active-turn\" | \"coordinator\";\n\tpid?: number;\n\tsessionId?: string;\n\tsessionFile?: string;\n\tcwd?: string;\n\tactive?: boolean;\n\tupdatedAt?: number;\n\tseenAt?: number;\n\treloadedAt?: number;\n\treason?: string;\n}\n\nexport interface PendingReloadBlockers {\n\tpending: boolean;\n\treason: string;\n\tblockers: ReloadSessionRecord[];\n\tdescriptions: string[];\n}\n\nexport interface ReloadBlockerOptions {\n\tagentDir?: string;\n\tnow?: number;\n\townKey?: string;\n\townPid?: number;\n\townSessionId?: string;\n\townSessionFile?: string;\n\tactiveTurnTtlMs?: number;\n\tcoordinatorTtlMs?: number;\n\t/** Auto Learn workers are memory-first, short-lived, and should not block foreground reload/adaptive work by default. */\n\tincludeAutoLearnSessions?: boolean;\n\tisProcessAlive?: (pid: number | undefined) => boolean;\n}\n\ninterface ParsedSession {\n\tpid?: number;\n\tsessionId?: string;\n\tsessionFile?: string;\n\tcwd?: string;\n\tactive?: boolean;\n\tupdatedAt?: number;\n\tseenAt?: number;\n\treloadedAt?: number;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction readJsonFile(file: string): unknown {\n\ttry {\n\t\tif (!existsSync(file)) return undefined;\n\t\treturn JSON.parse(readFileSync(file, \"utf8\")) as unknown;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction stringValue(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\treturn undefined;\n}\n\nfunction booleanValue(value: unknown): boolean | undefined {\n\treturn typeof value === \"boolean\" ? value : undefined;\n}\n\nfunction parseSession(value: unknown): ParsedSession | undefined {\n\tif (!isRecord(value)) return undefined;\n\treturn {\n\t\tpid: numberValue(value.pid),\n\t\tsessionId: stringValue(value.sessionId),\n\t\tsessionFile: stringValue(value.sessionFile),\n\t\tcwd: stringValue(value.cwd),\n\t\tactive: booleanValue(value.active),\n\t\tupdatedAt: numberValue(value.updatedAt),\n\t\tseenAt: numberValue(value.seenAt),\n\t\treloadedAt: numberValue(value.reloadedAt),\n\t};\n}\n\nexport function isReloadSessionProcessAlive(pid: number | undefined): boolean {\n\tif (pid === undefined || !Number.isFinite(pid) || pid <= 0) return false;\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\tconst code =\n\t\t\terror && typeof error === \"object\" && \"code\" in error ? String((error as { code?: unknown }).code) : \"\";\n\t\treturn code === \"EPERM\";\n\t}\n}\n\nfunction isOwnSession(key: string, session: ParsedSession, options: ReloadBlockerOptions): boolean {\n\tif (options.ownKey && key === options.ownKey) return true;\n\tif (options.ownPid !== undefined && session.pid === options.ownPid) return true;\n\tif (options.ownSessionId && session.sessionId === options.ownSessionId) return true;\n\tif (options.ownSessionFile && session.sessionFile === options.ownSessionFile) return true;\n\treturn false;\n}\n\nfunction isAutoLearnSession(session: ParsedSession): boolean {\n\treturn !!session.sessionId?.startsWith(\"auto-learn-\");\n}\n\nfunction shouldIgnoreSession(session: ParsedSession, options: ReloadBlockerOptions): boolean {\n\treturn options.includeAutoLearnSessions !== true && isAutoLearnSession(session);\n}\n\nfunction addBlocker(blockers: Map<string, ReloadSessionRecord>, record: ReloadSessionRecord): void {\n\tconst identity = [\n\t\trecord.key,\n\t\trecord.pid ?? \"\",\n\t\trecord.sessionId ?? \"\",\n\t\trecord.sessionFile ?? \"\",\n\t\trecord.cwd ?? \"\",\n\t].join(\"\\0\");\n\tconst existing = blockers.get(identity);\n\tif (!existing || (existing.source === \"coordinator\" && record.source === \"active-turn\")) {\n\t\tblockers.set(identity, record);\n\t}\n}\n\nfunction activeTurnBlockers(options: ReloadBlockerOptions): ReloadSessionRecord[] {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst now = options.now ?? Date.now();\n\tconst ttl = options.activeTurnTtlMs ?? ACTIVE_TURN_TTL_MS;\n\tconst isAlive = options.isProcessAlive ?? isReloadSessionProcessAlive;\n\tconst registry = readJsonFile(join(getReloadCoordinationDir(agentDir), \"active-turns.json\"));\n\tif (!isRecord(registry) || !isRecord(registry.sessions)) return [];\n\n\tconst blockers: ReloadSessionRecord[] = [];\n\tfor (const [key, rawSession] of Object.entries(registry.sessions)) {\n\t\tconst session = parseSession(rawSession);\n\t\tif (!session?.active) continue;\n\t\tif (isOwnSession(key, session, options) || shouldIgnoreSession(session, options)) continue;\n\t\tif (session.updatedAt === undefined || now - session.updatedAt > ttl) continue;\n\t\tif (!isAlive(session.pid)) continue;\n\t\tblockers.push({ key, source: \"active-turn\", ...session });\n\t}\n\treturn blockers;\n}\n\nfunction coordinatorBlockers(options: ReloadBlockerOptions): { blockers: ReloadSessionRecord[]; reason: string } {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst now = options.now ?? Date.now();\n\tconst ttl = options.coordinatorTtlMs ?? AUTO_RELOAD_COORDINATOR_TTL_MS;\n\tconst isAlive = options.isProcessAlive ?? isReloadSessionProcessAlive;\n\tconst coordinator = readJsonFile(join(getReloadCoordinationDir(agentDir), \"auto-reload-state.json\"));\n\tif (!isRecord(coordinator) || !isRecord(coordinator.changes)) return { blockers: [], reason: \"\" };\n\n\tconst blockers: ReloadSessionRecord[] = [];\n\tlet reason = \"\";\n\tfor (const rawChange of Object.values(coordinator.changes)) {\n\t\tif (!isRecord(rawChange)) continue;\n\t\tconst firstSeenAt = numberValue(rawChange.firstSeenAt);\n\t\tif (firstSeenAt === undefined || now - firstSeenAt > ttl) continue;\n\t\treason ||= stringValue(rawChange.reason) ?? \"\";\n\t\tif (!isRecord(rawChange.sessions)) continue;\n\t\tfor (const [key, rawSession] of Object.entries(rawChange.sessions)) {\n\t\t\tconst session = parseSession(rawSession);\n\t\t\tif (!session) continue;\n\t\t\tif (session.reloadedAt !== undefined) continue;\n\t\t\tif (isOwnSession(key, session, options) || shouldIgnoreSession(session, options)) continue;\n\t\t\tif (!isAlive(session.pid)) continue;\n\t\t\tblockers.push({ key, source: \"coordinator\", reason: stringValue(rawChange.reason), ...session });\n\t\t}\n\t}\n\treturn { blockers, reason };\n}\n\nexport function describeReloadSession(\n\trecord: Pick<ReloadSessionRecord, \"key\" | \"pid\" | \"sessionId\" | \"sessionFile\" | \"cwd\">,\n): string {\n\tconst label = record.sessionId ?? record.sessionFile ?? record.cwd ?? String(record.pid ?? \"unknown\");\n\tconst parts = [`${record.key}:${label}`];\n\tif (record.pid !== undefined) parts.push(`pid=${record.pid}`);\n\tif (record.cwd) parts.push(`cwd=${record.cwd}`);\n\tif (record.sessionFile) parts.push(`file=${record.sessionFile}`);\n\treturn parts.join(\" \");\n}\n\nexport function getPendingReloadBlockers(options: ReloadBlockerOptions = {}): PendingReloadBlockers {\n\tconst byIdentity = new Map<string, ReloadSessionRecord>();\n\tfor (const blocker of activeTurnBlockers(options)) addBlocker(byIdentity, blocker);\n\tconst coordinator = coordinatorBlockers(options);\n\tfor (const blocker of coordinator.blockers) addBlocker(byIdentity, blocker);\n\tconst blockers = [...byIdentity.values()].sort((a, b) =>\n\t\tdescribeReloadSession(a).localeCompare(describeReloadSession(b)),\n\t);\n\treturn {\n\t\tpending: blockers.length > 0,\n\t\treason:\n\t\t\tcoordinator.reason ||\n\t\t\t(blockers.length ? \"Pi auto-reload is waiting for active peer/background session(s).\" : \"\"),\n\t\tblockers,\n\t\tdescriptions: blockers.map(describeReloadSession),\n\t};\n}\n\n/**\n * In-process quiesce registry: the reload gate's unified source of truth for background work\n * running IN THIS PROCESS that must finish before a `/reload`, profile switch, or live extension\n * load/unload/reconcile may proceed — background lanes (research/worker/model-fitness), the\n * context-scout's own Agent, and isolated completions (through their single choke point,\n * `ReflectionController.runIsolatedCompletion`) all register here. Foreground streaming/compaction\n * are NOT registered here — the host already exposes those via `RuntimeBuilderDeps.isStreaming`/`isCompacting`,\n * and the gate checks both alongside this registry instead of duplicating that state into a second tracker.\n *\n * Keyed by `agentDir`, matching every cross-process function above, so two sessions rooted at\n * different agent dirs (as every test harness in this repo constructs them) never see each other's\n * in-flight work.\n *\n * Registration is a plain in-memory counter, not file-backed — nothing here survives a process\n * restart, and nothing needs to: a crashed process cannot hold its own reload gate hostage. The\n * returned deregister function MUST be called from a `finally` block by every caller — an\n * un-deregistered unit would wedge the gate forever — so deregistering twice is a safe no-op rather\n * than a footgun for a caller that also deregisters on an early-return path.\n */\nexport type InFlightWorkKind = \"lane\" | \"scout\" | \"isolated-completion\";\n\nexport interface InFlightWorkUnit {\n\tid: number;\n\tkind: InFlightWorkKind;\n\tlabel: string;\n\tregisteredAt: number;\n}\n\nlet _nextInFlightWorkId = 1;\nconst _inFlightWorkByAgentDir = new Map<string, Map<number, InFlightWorkUnit>>();\n\n/** Registers one in-flight background work unit for `agentDir`. Returns its deregister function. */\nexport function registerInFlightWork(agentDir: string, kind: InFlightWorkKind, label: string): () => void {\n\tlet units = _inFlightWorkByAgentDir.get(agentDir);\n\tif (!units) {\n\t\tunits = new Map<number, InFlightWorkUnit>();\n\t\t_inFlightWorkByAgentDir.set(agentDir, units);\n\t}\n\tconst scopedUnits = units;\n\tconst id = _nextInFlightWorkId++;\n\tscopedUnits.set(id, { id, kind, label, registeredAt: Date.now() });\n\tlet deregistered = false;\n\treturn () => {\n\t\tif (deregistered) return;\n\t\tderegistered = true;\n\t\tscopedUnits.delete(id);\n\t\tif (scopedUnits.size === 0) _inFlightWorkByAgentDir.delete(agentDir);\n\t};\n}\n\n/** Live in-flight units for `agentDir`, oldest first. Empty when nothing is registered. */\nexport function getInFlightWorkUnits(agentDir: string): InFlightWorkUnit[] {\n\tconst units = _inFlightWorkByAgentDir.get(agentDir);\n\treturn units ? [...units.values()].sort((a, b) => a.id - b.id) : [];\n}\n\nexport function describeInFlightWorkUnit(unit: InFlightWorkUnit): string {\n\treturn `${unit.kind}:${unit.label}`;\n}\n\n/**\n * Test-only escape hatch: clears every agentDir's registry so one test's leaked registration cannot\n * block another's reload gate or status text.\n */\nexport function resetInFlightWorkRegistryForTests(): void {\n\t_inFlightWorkByAgentDir.clear();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"reload-blockers.d.ts","sourceRoot":"","sources":["../../src/core/reload-blockers.ts"],"names":[],"mappings":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EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAU5E;AAgFD,wBAAgB,qBAAqB,CACpC,MAAM,EAAE,IAAI,CAAC,mBAAmB,EAAE,KAAK,GAAG,KAAK,GAAG,WAAW,GAAG,aAAa,GAAG,KAAK,CAAC,GACpF,MAAM,CAOR;AAED,wBAAgB,wBAAwB,CAAC,OAAO,GAAE,oBAAyB,GAAG,qBAAqB,CAgBlG;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,OAAO,GAAG,qBAAqB,CAAC;AAExE,MAAM,WAAW,gBAAgB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,gBAAgB,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,YAAY,EAAE,MAAM,CAAC;CACrB;AAKD,oGAAoG;AACpG,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,IAAI,CAgBxG;AAED,2FAA2F;AAC3F,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,GAAG,gBAAgB,EAAE,CAGzE;AAED,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,gBAAgB,GAAG,MAAM,CAEvE;AAED;;;GAGG;AACH,wBAAgB,iCAAiC,IAAI,IAAI,CAExD","sourcesContent":["/**\n * Reload/live-op blocker sources for THIS process's reload gate (`RuntimeBuilder`, see\n * runtime-builder.ts): cross-process peer/coordinator sessions (file-backed, below) AND the\n * in-process quiesce registry (`registerInFlightWork`/`getInFlightWorkUnits`) that tracks background\n * lanes, context-scout runs, and isolated completions running in THIS process. The gate reads both;\n * `getPendingReloadBlockers` (cross-process) also backs the `/autonomy` status text.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getAgentDir } from \"../config.ts\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\nimport { isRecordObject } from \"./util/value-guards.ts\";\n\nexport const ACTIVE_TURN_TTL_MS = 5 * 60_000;\nexport const AUTO_RELOAD_COORDINATOR_TTL_MS = 10 * 60_000;\n\nexport function getReloadCoordinationDir(agentDir: string = getAgentDir()): string {\n\treturn getProcessWorkRun(agentDir, \"coordination\", \"reload\", \"state\").path;\n}\n\nexport interface ReloadSessionRecord {\n\tkey: string;\n\tsource: \"active-turn\" | \"coordinator\";\n\tpid?: number;\n\tsessionId?: string;\n\tsessionFile?: string;\n\tcwd?: string;\n\tactive?: boolean;\n\tupdatedAt?: number;\n\tseenAt?: number;\n\treloadedAt?: number;\n\treason?: string;\n}\n\nexport interface PendingReloadBlockers {\n\tpending: boolean;\n\treason: string;\n\tblockers: ReloadSessionRecord[];\n\tdescriptions: string[];\n}\n\nexport interface ReloadBlockerOptions {\n\tagentDir?: string;\n\tnow?: number;\n\townKey?: string;\n\townPid?: number;\n\townSessionId?: string;\n\townSessionFile?: string;\n\tactiveTurnTtlMs?: number;\n\tcoordinatorTtlMs?: number;\n\t/** Auto Learn workers are memory-first, short-lived, and should not block foreground reload/adaptive work by default. */\n\tincludeAutoLearnSessions?: boolean;\n\tisProcessAlive?: (pid: number | undefined) => boolean;\n}\n\ninterface ParsedSession {\n\tpid?: number;\n\tsessionId?: string;\n\tsessionFile?: string;\n\tcwd?: string;\n\tactive?: boolean;\n\tupdatedAt?: number;\n\tseenAt?: number;\n\treloadedAt?: number;\n}\n\nfunction readJsonFile(file: string): unknown {\n\ttry {\n\t\tif (!existsSync(file)) return undefined;\n\t\treturn JSON.parse(readFileSync(file, \"utf8\")) as unknown;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction stringValue(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\treturn undefined;\n}\n\nfunction booleanValue(value: unknown): boolean | undefined {\n\treturn typeof value === \"boolean\" ? value : undefined;\n}\n\nfunction parseSession(value: unknown): ParsedSession | undefined {\n\tif (!isRecordObject(value)) return undefined;\n\treturn {\n\t\tpid: numberValue(value.pid),\n\t\tsessionId: stringValue(value.sessionId),\n\t\tsessionFile: stringValue(value.sessionFile),\n\t\tcwd: stringValue(value.cwd),\n\t\tactive: booleanValue(value.active),\n\t\tupdatedAt: numberValue(value.updatedAt),\n\t\tseenAt: numberValue(value.seenAt),\n\t\treloadedAt: numberValue(value.reloadedAt),\n\t};\n}\n\nexport function isReloadSessionProcessAlive(pid: number | undefined): boolean {\n\tif (pid === undefined || !Number.isFinite(pid) || pid <= 0) return false;\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\tconst code =\n\t\t\terror && typeof error === \"object\" && \"code\" in error ? String((error as { code?: unknown }).code) : \"\";\n\t\treturn code === \"EPERM\";\n\t}\n}\n\nfunction isOwnSession(key: string, session: ParsedSession, options: ReloadBlockerOptions): boolean {\n\tif (options.ownKey && key === options.ownKey) return true;\n\tif (options.ownPid !== undefined && session.pid === options.ownPid) return true;\n\tif (options.ownSessionId && session.sessionId === options.ownSessionId) return true;\n\tif (options.ownSessionFile && session.sessionFile === options.ownSessionFile) return true;\n\treturn false;\n}\n\nfunction isAutoLearnSession(session: ParsedSession): boolean {\n\treturn !!session.sessionId?.startsWith(\"auto-learn-\");\n}\n\nfunction shouldIgnoreSession(session: ParsedSession, options: ReloadBlockerOptions): boolean {\n\treturn options.includeAutoLearnSessions !== true && isAutoLearnSession(session);\n}\n\nfunction addBlocker(blockers: Map<string, ReloadSessionRecord>, record: ReloadSessionRecord): void {\n\tconst identity = [\n\t\trecord.key,\n\t\trecord.pid ?? \"\",\n\t\trecord.sessionId ?? \"\",\n\t\trecord.sessionFile ?? \"\",\n\t\trecord.cwd ?? \"\",\n\t].join(\"\\0\");\n\tconst existing = blockers.get(identity);\n\tif (!existing || (existing.source === \"coordinator\" && record.source === \"active-turn\")) {\n\t\tblockers.set(identity, record);\n\t}\n}\n\nfunction activeTurnBlockers(options: ReloadBlockerOptions): ReloadSessionRecord[] {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst now = options.now ?? Date.now();\n\tconst ttl = options.activeTurnTtlMs ?? ACTIVE_TURN_TTL_MS;\n\tconst isAlive = options.isProcessAlive ?? isReloadSessionProcessAlive;\n\tconst registry = readJsonFile(join(getReloadCoordinationDir(agentDir), \"active-turns.json\"));\n\tif (!isRecordObject(registry) || !isRecordObject(registry.sessions)) return [];\n\n\tconst blockers: ReloadSessionRecord[] = [];\n\tfor (const [key, rawSession] of Object.entries(registry.sessions)) {\n\t\tconst session = parseSession(rawSession);\n\t\tif (!session?.active) continue;\n\t\tif (isOwnSession(key, session, options) || shouldIgnoreSession(session, options)) continue;\n\t\tif (session.updatedAt === undefined || now - session.updatedAt > ttl) continue;\n\t\tif (!isAlive(session.pid)) continue;\n\t\tblockers.push({ key, source: \"active-turn\", ...session });\n\t}\n\treturn blockers;\n}\n\nfunction coordinatorBlockers(options: ReloadBlockerOptions): { blockers: ReloadSessionRecord[]; reason: string } {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst now = options.now ?? Date.now();\n\tconst ttl = options.coordinatorTtlMs ?? AUTO_RELOAD_COORDINATOR_TTL_MS;\n\tconst isAlive = options.isProcessAlive ?? isReloadSessionProcessAlive;\n\tconst coordinator = readJsonFile(join(getReloadCoordinationDir(agentDir), \"auto-reload-state.json\"));\n\tif (!isRecordObject(coordinator) || !isRecordObject(coordinator.changes)) return { blockers: [], reason: \"\" };\n\n\tconst blockers: ReloadSessionRecord[] = [];\n\tlet reason = \"\";\n\tfor (const rawChange of Object.values(coordinator.changes)) {\n\t\tif (!isRecordObject(rawChange)) continue;\n\t\tconst firstSeenAt = numberValue(rawChange.firstSeenAt);\n\t\tif (firstSeenAt === undefined || now - firstSeenAt > ttl) continue;\n\t\treason ||= stringValue(rawChange.reason) ?? \"\";\n\t\tif (!isRecordObject(rawChange.sessions)) continue;\n\t\tfor (const [key, rawSession] of Object.entries(rawChange.sessions)) {\n\t\t\tconst session = parseSession(rawSession);\n\t\t\tif (!session) continue;\n\t\t\tif (session.reloadedAt !== undefined) continue;\n\t\t\tif (isOwnSession(key, session, options) || shouldIgnoreSession(session, options)) continue;\n\t\t\tif (!isAlive(session.pid)) continue;\n\t\t\tblockers.push({ key, source: \"coordinator\", reason: stringValue(rawChange.reason), ...session });\n\t\t}\n\t}\n\treturn { blockers, reason };\n}\n\nexport function describeReloadSession(\n\trecord: Pick<ReloadSessionRecord, \"key\" | \"pid\" | \"sessionId\" | \"sessionFile\" | \"cwd\">,\n): string {\n\tconst label = record.sessionId ?? record.sessionFile ?? record.cwd ?? String(record.pid ?? \"unknown\");\n\tconst parts = [`${record.key}:${label}`];\n\tif (record.pid !== undefined) parts.push(`pid=${record.pid}`);\n\tif (record.cwd) parts.push(`cwd=${record.cwd}`);\n\tif (record.sessionFile) parts.push(`file=${record.sessionFile}`);\n\treturn parts.join(\" \");\n}\n\nexport function getPendingReloadBlockers(options: ReloadBlockerOptions = {}): PendingReloadBlockers {\n\tconst byIdentity = new Map<string, ReloadSessionRecord>();\n\tfor (const blocker of activeTurnBlockers(options)) addBlocker(byIdentity, blocker);\n\tconst coordinator = coordinatorBlockers(options);\n\tfor (const blocker of coordinator.blockers) addBlocker(byIdentity, blocker);\n\tconst blockers = [...byIdentity.values()].sort((a, b) =>\n\t\tdescribeReloadSession(a).localeCompare(describeReloadSession(b)),\n\t);\n\treturn {\n\t\tpending: blockers.length > 0,\n\t\treason:\n\t\t\tcoordinator.reason ||\n\t\t\t(blockers.length ? \"Pi auto-reload is waiting for active peer/background session(s).\" : \"\"),\n\t\tblockers,\n\t\tdescriptions: blockers.map(describeReloadSession),\n\t};\n}\n\n/**\n * In-process quiesce registry: the reload gate's unified source of truth for background work\n * running IN THIS PROCESS that must finish before a `/reload`, profile switch, or live extension\n * load/unload/reconcile may proceed — background lanes (research/worker/model-fitness), the\n * context-scout's own Agent, and isolated completions (through their single choke point,\n * `ReflectionController.runIsolatedCompletion`) all register here. Foreground streaming/compaction\n * are NOT registered here — the host already exposes those via `RuntimeBuilderDeps.isStreaming`/`isCompacting`,\n * and the gate checks both alongside this registry instead of duplicating that state into a second tracker.\n *\n * Keyed by `agentDir`, matching every cross-process function above, so two sessions rooted at\n * different agent dirs (as every test harness in this repo constructs them) never see each other's\n * in-flight work.\n *\n * Registration is a plain in-memory counter, not file-backed — nothing here survives a process\n * restart, and nothing needs to: a crashed process cannot hold its own reload gate hostage. The\n * returned deregister function MUST be called from a `finally` block by every caller — an\n * un-deregistered unit would wedge the gate forever — so deregistering twice is a safe no-op rather\n * than a footgun for a caller that also deregisters on an early-return path.\n */\nexport type InFlightWorkKind = \"lane\" | \"scout\" | \"isolated-completion\";\n\nexport interface InFlightWorkUnit {\n\tid: number;\n\tkind: InFlightWorkKind;\n\tlabel: string;\n\tregisteredAt: number;\n}\n\nlet _nextInFlightWorkId = 1;\nconst _inFlightWorkByAgentDir = new Map<string, Map<number, InFlightWorkUnit>>();\n\n/** Registers one in-flight background work unit for `agentDir`. Returns its deregister function. */\nexport function registerInFlightWork(agentDir: string, kind: InFlightWorkKind, label: string): () => void {\n\tlet units = _inFlightWorkByAgentDir.get(agentDir);\n\tif (!units) {\n\t\tunits = new Map<number, InFlightWorkUnit>();\n\t\t_inFlightWorkByAgentDir.set(agentDir, units);\n\t}\n\tconst scopedUnits = units;\n\tconst id = _nextInFlightWorkId++;\n\tscopedUnits.set(id, { id, kind, label, registeredAt: Date.now() });\n\tlet deregistered = false;\n\treturn () => {\n\t\tif (deregistered) return;\n\t\tderegistered = true;\n\t\tscopedUnits.delete(id);\n\t\tif (scopedUnits.size === 0) _inFlightWorkByAgentDir.delete(agentDir);\n\t};\n}\n\n/** Live in-flight units for `agentDir`, oldest first. Empty when nothing is registered. */\nexport function getInFlightWorkUnits(agentDir: string): InFlightWorkUnit[] {\n\tconst units = _inFlightWorkByAgentDir.get(agentDir);\n\treturn units ? [...units.values()].sort((a, b) => a.id - b.id) : [];\n}\n\nexport function describeInFlightWorkUnit(unit: InFlightWorkUnit): string {\n\treturn `${unit.kind}:${unit.label}`;\n}\n\n/**\n * Test-only escape hatch: clears every agentDir's registry so one test's leaked registration cannot\n * block another's reload gate or status text.\n */\nexport function resetInFlightWorkRegistryForTests(): void {\n\t_inFlightWorkByAgentDir.clear();\n}\n"]}
|
|
@@ -9,14 +9,12 @@ import { existsSync, readFileSync } from "node:fs";
|
|
|
9
9
|
import { join } from "node:path";
|
|
10
10
|
import { getAgentDir } from "../config.js";
|
|
11
11
|
import { getProcessWorkRun } from "../utils/work-directory.js";
|
|
12
|
+
import { isRecordObject } from "./util/value-guards.js";
|
|
12
13
|
export const ACTIVE_TURN_TTL_MS = 5 * 60_000;
|
|
13
14
|
export const AUTO_RELOAD_COORDINATOR_TTL_MS = 10 * 60_000;
|
|
14
15
|
export function getReloadCoordinationDir(agentDir = getAgentDir()) {
|
|
15
16
|
return getProcessWorkRun(agentDir, "coordination", "reload", "state").path;
|
|
16
17
|
}
|
|
17
|
-
function isRecord(value) {
|
|
18
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
19
|
-
}
|
|
20
18
|
function readJsonFile(file) {
|
|
21
19
|
try {
|
|
22
20
|
if (!existsSync(file))
|
|
@@ -39,7 +37,7 @@ function booleanValue(value) {
|
|
|
39
37
|
return typeof value === "boolean" ? value : undefined;
|
|
40
38
|
}
|
|
41
39
|
function parseSession(value) {
|
|
42
|
-
if (!
|
|
40
|
+
if (!isRecordObject(value))
|
|
43
41
|
return undefined;
|
|
44
42
|
return {
|
|
45
43
|
pid: numberValue(value.pid),
|
|
@@ -100,7 +98,7 @@ function activeTurnBlockers(options) {
|
|
|
100
98
|
const ttl = options.activeTurnTtlMs ?? ACTIVE_TURN_TTL_MS;
|
|
101
99
|
const isAlive = options.isProcessAlive ?? isReloadSessionProcessAlive;
|
|
102
100
|
const registry = readJsonFile(join(getReloadCoordinationDir(agentDir), "active-turns.json"));
|
|
103
|
-
if (!
|
|
101
|
+
if (!isRecordObject(registry) || !isRecordObject(registry.sessions))
|
|
104
102
|
return [];
|
|
105
103
|
const blockers = [];
|
|
106
104
|
for (const [key, rawSession] of Object.entries(registry.sessions)) {
|
|
@@ -123,18 +121,18 @@ function coordinatorBlockers(options) {
|
|
|
123
121
|
const ttl = options.coordinatorTtlMs ?? AUTO_RELOAD_COORDINATOR_TTL_MS;
|
|
124
122
|
const isAlive = options.isProcessAlive ?? isReloadSessionProcessAlive;
|
|
125
123
|
const coordinator = readJsonFile(join(getReloadCoordinationDir(agentDir), "auto-reload-state.json"));
|
|
126
|
-
if (!
|
|
124
|
+
if (!isRecordObject(coordinator) || !isRecordObject(coordinator.changes))
|
|
127
125
|
return { blockers: [], reason: "" };
|
|
128
126
|
const blockers = [];
|
|
129
127
|
let reason = "";
|
|
130
128
|
for (const rawChange of Object.values(coordinator.changes)) {
|
|
131
|
-
if (!
|
|
129
|
+
if (!isRecordObject(rawChange))
|
|
132
130
|
continue;
|
|
133
131
|
const firstSeenAt = numberValue(rawChange.firstSeenAt);
|
|
134
132
|
if (firstSeenAt === undefined || now - firstSeenAt > ttl)
|
|
135
133
|
continue;
|
|
136
134
|
reason ||= stringValue(rawChange.reason) ?? "";
|
|
137
|
-
if (!
|
|
135
|
+
if (!isRecordObject(rawChange.sessions))
|
|
138
136
|
continue;
|
|
139
137
|
for (const [key, rawSession] of Object.entries(rawChange.sessions)) {
|
|
140
138
|
const session = parseSession(rawSession);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reload-blockers.js","sourceRoot":"","sources":["../../src/core/reload-blockers.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,O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for THIS process's reload gate (`RuntimeBuilder`, see\n * runtime-builder.ts): cross-process peer/coordinator sessions (file-backed, below) AND the\n * in-process quiesce registry (`registerInFlightWork`/`getInFlightWorkUnits`) that tracks background\n * lanes, context-scout runs, and isolated completions running in THIS process. The gate reads both;\n * `getPendingReloadBlockers` (cross-process) also backs the `/autonomy` status text.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getAgentDir } from \"../config.ts\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\n\nexport const ACTIVE_TURN_TTL_MS = 5 * 60_000;\nexport const AUTO_RELOAD_COORDINATOR_TTL_MS = 10 * 60_000;\n\nexport function getReloadCoordinationDir(agentDir: string = getAgentDir()): string {\n\treturn getProcessWorkRun(agentDir, \"coordination\", \"reload\", \"state\").path;\n}\n\nexport interface ReloadSessionRecord {\n\tkey: string;\n\tsource: \"active-turn\" | \"coordinator\";\n\tpid?: number;\n\tsessionId?: string;\n\tsessionFile?: string;\n\tcwd?: string;\n\tactive?: boolean;\n\tupdatedAt?: number;\n\tseenAt?: number;\n\treloadedAt?: number;\n\treason?: string;\n}\n\nexport interface PendingReloadBlockers {\n\tpending: boolean;\n\treason: string;\n\tblockers: ReloadSessionRecord[];\n\tdescriptions: string[];\n}\n\nexport interface ReloadBlockerOptions {\n\tagentDir?: string;\n\tnow?: number;\n\townKey?: string;\n\townPid?: number;\n\townSessionId?: string;\n\townSessionFile?: string;\n\tactiveTurnTtlMs?: number;\n\tcoordinatorTtlMs?: number;\n\t/** Auto Learn workers are memory-first, short-lived, and should not block foreground reload/adaptive work by default. */\n\tincludeAutoLearnSessions?: boolean;\n\tisProcessAlive?: (pid: number | undefined) => boolean;\n}\n\ninterface ParsedSession {\n\tpid?: number;\n\tsessionId?: string;\n\tsessionFile?: string;\n\tcwd?: string;\n\tactive?: boolean;\n\tupdatedAt?: number;\n\tseenAt?: number;\n\treloadedAt?: number;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction readJsonFile(file: string): unknown {\n\ttry {\n\t\tif (!existsSync(file)) return undefined;\n\t\treturn JSON.parse(readFileSync(file, \"utf8\")) as unknown;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction stringValue(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\treturn undefined;\n}\n\nfunction booleanValue(value: unknown): boolean | undefined {\n\treturn typeof value === \"boolean\" ? value : undefined;\n}\n\nfunction parseSession(value: unknown): ParsedSession | undefined {\n\tif (!isRecord(value)) return undefined;\n\treturn {\n\t\tpid: numberValue(value.pid),\n\t\tsessionId: stringValue(value.sessionId),\n\t\tsessionFile: stringValue(value.sessionFile),\n\t\tcwd: stringValue(value.cwd),\n\t\tactive: booleanValue(value.active),\n\t\tupdatedAt: numberValue(value.updatedAt),\n\t\tseenAt: numberValue(value.seenAt),\n\t\treloadedAt: numberValue(value.reloadedAt),\n\t};\n}\n\nexport function isReloadSessionProcessAlive(pid: number | undefined): boolean {\n\tif (pid === undefined || !Number.isFinite(pid) || pid <= 0) return false;\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\tconst code =\n\t\t\terror && typeof error === \"object\" && \"code\" in error ? String((error as { code?: unknown }).code) : \"\";\n\t\treturn code === \"EPERM\";\n\t}\n}\n\nfunction isOwnSession(key: string, session: ParsedSession, options: ReloadBlockerOptions): boolean {\n\tif (options.ownKey && key === options.ownKey) return true;\n\tif (options.ownPid !== undefined && session.pid === options.ownPid) return true;\n\tif (options.ownSessionId && session.sessionId === options.ownSessionId) return true;\n\tif (options.ownSessionFile && session.sessionFile === options.ownSessionFile) return true;\n\treturn false;\n}\n\nfunction isAutoLearnSession(session: ParsedSession): boolean {\n\treturn !!session.sessionId?.startsWith(\"auto-learn-\");\n}\n\nfunction shouldIgnoreSession(session: ParsedSession, options: ReloadBlockerOptions): boolean {\n\treturn options.includeAutoLearnSessions !== true && isAutoLearnSession(session);\n}\n\nfunction addBlocker(blockers: Map<string, ReloadSessionRecord>, record: ReloadSessionRecord): void {\n\tconst identity = [\n\t\trecord.key,\n\t\trecord.pid ?? \"\",\n\t\trecord.sessionId ?? \"\",\n\t\trecord.sessionFile ?? \"\",\n\t\trecord.cwd ?? \"\",\n\t].join(\"\\0\");\n\tconst existing = blockers.get(identity);\n\tif (!existing || (existing.source === \"coordinator\" && record.source === \"active-turn\")) {\n\t\tblockers.set(identity, record);\n\t}\n}\n\nfunction activeTurnBlockers(options: ReloadBlockerOptions): ReloadSessionRecord[] {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst now = options.now ?? Date.now();\n\tconst ttl = options.activeTurnTtlMs ?? ACTIVE_TURN_TTL_MS;\n\tconst isAlive = options.isProcessAlive ?? isReloadSessionProcessAlive;\n\tconst registry = readJsonFile(join(getReloadCoordinationDir(agentDir), \"active-turns.json\"));\n\tif (!isRecord(registry) || !isRecord(registry.sessions)) return [];\n\n\tconst blockers: ReloadSessionRecord[] = [];\n\tfor (const [key, rawSession] of Object.entries(registry.sessions)) {\n\t\tconst session = parseSession(rawSession);\n\t\tif (!session?.active) continue;\n\t\tif (isOwnSession(key, session, options) || shouldIgnoreSession(session, options)) continue;\n\t\tif (session.updatedAt === undefined || now - session.updatedAt > ttl) continue;\n\t\tif (!isAlive(session.pid)) continue;\n\t\tblockers.push({ key, source: \"active-turn\", ...session });\n\t}\n\treturn blockers;\n}\n\nfunction coordinatorBlockers(options: ReloadBlockerOptions): { blockers: ReloadSessionRecord[]; reason: string } {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst now = options.now ?? Date.now();\n\tconst ttl = options.coordinatorTtlMs ?? AUTO_RELOAD_COORDINATOR_TTL_MS;\n\tconst isAlive = options.isProcessAlive ?? isReloadSessionProcessAlive;\n\tconst coordinator = readJsonFile(join(getReloadCoordinationDir(agentDir), \"auto-reload-state.json\"));\n\tif (!isRecord(coordinator) || !isRecord(coordinator.changes)) return { blockers: [], reason: \"\" };\n\n\tconst blockers: ReloadSessionRecord[] = [];\n\tlet reason = \"\";\n\tfor (const rawChange of Object.values(coordinator.changes)) {\n\t\tif (!isRecord(rawChange)) continue;\n\t\tconst firstSeenAt = numberValue(rawChange.firstSeenAt);\n\t\tif (firstSeenAt === undefined || now - firstSeenAt > ttl) continue;\n\t\treason ||= stringValue(rawChange.reason) ?? \"\";\n\t\tif (!isRecord(rawChange.sessions)) continue;\n\t\tfor (const [key, rawSession] of Object.entries(rawChange.sessions)) {\n\t\t\tconst session = parseSession(rawSession);\n\t\t\tif (!session) continue;\n\t\t\tif (session.reloadedAt !== undefined) continue;\n\t\t\tif (isOwnSession(key, session, options) || shouldIgnoreSession(session, options)) continue;\n\t\t\tif (!isAlive(session.pid)) continue;\n\t\t\tblockers.push({ key, source: \"coordinator\", reason: stringValue(rawChange.reason), ...session });\n\t\t}\n\t}\n\treturn { blockers, reason };\n}\n\nexport function describeReloadSession(\n\trecord: Pick<ReloadSessionRecord, \"key\" | \"pid\" | \"sessionId\" | \"sessionFile\" | \"cwd\">,\n): string {\n\tconst label = record.sessionId ?? record.sessionFile ?? record.cwd ?? String(record.pid ?? \"unknown\");\n\tconst parts = [`${record.key}:${label}`];\n\tif (record.pid !== undefined) parts.push(`pid=${record.pid}`);\n\tif (record.cwd) parts.push(`cwd=${record.cwd}`);\n\tif (record.sessionFile) parts.push(`file=${record.sessionFile}`);\n\treturn parts.join(\" \");\n}\n\nexport function getPendingReloadBlockers(options: ReloadBlockerOptions = {}): PendingReloadBlockers {\n\tconst byIdentity = new Map<string, ReloadSessionRecord>();\n\tfor (const blocker of activeTurnBlockers(options)) addBlocker(byIdentity, blocker);\n\tconst coordinator = coordinatorBlockers(options);\n\tfor (const blocker of coordinator.blockers) addBlocker(byIdentity, blocker);\n\tconst blockers = [...byIdentity.values()].sort((a, b) =>\n\t\tdescribeReloadSession(a).localeCompare(describeReloadSession(b)),\n\t);\n\treturn {\n\t\tpending: blockers.length > 0,\n\t\treason:\n\t\t\tcoordinator.reason ||\n\t\t\t(blockers.length ? \"Pi auto-reload is waiting for active peer/background session(s).\" : \"\"),\n\t\tblockers,\n\t\tdescriptions: blockers.map(describeReloadSession),\n\t};\n}\n\n/**\n * In-process quiesce registry: the reload gate's unified source of truth for background work\n * running IN THIS PROCESS that must finish before a `/reload`, profile switch, or live extension\n * load/unload/reconcile may proceed — background lanes (research/worker/model-fitness), the\n * context-scout's own Agent, and isolated completions (through their single choke point,\n * `ReflectionController.runIsolatedCompletion`) all register here. Foreground streaming/compaction\n * are NOT registered here — the host already exposes those via `RuntimeBuilderDeps.isStreaming`/`isCompacting`,\n * and the gate checks both alongside this registry instead of duplicating that state into a second tracker.\n *\n * Keyed by `agentDir`, matching every cross-process function above, so two sessions rooted at\n * different agent dirs (as every test harness in this repo constructs them) never see each other's\n * in-flight work.\n *\n * Registration is a plain in-memory counter, not file-backed — nothing here survives a process\n * restart, and nothing needs to: a crashed process cannot hold its own reload gate hostage. The\n * returned deregister function MUST be called from a `finally` block by every caller — an\n * un-deregistered unit would wedge the gate forever — so deregistering twice is a safe no-op rather\n * than a footgun for a caller that also deregisters on an early-return path.\n */\nexport type InFlightWorkKind = \"lane\" | \"scout\" | \"isolated-completion\";\n\nexport interface InFlightWorkUnit {\n\tid: number;\n\tkind: InFlightWorkKind;\n\tlabel: string;\n\tregisteredAt: number;\n}\n\nlet _nextInFlightWorkId = 1;\nconst _inFlightWorkByAgentDir = new Map<string, Map<number, InFlightWorkUnit>>();\n\n/** Registers one in-flight background work unit for `agentDir`. Returns its deregister function. */\nexport function registerInFlightWork(agentDir: string, kind: InFlightWorkKind, label: string): () => void {\n\tlet units = _inFlightWorkByAgentDir.get(agentDir);\n\tif (!units) {\n\t\tunits = new Map<number, InFlightWorkUnit>();\n\t\t_inFlightWorkByAgentDir.set(agentDir, units);\n\t}\n\tconst scopedUnits = units;\n\tconst id = _nextInFlightWorkId++;\n\tscopedUnits.set(id, { id, kind, label, registeredAt: Date.now() });\n\tlet deregistered = false;\n\treturn () => {\n\t\tif (deregistered) return;\n\t\tderegistered = true;\n\t\tscopedUnits.delete(id);\n\t\tif (scopedUnits.size === 0) _inFlightWorkByAgentDir.delete(agentDir);\n\t};\n}\n\n/** Live in-flight units for `agentDir`, oldest first. Empty when nothing is registered. */\nexport function getInFlightWorkUnits(agentDir: string): InFlightWorkUnit[] {\n\tconst units = _inFlightWorkByAgentDir.get(agentDir);\n\treturn units ? [...units.values()].sort((a, b) => a.id - b.id) : [];\n}\n\nexport function describeInFlightWorkUnit(unit: InFlightWorkUnit): string {\n\treturn `${unit.kind}:${unit.label}`;\n}\n\n/**\n * Test-only escape hatch: clears every agentDir's registry so one test's leaked registration cannot\n * block another's reload gate or status text.\n */\nexport function resetInFlightWorkRegistryForTests(): void {\n\t_inFlightWorkByAgentDir.clear();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"reload-blockers.js","sourceRoot":"","sources":["../../src/core/reload-blockers.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAExD,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,GAAG,MAAM,CAAC;AAC7C,MAAM,CAAC,MAAM,8BAA8B,GAAG,EAAE,GAAG,MAAM,CAAC;AAE1D,MAAM,UAAU,wBAAwB,CAAC,QAAQ,GAAW,WAAW,EAAE,EAAU;IAClF,OAAO,iBAAiB,CAAC,QAAQ,EAAE,cAAc,EAAE,QAA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AM,CAAC,EAAE,CAAC,CAAC;QACvB,IAAI,WAAW,CAAC,IAAI,KAAK,CAAC;YAAE,uBAAuB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAAA,CACrE,CAAC;AAAA,CACF;AAED,2FAA2F;AAC3F,MAAM,UAAU,oBAAoB,CAAC,QAAgB,EAAsB;IAC1E,MAAM,KAAK,GAAG,uBAAuB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACpD,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAAA,CACpE;AAED,MAAM,UAAU,wBAAwB,CAAC,IAAsB,EAAU;IACxE,OAAO,GAAG,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;AAAA,CACpC;AAED;;;GAGG;AACH,MAAM,UAAU,iCAAiC,GAAS;IACzD,uBAAuB,CAAC,KAAK,EAAE,CAAC;AAAA,CAChC","sourcesContent":["/**\n * Reload/live-op blocker sources for THIS process's reload gate (`RuntimeBuilder`, see\n * runtime-builder.ts): cross-process peer/coordinator sessions (file-backed, below) AND the\n * in-process quiesce registry (`registerInFlightWork`/`getInFlightWorkUnits`) that tracks background\n * lanes, context-scout runs, and isolated completions running in THIS process. The gate reads both;\n * `getPendingReloadBlockers` (cross-process) also backs the `/autonomy` status text.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getAgentDir } from \"../config.ts\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\nimport { isRecordObject } from \"./util/value-guards.ts\";\n\nexport const ACTIVE_TURN_TTL_MS = 5 * 60_000;\nexport const AUTO_RELOAD_COORDINATOR_TTL_MS = 10 * 60_000;\n\nexport function getReloadCoordinationDir(agentDir: string = getAgentDir()): string {\n\treturn getProcessWorkRun(agentDir, \"coordination\", \"reload\", \"state\").path;\n}\n\nexport interface ReloadSessionRecord {\n\tkey: string;\n\tsource: \"active-turn\" | \"coordinator\";\n\tpid?: number;\n\tsessionId?: string;\n\tsessionFile?: string;\n\tcwd?: string;\n\tactive?: boolean;\n\tupdatedAt?: number;\n\tseenAt?: number;\n\treloadedAt?: number;\n\treason?: string;\n}\n\nexport interface PendingReloadBlockers {\n\tpending: boolean;\n\treason: string;\n\tblockers: ReloadSessionRecord[];\n\tdescriptions: string[];\n}\n\nexport interface ReloadBlockerOptions {\n\tagentDir?: string;\n\tnow?: number;\n\townKey?: string;\n\townPid?: number;\n\townSessionId?: string;\n\townSessionFile?: string;\n\tactiveTurnTtlMs?: number;\n\tcoordinatorTtlMs?: number;\n\t/** Auto Learn workers are memory-first, short-lived, and should not block foreground reload/adaptive work by default. */\n\tincludeAutoLearnSessions?: boolean;\n\tisProcessAlive?: (pid: number | undefined) => boolean;\n}\n\ninterface ParsedSession {\n\tpid?: number;\n\tsessionId?: string;\n\tsessionFile?: string;\n\tcwd?: string;\n\tactive?: boolean;\n\tupdatedAt?: number;\n\tseenAt?: number;\n\treloadedAt?: number;\n}\n\nfunction readJsonFile(file: string): unknown {\n\ttry {\n\t\tif (!existsSync(file)) return undefined;\n\t\treturn JSON.parse(readFileSync(file, \"utf8\")) as unknown;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction stringValue(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\treturn undefined;\n}\n\nfunction booleanValue(value: unknown): boolean | undefined {\n\treturn typeof value === \"boolean\" ? value : undefined;\n}\n\nfunction parseSession(value: unknown): ParsedSession | undefined {\n\tif (!isRecordObject(value)) return undefined;\n\treturn {\n\t\tpid: numberValue(value.pid),\n\t\tsessionId: stringValue(value.sessionId),\n\t\tsessionFile: stringValue(value.sessionFile),\n\t\tcwd: stringValue(value.cwd),\n\t\tactive: booleanValue(value.active),\n\t\tupdatedAt: numberValue(value.updatedAt),\n\t\tseenAt: numberValue(value.seenAt),\n\t\treloadedAt: numberValue(value.reloadedAt),\n\t};\n}\n\nexport function isReloadSessionProcessAlive(pid: number | undefined): boolean {\n\tif (pid === undefined || !Number.isFinite(pid) || pid <= 0) return false;\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\tconst code =\n\t\t\terror && typeof error === \"object\" && \"code\" in error ? String((error as { code?: unknown }).code) : \"\";\n\t\treturn code === \"EPERM\";\n\t}\n}\n\nfunction isOwnSession(key: string, session: ParsedSession, options: ReloadBlockerOptions): boolean {\n\tif (options.ownKey && key === options.ownKey) return true;\n\tif (options.ownPid !== undefined && session.pid === options.ownPid) return true;\n\tif (options.ownSessionId && session.sessionId === options.ownSessionId) return true;\n\tif (options.ownSessionFile && session.sessionFile === options.ownSessionFile) return true;\n\treturn false;\n}\n\nfunction isAutoLearnSession(session: ParsedSession): boolean {\n\treturn !!session.sessionId?.startsWith(\"auto-learn-\");\n}\n\nfunction shouldIgnoreSession(session: ParsedSession, options: ReloadBlockerOptions): boolean {\n\treturn options.includeAutoLearnSessions !== true && isAutoLearnSession(session);\n}\n\nfunction addBlocker(blockers: Map<string, ReloadSessionRecord>, record: ReloadSessionRecord): void {\n\tconst identity = [\n\t\trecord.key,\n\t\trecord.pid ?? \"\",\n\t\trecord.sessionId ?? \"\",\n\t\trecord.sessionFile ?? \"\",\n\t\trecord.cwd ?? \"\",\n\t].join(\"\\0\");\n\tconst existing = blockers.get(identity);\n\tif (!existing || (existing.source === \"coordinator\" && record.source === \"active-turn\")) {\n\t\tblockers.set(identity, record);\n\t}\n}\n\nfunction activeTurnBlockers(options: ReloadBlockerOptions): ReloadSessionRecord[] {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst now = options.now ?? Date.now();\n\tconst ttl = options.activeTurnTtlMs ?? ACTIVE_TURN_TTL_MS;\n\tconst isAlive = options.isProcessAlive ?? isReloadSessionProcessAlive;\n\tconst registry = readJsonFile(join(getReloadCoordinationDir(agentDir), \"active-turns.json\"));\n\tif (!isRecordObject(registry) || !isRecordObject(registry.sessions)) return [];\n\n\tconst blockers: ReloadSessionRecord[] = [];\n\tfor (const [key, rawSession] of Object.entries(registry.sessions)) {\n\t\tconst session = parseSession(rawSession);\n\t\tif (!session?.active) continue;\n\t\tif (isOwnSession(key, session, options) || shouldIgnoreSession(session, options)) continue;\n\t\tif (session.updatedAt === undefined || now - session.updatedAt > ttl) continue;\n\t\tif (!isAlive(session.pid)) continue;\n\t\tblockers.push({ key, source: \"active-turn\", ...session });\n\t}\n\treturn blockers;\n}\n\nfunction coordinatorBlockers(options: ReloadBlockerOptions): { blockers: ReloadSessionRecord[]; reason: string } {\n\tconst agentDir = options.agentDir ?? getAgentDir();\n\tconst now = options.now ?? Date.now();\n\tconst ttl = options.coordinatorTtlMs ?? AUTO_RELOAD_COORDINATOR_TTL_MS;\n\tconst isAlive = options.isProcessAlive ?? isReloadSessionProcessAlive;\n\tconst coordinator = readJsonFile(join(getReloadCoordinationDir(agentDir), \"auto-reload-state.json\"));\n\tif (!isRecordObject(coordinator) || !isRecordObject(coordinator.changes)) return { blockers: [], reason: \"\" };\n\n\tconst blockers: ReloadSessionRecord[] = [];\n\tlet reason = \"\";\n\tfor (const rawChange of Object.values(coordinator.changes)) {\n\t\tif (!isRecordObject(rawChange)) continue;\n\t\tconst firstSeenAt = numberValue(rawChange.firstSeenAt);\n\t\tif (firstSeenAt === undefined || now - firstSeenAt > ttl) continue;\n\t\treason ||= stringValue(rawChange.reason) ?? \"\";\n\t\tif (!isRecordObject(rawChange.sessions)) continue;\n\t\tfor (const [key, rawSession] of Object.entries(rawChange.sessions)) {\n\t\t\tconst session = parseSession(rawSession);\n\t\t\tif (!session) continue;\n\t\t\tif (session.reloadedAt !== undefined) continue;\n\t\t\tif (isOwnSession(key, session, options) || shouldIgnoreSession(session, options)) continue;\n\t\t\tif (!isAlive(session.pid)) continue;\n\t\t\tblockers.push({ key, source: \"coordinator\", reason: stringValue(rawChange.reason), ...session });\n\t\t}\n\t}\n\treturn { blockers, reason };\n}\n\nexport function describeReloadSession(\n\trecord: Pick<ReloadSessionRecord, \"key\" | \"pid\" | \"sessionId\" | \"sessionFile\" | \"cwd\">,\n): string {\n\tconst label = record.sessionId ?? record.sessionFile ?? record.cwd ?? String(record.pid ?? \"unknown\");\n\tconst parts = [`${record.key}:${label}`];\n\tif (record.pid !== undefined) parts.push(`pid=${record.pid}`);\n\tif (record.cwd) parts.push(`cwd=${record.cwd}`);\n\tif (record.sessionFile) parts.push(`file=${record.sessionFile}`);\n\treturn parts.join(\" \");\n}\n\nexport function getPendingReloadBlockers(options: ReloadBlockerOptions = {}): PendingReloadBlockers {\n\tconst byIdentity = new Map<string, ReloadSessionRecord>();\n\tfor (const blocker of activeTurnBlockers(options)) addBlocker(byIdentity, blocker);\n\tconst coordinator = coordinatorBlockers(options);\n\tfor (const blocker of coordinator.blockers) addBlocker(byIdentity, blocker);\n\tconst blockers = [...byIdentity.values()].sort((a, b) =>\n\t\tdescribeReloadSession(a).localeCompare(describeReloadSession(b)),\n\t);\n\treturn {\n\t\tpending: blockers.length > 0,\n\t\treason:\n\t\t\tcoordinator.reason ||\n\t\t\t(blockers.length ? \"Pi auto-reload is waiting for active peer/background session(s).\" : \"\"),\n\t\tblockers,\n\t\tdescriptions: blockers.map(describeReloadSession),\n\t};\n}\n\n/**\n * In-process quiesce registry: the reload gate's unified source of truth for background work\n * running IN THIS PROCESS that must finish before a `/reload`, profile switch, or live extension\n * load/unload/reconcile may proceed — background lanes (research/worker/model-fitness), the\n * context-scout's own Agent, and isolated completions (through their single choke point,\n * `ReflectionController.runIsolatedCompletion`) all register here. Foreground streaming/compaction\n * are NOT registered here — the host already exposes those via `RuntimeBuilderDeps.isStreaming`/`isCompacting`,\n * and the gate checks both alongside this registry instead of duplicating that state into a second tracker.\n *\n * Keyed by `agentDir`, matching every cross-process function above, so two sessions rooted at\n * different agent dirs (as every test harness in this repo constructs them) never see each other's\n * in-flight work.\n *\n * Registration is a plain in-memory counter, not file-backed — nothing here survives a process\n * restart, and nothing needs to: a crashed process cannot hold its own reload gate hostage. The\n * returned deregister function MUST be called from a `finally` block by every caller — an\n * un-deregistered unit would wedge the gate forever — so deregistering twice is a safe no-op rather\n * than a footgun for a caller that also deregisters on an early-return path.\n */\nexport type InFlightWorkKind = \"lane\" | \"scout\" | \"isolated-completion\";\n\nexport interface InFlightWorkUnit {\n\tid: number;\n\tkind: InFlightWorkKind;\n\tlabel: string;\n\tregisteredAt: number;\n}\n\nlet _nextInFlightWorkId = 1;\nconst _inFlightWorkByAgentDir = new Map<string, Map<number, InFlightWorkUnit>>();\n\n/** Registers one in-flight background work unit for `agentDir`. Returns its deregister function. */\nexport function registerInFlightWork(agentDir: string, kind: InFlightWorkKind, label: string): () => void {\n\tlet units = _inFlightWorkByAgentDir.get(agentDir);\n\tif (!units) {\n\t\tunits = new Map<number, InFlightWorkUnit>();\n\t\t_inFlightWorkByAgentDir.set(agentDir, units);\n\t}\n\tconst scopedUnits = units;\n\tconst id = _nextInFlightWorkId++;\n\tscopedUnits.set(id, { id, kind, label, registeredAt: Date.now() });\n\tlet deregistered = false;\n\treturn () => {\n\t\tif (deregistered) return;\n\t\tderegistered = true;\n\t\tscopedUnits.delete(id);\n\t\tif (scopedUnits.size === 0) _inFlightWorkByAgentDir.delete(agentDir);\n\t};\n}\n\n/** Live in-flight units for `agentDir`, oldest first. Empty when nothing is registered. */\nexport function getInFlightWorkUnits(agentDir: string): InFlightWorkUnit[] {\n\tconst units = _inFlightWorkByAgentDir.get(agentDir);\n\treturn units ? [...units.values()].sort((a, b) => a.id - b.id) : [];\n}\n\nexport function describeInFlightWorkUnit(unit: InFlightWorkUnit): string {\n\treturn `${unit.kind}:${unit.label}`;\n}\n\n/**\n * Test-only escape hatch: clears every agentDir's registry so one test's leaked registration cannot\n * block another's reload gate or status text.\n */\nexport function resetInFlightWorkRegistryForTests(): void {\n\t_inFlightWorkByAgentDir.clear();\n}\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export interface RequestAuth {
|
|
2
|
+
apiKey?: string;
|
|
3
|
+
headers?: Record<string, string>;
|
|
4
|
+
}
|
|
5
|
+
export declare function hasAuthenticationHeaders(headers: Record<string, string> | undefined): boolean;
|
|
6
|
+
export declare function hasUsableRequestAuth(auth: RequestAuth): boolean;
|
|
7
|
+
//# sourceMappingURL=request-auth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request-auth.d.ts","sourceRoot":"","sources":["../../src/core/request-auth.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,WAAW;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACjC;AAID,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,GAAG,OAAO,CAI7F;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,WAAW,GAAG,OAAO,CAE/D","sourcesContent":["export interface RequestAuth {\n\tapiKey?: string;\n\theaders?: Record<string, string>;\n}\n\nconst AUTHENTICATION_HEADER_NAMES = new Set([\"authorization\", \"api-key\", \"x-api-key\"]);\n\nexport function hasAuthenticationHeaders(headers: Record<string, string> | undefined): boolean {\n\treturn Object.entries(headers ?? {}).some(\n\t\t([name, value]) => AUTHENTICATION_HEADER_NAMES.has(name.toLowerCase()) && value.trim().length > 0,\n\t);\n}\n\nexport function hasUsableRequestAuth(auth: RequestAuth): boolean {\n\treturn Boolean(auth.apiKey?.trim()) || hasAuthenticationHeaders(auth.headers);\n}\n"]}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
const AUTHENTICATION_HEADER_NAMES = new Set(["authorization", "api-key", "x-api-key"]);
|
|
2
|
+
export function hasAuthenticationHeaders(headers) {
|
|
3
|
+
return Object.entries(headers ?? {}).some(([name, value]) => AUTHENTICATION_HEADER_NAMES.has(name.toLowerCase()) && value.trim().length > 0);
|
|
4
|
+
}
|
|
5
|
+
export function hasUsableRequestAuth(auth) {
|
|
6
|
+
return Boolean(auth.apiKey?.trim()) || hasAuthenticationHeaders(auth.headers);
|
|
7
|
+
}
|
|
8
|
+
//# sourceMappingURL=request-auth.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request-auth.js","sourceRoot":"","sources":["../../src/core/request-auth.ts"],"names":[],"mappings":"AAKA,MAAM,2BAA2B,GAAG,IAAI,GAAG,CAAC,CAAC,eAAe,EAAE,SAAS,EAAE,WAAW,CAAC,CAAC,CAAC;AAEvF,MAAM,UAAU,wBAAwB,CAAC,OAA2C,EAAW;IAC9F,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,IAAI,CACxC,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,2BAA2B,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CACjG,CAAC;AAAA,CACF;AAED,MAAM,UAAU,oBAAoB,CAAC,IAAiB,EAAW;IAChE,OAAO,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,IAAI,wBAAwB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAAA,CAC9E","sourcesContent":["export interface RequestAuth {\n\tapiKey?: string;\n\theaders?: Record<string, string>;\n}\n\nconst AUTHENTICATION_HEADER_NAMES = new Set([\"authorization\", \"api-key\", \"x-api-key\"]);\n\nexport function hasAuthenticationHeaders(headers: Record<string, string> | undefined): boolean {\n\treturn Object.entries(headers ?? {}).some(\n\t\t([name, value]) => AUTHENTICATION_HEADER_NAMES.has(name.toLowerCase()) && value.trim().length > 0,\n\t);\n}\n\nexport function hasUsableRequestAuth(auth: RequestAuth): boolean {\n\treturn Boolean(auth.apiKey?.trim()) || hasAuthenticationHeaders(auth.headers);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"evidence-bundle.d.ts","sourceRoot":"","sources":["../../../src/core/research/evidence-bundle.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,OAAO,EAAyB,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"evidence-bundle.d.ts","sourceRoot":"","sources":["../../../src/core/research/evidence-bundle.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,OAAO,EAAyB,MAAM,0BAA0B,CAAC;AAsD5G,wBAAgB,oBAAoB,CAAC,IAAI,EAAE;IAC1C,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,SAAS,WAAW,EAAE,CAAC;IAChC,QAAQ,EAAE,SAAS,OAAO,EAAE,CAAC;IAC7B,GAAG,CAAC,EAAE,MAAM,CAAC;CACb,GAAG,cAAc,CAOjB;AAED,wBAAgB,6BAA6B,CAAC,MAAM,EAAE,cAAc,GAAG,cAAc,CAOpF;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,cAAc,CAqCxE","sourcesContent":["import type { EvidenceBundle, EvidenceRef, Finding, JsonObject, JsonValue } from \"../autonomy/contracts.ts\";\nimport { isPlainRecord } from \"../util/value-guards.ts\";\n\nfunction cloneJsonValue(value: JsonValue): JsonValue {\n\tif (Array.isArray(value)) {\n\t\treturn value.map(cloneJsonValue);\n\t}\n\tif (value !== null && typeof value === \"object\") {\n\t\treturn Object.fromEntries(Object.entries(value).map(([key, nested]) => [key, cloneJsonValue(nested)]));\n\t}\n\treturn value;\n}\n\nfunction cloneJsonObject(value: JsonObject): JsonObject {\n\treturn Object.fromEntries(Object.entries(value).map(([key, nested]) => [key, cloneJsonValue(nested)]));\n}\n\nfunction isJsonValue(value: unknown): value is JsonValue {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n\t\treturn true;\n\t}\n\tif (typeof value === \"number\") {\n\t\treturn Number.isFinite(value);\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.every(isJsonValue);\n\t}\n\tif (typeof value === \"object\") {\n\t\treturn isJsonObject(value);\n\t}\n\treturn false;\n}\n\nfunction isJsonObject(value: unknown): value is JsonObject {\n\tif (!isPlainRecord(value)) {\n\t\treturn false;\n\t}\n\treturn Object.values(value).every(isJsonValue);\n}\n\nfunction cloneEvidenceRef(source: EvidenceRef): EvidenceRef {\n\treturn {\n\t\t...source,\n\t\tmetadata: source.metadata ? cloneJsonObject(source.metadata) : undefined,\n\t};\n}\n\nfunction cloneFinding(finding: Finding): Finding {\n\treturn {\n\t\t...finding,\n\t\tevidenceIds: [...finding.evidenceIds],\n\t};\n}\n\nexport function createEvidenceBundle(args: {\n\tquery: string;\n\tsources: readonly EvidenceRef[];\n\tfindings: readonly Finding[];\n\tnow?: string;\n}): EvidenceBundle {\n\treturn {\n\t\tquery: args.query,\n\t\tsources: args.sources.map(cloneEvidenceRef),\n\t\tfindings: args.findings.map(cloneFinding),\n\t\tcreatedAt: args.now,\n\t};\n}\n\nexport function cloneEvidenceBundleForStorage(bundle: EvidenceBundle): EvidenceBundle {\n\treturn {\n\t\tquery: bundle.query,\n\t\tsources: bundle.sources.map(cloneEvidenceRef),\n\t\tfindings: bundle.findings.map(cloneFinding),\n\t\tcreatedAt: bundle.createdAt,\n\t};\n}\n\nexport function isEvidenceBundle(value: unknown): value is EvidenceBundle {\n\tif (!isPlainRecord(value)) return false;\n\tconst bundle = value as Record<string, unknown>;\n\n\tif (typeof bundle.query !== \"string\") return false;\n\tif (bundle.createdAt !== undefined && typeof bundle.createdAt !== \"string\") return false;\n\n\tif (!Array.isArray(bundle.sources)) return false;\n\tfor (const source of bundle.sources) {\n\t\tif (!isPlainRecord(source)) return false;\n\t\tconst ref = source as Record<string, unknown>;\n\t\tif (typeof ref.id !== \"string\") return false;\n\t\tif (\n\t\t\ttypeof ref.kind !== \"string\" ||\n\t\t\t![\"workspace\", \"transcript\", \"automata\", \"web\", \"user\", \"tool\"].includes(ref.kind)\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tif (typeof ref.trusted !== \"boolean\") return false;\n\t\tif (ref.title !== undefined && typeof ref.title !== \"string\") return false;\n\t\tif (ref.uri !== undefined && typeof ref.uri !== \"string\") return false;\n\t\tif (ref.excerpt !== undefined && typeof ref.excerpt !== \"string\") return false;\n\t\tif (ref.metadata !== undefined && !isJsonObject(ref.metadata)) return false;\n\t}\n\n\tif (!Array.isArray(bundle.findings)) return false;\n\tfor (const finding of bundle.findings) {\n\t\tif (!isPlainRecord(finding)) return false;\n\t\tconst f = finding as Record<string, unknown>;\n\t\tif (typeof f.id !== \"string\") return false;\n\t\tif (typeof f.summary !== \"string\") return false;\n\t\tif (f.confidence !== undefined && (typeof f.confidence !== \"number\" || !Number.isFinite(f.confidence)))\n\t\t\treturn false;\n\t\tif (!Array.isArray(f.evidenceIds) || !f.evidenceIds.every((id) => typeof id === \"string\")) return false;\n\t}\n\n\treturn true;\n}\n"]}
|