@bastani/atomic 0.9.38-alpha.4 → 0.9.38-alpha.6
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 +39 -0
- package/README.md +8 -6
- package/dist/builtin/intercom/CHANGELOG.md +15 -0
- package/dist/builtin/intercom/broker/broker.ts +6 -4
- package/dist/builtin/intercom/broker/delivered-message-cache.ts +50 -4
- package/dist/builtin/intercom/broker/send-handler.ts +6 -4
- package/dist/builtin/intercom/index.bundle.mjs +89 -40
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +29 -33
- package/dist/builtin/web-access/CHANGELOG.md +7 -0
- package/dist/builtin/web-access/index.bundle.mjs +53 -15
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +36 -0
- package/dist/builtin/workflows/builtin/{chunk-qrrkfg9v.js → chunk-2qgfyvzs.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-na3wpwzh.js → chunk-g1a4hw0s.js} +390 -345
- package/dist/builtin/workflows/builtin/{chunk-xg7kkgf8.js → chunk-neszcj53.js} +1 -1
- package/dist/builtin/workflows/builtin/goal.js +2 -2
- package/dist/builtin/workflows/builtin/index.js +3 -3
- package/dist/builtin/workflows/builtin/ralph.js +2 -2
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/authoring.d.ts +3 -8
- package/dist/builtin/workflows/src/durable/journal/conformance.d.ts +9 -1
- package/dist/builtin/workflows/src/durable/journal/internal.d.ts +20 -0
- package/dist/builtin/workflows/src/durable/journal/lease-expiry.d.ts +2 -0
- package/dist/builtin/workflows/src/durable/journal/memory-run-journal.d.ts +17 -1
- package/dist/builtin/workflows/src/durable/journal/resolution.d.ts +6 -1
- package/dist/builtin/workflows/src/durable/journal/sql-run-journal.d.ts +45 -0
- package/dist/builtin/workflows/src/durable/journal/sqlite-run-journal.d.ts +5 -47
- package/dist/builtin/workflows/src/durable/journal/types.d.ts +15 -30
- package/dist/builtin/workflows/src/durable/journal/values.d.ts +2 -0
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +23390 -22820
- package/dist/builtin/workflows/src/index.js +7614 -7060
- package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +7 -7
- package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +0 -14
- package/dist/cli/args.d.ts +1 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +6 -2
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/session-picker.d.ts +2 -2
- package/dist/cli/session-picker.d.ts.map +1 -1
- package/dist/cli/session-picker.js +3 -3
- package/dist/cli/session-picker.js.map +1 -1
- package/dist/core/agent-session-auto-compaction.d.ts +1 -1
- package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-auto-compaction.js +2 -2
- package/dist/core/agent-session-auto-compaction.js.map +1 -1
- package/dist/core/agent-session-bash.d.ts +2 -3
- package/dist/core/agent-session-bash.d.ts.map +1 -1
- package/dist/core/agent-session-bash.js +18 -10
- package/dist/core/agent-session-bash.js.map +1 -1
- package/dist/core/agent-session-boundaries.d.ts +6 -6
- package/dist/core/agent-session-boundaries.d.ts.map +1 -1
- package/dist/core/agent-session-boundaries.js +22 -22
- package/dist/core/agent-session-boundaries.js.map +1 -1
- package/dist/core/agent-session-compaction.js +2 -2
- package/dist/core/agent-session-compaction.js.map +1 -1
- package/dist/core/agent-session-custom-message-commit.d.ts.map +1 -1
- package/dist/core/agent-session-custom-message-commit.js +10 -12
- package/dist/core/agent-session-custom-message-commit.js.map +1 -1
- package/dist/core/agent-session-events.d.ts.map +1 -1
- package/dist/core/agent-session-events.js +20 -13
- package/dist/core/agent-session-events.js.map +1 -1
- package/dist/core/agent-session-export.js +1 -1
- package/dist/core/agent-session-export.js.map +1 -1
- package/dist/core/agent-session-extension-bindings.d.ts +2 -2
- package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
- package/dist/core/agent-session-extension-bindings.js +75 -59
- package/dist/core/agent-session-extension-bindings.js.map +1 -1
- package/dist/core/agent-session-message-queue.d.ts +2 -2
- package/dist/core/agent-session-message-queue.d.ts.map +1 -1
- package/dist/core/agent-session-message-queue.js +17 -8
- package/dist/core/agent-session-message-queue.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +15 -15
- 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 +59 -42
- package/dist/core/agent-session-models.js.map +1 -1
- package/dist/core/agent-session-persistent-custom-messages.d.ts +4 -4
- package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
- package/dist/core/agent-session-persistent-custom-messages.js +16 -17
- package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +6 -8
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-retry.d.ts.map +1 -1
- package/dist/core/agent-session-retry.js +17 -15
- package/dist/core/agent-session-retry.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +3 -8
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +44 -96
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-summary.js +1 -1
- package/dist/core/agent-session-summary.js.map +1 -1
- package/dist/core/agent-session-tree.d.ts +1 -1
- package/dist/core/agent-session-tree.d.ts.map +1 -1
- package/dist/core/agent-session-tree.js +7 -7
- package/dist/core/agent-session-tree.js.map +1 -1
- package/dist/core/cache-warmer.js +1 -1
- package/dist/core/cache-warmer.js.map +1 -1
- package/dist/core/export-html/index.js +1 -1
- package/dist/core/export-html/index.js.map +1 -1
- package/dist/core/export-html/template-js/entries-navigation.js +1 -1
- package/dist/core/export-html/template.js +1 -1
- package/dist/core/extensions/api-types.d.ts +12 -12
- package/dist/core/extensions/api-types.d.ts.map +1 -1
- package/dist/core/extensions/api-types.js.map +1 -1
- package/dist/core/extensions/context-types.d.ts +4 -2
- package/dist/core/extensions/context-types.d.ts.map +1 -1
- package/dist/core/extensions/context-types.js.map +1 -1
- package/dist/core/extensions/extension-work.d.ts +1 -0
- package/dist/core/extensions/extension-work.d.ts.map +1 -1
- package/dist/core/extensions/extension-work.js +5 -1
- package/dist/core/extensions/extension-work.js.map +1 -1
- package/dist/core/extensions/loader-api.d.ts.map +1 -1
- package/dist/core/extensions/loader-api.js +40 -42
- package/dist/core/extensions/loader-api.js.map +1 -1
- package/dist/core/extensions/loader-host-modules.d.ts +1 -1
- package/dist/core/extensions/loader-host-modules.d.ts.map +1 -1
- package/dist/core/extensions/loader-host-modules.js +6 -2
- package/dist/core/extensions/loader-host-modules.js.map +1 -1
- package/dist/core/extensions/loader-rollback.d.ts.map +1 -1
- package/dist/core/extensions/loader-rollback.js +1 -0
- package/dist/core/extensions/loader-rollback.js.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.js +1 -0
- package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
- package/dist/core/extensions/runner-context.d.ts +1 -0
- package/dist/core/extensions/runner-context.d.ts.map +1 -1
- package/dist/core/extensions/runner-context.js +3 -2
- package/dist/core/extensions/runner-context.js.map +1 -1
- package/dist/core/extensions/runner-handlers.d.ts +1 -1
- package/dist/core/extensions/runner-handlers.d.ts.map +1 -1
- package/dist/core/extensions/runner-handlers.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +3 -2
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +20 -12
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/runtime-types.d.ts +7 -7
- package/dist/core/extensions/runtime-types.d.ts.map +1 -1
- package/dist/core/extensions/runtime-types.js.map +1 -1
- package/dist/core/extensions/session-events.d.ts +5 -5
- package/dist/core/extensions/session-events.d.ts.map +1 -1
- package/dist/core/extensions/session-events.js.map +1 -1
- package/dist/core/fast-model-routing.d.ts.map +1 -1
- package/dist/core/fast-model-routing.js +1 -0
- package/dist/core/fast-model-routing.js.map +1 -1
- package/dist/core/intercom-runtime-group.js +1 -1
- package/dist/core/intercom-runtime-group.js.map +1 -1
- package/dist/core/provider-attribution.js +1 -1
- package/dist/core/provider-attribution.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +7 -6
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager-archive.d.ts +2 -16
- package/dist/core/session-manager-archive.d.ts.map +1 -1
- package/dist/core/session-manager-archive.js +8 -104
- package/dist/core/session-manager-archive.js.map +1 -1
- package/dist/core/session-manager-core.d.ts +48 -49
- package/dist/core/session-manager-core.d.ts.map +1 -1
- package/dist/core/session-manager-core.js +438 -306
- package/dist/core/session-manager-core.js.map +1 -1
- package/dist/core/session-manager-entries.d.ts.map +1 -1
- package/dist/core/session-manager-entries.js +5 -10
- package/dist/core/session-manager-entries.js.map +1 -1
- package/dist/core/session-manager-errors.d.ts +10 -0
- package/dist/core/session-manager-errors.d.ts.map +1 -0
- package/dist/core/session-manager-errors.js +27 -0
- package/dist/core/session-manager-errors.js.map +1 -0
- package/dist/core/session-manager-list.d.ts +1 -0
- package/dist/core/session-manager-list.d.ts.map +1 -1
- package/dist/core/session-manager-list.js +14 -7
- package/dist/core/session-manager-list.js.map +1 -1
- package/dist/core/session-manager-storage.d.ts +0 -11
- package/dist/core/session-manager-storage.d.ts.map +1 -1
- package/dist/core/session-manager-storage.js +4 -61
- package/dist/core/session-manager-storage.js.map +1 -1
- package/dist/core/session-manager-types.d.ts +2 -10
- package/dist/core/session-manager-types.d.ts.map +1 -1
- package/dist/core/session-manager-types.js.map +1 -1
- package/dist/core/session-manager-validation.d.ts.map +1 -1
- package/dist/core/session-manager-validation.js +3 -2
- package/dist/core/session-manager-validation.js.map +1 -1
- package/dist/core/session-manager.d.ts +1 -0
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +1 -0
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/session-mutation-queue.d.ts +3 -0
- package/dist/core/session-mutation-queue.d.ts.map +1 -0
- package/dist/core/session-mutation-queue.js +14 -0
- package/dist/core/session-mutation-queue.js.map +1 -0
- package/dist/core/settings-merge.d.ts.map +1 -1
- package/dist/core/settings-merge.js +3 -2
- package/dist/core/settings-merge.js.map +1 -1
- package/dist/core/settings-schema.d.ts +0 -5
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +1 -15
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/core/storage/index.d.ts +1 -1
- package/dist/core/storage/index.d.ts.map +1 -1
- package/dist/core/storage/index.js +1 -1
- package/dist/core/storage/index.js.map +1 -1
- package/dist/core/storage/node-sqlite.d.ts +2 -0
- package/dist/core/storage/node-sqlite.d.ts.map +1 -1
- package/dist/core/storage/node-sqlite.js +47 -6
- package/dist/core/storage/node-sqlite.js.map +1 -1
- package/dist/core/storage/session/jsonl-session-store.d.ts +9 -2
- package/dist/core/storage/session/jsonl-session-store.d.ts.map +1 -1
- package/dist/core/storage/session/jsonl-session-store.js +71 -27
- package/dist/core/storage/session/jsonl-session-store.js.map +1 -1
- package/dist/core/storage/session/validation.js +1 -1
- package/dist/core/storage/session/validation.js.map +1 -1
- package/dist/core/storage/testing.d.ts +2 -0
- package/dist/core/storage/testing.d.ts.map +1 -1
- package/dist/core/storage/testing.js +45 -0
- package/dist/core/storage/testing.js.map +1 -1
- package/dist/core/tasks/completion.d.ts.map +1 -1
- package/dist/core/tasks/completion.js +2 -4
- package/dist/core/tasks/completion.js.map +1 -1
- package/dist/core/tools/bash-session-environment.d.ts.map +1 -1
- package/dist/core/tools/bash-session-environment.js +0 -2
- package/dist/core/tools/bash-session-environment.js.map +1 -1
- package/dist/core/tools/todos-model.js +3 -3
- package/dist/core/tools/todos-model.js.map +1 -1
- package/dist/core/tools/todos-mutations.js +2 -2
- package/dist/core/tools/todos-mutations.js.map +1 -1
- package/dist/core/tools/todos-render.js +1 -1
- package/dist/core/tools/todos-render.js.map +1 -1
- package/dist/core/tools/todos-storage.js +2 -2
- package/dist/core/tools/todos-storage.js.map +1 -1
- package/dist/extensions/codemode/execute.js +1 -1
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts +1 -1
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/herdr/index.d.ts.map +1 -1
- package/dist/extensions/herdr/index.js +1 -5
- package/dist/extensions/herdr/index.js.map +1 -1
- package/dist/extensions/mcp/index.js +1 -1
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +6 -1
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main-session.d.ts +7 -1
- package/dist/main-session.d.ts.map +1 -1
- package/dist/main-session.js +86 -52
- package/dist/main-session.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +51 -30
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host.js +1 -0
- package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
- package/dist/modes/interactive/components/extension-input.d.ts +1 -1
- package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-input.js +2 -2
- package/dist/modes/interactive/components/extension-input.js.map +1 -1
- package/dist/modes/interactive/components/host-session-picker.js +1 -1
- package/dist/modes/interactive/components/host-session-picker.js.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +4 -1
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/session-selector-list.d.ts +9 -6
- package/dist/modes/interactive/components/session-selector-list.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector-list.js +15 -14
- package/dist/modes/interactive/components/session-selector-list.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +7 -4
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +12 -14
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector-component.d.ts +5 -1
- package/dist/modes/interactive/components/tree-selector-component.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector-component.js +20 -3
- package/dist/modes/interactive/components/tree-selector-component.js.map +1 -1
- package/dist/modes/interactive/interactive-bash-compact.js +1 -1
- package/dist/modes/interactive/interactive-bash-compact.js.map +1 -1
- package/dist/modes/interactive/interactive-deferred-startup.js +2 -2
- package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
- package/dist/modes/interactive/interactive-editor-actions.js +2 -2
- package/dist/modes/interactive/interactive-editor-actions.js.map +1 -1
- package/dist/modes/interactive/interactive-extension-runtime.js +2 -0
- package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.js +6 -4
- package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-helpers.js +1 -1
- package/dist/modes/interactive/interactive-mode-helpers.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.d.ts +5 -5
- package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.js +12 -7
- package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
- package/dist/modes/interactive/interactive-selectors.js +2 -2
- package/dist/modes/interactive/interactive-selectors.js.map +1 -1
- package/dist/modes/interactive/interactive-session-routing.js +24 -12
- package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
- package/dist/modes/interactive/interactive-slash-commands.js +2 -2
- package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
- package/dist/modes/interactive-engine/engine-args.d.ts.map +1 -1
- package/dist/modes/interactive-engine/engine-args.js +7 -4
- package/dist/modes/interactive-engine/engine-args.js.map +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.d.ts +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.js +90 -71
- package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
- package/dist/modes/rpc/rpc-bash-request-owners.js +1 -1
- package/dist/modes/rpc/rpc-bash-request-owners.js.map +1 -1
- package/dist/modes/rpc/rpc-client-api.d.ts +1 -1
- package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client-api.js +2 -2
- package/dist/modes/rpc/rpc-client-api.js.map +1 -1
- package/dist/modes/rpc/rpc-client-process.d.ts +2 -2
- package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client-process.js +18 -7
- package/dist/modes/rpc/rpc-client-process.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +4 -1
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +6 -2
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-command-handler.js +11 -8
- package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
- package/dist/modes/rpc/rpc-provider-auth.js +2 -2
- package/dist/modes/rpc/rpc-provider-auth.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +6 -2
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/docs/custom-provider/oauth.md +2 -2
- package/docs/custom-provider/override.md +3 -3
- package/docs/custom-provider/registration.md +7 -7
- package/docs/custom-provider/streaming.md +1 -1
- package/docs/custom-provider.md +5 -5
- package/docs/environment-variables.md +5 -1
- package/docs/extensions/api-reference.md +40 -19
- package/docs/extensions/authoring.md +1 -1
- package/docs/extensions/events.md +8 -8
- package/docs/extensions.md +2 -2
- package/docs/getting-started/installation.md +1 -2
- package/docs/providers.md +2 -2
- package/docs/quickstart.md +2 -1
- package/docs/reference/cli.md +3 -3
- package/docs/rpc/protocol.md +10 -4
- package/docs/sdk/reference.md +15 -13
- package/docs/sdk/web-server.md +5 -6
- package/docs/sdk.md +18 -1
- package/docs/session-format.md +7 -5
- package/docs/sessions.md +11 -2
- package/docs/settings.md +17 -2
- package/docs/storage.md +262 -1
- package/docs/usage.md +3 -2
- package/docs/workflows/api-reference.md +67 -11
- package/docs/workflows/operations.md +4 -2
- package/examples/extensions/bookmark.ts +2 -2
- package/examples/extensions/handoff.ts +2 -2
- package/examples/extensions/plan-mode/index.ts +15 -13
- package/examples/extensions/preset.ts +8 -8
- package/examples/extensions/session-name.ts +1 -1
- package/examples/extensions/snake.ts +3 -1
- package/examples/extensions/space-invaders.ts +3 -1
- package/examples/extensions/tic-tac-toe.ts +80 -80
- package/examples/sdk/11-sessions.ts +5 -5
- package/examples/sdk/13-session-runtime.ts +7 -7
- package/examples/sdk/README.md +1 -1
- package/npm-shrinkwrap.json +32 -32
- package/package.json +3 -3
- package/schemas/settings.schema.json +1 -22
- package/dist/builtin/workflows/builtin/chunk-h5fn47y5.js +0 -8
- package/dist/builtin/workflows/src/durable/journal/node-sqlite.d.ts +0 -20
|
@@ -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,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B,GAAG,SAAS,CAAC;QAC1E,UAAU,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,IAAI,CAAC,yBAAyB,KAAK,UAAU,CAAC,OAAO;YAAE,IAAI,CAAC,yBAAyB,GAAG,SAAS,CAAC;IACvG,CAAC;AACF,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAChD,uCAAuC;IACvC,gBAAgB;IAChB,kDAAkD;IAClD,4CAA4C;IAC5C,0BAA0B;IAC1B,4BAA4B;IAC5B,kBAAkB;CAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"@bastani/pi-ai/compat\";\nimport { isContextOverflow, isRecoverableLength } from \"@bastani/pi-ai/compat\";\nimport { emitSessionCompactFailed } from \"./agent-session-compaction.ts\";\nimport type { AgentSessionInternalSurface as AgentSession, AutoCompactionRunOutcome } from \"./agent-session-methods.ts\";\nimport {\n\ttype CompactionUrgency,\n\tcalculateContextTokens,\n\testimateContextTokens,\n\testimateProjectedContextTokens,\n\tshouldCompact,\n} from \"./compaction/index.ts\";\nimport { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from \"./openai-responses-payload-sanitizer.ts\";\nimport { type ContextEditEntry, getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\n\n/**\n * Upper bound on direct continuations after a response reaches its requested\n * output cap. Context-limited truncations use one compact-and-retry attempt\n * instead; this bound preserves Atomic's separate output-cap continuation.\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\n/** Create the settlement boundary for a regular automatic compaction run. */\nexport function createAutoCompactionCompletion(): {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n} {\n\tlet resolve!: () => void;\n\tconst promise = new Promise<void>((done) => {\n\t\tresolve = done;\n\t});\n\treturn { promise, resolve };\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(\n\tthis: AgentSession,\n\tassistantMessage: AssistantMessage,\n\tskipAbortedCheck = true,\n): Promise<void> {\n\tif (this._agentRunAbortRequested) return;\n\tif (this._pendingPostToolCompactionGuard) {\n\t\tconst { result } = this._pendingPostToolCompactionGuard;\n\t\tthis._pendingPostToolCompactionGuard = undefined;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult,\n\t\t\taborted: true,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t}\n\tif (\n\t\tthis._postToolCompactionPreflightError !== undefined &&\n\t\tassistantMessage.errorMessage === this._postToolCompactionPreflightError\n\t) {\n\t\tthis._postToolCompactionPreflightError = undefined;\n\t\treturn;\n\t}\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(this.model);\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\t// Skip overflow handling 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 !== undefined &&\n\t\tassistantMessage.provider === this.model.provider &&\n\t\tassistantMessage.model === this.model.id;\n\t// Usage and overflow signals belong to the request that produced this assistant.\n\t// A later context edit or compaction changes what the next request contains, so\n\t// only a projected, unedited assistant may drive usage-based decisions; an explicit\n\t// provider overflow error still recovers while its attempt is retained.\n\t// Guarded because fallback suites drive this function on a synthetic session.\n\tconst projectionAware =\n\t\ttypeof this.sessionManager?.buildSessionProjection === \"function\" &&\n\t\ttypeof this._findPersistedMessageEntryId === \"function\";\n\tconst currentProjection = projectionAware ? this.sessionManager.buildSessionProjection() : undefined;\n\tconst branch = projectionAware ? this.sessionManager.getBranch() : [];\n\tconst assistantEntryId = projectionAware ? this._findPersistedMessageEntryId(assistantMessage) : undefined;\n\tconst assistantIsProjected =\n\t\tassistantEntryId === undefined ||\n\t\tcurrentProjection?.entries.some(\n\t\t\t(entry) =>\n\t\t\t\tentry.sourceEntry.id === assistantEntryId && entry.messages.some((message) => message.role === \"assistant\"),\n\t\t) === true;\n\tconst assistantIndex = assistantEntryId ? branch.findIndex((entry) => entry.id === assistantEntryId) : -1;\n\tconst entriesAfterAssistant = assistantIndex >= 0 ? branch.slice(assistantIndex + 1) : [];\n\tconst hasPostAssistantContextEdit = entriesAfterAssistant.some((entry) => entry.type === \"context_edit\");\n\tconst latestAssistantEdit = entriesAfterAssistant\n\t\t.filter(\n\t\t\t(entry): entry is ContextEditEntry => entry.type === \"context_edit\" && entry.targetId === assistantEntryId,\n\t\t)\n\t\t.at(-1);\n\tconst assistantRetainedForExplicitRecovery =\n\t\tassistantEntryId === undefined ||\n\t\t(!entriesAfterAssistant.some((entry) => entry.type === \"compaction\") &&\n\t\t\tlatestAssistantEdit?.replacement !== null);\n\tconst assistantUsageMatchesProjection = assistantIsProjected && !hasPostAssistantContextEdit;\n\tconst explicitOverflow = assistantMessage.stopReason === \"error\" && isContextOverflow(assistantMessage);\n\tconst contextOverflow =\n\t\tsameModel &&\n\t\t((explicitOverflow && assistantRetainedForExplicitRecovery) ||\n\t\t\t(assistantUsageMatchesProjection && isContextOverflow(assistantMessage, contextWindow)));\n\tif (!settings.enabled) {\n\t\t// Compaction cannot recover this turn, so a configured fallback chain may\n\t\t// advance to a larger-context candidate instead of dead-ending.\n\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\treturn;\n\t}\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\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: Recoverable failure. Explicit/silent context overflow still uses\n\t// context metadata. A length stop below the model's original requested output\n\t// cap instead receives one compact-and-retry independent of context metadata.\n\t// This recovers a chat response; `truncated-range-recovery` separately parses\n\t// deletion records from a compaction planner response and is not involved here.\n\tconst desiredMaxOutput = this.model?.maxTokens ?? 0;\n\tconst recoverableLength =\n\t\tisLiveTurnCompletion &&\n\t\tsameModel &&\n\t\tassistantIsProjected &&\n\t\tisRecoverableLength(assistantMessage, desiredMaxOutput);\n\tif (contextOverflow || recoverableLength) {\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\tconst recoveryAttempted = contextOverflow\n\t\t\t? this._overflowRecoveryAttempted\n\t\t\t: this._recoverableLengthRecoveryAttempted;\n\t\tif (recoveryAttempted) {\n\t\t\t// One recovery of this kind has already been spent on this turn. A real\n\t\t\t// context overflow may now advance to a larger-context fallback; a\n\t\t\t// recoverable output truncation stops without claiming overflow.\n\t\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\t\tconst errorMessage = contextOverflow\n\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\t: \"Response truncation recovery stopped after one retry.\";\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\t...(contextOverflow ? { unresolvedOverflow: true } : {}),\n\t\t\t\terrorMessage,\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason: \"overflow\",\n\t\t\t\terrorMessage,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension: false,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = true;\n\t\telse this._recoverableLengthRecoveryAttempted = true;\n\t\tlet outcome: AutoCompactionRunOutcome;\n\t\ttry {\n\t\t\toutcome = contextOverflow\n\t\t\t\t? await this._runAutoCompaction(\"overflow\", willRetry)\n\t\t\t\t: await this._runAutoCompaction(\"overflow\", willRetry, \"recoverable\");\n\t\t} catch (error) {\n\t\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\t\tthrow error;\n\t\t}\n\t\tif (outcome === \"compacted\" || outcome === \"failed\") return;\n\t\t// No boundary means there is no context to free. Keep this recovery\n\t\t// attempt spent while its one direct continuation is pending, so another\n\t\t// below-cap stop cannot start a new compaction cycle.\n\t\tif (\n\t\t\trecoverableLength &&\n\t\t\toutcome === \"not_compactable\" &&\n\t\t\tthis._compactionAbortController === undefined &&\n\t\t\tthis._manualCompactionPromise === undefined\n\t\t) {\n\t\t\tthis._resumeAfterLengthTruncation();\n\t\t\treturn;\n\t\t}\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For errors or all-zero provider usage, estimate from message content.\n\tlet contextTokens = calculateContextTokens(assistantMessage.usage, assistantMessage.api);\n\tconst hasContextEdits =\n\t\tcurrentProjection?.entries.some((entry) => entry.sourceEntry.type === \"context_edit\") === true;\n\tif (currentProjection && hasContextEdits) {\n\t\t// Edited context invalidates usage captured before the edit; estimate the projection.\n\t\tcontextTokens = estimateProjectedContextTokens(currentProjection, branch).tokens;\n\t} else if (assistantMessage.stopReason === \"error\" || contextTokens === 0) {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\t// Without provider usage, estimate.tokens is the pure message-size estimate.\n\t\t// Only usage-backed estimates need the stale pre-compaction check.\n\t\tif (estimate.lastUsageIndex !== null) {\n\t\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\t\tif (\n\t\t\t\tcompactionBoundaryEntry &&\n\t\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t}\n\tif (shouldCompact(contextTokens, contextWindow, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage, desiredMaxOutput, isLiveTurnCompletion);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tconst errorMessage =\n\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\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});\n\t\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\terrorMessage,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\tfromExtension: false,\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 length stop that reached its requested output cap is not the\n\t// context-limited truncation recovered above. Preserve Atomic's bounded\n\t// direct-continuation policy for that distinct case.\n\tif (\n\t\tisLiveTurnCompletion &&\n\t\tisOutputCappedLengthStop(assistantMessage, desiredMaxOutput) &&\n\t\tthis._compactionAbortController === undefined &&\n\t\tthis._manualCompactionPromise === undefined\n\t) {\n\t\tthis._resumeAfterLengthTruncation();\n\t}\n}\n\nexport function isRetryWorthyLengthStop(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\nexport function isOutputCappedLengthStop(assistantMessage: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) && !isRecoverableLength(assistantMessage, desiredMaxOutput);\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\n\t\t? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param)\n\t\t: 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(\n\tassistantMessage: AssistantMessage,\n\tdesiredMaxOutput: number,\n\tisLiveTurnCompletion: boolean,\n): boolean {\n\treturn (\n\t\tisRetryWorthyOutputBudgetError(assistantMessage) ||\n\t\t(isLiveTurnCompletion && isOutputCappedLengthStop(assistantMessage, desiredMaxOutput))\n\t);\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\t// The attempt stays in raw session history; a durable context edit omits it from\n\t// the model projection so the continuation resumes from the preceding input.\n\tthis._omitTrailingAssistantAttempt(\n\t\t(assistant) => assistant.stopReason === \"error\" || assistant.stopReason === \"length\",\n\t);\n}\n\n/**\n * Internal: schedule a live post-event continuation after compaction_end listeners can flush queues.\n * The grace period preserves listener ordering. Queue-only probes wait for transient work to become\n * idle, while retry probes remain tied to the turn that scheduled them and are abandoned if another\n * turn owns the agent when the grace period ends.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(\n\tthis: AgentSession,\n\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tif (this._agentRunAbortRequested) return;\n\tconst token = this._postCompactionContinuationToken + 1;\n\tthis._postCompactionContinuationToken = token;\n\tconst fallbackScopeGeneration = this._fallbackOriginGeneration;\n\tlet pending: Promise<void>;\n\tpending = new Promise<void>((resolve) => {\n\t\tsetTimeout(() => {\n\t\t\tvoid (async () => {\n\t\t\t\tconst settleIfOwned = async (): Promise<void> => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tfallbackScopeGeneration === undefined ||\n\t\t\t\t\t\tthis._fallbackOriginGeneration !== fallbackScopeGeneration ||\n\t\t\t\t\t\ttypeof this._settleFallbackModelScope !== \"function\"\n\t\t\t\t\t)\n\t\t\t\t\t\treturn;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._settleFallbackModelScope();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// A listener must not strand the continuation waiter. The fallback\n\t\t\t\t\t\t// state was already settled before lifecycle notifications ran.\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tif (this._agentRunAbortRequested) return;\n\t\t\t\t\tif (willRetry) {\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} else {\n\t\t\t\t\t\tawait this.agent.waitForIdle();\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\tif (!this.agent.hasQueuedMessages()) {\n\t\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// A queued message starts the next user turn. Settle before Agent\n\t\t\t\t\t\t// snapshots the next request's model.\n\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this._pendingPostCompactionContinuation !== pending) return;\n\t\t\t\t\t// Clear this probe before entering the next run. Its promise is\n\t\t\t\t\t// still awaited by _awaitPendingPostCompactionContinuation, but\n\t\t\t\t\t// the nested agent_end must be free to schedule a new probe.\n\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\tif (willRetry && this._pendingPostCompactionContinuation === undefined) {\n\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tif (this._pendingPostCompactionContinuation === pending) {\n\t\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t})();\n\t\t}, 100);\n\t});\n\tthis._pendingPostCompactionContinuation = pending;\n}\n\nexport async function _awaitPendingPostCompactionContinuation(this: AgentSession): Promise<void> {\n\t// A continuation can schedule another probe (for example a second output-cap\n\t// stop). Keep the owning prompt alive until the whole automatic chain drains.\n\twhile (this._pendingPostCompactionContinuation !== undefined) {\n\t\tawait this._pendingPostCompactionContinuation;\n\t}\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 reached its requested output cap when the\n * context does not warrant compaction. Bounded so a model that repeatedly\n * stops at that 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/**\n * Whether an overflow turn is now unrecoverable by compaction, recording it on\n * the session so a configured fallback chain may advance to another candidate.\n */\nfunction overflowUnresolved(this: AgentSession, loadBearing: boolean, aborted = false): boolean | undefined {\n\tif (!loadBearing || aborted) return undefined;\n\tthis._contextOverflowUnresolved = true;\n\treturn true;\n}\n\nexport function hasPendingManualCompactionTakeover(this: AgentSession): boolean {\n\treturn this._compactionReason === \"manual\" && this._compactionAbortController !== undefined;\n}\n\nexport async function _runAutoCompaction(\n\tthis: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n\turgency: CompactionUrgency = reason === \"overflow\" ? \"load_bearing\" : \"recoverable\",\n): Promise<AutoCompactionRunOutcome> {\n\tif (\n\t\tthis._compactionAbortController !== undefined ||\n\t\tthis._manualCompactionPromise !== undefined ||\n\t\tthis._autoCompactionAbortController !== undefined\n\t)\n\t\treturn \"deferred\";\n\n\tconst controller = new AbortController();\n\tconst completion = createAutoCompactionCompletion();\n\tthis._autoCompactionAbortController = controller;\n\tthis._autoCompactionCompletion = completion.promise;\n\tthis._compactionReason = reason;\n\tlet fromExtension = false;\n\ttry {\n\t\tthis._emit({ type: \"compaction_start\", reason });\n\t} catch (error) {\n\t\t// A throwing start listener still propagates, matching current behavior,\n\t\t// but must not leave ownership published with no owner running.\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t\tthrow error;\n\t}\n\n\ttry {\n\t\tcontroller.signal.throwIfAborted();\n\t\tif (!this.model) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\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.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension: false,\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t\t}\n\n\t\t// Resolve auth only after extension hooks have had an opportunity to cancel\n\t\t// compaction or provide compacted text, so local extension compaction does not\n\t\t// require provider credentials. Missing auth then fails model-driven compaction\n\t\t// before persistence or continuation, matching other provider-call failures.\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate) => {\n\t\t\t\tconst authResult = await this._getRequiredRequestAuth(candidate, controller.signal);\n\t\t\t\treturn authResult.apiKey || authResult.headers ? authResult : undefined;\n\t\t\t},\n\t\t\tabortController: controller,\n\t\t\tbackupLabel: urgency === \"load_bearing\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t\turgency,\n\t\t\tonCompactionSource: (value) => {\n\t\t\t\tfromExtension = value;\n\t\t\t},\n\t\t\t// Only an actual context overflow proved the context cannot fit. A\n\t\t\t// recoverable length stop must never reach the fresh-context fallback.\n\t\t\t...(urgency === \"load_bearing\" ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\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.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension,\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"not_compactable\";\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult,\n\t\t\taborted: false,\n\t\t\twillRetry,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t\tif (!hasPendingManualCompactionTakeover.call(this)) {\n\t\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t\t}\n\t\treturn \"compacted\";\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted = controller.signal.aborted;\n\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\tconst formattedErrorMessage = aborted\n\t\t\t? undefined\n\t\t\t: reason === \"overflow\"\n\t\t\t\t? urgency === \"recoverable\"\n\t\t\t\t\t? `Response truncation recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t: `Auto-compaction failed: ${errorMessage}`;\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.call(this, urgency === \"load_bearing\", aborted),\n\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\terrorMessage: formattedErrorMessage,\n\t\t});\n\t\tawait emitSessionCompactFailed(this, {\n\t\t\treason,\n\t\t\terrorMessage: formattedErrorMessage,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tfromExtension,\n\t\t});\n\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t} finally {\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingPostCompactionContinuation,\n\t_checkCompaction,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_resumeAfterLengthTruncation,\n\t_runAutoCompaction,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-auto-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,wBAAwB,EAAE,MAAM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IAAI,CAAC,yBAAyB,KAAK,UAAU,CAAC,OAAO;YAAE,IAAI,CAAC,yBAAyB,GAAG,SAAS,CAAC;IACvG,CAAC;AACF,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAChD,uCAAuC;IACvC,gBAAgB;IAChB,kDAAkD;IAClD,4CAA4C;IAC5C,0BAA0B;IAC1B,4BAA4B;IAC5B,kBAAkB;CAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"@bastani/pi-ai/compat\";\nimport { isContextOverflow, isRecoverableLength } from \"@bastani/pi-ai/compat\";\nimport { emitSessionCompactFailed } from \"./agent-session-compaction.ts\";\nimport type { AgentSessionInternalSurface as AgentSession, AutoCompactionRunOutcome } from \"./agent-session-methods.ts\";\nimport {\n\ttype CompactionUrgency,\n\tcalculateContextTokens,\n\testimateContextTokens,\n\testimateProjectedContextTokens,\n\tshouldCompact,\n} from \"./compaction/index.ts\";\nimport { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from \"./openai-responses-payload-sanitizer.ts\";\nimport { type ContextEditEntry, getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\n\n/**\n * Upper bound on direct continuations after a response reaches its requested\n * output cap. Context-limited truncations use one compact-and-retry attempt\n * instead; this bound preserves Atomic's separate output-cap continuation.\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\n/** Create the settlement boundary for a regular automatic compaction run. */\nexport function createAutoCompactionCompletion(): {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n} {\n\tlet resolve!: () => void;\n\tconst promise = new Promise<void>((done) => {\n\t\tresolve = done;\n\t});\n\treturn { promise, resolve };\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(\n\tthis: AgentSession,\n\tassistantMessage: AssistantMessage,\n\tskipAbortedCheck = true,\n): Promise<void> {\n\tif (this._agentRunAbortRequested) return;\n\tif (this._pendingPostToolCompactionGuard) {\n\t\tconst { result } = this._pendingPostToolCompactionGuard;\n\t\tthis._pendingPostToolCompactionGuard = undefined;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult,\n\t\t\taborted: true,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t}\n\tif (\n\t\tthis._postToolCompactionPreflightError !== undefined &&\n\t\tassistantMessage.errorMessage === this._postToolCompactionPreflightError\n\t) {\n\t\tthis._postToolCompactionPreflightError = undefined;\n\t\treturn;\n\t}\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(this.model);\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\t// Skip overflow handling 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 !== undefined &&\n\t\tassistantMessage.provider === this.model.provider &&\n\t\tassistantMessage.model === this.model.id;\n\t// Usage and overflow signals belong to the request that produced this assistant.\n\t// A later context edit or compaction changes what the next request contains, so\n\t// only a projected, unedited assistant may drive usage-based decisions; an explicit\n\t// provider overflow error still recovers while its attempt is retained.\n\t// Guarded because fallback suites drive this function on a synthetic session.\n\tconst projectionAware =\n\t\ttypeof this.sessionManager?.buildSessionProjection === \"function\" &&\n\t\ttypeof this._findPersistedMessageEntryId === \"function\";\n\tconst currentProjection = projectionAware ? this.sessionManager.buildSessionProjection() : undefined;\n\tconst branch = projectionAware ? this.sessionManager.getBranch() : [];\n\tconst assistantEntryId = projectionAware ? this._findPersistedMessageEntryId(assistantMessage) : undefined;\n\tconst assistantIsProjected =\n\t\tassistantEntryId === undefined ||\n\t\tcurrentProjection?.entries.some(\n\t\t\t(entry) =>\n\t\t\t\tentry.sourceEntry.id === assistantEntryId && entry.messages.some((message) => message.role === \"assistant\"),\n\t\t) === true;\n\tconst assistantIndex = assistantEntryId ? branch.findIndex((entry) => entry.id === assistantEntryId) : -1;\n\tconst entriesAfterAssistant = assistantIndex >= 0 ? branch.slice(assistantIndex + 1) : [];\n\tconst hasPostAssistantContextEdit = entriesAfterAssistant.some((entry) => entry.type === \"context_edit\");\n\tconst latestAssistantEdit = entriesAfterAssistant\n\t\t.filter(\n\t\t\t(entry): entry is ContextEditEntry => entry.type === \"context_edit\" && entry.targetId === assistantEntryId,\n\t\t)\n\t\t.at(-1);\n\tconst assistantRetainedForExplicitRecovery =\n\t\tassistantEntryId === undefined ||\n\t\t(!entriesAfterAssistant.some((entry) => entry.type === \"compaction\") &&\n\t\t\tlatestAssistantEdit?.replacement !== null);\n\tconst assistantUsageMatchesProjection = assistantIsProjected && !hasPostAssistantContextEdit;\n\tconst explicitOverflow = assistantMessage.stopReason === \"error\" && isContextOverflow(assistantMessage);\n\tconst contextOverflow =\n\t\tsameModel &&\n\t\t((explicitOverflow && assistantRetainedForExplicitRecovery) ||\n\t\t\t(assistantUsageMatchesProjection && isContextOverflow(assistantMessage, contextWindow)));\n\tif (!settings.enabled) {\n\t\t// Compaction cannot recover this turn, so a configured fallback chain may\n\t\t// advance to a larger-context candidate instead of dead-ending.\n\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\treturn;\n\t}\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\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: Recoverable failure. Explicit/silent context overflow still uses\n\t// context metadata. A length stop below the model's original requested output\n\t// cap instead receives one compact-and-retry independent of context metadata.\n\t// This recovers a chat response; `truncated-range-recovery` separately parses\n\t// deletion records from a compaction planner response and is not involved here.\n\tconst desiredMaxOutput = this.model?.maxTokens ?? 0;\n\tconst recoverableLength =\n\t\tisLiveTurnCompletion &&\n\t\tsameModel &&\n\t\tassistantIsProjected &&\n\t\tisRecoverableLength(assistantMessage, desiredMaxOutput);\n\tif (contextOverflow || recoverableLength) {\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\tconst recoveryAttempted = contextOverflow\n\t\t\t? this._overflowRecoveryAttempted\n\t\t\t: this._recoverableLengthRecoveryAttempted;\n\t\tif (recoveryAttempted) {\n\t\t\t// One recovery of this kind has already been spent on this turn. A real\n\t\t\t// context overflow may now advance to a larger-context fallback; a\n\t\t\t// recoverable output truncation stops without claiming overflow.\n\t\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\t\tconst errorMessage = contextOverflow\n\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\t: \"Response truncation recovery stopped after one retry.\";\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\t...(contextOverflow ? { unresolvedOverflow: true } : {}),\n\t\t\t\terrorMessage,\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason: \"overflow\",\n\t\t\t\terrorMessage,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension: false,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = true;\n\t\telse this._recoverableLengthRecoveryAttempted = true;\n\t\tlet outcome: AutoCompactionRunOutcome;\n\t\ttry {\n\t\t\toutcome = contextOverflow\n\t\t\t\t? await this._runAutoCompaction(\"overflow\", willRetry)\n\t\t\t\t: await this._runAutoCompaction(\"overflow\", willRetry, \"recoverable\");\n\t\t} catch (error) {\n\t\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\t\tthrow error;\n\t\t}\n\t\tif (outcome === \"compacted\" || outcome === \"failed\") return;\n\t\t// No boundary means there is no context to free. Keep this recovery\n\t\t// attempt spent while its one direct continuation is pending, so another\n\t\t// below-cap stop cannot start a new compaction cycle.\n\t\tif (\n\t\t\trecoverableLength &&\n\t\t\toutcome === \"not_compactable\" &&\n\t\t\tthis._compactionAbortController === undefined &&\n\t\t\tthis._manualCompactionPromise === undefined\n\t\t) {\n\t\t\tthis._resumeAfterLengthTruncation();\n\t\t\treturn;\n\t\t}\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For errors or all-zero provider usage, estimate from message content.\n\tlet contextTokens = calculateContextTokens(assistantMessage.usage, assistantMessage.api);\n\tconst hasContextEdits =\n\t\tcurrentProjection?.entries.some((entry) => entry.sourceEntry.type === \"context_edit\") === true;\n\tif (currentProjection && hasContextEdits) {\n\t\t// Edited context invalidates usage captured before the edit; estimate the projection.\n\t\tcontextTokens = estimateProjectedContextTokens(currentProjection, branch).tokens;\n\t} else if (assistantMessage.stopReason === \"error\" || contextTokens === 0) {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\t// Without provider usage, estimate.tokens is the pure message-size estimate.\n\t\t// Only usage-backed estimates need the stale pre-compaction check.\n\t\tif (estimate.lastUsageIndex !== null) {\n\t\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\t\tif (\n\t\t\t\tcompactionBoundaryEntry &&\n\t\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t}\n\tif (shouldCompact(contextTokens, contextWindow, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage, desiredMaxOutput, isLiveTurnCompletion);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tconst errorMessage =\n\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\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});\n\t\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\terrorMessage,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\tfromExtension: false,\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 length stop that reached its requested output cap is not the\n\t// context-limited truncation recovered above. Preserve Atomic's bounded\n\t// direct-continuation policy for that distinct case.\n\tif (\n\t\tisLiveTurnCompletion &&\n\t\tisOutputCappedLengthStop(assistantMessage, desiredMaxOutput) &&\n\t\tthis._compactionAbortController === undefined &&\n\t\tthis._manualCompactionPromise === undefined\n\t) {\n\t\tthis._resumeAfterLengthTruncation();\n\t}\n}\n\nexport function isRetryWorthyLengthStop(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\nexport function isOutputCappedLengthStop(assistantMessage: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) && !isRecoverableLength(assistantMessage, desiredMaxOutput);\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\n\t\t? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param)\n\t\t: 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(\n\tassistantMessage: AssistantMessage,\n\tdesiredMaxOutput: number,\n\tisLiveTurnCompletion: boolean,\n): boolean {\n\treturn (\n\t\tisRetryWorthyOutputBudgetError(assistantMessage) ||\n\t\t(isLiveTurnCompletion && isOutputCappedLengthStop(assistantMessage, desiredMaxOutput))\n\t);\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport async function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): Promise<void> {\n\t// The attempt stays in raw session history; a durable context edit omits it from\n\t// the model projection so the continuation resumes from the preceding input.\n\tawait this._omitTrailingAssistantAttempt(\n\t\t(assistant) => assistant.stopReason === \"error\" || assistant.stopReason === \"length\",\n\t);\n}\n\n/**\n * Internal: schedule a live post-event continuation after compaction_end listeners can flush queues.\n * The grace period preserves listener ordering. Queue-only probes wait for transient work to become\n * idle, while retry probes remain tied to the turn that scheduled them and are abandoned if another\n * turn owns the agent when the grace period ends.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(\n\tthis: AgentSession,\n\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tif (this._agentRunAbortRequested) return;\n\tconst token = this._postCompactionContinuationToken + 1;\n\tthis._postCompactionContinuationToken = token;\n\tconst fallbackScopeGeneration = this._fallbackOriginGeneration;\n\tlet pending: Promise<void>;\n\tpending = new Promise<void>((resolve) => {\n\t\tsetTimeout(() => {\n\t\t\tvoid (async () => {\n\t\t\t\tconst settleIfOwned = async (): Promise<void> => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tfallbackScopeGeneration === undefined ||\n\t\t\t\t\t\tthis._fallbackOriginGeneration !== fallbackScopeGeneration ||\n\t\t\t\t\t\ttypeof this._settleFallbackModelScope !== \"function\"\n\t\t\t\t\t)\n\t\t\t\t\t\treturn;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._settleFallbackModelScope();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// A listener must not strand the continuation waiter. The fallback\n\t\t\t\t\t\t// state was already settled before lifecycle notifications ran.\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tif (this._agentRunAbortRequested) return;\n\t\t\t\t\tif (willRetry) {\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} else {\n\t\t\t\t\t\tawait this.agent.waitForIdle();\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\tif (!this.agent.hasQueuedMessages()) {\n\t\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// A queued message starts the next user turn. Settle before Agent\n\t\t\t\t\t\t// snapshots the next request's model.\n\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this._pendingPostCompactionContinuation !== pending) return;\n\t\t\t\t\t// Clear this probe before entering the next run. Its promise is\n\t\t\t\t\t// still awaited by _awaitPendingPostCompactionContinuation, but\n\t\t\t\t\t// the nested agent_end must be free to schedule a new probe.\n\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\tif (willRetry && this._pendingPostCompactionContinuation === undefined) {\n\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tif (this._pendingPostCompactionContinuation === pending) {\n\t\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t})();\n\t\t}, 100);\n\t});\n\tthis._pendingPostCompactionContinuation = pending;\n}\n\nexport async function _awaitPendingPostCompactionContinuation(this: AgentSession): Promise<void> {\n\t// A continuation can schedule another probe (for example a second output-cap\n\t// stop). Keep the owning prompt alive until the whole automatic chain drains.\n\twhile (this._pendingPostCompactionContinuation !== undefined) {\n\t\tawait this._pendingPostCompactionContinuation;\n\t}\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 reached its requested output cap when the\n * context does not warrant compaction. Bounded so a model that repeatedly\n * stops at that 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/**\n * Whether an overflow turn is now unrecoverable by compaction, recording it on\n * the session so a configured fallback chain may advance to another candidate.\n */\nfunction overflowUnresolved(this: AgentSession, loadBearing: boolean, aborted = false): boolean | undefined {\n\tif (!loadBearing || aborted) return undefined;\n\tthis._contextOverflowUnresolved = true;\n\treturn true;\n}\n\nexport function hasPendingManualCompactionTakeover(this: AgentSession): boolean {\n\treturn this._compactionReason === \"manual\" && this._compactionAbortController !== undefined;\n}\n\nexport async function _runAutoCompaction(\n\tthis: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n\turgency: CompactionUrgency = reason === \"overflow\" ? \"load_bearing\" : \"recoverable\",\n): Promise<AutoCompactionRunOutcome> {\n\tif (\n\t\tthis._compactionAbortController !== undefined ||\n\t\tthis._manualCompactionPromise !== undefined ||\n\t\tthis._autoCompactionAbortController !== undefined\n\t)\n\t\treturn \"deferred\";\n\n\tconst controller = new AbortController();\n\tconst completion = createAutoCompactionCompletion();\n\tthis._autoCompactionAbortController = controller;\n\tthis._autoCompactionCompletion = completion.promise;\n\tthis._compactionReason = reason;\n\tlet fromExtension = false;\n\ttry {\n\t\tthis._emit({ type: \"compaction_start\", reason });\n\t} catch (error) {\n\t\t// A throwing start listener still propagates, matching current behavior,\n\t\t// but must not leave ownership published with no owner running.\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t\tthrow error;\n\t}\n\n\ttry {\n\t\tcontroller.signal.throwIfAborted();\n\t\tif (!this.model) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\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.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension: false,\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t\t}\n\n\t\t// Resolve auth only after extension hooks have had an opportunity to cancel\n\t\t// compaction or provide compacted text, so local extension compaction does not\n\t\t// require provider credentials. Missing auth then fails model-driven compaction\n\t\t// before persistence or continuation, matching other provider-call failures.\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate) => {\n\t\t\t\tconst authResult = await this._getRequiredRequestAuth(candidate, controller.signal);\n\t\t\t\treturn authResult.apiKey || authResult.headers ? authResult : undefined;\n\t\t\t},\n\t\t\tabortController: controller,\n\t\t\tbackupLabel: urgency === \"load_bearing\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t\turgency,\n\t\t\tonCompactionSource: (value) => {\n\t\t\t\tfromExtension = value;\n\t\t\t},\n\t\t\t// Only an actual context overflow proved the context cannot fit. A\n\t\t\t// recoverable length stop must never reach the fresh-context fallback.\n\t\t\t...(urgency === \"load_bearing\" ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\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.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension,\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"not_compactable\";\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult,\n\t\t\taborted: false,\n\t\t\twillRetry,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t\tif (!hasPendingManualCompactionTakeover.call(this)) {\n\t\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t\t}\n\t\treturn \"compacted\";\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted = controller.signal.aborted;\n\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\tconst formattedErrorMessage = aborted\n\t\t\t? undefined\n\t\t\t: reason === \"overflow\"\n\t\t\t\t? urgency === \"recoverable\"\n\t\t\t\t\t? `Response truncation recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t: `Auto-compaction failed: ${errorMessage}`;\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.call(this, urgency === \"load_bearing\", aborted),\n\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\terrorMessage: formattedErrorMessage,\n\t\t});\n\t\tawait emitSessionCompactFailed(this, {\n\t\t\treason,\n\t\t\terrorMessage: formattedErrorMessage,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tfromExtension,\n\t\t});\n\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t} finally {\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingPostCompactionContinuation,\n\t_checkCompaction,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_resumeAfterLengthTruncation,\n\t_runAutoCompaction,\n};\n"]}
|
|
@@ -18,11 +18,10 @@ export declare function recordBashResult(this: AgentSession, command: string, re
|
|
|
18
18
|
excludeFromContext?: boolean;
|
|
19
19
|
persist?: boolean;
|
|
20
20
|
defer?: boolean;
|
|
21
|
-
}): void
|
|
21
|
+
}): Promise<void>;
|
|
22
22
|
/** Cancel one correlated bash request, or all active requests for legacy callers. */
|
|
23
23
|
export declare function abortBash(this: AgentSession, id?: string): void;
|
|
24
|
-
|
|
25
|
-
export declare function _flushPendingBashMessages(this: AgentSession): void;
|
|
24
|
+
export declare function _flushPendingBashMessages(this: AgentSession): Promise<void>;
|
|
26
25
|
/**
|
|
27
26
|
* Set a display name for the current session.
|
|
28
27
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-bash.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-bash.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC9F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAIrD,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,iBAAiB,EAA6B,MAAM,iBAAiB,CAAC;AAKzG,wBAAgB,WAAW,CAAC,IAAI,EAAE,YAAY,EAAE,GAAG,IAAI,EAAE,UAAU,CAAC,OAAO,oBAAoB,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,CAIrH;AAED,iBAAe,oBAAoB,CAClC,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,iBAAiB,KAAK,IAAI,EAC7D,OAAO,CAAC,EAAE;IACT,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,UAAU,CAAC,EAAE,cAAc,CAAC;IAC5B,GAAG,CAAC,EAAE,OAAO,CAAC;IACd,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,YAAY,CAAC,EAAE,OAAO,CAAC;CACvB,GACC,OAAO,CAAC,UAAU,CAAC,CAyCrB;AAED;;;GAGG;AAEH,
|
|
1
|
+
{"version":3,"file":"agent-session-bash.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-bash.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BA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,MAAM,uBAAuB;;;;;CAKnC,CAAC"}
|
|
@@ -39,7 +39,7 @@ async function executeBashOperation(command, onChunk, options) {
|
|
|
39
39
|
sessionTempDir: resolveSessionTempDirPath(this.sessionManager.getSessionId()),
|
|
40
40
|
});
|
|
41
41
|
if (options?.recordResult !== false)
|
|
42
|
-
this.recordBashResult(command, result, options);
|
|
42
|
+
await this.recordBashResult(command, result, options);
|
|
43
43
|
return result;
|
|
44
44
|
}
|
|
45
45
|
finally {
|
|
@@ -52,7 +52,7 @@ async function executeBashOperation(command, onChunk, options) {
|
|
|
52
52
|
* Record a bash execution result in session history.
|
|
53
53
|
* Used by executeBash and by extensions that handle bash execution themselves.
|
|
54
54
|
*/
|
|
55
|
-
export function recordBashResult(command, result, options) {
|
|
55
|
+
export async function recordBashResult(command, result, options) {
|
|
56
56
|
const bashMessage = {
|
|
57
57
|
role: "bashExecution",
|
|
58
58
|
command,
|
|
@@ -71,7 +71,7 @@ export function recordBashResult(command, result, options) {
|
|
|
71
71
|
}
|
|
72
72
|
else if (options?.persist !== false) {
|
|
73
73
|
// Persist first, then refresh the finalized context from the canonical projection.
|
|
74
|
-
this.sessionManager.appendMessage(bashMessage);
|
|
74
|
+
await this.sessionManager.appendMessage(bashMessage);
|
|
75
75
|
this._refreshFinalizedContext();
|
|
76
76
|
}
|
|
77
77
|
else {
|
|
@@ -95,15 +95,23 @@ export function abortBash(id) {
|
|
|
95
95
|
controller.abort();
|
|
96
96
|
}
|
|
97
97
|
}
|
|
98
|
-
|
|
98
|
+
const pendingBashDrains = new WeakMap();
|
|
99
99
|
export function _flushPendingBashMessages() {
|
|
100
|
+
const pending = pendingBashDrains.get(this);
|
|
101
|
+
if (pending)
|
|
102
|
+
return pending;
|
|
100
103
|
if (this._pendingBashMessages.length === 0)
|
|
101
|
-
return;
|
|
102
|
-
|
|
103
|
-
this.
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
104
|
+
return Promise.resolve();
|
|
105
|
+
const drain = (async () => {
|
|
106
|
+
while (this._pendingBashMessages.length > 0) {
|
|
107
|
+
await this.sessionManager.appendMessage(this._pendingBashMessages[0]);
|
|
108
|
+
this._pendingBashMessages.shift();
|
|
109
|
+
this._refreshFinalizedContext();
|
|
110
|
+
}
|
|
111
|
+
})();
|
|
112
|
+
pendingBashDrains.set(this, drain);
|
|
113
|
+
void drain.then(() => pendingBashDrains.delete(this), () => pendingBashDrains.delete(this));
|
|
114
|
+
return drain;
|
|
107
115
|
}
|
|
108
116
|
// =========================================================================
|
|
109
117
|
// Session Management
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-bash.js","sourceRoot":"","sources":["../../src/core/agent-session-bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAE/D,OAAO,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AACzF,OAAO,EAA+C,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AACzG,OAAO,EAAE,2BAA2B,EAAE,8BAA8B,EAAE,MAAM,qCAAqC,CAAC;AAClH,OAAO,EAAE,+BAA+B,EAAE,MAAM,uBAAuB,CAAC;AACxE,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AAExE,MAAM,UAAU,WAAW,CAAqB,GAAG,IAA6C;IAC/F,IAAI,IAAI,CAAC,SAAS,IAAI,wBAAwB,CAAC,GAAG,CAAC,IAAI,CAAC;QACvD,OAAO,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,mBAAmB,CAAC,EAAE,EAAE,IAAI,EAAE,eAAe,EAAE,CAAC,CAAC,CAAC;IACjG,OAAO,gBAAgB,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,oBAAoB,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,CAAC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oBAAoB,GAAG,EAAE,CAAC;IAC/B,IAAI,CAAC,wBAAwB,EAAE,CAAC;AACjC,CAAC;AAED,4EAA4E;AAC5E,qBAAqB;AACrB,4EAA4E;AAE5E;;GAEG;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACtC,WAAW;IACX,gBAAgB;IAChB,SAAS;IACT,yBAAyB;CACzB,CAAC","sourcesContent":["import { getShellEnv } from \"../utils/shell.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { BashResult } from \"./bash-executor.ts\";\nimport { executeBashWithOperations } from \"./bash-executor.ts\";\nimport type { BashExecutionMessage } from \"./messages.ts\";\nimport { sessionGenerationClosing, trackSessionWork } from \"./session-lifecycle-work.ts\";\nimport { type BashOperations, type BashOutputChannel, createLocalBashOperations } from \"./tools/bash.js\";\nimport { applyBashSessionEnvironment, snapshotBashSessionEnvironment } from \"./tools/bash-session-environment.ts\";\nimport { createLocalPowerShellOperations } from \"./tools/powershell.ts\";\nimport { resolveSessionTempDirPath } from \"./tools/session-temp-dir.ts\";\n\nexport function executeBash(this: AgentSession, ...args: Parameters<typeof executeBashOperation>): Promise<BashResult> {\n\tif (this._disposed || sessionGenerationClosing.has(this))\n\t\treturn Promise.reject(Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" }));\n\treturn trackSessionWork(this, () => executeBashOperation.call(this, ...args));\n}\n\nasync function executeBashOperation(\n\tthis: AgentSession,\n\tcommand: string,\n\tonChunk?: (chunk: string, channel: BashOutputChannel) => void,\n\toptions?: {\n\t\texcludeFromContext?: boolean;\n\t\tid?: string;\n\t\toperations?: BashOperations;\n\t\tpty?: boolean;\n\t\temitEvent?: boolean;\n\t\trecordResult?: boolean;\n\t},\n): Promise<BashResult> {\n\tconst requestKey = options?.id ?? Symbol(\"bash-request\");\n\tconst abortController = new AbortController();\n\tconst controllers = this._bashAbortControllers.get(requestKey) ?? new Set<AbortController>();\n\tcontrollers.add(abortController);\n\tthis._bashAbortControllers.set(requestKey, controllers);\n\t// Apply command prefix if configured (e.g., \"shopt -s expand_aliases\" for alias support)\n\tconst prefix = this.settingsManager.getShellCommandPrefix();\n\tconst shellPath = this.settingsManager.getShellPath();\n\tconst resolvedCommand = prefix ? `${prefix}\\n${command}` : command;\n\tconst env = { ...getShellEnv() };\n\tapplyBashSessionEnvironment(env, snapshotBashSessionEnvironment(this, true));\n\n\ttry {\n\t\tconst result = await executeBashWithOperations(\n\t\t\tresolvedCommand,\n\t\t\tthis.sessionManager.getCwd(),\n\t\t\toptions?.operations ??\n\t\t\t\t(process.platform === \"win32\"\n\t\t\t\t\t? createLocalPowerShellOperations()\n\t\t\t\t\t: createLocalBashOperations({ shellPath })),\n\t\t\t{\n\t\t\t\tonChunk: (delta, channel) => {\n\t\t\t\t\tonChunk?.(delta, channel);\n\t\t\t\t\tif (options?.emitEvent !== false) {\n\t\t\t\t\t\tthis._emit({ type: \"bash_execution_update\", id: options?.id, channel, delta });\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tsignal: abortController.signal,\n\t\t\t\tenv,\n\t\t\t\tpty: options?.pty,\n\t\t\t\tsessionTempDir: resolveSessionTempDirPath(this.sessionManager.getSessionId()),\n\t\t\t},\n\t\t);\n\n\t\tif (options?.recordResult !== false) this.recordBashResult(command, result, options);\n\t\treturn result;\n\t} finally {\n\t\tcontrollers.delete(abortController);\n\t\tif (controllers.size === 0) this._bashAbortControllers.delete(requestKey);\n\t}\n}\n\n/**\n * Record a bash execution result in session history.\n * Used by executeBash and by extensions that handle bash execution themselves.\n */\n\nexport function recordBashResult(\n\tthis: AgentSession,\n\tcommand: string,\n\tresult: BashResult,\n\toptions?: { excludeFromContext?: boolean; persist?: boolean; defer?: boolean },\n): void {\n\tconst bashMessage: BashExecutionMessage = {\n\t\trole: \"bashExecution\",\n\t\tcommand,\n\t\toutput: result.output,\n\t\texitCode: result.exitCode,\n\t\tcancelled: result.cancelled,\n\t\ttruncated: result.truncated,\n\t\tfullOutputPath: result.fullOutputPath,\n\t\ttimestamp: Date.now(),\n\t\texcludeFromContext: options?.excludeFromContext,\n\t};\n\n\t// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering\n\tif (this.isStreaming && options?.defer !== false) {\n\t\t// Queue for later - will be flushed on agent_end\n\t\tthis._pendingBashMessages.push(bashMessage);\n\t} else if (options?.persist !== false) {\n\t\t// Persist first, then refresh the finalized context from the canonical projection.\n\t\tthis.sessionManager.appendMessage(bashMessage);\n\t\tthis._refreshFinalizedContext();\n\t} else {\n\t\t// Avoid writing a source-owned result into a shared manager that an\n\t\t// in-memory fork changed while this execution was active. The result stays\n\t\t// visible to this run only, so it must be added to agent state directly.\n\t\tthis.agent.state.messages.push(bashMessage);\n\t}\n}\n\n/** Cancel one correlated bash request, or all active requests for legacy callers. */\nexport function abortBash(this: AgentSession, id?: string): void {\n\tif (id !== undefined) {\n\t\tfor (const controller of [...(this._bashAbortControllers.get(id) ?? [])]) controller.abort();\n\t\treturn;\n\t}\n\t// Snapshot first: aborting settles owners, and a listener that removes its own\n\t// entry must not shorten the cancellation sweep.\n\tfor (const controllers of [...this._bashAbortControllers.values()]) {\n\t\tfor (const controller of [...controllers]) controller.abort();\n\t}\n}\n\n/** Whether a bash command is currently running */\n\nexport function _flushPendingBashMessages(this: AgentSession): void {\n\tif (this._pendingBashMessages.length === 0) return;\n\n\tfor (const bashMessage of this._pendingBashMessages) {\n\t\tthis.sessionManager.appendMessage(bashMessage);\n\t}\n\tthis._pendingBashMessages = [];\n\tthis._refreshFinalizedContext();\n}\n\n// =========================================================================\n// Session Management\n// =========================================================================\n\n/**\n * Set a display name for the current session.\n */\n\nexport const agentSessionBashMethods = {\n\texecuteBash,\n\trecordBashResult,\n\tabortBash,\n\t_flushPendingBashMessages,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-bash.js","sourceRoot":"","sources":["../../src/core/agent-session-bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,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IAAI,CACd,GAAG,EAAE,CAAC,iBAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,EACpC,GAAG,EAAE,CAAC,iBAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,CACpC,CAAC;IACF,OAAO,KAAK,CAAC;AACd,CAAC;AAED,4EAA4E;AAC5E,qBAAqB;AACrB,4EAA4E;AAE5E;;GAEG;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACtC,WAAW;IACX,gBAAgB;IAChB,SAAS;IACT,yBAAyB;CACzB,CAAC","sourcesContent":["import { getShellEnv } from \"../utils/shell.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { BashResult } from \"./bash-executor.ts\";\nimport { executeBashWithOperations } from \"./bash-executor.ts\";\nimport type { BashExecutionMessage } from \"./messages.ts\";\nimport { sessionGenerationClosing, trackSessionWork } from \"./session-lifecycle-work.ts\";\nimport { type BashOperations, type BashOutputChannel, createLocalBashOperations } from \"./tools/bash.js\";\nimport { applyBashSessionEnvironment, snapshotBashSessionEnvironment } from \"./tools/bash-session-environment.ts\";\nimport { createLocalPowerShellOperations } from \"./tools/powershell.ts\";\nimport { resolveSessionTempDirPath } from \"./tools/session-temp-dir.ts\";\n\nexport function executeBash(this: AgentSession, ...args: Parameters<typeof executeBashOperation>): Promise<BashResult> {\n\tif (this._disposed || sessionGenerationClosing.has(this))\n\t\treturn Promise.reject(Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" }));\n\treturn trackSessionWork(this, () => executeBashOperation.call(this, ...args));\n}\n\nasync function executeBashOperation(\n\tthis: AgentSession,\n\tcommand: string,\n\tonChunk?: (chunk: string, channel: BashOutputChannel) => void,\n\toptions?: {\n\t\texcludeFromContext?: boolean;\n\t\tid?: string;\n\t\toperations?: BashOperations;\n\t\tpty?: boolean;\n\t\temitEvent?: boolean;\n\t\trecordResult?: boolean;\n\t},\n): Promise<BashResult> {\n\tconst requestKey = options?.id ?? Symbol(\"bash-request\");\n\tconst abortController = new AbortController();\n\tconst controllers = this._bashAbortControllers.get(requestKey) ?? new Set<AbortController>();\n\tcontrollers.add(abortController);\n\tthis._bashAbortControllers.set(requestKey, controllers);\n\t// Apply command prefix if configured (e.g., \"shopt -s expand_aliases\" for alias support)\n\tconst prefix = this.settingsManager.getShellCommandPrefix();\n\tconst shellPath = this.settingsManager.getShellPath();\n\tconst resolvedCommand = prefix ? `${prefix}\\n${command}` : command;\n\tconst env = { ...getShellEnv() };\n\tapplyBashSessionEnvironment(env, snapshotBashSessionEnvironment(this, true));\n\n\ttry {\n\t\tconst result = await executeBashWithOperations(\n\t\t\tresolvedCommand,\n\t\t\tthis.sessionManager.getCwd(),\n\t\t\toptions?.operations ??\n\t\t\t\t(process.platform === \"win32\"\n\t\t\t\t\t? createLocalPowerShellOperations()\n\t\t\t\t\t: createLocalBashOperations({ shellPath })),\n\t\t\t{\n\t\t\t\tonChunk: (delta, channel) => {\n\t\t\t\t\tonChunk?.(delta, channel);\n\t\t\t\t\tif (options?.emitEvent !== false) {\n\t\t\t\t\t\tthis._emit({ type: \"bash_execution_update\", id: options?.id, channel, delta });\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tsignal: abortController.signal,\n\t\t\t\tenv,\n\t\t\t\tpty: options?.pty,\n\t\t\t\tsessionTempDir: resolveSessionTempDirPath(this.sessionManager.getSessionId()),\n\t\t\t},\n\t\t);\n\n\t\tif (options?.recordResult !== false) await this.recordBashResult(command, result, options);\n\t\treturn result;\n\t} finally {\n\t\tcontrollers.delete(abortController);\n\t\tif (controllers.size === 0) this._bashAbortControllers.delete(requestKey);\n\t}\n}\n\n/**\n * Record a bash execution result in session history.\n * Used by executeBash and by extensions that handle bash execution themselves.\n */\n\nexport async function recordBashResult(\n\tthis: AgentSession,\n\tcommand: string,\n\tresult: BashResult,\n\toptions?: { excludeFromContext?: boolean; persist?: boolean; defer?: boolean },\n): Promise<void> {\n\tconst bashMessage: BashExecutionMessage = {\n\t\trole: \"bashExecution\",\n\t\tcommand,\n\t\toutput: result.output,\n\t\texitCode: result.exitCode,\n\t\tcancelled: result.cancelled,\n\t\ttruncated: result.truncated,\n\t\tfullOutputPath: result.fullOutputPath,\n\t\ttimestamp: Date.now(),\n\t\texcludeFromContext: options?.excludeFromContext,\n\t};\n\n\t// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering\n\tif (this.isStreaming && options?.defer !== false) {\n\t\t// Queue for later - will be flushed on agent_end\n\t\tthis._pendingBashMessages.push(bashMessage);\n\t} else if (options?.persist !== false) {\n\t\t// Persist first, then refresh the finalized context from the canonical projection.\n\t\tawait this.sessionManager.appendMessage(bashMessage);\n\t\tthis._refreshFinalizedContext();\n\t} else {\n\t\t// Avoid writing a source-owned result into a shared manager that an\n\t\t// in-memory fork changed while this execution was active. The result stays\n\t\t// visible to this run only, so it must be added to agent state directly.\n\t\tthis.agent.state.messages.push(bashMessage);\n\t}\n}\n\n/** Cancel one correlated bash request, or all active requests for legacy callers. */\nexport function abortBash(this: AgentSession, id?: string): void {\n\tif (id !== undefined) {\n\t\tfor (const controller of [...(this._bashAbortControllers.get(id) ?? [])]) controller.abort();\n\t\treturn;\n\t}\n\t// Snapshot first: aborting settles owners, and a listener that removes its own\n\t// entry must not shorten the cancellation sweep.\n\tfor (const controllers of [...this._bashAbortControllers.values()]) {\n\t\tfor (const controller of [...controllers]) controller.abort();\n\t}\n}\n\nconst pendingBashDrains = new WeakMap<AgentSession, Promise<void>>();\n\nexport function _flushPendingBashMessages(this: AgentSession): Promise<void> {\n\tconst pending = pendingBashDrains.get(this);\n\tif (pending) return pending;\n\tif (this._pendingBashMessages.length === 0) return Promise.resolve();\n\n\tconst drain = (async () => {\n\t\twhile (this._pendingBashMessages.length > 0) {\n\t\t\tawait this.sessionManager.appendMessage(this._pendingBashMessages[0]);\n\t\t\tthis._pendingBashMessages.shift();\n\t\t\tthis._refreshFinalizedContext();\n\t\t}\n\t})();\n\tpendingBashDrains.set(this, drain);\n\tvoid drain.then(\n\t\t() => pendingBashDrains.delete(this),\n\t\t() => pendingBashDrains.delete(this),\n\t);\n\treturn drain;\n}\n\n// =========================================================================\n// Session Management\n// =========================================================================\n\n/**\n * Set a display name for the current session.\n */\n\nexport const agentSessionBashMethods = {\n\texecuteBash,\n\trecordBashResult,\n\tabortBash,\n\t_flushPendingBashMessages,\n};\n"]}
|
|
@@ -29,21 +29,21 @@ export declare function _installAgentRequestProjection(this: AgentSession): void
|
|
|
29
29
|
/** Dispatch the actionable `turn_end` boundary from `finishTurn`, before agent-core's own `turn_end`. */
|
|
30
30
|
export declare function _installAgentBoundaryHooks(this: AgentSession): void;
|
|
31
31
|
export declare function _dispatchTurnEndBoundary(this: AgentSession, message: AssistantMessage, toolResults: ToolResultMessage[], awaitPersistence?: boolean): Promise<boolean>;
|
|
32
|
-
export declare function _applyBoundaryDrafts(this: AgentSession, manager: SessionManager, drafts: SessionBoundaryDraft[]): SessionEntry[]
|
|
33
|
-
export declare function _createBoundaryPreviewManager(this: AgentSession, drafts: SessionBoundaryDraft[]): SessionManager
|
|
32
|
+
export declare function _applyBoundaryDrafts(this: AgentSession, manager: SessionManager, drafts: SessionBoundaryDraft[]): Promise<SessionEntry[]>;
|
|
33
|
+
export declare function _createBoundaryPreviewManager(this: AgentSession, drafts: SessionBoundaryDraft[]): Promise<SessionManager>;
|
|
34
34
|
export declare function _getPendingBoundaryMessages(this: AgentSession): AgentMessage[];
|
|
35
|
-
export declare function _buildBoundaryContext(this: AgentSession, drafts: SessionBoundaryDraft[], boundary: BoundaryKind): BoundaryContextPreview
|
|
36
|
-
export declare function _commitBoundaryDrafts(this: AgentSession, drafts: SessionBoundaryDraft[]): void
|
|
35
|
+
export declare function _buildBoundaryContext(this: AgentSession, drafts: SessionBoundaryDraft[], boundary: BoundaryKind): Promise<BoundaryContextPreview>;
|
|
36
|
+
export declare function _commitBoundaryDrafts(this: AgentSession, drafts: SessionBoundaryDraft[]): Promise<void>;
|
|
37
37
|
export declare function _reportInvalidBoundaryContinuation(this: AgentSession, event: BoundaryKind): void;
|
|
38
38
|
export declare function _findPersistedMessageEntryId(this: AgentSession, message: AgentMessage): string | undefined;
|
|
39
39
|
/** Keep a failed attempt in raw history while durably omitting it from model projection. */
|
|
40
|
-
export declare function _omitRecoveryAttempt(this: AgentSession, message: AssistantMessage, toolResults?: AgentMessage[]): void
|
|
40
|
+
export declare function _omitRecoveryAttempt(this: AgentSession, message: AssistantMessage, toolResults?: AgentMessage[]): Promise<void>;
|
|
41
41
|
/**
|
|
42
42
|
* Omit the trailing assistant attempt (and any tool results it produced) from model
|
|
43
43
|
* projection when the loop must resume from the preceding input. Returns true when an
|
|
44
44
|
* assistant attempt was omitted.
|
|
45
45
|
*/
|
|
46
|
-
export declare function _omitTrailingAssistantAttempt(this: AgentSession, accept?: (message: AssistantMessage) => boolean): boolean
|
|
46
|
+
export declare function _omitTrailingAssistantAttempt(this: AgentSession, accept?: (message: AssistantMessage) => boolean): Promise<boolean>;
|
|
47
47
|
/** Run the pre-settlement boundary. Returns true when the run must continue once more. */
|
|
48
48
|
export declare function _runBeforeSettleBoundary(this: AgentSession): Promise<boolean>;
|
|
49
49
|
export declare const agentSessionBoundaryMethods: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-boundaries.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-boundaries.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AACjF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAW9F,OAAO,KAAK,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAEhH,OAAO,EAAE,KAAK,YAAY,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAA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E,YAAY,EAAE,OAAO,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,CAqB1G;AAED,4FAA4F;AAC5F,wBAAsB,oBAAoB,CACzC,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,gBAAgB,EACzB,WAAW,GAAE,YAAY,EAAO,GAC9B,OAAO,CAAC,IAAI,CAAC,CAgBf;AAED;;;;GAIG;AACH,wBAAsB,6BAA6B,CAClD,IAAI,EAAE,YAAY,EAClB,MAAM,GAAE,CAAC,OAAO,EAAE,gBAAgB,KAAK,OAAoB,GACzD,OAAO,CAAC,OAAO,CAAC,CAclB;AAED,0FAA0F;AAC1F,wBAAsB,wBAAwB,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC,CAsBnF;AAED,eAAO,MAAM,2BAA2B;;;;;;;;;;;;;;;;;CAiBvC,CAAC;AAEF,YAAY,EAAE,oBAAoB,EAAE,CAAC"}
|
|
@@ -124,9 +124,9 @@ export async function _dispatchTurnEndBoundary(message, toolResults, awaitPersis
|
|
|
124
124
|
messageEntryId,
|
|
125
125
|
toolResultEntryIds,
|
|
126
126
|
outcome: this._lastActivityOutcome,
|
|
127
|
-
}, (entries) => this._buildBoundaryContext(entries, "turn_end"));
|
|
128
|
-
this._commitBoundaryDrafts(boundary.entries);
|
|
129
|
-
if (boundary.continue && !this._buildBoundaryContext([], "turn_end").canContinue) {
|
|
127
|
+
}, async (entries) => await this._buildBoundaryContext(entries, "turn_end"));
|
|
128
|
+
await this._commitBoundaryDrafts(boundary.entries);
|
|
129
|
+
if (boundary.continue && !(await this._buildBoundaryContext([], "turn_end")).canContinue) {
|
|
130
130
|
this._reportInvalidBoundaryContinuation("turn_end");
|
|
131
131
|
return false;
|
|
132
132
|
}
|
|
@@ -156,25 +156,25 @@ function extensionCompactionDetails(manager, summary, tokensBefore) {
|
|
|
156
156
|
rung: "extension",
|
|
157
157
|
};
|
|
158
158
|
}
|
|
159
|
-
export function _applyBoundaryDrafts(manager, drafts) {
|
|
159
|
+
export async function _applyBoundaryDrafts(manager, drafts) {
|
|
160
160
|
const appended = [];
|
|
161
161
|
for (const draft of drafts) {
|
|
162
162
|
let entryId;
|
|
163
163
|
switch (draft.type) {
|
|
164
164
|
case "custom":
|
|
165
|
-
entryId = manager.appendCustomEntry(draft.customType, draft.data);
|
|
165
|
+
entryId = await manager.appendCustomEntry(draft.customType, draft.data);
|
|
166
166
|
break;
|
|
167
167
|
case "custom_message":
|
|
168
|
-
entryId = manager.appendCustomMessageEntry(draft.customType, draft.content, draft.display, draft.details);
|
|
168
|
+
entryId = await manager.appendCustomMessageEntry(draft.customType, draft.content, draft.display, draft.details);
|
|
169
169
|
break;
|
|
170
170
|
case "context_edit":
|
|
171
|
-
entryId = manager.appendContextEdit(draft.targetId, draft.replacement);
|
|
171
|
+
entryId = await manager.appendContextEdit(draft.targetId, draft.replacement);
|
|
172
172
|
break;
|
|
173
173
|
case "compaction": {
|
|
174
174
|
if (draft.summary.trim().length === 0)
|
|
175
175
|
throw new Error("Compaction draft summary must not be empty");
|
|
176
176
|
const tokensBefore = estimateProjectedContextTokens(manager.buildSessionProjection(), manager.getBranch()).tokens;
|
|
177
|
-
entryId = manager.appendCompaction(draft.summary, draft.firstKeptEntryId, tokensBefore, extensionCompactionDetails(manager, draft.summary, tokensBefore), draft.usage);
|
|
177
|
+
entryId = await manager.appendCompaction(draft.summary, draft.firstKeptEntryId, tokensBefore, extensionCompactionDetails(manager, draft.summary, tokensBefore), draft.usage);
|
|
178
178
|
break;
|
|
179
179
|
}
|
|
180
180
|
}
|
|
@@ -184,19 +184,19 @@ export function _applyBoundaryDrafts(manager, drafts) {
|
|
|
184
184
|
}
|
|
185
185
|
return appended;
|
|
186
186
|
}
|
|
187
|
-
export function _createBoundaryPreviewManager(drafts) {
|
|
187
|
+
export async function _createBoundaryPreviewManager(drafts) {
|
|
188
188
|
const header = this.sessionManager.getHeader();
|
|
189
189
|
if (!header)
|
|
190
190
|
throw new Error("Session header is missing");
|
|
191
191
|
const manager = SessionManager.inMemory(this._cwd, undefined, [header, ...this.sessionManager.getBranch()]);
|
|
192
|
-
this._applyBoundaryDrafts(manager, drafts);
|
|
192
|
+
await this._applyBoundaryDrafts(manager, drafts);
|
|
193
193
|
return manager;
|
|
194
194
|
}
|
|
195
195
|
export function _getPendingBoundaryMessages() {
|
|
196
196
|
return [...this.agent.peekQueuedMessages(), ...this._pendingCustomMessages];
|
|
197
197
|
}
|
|
198
|
-
export function _buildBoundaryContext(drafts, boundary) {
|
|
199
|
-
const projection = this._createBoundaryPreviewManager(drafts).buildSessionProjection();
|
|
198
|
+
export async function _buildBoundaryContext(drafts, boundary) {
|
|
199
|
+
const projection = (await this._createBoundaryPreviewManager(drafts)).buildSessionProjection();
|
|
200
200
|
const contextMessages = finalizeProjectedMessages(this, projection.messages);
|
|
201
201
|
const pendingMessages = this._getPendingBoundaryMessages();
|
|
202
202
|
const llmMessages = convertToLlm(contextMessages);
|
|
@@ -216,8 +216,8 @@ export function _buildBoundaryContext(drafts, boundary) {
|
|
|
216
216
|
: finalRole === "assistant" && this.agent.hasQueuedMessages()),
|
|
217
217
|
};
|
|
218
218
|
}
|
|
219
|
-
export function _commitBoundaryDrafts(drafts) {
|
|
220
|
-
const appended = this._applyBoundaryDrafts(this.sessionManager, drafts);
|
|
219
|
+
export async function _commitBoundaryDrafts(drafts) {
|
|
220
|
+
const appended = await this._applyBoundaryDrafts(this.sessionManager, drafts);
|
|
221
221
|
this._refreshFinalizedContext();
|
|
222
222
|
for (const entry of appended)
|
|
223
223
|
this._emit({ type: "entry_appended", entry });
|
|
@@ -254,7 +254,7 @@ export function _findPersistedMessageEntryId(message) {
|
|
|
254
254
|
return undefined;
|
|
255
255
|
}
|
|
256
256
|
/** Keep a failed attempt in raw history while durably omitting it from model projection. */
|
|
257
|
-
export function _omitRecoveryAttempt(message, toolResults = []) {
|
|
257
|
+
export async function _omitRecoveryAttempt(message, toolResults = []) {
|
|
258
258
|
const targets = [message, ...toolResults];
|
|
259
259
|
const targetIds = targets.map((target) => this._findPersistedMessageEntryId(target));
|
|
260
260
|
const unresolvedProjectedTarget = targets.some((target, index) => targetIds[index] === undefined && this.agent.state.messages.includes(target));
|
|
@@ -264,7 +264,7 @@ export function _omitRecoveryAttempt(message, toolResults = []) {
|
|
|
264
264
|
for (const targetId of targetIds) {
|
|
265
265
|
if (!targetId)
|
|
266
266
|
continue;
|
|
267
|
-
const editId = this.sessionManager.appendContextEdit(targetId, null);
|
|
267
|
+
const editId = await this.sessionManager.appendContextEdit(targetId, null);
|
|
268
268
|
const entry = this.sessionManager.getEntry(editId);
|
|
269
269
|
if (entry)
|
|
270
270
|
this._emit({ type: "entry_appended", entry });
|
|
@@ -276,7 +276,7 @@ export function _omitRecoveryAttempt(message, toolResults = []) {
|
|
|
276
276
|
* projection when the loop must resume from the preceding input. Returns true when an
|
|
277
277
|
* assistant attempt was omitted.
|
|
278
278
|
*/
|
|
279
|
-
export function _omitTrailingAssistantAttempt(accept = () => true) {
|
|
279
|
+
export async function _omitTrailingAssistantAttempt(accept = () => true) {
|
|
280
280
|
const messages = this.agent.state.messages;
|
|
281
281
|
let index = messages.length - 1;
|
|
282
282
|
const trailingToolResults = [];
|
|
@@ -290,7 +290,7 @@ export function _omitTrailingAssistantAttempt(accept = () => true) {
|
|
|
290
290
|
const assistant = candidate;
|
|
291
291
|
if (!accept(assistant))
|
|
292
292
|
return false;
|
|
293
|
-
this._omitRecoveryAttempt(assistant, trailingToolResults);
|
|
293
|
+
await this._omitRecoveryAttempt(assistant, trailingToolResults);
|
|
294
294
|
return true;
|
|
295
295
|
}
|
|
296
296
|
/** Run the pre-settlement boundary. Returns true when the run must continue once more. */
|
|
@@ -300,10 +300,10 @@ export async function _runBeforeSettleBoundary() {
|
|
|
300
300
|
this._isBeforeSettle = true;
|
|
301
301
|
this._abortDuringBeforeSettle = false;
|
|
302
302
|
try {
|
|
303
|
-
const result = await this._extensionRunner.emitBoundary({ type: "agent_before_settle", outcome: this._lastActivityOutcome }, (entries) => this._buildBoundaryContext(entries, "agent_before_settle"));
|
|
304
|
-
this._commitBoundaryDrafts(result.entries);
|
|
305
|
-
this._flushPendingCustomMessages();
|
|
306
|
-
const finalContext = this._buildBoundaryContext([], "agent_before_settle");
|
|
303
|
+
const result = await this._extensionRunner.emitBoundary({ type: "agent_before_settle", outcome: this._lastActivityOutcome }, async (entries) => await this._buildBoundaryContext(entries, "agent_before_settle"));
|
|
304
|
+
await this._commitBoundaryDrafts(result.entries);
|
|
305
|
+
await this._flushPendingCustomMessages();
|
|
306
|
+
const finalContext = await this._buildBoundaryContext([], "agent_before_settle");
|
|
307
307
|
if (this._abortDuringBeforeSettle)
|
|
308
308
|
return false;
|
|
309
309
|
const shouldContinue = result.continue || this.agent.hasQueuedMessages();
|