@caupulican/pi-adaptative 0.81.40 → 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 +25 -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 +1 -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 +1 -0
- package/dist/cli/args.d.ts +2 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +22 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-paths.d.ts +6 -0
- package/dist/core/agent-paths.d.ts.map +1 -1
- package/dist/core/agent-paths.js +12 -0
- 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.map +1 -1
- package/dist/core/agent-session-runtime.js +3 -0
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session.d.ts +26 -405
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +86 -307
- 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/lane-tool-surface.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.js +2 -1
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +3 -1
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +1 -0
- 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/compaction-controller.d.ts.map +1 -1
- package/dist/core/compaction-controller.js +1 -1
- package/dist/core/compaction-controller.js.map +1 -1
- package/dist/core/compaction-support.d.ts +3 -8
- 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-pipeline.d.ts +1 -1
- package/dist/core/context-pipeline.d.ts.map +1 -1
- package/dist/core/context-pipeline.js +7 -33
- 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 +1 -0
- package/dist/core/default-tool-surface.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/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +2 -3
- 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 +14 -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/types.d.ts +8 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/foreground-recovery-controller.d.ts +1 -0
- package/dist/core/foreground-recovery-controller.d.ts.map +1 -1
- package/dist/core/foreground-recovery-controller.js +13 -13
- package/dist/core/foreground-recovery-controller.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.map +1 -1
- package/dist/core/goals/goal-acceptance.js +2 -0
- package/dist/core/goals/goal-acceptance.js.map +1 -1
- package/dist/core/goals/goal-auto-continue-controller.d.ts +2 -1
- package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-auto-continue-controller.js +5 -8
- package/dist/core/goals/goal-auto-continue-controller.js.map +1 -1
- 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 +42 -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 +35 -12
- package/dist/core/goals/goal-lifecycle.d.ts.map +1 -1
- package/dist/core/goals/goal-lifecycle.js +98 -13
- package/dist/core/goals/goal-lifecycle.js.map +1 -1
- 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-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 +45 -25
- package/dist/core/goals/goal-state.d.ts.map +1 -1
- package/dist/core/goals/goal-state.js +85 -15
- package/dist/core/goals/goal-state.js.map +1 -1
- package/dist/core/goals/goal-tool-core.d.ts +1 -4
- package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
- package/dist/core/goals/goal-tool-core.js +49 -34
- package/dist/core/goals/goal-tool-core.js.map +1 -1
- package/dist/core/goals/session-goal-state.d.ts +18 -8
- package/dist/core/goals/session-goal-state.d.ts.map +1 -1
- package/dist/core/goals/session-goal-state.js +134 -11
- 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/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/model-capability.d.ts +0 -19
- package/dist/core/model-capability.d.ts.map +1 -1
- package/dist/core/model-capability.js +0 -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 +16 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +32 -16
- package/dist/core/model-resolver.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.map +1 -1
- package/dist/core/model-selection-controller.d.ts +1 -1
- package/dist/core/model-selection-controller.d.ts.map +1 -1
- package/dist/core/model-selection-controller.js.map +1 -1
- package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -1
- package/dist/core/orchestration/delegation-ledger.js +3 -0
- package/dist/core/orchestration/delegation-ledger.js.map +1 -1
- package/dist/core/orchestration/work-state-projection.d.ts.map +1 -1
- package/dist/core/orchestration/work-state-projection.js +1 -1
- package/dist/core/orchestration/work-state-projection.js.map +1 -1
- 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/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/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 +1 -1
- package/dist/core/reflection-controller.d.ts.map +1 -1
- package/dist/core/reflection-controller.js +3 -1
- package/dist/core/reflection-controller.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/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +16 -6
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/risk-classifier.d.ts.map +1 -1
- package/dist/core/risk-classifier.js +8 -0
- package/dist/core/risk-classifier.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +15 -3
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +132 -79
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +7 -1
- 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 +39 -69
- package/dist/core/session-analytics.js.map +1 -1
- package/dist/core/session-role.d.ts +5 -0
- package/dist/core/session-role.d.ts.map +1 -1
- package/dist/core/session-role.js +14 -1
- package/dist/core/session-role.js.map +1 -1
- 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 +1 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +1 -1
- 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/tool-capability-policy.d.ts.map +1 -1
- package/dist/core/tool-capability-policy.js +1 -0
- package/dist/core/tool-capability-policy.js.map +1 -1
- 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 +2 -4
- package/dist/core/tool-protocol-controller.d.ts.map +1 -1
- package/dist/core/tool-protocol-controller.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/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.map +1 -1
- package/dist/core/tools/delegate-status.js +6 -7
- package/dist/core/tools/delegate-status.js.map +1 -1
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +6 -8
- package/dist/core/tools/delegate.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 +5 -3
- package/dist/core/tools/goal.d.ts.map +1 -1
- package/dist/core/tools/goal.js +97 -19
- 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/orchestration-panel.d.ts +1 -4
- package/dist/core/tools/orchestration-panel.d.ts.map +1 -1
- package/dist/core/tools/orchestration-panel.js +0 -44
- package/dist/core/tools/orchestration-panel.js.map +1 -1
- 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/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.map +1 -1
- package/dist/core/tools/task-steps.js +4 -7
- package/dist/core/tools/task-steps.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/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +25 -11
- package/dist/main.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/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 +4 -4
- 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/extension-ui-host.d.ts.map +1 -1
- package/dist/modes/interactive/extension-ui-host.js +1 -0
- 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 +20 -25
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +196 -608
- package/dist/modes/interactive/interactive-mode.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/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 +10 -6
- package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
- package/dist/modes/interactive/session-flow-commands.js +123 -70
- package/dist/modes/interactive/session-flow-commands.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/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/docs/UI_POLISH_ORCHESTRATION.md +25 -31
- package/docs/UI_QUALITY_ORCHESTRATION.md +22 -24
- package/docs/providers.md +9 -1
- package/docs/ui-reference/README.md +6 -6
- package/docs/ui-reference/orchestration-after.txt +14 -7
- package/docs/ui-reference/orchestration-before.txt +12 -6
- package/docs/ui-reference/orchestration-reference.txt +15 -5
- package/docs/usage.md +9 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"background-lane-controller.js","sourceRoot":"","sources":["../../src/core/background-lane-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAUH,OAAO,EAAmB,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AAC3G,OAAO,EAAE,qBAAqB,EAAE,MAAM,yCAAyC,CAAC;AAChF,OAAO,EACN,0BAA0B,GAE1B,MAAM,8CAA8C,CAAC;AAEt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CACD","sourcesContent":["/**\n * Execution-plane coordinator for goal continuation, research, managed lanes, worker delegation,\n * and model fitness.\n *\n * Coordination state is owned by focused controllers. This coordinator retains one AgentSession\n * composition seam and a shared lane read model. Everything it needs\n * — the session manager, settings, model registry, live model, capability envelope, the goal\n * continuation LOOP, the isolated-completion primitive, spawned-usage accounting, and the telemetry\n * sink — is reached through narrow deps accessors rather than the whole AgentSession.\n *\n * Drive-loop boundary (deliberate): the idle triggers ({@link scheduleGoalAutoContinueFromIdle},\n * {@link scheduleResearchLaneFromIdle}) are invoked from the session's prompt tail as one-line\n * delegations; goal auto-continue itself only ever asks the session to `continueGoalLoop`, so this\n * controller never touches `prompt()`, the last-assistant-message, retry, or streaming state.\n */\n\nimport type { Api, Model } from \"@caupulican/pi-ai\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tPromptOptions,\n\tResearchLaneRunOutcome,\n\tWorkerDelegationRunOutcome,\n} from \"./agent-session.ts\";\nimport { type LaneRecord, LaneTracker } from \"./autonomy/lane-tracker.ts\";\nimport { appendLaneRecordSnapshot, getLatestLaneRecordSnapshots } from \"./autonomy/session-lane-record.ts\";\nimport { ManagedLaneController } from \"./delegation/managed-lane-controller.ts\";\nimport {\n\tWorkerDelegationController,\n\ttype WorkerDelegationControllerDeps,\n} from \"./delegation/worker-delegation-controller.ts\";\nimport type { WorkerDelegationRequest } from \"./delegation/worker-delegation-request.ts\";\nimport { WorkerLifecycle } from \"./delegation/worker-lifecycle.ts\";\nimport { WorkerNotificationCoordinator } from \"./delegation/worker-notification-coordinator.ts\";\nimport type { ManagedLaneEvent } from \"./extensions/types.ts\";\nimport { GoalAutoContinueController } from \"./goals/goal-auto-continue-controller.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goals/goal-runtime-snapshot.ts\";\nimport type { GoalState } from \"./goals/goal-state.ts\";\nimport type { ModelCapabilityProfile } from \"./model-capability.ts\";\nimport type { StoredFitnessReport } from \"./models/fitness-store.ts\";\nimport type { TaskRuntimeProjection } from \"./orchestration/task-runtime.ts\";\nimport { LaneModelResolver, type LaneModelResolverDeps } from \"./research/lane-model-resolver.ts\";\nimport type { ModelFitnessReport } from \"./research/model-fitness.ts\";\nimport { ModelFitnessController, type ModelFitnessControllerDeps } from \"./research/model-fitness-controller.ts\";\nimport { ResearchLaneController, type ResearchLaneControllerDeps } from \"./research/research-lane-controller.ts\";\nimport { getActiveSessionBranchEntries } from \"./session-snapshot.ts\";\n\nexport { isLocalExecutionModel } from \"./delegation/worker-delegation-controller.ts\";\nexport { clampLaneMaxUsd } from \"./research/lane-model-resolver.ts\";\n\nexport interface BackgroundLaneControllerDeps\n\textends WorkerDelegationControllerDeps,\n\t\tResearchLaneControllerDeps,\n\t\tModelFitnessControllerDeps,\n\t\tLaneModelResolverDeps {\n\t/** True iff the `goal` tool is in the session's ACTIVE surface -- the capability-adaptive gate\n\t * for every goal-continuation loop (see `continueGoalLoopExclusive`): a surface without the\n\t * goal tool (lean capability blocklist, worker role ceiling, --tools/profile exclusion) must\n\t * never be driven with continuation prompts it cannot execute. */\n\tisGoalToolActive(): boolean;\n\t/** Capability profile of the SESSION model (gates background lanes, scales continuation budgets). */\n\tgetModelCapabilityProfile(): ModelCapabilityProfile;\n\t/** Continuation gate + goal state for the idle autosteer scheduler. */\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\t/** Drive-loop boundary: the session's bounded goal-continuation loop (owns `prompt()`, not us). */\n\tcontinueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;\n}\n\nexport class BackgroundLaneController {\n\t/** Live lane registry — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tprivate readonly _laneTracker = new LaneTracker();\n\tprivate readonly _laneModels: LaneModelResolver;\n\tprivate readonly _goalAutoContinue: GoalAutoContinueController;\n\tprivate readonly _research: ResearchLaneController;\n\tprivate readonly _fitness: ModelFitnessController;\n\t/** Lazily materialized only when managed-lane state is queried or reported. */\n\tprivate _managedLanes: ManagedLaneController | undefined;\n\t/** Lazily materialized so a UAC surface without `delegate` allocates no worker runtime state. */\n\tprivate _workers: WorkerDelegationController | undefined;\n\t/** One durable lifecycle shared by every worker execution adapter. */\n\tprivate _workerLifecycle: WorkerLifecycle | undefined;\n\t/** Shared terminal outbox for managed and in-process workers; lazy under UAC omission. */\n\tprivate _workerNotifications: WorkerNotificationCoordinator | undefined;\n\tprivate readonly deps: BackgroundLaneControllerDeps;\n\n\t/** Emit a warning without ever throwing — used from disposal-adjacent persistence where a\n\t * listener failure (or a bare test double missing `emit`) must never block or crash cleanup. */\n\tprivate _safeWarn(message: string): void {\n\t\ttry {\n\t\t\tthis.deps.emit({ type: \"warning\", message });\n\t\t} catch {\n\t\t\t// Dispose must never throw.\n\t\t}\n\t}\n\n\tprivate _recordWorkerTerminal(record: LaneRecord, durableNotificationId: string): void {\n\t\tthis._getWorkerNotificationCoordinator().recordTerminal(record, durableNotificationId);\n\t}\n\n\tconstructor(deps: BackgroundLaneControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis._laneModels = new LaneModelResolver(deps);\n\t\tthis._research = new ResearchLaneController(deps, this._laneTracker, this._laneModels);\n\t\tthis._fitness = new ModelFitnessController(deps, this._laneModels);\n\t\tthis._goalAutoContinue = new GoalAutoContinueController({\n\t\t\tisDisposed: deps.isDisposed,\n\t\t\tisGoalToolActive: deps.isGoalToolActive,\n\t\t\tgetSettingsManager: deps.getSettingsManager,\n\t\t\tgetModelCapabilityProfile: deps.getModelCapabilityProfile,\n\t\t\tgetGoalRuntimeSnapshot: deps.getGoalRuntimeSnapshot,\n\t\t\thasInFlightLaneForGoal: (goalId) => this._hasInFlightLaneForGoal(goalId),\n\t\t\tcontinueGoalLoop: deps.continueGoalLoop,\n\t\t\temit: deps.emit,\n\t\t});\n\t}\n\n\tprivate _getWorkerController(): WorkerDelegationController {\n\t\tthis._workers ??= new WorkerDelegationController(\n\t\t\tthis.deps,\n\t\t\tthis._getWorkerNotificationCoordinator(),\n\t\t\tthis._getWorkerLifecycle(),\n\t\t);\n\t\treturn this._workers;\n\t}\n\n\tprivate _getWorkerLifecycle(): WorkerLifecycle {\n\t\tif (this._workerLifecycle) return this._workerLifecycle;\n\t\tconst lifecycle = new WorkerLifecycle({\n\t\t\tagentDir: this.deps.getAgentDir(),\n\t\t\tsessionId: this.deps.getSessionId(),\n\t\t});\n\t\tthis._workerLifecycle = lifecycle;\n\t\tfor (const notification of lifecycle.getPendingTerminalNotifications()) {\n\t\t\tthis._getWorkerNotificationCoordinator().recordTerminal(notification.record, notification.notificationId);\n\t\t}\n\t\treturn lifecycle;\n\t}\n\n\tprivate _getWorkerNotificationCoordinator(): WorkerNotificationCoordinator {\n\t\tthis._workerNotifications ??= new WorkerNotificationCoordinator({\n\t\t\tgetWorkerRecords: () => this._workerLifecycle?.getAllRecords() ?? [],\n\t\t\temitStatus: (status) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.deps.emit({\n\t\t\t\t\t\ttype: \"delegate_workers\",\n\t\t\t\t\t\t...status,\n\t\t\t\t\t\tterminalSinceFlush: [...status.terminalSinceFlush],\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\t// A partial integration must not crash the event-driven terminal outbox.\n\t\t\t\t}\n\t\t\t},\n\t\t\tnotify: (records) => this.deps.notifyWorkerTerminalHandoff(records),\n\t\t\twarn: (message) => this._safeWarn(message),\n\t\t\tmarkDurableDelivered: (notificationIds) => this._workerLifecycle?.markNotificationsDelivered(notificationIds),\n\t\t});\n\t\treturn this._workerNotifications;\n\t}\n\n\tprivate _getManagedLaneController(): ManagedLaneController {\n\t\tthis._managedLanes ??= new ManagedLaneController(\n\t\t\tthis.deps,\n\t\t\tthis._getWorkerLifecycle(),\n\t\t\t(record, notificationId) => this._recordWorkerTerminal(record, notificationId),\n\t\t);\n\t\treturn this._managedLanes;\n\t}\n\n\tprivate _hydrateManagedLanes(): void {\n\t\tif (this._managedLanes) {\n\t\t\tthis._managedLanes.ensureHydrated();\n\t\t\treturn;\n\t\t}\n\t\tconst hasPersistedActiveManagedLane = getLatestLaneRecordSnapshots(\n\t\t\tgetActiveSessionBranchEntries(this.deps.getSessionManager()),\n\t\t).some((record) => record.type === \"tmux-worker\" && (record.status === \"queued\" || record.status === \"running\"));\n\t\tif (hasPersistedActiveManagedLane) this._getManagedLaneController().ensureHydrated();\n\t}\n\n\t/** Live lane records tracked by this process (running and terminal). */\n\tgetLaneRecords(): LaneRecord[] {\n\t\tthis._hydrateManagedLanes();\n\t\tconst workerRecords =\n\t\t\tthis._workers?.getRecords() ??\n\t\t\t(this.deps.isDelegateToolActive?.() ? this._getWorkerController().getRecords() : []);\n\t\treturn [\n\t\t\t...this._laneTracker.getRecords(),\n\t\t\t...workerRecords,\n\t\t\t...(this._workerLifecycle?.getManagedRecords() ?? []),\n\t\t];\n\t}\n\n\t/** Does not materialize the worker controller when UAC omitted delegation. */\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined {\n\t\treturn this._workerLifecycle?.getTaskRuntimeSnapshot();\n\t}\n\n\t/** Reconcile only when delegation has already been materialized; UAC omission stays zero-load. */\n\tsynchronizeGoalState(goal: GoalState): void {\n\t\tthis._workers?.synchronizeGoalState(goal);\n\t}\n\n\t/**\n\t * Resolve a tracked managed-lane dispatch. The caller's stable id is also the canonical durable\n\t * lane id, so this is an existence check rather than an id translation.\n\t */\n\tresolveManagedLaneId(callerLaneId: string): string | undefined {\n\t\treturn this._getManagedLaneController().resolve(callerLaneId);\n\t}\n\n\t/** Live count of active lanes — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tgetActiveLaneCount(): number {\n\t\treturn this.getLaneRecords().filter((record) => record.status === \"queued\" || record.status === \"running\").length;\n\t}\n\n\t/** Belt-and-braces guard: whether ANY queued/running lane is tagged with this goalId. */\n\tprivate _hasInFlightLaneForGoal(goalId: string): boolean {\n\t\treturn this.getLaneRecords().some(\n\t\t\t(record) => record.goalId === goalId && (record.status === \"queued\" || record.status === \"running\"),\n\t\t);\n\t}\n\n\t/** Delegate the out-of-process dispatch/terminal claim to its single lifecycle owner. */\n\trecordManagedLane(event: ManagedLaneEvent): LaneRecord | undefined {\n\t\treturn this._getManagedLaneController().record(event);\n\t}\n\n\t/** Why the last idle research-lane evaluation skipped, for /autonomy diagnostics. */\n\tgetLastResearchLaneSkipReason(): string | undefined {\n\t\treturn this._research.getLastSkipReason();\n\t}\n\n\t/**\n\t * Abort in-flight research and delegate worker disposal to its single owning controller.\n\t *\n\t * This synchronous body is the LAST provably-safe write window for canceled/in-flight work.\n\t * `dispose()` (agent-session.ts) has already set the session's own disposed flag but has not yet\n\t * returned — no successor session (e.g. a `/reload` adoption) can exist yet, so an append here\n\t * cannot interleave with one; a post-await continuation resuming AFTER this method returns must\n\t * not append (see the disposed branch in `runWorkerDelegationOnce`). Persist FIRST, then\n\t * complete-in-memory, so a throw from one lane's persist cannot skip another's; each persist gets\n\t * its own try/catch — dispose must never throw.\n\t */\n\tabortInFlightLanes(): void {\n\t\tthis._goalAutoContinue.clearTimer();\n\t\tthis._research.abort();\n\t\tthis._fitness.abort();\n\t\tfor (const record of this._laneTracker.getRecords()) {\n\t\t\tif (record.status !== \"queued\" && record.status !== \"running\") continue;\n\t\t\tif (record.type === \"tmux-worker\") continue;\n\t\t\tconst canceled = this._laneTracker.complete(record.laneId, {\n\t\t\t\tstatus: \"canceled\",\n\t\t\t\treasonCode: \"session_disposed\",\n\t\t\t});\n\t\t\tif (!canceled) continue;\n\t\t\ttry {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), canceled);\n\t\t\t} catch (error) {\n\t\t\t\tthis._safeWarn(\n\t\t\t\t\t`Failed to persist canceled lane record ${canceled.laneId}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis._managedLanes?.release();\n\n\t\tthis._workers?.abort();\n\t\tthis._workerNotifications?.dispose();\n\t}\n\n\tclearGoalAutoContinueTimer(): void {\n\t\tthis._goalAutoContinue.clearTimer();\n\t}\n\n\tscheduleGoalAutoContinueFromIdle(options?: PromptOptions): void {\n\t\tthis._goalAutoContinue.scheduleFromIdle(options);\n\t}\n\n\t/**\n\t * Single-flight entry point for EVERY goal-continuation loop invocation — idle autosteer\n\t * ({@link _runScheduledGoalAutoContinue}) AND the manual `/goal start` / `/goal-continue`\n\t * commands (reached through `AgentSession.continueGoalLoop`). Both paths ultimately submit\n\t * continuation prompts through the session's single `prompt()` path, so two loops racing throws\n\t * \"Agent is already processing\" from whichever submits second. `_isGoalAutoContinuing` is the\n\t * ONE owner of that mutex; `deps.continueGoalLoop` (the raw {@link GoalLoopController} loop)\n\t * must never be called directly outside this method, or the guard is bypassed.\n\t */\n\tasync continueGoalLoopExclusive(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\treturn this._goalAutoContinue.continueExclusive(options);\n\t}\n\n\tclearResearchLaneTimer(): void {\n\t\tthis._research.clearTimer();\n\t}\n\n\tscheduleResearchLaneFromIdle(): void {\n\t\tthis._research.scheduleFromIdle();\n\t}\n\n\tresolveLaneModel(configuredPattern: string | undefined): Model<Api> | undefined {\n\t\treturn this._laneModels.resolveModel(configuredPattern);\n\t}\n\n\tgetOrchestrationProfileCatalog(): Array<{ profileId: string; role: string; description: string }> {\n\t\treturn this._getWorkerController().getProfileCatalog();\n\t}\n\n\t/**\n\t * Run one bounded, read-only research pass and persist its results: evidence bundle snapshot,\n\t * terminal lane record, and spawned-usage cost report (single-hop invariant, idempotent on the\n\t * lane's reportId). Explicit calls (e.g. `/autonomy research`) express user intent and bypass the\n\t * enabled/mode/dedupe gates the idle scheduler enforces; budget and capability gates always apply.\n\t */\n\tasync runResearchLaneOnce(request?: {\n\t\tquery?: string;\n\t\tcontext?: string;\n\t\tgoalId?: string;\n\t}): Promise<ResearchLaneRunOutcome> {\n\t\treturn this._research.runOnce(request);\n\t}\n\t/** Start a durable, profile-bound worker delegation. */\n\tstartWorkerDelegation(\n\t\trequest: WorkerDelegationRequest,\n\t): { started: false; skipReason: string } | { started: true; record: LaneRecord } {\n\t\treturn this._getWorkerController().start(request);\n\t}\n\n\t/** Run one worker immediately; used by focused integrations and tests. */\n\tasync runWorkerDelegationOnce(\n\t\trequest: WorkerDelegationRequest,\n\t\tonStarted?: (record: LaneRecord) => void,\n\t\texistingRecord?: LaneRecord,\n\t): Promise<WorkerDelegationRunOutcome> {\n\t\treturn this._getWorkerController().runOnce(request, onStarted, existingRecord);\n\t}\n\t/**\n\t * Probe a candidate model against the subagent contracts (research/worker/judge/search/\n\t * tool-call surfaces) via {@link runModelFitnessProbe}. The model must resolve and\n\t * authenticate; every probe call runs as an isolated completion on that model, and probe\n\t * spend is reported through spawned-usage accounting.\n\t */\n\tasync runModelFitness(args: {\n\t\tmodel: string;\n\t\ttrials?: number;\n\t\t/** LLM tool-call id, present only via the model_fitness tool path — see model-fitness.ts. */\n\t\ttoolCallId?: string;\n\t}): Promise<{ started: true; model: string; report: ModelFitnessReport } | { started: false; skipReason: string }> {\n\t\treturn this._fitness.run(args);\n\t}\n\n\t/** Start every capacity-eligible queued worker at the owner session's foreground-idle boundary. */\n\tdrainQueuedWorkerDelegations(): void {\n\t\tif (this.deps.isDelegateToolActive?.()) this._getWorkerController().drain();\n\t}\n\n\t/** Fitness reports persisted for THIS host (measured evidence for architect/profile decisions). */\n\tgetStoredFitnessReports(): StoredFitnessReport[] {\n\t\treturn this._fitness.getStoredReports();\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"background-lane-controller.js","sourceRoot":"","sources":["../../src/core/background-lane-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAUH,OAAO,EAAmB,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AAC3G,OAAO,EAAE,qBAAqB,EAAE,MAAM,yCAAyC,CA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ED,mGAAmG;IACnG,uBAAuB,GAA0B;QAChD,OAAO,IAAI,CAAC,QAAQ,CAAC,gBAAgB,EAAE,CAAC;IAAA,CACxC;CACD","sourcesContent":["/**\n * Execution-plane coordinator for goal continuation, research, managed lanes, worker delegation,\n * and model fitness.\n *\n * Coordination state is owned by focused controllers. This coordinator retains one AgentSession\n * composition seam and a shared lane read model. Everything it needs\n * — the session manager, settings, model registry, live model, capability envelope, the goal\n * continuation LOOP, the isolated-completion primitive, spawned-usage accounting, and the telemetry\n * sink — is reached through narrow deps accessors rather than the whole AgentSession.\n *\n * Drive-loop boundary (deliberate): the idle triggers ({@link scheduleGoalAutoContinueFromIdle},\n * {@link scheduleResearchLaneFromIdle}) are invoked from the session's prompt tail as one-line\n * delegations; goal auto-continue itself only ever asks the session to `continueGoalLoop`, so this\n * controller never touches `prompt()`, the last-assistant-message, retry, or streaming state.\n */\n\nimport type { Api, Model } from \"@caupulican/pi-ai\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tPromptOptions,\n\tResearchLaneRunOutcome,\n\tWorkerDelegationRunOutcome,\n} from \"./agent-session-contracts.ts\";\nimport { type LaneRecord, LaneTracker } from \"./autonomy/lane-tracker.ts\";\nimport { appendLaneRecordSnapshot, getLatestLaneRecordSnapshots } from \"./autonomy/session-lane-record.ts\";\nimport { ManagedLaneController } from \"./delegation/managed-lane-controller.ts\";\nimport {\n\tWorkerDelegationController,\n\ttype WorkerDelegationControllerDeps,\n} from \"./delegation/worker-delegation-controller.ts\";\nimport type { WorkerDelegationRequest } from \"./delegation/worker-delegation-request.ts\";\nimport { WorkerLifecycle } from \"./delegation/worker-lifecycle.ts\";\nimport { WorkerNotificationCoordinator } from \"./delegation/worker-notification-coordinator.ts\";\nimport type { ManagedLaneEvent } from \"./extensions/types.ts\";\nimport { GoalAutoContinueController } from \"./goals/goal-auto-continue-controller.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goals/goal-runtime-snapshot.ts\";\nimport type { GoalState } from \"./goals/goal-state.ts\";\nimport type { ModelCapabilityProfile } from \"./model-capability.ts\";\nimport type { StoredFitnessReport } from \"./models/fitness-store.ts\";\nimport type { TaskRuntimeProjection } from \"./orchestration/task-runtime.ts\";\nimport { LaneModelResolver, type LaneModelResolverDeps } from \"./research/lane-model-resolver.ts\";\nimport type { ModelFitnessReport } from \"./research/model-fitness.ts\";\nimport { ModelFitnessController, type ModelFitnessControllerDeps } from \"./research/model-fitness-controller.ts\";\nimport { ResearchLaneController, type ResearchLaneControllerDeps } from \"./research/research-lane-controller.ts\";\nimport { getActiveSessionBranchEntries } from \"./session-snapshot.ts\";\n\nexport { isLocalExecutionModel } from \"./delegation/worker-delegation-controller.ts\";\nexport { clampLaneMaxUsd } from \"./research/lane-model-resolver.ts\";\n\nexport interface BackgroundLaneControllerDeps\n\textends WorkerDelegationControllerDeps,\n\t\tResearchLaneControllerDeps,\n\t\tModelFitnessControllerDeps,\n\t\tLaneModelResolverDeps {\n\t/** True iff the `goal` tool is in the session's ACTIVE surface -- the capability-adaptive gate\n\t * for every goal-continuation loop (see `continueGoalLoopExclusive`): a surface without the\n\t * goal tool (lean capability blocklist, worker role ceiling, --tools/profile exclusion) must\n\t * never be driven with continuation prompts it cannot execute. */\n\tisGoalToolActive(): boolean;\n\t/** Capability profile of the SESSION model (gates background lanes, scales continuation budgets). */\n\tgetModelCapabilityProfile(): ModelCapabilityProfile;\n\t/** Continuation gate + goal state for the idle autosteer scheduler. */\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\t/** Drive-loop boundary: the session's bounded goal-continuation loop (owns `prompt()`, not us). */\n\tcontinueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;\n\t/** Persist an explicit stopped state when the selected surface cannot drive the active goal. */\n\tmarkGoalToolUnavailable(): void;\n}\n\nexport class BackgroundLaneController {\n\t/** Live lane registry — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tprivate readonly _laneTracker = new LaneTracker();\n\tprivate readonly _laneModels: LaneModelResolver;\n\tprivate readonly _goalAutoContinue: GoalAutoContinueController;\n\tprivate readonly _research: ResearchLaneController;\n\tprivate readonly _fitness: ModelFitnessController;\n\t/** Lazily materialized only when managed-lane state is queried or reported. */\n\tprivate _managedLanes: ManagedLaneController | undefined;\n\t/** Lazily materialized so a UAC surface without `delegate` allocates no worker runtime state. */\n\tprivate _workers: WorkerDelegationController | undefined;\n\t/** One durable lifecycle shared by every worker execution adapter. */\n\tprivate _workerLifecycle: WorkerLifecycle | undefined;\n\t/** Shared terminal outbox for managed and in-process workers; lazy under UAC omission. */\n\tprivate _workerNotifications: WorkerNotificationCoordinator | undefined;\n\tprivate readonly deps: BackgroundLaneControllerDeps;\n\n\t/** Emit a warning without ever throwing — used from disposal-adjacent persistence where a\n\t * listener failure (or a bare test double missing `emit`) must never block or crash cleanup. */\n\tprivate _safeWarn(message: string): void {\n\t\ttry {\n\t\t\tthis.deps.emit({ type: \"warning\", message });\n\t\t} catch {\n\t\t\t// Dispose must never throw.\n\t\t}\n\t}\n\n\tprivate _recordWorkerTerminal(record: LaneRecord, durableNotificationId: string): void {\n\t\tthis._getWorkerNotificationCoordinator().recordTerminal(record, durableNotificationId);\n\t}\n\n\tconstructor(deps: BackgroundLaneControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis._laneModels = new LaneModelResolver(deps);\n\t\tthis._research = new ResearchLaneController(deps, this._laneTracker, this._laneModels);\n\t\tthis._fitness = new ModelFitnessController(deps, this._laneModels);\n\t\tthis._goalAutoContinue = new GoalAutoContinueController({\n\t\t\tisDisposed: deps.isDisposed,\n\t\t\tisGoalToolActive: deps.isGoalToolActive,\n\t\t\tgetSettingsManager: deps.getSettingsManager,\n\t\t\tgetModelCapabilityProfile: deps.getModelCapabilityProfile,\n\t\t\tgetGoalRuntimeSnapshot: deps.getGoalRuntimeSnapshot,\n\t\t\thasInFlightLaneForGoal: (goalId) => this._hasInFlightLaneForGoal(goalId),\n\t\t\tcontinueGoalLoop: deps.continueGoalLoop,\n\t\t\tmarkGoalToolUnavailable: deps.markGoalToolUnavailable,\n\t\t\temit: deps.emit,\n\t\t});\n\t}\n\n\tprivate _getWorkerController(): WorkerDelegationController {\n\t\tthis._workers ??= new WorkerDelegationController(\n\t\t\tthis.deps,\n\t\t\tthis._getWorkerNotificationCoordinator(),\n\t\t\tthis._getWorkerLifecycle(),\n\t\t);\n\t\treturn this._workers;\n\t}\n\n\tprivate _getWorkerLifecycle(): WorkerLifecycle {\n\t\tif (this._workerLifecycle) return this._workerLifecycle;\n\t\tconst lifecycle = new WorkerLifecycle({\n\t\t\tagentDir: this.deps.getAgentDir(),\n\t\t\tsessionId: this.deps.getSessionId(),\n\t\t});\n\t\tthis._workerLifecycle = lifecycle;\n\t\tfor (const notification of lifecycle.getPendingTerminalNotifications()) {\n\t\t\tthis._getWorkerNotificationCoordinator().recordTerminal(notification.record, notification.notificationId);\n\t\t}\n\t\treturn lifecycle;\n\t}\n\n\tprivate _getWorkerNotificationCoordinator(): WorkerNotificationCoordinator {\n\t\tthis._workerNotifications ??= new WorkerNotificationCoordinator({\n\t\t\tgetWorkerRecords: () => this._workerLifecycle?.getAllRecords() ?? [],\n\t\t\temitStatus: (status) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.deps.emit({\n\t\t\t\t\t\ttype: \"delegate_workers\",\n\t\t\t\t\t\t...status,\n\t\t\t\t\t\tterminalSinceFlush: [...status.terminalSinceFlush],\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\t// A partial integration must not crash the event-driven terminal outbox.\n\t\t\t\t}\n\t\t\t},\n\t\t\tnotify: (records) => this.deps.notifyWorkerTerminalHandoff(records),\n\t\t\twarn: (message) => this._safeWarn(message),\n\t\t\tmarkDurableDelivered: (notificationIds) => this._workerLifecycle?.markNotificationsDelivered(notificationIds),\n\t\t});\n\t\treturn this._workerNotifications;\n\t}\n\n\tprivate _getManagedLaneController(): ManagedLaneController {\n\t\tthis._managedLanes ??= new ManagedLaneController(\n\t\t\tthis.deps,\n\t\t\tthis._getWorkerLifecycle(),\n\t\t\t(record, notificationId) => this._recordWorkerTerminal(record, notificationId),\n\t\t);\n\t\treturn this._managedLanes;\n\t}\n\n\tprivate _hydrateManagedLanes(): void {\n\t\tif (this._managedLanes) {\n\t\t\tthis._managedLanes.ensureHydrated();\n\t\t\treturn;\n\t\t}\n\t\tconst hasPersistedActiveManagedLane = getLatestLaneRecordSnapshots(\n\t\t\tgetActiveSessionBranchEntries(this.deps.getSessionManager()),\n\t\t).some((record) => record.type === \"tmux-worker\" && (record.status === \"queued\" || record.status === \"running\"));\n\t\tif (hasPersistedActiveManagedLane) this._getManagedLaneController().ensureHydrated();\n\t}\n\n\t/** Live lane records tracked by this process (running and terminal). */\n\tgetLaneRecords(): LaneRecord[] {\n\t\tthis._hydrateManagedLanes();\n\t\tconst workerRecords =\n\t\t\tthis._workers?.getRecords() ??\n\t\t\t(this.deps.isDelegateToolActive?.() ? this._getWorkerController().getRecords() : []);\n\t\treturn [\n\t\t\t...this._laneTracker.getRecords(),\n\t\t\t...workerRecords,\n\t\t\t...(this._workerLifecycle?.getManagedRecords() ?? []),\n\t\t];\n\t}\n\n\t/** Does not materialize the worker controller when UAC omitted delegation. */\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined {\n\t\treturn this._workerLifecycle?.getTaskRuntimeSnapshot();\n\t}\n\n\t/** Reconcile only when delegation has already been materialized; UAC omission stays zero-load. */\n\tsynchronizeGoalState(goal: GoalState): void {\n\t\tthis._workers?.synchronizeGoalState(goal);\n\t}\n\n\t/**\n\t * Resolve a tracked managed-lane dispatch. The caller's stable id is also the canonical durable\n\t * lane id, so this is an existence check rather than an id translation.\n\t */\n\tresolveManagedLaneId(callerLaneId: string): string | undefined {\n\t\treturn this._getManagedLaneController().resolve(callerLaneId);\n\t}\n\n\t/** Live count of active lanes — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tgetActiveLaneCount(): number {\n\t\treturn this.getLaneRecords().filter((record) => record.status === \"queued\" || record.status === \"running\").length;\n\t}\n\n\t/** Belt-and-braces guard: whether ANY queued/running lane is tagged with this goalId. */\n\tprivate _hasInFlightLaneForGoal(goalId: string): boolean {\n\t\treturn this.getLaneRecords().some(\n\t\t\t(record) => record.goalId === goalId && (record.status === \"queued\" || record.status === \"running\"),\n\t\t);\n\t}\n\n\t/** Delegate the out-of-process dispatch/terminal claim to its single lifecycle owner. */\n\trecordManagedLane(event: ManagedLaneEvent): LaneRecord | undefined {\n\t\treturn this._getManagedLaneController().record(event);\n\t}\n\n\t/** Why the last idle research-lane evaluation skipped, for /autonomy diagnostics. */\n\tgetLastResearchLaneSkipReason(): string | undefined {\n\t\treturn this._research.getLastSkipReason();\n\t}\n\n\t/**\n\t * Abort in-flight research and delegate worker disposal to its single owning controller.\n\t *\n\t * This synchronous body is the LAST provably-safe write window for canceled/in-flight work.\n\t * `dispose()` (agent-session.ts) has already set the session's own disposed flag but has not yet\n\t * returned — no successor session (e.g. a `/reload` adoption) can exist yet, so an append here\n\t * cannot interleave with one; a post-await continuation resuming AFTER this method returns must\n\t * not append (see the disposed branch in `runWorkerDelegationOnce`). Persist FIRST, then\n\t * complete-in-memory, so a throw from one lane's persist cannot skip another's; each persist gets\n\t * its own try/catch — dispose must never throw.\n\t */\n\tabortInFlightLanes(): void {\n\t\tthis._goalAutoContinue.clearTimer();\n\t\tthis._research.abort();\n\t\tthis._fitness.abort();\n\t\tfor (const record of this._laneTracker.getRecords()) {\n\t\t\tif (record.status !== \"queued\" && record.status !== \"running\") continue;\n\t\t\tif (record.type === \"tmux-worker\") continue;\n\t\t\tconst canceled = this._laneTracker.complete(record.laneId, {\n\t\t\t\tstatus: \"canceled\",\n\t\t\t\treasonCode: \"session_disposed\",\n\t\t\t});\n\t\t\tif (!canceled) continue;\n\t\t\ttry {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), canceled);\n\t\t\t} catch (error) {\n\t\t\t\tthis._safeWarn(\n\t\t\t\t\t`Failed to persist canceled lane record ${canceled.laneId}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis._managedLanes?.release();\n\n\t\tthis._workers?.abort();\n\t\tthis._workerNotifications?.dispose();\n\t}\n\n\tclearGoalAutoContinueTimer(): void {\n\t\tthis._goalAutoContinue.clearTimer();\n\t}\n\n\tscheduleGoalAutoContinueFromIdle(options?: PromptOptions): void {\n\t\tthis._goalAutoContinue.scheduleFromIdle(options);\n\t}\n\n\t/**\n\t * Single-flight entry point for EVERY goal-continuation loop invocation — idle autosteer\n\t * ({@link _runScheduledGoalAutoContinue}) AND the manual `/goal start` / `/goal-continue`\n\t * commands (reached through `AgentSession.continueGoalLoop`). Both paths ultimately submit\n\t * continuation prompts through the session's single `prompt()` path, so two loops racing throws\n\t * \"Agent is already processing\" from whichever submits second. `_isGoalAutoContinuing` is the\n\t * ONE owner of that mutex; `deps.continueGoalLoop` (the raw {@link GoalLoopController} loop)\n\t * must never be called directly outside this method, or the guard is bypassed.\n\t */\n\tasync continueGoalLoopExclusive(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\treturn this._goalAutoContinue.continueExclusive(options);\n\t}\n\n\tclearResearchLaneTimer(): void {\n\t\tthis._research.clearTimer();\n\t}\n\n\tscheduleResearchLaneFromIdle(): void {\n\t\tthis._research.scheduleFromIdle();\n\t}\n\n\tresolveLaneModel(configuredPattern: string | undefined): Model<Api> | undefined {\n\t\treturn this._laneModels.resolveModel(configuredPattern);\n\t}\n\n\tgetOrchestrationProfileCatalog(): Array<{ profileId: string; role: string; description: string }> {\n\t\treturn this._getWorkerController().getProfileCatalog();\n\t}\n\n\t/**\n\t * Run one bounded, read-only research pass and persist its results: evidence bundle snapshot,\n\t * terminal lane record, and spawned-usage cost report (single-hop invariant, idempotent on the\n\t * lane's reportId). Explicit calls (e.g. `/autonomy research`) express user intent and bypass the\n\t * enabled/mode/dedupe gates the idle scheduler enforces; budget and capability gates always apply.\n\t */\n\tasync runResearchLaneOnce(request?: {\n\t\tquery?: string;\n\t\tcontext?: string;\n\t\tgoalId?: string;\n\t}): Promise<ResearchLaneRunOutcome> {\n\t\treturn this._research.runOnce(request);\n\t}\n\t/** Start a durable, profile-bound worker delegation. */\n\tstartWorkerDelegation(\n\t\trequest: WorkerDelegationRequest,\n\t): { started: false; skipReason: string } | { started: true; record: LaneRecord } {\n\t\treturn this._getWorkerController().start(request);\n\t}\n\n\t/** Run one worker immediately; used by focused integrations and tests. */\n\tasync runWorkerDelegationOnce(\n\t\trequest: WorkerDelegationRequest,\n\t\tonStarted?: (record: LaneRecord) => void,\n\t\texistingRecord?: LaneRecord,\n\t): Promise<WorkerDelegationRunOutcome> {\n\t\treturn this._getWorkerController().runOnce(request, onStarted, existingRecord);\n\t}\n\t/**\n\t * Probe a candidate model against the subagent contracts (research/worker/judge/search/\n\t * tool-call surfaces) via {@link runModelFitnessProbe}. The model must resolve and\n\t * authenticate; every probe call runs as an isolated completion on that model, and probe\n\t * spend is reported through spawned-usage accounting.\n\t */\n\tasync runModelFitness(args: {\n\t\tmodel: string;\n\t\ttrials?: number;\n\t\t/** LLM tool-call id, present only via the model_fitness tool path — see model-fitness.ts. */\n\t\ttoolCallId?: string;\n\t}): Promise<{ started: true; model: string; report: ModelFitnessReport } | { started: false; skipReason: string }> {\n\t\treturn this._fitness.run(args);\n\t}\n\n\t/** Start every capacity-eligible queued worker at the owner session's foreground-idle boundary. */\n\tdrainQueuedWorkerDelegations(): void {\n\t\tif (this.deps.isDelegateToolActive?.()) this._getWorkerController().drain();\n\t}\n\n\t/** Fitness reports persisted for THIS host (measured evidence for architect/profile decisions). */\n\tgetStoredFitnessReports(): StoredFitnessReport[] {\n\t\treturn this._fitness.getStoredReports();\n\t}\n}\n"]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { InteractiveAuthRecoveryHandler } from "@caupulican/pi-ai";
|
|
2
|
+
import { execCommand } from "./exec.ts";
|
|
3
|
+
type ExecuteCommand = typeof execCommand;
|
|
4
|
+
export interface BedrockSsoLoginOptions {
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
execute?: ExecuteCommand;
|
|
7
|
+
isWorker?: () => boolean;
|
|
8
|
+
cwd?: string;
|
|
9
|
+
env?: NodeJS.ProcessEnv;
|
|
10
|
+
}
|
|
11
|
+
/** Run one foreground AWS SSO login per profile; concurrent callers share its terminal result. */
|
|
12
|
+
export declare function loginBedrockSsoProfile(profile: string, options?: BedrockSsoLoginOptions): Promise<void>;
|
|
13
|
+
/** Restore one request-owned Bedrock SSO session after the provider identifies explicit expiry. */
|
|
14
|
+
export declare const recoverBedrockSsoAuthentication: InteractiveAuthRecoveryHandler;
|
|
15
|
+
export {};
|
|
16
|
+
//# sourceMappingURL=bedrock-sso-login.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bedrock-sso-login.d.ts","sourceRoot":"","sources":["../../src/core/bedrock-sso-login.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AAExE,OAAO,EAAmB,WAAW,EAAE,MAAM,WAAW,CAAC;AAQzD,KAAK,cAAc,GAAG,OAAO,WAAW,CAAC;AAEzC,MAAM,WAAW,sBAAsB;IACtC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,OAAO,CAAC;IACzB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;CACxB;AAiED,kGAAkG;AAClG,wBAAsB,sBAAsB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,sBAA2B,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBjH;AAED,mGAAmG;AACnG,eAAO,MAAM,+BAA+B,EAAE,8BAK7C,CAAC","sourcesContent":["import type { InteractiveAuthRecoveryHandler } from \"@caupulican/pi-ai\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { type ExecResult, execCommand } from \"./exec.ts\";\nimport { isWorkerSession } from \"./session-role.ts\";\n\nconst LOGIN_TIMEOUT_MS = 15 * 60_000;\nconst LOGIN_OUTPUT_LIMIT = 32 * 1024;\nconst ERROR_DETAIL_LIMIT = 512;\nconst activeLogins = new Map<string, Promise<void>>();\n\ntype ExecuteCommand = typeof execCommand;\n\nexport interface BedrockSsoLoginOptions {\n\tsignal?: AbortSignal;\n\texecute?: ExecuteCommand;\n\tisWorker?: () => boolean;\n\tcwd?: string;\n\tenv?: NodeJS.ProcessEnv;\n}\n\nfunction validateProfile(profile: string): string {\n\tconst normalized = profile.trim();\n\tif (!normalized) throw new Error(\"AWS profile name is required\");\n\tif (normalized.length > 256 || /[\\u0000-\\u001f\\u007f-\\u009f]/.test(normalized)) {\n\t\tthrow new Error(\"AWS profile name contains unsupported characters\");\n\t}\n\treturn normalized;\n}\n\nfunction compactOutputDetail(result: ExecResult): string | undefined {\n\tconst raw = result.stderr.trim() || result.stdout.trim();\n\tif (!raw) return undefined;\n\tconst withoutAnsi = stripAnsi(raw);\n\tconst lines = withoutAnsi\n\t\t.split(/\\r?\\n/)\n\t\t.map((line) => line.trim())\n\t\t.filter(Boolean);\n\tconst detail = lines.at(-1);\n\tif (!detail) return undefined;\n\treturn detail.length <= ERROR_DETAIL_LIMIT ? detail : `${detail.slice(0, ERROR_DETAIL_LIMIT - 1)}…`;\n}\n\nasync function executeLogin(profile: string, options: BedrockSsoLoginOptions): Promise<void> {\n\tconst execute = options.execute ?? execCommand;\n\tconst result = await execute(\"aws\", [\"sso\", \"login\", \"--profile\", profile], options.cwd ?? process.cwd(), {\n\t\tsignal: options.signal,\n\t\ttimeout: LOGIN_TIMEOUT_MS,\n\t\tenv: options.env ?? process.env,\n\t\tmaxBuffer: LOGIN_OUTPUT_LIMIT,\n\t});\n\tif (result.errorMessage) {\n\t\tconst detail = result.errorMessage.slice(0, ERROR_DETAIL_LIMIT);\n\t\tthrow new Error(`AWS CLI v2 is required for managed SSO login: ${detail}`);\n\t}\n\tif (result.killed) {\n\t\tthrow new Error(options.signal?.aborted ? \"AWS SSO login was cancelled\" : \"AWS SSO login timed out\");\n\t}\n\tif (result.code !== 0) {\n\t\tconst detail = compactOutputDetail(result) ?? `aws exited with code ${result.code}`;\n\t\tthrow new Error(`AWS SSO login failed for profile \"${profile}\": ${detail}`);\n\t}\n}\n\nfunction waitForSharedLogin(login: Promise<void>, signal: AbortSignal | undefined): Promise<void> {\n\tif (!signal) return login;\n\treturn new Promise<void>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst finish = (settle: () => void) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tsettle();\n\t\t};\n\t\tconst onAbort = () => finish(() => reject(new Error(\"AWS SSO login was cancelled\")));\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid login.then(\n\t\t\t() => finish(resolve),\n\t\t\t(error: unknown) => finish(() => reject(error)),\n\t\t);\n\t\tif (signal.aborted) onAbort();\n\t});\n}\n\n/** Run one foreground AWS SSO login per profile; concurrent callers share its terminal result. */\nexport async function loginBedrockSsoProfile(profile: string, options: BedrockSsoLoginOptions = {}): Promise<void> {\n\tconst normalized = validateProfile(profile);\n\tif ((options.isWorker ?? isWorkerSession)()) {\n\t\tthrow new Error(\n\t\t\t`AWS SSO authentication for profile \"${normalized}\" requires a user session; run /login amazon-bedrock in the owning user session.`,\n\t\t);\n\t}\n\tif (options.signal?.aborted) throw new Error(\"AWS SSO login was cancelled\");\n\n\tconst existing = activeLogins.get(normalized);\n\tif (existing) return waitForSharedLogin(existing, options.signal);\n\tconst login = executeLogin(normalized, options);\n\tactiveLogins.set(normalized, login);\n\ttry {\n\t\tawait login;\n\t} finally {\n\t\tif (activeLogins.get(normalized) === login) activeLogins.delete(normalized);\n\t}\n}\n\n/** Restore one request-owned Bedrock SSO session after the provider identifies explicit expiry. */\nexport const recoverBedrockSsoAuthentication: InteractiveAuthRecoveryHandler = async (request) => {\n\tawait loginBedrockSsoProfile(request.profile, {\n\t\t...(request.signal ? { signal: request.signal } : {}),\n\t});\n\treturn true;\n};\n"]}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { stripAnsi } from "../utils/ansi.js";
|
|
2
|
+
import { execCommand } from "./exec.js";
|
|
3
|
+
import { isWorkerSession } from "./session-role.js";
|
|
4
|
+
const LOGIN_TIMEOUT_MS = 15 * 60_000;
|
|
5
|
+
const LOGIN_OUTPUT_LIMIT = 32 * 1024;
|
|
6
|
+
const ERROR_DETAIL_LIMIT = 512;
|
|
7
|
+
const activeLogins = new Map();
|
|
8
|
+
function validateProfile(profile) {
|
|
9
|
+
const normalized = profile.trim();
|
|
10
|
+
if (!normalized)
|
|
11
|
+
throw new Error("AWS profile name is required");
|
|
12
|
+
if (normalized.length > 256 || /[\u0000-\u001f\u007f-\u009f]/.test(normalized)) {
|
|
13
|
+
throw new Error("AWS profile name contains unsupported characters");
|
|
14
|
+
}
|
|
15
|
+
return normalized;
|
|
16
|
+
}
|
|
17
|
+
function compactOutputDetail(result) {
|
|
18
|
+
const raw = result.stderr.trim() || result.stdout.trim();
|
|
19
|
+
if (!raw)
|
|
20
|
+
return undefined;
|
|
21
|
+
const withoutAnsi = stripAnsi(raw);
|
|
22
|
+
const lines = withoutAnsi
|
|
23
|
+
.split(/\r?\n/)
|
|
24
|
+
.map((line) => line.trim())
|
|
25
|
+
.filter(Boolean);
|
|
26
|
+
const detail = lines.at(-1);
|
|
27
|
+
if (!detail)
|
|
28
|
+
return undefined;
|
|
29
|
+
return detail.length <= ERROR_DETAIL_LIMIT ? detail : `${detail.slice(0, ERROR_DETAIL_LIMIT - 1)}…`;
|
|
30
|
+
}
|
|
31
|
+
async function executeLogin(profile, options) {
|
|
32
|
+
const execute = options.execute ?? execCommand;
|
|
33
|
+
const result = await execute("aws", ["sso", "login", "--profile", profile], options.cwd ?? process.cwd(), {
|
|
34
|
+
signal: options.signal,
|
|
35
|
+
timeout: LOGIN_TIMEOUT_MS,
|
|
36
|
+
env: options.env ?? process.env,
|
|
37
|
+
maxBuffer: LOGIN_OUTPUT_LIMIT,
|
|
38
|
+
});
|
|
39
|
+
if (result.errorMessage) {
|
|
40
|
+
const detail = result.errorMessage.slice(0, ERROR_DETAIL_LIMIT);
|
|
41
|
+
throw new Error(`AWS CLI v2 is required for managed SSO login: ${detail}`);
|
|
42
|
+
}
|
|
43
|
+
if (result.killed) {
|
|
44
|
+
throw new Error(options.signal?.aborted ? "AWS SSO login was cancelled" : "AWS SSO login timed out");
|
|
45
|
+
}
|
|
46
|
+
if (result.code !== 0) {
|
|
47
|
+
const detail = compactOutputDetail(result) ?? `aws exited with code ${result.code}`;
|
|
48
|
+
throw new Error(`AWS SSO login failed for profile "${profile}": ${detail}`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function waitForSharedLogin(login, signal) {
|
|
52
|
+
if (!signal)
|
|
53
|
+
return login;
|
|
54
|
+
return new Promise((resolve, reject) => {
|
|
55
|
+
let settled = false;
|
|
56
|
+
const finish = (settle) => {
|
|
57
|
+
if (settled)
|
|
58
|
+
return;
|
|
59
|
+
settled = true;
|
|
60
|
+
signal.removeEventListener("abort", onAbort);
|
|
61
|
+
settle();
|
|
62
|
+
};
|
|
63
|
+
const onAbort = () => finish(() => reject(new Error("AWS SSO login was cancelled")));
|
|
64
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
65
|
+
void login.then(() => finish(resolve), (error) => finish(() => reject(error)));
|
|
66
|
+
if (signal.aborted)
|
|
67
|
+
onAbort();
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/** Run one foreground AWS SSO login per profile; concurrent callers share its terminal result. */
|
|
71
|
+
export async function loginBedrockSsoProfile(profile, options = {}) {
|
|
72
|
+
const normalized = validateProfile(profile);
|
|
73
|
+
if ((options.isWorker ?? isWorkerSession)()) {
|
|
74
|
+
throw new Error(`AWS SSO authentication for profile "${normalized}" requires a user session; run /login amazon-bedrock in the owning user session.`);
|
|
75
|
+
}
|
|
76
|
+
if (options.signal?.aborted)
|
|
77
|
+
throw new Error("AWS SSO login was cancelled");
|
|
78
|
+
const existing = activeLogins.get(normalized);
|
|
79
|
+
if (existing)
|
|
80
|
+
return waitForSharedLogin(existing, options.signal);
|
|
81
|
+
const login = executeLogin(normalized, options);
|
|
82
|
+
activeLogins.set(normalized, login);
|
|
83
|
+
try {
|
|
84
|
+
await login;
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
if (activeLogins.get(normalized) === login)
|
|
88
|
+
activeLogins.delete(normalized);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** Restore one request-owned Bedrock SSO session after the provider identifies explicit expiry. */
|
|
92
|
+
export const recoverBedrockSsoAuthentication = async (request) => {
|
|
93
|
+
await loginBedrockSsoProfile(request.profile, {
|
|
94
|
+
...(request.signal ? { signal: request.signal } : {}),
|
|
95
|
+
});
|
|
96
|
+
return true;
|
|
97
|
+
};
|
|
98
|
+
//# sourceMappingURL=bedrock-sso-login.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bedrock-sso-login.js","sourceRoot":"","sources":["../../src/core/bedrock-sso-login.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAmB,WAAW,EAAE,MAAM,WAAW,CAAC;AACzD,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEpD,MAAM,gBAAgB,GAAG,EAAE,GAAG,MAAM,CAAC;AACrC,MAAM,kBAAkB,GAAG,EAAE,GAAG,IAAI,CAAC;AACrC,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,YAAY,GAAG,IAAI,GAAG,EAA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AK,GAAG,YAAY,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAChD,YAAY,CAAC,GAAG,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IACpC,IAAI,CAAC;QACJ,MAAM,KAAK,CAAC;IACb,CAAC;YAAS,CAAC;QACV,IAAI,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,KAAK;YAAE,YAAY,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAC7E,CAAC;AAAA,CACD;AAED,mGAAmG;AACnG,MAAM,CAAC,MAAM,+BAA+B,GAAmC,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC;IACjG,MAAM,sBAAsB,CAAC,OAAO,CAAC,OAAO,EAAE;QAC7C,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACrD,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AAAA,CACZ,CAAC","sourcesContent":["import type { InteractiveAuthRecoveryHandler } from \"@caupulican/pi-ai\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { type ExecResult, execCommand } from \"./exec.ts\";\nimport { isWorkerSession } from \"./session-role.ts\";\n\nconst LOGIN_TIMEOUT_MS = 15 * 60_000;\nconst LOGIN_OUTPUT_LIMIT = 32 * 1024;\nconst ERROR_DETAIL_LIMIT = 512;\nconst activeLogins = new Map<string, Promise<void>>();\n\ntype ExecuteCommand = typeof execCommand;\n\nexport interface BedrockSsoLoginOptions {\n\tsignal?: AbortSignal;\n\texecute?: ExecuteCommand;\n\tisWorker?: () => boolean;\n\tcwd?: string;\n\tenv?: NodeJS.ProcessEnv;\n}\n\nfunction validateProfile(profile: string): string {\n\tconst normalized = profile.trim();\n\tif (!normalized) throw new Error(\"AWS profile name is required\");\n\tif (normalized.length > 256 || /[\\u0000-\\u001f\\u007f-\\u009f]/.test(normalized)) {\n\t\tthrow new Error(\"AWS profile name contains unsupported characters\");\n\t}\n\treturn normalized;\n}\n\nfunction compactOutputDetail(result: ExecResult): string | undefined {\n\tconst raw = result.stderr.trim() || result.stdout.trim();\n\tif (!raw) return undefined;\n\tconst withoutAnsi = stripAnsi(raw);\n\tconst lines = withoutAnsi\n\t\t.split(/\\r?\\n/)\n\t\t.map((line) => line.trim())\n\t\t.filter(Boolean);\n\tconst detail = lines.at(-1);\n\tif (!detail) return undefined;\n\treturn detail.length <= ERROR_DETAIL_LIMIT ? detail : `${detail.slice(0, ERROR_DETAIL_LIMIT - 1)}…`;\n}\n\nasync function executeLogin(profile: string, options: BedrockSsoLoginOptions): Promise<void> {\n\tconst execute = options.execute ?? execCommand;\n\tconst result = await execute(\"aws\", [\"sso\", \"login\", \"--profile\", profile], options.cwd ?? process.cwd(), {\n\t\tsignal: options.signal,\n\t\ttimeout: LOGIN_TIMEOUT_MS,\n\t\tenv: options.env ?? process.env,\n\t\tmaxBuffer: LOGIN_OUTPUT_LIMIT,\n\t});\n\tif (result.errorMessage) {\n\t\tconst detail = result.errorMessage.slice(0, ERROR_DETAIL_LIMIT);\n\t\tthrow new Error(`AWS CLI v2 is required for managed SSO login: ${detail}`);\n\t}\n\tif (result.killed) {\n\t\tthrow new Error(options.signal?.aborted ? \"AWS SSO login was cancelled\" : \"AWS SSO login timed out\");\n\t}\n\tif (result.code !== 0) {\n\t\tconst detail = compactOutputDetail(result) ?? `aws exited with code ${result.code}`;\n\t\tthrow new Error(`AWS SSO login failed for profile \"${profile}\": ${detail}`);\n\t}\n}\n\nfunction waitForSharedLogin(login: Promise<void>, signal: AbortSignal | undefined): Promise<void> {\n\tif (!signal) return login;\n\treturn new Promise<void>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst finish = (settle: () => void) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tsettle();\n\t\t};\n\t\tconst onAbort = () => finish(() => reject(new Error(\"AWS SSO login was cancelled\")));\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid login.then(\n\t\t\t() => finish(resolve),\n\t\t\t(error: unknown) => finish(() => reject(error)),\n\t\t);\n\t\tif (signal.aborted) onAbort();\n\t});\n}\n\n/** Run one foreground AWS SSO login per profile; concurrent callers share its terminal result. */\nexport async function loginBedrockSsoProfile(profile: string, options: BedrockSsoLoginOptions = {}): Promise<void> {\n\tconst normalized = validateProfile(profile);\n\tif ((options.isWorker ?? isWorkerSession)()) {\n\t\tthrow new Error(\n\t\t\t`AWS SSO authentication for profile \"${normalized}\" requires a user session; run /login amazon-bedrock in the owning user session.`,\n\t\t);\n\t}\n\tif (options.signal?.aborted) throw new Error(\"AWS SSO login was cancelled\");\n\n\tconst existing = activeLogins.get(normalized);\n\tif (existing) return waitForSharedLogin(existing, options.signal);\n\tconst login = executeLogin(normalized, options);\n\tactiveLogins.set(normalized, login);\n\ttry {\n\t\tawait login;\n\t} finally {\n\t\tif (activeLogins.get(normalized) === login) activeLogins.delete(normalized);\n\t}\n}\n\n/** Restore one request-owned Bedrock SSO session after the provider identifies explicit expiry. */\nexport const recoverBedrockSsoAuthentication: InteractiveAuthRecoveryHandler = async (request) => {\n\tawait loginBedrockSsoProfile(request.profile, {\n\t\t...(request.signal ? { signal: request.signal } : {}),\n\t});\n\treturn true;\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-controller.d.ts","sourceRoot":"","sources":["../../src/core/compaction-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,YAAY,EAAe,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAEjG,OAAO,EAGN,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EAQvB,KAAK,cAAc,EAEnB,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EAAE,GAAG,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAGtE,OAAO,KA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,EAAE,SAAS,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAgJhF;IAEK,gBAAgB,CACrB,GAAG,EAAE,MAAM,OAAO,CAAC,gBAAgB,CAAC,EACpC,MAAM,EAAE,WAAW,EACnB,QAAQ,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,gBAAgB,CAAC,CAQ3B;IAED,OAAO,CAAC,wBAAwB;YAQlB,sBAAsB;YAkBtB,WAAW;CAsBzB","sourcesContent":["import type { Agent, AgentMessage, RetryPolicy, ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { classifyFailure, computeRetryDelayMs, DEFAULT_RETRY_POLICY, sleepAbortable } from \"@caupulican/pi-agent-core\";\nimport {\n\ttype CompactionEntry,\n\ttype CompactionPreparation,\n\ttype CompactionResult,\n\ttype CompactionSettings,\n\tcalculateContextTokens,\n\tcompact,\n\tcreateDeterministicCompaction,\n\testimateContextTokens,\n\tgetLatestCompactionEntry,\n\tprepareCompaction,\n\trunCompactionLoop,\n\ttype SessionManager,\n\tshouldCompact,\n} from \"@caupulican/pi-agent-core/node\";\nimport type { Api, AssistantMessage, Model } from \"@caupulican/pi-ai\";\nimport { isContextOverflow } from \"@caupulican/pi-ai\";\nimport { formatNoModelSelectedMessage } from \"./auth-guidance.ts\";\nimport type { ExtensionRunner, SessionBeforeCompactResult } from \"./extensions/index.ts\";\nimport type { FailureCorpusRecorder } from \"./failure-corpus.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\nexport type AutoCompactionReason = \"overflow\" | \"threshold\";\n\ntype CompactionControllerEvent =\n\t| { type: \"compaction_start\"; reason: \"manual\" | AutoCompactionReason }\n\t| {\n\t\t\ttype: \"compaction_end\";\n\t\t\treason: \"manual\" | AutoCompactionReason;\n\t\t\tresult: CompactionResult | undefined;\n\t\t\taborted: boolean;\n\t\t\twillRetry: boolean;\n\t\t\terrorMessage?: string;\n\t\t\tskipReason?: string;\n\t }\n\t| { type: \"warning\"; message: string };\n\nexport interface CompactionControllerDeps {\n\tagent: Agent;\n\tsessionManager: SessionManager;\n\tsettingsManager: SettingsManager;\n\tgetModel(): Model<Api> | undefined;\n\tgetAdaptedSettings(): CompactionSettings;\n\tgetRequestAuth(model: Model<Api>): Promise<{ apiKey?: string; headers?: Record<string, string> }>;\n\tresolveModelAndAuth(\n\t\tcompactionModel: Model<Api>,\n\t\tsessionModel: Model<Api>,\n\t): Promise<{ model: Model<Api>; apiKey?: string; headers?: Record<string, string>; failure?: string }>;\n\tresolveModel(sessionModel: Model<Api>): Model<Api>;\n\tgetSelectionReason(): string | undefined;\n\tresolveThinkingLevel(compactionModel: Model<Api>, sessionModel: Model<Api>): ThinkingLevel | undefined;\n\tdescribeSummarizer(): string;\n\tgetExtensionRunner(): ExtensionRunner;\n\tisRawStream(): boolean;\n\tdisconnectAgent(): void;\n\treconnectAgent(): void;\n\tabortForeground(): Promise<void>;\n\temit(event: CompactionControllerEvent): void;\n\testimateCurrentContextTokens(messages: AgentMessage[]): number;\n\tbuildPreDigest(): ((text: string, signal?: AbortSignal) => Promise<string>) | undefined;\n\trefreshAfterCompaction(): void;\n\tgetFailureCorpus(): FailureCorpusRecorder;\n\tmeasureLiveContextTokens(): number;\n\trunAutoCompaction(reason: AutoCompactionReason, willRetry: boolean): Promise<boolean>;\n\tcompactWithRetry(\n\t\trun: () => Promise<CompactionResult>,\n\t\tsignal: AbortSignal,\n\t\tprovider?: string,\n\t): Promise<CompactionResult>;\n}\n\nexport async function runCompactionWithRetry<T>(options: {\n\trun(): Promise<T>;\n\tsignal: AbortSignal;\n\tprovider?: string;\n\tgetRetrySettings(): { enabled: boolean; maxRetries: number; baseDelayMs: number };\n\trecordFailure(record: Parameters<FailureCorpusRecorder[\"record\"]>[0]): void;\n}): Promise<T> {\n\tconst retrySettings = options.getRetrySettings();\n\tconst maxAttempts = retrySettings.enabled ? Math.max(1, retrySettings.maxRetries + 1) : 1;\n\tconst policy: RetryPolicy = {\n\t\tmaxAttempts,\n\t\tbaseDelayMs: retrySettings.baseDelayMs,\n\t\tmaxDelayMs: DEFAULT_RETRY_POLICY.maxDelayMs,\n\t\tjitterRatio: 0,\n\t};\n\tfor (let attempt = 1; ; attempt++) {\n\t\ttry {\n\t\t\treturn await options.run();\n\t\t} catch (error) {\n\t\t\tif (options.signal.aborted || attempt >= maxAttempts) throw error;\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconst classified = classifyFailure({ message, provider: options.provider });\n\t\t\toptions.recordFailure({ provider: options.provider, message, classified });\n\t\t\tif (!classified.retryable) throw error;\n\t\t\tawait sleepAbortable(\n\t\t\t\tcomputeRetryDelayMs(policy, attempt, { retryAfterMs: classified.retryAfterMs }),\n\t\t\t\toptions.signal,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/** Owns compaction detection, execution, retry, persistence, notification, and cancellation. */\nexport class CompactionController {\n\tprivate manualAbortController: AbortController | undefined;\n\tprivate autoAbortController: AbortController | undefined;\n\tprivate overflowRecoveryAttempted = false;\n\tprivate readonly deps: CompactionControllerDeps;\n\n\tconstructor(deps: CompactionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tisRunning(): boolean {\n\t\treturn this.manualAbortController !== undefined || this.autoAbortController !== undefined;\n\t}\n\n\tresetOverflowRecovery(): void {\n\t\tthis.overflowRecoveryAttempted = false;\n\t}\n\n\tabort(): void {\n\t\tthis.manualAbortController?.abort();\n\t\tthis.autoAbortController?.abort();\n\t}\n\n\tcheckContextWindowUsageWarning(): void {\n\t\tconst model = this.deps.getModel();\n\t\tif (!model) return;\n\t\tconst contextWindow = model.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) return;\n\n\t\tconst systemPromptTokens = Math.ceil((this.deps.agent.state.systemPrompt ?? \"\").length / 4);\n\t\tlet toolsChars = 0;\n\t\tfor (const tool of this.deps.agent.state.tools || []) {\n\t\t\ttoolsChars += tool.name.length;\n\t\t\ttoolsChars += tool.description?.length ?? 0;\n\t\t\tif (tool.parameters) toolsChars += JSON.stringify(tool.parameters).length;\n\t\t}\n\t\tconst baseTokens = systemPromptTokens + Math.ceil(toolsChars / 4);\n\n\t\tif (baseTokens >= contextWindow) {\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `Base configuration (system prompt and active tools) consumes ${baseTokens} tokens, which exceeds the model's context window of ${contextWindow} tokens. The model cannot process any prompts in this state.`,\n\t\t\t});\n\t\t} else if (baseTokens >= contextWindow * 0.7) {\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `Base configuration (system prompt and active tools) consumes ${baseTokens} tokens (${Math.round((baseTokens / contextWindow) * 100)}% of the ${contextWindow} context window). This leaves very little room for conversation history and may cause immediate compaction or context overflow.`,\n\t\t\t});\n\t\t}\n\t}\n\n\tasync maybeCompactBeforeContextTransform(\n\t\tmessages: AgentMessage[],\n\t\tprojectContextGc: (messages: AgentMessage[]) => AgentMessage[],\n\t): Promise<boolean> {\n\t\tconst settings = this.deps.getAdaptedSettings();\n\t\tconst model = this.deps.getModel();\n\t\tconst contextWindow = model?.contextWindow ?? 0;\n\t\tif (!settings.enabled || !model || contextWindow <= 0 || this.isRunning()) return false;\n\n\t\tconst triggerTokens = model.autoCompactionTriggerTokens;\n\t\tconst contextTokens = this.deps.estimateCurrentContextTokens(messages);\n\t\tif (!shouldCompact(contextTokens, contextWindow, settings, triggerTokens)) return false;\n\t\tconst projectedMessages = projectContextGc(messages);\n\t\tconst projectedTokens = this.deps.estimateCurrentContextTokens(projectedMessages);\n\t\tif (!shouldCompact(projectedTokens, contextWindow, settings, triggerTokens)) return false;\n\n\t\tconst latestBefore = getLatestCompactionEntry(this.deps.sessionManager.getBranch())?.id;\n\t\tawait this.deps.runAutoCompaction(\"threshold\", false);\n\t\tconst latestAfter = getLatestCompactionEntry(this.deps.sessionManager.getBranch())?.id;\n\t\treturn Boolean(latestAfter && latestAfter !== latestBefore);\n\t}\n\n\tasync compact(customInstructions?: string): Promise<CompactionResult> {\n\t\tthis.deps.disconnectAgent();\n\t\tawait this.deps.abortForeground();\n\t\tthis.manualAbortController = new AbortController();\n\t\tthis.deps.emit({ type: \"compaction_start\", reason: \"manual\" });\n\n\t\ttry {\n\t\t\tconst sessionModel = this.deps.getModel();\n\t\t\tif (!sessionModel) throw new Error(formatNoModelSelectedMessage());\n\n\t\t\tconst selectedCompactionModel = this.deps.resolveModel(sessionModel);\n\t\t\tif (this.deps.isRawStream()) await this.deps.getRequestAuth(selectedCompactionModel);\n\t\t\tconst selectionReason = this.deps.getSelectionReason() ?? \"unknown\";\n\t\t\tconst settings = this.deps.getAdaptedSettings();\n\t\t\tconst initialBranch = this.deps.sessionManager.getBranch();\n\t\t\tconst initialPreparation = prepareCompaction(initialBranch, settings);\n\t\t\tif (!initialPreparation) {\n\t\t\t\tconst lastEntry = initialBranch[initialBranch.length - 1];\n\t\t\t\tif (lastEntry?.type === \"compaction\") throw new Error(\"Already compacted\");\n\t\t\t\tthrow new Error(\"Nothing to compact (session too small)\");\n\t\t\t}\n\n\t\t\tconst signal = this.manualAbortController.signal;\n\t\t\tconst extension = await this.getExtensionCompaction(\n\t\t\t\tinitialPreparation,\n\t\t\t\tinitialBranch,\n\t\t\t\tcustomInstructions,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (extension.cancelled) throw new Error(\"Compaction cancelled\");\n\t\t\tif (extension.result) {\n\t\t\t\tawait this.applyResult(extension.result, true);\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"manual\",\n\t\t\t\t\tresult: extension.result,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t});\n\t\t\t\treturn extension.result;\n\t\t\t}\n\n\t\t\tlet appliedResult: CompactionResult | undefined;\n\t\t\tconst outcome = await runCompactionLoop({\n\t\t\t\tmeasureLiveTokens: () =>\n\t\t\t\t\tMath.max(this.deps.estimateCurrentContextTokens(this.deps.agent.state.messages), 1),\n\t\t\t\tshouldCompact: () => true,\n\t\t\t\tgetPostApplyMargin: () => 0,\n\t\t\t\tgetBranch: () => this.deps.sessionManager.getBranch(),\n\t\t\t\tgetBaseKeepRecentTokens: () => settings.keepRecentTokens,\n\t\t\t\tresolveModelAndAuth: async (modelTier) => {\n\t\t\t\t\tconst model = modelTier === \"cheap\" ? selectedCompactionModel : sessionModel;\n\t\t\t\t\treturn this.deps.resolveModelAndAuth(model, sessionModel);\n\t\t\t\t},\n\t\t\t\tsummarizeAndVerify: async (params, model, apiKey, headers, branch) => {\n\t\t\t\t\tconst preparation = prepareCompaction(\n\t\t\t\t\t\tbranch,\n\t\t\t\t\t\t{ ...settings, keepRecentTokens: params.keepRecentTokens },\n\t\t\t\t\t\t{ allowTrailingCompactionAsPrevious: true },\n\t\t\t\t\t);\n\t\t\t\t\tif (!preparation) throw new Error(\"Nothing to compact (session too small)\");\n\t\t\t\t\tconst compactionThinkingLevel = this.deps.resolveThinkingLevel(model, sessionModel);\n\t\t\t\t\tconst result = await this.deps.compactWithRetry(\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tcompact(\n\t\t\t\t\t\t\t\tpreparation,\n\t\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\t\tcustomInstructions,\n\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\tcompactionThinkingLevel,\n\t\t\t\t\t\t\t\tthis.deps.agent.streamFn,\n\t\t\t\t\t\t\t\tthis.deps.buildPreDigest(),\n\t\t\t\t\t\t\t\t{ chunked: params.chunked },\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tmodel.provider,\n\t\t\t\t\t);\n\t\t\t\t\treturn { result };\n\t\t\t\t},\n\t\t\t\tbuildDeterministicCheckpoint: () => ({ result: createDeterministicCompaction(initialPreparation) }),\n\t\t\t\tapply: async (result) => {\n\t\t\t\t\tif (signal.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\t\t\tawait this.applyResult(result, false);\n\t\t\t\t\tappliedResult = result;\n\t\t\t\t},\n\t\t\t\tverifyPostApplyEffect: () => false,\n\t\t\t\tonTransition: ({ cycle, cause, detail }) => {\n\t\t\t\t\tthis.deps.emit({\n\t\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\t\tmessage: `manual compaction cycle ${cycle}: ${cause}${detail ? ` (${detail})` : \"\"} — retrying from step 0 (${this.deps.describeSummarizer()})`,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t});\n\n\t\t\tif (outcome.kind === \"failed\") {\n\t\t\t\tif (outcome.reason === \"aborted\") throw new Error(\"Compaction cancelled\");\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`manual compaction failed after retry ladder using ${selectedCompactionModel.provider}/${selectedCompactionModel.id} (${selectionReason}); first failure: ${outcome.reason}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (outcome.kind === \"skip\" || !appliedResult) {\n\t\t\t\tthrow new Error(outcome.kind === \"skip\" ? outcome.reason : \"Compaction failed\");\n\t\t\t}\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"manual\",\n\t\t\t\tresult: appliedResult,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t});\n\t\t\treturn appliedResult;\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconst aborted = message === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"manual\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted,\n\t\t\t\twillRetry: false,\n\t\t\t\terrorMessage: aborted ? undefined : `Compaction failed: ${message}`,\n\t\t\t});\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tthis.manualAbortController = undefined;\n\t\t\tthis.deps.reconnectAgent();\n\t\t}\n\t}\n\n\tasync check(assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<boolean> {\n\t\tconst settings = this.deps.getAdaptedSettings();\n\t\tif (!settings.enabled) return false;\n\t\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return false;\n\n\t\tconst model = this.deps.getModel();\n\t\tconst contextWindow = model?.contextWindow ?? 0;\n\t\tconst sameModel = model && assistantMessage.provider === model.provider && assistantMessage.model === model.id;\n\t\tconst compactionEntry = getLatestCompactionEntry(this.deps.sessionManager.getBranch());\n\t\tconst assistantIsFromBeforeCompaction =\n\t\t\tcompactionEntry !== null && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime();\n\t\tif (assistantIsFromBeforeCompaction) return false;\n\n\t\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\n\t\t\tif (this.overflowRecoveryAttempted) {\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"overflow\",\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t\t});\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tthis.overflowRecoveryAttempted = true;\n\t\t\tconst messages = this.deps.agent.state.messages;\n\t\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\t\tthis.deps.agent.state.messages = messages.slice(0, -1);\n\t\t\t}\n\t\t\treturn this.deps.runAutoCompaction(\"overflow\", true);\n\t\t}\n\n\t\tlet contextTokens: number;\n\t\tif (assistantMessage.stopReason === \"error\") {\n\t\t\tconst messages = this.deps.agent.state.messages;\n\t\t\tconst estimate = estimateContextTokens(messages);\n\t\t\tif (estimate.lastUsageIndex === null) return false;\n\t\t\tconst usageMessage = messages[estimate.lastUsageIndex];\n\t\t\tif (\n\t\t\t\tcompactionEntry &&\n\t\t\t\tusageMessage.role === \"assistant\" &&\n\t\t\t\tusageMessage.timestamp <= new Date(compactionEntry.timestamp).getTime()\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tcontextTokens = estimate.tokens;\n\t\t} else {\n\t\t\tcontextTokens = calculateContextTokens(assistantMessage.usage);\n\t\t\tconst estimate = estimateContextTokens(this.deps.agent.state.messages);\n\t\t\tif (estimate.lastUsageIndex !== null) {\n\t\t\t\tconst usageMessage = this.deps.agent.state.messages[estimate.lastUsageIndex];\n\t\t\t\tconst usageIsPostCompaction = !(\n\t\t\t\t\tcompactionEntry &&\n\t\t\t\t\tusageMessage.role === \"assistant\" &&\n\t\t\t\t\tusageMessage.timestamp <= new Date(compactionEntry.timestamp).getTime()\n\t\t\t\t);\n\t\t\t\tif (usageIsPostCompaction) contextTokens = Math.max(contextTokens, estimate.tokens);\n\t\t\t}\n\t\t}\n\t\tif (shouldCompact(contextTokens, contextWindow, settings, model?.autoCompactionTriggerTokens)) {\n\t\t\treturn this.deps.runAutoCompaction(\"threshold\", false);\n\t\t}\n\t\treturn false;\n\t}\n\n\tmeasureLiveContextTokens(): number {\n\t\tconst estimatedTokens = this.deps.estimateCurrentContextTokens(this.deps.agent.state.messages);\n\t\tconst assistantMessage = this.findLastAssistantMessage();\n\t\tif (!assistantMessage || assistantMessage.stopReason === \"error\" || assistantMessage.stopReason === \"aborted\") {\n\t\t\treturn estimatedTokens;\n\t\t}\n\t\tconst compactionEntry = getLatestCompactionEntry(this.deps.sessionManager.getBranch());\n\t\tif (compactionEntry && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime()) {\n\t\t\treturn estimatedTokens;\n\t\t}\n\t\treturn Math.max(calculateContextTokens(assistantMessage.usage), estimatedTokens);\n\t}\n\n\tasync runAuto(reason: AutoCompactionReason, willRetry: boolean): Promise<boolean> {\n\t\tconst settings = this.deps.getAdaptedSettings();\n\t\tconst model = this.deps.getModel();\n\t\tthis.deps.emit({ type: \"compaction_start\", reason });\n\t\tconst hadQueuedMessages = this.deps.agent.hasQueuedMessages();\n\t\tthis.autoAbortController = new AbortController();\n\t\tconst signal = this.autoAbortController.signal;\n\t\tlet fromExtension = false;\n\t\tlet lastCompaction: CompactionResult | undefined;\n\t\tlet extensionCancelled = false;\n\t\ttry {\n\t\t\tif (!model) {\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason,\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\tskipReason: \"no model selected\",\n\t\t\t\t});\n\t\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t\t}\n\n\t\t\tconst contextWindow = model.contextWindow;\n\t\t\tconst margin = Math.max(0, Math.floor(0.01 * contextWindow));\n\t\t\tconst outcome = await runCompactionLoop({\n\t\t\t\tgetBranch: () => this.deps.sessionManager.getBranch(),\n\t\t\t\tmeasureLiveTokens: () => this.deps.measureLiveContextTokens(),\n\t\t\t\tshouldCompact:\n\t\t\t\t\treason === \"overflow\"\n\t\t\t\t\t\t? () => true\n\t\t\t\t\t\t: (tokens) => shouldCompact(tokens, contextWindow, settings, model.autoCompactionTriggerTokens),\n\t\t\t\tgetPostApplyMargin: () => margin,\n\t\t\t\tgetBaseKeepRecentTokens: () => settings.keepRecentTokens,\n\t\t\t\tresolveModelAndAuth: async (modelTier) =>\n\t\t\t\t\tthis.deps.resolveModelAndAuth(modelTier === \"session\" ? model : this.deps.resolveModel(model), model),\n\t\t\t\tsummarizeAndVerify: async (params, compactModel, apiKey, headers, branchEntries) => {\n\t\t\t\t\tfromExtension = false;\n\t\t\t\t\tconst preparation = prepareCompaction(branchEntries, {\n\t\t\t\t\t\t...settings,\n\t\t\t\t\t\tkeepRecentTokens: params.keepRecentTokens,\n\t\t\t\t\t});\n\t\t\t\t\tif (!preparation) throw new Error(\"already compacted\");\n\t\t\t\t\tconst compactionThinkingLevel = this.deps.resolveThinkingLevel(compactModel, model);\n\t\t\t\t\tconst extension = await this.getExtensionCompaction(preparation, branchEntries, undefined, signal);\n\t\t\t\t\tif (extension.cancelled) {\n\t\t\t\t\t\textensionCancelled = true;\n\t\t\t\t\t\tthrow new Error(\"auto-compaction-cancelled\");\n\t\t\t\t\t}\n\t\t\t\t\tif (extension.result) {\n\t\t\t\t\t\tfromExtension = true;\n\t\t\t\t\t\treturn { result: extension.result };\n\t\t\t\t\t}\n\t\t\t\t\tconst result = await this.deps.compactWithRetry(\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tcompact(\n\t\t\t\t\t\t\t\tpreparation,\n\t\t\t\t\t\t\t\tcompactModel,\n\t\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\tcompactionThinkingLevel,\n\t\t\t\t\t\t\t\tthis.deps.agent.streamFn,\n\t\t\t\t\t\t\t\tthis.deps.buildPreDigest(),\n\t\t\t\t\t\t\t\t{ chunked: params.chunked },\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tcompactModel.provider,\n\t\t\t\t\t);\n\t\t\t\t\treturn { result };\n\t\t\t\t},\n\t\t\t\tbuildDeterministicCheckpoint: () => {\n\t\t\t\t\tconst preparation = prepareCompaction(this.deps.sessionManager.getBranch(), settings);\n\t\t\t\t\tif (!preparation) throw new Error(\"already compacted\");\n\t\t\t\t\tfromExtension = false;\n\t\t\t\t\treturn { result: createDeterministicCompaction(preparation) };\n\t\t\t\t},\n\t\t\t\tapply: async (result) => {\n\t\t\t\t\tlastCompaction = result;\n\t\t\t\t\tawait this.applyResult(result, fromExtension);\n\t\t\t\t},\n\t\t\t\tverifyPostApplyEffect: reason === \"overflow\" ? () => false : undefined,\n\t\t\t\tonTransition: ({ cycle, cause, detail }) => {\n\t\t\t\t\tthis.deps.emit({\n\t\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\t\tmessage: `auto-compaction cycle ${cycle}: ${cause}${detail ? ` (${detail})` : \"\"} — retrying from step 0 (${this.deps.describeSummarizer()})`,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t});\n\n\t\t\tif (outcome.kind === \"skip\") {\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason,\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\tskipReason: outcome.reason,\n\t\t\t\t});\n\t\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t\t}\n\t\t\tif (outcome.kind === \"failed\") {\n\t\t\t\tif (outcome.reason === \"aborted\") {\n\t\t\t\t\tthis.deps.emit({ type: \"compaction_end\", reason, result: undefined, aborted: true, willRetry: false });\n\t\t\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t\t\t}\n\t\t\t\tthrow new Error(outcome.reason);\n\t\t\t}\n\t\t\tif (extensionCancelled || signal.aborted) {\n\t\t\t\tthis.deps.emit({ type: \"compaction_end\", reason, result: undefined, aborted: true, willRetry: false });\n\t\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t\t}\n\n\t\t\tconst result = outcome.kind === \"success\" ? outcome.result : lastCompaction;\n\t\t\tif (!result) throw new Error(\"Auto-compaction succeeded without a result\");\n\t\t\tthis.deps.emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\t\tif (willRetry) {\n\t\t\t\tconst messages = this.deps.agent.state.messages;\n\t\t\t\tconst lastMessage = messages[messages.length - 1];\n\t\t\t\tif (lastMessage?.role === \"assistant\" && lastMessage.stopReason === \"error\") {\n\t\t\t\t\tthis.deps.agent.state.messages = messages.slice(0, -1);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\terrorMessage:\n\t\t\t\t\treason === \"overflow\"\n\t\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t\t});\n\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t} finally {\n\t\t\tthis.autoAbortController = undefined;\n\t\t}\n\t}\n\n\tasync compactWithRetry(\n\t\trun: () => Promise<CompactionResult>,\n\t\tsignal: AbortSignal,\n\t\tprovider?: string,\n\t): Promise<CompactionResult> {\n\t\treturn runCompactionWithRetry({\n\t\t\trun,\n\t\t\tsignal,\n\t\t\tprovider,\n\t\t\tgetRetrySettings: () => this.deps.settingsManager.getRetrySettings(),\n\t\t\trecordFailure: (record) => this.deps.getFailureCorpus().record(record),\n\t\t});\n\t}\n\n\tprivate findLastAssistantMessage(): AssistantMessage | undefined {\n\t\tfor (let index = this.deps.agent.state.messages.length - 1; index >= 0; index--) {\n\t\t\tconst message = this.deps.agent.state.messages[index];\n\t\t\tif (message.role === \"assistant\") return message;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate async getExtensionCompaction(\n\t\tpreparation: CompactionPreparation,\n\t\tbranchEntries: ReturnType<SessionManager[\"getBranch\"]>,\n\t\tcustomInstructions: string | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<{ cancelled: boolean; result?: CompactionResult }> {\n\t\tconst extensionRunner = this.deps.getExtensionRunner();\n\t\tif (!extensionRunner.hasHandlers(\"session_before_compact\")) return { cancelled: false };\n\t\tconst extensionResult = (await extensionRunner.emit({\n\t\t\ttype: \"session_before_compact\",\n\t\t\tpreparation,\n\t\t\tbranchEntries,\n\t\t\tcustomInstructions,\n\t\t\tsignal,\n\t\t})) as SessionBeforeCompactResult | undefined;\n\t\treturn { cancelled: extensionResult?.cancel === true, result: extensionResult?.compaction };\n\t}\n\n\tprivate async applyResult(result: CompactionResult, fromExtension: boolean): Promise<void> {\n\t\tthis.deps.sessionManager.appendCompaction(\n\t\t\tresult.summary,\n\t\t\tresult.firstKeptEntryId,\n\t\t\tresult.tokensBefore,\n\t\t\tresult.details,\n\t\t\tfromExtension,\n\t\t);\n\t\tthis.deps.refreshAfterCompaction();\n\t\tconst savedEntry = this.deps.sessionManager\n\t\t\t.getEntries()\n\t\t\t.find((entry) => entry.type === \"compaction\" && entry.summary === result.summary) as\n\t\t\t| CompactionEntry\n\t\t\t| undefined;\n\t\tif (savedEntry) {\n\t\t\tawait this.deps.getExtensionRunner().emit({\n\t\t\t\ttype: \"session_compact\",\n\t\t\t\tcompactionEntry: savedEntry,\n\t\t\t\tfromExtension,\n\t\t\t});\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compaction-controller.d.ts","sourceRoot":"","sources":["../../src/core/compaction-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,YAAY,EAAe,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAEjG,OAAO,EAGN,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EAQvB,KAAK,cAAc,EAEnB,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EAAE,GAAG,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAGtE,OAAO,KAAK,EAAE,eAAe,EAA8B,MAAM,uBAAuB,CAAC;AACzF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE7D,MAAM,MAAM,oBAAoB,GAAG,UAAU,GAAG,WAAW,CAAC;AAE5D,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IAED,OAAO,CAAC,wBAAwB;YAQlB,sBAAsB;YAkBtB,WAAW;CAuBzB","sourcesContent":["import type { Agent, AgentMessage, RetryPolicy, ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { classifyFailure, computeRetryDelayMs, DEFAULT_RETRY_POLICY, sleepAbortable } from \"@caupulican/pi-agent-core\";\nimport {\n\ttype CompactionEntry,\n\ttype CompactionPreparation,\n\ttype CompactionResult,\n\ttype CompactionSettings,\n\tcalculateContextTokens,\n\tcompact,\n\tcreateDeterministicCompaction,\n\testimateContextTokens,\n\tgetLatestCompactionEntry,\n\tprepareCompaction,\n\trunCompactionLoop,\n\ttype SessionManager,\n\tshouldCompact,\n} from \"@caupulican/pi-agent-core/node\";\nimport type { Api, AssistantMessage, Model } from \"@caupulican/pi-ai\";\nimport { isContextOverflow } from \"@caupulican/pi-ai\";\nimport { formatNoModelSelectedMessage } from \"./auth-guidance.ts\";\nimport type { ExtensionRunner, SessionBeforeCompactResult } from \"./extensions/index.ts\";\nimport type { FailureCorpusRecorder } from \"./failure-corpus.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\nexport type AutoCompactionReason = \"overflow\" | \"threshold\";\n\ntype CompactionControllerEvent =\n\t| { type: \"compaction_start\"; reason: \"manual\" | AutoCompactionReason }\n\t| {\n\t\t\ttype: \"compaction_end\";\n\t\t\treason: \"manual\" | AutoCompactionReason;\n\t\t\tresult: CompactionResult | undefined;\n\t\t\taborted: boolean;\n\t\t\twillRetry: boolean;\n\t\t\terrorMessage?: string;\n\t\t\tskipReason?: string;\n\t }\n\t| { type: \"warning\"; message: string };\n\nexport interface CompactionControllerDeps {\n\tagent: Agent;\n\tsessionManager: SessionManager;\n\tsettingsManager: SettingsManager;\n\tgetModel(): Model<Api> | undefined;\n\tgetAdaptedSettings(): CompactionSettings;\n\tgetRequestAuth(model: Model<Api>): Promise<{ apiKey?: string; headers?: Record<string, string> }>;\n\tresolveModelAndAuth(\n\t\tcompactionModel: Model<Api>,\n\t\tsessionModel: Model<Api>,\n\t): Promise<{ model: Model<Api>; apiKey?: string; headers?: Record<string, string>; failure?: string }>;\n\tresolveModel(sessionModel: Model<Api>): Model<Api>;\n\tgetSelectionReason(): string | undefined;\n\tresolveThinkingLevel(compactionModel: Model<Api>, sessionModel: Model<Api>): ThinkingLevel | undefined;\n\tdescribeSummarizer(): string;\n\tgetExtensionRunner(): ExtensionRunner;\n\tisRawStream(): boolean;\n\tdisconnectAgent(): void;\n\treconnectAgent(): void;\n\tabortForeground(): Promise<void>;\n\temit(event: CompactionControllerEvent): void;\n\testimateCurrentContextTokens(messages: AgentMessage[]): number;\n\tbuildPreDigest(): ((text: string, signal?: AbortSignal) => Promise<string>) | undefined;\n\trefreshAfterCompaction(): void;\n\tgetFailureCorpus(): FailureCorpusRecorder;\n\tmeasureLiveContextTokens(): number;\n\trunAutoCompaction(reason: AutoCompactionReason, willRetry: boolean): Promise<boolean>;\n\tcompactWithRetry(\n\t\trun: () => Promise<CompactionResult>,\n\t\tsignal: AbortSignal,\n\t\tprovider?: string,\n\t): Promise<CompactionResult>;\n}\n\nexport async function runCompactionWithRetry<T>(options: {\n\trun(): Promise<T>;\n\tsignal: AbortSignal;\n\tprovider?: string;\n\tgetRetrySettings(): { enabled: boolean; maxRetries: number; baseDelayMs: number };\n\trecordFailure(record: Parameters<FailureCorpusRecorder[\"record\"]>[0]): void;\n}): Promise<T> {\n\tconst retrySettings = options.getRetrySettings();\n\tconst maxAttempts = retrySettings.enabled ? Math.max(1, retrySettings.maxRetries + 1) : 1;\n\tconst policy: RetryPolicy = {\n\t\tmaxAttempts,\n\t\tbaseDelayMs: retrySettings.baseDelayMs,\n\t\tmaxDelayMs: DEFAULT_RETRY_POLICY.maxDelayMs,\n\t\tjitterRatio: 0,\n\t};\n\tfor (let attempt = 1; ; attempt++) {\n\t\ttry {\n\t\t\treturn await options.run();\n\t\t} catch (error) {\n\t\t\tif (options.signal.aborted || attempt >= maxAttempts) throw error;\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconst classified = classifyFailure({ message, provider: options.provider });\n\t\t\toptions.recordFailure({ provider: options.provider, message, classified });\n\t\t\tif (!classified.retryable) throw error;\n\t\t\tawait sleepAbortable(\n\t\t\t\tcomputeRetryDelayMs(policy, attempt, { retryAfterMs: classified.retryAfterMs }),\n\t\t\t\toptions.signal,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/** Owns compaction detection, execution, retry, persistence, notification, and cancellation. */\nexport class CompactionController {\n\tprivate manualAbortController: AbortController | undefined;\n\tprivate autoAbortController: AbortController | undefined;\n\tprivate overflowRecoveryAttempted = false;\n\tprivate readonly deps: CompactionControllerDeps;\n\n\tconstructor(deps: CompactionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tisRunning(): boolean {\n\t\treturn this.manualAbortController !== undefined || this.autoAbortController !== undefined;\n\t}\n\n\tresetOverflowRecovery(): void {\n\t\tthis.overflowRecoveryAttempted = false;\n\t}\n\n\tabort(): void {\n\t\tthis.manualAbortController?.abort();\n\t\tthis.autoAbortController?.abort();\n\t}\n\n\tcheckContextWindowUsageWarning(): void {\n\t\tconst model = this.deps.getModel();\n\t\tif (!model) return;\n\t\tconst contextWindow = model.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) return;\n\n\t\tconst systemPromptTokens = Math.ceil((this.deps.agent.state.systemPrompt ?? \"\").length / 4);\n\t\tlet toolsChars = 0;\n\t\tfor (const tool of this.deps.agent.state.tools || []) {\n\t\t\ttoolsChars += tool.name.length;\n\t\t\ttoolsChars += tool.description?.length ?? 0;\n\t\t\tif (tool.parameters) toolsChars += JSON.stringify(tool.parameters).length;\n\t\t}\n\t\tconst baseTokens = systemPromptTokens + Math.ceil(toolsChars / 4);\n\n\t\tif (baseTokens >= contextWindow) {\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `Base configuration (system prompt and active tools) consumes ${baseTokens} tokens, which exceeds the model's context window of ${contextWindow} tokens. The model cannot process any prompts in this state.`,\n\t\t\t});\n\t\t} else if (baseTokens >= contextWindow * 0.7) {\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `Base configuration (system prompt and active tools) consumes ${baseTokens} tokens (${Math.round((baseTokens / contextWindow) * 100)}% of the ${contextWindow} context window). This leaves very little room for conversation history and may cause immediate compaction or context overflow.`,\n\t\t\t});\n\t\t}\n\t}\n\n\tasync maybeCompactBeforeContextTransform(\n\t\tmessages: AgentMessage[],\n\t\tprojectContextGc: (messages: AgentMessage[]) => AgentMessage[],\n\t): Promise<boolean> {\n\t\tconst settings = this.deps.getAdaptedSettings();\n\t\tconst model = this.deps.getModel();\n\t\tconst contextWindow = model?.contextWindow ?? 0;\n\t\tif (!settings.enabled || !model || contextWindow <= 0 || this.isRunning()) return false;\n\n\t\tconst triggerTokens = model.autoCompactionTriggerTokens;\n\t\tconst contextTokens = this.deps.estimateCurrentContextTokens(messages);\n\t\tif (!shouldCompact(contextTokens, contextWindow, settings, triggerTokens)) return false;\n\t\tconst projectedMessages = projectContextGc(messages);\n\t\tconst projectedTokens = this.deps.estimateCurrentContextTokens(projectedMessages);\n\t\tif (!shouldCompact(projectedTokens, contextWindow, settings, triggerTokens)) return false;\n\n\t\tconst latestBefore = getLatestCompactionEntry(this.deps.sessionManager.getBranch())?.id;\n\t\tawait this.deps.runAutoCompaction(\"threshold\", false);\n\t\tconst latestAfter = getLatestCompactionEntry(this.deps.sessionManager.getBranch())?.id;\n\t\treturn Boolean(latestAfter && latestAfter !== latestBefore);\n\t}\n\n\tasync compact(customInstructions?: string): Promise<CompactionResult> {\n\t\tthis.deps.disconnectAgent();\n\t\tawait this.deps.abortForeground();\n\t\tthis.manualAbortController = new AbortController();\n\t\tthis.deps.emit({ type: \"compaction_start\", reason: \"manual\" });\n\n\t\ttry {\n\t\t\tconst sessionModel = this.deps.getModel();\n\t\t\tif (!sessionModel) throw new Error(formatNoModelSelectedMessage());\n\n\t\t\tconst selectedCompactionModel = this.deps.resolveModel(sessionModel);\n\t\t\tif (this.deps.isRawStream()) await this.deps.getRequestAuth(selectedCompactionModel);\n\t\t\tconst selectionReason = this.deps.getSelectionReason() ?? \"unknown\";\n\t\t\tconst settings = this.deps.getAdaptedSettings();\n\t\t\tconst initialBranch = this.deps.sessionManager.getBranch();\n\t\t\tconst initialPreparation = prepareCompaction(initialBranch, settings);\n\t\t\tif (!initialPreparation) {\n\t\t\t\tconst lastEntry = initialBranch[initialBranch.length - 1];\n\t\t\t\tif (lastEntry?.type === \"compaction\") throw new Error(\"Already compacted\");\n\t\t\t\tthrow new Error(\"Nothing to compact (session too small)\");\n\t\t\t}\n\n\t\t\tconst signal = this.manualAbortController.signal;\n\t\t\tconst extension = await this.getExtensionCompaction(\n\t\t\t\tinitialPreparation,\n\t\t\t\tinitialBranch,\n\t\t\t\tcustomInstructions,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (extension.cancelled) throw new Error(\"Compaction cancelled\");\n\t\t\tif (extension.result) {\n\t\t\t\tawait this.applyResult(extension.result, true);\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"manual\",\n\t\t\t\t\tresult: extension.result,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t});\n\t\t\t\treturn extension.result;\n\t\t\t}\n\n\t\t\tlet appliedResult: CompactionResult | undefined;\n\t\t\tconst outcome = await runCompactionLoop({\n\t\t\t\tmeasureLiveTokens: () =>\n\t\t\t\t\tMath.max(this.deps.estimateCurrentContextTokens(this.deps.agent.state.messages), 1),\n\t\t\t\tshouldCompact: () => true,\n\t\t\t\tgetPostApplyMargin: () => 0,\n\t\t\t\tgetBranch: () => this.deps.sessionManager.getBranch(),\n\t\t\t\tgetBaseKeepRecentTokens: () => settings.keepRecentTokens,\n\t\t\t\tresolveModelAndAuth: async (modelTier) => {\n\t\t\t\t\tconst model = modelTier === \"cheap\" ? selectedCompactionModel : sessionModel;\n\t\t\t\t\treturn this.deps.resolveModelAndAuth(model, sessionModel);\n\t\t\t\t},\n\t\t\t\tsummarizeAndVerify: async (params, model, apiKey, headers, branch) => {\n\t\t\t\t\tconst preparation = prepareCompaction(\n\t\t\t\t\t\tbranch,\n\t\t\t\t\t\t{ ...settings, keepRecentTokens: params.keepRecentTokens },\n\t\t\t\t\t\t{ allowTrailingCompactionAsPrevious: true },\n\t\t\t\t\t);\n\t\t\t\t\tif (!preparation) throw new Error(\"Nothing to compact (session too small)\");\n\t\t\t\t\tconst compactionThinkingLevel = this.deps.resolveThinkingLevel(model, sessionModel);\n\t\t\t\t\tconst result = await this.deps.compactWithRetry(\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tcompact(\n\t\t\t\t\t\t\t\tpreparation,\n\t\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\t\tcustomInstructions,\n\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\tcompactionThinkingLevel,\n\t\t\t\t\t\t\t\tthis.deps.agent.streamFn,\n\t\t\t\t\t\t\t\tthis.deps.buildPreDigest(),\n\t\t\t\t\t\t\t\t{ chunked: params.chunked },\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tmodel.provider,\n\t\t\t\t\t);\n\t\t\t\t\treturn { result };\n\t\t\t\t},\n\t\t\t\tbuildDeterministicCheckpoint: () => ({ result: createDeterministicCompaction(initialPreparation) }),\n\t\t\t\tapply: async (result) => {\n\t\t\t\t\tif (signal.aborted) throw new Error(\"Compaction cancelled\");\n\t\t\t\t\tawait this.applyResult(result, false);\n\t\t\t\t\tappliedResult = result;\n\t\t\t\t},\n\t\t\t\tverifyPostApplyEffect: () => false,\n\t\t\t\tonTransition: ({ cycle, cause, detail }) => {\n\t\t\t\t\tthis.deps.emit({\n\t\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\t\tmessage: `manual compaction cycle ${cycle}: ${cause}${detail ? ` (${detail})` : \"\"} — retrying from step 0 (${this.deps.describeSummarizer()})`,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t});\n\n\t\t\tif (outcome.kind === \"failed\") {\n\t\t\t\tif (outcome.reason === \"aborted\") throw new Error(\"Compaction cancelled\");\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`manual compaction failed after retry ladder using ${selectedCompactionModel.provider}/${selectedCompactionModel.id} (${selectionReason}); first failure: ${outcome.reason}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (outcome.kind === \"skip\" || !appliedResult) {\n\t\t\t\tthrow new Error(outcome.kind === \"skip\" ? outcome.reason : \"Compaction failed\");\n\t\t\t}\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"manual\",\n\t\t\t\tresult: appliedResult,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t});\n\t\t\treturn appliedResult;\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconst aborted = message === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"manual\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted,\n\t\t\t\twillRetry: false,\n\t\t\t\terrorMessage: aborted ? undefined : `Compaction failed: ${message}`,\n\t\t\t});\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tthis.manualAbortController = undefined;\n\t\t\tthis.deps.reconnectAgent();\n\t\t}\n\t}\n\n\tasync check(assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<boolean> {\n\t\tconst settings = this.deps.getAdaptedSettings();\n\t\tif (!settings.enabled) return false;\n\t\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return false;\n\n\t\tconst model = this.deps.getModel();\n\t\tconst contextWindow = model?.contextWindow ?? 0;\n\t\tconst sameModel = model && assistantMessage.provider === model.provider && assistantMessage.model === model.id;\n\t\tconst compactionEntry = getLatestCompactionEntry(this.deps.sessionManager.getBranch());\n\t\tconst assistantIsFromBeforeCompaction =\n\t\t\tcompactionEntry !== null && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime();\n\t\tif (assistantIsFromBeforeCompaction) return false;\n\n\t\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\n\t\t\tif (this.overflowRecoveryAttempted) {\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"overflow\",\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t\t});\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tthis.overflowRecoveryAttempted = true;\n\t\t\tconst messages = this.deps.agent.state.messages;\n\t\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\t\tthis.deps.agent.state.messages = messages.slice(0, -1);\n\t\t\t}\n\t\t\treturn this.deps.runAutoCompaction(\"overflow\", true);\n\t\t}\n\n\t\tlet contextTokens: number;\n\t\tif (assistantMessage.stopReason === \"error\") {\n\t\t\tconst messages = this.deps.agent.state.messages;\n\t\t\tconst estimate = estimateContextTokens(messages);\n\t\t\tif (estimate.lastUsageIndex === null) return false;\n\t\t\tconst usageMessage = messages[estimate.lastUsageIndex];\n\t\t\tif (\n\t\t\t\tcompactionEntry &&\n\t\t\t\tusageMessage.role === \"assistant\" &&\n\t\t\t\tusageMessage.timestamp <= new Date(compactionEntry.timestamp).getTime()\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tcontextTokens = estimate.tokens;\n\t\t} else {\n\t\t\tcontextTokens = calculateContextTokens(assistantMessage.usage);\n\t\t\tconst estimate = estimateContextTokens(this.deps.agent.state.messages);\n\t\t\tif (estimate.lastUsageIndex !== null) {\n\t\t\t\tconst usageMessage = this.deps.agent.state.messages[estimate.lastUsageIndex];\n\t\t\t\tconst usageIsPostCompaction = !(\n\t\t\t\t\tcompactionEntry &&\n\t\t\t\t\tusageMessage.role === \"assistant\" &&\n\t\t\t\t\tusageMessage.timestamp <= new Date(compactionEntry.timestamp).getTime()\n\t\t\t\t);\n\t\t\t\tif (usageIsPostCompaction) contextTokens = Math.max(contextTokens, estimate.tokens);\n\t\t\t}\n\t\t}\n\t\tif (shouldCompact(contextTokens, contextWindow, settings, model?.autoCompactionTriggerTokens)) {\n\t\t\treturn this.deps.runAutoCompaction(\"threshold\", false);\n\t\t}\n\t\treturn false;\n\t}\n\n\tmeasureLiveContextTokens(): number {\n\t\tconst estimatedTokens = this.deps.estimateCurrentContextTokens(this.deps.agent.state.messages);\n\t\tconst assistantMessage = this.findLastAssistantMessage();\n\t\tif (!assistantMessage || assistantMessage.stopReason === \"error\" || assistantMessage.stopReason === \"aborted\") {\n\t\t\treturn estimatedTokens;\n\t\t}\n\t\tconst compactionEntry = getLatestCompactionEntry(this.deps.sessionManager.getBranch());\n\t\tif (compactionEntry && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime()) {\n\t\t\treturn estimatedTokens;\n\t\t}\n\t\treturn Math.max(calculateContextTokens(assistantMessage.usage), estimatedTokens);\n\t}\n\n\tasync runAuto(reason: AutoCompactionReason, willRetry: boolean): Promise<boolean> {\n\t\tconst settings = this.deps.getAdaptedSettings();\n\t\tconst model = this.deps.getModel();\n\t\tthis.deps.emit({ type: \"compaction_start\", reason });\n\t\tconst hadQueuedMessages = this.deps.agent.hasQueuedMessages();\n\t\tthis.autoAbortController = new AbortController();\n\t\tconst signal = this.autoAbortController.signal;\n\t\tlet fromExtension = false;\n\t\tlet lastCompaction: CompactionResult | undefined;\n\t\tlet extensionCancelled = false;\n\t\ttry {\n\t\t\tif (!model) {\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason,\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\tskipReason: \"no model selected\",\n\t\t\t\t});\n\t\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t\t}\n\n\t\t\tconst contextWindow = model.contextWindow;\n\t\t\tconst margin = Math.max(0, Math.floor(0.01 * contextWindow));\n\t\t\tconst outcome = await runCompactionLoop({\n\t\t\t\tgetBranch: () => this.deps.sessionManager.getBranch(),\n\t\t\t\tmeasureLiveTokens: () => this.deps.measureLiveContextTokens(),\n\t\t\t\tshouldCompact:\n\t\t\t\t\treason === \"overflow\"\n\t\t\t\t\t\t? () => true\n\t\t\t\t\t\t: (tokens) => shouldCompact(tokens, contextWindow, settings, model.autoCompactionTriggerTokens),\n\t\t\t\tgetPostApplyMargin: () => margin,\n\t\t\t\tgetBaseKeepRecentTokens: () => settings.keepRecentTokens,\n\t\t\t\tresolveModelAndAuth: async (modelTier) =>\n\t\t\t\t\tthis.deps.resolveModelAndAuth(modelTier === \"session\" ? model : this.deps.resolveModel(model), model),\n\t\t\t\tsummarizeAndVerify: async (params, compactModel, apiKey, headers, branchEntries) => {\n\t\t\t\t\tfromExtension = false;\n\t\t\t\t\tconst preparation = prepareCompaction(branchEntries, {\n\t\t\t\t\t\t...settings,\n\t\t\t\t\t\tkeepRecentTokens: params.keepRecentTokens,\n\t\t\t\t\t});\n\t\t\t\t\tif (!preparation) throw new Error(\"already compacted\");\n\t\t\t\t\tconst compactionThinkingLevel = this.deps.resolveThinkingLevel(compactModel, model);\n\t\t\t\t\tconst extension = await this.getExtensionCompaction(preparation, branchEntries, undefined, signal);\n\t\t\t\t\tif (extension.cancelled) {\n\t\t\t\t\t\textensionCancelled = true;\n\t\t\t\t\t\tthrow new Error(\"auto-compaction-cancelled\");\n\t\t\t\t\t}\n\t\t\t\t\tif (extension.result) {\n\t\t\t\t\t\tfromExtension = true;\n\t\t\t\t\t\treturn { result: extension.result };\n\t\t\t\t\t}\n\t\t\t\t\tconst result = await this.deps.compactWithRetry(\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tcompact(\n\t\t\t\t\t\t\t\tpreparation,\n\t\t\t\t\t\t\t\tcompactModel,\n\t\t\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\tcompactionThinkingLevel,\n\t\t\t\t\t\t\t\tthis.deps.agent.streamFn,\n\t\t\t\t\t\t\t\tthis.deps.buildPreDigest(),\n\t\t\t\t\t\t\t\t{ chunked: params.chunked },\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tcompactModel.provider,\n\t\t\t\t\t);\n\t\t\t\t\treturn { result };\n\t\t\t\t},\n\t\t\t\tbuildDeterministicCheckpoint: () => {\n\t\t\t\t\tconst preparation = prepareCompaction(this.deps.sessionManager.getBranch(), settings);\n\t\t\t\t\tif (!preparation) throw new Error(\"already compacted\");\n\t\t\t\t\tfromExtension = false;\n\t\t\t\t\treturn { result: createDeterministicCompaction(preparation) };\n\t\t\t\t},\n\t\t\t\tapply: async (result) => {\n\t\t\t\t\tlastCompaction = result;\n\t\t\t\t\tawait this.applyResult(result, fromExtension);\n\t\t\t\t},\n\t\t\t\tverifyPostApplyEffect: reason === \"overflow\" ? () => false : undefined,\n\t\t\t\tonTransition: ({ cycle, cause, detail }) => {\n\t\t\t\t\tthis.deps.emit({\n\t\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\t\tmessage: `auto-compaction cycle ${cycle}: ${cause}${detail ? ` (${detail})` : \"\"} — retrying from step 0 (${this.deps.describeSummarizer()})`,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t});\n\n\t\t\tif (outcome.kind === \"skip\") {\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason,\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\tskipReason: outcome.reason,\n\t\t\t\t});\n\t\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t\t}\n\t\t\tif (outcome.kind === \"failed\") {\n\t\t\t\tif (outcome.reason === \"aborted\") {\n\t\t\t\t\tthis.deps.emit({ type: \"compaction_end\", reason, result: undefined, aborted: true, willRetry: false });\n\t\t\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t\t\t}\n\t\t\t\tthrow new Error(outcome.reason);\n\t\t\t}\n\t\t\tif (extensionCancelled || signal.aborted) {\n\t\t\t\tthis.deps.emit({ type: \"compaction_end\", reason, result: undefined, aborted: true, willRetry: false });\n\t\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t\t}\n\n\t\t\tconst result = outcome.kind === \"success\" ? outcome.result : lastCompaction;\n\t\t\tif (!result) throw new Error(\"Auto-compaction succeeded without a result\");\n\t\t\tthis.deps.emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\t\tif (willRetry) {\n\t\t\t\tconst messages = this.deps.agent.state.messages;\n\t\t\t\tconst lastMessage = messages[messages.length - 1];\n\t\t\t\tif (lastMessage?.role === \"assistant\" && lastMessage.stopReason === \"error\") {\n\t\t\t\t\tthis.deps.agent.state.messages = messages.slice(0, -1);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\terrorMessage:\n\t\t\t\t\treason === \"overflow\"\n\t\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t\t});\n\t\t\treturn hadQueuedMessages || this.deps.agent.hasQueuedMessages();\n\t\t} finally {\n\t\t\tthis.autoAbortController = undefined;\n\t\t}\n\t}\n\n\tasync compactWithRetry(\n\t\trun: () => Promise<CompactionResult>,\n\t\tsignal: AbortSignal,\n\t\tprovider?: string,\n\t): Promise<CompactionResult> {\n\t\treturn runCompactionWithRetry({\n\t\t\trun,\n\t\t\tsignal,\n\t\t\tprovider,\n\t\t\tgetRetrySettings: () => this.deps.settingsManager.getRetrySettings(),\n\t\t\trecordFailure: (record) => this.deps.getFailureCorpus().record(record),\n\t\t});\n\t}\n\n\tprivate findLastAssistantMessage(): AssistantMessage | undefined {\n\t\tfor (let index = this.deps.agent.state.messages.length - 1; index >= 0; index--) {\n\t\t\tconst message = this.deps.agent.state.messages[index];\n\t\t\tif (message.role === \"assistant\") return message;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate async getExtensionCompaction(\n\t\tpreparation: CompactionPreparation,\n\t\tbranchEntries: ReturnType<SessionManager[\"getBranch\"]>,\n\t\tcustomInstructions: string | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<{ cancelled: boolean; result?: CompactionResult }> {\n\t\tconst extensionRunner = this.deps.getExtensionRunner();\n\t\tif (!extensionRunner.hasHandlers(\"session_before_compact\")) return { cancelled: false };\n\t\tconst extensionResult = (await extensionRunner.emit({\n\t\t\ttype: \"session_before_compact\",\n\t\t\tpreparation,\n\t\t\tbranchEntries,\n\t\t\tcustomInstructions,\n\t\t\tsignal,\n\t\t})) as SessionBeforeCompactResult | undefined;\n\t\treturn { cancelled: extensionResult?.cancel === true, result: extensionResult?.compaction };\n\t}\n\n\tprivate async applyResult(result: CompactionResult, fromExtension: boolean): Promise<void> {\n\t\tthis.deps.sessionManager.appendCompaction(\n\t\t\tresult.summary,\n\t\t\tresult.firstKeptEntryId,\n\t\t\tresult.tokensBefore,\n\t\t\tresult.details,\n\t\t\tfromExtension,\n\t\t\tresult.usage,\n\t\t);\n\t\tthis.deps.refreshAfterCompaction();\n\t\tconst savedEntry = this.deps.sessionManager\n\t\t\t.getEntries()\n\t\t\t.find((entry) => entry.type === \"compaction\" && entry.summary === result.summary) as\n\t\t\t| CompactionEntry\n\t\t\t| undefined;\n\t\tif (savedEntry) {\n\t\t\tawait this.deps.getExtensionRunner().emit({\n\t\t\t\ttype: \"session_compact\",\n\t\t\t\tcompactionEntry: savedEntry,\n\t\t\t\tfromExtension,\n\t\t\t});\n\t\t}\n\t}\n}\n"]}
|
|
@@ -435,7 +435,7 @@ export class CompactionController {
|
|
|
435
435
|
return { cancelled: extensionResult?.cancel === true, result: extensionResult?.compaction };
|
|
436
436
|
}
|
|
437
437
|
async applyResult(result, fromExtension) {
|
|
438
|
-
this.deps.sessionManager.appendCompaction(result.summary, result.firstKeptEntryId, result.tokensBefore, result.details, fromExtension);
|
|
438
|
+
this.deps.sessionManager.appendCompaction(result.summary, result.firstKeptEntryId, result.tokensBefore, result.details, fromExtension, result.usage);
|
|
439
439
|
this.deps.refreshAfterCompaction();
|
|
440
440
|
const savedEntry = this.deps.sessionManager
|
|
441
441
|
.getEntries()
|