@bastani/atomic 0.9.8 → 0.9.9-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/dist/builtin/cursor/CHANGELOG.md +6 -0
- package/dist/builtin/cursor/package.json +2 -2
- package/dist/builtin/intercom/CHANGELOG.md +6 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/CHANGELOG.md +6 -0
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +6 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/runs/background/async-execution-chain.ts +2 -0
- package/dist/builtin/subagents/src/runs/background/async-execution-common.ts +7 -1
- package/dist/builtin/subagents/src/runs/background/async-execution-single.ts +2 -0
- package/dist/builtin/subagents/src/runs/background/async-execution-types.ts +8 -2
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-parallel-runner.ts +2 -0
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-sequential-step.ts +2 -0
- package/dist/builtin/subagents/src/runs/foreground/execution-attempt.ts +2 -1
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-async.ts +2 -0
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel-task.ts +2 -0
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-resume.ts +2 -0
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-single.ts +2 -0
- package/dist/builtin/subagents/src/runs/shared/pi-args.ts +6 -0
- package/dist/builtin/subagents/src/shared/types-config.ts +4 -0
- package/dist/builtin/subagents/src/shared/types-depth.ts +29 -2
- package/dist/builtin/web-access/CHANGELOG.md +6 -0
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +22 -0
- package/dist/builtin/workflows/README.md +17 -8
- package/dist/builtin/workflows/builtin/goal-prompts.ts +8 -2
- package/dist/builtin/workflows/builtin/open-claude-design-utils.ts +26 -9
- package/dist/builtin/workflows/builtin/ralph-forked-prompts.ts +1 -1
- package/dist/builtin/workflows/builtin/ralph-reviewer-prompt.ts +8 -3
- package/dist/builtin/workflows/builtin/ralph-runner.ts +2 -0
- package/dist/builtin/workflows/builtin/shared-prompts.ts +24 -1
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/durable/backend.ts +53 -15
- package/dist/builtin/workflows/src/durable/completed-catalog.ts +245 -0
- package/dist/builtin/workflows/src/durable/completed-inspection.ts +213 -0
- package/dist/builtin/workflows/src/durable/dbos-backend.ts +120 -170
- package/dist/builtin/workflows/src/durable/dbos-envelope.ts +84 -8
- package/dist/builtin/workflows/src/durable/dbos-metadata.ts +98 -0
- package/dist/builtin/workflows/src/durable/dbos-tombstone.ts +27 -0
- package/dist/builtin/workflows/src/durable/factory.ts +1 -1
- package/dist/builtin/workflows/src/durable/file-backend.ts +247 -241
- package/dist/builtin/workflows/src/durable/file-lock.ts +153 -0
- package/dist/builtin/workflows/src/durable/file-state.ts +104 -0
- package/dist/builtin/workflows/src/durable/format-version.ts +12 -0
- package/dist/builtin/workflows/src/durable/index.ts +12 -0
- package/dist/builtin/workflows/src/durable/resume-catalog.ts +16 -27
- package/dist/builtin/workflows/src/durable/resume-eligibility.ts +20 -0
- package/dist/builtin/workflows/src/durable/resume-runtime.ts +29 -29
- package/dist/builtin/workflows/src/durable/scoped-backend.ts +20 -3
- package/dist/builtin/workflows/src/durable/stage-primitive.ts +29 -8
- package/dist/builtin/workflows/src/durable/types.ts +3 -0
- package/dist/builtin/workflows/src/engine/primitives/task.ts +1 -0
- package/dist/builtin/workflows/src/engine/run.ts +14 -14
- package/dist/builtin/workflows/src/extension/extension-lifecycle.ts +39 -9
- package/dist/builtin/workflows/src/extension/extension-runtime-state.ts +10 -0
- package/dist/builtin/workflows/src/extension/runtime-durable-resume.ts +133 -0
- package/dist/builtin/workflows/src/extension/runtime.ts +15 -40
- package/dist/builtin/workflows/src/extension/wiring.ts +9 -6
- package/dist/builtin/workflows/src/extension/workflow-durable-resume-command.ts +226 -0
- package/dist/builtin/workflows/src/extension/workflow-prompts.ts +1 -0
- package/dist/builtin/workflows/src/extension/workflow-run-control-command.ts +66 -112
- package/dist/builtin/workflows/src/extension/workflow-schema.ts +5 -5
- package/dist/builtin/workflows/src/extension/workflow-tool-control.ts +16 -1
- package/dist/builtin/workflows/src/runs/foreground/executor-direct-helpers.ts +50 -43
- package/dist/builtin/workflows/src/runs/foreground/executor-direct-output.ts +91 -0
- package/dist/builtin/workflows/src/runs/foreground/executor-direct.ts +95 -46
- package/dist/builtin/workflows/src/runs/foreground/executor-stage-call.ts +3 -1
- package/dist/builtin/workflows/src/runs/foreground/executor-task-prompts.ts +1 -1
- package/dist/builtin/workflows/src/runs/foreground/executor-types.ts +3 -0
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-controller.ts +1 -1
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-options.ts +36 -7
- package/dist/builtin/workflows/src/runs/shared/worktree-cache-lifecycle.ts +25 -0
- package/dist/builtin/workflows/src/runs/shared/worktree-cwd.ts +103 -0
- package/dist/builtin/workflows/src/runs/shared/worktree-generation.ts +57 -0
- package/dist/builtin/workflows/src/runs/shared/worktree-git.ts +134 -8
- package/dist/builtin/workflows/src/runs/shared/worktree.ts +2 -0
- package/dist/builtin/workflows/src/shared/resumable-workflow-notices.ts +43 -0
- package/dist/builtin/workflows/src/shared/timing.ts +4 -0
- package/dist/builtin/workflows/src/shared/types.ts +5 -3
- package/dist/builtin/workflows/src/tui/graph-view-constants.ts +1 -0
- package/dist/builtin/workflows/src/tui/graph-view-input.ts +24 -14
- package/dist/builtin/workflows/src/tui/workflow-resume-selector.ts +43 -13
- package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-auto-compaction.js +5 -7
- package/dist/core/agent-session-auto-compaction.js.map +1 -1
- package/dist/core/agent-session-compaction.d.ts +6 -34
- package/dist/core/agent-session-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-compaction.js +95 -233
- package/dist/core/agent-session-compaction.js.map +1 -1
- package/dist/core/agent-session-message-queue.d.ts +0 -4
- package/dist/core/agent-session-message-queue.d.ts.map +1 -1
- package/dist/core/agent-session-message-queue.js +1 -5
- package/dist/core/agent-session-message-queue.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +5 -6
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-types.d.ts +2 -12
- package/dist/core/agent-session-types.d.ts.map +1 -1
- package/dist/core/agent-session-types.js.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts +1 -1
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +1 -2
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction-boundary.d.ts +9 -0
- package/dist/core/compaction/compaction-boundary.d.ts.map +1 -0
- package/dist/core/compaction/compaction-boundary.js +115 -0
- package/dist/core/compaction/compaction-boundary.js.map +1 -0
- package/dist/core/compaction/compaction-parameters.d.ts +5 -0
- package/dist/core/compaction/compaction-parameters.d.ts.map +1 -0
- package/dist/core/compaction/compaction-parameters.js +27 -0
- package/dist/core/compaction/compaction-parameters.js.map +1 -0
- package/dist/core/compaction/compaction-runner.d.ts +14 -0
- package/dist/core/compaction/compaction-runner.d.ts.map +1 -0
- package/dist/core/compaction/compaction-runner.js +29 -0
- package/dist/core/compaction/compaction-runner.js.map +1 -0
- package/dist/core/compaction/compaction-types.d.ts +79 -0
- package/dist/core/compaction/compaction-types.d.ts.map +1 -0
- package/dist/core/compaction/compaction-types.js +6 -0
- package/dist/core/compaction/compaction-types.js.map +1 -0
- package/dist/core/compaction/deleted-ranges.d.ts +6 -0
- package/dist/core/compaction/deleted-ranges.d.ts.map +1 -0
- package/dist/core/compaction/deleted-ranges.js +134 -0
- package/dist/core/compaction/deleted-ranges.js.map +1 -0
- package/dist/core/compaction/index.d.ts +7 -1
- package/dist/core/compaction/index.d.ts.map +1 -1
- package/dist/core/compaction/index.js +7 -1
- package/dist/core/compaction/index.js.map +1 -1
- package/dist/core/compaction/range-planner.d.ts +21 -0
- package/dist/core/compaction/range-planner.d.ts.map +1 -0
- package/dist/core/compaction/range-planner.js +145 -0
- package/dist/core/compaction/range-planner.js.map +1 -0
- package/dist/core/compaction/transcript-serialization.d.ts +11 -0
- package/dist/core/compaction/transcript-serialization.d.ts.map +1 -0
- package/dist/core/compaction/transcript-serialization.js +104 -0
- package/dist/core/compaction/transcript-serialization.js.map +1 -0
- package/dist/core/extensions/context-types.d.ts +2 -2
- package/dist/core/extensions/context-types.d.ts.map +1 -1
- package/dist/core/extensions/context-types.js.map +1 -1
- package/dist/core/extensions/event-results.d.ts +2 -2
- package/dist/core/extensions/event-results.d.ts.map +1 -1
- package/dist/core/extensions/event-results.js.map +1 -1
- package/dist/core/extensions/session-events.d.ts +7 -7
- package/dist/core/extensions/session-events.d.ts.map +1 -1
- package/dist/core/extensions/session-events.js.map +1 -1
- package/dist/core/index.d.ts +1 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/messages.d.ts +4 -0
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +11 -0
- package/dist/core/messages.js.map +1 -1
- package/dist/core/provider-context-usage.d.ts.map +1 -1
- package/dist/core/provider-context-usage.js +1 -2
- package/dist/core/provider-context-usage.js.map +1 -1
- package/dist/core/session-manager-archive.d.ts +2 -1
- package/dist/core/session-manager-archive.d.ts.map +1 -1
- package/dist/core/session-manager-archive.js +2 -2
- package/dist/core/session-manager-archive.js.map +1 -1
- package/dist/core/session-manager-classification.d.ts +9 -0
- package/dist/core/session-manager-classification.d.ts.map +1 -0
- package/dist/core/session-manager-classification.js +37 -0
- package/dist/core/session-manager-classification.js.map +1 -0
- package/dist/core/session-manager-core.d.ts +4 -4
- package/dist/core/session-manager-core.d.ts.map +1 -1
- package/dist/core/session-manager-core.js +13 -8
- package/dist/core/session-manager-core.js.map +1 -1
- package/dist/core/session-manager-entries.d.ts +4 -3
- package/dist/core/session-manager-entries.d.ts.map +1 -1
- package/dist/core/session-manager-entries.js +12 -10
- package/dist/core/session-manager-entries.js.map +1 -1
- package/dist/core/session-manager-history.d.ts +6 -23
- package/dist/core/session-manager-history.d.ts.map +1 -1
- package/dist/core/session-manager-history.js +23 -256
- package/dist/core/session-manager-history.js.map +1 -1
- package/dist/core/session-manager-list.d.ts.map +1 -1
- package/dist/core/session-manager-list.js +3 -3
- package/dist/core/session-manager-list.js.map +1 -1
- package/dist/core/session-manager-storage.d.ts +1 -1
- package/dist/core/session-manager-storage.d.ts.map +1 -1
- package/dist/core/session-manager-storage.js +3 -2
- package/dist/core/session-manager-storage.js.map +1 -1
- package/dist/core/session-manager-types.d.ts +14 -15
- package/dist/core/session-manager-types.d.ts.map +1 -1
- package/dist/core/session-manager-types.js.map +1 -1
- package/dist/core/session-manager.d.ts +3 -2
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +1 -1
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +1 -1
- package/dist/core/slash-commands.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-session.d.ts +1 -0
- package/dist/main-session.d.ts.map +1 -1
- package/dist/main-session.js +7 -0
- package/dist/main-session.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +2 -2
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/chat-message-renderer.d.ts +4 -1
- package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-message-renderer.js +12 -22
- package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-events.js +5 -11
- package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-rendering.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-rendering.js +3 -0
- package/dist/modes/interactive/components/chat-session-host-rendering.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-state.d.ts +1 -0
- package/dist/modes/interactive/components/chat-session-host-state.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-state.js +1 -0
- package/dist/modes/interactive/components/chat-session-host-state.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-utils.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-utils.js +1 -1
- package/dist/modes/interactive/components/chat-session-host-utils.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host.js +1 -0
- package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
- package/dist/modes/interactive/components/compaction-boundary-message.d.ts +20 -0
- package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -0
- package/dist/modes/interactive/components/compaction-boundary-message.js +48 -0
- package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -0
- package/dist/modes/interactive/components/index.d.ts +1 -1
- package/dist/modes/interactive/components/index.d.ts.map +1 -1
- package/dist/modes/interactive/components/index.js +1 -1
- package/dist/modes/interactive/components/index.js.map +1 -1
- package/dist/modes/interactive/components/session-selector-list.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector-list.js +3 -0
- package/dist/modes/interactive/components/session-selector-list.js.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.js +3 -47
- package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-deps.d.ts +2 -2
- package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-deps.js +1 -1
- package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.d.ts +5 -3
- package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
- package/dist/modes/interactive/interactive-render-chat.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-render-chat.js +21 -12
- package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +3 -5
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +1 -6
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-command-handler.js +0 -4
- package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +2 -11
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/docs/compaction.md +97 -772
- package/docs/extensions.md +25 -29
- package/docs/json.md +2 -2
- package/docs/rpc.md +32 -24
- package/docs/sdk.md +3 -3
- package/docs/session-format.md +49 -30
- package/docs/sessions.md +5 -3
- package/docs/settings.md +14 -4
- package/docs/usage.md +1 -1
- package/docs/workflows.md +30 -15
- package/examples/extensions/custom-compaction.ts +14 -58
- package/examples/extensions/handoff.ts +2 -3
- package/npm-shrinkwrap.json +23 -23
- package/package.json +2 -2
- package/dist/core/compaction/context-assistant-turns.d.ts +0 -42
- package/dist/core/compaction/context-assistant-turns.d.ts.map +0 -1
- package/dist/core/compaction/context-assistant-turns.js +0 -87
- package/dist/core/compaction/context-assistant-turns.js.map +0 -1
- package/dist/core/compaction/context-compaction-critical.d.ts +0 -15
- package/dist/core/compaction/context-compaction-critical.d.ts.map +0 -1
- package/dist/core/compaction/context-compaction-critical.js +0 -57
- package/dist/core/compaction/context-compaction-critical.js.map +0 -1
- package/dist/core/compaction/context-compaction-eviction-alternates.d.ts +0 -18
- package/dist/core/compaction/context-compaction-eviction-alternates.d.ts.map +0 -1
- package/dist/core/compaction/context-compaction-eviction-alternates.js +0 -186
- package/dist/core/compaction/context-compaction-eviction-alternates.js.map +0 -1
- package/dist/core/compaction/context-compaction-eviction.d.ts +0 -12
- package/dist/core/compaction/context-compaction-eviction.d.ts.map +0 -1
- package/dist/core/compaction/context-compaction-eviction.js +0 -222
- package/dist/core/compaction/context-compaction-eviction.js.map +0 -1
- package/dist/core/compaction/context-compaction-metrics.d.ts +0 -28
- package/dist/core/compaction/context-compaction-metrics.d.ts.map +0 -1
- package/dist/core/compaction/context-compaction-metrics.js +0 -107
- package/dist/core/compaction/context-compaction-metrics.js.map +0 -1
- package/dist/core/compaction/context-compaction-prompt.d.ts +0 -9
- package/dist/core/compaction/context-compaction-prompt.d.ts.map +0 -1
- package/dist/core/compaction/context-compaction-prompt.js +0 -163
- package/dist/core/compaction/context-compaction-prompt.js.map +0 -1
- package/dist/core/compaction/context-compaction-runner.d.ts +0 -11
- package/dist/core/compaction/context-compaction-runner.d.ts.map +0 -1
- package/dist/core/compaction/context-compaction-runner.js +0 -273
- package/dist/core/compaction/context-compaction-runner.js.map +0 -1
- package/dist/core/compaction/context-compaction-strategy.d.ts +0 -5
- package/dist/core/compaction/context-compaction-strategy.d.ts.map +0 -1
- package/dist/core/compaction/context-compaction-strategy.js +0 -27
- package/dist/core/compaction/context-compaction-strategy.js.map +0 -1
- package/dist/core/compaction/context-compaction-types.d.ts +0 -75
- package/dist/core/compaction/context-compaction-types.d.ts.map +0 -1
- package/dist/core/compaction/context-compaction-types.js +0 -6
- package/dist/core/compaction/context-compaction-types.js.map +0 -1
- package/dist/core/compaction/context-compaction.d.ts +0 -10
- package/dist/core/compaction/context-compaction.d.ts.map +0 -1
- package/dist/core/compaction/context-compaction.js +0 -8
- package/dist/core/compaction/context-compaction.js.map +0 -1
- package/dist/core/compaction/context-deletion-application.d.ts +0 -14
- package/dist/core/compaction/context-deletion-application.d.ts.map +0 -1
- package/dist/core/compaction/context-deletion-application.js +0 -261
- package/dist/core/compaction/context-deletion-application.js.map +0 -1
- package/dist/core/compaction/context-deletion-store.d.ts +0 -78
- package/dist/core/compaction/context-deletion-store.d.ts.map +0 -1
- package/dist/core/compaction/context-deletion-store.js +0 -162
- package/dist/core/compaction/context-deletion-store.js.map +0 -1
- package/dist/core/compaction/context-deletion-targets.d.ts +0 -43
- package/dist/core/compaction/context-deletion-targets.d.ts.map +0 -1
- package/dist/core/compaction/context-deletion-targets.js +0 -292
- package/dist/core/compaction/context-deletion-targets.js.map +0 -1
- package/dist/core/compaction/context-deletion-tool-definitions.d.ts +0 -193
- package/dist/core/compaction/context-deletion-tool-definitions.d.ts.map +0 -1
- package/dist/core/compaction/context-deletion-tool-definitions.js +0 -98
- package/dist/core/compaction/context-deletion-tool-definitions.js.map +0 -1
- package/dist/core/compaction/context-deletion-tool-helpers.d.ts +0 -19
- package/dist/core/compaction/context-deletion-tool-helpers.d.ts.map +0 -1
- package/dist/core/compaction/context-deletion-tool-helpers.js +0 -210
- package/dist/core/compaction/context-deletion-tool-helpers.js.map +0 -1
- package/dist/core/compaction/context-deletion-tools.d.ts +0 -4
- package/dist/core/compaction/context-deletion-tools.d.ts.map +0 -1
- package/dist/core/compaction/context-deletion-tools.js +0 -403
- package/dist/core/compaction/context-deletion-tools.js.map +0 -1
- package/dist/core/compaction/context-transcript-analysis.d.ts +0 -11
- package/dist/core/compaction/context-transcript-analysis.d.ts.map +0 -1
- package/dist/core/compaction/context-transcript-analysis.js +0 -228
- package/dist/core/compaction/context-transcript-analysis.js.map +0 -1
- package/dist/core/session-manager-tool-dependencies.d.ts +0 -10
- package/dist/core/session-manager-tool-dependencies.d.ts.map +0 -1
- package/dist/core/session-manager-tool-dependencies.js +0 -133
- package/dist/core/session-manager-tool-dependencies.js.map +0 -1
- package/dist/modes/interactive/components/context-compaction-summary-message.d.ts +0 -17
- package/dist/modes/interactive/components/context-compaction-summary-message.d.ts.map +0 -1
- package/dist/modes/interactive/components/context-compaction-summary-message.js +0 -83
- package/dist/modes/interactive/components/context-compaction-summary-message.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-auto-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACrG,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAG1F;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAElD,MAAM,CAAC,MAAM,6CAA6C,GAAG,CAAC,CAAC;AAS/D,MAAM,+BAA+B,GAAG,uBAAuB,CAAC;AAChE,MAAM,+BAA+B,GAAG,IAAI,MAAM,CACjD,gFAAgF,+BAA+B,uBAAuB,CACtI,CAAC;AAEF,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAqB,gBAAkC,EAAE,gBAAgB,GAAG,IAAI;IACrH,8EAA8E;IAC9E,0EAA0E;IAC1E,yEAAyE;IACzE,MAAM,oBAAoB,GAAG,gBAAgB,CAAC;IAC9C,MAAM,QAAQ,GAAG,IAAI,CAAC,eAAe,CAAC,qBAAqB,EAAE,CAAC;IAC9D,IAAI,CAAC,QAAQ,CAAC,OAAO;QAAE,OAAO;IAE9B,kFAAkF;IAClF,IAAI,gBAAgB,IAAI,gBAAgB,CAAC,UAAU,KAAK,SAAS;QAAE,OAAO;IAE1E,MAAM,aAAa,GAAG,IAAI,CAAC,KAAK,EAAE,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,CAAC","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { isContextOverflow } from \"@earendil-works/pi-ai/compat\";\nimport { getEffectiveInputBudget } from \"./context-window.ts\";\nimport { parseCopilotPromptLimitError } from \"./copilot-errors.ts\";\nimport { calculateContextTokens, estimateContextTokens, shouldCompact } from \"./compaction/index.ts\";\nimport { getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\nimport { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from \"./openai-responses-payload-sanitizer.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\n/**\n * Upper bound on consecutive automatic continuations of a response that was\n * truncated at the output-token cap (\"length\") while the context is still\n * below the compaction budget. Each continuation regenerates the cut-off turn,\n * so a model that insists on emitting more than its per-turn output cap can\n * still terminate instead of looping forever.\n */\nexport const MAX_LENGTH_CONTINUATION_ATTEMPTS = 3;\n\nexport const MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS = 1;\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\ntype ProviderErrorDetails = {\n\tmessage?: string;\n\tcode?: string;\n\tparam?: string;\n};\n\nconst OUTPUT_BUDGET_PARAMETER_PATTERN = /\\bmax_output_tokens\\b/;\nconst OUTPUT_BUDGET_UNDERFLOW_PATTERN = new RegExp(\n\t`(?:integer\\\\s+below\\\\s+minimum\\\\s+value|expected\\\\s+(?:a\\\\s+)?value\\\\s*>=\\\\s*${MIN_RESPONSES_MAX_OUTPUT_TOKENS}|got\\\\s+1\\\\s+instead)`,\n);\n\nexport async function _checkCompaction(this: AgentSession, assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<void> {\n\t// The agent_end path passes skipAbortedCheck=true; the pre-prompt path passes\n\t// false. Only the live turn-completion path may auto-continue a truncated\n\t// response — before a fresh user prompt we must not resume the old turn.\n\tconst isLiveTurnCompletion = skipAbortedCheck;\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tif (!settings.enabled) return;\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\n\t// Skip overflow check if the message came from a different model.\n\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t// shouldn't trigger compaction for the new model.\n\tconst sameModel =\n\t\tthis.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;\n\n\t// Skip compaction checks if this assistant message is older than the latest\n\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t// from retriggering compaction on the first prompt after compaction.\n\tconst compactionBoundaryEntry = getLatestCompactionBoundaryEntry(this.sessionManager.getBranch());\n\tconst assistantIsFromBeforeCompactionBoundary =\n\t\tcompactionBoundaryEntry !== null &&\n\t\tassistantMessage.timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime();\n\tif (assistantIsFromBeforeCompactionBoundary) {\n\t\treturn;\n\t}\n\n\t// Case 1: Overflow - LLM returned context overflow error\n\t// When Copilot rejects a 1m client-budget prompt at a lower server cap (for example\n\t// because long-context/usage-based billing entitlement is missing), leave the friendly\n\t// error visible instead of auto-compacting down to a smaller server tier silently.\n\tif (sameModel && this._isCopilotServerCapBelowSelectedContextWindow(assistantMessage)) {\n\t\treturn;\n\t}\n\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\n\t\tconst willRetry = assistantMessage.stopReason !== \"stop\";\n\t\tif (!willRetry) {\n\t\t\tawait this._runAutoCompaction(\"overflow\", false);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._overflowRecoveryAttempted) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"overflow\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: true,\n\t\t\t\terrorMessage:\n\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});\n\t\t\treturn;\n\t\t}\n\n\t\tthis._overflowRecoveryAttempted = true;\n\t\t// Remove the error message from agent state (it IS saved to session for history,\n\t\t// but we don't want it in context for the retry)\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tawait this._runAutoCompaction(\"overflow\", willRetry);\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For error messages (no usage data), estimate from last successful response.\n\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\tlet contextTokens: number;\n\tif (assistantMessage.stopReason === \"error\") {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t// trigger compaction right after one just finished.\n\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\tif (\n\t\t\tcompactionBoundaryEntry &&\n\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t} else {\n\t\tcontextTokens = calculateContextTokens(assistantMessage.usage);\n\t}\n\t// Compact against the effective input budget (the hard prompt cap for providers like Copilot\n\t// that advertise a larger total window) so we compact before overrunning the server-side limit\n\t// rather than relying on reactive overflow recovery near the cap.\n\tconst compactionBudget = this.model ? getEffectiveInputBudget(this.model) : contextWindow;\n\tif (shouldCompact(contextTokens, compactionBudget, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"threshold\",\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\"Output-budget recovery stopped after a compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._outputBudgetErrorContinuationAttempts += 1;\n\t\t}\n\t\tawait this._runAutoCompaction(\"threshold\", willRetry);\n\t\treturn;\n\t}\n\n\t// A response truncated at the output-token cap (\"length\") with the context\n\t// still below the compaction budget is genuine work cut off mid-flight, not a\n\t// context overflow. Compaction would not free any room, so continue the\n\t// generation directly instead of dead-ending on the truncation and leaving\n\t// the task half-finished.\n\tif (isLiveTurnCompletion && isRetryWorthyLengthStop(assistantMessage)) {\n\t\tthis._resumeAfterLengthTruncation();\n\t}\n}\n\n\nexport function _isCopilotServerCapBelowSelectedContextWindow(this: AgentSession, assistantMessage: AssistantMessage): boolean {\n\tif (!this.model || this.model.provider !== \"github-copilot\" || !assistantMessage.errorMessage) return false;\n\tconst promptLimitError = parseCopilotPromptLimitError(assistantMessage.errorMessage);\n\t// Compare against the effective input budget (the model's real prompt cap), not the displayed\n\t// total window. A rejection at the prompt cap is a normal overflow we should compact-and-retry;\n\t// only a rejection *below* the cap (e.g. a missing long-context entitlement dropping the account\n\t// to a lower server tier) keeps the friendly error visible instead of silently compacting down.\n\treturn promptLimitError !== undefined && getEffectiveInputBudget(this.model) > promptLimitError.limitTokens;\n}\n\nexport function isRetryWorthyLengthStop(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\nfunction isJsonRecord(value: JsonValue): value is { [key: string]: JsonValue } {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: { [key: string]: JsonValue }, key: string): string | undefined {\n\tconst value = record[key];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction parseProviderErrorDetails(errorMessage: string): ProviderErrorDetails | undefined {\n\tconst start = errorMessage.indexOf(\"{\");\n\tconst end = errorMessage.lastIndexOf(\"}\");\n\tif (start === -1 || end <= start) return undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(errorMessage.slice(start, end + 1)) as JsonValue;\n\t\tif (!isJsonRecord(parsed)) return undefined;\n\n\t\tconst nestedError = parsed.error;\n\t\tif (nestedError !== undefined && isJsonRecord(nestedError)) {\n\t\t\treturn {\n\t\t\t\tmessage: stringField(nestedError, \"message\"),\n\t\t\t\tcode: stringField(nestedError, \"code\") ?? stringField(parsed, \"code\"),\n\t\t\t\tparam: stringField(nestedError, \"param\") ?? stringField(parsed, \"param\"),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tmessage: stringField(parsed, \"message\"),\n\t\t\tcode: stringField(parsed, \"code\"),\n\t\t\tparam: stringField(parsed, \"param\"),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isOutputBudgetUnderflowText(text: string): boolean {\n\tconst message = text.toLowerCase();\n\treturn OUTPUT_BUDGET_PARAMETER_PATTERN.test(message) && OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message);\n}\n\nfunction isStructuredOutputBudgetUnderflow(details: ProviderErrorDetails): boolean {\n\tconst message = details.message?.toLowerCase() ?? \"\";\n\tconst param = details.param?.toLowerCase();\n\tif (!OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message)) return false;\n\treturn param !== undefined ? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param) : OUTPUT_BUDGET_PARAMETER_PATTERN.test(message);\n}\n\nexport function isRetryWorthyOutputBudgetError(assistantMessage: AssistantMessage): boolean {\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return false;\n\tif (assistantMessage.api !== \"openai-responses\") return false;\n\n\tconst structuredDetails = parseProviderErrorDetails(assistantMessage.errorMessage);\n\tif (structuredDetails && isStructuredOutputBudgetUnderflow(structuredDetails)) return true;\n\n\treturn isOutputBudgetUnderflowText(assistantMessage.errorMessage);\n}\n\nexport function shouldRetryAfterThresholdCompaction(assistantMessage: AssistantMessage): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) || isRetryWorthyOutputBudgetError(assistantMessage);\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): void {\n\tconst messages = this.agent.state.messages;\n\tconst lastMsg = messages[messages.length - 1];\n\tif (lastMsg?.role !== \"assistant\") return;\n\tconst stopReason = (lastMsg as AssistantMessage).stopReason;\n\tif (stopReason === \"error\" || stopReason === \"length\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n}\n\n/**\n * Internal: schedule a live post-event continuation probe after compaction_end listeners can flush queues.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(this: AgentSession,\n\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tif (willRetry) {\n\t\tconst token = this._postCompactionContinuationToken + 1;\n\t\tthis._postCompactionContinuationToken = token;\n\t\tlet pending: Promise<void>;\n\t\tpending = new Promise<void>((resolve) => {\n\t\t\tsetTimeout(() => {\n\t\t\t\tvoid (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (this._pendingPostCompactionContinuation === pending) {\n\t\t\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t}, 100);\n\t\t});\n\t\tthis._pendingPostCompactionContinuation = pending;\n\t\treturn;\n\t}\n\n\tsetTimeout(() => {\n\t\tif (this.isCompacting || this.isStreaming) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\treturn;\n\t\t}\n\n\t\tvoid this._resumeAfterAutoCompaction();\n\t}, 100);\n}\n\nexport async function _awaitPendingPostCompactionContinuation(this: AgentSession): Promise<void> {\n\tconst pending = this._pendingPostCompactionContinuation;\n\tif (pending === undefined) return;\n\tawait pending;\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport async function _resumeAfterAutoCompaction(this: AgentSession): Promise<void> {\n\ttry {\n\t\tawait this._runAgentContinue();\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis._emit({\n\t\t\ttype: \"agent_continue_error\",\n\t\t\tsource: \"post_compaction\",\n\t\t\terrorMessage: `Post-compaction continuation failed: ${message}`,\n\t\t});\n\t}\n}\n\n/**\n * Internal: resume a response that was truncated at the output-token cap\n * (\"length\") when the context does not warrant compaction. The generation is\n * continued directly so the model finishes the work it was cut off from, rather\n * than dead-ending on the truncation. Bounded by MAX_LENGTH_CONTINUATION_ATTEMPTS\n * so a turn that keeps exceeding the per-turn output cap can still terminate.\n */\n\nexport function _resumeAfterLengthTruncation(this: AgentSession): void {\n\tif (this._lengthContinuationAttempts >= MAX_LENGTH_CONTINUATION_ATTEMPTS) return;\n\tthis._lengthContinuationAttempts += 1;\n\t// agent.continue() rejects an assistant tail; drop the incomplete\n\t// length-stopped message so the preceding user/tool-result anchors the\n\t// continuation. It remains persisted in session history.\n\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\tthis._schedulePostAutoCompactionContinuationProbe(\"threshold\", true);\n}\n\n\nfunction overflowUnresolved(reason: \"overflow\" | \"threshold\", aborted = false): boolean | undefined {\n\treturn reason === \"overflow\" && !aborted ? true : undefined;\n}\n\nexport async function _runAutoCompaction(this: AgentSession, reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void> {\n\tthis._emit({ type: \"compaction_start\", reason });\n\tthis._autoCompactionAbortController = new AbortController();\n\n\ttry {\n\t\tif (!this.model) {\n\t\t\tthis._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\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Auth is resolved lazily: only called when the planner fallback is needed.\n\t\t// This allows extension-provided deletion requests to run before auth is checked,\n\t\t// enabling local extension compaction even when API credentials are unavailable.\n\t\t// Auto-mode resolver returns undefined (rather than throwing) when auth is missing;\n\t\t// overflow recovery then falls back to deterministic no-auth eviction, while\n\t\t// threshold compaction keeps the previous no-op behavior.\n\t\tconst model = this.model;\n\t\tconst result = await this._applyContextVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async () => {\n\t\t\t\tconst authResult = await this._modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\tif (!authResult.ok || !authResult.apiKey) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\treturn { apiKey: authResult.apiKey, headers: authResult.headers };\n\t\t\t},\n\t\t\tabortController: this._autoCompactionAbortController,\n\t\t\tbackupLabel: reason === \"overflow\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t});\n\t\tif (!result) {\n\t\t\tthis._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\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted = errorMessage === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tunresolvedOverflow: overflowUnresolved(reason, aborted),\n\t\t\terrorMessage: aborted\n\t\t\t\t? undefined\n\t\t\t\t: reason === \"overflow\"\n\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t});\n\t} finally {\n\t\tthis._autoCompactionAbortController = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingPostCompactionContinuation,\n\t_checkCompaction,\n\t_isCopilotServerCapBelowSelectedContextWindow,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_resumeAfterLengthTruncation,\n\t_runAutoCompaction,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-auto-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACrG,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,+B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,CAAC,IAAI,KAAK,YAAY,CAAC,CAAC;QACnH,IAAI,CAAC,KAAK,CAAC;YACV,IAAI,EAAE,gBAAgB;YACtB,MAAM;YACN,MAAM,EAAE,SAAS;YACjB,OAAO;YACP,SAAS,EAAE,KAAK;YAChB,kBAAkB,EAAE,kBAAkB,CAAC,MAAM,EAAE,OAAO,CAAC;YACvD,YAAY,EAAE,OAAO;gBACpB,CAAC,CAAC,SAAS;gBACX,CAAC,CAAC,MAAM,KAAK,UAAU;oBACtB,CAAC,CAAC,qCAAqC,YAAY,EAAE;oBACrD,CAAC,CAAC,2BAA2B,YAAY,EAAE;SAC7C,CAAC,CAAC;IACJ,CAAC;YAAS,CAAC;QACV,IAAI,CAAC,8BAA8B,GAAG,SAAS,CAAC;IACjD,CAAC;AACF,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAChD,uCAAuC;IACvC,gBAAgB;IAChB,6CAA6C;IAC7C,kDAAkD;IAClD,4CAA4C;IAC5C,0BAA0B;IAC1B,4BAA4B;IAC5B,kBAAkB;CAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { isContextOverflow } from \"@earendil-works/pi-ai/compat\";\nimport { getEffectiveInputBudget } from \"./context-window.ts\";\nimport { parseCopilotPromptLimitError } from \"./copilot-errors.ts\";\nimport { calculateContextTokens, estimateContextTokens, shouldCompact } from \"./compaction/index.ts\";\nimport { getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\nimport { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from \"./openai-responses-payload-sanitizer.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\n/**\n * Upper bound on consecutive automatic continuations of a response that was\n * truncated at the output-token cap (\"length\") while the context is still\n * below the compaction budget. Each continuation regenerates the cut-off turn,\n * so a model that insists on emitting more than its per-turn output cap can\n * still terminate instead of looping forever.\n */\nexport const MAX_LENGTH_CONTINUATION_ATTEMPTS = 3;\n\nexport const MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS = 1;\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\ntype ProviderErrorDetails = {\n\tmessage?: string;\n\tcode?: string;\n\tparam?: string;\n};\n\nconst OUTPUT_BUDGET_PARAMETER_PATTERN = /\\bmax_output_tokens\\b/;\nconst OUTPUT_BUDGET_UNDERFLOW_PATTERN = new RegExp(\n\t`(?:integer\\\\s+below\\\\s+minimum\\\\s+value|expected\\\\s+(?:a\\\\s+)?value\\\\s*>=\\\\s*${MIN_RESPONSES_MAX_OUTPUT_TOKENS}|got\\\\s+1\\\\s+instead)`,\n);\n\nexport async function _checkCompaction(this: AgentSession, assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<void> {\n\t// The agent_end path passes skipAbortedCheck=true; the pre-prompt path passes\n\t// false. Only the live turn-completion path may auto-continue a truncated\n\t// response — before a fresh user prompt we must not resume the old turn.\n\tconst isLiveTurnCompletion = skipAbortedCheck;\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tif (!settings.enabled) return;\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\n\t// Skip overflow check if the message came from a different model.\n\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t// shouldn't trigger compaction for the new model.\n\tconst sameModel =\n\t\tthis.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;\n\n\t// Skip compaction checks if this assistant message is older than the latest\n\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t// from retriggering compaction on the first prompt after compaction.\n\tconst compactionBoundaryEntry = getLatestCompactionBoundaryEntry(this.sessionManager.getBranch());\n\tconst assistantIsFromBeforeCompactionBoundary =\n\t\tcompactionBoundaryEntry !== null &&\n\t\tassistantMessage.timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime();\n\tif (assistantIsFromBeforeCompactionBoundary) {\n\t\treturn;\n\t}\n\n\t// Case 1: Overflow - LLM returned context overflow error\n\t// When Copilot rejects a 1m client-budget prompt at a lower server cap (for example\n\t// because long-context/usage-based billing entitlement is missing), leave the friendly\n\t// error visible instead of auto-compacting down to a smaller server tier silently.\n\tif (sameModel && this._isCopilotServerCapBelowSelectedContextWindow(assistantMessage)) {\n\t\treturn;\n\t}\n\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\n\t\tconst willRetry = assistantMessage.stopReason !== \"stop\";\n\t\tif (!willRetry) {\n\t\t\tawait this._runAutoCompaction(\"overflow\", false);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._overflowRecoveryAttempted) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"overflow\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: true,\n\t\t\t\terrorMessage:\n\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});\n\t\t\treturn;\n\t\t}\n\n\t\tthis._overflowRecoveryAttempted = true;\n\t\t// Remove the error message from agent state (it IS saved to session for history,\n\t\t// but we don't want it in context for the retry)\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tawait this._runAutoCompaction(\"overflow\", willRetry);\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For error messages (no usage data), estimate from last successful response.\n\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\tlet contextTokens: number;\n\tif (assistantMessage.stopReason === \"error\") {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t// trigger compaction right after one just finished.\n\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\tif (\n\t\t\tcompactionBoundaryEntry &&\n\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t} else {\n\t\tcontextTokens = calculateContextTokens(assistantMessage.usage);\n\t}\n\t// Compact against the effective input budget (the hard prompt cap for providers like Copilot\n\t// that advertise a larger total window) so we compact before overrunning the server-side limit\n\t// rather than relying on reactive overflow recovery near the cap.\n\tconst compactionBudget = this.model ? getEffectiveInputBudget(this.model) : contextWindow;\n\tif (shouldCompact(contextTokens, compactionBudget, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"threshold\",\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\"Output-budget recovery stopped after a compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._outputBudgetErrorContinuationAttempts += 1;\n\t\t}\n\t\tawait this._runAutoCompaction(\"threshold\", willRetry);\n\t\treturn;\n\t}\n\n\t// A response truncated at the output-token cap (\"length\") with the context\n\t// still below the compaction budget is genuine work cut off mid-flight, not a\n\t// context overflow. Compaction would not free any room, so continue the\n\t// generation directly instead of dead-ending on the truncation and leaving\n\t// the task half-finished.\n\tif (isLiveTurnCompletion && isRetryWorthyLengthStop(assistantMessage)) {\n\t\tthis._resumeAfterLengthTruncation();\n\t}\n}\n\n\nexport function _isCopilotServerCapBelowSelectedContextWindow(this: AgentSession, assistantMessage: AssistantMessage): boolean {\n\tif (!this.model || this.model.provider !== \"github-copilot\" || !assistantMessage.errorMessage) return false;\n\tconst promptLimitError = parseCopilotPromptLimitError(assistantMessage.errorMessage);\n\t// Compare against the effective input budget (the model's real prompt cap), not the displayed\n\t// total window. A rejection at the prompt cap is a normal overflow we should compact-and-retry;\n\t// only a rejection *below* the cap (e.g. a missing long-context entitlement dropping the account\n\t// to a lower server tier) keeps the friendly error visible instead of silently compacting down.\n\treturn promptLimitError !== undefined && getEffectiveInputBudget(this.model) > promptLimitError.limitTokens;\n}\n\nexport function isRetryWorthyLengthStop(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\nfunction isJsonRecord(value: JsonValue): value is { [key: string]: JsonValue } {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: { [key: string]: JsonValue }, key: string): string | undefined {\n\tconst value = record[key];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction parseProviderErrorDetails(errorMessage: string): ProviderErrorDetails | undefined {\n\tconst start = errorMessage.indexOf(\"{\");\n\tconst end = errorMessage.lastIndexOf(\"}\");\n\tif (start === -1 || end <= start) return undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(errorMessage.slice(start, end + 1)) as JsonValue;\n\t\tif (!isJsonRecord(parsed)) return undefined;\n\n\t\tconst nestedError = parsed.error;\n\t\tif (nestedError !== undefined && isJsonRecord(nestedError)) {\n\t\t\treturn {\n\t\t\t\tmessage: stringField(nestedError, \"message\"),\n\t\t\t\tcode: stringField(nestedError, \"code\") ?? stringField(parsed, \"code\"),\n\t\t\t\tparam: stringField(nestedError, \"param\") ?? stringField(parsed, \"param\"),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tmessage: stringField(parsed, \"message\"),\n\t\t\tcode: stringField(parsed, \"code\"),\n\t\t\tparam: stringField(parsed, \"param\"),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isOutputBudgetUnderflowText(text: string): boolean {\n\tconst message = text.toLowerCase();\n\treturn OUTPUT_BUDGET_PARAMETER_PATTERN.test(message) && OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message);\n}\n\nfunction isStructuredOutputBudgetUnderflow(details: ProviderErrorDetails): boolean {\n\tconst message = details.message?.toLowerCase() ?? \"\";\n\tconst param = details.param?.toLowerCase();\n\tif (!OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message)) return false;\n\treturn param !== undefined ? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param) : OUTPUT_BUDGET_PARAMETER_PATTERN.test(message);\n}\n\nexport function isRetryWorthyOutputBudgetError(assistantMessage: AssistantMessage): boolean {\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return false;\n\tif (assistantMessage.api !== \"openai-responses\") return false;\n\n\tconst structuredDetails = parseProviderErrorDetails(assistantMessage.errorMessage);\n\tif (structuredDetails && isStructuredOutputBudgetUnderflow(structuredDetails)) return true;\n\n\treturn isOutputBudgetUnderflowText(assistantMessage.errorMessage);\n}\n\nexport function shouldRetryAfterThresholdCompaction(assistantMessage: AssistantMessage): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) || isRetryWorthyOutputBudgetError(assistantMessage);\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): void {\n\tconst messages = this.agent.state.messages;\n\tconst lastMsg = messages[messages.length - 1];\n\tif (lastMsg?.role !== \"assistant\") return;\n\tconst stopReason = (lastMsg as AssistantMessage).stopReason;\n\tif (stopReason === \"error\" || stopReason === \"length\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n}\n\n/**\n * Internal: schedule a live post-event continuation probe after compaction_end listeners can flush queues.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(this: AgentSession,\n\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tif (willRetry) {\n\t\tconst token = this._postCompactionContinuationToken + 1;\n\t\tthis._postCompactionContinuationToken = token;\n\t\tlet pending: Promise<void>;\n\t\tpending = new Promise<void>((resolve) => {\n\t\t\tsetTimeout(() => {\n\t\t\t\tvoid (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (this._pendingPostCompactionContinuation === pending) {\n\t\t\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t}, 100);\n\t\t});\n\t\tthis._pendingPostCompactionContinuation = pending;\n\t\treturn;\n\t}\n\n\tsetTimeout(() => {\n\t\tif (this.isCompacting || this.isStreaming) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\treturn;\n\t\t}\n\n\t\tvoid this._resumeAfterAutoCompaction();\n\t}, 100);\n}\n\nexport async function _awaitPendingPostCompactionContinuation(this: AgentSession): Promise<void> {\n\tconst pending = this._pendingPostCompactionContinuation;\n\tif (pending === undefined) return;\n\tawait pending;\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport async function _resumeAfterAutoCompaction(this: AgentSession): Promise<void> {\n\ttry {\n\t\tawait this._runAgentContinue();\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis._emit({\n\t\t\ttype: \"agent_continue_error\",\n\t\t\tsource: \"post_compaction\",\n\t\t\terrorMessage: `Post-compaction continuation failed: ${message}`,\n\t\t});\n\t}\n}\n\n/**\n * Internal: resume a response that was truncated at the output-token cap\n * (\"length\") when the context does not warrant compaction. The generation is\n * continued directly so the model finishes the work it was cut off from, rather\n * than dead-ending on the truncation. Bounded by MAX_LENGTH_CONTINUATION_ATTEMPTS\n * so a turn that keeps exceeding the per-turn output cap can still terminate.\n */\n\nexport function _resumeAfterLengthTruncation(this: AgentSession): void {\n\tif (this._lengthContinuationAttempts >= MAX_LENGTH_CONTINUATION_ATTEMPTS) return;\n\tthis._lengthContinuationAttempts += 1;\n\t// agent.continue() rejects an assistant tail; drop the incomplete\n\t// length-stopped message so the preceding user/tool-result anchors the\n\t// continuation. It remains persisted in session history.\n\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\tthis._schedulePostAutoCompactionContinuationProbe(\"threshold\", true);\n}\n\n\nfunction overflowUnresolved(reason: \"overflow\" | \"threshold\", aborted = false): boolean | undefined {\n\treturn reason === \"overflow\" && !aborted ? true : undefined;\n}\n\nexport async function _runAutoCompaction(this: AgentSession, reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void> {\n\tthis._emit({ type: \"compaction_start\", reason });\n\tthis._autoCompactionAbortController = new AbortController();\n\n\ttry {\n\t\tif (!this.model) {\n\t\t\tthis._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\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Resolve auth only after extension hooks have had an opportunity to cancel\n\t\t// compaction or provide compacted text, so local extension compaction does not\n\t\t// require provider credentials. Missing auth then fails model-driven compaction\n\t\t// before persistence or continuation, matching other provider-call failures.\n\t\tconst model = this.model;\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async () => {\n\t\t\t\tconst authResult = await this._modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\tif (!authResult.ok || !authResult.apiKey) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\treturn { apiKey: authResult.apiKey, headers: authResult.headers };\n\t\t\t},\n\t\t\tabortController: this._autoCompactionAbortController,\n\t\t\tbackupLabel: reason === \"overflow\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t});\n\t\tif (!result) {\n\t\t\tthis._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\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted = errorMessage === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tunresolvedOverflow: overflowUnresolved(reason, aborted),\n\t\t\terrorMessage: aborted\n\t\t\t\t? undefined\n\t\t\t\t: reason === \"overflow\"\n\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t});\n\t} finally {\n\t\tthis._autoCompactionAbortController = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingPostCompactionContinuation,\n\t_checkCompaction,\n\t_isCopilotServerCapBelowSelectedContextWindow,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_resumeAfterLengthTruncation,\n\t_runAutoCompaction,\n};\n"]}
|
|
@@ -1,42 +1,14 @@
|
|
|
1
|
-
import type { AgentSessionInternalSurface as AgentSession } from "./agent-session-methods.ts";
|
|
2
|
-
import type
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
* Manually compact the session context using deletion-only verbatim context compaction.
|
|
7
|
-
* Aborts current agent operation first.
|
|
8
|
-
*/
|
|
9
|
-
export declare function compact(this: AgentSession, options?: Partial<ContextCompactionParameters>): Promise<ContextCompactionResult>;
|
|
10
|
-
/**
|
|
11
|
-
* Manually compact the session context by applying validated logical deletions.
|
|
12
|
-
* Retained transcript entries/content blocks stay verbatim; no user prompt text is accepted.
|
|
13
|
-
*/
|
|
14
|
-
export declare function contextCompact(this: AgentSession): Promise<ContextCompactionResult>;
|
|
15
|
-
/**
|
|
16
|
-
* Cancel in-progress compaction (manual or auto).
|
|
17
|
-
*/
|
|
1
|
+
import type { AgentSessionInternalSurface as AgentSession, VerbatimCompactionApplyOptions } from "./agent-session-methods.ts";
|
|
2
|
+
import { type VerbatimCompactionParameters, type VerbatimCompactionResult } from "./compaction/index.ts";
|
|
3
|
+
export declare function _applyVerbatimCompaction(this: AgentSession, options: VerbatimCompactionApplyOptions): Promise<VerbatimCompactionResult | undefined>;
|
|
4
|
+
/** Persist one verbatim line-subset compaction boundary. */
|
|
5
|
+
export declare function compact(this: AgentSession, options?: Partial<VerbatimCompactionParameters>): Promise<VerbatimCompactionResult>;
|
|
18
6
|
export declare function abortCompaction(this: AgentSession): void;
|
|
19
|
-
/**
|
|
20
|
-
* Cancel in-progress branch summarization.
|
|
21
|
-
*/
|
|
22
7
|
export declare function abortBranchSummary(this: AgentSession): void;
|
|
23
|
-
/**
|
|
24
|
-
* Check if compaction is needed and run it.
|
|
25
|
-
* Called after agent_end and before prompt submission.
|
|
26
|
-
*
|
|
27
|
-
* Two cases:
|
|
28
|
-
* 1. Overflow: LLM returned context overflow error, remove error message from agent state, compact, auto-retry
|
|
29
|
-
* 2. Threshold: Context over threshold, compact, resume queued active-turn work if present; otherwise wait for user
|
|
30
|
-
*
|
|
31
|
-
* @param assistantMessage The assistant message to check
|
|
32
|
-
* @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true
|
|
33
|
-
*/
|
|
34
8
|
export declare function setAutoCompactionEnabled(this: AgentSession, enabled: boolean): void;
|
|
35
|
-
/** Whether auto-compaction is enabled */
|
|
36
9
|
export declare const agentSessionCompactionMethods: {
|
|
37
|
-
|
|
10
|
+
_applyVerbatimCompaction: typeof _applyVerbatimCompaction;
|
|
38
11
|
compact: typeof compact;
|
|
39
|
-
contextCompact: typeof contextCompact;
|
|
40
12
|
abortCompaction: typeof abortCompaction;
|
|
41
13
|
abortBranchSummary: typeof abortBranchSummary;
|
|
42
14
|
setAutoCompactionEnabled: typeof setAutoCompactionEnabled;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-compaction.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC9F,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAEhF,OAAO,EAAE,KAAK,2BAA2B,EAAqC,KAAK,uBAAuB,EAAmK,MAAM,uBAAuB,CAAC;AAiB3S,wBAAsB,+BAA+B,CACpD,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,6BAA6B,GACpC,OAAO,CAAC,uBAAuB,GAAG,SAAS,CAAC,CA2K9C;AAED;;;GAGG;AAEH,wBAAsB,OAAO,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,GAAE,OAAO,CAAC,2BAA2B,CAAM,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAmDtI;AAED;;;GAGG;AAEH,wBAAsB,cAAc,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAgDzF;AAED;;GAEG;AAEH,wBAAgB,eAAe,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAGxD;AAED;;GAEG;AAEH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAE3D;AAED;;;;;;;;;;GAUG;AAEH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI,CAEnF;AAED,yCAAyC;AAEzC,eAAO,MAAM,6BAA6B;;;;;;;CAOzC,CAAC","sourcesContent":["import { formatNoModelSelectedMessage } from \"./auth-guidance.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { ContextCompactionApplyOptions } from \"./agent-session-methods.ts\";\nimport { getEffectiveInputBudget } from \"./context-window.ts\";\nimport { type ContextCompactionParameters, type ContextCompactionPreparation, type ContextCompactionResult, type ContextDeletionRequest, type ValidatedContextDeletionResult, contextCompact as runContextCompact, prepareContextCompaction, validateContextDeletionRequest } from \"./compaction/index.ts\";\nimport { runDeterministicContextEviction } from \"./compaction/context-compaction-eviction.ts\";\n// Type-only import: erased at runtime so module mocks of the compaction barrel stay authoritative.\nimport type { ContextCompactionLadderOptions } from \"./compaction/context-compaction-runner.ts\";\nimport type { SessionBeforeCompactEvent, SessionBeforeCompactResult, SessionCompactEvent } from \"./extensions/index.ts\";\nimport type { ContextCompactionEntry } from \"./session-manager.ts\";\n\nfunction deepFreeze<T>(value: T): T {\n\tif (value && typeof value === \"object\") {\n\t\tObject.freeze(value);\n\t\tfor (const nested of Object.values(value)) {\n\t\t\tdeepFreeze(nested);\n\t\t}\n\t}\n\treturn value;\n}\n\nexport async function _applyContextVerbatimCompaction(\n\tthis: AgentSession,\n\toptions: ContextCompactionApplyOptions,\n): Promise<ContextCompactionResult | undefined> {\n\tif (!this.model) {\n\t\tthrow new Error(formatNoModelSelectedMessage());\n\t}\n\t// Capture the narrowed model now (control-flow narrowing holds immediately after the\n\t// guard) so the lazy planner-fallback closure below can use a non-undefined model.\n\tconst model = this.model;\n\tconst compactionThinkingLevel = this.thinkingLevel;\n\n\tconst pathEntries = this.sessionManager.getBranch();\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tconst preparation = prepareContextCompaction(pathEntries, settings, {\n\t\t...(options.compression_ratio === undefined ? {} : { compression_ratio: options.compression_ratio }),\n\t\t...(options.preserve_recent === undefined ? {} : { preserve_recent: options.preserve_recent }),\n\t\t...(options.query === undefined ? {} : { query: options.query }),\n\t});\n\tif (!preparation) {\n\t\t// Overflow recovery must be loud when there is no transcript the ladder can compact:\n\t\t// a silent no-op would leave the session overflowing without proving safe deletion is exhausted.\n\t\tif (options.reason === \"overflow\") {\n\t\t\tthrow new Error(\"Context compaction found no compactable transcript entries; nothing more was safely deletable\");\n\t\t}\n\t\treturn undefined;\n\t}\n\tconst parameters: ContextCompactionParameters = preparation.parameters;\n\tconst effectiveBudget = getEffectiveInputBudget(model);\n\tconst ladderOptions: ContextCompactionLadderOptions | undefined =\n\t\toptions.reason === \"overflow\"\n\t\t\t? { acceptanceTokenBudget: effectiveBudget, criticalEvictionTokenBudget: effectiveBudget }\n\t\t\t: options.reason === \"threshold\"\n\t\t\t\t// Match the shouldCompact trigger boundary in transcript-estimate space:\n\t\t\t\t// tokensAfter <= effectiveBudget - reserveTokens is equivalent to\n\t\t\t\t// !shouldCompact(tokensAfter, effectiveBudget, settings). The live post-retry\n\t\t\t\t// trigger uses provider usage (system/tools included), so this is a best-effort\n\t\t\t\t// boundary; a negative boundary correctly means no estimated result fits.\n\t\t\t\t? { acceptanceTokenBudget: effectiveBudget - settings.reserveTokens }\n\t\t\t\t: undefined;\n\n\t// Planner fallback used when no extension supplies a deletionRequest. Auth is resolved\n\t// lazily here so extension-provided deletion requests keep working offline. Overflow with\n\t// missing auth uses deterministic eviction directly instead of silently no-oping.\n\tconst runPlanner = async (): Promise<ValidatedContextDeletionResult | undefined> => {\n\t\tconst auth = await options.resolvePlannerAuth();\n\t\tif (!auth) {\n\t\t\tif (options.reason === \"overflow\") return runDeterministicContextEviction(preparation.transcript, effectiveBudget);\n\t\t\treturn undefined;\n\t\t}\n\t\treturn runContextCompact(\n\t\t\tpreparation,\n\t\t\tmodel,\n\t\t\tauth.apiKey,\n\t\t\tauth.headers,\n\t\t\toptions.abortController.signal,\n\t\t\tcompactionThinkingLevel,\n\t\t\tladderOptions,\n\t\t);\n\t};\n\n\t// Emit session_before_compact to allow extensions to cancel or provide a deletion request.\n\t// This happens BEFORE any auth resolution so local extension deletion requests work\n\t// without configured API credentials.\n\tlet fromExtension = false;\n\tlet validated: ValidatedContextDeletionResult | undefined;\n\n\tif (this._extensionRunner.hasHandlers(\"session_before_compact\")) {\n\t\t// Deep-clone the preparation only when a before-compact handler actually exists. Extensions\n\t\t// receive an isolated, frozen snapshot so they cannot mutate protection metadata\n\t\t// (protectedEntryIds, entry .protected flags, etc.) on the internal preparation used for\n\t\t// validation. Building it lazily avoids deep-cloning the transcript — largest exactly when\n\t\t// compaction fires — on the common no-extension path.\n\t\tlet extensionPreparation: ContextCompactionPreparation;\n\t\ttry {\n\t\t\textensionPreparation = deepFreeze(structuredClone(preparation));\n\t\t} catch (error) {\n\t\t\t// structuredClone only throws if an entry carries a non-cloneable value (a function or a\n\t\t\t// class instance). Transcript entries are plain data today, so this guards a latent\n\t\t\t// invariant: surface a clear error instead of letting a raw DataCloneError abort an\n\t\t\t// otherwise-viable compaction.\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to snapshot transcript for compaction extensions: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\n\t\tconst hookResult = (await this._extensionRunner.emit({\n\t\t\ttype: \"session_before_compact\",\n\t\t\treason: options.reason,\n\t\t\tparameters,\n\t\t\tpreparation: extensionPreparation,\n\t\t\tbranchEntries: pathEntries,\n\t\t\tsignal: options.abortController.signal,\n\t\t} satisfies SessionBeforeCompactEvent)) as SessionBeforeCompactResult | undefined;\n\n\t\tif (hookResult?.cancel) {\n\t\t\tthrow new Error(\"Compaction cancelled\");\n\t\t}\n\n\t\tif (hookResult?.deletionRequest) {\n\t\t\tconst extensionDeletionRequest = hookResult.deletionRequest as ContextDeletionRequest;\n\t\t\t// Reject empty deletion requests before any side effects (backup, append, rebuild).\n\t\t\tif (!Array.isArray(extensionDeletionRequest.deletions) || extensionDeletionRequest.deletions.length === 0) {\n\t\t\t\tthrow new Error(\"No safe context deletions proposed by extension\");\n\t\t\t}\n\t\t\t// Validate against the internal transcript snapshot, not the extension-facing clone.\n\t\t\t// Auth is NOT resolved here — local extension deletion requests work offline.\n\t\t\tvalidated = validateContextDeletionRequest(extensionDeletionRequest, preparation.transcript);\n\t\t\t// Reject if reconciliation reduced deletions to zero.\n\t\t\tif (validated.deletedTargets.length === 0) {\n\t\t\t\tthrow new Error(\"No safe context deletions proposed by extension\");\n\t\t\t}\n\t\t\tfromExtension = true;\n\t\t}\n\t}\n\n\t// Planner fallback shared by both paths: no before-compact handler at all, or a handler that\n\t// observed without supplying a deletionRequest. Resolves auth lazily; undefined means auth is\n\t// unavailable (auto-mode resolvers), so compaction is a no-op.\n\tif (!validated) {\n\t\tconst plannerResult = await runPlanner();\n\t\tif (!plannerResult) {\n\t\t\treturn undefined;\n\t\t}\n\t\tvalidated = plannerResult;\n\t}\n\n\tif (options.abortController.signal.aborted) {\n\t\tthrow new Error(\"Compaction cancelled\");\n\t}\n\n\tconst backupPath = this.sessionManager.writeBackupSnapshot(options.backupLabel);\n\tconst compactionEntryId = this.sessionManager.appendContextCompaction(\n\t\tvalidated.deletedTargets,\n\t\tvalidated.protectedEntryIds,\n\t\tvalidated.stats,\n\t\tbackupPath,\n\t);\n\tconst sessionContext = this.sessionManager.buildSessionContext();\n\tthis.agent.state.messages = sessionContext.messages;\n\n\tconst result: ContextCompactionResult = {\n\t\t...validated,\n\t\tpromptVersion: 1,\n\t\tparameters,\n\t\t...(backupPath ? { backupPath } : {}),\n\t};\n\n\t// Emit session_compact so extensions can observe the validated result. This is a pure\n\t// observation hook fired AFTER the compaction has been committed (backup written,\n\t// context_compaction entry persisted, active context rebuilt). A misbehaving observer must\n\t// never turn a successful, already-persisted compaction into a reported failure, so any\n\t// throw is routed to the non-fatal extension-error channel and compaction still reports\n\t// success.\n\tconst contextCompactionEntry = this.sessionManager.getEntry(compactionEntryId) as ContextCompactionEntry;\n\ttry {\n\t\tawait this._extensionRunner.emit({\n\t\t\ttype: \"session_compact\",\n\t\t\treason: options.reason,\n\t\t\tparameters,\n\t\t\tresult,\n\t\t\tcontextCompactionEntry,\n\t\t\tfromExtension,\n\t\t} satisfies SessionCompactEvent);\n\t} catch (error) {\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: \"<session_compact>\",\n\t\t\tevent: \"session_compact\",\n\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\tstack: error instanceof Error ? error.stack : undefined,\n\t\t});\n\t}\n\n\treturn result;\n}\n\n/**\n * Manually compact the session context using deletion-only verbatim context compaction.\n * Aborts current agent operation first.\n */\n\nexport async function compact(this: AgentSession, options: Partial<ContextCompactionParameters> = {}): Promise<ContextCompactionResult> {\n\tthis._disconnectFromAgent();\n\tawait this.abort();\n\tthis._compactionAbortController = new AbortController();\n\tthis._emit({ type: \"compaction_start\", reason: \"manual\" });\n\n\ttry {\n\t\tif (!this.model) {\n\t\t\tthrow new Error(formatNoModelSelectedMessage());\n\t\t}\n\n\t\t// Auth is resolved lazily: only called when the planner fallback is needed.\n\t\t// Extensions that provide a deletionRequest work without configured credentials.\n\t\tconst model = this.model;\n\t\tconst result = await this._applyContextVerbatimCompaction({\n\t\t\tresolvePlannerAuth: () => this._getRequiredRequestAuth(model),\n\t\t\tabortController: this._compactionAbortController,\n\t\t\tbackupLabel: \"compact\",\n\t\t\treason: \"manual\",\n\t\t\t...(options.compression_ratio === undefined ? {} : { compression_ratio: options.compression_ratio }),\n\t\t\t...(options.preserve_recent === undefined ? {} : { preserve_recent: options.preserve_recent }),\n\t\t\t...(options.query === undefined ? {} : { query: options.query }),\n\t\t});\n\t\tif (!result) {\n\t\t\tthrow new Error(\"Nothing to compact (session too small)\");\n\t\t}\n\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"manual\",\n\t\t\tresult,\n\t\t\taborted: false,\n\t\t\twillRetry: false,\n\t\t});\n\t\treturn result;\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst aborted = message === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"manual\",\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\terrorMessage: aborted ? undefined : `Compaction failed: ${message}`,\n\t\t});\n\t\tthrow error;\n\t} finally {\n\t\tthis._compactionAbortController = undefined;\n\t\tthis._reconnectToAgent();\n\t}\n}\n\n/**\n * Manually compact the session context by applying validated logical deletions.\n * Retained transcript entries/content blocks stay verbatim; no user prompt text is accepted.\n */\n\nexport async function contextCompact(this: AgentSession): Promise<ContextCompactionResult> {\n\tthis._disconnectFromAgent();\n\tawait this.abort();\n\tthis._compactionAbortController = new AbortController();\n\tthis._emit({ type: \"context_compaction_start\", reason: \"manual\" });\n\n\ttry {\n\t\tif (!this.model) {\n\t\t\tthrow new Error(formatNoModelSelectedMessage());\n\t\t}\n\n\t\t// Auth is resolved lazily: only called when the planner fallback is needed.\n\t\t// Extensions that provide a deletionRequest work without configured credentials.\n\t\tconst model = this.model;\n\t\tconst result = await this._applyContextVerbatimCompaction({\n\t\t\tresolvePlannerAuth: () => this._getRequiredRequestAuth(model),\n\t\t\tabortController: this._compactionAbortController,\n\t\t\tbackupLabel: \"context-compact\",\n\t\t\treason: \"manual\",\n\t\t});\n\t\tif (!result) {\n\t\t\tthrow new Error(\"Nothing to context-compact (session too small)\");\n\t\t}\n\n\t\tthis._emit({\n\t\t\ttype: \"context_compaction_end\",\n\t\t\treason: \"manual\",\n\t\t\tresult,\n\t\t\taborted: false,\n\t\t\twillRetry: false,\n\t\t});\n\t\treturn result;\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst aborted = message === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tthis._emit({\n\t\t\ttype: \"context_compaction_end\",\n\t\t\treason: \"manual\",\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\terrorMessage: aborted ? undefined : `Context compaction failed: ${message}`,\n\t\t});\n\t\tthrow error;\n\t} finally {\n\t\tthis._compactionAbortController = undefined;\n\t\tthis._reconnectToAgent();\n\t}\n}\n\n/**\n * Cancel in-progress compaction (manual or auto).\n */\n\nexport function abortCompaction(this: AgentSession): void {\n\tthis._compactionAbortController?.abort();\n\tthis._autoCompactionAbortController?.abort();\n}\n\n/**\n * Cancel in-progress branch summarization.\n */\n\nexport function abortBranchSummary(this: AgentSession): void {\n\tthis._branchSummaryAbortController?.abort();\n}\n\n/**\n * Check if compaction is needed and run it.\n * Called after agent_end and before prompt submission.\n *\n * Two cases:\n * 1. Overflow: LLM returned context overflow error, remove error message from agent state, compact, auto-retry\n * 2. Threshold: Context over threshold, compact, resume queued active-turn work if present; otherwise wait for user\n *\n * @param assistantMessage The assistant message to check\n * @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true\n */\n\nexport function setAutoCompactionEnabled(this: AgentSession, enabled: boolean): void {\n\tthis.settingsManager.setCompactionEnabled(enabled);\n}\n\n/** Whether auto-compaction is enabled */\n\nexport const agentSessionCompactionMethods = {\n\t_applyContextVerbatimCompaction,\n\tcompact,\n\tcontextCompact,\n\tabortCompaction,\n\tabortBranchSummary,\n\tsetAutoCompactionEnabled,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-compaction.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,8BAA8B,EAAE,MAAM,4BAA4B,CAAC;AAC9H,OAAO,EAQN,KAAK,4BAA4B,EAEjC,KAAK,wBAAwB,EAE7B,MAAM,uBAAuB,CAAC;AA6C/B,wBAAsB,wBAAwB,CAC7C,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,8BAA8B,GACrC,OAAO,CAAC,wBAAwB,GAAG,SAAS,CAAC,CAqF/C;AAED,4DAA4D;AAC5D,wBAAsB,OAAO,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,GAAE,OAAO,CAAC,4BAA4B,CAAM,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAwBxI;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAA4F;AACrJ,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAAiD;AAC7G,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI,CAAwD;AAE5I,eAAO,MAAM,6BAA6B;;;;;;CAAuG,CAAC","sourcesContent":["import { formatNoModelSelectedMessage } from \"./auth-guidance.ts\";\nimport type { AgentSessionInternalSurface as AgentSession, VerbatimCompactionApplyOptions } from \"./agent-session-methods.ts\";\nimport {\n\tgetKeptTailTokenEstimate,\n\tprepareCompactionBoundary,\n\trunVerbatimCompaction,\n\tVERBATIM_COMPACTION_PROMPT_VERSION,\n\tVERBATIM_COMPACTION_STRATEGY,\n\ttype CompactionPlanOptions,\n\ttype VerbatimCompactionDetails,\n\ttype VerbatimCompactionParameters,\n\ttype VerbatimCompactionPreparation,\n\ttype VerbatimCompactionResult,\n\ttype VerbatimCompactionStats,\n} from \"./compaction/index.ts\";\nimport type { SessionBeforeCompactEvent, SessionBeforeCompactResult, SessionCompactEvent } from \"./extensions/index.ts\";\nimport type { CompactionEntry } from \"./session-manager.ts\";\n\nfunction frozenCollectionMutation(): never {\n\tthrow new TypeError(\"Cannot mutate frozen compaction preparation\");\n}\n\nfunction deepFreeze<T>(value: T): T {\n\tif (!value || typeof value !== \"object\" || Object.isFrozen(value)) return value;\n\tif (value instanceof Map) {\n\t\tfor (const [key, nested] of value) { deepFreeze(key); deepFreeze(nested); }\n\t\tObject.defineProperties(value, {\n\t\t\tset: { value: frozenCollectionMutation },\n\t\t\tdelete: { value: frozenCollectionMutation },\n\t\t\tclear: { value: frozenCollectionMutation },\n\t\t});\n\t} else if (value instanceof Set) {\n\t\tfor (const nested of value) deepFreeze(nested);\n\t\tObject.defineProperties(value, {\n\t\t\tadd: { value: frozenCollectionMutation },\n\t\t\tdelete: { value: frozenCollectionMutation },\n\t\t\tclear: { value: frozenCollectionMutation },\n\t\t});\n\t} else {\n\t\tfor (const nested of Object.values(value)) deepFreeze(nested);\n\t}\n\treturn Object.freeze(value);\n}\n\nfunction extensionStats(preparation: VerbatimCompactionPreparation, compactedText: string): VerbatimCompactionStats {\n\tconst linesBefore = preparation.region.lines.length;\n\tconst linesKept = compactedText.split(\"\\n\").length;\n\tconst tokensAfter = Math.ceil(compactedText.length / 4) + getKeptTailTokenEstimate(preparation);\n\treturn {\n\t\tlinesBefore,\n\t\tlinesDeleted: Math.max(0, linesBefore - linesKept),\n\t\tlinesKept,\n\t\trangeCount: 0,\n\t\ttokensBefore: preparation.tokensBefore,\n\t\ttokensAfter,\n\t\tpercentReduction: preparation.tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / preparation.tokensBefore) * 1000) / 10,\n\t};\n}\n\nexport async function _applyVerbatimCompaction(\n\tthis: AgentSession,\n\toptions: VerbatimCompactionApplyOptions,\n): Promise<VerbatimCompactionResult | undefined> {\n\tif (!this.model) throw new Error(formatNoModelSelectedMessage());\n\tconst model = this.model;\n\tconst pathEntries = this.sessionManager.getBranch();\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tconst preparation = prepareCompactionBoundary(pathEntries, settings, {\n\t\t...(options.compression_ratio === undefined ? {} : { compression_ratio: options.compression_ratio }),\n\t\t...(options.preserve_recent === undefined ? {} : { preserve_recent: options.preserve_recent }),\n\t\t...(options.query === undefined ? {} : { query: options.query }),\n\t});\n\tif (!preparation) {\n\t\tif (options.reason === \"overflow\") throw new Error(\"Context compaction found no compactable transcript entries; nothing more was safely deletable\");\n\t\treturn undefined;\n\t}\n\n\tconst plan: CompactionPlanOptions = { streamFn: this.agent.streamFn };\n\tlet fromExtension = false;\n\tlet compacted: { text: string; stats: VerbatimCompactionStats; rung: VerbatimCompactionResult[\"rung\"] } | undefined;\n\n\tif (this._extensionRunner.hasHandlers(\"session_before_compact\")) {\n\t\tlet snapshot: VerbatimCompactionPreparation;\n\t\ttry {\n\t\t\tsnapshot = deepFreeze(structuredClone(preparation));\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Failed to snapshot transcript for compaction extensions: ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\t\tconst hookResult = (await this._extensionRunner.emit({\n\t\t\ttype: \"session_before_compact\",\n\t\t\treason: options.reason,\n\t\t\tparameters: preparation.parameters,\n\t\t\tpreparation: snapshot,\n\t\t\tbranchEntries: pathEntries,\n\t\t\tsignal: options.abortController.signal,\n\t\t} satisfies SessionBeforeCompactEvent)) as SessionBeforeCompactResult | undefined;\n\t\tif (hookResult?.cancel) throw new Error(\"Compaction cancelled\");\n\t\tif (hookResult?.compactedText !== undefined) {\n\t\t\tif (hookResult.compactedText.trim().length === 0) throw new Error(\"No compacted text provided by extension\");\n\t\t\tcompacted = { text: hookResult.compactedText, stats: extensionStats(preparation, hookResult.compactedText), rung: \"extension\" };\n\t\t\tfromExtension = true;\n\t\t}\n\t}\n\n\tif (!compacted) {\n\t\tconst auth = await options.resolvePlannerAuth();\n\t\tif (!auth) throw new Error(\"Compaction provider authentication is unavailable\");\n\t\tcompacted = await runVerbatimCompaction(\n\t\t\tpreparation,\n\t\t\tmodel,\n\t\t\tauth.apiKey,\n\t\t\tauth.headers,\n\t\t\toptions.abortController.signal,\n\t\t\tthis.thinkingLevel,\n\t\t\tplan,\n\t\t);\n\t}\n\tif (options.abortController.signal.aborted) throw new Error(\"Compaction cancelled\");\n\n\tconst backupPath = this.sessionManager.writeBackupSnapshot(options.backupLabel);\n\tconst details: VerbatimCompactionDetails = {\n\t\tstrategy: VERBATIM_COMPACTION_STRATEGY,\n\t\tpromptVersion: VERBATIM_COMPACTION_PROMPT_VERSION,\n\t\tparameters: preparation.parameters,\n\t\tstats: compacted.stats,\n\t\trung: compacted.rung,\n\t\t...(backupPath ? { backupPath } : {}),\n\t};\n\tconst entryId = this.sessionManager.appendCompaction(compacted.text, preparation.firstKeptEntryId, preparation.tokensBefore, details);\n\tthis.agent.state.messages = this.sessionManager.buildSessionContext().messages;\n\tconst result: VerbatimCompactionResult = {\n\t\tcompactedText: compacted.text,\n\t\tfirstKeptEntryId: preparation.firstKeptEntryId,\n\t\ttokensBefore: preparation.tokensBefore,\n\t\tstats: compacted.stats,\n\t\tparameters: preparation.parameters,\n\t\tpromptVersion: VERBATIM_COMPACTION_PROMPT_VERSION,\n\t\trung: compacted.rung,\n\t\t...(backupPath ? { backupPath } : {}),\n\t};\n\tconst compactionEntry = this.sessionManager.getEntry(entryId) as CompactionEntry<VerbatimCompactionDetails>;\n\ttry {\n\t\tawait this._extensionRunner.emit({ type: \"session_compact\", reason: options.reason, parameters: preparation.parameters, result, compactionEntry, fromExtension } satisfies SessionCompactEvent);\n\t} catch (error) {\n\t\tthis._extensionRunner.emitError({ extensionPath: \"<session_compact>\", event: \"session_compact\", error: error instanceof Error ? error.message : String(error), stack: error instanceof Error ? error.stack : undefined });\n\t}\n\treturn result;\n}\n\n/** Persist one verbatim line-subset compaction boundary. */\nexport async function compact(this: AgentSession, options: Partial<VerbatimCompactionParameters> = {}): Promise<VerbatimCompactionResult> {\n\tthis._disconnectFromAgent();\n\tawait this.abort();\n\tthis._compactionAbortController = new AbortController();\n\tthis._emit({ type: \"compaction_start\", reason: \"manual\" });\n\ttry {\n\t\tif (!this.model) throw new Error(formatNoModelSelectedMessage());\n\t\tconst model = this.model;\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: () => this._getRequiredRequestAuth(model), abortController: this._compactionAbortController,\n\t\t\tbackupLabel: \"compact\", reason: \"manual\", ...options,\n\t\t});\n\t\tif (!result) throw new Error(\"Nothing to compact (session too small)\");\n\t\tthis._emit({ type: \"compaction_end\", reason: \"manual\", result, aborted: false, willRetry: false });\n\t\treturn result;\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst aborted = message === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tthis._emit({ type: \"compaction_end\", reason: \"manual\", result: undefined, aborted, willRetry: false, errorMessage: aborted ? undefined : `Compaction failed: ${message}` });\n\t\tthrow error;\n\t} finally {\n\t\tthis._compactionAbortController = undefined;\n\t\tthis._reconnectToAgent();\n\t}\n}\n\nexport function abortCompaction(this: AgentSession): void { this._compactionAbortController?.abort(); this._autoCompactionAbortController?.abort(); }\nexport function abortBranchSummary(this: AgentSession): void { this._branchSummaryAbortController?.abort(); }\nexport function setAutoCompactionEnabled(this: AgentSession, enabled: boolean): void { this.settingsManager.setCompactionEnabled(enabled); }\n\nexport const agentSessionCompactionMethods = { _applyVerbatimCompaction, compact, abortCompaction, abortBranchSummary, setAutoCompactionEnabled };\n"]}
|