@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,163 +0,0 @@
|
|
|
1
|
-
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
-
import { tmpdir } from "node:os";
|
|
3
|
-
import { join } from "node:path";
|
|
4
|
-
import { contextCompactionTargetLabel, contextCompactionTargetReductionPercent, } from "./context-compaction-metrics.js";
|
|
5
|
-
import { getTranscriptCompactionParameters } from "./context-compaction-strategy.js";
|
|
6
|
-
import { isExcludedFromLlmContext } from "./context-transcript-analysis.js";
|
|
7
|
-
const CONTEXT_MANIFEST_MAX_ENTRIES = 80;
|
|
8
|
-
const CONTEXT_MANIFEST_PREVIEW_CHARS = 240;
|
|
9
|
-
export const CONTEXT_COMPACTION_SYSTEM_PROMPT = `You are a context compaction assistant.
|
|
10
|
-
|
|
11
|
-
Your task is to read relevant parts of a conversation between a user and an AI assistant provided via a transcript file, then run a series of tools to apply deletion-only verbatim compaction using the exact context_delete or context_grep_delete format specified.`;
|
|
12
|
-
function contextCompactionFixedPrompt(parameters) {
|
|
13
|
-
const targetLabel = contextCompactionTargetLabel(parameters);
|
|
14
|
-
return `Reference the provided transcript file transcript and use your search/read tools for small inspections, then use context_delete or context_grep_delete for deletions.
|
|
15
|
-
|
|
16
|
-
Compaction records deletion targets, not replacement content.
|
|
17
|
-
For context_delete, use id-only targets: stable entryId values and optional blockIndex values only.
|
|
18
|
-
For context_grep_delete, use a concise literal or regex pattern to select matching entries or blocks; do not paste full transcript entries or content-block bodies.
|
|
19
|
-
Do not summarize, paraphrase, or generate replacement context; those are not accepted compaction outputs.
|
|
20
|
-
Do not mutate retained transcript objects or content.
|
|
21
|
-
Deletion tool calls are the compaction action.
|
|
22
|
-
|
|
23
|
-
Strategy:
|
|
24
|
-
- Start by calling context_compaction_budget to see how much of the context window is full and how much reduction is needed.
|
|
25
|
-
- Spend a few turns exploring with search/read tools to gain high confidence of candidate blocks to remove.
|
|
26
|
-
- Prefer high-confidence exploit actions after that: delete obvious low-value entries via context_grep_delete or context_delete.
|
|
27
|
-
- Use grep deletion for repeated low-value patterns.
|
|
28
|
-
- Use exact id deletion for inspected one-off stale entries.
|
|
29
|
-
- Check context_compaction_budget after deletion batches to track progress.
|
|
30
|
-
- Strict requirement: reduce current context by at least ${targetLabel} before finishing. This is a hard completion gate, not a loose goal.
|
|
31
|
-
- Do not send a final plain-text completion message until context_compaction_budget reports at least ${targetLabel} currentReductionPercent.
|
|
32
|
-
- If the strict ${targetLabel} reduction is not met yet, continue removing low-value message entries or content blocks with context_delete/context_grep_delete.
|
|
33
|
-
- Use the focus query to preserve relevant context: ${JSON.stringify(parameters.query)}.
|
|
34
|
-
|
|
35
|
-
What Gets Deleted:
|
|
36
|
-
- Redundant tool outputs: file reads already acted on, grep/search results already processed, passing test output no longer needed.
|
|
37
|
-
- Exploratory dead ends: irrelevant files read, unhelpful or empty searches.
|
|
38
|
-
- Verbose boilerplate: license headers, import blocks the agent isn't modifying, configuration files read for reference.
|
|
39
|
-
- Superseded information: earlier versions of files that have since been edited, old error messages from bugs already fixed.
|
|
40
|
-
- Stale/superseded image context: image content blocks (shown as type "image" / text "[image]") in older tool results, custom messages, or old user-pasted attachments that the agent has already inspected and no longer needs. Image blocks are large (each costs far more tokens than its "[image]" text preview suggests, as reported by context_compaction_budget imageTokenPercent). When images dominate the context, prefer deleting these stale image content blocks before removing useful recent text. Use context_grep_delete with the literal pattern "[image]" and target "content_block" to find image candidates, then confirm they are stale with context_read_entry before deleting. User text blocks remain protected. Old non-recent user image blocks may be deleted only when non-image user content remains in the same entry; old image-only user entries may be deleted as whole entries only when another task-bearing entry remains.
|
|
41
|
-
|
|
42
|
-
What Survives:
|
|
43
|
-
- Active file paths and line numbers: Any reference the agent might need to navigate.
|
|
44
|
-
- Current error messages: Unresolved bugs and their exact text.
|
|
45
|
-
- Reasoning decisions: Why the agent chose approach A over B. An agent's chain of thought (why it chose this file, what pattern it noticed, what fix it decided on) carries more information-per-token than the raw grep output or file content that informed those decisions.
|
|
46
|
-
- Recent tool calls and their results: The last 3-5 operations.
|
|
47
|
-
- User instructions: The original task and any clarifications.
|
|
48
|
-
- Task-relevant images: Images that are part of the active user task (for example, a screenshot the user just asked about, or the most recent image-bearing result the agent is still acting on). Recent user images and recent tool results are protected by preserve_recent, so do not delete images the agent still needs.
|
|
49
|
-
|
|
50
|
-
Conditionally Deleted:
|
|
51
|
-
- Old reasoning decisions: If there is nothing else to remove and the target reduction is not met, you may omit signed reasoning only as a complete logical assistant tool-use turn sequence. Each provider-visible user-like input starts a turn: a non-empty user/custom input (non-whitespace text or an image), a context-eligible bash execution, or a non-empty branch summary. Empty/whitespace-only user or custom inputs and empty branch summaries do not establish a boundary; whitespace-only branch summaries do because their wrapper is visible. Assistant messages and intervening tool results remain in that turn until the next visible user-like input. Never delete any thinking/redacted_thinking-bearing assistant entry from the current final logical turn; a trailing visible input without an assistant response makes the preceding assistant turn historical. In a completed historical turn, retain all thinking/redacted_thinking-bearing assistant entries or delete all of them as whole entries; never retain a proper subset. Never delete individual content blocks from a retained thinking-bearing assistant message.
|
|
52
|
-
|
|
53
|
-
<output_format>
|
|
54
|
-
Call the context_delete tool one or more times with deletion targets in this shape:
|
|
55
|
-
{ "deletions": [{ "kind": "entry", "entryId": "..." }] }
|
|
56
|
-
|
|
57
|
-
For content-block deletions, use:
|
|
58
|
-
{ "kind": "content_block", "entryId": "...", "blockIndex": 0 }
|
|
59
|
-
|
|
60
|
-
The tool applies and validates deletion targets immediately. You can continue calling it for additional deletions if useful.
|
|
61
|
-
|
|
62
|
-
For guarded bulk deletion by text match, call context_grep_delete with a literal pattern or regex. It removes valid matching context, silently ignores candidates that validation does not allow so they are not counted as removals, enforces a per-call maxMatches safety cap and optional expectedMatchCount, and validates through the same tool-call/tool-result safety rules. maxMatches only limits one tool call; there is no cumulative cap across corrected or repeated deletion calls.
|
|
63
|
-
|
|
64
|
-
The full transcript is available as a JSONL file path in the prompt, but do NOT try to load the whole file into context. Use context_search_transcript to find candidate entry IDs and context_read_entry to read only small slices (for example maxChars 1000-4000) before deleting.
|
|
65
|
-
|
|
66
|
-
When the strict ${targetLabel} reduction requirement is met, reply with a brief plain-text completion message. Do not include deletion target IDs outside tool calls.
|
|
67
|
-
</output_format>`;
|
|
68
|
-
}
|
|
69
|
-
function truncateForPrompt(text, maxChars) {
|
|
70
|
-
if (text.length <= maxChars)
|
|
71
|
-
return text;
|
|
72
|
-
return `${text.slice(0, maxChars)}\n[... ${text.length - maxChars} more characters omitted from context compaction prompt]`;
|
|
73
|
-
}
|
|
74
|
-
function transcriptEntryFilePayload(entry) {
|
|
75
|
-
return {
|
|
76
|
-
entryId: entry.entryId,
|
|
77
|
-
entryType: entry.entryType,
|
|
78
|
-
role: entry.role,
|
|
79
|
-
protected: entry.protected,
|
|
80
|
-
tokenEstimate: entry.tokenEstimate,
|
|
81
|
-
toolCallIds: entry.toolCallIds,
|
|
82
|
-
toolResultFor: entry.toolResultFor,
|
|
83
|
-
text: entry.text,
|
|
84
|
-
contentBlocks: entry.contentBlocks.map((block) => ({
|
|
85
|
-
blockIndex: block.blockIndex,
|
|
86
|
-
type: block.type,
|
|
87
|
-
protected: block.protected,
|
|
88
|
-
toolCallId: block.toolCallId,
|
|
89
|
-
tokenEstimate: block.tokenEstimate,
|
|
90
|
-
text: block.text,
|
|
91
|
-
})),
|
|
92
|
-
};
|
|
93
|
-
}
|
|
94
|
-
export function writeContextCompactionTranscriptFile(transcript) {
|
|
95
|
-
const directory = mkdtempSync(join(tmpdir(), "atomic-context-transcript-"));
|
|
96
|
-
const path = join(directory, "transcript.jsonl");
|
|
97
|
-
const lines = transcript.entries
|
|
98
|
-
.filter((entry) => !isExcludedFromLlmContext(entry.message))
|
|
99
|
-
.map((entry) => JSON.stringify(transcriptEntryFilePayload(entry)));
|
|
100
|
-
writeFileSync(path, `${lines.join("\n")}\n`, "utf8");
|
|
101
|
-
return {
|
|
102
|
-
path,
|
|
103
|
-
cleanup: () => rmSync(directory, { recursive: true, force: true }),
|
|
104
|
-
};
|
|
105
|
-
}
|
|
106
|
-
function contextCompactionTranscriptManifest(transcript, transcriptFilePath) {
|
|
107
|
-
const eligibleEntries = transcript.entries.filter((entry) => !isExcludedFromLlmContext(entry.message));
|
|
108
|
-
const selectedEntryIds = new Set();
|
|
109
|
-
const selectedEntries = [];
|
|
110
|
-
const addEntry = (entry) => {
|
|
111
|
-
if (selectedEntryIds.has(entry.entryId) || selectedEntries.length >= CONTEXT_MANIFEST_MAX_ENTRIES)
|
|
112
|
-
return;
|
|
113
|
-
selectedEntryIds.add(entry.entryId);
|
|
114
|
-
selectedEntries.push(entry);
|
|
115
|
-
};
|
|
116
|
-
for (const entry of eligibleEntries.filter((entry) => entry.protected)) {
|
|
117
|
-
addEntry(entry);
|
|
118
|
-
}
|
|
119
|
-
for (const entry of [...eligibleEntries]
|
|
120
|
-
.filter((entry) => !entry.protected)
|
|
121
|
-
.sort((left, right) => right.tokenEstimate - left.tokenEstimate)) {
|
|
122
|
-
addEntry(entry);
|
|
123
|
-
}
|
|
124
|
-
selectedEntries.sort((left, right) => eligibleEntries.indexOf(left) - eligibleEntries.indexOf(right));
|
|
125
|
-
return {
|
|
126
|
-
transcriptFilePath,
|
|
127
|
-
transcriptFileFormat: "jsonl: one compactable transcript entry per line with full text and contentBlocks text",
|
|
128
|
-
totalEntries: eligibleEntries.length,
|
|
129
|
-
manifestEntries: selectedEntries.length,
|
|
130
|
-
omittedEntries: Math.max(0, eligibleEntries.length - selectedEntries.length),
|
|
131
|
-
tokensBefore: transcript.tokensBefore,
|
|
132
|
-
protectedEntryIds: transcript.protectedEntryIds,
|
|
133
|
-
entries: selectedEntries.map((entry) => ({
|
|
134
|
-
entryId: entry.entryId,
|
|
135
|
-
role: entry.role,
|
|
136
|
-
protected: entry.protected,
|
|
137
|
-
tokenEstimate: entry.tokenEstimate,
|
|
138
|
-
toolCallIds: entry.toolCallIds,
|
|
139
|
-
toolResultFor: entry.toolResultFor,
|
|
140
|
-
contentBlockCount: entry.contentBlocks.length,
|
|
141
|
-
contentBlocks: entry.contentBlocks.map((block) => ({
|
|
142
|
-
blockIndex: block.blockIndex,
|
|
143
|
-
type: block.type,
|
|
144
|
-
protected: block.protected,
|
|
145
|
-
toolCallId: block.toolCallId,
|
|
146
|
-
tokenEstimate: block.tokenEstimate,
|
|
147
|
-
})),
|
|
148
|
-
preview: truncateForPrompt(entry.text, CONTEXT_MANIFEST_PREVIEW_CHARS),
|
|
149
|
-
})),
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
function contextCompactionParametersPrompt(parameters) {
|
|
153
|
-
return `\n<compaction-parameters>\n${JSON.stringify({
|
|
154
|
-
compression_ratio: parameters.compression_ratio,
|
|
155
|
-
preserve_recent: parameters.preserve_recent,
|
|
156
|
-
query: parameters.query,
|
|
157
|
-
target_reduction_percent: contextCompactionTargetReductionPercent(parameters),
|
|
158
|
-
}, null, 2)}\n</compaction-parameters>`;
|
|
159
|
-
}
|
|
160
|
-
export function buildContextCompactionPrompt(transcript, transcriptFilePath = "<transcript file will be written during context compaction>", parameters = getTranscriptCompactionParameters(transcript)) {
|
|
161
|
-
return `${contextCompactionFixedPrompt(parameters)}${contextCompactionParametersPrompt(parameters)}\n\n<transcript-file>\n${transcriptFilePath}\n</transcript-file>\n\n<context-manifest>\n${JSON.stringify(contextCompactionTranscriptManifest(transcript, transcriptFilePath), null, 2)}\n</context-manifest>`;
|
|
162
|
-
}
|
|
163
|
-
//# sourceMappingURL=context-compaction-prompt.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"context-compaction-prompt.js","sourceRoot":"","sources":["../../../src/core/compaction/context-compaction-prompt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;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,UAAiC,EACjC,kBAAkB,GAAG,6DAA6D,EAClF,UAAU,GAAgC,iCAAiC,CAAC,UAAU,CAAC;IAEvF,OAAO,GAAG,4BAA4B,CAAC,UAAU,CAAC,GAAG,iCAAiC,CAAC,UAAU,CAAC,0BAA0B,kBAAkB,+CAA+C,IAAI,CAAC,SAAS,CAAC,mCAAmC,CAAC,UAAU,EAAE,kBAAkB,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,uBAAuB,CAAC;AAClT,CAAC","sourcesContent":["import { mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type {\n\tCompactableTranscript,\n\tCompactableTranscriptEntry,\n\tContextCompactionParameters,\n} from \"./context-compaction-types.ts\";\nimport {\n\tcontextCompactionTargetLabel,\n\tcontextCompactionTargetReductionPercent,\n} from \"./context-compaction-metrics.ts\";\nimport { getTranscriptCompactionParameters } from \"./context-compaction-strategy.ts\";\nimport { isExcludedFromLlmContext } from \"./context-transcript-analysis.ts\";\n\nconst CONTEXT_MANIFEST_MAX_ENTRIES = 80;\nconst CONTEXT_MANIFEST_PREVIEW_CHARS = 240;\n\nexport const CONTEXT_COMPACTION_SYSTEM_PROMPT = `You are a context compaction assistant.\n\nYour task is to read relevant parts of a conversation between a user and an AI assistant provided via a transcript file, then run a series of tools to apply deletion-only verbatim compaction using the exact context_delete or context_grep_delete format specified.`;\n\nfunction contextCompactionFixedPrompt(parameters: ContextCompactionParameters): string {\n\tconst targetLabel = contextCompactionTargetLabel(parameters);\n\treturn `Reference the provided transcript file transcript and use your search/read tools for small inspections, then use context_delete or context_grep_delete for deletions.\n\nCompaction records deletion targets, not replacement content.\nFor context_delete, use id-only targets: stable entryId values and optional blockIndex values only.\nFor context_grep_delete, use a concise literal or regex pattern to select matching entries or blocks; do not paste full transcript entries or content-block bodies.\nDo not summarize, paraphrase, or generate replacement context; those are not accepted compaction outputs.\nDo not mutate retained transcript objects or content.\nDeletion tool calls are the compaction action.\n\nStrategy:\n- Start by calling context_compaction_budget to see how much of the context window is full and how much reduction is needed.\n- Spend a few turns exploring with search/read tools to gain high confidence of candidate blocks to remove.\n- Prefer high-confidence exploit actions after that: delete obvious low-value entries via context_grep_delete or context_delete.\n- Use grep deletion for repeated low-value patterns.\n- Use exact id deletion for inspected one-off stale entries.\n- Check context_compaction_budget after deletion batches to track progress.\n- Strict requirement: reduce current context by at least ${targetLabel} before finishing. This is a hard completion gate, not a loose goal.\n- Do not send a final plain-text completion message until context_compaction_budget reports at least ${targetLabel} currentReductionPercent.\n- If the strict ${targetLabel} reduction is not met yet, continue removing low-value message entries or content blocks with context_delete/context_grep_delete.\n- Use the focus query to preserve relevant context: ${JSON.stringify(parameters.query)}.\n\nWhat Gets Deleted:\n- Redundant tool outputs: file reads already acted on, grep/search results already processed, passing test output no longer needed.\n- Exploratory dead ends: irrelevant files read, unhelpful or empty searches.\n- Verbose boilerplate: license headers, import blocks the agent isn't modifying, configuration files read for reference.\n- Superseded information: earlier versions of files that have since been edited, old error messages from bugs already fixed.\n- Stale/superseded image context: image content blocks (shown as type \"image\" / text \"[image]\") in older tool results, custom messages, or old user-pasted attachments that the agent has already inspected and no longer needs. Image blocks are large (each costs far more tokens than its \"[image]\" text preview suggests, as reported by context_compaction_budget imageTokenPercent). When images dominate the context, prefer deleting these stale image content blocks before removing useful recent text. Use context_grep_delete with the literal pattern \"[image]\" and target \"content_block\" to find image candidates, then confirm they are stale with context_read_entry before deleting. User text blocks remain protected. Old non-recent user image blocks may be deleted only when non-image user content remains in the same entry; old image-only user entries may be deleted as whole entries only when another task-bearing entry remains.\n\nWhat Survives:\n- Active file paths and line numbers: Any reference the agent might need to navigate.\n- Current error messages: Unresolved bugs and their exact text.\n- Reasoning decisions: Why the agent chose approach A over B. An agent's chain of thought (why it chose this file, what pattern it noticed, what fix it decided on) carries more information-per-token than the raw grep output or file content that informed those decisions.\n- Recent tool calls and their results: The last 3-5 operations.\n- User instructions: The original task and any clarifications.\n- Task-relevant images: Images that are part of the active user task (for example, a screenshot the user just asked about, or the most recent image-bearing result the agent is still acting on). Recent user images and recent tool results are protected by preserve_recent, so do not delete images the agent still needs.\n\nConditionally Deleted:\n- Old reasoning decisions: If there is nothing else to remove and the target reduction is not met, you may omit signed reasoning only as a complete logical assistant tool-use turn sequence. Each provider-visible user-like input starts a turn: a non-empty user/custom input (non-whitespace text or an image), a context-eligible bash execution, or a non-empty branch summary. Empty/whitespace-only user or custom inputs and empty branch summaries do not establish a boundary; whitespace-only branch summaries do because their wrapper is visible. Assistant messages and intervening tool results remain in that turn until the next visible user-like input. Never delete any thinking/redacted_thinking-bearing assistant entry from the current final logical turn; a trailing visible input without an assistant response makes the preceding assistant turn historical. In a completed historical turn, retain all thinking/redacted_thinking-bearing assistant entries or delete all of them as whole entries; never retain a proper subset. Never delete individual content blocks from a retained thinking-bearing assistant message.\n\n<output_format>\nCall the context_delete tool one or more times with deletion targets in this shape:\n{ \"deletions\": [{ \"kind\": \"entry\", \"entryId\": \"...\" }] }\n\nFor content-block deletions, use:\n{ \"kind\": \"content_block\", \"entryId\": \"...\", \"blockIndex\": 0 }\n\nThe tool applies and validates deletion targets immediately. You can continue calling it for additional deletions if useful.\n\nFor guarded bulk deletion by text match, call context_grep_delete with a literal pattern or regex. It removes valid matching context, silently ignores candidates that validation does not allow so they are not counted as removals, enforces a per-call maxMatches safety cap and optional expectedMatchCount, and validates through the same tool-call/tool-result safety rules. maxMatches only limits one tool call; there is no cumulative cap across corrected or repeated deletion calls.\n\nThe full transcript is available as a JSONL file path in the prompt, but do NOT try to load the whole file into context. Use context_search_transcript to find candidate entry IDs and context_read_entry to read only small slices (for example maxChars 1000-4000) before deleting.\n\nWhen the strict ${targetLabel} reduction requirement is met, reply with a brief plain-text completion message. Do not include deletion target IDs outside tool calls.\n</output_format>`;\n}\n\nfunction truncateForPrompt(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}\\n[... ${text.length - maxChars} more characters omitted from context compaction prompt]`;\n}\n\nfunction transcriptEntryFilePayload(entry: CompactableTranscriptEntry): unknown {\n\treturn {\n\t\tentryId: entry.entryId,\n\t\tentryType: entry.entryType,\n\t\trole: entry.role,\n\t\tprotected: entry.protected,\n\t\ttokenEstimate: entry.tokenEstimate,\n\t\ttoolCallIds: entry.toolCallIds,\n\t\ttoolResultFor: entry.toolResultFor,\n\t\ttext: entry.text,\n\t\tcontentBlocks: entry.contentBlocks.map((block) => ({\n\t\t\tblockIndex: block.blockIndex,\n\t\t\ttype: block.type,\n\t\t\tprotected: block.protected,\n\t\t\ttoolCallId: block.toolCallId,\n\t\t\ttokenEstimate: block.tokenEstimate,\n\t\t\ttext: block.text,\n\t\t})),\n\t};\n}\n\nexport interface ContextCompactionTranscriptFile {\n\tpath: string;\n\tcleanup(): void;\n}\n\nexport function writeContextCompactionTranscriptFile(transcript: CompactableTranscript): ContextCompactionTranscriptFile {\n\tconst directory = mkdtempSync(join(tmpdir(), \"atomic-context-transcript-\"));\n\tconst path = join(directory, \"transcript.jsonl\");\n\tconst lines = transcript.entries\n\t\t.filter((entry) => !isExcludedFromLlmContext(entry.message))\n\t\t.map((entry) => JSON.stringify(transcriptEntryFilePayload(entry)));\n\twriteFileSync(path, `${lines.join(\"\\n\")}\\n`, \"utf8\");\n\treturn {\n\t\tpath,\n\t\tcleanup: () => rmSync(directory, { recursive: true, force: true }),\n\t};\n}\n\nfunction contextCompactionTranscriptManifest(transcript: CompactableTranscript, transcriptFilePath: string): unknown {\n\tconst eligibleEntries = transcript.entries.filter((entry) => !isExcludedFromLlmContext(entry.message));\n\tconst selectedEntryIds = new Set<string>();\n\tconst selectedEntries: CompactableTranscriptEntry[] = [];\n\tconst addEntry = (entry: CompactableTranscriptEntry): void => {\n\t\tif (selectedEntryIds.has(entry.entryId) || selectedEntries.length >= CONTEXT_MANIFEST_MAX_ENTRIES) return;\n\t\tselectedEntryIds.add(entry.entryId);\n\t\tselectedEntries.push(entry);\n\t};\n\n\tfor (const entry of eligibleEntries.filter((entry) => entry.protected)) {\n\t\taddEntry(entry);\n\t}\n\tfor (const entry of [...eligibleEntries]\n\t\t.filter((entry) => !entry.protected)\n\t\t.sort((left, right) => right.tokenEstimate - left.tokenEstimate)) {\n\t\taddEntry(entry);\n\t}\n\tselectedEntries.sort((left, right) => eligibleEntries.indexOf(left) - eligibleEntries.indexOf(right));\n\n\treturn {\n\t\ttranscriptFilePath,\n\t\ttranscriptFileFormat: \"jsonl: one compactable transcript entry per line with full text and contentBlocks text\",\n\t\ttotalEntries: eligibleEntries.length,\n\t\tmanifestEntries: selectedEntries.length,\n\t\tomittedEntries: Math.max(0, eligibleEntries.length - selectedEntries.length),\n\t\ttokensBefore: transcript.tokensBefore,\n\t\tprotectedEntryIds: transcript.protectedEntryIds,\n\t\tentries: selectedEntries.map((entry) => ({\n\t\t\tentryId: entry.entryId,\n\t\t\trole: entry.role,\n\t\t\tprotected: entry.protected,\n\t\t\ttokenEstimate: entry.tokenEstimate,\n\t\t\ttoolCallIds: entry.toolCallIds,\n\t\t\ttoolResultFor: entry.toolResultFor,\n\t\t\tcontentBlockCount: entry.contentBlocks.length,\n\t\t\tcontentBlocks: entry.contentBlocks.map((block) => ({\n\t\t\t\tblockIndex: block.blockIndex,\n\t\t\t\ttype: block.type,\n\t\t\t\tprotected: block.protected,\n\t\t\t\ttoolCallId: block.toolCallId,\n\t\t\t\ttokenEstimate: block.tokenEstimate,\n\t\t\t})),\n\t\t\tpreview: truncateForPrompt(entry.text, CONTEXT_MANIFEST_PREVIEW_CHARS),\n\t\t})),\n\t};\n}\n\nfunction contextCompactionParametersPrompt(parameters: ContextCompactionParameters): string {\n\treturn `\\n<compaction-parameters>\\n${JSON.stringify(\n\t\t{\n\t\t\tcompression_ratio: parameters.compression_ratio,\n\t\t\tpreserve_recent: parameters.preserve_recent,\n\t\t\tquery: parameters.query,\n\t\t\ttarget_reduction_percent: contextCompactionTargetReductionPercent(parameters),\n\t\t},\n\t\tnull,\n\t\t2,\n\t)}\\n</compaction-parameters>`;\n}\n\nexport function buildContextCompactionPrompt(\n\ttranscript: CompactableTranscript,\n\ttranscriptFilePath = \"<transcript file will be written during context compaction>\",\n\tparameters: ContextCompactionParameters = getTranscriptCompactionParameters(transcript),\n): string {\n\treturn `${contextCompactionFixedPrompt(parameters)}${contextCompactionParametersPrompt(parameters)}\\n\\n<transcript-file>\\n${transcriptFilePath}\\n</transcript-file>\\n\\n<context-manifest>\\n${JSON.stringify(contextCompactionTranscriptManifest(transcript, transcriptFilePath), null, 2)}\\n</context-manifest>`;\n}\n"]}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { type ThinkingLevel } from "@earendil-works/pi-agent-core";
|
|
2
|
-
import type { Api, Model } from "@earendil-works/pi-ai/compat";
|
|
3
|
-
import type { ContextCompactionPreparation, ValidatedContextDeletionResult } from "./context-compaction-types.ts";
|
|
4
|
-
export declare const CONTEXT_COMPACTION_MAX_TURNS = 50;
|
|
5
|
-
export declare const CONTEXT_COMPACTION_MAX_PLANNER_NUDGES = 50;
|
|
6
|
-
export interface ContextCompactionLadderOptions {
|
|
7
|
-
acceptanceTokenBudget?: number;
|
|
8
|
-
criticalEvictionTokenBudget?: number;
|
|
9
|
-
}
|
|
10
|
-
export declare function contextCompact(preparation: ContextCompactionPreparation, model: Model<Api>, apiKey: string, headers?: Record<string, string>, signal?: AbortSignal, thinkingLevel?: ThinkingLevel, ladder?: ContextCompactionLadderOptions): Promise<ValidatedContextDeletionResult>;
|
|
11
|
-
//# sourceMappingURL=context-compaction-runner.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"context-compaction-runner.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/context-compaction-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4B,KAAK,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC7F,OAAO,KAAK,EAAE,GAAG,EAAoB,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAGjF,OAAO,KAAK,EAGX,4BAA4B,EAC5B,8BAA8B,EAC9B,MAAM,+BAA+B,CAAC;AA+BvC,eAAO,MAAM,4BAA4B,KAAK,CAAC;AAC/C,eAAO,MAAM,qCAAqC,KAAK,CAAC;AAExD,MAAM,WAAW,8BAA8B;IAC9C,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,2BAA2B,CAAC,EAAE,MAAM,CAAC;CACrC;AAyQD,wBAAsB,cAAc,CACnC,WAAW,EAAE,4BAA4B,EACzC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAChC,MAAM,CAAC,EAAE,WAAW,EACpB,aAAa,GAAE,aAAqB,EACpC,MAAM,CAAC,EAAE,8BAA8B,GACrC,OAAO,CAAC,8BAA8B,CAAC,CAyDzC","sourcesContent":["import { Agent, type AgentMessage, type ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, Model } from \"@earendil-works/pi-ai/compat\";\nimport { createAssistantMessageEventStream, isContextOverflow, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport { formatCopilotProviderError } from \"../copilot-errors.ts\";\nimport type {\n\tCompactableTranscript,\n\tContextCompactionParameters,\n\tContextCompactionPreparation,\n\tValidatedContextDeletionResult,\n} from \"./context-compaction-types.ts\";\nimport { CONTEXT_COMPACTION_AUTO_QUERY } from \"./context-compaction-types.ts\";\nimport {\n\tcreateContextCompactionBudgetDetails,\n\tcontextCompactionProgressKey,\n\tcontextCompactionProgressPercent,\n\tcontextCompactionTargetLabel,\n\tcontextCompactionTargetMet,\n\tformatErrorMessage,\n} from \"./context-compaction-metrics.ts\";\nimport { getTranscriptCompactionParameters, normalizeContextCompactionParameters } from \"./context-compaction-strategy.ts\";\nimport {\n\tCONTEXT_COMPACTION_BUDGET_TOOL_NAME,\n\tCONTEXT_DELETE_TOOL_NAME,\n\tCONTEXT_GREP_DELETE_TOOL_NAME,\n\tCONTEXT_READ_ENTRY_TOOL_NAME,\n\tCONTEXT_SEARCH_TRANSCRIPT_TOOL_NAME,\n} from \"./context-deletion-tool-definitions.ts\";\nimport { createContextDeletionTool } from \"./context-deletion-tools.ts\";\nimport {\n\tbuildContextCompactionPrompt,\n\tCONTEXT_COMPACTION_SYSTEM_PROMPT,\n\twriteContextCompactionTranscriptFile,\n} from \"./context-compaction-prompt.ts\";\nimport {\n\tCONTEXT_COMPACTION_CRITICAL_OVERFLOW_PROMPT,\n\tcriticalCompactionParameters,\n\trelaxTranscriptForCriticalEviction,\n} from \"./context-compaction-critical.ts\";\nimport { runDeterministicContextEviction } from \"./context-compaction-eviction.ts\";\n\nexport const CONTEXT_COMPACTION_MAX_TURNS = 50;\nexport const CONTEXT_COMPACTION_MAX_PLANNER_NUDGES = 50;\n\nexport interface ContextCompactionLadderOptions {\n\tacceptanceTokenBudget?: number;\n\tcriticalEvictionTokenBudget?: number;\n}\n\ninterface ContextDeletionAssistantOptions {\n\tpromptSuffix?: string;\n\tacceptanceTokenBudget?: number;\n}\n\nfunction createContextCompactionTargetNudgeMessage(\n\tresult: ValidatedContextDeletionResult | undefined,\n\tparameters: ContextCompactionParameters,\n): AgentMessage {\n\tconst currentReductionPercent = contextCompactionProgressPercent(result);\n\tconst targetLabel = contextCompactionTargetLabel(parameters);\n\tconst tokensToDelete = result\n\t\t? createContextCompactionBudgetDetails(result.stats, 0, undefined, parameters, 0, 0).tokensToDeleteForTarget\n\t\t: undefined;\n\tconst remainingText = tokensToDelete !== undefined ? ` Delete about ${tokensToDelete} more token(s) if safe candidates exist.` : \"\";\n\treturn {\n\t\trole: \"user\",\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `The strict ${targetLabel} context-reduction requirement is not met yet; current validated reduction is ${currentReductionPercent}%.${remainingText} Continue removing low-value message entries or message content blocks using ${CONTEXT_DELETE_TOOL_NAME} or ${CONTEXT_GREP_DELETE_TOOL_NAME}. Use the focus query ${JSON.stringify(parameters.query)} to preserve relevant context. Call ${CONTEXT_COMPACTION_BUDGET_TOOL_NAME} to verify progress, and do not provide a final answer until the validated reduction is at least ${targetLabel}.`,\n\t\t\t},\n\t\t],\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createContextCompactionAssistantMessage(\n\tmodel: Model<Api>,\n\tcontent: AssistantMessage[\"content\"],\n\tstopReason: AssistantMessage[\"stopReason\"],\n\terrorMessage?: string,\n): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent,\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason,\n\t\t...(errorMessage !== undefined ? { errorMessage } : {}),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createContextCompactionStopStream(model: Model<Api>, text: string) {\n\tconst stream = createAssistantMessageEventStream();\n\tqueueMicrotask(() => {\n\t\tconst message = createContextCompactionAssistantMessage(model, [{ type: \"text\", text }], \"stop\");\n\t\tstream.push({ type: \"done\", reason: \"stop\", message });\n\t\tstream.end(message);\n\t});\n\treturn stream;\n}\n\nfunction isContextCompactionOverflowError(model: Model<Api>, errorMessage: string): boolean {\n\treturn isContextOverflow(createContextCompactionAssistantMessage(model, [], \"error\", errorMessage), model.contextWindow);\n}\n\nfunction feasibleAccepted(\n\tresult: ValidatedContextDeletionResult | undefined,\n\tacceptanceTokenBudget: number | undefined,\n): result is ValidatedContextDeletionResult {\n\treturn (\n\t\tacceptanceTokenBudget !== undefined &&\n\t\tresult !== undefined &&\n\t\tresult.deletedTargets.length > 0 &&\n\t\tresult.stats.tokensAfter <= acceptanceTokenBudget\n\t);\n}\n\nfunction acceptedWithinRun(\n\tresult: ValidatedContextDeletionResult | undefined,\n\tparameters: ContextCompactionParameters,\n\tacceptanceTokenBudget: number | undefined,\n): result is ValidatedContextDeletionResult {\n\tif (acceptanceTokenBudget !== undefined) return feasibleAccepted(result, acceptanceTokenBudget);\n\treturn contextCompactionTargetMet(result, parameters);\n}\n\nfunction targetMetAcceptedForLadder(\n\trun: ContextDeletionRun,\n\tparameters: ContextCompactionParameters,\n\tladder: ContextCompactionLadderOptions | undefined,\n): run is ContextDeletionRun & { validatedResult: ValidatedContextDeletionResult } {\n\tif (!hasMetContextCompactionTarget(run, parameters)) return false;\n\tconst overflowBudget = ladder?.criticalEvictionTokenBudget;\n\treturn overflowBudget === undefined || run.validatedResult.stats.tokensAfter <= overflowBudget;\n}\n\ninterface ContextDeletionRun {\n\tvalidatedResult: ValidatedContextDeletionResult | undefined;\n\tlastToolError: string | undefined;\n\tproviderError: string | undefined;\n\tproviderOverflow: boolean;\n}\n\nasync function runContextDeletionAssistant(\n\tinputTranscript: CompactableTranscript,\n\tmodel: Model<Api>,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel: ThinkingLevel = \"off\",\n\tparameters: ContextCompactionParameters = getTranscriptCompactionParameters(inputTranscript),\n\toptions: ContextDeletionAssistantOptions = {},\n): Promise<ContextDeletionRun> {\n\tconst transcript: CompactableTranscript = { ...inputTranscript, parameters };\n\tconst maxTokens = model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY;\n\tif (signal?.aborted) throw new Error(\"Context compaction failed: Request was aborted\");\n\tconst transcriptFile = writeContextCompactionTranscriptFile(transcript);\n\tconst promptText = buildContextCompactionPrompt(transcript, transcriptFile.path, parameters) + (options.promptSuffix ?? \"\");\n\tconst promptMessage: AgentMessage = {\n\t\trole: \"user\",\n\t\tcontent: [{ type: \"text\", text: promptText }],\n\t\ttimestamp: Date.now(),\n\t};\n\tconst deletionTool = createContextDeletionTool(transcript, { contextWindow: model.contextWindow, ...parameters });\n\tlet providerTurnCount = 0;\n\tconst agent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: CONTEXT_COMPACTION_SYSTEM_PROMPT,\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: deletionTool.tools,\n\t\t},\n\t\ttoolExecution: \"parallel\",\n\t\tstreamFn: async (requestModel, context, streamOptions) => {\n\t\t\tconst currentResult = deletionTool.getValidatedResult();\n\t\t\tif (acceptedWithinRun(currentResult, parameters, options.acceptanceTokenBudget)) {\n\t\t\t\treturn createContextCompactionStopStream(\n\t\t\t\t\trequestModel,\n\t\t\t\t\t`Reached an acceptable context-reduction result (${currentResult.stats.percentReduction}%, ${currentResult.stats.tokensAfter} token(s) after deletion); using the validated deletions recorded so far.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (providerTurnCount >= CONTEXT_COMPACTION_MAX_TURNS) {\n\t\t\t\treturn createContextCompactionStopStream(\n\t\t\t\t\trequestModel,\n\t\t\t\t\t`Reached the context compaction turn cap (${CONTEXT_COMPACTION_MAX_TURNS}); using the validated deletions recorded so far.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tproviderTurnCount += 1;\n\t\t\treturn streamSimple(requestModel, context, {\n\t\t\t\t...streamOptions,\n\t\t\t\tmaxTokens,\n\t\t\t\tapiKey,\n\t\t\t\theaders: headers ?? streamOptions?.headers,\n\t\t\t});\n\t\t},\n\t});\n\n\tlet lastNudgedProgressKey: string | undefined;\n\tlet nudgeCount = 0;\n\tconst unsubscribeNudge = agent.subscribe((event, eventSignal) => {\n\t\tif (event.type !== \"turn_end\" || signal?.aborted || eventSignal.aborted) return;\n\t\tif (event.message.role !== \"assistant\") return;\n\t\tif (event.message.stopReason === \"error\" || event.message.stopReason === \"aborted\") return;\n\t\tif (event.message.content.some((content) => content.type === \"toolCall\")) return;\n\t\tif (nudgeCount >= CONTEXT_COMPACTION_MAX_PLANNER_NUDGES) return;\n\t\tconst currentResult = deletionTool.getValidatedResult();\n\t\tif (acceptedWithinRun(currentResult, parameters, options.acceptanceTokenBudget)) return;\n\t\tconst progressKey = contextCompactionProgressKey(currentResult);\n\t\tif (progressKey === lastNudgedProgressKey) return;\n\t\tlastNudgedProgressKey = progressKey;\n\t\tnudgeCount += 1;\n\t\tagent.followUp(createContextCompactionTargetNudgeMessage(currentResult, parameters));\n\t});\n\n\tconst abortOnSignal = () => agent.abort();\n\tsignal?.addEventListener(\"abort\", abortOnSignal, { once: true });\n\ttry {\n\t\tawait agent.prompt(promptMessage);\n\t} catch (error) {\n\t\tif (signal?.aborted) throw new Error(\"Context compaction failed: Request was aborted\");\n\t\tconst errorMessage = formatErrorMessage(error);\n\t\tconst formattedErrorMessage = formatCopilotProviderError(model.provider, errorMessage);\n\t\tif (isContextCompactionOverflowError(model, errorMessage)) {\n\t\t\treturn {\n\t\t\t\tvalidatedResult: deletionTool.getValidatedResult(),\n\t\t\t\tlastToolError: deletionTool.getLastError(),\n\t\t\t\tproviderError: formattedErrorMessage,\n\t\t\t\tproviderOverflow: true,\n\t\t\t};\n\t\t}\n\t\tthrow new Error(`Context compaction failed: ${formattedErrorMessage}`);\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", abortOnSignal);\n\t\tunsubscribeNudge();\n\t\ttranscriptFile.cleanup();\n\t}\n\n\tif (signal?.aborted) throw new Error(\"Context compaction failed: Request was aborted\");\n\tif (agent.state.errorMessage) {\n\t\tconst formattedErrorMessage = formatCopilotProviderError(model.provider, agent.state.errorMessage);\n\t\tif (isContextCompactionOverflowError(model, agent.state.errorMessage)) {\n\t\t\treturn {\n\t\t\t\tvalidatedResult: deletionTool.getValidatedResult(),\n\t\t\t\tlastToolError: deletionTool.getLastError(),\n\t\t\t\tproviderError: formattedErrorMessage === agent.state.errorMessage ? undefined : formattedErrorMessage,\n\t\t\t\tproviderOverflow: true,\n\t\t\t};\n\t\t}\n\t\tthrow new Error(`Context compaction failed: ${formattedErrorMessage}`);\n\t}\n\tif (deletionTool.getCallCount() === 0) {\n\t\tthrow new Error(\n\t\t\t`Context compaction did not call any transcript inspection, budget, or deletion tools (${CONTEXT_SEARCH_TRANSCRIPT_TOOL_NAME}, ${CONTEXT_READ_ENTRY_TOOL_NAME}, ${CONTEXT_COMPACTION_BUDGET_TOOL_NAME}, ${CONTEXT_DELETE_TOOL_NAME}, or ${CONTEXT_GREP_DELETE_TOOL_NAME})`,\n\t\t);\n\t}\n\treturn {\n\t\tvalidatedResult: deletionTool.getValidatedResult(),\n\t\tlastToolError: deletionTool.getLastError(),\n\t\tproviderError: undefined,\n\t\tproviderOverflow: false,\n\t};\n}\n\nfunction hasMetContextCompactionTarget(\n\trun: ContextDeletionRun,\n\tparameters: ContextCompactionParameters,\n): run is ContextDeletionRun & { validatedResult: ValidatedContextDeletionResult } {\n\treturn contextCompactionTargetMet(run.validatedResult, parameters);\n}\n\nfunction formatContextCompactionTargetFailureMessage(\n\tattempts: readonly ContextDeletionRunAttempt[],\n\tparameters: ContextCompactionParameters,\n): string {\n\tconst targetLabel = contextCompactionTargetLabel(parameters);\n\tif (attempts.length === 0) return `Context compaction did not meet the strict ${targetLabel} reduction requirement`;\n\tconst attemptDetails = attempts\n\t\t.map((attempt) => {\n\t\t\tconst reduction = contextCompactionProgressPercent(attempt.validatedResult);\n\t\t\tconst deletionCount = attempt.validatedResult?.deletedTargets.length ?? 0;\n\t\t\tconst tokensAfterText = attempt.validatedResult ? `; tokens after: ${attempt.validatedResult.stats.tokensAfter}` : \"\";\n\t\t\tconst toolErrorText = attempt.lastToolError ? `; last deletion tool error: ${attempt.lastToolError}` : \"\";\n\t\t\tconst providerErrorText = attempt.providerError ? `; provider error: ${attempt.providerError}` : \"\";\n\t\t\treturn `attempt reached ${reduction}% with ${deletionCount} validated deletion target(s)${tokensAfterText}${toolErrorText}${providerErrorText}`;\n\t\t})\n\t\t.join(\"; \");\n\treturn `Context compaction did not meet the strict ${targetLabel} reduction requirement; ${attemptDetails}`;\n}\n\nfunction runFailedAttempt(error: Error): ContextDeletionRunAttempt {\n\treturn { validatedResult: undefined, lastToolError: undefined, providerError: error.message, providerOverflow: false };\n}\n\nfunction shouldRethrowPlannerError(error: Error, signal: AbortSignal | undefined, ladder: ContextCompactionLadderOptions | undefined): boolean {\n\tif (signal?.aborted) return true;\n\tif (error.message === \"Context compaction failed: Request was aborted\") return true;\n\treturn ladder?.criticalEvictionTokenBudget === undefined;\n}\n\ninterface ContextDeletionRunAttempt extends ContextDeletionRun {}\n\nexport async function contextCompact(\n\tpreparation: ContextCompactionPreparation,\n\tmodel: Model<Api>,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel: ThinkingLevel = \"off\",\n\tladder?: ContextCompactionLadderOptions,\n): Promise<ValidatedContextDeletionResult> {\n\tconst parameters = normalizeContextCompactionParameters(\n\t\tpreparation.parameters ?? preparation.transcript.parameters,\n\t\tpreparation.parameters?.query ?? preparation.transcript.parameters?.query ?? CONTEXT_COMPACTION_AUTO_QUERY,\n\t);\n\tconst transcript: CompactableTranscript = { ...preparation.transcript, parameters };\n\tconst attempts: ContextDeletionRunAttempt[] = [];\n\tlet skipCriticalPlanner = false;\n\ttry {\n\t\tconst standardRun = await runContextDeletionAssistant(transcript, model, apiKey, headers, signal, thinkingLevel, parameters);\n\t\tif (targetMetAcceptedForLadder(standardRun, parameters, ladder)) return standardRun.validatedResult;\n\t\tif (feasibleAccepted(standardRun.validatedResult, ladder?.acceptanceTokenBudget)) return standardRun.validatedResult;\n\t\tskipCriticalPlanner = standardRun.providerOverflow;\n\t\tattempts.push({ ...standardRun });\n\t} catch (error) {\n\t\tconst formattedError = error instanceof Error ? error : new Error(formatErrorMessage(error));\n\t\tif (shouldRethrowPlannerError(formattedError, signal, ladder)) throw formattedError;\n\t\tattempts.push(runFailedAttempt(formattedError));\n\t}\n\n\tif (ladder?.criticalEvictionTokenBudget === undefined) {\n\t\tthrow new Error(formatContextCompactionTargetFailureMessage(attempts, parameters));\n\t}\n\n\tif (!skipCriticalPlanner) {\n\t\ttry {\n\t\t\tconst criticalParameters = criticalCompactionParameters(parameters);\n\t\t\tconst criticalTranscript = relaxTranscriptForCriticalEviction(transcript);\n\t\t\tconst criticalRun = await runContextDeletionAssistant(\n\t\t\t\tcriticalTranscript,\n\t\t\t\tmodel,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tsignal,\n\t\t\t\tthinkingLevel,\n\t\t\t\tcriticalParameters,\n\t\t\t\t{\n\t\t\t\t\tpromptSuffix: CONTEXT_COMPACTION_CRITICAL_OVERFLOW_PROMPT,\n\t\t\t\t\tacceptanceTokenBudget: ladder.criticalEvictionTokenBudget,\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (targetMetAcceptedForLadder(criticalRun, parameters, ladder)) return criticalRun.validatedResult;\n\t\t\tif (feasibleAccepted(criticalRun.validatedResult, ladder.criticalEvictionTokenBudget)) return criticalRun.validatedResult;\n\t\t\tattempts.push({ ...criticalRun });\n\t\t} catch (error) {\n\t\t\tconst formattedError = error instanceof Error ? error : new Error(formatErrorMessage(error));\n\t\t\tif (signal?.aborted || formattedError.message === \"Context compaction failed: Request was aborted\") throw formattedError;\n\t\t\tattempts.push(runFailedAttempt(formattedError));\n\t\t}\n\t}\n\n\ttry {\n\t\treturn runDeterministicContextEviction(transcript, ladder.criticalEvictionTokenBudget);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : formatErrorMessage(error);\n\t\tthrow new Error(`${formatContextCompactionTargetFailureMessage(attempts, parameters)}; ${message}`);\n\t}\n}\n"]}
|
|
@@ -1,273 +0,0 @@
|
|
|
1
|
-
import { Agent } from "@earendil-works/pi-agent-core";
|
|
2
|
-
import { createAssistantMessageEventStream, isContextOverflow, streamSimple } from "@earendil-works/pi-ai/compat";
|
|
3
|
-
import { formatCopilotProviderError } from "../copilot-errors.js";
|
|
4
|
-
import { CONTEXT_COMPACTION_AUTO_QUERY } from "./context-compaction-types.js";
|
|
5
|
-
import { createContextCompactionBudgetDetails, contextCompactionProgressKey, contextCompactionProgressPercent, contextCompactionTargetLabel, contextCompactionTargetMet, formatErrorMessage, } from "./context-compaction-metrics.js";
|
|
6
|
-
import { getTranscriptCompactionParameters, normalizeContextCompactionParameters } from "./context-compaction-strategy.js";
|
|
7
|
-
import { CONTEXT_COMPACTION_BUDGET_TOOL_NAME, CONTEXT_DELETE_TOOL_NAME, CONTEXT_GREP_DELETE_TOOL_NAME, CONTEXT_READ_ENTRY_TOOL_NAME, CONTEXT_SEARCH_TRANSCRIPT_TOOL_NAME, } from "./context-deletion-tool-definitions.js";
|
|
8
|
-
import { createContextDeletionTool } from "./context-deletion-tools.js";
|
|
9
|
-
import { buildContextCompactionPrompt, CONTEXT_COMPACTION_SYSTEM_PROMPT, writeContextCompactionTranscriptFile, } from "./context-compaction-prompt.js";
|
|
10
|
-
import { CONTEXT_COMPACTION_CRITICAL_OVERFLOW_PROMPT, criticalCompactionParameters, relaxTranscriptForCriticalEviction, } from "./context-compaction-critical.js";
|
|
11
|
-
import { runDeterministicContextEviction } from "./context-compaction-eviction.js";
|
|
12
|
-
export const CONTEXT_COMPACTION_MAX_TURNS = 50;
|
|
13
|
-
export const CONTEXT_COMPACTION_MAX_PLANNER_NUDGES = 50;
|
|
14
|
-
function createContextCompactionTargetNudgeMessage(result, parameters) {
|
|
15
|
-
const currentReductionPercent = contextCompactionProgressPercent(result);
|
|
16
|
-
const targetLabel = contextCompactionTargetLabel(parameters);
|
|
17
|
-
const tokensToDelete = result
|
|
18
|
-
? createContextCompactionBudgetDetails(result.stats, 0, undefined, parameters, 0, 0).tokensToDeleteForTarget
|
|
19
|
-
: undefined;
|
|
20
|
-
const remainingText = tokensToDelete !== undefined ? ` Delete about ${tokensToDelete} more token(s) if safe candidates exist.` : "";
|
|
21
|
-
return {
|
|
22
|
-
role: "user",
|
|
23
|
-
content: [
|
|
24
|
-
{
|
|
25
|
-
type: "text",
|
|
26
|
-
text: `The strict ${targetLabel} context-reduction requirement is not met yet; current validated reduction is ${currentReductionPercent}%.${remainingText} Continue removing low-value message entries or message content blocks using ${CONTEXT_DELETE_TOOL_NAME} or ${CONTEXT_GREP_DELETE_TOOL_NAME}. Use the focus query ${JSON.stringify(parameters.query)} to preserve relevant context. Call ${CONTEXT_COMPACTION_BUDGET_TOOL_NAME} to verify progress, and do not provide a final answer until the validated reduction is at least ${targetLabel}.`,
|
|
27
|
-
},
|
|
28
|
-
],
|
|
29
|
-
timestamp: Date.now(),
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
function createContextCompactionAssistantMessage(model, content, stopReason, errorMessage) {
|
|
33
|
-
return {
|
|
34
|
-
role: "assistant",
|
|
35
|
-
content,
|
|
36
|
-
api: model.api,
|
|
37
|
-
provider: model.provider,
|
|
38
|
-
model: model.id,
|
|
39
|
-
usage: {
|
|
40
|
-
input: 0,
|
|
41
|
-
output: 0,
|
|
42
|
-
cacheRead: 0,
|
|
43
|
-
cacheWrite: 0,
|
|
44
|
-
totalTokens: 0,
|
|
45
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
46
|
-
},
|
|
47
|
-
stopReason,
|
|
48
|
-
...(errorMessage !== undefined ? { errorMessage } : {}),
|
|
49
|
-
timestamp: Date.now(),
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
function createContextCompactionStopStream(model, text) {
|
|
53
|
-
const stream = createAssistantMessageEventStream();
|
|
54
|
-
queueMicrotask(() => {
|
|
55
|
-
const message = createContextCompactionAssistantMessage(model, [{ type: "text", text }], "stop");
|
|
56
|
-
stream.push({ type: "done", reason: "stop", message });
|
|
57
|
-
stream.end(message);
|
|
58
|
-
});
|
|
59
|
-
return stream;
|
|
60
|
-
}
|
|
61
|
-
function isContextCompactionOverflowError(model, errorMessage) {
|
|
62
|
-
return isContextOverflow(createContextCompactionAssistantMessage(model, [], "error", errorMessage), model.contextWindow);
|
|
63
|
-
}
|
|
64
|
-
function feasibleAccepted(result, acceptanceTokenBudget) {
|
|
65
|
-
return (acceptanceTokenBudget !== undefined &&
|
|
66
|
-
result !== undefined &&
|
|
67
|
-
result.deletedTargets.length > 0 &&
|
|
68
|
-
result.stats.tokensAfter <= acceptanceTokenBudget);
|
|
69
|
-
}
|
|
70
|
-
function acceptedWithinRun(result, parameters, acceptanceTokenBudget) {
|
|
71
|
-
if (acceptanceTokenBudget !== undefined)
|
|
72
|
-
return feasibleAccepted(result, acceptanceTokenBudget);
|
|
73
|
-
return contextCompactionTargetMet(result, parameters);
|
|
74
|
-
}
|
|
75
|
-
function targetMetAcceptedForLadder(run, parameters, ladder) {
|
|
76
|
-
if (!hasMetContextCompactionTarget(run, parameters))
|
|
77
|
-
return false;
|
|
78
|
-
const overflowBudget = ladder?.criticalEvictionTokenBudget;
|
|
79
|
-
return overflowBudget === undefined || run.validatedResult.stats.tokensAfter <= overflowBudget;
|
|
80
|
-
}
|
|
81
|
-
async function runContextDeletionAssistant(inputTranscript, model, apiKey, headers, signal, thinkingLevel = "off", parameters = getTranscriptCompactionParameters(inputTranscript), options = {}) {
|
|
82
|
-
const transcript = { ...inputTranscript, parameters };
|
|
83
|
-
const maxTokens = model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY;
|
|
84
|
-
if (signal?.aborted)
|
|
85
|
-
throw new Error("Context compaction failed: Request was aborted");
|
|
86
|
-
const transcriptFile = writeContextCompactionTranscriptFile(transcript);
|
|
87
|
-
const promptText = buildContextCompactionPrompt(transcript, transcriptFile.path, parameters) + (options.promptSuffix ?? "");
|
|
88
|
-
const promptMessage = {
|
|
89
|
-
role: "user",
|
|
90
|
-
content: [{ type: "text", text: promptText }],
|
|
91
|
-
timestamp: Date.now(),
|
|
92
|
-
};
|
|
93
|
-
const deletionTool = createContextDeletionTool(transcript, { contextWindow: model.contextWindow, ...parameters });
|
|
94
|
-
let providerTurnCount = 0;
|
|
95
|
-
const agent = new Agent({
|
|
96
|
-
initialState: {
|
|
97
|
-
systemPrompt: CONTEXT_COMPACTION_SYSTEM_PROMPT,
|
|
98
|
-
model,
|
|
99
|
-
thinkingLevel,
|
|
100
|
-
tools: deletionTool.tools,
|
|
101
|
-
},
|
|
102
|
-
toolExecution: "parallel",
|
|
103
|
-
streamFn: async (requestModel, context, streamOptions) => {
|
|
104
|
-
const currentResult = deletionTool.getValidatedResult();
|
|
105
|
-
if (acceptedWithinRun(currentResult, parameters, options.acceptanceTokenBudget)) {
|
|
106
|
-
return createContextCompactionStopStream(requestModel, `Reached an acceptable context-reduction result (${currentResult.stats.percentReduction}%, ${currentResult.stats.tokensAfter} token(s) after deletion); using the validated deletions recorded so far.`);
|
|
107
|
-
}
|
|
108
|
-
if (providerTurnCount >= CONTEXT_COMPACTION_MAX_TURNS) {
|
|
109
|
-
return createContextCompactionStopStream(requestModel, `Reached the context compaction turn cap (${CONTEXT_COMPACTION_MAX_TURNS}); using the validated deletions recorded so far.`);
|
|
110
|
-
}
|
|
111
|
-
providerTurnCount += 1;
|
|
112
|
-
return streamSimple(requestModel, context, {
|
|
113
|
-
...streamOptions,
|
|
114
|
-
maxTokens,
|
|
115
|
-
apiKey,
|
|
116
|
-
headers: headers ?? streamOptions?.headers,
|
|
117
|
-
});
|
|
118
|
-
},
|
|
119
|
-
});
|
|
120
|
-
let lastNudgedProgressKey;
|
|
121
|
-
let nudgeCount = 0;
|
|
122
|
-
const unsubscribeNudge = agent.subscribe((event, eventSignal) => {
|
|
123
|
-
if (event.type !== "turn_end" || signal?.aborted || eventSignal.aborted)
|
|
124
|
-
return;
|
|
125
|
-
if (event.message.role !== "assistant")
|
|
126
|
-
return;
|
|
127
|
-
if (event.message.stopReason === "error" || event.message.stopReason === "aborted")
|
|
128
|
-
return;
|
|
129
|
-
if (event.message.content.some((content) => content.type === "toolCall"))
|
|
130
|
-
return;
|
|
131
|
-
if (nudgeCount >= CONTEXT_COMPACTION_MAX_PLANNER_NUDGES)
|
|
132
|
-
return;
|
|
133
|
-
const currentResult = deletionTool.getValidatedResult();
|
|
134
|
-
if (acceptedWithinRun(currentResult, parameters, options.acceptanceTokenBudget))
|
|
135
|
-
return;
|
|
136
|
-
const progressKey = contextCompactionProgressKey(currentResult);
|
|
137
|
-
if (progressKey === lastNudgedProgressKey)
|
|
138
|
-
return;
|
|
139
|
-
lastNudgedProgressKey = progressKey;
|
|
140
|
-
nudgeCount += 1;
|
|
141
|
-
agent.followUp(createContextCompactionTargetNudgeMessage(currentResult, parameters));
|
|
142
|
-
});
|
|
143
|
-
const abortOnSignal = () => agent.abort();
|
|
144
|
-
signal?.addEventListener("abort", abortOnSignal, { once: true });
|
|
145
|
-
try {
|
|
146
|
-
await agent.prompt(promptMessage);
|
|
147
|
-
}
|
|
148
|
-
catch (error) {
|
|
149
|
-
if (signal?.aborted)
|
|
150
|
-
throw new Error("Context compaction failed: Request was aborted");
|
|
151
|
-
const errorMessage = formatErrorMessage(error);
|
|
152
|
-
const formattedErrorMessage = formatCopilotProviderError(model.provider, errorMessage);
|
|
153
|
-
if (isContextCompactionOverflowError(model, errorMessage)) {
|
|
154
|
-
return {
|
|
155
|
-
validatedResult: deletionTool.getValidatedResult(),
|
|
156
|
-
lastToolError: deletionTool.getLastError(),
|
|
157
|
-
providerError: formattedErrorMessage,
|
|
158
|
-
providerOverflow: true,
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
throw new Error(`Context compaction failed: ${formattedErrorMessage}`);
|
|
162
|
-
}
|
|
163
|
-
finally {
|
|
164
|
-
signal?.removeEventListener("abort", abortOnSignal);
|
|
165
|
-
unsubscribeNudge();
|
|
166
|
-
transcriptFile.cleanup();
|
|
167
|
-
}
|
|
168
|
-
if (signal?.aborted)
|
|
169
|
-
throw new Error("Context compaction failed: Request was aborted");
|
|
170
|
-
if (agent.state.errorMessage) {
|
|
171
|
-
const formattedErrorMessage = formatCopilotProviderError(model.provider, agent.state.errorMessage);
|
|
172
|
-
if (isContextCompactionOverflowError(model, agent.state.errorMessage)) {
|
|
173
|
-
return {
|
|
174
|
-
validatedResult: deletionTool.getValidatedResult(),
|
|
175
|
-
lastToolError: deletionTool.getLastError(),
|
|
176
|
-
providerError: formattedErrorMessage === agent.state.errorMessage ? undefined : formattedErrorMessage,
|
|
177
|
-
providerOverflow: true,
|
|
178
|
-
};
|
|
179
|
-
}
|
|
180
|
-
throw new Error(`Context compaction failed: ${formattedErrorMessage}`);
|
|
181
|
-
}
|
|
182
|
-
if (deletionTool.getCallCount() === 0) {
|
|
183
|
-
throw new Error(`Context compaction did not call any transcript inspection, budget, or deletion tools (${CONTEXT_SEARCH_TRANSCRIPT_TOOL_NAME}, ${CONTEXT_READ_ENTRY_TOOL_NAME}, ${CONTEXT_COMPACTION_BUDGET_TOOL_NAME}, ${CONTEXT_DELETE_TOOL_NAME}, or ${CONTEXT_GREP_DELETE_TOOL_NAME})`);
|
|
184
|
-
}
|
|
185
|
-
return {
|
|
186
|
-
validatedResult: deletionTool.getValidatedResult(),
|
|
187
|
-
lastToolError: deletionTool.getLastError(),
|
|
188
|
-
providerError: undefined,
|
|
189
|
-
providerOverflow: false,
|
|
190
|
-
};
|
|
191
|
-
}
|
|
192
|
-
function hasMetContextCompactionTarget(run, parameters) {
|
|
193
|
-
return contextCompactionTargetMet(run.validatedResult, parameters);
|
|
194
|
-
}
|
|
195
|
-
function formatContextCompactionTargetFailureMessage(attempts, parameters) {
|
|
196
|
-
const targetLabel = contextCompactionTargetLabel(parameters);
|
|
197
|
-
if (attempts.length === 0)
|
|
198
|
-
return `Context compaction did not meet the strict ${targetLabel} reduction requirement`;
|
|
199
|
-
const attemptDetails = attempts
|
|
200
|
-
.map((attempt) => {
|
|
201
|
-
const reduction = contextCompactionProgressPercent(attempt.validatedResult);
|
|
202
|
-
const deletionCount = attempt.validatedResult?.deletedTargets.length ?? 0;
|
|
203
|
-
const tokensAfterText = attempt.validatedResult ? `; tokens after: ${attempt.validatedResult.stats.tokensAfter}` : "";
|
|
204
|
-
const toolErrorText = attempt.lastToolError ? `; last deletion tool error: ${attempt.lastToolError}` : "";
|
|
205
|
-
const providerErrorText = attempt.providerError ? `; provider error: ${attempt.providerError}` : "";
|
|
206
|
-
return `attempt reached ${reduction}% with ${deletionCount} validated deletion target(s)${tokensAfterText}${toolErrorText}${providerErrorText}`;
|
|
207
|
-
})
|
|
208
|
-
.join("; ");
|
|
209
|
-
return `Context compaction did not meet the strict ${targetLabel} reduction requirement; ${attemptDetails}`;
|
|
210
|
-
}
|
|
211
|
-
function runFailedAttempt(error) {
|
|
212
|
-
return { validatedResult: undefined, lastToolError: undefined, providerError: error.message, providerOverflow: false };
|
|
213
|
-
}
|
|
214
|
-
function shouldRethrowPlannerError(error, signal, ladder) {
|
|
215
|
-
if (signal?.aborted)
|
|
216
|
-
return true;
|
|
217
|
-
if (error.message === "Context compaction failed: Request was aborted")
|
|
218
|
-
return true;
|
|
219
|
-
return ladder?.criticalEvictionTokenBudget === undefined;
|
|
220
|
-
}
|
|
221
|
-
export async function contextCompact(preparation, model, apiKey, headers, signal, thinkingLevel = "off", ladder) {
|
|
222
|
-
const parameters = normalizeContextCompactionParameters(preparation.parameters ?? preparation.transcript.parameters, preparation.parameters?.query ?? preparation.transcript.parameters?.query ?? CONTEXT_COMPACTION_AUTO_QUERY);
|
|
223
|
-
const transcript = { ...preparation.transcript, parameters };
|
|
224
|
-
const attempts = [];
|
|
225
|
-
let skipCriticalPlanner = false;
|
|
226
|
-
try {
|
|
227
|
-
const standardRun = await runContextDeletionAssistant(transcript, model, apiKey, headers, signal, thinkingLevel, parameters);
|
|
228
|
-
if (targetMetAcceptedForLadder(standardRun, parameters, ladder))
|
|
229
|
-
return standardRun.validatedResult;
|
|
230
|
-
if (feasibleAccepted(standardRun.validatedResult, ladder?.acceptanceTokenBudget))
|
|
231
|
-
return standardRun.validatedResult;
|
|
232
|
-
skipCriticalPlanner = standardRun.providerOverflow;
|
|
233
|
-
attempts.push({ ...standardRun });
|
|
234
|
-
}
|
|
235
|
-
catch (error) {
|
|
236
|
-
const formattedError = error instanceof Error ? error : new Error(formatErrorMessage(error));
|
|
237
|
-
if (shouldRethrowPlannerError(formattedError, signal, ladder))
|
|
238
|
-
throw formattedError;
|
|
239
|
-
attempts.push(runFailedAttempt(formattedError));
|
|
240
|
-
}
|
|
241
|
-
if (ladder?.criticalEvictionTokenBudget === undefined) {
|
|
242
|
-
throw new Error(formatContextCompactionTargetFailureMessage(attempts, parameters));
|
|
243
|
-
}
|
|
244
|
-
if (!skipCriticalPlanner) {
|
|
245
|
-
try {
|
|
246
|
-
const criticalParameters = criticalCompactionParameters(parameters);
|
|
247
|
-
const criticalTranscript = relaxTranscriptForCriticalEviction(transcript);
|
|
248
|
-
const criticalRun = await runContextDeletionAssistant(criticalTranscript, model, apiKey, headers, signal, thinkingLevel, criticalParameters, {
|
|
249
|
-
promptSuffix: CONTEXT_COMPACTION_CRITICAL_OVERFLOW_PROMPT,
|
|
250
|
-
acceptanceTokenBudget: ladder.criticalEvictionTokenBudget,
|
|
251
|
-
});
|
|
252
|
-
if (targetMetAcceptedForLadder(criticalRun, parameters, ladder))
|
|
253
|
-
return criticalRun.validatedResult;
|
|
254
|
-
if (feasibleAccepted(criticalRun.validatedResult, ladder.criticalEvictionTokenBudget))
|
|
255
|
-
return criticalRun.validatedResult;
|
|
256
|
-
attempts.push({ ...criticalRun });
|
|
257
|
-
}
|
|
258
|
-
catch (error) {
|
|
259
|
-
const formattedError = error instanceof Error ? error : new Error(formatErrorMessage(error));
|
|
260
|
-
if (signal?.aborted || formattedError.message === "Context compaction failed: Request was aborted")
|
|
261
|
-
throw formattedError;
|
|
262
|
-
attempts.push(runFailedAttempt(formattedError));
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
try {
|
|
266
|
-
return runDeterministicContextEviction(transcript, ladder.criticalEvictionTokenBudget);
|
|
267
|
-
}
|
|
268
|
-
catch (error) {
|
|
269
|
-
const message = error instanceof Error ? error.message : formatErrorMessage(error);
|
|
270
|
-
throw new Error(`${formatContextCompactionTargetFailureMessage(attempts, parameters)}; ${message}`);
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
//# sourceMappingURL=context-compaction-runner.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"context-compaction-runner.js","sourceRoot":"","sources":["../../../src/core/compaction/context-compaction-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAyC,MAAM,+BAA+B,CAAC;AAE7F,OAAO,EAAE,iCAAiC,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAClH,OAAO,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAOlE,OAAO,EAAE,6BAA6B,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,EACN,oCAAoC,EACpC,4BAA4B,EAC5B,gCAAgC,EAChC,4BAA4B,EAC5B,0BAA0B,EAC1B,kBAAkB,GAClB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,iCAAiC,EAAE,oCAAoC,EAAE,MAAM,kCAAkC,CAAC;AAC3H,OAAO,EACN,mCAAmC,EACnC,wBAAwB,EACxB,6BAA6B,EAC7B,4BAA4B,EAC5B,mCAAmC,GACnC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EACN,4BAA4B,EAC5B,gCAAgC,EAChC,oCAAoC,GACpC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACN,2CAA2C,EAC3C,4BAA4B,EAC5B,kCAAkC,GAClC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,+BAA+B,EAAE,MAAM,kCAAkC,CAAC;AAEnF,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,CAAC;AAC/C,MAAM,CAAC,MAAM,qCAAqC,GAAG,EAAE,CAAC;AAYxD,SAAS,yCAAyC,CACjD,MAAkD,EAClD,UAAuC;IAEvC,MAAM,uBAAuB,GAAG,gCAAgC,CAAC,MAAM,CAAC,CAAC;IACzE,MAA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a,EACb,kBAAkB,EAClB;gBACC,YAAY,EAAE,2CAA2C;gBACzD,qBAAqB,EAAE,MAAM,CAAC,2BAA2B;aACzD,CACD,CAAC;YACF,IAAI,0BAA0B,CAAC,WAAW,EAAE,UAAU,EAAE,MAAM,CAAC;gBAAE,OAAO,WAAW,CAAC,eAAe,CAAC;YACpG,IAAI,gBAAgB,CAAC,WAAW,CAAC,eAAe,EAAE,MAAM,CAAC,2BAA2B,CAAC;gBAAE,OAAO,WAAW,CAAC,eAAe,CAAC;YAC1H,QAAQ,CAAC,IAAI,CAAC,EAAE,GAAG,WAAW,EAAE,CAAC,CAAC;QACnC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,MAAM,cAAc,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC;YAC7F,IAAI,MAAM,EAAE,OAAO,IAAI,cAAc,CAAC,OAAO,KAAK,gDAAgD;gBAAE,MAAM,cAAc,CAAC;YACzH,QAAQ,CAAC,IAAI,CAAC,gBAAgB,CAAC,cAAc,CAAC,CAAC,CAAC;QACjD,CAAC;IACF,CAAC;IAED,IAAI,CAAC;QACJ,OAAO,+BAA+B,CAAC,UAAU,EAAE,MAAM,CAAC,2BAA2B,CAAC,CAAC;IACxF,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;QACnF,MAAM,IAAI,KAAK,CAAC,GAAG,2CAA2C,CAAC,QAAQ,EAAE,UAAU,CAAC,KAAK,OAAO,EAAE,CAAC,CAAC;IACrG,CAAC;AACF,CAAC","sourcesContent":["import { Agent, type AgentMessage, type ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, Model } from \"@earendil-works/pi-ai/compat\";\nimport { createAssistantMessageEventStream, isContextOverflow, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport { formatCopilotProviderError } from \"../copilot-errors.ts\";\nimport type {\n\tCompactableTranscript,\n\tContextCompactionParameters,\n\tContextCompactionPreparation,\n\tValidatedContextDeletionResult,\n} from \"./context-compaction-types.ts\";\nimport { CONTEXT_COMPACTION_AUTO_QUERY } from \"./context-compaction-types.ts\";\nimport {\n\tcreateContextCompactionBudgetDetails,\n\tcontextCompactionProgressKey,\n\tcontextCompactionProgressPercent,\n\tcontextCompactionTargetLabel,\n\tcontextCompactionTargetMet,\n\tformatErrorMessage,\n} from \"./context-compaction-metrics.ts\";\nimport { getTranscriptCompactionParameters, normalizeContextCompactionParameters } from \"./context-compaction-strategy.ts\";\nimport {\n\tCONTEXT_COMPACTION_BUDGET_TOOL_NAME,\n\tCONTEXT_DELETE_TOOL_NAME,\n\tCONTEXT_GREP_DELETE_TOOL_NAME,\n\tCONTEXT_READ_ENTRY_TOOL_NAME,\n\tCONTEXT_SEARCH_TRANSCRIPT_TOOL_NAME,\n} from \"./context-deletion-tool-definitions.ts\";\nimport { createContextDeletionTool } from \"./context-deletion-tools.ts\";\nimport {\n\tbuildContextCompactionPrompt,\n\tCONTEXT_COMPACTION_SYSTEM_PROMPT,\n\twriteContextCompactionTranscriptFile,\n} from \"./context-compaction-prompt.ts\";\nimport {\n\tCONTEXT_COMPACTION_CRITICAL_OVERFLOW_PROMPT,\n\tcriticalCompactionParameters,\n\trelaxTranscriptForCriticalEviction,\n} from \"./context-compaction-critical.ts\";\nimport { runDeterministicContextEviction } from \"./context-compaction-eviction.ts\";\n\nexport const CONTEXT_COMPACTION_MAX_TURNS = 50;\nexport const CONTEXT_COMPACTION_MAX_PLANNER_NUDGES = 50;\n\nexport interface ContextCompactionLadderOptions {\n\tacceptanceTokenBudget?: number;\n\tcriticalEvictionTokenBudget?: number;\n}\n\ninterface ContextDeletionAssistantOptions {\n\tpromptSuffix?: string;\n\tacceptanceTokenBudget?: number;\n}\n\nfunction createContextCompactionTargetNudgeMessage(\n\tresult: ValidatedContextDeletionResult | undefined,\n\tparameters: ContextCompactionParameters,\n): AgentMessage {\n\tconst currentReductionPercent = contextCompactionProgressPercent(result);\n\tconst targetLabel = contextCompactionTargetLabel(parameters);\n\tconst tokensToDelete = result\n\t\t? createContextCompactionBudgetDetails(result.stats, 0, undefined, parameters, 0, 0).tokensToDeleteForTarget\n\t\t: undefined;\n\tconst remainingText = tokensToDelete !== undefined ? ` Delete about ${tokensToDelete} more token(s) if safe candidates exist.` : \"\";\n\treturn {\n\t\trole: \"user\",\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `The strict ${targetLabel} context-reduction requirement is not met yet; current validated reduction is ${currentReductionPercent}%.${remainingText} Continue removing low-value message entries or message content blocks using ${CONTEXT_DELETE_TOOL_NAME} or ${CONTEXT_GREP_DELETE_TOOL_NAME}. Use the focus query ${JSON.stringify(parameters.query)} to preserve relevant context. Call ${CONTEXT_COMPACTION_BUDGET_TOOL_NAME} to verify progress, and do not provide a final answer until the validated reduction is at least ${targetLabel}.`,\n\t\t\t},\n\t\t],\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createContextCompactionAssistantMessage(\n\tmodel: Model<Api>,\n\tcontent: AssistantMessage[\"content\"],\n\tstopReason: AssistantMessage[\"stopReason\"],\n\terrorMessage?: string,\n): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent,\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason,\n\t\t...(errorMessage !== undefined ? { errorMessage } : {}),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createContextCompactionStopStream(model: Model<Api>, text: string) {\n\tconst stream = createAssistantMessageEventStream();\n\tqueueMicrotask(() => {\n\t\tconst message = createContextCompactionAssistantMessage(model, [{ type: \"text\", text }], \"stop\");\n\t\tstream.push({ type: \"done\", reason: \"stop\", message });\n\t\tstream.end(message);\n\t});\n\treturn stream;\n}\n\nfunction isContextCompactionOverflowError(model: Model<Api>, errorMessage: string): boolean {\n\treturn isContextOverflow(createContextCompactionAssistantMessage(model, [], \"error\", errorMessage), model.contextWindow);\n}\n\nfunction feasibleAccepted(\n\tresult: ValidatedContextDeletionResult | undefined,\n\tacceptanceTokenBudget: number | undefined,\n): result is ValidatedContextDeletionResult {\n\treturn (\n\t\tacceptanceTokenBudget !== undefined &&\n\t\tresult !== undefined &&\n\t\tresult.deletedTargets.length > 0 &&\n\t\tresult.stats.tokensAfter <= acceptanceTokenBudget\n\t);\n}\n\nfunction acceptedWithinRun(\n\tresult: ValidatedContextDeletionResult | undefined,\n\tparameters: ContextCompactionParameters,\n\tacceptanceTokenBudget: number | undefined,\n): result is ValidatedContextDeletionResult {\n\tif (acceptanceTokenBudget !== undefined) return feasibleAccepted(result, acceptanceTokenBudget);\n\treturn contextCompactionTargetMet(result, parameters);\n}\n\nfunction targetMetAcceptedForLadder(\n\trun: ContextDeletionRun,\n\tparameters: ContextCompactionParameters,\n\tladder: ContextCompactionLadderOptions | undefined,\n): run is ContextDeletionRun & { validatedResult: ValidatedContextDeletionResult } {\n\tif (!hasMetContextCompactionTarget(run, parameters)) return false;\n\tconst overflowBudget = ladder?.criticalEvictionTokenBudget;\n\treturn overflowBudget === undefined || run.validatedResult.stats.tokensAfter <= overflowBudget;\n}\n\ninterface ContextDeletionRun {\n\tvalidatedResult: ValidatedContextDeletionResult | undefined;\n\tlastToolError: string | undefined;\n\tproviderError: string | undefined;\n\tproviderOverflow: boolean;\n}\n\nasync function runContextDeletionAssistant(\n\tinputTranscript: CompactableTranscript,\n\tmodel: Model<Api>,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel: ThinkingLevel = \"off\",\n\tparameters: ContextCompactionParameters = getTranscriptCompactionParameters(inputTranscript),\n\toptions: ContextDeletionAssistantOptions = {},\n): Promise<ContextDeletionRun> {\n\tconst transcript: CompactableTranscript = { ...inputTranscript, parameters };\n\tconst maxTokens = model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY;\n\tif (signal?.aborted) throw new Error(\"Context compaction failed: Request was aborted\");\n\tconst transcriptFile = writeContextCompactionTranscriptFile(transcript);\n\tconst promptText = buildContextCompactionPrompt(transcript, transcriptFile.path, parameters) + (options.promptSuffix ?? \"\");\n\tconst promptMessage: AgentMessage = {\n\t\trole: \"user\",\n\t\tcontent: [{ type: \"text\", text: promptText }],\n\t\ttimestamp: Date.now(),\n\t};\n\tconst deletionTool = createContextDeletionTool(transcript, { contextWindow: model.contextWindow, ...parameters });\n\tlet providerTurnCount = 0;\n\tconst agent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: CONTEXT_COMPACTION_SYSTEM_PROMPT,\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: deletionTool.tools,\n\t\t},\n\t\ttoolExecution: \"parallel\",\n\t\tstreamFn: async (requestModel, context, streamOptions) => {\n\t\t\tconst currentResult = deletionTool.getValidatedResult();\n\t\t\tif (acceptedWithinRun(currentResult, parameters, options.acceptanceTokenBudget)) {\n\t\t\t\treturn createContextCompactionStopStream(\n\t\t\t\t\trequestModel,\n\t\t\t\t\t`Reached an acceptable context-reduction result (${currentResult.stats.percentReduction}%, ${currentResult.stats.tokensAfter} token(s) after deletion); using the validated deletions recorded so far.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (providerTurnCount >= CONTEXT_COMPACTION_MAX_TURNS) {\n\t\t\t\treturn createContextCompactionStopStream(\n\t\t\t\t\trequestModel,\n\t\t\t\t\t`Reached the context compaction turn cap (${CONTEXT_COMPACTION_MAX_TURNS}); using the validated deletions recorded so far.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tproviderTurnCount += 1;\n\t\t\treturn streamSimple(requestModel, context, {\n\t\t\t\t...streamOptions,\n\t\t\t\tmaxTokens,\n\t\t\t\tapiKey,\n\t\t\t\theaders: headers ?? streamOptions?.headers,\n\t\t\t});\n\t\t},\n\t});\n\n\tlet lastNudgedProgressKey: string | undefined;\n\tlet nudgeCount = 0;\n\tconst unsubscribeNudge = agent.subscribe((event, eventSignal) => {\n\t\tif (event.type !== \"turn_end\" || signal?.aborted || eventSignal.aborted) return;\n\t\tif (event.message.role !== \"assistant\") return;\n\t\tif (event.message.stopReason === \"error\" || event.message.stopReason === \"aborted\") return;\n\t\tif (event.message.content.some((content) => content.type === \"toolCall\")) return;\n\t\tif (nudgeCount >= CONTEXT_COMPACTION_MAX_PLANNER_NUDGES) return;\n\t\tconst currentResult = deletionTool.getValidatedResult();\n\t\tif (acceptedWithinRun(currentResult, parameters, options.acceptanceTokenBudget)) return;\n\t\tconst progressKey = contextCompactionProgressKey(currentResult);\n\t\tif (progressKey === lastNudgedProgressKey) return;\n\t\tlastNudgedProgressKey = progressKey;\n\t\tnudgeCount += 1;\n\t\tagent.followUp(createContextCompactionTargetNudgeMessage(currentResult, parameters));\n\t});\n\n\tconst abortOnSignal = () => agent.abort();\n\tsignal?.addEventListener(\"abort\", abortOnSignal, { once: true });\n\ttry {\n\t\tawait agent.prompt(promptMessage);\n\t} catch (error) {\n\t\tif (signal?.aborted) throw new Error(\"Context compaction failed: Request was aborted\");\n\t\tconst errorMessage = formatErrorMessage(error);\n\t\tconst formattedErrorMessage = formatCopilotProviderError(model.provider, errorMessage);\n\t\tif (isContextCompactionOverflowError(model, errorMessage)) {\n\t\t\treturn {\n\t\t\t\tvalidatedResult: deletionTool.getValidatedResult(),\n\t\t\t\tlastToolError: deletionTool.getLastError(),\n\t\t\t\tproviderError: formattedErrorMessage,\n\t\t\t\tproviderOverflow: true,\n\t\t\t};\n\t\t}\n\t\tthrow new Error(`Context compaction failed: ${formattedErrorMessage}`);\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", abortOnSignal);\n\t\tunsubscribeNudge();\n\t\ttranscriptFile.cleanup();\n\t}\n\n\tif (signal?.aborted) throw new Error(\"Context compaction failed: Request was aborted\");\n\tif (agent.state.errorMessage) {\n\t\tconst formattedErrorMessage = formatCopilotProviderError(model.provider, agent.state.errorMessage);\n\t\tif (isContextCompactionOverflowError(model, agent.state.errorMessage)) {\n\t\t\treturn {\n\t\t\t\tvalidatedResult: deletionTool.getValidatedResult(),\n\t\t\t\tlastToolError: deletionTool.getLastError(),\n\t\t\t\tproviderError: formattedErrorMessage === agent.state.errorMessage ? undefined : formattedErrorMessage,\n\t\t\t\tproviderOverflow: true,\n\t\t\t};\n\t\t}\n\t\tthrow new Error(`Context compaction failed: ${formattedErrorMessage}`);\n\t}\n\tif (deletionTool.getCallCount() === 0) {\n\t\tthrow new Error(\n\t\t\t`Context compaction did not call any transcript inspection, budget, or deletion tools (${CONTEXT_SEARCH_TRANSCRIPT_TOOL_NAME}, ${CONTEXT_READ_ENTRY_TOOL_NAME}, ${CONTEXT_COMPACTION_BUDGET_TOOL_NAME}, ${CONTEXT_DELETE_TOOL_NAME}, or ${CONTEXT_GREP_DELETE_TOOL_NAME})`,\n\t\t);\n\t}\n\treturn {\n\t\tvalidatedResult: deletionTool.getValidatedResult(),\n\t\tlastToolError: deletionTool.getLastError(),\n\t\tproviderError: undefined,\n\t\tproviderOverflow: false,\n\t};\n}\n\nfunction hasMetContextCompactionTarget(\n\trun: ContextDeletionRun,\n\tparameters: ContextCompactionParameters,\n): run is ContextDeletionRun & { validatedResult: ValidatedContextDeletionResult } {\n\treturn contextCompactionTargetMet(run.validatedResult, parameters);\n}\n\nfunction formatContextCompactionTargetFailureMessage(\n\tattempts: readonly ContextDeletionRunAttempt[],\n\tparameters: ContextCompactionParameters,\n): string {\n\tconst targetLabel = contextCompactionTargetLabel(parameters);\n\tif (attempts.length === 0) return `Context compaction did not meet the strict ${targetLabel} reduction requirement`;\n\tconst attemptDetails = attempts\n\t\t.map((attempt) => {\n\t\t\tconst reduction = contextCompactionProgressPercent(attempt.validatedResult);\n\t\t\tconst deletionCount = attempt.validatedResult?.deletedTargets.length ?? 0;\n\t\t\tconst tokensAfterText = attempt.validatedResult ? `; tokens after: ${attempt.validatedResult.stats.tokensAfter}` : \"\";\n\t\t\tconst toolErrorText = attempt.lastToolError ? `; last deletion tool error: ${attempt.lastToolError}` : \"\";\n\t\t\tconst providerErrorText = attempt.providerError ? `; provider error: ${attempt.providerError}` : \"\";\n\t\t\treturn `attempt reached ${reduction}% with ${deletionCount} validated deletion target(s)${tokensAfterText}${toolErrorText}${providerErrorText}`;\n\t\t})\n\t\t.join(\"; \");\n\treturn `Context compaction did not meet the strict ${targetLabel} reduction requirement; ${attemptDetails}`;\n}\n\nfunction runFailedAttempt(error: Error): ContextDeletionRunAttempt {\n\treturn { validatedResult: undefined, lastToolError: undefined, providerError: error.message, providerOverflow: false };\n}\n\nfunction shouldRethrowPlannerError(error: Error, signal: AbortSignal | undefined, ladder: ContextCompactionLadderOptions | undefined): boolean {\n\tif (signal?.aborted) return true;\n\tif (error.message === \"Context compaction failed: Request was aborted\") return true;\n\treturn ladder?.criticalEvictionTokenBudget === undefined;\n}\n\ninterface ContextDeletionRunAttempt extends ContextDeletionRun {}\n\nexport async function contextCompact(\n\tpreparation: ContextCompactionPreparation,\n\tmodel: Model<Api>,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel: ThinkingLevel = \"off\",\n\tladder?: ContextCompactionLadderOptions,\n): Promise<ValidatedContextDeletionResult> {\n\tconst parameters = normalizeContextCompactionParameters(\n\t\tpreparation.parameters ?? preparation.transcript.parameters,\n\t\tpreparation.parameters?.query ?? preparation.transcript.parameters?.query ?? CONTEXT_COMPACTION_AUTO_QUERY,\n\t);\n\tconst transcript: CompactableTranscript = { ...preparation.transcript, parameters };\n\tconst attempts: ContextDeletionRunAttempt[] = [];\n\tlet skipCriticalPlanner = false;\n\ttry {\n\t\tconst standardRun = await runContextDeletionAssistant(transcript, model, apiKey, headers, signal, thinkingLevel, parameters);\n\t\tif (targetMetAcceptedForLadder(standardRun, parameters, ladder)) return standardRun.validatedResult;\n\t\tif (feasibleAccepted(standardRun.validatedResult, ladder?.acceptanceTokenBudget)) return standardRun.validatedResult;\n\t\tskipCriticalPlanner = standardRun.providerOverflow;\n\t\tattempts.push({ ...standardRun });\n\t} catch (error) {\n\t\tconst formattedError = error instanceof Error ? error : new Error(formatErrorMessage(error));\n\t\tif (shouldRethrowPlannerError(formattedError, signal, ladder)) throw formattedError;\n\t\tattempts.push(runFailedAttempt(formattedError));\n\t}\n\n\tif (ladder?.criticalEvictionTokenBudget === undefined) {\n\t\tthrow new Error(formatContextCompactionTargetFailureMessage(attempts, parameters));\n\t}\n\n\tif (!skipCriticalPlanner) {\n\t\ttry {\n\t\t\tconst criticalParameters = criticalCompactionParameters(parameters);\n\t\t\tconst criticalTranscript = relaxTranscriptForCriticalEviction(transcript);\n\t\t\tconst criticalRun = await runContextDeletionAssistant(\n\t\t\t\tcriticalTranscript,\n\t\t\t\tmodel,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tsignal,\n\t\t\t\tthinkingLevel,\n\t\t\t\tcriticalParameters,\n\t\t\t\t{\n\t\t\t\t\tpromptSuffix: CONTEXT_COMPACTION_CRITICAL_OVERFLOW_PROMPT,\n\t\t\t\t\tacceptanceTokenBudget: ladder.criticalEvictionTokenBudget,\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (targetMetAcceptedForLadder(criticalRun, parameters, ladder)) return criticalRun.validatedResult;\n\t\t\tif (feasibleAccepted(criticalRun.validatedResult, ladder.criticalEvictionTokenBudget)) return criticalRun.validatedResult;\n\t\t\tattempts.push({ ...criticalRun });\n\t\t} catch (error) {\n\t\t\tconst formattedError = error instanceof Error ? error : new Error(formatErrorMessage(error));\n\t\t\tif (signal?.aborted || formattedError.message === \"Context compaction failed: Request was aborted\") throw formattedError;\n\t\t\tattempts.push(runFailedAttempt(formattedError));\n\t\t}\n\t}\n\n\ttry {\n\t\treturn runDeterministicContextEviction(transcript, ladder.criticalEvictionTokenBudget);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : formatErrorMessage(error);\n\t\tthrow new Error(`${formatContextCompactionTargetFailureMessage(attempts, parameters)}; ${message}`);\n\t}\n}\n"]}
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import { type CompactableTranscript, type ContextCompactionParameters } from "./context-compaction-types.ts";
|
|
2
|
-
export declare function normalizeContextCompactionQuery(value: string | undefined, fallbackQuery: string): string;
|
|
3
|
-
export declare function normalizeContextCompactionParameters(input?: Partial<ContextCompactionParameters>, fallbackQuery?: string): ContextCompactionParameters;
|
|
4
|
-
export declare function getTranscriptCompactionParameters(transcript: CompactableTranscript): ContextCompactionParameters;
|
|
5
|
-
//# sourceMappingURL=context-compaction-strategy.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"context-compaction-strategy.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/context-compaction-strategy.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,KAAK,qBAAqB,EAC1B,KAAK,2BAA2B,EAChC,MAAM,+BAA+B,CAAC;AAcvC,wBAAgB,+BAA+B,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,aAAa,EAAE,MAAM,GAAG,MAAM,CAKxG;AAED,wBAAgB,oCAAoC,CACnD,KAAK,GAAE,OAAO,CAAC,2BAA2B,CAAM,EAChD,aAAa,GAAE,MAAsC,GACnD,2BAA2B,CAM7B;AAED,wBAAgB,iCAAiC,CAAC,UAAU,EAAE,qBAAqB,GAAG,2BAA2B,CAKhH","sourcesContent":["import {\n\tCONTEXT_COMPACTION_AUTO_QUERY,\n\tCONTEXT_COMPACTION_DEFAULT_COMPRESSION_RATIO,\n\tCONTEXT_COMPACTION_DEFAULT_PRESERVE_RECENT,\n\ttype CompactableTranscript,\n\ttype ContextCompactionParameters,\n} from \"./context-compaction-types.ts\";\n\nconst CONTEXT_COMPACTION_QUERY_MAX_CHARS = 1000;\n\nfunction normalizeCompressionRatio(value: number | undefined): number {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value > 0 && value < 1\n\t\t? value\n\t\t: CONTEXT_COMPACTION_DEFAULT_COMPRESSION_RATIO;\n}\n\nfunction normalizePreserveRecent(value: number | undefined): number {\n\treturn typeof value === \"number\" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : CONTEXT_COMPACTION_DEFAULT_PRESERVE_RECENT;\n}\n\nexport function normalizeContextCompactionQuery(value: string | undefined, fallbackQuery: string): string {\n\tconst query = value?.trim() || fallbackQuery.trim() || CONTEXT_COMPACTION_AUTO_QUERY;\n\treturn query.length > CONTEXT_COMPACTION_QUERY_MAX_CHARS\n\t\t? `${query.slice(0, CONTEXT_COMPACTION_QUERY_MAX_CHARS)}\\n[... ${query.length - CONTEXT_COMPACTION_QUERY_MAX_CHARS} more characters omitted from compaction query]`\n\t\t: query;\n}\n\nexport function normalizeContextCompactionParameters(\n\tinput: Partial<ContextCompactionParameters> = {},\n\tfallbackQuery: string = CONTEXT_COMPACTION_AUTO_QUERY,\n): ContextCompactionParameters {\n\treturn {\n\t\tcompression_ratio: normalizeCompressionRatio(input.compression_ratio),\n\t\tpreserve_recent: normalizePreserveRecent(input.preserve_recent),\n\t\tquery: normalizeContextCompactionQuery(input.query, fallbackQuery),\n\t};\n}\n\nexport function getTranscriptCompactionParameters(transcript: CompactableTranscript): ContextCompactionParameters {\n\treturn normalizeContextCompactionParameters(\n\t\ttranscript.parameters ?? transcript.settings,\n\t\ttranscript.parameters?.query ?? transcript.settings.query ?? CONTEXT_COMPACTION_AUTO_QUERY,\n\t);\n}\n"]}
|