@bastani/atomic 0.9.5-alpha.7 → 0.9.5-alpha.9
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 +33 -2
- package/dist/builtin/cursor/package.json +2 -2
- package/dist/builtin/intercom/CHANGELOG.md +17 -0
- package/dist/builtin/intercom/README.md +27 -21
- package/dist/builtin/intercom/broker/broker.ts +3 -6
- package/dist/builtin/intercom/broker/paths.ts +42 -5
- package/dist/builtin/intercom/broker/spawn.ts +78 -10
- package/dist/builtin/intercom/config.ts +6 -3
- package/dist/builtin/intercom/contact-supervisor-tool.ts +6 -4
- package/dist/builtin/intercom/index-heavy.ts +1 -1
- package/dist/builtin/intercom/index.ts +162 -130
- package/dist/builtin/intercom/intercom-tool.ts +9 -3
- package/dist/builtin/intercom/package.json +10 -1
- package/dist/builtin/intercom/result-renderers.ts +1 -1
- package/dist/builtin/intercom/ui/compose.ts +2 -2
- package/dist/builtin/intercom/ui/inline-message.ts +2 -2
- package/dist/builtin/intercom/ui/session-list.ts +2 -2
- package/dist/builtin/mcp/CHANGELOG.md +11 -0
- package/dist/builtin/mcp/README.md +6 -6
- package/dist/builtin/mcp/direct-tools.ts +41 -23
- package/dist/builtin/mcp/index.ts +31 -4
- package/dist/builtin/mcp/init.ts +4 -43
- package/dist/builtin/mcp/metadata-hydration.ts +37 -0
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/mcp/proxy-info-modes.ts +67 -14
- package/dist/builtin/mcp/startup-warmup.ts +98 -0
- package/dist/builtin/mcp/tool-result-renderer.ts +3 -3
- package/dist/builtin/subagents/CHANGELOG.md +18 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/extension/index.ts +14 -25
- package/dist/builtin/subagents/src/extension/startup-maintenance.ts +89 -0
- package/dist/builtin/subagents/src/runs/background/async-execution-common.ts +23 -18
- package/dist/builtin/subagents/src/runs/background/result-watcher.ts +20 -10
- package/dist/builtin/subagents/src/runs/background/subagent-runner-streaming.ts +13 -3
- package/dist/builtin/subagents/src/runs/foreground/execution-attempt.ts +10 -2
- package/dist/builtin/subagents/src/runs/shared/pi-spawn.ts +28 -1
- package/dist/builtin/subagents/src/tui/render-event-formatting.ts +15 -48
- package/dist/builtin/subagents/src/tui/render-layout.ts +9 -0
- package/dist/builtin/subagents/src/tui/render-widget-graph.ts +27 -25
- package/dist/builtin/subagents/src/tui/render-widget.ts +72 -66
- package/dist/builtin/subagents/src/tui/render.ts +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +29 -0
- package/dist/builtin/workflows/README.md +4 -2
- package/dist/builtin/workflows/builtin/goal-artifacts.ts +3 -1
- package/dist/builtin/workflows/builtin/goal-prompts.ts +23 -2
- package/dist/builtin/workflows/builtin/goal-reducer.ts +21 -0
- package/dist/builtin/workflows/builtin/goal-review.ts +60 -6
- package/dist/builtin/workflows/builtin/goal-runner.ts +71 -22
- package/dist/builtin/workflows/builtin/goal-types.ts +7 -1
- package/dist/builtin/workflows/builtin/ralph-core.ts +52 -4
- package/dist/builtin/workflows/builtin/ralph-review-gate.ts +10 -3
- package/dist/builtin/workflows/builtin/ralph-reviewer-prompt.ts +23 -2
- package/dist/builtin/workflows/builtin/ralph-runner.ts +38 -16
- package/dist/builtin/workflows/builtin/review-convergence.ts +111 -0
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/skills/create-spec/SKILL.md +2 -0
- 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/child-primitive.ts +12 -8
- package/dist/builtin/workflows/src/durable/dbos-backend.ts +63 -2
- package/dist/builtin/workflows/src/durable/dbos-envelope.ts +28 -0
- 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 +165 -27
- package/dist/builtin/workflows/src/durable/types.ts +30 -1
- package/dist/builtin/workflows/src/engine/primitives/task.ts +1 -0
- 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 +32 -32
- 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 +2 -0
- package/dist/builtin/workflows/src/extension/workflow-run-control-command.ts +48 -23
- 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-continuation.ts +13 -3
- package/dist/builtin/workflows/src/runs/foreground/executor-direct-helpers.ts +29 -8
- package/dist/builtin/workflows/src/runs/foreground/executor-hil.ts +2 -1
- package/dist/builtin/workflows/src/runs/foreground/executor-stage-factory.ts +4 -3
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-controller.ts +18 -19
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-unresolved-overflow.ts +38 -0
- 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/persistence-restore-helpers.ts +18 -1
- package/dist/builtin/workflows/src/shared/persistence-restore.ts +23 -5
- package/dist/builtin/workflows/src/shared/persistence-session-entries.ts +4 -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/status-list.ts +22 -15
- package/dist/builtin/workflows/src/tui/workflow-attach-pane.ts +4 -4
- package/dist/bun/internal-intercom-broker.d.ts +6 -0
- package/dist/bun/internal-intercom-broker.d.ts.map +1 -0
- package/dist/bun/internal-intercom-broker.js +39 -0
- package/dist/bun/internal-intercom-broker.js.map +1 -0
- package/dist/bun/split-loader.d.ts.map +1 -1
- package/dist/bun/split-loader.js +21 -8
- package/dist/bun/split-loader.js.map +1 -1
- package/dist/core/agent-session-auto-compaction.d.ts +21 -2
- package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-auto-compaction.js +163 -11
- 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 +10 -1
- package/dist/core/agent-session-events.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +12 -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-models.d.ts +2 -2
- package/dist/core/agent-session-models.d.ts.map +1 -1
- package/dist/core/agent-session-models.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +1 -0
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-retry.d.ts +2 -0
- package/dist/core/agent-session-retry.d.ts.map +1 -1
- package/dist/core/agent-session-retry.js +152 -4
- package/dist/core/agent-session-retry.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +1 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +1 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session-types.d.ts +15 -1
- package/dist/core/agent-session-types.d.ts.map +1 -1
- package/dist/core/agent-session-types.js.map +1 -1
- package/dist/core/agent-session.d.ts +6 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +6 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/compaction/context-compaction-runner.d.ts.map +1 -1
- package/dist/core/compaction/context-compaction-runner.js +36 -20
- package/dist/core/compaction/context-compaction-runner.js.map +1 -1
- package/dist/core/copilot-anthropic-sse-repair.d.ts +23 -0
- package/dist/core/copilot-anthropic-sse-repair.d.ts.map +1 -0
- package/dist/core/copilot-anthropic-sse-repair.js +340 -0
- package/dist/core/copilot-anthropic-sse-repair.js.map +1 -0
- package/dist/core/copilot-gemini-reasoning.d.ts +16 -8
- package/dist/core/copilot-gemini-reasoning.d.ts.map +1 -1
- package/dist/core/copilot-gemini-reasoning.js +27 -22
- package/dist/core/copilot-gemini-reasoning.js.map +1 -1
- package/dist/core/copilot-hosts.d.ts +12 -0
- package/dist/core/copilot-hosts.d.ts.map +1 -0
- package/dist/core/copilot-hosts.js +33 -0
- package/dist/core/copilot-hosts.js.map +1 -0
- package/dist/core/extensions/agent-events.d.ts +1 -1
- package/dist/core/extensions/agent-events.d.ts.map +1 -1
- package/dist/core/extensions/agent-events.js.map +1 -1
- package/dist/core/extensions/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/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/http-dispatcher.d.ts.map +1 -1
- package/dist/core/http-dispatcher.js +5 -5
- package/dist/core/http-dispatcher.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/sdk-types.d.ts +2 -0
- package/dist/core/sdk-types.d.ts.map +1 -1
- package/dist/core/sdk-types.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +1 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager-basic-accessors.d.ts +1 -0
- package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
- package/dist/core/settings-manager-basic-accessors.js +6 -0
- package/dist/core/settings-manager-basic-accessors.js.map +1 -1
- package/dist/core/settings-types.d.ts +1 -0
- 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/index-extensions.d.ts +1 -1
- package/dist/index-extensions.d.ts.map +1 -1
- package/dist/index-extensions.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 +12 -0
- package/dist/main-deferred-startup.d.ts.map +1 -1
- package/dist/main-deferred-startup.js +23 -2
- package/dist/main-deferred-startup.js.map +1 -1
- package/dist/main-early-input.d.ts +41 -0
- package/dist/main-early-input.d.ts.map +1 -0
- package/dist/main-early-input.js +154 -0
- package/dist/main-early-input.js.map +1 -0
- package/dist/main.d.ts +0 -6
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +20 -14
- 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/chat-session-host-events.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-events.js +15 -0
- package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.js +25 -0
- 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-deferred-startup.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-deferred-startup.js +41 -28
- 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 +318 -185
- package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.d.ts +12 -0
- package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.js +39 -0
- package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-deps.d.ts +1 -1
- package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-deps.js +1 -1
- package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.d.ts +6 -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-mode-types.d.ts +3 -0
- package/dist/modes/interactive/interactive-mode-types.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-types.js.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.js +3 -1
- 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 +36 -10
- 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 +26 -22
- 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/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/compaction.md +8 -0
- package/docs/development.md +4 -0
- package/docs/extensions.md +5 -0
- package/docs/json.md +3 -1
- package/docs/providers.md +1 -0
- package/docs/quickstart.md +1 -1
- package/docs/rpc.md +3 -1
- package/docs/settings.md +27 -1
- package/docs/subagents.md +4 -0
- package/docs/terminal-setup.md +4 -0
- package/docs/usage.md +2 -2
- package/docs/windows.md +4 -0
- package/docs/workflows.md +21 -9
- package/npm-shrinkwrap.json +513 -23
- package/package.json +3 -2
|
@@ -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;
|
|
@@ -45,6 +61,7 @@ export async function _checkCompaction(assistantMessage, skipAbortedCheck = true
|
|
|
45
61
|
result: undefined,
|
|
46
62
|
aborted: false,
|
|
47
63
|
willRetry: false,
|
|
64
|
+
unresolvedOverflow: true,
|
|
48
65
|
errorMessage: "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.",
|
|
49
66
|
});
|
|
50
67
|
return;
|
|
@@ -87,7 +104,31 @@ export async function _checkCompaction(assistantMessage, skipAbortedCheck = true
|
|
|
87
104
|
// rather than relying on reactive overflow recovery near the cap.
|
|
88
105
|
const compactionBudget = this.model ? getEffectiveInputBudget(this.model) : contextWindow;
|
|
89
106
|
if (shouldCompact(contextTokens, compactionBudget, settings)) {
|
|
90
|
-
|
|
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();
|
|
91
132
|
}
|
|
92
133
|
}
|
|
93
134
|
export function _isCopilotServerCapBelowSelectedContextWindow(assistantMessage) {
|
|
@@ -100,9 +141,67 @@ export function _isCopilotServerCapBelowSelectedContextWindow(assistantMessage)
|
|
|
100
141
|
// to a lower server tier) keeps the friendly error visible instead of silently compacting down.
|
|
101
142
|
return promptLimitError !== undefined && getEffectiveInputBudget(this.model) > promptLimitError.limitTokens;
|
|
102
143
|
}
|
|
103
|
-
export function
|
|
144
|
+
export function isRetryWorthyLengthStop(assistantMessage) {
|
|
104
145
|
return assistantMessage.stopReason === "length" && assistantMessage.usage.output > 0;
|
|
105
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
|
+
}
|
|
106
205
|
/**
|
|
107
206
|
* Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.
|
|
108
207
|
*/
|
|
@@ -120,36 +219,84 @@ export function _dropTrailingAutoCompactionRetryAssistantIfPresent() {
|
|
|
120
219
|
* Internal: schedule a live post-event continuation probe after compaction_end listeners can flush queues.
|
|
121
220
|
*/
|
|
122
221
|
export function _schedulePostAutoCompactionContinuationProbe(_reason, willRetry) {
|
|
222
|
+
if (willRetry) {
|
|
223
|
+
const token = this._postCompactionContinuationToken + 1;
|
|
224
|
+
this._postCompactionContinuationToken = token;
|
|
225
|
+
let pending;
|
|
226
|
+
pending = new Promise((resolve) => {
|
|
227
|
+
setTimeout(() => {
|
|
228
|
+
void (async () => {
|
|
229
|
+
try {
|
|
230
|
+
if (this._postCompactionContinuationToken !== token)
|
|
231
|
+
return;
|
|
232
|
+
if (this.isCompacting || this.isStreaming)
|
|
233
|
+
return;
|
|
234
|
+
await this._resumeAfterAutoCompaction();
|
|
235
|
+
}
|
|
236
|
+
finally {
|
|
237
|
+
if (this._pendingPostCompactionContinuation === pending) {
|
|
238
|
+
this._pendingPostCompactionContinuation = undefined;
|
|
239
|
+
}
|
|
240
|
+
resolve();
|
|
241
|
+
}
|
|
242
|
+
})();
|
|
243
|
+
}, 100);
|
|
244
|
+
});
|
|
245
|
+
this._pendingPostCompactionContinuation = pending;
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
123
248
|
setTimeout(() => {
|
|
124
249
|
if (this.isCompacting || this.isStreaming) {
|
|
125
250
|
return;
|
|
126
251
|
}
|
|
127
|
-
if (willRetry) {
|
|
128
|
-
this._resumeAfterAutoCompaction();
|
|
129
|
-
return;
|
|
130
|
-
}
|
|
131
252
|
if (!this.agent.hasQueuedMessages()) {
|
|
132
253
|
return;
|
|
133
254
|
}
|
|
134
|
-
this._resumeAfterAutoCompaction();
|
|
255
|
+
void this._resumeAfterAutoCompaction();
|
|
135
256
|
}, 100);
|
|
136
257
|
}
|
|
258
|
+
export async function _awaitPendingPostCompactionContinuation() {
|
|
259
|
+
const pending = this._pendingPostCompactionContinuation;
|
|
260
|
+
if (pending === undefined)
|
|
261
|
+
return;
|
|
262
|
+
await pending;
|
|
263
|
+
}
|
|
137
264
|
/**
|
|
138
265
|
* Internal: resume generation after successful auto-compaction only when active work remains.
|
|
139
266
|
*/
|
|
140
|
-
export function _resumeAfterAutoCompaction() {
|
|
141
|
-
|
|
267
|
+
export async function _resumeAfterAutoCompaction() {
|
|
268
|
+
try {
|
|
269
|
+
await this._runAgentContinue();
|
|
270
|
+
}
|
|
271
|
+
catch (error) {
|
|
142
272
|
const message = error instanceof Error ? error.message : String(error);
|
|
143
273
|
this._emit({
|
|
144
274
|
type: "agent_continue_error",
|
|
145
275
|
source: "post_compaction",
|
|
146
276
|
errorMessage: `Post-compaction continuation failed: ${message}`,
|
|
147
277
|
});
|
|
148
|
-
}
|
|
278
|
+
}
|
|
149
279
|
}
|
|
150
280
|
/**
|
|
151
|
-
* Internal:
|
|
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.
|
|
152
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
|
+
}
|
|
297
|
+
function overflowUnresolved(reason, aborted = false) {
|
|
298
|
+
return reason === "overflow" && !aborted ? true : undefined;
|
|
299
|
+
}
|
|
153
300
|
export async function _runAutoCompaction(reason, willRetry) {
|
|
154
301
|
this._emit({ type: "compaction_start", reason });
|
|
155
302
|
this._autoCompactionAbortController = new AbortController();
|
|
@@ -161,6 +308,7 @@ export async function _runAutoCompaction(reason, willRetry) {
|
|
|
161
308
|
result: undefined,
|
|
162
309
|
aborted: false,
|
|
163
310
|
willRetry: false,
|
|
311
|
+
unresolvedOverflow: overflowUnresolved(reason),
|
|
164
312
|
});
|
|
165
313
|
return;
|
|
166
314
|
}
|
|
@@ -190,6 +338,7 @@ export async function _runAutoCompaction(reason, willRetry) {
|
|
|
190
338
|
result: undefined,
|
|
191
339
|
aborted: false,
|
|
192
340
|
willRetry: false,
|
|
341
|
+
unresolvedOverflow: overflowUnresolved(reason),
|
|
193
342
|
});
|
|
194
343
|
return;
|
|
195
344
|
}
|
|
@@ -208,6 +357,7 @@ export async function _runAutoCompaction(reason, willRetry) {
|
|
|
208
357
|
result: undefined,
|
|
209
358
|
aborted,
|
|
210
359
|
willRetry: false,
|
|
360
|
+
unresolvedOverflow: overflowUnresolved(reason, aborted),
|
|
211
361
|
errorMessage: aborted
|
|
212
362
|
? undefined
|
|
213
363
|
: reason === "overflow"
|
|
@@ -223,11 +373,13 @@ export async function _runAutoCompaction(reason, willRetry) {
|
|
|
223
373
|
* Toggle auto-compaction setting.
|
|
224
374
|
*/
|
|
225
375
|
export const agentSessionAutoCompactionMethods = {
|
|
376
|
+
_awaitPendingPostCompactionContinuation,
|
|
226
377
|
_checkCompaction,
|
|
227
378
|
_isCopilotServerCapBelowSelectedContextWindow,
|
|
228
379
|
_dropTrailingAutoCompactionRetryAssistantIfPresent,
|
|
229
380
|
_schedulePostAutoCompactionContinuationProbe,
|
|
230
381
|
_resumeAfterAutoCompaction,
|
|
382
|
+
_resumeAfterLengthTruncation,
|
|
231
383
|
_runAutoCompaction,
|
|
232
384
|
};
|
|
233
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,CAAC,KAAK,IAAI,gBAAgB,CAAC,QAAQ,KAAK,IAAI,CAAC,KAAK,CAAC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,CAAC,kDAAkD,EAAE,CAAC;QAC3D,CAAC;QAED,IAAI,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,gBAAgB,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;QAClF,IAAI,CAAC,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,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,gBAAgB;IAChB,6CAA6C;IAC7C,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\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\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tsetTimeout(() => {\n\t\tif (this.isCompacting || this.isStreaming) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._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\tthis._resumeAfterAutoCompaction();\n\t}, 100);\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport function _resumeAfterAutoCompaction(this: AgentSession): void {\n\tvoid this._runAgentContinue().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: Run auto-compaction with events.\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});\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});\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\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_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,CA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AI,CAAC,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,wBAA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AAI,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\";\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) {\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\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._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","sourceRoot":"","sources":["../../src/core/agent-session-events.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UA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gB,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\";\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, 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"]}
|
|
@@ -31,7 +31,7 @@ export function _createRetryPromiseForAgentEnd(event) {
|
|
|
31
31
|
return;
|
|
32
32
|
}
|
|
33
33
|
const settings = this.settingsManager.getRetrySettings();
|
|
34
|
-
if (!settings.enabled) {
|
|
34
|
+
if (!settings.enabled && this._fallbackModels.length === 0) {
|
|
35
35
|
return;
|
|
36
36
|
}
|
|
37
37
|
const lastAssistant = this._findLastAssistantInMessages(event.messages);
|
|
@@ -60,6 +60,7 @@ export async function _processAgentEvent(event) {
|
|
|
60
60
|
// This ensures the UI sees the updated queue state
|
|
61
61
|
if (event.type === "message_start" && event.message.role === "user") {
|
|
62
62
|
this._overflowRecoveryAttempted = false;
|
|
63
|
+
this._fallbackAttemptedKeys.clear();
|
|
63
64
|
const messageText = this._getUserMessageText(event.message);
|
|
64
65
|
if (messageText) {
|
|
65
66
|
// Check steering queue first
|
|
@@ -112,7 +113,15 @@ export async function _processAgentEvent(event) {
|
|
|
112
113
|
// retries instead of honoring maxRetries.
|
|
113
114
|
const assistantFailed = assistantMsg.stopReason === "error" || this._isEmptyCompletion(assistantMsg) || this._isSafetyRefusal(assistantMsg);
|
|
114
115
|
if (!assistantFailed) {
|
|
116
|
+
this._fallbackAttemptedKeys.clear();
|
|
115
117
|
this._overflowRecoveryAttempted = false;
|
|
118
|
+
this._outputBudgetErrorContinuationAttempts = 0;
|
|
119
|
+
}
|
|
120
|
+
// A non-truncated assistant response means the length-continuation loop
|
|
121
|
+
// made progress (or the turn completed cleanly), so reset the bounded
|
|
122
|
+
// output-cap continuation counter.
|
|
123
|
+
if (assistantMsg.stopReason !== "length") {
|
|
124
|
+
this._lengthContinuationAttempts = 0;
|
|
116
125
|
}
|
|
117
126
|
// Reset retry counter immediately on successful assistant response
|
|
118
127
|
// This prevents accumulation across multiple LLM calls within a turn
|