@bastani/atomic 0.9.5-alpha.8 → 0.9.5
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 +122 -0
- package/README.md +2 -2
- package/dist/builtin/cursor/CHANGELOG.md +12 -0
- package/dist/builtin/cursor/package.json +3 -3
- package/dist/builtin/cursor/src/model-mapper.ts +6 -3
- package/dist/builtin/intercom/CHANGELOG.md +37 -0
- package/dist/builtin/intercom/README.md +4 -2
- package/dist/builtin/intercom/broker/broker.ts +6 -114
- package/dist/builtin/intercom/broker/client.ts +29 -54
- package/dist/builtin/intercom/broker/delivered-message-cache.ts +44 -0
- package/dist/builtin/intercom/broker/pending-send-registry.ts +142 -0
- package/dist/builtin/intercom/broker/send-handler.ts +106 -0
- package/dist/builtin/intercom/broker/send-signature.ts +37 -0
- package/dist/builtin/intercom/foreground-detach-handoff.ts +136 -0
- package/dist/builtin/intercom/index-heavy.ts +49 -53
- package/dist/builtin/intercom/index.ts +278 -262
- package/dist/builtin/intercom/lazy-heavy-proxy.ts +114 -0
- package/dist/builtin/intercom/lazy-subagent-ack.ts +20 -0
- package/dist/builtin/intercom/lazy-tool-execution.ts +39 -0
- package/dist/builtin/intercom/lifecycle-lease.ts +51 -0
- package/dist/builtin/intercom/lifecycle.ts +37 -20
- package/dist/builtin/intercom/package.json +3 -6
- package/dist/builtin/intercom/reply-routing.ts +17 -0
- package/dist/builtin/intercom/subagent-relay.ts +58 -12
- package/dist/builtin/intercom/types.ts +3 -3
- package/dist/builtin/mcp/CHANGELOG.md +38 -0
- package/dist/builtin/mcp/OAUTH.md +1 -0
- package/dist/builtin/mcp/README.md +10 -6
- package/dist/builtin/mcp/apps-cancellation.ts +32 -0
- package/dist/builtin/mcp/call-tool-result.ts +9 -0
- package/dist/builtin/mcp/caller-wait.ts +50 -0
- package/dist/builtin/mcp/command-registration.ts +82 -0
- package/dist/builtin/mcp/direct-tool-executor.ts +279 -0
- package/dist/builtin/mcp/direct-tools.ts +40 -255
- package/dist/builtin/mcp/host-html-template.ts +4 -2
- package/dist/builtin/mcp/index.ts +274 -239
- package/dist/builtin/mcp/init.ts +96 -126
- package/dist/builtin/mcp/mcp-auth-flow.ts +247 -237
- package/dist/builtin/mcp/mcp-callback-server.ts +89 -68
- package/dist/builtin/mcp/mcp-oauth-provider.ts +23 -1
- package/dist/builtin/mcp/metadata-hydration.ts +52 -0
- package/dist/builtin/mcp/package.json +3 -3
- package/dist/builtin/mcp/proxy-auth.ts +4 -4
- package/dist/builtin/mcp/proxy-call.ts +111 -40
- package/dist/builtin/mcp/proxy-connect.ts +35 -15
- package/dist/builtin/mcp/proxy-info-modes.ts +106 -23
- package/dist/builtin/mcp/proxy-modes.ts +3 -3
- package/dist/builtin/mcp/session-cleanup-barrier.ts +43 -0
- package/dist/builtin/mcp/startup-warmup.ts +98 -0
- package/dist/builtin/mcp/state-lease.ts +12 -0
- package/dist/builtin/mcp/tool-result-renderer.ts +3 -3
- package/dist/builtin/mcp/ui-server.ts +8 -8
- package/dist/builtin/mcp/ui-session.ts +9 -18
- package/dist/builtin/subagents/CHANGELOG.md +78 -0
- package/dist/builtin/subagents/README.md +30 -29
- 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/debugger.md +2 -2
- package/dist/builtin/subagents/agents/worker.md +2 -2
- package/dist/builtin/subagents/package.json +5 -5
- package/dist/builtin/subagents/prompts/review-loop.md +1 -1
- package/dist/builtin/subagents/skills/subagent/SKILL.md +37 -36
- package/dist/builtin/subagents/src/extension/api-lifecycle.ts +64 -0
- package/dist/builtin/subagents/src/extension/fanout-child.ts +44 -51
- package/dist/builtin/subagents/src/extension/index.ts +289 -320
- package/dist/builtin/subagents/src/extension/prompt-guidance.ts +7 -10
- package/dist/builtin/subagents/src/extension/schemas.ts +22 -5
- package/dist/builtin/subagents/src/extension/startup-maintenance.ts +89 -0
- package/dist/builtin/subagents/src/extension/tool-description.ts +29 -0
- package/dist/builtin/subagents/src/intercom/intercom-bridge.ts +13 -2
- package/dist/builtin/subagents/src/intercom/result-intercom.ts +4 -4
- package/dist/builtin/subagents/src/runs/background/async-event-journal.ts +106 -0
- package/dist/builtin/subagents/src/runs/background/async-execution-common.ts +26 -20
- package/dist/builtin/subagents/src/runs/background/async-execution-single.ts +13 -2
- package/dist/builtin/subagents/src/runs/background/async-execution-types.ts +3 -0
- package/dist/builtin/subagents/src/runs/background/async-job-tracker.ts +1 -1
- package/dist/builtin/subagents/src/runs/background/completion-claims.ts +189 -0
- package/dist/builtin/subagents/src/runs/background/completion-dedupe.ts +44 -7
- package/dist/builtin/subagents/src/runs/background/completion-notification.ts +34 -0
- package/dist/builtin/subagents/src/runs/background/notify.ts +72 -22
- package/dist/builtin/subagents/src/runs/background/result-delivery-processor.ts +232 -0
- package/dist/builtin/subagents/src/runs/background/result-file-claims.ts +151 -0
- package/dist/builtin/subagents/src/runs/background/result-quarantine.ts +72 -0
- package/dist/builtin/subagents/src/runs/background/result-retry-scheduler.ts +48 -0
- package/dist/builtin/subagents/src/runs/background/result-status.ts +81 -0
- package/dist/builtin/subagents/src/runs/background/result-watcher-data.ts +59 -0
- package/dist/builtin/subagents/src/runs/background/result-watcher.ts +177 -233
- package/dist/builtin/subagents/src/runs/background/run-id-resolver.ts +3 -2
- package/dist/builtin/subagents/src/runs/background/stale-run-reconciler.ts +73 -14
- package/dist/builtin/subagents/src/runs/background/subagent-runner-streaming.ts +29 -15
- package/dist/builtin/subagents/src/runs/background/top-level-async.ts +1 -2
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-dynamic-step.ts +1 -0
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-parallel-runner.ts +1 -0
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-parallel-step.ts +1 -0
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-sequential-step.ts +7 -9
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-types.ts +3 -13
- package/dist/builtin/subagents/src/runs/foreground/chain-execution.ts +2 -15
- package/dist/builtin/subagents/src/runs/foreground/execution-attempt-finalize.ts +2 -2
- package/dist/builtin/subagents/src/runs/foreground/execution-attempt.ts +63 -46
- package/dist/builtin/subagents/src/runs/foreground/execution-detach-reservations.ts +48 -0
- package/dist/builtin/subagents/src/runs/foreground/execution-detach-route.ts +17 -0
- package/dist/builtin/subagents/src/runs/foreground/execution-run-sync.ts +39 -26
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-async.ts +3 -1
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-chain.ts +3 -51
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-context.ts +6 -11
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-input.ts +11 -2
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel-task.ts +2 -0
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel.ts +5 -112
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-resume.ts +2 -0
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-single.ts +68 -118
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-status.ts +79 -7
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-types.ts +2 -2
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor.ts +3 -0
- package/dist/builtin/subagents/src/runs/shared/pi-args.ts +2 -2
- package/dist/builtin/subagents/src/runs/shared/pi-spawn.ts +55 -12
- package/dist/builtin/subagents/src/shared/artifacts.ts +22 -11
- package/dist/builtin/subagents/src/shared/event-jsonl-writer.ts +294 -0
- package/dist/builtin/subagents/src/shared/exclusive-file-publication.ts +44 -0
- package/dist/builtin/subagents/src/shared/jsonl-writer.ts +1 -0
- package/dist/builtin/subagents/src/shared/model-info.ts +2 -2
- package/dist/builtin/subagents/src/shared/settings.ts +20 -10
- package/dist/builtin/subagents/src/shared/types-async.ts +3 -1
- package/dist/builtin/subagents/src/shared/types-config.ts +2 -0
- package/dist/builtin/subagents/src/shared/types-runtime.ts +3 -2
- package/dist/builtin/subagents/src/slash/slash-commands.ts +9 -12
- package/dist/builtin/subagents/src/slash/slash-live-state.ts +63 -32
- package/dist/builtin/subagents/src/tui/render-result.ts +7 -0
- package/dist/builtin/subagents/src/tui/render-stable-output.ts +1 -0
- package/dist/builtin/subagents/src/tui/render-widget.ts +157 -89
- package/dist/builtin/web-access/CHANGELOG.md +28 -0
- package/dist/builtin/web-access/README.md +4 -0
- package/dist/builtin/web-access/content-tools.ts +8 -3
- package/dist/builtin/web-access/index-heavy.ts +1 -1
- package/dist/builtin/web-access/index.ts +190 -46
- package/dist/builtin/web-access/lifecycle-lease.ts +38 -0
- package/dist/builtin/web-access/package.json +2 -2
- package/dist/builtin/web-access/result-renderers.ts +1 -1
- package/dist/builtin/web-access/summary-review.ts +1 -1
- package/dist/builtin/web-access/web-search-activity.ts +1 -1
- package/dist/builtin/web-access/web-search-return.ts +7 -0
- package/dist/builtin/web-access/web-search-summary.ts +1 -1
- package/dist/builtin/web-access/web-search-tool.ts +4 -2
- package/dist/builtin/workflows/CHANGELOG.md +86 -0
- package/dist/builtin/workflows/README.md +5 -5
- package/dist/builtin/workflows/builtin/deep-research-codebase-utils.ts +27 -4
- package/dist/builtin/workflows/builtin/goal-runner.ts +86 -27
- package/dist/builtin/workflows/builtin/open-claude-design-runner.ts +10 -0
- package/dist/builtin/workflows/builtin/ralph-core.ts +9 -9
- package/dist/builtin/workflows/builtin/ralph-models.ts +71 -36
- package/dist/builtin/workflows/builtin/ralph-runner.ts +20 -31
- package/dist/builtin/workflows/package.json +2 -2
- package/dist/builtin/workflows/skills/impeccable/SKILL.md +16 -13
- package/dist/builtin/workflows/skills/impeccable/reference/adapt.md +1 -0
- package/dist/builtin/workflows/skills/impeccable/reference/adapt.native.md +58 -0
- package/dist/builtin/workflows/skills/impeccable/reference/android.md +40 -0
- package/dist/builtin/workflows/skills/impeccable/reference/animate.md +2 -0
- package/dist/builtin/workflows/skills/impeccable/reference/audit.md +2 -0
- package/dist/builtin/workflows/skills/impeccable/reference/audit.native.md +139 -0
- package/dist/builtin/workflows/skills/impeccable/reference/bolder.md +69 -62
- package/dist/builtin/workflows/skills/impeccable/reference/critique.md +21 -7
- package/dist/builtin/workflows/skills/impeccable/reference/document.md +1 -1
- package/dist/builtin/workflows/skills/impeccable/reference/hooks.md +92 -0
- package/dist/builtin/workflows/skills/impeccable/reference/init.md +29 -7
- package/dist/builtin/workflows/skills/impeccable/reference/ios.md +45 -0
- package/dist/builtin/workflows/skills/impeccable/reference/layout.md +25 -1
- package/dist/builtin/workflows/skills/impeccable/reference/typeset.md +23 -1
- package/dist/builtin/workflows/skills/impeccable/scripts/context-signals.mjs +2 -1
- package/dist/builtin/workflows/skills/impeccable/scripts/context.mjs +75 -14
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/browser/injected/index.mjs +1 -1
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/cli/main.mjs +31 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/design-system.mjs +64 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/detect-antipatterns-browser.js +118 -11
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs +16 -11
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/registry/antipatterns.mjs +66 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/rules/checks.mjs +42 -10
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/fonts.mjs +30 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/page.mjs +4 -6
- package/dist/builtin/workflows/skills/impeccable/scripts/hook-admin.mjs +660 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/hook-before-edit.mjs +516 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/hook-lib.mjs +1764 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/hook.mjs +61 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/lib/impeccable-config.mjs +4 -2
- package/dist/builtin/workflows/skills/impeccable/scripts/lib/is-generated.mjs +2 -2
- package/dist/builtin/workflows/skills/impeccable/scripts/live/svelte-component.mjs +13 -16
- package/dist/builtin/workflows/skills/impeccable/scripts/live-accept.mjs +17 -11
- package/dist/builtin/workflows/skills/impeccable/scripts/live-browser.js +104 -37
- package/dist/builtin/workflows/skills/impeccable/scripts/live-wrap.mjs +9 -0
- package/dist/builtin/workflows/src/durable/backend.ts +12 -0
- package/dist/builtin/workflows/src/durable/dbos-backend.ts +17 -1
- package/dist/builtin/workflows/src/durable/resume-catalog.ts +12 -0
- package/dist/builtin/workflows/src/durable/resume-runtime.ts +5 -2
- package/dist/builtin/workflows/src/durable/stage-primitive.ts +2 -1
- package/dist/builtin/workflows/src/durable/types.ts +16 -0
- package/dist/builtin/workflows/src/engine/primitives/task.ts +3 -1
- package/dist/builtin/workflows/src/engine/run-durable-finalize.ts +1 -2
- package/dist/builtin/workflows/src/engine/run-returned-status.ts +50 -16
- package/dist/builtin/workflows/src/engine/run.ts +20 -19
- package/dist/builtin/workflows/src/engine/runtime.ts +5 -0
- package/dist/builtin/workflows/src/extension/extension-factory.ts +3 -0
- package/dist/builtin/workflows/src/extension/extension-lifecycle.ts +9 -2
- package/dist/builtin/workflows/src/extension/extension-runtime-state.ts +137 -27
- package/dist/builtin/workflows/src/extension/lifecycle-notifications.ts +22 -6
- package/dist/builtin/workflows/src/extension/public-types.ts +1 -1
- package/dist/builtin/workflows/src/extension/workflow-command-completions.ts +13 -1
- package/dist/builtin/workflows/src/extension/workflow-command-registration.ts +19 -4
- package/dist/builtin/workflows/src/extension/workflow-command-surfaces.ts +9 -0
- package/dist/builtin/workflows/src/extension/workflow-prompts.ts +17 -22
- package/dist/builtin/workflows/src/extension/workflow-run-control-command.ts +48 -23
- package/dist/builtin/workflows/src/extension/workflow-schema.ts +15 -2
- package/dist/builtin/workflows/src/extension/workflow-tool-control.ts +20 -8
- package/dist/builtin/workflows/src/extension/workflow-tool.ts +24 -8
- package/dist/builtin/workflows/src/runs/background/status.ts +4 -3
- package/dist/builtin/workflows/src/runs/foreground/executor-direct-helpers.ts +29 -8
- package/dist/builtin/workflows/src/runs/foreground/executor-hil.ts +1 -1
- package/dist/builtin/workflows/src/runs/foreground/executor-stage-factory.ts +3 -2
- package/dist/builtin/workflows/src/runs/shared/model-fallback-candidates.ts +1 -1
- package/dist/builtin/workflows/src/runs/shared/worktree-git.ts +155 -20
- package/dist/builtin/workflows/src/runs/shared/worktree-types.ts +6 -0
- package/dist/builtin/workflows/src/runs/shared/worktree.ts +2 -1
- package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +2 -2
- package/dist/builtin/workflows/src/shared/authoring-contract-stage.ts +2 -2
- package/dist/builtin/workflows/src/shared/resume-continuation.ts +2 -0
- package/dist/builtin/workflows/src/shared/returned-run-status.ts +116 -0
- package/dist/builtin/workflows/src/shared/workflow-failures-decisions.ts +2 -0
- package/dist/builtin/workflows/src/tui/graph-view-render-helpers.ts +21 -3
- package/dist/builtin/workflows/src/tui/graph-view-state.ts +3 -0
- package/dist/builtin/workflows/src/tui/graph-view-types.ts +3 -0
- package/dist/builtin/workflows/src/tui/stage-chat-view-archive-history.ts +1 -23
- package/dist/builtin/workflows/src/tui/stage-chat-view-footer-status.ts +54 -9
- package/dist/builtin/workflows/src/tui/stage-chat-view.ts +5 -2
- package/dist/builtin/workflows/src/tui/status-list.ts +22 -15
- package/dist/builtin/workflows/src/tui/workflow-attach-pane.ts +4 -4
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +2 -2
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-session-auto-compaction.d.ts +23 -3
- package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-auto-compaction.js +129 -17
- package/dist/core/agent-session-auto-compaction.js.map +1 -1
- package/dist/core/agent-session-events.d.ts.map +1 -1
- package/dist/core/agent-session-events.js +9 -1
- package/dist/core/agent-session-events.js.map +1 -1
- package/dist/core/agent-session-message-queue.d.ts.map +1 -1
- package/dist/core/agent-session-message-queue.js +1 -1
- package/dist/core/agent-session-message-queue.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +6 -3
- 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-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +2 -2
- package/dist/core/agent-session-prompt.js.map +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-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +3 -2
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session-types.d.ts.map +1 -1
- package/dist/core/agent-session-types.js +1 -1
- package/dist/core/agent-session-types.js.map +1 -1
- package/dist/core/agent-session.d.ts +4 -2
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +4 -2
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/anthropic-thinking-guard.d.ts +5 -5
- package/dist/core/anthropic-thinking-guard.d.ts.map +1 -1
- package/dist/core/anthropic-thinking-guard.js +42 -32
- package/dist/core/anthropic-thinking-guard.js.map +1 -1
- package/dist/core/atomic-guide-command.d.ts.map +1 -1
- package/dist/core/atomic-guide-command.js +15 -15
- package/dist/core/atomic-guide-command.js.map +1 -1
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +14 -9
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +2 -0
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +79 -46
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/context-assistant-turns.d.ts +42 -0
- package/dist/core/compaction/context-assistant-turns.d.ts.map +1 -0
- package/dist/core/compaction/context-assistant-turns.js +87 -0
- package/dist/core/compaction/context-assistant-turns.js.map +1 -0
- package/dist/core/compaction/context-compaction-critical.d.ts +1 -1
- package/dist/core/compaction/context-compaction-critical.d.ts.map +1 -1
- package/dist/core/compaction/context-compaction-critical.js +2 -2
- package/dist/core/compaction/context-compaction-critical.js.map +1 -1
- package/dist/core/compaction/context-compaction-eviction-alternates.d.ts +18 -0
- package/dist/core/compaction/context-compaction-eviction-alternates.d.ts.map +1 -0
- package/dist/core/compaction/context-compaction-eviction-alternates.js +186 -0
- package/dist/core/compaction/context-compaction-eviction-alternates.js.map +1 -0
- package/dist/core/compaction/context-compaction-eviction.d.ts +10 -2
- package/dist/core/compaction/context-compaction-eviction.d.ts.map +1 -1
- package/dist/core/compaction/context-compaction-eviction.js +196 -146
- package/dist/core/compaction/context-compaction-eviction.js.map +1 -1
- package/dist/core/compaction/context-compaction-prompt.d.ts.map +1 -1
- package/dist/core/compaction/context-compaction-prompt.js +1 -1
- package/dist/core/compaction/context-compaction-prompt.js.map +1 -1
- package/dist/core/compaction/context-compaction-types.d.ts +2 -0
- package/dist/core/compaction/context-compaction-types.d.ts.map +1 -1
- package/dist/core/compaction/context-compaction-types.js.map +1 -1
- package/dist/core/compaction/context-deletion-application.d.ts +5 -4
- package/dist/core/compaction/context-deletion-application.d.ts.map +1 -1
- package/dist/core/compaction/context-deletion-application.js +17 -15
- package/dist/core/compaction/context-deletion-application.js.map +1 -1
- package/dist/core/compaction/context-deletion-store.d.ts.map +1 -1
- package/dist/core/compaction/context-deletion-store.js +1 -1
- package/dist/core/compaction/context-deletion-store.js.map +1 -1
- package/dist/core/compaction/context-deletion-targets.d.ts +2 -1
- package/dist/core/compaction/context-deletion-targets.d.ts.map +1 -1
- package/dist/core/compaction/context-deletion-targets.js +36 -31
- package/dist/core/compaction/context-deletion-targets.js.map +1 -1
- package/dist/core/compaction/context-deletion-tool-helpers.d.ts.map +1 -1
- package/dist/core/compaction/context-deletion-tool-helpers.js +116 -43
- package/dist/core/compaction/context-deletion-tool-helpers.js.map +1 -1
- package/dist/core/compaction/context-transcript-analysis.d.ts +1 -2
- package/dist/core/compaction/context-transcript-analysis.d.ts.map +1 -1
- package/dist/core/compaction/context-transcript-analysis.js +33 -37
- package/dist/core/compaction/context-transcript-analysis.js.map +1 -1
- package/dist/core/copilot-model-synthesis.d.ts.map +1 -1
- package/dist/core/copilot-model-synthesis.js +3 -1
- package/dist/core/copilot-model-synthesis.js.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.d.ts +8 -1
- package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.js +2 -1
- package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
- package/dist/core/extensions/provider-types.d.ts +2 -7
- package/dist/core/extensions/provider-types.d.ts.map +1 -1
- package/dist/core/extensions/provider-types.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts +6 -0
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js +72 -29
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/messages.d.ts +9 -0
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +100 -18
- package/dist/core/messages.js.map +1 -1
- package/dist/core/model-registry-builtins.d.ts.map +1 -1
- package/dist/core/model-registry-builtins.js +5 -0
- package/dist/core/model-registry-builtins.js.map +1 -1
- package/dist/core/model-registry-custom-loader.d.ts.map +1 -1
- package/dist/core/model-registry-custom-loader.js +49 -8
- package/dist/core/model-registry-custom-loader.js.map +1 -1
- package/dist/core/model-registry-dynamic.d.ts.map +1 -1
- package/dist/core/model-registry-dynamic.js +11 -5
- package/dist/core/model-registry-dynamic.js.map +1 -1
- package/dist/core/model-registry-loader.d.ts.map +1 -1
- package/dist/core/model-registry-loader.js +8 -0
- package/dist/core/model-registry-loader.js.map +1 -1
- package/dist/core/model-registry-schemas.d.ts +93 -8
- package/dist/core/model-registry-schemas.d.ts.map +1 -1
- package/dist/core/model-registry-schemas.js +24 -12
- package/dist/core/model-registry-schemas.js.map +1 -1
- package/dist/core/model-registry-types.d.ts +7 -6
- package/dist/core/model-registry-types.d.ts.map +1 -1
- package/dist/core/model-registry-types.js.map +1 -1
- package/dist/core/model-registry.d.ts +5 -0
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +23 -0
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver-cli.d.ts.map +1 -1
- package/dist/core/model-resolver-cli.js +33 -5
- package/dist/core/model-resolver-cli.js.map +1 -1
- package/dist/core/model-resolver-initial.d.ts +6 -1
- package/dist/core/model-resolver-initial.d.ts.map +1 -1
- package/dist/core/model-resolver-initial.js +12 -7
- package/dist/core/model-resolver-initial.js.map +1 -1
- package/dist/core/model-resolver.d.ts +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/openai-responses-payload-sanitizer.d.ts +1 -0
- package/dist/core/openai-responses-payload-sanitizer.d.ts.map +1 -1
- package/dist/core/openai-responses-payload-sanitizer.js +24 -9
- package/dist/core/openai-responses-payload-sanitizer.js.map +1 -1
- package/dist/core/resource-loader-context-files.d.ts +1 -0
- package/dist/core/resource-loader-context-files.d.ts.map +1 -1
- package/dist/core/resource-loader-context-files.js +13 -10
- package/dist/core/resource-loader-context-files.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +2 -2
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-entry-normalization.d.ts +7 -0
- package/dist/core/session-entry-normalization.d.ts.map +1 -0
- package/dist/core/session-entry-normalization.js +14 -0
- package/dist/core/session-entry-normalization.js.map +1 -0
- package/dist/core/session-manager-core.d.ts.map +1 -1
- package/dist/core/session-manager-core.js +1 -0
- package/dist/core/session-manager-core.js.map +1 -1
- package/dist/core/session-manager-history.d.ts +2 -2
- package/dist/core/session-manager-history.d.ts.map +1 -1
- package/dist/core/session-manager-history.js +127 -108
- package/dist/core/session-manager-history.js.map +1 -1
- package/dist/core/settings-manager-basic-accessors.d.ts +2 -2
- package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
- package/dist/core/settings-manager-basic-accessors.js.map +1 -1
- package/dist/core/settings-types.d.ts +1 -1
- package/dist/core/settings-types.d.ts.map +1 -1
- package/dist/core/settings-types.js.map +1 -1
- package/dist/core/slash-commands.d.ts +2 -0
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +141 -0
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +11 -8
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/main-deferred-startup.d.ts.map +1 -1
- package/dist/main-deferred-startup.js +2 -2
- package/dist/main-deferred-startup.js.map +1 -1
- package/dist/main-early-input.d.ts.map +1 -1
- package/dist/main-early-input.js +7 -0
- package/dist/main-early-input.js.map +1 -1
- package/dist/main-session.d.ts.map +1 -1
- package/dist/main-session.js +1 -0
- package/dist/main-session.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -1
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-actions.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-actions.js +0 -1
- package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector-options.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector-options.js +3 -1
- package/dist/modes/interactive/components/settings-selector-options.js.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +2 -1
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.js +3 -1
- package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
- package/dist/modes/interactive/interactive-autocomplete.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-autocomplete.js +21 -9
- package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
- package/dist/modes/interactive/interactive-child-ordering.d.ts +7 -0
- package/dist/modes/interactive/interactive-child-ordering.d.ts.map +1 -0
- package/dist/modes/interactive/interactive-child-ordering.js +26 -0
- package/dist/modes/interactive/interactive-child-ordering.js.map +1 -0
- package/dist/modes/interactive/interactive-deferred-startup.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-deferred-startup.js +43 -30
- package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
- package/dist/modes/interactive/interactive-hotkeys-debug.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-hotkeys-debug.js +1 -0
- package/dist/modes/interactive/interactive-hotkeys-debug.js.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.js +41 -6
- package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.d.ts +3 -0
- package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.js +3 -0
- package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-deps.d.ts +2 -2
- package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-deps.js +2 -2
- package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.d.ts +2 -2
- package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.js +11 -4
- package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
- package/dist/modes/interactive/interactive-process-lifecycle.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-process-lifecycle.js +0 -3
- package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
- package/dist/modes/interactive/interactive-render-chat.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-render-chat.js +15 -1
- package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
- package/dist/modes/interactive/interactive-session-routing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-session-routing.js +5 -1
- package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
- package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-startup.js +20 -21
- package/dist/modes/interactive/interactive-startup.js.map +1 -1
- package/dist/modes/interactive/theme/global-theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/global-theme.js +26 -2
- package/dist/modes/interactive/theme/global-theme.js.map +1 -1
- package/dist/modes/interactive/theme/theme-class.d.ts +1 -1
- package/dist/modes/interactive/theme/theme-class.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme-class.js +2 -0
- package/dist/modes/interactive/theme/theme-class.js.map +1 -1
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +3 -0
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/fs-watch.d.ts +24 -1
- package/dist/utils/fs-watch.d.ts.map +1 -1
- package/dist/utils/fs-watch.js +60 -5
- package/dist/utils/fs-watch.js.map +1 -1
- package/docs/changelog.mdx +19 -0
- package/docs/compaction.md +60 -49
- package/docs/custom-provider.md +18 -5
- package/docs/development.md +4 -0
- package/docs/extensions.md +11 -2
- package/docs/json.md +1 -1
- package/docs/models.md +69 -10
- package/docs/providers.md +1 -1
- package/docs/quickstart.md +12 -8
- package/docs/rpc.md +2 -2
- package/docs/sdk.md +1 -1
- package/docs/settings.md +4 -4
- package/docs/subagents.md +40 -5
- package/docs/tools.md +1 -1
- package/docs/usage.md +4 -2
- package/docs/windows.md +4 -0
- package/docs/workflows.md +33 -48
- package/examples/extensions/preset.ts +2 -2
- package/examples/extensions/subagent/README.md +2 -2
- package/examples/extensions/subagent/index.ts +1 -2
- package/examples/extensions/subagent/schemas.ts +4 -1
- package/examples/sdk/12-full-control.ts +1 -1
- package/npm-shrinkwrap.json +48 -51
- package/package.json +7 -7
- package/dist/builtin/subagents/src/runs/foreground/chain-clarify-behavior.ts +0 -75
- package/dist/builtin/subagents/src/runs/foreground/chain-clarify-component.ts +0 -202
- package/dist/builtin/subagents/src/runs/foreground/chain-clarify-edit.ts +0 -97
- package/dist/builtin/subagents/src/runs/foreground/chain-clarify-editor.ts +0 -160
- package/dist/builtin/subagents/src/runs/foreground/chain-clarify-frame.ts +0 -72
- package/dist/builtin/subagents/src/runs/foreground/chain-clarify-render-modes.ts +0 -161
- package/dist/builtin/subagents/src/runs/foreground/chain-clarify-render-selectors.ts +0 -203
- package/dist/builtin/subagents/src/runs/foreground/chain-clarify-selectors.ts +0 -234
- package/dist/builtin/subagents/src/runs/foreground/chain-clarify-state.ts +0 -103
- package/dist/builtin/subagents/src/runs/foreground/chain-clarify-types.ts +0 -29
- package/dist/builtin/subagents/src/runs/foreground/chain-clarify.ts +0 -9
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-clarify.ts +0 -117
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-auto-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAMrE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE9F,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,UAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAgGrI;AAGD,wBAAgB,6CAA6C,CAAC,IAAI,EAAE,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAQ7H;AAED,wBAAgB,mCAAmC,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAE/F;AAED;;GAEG;AAEH,wBAAgB,kDAAkD,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAQ3F;AAED;;GAEG;AAEH,wBAAgB,4CAA4C,CAAC,IAAI,EAAE,YAAY,EAC9E,MAAM,EAAE,UAAU,GAAG,WAAW,EAChC,SAAS,EAAE,OAAO,GAChB,IAAI,CAyCN;AAED,wBAAsB,+CAA+C,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAIvG;AAED;;GAEG;AAEH,wBAAsB,0BAA0B,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAWlF;AAOD,wBAAsB,kBAAkB,CAAC,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,UAAU,GAAG,WAAW,EAAE,SAAS,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAyEhI;AAED;;GAEG;AAEH,eAAO,MAAM,iCAAiC;;;;;;;;CAQ7C,CAAC","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { isContextOverflow } from \"@earendil-works/pi-ai/compat\";\nimport { getEffectiveInputBudget } from \"./context-window.ts\";\nimport { parseCopilotPromptLimitError } from \"./copilot-errors.ts\";\nimport { calculateContextTokens, estimateContextTokens, shouldCompact } from \"./compaction/index.ts\";\nimport { getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\nexport async function _checkCompaction(this: AgentSession, assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<void> {\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tif (!settings.enabled) return;\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\n\t// Skip overflow check if the message came from a different model.\n\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t// shouldn't trigger compaction for the new model.\n\tconst sameModel =\n\t\tthis.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;\n\n\t// Skip compaction checks if this assistant message is older than the latest\n\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t// from retriggering compaction on the first prompt after compaction.\n\tconst compactionBoundaryEntry = getLatestCompactionBoundaryEntry(this.sessionManager.getBranch());\n\tconst assistantIsFromBeforeCompactionBoundary =\n\t\tcompactionBoundaryEntry !== null &&\n\t\tassistantMessage.timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime();\n\tif (assistantIsFromBeforeCompactionBoundary) {\n\t\treturn;\n\t}\n\n\t// Case 1: Overflow - LLM returned context overflow error\n\t// When Copilot rejects a 1m client-budget prompt at a lower server cap (for example\n\t// because long-context/usage-based billing entitlement is missing), leave the friendly\n\t// error visible instead of auto-compacting down to a smaller server tier silently.\n\tif (sameModel && this._isCopilotServerCapBelowSelectedContextWindow(assistantMessage)) {\n\t\treturn;\n\t}\n\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\n\t\tconst willRetry = assistantMessage.stopReason !== \"stop\";\n\t\tif (!willRetry) {\n\t\t\tawait this._runAutoCompaction(\"overflow\", false);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._overflowRecoveryAttempted) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"overflow\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: true,\n\t\t\t\terrorMessage:\n\t\t\t\t\t\"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tthis._overflowRecoveryAttempted = true;\n\t\t// Remove the error message from agent state (it IS saved to session for history,\n\t\t// but we don't want it in context for the retry)\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tawait this._runAutoCompaction(\"overflow\", willRetry);\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For error messages (no usage data), estimate from last successful response.\n\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\tlet contextTokens: number;\n\tif (assistantMessage.stopReason === \"error\") {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t// trigger compaction right after one just finished.\n\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\tif (\n\t\t\tcompactionBoundaryEntry &&\n\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t} else {\n\t\tcontextTokens = calculateContextTokens(assistantMessage.usage);\n\t}\n\t// Compact against the effective input budget (the hard prompt cap for providers like Copilot\n\t// that advertise a larger total window) so we compact before overrunning the server-side limit\n\t// rather than relying on reactive overflow recovery near the cap.\n\tconst compactionBudget = this.model ? getEffectiveInputBudget(this.model) : contextWindow;\n\tif (shouldCompact(contextTokens, compactionBudget, settings)) {\n\t\tawait this._runAutoCompaction(\"threshold\", shouldRetryAfterThresholdCompaction(assistantMessage));\n\t}\n}\n\n\nexport function _isCopilotServerCapBelowSelectedContextWindow(this: AgentSession, assistantMessage: AssistantMessage): boolean {\n\tif (!this.model || this.model.provider !== \"github-copilot\" || !assistantMessage.errorMessage) return false;\n\tconst promptLimitError = parseCopilotPromptLimitError(assistantMessage.errorMessage);\n\t// Compare against the effective input budget (the model's real prompt cap), not the displayed\n\t// total window. A rejection at the prompt cap is a normal overflow we should compact-and-retry;\n\t// only a rejection *below* the cap (e.g. a missing long-context entitlement dropping the account\n\t// to a lower server tier) keeps the friendly error visible instead of silently compacting down.\n\treturn promptLimitError !== undefined && getEffectiveInputBudget(this.model) > promptLimitError.limitTokens;\n}\n\nexport function shouldRetryAfterThresholdCompaction(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): void {\n\tconst messages = this.agent.state.messages;\n\tconst lastMsg = messages[messages.length - 1];\n\tif (lastMsg?.role !== \"assistant\") return;\n\tconst stopReason = (lastMsg as AssistantMessage).stopReason;\n\tif (stopReason === \"error\" || stopReason === \"length\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n}\n\n/**\n * Internal: schedule a live post-event continuation probe after compaction_end listeners can flush queues.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(this: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tif (reason === \"overflow\" && willRetry) {\n\t\tconst token = this._overflowPostCompactionContinuationToken + 1;\n\t\tthis._overflowPostCompactionContinuationToken = token;\n\t\tlet pending: Promise<void>;\n\t\tpending = new Promise<void>((resolve) => {\n\t\t\tsetTimeout(() => {\n\t\t\t\tvoid (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (this._overflowPostCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (this._pendingOverflowPostCompactionContinuation === pending) {\n\t\t\t\t\t\t\tthis._pendingOverflowPostCompactionContinuation = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t}, 100);\n\t\t});\n\t\tthis._pendingOverflowPostCompactionContinuation = pending;\n\t\treturn;\n\t}\n\n\tsetTimeout(() => {\n\t\tif (this.isCompacting || this.isStreaming) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tvoid this._resumeAfterAutoCompaction();\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\treturn;\n\t\t}\n\n\t\tvoid this._resumeAfterAutoCompaction();\n\t}, 100);\n}\n\nexport async function _awaitPendingOverflowPostCompactionContinuation(this: AgentSession): Promise<void> {\n\tconst pending = this._pendingOverflowPostCompactionContinuation;\n\tif (pending === undefined) return;\n\tawait pending;\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport async function _resumeAfterAutoCompaction(this: AgentSession): Promise<void> {\n\ttry {\n\t\tawait this._runAgentContinue();\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis._emit({\n\t\t\ttype: \"agent_continue_error\",\n\t\t\tsource: \"post_compaction\",\n\t\t\terrorMessage: `Post-compaction continuation failed: ${message}`,\n\t\t});\n\t}\n}\n\n\nfunction overflowUnresolved(reason: \"overflow\" | \"threshold\", aborted = false): boolean | undefined {\n\treturn reason === \"overflow\" && !aborted ? true : undefined;\n}\n\nexport async function _runAutoCompaction(this: AgentSession, reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void> {\n\tthis._emit({ type: \"compaction_start\", reason });\n\tthis._autoCompactionAbortController = new AbortController();\n\n\ttry {\n\t\tif (!this.model) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Auth is resolved lazily: only called when the planner fallback is needed.\n\t\t// This allows extension-provided deletion requests to run before auth is checked,\n\t\t// enabling local extension compaction even when API credentials are unavailable.\n\t\t// Auto-mode resolver returns undefined (rather than throwing) when auth is missing;\n\t\t// overflow recovery then falls back to deterministic no-auth eviction, while\n\t\t// threshold compaction keeps the previous no-op behavior.\n\t\tconst model = this.model;\n\t\tconst result = await this._applyContextVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async () => {\n\t\t\t\tconst authResult = await this._modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\tif (!authResult.ok || !authResult.apiKey) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\treturn { apiKey: authResult.apiKey, headers: authResult.headers };\n\t\t\t},\n\t\t\tabortController: this._autoCompactionAbortController,\n\t\t\tbackupLabel: reason === \"overflow\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t});\n\t\tif (!result) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted = errorMessage === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tunresolvedOverflow: overflowUnresolved(reason, aborted),\n\t\t\terrorMessage: aborted\n\t\t\t\t? undefined\n\t\t\t\t: reason === \"overflow\"\n\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t});\n\t} finally {\n\t\tthis._autoCompactionAbortController = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingOverflowPostCompactionContinuation,\n\t_checkCompaction,\n\t_isCopilotServerCapBelowSelectedContextWindow,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_runAutoCompaction,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-auto-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAOrE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE9F;;;;;;GAMG;AACH,eAAO,MAAM,gCAAgC,IAAI,CAAC;AAElD,eAAO,MAAM,6CAA6C,IAAI,CAAC;AAc/D,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,UAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CA8HrI;AAGD,wBAAgB,6CAA6C,CAAC,IAAI,EAAE,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAQ7H;AAED,wBAAgB,uBAAuB,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAEnF;AAmDD,wBAAgB,8BAA8B,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAQ1F;AAED,wBAAgB,mCAAmC,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAE/F;AAED;;GAEG;AAEH,wBAAgB,kDAAkD,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAQ3F;AAED;;GAEG;AAEH,wBAAgB,4CAA4C,CAAC,IAAI,EAAE,YAAY,EAC9E,OAAO,EAAE,UAAU,GAAG,WAAW,EACjC,SAAS,EAAE,OAAO,GAChB,IAAI,CAoCN;AAED,wBAAsB,uCAAuC,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAI/F;AAED;;GAEG;AAEH,wBAAsB,0BAA0B,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAWlF;AAED;;;;;;GAMG;AAEH,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAQrE;AAOD,wBAAsB,kBAAkB,CAAC,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,UAAU,GAAG,WAAW,EAAE,SAAS,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAyEhI;AAED;;GAEG;AAEH,eAAO,MAAM,iCAAiC;;;;;;;;;CAS7C,CAAC","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { isContextOverflow } from \"@earendil-works/pi-ai/compat\";\nimport { getEffectiveInputBudget } from \"./context-window.ts\";\nimport { parseCopilotPromptLimitError } from \"./copilot-errors.ts\";\nimport { calculateContextTokens, estimateContextTokens, shouldCompact } from \"./compaction/index.ts\";\nimport { getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\nimport { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from \"./openai-responses-payload-sanitizer.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\n/**\n * Upper bound on consecutive automatic continuations of a response that was\n * truncated at the output-token cap (\"length\") while the context is still\n * below the compaction budget. Each continuation regenerates the cut-off turn,\n * so a model that insists on emitting more than its per-turn output cap can\n * still terminate instead of looping forever.\n */\nexport const MAX_LENGTH_CONTINUATION_ATTEMPTS = 3;\n\nexport const MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS = 1;\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\ntype ProviderErrorDetails = {\n\tmessage?: string;\n\tcode?: string;\n\tparam?: string;\n};\n\nconst OUTPUT_BUDGET_PARAMETER_PATTERN = /\\bmax_output_tokens\\b/;\nconst OUTPUT_BUDGET_UNDERFLOW_PATTERN = new RegExp(\n\t`(?:integer\\\\s+below\\\\s+minimum\\\\s+value|expected\\\\s+(?:a\\\\s+)?value\\\\s*>=\\\\s*${MIN_RESPONSES_MAX_OUTPUT_TOKENS}|got\\\\s+1\\\\s+instead)`,\n);\n\nexport async function _checkCompaction(this: AgentSession, assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<void> {\n\t// The agent_end path passes skipAbortedCheck=true; the pre-prompt path passes\n\t// false. Only the live turn-completion path may auto-continue a truncated\n\t// response — before a fresh user prompt we must not resume the old turn.\n\tconst isLiveTurnCompletion = skipAbortedCheck;\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tif (!settings.enabled) return;\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\n\t// Skip overflow check if the message came from a different model.\n\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t// shouldn't trigger compaction for the new model.\n\tconst sameModel =\n\t\tthis.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;\n\n\t// Skip compaction checks if this assistant message is older than the latest\n\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t// from retriggering compaction on the first prompt after compaction.\n\tconst compactionBoundaryEntry = getLatestCompactionBoundaryEntry(this.sessionManager.getBranch());\n\tconst assistantIsFromBeforeCompactionBoundary =\n\t\tcompactionBoundaryEntry !== null &&\n\t\tassistantMessage.timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime();\n\tif (assistantIsFromBeforeCompactionBoundary) {\n\t\treturn;\n\t}\n\n\t// Case 1: Overflow - LLM returned context overflow error\n\t// When Copilot rejects a 1m client-budget prompt at a lower server cap (for example\n\t// because long-context/usage-based billing entitlement is missing), leave the friendly\n\t// error visible instead of auto-compacting down to a smaller server tier silently.\n\tif (sameModel && this._isCopilotServerCapBelowSelectedContextWindow(assistantMessage)) {\n\t\treturn;\n\t}\n\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\n\t\tconst willRetry = assistantMessage.stopReason !== \"stop\";\n\t\tif (!willRetry) {\n\t\t\tawait this._runAutoCompaction(\"overflow\", false);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._overflowRecoveryAttempted) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"overflow\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: true,\n\t\t\t\terrorMessage:\n\t\t\t\t\t\"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tthis._overflowRecoveryAttempted = true;\n\t\t// Remove the error message from agent state (it IS saved to session for history,\n\t\t// but we don't want it in context for the retry)\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tawait this._runAutoCompaction(\"overflow\", willRetry);\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For error messages (no usage data), estimate from last successful response.\n\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\tlet contextTokens: number;\n\tif (assistantMessage.stopReason === \"error\") {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t// trigger compaction right after one just finished.\n\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\tif (\n\t\t\tcompactionBoundaryEntry &&\n\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t} else {\n\t\tcontextTokens = calculateContextTokens(assistantMessage.usage);\n\t}\n\t// Compact against the effective input budget (the hard prompt cap for providers like Copilot\n\t// that advertise a larger total window) so we compact before overrunning the server-side limit\n\t// rather than relying on reactive overflow recovery near the cap.\n\tconst compactionBudget = this.model ? getEffectiveInputBudget(this.model) : contextWindow;\n\tif (shouldCompact(contextTokens, compactionBudget, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\"Output-budget recovery stopped after a compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._outputBudgetErrorContinuationAttempts += 1;\n\t\t}\n\t\tawait this._runAutoCompaction(\"threshold\", willRetry);\n\t\treturn;\n\t}\n\n\t// A response truncated at the output-token cap (\"length\") with the context\n\t// still below the compaction budget is genuine work cut off mid-flight, not a\n\t// context overflow. Compaction would not free any room, so continue the\n\t// generation directly instead of dead-ending on the truncation and leaving\n\t// the task half-finished.\n\tif (isLiveTurnCompletion && isRetryWorthyLengthStop(assistantMessage)) {\n\t\tthis._resumeAfterLengthTruncation();\n\t}\n}\n\n\nexport function _isCopilotServerCapBelowSelectedContextWindow(this: AgentSession, assistantMessage: AssistantMessage): boolean {\n\tif (!this.model || this.model.provider !== \"github-copilot\" || !assistantMessage.errorMessage) return false;\n\tconst promptLimitError = parseCopilotPromptLimitError(assistantMessage.errorMessage);\n\t// Compare against the effective input budget (the model's real prompt cap), not the displayed\n\t// total window. A rejection at the prompt cap is a normal overflow we should compact-and-retry;\n\t// only a rejection *below* the cap (e.g. a missing long-context entitlement dropping the account\n\t// to a lower server tier) keeps the friendly error visible instead of silently compacting down.\n\treturn promptLimitError !== undefined && getEffectiveInputBudget(this.model) > promptLimitError.limitTokens;\n}\n\nexport function isRetryWorthyLengthStop(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\nfunction isJsonRecord(value: JsonValue): value is { [key: string]: JsonValue } {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: { [key: string]: JsonValue }, key: string): string | undefined {\n\tconst value = record[key];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction parseProviderErrorDetails(errorMessage: string): ProviderErrorDetails | undefined {\n\tconst start = errorMessage.indexOf(\"{\");\n\tconst end = errorMessage.lastIndexOf(\"}\");\n\tif (start === -1 || end <= start) return undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(errorMessage.slice(start, end + 1)) as JsonValue;\n\t\tif (!isJsonRecord(parsed)) return undefined;\n\n\t\tconst nestedError = parsed.error;\n\t\tif (nestedError !== undefined && isJsonRecord(nestedError)) {\n\t\t\treturn {\n\t\t\t\tmessage: stringField(nestedError, \"message\"),\n\t\t\t\tcode: stringField(nestedError, \"code\") ?? stringField(parsed, \"code\"),\n\t\t\t\tparam: stringField(nestedError, \"param\") ?? stringField(parsed, \"param\"),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tmessage: stringField(parsed, \"message\"),\n\t\t\tcode: stringField(parsed, \"code\"),\n\t\t\tparam: stringField(parsed, \"param\"),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isOutputBudgetUnderflowText(text: string): boolean {\n\tconst message = text.toLowerCase();\n\treturn OUTPUT_BUDGET_PARAMETER_PATTERN.test(message) && OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message);\n}\n\nfunction isStructuredOutputBudgetUnderflow(details: ProviderErrorDetails): boolean {\n\tconst message = details.message?.toLowerCase() ?? \"\";\n\tconst param = details.param?.toLowerCase();\n\tif (!OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message)) return false;\n\treturn param !== undefined ? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param) : OUTPUT_BUDGET_PARAMETER_PATTERN.test(message);\n}\n\nexport function isRetryWorthyOutputBudgetError(assistantMessage: AssistantMessage): boolean {\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return false;\n\tif (assistantMessage.api !== \"openai-responses\") return false;\n\n\tconst structuredDetails = parseProviderErrorDetails(assistantMessage.errorMessage);\n\tif (structuredDetails && isStructuredOutputBudgetUnderflow(structuredDetails)) return true;\n\n\treturn isOutputBudgetUnderflowText(assistantMessage.errorMessage);\n}\n\nexport function shouldRetryAfterThresholdCompaction(assistantMessage: AssistantMessage): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) || isRetryWorthyOutputBudgetError(assistantMessage);\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): void {\n\tconst messages = this.agent.state.messages;\n\tconst lastMsg = messages[messages.length - 1];\n\tif (lastMsg?.role !== \"assistant\") return;\n\tconst stopReason = (lastMsg as AssistantMessage).stopReason;\n\tif (stopReason === \"error\" || stopReason === \"length\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n}\n\n/**\n * Internal: schedule a live post-event continuation probe after compaction_end listeners can flush queues.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(this: AgentSession,\n\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tif (willRetry) {\n\t\tconst token = this._postCompactionContinuationToken + 1;\n\t\tthis._postCompactionContinuationToken = token;\n\t\tlet pending: Promise<void>;\n\t\tpending = new Promise<void>((resolve) => {\n\t\t\tsetTimeout(() => {\n\t\t\t\tvoid (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (this._pendingPostCompactionContinuation === pending) {\n\t\t\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t}, 100);\n\t\t});\n\t\tthis._pendingPostCompactionContinuation = pending;\n\t\treturn;\n\t}\n\n\tsetTimeout(() => {\n\t\tif (this.isCompacting || this.isStreaming) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\treturn;\n\t\t}\n\n\t\tvoid this._resumeAfterAutoCompaction();\n\t}, 100);\n}\n\nexport async function _awaitPendingPostCompactionContinuation(this: AgentSession): Promise<void> {\n\tconst pending = this._pendingPostCompactionContinuation;\n\tif (pending === undefined) return;\n\tawait pending;\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport async function _resumeAfterAutoCompaction(this: AgentSession): Promise<void> {\n\ttry {\n\t\tawait this._runAgentContinue();\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis._emit({\n\t\t\ttype: \"agent_continue_error\",\n\t\t\tsource: \"post_compaction\",\n\t\t\terrorMessage: `Post-compaction continuation failed: ${message}`,\n\t\t});\n\t}\n}\n\n/**\n * Internal: resume a response that was truncated at the output-token cap\n * (\"length\") when the context does not warrant compaction. The generation is\n * continued directly so the model finishes the work it was cut off from, rather\n * than dead-ending on the truncation. Bounded by MAX_LENGTH_CONTINUATION_ATTEMPTS\n * so a turn that keeps exceeding the per-turn output cap can still terminate.\n */\n\nexport function _resumeAfterLengthTruncation(this: AgentSession): void {\n\tif (this._lengthContinuationAttempts >= MAX_LENGTH_CONTINUATION_ATTEMPTS) return;\n\tthis._lengthContinuationAttempts += 1;\n\t// agent.continue() rejects an assistant tail; drop the incomplete\n\t// length-stopped message so the preceding user/tool-result anchors the\n\t// continuation. It remains persisted in session history.\n\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\tthis._schedulePostAutoCompactionContinuationProbe(\"threshold\", true);\n}\n\n\nfunction overflowUnresolved(reason: \"overflow\" | \"threshold\", aborted = false): boolean | undefined {\n\treturn reason === \"overflow\" && !aborted ? true : undefined;\n}\n\nexport async function _runAutoCompaction(this: AgentSession, reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void> {\n\tthis._emit({ type: \"compaction_start\", reason });\n\tthis._autoCompactionAbortController = new AbortController();\n\n\ttry {\n\t\tif (!this.model) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Auth is resolved lazily: only called when the planner fallback is needed.\n\t\t// This allows extension-provided deletion requests to run before auth is checked,\n\t\t// enabling local extension compaction even when API credentials are unavailable.\n\t\t// Auto-mode resolver returns undefined (rather than throwing) when auth is missing;\n\t\t// overflow recovery then falls back to deterministic no-auth eviction, while\n\t\t// threshold compaction keeps the previous no-op behavior.\n\t\tconst model = this.model;\n\t\tconst result = await this._applyContextVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async () => {\n\t\t\t\tconst authResult = await this._modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\tif (!authResult.ok || !authResult.apiKey) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\treturn { apiKey: authResult.apiKey, headers: authResult.headers };\n\t\t\t},\n\t\t\tabortController: this._autoCompactionAbortController,\n\t\t\tbackupLabel: reason === \"overflow\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t});\n\t\tif (!result) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted = errorMessage === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tunresolvedOverflow: overflowUnresolved(reason, aborted),\n\t\t\terrorMessage: aborted\n\t\t\t\t? undefined\n\t\t\t\t: reason === \"overflow\"\n\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t});\n\t} finally {\n\t\tthis._autoCompactionAbortController = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingPostCompactionContinuation,\n\t_checkCompaction,\n\t_isCopilotServerCapBelowSelectedContextWindow,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_resumeAfterLengthTruncation,\n\t_runAutoCompaction,\n};\n"]}
|
|
@@ -3,7 +3,23 @@ import { getEffectiveInputBudget } from "./context-window.js";
|
|
|
3
3
|
import { parseCopilotPromptLimitError } from "./copilot-errors.js";
|
|
4
4
|
import { calculateContextTokens, estimateContextTokens, shouldCompact } from "./compaction/index.js";
|
|
5
5
|
import { getLatestCompactionBoundaryEntry } from "./session-manager.js";
|
|
6
|
+
import { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from "./openai-responses-payload-sanitizer.js";
|
|
7
|
+
/**
|
|
8
|
+
* Upper bound on consecutive automatic continuations of a response that was
|
|
9
|
+
* truncated at the output-token cap ("length") while the context is still
|
|
10
|
+
* below the compaction budget. Each continuation regenerates the cut-off turn,
|
|
11
|
+
* so a model that insists on emitting more than its per-turn output cap can
|
|
12
|
+
* still terminate instead of looping forever.
|
|
13
|
+
*/
|
|
14
|
+
export const MAX_LENGTH_CONTINUATION_ATTEMPTS = 3;
|
|
15
|
+
export const MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS = 1;
|
|
16
|
+
const OUTPUT_BUDGET_PARAMETER_PATTERN = /\bmax_output_tokens\b/;
|
|
17
|
+
const OUTPUT_BUDGET_UNDERFLOW_PATTERN = new RegExp(`(?:integer\\s+below\\s+minimum\\s+value|expected\\s+(?:a\\s+)?value\\s*>=\\s*${MIN_RESPONSES_MAX_OUTPUT_TOKENS}|got\\s+1\\s+instead)`);
|
|
6
18
|
export async function _checkCompaction(assistantMessage, skipAbortedCheck = true) {
|
|
19
|
+
// The agent_end path passes skipAbortedCheck=true; the pre-prompt path passes
|
|
20
|
+
// false. Only the live turn-completion path may auto-continue a truncated
|
|
21
|
+
// response — before a fresh user prompt we must not resume the old turn.
|
|
22
|
+
const isLiveTurnCompletion = skipAbortedCheck;
|
|
7
23
|
const settings = this.settingsManager.getCompactionSettings();
|
|
8
24
|
if (!settings.enabled)
|
|
9
25
|
return;
|
|
@@ -88,7 +104,31 @@ export async function _checkCompaction(assistantMessage, skipAbortedCheck = true
|
|
|
88
104
|
// rather than relying on reactive overflow recovery near the cap.
|
|
89
105
|
const compactionBudget = this.model ? getEffectiveInputBudget(this.model) : contextWindow;
|
|
90
106
|
if (shouldCompact(contextTokens, compactionBudget, settings)) {
|
|
91
|
-
|
|
107
|
+
const willRetry = shouldRetryAfterThresholdCompaction(assistantMessage);
|
|
108
|
+
if (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {
|
|
109
|
+
if (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {
|
|
110
|
+
this._emit({
|
|
111
|
+
type: "compaction_end",
|
|
112
|
+
reason: "threshold",
|
|
113
|
+
result: undefined,
|
|
114
|
+
aborted: false,
|
|
115
|
+
willRetry: false,
|
|
116
|
+
errorMessage: "Output-budget recovery stopped after a compact-and-retry attempt. Try reducing context or switching to a larger-context model.",
|
|
117
|
+
});
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
this._outputBudgetErrorContinuationAttempts += 1;
|
|
121
|
+
}
|
|
122
|
+
await this._runAutoCompaction("threshold", willRetry);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
// A response truncated at the output-token cap ("length") with the context
|
|
126
|
+
// still below the compaction budget is genuine work cut off mid-flight, not a
|
|
127
|
+
// context overflow. Compaction would not free any room, so continue the
|
|
128
|
+
// generation directly instead of dead-ending on the truncation and leaving
|
|
129
|
+
// the task half-finished.
|
|
130
|
+
if (isLiveTurnCompletion && isRetryWorthyLengthStop(assistantMessage)) {
|
|
131
|
+
this._resumeAfterLengthTruncation();
|
|
92
132
|
}
|
|
93
133
|
}
|
|
94
134
|
export function _isCopilotServerCapBelowSelectedContextWindow(assistantMessage) {
|
|
@@ -101,9 +141,67 @@ export function _isCopilotServerCapBelowSelectedContextWindow(assistantMessage)
|
|
|
101
141
|
// to a lower server tier) keeps the friendly error visible instead of silently compacting down.
|
|
102
142
|
return promptLimitError !== undefined && getEffectiveInputBudget(this.model) > promptLimitError.limitTokens;
|
|
103
143
|
}
|
|
104
|
-
export function
|
|
144
|
+
export function isRetryWorthyLengthStop(assistantMessage) {
|
|
105
145
|
return assistantMessage.stopReason === "length" && assistantMessage.usage.output > 0;
|
|
106
146
|
}
|
|
147
|
+
function isJsonRecord(value) {
|
|
148
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
149
|
+
}
|
|
150
|
+
function stringField(record, key) {
|
|
151
|
+
const value = record[key];
|
|
152
|
+
return typeof value === "string" ? value : undefined;
|
|
153
|
+
}
|
|
154
|
+
function parseProviderErrorDetails(errorMessage) {
|
|
155
|
+
const start = errorMessage.indexOf("{");
|
|
156
|
+
const end = errorMessage.lastIndexOf("}");
|
|
157
|
+
if (start === -1 || end <= start)
|
|
158
|
+
return undefined;
|
|
159
|
+
try {
|
|
160
|
+
const parsed = JSON.parse(errorMessage.slice(start, end + 1));
|
|
161
|
+
if (!isJsonRecord(parsed))
|
|
162
|
+
return undefined;
|
|
163
|
+
const nestedError = parsed.error;
|
|
164
|
+
if (nestedError !== undefined && isJsonRecord(nestedError)) {
|
|
165
|
+
return {
|
|
166
|
+
message: stringField(nestedError, "message"),
|
|
167
|
+
code: stringField(nestedError, "code") ?? stringField(parsed, "code"),
|
|
168
|
+
param: stringField(nestedError, "param") ?? stringField(parsed, "param"),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
message: stringField(parsed, "message"),
|
|
173
|
+
code: stringField(parsed, "code"),
|
|
174
|
+
param: stringField(parsed, "param"),
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
return undefined;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function isOutputBudgetUnderflowText(text) {
|
|
182
|
+
const message = text.toLowerCase();
|
|
183
|
+
return OUTPUT_BUDGET_PARAMETER_PATTERN.test(message) && OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message);
|
|
184
|
+
}
|
|
185
|
+
function isStructuredOutputBudgetUnderflow(details) {
|
|
186
|
+
const message = details.message?.toLowerCase() ?? "";
|
|
187
|
+
const param = details.param?.toLowerCase();
|
|
188
|
+
if (!OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message))
|
|
189
|
+
return false;
|
|
190
|
+
return param !== undefined ? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param) : OUTPUT_BUDGET_PARAMETER_PATTERN.test(message);
|
|
191
|
+
}
|
|
192
|
+
export function isRetryWorthyOutputBudgetError(assistantMessage) {
|
|
193
|
+
if (assistantMessage.stopReason !== "error" || !assistantMessage.errorMessage)
|
|
194
|
+
return false;
|
|
195
|
+
if (assistantMessage.api !== "openai-responses")
|
|
196
|
+
return false;
|
|
197
|
+
const structuredDetails = parseProviderErrorDetails(assistantMessage.errorMessage);
|
|
198
|
+
if (structuredDetails && isStructuredOutputBudgetUnderflow(structuredDetails))
|
|
199
|
+
return true;
|
|
200
|
+
return isOutputBudgetUnderflowText(assistantMessage.errorMessage);
|
|
201
|
+
}
|
|
202
|
+
export function shouldRetryAfterThresholdCompaction(assistantMessage) {
|
|
203
|
+
return isRetryWorthyLengthStop(assistantMessage) || isRetryWorthyOutputBudgetError(assistantMessage);
|
|
204
|
+
}
|
|
107
205
|
/**
|
|
108
206
|
* Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.
|
|
109
207
|
*/
|
|
@@ -120,49 +218,45 @@ export function _dropTrailingAutoCompactionRetryAssistantIfPresent() {
|
|
|
120
218
|
/**
|
|
121
219
|
* Internal: schedule a live post-event continuation probe after compaction_end listeners can flush queues.
|
|
122
220
|
*/
|
|
123
|
-
export function _schedulePostAutoCompactionContinuationProbe(
|
|
124
|
-
if (
|
|
125
|
-
const token = this.
|
|
126
|
-
this.
|
|
221
|
+
export function _schedulePostAutoCompactionContinuationProbe(_reason, willRetry) {
|
|
222
|
+
if (willRetry) {
|
|
223
|
+
const token = this._postCompactionContinuationToken + 1;
|
|
224
|
+
this._postCompactionContinuationToken = token;
|
|
127
225
|
let pending;
|
|
128
226
|
pending = new Promise((resolve) => {
|
|
129
227
|
setTimeout(() => {
|
|
130
228
|
void (async () => {
|
|
131
229
|
try {
|
|
132
|
-
if (this.
|
|
230
|
+
if (this._postCompactionContinuationToken !== token)
|
|
133
231
|
return;
|
|
134
232
|
if (this.isCompacting || this.isStreaming)
|
|
135
233
|
return;
|
|
136
234
|
await this._resumeAfterAutoCompaction();
|
|
137
235
|
}
|
|
138
236
|
finally {
|
|
139
|
-
if (this.
|
|
140
|
-
this.
|
|
237
|
+
if (this._pendingPostCompactionContinuation === pending) {
|
|
238
|
+
this._pendingPostCompactionContinuation = undefined;
|
|
141
239
|
}
|
|
142
240
|
resolve();
|
|
143
241
|
}
|
|
144
242
|
})();
|
|
145
243
|
}, 100);
|
|
146
244
|
});
|
|
147
|
-
this.
|
|
245
|
+
this._pendingPostCompactionContinuation = pending;
|
|
148
246
|
return;
|
|
149
247
|
}
|
|
150
248
|
setTimeout(() => {
|
|
151
249
|
if (this.isCompacting || this.isStreaming) {
|
|
152
250
|
return;
|
|
153
251
|
}
|
|
154
|
-
if (willRetry) {
|
|
155
|
-
void this._resumeAfterAutoCompaction();
|
|
156
|
-
return;
|
|
157
|
-
}
|
|
158
252
|
if (!this.agent.hasQueuedMessages()) {
|
|
159
253
|
return;
|
|
160
254
|
}
|
|
161
255
|
void this._resumeAfterAutoCompaction();
|
|
162
256
|
}, 100);
|
|
163
257
|
}
|
|
164
|
-
export async function
|
|
165
|
-
const pending = this.
|
|
258
|
+
export async function _awaitPendingPostCompactionContinuation() {
|
|
259
|
+
const pending = this._pendingPostCompactionContinuation;
|
|
166
260
|
if (pending === undefined)
|
|
167
261
|
return;
|
|
168
262
|
await pending;
|
|
@@ -183,6 +277,23 @@ export async function _resumeAfterAutoCompaction() {
|
|
|
183
277
|
});
|
|
184
278
|
}
|
|
185
279
|
}
|
|
280
|
+
/**
|
|
281
|
+
* Internal: resume a response that was truncated at the output-token cap
|
|
282
|
+
* ("length") when the context does not warrant compaction. The generation is
|
|
283
|
+
* continued directly so the model finishes the work it was cut off from, rather
|
|
284
|
+
* than dead-ending on the truncation. Bounded by MAX_LENGTH_CONTINUATION_ATTEMPTS
|
|
285
|
+
* so a turn that keeps exceeding the per-turn output cap can still terminate.
|
|
286
|
+
*/
|
|
287
|
+
export function _resumeAfterLengthTruncation() {
|
|
288
|
+
if (this._lengthContinuationAttempts >= MAX_LENGTH_CONTINUATION_ATTEMPTS)
|
|
289
|
+
return;
|
|
290
|
+
this._lengthContinuationAttempts += 1;
|
|
291
|
+
// agent.continue() rejects an assistant tail; drop the incomplete
|
|
292
|
+
// length-stopped message so the preceding user/tool-result anchors the
|
|
293
|
+
// continuation. It remains persisted in session history.
|
|
294
|
+
this._dropTrailingAutoCompactionRetryAssistantIfPresent();
|
|
295
|
+
this._schedulePostAutoCompactionContinuationProbe("threshold", true);
|
|
296
|
+
}
|
|
186
297
|
function overflowUnresolved(reason, aborted = false) {
|
|
187
298
|
return reason === "overflow" && !aborted ? true : undefined;
|
|
188
299
|
}
|
|
@@ -262,12 +373,13 @@ export async function _runAutoCompaction(reason, willRetry) {
|
|
|
262
373
|
* Toggle auto-compaction setting.
|
|
263
374
|
*/
|
|
264
375
|
export const agentSessionAutoCompactionMethods = {
|
|
265
|
-
|
|
376
|
+
_awaitPendingPostCompactionContinuation,
|
|
266
377
|
_checkCompaction,
|
|
267
378
|
_isCopilotServerCapBelowSelectedContextWindow,
|
|
268
379
|
_dropTrailingAutoCompactionRetryAssistantIfPresent,
|
|
269
380
|
_schedulePostAutoCompactionContinuationProbe,
|
|
270
381
|
_resumeAfterAutoCompaction,
|
|
382
|
+
_resumeAfterLengthTruncation,
|
|
271
383
|
_runAutoCompaction,
|
|
272
384
|
};
|
|
273
385
|
//# sourceMappingURL=agent-session-auto-compaction.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-auto-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACrG,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAGxE,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAqB,gBAAkC,EAAE,gBAAgB,GAAG,IAAI;IACrH,MAAM,QAAQ,GAAG,IAAI,CAAC,eAAe,CAAC,qBAAqB,EAAE,CAAC;IAC9D,IAAI,CAAC,QAAQ,CAAC,OAAO;QAAE,OAAO;IAE9B,kFAAkF;IAClF,IAAI,gBAAgB,IAAI,gBAAgB,CAAC,UAAU,KAAK,SAAS;QAAE,OAAO;IAE1E,MAAM,aAAa,GAAG,IAAI,CAAC,KAAK,EAAE,aAAa,IAAI,CAAC,CAAC;IAErD,kEAAkE;IAClE,qFAAqF;IACrF,iFAAiF;IACjF,kDAAkD;IAClD,MAAM,SAAS,GACd,IAAI,C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7C,kDAAkD;IAClD,4CAA4C;IAC5C,0BAA0B;IAC1B,kBAAkB;CAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { isContextOverflow } from \"@earendil-works/pi-ai/compat\";\nimport { getEffectiveInputBudget } from \"./context-window.ts\";\nimport { parseCopilotPromptLimitError } from \"./copilot-errors.ts\";\nimport { calculateContextTokens, estimateContextTokens, shouldCompact } from \"./compaction/index.ts\";\nimport { getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\nexport async function _checkCompaction(this: AgentSession, assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<void> {\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tif (!settings.enabled) return;\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\n\t// Skip overflow check if the message came from a different model.\n\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t// shouldn't trigger compaction for the new model.\n\tconst sameModel =\n\t\tthis.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;\n\n\t// Skip compaction checks if this assistant message is older than the latest\n\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t// from retriggering compaction on the first prompt after compaction.\n\tconst compactionBoundaryEntry = getLatestCompactionBoundaryEntry(this.sessionManager.getBranch());\n\tconst assistantIsFromBeforeCompactionBoundary =\n\t\tcompactionBoundaryEntry !== null &&\n\t\tassistantMessage.timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime();\n\tif (assistantIsFromBeforeCompactionBoundary) {\n\t\treturn;\n\t}\n\n\t// Case 1: Overflow - LLM returned context overflow error\n\t// When Copilot rejects a 1m client-budget prompt at a lower server cap (for example\n\t// because long-context/usage-based billing entitlement is missing), leave the friendly\n\t// error visible instead of auto-compacting down to a smaller server tier silently.\n\tif (sameModel && this._isCopilotServerCapBelowSelectedContextWindow(assistantMessage)) {\n\t\treturn;\n\t}\n\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\n\t\tconst willRetry = assistantMessage.stopReason !== \"stop\";\n\t\tif (!willRetry) {\n\t\t\tawait this._runAutoCompaction(\"overflow\", false);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._overflowRecoveryAttempted) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"overflow\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: true,\n\t\t\t\terrorMessage:\n\t\t\t\t\t\"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tthis._overflowRecoveryAttempted = true;\n\t\t// Remove the error message from agent state (it IS saved to session for history,\n\t\t// but we don't want it in context for the retry)\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tawait this._runAutoCompaction(\"overflow\", willRetry);\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For error messages (no usage data), estimate from last successful response.\n\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\tlet contextTokens: number;\n\tif (assistantMessage.stopReason === \"error\") {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t// trigger compaction right after one just finished.\n\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\tif (\n\t\t\tcompactionBoundaryEntry &&\n\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t} else {\n\t\tcontextTokens = calculateContextTokens(assistantMessage.usage);\n\t}\n\t// Compact against the effective input budget (the hard prompt cap for providers like Copilot\n\t// that advertise a larger total window) so we compact before overrunning the server-side limit\n\t// rather than relying on reactive overflow recovery near the cap.\n\tconst compactionBudget = this.model ? getEffectiveInputBudget(this.model) : contextWindow;\n\tif (shouldCompact(contextTokens, compactionBudget, settings)) {\n\t\tawait this._runAutoCompaction(\"threshold\", shouldRetryAfterThresholdCompaction(assistantMessage));\n\t}\n}\n\n\nexport function _isCopilotServerCapBelowSelectedContextWindow(this: AgentSession, assistantMessage: AssistantMessage): boolean {\n\tif (!this.model || this.model.provider !== \"github-copilot\" || !assistantMessage.errorMessage) return false;\n\tconst promptLimitError = parseCopilotPromptLimitError(assistantMessage.errorMessage);\n\t// Compare against the effective input budget (the model's real prompt cap), not the displayed\n\t// total window. A rejection at the prompt cap is a normal overflow we should compact-and-retry;\n\t// only a rejection *below* the cap (e.g. a missing long-context entitlement dropping the account\n\t// to a lower server tier) keeps the friendly error visible instead of silently compacting down.\n\treturn promptLimitError !== undefined && getEffectiveInputBudget(this.model) > promptLimitError.limitTokens;\n}\n\nexport function shouldRetryAfterThresholdCompaction(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): void {\n\tconst messages = this.agent.state.messages;\n\tconst lastMsg = messages[messages.length - 1];\n\tif (lastMsg?.role !== \"assistant\") return;\n\tconst stopReason = (lastMsg as AssistantMessage).stopReason;\n\tif (stopReason === \"error\" || stopReason === \"length\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n}\n\n/**\n * Internal: schedule a live post-event continuation probe after compaction_end listeners can flush queues.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(this: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tif (reason === \"overflow\" && willRetry) {\n\t\tconst token = this._overflowPostCompactionContinuationToken + 1;\n\t\tthis._overflowPostCompactionContinuationToken = token;\n\t\tlet pending: Promise<void>;\n\t\tpending = new Promise<void>((resolve) => {\n\t\t\tsetTimeout(() => {\n\t\t\t\tvoid (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (this._overflowPostCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (this._pendingOverflowPostCompactionContinuation === pending) {\n\t\t\t\t\t\t\tthis._pendingOverflowPostCompactionContinuation = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t}, 100);\n\t\t});\n\t\tthis._pendingOverflowPostCompactionContinuation = pending;\n\t\treturn;\n\t}\n\n\tsetTimeout(() => {\n\t\tif (this.isCompacting || this.isStreaming) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tvoid this._resumeAfterAutoCompaction();\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\treturn;\n\t\t}\n\n\t\tvoid this._resumeAfterAutoCompaction();\n\t}, 100);\n}\n\nexport async function _awaitPendingOverflowPostCompactionContinuation(this: AgentSession): Promise<void> {\n\tconst pending = this._pendingOverflowPostCompactionContinuation;\n\tif (pending === undefined) return;\n\tawait pending;\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport async function _resumeAfterAutoCompaction(this: AgentSession): Promise<void> {\n\ttry {\n\t\tawait this._runAgentContinue();\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis._emit({\n\t\t\ttype: \"agent_continue_error\",\n\t\t\tsource: \"post_compaction\",\n\t\t\terrorMessage: `Post-compaction continuation failed: ${message}`,\n\t\t});\n\t}\n}\n\n\nfunction overflowUnresolved(reason: \"overflow\" | \"threshold\", aborted = false): boolean | undefined {\n\treturn reason === \"overflow\" && !aborted ? true : undefined;\n}\n\nexport async function _runAutoCompaction(this: AgentSession, reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void> {\n\tthis._emit({ type: \"compaction_start\", reason });\n\tthis._autoCompactionAbortController = new AbortController();\n\n\ttry {\n\t\tif (!this.model) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Auth is resolved lazily: only called when the planner fallback is needed.\n\t\t// This allows extension-provided deletion requests to run before auth is checked,\n\t\t// enabling local extension compaction even when API credentials are unavailable.\n\t\t// Auto-mode resolver returns undefined (rather than throwing) when auth is missing;\n\t\t// overflow recovery then falls back to deterministic no-auth eviction, while\n\t\t// threshold compaction keeps the previous no-op behavior.\n\t\tconst model = this.model;\n\t\tconst result = await this._applyContextVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async () => {\n\t\t\t\tconst authResult = await this._modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\tif (!authResult.ok || !authResult.apiKey) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\treturn { apiKey: authResult.apiKey, headers: authResult.headers };\n\t\t\t},\n\t\t\tabortController: this._autoCompactionAbortController,\n\t\t\tbackupLabel: reason === \"overflow\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t});\n\t\tif (!result) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted = errorMessage === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tunresolvedOverflow: overflowUnresolved(reason, aborted),\n\t\t\terrorMessage: aborted\n\t\t\t\t? undefined\n\t\t\t\t: reason === \"overflow\"\n\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t});\n\t} finally {\n\t\tthis._autoCompactionAbortController = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingOverflowPostCompactionContinuation,\n\t_checkCompaction,\n\t_isCopilotServerCapBelowSelectedContextWindow,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_runAutoCompaction,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-auto-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACj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C,4CAA4C,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IACtE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,YAAY,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,mBAAmB,CAAC;QAClF,MAAM,OAAO,GAAG,YAAY,KAAK,sBAAsB,IAAI,CAAC,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,CAAC,CAAC;QACnH,IAAI,CAAC,KAAK,CAAC;YACV,IAAI,EAAE,gBAAgB;YACtB,MAAM;YACN,MAAM,EAAE,SAAS;YACjB,OAAO;YACP,SAAS,EAAE,KAAK;YAChB,kBAAkB,EAAE,kBAAkB,CAAC,MAAM,EAAE,OAAO,CAAC;YACvD,YAAY,EAAE,OAAO;gBACpB,CAAC,CAAC,SAAS;gBACX,CAAC,CAAC,MAAM,KAAK,UAAU;oBACtB,CAAC,CAAC,qCAAqC,YAAY,EAAE;oBACrD,CAAC,CAAC,2BAA2B,YAAY,EAAE;SAC7C,CAAC,CAAC;IACJ,CAAC;YAAS,CAAC;QACV,IAAI,CAAC,8BAA8B,GAAG,SAAS,CAAC;IACjD,CAAC;AACF,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAChD,uCAAuC;IACvC,gBAAgB;IAChB,6CAA6C;IAC7C,kDAAkD;IAClD,4CAA4C;IAC5C,0BAA0B;IAC1B,4BAA4B;IAC5B,kBAAkB;CAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { isContextOverflow } from \"@earendil-works/pi-ai/compat\";\nimport { getEffectiveInputBudget } from \"./context-window.ts\";\nimport { parseCopilotPromptLimitError } from \"./copilot-errors.ts\";\nimport { calculateContextTokens, estimateContextTokens, shouldCompact } from \"./compaction/index.ts\";\nimport { getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\nimport { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from \"./openai-responses-payload-sanitizer.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\n/**\n * Upper bound on consecutive automatic continuations of a response that was\n * truncated at the output-token cap (\"length\") while the context is still\n * below the compaction budget. Each continuation regenerates the cut-off turn,\n * so a model that insists on emitting more than its per-turn output cap can\n * still terminate instead of looping forever.\n */\nexport const MAX_LENGTH_CONTINUATION_ATTEMPTS = 3;\n\nexport const MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS = 1;\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\ntype ProviderErrorDetails = {\n\tmessage?: string;\n\tcode?: string;\n\tparam?: string;\n};\n\nconst OUTPUT_BUDGET_PARAMETER_PATTERN = /\\bmax_output_tokens\\b/;\nconst OUTPUT_BUDGET_UNDERFLOW_PATTERN = new RegExp(\n\t`(?:integer\\\\s+below\\\\s+minimum\\\\s+value|expected\\\\s+(?:a\\\\s+)?value\\\\s*>=\\\\s*${MIN_RESPONSES_MAX_OUTPUT_TOKENS}|got\\\\s+1\\\\s+instead)`,\n);\n\nexport async function _checkCompaction(this: AgentSession, assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<void> {\n\t// The agent_end path passes skipAbortedCheck=true; the pre-prompt path passes\n\t// false. Only the live turn-completion path may auto-continue a truncated\n\t// response — before a fresh user prompt we must not resume the old turn.\n\tconst isLiveTurnCompletion = skipAbortedCheck;\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tif (!settings.enabled) return;\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\n\t// Skip overflow check if the message came from a different model.\n\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t// shouldn't trigger compaction for the new model.\n\tconst sameModel =\n\t\tthis.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;\n\n\t// Skip compaction checks if this assistant message is older than the latest\n\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t// from retriggering compaction on the first prompt after compaction.\n\tconst compactionBoundaryEntry = getLatestCompactionBoundaryEntry(this.sessionManager.getBranch());\n\tconst assistantIsFromBeforeCompactionBoundary =\n\t\tcompactionBoundaryEntry !== null &&\n\t\tassistantMessage.timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime();\n\tif (assistantIsFromBeforeCompactionBoundary) {\n\t\treturn;\n\t}\n\n\t// Case 1: Overflow - LLM returned context overflow error\n\t// When Copilot rejects a 1m client-budget prompt at a lower server cap (for example\n\t// because long-context/usage-based billing entitlement is missing), leave the friendly\n\t// error visible instead of auto-compacting down to a smaller server tier silently.\n\tif (sameModel && this._isCopilotServerCapBelowSelectedContextWindow(assistantMessage)) {\n\t\treturn;\n\t}\n\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\n\t\tconst willRetry = assistantMessage.stopReason !== \"stop\";\n\t\tif (!willRetry) {\n\t\t\tawait this._runAutoCompaction(\"overflow\", false);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._overflowRecoveryAttempted) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"overflow\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: true,\n\t\t\t\terrorMessage:\n\t\t\t\t\t\"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tthis._overflowRecoveryAttempted = true;\n\t\t// Remove the error message from agent state (it IS saved to session for history,\n\t\t// but we don't want it in context for the retry)\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tawait this._runAutoCompaction(\"overflow\", willRetry);\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For error messages (no usage data), estimate from last successful response.\n\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\tlet contextTokens: number;\n\tif (assistantMessage.stopReason === \"error\") {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t// trigger compaction right after one just finished.\n\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\tif (\n\t\t\tcompactionBoundaryEntry &&\n\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t} else {\n\t\tcontextTokens = calculateContextTokens(assistantMessage.usage);\n\t}\n\t// Compact against the effective input budget (the hard prompt cap for providers like Copilot\n\t// that advertise a larger total window) so we compact before overrunning the server-side limit\n\t// rather than relying on reactive overflow recovery near the cap.\n\tconst compactionBudget = this.model ? getEffectiveInputBudget(this.model) : contextWindow;\n\tif (shouldCompact(contextTokens, compactionBudget, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\"Output-budget recovery stopped after a compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._outputBudgetErrorContinuationAttempts += 1;\n\t\t}\n\t\tawait this._runAutoCompaction(\"threshold\", willRetry);\n\t\treturn;\n\t}\n\n\t// A response truncated at the output-token cap (\"length\") with the context\n\t// still below the compaction budget is genuine work cut off mid-flight, not a\n\t// context overflow. Compaction would not free any room, so continue the\n\t// generation directly instead of dead-ending on the truncation and leaving\n\t// the task half-finished.\n\tif (isLiveTurnCompletion && isRetryWorthyLengthStop(assistantMessage)) {\n\t\tthis._resumeAfterLengthTruncation();\n\t}\n}\n\n\nexport function _isCopilotServerCapBelowSelectedContextWindow(this: AgentSession, assistantMessage: AssistantMessage): boolean {\n\tif (!this.model || this.model.provider !== \"github-copilot\" || !assistantMessage.errorMessage) return false;\n\tconst promptLimitError = parseCopilotPromptLimitError(assistantMessage.errorMessage);\n\t// Compare against the effective input budget (the model's real prompt cap), not the displayed\n\t// total window. A rejection at the prompt cap is a normal overflow we should compact-and-retry;\n\t// only a rejection *below* the cap (e.g. a missing long-context entitlement dropping the account\n\t// to a lower server tier) keeps the friendly error visible instead of silently compacting down.\n\treturn promptLimitError !== undefined && getEffectiveInputBudget(this.model) > promptLimitError.limitTokens;\n}\n\nexport function isRetryWorthyLengthStop(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\nfunction isJsonRecord(value: JsonValue): value is { [key: string]: JsonValue } {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: { [key: string]: JsonValue }, key: string): string | undefined {\n\tconst value = record[key];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction parseProviderErrorDetails(errorMessage: string): ProviderErrorDetails | undefined {\n\tconst start = errorMessage.indexOf(\"{\");\n\tconst end = errorMessage.lastIndexOf(\"}\");\n\tif (start === -1 || end <= start) return undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(errorMessage.slice(start, end + 1)) as JsonValue;\n\t\tif (!isJsonRecord(parsed)) return undefined;\n\n\t\tconst nestedError = parsed.error;\n\t\tif (nestedError !== undefined && isJsonRecord(nestedError)) {\n\t\t\treturn {\n\t\t\t\tmessage: stringField(nestedError, \"message\"),\n\t\t\t\tcode: stringField(nestedError, \"code\") ?? stringField(parsed, \"code\"),\n\t\t\t\tparam: stringField(nestedError, \"param\") ?? stringField(parsed, \"param\"),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tmessage: stringField(parsed, \"message\"),\n\t\t\tcode: stringField(parsed, \"code\"),\n\t\t\tparam: stringField(parsed, \"param\"),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isOutputBudgetUnderflowText(text: string): boolean {\n\tconst message = text.toLowerCase();\n\treturn OUTPUT_BUDGET_PARAMETER_PATTERN.test(message) && OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message);\n}\n\nfunction isStructuredOutputBudgetUnderflow(details: ProviderErrorDetails): boolean {\n\tconst message = details.message?.toLowerCase() ?? \"\";\n\tconst param = details.param?.toLowerCase();\n\tif (!OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message)) return false;\n\treturn param !== undefined ? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param) : OUTPUT_BUDGET_PARAMETER_PATTERN.test(message);\n}\n\nexport function isRetryWorthyOutputBudgetError(assistantMessage: AssistantMessage): boolean {\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return false;\n\tif (assistantMessage.api !== \"openai-responses\") return false;\n\n\tconst structuredDetails = parseProviderErrorDetails(assistantMessage.errorMessage);\n\tif (structuredDetails && isStructuredOutputBudgetUnderflow(structuredDetails)) return true;\n\n\treturn isOutputBudgetUnderflowText(assistantMessage.errorMessage);\n}\n\nexport function shouldRetryAfterThresholdCompaction(assistantMessage: AssistantMessage): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) || isRetryWorthyOutputBudgetError(assistantMessage);\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): void {\n\tconst messages = this.agent.state.messages;\n\tconst lastMsg = messages[messages.length - 1];\n\tif (lastMsg?.role !== \"assistant\") return;\n\tconst stopReason = (lastMsg as AssistantMessage).stopReason;\n\tif (stopReason === \"error\" || stopReason === \"length\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n}\n\n/**\n * Internal: schedule a live post-event continuation probe after compaction_end listeners can flush queues.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(this: AgentSession,\n\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tif (willRetry) {\n\t\tconst token = this._postCompactionContinuationToken + 1;\n\t\tthis._postCompactionContinuationToken = token;\n\t\tlet pending: Promise<void>;\n\t\tpending = new Promise<void>((resolve) => {\n\t\t\tsetTimeout(() => {\n\t\t\t\tvoid (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (this._pendingPostCompactionContinuation === pending) {\n\t\t\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t}, 100);\n\t\t});\n\t\tthis._pendingPostCompactionContinuation = pending;\n\t\treturn;\n\t}\n\n\tsetTimeout(() => {\n\t\tif (this.isCompacting || this.isStreaming) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\treturn;\n\t\t}\n\n\t\tvoid this._resumeAfterAutoCompaction();\n\t}, 100);\n}\n\nexport async function _awaitPendingPostCompactionContinuation(this: AgentSession): Promise<void> {\n\tconst pending = this._pendingPostCompactionContinuation;\n\tif (pending === undefined) return;\n\tawait pending;\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport async function _resumeAfterAutoCompaction(this: AgentSession): Promise<void> {\n\ttry {\n\t\tawait this._runAgentContinue();\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis._emit({\n\t\t\ttype: \"agent_continue_error\",\n\t\t\tsource: \"post_compaction\",\n\t\t\terrorMessage: `Post-compaction continuation failed: ${message}`,\n\t\t});\n\t}\n}\n\n/**\n * Internal: resume a response that was truncated at the output-token cap\n * (\"length\") when the context does not warrant compaction. The generation is\n * continued directly so the model finishes the work it was cut off from, rather\n * than dead-ending on the truncation. Bounded by MAX_LENGTH_CONTINUATION_ATTEMPTS\n * so a turn that keeps exceeding the per-turn output cap can still terminate.\n */\n\nexport function _resumeAfterLengthTruncation(this: AgentSession): void {\n\tif (this._lengthContinuationAttempts >= MAX_LENGTH_CONTINUATION_ATTEMPTS) return;\n\tthis._lengthContinuationAttempts += 1;\n\t// agent.continue() rejects an assistant tail; drop the incomplete\n\t// length-stopped message so the preceding user/tool-result anchors the\n\t// continuation. It remains persisted in session history.\n\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\tthis._schedulePostAutoCompactionContinuationProbe(\"threshold\", true);\n}\n\n\nfunction overflowUnresolved(reason: \"overflow\" | \"threshold\", aborted = false): boolean | undefined {\n\treturn reason === \"overflow\" && !aborted ? true : undefined;\n}\n\nexport async function _runAutoCompaction(this: AgentSession, reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void> {\n\tthis._emit({ type: \"compaction_start\", reason });\n\tthis._autoCompactionAbortController = new AbortController();\n\n\ttry {\n\t\tif (!this.model) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Auth is resolved lazily: only called when the planner fallback is needed.\n\t\t// This allows extension-provided deletion requests to run before auth is checked,\n\t\t// enabling local extension compaction even when API credentials are unavailable.\n\t\t// Auto-mode resolver returns undefined (rather than throwing) when auth is missing;\n\t\t// overflow recovery then falls back to deterministic no-auth eviction, while\n\t\t// threshold compaction keeps the previous no-op behavior.\n\t\tconst model = this.model;\n\t\tconst result = await this._applyContextVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async () => {\n\t\t\t\tconst authResult = await this._modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\tif (!authResult.ok || !authResult.apiKey) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\treturn { apiKey: authResult.apiKey, headers: authResult.headers };\n\t\t\t},\n\t\t\tabortController: this._autoCompactionAbortController,\n\t\t\tbackupLabel: reason === \"overflow\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t});\n\t\tif (!result) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted = errorMessage === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tunresolvedOverflow: overflowUnresolved(reason, aborted),\n\t\t\terrorMessage: aborted\n\t\t\t\t? undefined\n\t\t\t\t: reason === \"overflow\"\n\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t});\n\t} finally {\n\t\tthis._autoCompactionAbortController = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingPostCompactionContinuation,\n\t_checkCompaction,\n\t_isCopilotServerCapBelowSelectedContextWindow,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_resumeAfterLengthTruncation,\n\t_runAutoCompaction,\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-events.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-events.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAe,MAAM,8BAA8B,CAAC;AAG3F,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC9F,OAAO,EAA0F,KAAK,iBAAiB,EAAE,KAAK,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AAG1L,wBAAgB,KAAK,CAAC,IAAI,EAAE,YAAY,EAAE,KAAK,EAAE,iBAAiB,GAAG,IAAI,CAIxE;AAGD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAMzD;AAED,4EAA4E;AAE5E,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,YAAY,EAAE,KAAK,EAAE,UAAU,GAAG,IAAI,CAe7E;AAGD,wBAAgB,8BA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AE,YAAY,GAAG,IAAI,CAG1D;AAED;;;GAGG;AAEH,wBAAgB,OAAO,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAQhD;AAMD,uBAAuB;AAEvB,eAAO,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;CAkBrC,CAAC","sourcesContent":["import { disposeSessionAsyncJobManager } from \"./async/session-manager.js\";\nimport type { AgentEvent, AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { AssistantMessage, Message, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport { cleanupSessionResources } from \"@earendil-works/pi-ai/compat\";\nimport { formatCopilotProviderError } from \"./copilot-errors.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { customMessageExcludesContext, isSingleGenericAbortTextContent, replacementAbortContent, type AgentSessionEvent, type AgentSessionEventListener } from \"./agent-session-types.ts\";\nimport type { MessageEndEvent, MessageStartEvent, MessageUpdateEvent, ToolExecutionEndEvent, ToolExecutionStartEvent, ToolExecutionUpdateEvent, TurnEndEvent, TurnStartEvent } from \"./extensions/index.ts\";\n\nexport function _emit(this: AgentSession, event: AgentSessionEvent): void {\n\tfor (const l of this._eventListeners) {\n\t\tl(event);\n\t}\n}\n\n\nexport function _emitQueueUpdate(this: AgentSession): void {\n\tthis._emit({\n\t\ttype: \"queue_update\",\n\t\tsteering: [...this._steeringMessages],\n\t\tfollowUp: [...this._followUpMessages],\n\t});\n}\n\n/** Internal handler for agent events - shared by subscribe and reconnect */\n\nexport function _handleAgentEvent(this: AgentSession, event: AgentEvent): void {\n\t// Create retry promise synchronously before queueing async processing.\n\t// Agent.emit() calls this handler synchronously, and prompt() calls waitForRetry()\n\t// as soon as agent.prompt() resolves. If _retryPromise is created only inside\n\t// _processAgentEvent, slow earlier queued events can delay agent_end processing\n\t// and waitForRetry() can miss the in-flight retry.\n\tthis._createRetryPromiseForAgentEnd(event);\n\n\tthis._agentEventQueue = this._agentEventQueue.then(\n\t\t() => this._processAgentEvent(event),\n\t\t() => this._processAgentEvent(event),\n\t);\n\n\t// Keep queue alive if an event handler fails\n\tthis._agentEventQueue.catch(() => {});\n}\n\n\nexport function _createRetryPromiseForAgentEnd(this: AgentSession, event: AgentEvent): void {\n\tif (event.type !== \"agent_end\" || this._retryPromise) {\n\t\treturn;\n\t}\n\n\tconst settings = this.settingsManager.getRetrySettings();\n\tif (!settings.enabled && this._fallbackModels.length === 0) {\n\t\treturn;\n\t}\n\n\tconst lastAssistant = this._findLastAssistantInMessages(event.messages);\n\tif (!lastAssistant) {\n\t\treturn;\n\t}\n\n\tconst shouldRetry = this._isRetryableError(lastAssistant) || this._isEmptyCompletion(lastAssistant) || this._isSafetyRefusal(lastAssistant);\n\tif (!shouldRetry) {\n\t\treturn;\n\t}\n\n\tthis._retryPromise = new Promise((resolve) => {\n\t\tthis._retryResolve = resolve;\n\t});\n}\n\n\nexport function _findLastAssistantInMessages(this: AgentSession, messages: AgentMessage[]): AssistantMessage | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst message = messages[i];\n\t\tif (message.role === \"assistant\") {\n\t\t\treturn message as AssistantMessage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n\nexport async function _processAgentEvent(this: AgentSession, event: AgentEvent): Promise<void> {\n\t// When a user message starts, check if it's from either queue and remove it BEFORE emitting\n\t// This ensures the UI sees the updated queue state\n\tif (event.type === \"message_start\" && event.message.role === \"user\") {\n\t\tthis._overflowRecoveryAttempted = false;\n\t\tthis._fallbackAttemptedKeys.clear();\n\t\tconst messageText = this._getUserMessageText(event.message);\n\t\tif (messageText) {\n\t\t\t// Check steering queue first\n\t\t\tconst steeringIndex = this._steeringMessages.indexOf(messageText);\n\t\t\tif (steeringIndex !== -1) {\n\t\t\t\tthis._steeringMessages.splice(steeringIndex, 1);\n\t\t\t\tthis._emitQueueUpdate();\n\t\t\t} else {\n\t\t\t\t// Check follow-up queue\n\t\t\t\tconst followUpIndex = this._followUpMessages.indexOf(messageText);\n\t\t\t\tif (followUpIndex !== -1) {\n\t\t\t\t\tthis._followUpMessages.splice(followUpIndex, 1);\n\t\t\t\t\tthis._emitQueueUpdate();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tthis._applyInterruptAbortMessage(event);\n\tthis._applyProviderErrorGuidance(event);\n\n\t// Emit to extensions first\n\tawait this._emitExtensionEvent(event);\n\n\t// Notify all listeners\n\tthis._emit(event);\n\n\t// Handle session persistence\n\tif (event.type === \"message_end\") {\n\t\t// Check if this is a custom message from extensions\n\t\tif (event.message.role === \"custom\") {\n\t\t\t// Persist as CustomMessageEntry\n\t\t\tthis.sessionManager.appendCustomMessageEntry(\n\t\t\t\tevent.message.customType,\n\t\t\t\tevent.message.content,\n\t\t\t\tevent.message.display,\n\t\t\t\tevent.message.details,\n\t\t\t\tcustomMessageExcludesContext(event.message),\n\t\t\t);\n\t\t} else if (\n\t\t\tevent.message.role === \"user\" ||\n\t\t\tevent.message.role === \"assistant\" ||\n\t\t\tevent.message.role === \"toolResult\"\n\t\t) {\n\t\t\tif (event.message.role === \"assistant\") {\n\t\t\t\tthis._normalizePersistedGeminiToolArgs(event.message);\n\t\t\t}\n\t\t\t// Regular LLM message - persist as SessionMessageEntry\n\t\t\tthis.sessionManager.appendMessage(event.message);\n\t\t}\n\t\t// Other message types (bashExecution, branchSummary) are persisted elsewhere\n\n\t\t// Track assistant message for auto-compaction (checked on agent_end)\n\t\tif (event.message.role === \"assistant\") {\n\t\t\tthis._lastAssistantMessage = event.message;\n\n\t\t\tconst assistantMsg = event.message as AssistantMessage;\n\t\t\t// Treat degenerate empty completions (no content, zero output tokens) and\n\t\t\t// intercepted canned safety refusals as failures alongside stopReason ===\n\t\t\t// \"error\". Otherwise such a turn that stops with reason \"stop\"/\"length\"\n\t\t\t// would reset the retry counter on every attempt, causing unbounded\n\t\t\t// retries instead of honoring maxRetries.\n\t\t\tconst assistantFailed = assistantMsg.stopReason === \"error\" || this._isEmptyCompletion(assistantMsg) || this._isSafetyRefusal(assistantMsg);\n\t\t\tif (!assistantFailed) {\n\t\t\t\tthis._fallbackAttemptedKeys.clear();\n\t\t\t\tthis._overflowRecoveryAttempted = false;\n\t\t\t}\n\n\t\t\t// Reset retry counter immediately on successful assistant response\n\t\t\t// This prevents accumulation across multiple LLM calls within a turn\n\t\t\tif (!assistantFailed && this._retryAttempt > 0) {\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tattempt: this._retryAttempt,\n\t\t\t\t});\n\t\t\t\tthis._retryAttempt = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check auto-retry and auto-compaction after agent completes\n\tif (event.type === \"agent_end\" && this._lastAssistantMessage) {\n\t\tconst msg = this._lastAssistantMessage;\n\t\tthis._lastAssistantMessage = undefined;\n\n\t\t// Check for retryable errors first (overloaded, rate limit, server errors,\n\t\t// transient provider finish_reason errors, degenerate empty completions,\n\t\t// or intercepted canned safety refusals)\n\t\tconst retryableError = this._isRetryableError(msg);\n\t\tconst emptyCompletion = !retryableError && this._isEmptyCompletion(msg);\n\t\tconst safetyRefusal = !retryableError && !emptyCompletion && this._isSafetyRefusal(msg);\n\t\tif (retryableError || emptyCompletion || safetyRefusal) {\n\t\t\tif (emptyCompletion && !msg.errorMessage) {\n\t\t\t\t// Surface a clear reason in the retry banner; empty completions carry no\n\t\t\t\t// provider error message of their own.\n\t\t\t\tmsg.errorMessage = \"Provider returned an empty completion\";\n\t\t\t} else if (safetyRefusal && !msg.errorMessage) {\n\t\t\t\tmsg.errorMessage = \"Provider returned a canned safety refusal\";\n\t\t\t}\n\t\t\tconst didRetry = await this._handleRetryableError(msg);\n\t\t\tif (didRetry) return; // Retry was initiated, don't proceed to compaction\n\t\t}\n\n\t\tthis._resolveRetry();\n\t\tawait this._checkCompaction(msg);\n\t}\n}\n\n\nexport function _applyInterruptAbortMessage(this: AgentSession, event: AgentEvent): void {\n\tconst abortMessage = this._activeInterruptAbortMessage;\n\tif (!abortMessage) return;\n\n\tif (event.type === \"tool_execution_end\" && event.isError && isSingleGenericAbortTextContent(event.result.content)) {\n\t\tevent.result.content = replacementAbortContent(abortMessage);\n\t\treturn;\n\t}\n\n\tif (event.type !== \"message_start\" && event.type !== \"message_end\") return;\n\n\tif (event.message.role === \"toolResult\" && event.message.isError && isSingleGenericAbortTextContent(event.message.content)) {\n\t\tevent.message.content = replacementAbortContent(abortMessage);\n\t\treturn;\n\t}\n\n\tif (event.message.role === \"assistant\") {\n\t\tconst assistantMessage = event.message as AssistantMessage;\n\t\tif (assistantMessage.stopReason === \"aborted\") {\n\t\t\tassistantMessage.errorMessage = abortMessage;\n\t\t}\n\t}\n}\n\n\nexport function _applyProviderErrorGuidance(this: AgentSession, event: AgentEvent): void {\n\tif (event.type !== \"message_start\" && event.type !== \"message_update\" && event.type !== \"message_end\") return;\n\tif (event.message.role !== \"assistant\") return;\n\n\tconst assistantMessage = event.message as AssistantMessage;\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return;\n\n\tassistantMessage.errorMessage = formatCopilotProviderError(\n\t\tassistantMessage.provider,\n\t\tassistantMessage.errorMessage,\n\t);\n}\n\n/** Resolve the pending retry promise */\n\nexport function _resolveRetry(this: AgentSession): void {\n\tif (this._retryResolve) {\n\t\tthis._retryResolve();\n\t\tthis._retryResolve = undefined;\n\t\tthis._retryPromise = undefined;\n\t}\n}\n\n/** Extract text content from a message */\n\nexport function _getUserMessageText(this: AgentSession, message: Message): string {\n\tif (message.role !== \"user\") return \"\";\n\tconst content = message.content;\n\tif (typeof content === \"string\") return content;\n\tconst textBlocks = content.filter((c) => c.type === \"text\");\n\treturn textBlocks.map((c) => (c as TextContent).text).join(\"\");\n}\n\n/** Find the last assistant message in agent state (including aborted ones) */\n\nexport function _findLastAssistantMessage(this: AgentSession): AssistantMessage | undefined {\n\tconst messages = this.agent.state.messages;\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst msg = messages[i];\n\t\tif (msg.role === \"assistant\") {\n\t\t\treturn msg as AssistantMessage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n\nexport function _replaceMessageInPlace(this: AgentSession, target: AgentMessage, replacement: AgentMessage): void {\n\t// Agent-core stores the finalized message object in its state before emitting message_end.\n\t// SessionManager persistence happens later in _processAgentEvent() with event.message.\n\t// Mutating this object in place keeps agent state, later turn/agent events, listeners,\n\t// and the eventual SessionManager.appendMessage(event.message) persistence in sync.\n\tif (target === replacement) {\n\t\treturn;\n\t}\n\n\tconst targetRecord = target as unknown as Record<string, unknown>;\n\tfor (const key of Object.keys(targetRecord)) {\n\t\tdelete targetRecord[key];\n\t}\n\tObject.assign(targetRecord, replacement);\n}\n\n/** Emit extension events based on agent events */\n\nexport async function _emitExtensionEvent(this: AgentSession, event: AgentEvent): Promise<void> {\n\tif (event.type === \"agent_start\") {\n\t\tthis._turnIndex = 0;\n\t\tawait this._extensionRunner.emit({ type: \"agent_start\" });\n\t} else if (event.type === \"agent_end\") {\n\t\tawait this._extensionRunner.emit({ type: \"agent_end\", messages: event.messages });\n\t} else if (event.type === \"turn_start\") {\n\t\tconst extensionEvent: TurnStartEvent = {\n\t\t\ttype: \"turn_start\",\n\t\t\tturnIndex: this._turnIndex,\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"turn_end\") {\n\t\tconst extensionEvent: TurnEndEvent = {\n\t\t\ttype: \"turn_end\",\n\t\t\tturnIndex: this._turnIndex,\n\t\t\tmessage: event.message,\n\t\t\ttoolResults: event.toolResults,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t\tthis._turnIndex++;\n\t} else if (event.type === \"message_start\") {\n\t\tconst extensionEvent: MessageStartEvent = {\n\t\t\ttype: \"message_start\",\n\t\t\tmessage: event.message,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"message_update\") {\n\t\tconst extensionEvent: MessageUpdateEvent = {\n\t\t\ttype: \"message_update\",\n\t\t\tmessage: event.message,\n\t\t\tassistantMessageEvent: event.assistantMessageEvent,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"message_end\") {\n\t\tconst extensionEvent: MessageEndEvent = {\n\t\t\ttype: \"message_end\",\n\t\t\tmessage: event.message,\n\t\t};\n\t\tconst replacement = await this._extensionRunner.emitMessageEnd(extensionEvent);\n\t\tif (replacement) {\n\t\t\tthis._replaceMessageInPlace(event.message, replacement);\n\t\t}\n\t} else if (event.type === \"tool_execution_start\") {\n\t\tconst extensionEvent: ToolExecutionStartEvent = {\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: event.toolCallId,\n\t\t\ttoolName: event.toolName,\n\t\t\targs: event.args,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"tool_execution_update\") {\n\t\tconst extensionEvent: ToolExecutionUpdateEvent = {\n\t\t\ttype: \"tool_execution_update\",\n\t\t\ttoolCallId: event.toolCallId,\n\t\t\ttoolName: event.toolName,\n\t\t\targs: event.args,\n\t\t\tpartialResult: event.partialResult,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"tool_execution_end\") {\n\t\tconst extensionEvent: ToolExecutionEndEvent = {\n\t\t\ttype: \"tool_execution_end\",\n\t\t\ttoolCallId: event.toolCallId,\n\t\t\ttoolName: event.toolName,\n\t\t\tresult: event.result,\n\t\t\tisError: event.isError,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t}\n}\n\n/**\n * Subscribe to agent events.\n * Session persistence is handled internally (saves messages on message_end).\n * Multiple listeners can be added. Returns unsubscribe function for this listener.\n */\n\nexport function subscribe(this: AgentSession, listener: AgentSessionEventListener): () => void {\n\tthis._eventListeners.push(listener);\n\n\t// Return unsubscribe function for this specific listener\n\treturn () => {\n\t\tconst index = this._eventListeners.indexOf(listener);\n\t\tif (index !== -1) {\n\t\t\tthis._eventListeners.splice(index, 1);\n\t\t}\n\t};\n}\n\n/**\n * Temporarily disconnect from agent events.\n * User listeners are preserved and will receive events again after resubscribe().\n * Used internally during operations that need to pause event processing.\n */\n\nexport function _disconnectFromAgent(this: AgentSession): void {\n\tif (this._unsubscribeAgent) {\n\t\tthis._unsubscribeAgent();\n\t\tthis._unsubscribeAgent = undefined;\n\t}\n}\n\n/**\n * Reconnect to agent events after _disconnectFromAgent().\n * Preserves all existing listeners.\n */\n\nexport function _reconnectToAgent(this: AgentSession): void {\n\tif (this._unsubscribeAgent) return; // Already connected\n\tthis._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);\n}\n\n/**\n * Remove all listeners and disconnect from agent.\n * Call this when completely done with the session.\n */\n\nexport function dispose(this: AgentSession): void {\n\tthis._extensionRunner.invalidate(\n\t\t\"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().\",\n\t);\n\tdisposeSessionAsyncJobManager(this._asyncJobManager, this._asyncJobManagerSessionId);\n\tthis._disconnectFromAgent();\n\tthis._eventListeners = [];\n\tcleanupSessionResources(this.sessionId);\n}\n\n// =========================================================================\n// Read-only State Access\n// =========================================================================\n\n/** Full agent state */\n\nexport const agentSessionEventsMethods = {\n\t_emit,\n\t_emitQueueUpdate,\n\t_handleAgentEvent,\n\t_createRetryPromiseForAgentEnd,\n\t_findLastAssistantInMessages,\n\t_processAgentEvent,\n\t_applyInterruptAbortMessage,\n\t_applyProviderErrorGuidance,\n\t_resolveRetry,\n\t_getUserMessageText,\n\t_findLastAssistantMessage,\n\t_replaceMessageInPlace,\n\t_emitExtensionEvent,\n\tsubscribe,\n\t_disconnectFromAgent,\n\t_reconnectToAgent,\n\tdispose,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-events.d.ts","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YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,MAAM,CAMhF;AAED,8EAA8E;AAE9E,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,YAAY,GAAG,gBAAgB,GAAG,SAAS,CAS1F;AAGD,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,YAAY,EAAE,WAAW,EAAE,YAAY,GAAG,IAAI,CAchH;AAED,kDAAkD;AAElD,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,YAAY,EAAE,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAuE9F;AAED;;;;GAIG;AAEH,wBAAgB,SAAS,CAAC,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,yBAAyB,GAAG,MAAM,IAAI,CAU7F;AAED;;;;GAIG;AAEH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAK7D;AAED;;;GAGG;AAEH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAG1D;AAED;;;GAGG;AAEH,wBAAgB,OAAO,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAQhD;AAMD,uBAAuB;AAEvB,eAAO,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;CAkBrC,CAAC","sourcesContent":["import { disposeSessionAsyncJobManager } from \"./async/session-manager.js\";\nimport type { AgentEvent, AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { AssistantMessage, Message, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport { cleanupSessionResources } from \"@earendil-works/pi-ai/compat\";\nimport { formatCopilotProviderError } from \"./copilot-errors.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { customMessageExcludesContext, isSingleGenericAbortTextContent, replacementAbortContent, type AgentSessionEvent, type AgentSessionEventListener } from \"./agent-session-types.ts\";\nimport type { MessageEndEvent, MessageStartEvent, MessageUpdateEvent, ToolExecutionEndEvent, ToolExecutionStartEvent, ToolExecutionUpdateEvent, TurnEndEvent, TurnStartEvent } from \"./extensions/index.ts\";\nimport { normalizeMessageContent } from \"./messages.ts\";\n\nexport function _emit(this: AgentSession, event: AgentSessionEvent): void {\n\tfor (const l of this._eventListeners) {\n\t\tl(event);\n\t}\n}\n\n\nexport function _emitQueueUpdate(this: AgentSession): void {\n\tthis._emit({\n\t\ttype: \"queue_update\",\n\t\tsteering: [...this._steeringMessages],\n\t\tfollowUp: [...this._followUpMessages],\n\t});\n}\n\n/** Internal handler for agent events - shared by subscribe and reconnect */\n\nexport function _handleAgentEvent(this: AgentSession, event: AgentEvent): void {\n\t// Create retry promise synchronously before queueing async processing.\n\t// Agent.emit() calls this handler synchronously, and prompt() calls waitForRetry()\n\t// as soon as agent.prompt() resolves. If _retryPromise is created only inside\n\t// _processAgentEvent, slow earlier queued events can delay agent_end processing\n\t// and waitForRetry() can miss the in-flight retry.\n\tthis._createRetryPromiseForAgentEnd(event);\n\n\tthis._agentEventQueue = this._agentEventQueue.then(\n\t\t() => this._processAgentEvent(event),\n\t\t() => this._processAgentEvent(event),\n\t);\n\n\t// Keep queue alive if an event handler fails\n\tthis._agentEventQueue.catch(() => {});\n}\n\n\nexport function _createRetryPromiseForAgentEnd(this: AgentSession, event: AgentEvent): void {\n\tif (event.type !== \"agent_end\" || this._retryPromise) {\n\t\treturn;\n\t}\n\n\tconst settings = this.settingsManager.getRetrySettings();\n\tif (!settings.enabled && this._fallbackModels.length === 0) {\n\t\treturn;\n\t}\n\n\tconst lastAssistant = this._findLastAssistantInMessages(event.messages);\n\tif (!lastAssistant) {\n\t\treturn;\n\t}\n\n\tconst shouldRetry = this._isRetryableError(lastAssistant) || this._isEmptyCompletion(lastAssistant) || this._isSafetyRefusal(lastAssistant);\n\tif (!shouldRetry) {\n\t\treturn;\n\t}\n\n\tthis._retryPromise = new Promise((resolve) => {\n\t\tthis._retryResolve = resolve;\n\t});\n}\n\n\nexport function _findLastAssistantInMessages(this: AgentSession, messages: AgentMessage[]): AssistantMessage | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst message = messages[i];\n\t\tif (message.role === \"assistant\") {\n\t\t\treturn message as AssistantMessage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n\nexport async function _processAgentEvent(this: AgentSession, event: AgentEvent): Promise<void> {\n\t// When a user message starts, check if it's from either queue and remove it BEFORE emitting\n\t// This ensures the UI sees the updated queue state\n\tif (event.type === \"message_start\" && event.message.role === \"user\") {\n\t\tthis._overflowRecoveryAttempted = false;\n\t\tthis._fallbackAttemptedKeys.clear();\n\t\tconst messageText = this._getUserMessageText(event.message);\n\t\tif (messageText) {\n\t\t\t// Check steering queue first\n\t\t\tconst steeringIndex = this._steeringMessages.indexOf(messageText);\n\t\t\tif (steeringIndex !== -1) {\n\t\t\t\tthis._steeringMessages.splice(steeringIndex, 1);\n\t\t\t\tthis._emitQueueUpdate();\n\t\t\t} else {\n\t\t\t\t// Check follow-up queue\n\t\t\t\tconst followUpIndex = this._followUpMessages.indexOf(messageText);\n\t\t\t\tif (followUpIndex !== -1) {\n\t\t\t\t\tthis._followUpMessages.splice(followUpIndex, 1);\n\t\t\t\t\tthis._emitQueueUpdate();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tthis._applyInterruptAbortMessage(event);\n\tthis._applyProviderErrorGuidance(event);\n\n\t// Emit to extensions first\n\tawait this._emitExtensionEvent(event);\n\n\t// Notify all listeners\n\tthis._emit(event);\n\n\t// Handle session persistence\n\tif (event.type === \"message_end\") {\n\t\t// Check if this is a custom message from extensions\n\t\tif (event.message.role === \"custom\") {\n\t\t\t// Persist as CustomMessageEntry\n\t\t\tthis.sessionManager.appendCustomMessageEntry(\n\t\t\t\tevent.message.customType,\n\t\t\t\tevent.message.content,\n\t\t\t\tevent.message.display,\n\t\t\t\tevent.message.details,\n\t\t\t\tcustomMessageExcludesContext(event.message),\n\t\t\t);\n\t\t} else if (\n\t\t\tevent.message.role === \"user\" ||\n\t\t\tevent.message.role === \"assistant\" ||\n\t\t\tevent.message.role === \"toolResult\"\n\t\t) {\n\t\t\tif (event.message.role === \"assistant\") {\n\t\t\t\tthis._normalizePersistedGeminiToolArgs(event.message);\n\t\t\t}\n\t\t\t// Regular LLM message - persist as SessionMessageEntry\n\t\t\tthis.sessionManager.appendMessage(event.message);\n\t\t}\n\t\t// Other message types (bashExecution, branchSummary) are persisted elsewhere\n\n\t\t// Track assistant message for auto-compaction (checked on agent_end)\n\t\tif (event.message.role === \"assistant\") {\n\t\t\tthis._lastAssistantMessage = event.message;\n\n\t\t\tconst assistantMsg = event.message as AssistantMessage;\n\t\t\t// Treat degenerate empty completions (no content, zero output tokens) and\n\t\t\t// intercepted canned safety refusals as failures alongside stopReason ===\n\t\t\t// \"error\". Otherwise such a turn that stops with reason \"stop\"/\"length\"\n\t\t\t// would reset the retry counter on every attempt, causing unbounded\n\t\t\t// retries instead of honoring maxRetries.\n\t\t\tconst assistantFailed = assistantMsg.stopReason === \"error\" || this._isEmptyCompletion(assistantMsg) || this._isSafetyRefusal(assistantMsg);\n\t\t\tif (!assistantFailed) {\n\t\t\t\tthis._fallbackAttemptedKeys.clear();\n\t\t\t\tthis._overflowRecoveryAttempted = false;\n\t\t\t\tthis._outputBudgetErrorContinuationAttempts = 0;\n\t\t\t}\n\n\t\t\t// A non-truncated assistant response means the length-continuation loop\n\t\t\t// made progress (or the turn completed cleanly), so reset the bounded\n\t\t\t// output-cap continuation counter.\n\t\t\tif (assistantMsg.stopReason !== \"length\") {\n\t\t\t\tthis._lengthContinuationAttempts = 0;\n\t\t\t}\n\n\t\t\t// Reset retry counter immediately on successful assistant response\n\t\t\t// This prevents accumulation across multiple LLM calls within a turn\n\t\t\tif (!assistantFailed && this._retryAttempt > 0) {\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tattempt: this._retryAttempt,\n\t\t\t\t});\n\t\t\t\tthis._retryAttempt = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check auto-retry and auto-compaction after agent completes\n\tif (event.type === \"agent_end\" && this._lastAssistantMessage) {\n\t\tconst msg = this._lastAssistantMessage;\n\t\tthis._lastAssistantMessage = undefined;\n\n\t\t// Check for retryable errors first (overloaded, rate limit, server errors,\n\t\t// transient provider finish_reason errors, degenerate empty completions,\n\t\t// or intercepted canned safety refusals)\n\t\tconst retryableError = this._isRetryableError(msg);\n\t\tconst emptyCompletion = !retryableError && this._isEmptyCompletion(msg);\n\t\tconst safetyRefusal = !retryableError && !emptyCompletion && this._isSafetyRefusal(msg);\n\t\tif (retryableError || emptyCompletion || safetyRefusal) {\n\t\t\tif (emptyCompletion && !msg.errorMessage) {\n\t\t\t\t// Surface a clear reason in the retry banner; empty completions carry no\n\t\t\t\t// provider error message of their own.\n\t\t\t\tmsg.errorMessage = \"Provider returned an empty completion\";\n\t\t\t} else if (safetyRefusal && !msg.errorMessage) {\n\t\t\t\tmsg.errorMessage = \"Provider returned a canned safety refusal\";\n\t\t\t}\n\t\t\tconst didRetry = await this._handleRetryableError(msg);\n\t\t\tif (didRetry) return; // Retry was initiated, don't proceed to compaction\n\t\t}\n\n\t\tthis._resolveRetry();\n\t\tawait this._checkCompaction(msg);\n\t}\n}\n\n\nexport function _applyInterruptAbortMessage(this: AgentSession, event: AgentEvent): void {\n\tconst abortMessage = this._activeInterruptAbortMessage;\n\tif (!abortMessage) return;\n\n\tif (event.type === \"tool_execution_end\" && event.isError && isSingleGenericAbortTextContent(event.result.content)) {\n\t\tevent.result.content = replacementAbortContent(abortMessage);\n\t\treturn;\n\t}\n\n\tif (event.type !== \"message_start\" && event.type !== \"message_end\") return;\n\n\tif (event.message.role === \"toolResult\" && event.message.isError && isSingleGenericAbortTextContent(event.message.content)) {\n\t\tevent.message.content = replacementAbortContent(abortMessage);\n\t\treturn;\n\t}\n\n\tif (event.message.role === \"assistant\") {\n\t\tconst assistantMessage = event.message as AssistantMessage;\n\t\tif (assistantMessage.stopReason === \"aborted\") {\n\t\t\tassistantMessage.errorMessage = abortMessage;\n\t\t}\n\t}\n}\n\n\nexport function _applyProviderErrorGuidance(this: AgentSession, event: AgentEvent): void {\n\tif (event.type !== \"message_start\" && event.type !== \"message_update\" && event.type !== \"message_end\") return;\n\tif (event.message.role !== \"assistant\") return;\n\n\tconst assistantMessage = event.message as AssistantMessage;\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return;\n\n\tassistantMessage.errorMessage = formatCopilotProviderError(\n\t\tassistantMessage.provider,\n\t\tassistantMessage.errorMessage,\n\t);\n}\n\n/** Resolve the pending retry promise */\n\nexport function _resolveRetry(this: AgentSession): void {\n\tif (this._retryResolve) {\n\t\tthis._retryResolve();\n\t\tthis._retryResolve = undefined;\n\t\tthis._retryPromise = undefined;\n\t}\n}\n\n/** Extract text content from a message */\n\nexport function _getUserMessageText(this: AgentSession, message: Message): string {\n\tif (message.role !== \"user\") return \"\";\n\tconst content = message.content;\n\tif (typeof content === \"string\") return content;\n\tconst textBlocks = content.filter((c) => c.type === \"text\");\n\treturn textBlocks.map((c) => (c as TextContent).text).join(\"\");\n}\n\n/** Find the last assistant message in agent state (including aborted ones) */\n\nexport function _findLastAssistantMessage(this: AgentSession): AssistantMessage | undefined {\n\tconst messages = this.agent.state.messages;\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst msg = messages[i];\n\t\tif (msg.role === \"assistant\") {\n\t\t\treturn msg as AssistantMessage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n\nexport function _replaceMessageInPlace(this: AgentSession, target: AgentMessage, replacement: AgentMessage): void {\n\t// Agent-core stores the finalized message object in its state before emitting message_end.\n\t// SessionManager persistence happens later in _processAgentEvent() with event.message.\n\t// Mutating this object in place keeps agent state, later turn/agent events, listeners,\n\t// and the eventual SessionManager.appendMessage(event.message) persistence in sync.\n\tif (target === replacement) {\n\t\treturn;\n\t}\n\n\tconst targetRecord = target as unknown as Record<string, unknown>;\n\tfor (const key of Object.keys(targetRecord)) {\n\t\tdelete targetRecord[key];\n\t}\n\tObject.assign(targetRecord, replacement);\n}\n\n/** Emit extension events based on agent events */\n\nexport async function _emitExtensionEvent(this: AgentSession, event: AgentEvent): Promise<void> {\n\tif (event.type === \"agent_start\") {\n\t\tthis._turnIndex = 0;\n\t\tawait this._extensionRunner.emit({ type: \"agent_start\" });\n\t} else if (event.type === \"agent_end\") {\n\t\tawait this._extensionRunner.emit({ type: \"agent_end\", messages: event.messages });\n\t} else if (event.type === \"turn_start\") {\n\t\tconst extensionEvent: TurnStartEvent = {\n\t\t\ttype: \"turn_start\",\n\t\t\tturnIndex: this._turnIndex,\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"turn_end\") {\n\t\tconst extensionEvent: TurnEndEvent = {\n\t\t\ttype: \"turn_end\",\n\t\t\tturnIndex: this._turnIndex,\n\t\t\tmessage: event.message,\n\t\t\ttoolResults: event.toolResults,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t\tthis._turnIndex++;\n\t} else if (event.type === \"message_start\") {\n\t\tconst extensionEvent: MessageStartEvent = {\n\t\t\ttype: \"message_start\",\n\t\t\tmessage: event.message,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"message_update\") {\n\t\tconst extensionEvent: MessageUpdateEvent = {\n\t\t\ttype: \"message_update\",\n\t\t\tmessage: event.message,\n\t\t\tassistantMessageEvent: event.assistantMessageEvent,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"message_end\") {\n\t\tconst extensionEvent: MessageEndEvent = {\n\t\t\ttype: \"message_end\",\n\t\t\tmessage: event.message,\n\t\t};\n\t\tconst replacement = await this._extensionRunner.emitMessageEnd(extensionEvent);\n\t\tif (replacement) {\n\t\t\tthis._replaceMessageInPlace(event.message, normalizeMessageContent(replacement));\n\t\t}\n\t} else if (event.type === \"tool_execution_start\") {\n\t\tconst extensionEvent: ToolExecutionStartEvent = {\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: event.toolCallId,\n\t\t\ttoolName: event.toolName,\n\t\t\targs: event.args,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"tool_execution_update\") {\n\t\tconst extensionEvent: ToolExecutionUpdateEvent = {\n\t\t\ttype: \"tool_execution_update\",\n\t\t\ttoolCallId: event.toolCallId,\n\t\t\ttoolName: event.toolName,\n\t\t\targs: event.args,\n\t\t\tpartialResult: event.partialResult,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"tool_execution_end\") {\n\t\tconst extensionEvent: ToolExecutionEndEvent = {\n\t\t\ttype: \"tool_execution_end\",\n\t\t\ttoolCallId: event.toolCallId,\n\t\t\ttoolName: event.toolName,\n\t\t\tresult: event.result,\n\t\t\tisError: event.isError,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t}\n}\n\n/**\n * Subscribe to agent events.\n * Session persistence is handled internally (saves messages on message_end).\n * Multiple listeners can be added. Returns unsubscribe function for this listener.\n */\n\nexport function subscribe(this: AgentSession, listener: AgentSessionEventListener): () => void {\n\tthis._eventListeners.push(listener);\n\n\t// Return unsubscribe function for this specific listener\n\treturn () => {\n\t\tconst index = this._eventListeners.indexOf(listener);\n\t\tif (index !== -1) {\n\t\t\tthis._eventListeners.splice(index, 1);\n\t\t}\n\t};\n}\n\n/**\n * Temporarily disconnect from agent events.\n * User listeners are preserved and will receive events again after resubscribe().\n * Used internally during operations that need to pause event processing.\n */\n\nexport function _disconnectFromAgent(this: AgentSession): void {\n\tif (this._unsubscribeAgent) {\n\t\tthis._unsubscribeAgent();\n\t\tthis._unsubscribeAgent = undefined;\n\t}\n}\n\n/**\n * Reconnect to agent events after _disconnectFromAgent().\n * Preserves all existing listeners.\n */\n\nexport function _reconnectToAgent(this: AgentSession): void {\n\tif (this._unsubscribeAgent) return; // Already connected\n\tthis._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);\n}\n\n/**\n * Remove all listeners and disconnect from agent.\n * Call this when completely done with the session.\n */\n\nexport function dispose(this: AgentSession): void {\n\tthis._extensionRunner.invalidate(\n\t\t\"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().\",\n\t);\n\tdisposeSessionAsyncJobManager(this._asyncJobManager, this._asyncJobManagerSessionId);\n\tthis._disconnectFromAgent();\n\tthis._eventListeners = [];\n\tcleanupSessionResources(this.sessionId);\n}\n\n// =========================================================================\n// Read-only State Access\n// =========================================================================\n\n/** Full agent state */\n\nexport const agentSessionEventsMethods = {\n\t_emit,\n\t_emitQueueUpdate,\n\t_handleAgentEvent,\n\t_createRetryPromiseForAgentEnd,\n\t_findLastAssistantInMessages,\n\t_processAgentEvent,\n\t_applyInterruptAbortMessage,\n\t_applyProviderErrorGuidance,\n\t_resolveRetry,\n\t_getUserMessageText,\n\t_findLastAssistantMessage,\n\t_replaceMessageInPlace,\n\t_emitExtensionEvent,\n\tsubscribe,\n\t_disconnectFromAgent,\n\t_reconnectToAgent,\n\tdispose,\n};\n"]}
|
|
@@ -2,6 +2,7 @@ import { disposeSessionAsyncJobManager } from "./async/session-manager.js";
|
|
|
2
2
|
import { cleanupSessionResources } from "@earendil-works/pi-ai/compat";
|
|
3
3
|
import { formatCopilotProviderError } from "./copilot-errors.js";
|
|
4
4
|
import { customMessageExcludesContext, isSingleGenericAbortTextContent, replacementAbortContent } from "./agent-session-types.js";
|
|
5
|
+
import { normalizeMessageContent } from "./messages.js";
|
|
5
6
|
export function _emit(event) {
|
|
6
7
|
for (const l of this._eventListeners) {
|
|
7
8
|
l(event);
|
|
@@ -115,6 +116,13 @@ export async function _processAgentEvent(event) {
|
|
|
115
116
|
if (!assistantFailed) {
|
|
116
117
|
this._fallbackAttemptedKeys.clear();
|
|
117
118
|
this._overflowRecoveryAttempted = false;
|
|
119
|
+
this._outputBudgetErrorContinuationAttempts = 0;
|
|
120
|
+
}
|
|
121
|
+
// A non-truncated assistant response means the length-continuation loop
|
|
122
|
+
// made progress (or the turn completed cleanly), so reset the bounded
|
|
123
|
+
// output-cap continuation counter.
|
|
124
|
+
if (assistantMsg.stopReason !== "length") {
|
|
125
|
+
this._lengthContinuationAttempts = 0;
|
|
118
126
|
}
|
|
119
127
|
// Reset retry counter immediately on successful assistant response
|
|
120
128
|
// This prevents accumulation across multiple LLM calls within a turn
|
|
@@ -278,7 +286,7 @@ export async function _emitExtensionEvent(event) {
|
|
|
278
286
|
};
|
|
279
287
|
const replacement = await this._extensionRunner.emitMessageEnd(extensionEvent);
|
|
280
288
|
if (replacement) {
|
|
281
|
-
this._replaceMessageInPlace(event.message, replacement);
|
|
289
|
+
this._replaceMessageInPlace(event.message, normalizeMessageContent(replacement));
|
|
282
290
|
}
|
|
283
291
|
}
|
|
284
292
|
else if (event.type === "tool_execution_start") {
|