@bastani/atomic 0.9.14 → 0.9.15
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 +45 -0
- package/README.md +1 -1
- package/dist/builtin/intercom/package.json +2 -2
- package/dist/builtin/mcp/CHANGELOG.md +14 -0
- package/dist/builtin/mcp/package.json +4 -4
- package/dist/builtin/mcp/sampling-handler.ts +2 -2
- package/dist/builtin/mcp/types.ts +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +40 -0
- package/dist/builtin/subagents/README.md +5 -22
- package/dist/builtin/subagents/agents/code-simplifier.md +2 -2
- package/dist/builtin/subagents/agents/codebase-analyzer.md +2 -2
- package/dist/builtin/subagents/agents/codebase-locator.md +2 -2
- package/dist/builtin/subagents/agents/codebase-online-researcher.md +2 -2
- package/dist/builtin/subagents/agents/codebase-pattern-finder.md +2 -2
- package/dist/builtin/subagents/agents/codebase-research-analyzer.md +2 -2
- package/dist/builtin/subagents/agents/codebase-research-locator.md +2 -2
- package/dist/builtin/subagents/agents/worker.md +2 -2
- package/dist/builtin/subagents/package.json +4 -4
- package/dist/builtin/subagents/skills/subagent/SKILL.md +6 -6
- package/dist/builtin/subagents/src/agents/agent-loaders.ts +0 -4
- package/dist/builtin/subagents/src/agents/agent-management-helpers.ts +1 -12
- package/dist/builtin/subagents/src/agents/agent-management.ts +0 -1
- package/dist/builtin/subagents/src/agents/agent-serializer.ts +7 -6
- package/dist/builtin/subagents/src/agents/agent-types.ts +0 -1
- package/dist/builtin/subagents/src/extension/schemas.ts +2 -2
- package/dist/builtin/subagents/src/extension/startup-maintenance.ts +2 -2
- package/dist/builtin/subagents/src/intercom/result-intercom.ts +0 -127
- package/dist/builtin/subagents/src/runs/foreground/inprocess-run-sync.ts +1 -3
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-context.ts +15 -106
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel-task.ts +0 -3
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel.ts +2 -13
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-single.ts +2 -12
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-status.ts +1 -20
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-types.ts +0 -6
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor.ts +10 -21
- package/dist/builtin/subagents/src/runs/inprocess/attempt-handles.ts +104 -0
- package/dist/builtin/subagents/src/runs/inprocess/index.ts +10 -21
- package/dist/builtin/subagents/src/runs/inprocess/prompt-behavior.ts +2 -3
- package/dist/builtin/subagents/src/runs/inprocess/runner.ts +11 -32
- package/dist/builtin/subagents/src/runs/inprocess/runtime-support/temp-cleanup.ts +69 -0
- package/dist/builtin/subagents/src/shared/model-resolution.ts +1 -1
- package/dist/builtin/subagents/src/shared/types-config.ts +0 -4
- package/dist/builtin/subagents/src/shared/types-depth.ts +15 -103
- package/dist/builtin/subagents/src/shared/types-foreground-state.ts +56 -0
- package/dist/builtin/subagents/src/shared/types-results.ts +1 -59
- package/dist/builtin/subagents/src/shared/types-runtime.ts +0 -2
- package/dist/builtin/subagents/src/shared/types.ts +1 -1
- package/dist/builtin/subagents/src/shared/utils.ts +1 -1
- package/dist/builtin/subagents/src/slash/slash-live-state.ts +1 -1
- package/dist/builtin/web-access/package.json +2 -2
- package/dist/builtin/web-access/summary-review.ts +2 -2
- package/dist/builtin/web-access/web-search-summary.ts +2 -2
- package/dist/builtin/workflows/CHANGELOG.md +30 -0
- package/dist/builtin/workflows/README.md +2 -2
- package/dist/builtin/workflows/package.json +2 -2
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +60473 -401
- package/dist/builtin/workflows/src/extension/public-types.ts +1 -1
- package/dist/builtin/workflows/src/extension/wiring.ts +1 -1
- package/dist/builtin/workflows/src/extension/workflow-heartbeat-delivery.ts +48 -4
- package/dist/builtin/workflows/src/extension/workflow-tool.ts +1 -1
- package/dist/builtin/workflows/src/runs/foreground/executor-stage-factory.ts +5 -0
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-controller.ts +35 -2
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-options.ts +1 -1
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-pause.ts +6 -0
- package/dist/builtin/workflows/src/tui/chat-surface-message.ts +15 -13
- package/dist/builtin/workflows/src/tui/store-widget-installer.ts +25 -2
- package/dist/bun/cli.js +1 -1
- package/dist/bun/cli.js.map +1 -1
- package/dist/bun/register-bedrock.js +2 -2
- package/dist/bun/register-bedrock.js.map +1 -1
- package/dist/cli/auth-check.d.ts +1 -1
- package/dist/cli/auth-check.d.ts.map +1 -1
- package/dist/cli/auth-check.js +1 -1
- package/dist/cli/auth-check.js.map +1 -1
- package/dist/cli/credential-print.d.ts +1 -1
- package/dist/cli/credential-print.d.ts.map +1 -1
- package/dist/cli/credential-print.js +2 -2
- package/dist/cli/credential-print.js.map +1 -1
- package/dist/cli/file-processor.d.ts +1 -1
- package/dist/cli/file-processor.d.ts.map +1 -1
- package/dist/cli/file-processor.js.map +1 -1
- package/dist/cli/initial-message.d.ts +1 -1
- package/dist/cli/initial-message.d.ts.map +1 -1
- package/dist/cli/initial-message.js.map +1 -1
- package/dist/cli/list-models.js.map +1 -1
- package/dist/core/agent-session-auto-compaction.d.ts +1 -1
- package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-auto-compaction.js +1 -1
- package/dist/core/agent-session-auto-compaction.js.map +1 -1
- package/dist/core/agent-session-events.d.ts +1 -1
- package/dist/core/agent-session-events.d.ts.map +1 -1
- package/dist/core/agent-session-events.js +1 -1
- package/dist/core/agent-session-events.js.map +1 -1
- package/dist/core/agent-session-export.js.map +1 -1
- package/dist/core/agent-session-extension-bindings.js +1 -1
- package/dist/core/agent-session-extension-bindings.js.map +1 -1
- package/dist/core/agent-session-message-queue.d.ts +1 -1
- package/dist/core/agent-session-message-queue.d.ts.map +1 -1
- package/dist/core/agent-session-message-queue.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +2 -2
- 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-models.d.ts +2 -2
- package/dist/core/agent-session-models.d.ts.map +1 -1
- package/dist/core/agent-session-models.js +2 -2
- package/dist/core/agent-session-models.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts +1 -1
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-retry.d.ts +1 -1
- package/dist/core/agent-session-retry.d.ts.map +1 -1
- package/dist/core/agent-session-retry.js +1 -1
- package/dist/core/agent-session-retry.js.map +1 -1
- package/dist/core/agent-session-runtime-auth.js +1 -1
- package/dist/core/agent-session-runtime-auth.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +1 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +1 -1
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +1 -1
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session-state.d.ts +1 -1
- package/dist/core/agent-session-state.d.ts.map +1 -1
- package/dist/core/agent-session-state.js.map +1 -1
- package/dist/core/agent-session-tree.js.map +1 -1
- package/dist/core/agent-session-types.d.ts +1 -1
- package/dist/core/agent-session-types.d.ts.map +1 -1
- package/dist/core/agent-session-types.js.map +1 -1
- package/dist/core/agent-session.d.ts +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/anthropic-thinking-guard.d.ts +1 -1
- package/dist/core/anthropic-thinking-guard.d.ts.map +1 -1
- package/dist/core/anthropic-thinking-guard.js +1 -1
- package/dist/core/anthropic-thinking-guard.js.map +1 -1
- package/dist/core/auth-storage.d.ts +1 -1
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/cache-stats.d.ts +1 -1
- package/dist/core/cache-stats.d.ts.map +1 -1
- package/dist/core/cache-stats.js.map +1 -1
- package/dist/core/cloudflare-gateway-binding.d.ts +1 -1
- package/dist/core/cloudflare-gateway-binding.d.ts.map +1 -1
- package/dist/core/cloudflare-gateway-binding.js +1 -1
- package/dist/core/cloudflare-gateway-binding.js.map +1 -1
- package/dist/core/codex-fast-mode.d.ts +2 -2
- package/dist/core/codex-fast-mode.d.ts.map +1 -1
- package/dist/core/codex-fast-mode.js +3 -2
- package/dist/core/codex-fast-mode.js.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts +2 -2
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +2 -2
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction-runner.d.ts +2 -2
- package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
- package/dist/core/compaction/compaction-runner.js.map +1 -1
- package/dist/core/compaction/compaction-types.d.ts +2 -2
- package/dist/core/compaction/compaction-types.d.ts.map +1 -1
- package/dist/core/compaction/compaction-types.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +1 -1
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/fallback-planner.d.ts +1 -1
- package/dist/core/compaction/fallback-planner.d.ts.map +1 -1
- package/dist/core/compaction/fallback-planner.js.map +1 -1
- package/dist/core/compaction/planner-outcome.d.ts +1 -1
- package/dist/core/compaction/planner-outcome.d.ts.map +1 -1
- package/dist/core/compaction/planner-outcome.js +1 -1
- package/dist/core/compaction/planner-outcome.js.map +1 -1
- package/dist/core/compaction/range-planner-diagnostics.d.ts +1 -1
- package/dist/core/compaction/range-planner-diagnostics.d.ts.map +1 -1
- package/dist/core/compaction/range-planner-diagnostics.js +1 -1
- package/dist/core/compaction/range-planner-diagnostics.js.map +1 -1
- package/dist/core/compaction/range-planner.d.ts +2 -2
- package/dist/core/compaction/range-planner.d.ts.map +1 -1
- package/dist/core/compaction/range-planner.js +2 -2
- package/dist/core/compaction/range-planner.js.map +1 -1
- package/dist/core/compaction/session-summarization.d.ts +2 -2
- package/dist/core/compaction/session-summarization.d.ts.map +1 -1
- package/dist/core/compaction/session-summarization.js +2 -2
- package/dist/core/compaction/session-summarization.js.map +1 -1
- package/dist/core/compaction/transcript-serialization.d.ts +1 -1
- package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
- package/dist/core/compaction/transcript-serialization.js.map +1 -1
- package/dist/core/compaction/utils.d.ts +1 -1
- package/dist/core/compaction/utils.d.ts.map +1 -1
- package/dist/core/compaction/utils.js.map +1 -1
- package/dist/core/experimental.d.ts +1 -1
- package/dist/core/experimental.d.ts.map +1 -1
- package/dist/core/experimental.js.map +1 -1
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/agent-events.d.ts +2 -2
- package/dist/core/extensions/agent-events.d.ts.map +1 -1
- package/dist/core/extensions/agent-events.js.map +1 -1
- package/dist/core/extensions/api-types.d.ts +2 -2
- package/dist/core/extensions/api-types.d.ts.map +1 -1
- package/dist/core/extensions/api-types.js.map +1 -1
- package/dist/core/extensions/context-types.d.ts +1 -7
- 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 +1 -1
- 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/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader-api.js.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.js +21 -9
- package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
- package/dist/core/extensions/provider-types.d.ts +2 -2
- package/dist/core/extensions/provider-types.d.ts.map +1 -1
- package/dist/core/extensions/provider-types.js.map +1 -1
- package/dist/core/extensions/reactive-widget.d.ts +6 -0
- package/dist/core/extensions/reactive-widget.d.ts.map +1 -1
- package/dist/core/extensions/reactive-widget.js +62 -6
- package/dist/core/extensions/reactive-widget.js.map +1 -1
- package/dist/core/extensions/runner-context.d.ts +1 -1
- package/dist/core/extensions/runner-context.d.ts.map +1 -1
- package/dist/core/extensions/runner-context.js.map +1 -1
- package/dist/core/extensions/runner-events.d.ts +1 -1
- package/dist/core/extensions/runner-events.d.ts.map +1 -1
- package/dist/core/extensions/runner-events.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +2 -2
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/runtime-types.d.ts +2 -2
- package/dist/core/extensions/runtime-types.d.ts.map +1 -1
- package/dist/core/extensions/runtime-types.js.map +1 -1
- package/dist/core/extensions/tool-events.d.ts +1 -1
- package/dist/core/extensions/tool-events.d.ts.map +1 -1
- package/dist/core/extensions/tool-events.js.map +1 -1
- package/dist/core/extensions/tool-types.d.ts +2 -2
- package/dist/core/extensions/tool-types.d.ts.map +1 -1
- package/dist/core/extensions/tool-types.js.map +1 -1
- package/dist/core/extensions/ui-types.d.ts +2 -0
- package/dist/core/extensions/ui-types.d.ts.map +1 -1
- package/dist/core/extensions/ui-types.js.map +1 -1
- package/dist/core/fallback-models.d.ts +1 -1
- package/dist/core/fallback-models.d.ts.map +1 -1
- package/dist/core/fallback-models.js.map +1 -1
- package/dist/core/http-dispatcher.d.ts.map +1 -1
- package/dist/core/http-dispatcher.js +14 -0
- package/dist/core/http-dispatcher.js.map +1 -1
- package/dist/core/messages.d.ts +1 -1
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js.map +1 -1
- package/dist/core/model-capabilities.d.ts +1 -1
- package/dist/core/model-capabilities.d.ts.map +1 -1
- package/dist/core/model-capabilities.js.map +1 -1
- package/dist/core/model-fallback-failures.d.ts.map +1 -1
- package/dist/core/model-fallback-failures.js +18 -1
- package/dist/core/model-fallback-failures.js.map +1 -1
- package/dist/core/model-registry.d.ts +1 -1
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver-cli.js.map +1 -1
- package/dist/core/model-resolver-defaults.d.ts +1 -1
- package/dist/core/model-resolver-defaults.d.ts.map +1 -1
- package/dist/core/model-resolver-defaults.js +1 -1
- package/dist/core/model-resolver-defaults.js.map +1 -1
- package/dist/core/model-resolver-initial.d.ts +1 -1
- package/dist/core/model-resolver-initial.d.ts.map +1 -1
- package/dist/core/model-resolver-initial.js.map +1 -1
- package/dist/core/model-resolver-patterns.d.ts +1 -1
- package/dist/core/model-resolver-patterns.d.ts.map +1 -1
- package/dist/core/model-resolver-patterns.js.map +1 -1
- package/dist/core/model-resolver-scope.d.ts +1 -1
- package/dist/core/model-resolver-scope.d.ts.map +1 -1
- package/dist/core/model-resolver-scope.js +1 -1
- package/dist/core/model-resolver-scope.js.map +1 -1
- package/dist/core/model-resolver-types.d.ts +1 -1
- package/dist/core/model-resolver-types.d.ts.map +1 -1
- package/dist/core/model-resolver-types.js.map +1 -1
- package/dist/core/model-runtime-auth.d.ts +1 -1
- package/dist/core/model-runtime-auth.d.ts.map +1 -1
- package/dist/core/model-runtime-auth.js.map +1 -1
- package/dist/core/model-runtime-providers.d.ts +2 -2
- package/dist/core/model-runtime-providers.d.ts.map +1 -1
- package/dist/core/model-runtime-providers.js +2 -2
- package/dist/core/model-runtime-providers.js.map +1 -1
- package/dist/core/model-runtime-restoration.d.ts +1 -1
- package/dist/core/model-runtime-restoration.d.ts.map +1 -1
- package/dist/core/model-runtime-restoration.js.map +1 -1
- package/dist/core/model-runtime-snapshot.d.ts +1 -1
- package/dist/core/model-runtime-snapshot.d.ts.map +1 -1
- package/dist/core/model-runtime-snapshot.js.map +1 -1
- package/dist/core/model-runtime-streaming.d.ts +1 -1
- package/dist/core/model-runtime-streaming.d.ts.map +1 -1
- package/dist/core/model-runtime-streaming.js +1 -1
- package/dist/core/model-runtime-streaming.js.map +1 -1
- package/dist/core/model-runtime-types.d.ts +1 -1
- package/dist/core/model-runtime-types.d.ts.map +1 -1
- package/dist/core/model-runtime-types.js.map +1 -1
- package/dist/core/model-runtime.d.ts +8 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +15 -3
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/models-store.d.ts +1 -1
- package/dist/core/models-store.d.ts.map +1 -1
- package/dist/core/models-store.js.map +1 -1
- package/dist/core/oauth-login.d.ts +1 -1
- package/dist/core/oauth-login.d.ts.map +1 -1
- package/dist/core/oauth-login.js.map +1 -1
- package/dist/core/oauth-provider-metadata.d.ts +1 -1
- package/dist/core/oauth-provider-metadata.d.ts.map +1 -1
- package/dist/core/oauth-provider-metadata.js.map +1 -1
- package/dist/core/openai-responses-payload-sanitizer.d.ts +1 -1
- package/dist/core/openai-responses-payload-sanitizer.d.ts.map +1 -1
- package/dist/core/openai-responses-payload-sanitizer.js.map +1 -1
- package/dist/core/provider-attribution.d.ts +1 -1
- package/dist/core/provider-attribution.d.ts.map +1 -1
- package/dist/core/provider-attribution.js.map +1 -1
- package/dist/core/provider-composer-internal.d.ts +1 -1
- package/dist/core/provider-composer-internal.d.ts.map +1 -1
- package/dist/core/provider-composer-internal.js.map +1 -1
- package/dist/core/provider-composer.d.ts +1 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +2 -2
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/provider-context-usage.d.ts.map +1 -1
- package/dist/core/provider-context-usage.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts +1 -1
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/runtime-credentials.d.ts +1 -1
- package/dist/core/runtime-credentials.d.ts.map +1 -1
- package/dist/core/runtime-credentials.js.map +1 -1
- package/dist/core/sdk-types.d.ts +1 -1
- package/dist/core/sdk-types.d.ts.map +1 -1
- package/dist/core/sdk-types.js.map +1 -1
- package/dist/core/sdk.d.ts +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +30 -6
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager-core.d.ts +2 -2
- package/dist/core/session-manager-core.d.ts.map +1 -1
- package/dist/core/session-manager-core.js.map +1 -1
- package/dist/core/session-manager-entries.d.ts +1 -1
- package/dist/core/session-manager-entries.d.ts.map +1 -1
- package/dist/core/session-manager-entries.js.map +1 -1
- package/dist/core/session-manager-list.js.map +1 -1
- package/dist/core/session-manager-types.d.ts +1 -1
- 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-validation.js +1 -1
- package/dist/core/session-manager-validation.js.map +1 -1
- package/dist/core/settings-manager-basic-accessors.d.ts +1 -0
- package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
- package/dist/core/settings-manager-basic-accessors.js +11 -0
- package/dist/core/settings-manager-basic-accessors.js.map +1 -1
- package/dist/core/settings-types.d.ts +2 -1
- package/dist/core/settings-types.d.ts.map +1 -1
- package/dist/core/settings-types.js.map +1 -1
- package/dist/core/summarization-retry.d.ts +1 -1
- package/dist/core/summarization-retry.d.ts.map +1 -1
- package/dist/core/summarization-retry.js.map +1 -1
- package/dist/core/tools/bash-session-environment.d.ts +1 -1
- package/dist/core/tools/bash-session-environment.d.ts.map +1 -1
- package/dist/core/tools/bash-session-environment.js.map +1 -1
- package/dist/core/tools/oversized-tool-result.d.ts +1 -1
- package/dist/core/tools/oversized-tool-result.d.ts.map +1 -1
- package/dist/core/tools/oversized-tool-result.js.map +1 -1
- package/dist/core/tools/read-url.d.ts +1 -1
- package/dist/core/tools/read-url.d.ts.map +1 -1
- package/dist/core/tools/read-url.js.map +1 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/render-utils.d.ts +1 -1
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/tools/resource-selectors.d.ts +1 -1
- package/dist/core/tools/resource-selectors.d.ts.map +1 -1
- package/dist/core/tools/resource-selectors.js +2 -7
- package/dist/core/tools/resource-selectors.js.map +1 -1
- package/dist/core/typebox-compat.js +1 -1
- package/dist/core/typebox-compat.js.map +1 -1
- package/dist/core/usage-totals.d.ts +1 -1
- package/dist/core/usage-totals.d.ts.map +1 -1
- package/dist/core/usage-totals.js.map +1 -1
- package/dist/extensions/llama/provider.d.ts +1 -1
- package/dist/extensions/llama/provider.d.ts.map +1 -1
- package/dist/extensions/llama/provider.js +1 -1
- package/dist/extensions/llama/provider.js.map +1 -1
- package/dist/main-app-mode.d.ts +1 -1
- package/dist/main-app-mode.d.ts.map +1 -1
- package/dist/main-app-mode.js.map +1 -1
- package/dist/main-session-options.js +1 -1
- package/dist/main-session-options.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/chat-message-renderer.d.ts +1 -1
- package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
- package/dist/modes/interactive/components/custom-message.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +1 -1
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector-handlers.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector-types.d.ts +1 -1
- package/dist/modes/interactive/components/settings-selector-types.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
- package/dist/modes/interactive/interactive-auth-routing.js +1 -1
- package/dist/modes/interactive/interactive-auth-routing.js.map +1 -1
- package/dist/modes/interactive/interactive-deferred-startup.js +1 -1
- package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
- package/dist/modes/interactive/interactive-extension-context.js +26 -0
- package/dist/modes/interactive/interactive-extension-context.js.map +1 -1
- package/dist/modes/interactive/interactive-extension-runtime.js +7 -2
- package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.d.ts +1 -0
- package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.js +1 -0
- package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-deps.d.ts +1 -1
- 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-helpers.js +1 -1
- package/dist/modes/interactive/interactive-mode-helpers.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.d.ts +2 -0
- 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/model-catalog-refresh.d.ts +1 -1
- package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -1
- package/dist/modes/interactive/model-catalog-refresh.js.map +1 -1
- package/dist/modes/interactive/streaming-assistant-message.d.ts +1 -1
- package/dist/modes/interactive/streaming-assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/streaming-assistant-message.js.map +1 -1
- package/dist/modes/interactive-engine/engine-custom-ui.d.ts +3 -0
- package/dist/modes/interactive-engine/engine-custom-ui.d.ts.map +1 -1
- package/dist/modes/interactive-engine/engine-custom-ui.js +26 -3
- package/dist/modes/interactive-engine/engine-custom-ui.js.map +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
- package/dist/modes/interactive-engine/remote-component.d.ts +2 -1
- package/dist/modes/interactive-engine/remote-component.d.ts.map +1 -1
- package/dist/modes/interactive-engine/remote-component.js +14 -0
- package/dist/modes/interactive-engine/remote-component.js.map +1 -1
- package/dist/modes/interactive-engine/remote-model-catalog.js.map +1 -1
- package/dist/modes/json-event.d.ts +1 -1
- package/dist/modes/json-event.d.ts.map +1 -1
- package/dist/modes/json-event.js.map +1 -1
- package/dist/modes/print-mode.d.ts +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-client-api.d.ts +2 -2
- package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client-api.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +1 -1
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-extension-ui.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-extension-ui.js +4 -1
- package/dist/modes/rpc/rpc-extension-ui.js.map +1 -1
- package/dist/modes/rpc/rpc-provider-auth.d.ts +1 -1
- package/dist/modes/rpc/rpc-provider-auth.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-provider-auth.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +2 -2
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/utils/tool-result-images.d.ts +1 -1
- package/dist/utils/tool-result-images.d.ts.map +1 -1
- package/dist/utils/tool-result-images.js.map +1 -1
- package/docs/custom-provider.md +11 -8
- package/docs/development.md +0 -2
- package/docs/extensions.md +2 -2
- package/docs/json.md +1 -1
- package/docs/models/artificial-analysis-index.md +2 -2
- package/docs/models/model-selection.md +8 -8
- package/docs/models/pareto-efficiency.md +10 -10
- package/docs/models.md +9 -3
- package/docs/packages.md +1 -1
- package/docs/providers.md +5 -3
- package/docs/quickstart.md +1 -1
- package/docs/rpc.md +1 -1
- package/docs/sdk.md +2 -2
- package/docs/session-format.md +2 -2
- package/docs/settings.md +2 -1
- package/docs/subagents.md +5 -6
- package/docs/tui.md +3 -0
- package/docs/workflows.md +3 -1
- package/examples/extensions/README.md +1 -1
- package/examples/extensions/custom-footer.ts +1 -1
- package/examples/extensions/custom-provider-anthropic/index.ts +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/index.ts +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/test.ts +1 -1
- package/examples/extensions/handoff.ts +2 -2
- package/examples/extensions/hello.ts +1 -1
- package/examples/extensions/plan-mode/index.ts +1 -1
- package/examples/extensions/preset.ts +1 -1
- package/examples/extensions/qna.ts +1 -1
- package/examples/extensions/subagent/display.ts +1 -1
- package/examples/extensions/subagent/runner.ts +1 -1
- package/examples/extensions/subagent/types.ts +1 -1
- package/examples/extensions/summarize.ts +2 -2
- package/examples/extensions/tool-override.ts +1 -1
- package/examples/sdk/02-custom-model.ts +1 -1
- package/examples/sdk/12-full-control.ts +1 -1
- package/examples/sdk/README.md +1 -1
- package/npm-shrinkwrap.json +54 -31
- package/package.json +3 -3
- package/dist/builtin/subagents/src/extension/fanout-child.ts +0 -259
- package/dist/builtin/subagents/src/runs/inprocess/nested-routing.ts +0 -218
- package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-api.ts +0 -55
- package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-control.ts +0 -178
- package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-core.ts +0 -187
- package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-paths.ts +0 -57
- package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-projection.ts +0 -42
- package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-registry.ts +0 -352
- package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-rendering.ts +0 -136
- package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-sanitize.ts +0 -252
- package/dist/builtin/subagents/src/shared/types-nested.ts +0 -127
- package/dist/core/copilot-env-routing.d.ts +0 -36
- package/dist/core/copilot-env-routing.d.ts.map +0 -1
- package/dist/core/copilot-env-routing.js +0 -94
- package/dist/core/copilot-env-routing.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-stats.js","sourceRoot":"","sources":["../../src/core/cache-stats.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAC1C,MAAM,oBAAoB,GAAG,MAAM,CAAC;AACpC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAuBhC,SAAS,MAAM,CACd,IAAiC,EACjC,OAAyB,EACzB,MAAwB;IAExB,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;IAC5B,MAAM,YAAY,GAAG,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,UAAU,CAAC;IACtE,IAAI,CAAC,IAAI,IAAI,YAAY,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,UAAU,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC;QAClG,OAAO,SAAS,CAAC;IAClB,MAAM,YAAY,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,EAAE,YAAY,CAAC,GAAG,KAAK,CAAC,SAAS,CAAC;IACjF,IAAI,YAAY,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC;I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CAAC;IACD,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AACjC,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,OAAuB,EAAE,MAAwB;IAClF,OAAO,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC;AACrC,CAAC;AACD,MAAM,UAAU,kBAAkB,CACjC,OAAuB,EACvB,MAAwB;IAExB,OAAO,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC;AACrC,CAAC;AACD,MAAM,UAAU,eAAe,CAC9B,OAAuB,EACvB,OAAyB,EACzB,MAAwB;IAExB,OAAO,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["import type { AssistantMessage } from \"@
|
|
1
|
+
{"version":3,"file":"cache-stats.js","sourceRoot":"","sources":["../../src/core/cache-stats.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAC1C,MAAM,oBAAoB,GAAG,MAAM,CAAC;AACpC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAuBhC,SAAS,MAAM,CACd,IAAiC,EACjC,OAAyB,EACzB,MAAwB;IAExB,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;IAC5B,MAAM,YAAY,GAAG,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,UAAU,CAAC;IACtE,IAAI,CAAC,IAAI,IAAI,YAAY,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC,UAAU,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC;QAClG,OAAO,SAAS,CAAC;IAClB,MAAM,YAAY,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,EAA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G,QAAQ,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,EAAE,aAAa,IAAI,KAAK,CAAC,IAAI,IAAI,CAAC;IACtE,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AACjC,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,OAAuB,EAAE,MAAwB;IAClF,OAAO,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC;AACrC,CAAC;AACD,MAAM,UAAU,kBAAkB,CACjC,OAAuB,EACvB,MAAwB;IAExB,OAAO,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC;AACrC,CAAC;AACD,MAAM,UAAU,eAAe,CAC9B,OAAuB,EACvB,OAAyB,EACzB,MAAwB;IAExB,OAAO,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["import type { AssistantMessage } from \"@bastani/pi-ai/compat\";\nimport type { SessionEntry } from \"./session-manager.ts\";\n\nexport const CACHE_TTL_MS = 5 * 60 * 1000;\nconst MISS_TOKEN_THRESHOLD = 20_000;\nconst MISS_COST_THRESHOLD = 0.1;\n\nexport interface CacheMiss {\n\tmissedTokens: number;\n\tmissedCost: number;\n\tidleMs: number;\n\tmodelChanged: boolean;\n}\nexport interface CacheWasteTotals {\n\tmissedTokens: number;\n\tmissedCost: number;\n\tmissCount: number;\n}\nexport interface ModelPriceSource {\n\tgetModel(provider: string, modelId: string): { cost: { cacheRead: number } } | undefined;\n}\ninterface PreviousRequest {\n\tpromptTokens: number;\n\tmodelKey: string;\n\ttimestamp: number;\n\treportedCache: boolean;\n}\n\nfunction detect(\n\tprev: PreviousRequest | undefined,\n\tmessage: AssistantMessage,\n\tmodels: ModelPriceSource,\n): CacheMiss | undefined {\n\tconst usage = message.usage;\n\tconst promptTokens = usage.input + usage.cacheRead + usage.cacheWrite;\n\tif (!prev || promptTokens <= 0 || (usage.cacheRead + usage.cacheWrite === 0 && !prev.reportedCache))\n\t\treturn undefined;\n\tconst missedTokens = Math.min(prev.promptTokens, promptTokens) - usage.cacheRead;\n\tif (missedTokens <= 0) return undefined;\n\tconst paidTokens = usage.input + usage.cacheWrite;\n\tconst paidRate = paidTokens > 0 ? (usage.cost.input + usage.cost.cacheWrite) / paidTokens : 0;\n\tconst readRate =\n\t\tusage.cacheRead > 0\n\t\t\t? usage.cost.cacheRead / usage.cacheRead\n\t\t\t: (models.getModel(message.provider, message.model)?.cost.cacheRead ?? 0) / 1_000_000;\n\tconst missedCost = missedTokens * Math.max(0, paidRate - readRate);\n\tif (missedTokens < MISS_TOKEN_THRESHOLD && missedCost < MISS_COST_THRESHOLD) return undefined;\n\treturn {\n\t\tmissedTokens,\n\t\tmissedCost,\n\t\tidleMs: Math.max(0, message.timestamp - prev.timestamp),\n\t\tmodelChanged: `${message.provider}/${message.model}` !== prev.modelKey,\n\t};\n}\n\nfunction previous(message: AssistantMessage, reportedCache: boolean): PreviousRequest | undefined {\n\tconst usage = message.usage;\n\tconst promptTokens = usage.input + usage.cacheRead + usage.cacheWrite;\n\treturn promptTokens > 0\n\t\t? {\n\t\t\t\tpromptTokens,\n\t\t\t\tmodelKey: `${message.provider}/${message.model}`,\n\t\t\t\ttimestamp: message.timestamp,\n\t\t\t\treportedCache: reportedCache || usage.cacheRead + usage.cacheWrite > 0,\n\t\t\t}\n\t\t: undefined;\n}\n\nfunction scan(entries: SessionEntry[], models: ModelPriceSource) {\n\tlet prev: PreviousRequest | undefined;\n\tconst totals: CacheWasteTotals = { missedTokens: 0, missedCost: 0, missCount: 0 };\n\tconst misses = new Map<AssistantMessage, CacheMiss>();\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"compaction\" || entry.type === \"branch_summary\") {\n\t\t\tprev = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.type !== \"message\" || entry.message.role !== \"assistant\") continue;\n\t\tconst miss = detect(prev, entry.message, models);\n\t\tif (miss) {\n\t\t\ttotals.missedTokens += miss.missedTokens;\n\t\t\ttotals.missedCost += miss.missedCost;\n\t\t\ttotals.missCount++;\n\t\t\tmisses.set(entry.message, miss);\n\t\t}\n\t\tprev = previous(entry.message, prev?.reportedCache ?? false) ?? prev;\n\t}\n\treturn { prev, totals, misses };\n}\n\nexport function computeCacheWaste(entries: SessionEntry[], models: ModelPriceSource): CacheWasteTotals {\n\treturn scan(entries, models).totals;\n}\nexport function collectCacheMisses(\n\tentries: SessionEntry[],\n\tmodels: ModelPriceSource,\n): Map<AssistantMessage, CacheMiss> {\n\treturn scan(entries, models).misses;\n}\nexport function detectCacheMiss(\n\tentries: SessionEntry[],\n\tmessage: AssistantMessage,\n\tmodels: ModelPriceSource,\n): CacheMiss | undefined {\n\treturn detect(scan(entries, models).prev, message, models);\n}\n"]}
|
|
@@ -7,5 +7,5 @@
|
|
|
7
7
|
* `CLOUDFLARE_API_KEY` stays the default for everywhere else. See
|
|
8
8
|
* `docs/providers.md` → "Cloudflare AI Gateway" for a working provider-extension example.
|
|
9
9
|
*/
|
|
10
|
-
export { type AiGatewayBinding, type AiGatewayBindingGateway, type AiGatewayUniversalRequestLike, CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, createGatewayBindingFetch, type GatewayBindingFetchOptions, } from "@
|
|
10
|
+
export { type AiGatewayBinding, type AiGatewayBindingGateway, type AiGatewayUniversalRequestLike, CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, createGatewayBindingFetch, type GatewayBindingFetchOptions, } from "@bastani/pi-ai/api/cloudflare-gateway-binding";
|
|
11
11
|
//# sourceMappingURL=cloudflare-gateway-binding.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cloudflare-gateway-binding.d.ts","sourceRoot":"","sources":["../../src/core/cloudflare-gateway-binding.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EACN,KAAK,gBAAgB,EACrB,KAAK,uBAAuB,EAC5B,KAAK,6BAA6B,EAClC,wCAAwC,EACxC,yBAAyB,EACzB,KAAK,0BAA0B,GAC/B,MAAM,
|
|
1
|
+
{"version":3,"file":"cloudflare-gateway-binding.d.ts","sourceRoot":"","sources":["../../src/core/cloudflare-gateway-binding.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EACN,KAAK,gBAAgB,EACrB,KAAK,uBAAuB,EAC5B,KAAK,6BAA6B,EAClC,wCAAwC,EACxC,yBAAyB,EACzB,KAAK,0BAA0B,GAC/B,MAAM,+CAA+C,CAAC"}
|
|
@@ -7,5 +7,5 @@
|
|
|
7
7
|
* `CLOUDFLARE_API_KEY` stays the default for everywhere else. See
|
|
8
8
|
* `docs/providers.md` → "Cloudflare AI Gateway" for a working provider-extension example.
|
|
9
9
|
*/
|
|
10
|
-
export { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, createGatewayBindingFetch, } from "@
|
|
10
|
+
export { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, createGatewayBindingFetch, } from "@bastani/pi-ai/api/cloudflare-gateway-binding";
|
|
11
11
|
//# sourceMappingURL=cloudflare-gateway-binding.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cloudflare-gateway-binding.js","sourceRoot":"","sources":["../../src/core/cloudflare-gateway-binding.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAIN,wCAAwC,EACxC,yBAAyB,GAEzB,MAAM,
|
|
1
|
+
{"version":3,"file":"cloudflare-gateway-binding.js","sourceRoot":"","sources":["../../src/core/cloudflare-gateway-binding.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAIN,wCAAwC,EACxC,yBAAyB,GAEzB,MAAM,+CAA+C,CAAC","sourcesContent":["/**\n * Cloudflare AI Gateway transport over the Workers AI binding.\n *\n * pi-ai ships this transport (upstream #7901); Atomic re-exports it so SDK users and\n * extension authors can route gateway requests through `env.AI` with **no API token**:\n * binding calls are pre-authenticated in the gateway's own account. The HTTPS route with\n * `CLOUDFLARE_API_KEY` stays the default for everywhere else. See\n * `docs/providers.md` → \"Cloudflare AI Gateway\" for a working provider-extension example.\n */\nexport {\n\ttype AiGatewayBinding,\n\ttype AiGatewayBindingGateway,\n\ttype AiGatewayUniversalRequestLike,\n\tCLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL,\n\tcreateGatewayBindingFetch,\n\ttype GatewayBindingFetchOptions,\n} from \"@bastani/pi-ai/api/cloudflare-gateway-binding\";\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { closeOpenAICodexWebSocketSessions } from "@
|
|
2
|
-
import { type Api, type AssistantMessageEventStream, type Context, type Model, type OpenAICodexResponsesOptions, type OpenAIResponsesOptions, type ProviderHeaders, type SimpleStreamOptions, type StreamOptions, type ThinkingLevel } from "@
|
|
1
|
+
import { closeOpenAICodexWebSocketSessions } from "@bastani/pi-ai/api/openai-codex-responses";
|
|
2
|
+
import { type Api, type AssistantMessageEventStream, type Context, type Model, type OpenAICodexResponsesOptions, type OpenAIResponsesOptions, type ProviderHeaders, type SimpleStreamOptions, type StreamOptions, type ThinkingLevel } from "@bastani/pi-ai/compat";
|
|
3
3
|
import type { OrchestrationContext } from "./extensions/index.ts";
|
|
4
4
|
export declare const CODEX_FAST_MODE_SERVICE_TIER: "priority";
|
|
5
5
|
export interface CodexFastModeResolvedSettings {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codex-fast-mode.d.ts","sourceRoot":"","sources":["../../src/core/codex-fast-mode.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"codex-fast-mode.d.ts","sourceRoot":"","sources":["../../src/core/codex-fast-mode.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,2CAA2C,CAAC;AAC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AAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,0BAA0B,GAAG,SAAS,EAC/C,SAAS,GAAE,sBAA0D,GACnE,2BAA2B,CAyB7B;AAMD,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CASpF;AAED,wBAAgB,6BAA6B,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,MAAM,CAEzF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { closeOpenAICodexWebSocketSessions } from "@
|
|
2
|
-
import { clampThinkingLevel, streamOpenAICodexResponses, streamOpenAIResponses, streamSimple, } from "@
|
|
1
|
+
import { closeOpenAICodexWebSocketSessions } from "@bastani/pi-ai/api/openai-codex-responses";
|
|
2
|
+
import { clampThinkingLevel, streamOpenAICodexResponses, streamOpenAIResponses, streamSimple, } from "@bastani/pi-ai/compat";
|
|
3
3
|
import { CODEX_FAST_MODE_ORIGINATOR, CODEX_FAST_MODE_ROUTING_HEADER, clearCodexFastModeRequestMarker, installCodexFastModeWebSocketIdentity, isFirstPartyCodexBaseUrl, markCodexFastModeRequest, wrapCodexFastModeFetch, } from "./codex-fast-mode-transport.js";
|
|
4
4
|
export const CODEX_FAST_MODE_SERVICE_TIER = "priority";
|
|
5
5
|
const DEFAULT_CODEX_FAST_MODE_STREAMERS = {
|
|
@@ -173,6 +173,7 @@ function buildCodexFastModeBaseProviderOptions(model, options) {
|
|
|
173
173
|
headers: options?.headers,
|
|
174
174
|
timeoutMs: options?.timeoutMs,
|
|
175
175
|
websocketConnectTimeoutMs: options?.websocketConnectTimeoutMs,
|
|
176
|
+
streamDeadlineMs: options?.streamDeadlineMs,
|
|
176
177
|
maxRetries: options?.maxRetries,
|
|
177
178
|
maxRetryDelayMs: options?.maxRetryDelayMs,
|
|
178
179
|
metadata: options?.metadata,
|
|
@@ -1 +1 @@
|
|
|
1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AAE,OAAO,EAAE,OAAO,CAAC,CAAC;AACxD,CAAC;AAED,SAAS,eAAe,CAAC,OAAgB;IACxC,OAAO,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;AACnF,CAAC;AAED,MAAM,UAAU,wBAAwB,CAAC,OAAgB,EAAE,OAAgB;IAC1E,IAAI,CAAC,OAAO,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,YAAY,KAAK,SAAS,EAAE,CAAC;QACjF,OAAO,OAAO,CAAC;IAChB,CAAC;IAED,OAAO;QACN,GAAG,OAAO;QACV,YAAY,EAAE,4BAA4B;KAC1C,CAAC;AACH,CAAC;AAED,MAAM,UAAU,6BAA6B,CAAC,SAAiB,EAAE,OAAgB;IAChF,OAAO,OAAO,CAAC,CAAC,CAAC,GAAG,SAAS,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AAClD,CAAC","sourcesContent":["import { closeOpenAICodexWebSocketSessions } from \"@earendil-works/pi-ai/api/openai-codex-responses\";\nimport {\n\ttype Api,\n\ttype AssistantMessageEventStream,\n\ttype Context,\n\tclampThinkingLevel,\n\ttype Model,\n\ttype OpenAICodexResponsesOptions,\n\ttype OpenAIResponsesOptions,\n\ttype ProviderHeaders,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n\tstreamOpenAICodexResponses,\n\tstreamOpenAIResponses,\n\tstreamSimple,\n\ttype ThinkingLevel,\n} from \"@earendil-works/pi-ai/compat\";\nimport {\n\tCODEX_FAST_MODE_ORIGINATOR,\n\tCODEX_FAST_MODE_ROUTING_HEADER,\n\tclearCodexFastModeRequestMarker,\n\tinstallCodexFastModeWebSocketIdentity,\n\tisFirstPartyCodexBaseUrl,\n\tmarkCodexFastModeRequest,\n\twrapCodexFastModeFetch,\n} from \"./codex-fast-mode-transport.ts\";\nimport type { OrchestrationContext } from \"./extensions/index.ts\";\n\nexport const CODEX_FAST_MODE_SERVICE_TIER = \"priority\" as const;\n\nexport interface CodexFastModeResolvedSettings {\n\tchat: boolean;\n\tworkflow: boolean;\n}\n\nexport type CodexFastModeScope = \"chat\" | \"workflow\";\n\nexport interface CodexFastModeStreamOptions extends SimpleStreamOptions {\n\tserviceTier?: typeof CODEX_FAST_MODE_SERVICE_TIER;\n}\n\nexport interface CodexFastModeStreamers {\n\tstreamSimple: (model: Model<Api>, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\tstreamOpenAIResponses: (\n\t\tmodel: Model<\"openai-responses\">,\n\t\tcontext: Context,\n\t\toptions?: OpenAIResponsesOptions,\n\t) => AssistantMessageEventStream;\n\tstreamOpenAICodexResponses: (\n\t\tmodel: Model<\"openai-codex-responses\">,\n\t\tcontext: Context,\n\t\toptions?: OpenAICodexResponsesOptions,\n\t) => AssistantMessageEventStream;\n}\n\nconst DEFAULT_CODEX_FAST_MODE_STREAMERS: CodexFastModeStreamers = {\n\tstreamSimple,\n\tstreamOpenAIResponses,\n\tstreamOpenAICodexResponses,\n};\n\ntype CodexFastModeModelIdentity = Pick<Model<Api>, \"provider\"> & Partial<Pick<Model<Api>, \"api\">>;\n\nconst CODEX_WEBSOCKET_ROUTING_STATE_IDLE_MS = 6 * 60 * 1000;\nconst codexWebSocketRoutingState = new Map<string, { signature: string; expiry: ReturnType<typeof setTimeout> }>();\n\nexport function isCodexFastModeSupportedProvider(provider: string): boolean {\n\treturn provider === \"openai\" || provider === \"openai-codex\";\n}\n\nexport function isCodexFastModeCandidateModelId(modelId: string | undefined): boolean {\n\tconst provider = modelId?.split(\"/\", 1)[0];\n\treturn provider !== undefined && isCodexFastModeSupportedProvider(provider);\n}\n\nexport function isCodexFastModeSupportedModel(model: CodexFastModeModelIdentity): boolean {\n\treturn isCodexFastModeSupportedProvider(model.provider) || model.api === \"openai-codex-responses\";\n}\n\nexport function hasSupportedCodexFastModeModel(models: readonly CodexFastModeModelIdentity[]): boolean {\n\treturn models.some(isCodexFastModeSupportedModel);\n}\n\nexport function isWorkflowStageOrchestrationContext(context: OrchestrationContext | undefined): boolean {\n\treturn context?.kind === \"workflow-stage\";\n}\n\nexport function getCodexFastModeScope(context: OrchestrationContext | undefined): CodexFastModeScope {\n\treturn isWorkflowStageOrchestrationContext(context) ? \"workflow\" : \"chat\";\n}\n\nexport function isCodexFastModeEnabledForScope(\n\tsettings: CodexFastModeResolvedSettings,\n\tscope: CodexFastModeScope,\n): boolean {\n\treturn settings[scope];\n}\n\nexport function isCodexFastModeEnabledForSession(\n\tsettings: CodexFastModeResolvedSettings,\n\tcontext: OrchestrationContext | undefined,\n): boolean {\n\treturn isCodexFastModeEnabledForScope(settings, getCodexFastModeScope(context));\n}\n\nexport function shouldApplyCodexFastModeForScope(\n\tmodel: CodexFastModeModelIdentity,\n\tsettings: CodexFastModeResolvedSettings,\n\tscope: CodexFastModeScope,\n): boolean {\n\treturn isCodexFastModeSupportedModel(model) && isCodexFastModeEnabledForScope(settings, scope);\n}\n\nexport function shouldApplyCodexFastMode(\n\tmodel: CodexFastModeModelIdentity,\n\tsettings: CodexFastModeResolvedSettings,\n\tcontext: OrchestrationContext | undefined,\n): boolean {\n\treturn shouldApplyCodexFastModeForScope(model, settings, getCodexFastModeScope(context));\n}\n\n/**\n * Preserve the eager first-party header helper for callers that only know a\n * provider and base URL. The shared transport wrapper below recomputes the\n * identity from the final payload and also covers aliases and proxies.\n */\nexport function usesFirstPartyCodexRouting(model: Pick<Model<Api>, \"baseUrl\" | \"provider\">): boolean {\n\treturn model.provider === \"openai-codex\" && isFirstPartyCodexBaseUrl(model.baseUrl);\n}\n\n/** A provider alias or proxy still uses the shared ChatGPT Codex protocol when its API does. */\nexport function usesChatGptCodexTransport(model: Pick<Model<Api>, \"api\">): boolean {\n\treturn model.api === \"openai-codex-responses\";\n}\n\nfunction deleteHeader(headers: ProviderHeaders, name: string): void {\n\tfor (const existingName of Object.keys(headers)) {\n\t\tif (existingName.toLowerCase() === name.toLowerCase()) delete headers[existingName];\n\t}\n}\n\nfunction setHeader(headers: ProviderHeaders, name: string, value: string): void {\n\tdeleteHeader(headers, name);\n\theaders[name] = value;\n}\n\nexport function withCodexFastModeHeaders(\n\tmodel: Pick<Model<Api>, \"baseUrl\" | \"id\" | \"provider\">,\n\theaders: ProviderHeaders | undefined,\n\tenabled: boolean,\n): ProviderHeaders | undefined {\n\tif (!enabled || !usesFirstPartyCodexRouting(model)) return headers;\n\tconst fastHeaders: ProviderHeaders = { ...(headers ?? {}) };\n\tsetHeader(fastHeaders, \"originator\", CODEX_FAST_MODE_ORIGINATOR);\n\tsetHeader(fastHeaders, CODEX_FAST_MODE_ROUTING_HEADER, `model=${model.id};tier=${CODEX_FAST_MODE_SERVICE_TIER}`);\n\treturn fastHeaders;\n}\n\nexport function withCodexFastModeStreamOptions(\n\t_model: Pick<Model<Api>, \"baseUrl\" | \"id\" | \"provider\">,\n\toptions: SimpleStreamOptions | undefined,\n\tenabled: boolean,\n): CodexFastModeStreamOptions | undefined {\n\tif (!enabled) {\n\t\treturn options;\n\t}\n\n\treturn {\n\t\t...(options ?? {}),\n\t\theaders: options?.headers,\n\t\tserviceTier: CODEX_FAST_MODE_SERVICE_TIER,\n\t};\n}\n\nexport function isCodexFastModeNativeApi(api: Api): api is \"openai-responses\" | \"openai-codex-responses\" {\n\treturn api === \"openai-responses\" || api === \"openai-codex-responses\";\n}\n\nexport function shouldUseNativeCodexFastMode(\n\tmodel: Pick<Model<Api>, \"api\" | \"provider\">,\n\toptions: CodexFastModeStreamOptions | undefined,\n): boolean {\n\treturn (\n\t\tisCodexFastModeSupportedModel(model) &&\n\t\tisCodexFastModeNativeApi(model.api) &&\n\t\toptions?.serviceTier === CODEX_FAST_MODE_SERVICE_TIER\n\t);\n}\n\nfunction payloadRecord(payload: unknown): Record<string, unknown> | undefined {\n\treturn typeof payload === \"object\" && payload !== null && !Array.isArray(payload)\n\t\t? (payload as Record<string, unknown>)\n\t\t: undefined;\n}\n\nfunction codexEnvironmentScope(env: StreamOptions[\"env\"]): string {\n\tif (!env) return \"none\";\n\tconst serialized = JSON.stringify(Object.entries(env).sort(([left], [right]) => left.localeCompare(right)));\n\tlet hash = 2166136261;\n\tfor (let index = 0; index < serialized.length; index += 1) {\n\t\thash = Math.imul(hash ^ serialized.charCodeAt(index), 16777619);\n\t}\n\treturn (hash >>> 0).toString(16);\n}\n\ntype CloseCodexWebSocketSessions = typeof closeOpenAICodexWebSocketSessions;\nfunction updateCodexWebSocketRoutingState(\n\tmodel: Pick<Model<Api>, \"baseUrl\" | \"provider\">,\n\troutedModel: string,\n\toptions: Pick<StreamOptions, \"env\" | \"sessionId\" | \"transport\">,\n\tpriority: boolean,\n\tcloseWebSocketSessions: CloseCodexWebSocketSessions,\n): void {\n\tif (options.transport === \"sse\" || !options.sessionId) return;\n\tconst signature = `${model.provider}\\0${model.baseUrl}\\0${codexEnvironmentScope(options.env)}\\0${priority ? `priority:${routedModel}` : \"normal\"}`;\n\tconst previous = codexWebSocketRoutingState.get(options.sessionId);\n\tif (previous?.signature !== undefined && previous.signature !== signature) {\n\t\tcloseWebSocketSessions(options.sessionId);\n\t}\n\tif (previous) clearTimeout(previous.expiry);\n\tconst expiry = setTimeout(() => {\n\t\tif (codexWebSocketRoutingState.get(options.sessionId!)?.signature === signature) {\n\t\t\tcodexWebSocketRoutingState.delete(options.sessionId!);\n\t\t}\n\t}, CODEX_WEBSOCKET_ROUTING_STATE_IDLE_MS);\n\texpiry.unref?.();\n\tcodexWebSocketRoutingState.set(options.sessionId, { signature, expiry });\n}\n\nexport function withChatGptCodexTransportRouting<TOptions extends StreamOptions>(\n\tmodel: Model<Api>,\n\toptions: TOptions,\n\tenabled = true,\n\tcloseWebSocketSessions: CloseCodexWebSocketSessions = closeOpenAICodexWebSocketSessions,\n): TOptions {\n\tconst headers: ProviderHeaders = { ...(options.headers ?? {}) };\n\tconst onPayload = options.onPayload;\n\treturn {\n\t\t...options,\n\t\theaders,\n\t\tfetch: wrapCodexFastModeFetch(options.fetch ?? globalThis.fetch),\n\t\tonPayload: async (payload, requestModel) => {\n\t\t\tconst replacement = await onPayload?.(payload, requestModel);\n\t\t\tconst finalPayload = replacement === undefined ? payload : replacement;\n\t\t\tconst record = payloadRecord(finalPayload);\n\t\t\tconst priority = enabled && record?.service_tier === CODEX_FAST_MODE_SERVICE_TIER;\n\t\t\tconst routedModel = typeof record?.model === \"string\" ? record.model : model.id;\n\t\t\tdeleteHeader(headers, CODEX_FAST_MODE_ROUTING_HEADER);\n\t\t\tclearCodexFastModeRequestMarker(headers);\n\t\t\tif (priority) {\n\t\t\t\tsetHeader(\n\t\t\t\t\theaders,\n\t\t\t\t\tCODEX_FAST_MODE_ROUTING_HEADER,\n\t\t\t\t\t`model=${routedModel};tier=${CODEX_FAST_MODE_SERVICE_TIER}`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tfor (const [name, value] of Object.entries(headers)) {\n\t\t\t\t\tif (name.toLowerCase() === \"originator\" && value === CODEX_FAST_MODE_ORIGINATOR) delete headers[name];\n\t\t\t\t}\n\t\t\t}\n\t\t\tmarkCodexFastModeRequest(headers, priority);\n\t\t\tupdateCodexWebSocketRoutingState(model, routedModel, options, priority, closeWebSocketSessions);\n\t\t\treturn finalPayload;\n\t\t},\n\t} as TOptions;\n}\n\nfunction buildCodexFastModeBaseProviderOptions(\n\tmodel: Model<Api>,\n\toptions: CodexFastModeStreamOptions | undefined,\n): StreamOptions {\n\t// Native fast-mode streams bypass pi-ai's streamSimple base-options merge.\n\tconst samplingParams =\n\t\tmodel.samplingParams || options?.samplingParams\n\t\t\t? { ...model.samplingParams, ...options?.samplingParams }\n\t\t\t: undefined;\n\tconst providerOptions: StreamOptions = {\n\t\tsamplingParams,\n\t\ttemperature: options?.temperature,\n\t\tmaxTokens: options?.maxTokens,\n\t\tsignal: options?.signal,\n\t\tapiKey: options?.apiKey,\n\t\tfetch: options?.fetch,\n\t\tenv: options?.env,\n\t\ttelemetryContext: options?.telemetryContext,\n\t\ttransport: options?.transport,\n\t\tcacheRetention: options?.cacheRetention,\n\t\tsessionId: options?.sessionId,\n\t\tonPayload: options?.onPayload,\n\t\tonResponse: options?.onResponse,\n\t\theaders: options?.headers,\n\t\ttimeoutMs: options?.timeoutMs,\n\t\twebsocketConnectTimeoutMs: options?.websocketConnectTimeoutMs,\n\t\tmaxRetries: options?.maxRetries,\n\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t\tmetadata: options?.metadata,\n\t};\n\treturn usesChatGptCodexTransport(model) ? withChatGptCodexTransportRouting(model, providerOptions) : providerOptions;\n}\n\nexport function mapCodexFastModeReasoningEffort(\n\tmodel: Model<Api>,\n\treasoning: ThinkingLevel | undefined,\n): ThinkingLevel | undefined {\n\tconst clampedReasoning = reasoning ? clampThinkingLevel(model, reasoning) : undefined;\n\treturn clampedReasoning === \"off\" ? undefined : clampedReasoning;\n}\n\nexport function buildOpenAIResponsesCodexFastModeOptions(\n\tmodel: Model<Api>,\n\toptions: CodexFastModeStreamOptions | undefined,\n): OpenAIResponsesOptions {\n\treturn {\n\t\t...buildCodexFastModeBaseProviderOptions(model, options),\n\t\treasoningEffort: mapCodexFastModeReasoningEffort(model, options?.reasoning),\n\t\tserviceTier: options?.serviceTier,\n\t};\n}\n\nexport function buildOpenAICodexResponsesCodexFastModeOptions(\n\tmodel: Model<Api>,\n\toptions: CodexFastModeStreamOptions | undefined,\n): OpenAICodexResponsesOptions {\n\treturn {\n\t\t...buildCodexFastModeBaseProviderOptions(model, options),\n\t\treasoningEffort: mapCodexFastModeReasoningEffort(model, options?.reasoning),\n\t\tserviceTier: options?.serviceTier,\n\t};\n}\n\nexport function streamWithCodexFastMode(\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: CodexFastModeStreamOptions | undefined,\n\tstreamers: CodexFastModeStreamers = DEFAULT_CODEX_FAST_MODE_STREAMERS,\n): AssistantMessageEventStream {\n\tif (shouldUseNativeCodexFastMode(model, options)) {\n\t\tif (model.api === \"openai-responses\") {\n\t\t\treturn streamers.streamOpenAIResponses(\n\t\t\t\tmodel as Model<\"openai-responses\">,\n\t\t\t\tcontext,\n\t\t\t\tbuildOpenAIResponsesCodexFastModeOptions(model, options),\n\t\t\t);\n\t\t}\n\n\t\t// The WebSocket handshake builds its headers inside pi-ai, and the runtime\n\t\t// constructor can be cached before the first turn, so repair the identity\n\t\t// through the global constructor rather than per-request options.\n\t\tif (options?.transport !== \"sse\" && usesChatGptCodexTransport(model)) {\n\t\t\tinstallCodexFastModeWebSocketIdentity();\n\t\t}\n\n\t\treturn streamers.streamOpenAICodexResponses(\n\t\t\tmodel as Model<\"openai-codex-responses\">,\n\t\t\tcontext,\n\t\t\tbuildOpenAICodexResponsesCodexFastModeOptions(model, options),\n\t\t);\n\t}\n\n\treturn streamers.streamSimple(model, context, options);\n}\n\nfunction isObjectPayload(payload: unknown): payload is Record<string, unknown> {\n\treturn typeof payload === \"object\" && payload !== null && !Array.isArray(payload);\n}\n\nexport function withCodexFastModePayload(payload: unknown, enabled: boolean): unknown {\n\tif (!enabled || !isObjectPayload(payload) || payload.service_tier !== undefined) {\n\t\treturn payload;\n\t}\n\n\treturn {\n\t\t...payload,\n\t\tservice_tier: CODEX_FAST_MODE_SERVICE_TIER,\n\t};\n}\n\nexport function formatCodexFastModeModelLabel(modelName: string, enabled: boolean): string {\n\treturn enabled ? `${modelName} fast` : modelName;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"codex-fast-mode.js","sourceRoot":"","sources":["../../src/core/codex-fast-mode.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,2CAA2C,CAAC;AAC9F,OAAO,EAIN,kBAAkB,EAOlB,0BAA0B,EAC1B,qBAAqB,EACrB,YAAY,GAEZ,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,0BAA0B,EAC1B,8BAA8B,EAC9B,+BAA+B,EAC/B,qCAAqC,EACrC,wBAAwB,EACxB,wBAAwB,EACxB,sBAAsB,GACtB,MAA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,IAAI,OAAO,CAAC,YAAY,KAAK,SAAS,EAAE,CAAC;QACjF,OAAO,OAAO,CAAC;IAChB,CAAC;IAED,OAAO;QACN,GAAG,OAAO;QACV,YAAY,EAAE,4BAA4B;KAC1C,CAAC;AACH,CAAC;AAED,MAAM,UAAU,6BAA6B,CAAC,SAAiB,EAAE,OAAgB;IAChF,OAAO,OAAO,CAAC,CAAC,CAAC,GAAG,SAAS,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AAClD,CAAC","sourcesContent":["import { closeOpenAICodexWebSocketSessions } from \"@bastani/pi-ai/api/openai-codex-responses\";\nimport {\n\ttype Api,\n\ttype AssistantMessageEventStream,\n\ttype Context,\n\tclampThinkingLevel,\n\ttype Model,\n\ttype OpenAICodexResponsesOptions,\n\ttype OpenAIResponsesOptions,\n\ttype ProviderHeaders,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n\tstreamOpenAICodexResponses,\n\tstreamOpenAIResponses,\n\tstreamSimple,\n\ttype ThinkingLevel,\n} from \"@bastani/pi-ai/compat\";\nimport {\n\tCODEX_FAST_MODE_ORIGINATOR,\n\tCODEX_FAST_MODE_ROUTING_HEADER,\n\tclearCodexFastModeRequestMarker,\n\tinstallCodexFastModeWebSocketIdentity,\n\tisFirstPartyCodexBaseUrl,\n\tmarkCodexFastModeRequest,\n\twrapCodexFastModeFetch,\n} from \"./codex-fast-mode-transport.ts\";\nimport type { OrchestrationContext } from \"./extensions/index.ts\";\n\nexport const CODEX_FAST_MODE_SERVICE_TIER = \"priority\" as const;\n\nexport interface CodexFastModeResolvedSettings {\n\tchat: boolean;\n\tworkflow: boolean;\n}\n\nexport type CodexFastModeScope = \"chat\" | \"workflow\";\n\nexport interface CodexFastModeStreamOptions extends SimpleStreamOptions {\n\tserviceTier?: typeof CODEX_FAST_MODE_SERVICE_TIER;\n}\n\nexport interface CodexFastModeStreamers {\n\tstreamSimple: (model: Model<Api>, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\tstreamOpenAIResponses: (\n\t\tmodel: Model<\"openai-responses\">,\n\t\tcontext: Context,\n\t\toptions?: OpenAIResponsesOptions,\n\t) => AssistantMessageEventStream;\n\tstreamOpenAICodexResponses: (\n\t\tmodel: Model<\"openai-codex-responses\">,\n\t\tcontext: Context,\n\t\toptions?: OpenAICodexResponsesOptions,\n\t) => AssistantMessageEventStream;\n}\n\nconst DEFAULT_CODEX_FAST_MODE_STREAMERS: CodexFastModeStreamers = {\n\tstreamSimple,\n\tstreamOpenAIResponses,\n\tstreamOpenAICodexResponses,\n};\n\ntype CodexFastModeModelIdentity = Pick<Model<Api>, \"provider\"> & Partial<Pick<Model<Api>, \"api\">>;\n\nconst CODEX_WEBSOCKET_ROUTING_STATE_IDLE_MS = 6 * 60 * 1000;\nconst codexWebSocketRoutingState = new Map<string, { signature: string; expiry: ReturnType<typeof setTimeout> }>();\n\nexport function isCodexFastModeSupportedProvider(provider: string): boolean {\n\treturn provider === \"openai\" || provider === \"openai-codex\";\n}\n\nexport function isCodexFastModeCandidateModelId(modelId: string | undefined): boolean {\n\tconst provider = modelId?.split(\"/\", 1)[0];\n\treturn provider !== undefined && isCodexFastModeSupportedProvider(provider);\n}\n\nexport function isCodexFastModeSupportedModel(model: CodexFastModeModelIdentity): boolean {\n\treturn isCodexFastModeSupportedProvider(model.provider) || model.api === \"openai-codex-responses\";\n}\n\nexport function hasSupportedCodexFastModeModel(models: readonly CodexFastModeModelIdentity[]): boolean {\n\treturn models.some(isCodexFastModeSupportedModel);\n}\n\nexport function isWorkflowStageOrchestrationContext(context: OrchestrationContext | undefined): boolean {\n\treturn context?.kind === \"workflow-stage\";\n}\n\nexport function getCodexFastModeScope(context: OrchestrationContext | undefined): CodexFastModeScope {\n\treturn isWorkflowStageOrchestrationContext(context) ? \"workflow\" : \"chat\";\n}\n\nexport function isCodexFastModeEnabledForScope(\n\tsettings: CodexFastModeResolvedSettings,\n\tscope: CodexFastModeScope,\n): boolean {\n\treturn settings[scope];\n}\n\nexport function isCodexFastModeEnabledForSession(\n\tsettings: CodexFastModeResolvedSettings,\n\tcontext: OrchestrationContext | undefined,\n): boolean {\n\treturn isCodexFastModeEnabledForScope(settings, getCodexFastModeScope(context));\n}\n\nexport function shouldApplyCodexFastModeForScope(\n\tmodel: CodexFastModeModelIdentity,\n\tsettings: CodexFastModeResolvedSettings,\n\tscope: CodexFastModeScope,\n): boolean {\n\treturn isCodexFastModeSupportedModel(model) && isCodexFastModeEnabledForScope(settings, scope);\n}\n\nexport function shouldApplyCodexFastMode(\n\tmodel: CodexFastModeModelIdentity,\n\tsettings: CodexFastModeResolvedSettings,\n\tcontext: OrchestrationContext | undefined,\n): boolean {\n\treturn shouldApplyCodexFastModeForScope(model, settings, getCodexFastModeScope(context));\n}\n\n/**\n * Preserve the eager first-party header helper for callers that only know a\n * provider and base URL. The shared transport wrapper below recomputes the\n * identity from the final payload and also covers aliases and proxies.\n */\nexport function usesFirstPartyCodexRouting(model: Pick<Model<Api>, \"baseUrl\" | \"provider\">): boolean {\n\treturn model.provider === \"openai-codex\" && isFirstPartyCodexBaseUrl(model.baseUrl);\n}\n\n/** A provider alias or proxy still uses the shared ChatGPT Codex protocol when its API does. */\nexport function usesChatGptCodexTransport(model: Pick<Model<Api>, \"api\">): boolean {\n\treturn model.api === \"openai-codex-responses\";\n}\n\nfunction deleteHeader(headers: ProviderHeaders, name: string): void {\n\tfor (const existingName of Object.keys(headers)) {\n\t\tif (existingName.toLowerCase() === name.toLowerCase()) delete headers[existingName];\n\t}\n}\n\nfunction setHeader(headers: ProviderHeaders, name: string, value: string): void {\n\tdeleteHeader(headers, name);\n\theaders[name] = value;\n}\n\nexport function withCodexFastModeHeaders(\n\tmodel: Pick<Model<Api>, \"baseUrl\" | \"id\" | \"provider\">,\n\theaders: ProviderHeaders | undefined,\n\tenabled: boolean,\n): ProviderHeaders | undefined {\n\tif (!enabled || !usesFirstPartyCodexRouting(model)) return headers;\n\tconst fastHeaders: ProviderHeaders = { ...(headers ?? {}) };\n\tsetHeader(fastHeaders, \"originator\", CODEX_FAST_MODE_ORIGINATOR);\n\tsetHeader(fastHeaders, CODEX_FAST_MODE_ROUTING_HEADER, `model=${model.id};tier=${CODEX_FAST_MODE_SERVICE_TIER}`);\n\treturn fastHeaders;\n}\n\nexport function withCodexFastModeStreamOptions(\n\t_model: Pick<Model<Api>, \"baseUrl\" | \"id\" | \"provider\">,\n\toptions: SimpleStreamOptions | undefined,\n\tenabled: boolean,\n): CodexFastModeStreamOptions | undefined {\n\tif (!enabled) {\n\t\treturn options;\n\t}\n\n\treturn {\n\t\t...(options ?? {}),\n\t\theaders: options?.headers,\n\t\tserviceTier: CODEX_FAST_MODE_SERVICE_TIER,\n\t};\n}\n\nexport function isCodexFastModeNativeApi(api: Api): api is \"openai-responses\" | \"openai-codex-responses\" {\n\treturn api === \"openai-responses\" || api === \"openai-codex-responses\";\n}\n\nexport function shouldUseNativeCodexFastMode(\n\tmodel: Pick<Model<Api>, \"api\" | \"provider\">,\n\toptions: CodexFastModeStreamOptions | undefined,\n): boolean {\n\treturn (\n\t\tisCodexFastModeSupportedModel(model) &&\n\t\tisCodexFastModeNativeApi(model.api) &&\n\t\toptions?.serviceTier === CODEX_FAST_MODE_SERVICE_TIER\n\t);\n}\n\nfunction payloadRecord(payload: unknown): Record<string, unknown> | undefined {\n\treturn typeof payload === \"object\" && payload !== null && !Array.isArray(payload)\n\t\t? (payload as Record<string, unknown>)\n\t\t: undefined;\n}\n\nfunction codexEnvironmentScope(env: StreamOptions[\"env\"]): string {\n\tif (!env) return \"none\";\n\tconst serialized = JSON.stringify(Object.entries(env).sort(([left], [right]) => left.localeCompare(right)));\n\tlet hash = 2166136261;\n\tfor (let index = 0; index < serialized.length; index += 1) {\n\t\thash = Math.imul(hash ^ serialized.charCodeAt(index), 16777619);\n\t}\n\treturn (hash >>> 0).toString(16);\n}\n\ntype CloseCodexWebSocketSessions = typeof closeOpenAICodexWebSocketSessions;\nfunction updateCodexWebSocketRoutingState(\n\tmodel: Pick<Model<Api>, \"baseUrl\" | \"provider\">,\n\troutedModel: string,\n\toptions: Pick<StreamOptions, \"env\" | \"sessionId\" | \"transport\">,\n\tpriority: boolean,\n\tcloseWebSocketSessions: CloseCodexWebSocketSessions,\n): void {\n\tif (options.transport === \"sse\" || !options.sessionId) return;\n\tconst signature = `${model.provider}\\0${model.baseUrl}\\0${codexEnvironmentScope(options.env)}\\0${priority ? `priority:${routedModel}` : \"normal\"}`;\n\tconst previous = codexWebSocketRoutingState.get(options.sessionId);\n\tif (previous?.signature !== undefined && previous.signature !== signature) {\n\t\tcloseWebSocketSessions(options.sessionId);\n\t}\n\tif (previous) clearTimeout(previous.expiry);\n\tconst expiry = setTimeout(() => {\n\t\tif (codexWebSocketRoutingState.get(options.sessionId!)?.signature === signature) {\n\t\t\tcodexWebSocketRoutingState.delete(options.sessionId!);\n\t\t}\n\t}, CODEX_WEBSOCKET_ROUTING_STATE_IDLE_MS);\n\texpiry.unref?.();\n\tcodexWebSocketRoutingState.set(options.sessionId, { signature, expiry });\n}\n\nexport function withChatGptCodexTransportRouting<TOptions extends StreamOptions>(\n\tmodel: Model<Api>,\n\toptions: TOptions,\n\tenabled = true,\n\tcloseWebSocketSessions: CloseCodexWebSocketSessions = closeOpenAICodexWebSocketSessions,\n): TOptions {\n\tconst headers: ProviderHeaders = { ...(options.headers ?? {}) };\n\tconst onPayload = options.onPayload;\n\treturn {\n\t\t...options,\n\t\theaders,\n\t\tfetch: wrapCodexFastModeFetch(options.fetch ?? globalThis.fetch),\n\t\tonPayload: async (payload, requestModel) => {\n\t\t\tconst replacement = await onPayload?.(payload, requestModel);\n\t\t\tconst finalPayload = replacement === undefined ? payload : replacement;\n\t\t\tconst record = payloadRecord(finalPayload);\n\t\t\tconst priority = enabled && record?.service_tier === CODEX_FAST_MODE_SERVICE_TIER;\n\t\t\tconst routedModel = typeof record?.model === \"string\" ? record.model : model.id;\n\t\t\tdeleteHeader(headers, CODEX_FAST_MODE_ROUTING_HEADER);\n\t\t\tclearCodexFastModeRequestMarker(headers);\n\t\t\tif (priority) {\n\t\t\t\tsetHeader(\n\t\t\t\t\theaders,\n\t\t\t\t\tCODEX_FAST_MODE_ROUTING_HEADER,\n\t\t\t\t\t`model=${routedModel};tier=${CODEX_FAST_MODE_SERVICE_TIER}`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tfor (const [name, value] of Object.entries(headers)) {\n\t\t\t\t\tif (name.toLowerCase() === \"originator\" && value === CODEX_FAST_MODE_ORIGINATOR) delete headers[name];\n\t\t\t\t}\n\t\t\t}\n\t\t\tmarkCodexFastModeRequest(headers, priority);\n\t\t\tupdateCodexWebSocketRoutingState(model, routedModel, options, priority, closeWebSocketSessions);\n\t\t\treturn finalPayload;\n\t\t},\n\t} as TOptions;\n}\n\nfunction buildCodexFastModeBaseProviderOptions(\n\tmodel: Model<Api>,\n\toptions: CodexFastModeStreamOptions | undefined,\n): StreamOptions {\n\t// Native fast-mode streams bypass pi-ai's streamSimple base-options merge.\n\tconst samplingParams =\n\t\tmodel.samplingParams || options?.samplingParams\n\t\t\t? { ...model.samplingParams, ...options?.samplingParams }\n\t\t\t: undefined;\n\tconst providerOptions: StreamOptions = {\n\t\tsamplingParams,\n\t\ttemperature: options?.temperature,\n\t\tmaxTokens: options?.maxTokens,\n\t\tsignal: options?.signal,\n\t\tapiKey: options?.apiKey,\n\t\tfetch: options?.fetch,\n\t\tenv: options?.env,\n\t\ttelemetryContext: options?.telemetryContext,\n\t\ttransport: options?.transport,\n\t\tcacheRetention: options?.cacheRetention,\n\t\tsessionId: options?.sessionId,\n\t\tonPayload: options?.onPayload,\n\t\tonResponse: options?.onResponse,\n\t\theaders: options?.headers,\n\t\ttimeoutMs: options?.timeoutMs,\n\t\twebsocketConnectTimeoutMs: options?.websocketConnectTimeoutMs,\n\t\tstreamDeadlineMs: options?.streamDeadlineMs,\n\t\tmaxRetries: options?.maxRetries,\n\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t\tmetadata: options?.metadata,\n\t};\n\treturn usesChatGptCodexTransport(model) ? withChatGptCodexTransportRouting(model, providerOptions) : providerOptions;\n}\n\nexport function mapCodexFastModeReasoningEffort(\n\tmodel: Model<Api>,\n\treasoning: ThinkingLevel | undefined,\n): ThinkingLevel | undefined {\n\tconst clampedReasoning = reasoning ? clampThinkingLevel(model, reasoning) : undefined;\n\treturn clampedReasoning === \"off\" ? undefined : clampedReasoning;\n}\n\nexport function buildOpenAIResponsesCodexFastModeOptions(\n\tmodel: Model<Api>,\n\toptions: CodexFastModeStreamOptions | undefined,\n): OpenAIResponsesOptions {\n\treturn {\n\t\t...buildCodexFastModeBaseProviderOptions(model, options),\n\t\treasoningEffort: mapCodexFastModeReasoningEffort(model, options?.reasoning),\n\t\tserviceTier: options?.serviceTier,\n\t};\n}\n\nexport function buildOpenAICodexResponsesCodexFastModeOptions(\n\tmodel: Model<Api>,\n\toptions: CodexFastModeStreamOptions | undefined,\n): OpenAICodexResponsesOptions {\n\treturn {\n\t\t...buildCodexFastModeBaseProviderOptions(model, options),\n\t\treasoningEffort: mapCodexFastModeReasoningEffort(model, options?.reasoning),\n\t\tserviceTier: options?.serviceTier,\n\t};\n}\n\nexport function streamWithCodexFastMode(\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: CodexFastModeStreamOptions | undefined,\n\tstreamers: CodexFastModeStreamers = DEFAULT_CODEX_FAST_MODE_STREAMERS,\n): AssistantMessageEventStream {\n\tif (shouldUseNativeCodexFastMode(model, options)) {\n\t\tif (model.api === \"openai-responses\") {\n\t\t\treturn streamers.streamOpenAIResponses(\n\t\t\t\tmodel as Model<\"openai-responses\">,\n\t\t\t\tcontext,\n\t\t\t\tbuildOpenAIResponsesCodexFastModeOptions(model, options),\n\t\t\t);\n\t\t}\n\n\t\t// The WebSocket handshake builds its headers inside pi-ai, and the runtime\n\t\t// constructor can be cached before the first turn, so repair the identity\n\t\t// through the global constructor rather than per-request options.\n\t\tif (options?.transport !== \"sse\" && usesChatGptCodexTransport(model)) {\n\t\t\tinstallCodexFastModeWebSocketIdentity();\n\t\t}\n\n\t\treturn streamers.streamOpenAICodexResponses(\n\t\t\tmodel as Model<\"openai-codex-responses\">,\n\t\t\tcontext,\n\t\t\tbuildOpenAICodexResponsesCodexFastModeOptions(model, options),\n\t\t);\n\t}\n\n\treturn streamers.streamSimple(model, context, options);\n}\n\nfunction isObjectPayload(payload: unknown): payload is Record<string, unknown> {\n\treturn typeof payload === \"object\" && payload !== null && !Array.isArray(payload);\n}\n\nexport function withCodexFastModePayload(payload: unknown, enabled: boolean): unknown {\n\tif (!enabled || !isObjectPayload(payload) || payload.service_tier !== undefined) {\n\t\treturn payload;\n\t}\n\n\treturn {\n\t\t...payload,\n\t\tservice_tier: CODEX_FAST_MODE_SERVICE_TIER,\n\t};\n}\n\nexport function formatCodexFastModeModelLabel(modelName: string, enabled: boolean): string {\n\treturn enabled ? `${modelName} fast` : modelName;\n}\n"]}
|
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
* When navigating to a different point in the session tree, this generates
|
|
5
5
|
* a summary of the branch being left so context isn't lost.
|
|
6
6
|
*/
|
|
7
|
+
import { type ProviderHeaders, type RetryCallbacks, type RetryPolicy } from "@bastani/pi-ai";
|
|
8
|
+
import type { Api, Model, Usage } from "@bastani/pi-ai/compat";
|
|
7
9
|
import type { AgentMessage, StreamFn, ThinkingLevel } from "@earendil-works/pi-agent-core";
|
|
8
|
-
import { type ProviderHeaders, type RetryCallbacks, type RetryPolicy } from "@earendil-works/pi-ai";
|
|
9
|
-
import type { Api, Model, Usage } from "@earendil-works/pi-ai/compat";
|
|
10
10
|
import type { ReadonlySessionManager, SessionEntry } from "../session-manager.ts";
|
|
11
11
|
import { type FileOperations } from "./utils.ts";
|
|
12
12
|
export interface BranchSummaryResult {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"branch-summarization.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/branch-summarization.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"branch-summarization.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/branch-summarization.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACN,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,WAAW,EAGhB,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAuB,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAEpF,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAE3F,OAAO,KAAK,EAAE,sBAAsB,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAGlF,OAAO,EAIN,KAAK,cAAc,EAInB,MAAM,YAAY,CAAC;AAMpB,MAAM,WAAW,mBAAmB;IACnC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,qEAAqE;AACrE,MAAM,WAAW,oBAAoB;IACpC,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,aAAa,EAAE,MAAM,EAAE,CAAC;CACxB;AAED,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,MAAM,WAAW,iBAAiB;IACjC,mEAAmE;IACnE,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,gDAAgD;IAChD,OAAO,EAAE,cAAc,CAAC;IACxB,yCAAyC;IACzC,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,oBAAoB;IACpC,mDAAmD;IACnD,OAAO,EAAE,YAAY,EAAE,CAAC;IACxB,2DAA2D;IAC3D,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC;AAED,MAAM,WAAW,4BAA4B;IAC5C,qCAAqC;IACrC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IAClB,4EAA4E;IAC5E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,oCAAoC;IACpC,OAAO,CAAC,EAAE,eAAe,CAAC;IAC1B,yDAAyD;IACzD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,oCAAoC;IACpC,MAAM,EAAE,WAAW,CAAC;IACpB,qDAAqD;IACrD,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,wFAAwF;IACxF,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,gEAAgE;IAChE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;OAGG;IACH,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,4GAA4G;IAC5G,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,yDAAyD;IACzD,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,iCAAiC;IACjC,SAAS,CAAC,EAAE,cAAc,CAAC;CAC3B;AAMD;;;;;;;;;;;GAWG;AACH,wBAAgB,8BAA8B,CAC7C,OAAO,EAAE,sBAAsB,EAC/B,SAAS,EAAE,MAAM,GAAG,IAAI,EACxB,QAAQ,EAAE,MAAM,GACd,oBAAoB,CAkCtB;AA6CD;;;;;;;;;;;;GAYG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,WAAW,GAAE,MAAU,GAAG,iBAAiB,CAqDxG;AAwCD;;;;;GAKG;AACH,wBAAsB,qBAAqB,CAC1C,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,4BAA4B,GACnC,OAAO,CAAC,mBAAmB,CAAC,CAiH9B"}
|
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
* When navigating to a different point in the session tree, this generates
|
|
5
5
|
* a summary of the branch being left so context isn't lost.
|
|
6
6
|
*/
|
|
7
|
-
import { retryAssistantCall, uuidv7, } from "@
|
|
8
|
-
import { completeSimple } from "@
|
|
7
|
+
import { retryAssistantCall, uuidv7, } from "@bastani/pi-ai";
|
|
8
|
+
import { completeSimple } from "@bastani/pi-ai/compat";
|
|
9
9
|
import { convertToLlm, createBranchSummaryMessage, createCustomMessage } from "../messages.js";
|
|
10
10
|
import { estimateTokens } from "./compaction.js";
|
|
11
11
|
import { resolvePlannerRequest } from "./range-planner.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"branch-summarization.js","sourceRoot":"","sources":["../../../src/core/compaction/branch-summarization.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAIN,kBAAkB,EAClB,MAAM,GACN,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,0BAA0B,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE/F,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EACN,gBAAgB,EAChB,aAAa,EACb,yBAAyB,EAEzB,oBAAoB,EACpB,2BAA2B,EAC3B,qBAAqB,GACrB,MAAM,YAAY,CAAC;AAqEpB,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,8BAA8B,CAC7C,OAA+B,EAC/B,SAAwB,EACxB,QAAgB;IAEhB,2CAA2C;IAC3C,IAAI,CAAC,SAAS,EAAE,CAAC;QAChB,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,gBAAgB,EAAE,IAAI,EAAE,CAAC;IAChD,CAAC;IAED,2DAA2D;IAC3D,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,CA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,aAAa;KACb,CAAC;AACH,CAAC","sourcesContent":["/**\n * Branch summarization for tree navigation.\n *\n * When navigating to a different point in the session tree, this generates\n * a summary of the branch being left so context isn't lost.\n */\n\nimport type { AgentMessage, StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype ProviderHeaders,\n\ttype RetryCallbacks,\n\ttype RetryPolicy,\n\tretryAssistantCall,\n\tuuidv7,\n} from \"@earendil-works/pi-ai\";\nimport type { Api, Model, SimpleStreamOptions, Usage } from \"@earendil-works/pi-ai/compat\";\nimport { completeSimple } from \"@earendil-works/pi-ai/compat\";\nimport { convertToLlm, createBranchSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport type { ReadonlySessionManager, SessionEntry } from \"../session-manager.ts\";\nimport { estimateTokens } from \"./compaction.ts\";\nimport { resolvePlannerRequest } from \"./range-planner.js\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BranchSummaryResult {\n\tsummary?: string;\n\treadFiles?: string[];\n\tmodifiedFiles?: string[];\n\tusage?: Usage;\n\taborted?: boolean;\n\terror?: string;\n}\n\n/** Details stored in BranchSummaryEntry.details for file tracking */\nexport interface BranchSummaryDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\nexport type { FileOperations } from \"./utils.ts\";\n\nexport interface BranchPreparation {\n\t/** Messages extracted for summarization, in chronological order */\n\tmessages: AgentMessage[];\n\t/** File operations extracted from tool calls */\n\tfileOps: FileOperations;\n\t/** Total estimated tokens in messages */\n\ttotalTokens: number;\n}\n\nexport interface CollectEntriesResult {\n\t/** Entries to summarize, in chronological order */\n\tentries: SessionEntry[];\n\t/** Common ancestor between old and new position, if any */\n\tcommonAncestorId: string | null;\n}\n\nexport interface GenerateBranchSummaryOptions {\n\t/** Model to use for summarization */\n\tmodel: Model<Api>;\n\t/** API key for the model; omitted for header-only bearer authentication. */\n\tapiKey?: string;\n\t/** Request headers for the model */\n\theaders?: ProviderHeaders;\n\t/** Credential-specific request endpoint for the model */\n\tbaseUrl?: string;\n\t/** Abort signal for cancellation */\n\tsignal: AbortSignal;\n\t/** Optional custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** If true, customInstructions replaces the default prompt instead of being appended */\n\treplaceInstructions?: boolean;\n\t/** Tokens reserved for prompt + LLM response (default 16384) */\n\treserveTokens?: number;\n\t/**\n\t * Session reasoning level, inherited by the summarization request.\n\t * No output cap is sent, so thinking has no artificial budget to exhaust.\n\t */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Optional session stream function. Used to preserve SDK request behavior without mutating agent state. */\n\tstreamFn?: StreamFn;\n\t/** Retry policy for transient summarization failures. */\n\tretry?: RetryPolicy;\n\t/** Retry lifecycle callbacks. */\n\tcallbacks?: RetryCallbacks;\n}\n\n// ============================================================================\n// Entry Collection\n// ============================================================================\n\n/**\n * Collect entries that should be summarized when navigating from one position to another.\n *\n * Walks from oldLeafId back to the common ancestor with targetId, collecting entries\n * along the way. Does NOT stop at legacy compaction entries, but those entries are\n * inert and are not fed into branch summarization prompts.\n *\n * @param session - Session manager (read-only access)\n * @param oldLeafId - Current position (where we're navigating from)\n * @param targetId - Target position (where we're navigating to)\n * @returns Entries to summarize and the common ancestor\n */\nexport function collectEntriesForBranchSummary(\n\tsession: ReadonlySessionManager,\n\toldLeafId: string | null,\n\ttargetId: string,\n): CollectEntriesResult {\n\t// If no old position, nothing to summarize\n\tif (!oldLeafId) {\n\t\treturn { entries: [], commonAncestorId: null };\n\t}\n\n\t// Find common ancestor (deepest node that's on both paths)\n\tconst oldPath = new Set(session.getBranch(oldLeafId).map((e) => e.id));\n\tconst targetPath = session.getBranch(targetId);\n\n\t// targetPath is root-first, so iterate backwards to find deepest common ancestor\n\tlet commonAncestorId: string | null = null;\n\tfor (let i = targetPath.length - 1; i >= 0; i--) {\n\t\tif (oldPath.has(targetPath[i].id)) {\n\t\t\tcommonAncestorId = targetPath[i].id;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Collect entries from old leaf back to common ancestor\n\tconst entries: SessionEntry[] = [];\n\tlet current: string | null = oldLeafId;\n\n\twhile (current && current !== commonAncestorId) {\n\t\tconst entry = session.getEntry(current);\n\t\tif (!entry) break;\n\t\tentries.push(entry);\n\t\tcurrent = entry.parentId;\n\t}\n\n\t// Reverse to get chronological order\n\tentries.reverse();\n\n\treturn { entries, commonAncestorId };\n}\n\n// ============================================================================\n// Entry to Message Conversion\n// ============================================================================\n\n/**\n * Extract AgentMessage from a session entry.\n * Similar to getMessageFromEntry in compaction.ts, with legacy compaction entries kept inert.\n */\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\t// Skip tool results - context is in assistant's tool call\n\t\t\tif (entry.message.role === \"toolResult\") return undefined;\n\t\t\treturn entry.message;\n\n\t\tcase \"custom_message\":\n\t\t\treturn createCustomMessage(\n\t\t\t\tentry.customType,\n\t\t\t\tentry.content,\n\t\t\t\tentry.display,\n\t\t\t\tentry.details,\n\t\t\t\tentry.timestamp,\n\t\t\t\tentry.excludeFromContext,\n\t\t\t);\n\n\t\tcase \"branch_summary\":\n\t\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\n\t\tcase \"compaction\":\n\t\t\treturn undefined;\n\n\t\t// These don't contribute to conversation content\n\t\tcase \"thinking_level_change\":\n\t\tcase \"model_change\":\n\t\tcase \"custom\":\n\t\tcase \"label\":\n\t\tcase \"session_info\":\n\t\tcase \"session_summary\":\n\t\tcase \"context_compaction\":\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Prepare entries for summarization with token budget.\n *\n * Walks entries from NEWEST to OLDEST, adding messages until we hit the token budget.\n * This ensures we keep the most recent context when the branch is too long.\n *\n * Also collects file operations from:\n * - Tool calls in assistant messages\n * - Existing branch_summary entries' details (for cumulative tracking)\n *\n * @param entries - Entries in chronological order\n * @param tokenBudget - Maximum tokens to include (0 = no limit)\n */\nexport function prepareBranchEntries(entries: SessionEntry[], tokenBudget: number = 0): BranchPreparation {\n\tconst messages: AgentMessage[] = [];\n\tconst fileOps = createFileOps();\n\tconst filteredEntries = entries;\n\tlet totalTokens = 0;\n\n\t// First pass: collect file ops from ALL entries (even if they don't fit in token budget)\n\t// This ensures we capture cumulative file tracking from nested branch summaries\n\t// Only extract from pi-generated summaries (fromHook !== true), not extension-generated ones\n\tfor (const entry of filteredEntries) {\n\t\tif (entry.type === \"branch_summary\" && !entry.fromHook && entry.details) {\n\t\t\tconst details = entry.details as BranchSummaryDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\t// Modified files go into both edited and written for proper deduplication\n\t\t\t\tfor (const f of details.modifiedFiles) {\n\t\t\t\t\tfileOps.edited.add(f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: walk from newest to oldest, adding messages until token budget\n\tfor (let i = filteredEntries.length - 1; i >= 0; i--) {\n\t\tconst entry = filteredEntries[i];\n\t\tconst message = getMessageFromEntry(entry);\n\t\tif (!message) continue;\n\n\t\t// Extract file ops from assistant messages (tool calls)\n\t\textractFileOpsFromMessage(message, fileOps);\n\n\t\tconst tokens = estimateTokens(message);\n\n\t\t// Check budget before adding\n\t\tif (tokenBudget > 0 && totalTokens + tokens > tokenBudget) {\n\t\t\t// If this is a branch summary entry, try to fit it anyway as it's important context\n\t\t\tif (entry.type === \"branch_summary\") {\n\t\t\t\tif (totalTokens < tokenBudget * 0.9) {\n\t\t\t\t\tmessages.unshift(message);\n\t\t\t\t\ttotalTokens += tokens;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Stop - we've hit the budget\n\t\t\tbreak;\n\t\t}\n\n\t\tmessages.unshift(message);\n\t\ttotalTokens += tokens;\n\t}\n\n\treturn { messages, fileOps, totalTokens };\n}\n\n// ============================================================================\n// Summary Generation\n// ============================================================================\n\nconst BRANCH_SUMMARY_PREAMBLE = `The user explored a different conversation branch before returning here.\nSummary of that exploration:\n\n`;\n\nconst BRANCH_SUMMARY_PROMPT = `Create a structured summary of this conversation branch for context when returning later.\n\nUse this EXACT format:\n\n## Goal\n[What was the user trying to accomplish in this branch?]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Work that was started but not finished]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [What should happen next to continue this work]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\n/**\n * Generate a summary of abandoned branch entries.\n *\n * @param entries - Session entries to summarize (chronological order)\n * @param options - Generation options\n */\nexport async function generateBranchSummary(\n\tentries: SessionEntry[],\n\toptions: GenerateBranchSummaryOptions,\n): Promise<BranchSummaryResult> {\n\tconst {\n\t\tmodel,\n\t\tapiKey,\n\t\theaders,\n\t\tbaseUrl,\n\t\tsignal,\n\t\tcustomInstructions,\n\t\treplaceInstructions,\n\t\treserveTokens = 16384,\n\t\tthinkingLevel,\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t} = options;\n\n\t// Token budget = context window minus reserved space for prompt + response\n\tconst contextWindow = model.contextWindow || 128000;\n\tconst tokenBudget = contextWindow - reserveTokens;\n\n\tconst { messages, fileOps } = prepareBranchEntries(entries, tokenBudget);\n\n\tif (messages.length === 0) {\n\t\treturn { summary: \"No content to summarize\" };\n\t}\n\n\t// Transform to LLM-compatible messages, then serialize to text\n\t// Serialization prevents the model from treating it as a conversation to continue\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build prompt\n\tlet instructions: string;\n\tif (replaceInstructions && customInstructions) {\n\t\tinstructions = customInstructions;\n\t} else if (customInstructions) {\n\t\tinstructions = `${BRANCH_SUMMARY_PROMPT}\\n\\nAdditional focus: ${customInstructions}`;\n\t} else {\n\t\tinstructions = BRANCH_SUMMARY_PROMPT;\n\t}\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${instructions}`;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\t// Call LLM for summarization. Prefer the session stream function so SDK\n\t// request behavior stays consistent without mutating agent state.\n\tconst context = { systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages };\n\tconst requestModel = baseUrl === undefined || baseUrl === model.baseUrl ? model : { ...model, baseUrl };\n\t// Same budget rule as the compaction planner: no output cap is sent, so\n\t// pi-ai's context clamp is the only bound and the inherited reasoning level\n\t// has no artificial budget to exhaust. `reserveTokens` keeps its input-side\n\t// meaning above, unchanged.\n\tconst budget = resolvePlannerRequest(requestModel, thinkingLevel);\n\tconst requestOptions: SimpleStreamOptions = {\n\t\tapiKey,\n\t\theaders,\n\t\tsignal,\n\t\tcacheRetention: \"none\",\n\t\tsessionId: uuidv7(),\n\t\t...(budget.reasoning && budget.reasoning !== \"off\" ? { reasoning: budget.reasoning } : {}),\n\t};\n\tconst response = await (async () => {\n\t\ttry {\n\t\t\treturn await retryAssistantCall(\n\t\t\t\tasync () =>\n\t\t\t\t\tstreamFn\n\t\t\t\t\t\t? (await streamFn(requestModel, context, requestOptions)).result()\n\t\t\t\t\t\t: completeSimple(requestModel, context, requestOptions),\n\t\t\t\tretry,\n\t\t\t\tsignal,\n\t\t\t\tcallbacks,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (signal.aborted) return undefined;\n\t\t\treturn {\n\t\t\t\tstopReason: \"error\" as const,\n\t\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\t};\n\t\t}\n\t})();\n\n\t// Check if aborted or errored\n\tif (!response || response.stopReason === \"aborted\") {\n\t\treturn { aborted: true };\n\t}\n\tif (response.stopReason === \"error\") {\n\t\treturn { error: response.errorMessage || \"Summarization failed\" };\n\t}\n\n\tlet summary = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\t// Prepend preamble to provide context about the branch summary\n\tsummary = BRANCH_SUMMARY_PREAMBLE + summary;\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\treturn {\n\t\tsummary: summary || \"No summary generated\",\n\t\tusage: response.usage,\n\t\treadFiles,\n\t\tmodifiedFiles,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"branch-summarization.js","sourceRoot":"","sources":["../../../src/core/compaction/branch-summarization.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAIN,kBAAkB,EAClB,MAAM,GACN,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEvD,OAAO,EAAE,YAAY,EAAE,0BAA0B,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE/F,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EACN,gBAAgB,EAChB,aAAa,EACb,yBAAyB,EAEzB,oBAAoB,EACpB,2BAA2B,EAC3B,qBAAqB,GACrB,MAAM,YAAY,CAAC;AAqEpB,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,8BAA8B,CAC7C,O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uBAAuB,GAAG,OAAO,CAAC;IAE5C,2CAA2C;IAC3C,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;IAC/D,OAAO,IAAI,oBAAoB,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;IAE1D,OAAO;QACN,OAAO,EAAE,OAAO,IAAI,sBAAsB;QAC1C,KAAK,EAAE,QAAQ,CAAC,KAAK;QACrB,SAAS;QACT,aAAa;KACb,CAAC;AACH,CAAC","sourcesContent":["/**\n * Branch summarization for tree navigation.\n *\n * When navigating to a different point in the session tree, this generates\n * a summary of the branch being left so context isn't lost.\n */\n\nimport {\n\ttype ProviderHeaders,\n\ttype RetryCallbacks,\n\ttype RetryPolicy,\n\tretryAssistantCall,\n\tuuidv7,\n} from \"@bastani/pi-ai\";\nimport type { Api, Model, SimpleStreamOptions, Usage } from \"@bastani/pi-ai/compat\";\nimport { completeSimple } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage, StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { convertToLlm, createBranchSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport type { ReadonlySessionManager, SessionEntry } from \"../session-manager.ts\";\nimport { estimateTokens } from \"./compaction.ts\";\nimport { resolvePlannerRequest } from \"./range-planner.js\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BranchSummaryResult {\n\tsummary?: string;\n\treadFiles?: string[];\n\tmodifiedFiles?: string[];\n\tusage?: Usage;\n\taborted?: boolean;\n\terror?: string;\n}\n\n/** Details stored in BranchSummaryEntry.details for file tracking */\nexport interface BranchSummaryDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\nexport type { FileOperations } from \"./utils.ts\";\n\nexport interface BranchPreparation {\n\t/** Messages extracted for summarization, in chronological order */\n\tmessages: AgentMessage[];\n\t/** File operations extracted from tool calls */\n\tfileOps: FileOperations;\n\t/** Total estimated tokens in messages */\n\ttotalTokens: number;\n}\n\nexport interface CollectEntriesResult {\n\t/** Entries to summarize, in chronological order */\n\tentries: SessionEntry[];\n\t/** Common ancestor between old and new position, if any */\n\tcommonAncestorId: string | null;\n}\n\nexport interface GenerateBranchSummaryOptions {\n\t/** Model to use for summarization */\n\tmodel: Model<Api>;\n\t/** API key for the model; omitted for header-only bearer authentication. */\n\tapiKey?: string;\n\t/** Request headers for the model */\n\theaders?: ProviderHeaders;\n\t/** Credential-specific request endpoint for the model */\n\tbaseUrl?: string;\n\t/** Abort signal for cancellation */\n\tsignal: AbortSignal;\n\t/** Optional custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** If true, customInstructions replaces the default prompt instead of being appended */\n\treplaceInstructions?: boolean;\n\t/** Tokens reserved for prompt + LLM response (default 16384) */\n\treserveTokens?: number;\n\t/**\n\t * Session reasoning level, inherited by the summarization request.\n\t * No output cap is sent, so thinking has no artificial budget to exhaust.\n\t */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Optional session stream function. Used to preserve SDK request behavior without mutating agent state. */\n\tstreamFn?: StreamFn;\n\t/** Retry policy for transient summarization failures. */\n\tretry?: RetryPolicy;\n\t/** Retry lifecycle callbacks. */\n\tcallbacks?: RetryCallbacks;\n}\n\n// ============================================================================\n// Entry Collection\n// ============================================================================\n\n/**\n * Collect entries that should be summarized when navigating from one position to another.\n *\n * Walks from oldLeafId back to the common ancestor with targetId, collecting entries\n * along the way. Does NOT stop at legacy compaction entries, but those entries are\n * inert and are not fed into branch summarization prompts.\n *\n * @param session - Session manager (read-only access)\n * @param oldLeafId - Current position (where we're navigating from)\n * @param targetId - Target position (where we're navigating to)\n * @returns Entries to summarize and the common ancestor\n */\nexport function collectEntriesForBranchSummary(\n\tsession: ReadonlySessionManager,\n\toldLeafId: string | null,\n\ttargetId: string,\n): CollectEntriesResult {\n\t// If no old position, nothing to summarize\n\tif (!oldLeafId) {\n\t\treturn { entries: [], commonAncestorId: null };\n\t}\n\n\t// Find common ancestor (deepest node that's on both paths)\n\tconst oldPath = new Set(session.getBranch(oldLeafId).map((e) => e.id));\n\tconst targetPath = session.getBranch(targetId);\n\n\t// targetPath is root-first, so iterate backwards to find deepest common ancestor\n\tlet commonAncestorId: string | null = null;\n\tfor (let i = targetPath.length - 1; i >= 0; i--) {\n\t\tif (oldPath.has(targetPath[i].id)) {\n\t\t\tcommonAncestorId = targetPath[i].id;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Collect entries from old leaf back to common ancestor\n\tconst entries: SessionEntry[] = [];\n\tlet current: string | null = oldLeafId;\n\n\twhile (current && current !== commonAncestorId) {\n\t\tconst entry = session.getEntry(current);\n\t\tif (!entry) break;\n\t\tentries.push(entry);\n\t\tcurrent = entry.parentId;\n\t}\n\n\t// Reverse to get chronological order\n\tentries.reverse();\n\n\treturn { entries, commonAncestorId };\n}\n\n// ============================================================================\n// Entry to Message Conversion\n// ============================================================================\n\n/**\n * Extract AgentMessage from a session entry.\n * Similar to getMessageFromEntry in compaction.ts, with legacy compaction entries kept inert.\n */\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\t// Skip tool results - context is in assistant's tool call\n\t\t\tif (entry.message.role === \"toolResult\") return undefined;\n\t\t\treturn entry.message;\n\n\t\tcase \"custom_message\":\n\t\t\treturn createCustomMessage(\n\t\t\t\tentry.customType,\n\t\t\t\tentry.content,\n\t\t\t\tentry.display,\n\t\t\t\tentry.details,\n\t\t\t\tentry.timestamp,\n\t\t\t\tentry.excludeFromContext,\n\t\t\t);\n\n\t\tcase \"branch_summary\":\n\t\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\n\t\tcase \"compaction\":\n\t\t\treturn undefined;\n\n\t\t// These don't contribute to conversation content\n\t\tcase \"thinking_level_change\":\n\t\tcase \"model_change\":\n\t\tcase \"custom\":\n\t\tcase \"label\":\n\t\tcase \"session_info\":\n\t\tcase \"session_summary\":\n\t\tcase \"context_compaction\":\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Prepare entries for summarization with token budget.\n *\n * Walks entries from NEWEST to OLDEST, adding messages until we hit the token budget.\n * This ensures we keep the most recent context when the branch is too long.\n *\n * Also collects file operations from:\n * - Tool calls in assistant messages\n * - Existing branch_summary entries' details (for cumulative tracking)\n *\n * @param entries - Entries in chronological order\n * @param tokenBudget - Maximum tokens to include (0 = no limit)\n */\nexport function prepareBranchEntries(entries: SessionEntry[], tokenBudget: number = 0): BranchPreparation {\n\tconst messages: AgentMessage[] = [];\n\tconst fileOps = createFileOps();\n\tconst filteredEntries = entries;\n\tlet totalTokens = 0;\n\n\t// First pass: collect file ops from ALL entries (even if they don't fit in token budget)\n\t// This ensures we capture cumulative file tracking from nested branch summaries\n\t// Only extract from pi-generated summaries (fromHook !== true), not extension-generated ones\n\tfor (const entry of filteredEntries) {\n\t\tif (entry.type === \"branch_summary\" && !entry.fromHook && entry.details) {\n\t\t\tconst details = entry.details as BranchSummaryDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\t// Modified files go into both edited and written for proper deduplication\n\t\t\t\tfor (const f of details.modifiedFiles) {\n\t\t\t\t\tfileOps.edited.add(f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: walk from newest to oldest, adding messages until token budget\n\tfor (let i = filteredEntries.length - 1; i >= 0; i--) {\n\t\tconst entry = filteredEntries[i];\n\t\tconst message = getMessageFromEntry(entry);\n\t\tif (!message) continue;\n\n\t\t// Extract file ops from assistant messages (tool calls)\n\t\textractFileOpsFromMessage(message, fileOps);\n\n\t\tconst tokens = estimateTokens(message);\n\n\t\t// Check budget before adding\n\t\tif (tokenBudget > 0 && totalTokens + tokens > tokenBudget) {\n\t\t\t// If this is a branch summary entry, try to fit it anyway as it's important context\n\t\t\tif (entry.type === \"branch_summary\") {\n\t\t\t\tif (totalTokens < tokenBudget * 0.9) {\n\t\t\t\t\tmessages.unshift(message);\n\t\t\t\t\ttotalTokens += tokens;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Stop - we've hit the budget\n\t\t\tbreak;\n\t\t}\n\n\t\tmessages.unshift(message);\n\t\ttotalTokens += tokens;\n\t}\n\n\treturn { messages, fileOps, totalTokens };\n}\n\n// ============================================================================\n// Summary Generation\n// ============================================================================\n\nconst BRANCH_SUMMARY_PREAMBLE = `The user explored a different conversation branch before returning here.\nSummary of that exploration:\n\n`;\n\nconst BRANCH_SUMMARY_PROMPT = `Create a structured summary of this conversation branch for context when returning later.\n\nUse this EXACT format:\n\n## Goal\n[What was the user trying to accomplish in this branch?]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Work that was started but not finished]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [What should happen next to continue this work]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\n/**\n * Generate a summary of abandoned branch entries.\n *\n * @param entries - Session entries to summarize (chronological order)\n * @param options - Generation options\n */\nexport async function generateBranchSummary(\n\tentries: SessionEntry[],\n\toptions: GenerateBranchSummaryOptions,\n): Promise<BranchSummaryResult> {\n\tconst {\n\t\tmodel,\n\t\tapiKey,\n\t\theaders,\n\t\tbaseUrl,\n\t\tsignal,\n\t\tcustomInstructions,\n\t\treplaceInstructions,\n\t\treserveTokens = 16384,\n\t\tthinkingLevel,\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t} = options;\n\n\t// Token budget = context window minus reserved space for prompt + response\n\tconst contextWindow = model.contextWindow || 128000;\n\tconst tokenBudget = contextWindow - reserveTokens;\n\n\tconst { messages, fileOps } = prepareBranchEntries(entries, tokenBudget);\n\n\tif (messages.length === 0) {\n\t\treturn { summary: \"No content to summarize\" };\n\t}\n\n\t// Transform to LLM-compatible messages, then serialize to text\n\t// Serialization prevents the model from treating it as a conversation to continue\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build prompt\n\tlet instructions: string;\n\tif (replaceInstructions && customInstructions) {\n\t\tinstructions = customInstructions;\n\t} else if (customInstructions) {\n\t\tinstructions = `${BRANCH_SUMMARY_PROMPT}\\n\\nAdditional focus: ${customInstructions}`;\n\t} else {\n\t\tinstructions = BRANCH_SUMMARY_PROMPT;\n\t}\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${instructions}`;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\t// Call LLM for summarization. Prefer the session stream function so SDK\n\t// request behavior stays consistent without mutating agent state.\n\tconst context = { systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages };\n\tconst requestModel = baseUrl === undefined || baseUrl === model.baseUrl ? model : { ...model, baseUrl };\n\t// Same budget rule as the compaction planner: no output cap is sent, so\n\t// pi-ai's context clamp is the only bound and the inherited reasoning level\n\t// has no artificial budget to exhaust. `reserveTokens` keeps its input-side\n\t// meaning above, unchanged.\n\tconst budget = resolvePlannerRequest(requestModel, thinkingLevel);\n\tconst requestOptions: SimpleStreamOptions = {\n\t\tapiKey,\n\t\theaders,\n\t\tsignal,\n\t\tcacheRetention: \"none\",\n\t\tsessionId: uuidv7(),\n\t\t...(budget.reasoning && budget.reasoning !== \"off\" ? { reasoning: budget.reasoning } : {}),\n\t};\n\tconst response = await (async () => {\n\t\ttry {\n\t\t\treturn await retryAssistantCall(\n\t\t\t\tasync () =>\n\t\t\t\t\tstreamFn\n\t\t\t\t\t\t? (await streamFn(requestModel, context, requestOptions)).result()\n\t\t\t\t\t\t: completeSimple(requestModel, context, requestOptions),\n\t\t\t\tretry,\n\t\t\t\tsignal,\n\t\t\t\tcallbacks,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (signal.aborted) return undefined;\n\t\t\treturn {\n\t\t\t\tstopReason: \"error\" as const,\n\t\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\t};\n\t\t}\n\t})();\n\n\t// Check if aborted or errored\n\tif (!response || response.stopReason === \"aborted\") {\n\t\treturn { aborted: true };\n\t}\n\tif (response.stopReason === \"error\") {\n\t\treturn { error: response.errorMessage || \"Summarization failed\" };\n\t}\n\n\tlet summary = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\t// Prepend preamble to provide context about the branch summary\n\tsummary = BRANCH_SUMMARY_PREAMBLE + summary;\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\treturn {\n\t\tsummary: summary || \"No summary generated\",\n\t\tusage: response.usage,\n\t\treadFiles,\n\t\tmodifiedFiles,\n\t};\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import type { RetryCallbacks, RetryPolicy } from "@bastani/pi-ai";
|
|
2
|
+
import type { Api, Model } from "@bastani/pi-ai/compat";
|
|
1
3
|
import type { StreamFn, ThinkingLevel } from "@earendil-works/pi-agent-core";
|
|
2
|
-
import type { RetryCallbacks, RetryPolicy } from "@earendil-works/pi-ai";
|
|
3
|
-
import type { Api, Model } from "@earendil-works/pi-ai/compat";
|
|
4
4
|
import type { CompactedTranscript, CompactionPlannerModel, CompactionUrgency, PlannerAuth, VerbatimCompactionPreparation } from "./compaction-types.js";
|
|
5
5
|
import { type FallbackPlannerContext } from "./fallback-planner.js";
|
|
6
6
|
export interface CompactionPlanOptions {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-runner.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"compaction-runner.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClE,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,KAAK,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAE7E,OAAO,KAAK,EAEX,mBAAmB,EACnB,sBAAsB,EACtB,iBAAiB,EACjB,WAAW,EAEX,6BAA6B,EAC7B,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAGN,KAAK,sBAAsB,EAE3B,MAAM,uBAAuB,CAAC;AAY/B,MAAM,WAAW,qBAAqB;IACrC,QAAQ,EAAE,QAAQ,CAAC;IACnB,qFAAqF;IACrF,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,SAAS,CAAC,EAAE,cAAc,CAAC;CAC3B;AAED,8EAA8E;AAC9E,MAAM,WAAW,oBAAqB,SAAQ,qBAAqB;IAClE,2FAA2F;IAC3F,WAAW,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,KAAK,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC,CAAC;IACrE,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,mEAAmE;IACnE,aAAa,EAAE,aAAa,GAAG,SAAS,CAAC;IACzC,OAAO,EAAE,iBAAiB,CAAC;IAC3B,6EAA6E;IAC7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C7B,eAAe,EAAE,OAAO,CAAC,eAAe;oBACxC,KAAK,EAAE,OAAO,CAAC,KAAK;oBACpB,eAAe,EAAE,kBAAkB;oBACnC,GAAG,CAAC,YAAY,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,YAAY,CAAC,aAAa,EAAE,CAAC;iBAClG,CAAC,CAAC;YACJ,CAAC;YACD,OAAO,aAAa,CAAC,WAAW,EAAE,OAAO,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;QACjE,CAAC;QACD,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC;QAC/B,SAAS,CAAC,GAAG,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC,CAAC;QAC1C,OAAO,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC5E,QAAQ,GAAG,OAAO,KAAK,SAAS,CAAC;QACjC,IAAI,MAAM,EAAE,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;IAC9D,CAAC;IAED,IAAI,OAAO,CAAC,OAAO,KAAK,cAAc;QAAE,MAAM,aAAa,CAAC,YAAY,CAAC,CAAC;IAC1E,OAAO,WAAW,CAAC,WAAW,EAAE,cAAc,CAAC,CAAC;AACjD,CAAC","sourcesContent":["import type { StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { RetryCallbacks, RetryPolicy } from \"@earendil-works/pi-ai\";\nimport type { Api, Model } from \"@earendil-works/pi-ai/compat\";\nimport { getKeptTailTokenEstimate } from \"./compaction-boundary.js\";\nimport type {\n\tBorrowedPlanner,\n\tCompactedTranscript,\n\tCompactionPlannerModel,\n\tCompactionUrgency,\n\tPlannerAuth,\n\tRawLineRange,\n\tVerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { MIN_COMPACTABLE_REGION_LINES } from \"./compaction-types.js\";\nimport { reconstructCompactedTranscript, validateDeletedRanges } from \"./deleted-ranges.js\";\nimport {\n\ttype BorrowFallbackPlanner,\n\tcreateFallbackPlannerBorrower,\n\ttype FallbackPlannerContext,\n\tplannerAttemptKey,\n} from \"./fallback-planner.js\";\nimport type { TerminalPlannerOutcome } from \"./planner-outcome.js\";\nimport {\n\tMALFORMED_OUTPUT_MESSAGE,\n\tNO_USABLE_RANGES_MESSAGE,\n\tplanDeletedLineRanges,\n\tRangePlanError,\n\tresolvePlannerRequest,\n} from \"./range-planner.js\";\nimport { writeSuccessDiagnosticSidecar } from \"./range-planner-diagnostics.js\";\nimport { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from \"./region-trimming.js\";\n\nexport interface CompactionPlanOptions {\n\tstreamFn: StreamFn;\n\t/** Absolute path of the persisted session file. Undefined for in-memory sessions. */\n\tsessionFilePath?: string;\n\tretry?: RetryPolicy;\n\tcallbacks?: RetryCallbacks;\n}\n\n/** One compaction run's request. Urgency is required; there is no default. */\nexport interface CompactionRunRequest extends CompactionPlanOptions {\n\t/** Per-model credentials; a borrowed candidate uses its own, never the session model's. */\n\tresolveAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>;\n\tsignal?: AbortSignal;\n\t/** Inherited by the planner and never modified across attempts. */\n\tthinkingLevel: ThinkingLevel | undefined;\n\turgency: CompactionUrgency;\n\t/** Configured fallback candidates. Omitted means borrowing is impossible. */\n\tfallback?: FallbackPlannerContext;\n}\n\nexport type CompactionRungResult = CompactedTranscript & {\n\trung: \"planned\" | \"fresh\";\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** False only when the fresh rung had to drop the protected tail. */\n\tkeptTail: boolean;\n};\n\n/** Runner-internal fresh-window build: the transcript plus the tail decision. */\ninterface FreshWindowBuild {\n\ttranscript: CompactedTranscript;\n\tkeptTail: boolean;\n}\n\n/**\n * Calculate the single global line threshold from the prepared setting.\n *\n * Protected lines count *against* this target rather than raising it: keeping 40% under a 0.5\n * ratio leaves the remaining 60% to compress harder to hit the same total. That keeps the\n * compression ratio a real bound on output size, so protection can never enlarge the result.\n *\n * This is the untrimmed target. Overflow trimming does NOT reuse it:\n * `planWithTrimming` recomputes the threshold against each trimmed view, so the\n * planner is always asked to keep a proportion of the lines it actually\n * received rather than a proportion of a region it never saw.\n *\n * Retained as an exported helper for tests and consumers that need the\n * pre-trim target; production planning goes through `planWithTrimming`.\n */\nexport function targetKeepLines(preparation: VerbatimCompactionPreparation): number {\n\tconst region = preparation.region;\n\treturn Math.round(region.lines.length * preparation.parameters.compression_ratio);\n}\n\nfunction hardInputLimitFor(model: Model<Api>): number {\n\treturn model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n}\n\nfunction withWholeContextStats(\n\tresult: CompactedTranscript,\n\tpreparation: VerbatimCompactionPreparation,\n\tkeptTail: boolean,\n): CompactedTranscript {\n\tconst tokensAfter = result.stats.tokensAfter + (keptTail ? getKeptTailTokenEstimate(preparation) : 0);\n\tconst percentReduction =\n\t\tpreparation.tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / preparation.tokensBefore) * 1000) / 10;\n\treturn {\n\t\t...result,\n\t\tstats: { ...result.stats, tokensBefore: preparation.tokensBefore, tokensAfter, percentReduction },\n\t};\n}\n\n/**\n * Build a fresh context window and the tail decision that goes with it.\n *\n * Private on purpose: `keptTail` is runner bookkeeping that persistence needs in\n * order to write `firstKeptEntryId: null` when the protected tail is dropped. It\n * is deliberately absent from the public door's return value, which is exactly a\n * `CompactedTranscript`.\n */\nfunction buildFreshTranscript(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\tconst region = preparation.region;\n\tconst whole: RawLineRange[] = region.lines.length > 0 ? [{ start: 1, end: region.lines.length }] : [];\n\treturn reconstructCompactedTranscript(region, validateDeletedRanges(whole, region));\n}\n\nfunction buildFreshContextWindow(preparation: VerbatimCompactionPreparation, hardInputLimit: number): FreshWindowBuild {\n\tconst limit = Number.isFinite(hardInputLimit) && hardInputLimit > 0 ? hardInputLimit : Number.POSITIVE_INFINITY;\n\t// The rule is \"tail under the limit ⇒ tail kept\", so the comparison is the\n\t// tail alone. Explicit protected lines are a hard floor that survives either\n\t// way, and counting the reconstructed protected/marker text here would drop a\n\t// tail that fits. A rebuilt context that still cannot be sent is the post-tool\n\t// gate's problem, not a reason for this rung to discard more.\n\treturn { transcript: buildFreshTranscript(preparation), keptTail: getKeptTailTokenEstimate(preparation) <= limit };\n}\n\n/**\n * Discard every compactable line and start a fresh context window.\n *\n * TOTAL. No provider, no credentials, no network, no signal, no failure mode,\n * no `Promise`. Port of codex `compact_token_budget` →\n * `Session::start_new_context_window`. Atomic's system prompt, context files,\n * and skills are rebuilt per request and were never in the transcript, so they\n * survive automatically.\n *\n * The whole region is emitted as one deletion range and handed to the unchanged\n * `validateDeletedRanges` → `reconstructCompactedTranscript` path, which splits\n * around protected spans and folds prior markers.\n *\n * Returns exactly a `CompactedTranscript` — `text`, `ranges`, `stats` and\n * nothing else. Whether the `preserve_recent` tail survives is a persistence\n * concern and travels on `CompactionRungResult.keptTail`, not on this door.\n */\nexport function startNewContextWindow(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\treturn buildFreshTranscript(preparation);\n}\n\nfunction plannedResult(\n\tpreparation: VerbatimCompactionPreparation,\n\tranges: RawLineRange[],\n\tplannerModel: CompactionPlannerModel | undefined,\n): CompactionRungResult {\n\tconst reconstructed = reconstructCompactedTranscript(\n\t\tpreparation.region,\n\t\tvalidateDeletedRanges(ranges, preparation.region),\n\t);\n\treturn {\n\t\t...withWholeContextStats(reconstructed, preparation, true),\n\t\trung: \"planned\",\n\t\t...(plannerModel ? { plannerModel } : {}),\n\t\tkeptTail: true,\n\t};\n}\n\nfunction borrowedIdentity(planner: BorrowedPlanner): CompactionPlannerModel {\n\treturn {\n\t\tprovider: planner.model.provider,\n\t\tid: planner.model.id,\n\t\t...(planner.budget.reasoning ? { thinkingLevel: planner.budget.reasoning } : {}),\n\t};\n}\n\nfunction terminalError(outcome: TerminalPlannerOutcome | undefined): RangePlanError {\n\tif (!outcome) return new RangePlanError(MALFORMED_OUTPUT_MESSAGE, 1, \"\", false);\n\tif (outcome.kind === \"rateLimited\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tif (outcome.kind === \"overflowed\") {\n\t\treturn new RangePlanError(\n\t\t\t\"Compaction range planning exceeded the model context window\",\n\t\t\t1,\n\t\t\t\"\",\n\t\t\ttrue,\n\t\t\toutcome.diagnosticPath,\n\t\t\toutcome,\n\t\t);\n\t}\n\tif (outcome.kind === \"providerError\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tconst message = outcome.category === \"malformed_output\" ? MALFORMED_OUTPUT_MESSAGE : NO_USABLE_RANGES_MESSAGE;\n\treturn new RangePlanError(message, 1, outcome.excerpt, false, outcome.diagnosticPath, outcome);\n}\n\ntype PlannerAttempt =\n\t| { kind: \"planned\"; ranges: RawLineRange[] }\n\t| { kind: \"terminal\"; outcome: TerminalPlannerOutcome };\n\n/**\n * Run one planner model, retrying the same model after oldest-first input\n * trimming when the request itself overflows the context window.\n *\n * Trimming continues until no strictly smaller view exists; `nextTrimOffset`\n * halves the remaining suffix, so the walk is finite. Only then is `overflowed`\n * terminal and the ladder advances.\n *\n * Each view gets its own keep target from `compression_ratio`. Reusing the\n * original whole-preparation target is what asked a halved 20-line region to\n * keep 10 of its 10 visible lines — a request for zero deletions, whose obedient\n * empty answer then hits the non-negotiable zero-range rejection. Extra\n * reduction still comes only from the head the runner withheld.\n */\nasync function planWithTrimming(\n\tpreparation: VerbatimCompactionPreparation,\n\tplanner: BorrowedPlanner,\n\toptions: CompactionPlanOptions & { signal?: AbortSignal },\n): Promise<PlannerAttempt> {\n\tlet offset = 0;\n\tfor (;;) {\n\t\tconst region = offset === 0 ? preparation.region : trimRegionHead(preparation.region, offset);\n\t\tif (!region) return { kind: \"terminal\", outcome: { kind: \"overflowed\" } };\n\t\tconst keepTarget = Math.max(\n\t\t\tregion.protectedLineNumbers?.size ?? 0,\n\t\t\tMath.round(region.lines.length * preparation.parameters.compression_ratio),\n\t\t);\n\t\tconst outcome = await planDeletedLineRanges(region, preparation.parameters, planner, keepTarget, options);\n\t\tif (outcome.kind === \"ranked\" || outcome.kind === \"recovered\") {\n\t\t\tif (offset === 0) return { kind: \"planned\", ranges: outcome.ranges };\n\t\t\tconst validated = validateDeletedRanges(outcome.ranges, region);\n\t\t\treturn { kind: \"planned\", ranges: rebaseTrimmedRanges(validated, offset) };\n\t\t}\n\t\tif (outcome.kind !== \"overflowed\") return { kind: \"terminal\", outcome };\n\t\tif (options.signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tconst next = nextTrimOffset(preparation.region, offset);\n\t\tif (next === undefined) return { kind: \"terminal\", outcome };\n\t\toffset = next;\n\t}\n}\n\nconst MISSING_AUTH_MESSAGE = \"Compaction provider authentication is unavailable\";\n\n/**\n * A runner-local terminal cause with no provider attempt behind it.\n *\n * Missing credentials are not a provider outcome — no request was made — so no\n * synthetic response is fabricated and no diagnostic sidecar is written. It is\n * carried as `providerError` purely so the ladder can advance past it.\n */\nfunction authFailureOutcome(error: unknown): TerminalPlannerOutcome {\n\tconst message = error instanceof Error ? error.message : error === undefined ? MISSING_AUTH_MESSAGE : String(error);\n\treturn { kind: \"providerError\", message: message || MISSING_AUTH_MESSAGE };\n}\n\n/** Resolve one model's credentials, normalizing a rejection and `undefined` alike. */\nasync function resolvePlannerAuth(\n\tresolveAuth: CompactionRunRequest[\"resolveAuth\"],\n\tmodel: Model<Api>,\n): Promise<{ auth: PlannerAuth } | { failure: TerminalPlannerOutcome }> {\n\ttry {\n\t\tconst auth = await resolveAuth(model);\n\t\treturn auth ? { auth } : { failure: authFailureOutcome(undefined) };\n\t} catch (error) {\n\t\treturn { failure: authFailureOutcome(error) };\n\t}\n}\n\nfunction freshResult(preparation: VerbatimCompactionPreparation, hardInputLimit: number): CompactionRungResult {\n\tconst fresh = buildFreshContextWindow(preparation, hardInputLimit);\n\treturn {\n\t\t...withWholeContextStats(fresh.transcript, preparation, fresh.keptTail),\n\t\trung: \"fresh\",\n\t\tkeptTail: fresh.keptTail,\n\t};\n}\n\n/**\n * Produce one compacted transcript, tagged with the rung that produced it.\n *\n * The ladder is: the session model, then each configured fallback model\n * borrowed for one planner request, then — only under `load_bearing` urgency —\n * a fresh context window. A manual `/compact` runs at `recoverable` urgency and\n * therefore cannot reach the context-destroying rung; it fails honestly instead.\n *\n * Unavailable credentials are ladder control flow, not an early throw: a\n * borrowed candidate with its own working credentials can still rank the lines,\n * and a load-bearing caller still reaches the credential-free fresh rung.\n */\nexport async function runVerbatimCompaction(\n\tpreparation: VerbatimCompactionPreparation,\n\tmodel: Model<Api>,\n\trequest: CompactionRunRequest,\n): Promise<CompactionRungResult> {\n\tconst signal = request.signal;\n\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\tconst plannerOptions = {\n\t\tstreamFn: request.streamFn,\n\t\tsessionFilePath: request.sessionFilePath,\n\t\tretry: request.retry,\n\t\tcallbacks: request.callbacks,\n\t\tsignal,\n\t};\n\tconst hardInputLimit = hardInputLimitFor(model);\n\n\t// A region below the planner minimum cannot be made rankable by changing\n\t// models, so no planner is invoked. Only a load-bearing caller can reach a\n\t// preparation this small; recoverable callers were refused before the runner.\n\tif (preparation.region.lines.length < MIN_COMPACTABLE_REGION_LINES) {\n\t\tif (request.urgency !== \"load_bearing\") throw new RangePlanError(NO_USABLE_RANGES_MESSAGE, 0, \"\", false);\n\t\treturn freshResult(preparation, hardInputLimit);\n\t}\n\n\tconst attempted = new Set<string>();\n\t// One borrower per run owns the monotonic cursor, so the configured list is\n\t// walked exactly once no matter how many terminal outcomes occur.\n\tconst borrow: BorrowFallbackPlanner | undefined = request.fallback\n\t\t? createFallbackPlannerBorrower(request.fallback)\n\t\t: undefined;\n\tconst primaryBudget = resolvePlannerRequest(model, request.thinkingLevel);\n\tconst primaryAuth = await resolvePlannerAuth(request.resolveAuth, model);\n\tlet lastTerminal: TerminalPlannerOutcome | undefined = \"failure\" in primaryAuth ? primaryAuth.failure : undefined;\n\tlet borrowed = false;\n\tlet planner: BorrowedPlanner | undefined;\n\n\tif (\"auth\" in primaryAuth) {\n\t\tplanner = { model, budget: primaryBudget, auth: primaryAuth.auth };\n\t} else {\n\t\t// No request was made, but this candidate must not be retried.\n\t\tattempted.add(plannerAttemptKey({ model, budget: primaryBudget, auth: {} }));\n\t\tplanner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t}\n\n\twhile (planner) {\n\t\tconst attempt = await planWithTrimming(preparation, planner, plannerOptions);\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tif (attempt.kind === \"planned\") {\n\t\t\tconst plannerModel = borrowed ? borrowedIdentity(planner) : undefined;\n\t\t\tif (plannerModel) {\n\t\t\t\t// Best-effort: the durable entry already records the borrowed model;\n\t\t\t\t// a sidecar write failure never affects compaction success.\n\t\t\t\twriteSuccessDiagnosticSidecar({\n\t\t\t\t\tsessionFilePath: request.sessionFilePath,\n\t\t\t\t\tmodel: planner.model,\n\t\t\t\t\tsuccessCategory: \"borrowed_planner\",\n\t\t\t\t\t...(plannerModel.thinkingLevel === undefined ? {} : { thinkingLevel: plannerModel.thinkingLevel }),\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn plannedResult(preparation, attempt.ranges, plannerModel);\n\t\t}\n\t\tlastTerminal = attempt.outcome;\n\t\tattempted.add(plannerAttemptKey(planner));\n\t\tplanner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t}\n\n\tif (request.urgency !== \"load_bearing\") throw terminalError(lastTerminal);\n\treturn freshResult(preparation, hardInputLimit);\n}\n"]}
|
|
1
|
+
{"version":3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AE,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;IAC9D,CAAC;IAED,IAAI,OAAO,CAAC,OAAO,KAAK,cAAc;QAAE,MAAM,aAAa,CAAC,YAAY,CAAC,CAAC;IAC1E,OAAO,WAAW,CAAC,WAAW,EAAE,cAAc,CAAC,CAAC;AACjD,CAAC","sourcesContent":["import type { RetryCallbacks, RetryPolicy } from \"@bastani/pi-ai\";\nimport type { Api, Model } from \"@bastani/pi-ai/compat\";\nimport type { StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { getKeptTailTokenEstimate } from \"./compaction-boundary.js\";\nimport type {\n\tBorrowedPlanner,\n\tCompactedTranscript,\n\tCompactionPlannerModel,\n\tCompactionUrgency,\n\tPlannerAuth,\n\tRawLineRange,\n\tVerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { MIN_COMPACTABLE_REGION_LINES } from \"./compaction-types.js\";\nimport { reconstructCompactedTranscript, validateDeletedRanges } from \"./deleted-ranges.js\";\nimport {\n\ttype BorrowFallbackPlanner,\n\tcreateFallbackPlannerBorrower,\n\ttype FallbackPlannerContext,\n\tplannerAttemptKey,\n} from \"./fallback-planner.js\";\nimport type { TerminalPlannerOutcome } from \"./planner-outcome.js\";\nimport {\n\tMALFORMED_OUTPUT_MESSAGE,\n\tNO_USABLE_RANGES_MESSAGE,\n\tplanDeletedLineRanges,\n\tRangePlanError,\n\tresolvePlannerRequest,\n} from \"./range-planner.js\";\nimport { writeSuccessDiagnosticSidecar } from \"./range-planner-diagnostics.js\";\nimport { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from \"./region-trimming.js\";\n\nexport interface CompactionPlanOptions {\n\tstreamFn: StreamFn;\n\t/** Absolute path of the persisted session file. Undefined for in-memory sessions. */\n\tsessionFilePath?: string;\n\tretry?: RetryPolicy;\n\tcallbacks?: RetryCallbacks;\n}\n\n/** One compaction run's request. Urgency is required; there is no default. */\nexport interface CompactionRunRequest extends CompactionPlanOptions {\n\t/** Per-model credentials; a borrowed candidate uses its own, never the session model's. */\n\tresolveAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>;\n\tsignal?: AbortSignal;\n\t/** Inherited by the planner and never modified across attempts. */\n\tthinkingLevel: ThinkingLevel | undefined;\n\turgency: CompactionUrgency;\n\t/** Configured fallback candidates. Omitted means borrowing is impossible. */\n\tfallback?: FallbackPlannerContext;\n}\n\nexport type CompactionRungResult = CompactedTranscript & {\n\trung: \"planned\" | \"fresh\";\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\t/** False only when the fresh rung had to drop the protected tail. */\n\tkeptTail: boolean;\n};\n\n/** Runner-internal fresh-window build: the transcript plus the tail decision. */\ninterface FreshWindowBuild {\n\ttranscript: CompactedTranscript;\n\tkeptTail: boolean;\n}\n\n/**\n * Calculate the single global line threshold from the prepared setting.\n *\n * Protected lines count *against* this target rather than raising it: keeping 40% under a 0.5\n * ratio leaves the remaining 60% to compress harder to hit the same total. That keeps the\n * compression ratio a real bound on output size, so protection can never enlarge the result.\n *\n * This is the untrimmed target. Overflow trimming does NOT reuse it:\n * `planWithTrimming` recomputes the threshold against each trimmed view, so the\n * planner is always asked to keep a proportion of the lines it actually\n * received rather than a proportion of a region it never saw.\n *\n * Retained as an exported helper for tests and consumers that need the\n * pre-trim target; production planning goes through `planWithTrimming`.\n */\nexport function targetKeepLines(preparation: VerbatimCompactionPreparation): number {\n\tconst region = preparation.region;\n\treturn Math.round(region.lines.length * preparation.parameters.compression_ratio);\n}\n\nfunction hardInputLimitFor(model: Model<Api>): number {\n\treturn model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n}\n\nfunction withWholeContextStats(\n\tresult: CompactedTranscript,\n\tpreparation: VerbatimCompactionPreparation,\n\tkeptTail: boolean,\n): CompactedTranscript {\n\tconst tokensAfter = result.stats.tokensAfter + (keptTail ? getKeptTailTokenEstimate(preparation) : 0);\n\tconst percentReduction =\n\t\tpreparation.tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / preparation.tokensBefore) * 1000) / 10;\n\treturn {\n\t\t...result,\n\t\tstats: { ...result.stats, tokensBefore: preparation.tokensBefore, tokensAfter, percentReduction },\n\t};\n}\n\n/**\n * Build a fresh context window and the tail decision that goes with it.\n *\n * Private on purpose: `keptTail` is runner bookkeeping that persistence needs in\n * order to write `firstKeptEntryId: null` when the protected tail is dropped. It\n * is deliberately absent from the public door's return value, which is exactly a\n * `CompactedTranscript`.\n */\nfunction buildFreshTranscript(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\tconst region = preparation.region;\n\tconst whole: RawLineRange[] = region.lines.length > 0 ? [{ start: 1, end: region.lines.length }] : [];\n\treturn reconstructCompactedTranscript(region, validateDeletedRanges(whole, region));\n}\n\nfunction buildFreshContextWindow(preparation: VerbatimCompactionPreparation, hardInputLimit: number): FreshWindowBuild {\n\tconst limit = Number.isFinite(hardInputLimit) && hardInputLimit > 0 ? hardInputLimit : Number.POSITIVE_INFINITY;\n\t// The rule is \"tail under the limit ⇒ tail kept\", so the comparison is the\n\t// tail alone. Explicit protected lines are a hard floor that survives either\n\t// way, and counting the reconstructed protected/marker text here would drop a\n\t// tail that fits. A rebuilt context that still cannot be sent is the post-tool\n\t// gate's problem, not a reason for this rung to discard more.\n\treturn { transcript: buildFreshTranscript(preparation), keptTail: getKeptTailTokenEstimate(preparation) <= limit };\n}\n\n/**\n * Discard every compactable line and start a fresh context window.\n *\n * TOTAL. No provider, no credentials, no network, no signal, no failure mode,\n * no `Promise`. Port of codex `compact_token_budget` →\n * `Session::start_new_context_window`. Atomic's system prompt, context files,\n * and skills are rebuilt per request and were never in the transcript, so they\n * survive automatically.\n *\n * The whole region is emitted as one deletion range and handed to the unchanged\n * `validateDeletedRanges` → `reconstructCompactedTranscript` path, which splits\n * around protected spans and folds prior markers.\n *\n * Returns exactly a `CompactedTranscript` — `text`, `ranges`, `stats` and\n * nothing else. Whether the `preserve_recent` tail survives is a persistence\n * concern and travels on `CompactionRungResult.keptTail`, not on this door.\n */\nexport function startNewContextWindow(preparation: VerbatimCompactionPreparation): CompactedTranscript {\n\treturn buildFreshTranscript(preparation);\n}\n\nfunction plannedResult(\n\tpreparation: VerbatimCompactionPreparation,\n\tranges: RawLineRange[],\n\tplannerModel: CompactionPlannerModel | undefined,\n): CompactionRungResult {\n\tconst reconstructed = reconstructCompactedTranscript(\n\t\tpreparation.region,\n\t\tvalidateDeletedRanges(ranges, preparation.region),\n\t);\n\treturn {\n\t\t...withWholeContextStats(reconstructed, preparation, true),\n\t\trung: \"planned\",\n\t\t...(plannerModel ? { plannerModel } : {}),\n\t\tkeptTail: true,\n\t};\n}\n\nfunction borrowedIdentity(planner: BorrowedPlanner): CompactionPlannerModel {\n\treturn {\n\t\tprovider: planner.model.provider,\n\t\tid: planner.model.id,\n\t\t...(planner.budget.reasoning ? { thinkingLevel: planner.budget.reasoning } : {}),\n\t};\n}\n\nfunction terminalError(outcome: TerminalPlannerOutcome | undefined): RangePlanError {\n\tif (!outcome) return new RangePlanError(MALFORMED_OUTPUT_MESSAGE, 1, \"\", false);\n\tif (outcome.kind === \"rateLimited\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tif (outcome.kind === \"overflowed\") {\n\t\treturn new RangePlanError(\n\t\t\t\"Compaction range planning exceeded the model context window\",\n\t\t\t1,\n\t\t\t\"\",\n\t\t\ttrue,\n\t\t\toutcome.diagnosticPath,\n\t\t\toutcome,\n\t\t);\n\t}\n\tif (outcome.kind === \"providerError\") {\n\t\treturn new RangePlanError(outcome.message, 1, \"\", false, outcome.diagnosticPath, outcome);\n\t}\n\tconst message = outcome.category === \"malformed_output\" ? MALFORMED_OUTPUT_MESSAGE : NO_USABLE_RANGES_MESSAGE;\n\treturn new RangePlanError(message, 1, outcome.excerpt, false, outcome.diagnosticPath, outcome);\n}\n\ntype PlannerAttempt =\n\t| { kind: \"planned\"; ranges: RawLineRange[] }\n\t| { kind: \"terminal\"; outcome: TerminalPlannerOutcome };\n\n/**\n * Run one planner model, retrying the same model after oldest-first input\n * trimming when the request itself overflows the context window.\n *\n * Trimming continues until no strictly smaller view exists; `nextTrimOffset`\n * halves the remaining suffix, so the walk is finite. Only then is `overflowed`\n * terminal and the ladder advances.\n *\n * Each view gets its own keep target from `compression_ratio`. Reusing the\n * original whole-preparation target is what asked a halved 20-line region to\n * keep 10 of its 10 visible lines — a request for zero deletions, whose obedient\n * empty answer then hits the non-negotiable zero-range rejection. Extra\n * reduction still comes only from the head the runner withheld.\n */\nasync function planWithTrimming(\n\tpreparation: VerbatimCompactionPreparation,\n\tplanner: BorrowedPlanner,\n\toptions: CompactionPlanOptions & { signal?: AbortSignal },\n): Promise<PlannerAttempt> {\n\tlet offset = 0;\n\tfor (;;) {\n\t\tconst region = offset === 0 ? preparation.region : trimRegionHead(preparation.region, offset);\n\t\tif (!region) return { kind: \"terminal\", outcome: { kind: \"overflowed\" } };\n\t\tconst keepTarget = Math.max(\n\t\t\tregion.protectedLineNumbers?.size ?? 0,\n\t\t\tMath.round(region.lines.length * preparation.parameters.compression_ratio),\n\t\t);\n\t\tconst outcome = await planDeletedLineRanges(region, preparation.parameters, planner, keepTarget, options);\n\t\tif (outcome.kind === \"ranked\" || outcome.kind === \"recovered\") {\n\t\t\tif (offset === 0) return { kind: \"planned\", ranges: outcome.ranges };\n\t\t\tconst validated = validateDeletedRanges(outcome.ranges, region);\n\t\t\treturn { kind: \"planned\", ranges: rebaseTrimmedRanges(validated, offset) };\n\t\t}\n\t\tif (outcome.kind !== \"overflowed\") return { kind: \"terminal\", outcome };\n\t\tif (options.signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tconst next = nextTrimOffset(preparation.region, offset);\n\t\tif (next === undefined) return { kind: \"terminal\", outcome };\n\t\toffset = next;\n\t}\n}\n\nconst MISSING_AUTH_MESSAGE = \"Compaction provider authentication is unavailable\";\n\n/**\n * A runner-local terminal cause with no provider attempt behind it.\n *\n * Missing credentials are not a provider outcome — no request was made — so no\n * synthetic response is fabricated and no diagnostic sidecar is written. It is\n * carried as `providerError` purely so the ladder can advance past it.\n */\nfunction authFailureOutcome(error: unknown): TerminalPlannerOutcome {\n\tconst message = error instanceof Error ? error.message : error === undefined ? MISSING_AUTH_MESSAGE : String(error);\n\treturn { kind: \"providerError\", message: message || MISSING_AUTH_MESSAGE };\n}\n\n/** Resolve one model's credentials, normalizing a rejection and `undefined` alike. */\nasync function resolvePlannerAuth(\n\tresolveAuth: CompactionRunRequest[\"resolveAuth\"],\n\tmodel: Model<Api>,\n): Promise<{ auth: PlannerAuth } | { failure: TerminalPlannerOutcome }> {\n\ttry {\n\t\tconst auth = await resolveAuth(model);\n\t\treturn auth ? { auth } : { failure: authFailureOutcome(undefined) };\n\t} catch (error) {\n\t\treturn { failure: authFailureOutcome(error) };\n\t}\n}\n\nfunction freshResult(preparation: VerbatimCompactionPreparation, hardInputLimit: number): CompactionRungResult {\n\tconst fresh = buildFreshContextWindow(preparation, hardInputLimit);\n\treturn {\n\t\t...withWholeContextStats(fresh.transcript, preparation, fresh.keptTail),\n\t\trung: \"fresh\",\n\t\tkeptTail: fresh.keptTail,\n\t};\n}\n\n/**\n * Produce one compacted transcript, tagged with the rung that produced it.\n *\n * The ladder is: the session model, then each configured fallback model\n * borrowed for one planner request, then — only under `load_bearing` urgency —\n * a fresh context window. A manual `/compact` runs at `recoverable` urgency and\n * therefore cannot reach the context-destroying rung; it fails honestly instead.\n *\n * Unavailable credentials are ladder control flow, not an early throw: a\n * borrowed candidate with its own working credentials can still rank the lines,\n * and a load-bearing caller still reaches the credential-free fresh rung.\n */\nexport async function runVerbatimCompaction(\n\tpreparation: VerbatimCompactionPreparation,\n\tmodel: Model<Api>,\n\trequest: CompactionRunRequest,\n): Promise<CompactionRungResult> {\n\tconst signal = request.signal;\n\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\tconst plannerOptions = {\n\t\tstreamFn: request.streamFn,\n\t\tsessionFilePath: request.sessionFilePath,\n\t\tretry: request.retry,\n\t\tcallbacks: request.callbacks,\n\t\tsignal,\n\t};\n\tconst hardInputLimit = hardInputLimitFor(model);\n\n\t// A region below the planner minimum cannot be made rankable by changing\n\t// models, so no planner is invoked. Only a load-bearing caller can reach a\n\t// preparation this small; recoverable callers were refused before the runner.\n\tif (preparation.region.lines.length < MIN_COMPACTABLE_REGION_LINES) {\n\t\tif (request.urgency !== \"load_bearing\") throw new RangePlanError(NO_USABLE_RANGES_MESSAGE, 0, \"\", false);\n\t\treturn freshResult(preparation, hardInputLimit);\n\t}\n\n\tconst attempted = new Set<string>();\n\t// One borrower per run owns the monotonic cursor, so the configured list is\n\t// walked exactly once no matter how many terminal outcomes occur.\n\tconst borrow: BorrowFallbackPlanner | undefined = request.fallback\n\t\t? createFallbackPlannerBorrower(request.fallback)\n\t\t: undefined;\n\tconst primaryBudget = resolvePlannerRequest(model, request.thinkingLevel);\n\tconst primaryAuth = await resolvePlannerAuth(request.resolveAuth, model);\n\tlet lastTerminal: TerminalPlannerOutcome | undefined = \"failure\" in primaryAuth ? primaryAuth.failure : undefined;\n\tlet borrowed = false;\n\tlet planner: BorrowedPlanner | undefined;\n\n\tif (\"auth\" in primaryAuth) {\n\t\tplanner = { model, budget: primaryBudget, auth: primaryAuth.auth };\n\t} else {\n\t\t// No request was made, but this candidate must not be retried.\n\t\tattempted.add(plannerAttemptKey({ model, budget: primaryBudget, auth: {} }));\n\t\tplanner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t}\n\n\twhile (planner) {\n\t\tconst attempt = await planWithTrimming(preparation, planner, plannerOptions);\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t\tif (attempt.kind === \"planned\") {\n\t\t\tconst plannerModel = borrowed ? borrowedIdentity(planner) : undefined;\n\t\t\tif (plannerModel) {\n\t\t\t\t// Best-effort: the durable entry already records the borrowed model;\n\t\t\t\t// a sidecar write failure never affects compaction success.\n\t\t\t\twriteSuccessDiagnosticSidecar({\n\t\t\t\t\tsessionFilePath: request.sessionFilePath,\n\t\t\t\t\tmodel: planner.model,\n\t\t\t\t\tsuccessCategory: \"borrowed_planner\",\n\t\t\t\t\t...(plannerModel.thinkingLevel === undefined ? {} : { thinkingLevel: plannerModel.thinkingLevel }),\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn plannedResult(preparation, attempt.ranges, plannerModel);\n\t\t}\n\t\tlastTerminal = attempt.outcome;\n\t\tattempted.add(plannerAttemptKey(planner));\n\t\tplanner = borrow ? await borrow(attempted, request.resolveAuth) : undefined;\n\t\tborrowed = planner !== undefined;\n\t\tif (signal?.aborted) throw new Error(\"Compaction cancelled\");\n\t}\n\n\tif (request.urgency !== \"load_bearing\") throw terminalError(lastTerminal);\n\treturn freshResult(preparation, hardInputLimit);\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import type { ProviderHeaders } from "@bastani/pi-ai";
|
|
2
|
+
import type { Api, Model } from "@bastani/pi-ai/compat";
|
|
1
3
|
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
|
|
2
|
-
import type { ProviderHeaders } from "@earendil-works/pi-ai";
|
|
3
|
-
import type { Api, Model } from "@earendil-works/pi-ai/compat";
|
|
4
4
|
import type { CompactionSettings } from "./compaction.ts";
|
|
5
5
|
export declare const VERBATIM_COMPACTION_PROMPT_VERSION: 3;
|
|
6
6
|
export declare const VERBATIM_COMPACTION_STRATEGY: "verbatim-lines";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-types.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"compaction-types.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAC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,EAAE,MAAM,CAAC;IACjB,EAAE,EAAE,MAAM,CAAC;IACX,aAAa,CAAC,EAAE,aAAa,CAAC;CAC9B;AAED,MAAM,WAAW,yBAAyB;IACzC,QAAQ,EAAE,OAAO,4BAA4B,CAAC;IAC9C,aAAa,EAAE,OAAO,kCAAkC,CAAC;IACzD,UAAU,EAAE,4BAA4B,CAAC;IACzC,KAAK,EAAE,uBAAuB,CAAC;IAC/B,IAAI,EAAE,cAAc,CAAC;IACrB,oEAAoE;IACpE,YAAY,CAAC,EAAE,sBAAsB,CAAC;IACtC,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,6BAA6B;IAC7C,0FAA0F;IAC1F,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,MAAM,EAAE,cAAc,CAAC;IACvB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,4BAA4B,CAAC;IACzC,QAAQ,EAAE,kBAAkB,CAAC;CAC7B;AAED,MAAM,WAAW,wBAAwB;IACxC,aAAa,EAAE,MAAM,CAAC;IACtB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,uBAAuB,CAAC;IAC/B,UAAU,EAAE,4BAA4B,CAAC;IACzC,aAAa,EAAE,OAAO,kCAAkC,CAAC;IACzD,IAAI,EAAE,cAAc,CAAC;IACrB,oEAAoE;IACpE,YAAY,CAAC,EAAE,sBAAsB,CAAC;IACtC,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-types.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAU,CAAC;AAC7D,MAAM,CAAC,MAAM,4BAA4B,GAAG,gBAAyB,CAAC;AAEtE,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAC7C,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AACzC,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,CAAC","sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"compaction-types.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAU,CAAC;AAC7D,MAAM,CAAC,MAAM,4BAA4B,GAAG,gBAAyB,CAAC;AAEtE,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAC7C,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AACzC,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,CAAC","sourcesContent":["import type { ProviderHeaders } from \"@bastani/pi-ai\";\nimport type { Api, Model } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { CompactionSettings } from \"./compaction.ts\";\n\nexport const VERBATIM_COMPACTION_PROMPT_VERSION = 3 as const;\nexport const VERBATIM_COMPACTION_STRATEGY = \"verbatim-lines\" as const;\n\nexport const DEFAULT_COMPRESSION_RATIO = 0.5;\nexport const DEFAULT_PRESERVE_RECENT = 2;\nexport const MIN_COMPACTABLE_REGION_LINES = 20;\n\nexport interface VerbatimCompactionParameters {\n\t/** Fraction of compactable region lines to keep. */\n\tcompression_ratio: number;\n\t/** Recent context-eligible messages retained outside the compactable region. */\n\tpreserve_recent: number;\n\t/** Relevance focus used by the range planner. */\n\tquery: string;\n}\n\nexport interface LineRange {\n\t/** One-based inclusive first line. */\n\tstart: number;\n\t/** One-based inclusive last line. */\n\tend: number;\n}\n\nexport type RawLineEndpoint = number | string | boolean | null;\n\nexport interface RawLineRange {\n\tstart?: RawLineEndpoint;\n\tend?: RawLineEndpoint;\n}\n\nexport interface NumberedRegion {\n\treadonly __brand: \"NumberedRegion\";\n\tlines: string[];\n\theaderLineNumbers: ReadonlySet<number>;\n\tpriorMarkerNs: ReadonlyMap<number, number>;\n\t/** Optional future protected spans, expressed as one-based line numbers. */\n\tprotectedLineNumbers?: ReadonlySet<number>;\n\ttokenEstimate: number;\n}\n\nexport type ValidatedRanges = readonly LineRange[] & { readonly __brand: \"ValidatedRanges\" };\n\nexport interface CompactedTranscript {\n\ttext: string;\n\tranges: LineRange[];\n\t/**\n\t * Ranges force-preserved by `<keepContext>` protection; empty when nothing was protected.\n\t * Reported so protection that fired unexpectedly — a transcript that quotes tag text, say —\n\t * is diagnosable rather than a silent reduction in what compaction reclaimed.\n\t */\n\tkeptRanges: LineRange[];\n\tstats: VerbatimCompactionStats;\n}\n\nexport interface VerbatimCompactionStats {\n\tlinesBefore: number;\n\tlinesDeleted: number;\n\tlinesKept: number;\n\trangeCount: number;\n\ttokensBefore: number;\n\ttokensAfter: number;\n\tpercentReduction: number;\n}\n\n/** How much the caller can afford to lose if compaction does not happen. */\nexport type CompactionUrgency =\n\t/** Manual /compact, threshold auto-compaction — failing is safe. */\n\t| \"recoverable\"\n\t/** Overflow recovery, post-tool preflight — failing kills the turn. */\n\t| \"load_bearing\";\n\n/** How a durable compaction boundary was produced. */\nexport type CompactionRung = \"planned\" | \"extension\" | \"fresh\";\n\n/** Credentials for one planner request. Resolved per model, never shared. */\nexport interface PlannerAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * What one planner request may spend.\n *\n * `maxTokens` is declared `undefined`, not `number | undefined`: the type\n * forbids reintroducing the `0.8 * reserveTokens` output cap without changing\n * the type and failing review. pi-ai's `clampMaxTokensToContext` is the only bound.\n */\nexport interface PlannerBudget {\n\treadonly maxTokens: undefined;\n\treadonly reasoning: ThinkingLevel | undefined;\n}\n\n/**\n * A planner-only model borrowing. Cannot be confused with a session model switch.\n *\n * It carries no attempted-set key: the effective identity of an attempt is\n * `provider/model:<effective reasoning>`, derived from `model` and\n * `budget.reasoning` by `plannerAttemptKey`. Storing a key resolved from the raw\n * optional suffix would let the same effective request run twice.\n */\nexport interface BorrowedPlanner {\n\treadonly model: Model<Api>;\n\treadonly budget: PlannerBudget;\n\treadonly auth: PlannerAuth;\n}\n\n/** Identity of the model that ranked the deleted lines, when it was borrowed. */\nexport interface CompactionPlannerModel {\n\tprovider: string;\n\tid: string;\n\tthinkingLevel?: ThinkingLevel;\n}\n\nexport interface VerbatimCompactionDetails {\n\tstrategy: typeof VERBATIM_COMPACTION_STRATEGY;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\tparameters: VerbatimCompactionParameters;\n\tstats: VerbatimCompactionStats;\n\trung: CompactionRung;\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\tbackupPath?: string;\n}\n\nexport interface VerbatimCompactionPreparation {\n\t/** First context-visible tail entry, or null when no pre-boundary message is retained. */\n\tfirstKeptEntryId: string | null;\n\tregion: NumberedRegion;\n\tregionEntryIds: string[];\n\tkeptTailMessageCount: number;\n\ttokensBefore: number;\n\tparameters: VerbatimCompactionParameters;\n\tsettings: CompactionSettings;\n}\n\nexport interface VerbatimCompactionResult {\n\tcompactedText: string;\n\tfirstKeptEntryId: string | null;\n\ttokensBefore: number;\n\tstats: VerbatimCompactionStats;\n\tparameters: VerbatimCompactionParameters;\n\tpromptVersion: typeof VERBATIM_COMPACTION_PROMPT_VERSION;\n\trung: CompactionRung;\n\t/** Present only when a borrowed fallback model ranked the lines. */\n\tplannerModel?: CompactionPlannerModel;\n\tbackupPath?: string;\n}\n"]}
|