@bastani/atomic 0.9.11-alpha.6 → 0.9.11-alpha.8
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 +38 -0
- package/README.md +3 -5
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/mcp/sampling-handler.ts +1 -5
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +1 -0
- package/dist/builtin/workflows/README.md +1 -1
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/skills/impeccable/SKILL.md +33 -129
- package/dist/builtin/workflows/skills/impeccable/agents/impeccable_asset_producer.toml +11 -3
- package/dist/builtin/workflows/skills/impeccable/agents/impeccable_documenter.toml +26 -0
- package/dist/builtin/workflows/skills/impeccable/agents/impeccable_finish_reviewer.toml +35 -0
- package/dist/builtin/workflows/skills/impeccable/reference/android.md +1 -1
- package/dist/builtin/workflows/skills/impeccable/reference/animate.md +72 -189
- package/dist/builtin/workflows/skills/impeccable/reference/audit.md +10 -9
- package/dist/builtin/workflows/skills/impeccable/reference/audit.native.md +2 -2
- package/dist/builtin/workflows/skills/impeccable/reference/bolder.md +19 -108
- package/dist/builtin/workflows/skills/impeccable/reference/clarify.md +59 -253
- package/dist/builtin/workflows/skills/impeccable/reference/colorize.md +51 -222
- package/dist/builtin/workflows/skills/impeccable/reference/craft-floor.md +45 -0
- package/dist/builtin/workflows/skills/impeccable/reference/craft.md +3 -121
- package/dist/builtin/workflows/skills/impeccable/reference/critique.md +28 -20
- package/dist/builtin/workflows/skills/impeccable/reference/degraded/asset-producer.md +97 -0
- package/dist/builtin/workflows/skills/impeccable/reference/degraded/documenter.md +23 -0
- package/dist/builtin/workflows/skills/impeccable/reference/degraded/finish-reviewer.md +32 -0
- package/dist/builtin/workflows/skills/impeccable/reference/degraded/manual-edit-applier.md +92 -0
- package/dist/builtin/workflows/skills/impeccable/reference/delight.md +47 -279
- package/dist/builtin/workflows/skills/impeccable/reference/distill.md +2 -2
- package/dist/builtin/workflows/skills/impeccable/reference/doctor.md +53 -0
- package/dist/builtin/workflows/skills/impeccable/reference/document.md +60 -73
- package/dist/builtin/workflows/skills/impeccable/reference/harden.md +1 -12
- package/dist/builtin/workflows/skills/impeccable/reference/hooks.md +17 -4
- package/dist/builtin/workflows/skills/impeccable/reference/init.md +64 -163
- package/dist/builtin/workflows/skills/impeccable/reference/ios.md +1 -1
- package/dist/builtin/workflows/skills/impeccable/reference/layout.md +52 -153
- package/dist/builtin/workflows/skills/impeccable/reference/live.md +44 -32
- package/dist/builtin/workflows/skills/impeccable/reference/new-work.md +105 -0
- package/dist/builtin/workflows/skills/impeccable/reference/{product.md → operate.md} +6 -5
- package/dist/builtin/workflows/skills/impeccable/reference/optimize.md +4 -4
- package/dist/builtin/workflows/skills/impeccable/reference/overdrive.md +1 -4
- package/dist/builtin/workflows/skills/impeccable/reference/polish.md +68 -212
- package/dist/builtin/workflows/skills/impeccable/reference/quieter.md +3 -3
- package/dist/builtin/workflows/skills/impeccable/reference/routing.md +18 -0
- package/dist/builtin/workflows/skills/impeccable/reference/shape.md +38 -144
- package/dist/builtin/workflows/skills/impeccable/reference/typeset.md +48 -269
- package/dist/builtin/workflows/skills/impeccable/reference/visualize.md +38 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/command-metadata.json +1 -1
- package/dist/builtin/workflows/skills/impeccable/scripts/concept-seed.mjs +584 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/context-signals.mjs +117 -9
- package/dist/builtin/workflows/skills/impeccable/scripts/context.mjs +486 -59
- package/dist/builtin/workflows/skills/impeccable/scripts/critique-storage.mjs +16 -45
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/browser/injected/index.mjs +96 -10
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/cli/main.mjs +143 -26
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/design-system.mjs +181 -12
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/detect-antipatterns-browser.js +3187 -182
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs +102 -7
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs +282 -70
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/static-html/css-cascade.mjs +183 -15
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs +22 -7
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/findings.mjs +7 -1
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/node/file-system.mjs +16 -2
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/registry/antipatterns.mjs +155 -42
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/rules/checks.mjs +2988 -155
- package/dist/builtin/workflows/skills/impeccable/scripts/detector/shared/constants.mjs +11 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/doctor.mjs +336 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/generate-image.mjs +232 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/hook-admin.mjs +90 -10
- package/dist/builtin/workflows/skills/impeccable/scripts/hook-lib.mjs +410 -78
- package/dist/builtin/workflows/skills/impeccable/scripts/hook.mjs +25 -8
- package/dist/builtin/workflows/skills/impeccable/scripts/lib/artifact-schema.mjs +93 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/lib/composition-catalog.mjs +165 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/lib/concept-catalog.mjs +329 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/lib/impeccable-config.mjs +20 -5
- package/dist/builtin/workflows/skills/impeccable/scripts/lib/impeccable-paths.mjs +16 -8
- package/dist/builtin/workflows/skills/impeccable/scripts/lib/provider.mjs +1 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/lib/staleness-deep.mjs +455 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/lib/staleness-notice.mjs +169 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/lib/staleness.mjs +457 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/lib/surface-briefs.mjs +151 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/lib/target-slug.mjs +33 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/lib/template-extensions.mjs +146 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/live/completion.mjs +10 -1
- package/dist/builtin/workflows/skills/impeccable/scripts/live/event-validation.mjs +15 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/live/generation-preflight.mjs +149 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/live/poll-lanes.mjs +14 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/live/session-store.mjs +109 -32
- package/dist/builtin/workflows/skills/impeccable/scripts/live/source-lock.mjs +105 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/live/source-search.mjs +105 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/live/sveltekit-adapter.mjs +8 -6
- package/dist/builtin/workflows/skills/impeccable/scripts/live/tanstack-adapter.mjs +280 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/live-accept.mjs +208 -68
- package/dist/builtin/workflows/skills/impeccable/scripts/live-browser.js +563 -112
- package/dist/builtin/workflows/skills/impeccable/scripts/live-commit-manual-edits.mjs +3 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/live-inject.mjs +198 -13
- package/dist/builtin/workflows/skills/impeccable/scripts/live-insert.mjs +24 -6
- package/dist/builtin/workflows/skills/impeccable/scripts/live-manual-edit-evidence.mjs +6 -1
- package/dist/builtin/workflows/skills/impeccable/scripts/live-poll.mjs +44 -14
- package/dist/builtin/workflows/skills/impeccable/scripts/live-server.mjs +398 -33
- package/dist/builtin/workflows/skills/impeccable/scripts/live-status.mjs +9 -5
- package/dist/builtin/workflows/skills/impeccable/scripts/live-wrap.mjs +81 -67
- package/dist/builtin/workflows/skills/impeccable/scripts/live.mjs +7 -2
- package/dist/builtin/workflows/skills/impeccable/scripts/palette.mjs +76 -81
- package/dist/builtin/workflows/skills/impeccable/scripts/pin.mjs +2 -2
- package/dist/builtin/workflows/skills/impeccable/scripts/serve-question.mjs +890 -0
- package/dist/builtin/workflows/skills/impeccable/scripts/surface-brief.mjs +74 -0
- package/dist/builtin/workflows/src/extension/extension-runtime-state.ts +1 -24
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +232 -50
- package/dist/builtin/workflows/src/extension/workflow-model-catalog.ts +26 -0
- package/dist/builtin/workflows/src/extension/workflow-prompts.ts +3 -2
- package/dist/builtin/workflows/src/runs/foreground/executor-stage-control.ts +23 -9
- package/dist/builtin/workflows/src/runs/foreground/executor-stage-replay.ts +1 -0
- package/dist/builtin/workflows/src/runs/foreground/postmortem-stage-chat.ts +20 -5
- package/dist/builtin/workflows/src/runs/foreground/stage-control-registry.ts +10 -0
- package/dist/builtin/workflows/src/runs/foreground/stage-delivery-activity.ts +86 -0
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-context.ts +6 -2
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-controller.ts +24 -18
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-send-user-message.ts +8 -0
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-session-options.ts +3 -3
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-session.ts +2 -2
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-types.ts +16 -0
- package/dist/builtin/workflows/src/tui/stage-chat-view-delivery-activity.ts +121 -0
- package/dist/builtin/workflows/src/tui/stage-chat-view-live-events.ts +42 -0
- package/dist/builtin/workflows/src/tui/stage-chat-view-state.ts +16 -0
- package/dist/builtin/workflows/src/tui/stage-chat-view-types.ts +4 -0
- package/dist/cli/list-models.d.ts +2 -2
- package/dist/cli/list-models.d.ts.map +1 -1
- package/dist/cli/list-models.js +5 -5
- package/dist/cli/list-models.js.map +1 -1
- package/dist/core/agent-session-accessors.js +1 -1
- package/dist/core/agent-session-accessors.js.map +1 -1
- package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-auto-compaction.js +2 -5
- package/dist/core/agent-session-auto-compaction.js.map +1 -1
- package/dist/core/agent-session-compaction.js +1 -1
- package/dist/core/agent-session-compaction.js.map +1 -1
- package/dist/core/agent-session-extension-bindings.js +5 -5
- package/dist/core/agent-session-extension-bindings.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +4 -4
- 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 +1 -1
- package/dist/core/agent-session-models.d.ts.map +1 -1
- package/dist/core/agent-session-models.js +18 -14
- package/dist/core/agent-session-models.js.map +1 -1
- package/dist/core/agent-session-post-tool-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-post-tool-compaction.js +2 -4
- package/dist/core/agent-session-post-tool-compaction.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +3 -7
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-retry.js +1 -1
- package/dist/core/agent-session-retry.js.map +1 -1
- package/dist/core/agent-session-runtime-auth.d.ts +3 -3
- package/dist/core/agent-session-runtime-auth.d.ts.map +1 -1
- package/dist/core/agent-session-runtime-auth.js +4 -14
- package/dist/core/agent-session-runtime-auth.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +1 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +3 -3
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +3 -8
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +16 -23
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
- package/dist/core/agent-session-tool-registry.js +2 -1
- package/dist/core/agent-session-tool-registry.js.map +1 -1
- package/dist/core/agent-session-types.d.ts +2 -2
- package/dist/core/agent-session-types.d.ts.map +1 -1
- package/dist/core/agent-session-types.js.map +1 -1
- package/dist/core/agent-session.d.ts +2 -2
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +1 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage-backends.d.ts +1 -0
- package/dist/core/auth-storage-backends.d.ts.map +1 -1
- package/dist/core/auth-storage-backends.js +18 -4
- package/dist/core/auth-storage-backends.js.map +1 -1
- package/dist/core/auth-storage.d.ts +12 -139
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +68 -374
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/copilot-env-routing.d.ts +36 -0
- package/dist/core/copilot-env-routing.d.ts.map +1 -0
- package/dist/core/copilot-env-routing.js +94 -0
- package/dist/core/copilot-env-routing.js.map +1 -0
- package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.js +10 -2
- package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
- package/dist/core/extensions/provider-types.d.ts +0 -40
- package/dist/core/extensions/provider-types.d.ts.map +1 -1
- package/dist/core/extensions/provider-types.js.map +1 -1
- package/dist/core/fallback-models.d.ts +4 -4
- package/dist/core/fallback-models.d.ts.map +1 -1
- package/dist/core/fallback-models.js +3 -3
- package/dist/core/fallback-models.js.map +1 -1
- package/dist/core/model-config.d.ts +542 -0
- package/dist/core/model-config.d.ts.map +1 -0
- package/dist/core/{model-registry-schemas.js → model-config.js} +85 -34
- package/dist/core/model-config.js.map +1 -0
- package/dist/core/model-registry.d.ts +25 -85
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +65 -388
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver-cli.d.ts +2 -2
- package/dist/core/model-resolver-cli.d.ts.map +1 -1
- package/dist/core/model-resolver-cli.js +2 -2
- package/dist/core/model-resolver-cli.js.map +1 -1
- package/dist/core/model-resolver-initial.d.ts +4 -4
- package/dist/core/model-resolver-initial.d.ts.map +1 -1
- package/dist/core/model-resolver-initial.js +17 -17
- package/dist/core/model-resolver-initial.js.map +1 -1
- package/dist/core/model-resolver-scope.d.ts +3 -3
- package/dist/core/model-resolver-scope.d.ts.map +1 -1
- package/dist/core/model-resolver-scope.js +4 -4
- package/dist/core/model-resolver-scope.js.map +1 -1
- package/dist/core/model-runtime-auth.d.ts +7 -0
- package/dist/core/model-runtime-auth.d.ts.map +1 -0
- package/dist/core/model-runtime-auth.js +14 -0
- package/dist/core/model-runtime-auth.js.map +1 -0
- package/dist/core/model-runtime-providers.d.ts +6 -0
- package/dist/core/model-runtime-providers.d.ts.map +1 -0
- package/dist/core/model-runtime-providers.js +22 -0
- package/dist/core/model-runtime-providers.js.map +1 -0
- package/dist/core/model-runtime-restoration.d.ts +6 -0
- package/dist/core/model-runtime-restoration.d.ts.map +1 -0
- package/dist/core/model-runtime-restoration.js +21 -0
- package/dist/core/model-runtime-restoration.js.map +1 -0
- package/dist/core/model-runtime-snapshot.d.ts +16 -0
- package/dist/core/model-runtime-snapshot.d.ts.map +1 -0
- package/dist/core/model-runtime-snapshot.js +52 -0
- package/dist/core/model-runtime-snapshot.js.map +1 -0
- package/dist/core/model-runtime-streaming.d.ts +17 -0
- package/dist/core/model-runtime-streaming.d.ts.map +1 -0
- package/dist/core/model-runtime-streaming.js +66 -0
- package/dist/core/model-runtime-streaming.js.map +1 -0
- package/dist/core/model-runtime-types.d.ts +21 -0
- package/dist/core/model-runtime-types.d.ts.map +1 -0
- package/dist/core/model-runtime-types.js +2 -0
- package/dist/core/model-runtime-types.js.map +1 -0
- package/dist/core/model-runtime.d.ts +50 -29
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +330 -90
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/models-store.d.ts +2 -10
- package/dist/core/models-store.d.ts.map +1 -1
- package/dist/core/models-store.js +2 -29
- package/dist/core/models-store.js.map +1 -1
- package/dist/core/oauth-login.d.ts +24 -0
- package/dist/core/oauth-login.d.ts.map +1 -0
- package/dist/core/oauth-login.js +87 -0
- package/dist/core/oauth-login.js.map +1 -0
- package/dist/core/oauth-provider-metadata.d.ts +5 -0
- package/dist/core/oauth-provider-metadata.d.ts.map +1 -0
- package/dist/core/oauth-provider-metadata.js +19 -0
- package/dist/core/oauth-provider-metadata.js.map +1 -0
- package/dist/core/provider-composer-internal.d.ts +53 -0
- package/dist/core/provider-composer-internal.d.ts.map +1 -0
- package/dist/core/provider-composer-internal.js +273 -0
- package/dist/core/provider-composer-internal.js.map +1 -0
- package/dist/core/provider-composer.d.ts +16 -0
- package/dist/core/provider-composer.d.ts.map +1 -0
- package/dist/core/provider-composer.js +108 -0
- package/dist/core/provider-composer.js.map +1 -0
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +74 -122
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/resolve-config-value.d.ts +8 -7
- package/dist/core/resolve-config-value.d.ts.map +1 -1
- package/dist/core/resolve-config-value.js +26 -23
- package/dist/core/resolve-config-value.js.map +1 -1
- package/dist/core/runtime-credentials.d.ts +16 -0
- package/dist/core/runtime-credentials.d.ts.map +1 -0
- package/dist/core/runtime-credentials.js +42 -0
- package/dist/core/runtime-credentials.js.map +1 -0
- package/dist/core/sdk-types.d.ts +1 -7
- package/dist/core/sdk-types.d.ts.map +1 -1
- package/dist/core/sdk-types.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +27 -28
- package/dist/core/sdk.js.map +1 -1
- package/dist/extensions/llama/index.js +1 -1
- package/dist/extensions/llama/index.js.map +1 -1
- package/dist/extensions/llama/provider.d.ts +2 -4
- package/dist/extensions/llama/provider.d.ts.map +1 -1
- package/dist/extensions/llama/provider.js +25 -17
- package/dist/extensions/llama/provider.js.map +1 -1
- package/dist/index.d.ts +2 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -4
- package/dist/index.js.map +1 -1
- package/dist/main-runtime-api-key.d.ts +6 -0
- package/dist/main-runtime-api-key.d.ts.map +1 -0
- package/dist/main-runtime-api-key.js +6 -0
- package/dist/main-runtime-api-key.js.map +1 -0
- package/dist/main-session-options.d.ts +2 -2
- package/dist/main-session-options.d.ts.map +1 -1
- package/dist/main-session-options.js +3 -3
- package/dist/main-session-options.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +9 -11
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-actions.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-actions.js +2 -14
- package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-events.js +9 -0
- package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-runtime.d.ts +25 -0
- package/dist/modes/interactive/components/chat-session-host-runtime.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-runtime.js +53 -0
- package/dist/modes/interactive/components/chat-session-host-runtime.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host.d.ts +13 -0
- package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host.js +22 -1
- package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
- package/dist/modes/interactive/components/footer.js +1 -1
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +1 -3
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +4 -3
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +56 -73
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +4 -3
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +15 -24
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.js +10 -4
- package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
- package/dist/modes/interactive/interactive-auth-login.js +20 -31
- package/dist/modes/interactive/interactive-auth-login.js.map +1 -1
- package/dist/modes/interactive/interactive-auth-routing.d.ts +1 -1
- package/dist/modes/interactive/interactive-auth-routing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-auth-routing.js +21 -47
- package/dist/modes/interactive/interactive-auth-routing.js.map +1 -1
- package/dist/modes/interactive/interactive-autocomplete.js +3 -3
- package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
- package/dist/modes/interactive/interactive-deferred-startup.js +8 -8
- package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
- package/dist/modes/interactive/interactive-extension-runtime.js +2 -1
- package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
- package/dist/modes/interactive/interactive-model-catalog-startup.js +2 -2
- package/dist/modes/interactive/interactive-model-catalog-startup.js.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.js +11 -11
- package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
- package/dist/modes/interactive/interactive-render-chat.js +1 -1
- package/dist/modes/interactive/interactive-render-chat.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/interactive-startup.js +1 -1
- package/dist/modes/interactive/interactive-startup.js.map +1 -1
- package/dist/modes/interactive-engine/isolated-auth.d.ts +2 -2
- package/dist/modes/interactive-engine/isolated-auth.d.ts.map +1 -1
- package/dist/modes/interactive-engine/isolated-auth.js +4 -3
- package/dist/modes/interactive-engine/isolated-auth.js.map +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.js +4 -3
- package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
- package/dist/modes/interactive-engine/remote-model-catalog.d.ts +0 -1
- package/dist/modes/interactive-engine/remote-model-catalog.d.ts.map +1 -1
- package/dist/modes/interactive-engine/remote-model-catalog.js +11 -50
- package/dist/modes/interactive-engine/remote-model-catalog.js.map +1 -1
- package/dist/modes/rpc/rpc-client-api.d.ts +2 -2
- package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client-api.js.map +1 -1
- package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-command-handler.js +26 -19
- package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
- package/dist/modes/rpc/rpc-oauth-client.d.ts +1 -1
- package/dist/modes/rpc/rpc-oauth-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-oauth-client.js +1 -1
- package/dist/modes/rpc/rpc-oauth-client.js.map +1 -1
- package/dist/modes/rpc/rpc-oauth-interaction.d.ts +1 -1
- package/dist/modes/rpc/rpc-oauth-interaction.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-oauth-interaction.js +1 -1
- package/dist/modes/rpc/rpc-oauth-interaction.js.map +1 -1
- package/dist/modes/rpc/rpc-provider-auth.d.ts +4 -5
- package/dist/modes/rpc/rpc-provider-auth.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-provider-auth.js +19 -66
- package/dist/modes/rpc/rpc-provider-auth.js.map +1 -1
- package/dist/modes/rpc/rpc-session-binding.js +1 -1
- package/dist/modes/rpc/rpc-session-binding.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +7 -4
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +5 -7
- package/dist/package-manager-cli.js.map +1 -1
- package/docs/changelog.mdx +1 -1
- package/docs/custom-provider.md +1 -1
- package/docs/models.md +4 -6
- package/docs/providers.md +13 -0
- package/docs/quickstart.md +2 -1
- package/docs/sdk.md +32 -49
- package/docs/tui.md +7 -2
- package/docs/workflows.md +4 -4
- package/examples/sdk/02-custom-model.ts +8 -10
- package/examples/sdk/09-api-keys-and-oauth.ts +17 -23
- package/examples/sdk/12-full-control.ts +9 -11
- package/examples/sdk/README.md +17 -21
- package/npm-shrinkwrap.json +23 -23
- package/package.json +2 -2
- package/dist/builtin/workflows/skills/impeccable/reference/brand.md +0 -108
- package/dist/builtin/workflows/skills/impeccable/reference/codex.md +0 -105
- package/dist/builtin/workflows/skills/impeccable/reference/interaction-design.md +0 -189
- package/dist/core/model-registry-auth.d.ts +0 -10
- package/dist/core/model-registry-auth.d.ts.map +0 -1
- package/dist/core/model-registry-auth.js +0 -98
- package/dist/core/model-registry-auth.js.map +0 -1
- package/dist/core/model-registry-builtins.d.ts +0 -8
- package/dist/core/model-registry-builtins.d.ts.map +0 -1
- package/dist/core/model-registry-builtins.js +0 -104
- package/dist/core/model-registry-builtins.js.map +0 -1
- package/dist/core/model-registry-custom-loader.d.ts +0 -3
- package/dist/core/model-registry-custom-loader.d.ts.map +0 -1
- package/dist/core/model-registry-custom-loader.js +0 -255
- package/dist/core/model-registry-custom-loader.js.map +0 -1
- package/dist/core/model-registry-dynamic.d.ts +0 -7
- package/dist/core/model-registry-dynamic.d.ts.map +0 -1
- package/dist/core/model-registry-dynamic.js +0 -189
- package/dist/core/model-registry-dynamic.js.map +0 -1
- package/dist/core/model-registry-extension-refresh.d.ts +0 -23
- package/dist/core/model-registry-extension-refresh.d.ts.map +0 -1
- package/dist/core/model-registry-extension-refresh.js +0 -32
- package/dist/core/model-registry-extension-refresh.js.map +0 -1
- package/dist/core/model-registry-loader.d.ts +0 -5
- package/dist/core/model-registry-loader.d.ts.map +0 -1
- package/dist/core/model-registry-loader.js +0 -29
- package/dist/core/model-registry-loader.js.map +0 -1
- package/dist/core/model-registry-schemas.d.ts +0 -1399
- package/dist/core/model-registry-schemas.d.ts.map +0 -1
- package/dist/core/model-registry-schemas.js.map +0 -1
- package/dist/core/model-registry-types.d.ts +0 -91
- package/dist/core/model-registry-types.d.ts.map +0 -1
- package/dist/core/model-registry-types.js +0 -2
- package/dist/core/model-registry-types.js.map +0 -1
- package/dist/core/model-registry-validation.d.ts +0 -7
- package/dist/core/model-registry-validation.d.ts.map +0 -1
- package/dist/core/model-registry-validation.js +0 -12
- package/dist/core/model-registry-validation.js.map +0 -1
- package/dist/core/oauth-compat.d.ts +0 -17
- package/dist/core/oauth-compat.d.ts.map +0 -1
- package/dist/core/oauth-compat.js +0 -2
- package/dist/core/oauth-compat.js.map +0 -1
- package/dist/core/oauth-provider-bridge.d.ts +0 -63
- package/dist/core/oauth-provider-bridge.d.ts.map +0 -1
- package/dist/core/oauth-provider-bridge.js +0 -232
- package/dist/core/oauth-provider-bridge.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-models.js","sourceRoot":"","sources":["../../src/core/agent-session-models.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,kBAAkB,EAAE,0BAA0B,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9G,OAAO,EAAE,0BAA0B,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,EAAE,eAAe,EAAyB,MAAM,0BAA0B,CAAC;AAElF,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAqB,KAAiB;IAKlF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,mBAAmB,CAAC,KAAK,CAAC,CAAC;IACpE,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;QAChB,IAAI,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,kBAAkB,CAAC,EAAE,CAAC;YACjD,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAA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A6B;IAChG,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;QACjC,OAAO,aAAa,CAAC;IACtB,CAAC;IACD,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,EAAE,CAAC;QAC9B,OAAO,IAAI,CAAC,eAAe,CAAC,uBAAuB,EAAE,IAAI,sBAAsB,CAAC;IACjF,CAAC;IACD,OAAO,IAAI,CAAC,aAAa,CAAC;AAC3B,CAAC;AAGD,MAAM,UAAU,mBAAmB,CAAqB,KAAoB,EAAE,gBAAiC;IAC9G,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAE,kBAAkB,CAAC,IAAI,CAAC,KAAK,EAAE,KAAK,CAAmB,CAAC,CAAC,CAAC,KAAK,CAAC;AACtF,CAAC;AAGD,4EAA4E;AAC5E,wBAAwB;AACxB,4EAA4E;AAE5E;;;GAGG;AAEH,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACxC,uBAAuB;IACvB,iBAAiB;IACjB,gBAAgB;IAChB,QAAQ;IACR,UAAU;IACV,iBAAiB;IACjB,oBAAoB;IACpB,gBAAgB;IAChB,kBAAkB;IAClB,0BAA0B;IAC1B,gBAAgB;IAChB,+BAA+B;IAC/B,mBAAmB;CACnB,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { ProviderHeaders } from \"@earendil-works/pi-ai\";\nimport type { Api, Model } from \"@earendil-works/pi-ai/compat\";\nimport { clampThinkingLevel, getSupportedThinkingLevels, modelsAreEqual } from \"@earendil-works/pi-ai/compat\";\nimport { formatNoApiKeyFoundMessage } from \"./auth-guidance.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { THINKING_LEVELS, type ModelCycleResult } from \"./agent-session-types.ts\";\n\nexport async function _getRequiredRequestAuth(this: AgentSession, model: Model<Api>): Promise<{\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}> {\n\tconst result = await this._modelRegistry.getApiKeyAndHeaders(model);\n\tif (!result.ok) {\n\t\tif (result.error.startsWith(\"No API key found\")) {\n\t\t\tthrow new Error(formatNoApiKeyFoundMessage(model.provider));\n\t\t}\n\t\tthrow new Error(result.error);\n\t}\n\tif (result.apiKey || result.headers) {\n\t\treturn { apiKey: result.apiKey, headers: result.headers, baseUrl: result.baseUrl };\n\t}\n\n\tconst isOAuth = this._modelRegistry.isUsingOAuth(model);\n\tif (isOAuth) {\n\t\tthrow new Error(\n\t\t\t`Authentication failed for \"${model.provider}\". ` +\n\t\t\t\t`Credentials may have expired or network is unavailable. ` +\n\t\t\t\t`Run '/login ${model.provider}' to re-authenticate.`,\n\t\t);\n\t}\n\tthrow new Error(formatNoApiKeyFoundMessage(model.provider));\n}\n\n/**\n * Install tool hooks once on the Agent instance.\n *\n * The callbacks read `this._extensionRunner` at execution time, so extension reload swaps in the\n * new runner without reinstalling hooks. Extension-specific tool wrappers are still used to adapt\n * registered tool execution to the extension context. Tool call and tool result interception now\n * happens here instead of in wrappers.\n */\n\nexport function _emitModelChanged(this: AgentSession, \n\tnextModel: Model<Api>,\n\tpreviousModel: Model<Api> | undefined,\n\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\",\n): void {\n\tif (modelsAreEqual(previousModel, nextModel)) return;\n\tthis._emit({\n\t\ttype: \"model_changed\",\n\t\tmodel: nextModel,\n\t\tpreviousModel,\n\t\tsource,\n\t});\n}\n\n\nexport async function _emitModelSelect(this: AgentSession, \n\tnextModel: Model<Api>,\n\tpreviousModel: Model<Api> | undefined,\n\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\",\n): Promise<void> {\n\tif (modelsAreEqual(previousModel, nextModel)) return;\n\tawait this._extensionRunner.emit({\n\t\ttype: \"model_select\",\n\t\tmodel: nextModel,\n\t\tpreviousModel,\n\t\tsource,\n\t});\n}\n\n/**\n * Set model directly.\n * Validates that auth is configured, saves to session and settings.\n * @throws Error if no auth is configured for the model\n */\n\nexport async function setModel(this: AgentSession, model: Model<Api>): Promise<void> {\n\tif (!this._modelRegistry.hasConfiguredAuth(model)) {\n\t\tthrow new Error(`No API key for ${model.provider}/${model.id}`);\n\t}\n\n\tconst previousModel = this.model;\n\tconst thinkingLevel = this._getThinkingLevelForModelSwitch();\n\tconst nextModel = model;\n\tthis.agent.state.model = nextModel;\n\tthis.sessionManager.appendModelChange(nextModel.provider, nextModel.id);\n\tthis.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);\n\n\t// Re-clamp thinking level for new model's capabilities\n\tthis.setThinkingLevel(thinkingLevel);\n\tthis._refreshBaseSystemPromptFromActiveTools();\n\n\tthis._emitModelChanged(nextModel, previousModel, \"set\");\n\tawait this._emitModelSelect(nextModel, previousModel, \"set\");\n}\n\n/**\n * Cycle to next/previous model.\n * Uses scoped models (from --models flag) if available, otherwise all available models.\n * @param direction - \"forward\" (default) or \"backward\"\n * @returns The new model info, or undefined if only one model available\n */\n\nexport async function cycleModel(this: AgentSession, direction: \"forward\" | \"backward\" = \"forward\"): Promise<ModelCycleResult | undefined> {\n\tif (this._scopedModels.length > 0) {\n\t\treturn this._cycleScopedModel(direction);\n\t}\n\treturn this._cycleAvailableModel(direction);\n}\n\n\nexport async function _cycleScopedModel(this: AgentSession, direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined> {\n\tconst scopedModels = this._scopedModels.filter((scoped) => this._modelRegistry.hasConfiguredAuth(scoped.model));\n\tif (scopedModels.length <= 1) return undefined;\n\n\tconst currentModel = this.model;\n\tlet currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));\n\n\tif (currentIndex === -1) currentIndex = 0;\n\tconst len = scopedModels.length;\n\tconst nextIndex = direction === \"forward\" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;\n\tconst next = scopedModels[nextIndex];\n\tconst thinkingLevel = this._getThinkingLevelForModelSwitch(next.thinkingLevel);\n\tconst nextModel = next.model;\n\n\t// Apply model\n\tthis.agent.state.model = nextModel;\n\tthis.sessionManager.appendModelChange(nextModel.provider, nextModel.id);\n\tthis.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);\n\n\t// Apply thinking level.\n\t// - Explicit scoped model thinking level overrides current session level\n\t// - Undefined scoped model thinking level inherits the current session preference\n\t// setThinkingLevel clamps to model capabilities.\n\tthis.setThinkingLevel(thinkingLevel);\n\tthis._refreshBaseSystemPromptFromActiveTools();\n\n\tthis._emitModelChanged(nextModel, currentModel, \"cycle\");\n\tawait this._emitModelSelect(nextModel, currentModel, \"cycle\");\n\n\treturn { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: true };\n}\n\n\nexport async function _cycleAvailableModel(this: AgentSession, direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined> {\n\tconst availableModels = await this._modelRegistry.getAvailable();\n\tif (availableModels.length <= 1) return undefined;\n\n\tconst currentModel = this.model;\n\tlet currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));\n\n\tif (currentIndex === -1) currentIndex = 0;\n\tconst len = availableModels.length;\n\tconst nextIndex = direction === \"forward\" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;\n\tconst selectedModel = availableModels[nextIndex];\n\n\tconst thinkingLevel = this._getThinkingLevelForModelSwitch();\n\tthis.agent.state.model = selectedModel;\n\tthis.sessionManager.appendModelChange(selectedModel.provider, selectedModel.id);\n\tthis.settingsManager.setDefaultModelAndProvider(selectedModel.provider, selectedModel.id);\n\n\t// Re-clamp thinking level for new model's capabilities\n\tthis.setThinkingLevel(thinkingLevel);\n\tthis._refreshBaseSystemPromptFromActiveTools();\n\n\tthis._emitModelChanged(selectedModel, currentModel, \"cycle\");\n\tawait this._emitModelSelect(selectedModel, currentModel, \"cycle\");\n\n\treturn { model: selectedModel, thinkingLevel: this.thinkingLevel, isScoped: false };\n}\n\n// =========================================================================\n// Thinking Level Management\n// =========================================================================\n\n/**\n * Set thinking level.\n * Clamps to model capabilities based on available thinking levels.\n * Saves to session and settings only if the level actually changes.\n */\n\nexport function setThinkingLevel(this: AgentSession, level: ThinkingLevel): void {\n\tconst availableLevels = this.getAvailableThinkingLevels();\n\tconst effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);\n\n\t// Only persist if actually changing\n\tconst previousLevel = this.agent.state.thinkingLevel;\n\tconst isChanging = effectiveLevel !== previousLevel;\n\n\tthis.agent.state.thinkingLevel = effectiveLevel;\n\n\tif (isChanging) {\n\t\tthis.sessionManager.appendThinkingLevelChange(effectiveLevel);\n\t\tthis._refreshBaseSystemPromptFromActiveTools();\n\t\tif (this.supportsThinking() || effectiveLevel !== \"off\") {\n\t\t\tthis.settingsManager.setDefaultThinkingLevel(effectiveLevel);\n\t\t}\n\t\tthis._emit({ type: \"thinking_level_changed\", level: effectiveLevel });\n\t\tvoid this._extensionRunner.emit({\n\t\t\ttype: \"thinking_level_select\",\n\t\t\tlevel: effectiveLevel,\n\t\t\tpreviousLevel,\n\t\t});\n\t}\n}\n\n/**\n * Cycle to next thinking level.\n * @returns New level, or undefined if model doesn't support thinking\n */\n\nexport function cycleThinkingLevel(this: AgentSession): ThinkingLevel | undefined {\n\tif (!this.supportsThinking()) return undefined;\n\n\tconst levels = this.getAvailableThinkingLevels();\n\tconst currentIndex = levels.indexOf(this.thinkingLevel);\n\tconst nextIndex = (currentIndex + 1) % levels.length;\n\tconst nextLevel = levels[nextIndex];\n\n\tthis.setThinkingLevel(nextLevel);\n\treturn nextLevel;\n}\n\n/**\n * Get available thinking levels for current model.\n * The provider will clamp to what the specific model supports internally.\n */\n\nexport function getAvailableThinkingLevels(this: AgentSession): ThinkingLevel[] {\n\tif (!this.model) return THINKING_LEVELS;\n\treturn getSupportedThinkingLevels(this.model) as ThinkingLevel[];\n}\n\n/**\n * Check if current model supports thinking/reasoning.\n */\n\nexport function supportsThinking(this: AgentSession): boolean {\n\treturn !!this.model?.reasoning;\n}\n\n\nexport function _getThinkingLevelForModelSwitch(this: AgentSession, explicitLevel?: ThinkingLevel): ThinkingLevel {\n\tif (explicitLevel !== undefined) {\n\t\treturn explicitLevel;\n\t}\n\tif (!this.supportsThinking()) {\n\t\treturn this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\treturn this.thinkingLevel;\n}\n\n\nexport function _clampThinkingLevel(this: AgentSession, level: ThinkingLevel, _availableLevels: ThinkingLevel[]): ThinkingLevel {\n\treturn this.model ? (clampThinkingLevel(this.model, level) as ThinkingLevel) : \"off\";\n}\n\n\n// =========================================================================\n// Queue Mode Management\n// =========================================================================\n\n/**\n * Set steering message mode.\n * Saves to settings.\n */\n\nexport const agentSessionModelsMethods = {\n\t_getRequiredRequestAuth,\n\t_emitModelChanged,\n\t_emitModelSelect,\n\tsetModel,\n\tcycleModel,\n\t_cycleScopedModel,\n\t_cycleAvailableModel,\n\tsetThinkingLevel,\n\tcycleThinkingLevel,\n\tgetAvailableThinkingLevels,\n\tsupportsThinking,\n\t_getThinkingLevelForModelSwitch,\n\t_clampThinkingLevel,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-models.js","sourceRoot":"","sources":["../../src/core/agent-session-models.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,kBAAkB,EAAE,0BAA0B,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9G,OAAO,EAAE,0BAA0B,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,EAAE,eAAe,EAAyB,MAAM,0BAA0B,CAAC;AAElF,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAqB,KAAiB;IAKlF,IAAI,MAAM,CAAC;IACX,IAAI,CAAC;QACJ,MAAM,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IAClD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,KAAK,GAAG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ACnB,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { ProviderHeaders } from \"@earendil-works/pi-ai\";\nimport type { Api, Model } from \"@earendil-works/pi-ai/compat\";\nimport { clampThinkingLevel, getSupportedThinkingLevels, modelsAreEqual } from \"@earendil-works/pi-ai/compat\";\nimport { formatNoApiKeyFoundMessage } from \"./auth-guidance.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { THINKING_LEVELS, type ModelCycleResult } from \"./agent-session-types.ts\";\n\nexport async function _getRequiredRequestAuth(this: AgentSession, model: Model<Api>): Promise<{\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tenv?: Record<string, string>;\n}> {\n\tlet result;\n\ttry {\n\t\tresult = await this._modelRuntime.getAuth(model);\n\t} catch (error) {\n\t\tconst cause = error instanceof Error ? error.cause : undefined;\n\t\tif (cause instanceof Error && cause.message === \"authHeader requires a resolved API key\") {\n\t\t\tthrow new Error(formatNoApiKeyFoundMessage(model.provider));\n\t\t}\n\t\tthrow error;\n\t}\n\tif (result && (result.auth.apiKey || result.auth.headers)) {\n\t\tconst headers = result.auth.headers\n\t\t\t? Object.fromEntries(Object.entries(result.auth.headers).filter((entry): entry is [string, string] => entry[1] !== null))\n\t\t\t: undefined;\n\t\treturn { apiKey: result.auth.apiKey, headers, env: result.env };\n\t}\n\tif (this._modelRuntime.isUsingOAuth(model.provider)) {\n\t\tthrow new Error(`Authentication failed for \"${model.provider}\". Credentials may have expired or network is unavailable. Run '/login ${model.provider}' to re-authenticate.`);\n\t}\n\tthrow new Error(formatNoApiKeyFoundMessage(model.provider));\n}\n\n/**\n * Install tool hooks once on the Agent instance.\n *\n * The callbacks read `this._extensionRunner` at execution time, so extension reload swaps in the\n * new runner without reinstalling hooks. Extension-specific tool wrappers are still used to adapt\n * registered tool execution to the extension context. Tool call and tool result interception now\n * happens here instead of in wrappers.\n */\n\nexport function _emitModelChanged(this: AgentSession, \n\tnextModel: Model<Api>,\n\tpreviousModel: Model<Api> | undefined,\n\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\",\n): void {\n\tif (modelsAreEqual(previousModel, nextModel)) return;\n\tthis._emit({\n\t\ttype: \"model_changed\",\n\t\tmodel: nextModel,\n\t\tpreviousModel,\n\t\tsource,\n\t});\n}\n\n\nexport async function _emitModelSelect(this: AgentSession, \n\tnextModel: Model<Api>,\n\tpreviousModel: Model<Api> | undefined,\n\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\",\n): Promise<void> {\n\tif (modelsAreEqual(previousModel, nextModel)) return;\n\tawait this._extensionRunner.emit({\n\t\ttype: \"model_select\",\n\t\tmodel: nextModel,\n\t\tpreviousModel,\n\t\tsource,\n\t});\n}\n\n/**\n * Set model directly.\n * Validates that auth is configured, saves to session and settings.\n * @throws Error if no auth is configured for the model\n */\n\nexport async function setModel(this: AgentSession, model: Model<Api>): Promise<void> {\n\tif (!this._modelRuntime.hasConfiguredAuth(model.provider)) {\n\t\tthrow new Error(`No API key for ${model.provider}/${model.id}`);\n\t}\n\n\tconst previousModel = this.model;\n\tconst thinkingLevel = this._getThinkingLevelForModelSwitch();\n\tconst nextModel = model;\n\tthis.agent.state.model = nextModel;\n\tthis.sessionManager.appendModelChange(nextModel.provider, nextModel.id);\n\tthis.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);\n\n\t// Re-clamp thinking level for new model's capabilities\n\tthis.setThinkingLevel(thinkingLevel);\n\tthis._refreshBaseSystemPromptFromActiveTools();\n\n\tthis._emitModelChanged(nextModel, previousModel, \"set\");\n\tawait this._emitModelSelect(nextModel, previousModel, \"set\");\n}\n\n/**\n * Cycle to next/previous model.\n * Uses scoped models (from --models flag) if available, otherwise all available models.\n * @param direction - \"forward\" (default) or \"backward\"\n * @returns The new model info, or undefined if only one model available\n */\n\nexport async function cycleModel(this: AgentSession, direction: \"forward\" | \"backward\" = \"forward\"): Promise<ModelCycleResult | undefined> {\n\tif (this._scopedModels.length > 0) {\n\t\treturn this._cycleScopedModel(direction);\n\t}\n\treturn this._cycleAvailableModel(direction);\n}\n\n\nexport async function _cycleScopedModel(this: AgentSession, direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined> {\n\tconst scopedModels = this._scopedModels.filter((scoped) => this._modelRuntime.hasConfiguredAuth(scoped.model.provider));\n\tif (scopedModels.length <= 1) return undefined;\n\n\tconst currentModel = this.model;\n\tlet currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));\n\n\tif (currentIndex === -1) currentIndex = 0;\n\tconst len = scopedModels.length;\n\tconst nextIndex = direction === \"forward\" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;\n\tconst next = scopedModels[nextIndex];\n\tconst thinkingLevel = this._getThinkingLevelForModelSwitch(next.thinkingLevel);\n\tconst nextModel = next.model;\n\n\t// Apply model\n\tthis.agent.state.model = nextModel;\n\tthis.sessionManager.appendModelChange(nextModel.provider, nextModel.id);\n\tthis.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);\n\n\t// Apply thinking level.\n\t// - Explicit scoped model thinking level overrides current session level\n\t// - Undefined scoped model thinking level inherits the current session preference\n\t// setThinkingLevel clamps to model capabilities.\n\tthis.setThinkingLevel(thinkingLevel);\n\tthis._refreshBaseSystemPromptFromActiveTools();\n\n\tthis._emitModelChanged(nextModel, currentModel, \"cycle\");\n\tawait this._emitModelSelect(nextModel, currentModel, \"cycle\");\n\n\treturn { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: true };\n}\n\n\nexport async function _cycleAvailableModel(this: AgentSession, direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined> {\n\tconst availableModels = await this._modelRuntime.getAvailableSnapshot();\n\tif (availableModels.length <= 1) return undefined;\n\n\tconst currentModel = this.model;\n\tlet currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));\n\n\tif (currentIndex === -1) currentIndex = 0;\n\tconst len = availableModels.length;\n\tconst nextIndex = direction === \"forward\" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;\n\tconst selectedModel = availableModels[nextIndex];\n\n\tconst thinkingLevel = this._getThinkingLevelForModelSwitch();\n\tthis.agent.state.model = selectedModel;\n\tthis.sessionManager.appendModelChange(selectedModel.provider, selectedModel.id);\n\tthis.settingsManager.setDefaultModelAndProvider(selectedModel.provider, selectedModel.id);\n\n\t// Re-clamp thinking level for new model's capabilities\n\tthis.setThinkingLevel(thinkingLevel);\n\tthis._refreshBaseSystemPromptFromActiveTools();\n\n\tthis._emitModelChanged(selectedModel, currentModel, \"cycle\");\n\tawait this._emitModelSelect(selectedModel, currentModel, \"cycle\");\n\n\treturn { model: selectedModel, thinkingLevel: this.thinkingLevel, isScoped: false };\n}\n\n// =========================================================================\n// Thinking Level Management\n// =========================================================================\n\n/**\n * Set thinking level.\n * Clamps to model capabilities based on available thinking levels.\n * Saves to session and settings only if the level actually changes.\n */\n\nexport function setThinkingLevel(this: AgentSession, level: ThinkingLevel): void {\n\tconst availableLevels = this.getAvailableThinkingLevels();\n\tconst effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);\n\n\t// Only persist if actually changing\n\tconst previousLevel = this.agent.state.thinkingLevel;\n\tconst isChanging = effectiveLevel !== previousLevel;\n\n\tthis.agent.state.thinkingLevel = effectiveLevel;\n\n\tif (isChanging) {\n\t\tthis.sessionManager.appendThinkingLevelChange(effectiveLevel);\n\t\tthis._refreshBaseSystemPromptFromActiveTools();\n\t\tif (this.supportsThinking() || effectiveLevel !== \"off\") {\n\t\t\tthis.settingsManager.setDefaultThinkingLevel(effectiveLevel);\n\t\t}\n\t\tthis._emit({ type: \"thinking_level_changed\", level: effectiveLevel });\n\t\tvoid this._extensionRunner.emit({\n\t\t\ttype: \"thinking_level_select\",\n\t\t\tlevel: effectiveLevel,\n\t\t\tpreviousLevel,\n\t\t});\n\t}\n}\n\n/**\n * Cycle to next thinking level.\n * @returns New level, or undefined if model doesn't support thinking\n */\n\nexport function cycleThinkingLevel(this: AgentSession): ThinkingLevel | undefined {\n\tif (!this.supportsThinking()) return undefined;\n\n\tconst levels = this.getAvailableThinkingLevels();\n\tconst currentIndex = levels.indexOf(this.thinkingLevel);\n\tconst nextIndex = (currentIndex + 1) % levels.length;\n\tconst nextLevel = levels[nextIndex];\n\n\tthis.setThinkingLevel(nextLevel);\n\treturn nextLevel;\n}\n\n/**\n * Get available thinking levels for current model.\n * The provider will clamp to what the specific model supports internally.\n */\n\nexport function getAvailableThinkingLevels(this: AgentSession): ThinkingLevel[] {\n\tif (!this.model) return THINKING_LEVELS;\n\treturn getSupportedThinkingLevels(this.model) as ThinkingLevel[];\n}\n\n/**\n * Check if current model supports thinking/reasoning.\n */\n\nexport function supportsThinking(this: AgentSession): boolean {\n\treturn !!this.model?.reasoning;\n}\n\n\nexport function _getThinkingLevelForModelSwitch(this: AgentSession, explicitLevel?: ThinkingLevel): ThinkingLevel {\n\tif (explicitLevel !== undefined) {\n\t\treturn explicitLevel;\n\t}\n\tif (!this.supportsThinking()) {\n\t\treturn this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\treturn this.thinkingLevel;\n}\n\n\nexport function _clampThinkingLevel(this: AgentSession, level: ThinkingLevel, _availableLevels: ThinkingLevel[]): ThinkingLevel {\n\treturn this.model ? (clampThinkingLevel(this.model, level) as ThinkingLevel) : \"off\";\n}\n\n\n// =========================================================================\n// Queue Mode Management\n// =========================================================================\n\n/**\n * Set steering message mode.\n * Saves to settings.\n */\n\nexport const agentSessionModelsMethods = {\n\t_getRequiredRequestAuth,\n\t_emitModelChanged,\n\t_emitModelSelect,\n\tsetModel,\n\tcycleModel,\n\t_cycleScopedModel,\n\t_cycleAvailableModel,\n\tsetThinkingLevel,\n\tcycleThinkingLevel,\n\tgetAvailableThinkingLevels,\n\tsupportsThinking,\n\t_getThinkingLevelForModelSwitch,\n\t_clampThinkingLevel,\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-post-tool-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-post-tool-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAAwC,KAAK,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AAC5G,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAY9F,oFAAoF;AACpF,wBAAsB,yBAAyB,CAC9C,IAAI,EAAE,YAAY,EAClB,QAAQ,EAAE,YAAY,EAAE,EACxB,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,YAAY,EAAE,CAAC,
|
|
1
|
+
{"version":3,"file":"agent-session-post-tool-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-post-tool-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAAwC,KAAK,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AAC5G,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAY9F,oFAAoF;AACpF,wBAAsB,yBAAyB,CAC9C,IAAI,EAAE,YAAY,EAClB,QAAQ,EAAE,YAAY,EAAE,EACxB,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,YAAY,EAAE,CAAC,CAyFzB;AAED,mFAAmF;AACnF,wBAAgB,kCAAkC,CACjD,IAAI,EAAE,YAAY,EAClB,QAAQ,EAAE,YAAY,EAAE,GACtB,YAAY,EAAE,CA+BhB;AAED,MAAM,WAAW,8BAA8B;IAC9C,cAAc,EAAE,MAAM,CAAC;IACvB,MAAM,EAAE,wBAAwB,CAAC;CACjC;AAED,eAAO,MAAM,qCAAqC;;;CAGjD,CAAC"}
|
|
@@ -39,10 +39,8 @@ export async function _preflightPostToolContext(messages, signal) {
|
|
|
39
39
|
try {
|
|
40
40
|
const result = await this._applyVerbatimCompaction({
|
|
41
41
|
resolvePlannerAuth: async (candidate) => {
|
|
42
|
-
const auth = await this.
|
|
43
|
-
return auth.
|
|
44
|
-
? { apiKey: auth.apiKey, headers: auth.headers, baseUrl: auth.baseUrl }
|
|
45
|
-
: undefined;
|
|
42
|
+
const auth = await this._getRequiredRequestAuth(candidate);
|
|
43
|
+
return auth.apiKey || auth.headers ? auth : undefined;
|
|
46
44
|
},
|
|
47
45
|
abortController,
|
|
48
46
|
backupLabel: "auto-compact",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-post-tool-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-post-tool-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAiC,MAAM,uBAAuB,CAAC;AAE5G,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAE/E,SAAS,sBAAsB,CAAC,KAAc;IAC7C,MAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACtE,OAAO,yEAAyE,MAAM,EAAE,CAAC;AAC1F,CAAC;AAED,SAAS,gBAAgB,CAAC,eAAuB,EAAE,cAAsB;IACxE,OAAO,kFAAkF,eAAe,MAAM,cAAc,mDAAmD,CAAC;AACjL,CAAC;AAED,oFAAoF;AACpF,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAE9C,QAAwB,EACxB,MAAoB;IAEpB,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;IACzB,MAAM,QAAQ,GAAG,IAAI,CAAC,eAAe,CAAC,qBAAqB,EAAE,CAAC;IAC9D,IAAI,CAAC,KAAK,IAAI,CAAC,QAAQ,CAAC,OAAO;QAAE,OAAO,QAAQ,CAAC;I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I,eAAe,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;QAC9C,MAAM,YAAY,GAAG,gBAAgB,CAAC,eAAe,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;QAC/E,IAAI,CAAC,iCAAiC,GAAG,YAAY,CAAC;QACtD,IAAI,CAAC,KAAK,CAAC;YACV,IAAI,EAAE,gBAAgB;YACtB,MAAM,EAAE,WAAW;YACnB,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,OAAO,EAAE,KAAK;YACd,SAAS,EAAE,KAAK;YAChB,OAAO,EAAE,IAAI;YACb,YAAY;SACZ,CAAC,CAAC;QACH,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;IAC/B,CAAC;IAED,IAAI,CAAC,KAAK,CAAC;QACV,IAAI,EAAE,gBAAgB;QACtB,MAAM,EAAE,WAAW;QACnB,MAAM,EAAE,OAAO,CAAC,MAAM;QACtB,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,KAAK;QAChB,OAAO,EAAE,IAAI;KACb,CAAC,CAAC;IACH,OAAO,qBAAqB,CAAC;AAC9B,CAAC;AAOD,MAAM,CAAC,MAAM,qCAAqC,GAAG;IACpD,yBAAyB;IACzB,kCAAkC;CAClC,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { estimateContextTokens, shouldCompact, type VerbatimCompactionResult } from \"./compaction/index.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { scrubPreCompactionAssistantUsage } from \"./provider-context-usage.ts\";\n\nfunction postToolFailureMessage(error: unknown): string {\n\tconst detail = error instanceof Error ? error.message : String(error);\n\treturn `Post-tool context compaction failed before the next provider request: ${detail}`;\n}\n\nfunction hardLimitMessage(projectedTokens: number, hardInputLimit: number): string {\n\treturn `Post-tool context remains over the provider hard input limit after compaction (${projectedTokens} > ${hardInputLimit} tokens); the next provider request was not sent.`;\n}\n\n/** Compact tool-expanded context without scheduling a second Agent continuation. */\nexport async function _preflightPostToolContext(\n\tthis: AgentSession,\n\tmessages: AgentMessage[],\n\tsignal?: AbortSignal,\n): Promise<AgentMessage[]> {\n\tconst model = this.model;\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tif (!model || !settings.enabled) return messages;\n\n\tconst hardInputLimit = model.contextWindow;\n\tconst projectedTokens = estimateContextTokens(messages).tokens;\n\tif (!shouldCompact(projectedTokens, hardInputLimit, settings)) return messages;\n\t// Only a context that genuinely will not fit may clear a sub-minimum region.\n\t// The threshold sits at `contextWindow - reserveTokens`, well below the hard\n\t// limit, so a crossing alone is no reason to destroy context.\n\tconst overHardLimit = hardInputLimit > 0 && projectedTokens > hardInputLimit;\n\n\t// Tool-result persistence is ordered on AgentSession's event queue, while Pi\n\t// may reach its next-turn hook as soon as its own listener barrier settles.\n\tawait this._agentEventQueue;\n\tif (this._autoCompactionAbortController) {\n\t\tconst message = postToolFailureMessage(\"another automatic compaction is already active\");\n\t\tthis._postToolCompactionPreflightError = message;\n\t\tthrow new Error(message);\n\t}\n\n\tconst abortController = new AbortController();\n\tconst relayAbort = () => abortController.abort();\n\tsignal?.addEventListener(\"abort\", relayAbort, { once: true });\n\tif (signal?.aborted) abortController.abort();\n\tthis._autoCompactionAbortController = abortController;\n\tthis._emit({ type: \"compaction_start\", reason: \"threshold\", midTurn: true });\n\n\ttry {\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate) => {\n\t\t\t\tconst auth = await this._modelRegistry.getApiKeyAndHeaders(candidate);\n\t\t\t\treturn auth.ok && (auth.apiKey || auth.headers)\n\t\t\t\t\t? { apiKey: auth.apiKey, headers: auth.headers, baseUrl: auth.baseUrl }\n\t\t\t\t\t: undefined;\n\t\t\t},\n\t\t\tabortController,\n\t\t\tbackupLabel: \"auto-compact\",\n\t\t\treason: \"threshold\",\n\t\t\t// Mid-turn: a compaction failure here kills the active turn.\n\t\t\turgency: \"load_bearing\",\n\t\t\t...(overHardLimit ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\t// Nothing was compactable and the projected context still fits, so the\n\t\t\t// follow-up request can be sent unchanged. That is a successful no-op,\n\t\t\t// not a failure: raising here is what killed the active turn.\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"threshold\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tmidTurn: true,\n\t\t\t});\n\t\t\treturn messages;\n\t\t}\n\n\t\tthis._pendingPostToolCompactionGuard = { hardInputLimit, result };\n\t\t// `AgentState.messages` has an asymmetric accessor pair: the setter copies, the\n\t\t// getter hands back the live internal array. Returning it directly would make the\n\t\t// agent loop's `currentContext.messages` an alias of `agent.state.messages`, and\n\t\t// from the next turn on both writers (`runLoop` and the `message_end` reducer)\n\t\t// would append every message twice — duplicate `tool_result` blocks for one\n\t\t// `tool_use` id, which the provider rejects with an unrecoverable 400.\n\t\treturn this.agent.state.messages.slice();\n\t} catch (error) {\n\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\tconst aborted =\n\t\t\tabortController.signal.aborted ||\n\t\t\tdetail === \"Compaction cancelled\" ||\n\t\t\t(error instanceof Error && error.name === \"AbortError\");\n\t\tconst errorMessage = aborted\n\t\t\t? \"Post-tool context compaction was cancelled before the next provider request.\"\n\t\t\t: postToolFailureMessage(error);\n\t\tthis._postToolCompactionPreflightError = errorMessage;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\t...(aborted ? {} : { errorMessage }),\n\t\t});\n\t\tthrow new Error(errorMessage, { cause: error });\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", relayAbort);\n\t\tthis._autoCompactionAbortController = undefined;\n\t}\n}\n\n/** Gate the transformed message context immediately before provider conversion. */\nexport function _finishPostToolCompactionPreflight(\n\tthis: AgentSession,\n\tmessages: AgentMessage[],\n): AgentMessage[] {\n\tconst pending = this._pendingPostToolCompactionGuard;\n\tif (!pending) return messages;\n\tthis._pendingPostToolCompactionGuard = undefined;\n\n\tconst providerBoundMessages = scrubPreCompactionAssistantUsage(messages, this.sessionManager.getBranch());\n\tconst projectedTokens = estimateContextTokens(providerBoundMessages).tokens;\n\tif (projectedTokens > pending.hardInputLimit) {\n\t\tconst errorMessage = hardLimitMessage(projectedTokens, pending.hardInputLimit);\n\t\tthis._postToolCompactionPreflightError = errorMessage;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult: pending.result,\n\t\t\taborted: false,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\terrorMessage,\n\t\t});\n\t\tthrow new Error(errorMessage);\n\t}\n\n\tthis._emit({\n\t\ttype: \"compaction_end\",\n\t\treason: \"threshold\",\n\t\tresult: pending.result,\n\t\taborted: false,\n\t\twillRetry: false,\n\t\tmidTurn: true,\n\t});\n\treturn providerBoundMessages;\n}\n\nexport interface PendingPostToolCompactionGuard {\n\thardInputLimit: number;\n\tresult: VerbatimCompactionResult;\n}\n\nexport const agentSessionPostToolCompactionMethods = {\n\t_preflightPostToolContext,\n\t_finishPostToolCompactionPreflight,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-post-tool-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-post-tool-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAiC,MAAM,uBAAuB,CAAC;AAE5G,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAE/E,SAAS,sBAAsB,CAAC,KAAc;IAC7C,MAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACtE,OAAO,yEAAyE,M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,OAAO;QAAE,OAAO,QAAQ,CAAC;IAC9B,IAAI,CAAC,+BAA+B,GAAG,SAAS,CAAC;IAEjD,MAAM,qBAAqB,GAAG,gCAAgC,CAAC,QAAQ,EAAE,IAAI,CAAC,cAAc,CAAC,SAAS,EAAE,CAAC,CAAC;IAC1G,MAAM,eAAe,GAAG,qBAAqB,CAAC,qBAAqB,CAAC,CAAC,MAAM,CAAC;IAC5E,IAAI,eAAe,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;QAC9C,MAAM,YAAY,GAAG,gBAAgB,CAAC,eAAe,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;QAC/E,IAAI,CAAC,iCAAiC,GAAG,YAAY,CAAC;QACtD,IAAI,CAAC,KAAK,CAAC;YACV,IAAI,EAAE,gBAAgB;YACtB,MAAM,EAAE,WAAW;YACnB,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,OAAO,EAAE,KAAK;YACd,SAAS,EAAE,KAAK;YAChB,OAAO,EAAE,IAAI;YACb,YAAY;SACZ,CAAC,CAAC;QACH,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;IAC/B,CAAC;IAED,IAAI,CAAC,KAAK,CAAC;QACV,IAAI,EAAE,gBAAgB;QACtB,MAAM,EAAE,WAAW;QACnB,MAAM,EAAE,OAAO,CAAC,MAAM;QACtB,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,KAAK;QAChB,OAAO,EAAE,IAAI;KACb,CAAC,CAAC;IACH,OAAO,qBAAqB,CAAC;AAC9B,CAAC;AAOD,MAAM,CAAC,MAAM,qCAAqC,GAAG;IACpD,yBAAyB;IACzB,kCAAkC;CAClC,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { estimateContextTokens, shouldCompact, type VerbatimCompactionResult } from \"./compaction/index.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { scrubPreCompactionAssistantUsage } from \"./provider-context-usage.ts\";\n\nfunction postToolFailureMessage(error: unknown): string {\n\tconst detail = error instanceof Error ? error.message : String(error);\n\treturn `Post-tool context compaction failed before the next provider request: ${detail}`;\n}\n\nfunction hardLimitMessage(projectedTokens: number, hardInputLimit: number): string {\n\treturn `Post-tool context remains over the provider hard input limit after compaction (${projectedTokens} > ${hardInputLimit} tokens); the next provider request was not sent.`;\n}\n\n/** Compact tool-expanded context without scheduling a second Agent continuation. */\nexport async function _preflightPostToolContext(\n\tthis: AgentSession,\n\tmessages: AgentMessage[],\n\tsignal?: AbortSignal,\n): Promise<AgentMessage[]> {\n\tconst model = this.model;\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tif (!model || !settings.enabled) return messages;\n\n\tconst hardInputLimit = model.contextWindow;\n\tconst projectedTokens = estimateContextTokens(messages).tokens;\n\tif (!shouldCompact(projectedTokens, hardInputLimit, settings)) return messages;\n\t// Only a context that genuinely will not fit may clear a sub-minimum region.\n\t// The threshold sits at `contextWindow - reserveTokens`, well below the hard\n\t// limit, so a crossing alone is no reason to destroy context.\n\tconst overHardLimit = hardInputLimit > 0 && projectedTokens > hardInputLimit;\n\n\t// Tool-result persistence is ordered on AgentSession's event queue, while Pi\n\t// may reach its next-turn hook as soon as its own listener barrier settles.\n\tawait this._agentEventQueue;\n\tif (this._autoCompactionAbortController) {\n\t\tconst message = postToolFailureMessage(\"another automatic compaction is already active\");\n\t\tthis._postToolCompactionPreflightError = message;\n\t\tthrow new Error(message);\n\t}\n\n\tconst abortController = new AbortController();\n\tconst relayAbort = () => abortController.abort();\n\tsignal?.addEventListener(\"abort\", relayAbort, { once: true });\n\tif (signal?.aborted) abortController.abort();\n\tthis._autoCompactionAbortController = abortController;\n\tthis._emit({ type: \"compaction_start\", reason: \"threshold\", midTurn: true });\n\n\ttry {\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate) => {\n\t\t\t\tconst auth = await this._getRequiredRequestAuth(candidate);\n\t\t\t\treturn auth.apiKey || auth.headers ? auth : undefined;\n\t\t\t},\n\t\t\tabortController,\n\t\t\tbackupLabel: \"auto-compact\",\n\t\t\treason: \"threshold\",\n\t\t\t// Mid-turn: a compaction failure here kills the active turn.\n\t\t\turgency: \"load_bearing\",\n\t\t\t...(overHardLimit ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\t// Nothing was compactable and the projected context still fits, so the\n\t\t\t// follow-up request can be sent unchanged. That is a successful no-op,\n\t\t\t// not a failure: raising here is what killed the active turn.\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"threshold\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tmidTurn: true,\n\t\t\t});\n\t\t\treturn messages;\n\t\t}\n\n\t\tthis._pendingPostToolCompactionGuard = { hardInputLimit, result };\n\t\t// `AgentState.messages` has an asymmetric accessor pair: the setter copies, the\n\t\t// getter hands back the live internal array. Returning it directly would make the\n\t\t// agent loop's `currentContext.messages` an alias of `agent.state.messages`, and\n\t\t// from the next turn on both writers (`runLoop` and the `message_end` reducer)\n\t\t// would append every message twice — duplicate `tool_result` blocks for one\n\t\t// `tool_use` id, which the provider rejects with an unrecoverable 400.\n\t\treturn this.agent.state.messages.slice();\n\t} catch (error) {\n\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\tconst aborted =\n\t\t\tabortController.signal.aborted ||\n\t\t\tdetail === \"Compaction cancelled\" ||\n\t\t\t(error instanceof Error && error.name === \"AbortError\");\n\t\tconst errorMessage = aborted\n\t\t\t? \"Post-tool context compaction was cancelled before the next provider request.\"\n\t\t\t: postToolFailureMessage(error);\n\t\tthis._postToolCompactionPreflightError = errorMessage;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\t...(aborted ? {} : { errorMessage }),\n\t\t});\n\t\tthrow new Error(errorMessage, { cause: error });\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", relayAbort);\n\t\tthis._autoCompactionAbortController = undefined;\n\t}\n}\n\n/** Gate the transformed message context immediately before provider conversion. */\nexport function _finishPostToolCompactionPreflight(\n\tthis: AgentSession,\n\tmessages: AgentMessage[],\n): AgentMessage[] {\n\tconst pending = this._pendingPostToolCompactionGuard;\n\tif (!pending) return messages;\n\tthis._pendingPostToolCompactionGuard = undefined;\n\n\tconst providerBoundMessages = scrubPreCompactionAssistantUsage(messages, this.sessionManager.getBranch());\n\tconst projectedTokens = estimateContextTokens(providerBoundMessages).tokens;\n\tif (projectedTokens > pending.hardInputLimit) {\n\t\tconst errorMessage = hardLimitMessage(projectedTokens, pending.hardInputLimit);\n\t\tthis._postToolCompactionPreflightError = errorMessage;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult: pending.result,\n\t\t\taborted: false,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\terrorMessage,\n\t\t});\n\t\tthrow new Error(errorMessage);\n\t}\n\n\tthis._emit({\n\t\ttype: \"compaction_end\",\n\t\treason: \"threshold\",\n\t\tresult: pending.result,\n\t\taborted: false,\n\t\twillRetry: false,\n\t\tmidTurn: true,\n\t});\n\treturn providerBoundMessages;\n}\n\nexport interface PendingPostToolCompactionGuard {\n\thardInputLimit: number;\n\tresult: VerbatimCompactionResult;\n}\n\nexport const agentSessionPostToolCompactionMethods = {\n\t_preflightPostToolContext,\n\t_finishPostToolCompactionPreflight,\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-prompt.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-prompt.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,8BAA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,mBAAmB,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAwB5E;AAED;;;;;;;GAOG;AAEH,wBAAsB,KAAK,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAWpG;AAED;;;;;;GAMG;AAEH,wBAAsB,QAAQ,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAWvG;AAED;;GAEG;AAEH,wBAAsB,eAAe,CAAC,IAAI,EAAE,YAAY,EACvD,OAAO,EAAE,MAAM,GAAG,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,EAChD,OAAO,CAAC,EAAE;IACT,SAAS,CAAC,EAAE,OAAO,GAAG,UAAU,CAAC;IACjC,kBAAkB,CAAC,EAAE,iCAAiC,CAAC,oBAAoB,CAAC,CAAC;CAC7E,GACC,OAAO,CAAC,IAAI,CAAC,CA+Bf;AAED;;;;GAIG;AAEH,eAAO,MAAM,yBAAyB;;;;;;;;;;;CAWrC,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
import { runCallback } from "./callback-activity.js";
|
|
3
3
|
import { ATOMIC_GUIDE_COMMAND_NAME, ATOMIC_GUIDE_HELP_CHOICES, atomicGuideModeForChoice, getAtomicGuideMessage, isAtomicGuideHelpChoice, normalizeAtomicGuideMode } from "./atomic-guide-command.js";
|
|
4
|
-
import {
|
|
4
|
+
import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage, formatUnresolvedModelMessage } from "./auth-guidance.js";
|
|
5
5
|
import { expandPromptTemplate } from "./prompt-templates.js";
|
|
6
6
|
import { stripFrontmatter } from "../utils/frontmatter.js";
|
|
7
7
|
import { resolveWorkflowStageDeliveryTarget } from "./agent-session-delivery-forwarding.js";
|
|
@@ -96,18 +96,14 @@ export async function prompt(text, options) {
|
|
|
96
96
|
if (typeof resolvedProvider !== "string" || resolvedProvider.length === 0) {
|
|
97
97
|
throw new Error(formatUnresolvedModelMessage(this.model));
|
|
98
98
|
}
|
|
99
|
-
if (!this.
|
|
99
|
+
if (!this._modelRuntime.hasConfiguredAuth(this.model.provider)) {
|
|
100
100
|
// A failed credential-store load (for example auth.json briefly locked
|
|
101
101
|
// by a concurrent process, or invalid JSON) leaves an empty in-memory
|
|
102
102
|
// credential set. That would otherwise be misreported here as
|
|
103
103
|
// "No API key found" even though the credentials exist on disk. Surface
|
|
104
104
|
// the real load failure instead so configured providers are not falsely
|
|
105
105
|
// reported as unauthenticated (issue #1431).
|
|
106
|
-
const
|
|
107
|
-
if (authLoadError) {
|
|
108
|
-
throw new Error(formatAuthStorageLoadFailedMessage(this.model.provider, authLoadError), { cause: authLoadError });
|
|
109
|
-
}
|
|
110
|
-
const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
|
|
106
|
+
const isOAuth = this._modelRuntime.isUsingOAuth(this.model.provider);
|
|
111
107
|
if (isOAuth) {
|
|
112
108
|
throw new Error(`Authentication failed for "${this.model.provider}". ` +
|
|
113
109
|
`Credentials may have expired or network is unavailable. ` +
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-prompt.js","sourceRoot":"","sources":["../../src/core/agent-session-prompt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAGvC,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,yBAAyB,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrM,OAAO,EAAE,kCAAkC,EAAE,0BAA0B,EAAE,4BAA4B,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAA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agent-core\";\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport { runCallback } from \"./callback-activity.ts\";\nimport { ATOMIC_GUIDE_COMMAND_NAME, ATOMIC_GUIDE_HELP_CHOICES, atomicGuideModeForChoice, getAtomicGuideMessage, isAtomicGuideHelpChoice, normalizeAtomicGuideMode } from \"./atomic-guide-command.ts\";\nimport { formatAuthStorageLoadFailedMessage, formatNoApiKeyFoundMessage, formatNoModelSelectedMessage, formatUnresolvedModelMessage } from \"./auth-guidance.ts\";\nimport { expandPromptTemplate } from \"./prompt-templates.ts\";\nimport { stripFrontmatter } from \"../utils/frontmatter.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { resolveWorkflowStageDeliveryTarget } from \"./agent-session-delivery-forwarding.ts\";\nimport type { PromptOptions } from \"./agent-session-types.ts\";\n\ntype UserMessageDeliveryAction = \"prompt\" | \"steer\" | \"followUp\" | \"handled\";\n\ntype PromptOptionsWithWorkflowDelivery = PromptOptions & {\n\treadonly __workflowDelivery?: {\n\t\treadonly beforeDelivery?: () => void;\n\t\t/** Called only after an idle prompt has synchronously entered the agent turn. */\n\t\treadonly promptStarted?: () => void;\n\t\treadonly delivered?: (action: UserMessageDeliveryAction) => void;\n\t};\n};\n\n/** Dispatch registered slash commands without changing the raw queue pause gate. */\nexport async function tryExecuteSessionSlashCommand(\n session: Pick<AgentSession, \"_tryExecuteBuiltinSlashCommand\" | \"_tryExecuteExtensionCommand\">,\n text: string,\n): Promise<boolean> {\n if (!text.startsWith(\"/\")) return false;\n if (await session._tryExecuteBuiltinSlashCommand(text)) return true;\n return session._tryExecuteExtensionCommand(text);\n}\n\nexport async function prompt(this: AgentSession, text: string, options?: PromptOptions): Promise<void> {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner.prompt(text, options);\n\tconst expandPromptTemplates = options?.expandPromptTemplates ?? true;\n\tconst preflightResult = options?.preflightResult;\n\tconst workflowDelivery = (options as PromptOptionsWithWorkflowDelivery | undefined)?.__workflowDelivery;\n\tlet messages: AgentMessage[] | undefined;\n\n try {\n // Authorize workflow delivery before commands or input extensions can perform side effects.\n // A later terminal transition cannot retroactively reject input accepted at this boundary.\n workflowDelivery?.beforeDelivery?.();\n // Registered slash commands execute without releasing ordinary queued work.\n // Unknown slash input continues through the normal paused admission path.\n if (expandPromptTemplates && await tryExecuteSessionSlashCommand(this, text)) {\n workflowDelivery?.delivered?.(\"handled\");\n preflightResult?.(true);\n return;\n }\n // A controlled pause is an admission gate, including the idle gap after\n // abort settles. Preserve the raw user payload without running input hooks,\n // compaction, or a provider turn; explicit resume makes it eligible again.\n if (this._queuedMessagesPaused) {\n const delivery = options?.streamingBehavior === \"followUp\" ? \"followUp\" : \"steer\";\n if (delivery === \"followUp\") await this._queueFollowUp(text, options?.images);\n else await this._queueSteer(text, options?.images);\n workflowDelivery?.delivered?.(delivery);\n preflightResult?.(true);\n return;\n }\n\n\n\t\t// Emit input event for extension interception (before skill/template expansion)\n\t\tlet currentText = text;\n\t\tlet currentImages = options?.images;\n\t\tif (this._extensionRunner.hasHandlers(\"input\")) {\n\t\t\tconst inputResult = await this._extensionRunner.emitInput(\n\t\t\t\tcurrentText,\n\t\t\t\tcurrentImages,\n\t\t\t\toptions?.source ?? \"interactive\",\n\t\t\t\tthis.isStreaming ? options?.streamingBehavior : undefined,\n\t\t\t);\n\t\t\tif (inputResult.action === \"handled\") {\n\t\t\t\tworkflowDelivery?.delivered?.(\"handled\");\n\t\t\t\tpreflightResult?.(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (inputResult.action === \"transform\") {\n\t\t\t\tcurrentText = inputResult.text;\n\t\t\t\tcurrentImages = inputResult.images ?? currentImages;\n\t\t\t}\n\t\t}\n\n\t\t// Expand skill commands (/skill:name args) and prompt templates (/template args)\n\t\tlet expandedText = currentText;\n\t\tif (expandPromptTemplates) {\n\t\t\texpandedText = this._expandSkillCommand(expandedText);\n\t\t\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\t\t}\n\n\t\t// If streaming, queue via steer() or followUp() based on option\n\t\tif (this.isStreaming) {\n\t\t\tif (!options?.streamingBehavior) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (options.streamingBehavior === \"followUp\") {\n\t\t\t\tawait this._queueFollowUp(expandedText, currentImages);\n\t\t\t} else {\n\t\t\t\tawait this._queueSteer(expandedText, currentImages);\n\t\t\t}\n\t\t\tworkflowDelivery?.delivered?.(options.streamingBehavior);\n\t\t\tpreflightResult?.(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Flush any pending bash messages before the new prompt\n\t\tthis._flushPendingBashMessages();\n\n\t\t// Validate model\n\t\tif (!this.model) {\n\t\t\tthrow new Error(formatNoModelSelectedMessage());\n\t\t}\n\n\t\t// Defensive guard: a model that never resolved to a real provider\n\t\t// (for example an unknown/unresolved model id that reached this path\n\t\t// as a bare string) has no `provider`, which would otherwise fail deep\n\t\t// in auth resolution as the confusing \"No API key found for undefined\".\n\t\t// Surface a clear, accurate \"unknown model\" error instead.\n\t\tconst resolvedProvider = (this.model as { provider?: unknown }).provider;\n\t\tif (typeof resolvedProvider !== \"string\" || resolvedProvider.length === 0) {\n\t\t\tthrow new Error(formatUnresolvedModelMessage(this.model));\n\t\t}\n\n\t\tif (!this._modelRegistry.hasConfiguredAuth(this.model)) {\n\t\t\t// A failed credential-store load (for example auth.json briefly locked\n\t\t\t// by a concurrent process, or invalid JSON) leaves an empty in-memory\n\t\t\t// credential set. That would otherwise be misreported here as\n\t\t\t// \"No API key found\" even though the credentials exist on disk. Surface\n\t\t\t// the real load failure instead so configured providers are not falsely\n\t\t\t// reported as unauthenticated (issue #1431).\n\t\t\tconst authLoadError = this._modelRegistry.authStorage.getLoadError();\n\t\t\tif (authLoadError) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\tformatAuthStorageLoadFailedMessage(this.model.provider, authLoadError),\n\t\t\t\t\t{ cause: authLoadError },\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst isOAuth = this._modelRegistry.isUsingOAuth(this.model);\n\t\t\tif (isOAuth) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Authentication failed for \"${this.model.provider}\". ` +\n\t\t\t\t\t\t`Credentials may have expired or network is unavailable. ` +\n\t\t\t\t\t\t`Run '/login ${this.model.provider}' to re-authenticate.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(formatNoApiKeyFoundMessage(this.model.provider));\n\t\t}\n\n\t\t// Check if we need to compact before sending (catches aborted responses)\n\t\tconst lastAssistant = this._findLastAssistantMessage();\n\t\tif (lastAssistant) {\n\t\t\tawait this._checkCompaction(lastAssistant, false);\n\t\t}\n\n\t\t// Build messages array (custom message if any, then user message)\n\t\tmessages = [];\n\n\t\t// Add user message\n\t\tconst userContent: (TextContent | ImageContent)[] = [{ type: \"text\", text: expandedText }];\n\t\tif (currentImages) {\n\t\t\tuserContent.push(...currentImages);\n\t\t}\n\t\tmessages.push({\n\t\t\trole: \"user\",\n\t\t\tcontent: userContent,\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\n\t\t// Inject any pending \"nextTurn\" messages as context alongside the user message\n\t\tfor (const msg of this._pendingNextTurnMessages) {\n\t\t\tmessages.push(msg);\n\t\t}\n\t\tthis._pendingNextTurnMessages = [];\n\n\t\t// Emit before_agent_start extension event\n\t\tconst result = await this._extensionRunner.emitBeforeAgentStart(\n\t\t\texpandedText,\n\t\t\tcurrentImages,\n\t\t\tthis._baseSystemPrompt,\n\t\t\tthis._baseSystemPromptOptions,\n\t\t);\n\t\t// Add all custom messages from extensions\n\t\tif (result?.messages) {\n\t\t\tfor (const msg of result.messages) {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"custom\",\n\t\t\t\t\tcustomType: msg.customType,\n\t\t\t\t\tcontent: msg.content ?? [],\n\t\t\t\t\tdisplay: msg.display,\n\t\t\t\t\tdetails: msg.details,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\t// Apply extension-modified system prompt, or reset to base\n\t\tif (result?.systemPrompt !== undefined) {\n\t\t\tthis._systemPromptOverride = result.systemPrompt;\n\t\t\tthis.agent.state.systemPrompt = result.systemPrompt;\n\t\t} else {\n\t\t\t// Ensure we're using the base prompt (in case previous turn had modifications)\n\t\t\tthis._systemPromptOverride = undefined;\n\t\t\tthis.agent.state.systemPrompt = this._baseSystemPrompt;\n\t\t}\n\t} catch (error) {\n\t\tpreflightResult?.(false);\n\t\tthrow error;\n\t}\n\n\tpreflightResult?.(true);\n\tconst turn = this._runAgentPrompt(messages, workflowDelivery?.promptStarted);\n\tworkflowDelivery?.delivered?.(\"prompt\");\n\tawait turn;\n}\n\n\nexport async function _runAgentPrompt(\n\tthis: AgentSession,\n\tmessages: AgentMessage | AgentMessage[],\n\tpromptStarted?: () => void,\n): Promise<void> {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) {\n\t\tif (owner._queuedMessagesPaused) {\n\t\t\tconst items = Array.isArray(messages) ? messages : [messages];\n\t\t\tfor (const message of items) owner._queueAgentMessage(message, \"steer\");\n\t\t\treturn;\n\t\t}\n\t\treturn owner._runAgentPrompt(messages, promptStarted);\n\t}\n\ttry {\n\t\tconst turn = this.agent.prompt(messages);\n\t\tif (this.isStreaming) promptStarted?.();\n\t\tawait turn;\n\t\tawait this.waitForRetry();\n\t\tawait this._continueQueuedAgentMessages();\n\t\tawait this._awaitPendingPostCompactionContinuation();\n\t} finally {\n\t\tthis._systemPromptOverride = undefined;\n\t\tawait this._agentEventQueue;\n\t\tif (typeof this._extensionRunner?.emit === \"function\") {\n\t\t\tawait this._extensionRunner.emit({ type: \"agent_settled\" });\n\t\t}\n\t\tthis._emit?.({ type: \"agent_settled\" });\n\t}\n}\n\nexport async function _runAgentContinue(this: AgentSession): Promise<void> {\n\tawait this.agent.continue();\n\tawait this.waitForRetry();\n\tawait this._continueQueuedAgentMessages();\n}\n\n\nexport async function _continueQueuedAgentMessages(this: AgentSession): Promise<void> {\n\tawait this._agentEventQueue;\n\n\twhile (!this._queuedMessagesPaused && this.agent.hasQueuedMessages()) {\n\t\tawait this.agent.continue();\n\t\tawait this.waitForRetry();\n\t\tawait this._agentEventQueue;\n\t}\n}\n\n/**\n * Try to execute a built-in slash command. Returns true if command was found and executed.\n */\n\nexport async function _tryExecuteBuiltinSlashCommand(this: AgentSession, text: string): Promise<boolean> {\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\tif (commandName !== ATOMIC_GUIDE_COMMAND_NAME) return false;\n\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1);\n\tconst mode = normalizeAtomicGuideMode(args);\n\tif (mode === \"help\" && this._extensionUIContext) {\n\t\tconst choice = await this._extensionUIContext.select(\"Atomic. Select where to start:\", [\n\t\t\t...ATOMIC_GUIDE_HELP_CHOICES,\n\t\t]);\n\t\tif (!choice || !isAtomicGuideHelpChoice(choice)) return true;\n\t\tawait this.sendCustomMessage(\n\t\t\t{\n\t\t\t\tcustomType: \"atomic\",\n\t\t\t\tcontent: getAtomicGuideMessage(atomicGuideModeForChoice(choice), this._cwd),\n\t\t\t\tdisplay: true,\n\t\t\t},\n\t\t\t{ triggerTurn: false },\n\t\t);\n\t\treturn true;\n\t}\n\n\tawait this.sendCustomMessage(\n\t\t{\n\t\t\tcustomType: \"atomic\",\n\t\t\tcontent: getAtomicGuideMessage(mode, this._cwd),\n\t\t\tdisplay: true,\n\t\t},\n\t\t{ triggerTurn: false },\n\t);\n\treturn true;\n}\n\n/**\n * Try to execute an extension command. Returns true if command was found and executed.\n */\n\nexport async function _tryExecuteExtensionCommand(this: AgentSession, text: string): Promise<boolean> {\n\t// Parse command name and args\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1);\n\n\tconst command = this._extensionRunner.getCommand(commandName);\n\tif (!command) return false;\n\n\t// Get command context from extension runner (includes session control methods)\n\tconst ctx = this._extensionRunner.createCommandContext();\n\n\ttry {\n\t\tawait runCallback(\n\t\t\t{ kind: \"extension.hook\", name: `command:${commandName}`, sourcePath: command.sourceInfo.path },\n\t\t\t() => command.handler(args, ctx),\n\t\t);\n\t\treturn true;\n\t} catch (err) {\n\t\t// Emit error via extension runner\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: `command:${commandName}`,\n\t\t\tevent: \"command\",\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn true;\n\t}\n}\n\n/**\n * Expand skill commands (/skill:name args) to their full content.\n * Returns the expanded text, or the original text if not a skill command or skill not found.\n * Emits errors via extension runner if file read fails.\n */\n\nexport function _expandSkillCommand(this: AgentSession, text: string): string {\n\tif (!text.startsWith(\"/skill:\")) return text;\n\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1).trim();\n\n\tconst skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);\n\tif (!skill) return text; // Unknown skill, pass through\n\n\ttry {\n\t\tconst content = readFileSync(skill.filePath, \"utf-8\");\n\t\tconst body = stripFrontmatter(content).trim();\n\t\tconst skillBlock = `<skill name=\"${skill.name}\" location=\"${skill.filePath}\">\\nReferences are relative to ${skill.baseDir}.\\n\\n${body}\\n</skill>`;\n\t\treturn args ? `${skillBlock}\\n\\n${args}` : skillBlock;\n\t} catch (err) {\n\t\t// Emit error like extension commands do\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: skill.filePath,\n\t\t\tevent: \"skill_expansion\",\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn text; // Return original on error\n\t}\n}\n\n/**\n * Queue a steering message while the agent is running.\n * Delivered after the current assistant turn finishes executing its tool calls,\n * before the next LLM call.\n * Expands skill commands and prompt templates. Errors on extension commands.\n * @param images Optional image attachments to include with the message\n * @throws Error if text is an extension command\n */\n\nexport async function steer(this: AgentSession, text: string, images?: ImageContent[]): Promise<void> {\n\t// Check for extension commands (cannot be queued)\n\tif (text.startsWith(\"/\")) {\n\t\tthis._throwIfExtensionCommand(text);\n\t}\n\n\t// Expand skill commands and prompt templates\n\tlet expandedText = this._expandSkillCommand(text);\n\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\n\tawait this._queueSteer(expandedText, images);\n}\n\n/**\n * Queue a follow-up message to be processed after the agent finishes.\n * Delivered only when agent has no more tool calls or steering messages.\n * Expands skill commands and prompt templates. Errors on extension commands.\n * @param images Optional image attachments to include with the message\n * @throws Error if text is an extension command\n */\n\nexport async function followUp(this: AgentSession, text: string, images?: ImageContent[]): Promise<void> {\n\t// Check for extension commands (cannot be queued)\n\tif (text.startsWith(\"/\")) {\n\t\tthis._throwIfExtensionCommand(text);\n\t}\n\n\t// Expand skill commands and prompt templates\n\tlet expandedText = this._expandSkillCommand(text);\n\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\n\tawait this._queueFollowUp(expandedText, images);\n}\n\n/**\n * Internal: Queue a steering message (already expanded, no extension command check).\n */\n\nexport async function sendUserMessage(this: AgentSession,\n\tcontent: string | (TextContent | ImageContent)[],\n\toptions?: {\n\t\tdeliverAs?: \"steer\" | \"followUp\";\n\t\t__workflowDelivery?: PromptOptionsWithWorkflowDelivery[\"__workflowDelivery\"];\n\t},\n): Promise<void> {\n\t// Normalize content to text string + optional images\n\tlet text: string;\n\tlet images: ImageContent[] | undefined;\n\n\tif (typeof content === \"string\") {\n\t\ttext = content;\n\t} else {\n\t\tconst textParts: string[] = [];\n\t\timages = [];\n\t\tfor (const part of content) {\n\t\t\tif (part.type === \"text\") {\n\t\t\t\ttextParts.push(part.text);\n\t\t\t} else {\n\t\t\t\timages.push(part);\n\t\t\t}\n\t\t}\n\t\ttext = textParts.join(\"\\n\");\n\t\tif (images.length === 0) images = undefined;\n\t}\n\n\t// Use prompt() with expandPromptTemplates: false to skip command handling and template expansion.\n\t// The private delivery hook lets workflow routing report and gate the branch\n\t// selected after asynchronous input/compaction extension preflight.\n\tawait this.prompt(text, {\n\t\texpandPromptTemplates: false,\n\t\tstreamingBehavior: options?.deliverAs,\n\t\timages,\n\t\tsource: \"extension\",\n\t\t__workflowDelivery: options?.__workflowDelivery,\n\t} as PromptOptionsWithWorkflowDelivery);\n}\n\n/**\n * Clear all queued messages and return them.\n * Useful for restoring to editor when user aborts.\n * @returns Object with steering and followUp arrays\n */\n\nexport const agentSessionPromptMethods = {\n\tprompt,\n\t_runAgentPrompt,\n\t_runAgentContinue,\n\t_continueQueuedAgentMessages,\n\t_tryExecuteBuiltinSlashCommand,\n\t_tryExecuteExtensionCommand,\n\t_expandSkillCommand,\n\tsteer,\n\tfollowUp,\n\tsendUserMessage,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-prompt.js","sourceRoot":"","sources":["../../src/core/agent-session-prompt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAGvC,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,yBAAyB,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrM,OAAO,EAAE,0BAA0B,EAAE,4BAA4B,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAC5H,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAE3D,OAAO,EAAE,k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IAAI,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;gBAC1B,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAC3B,CAAC;iBAAM,CAAC;gBACP,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACnB,CAAC;QACF,CAAC;QACD,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC5B,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,MAAM,GAAG,SAAS,CAAC;IAC7C,CAAC;IAED,kGAAkG;IAClG,6EAA6E;IAC7E,oEAAoE;IACpE,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE;QACvB,qBAAqB,EAAE,KAAK;QAC5B,iBAAiB,EAAE,OAAO,EAAE,SAAS;QACrC,MAAM;QACN,MAAM,EAAE,WAAW;QACnB,kBAAkB,EAAE,OAAO,EAAE,kBAAkB;KACV,CAAC,CAAC;AACzC,CAAC;AAED;;;;GAIG;AAEH,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACxC,MAAM;IACN,eAAe;IACf,iBAAiB;IACjB,4BAA4B;IAC5B,8BAA8B;IAC9B,2BAA2B;IAC3B,mBAAmB;IACnB,KAAK;IACL,QAAQ;IACR,eAAe;CACf,CAAC","sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport { runCallback } from \"./callback-activity.ts\";\nimport { ATOMIC_GUIDE_COMMAND_NAME, ATOMIC_GUIDE_HELP_CHOICES, atomicGuideModeForChoice, getAtomicGuideMessage, isAtomicGuideHelpChoice, normalizeAtomicGuideMode } from \"./atomic-guide-command.ts\";\nimport { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage, formatUnresolvedModelMessage } from \"./auth-guidance.ts\";\nimport { expandPromptTemplate } from \"./prompt-templates.ts\";\nimport { stripFrontmatter } from \"../utils/frontmatter.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { resolveWorkflowStageDeliveryTarget } from \"./agent-session-delivery-forwarding.ts\";\nimport type { PromptOptions } from \"./agent-session-types.ts\";\n\ntype UserMessageDeliveryAction = \"prompt\" | \"steer\" | \"followUp\" | \"handled\";\n\ntype PromptOptionsWithWorkflowDelivery = PromptOptions & {\n\treadonly __workflowDelivery?: {\n\t\treadonly beforeDelivery?: () => void;\n\t\t/** Called only after an idle prompt has synchronously entered the agent turn. */\n\t\treadonly promptStarted?: () => void;\n\t\treadonly delivered?: (action: UserMessageDeliveryAction) => void;\n\t};\n};\n\n/** Dispatch registered slash commands without changing the raw queue pause gate. */\nexport async function tryExecuteSessionSlashCommand(\n session: Pick<AgentSession, \"_tryExecuteBuiltinSlashCommand\" | \"_tryExecuteExtensionCommand\">,\n text: string,\n): Promise<boolean> {\n if (!text.startsWith(\"/\")) return false;\n if (await session._tryExecuteBuiltinSlashCommand(text)) return true;\n return session._tryExecuteExtensionCommand(text);\n}\n\nexport async function prompt(this: AgentSession, text: string, options?: PromptOptions): Promise<void> {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner.prompt(text, options);\n\tconst expandPromptTemplates = options?.expandPromptTemplates ?? true;\n\tconst preflightResult = options?.preflightResult;\n\tconst workflowDelivery = (options as PromptOptionsWithWorkflowDelivery | undefined)?.__workflowDelivery;\n\tlet messages: AgentMessage[] | undefined;\n\n try {\n // Authorize workflow delivery before commands or input extensions can perform side effects.\n // A later terminal transition cannot retroactively reject input accepted at this boundary.\n workflowDelivery?.beforeDelivery?.();\n // Registered slash commands execute without releasing ordinary queued work.\n // Unknown slash input continues through the normal paused admission path.\n if (expandPromptTemplates && await tryExecuteSessionSlashCommand(this, text)) {\n workflowDelivery?.delivered?.(\"handled\");\n preflightResult?.(true);\n return;\n }\n // A controlled pause is an admission gate, including the idle gap after\n // abort settles. Preserve the raw user payload without running input hooks,\n // compaction, or a provider turn; explicit resume makes it eligible again.\n if (this._queuedMessagesPaused) {\n const delivery = options?.streamingBehavior === \"followUp\" ? \"followUp\" : \"steer\";\n if (delivery === \"followUp\") await this._queueFollowUp(text, options?.images);\n else await this._queueSteer(text, options?.images);\n workflowDelivery?.delivered?.(delivery);\n preflightResult?.(true);\n return;\n }\n\n\n\t\t// Emit input event for extension interception (before skill/template expansion)\n\t\tlet currentText = text;\n\t\tlet currentImages = options?.images;\n\t\tif (this._extensionRunner.hasHandlers(\"input\")) {\n\t\t\tconst inputResult = await this._extensionRunner.emitInput(\n\t\t\t\tcurrentText,\n\t\t\t\tcurrentImages,\n\t\t\t\toptions?.source ?? \"interactive\",\n\t\t\t\tthis.isStreaming ? options?.streamingBehavior : undefined,\n\t\t\t);\n\t\t\tif (inputResult.action === \"handled\") {\n\t\t\t\tworkflowDelivery?.delivered?.(\"handled\");\n\t\t\t\tpreflightResult?.(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (inputResult.action === \"transform\") {\n\t\t\t\tcurrentText = inputResult.text;\n\t\t\t\tcurrentImages = inputResult.images ?? currentImages;\n\t\t\t}\n\t\t}\n\n\t\t// Expand skill commands (/skill:name args) and prompt templates (/template args)\n\t\tlet expandedText = currentText;\n\t\tif (expandPromptTemplates) {\n\t\t\texpandedText = this._expandSkillCommand(expandedText);\n\t\t\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\t\t}\n\n\t\t// If streaming, queue via steer() or followUp() based on option\n\t\tif (this.isStreaming) {\n\t\t\tif (!options?.streamingBehavior) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (options.streamingBehavior === \"followUp\") {\n\t\t\t\tawait this._queueFollowUp(expandedText, currentImages);\n\t\t\t} else {\n\t\t\t\tawait this._queueSteer(expandedText, currentImages);\n\t\t\t}\n\t\t\tworkflowDelivery?.delivered?.(options.streamingBehavior);\n\t\t\tpreflightResult?.(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Flush any pending bash messages before the new prompt\n\t\tthis._flushPendingBashMessages();\n\n\t\t// Validate model\n\t\tif (!this.model) {\n\t\t\tthrow new Error(formatNoModelSelectedMessage());\n\t\t}\n\n\t\t// Defensive guard: a model that never resolved to a real provider\n\t\t// (for example an unknown/unresolved model id that reached this path\n\t\t// as a bare string) has no `provider`, which would otherwise fail deep\n\t\t// in auth resolution as the confusing \"No API key found for undefined\".\n\t\t// Surface a clear, accurate \"unknown model\" error instead.\n\t\tconst resolvedProvider = (this.model as { provider?: unknown }).provider;\n\t\tif (typeof resolvedProvider !== \"string\" || resolvedProvider.length === 0) {\n\t\t\tthrow new Error(formatUnresolvedModelMessage(this.model));\n\t\t}\n\n\t\tif (!this._modelRuntime.hasConfiguredAuth(this.model.provider)) {\n\t\t\t// A failed credential-store load (for example auth.json briefly locked\n\t\t\t// by a concurrent process, or invalid JSON) leaves an empty in-memory\n\t\t\t// credential set. That would otherwise be misreported here as\n\t\t\t// \"No API key found\" even though the credentials exist on disk. Surface\n\t\t\t// the real load failure instead so configured providers are not falsely\n\t\t\t// reported as unauthenticated (issue #1431).\n\t\t\tconst isOAuth = this._modelRuntime.isUsingOAuth(this.model.provider);\n\t\t\tif (isOAuth) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Authentication failed for \"${this.model.provider}\". ` +\n\t\t\t\t\t\t`Credentials may have expired or network is unavailable. ` +\n\t\t\t\t\t\t`Run '/login ${this.model.provider}' to re-authenticate.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(formatNoApiKeyFoundMessage(this.model.provider));\n\t\t}\n\n\t\t// Check if we need to compact before sending (catches aborted responses)\n\t\tconst lastAssistant = this._findLastAssistantMessage();\n\t\tif (lastAssistant) {\n\t\t\tawait this._checkCompaction(lastAssistant, false);\n\t\t}\n\n\t\t// Build messages array (custom message if any, then user message)\n\t\tmessages = [];\n\n\t\t// Add user message\n\t\tconst userContent: (TextContent | ImageContent)[] = [{ type: \"text\", text: expandedText }];\n\t\tif (currentImages) {\n\t\t\tuserContent.push(...currentImages);\n\t\t}\n\t\tmessages.push({\n\t\t\trole: \"user\",\n\t\t\tcontent: userContent,\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\n\t\t// Inject any pending \"nextTurn\" messages as context alongside the user message\n\t\tfor (const msg of this._pendingNextTurnMessages) {\n\t\t\tmessages.push(msg);\n\t\t}\n\t\tthis._pendingNextTurnMessages = [];\n\n\t\t// Emit before_agent_start extension event\n\t\tconst result = await this._extensionRunner.emitBeforeAgentStart(\n\t\t\texpandedText,\n\t\t\tcurrentImages,\n\t\t\tthis._baseSystemPrompt,\n\t\t\tthis._baseSystemPromptOptions,\n\t\t);\n\t\t// Add all custom messages from extensions\n\t\tif (result?.messages) {\n\t\t\tfor (const msg of result.messages) {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"custom\",\n\t\t\t\t\tcustomType: msg.customType,\n\t\t\t\t\tcontent: msg.content ?? [],\n\t\t\t\t\tdisplay: msg.display,\n\t\t\t\t\tdetails: msg.details,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\t// Apply extension-modified system prompt, or reset to base\n\t\tif (result?.systemPrompt !== undefined) {\n\t\t\tthis._systemPromptOverride = result.systemPrompt;\n\t\t\tthis.agent.state.systemPrompt = result.systemPrompt;\n\t\t} else {\n\t\t\t// Ensure we're using the base prompt (in case previous turn had modifications)\n\t\t\tthis._systemPromptOverride = undefined;\n\t\t\tthis.agent.state.systemPrompt = this._baseSystemPrompt;\n\t\t}\n\t} catch (error) {\n\t\tpreflightResult?.(false);\n\t\tthrow error;\n\t}\n\n\tpreflightResult?.(true);\n\tconst turn = this._runAgentPrompt(messages, workflowDelivery?.promptStarted);\n\tworkflowDelivery?.delivered?.(\"prompt\");\n\tawait turn;\n}\n\n\nexport async function _runAgentPrompt(\n\tthis: AgentSession,\n\tmessages: AgentMessage | AgentMessage[],\n\tpromptStarted?: () => void,\n): Promise<void> {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) {\n\t\tif (owner._queuedMessagesPaused) {\n\t\t\tconst items = Array.isArray(messages) ? messages : [messages];\n\t\t\tfor (const message of items) owner._queueAgentMessage(message, \"steer\");\n\t\t\treturn;\n\t\t}\n\t\treturn owner._runAgentPrompt(messages, promptStarted);\n\t}\n\ttry {\n\t\tconst turn = this.agent.prompt(messages);\n\t\tif (this.isStreaming) promptStarted?.();\n\t\tawait turn;\n\t\tawait this.waitForRetry();\n\t\tawait this._continueQueuedAgentMessages();\n\t\tawait this._awaitPendingPostCompactionContinuation();\n\t} finally {\n\t\tthis._systemPromptOverride = undefined;\n\t\tawait this._agentEventQueue;\n\t\tif (typeof this._extensionRunner?.emit === \"function\") {\n\t\t\tawait this._extensionRunner.emit({ type: \"agent_settled\" });\n\t\t}\n\t\tthis._emit?.({ type: \"agent_settled\" });\n\t}\n}\n\nexport async function _runAgentContinue(this: AgentSession): Promise<void> {\n\tawait this.agent.continue();\n\tawait this.waitForRetry();\n\tawait this._continueQueuedAgentMessages();\n}\n\n\nexport async function _continueQueuedAgentMessages(this: AgentSession): Promise<void> {\n\tawait this._agentEventQueue;\n\n\twhile (!this._queuedMessagesPaused && this.agent.hasQueuedMessages()) {\n\t\tawait this.agent.continue();\n\t\tawait this.waitForRetry();\n\t\tawait this._agentEventQueue;\n\t}\n}\n\n/**\n * Try to execute a built-in slash command. Returns true if command was found and executed.\n */\n\nexport async function _tryExecuteBuiltinSlashCommand(this: AgentSession, text: string): Promise<boolean> {\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\tif (commandName !== ATOMIC_GUIDE_COMMAND_NAME) return false;\n\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1);\n\tconst mode = normalizeAtomicGuideMode(args);\n\tif (mode === \"help\" && this._extensionUIContext) {\n\t\tconst choice = await this._extensionUIContext.select(\"Atomic. Select where to start:\", [\n\t\t\t...ATOMIC_GUIDE_HELP_CHOICES,\n\t\t]);\n\t\tif (!choice || !isAtomicGuideHelpChoice(choice)) return true;\n\t\tawait this.sendCustomMessage(\n\t\t\t{\n\t\t\t\tcustomType: \"atomic\",\n\t\t\t\tcontent: getAtomicGuideMessage(atomicGuideModeForChoice(choice), this._cwd),\n\t\t\t\tdisplay: true,\n\t\t\t},\n\t\t\t{ triggerTurn: false },\n\t\t);\n\t\treturn true;\n\t}\n\n\tawait this.sendCustomMessage(\n\t\t{\n\t\t\tcustomType: \"atomic\",\n\t\t\tcontent: getAtomicGuideMessage(mode, this._cwd),\n\t\t\tdisplay: true,\n\t\t},\n\t\t{ triggerTurn: false },\n\t);\n\treturn true;\n}\n\n/**\n * Try to execute an extension command. Returns true if command was found and executed.\n */\n\nexport async function _tryExecuteExtensionCommand(this: AgentSession, text: string): Promise<boolean> {\n\t// Parse command name and args\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1);\n\n\tconst command = this._extensionRunner.getCommand(commandName);\n\tif (!command) return false;\n\n\t// Get command context from extension runner (includes session control methods)\n\tconst ctx = this._extensionRunner.createCommandContext();\n\n\ttry {\n\t\tawait runCallback(\n\t\t\t{ kind: \"extension.hook\", name: `command:${commandName}`, sourcePath: command.sourceInfo.path },\n\t\t\t() => command.handler(args, ctx),\n\t\t);\n\t\treturn true;\n\t} catch (err) {\n\t\t// Emit error via extension runner\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: `command:${commandName}`,\n\t\t\tevent: \"command\",\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn true;\n\t}\n}\n\n/**\n * Expand skill commands (/skill:name args) to their full content.\n * Returns the expanded text, or the original text if not a skill command or skill not found.\n * Emits errors via extension runner if file read fails.\n */\n\nexport function _expandSkillCommand(this: AgentSession, text: string): string {\n\tif (!text.startsWith(\"/skill:\")) return text;\n\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1).trim();\n\n\tconst skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);\n\tif (!skill) return text; // Unknown skill, pass through\n\n\ttry {\n\t\tconst content = readFileSync(skill.filePath, \"utf-8\");\n\t\tconst body = stripFrontmatter(content).trim();\n\t\tconst skillBlock = `<skill name=\"${skill.name}\" location=\"${skill.filePath}\">\\nReferences are relative to ${skill.baseDir}.\\n\\n${body}\\n</skill>`;\n\t\treturn args ? `${skillBlock}\\n\\n${args}` : skillBlock;\n\t} catch (err) {\n\t\t// Emit error like extension commands do\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: skill.filePath,\n\t\t\tevent: \"skill_expansion\",\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn text; // Return original on error\n\t}\n}\n\n/**\n * Queue a steering message while the agent is running.\n * Delivered after the current assistant turn finishes executing its tool calls,\n * before the next LLM call.\n * Expands skill commands and prompt templates. Errors on extension commands.\n * @param images Optional image attachments to include with the message\n * @throws Error if text is an extension command\n */\n\nexport async function steer(this: AgentSession, text: string, images?: ImageContent[]): Promise<void> {\n\t// Check for extension commands (cannot be queued)\n\tif (text.startsWith(\"/\")) {\n\t\tthis._throwIfExtensionCommand(text);\n\t}\n\n\t// Expand skill commands and prompt templates\n\tlet expandedText = this._expandSkillCommand(text);\n\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\n\tawait this._queueSteer(expandedText, images);\n}\n\n/**\n * Queue a follow-up message to be processed after the agent finishes.\n * Delivered only when agent has no more tool calls or steering messages.\n * Expands skill commands and prompt templates. Errors on extension commands.\n * @param images Optional image attachments to include with the message\n * @throws Error if text is an extension command\n */\n\nexport async function followUp(this: AgentSession, text: string, images?: ImageContent[]): Promise<void> {\n\t// Check for extension commands (cannot be queued)\n\tif (text.startsWith(\"/\")) {\n\t\tthis._throwIfExtensionCommand(text);\n\t}\n\n\t// Expand skill commands and prompt templates\n\tlet expandedText = this._expandSkillCommand(text);\n\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\n\tawait this._queueFollowUp(expandedText, images);\n}\n\n/**\n * Internal: Queue a steering message (already expanded, no extension command check).\n */\n\nexport async function sendUserMessage(this: AgentSession,\n\tcontent: string | (TextContent | ImageContent)[],\n\toptions?: {\n\t\tdeliverAs?: \"steer\" | \"followUp\";\n\t\t__workflowDelivery?: PromptOptionsWithWorkflowDelivery[\"__workflowDelivery\"];\n\t},\n): Promise<void> {\n\t// Normalize content to text string + optional images\n\tlet text: string;\n\tlet images: ImageContent[] | undefined;\n\n\tif (typeof content === \"string\") {\n\t\ttext = content;\n\t} else {\n\t\tconst textParts: string[] = [];\n\t\timages = [];\n\t\tfor (const part of content) {\n\t\t\tif (part.type === \"text\") {\n\t\t\t\ttextParts.push(part.text);\n\t\t\t} else {\n\t\t\t\timages.push(part);\n\t\t\t}\n\t\t}\n\t\ttext = textParts.join(\"\\n\");\n\t\tif (images.length === 0) images = undefined;\n\t}\n\n\t// Use prompt() with expandPromptTemplates: false to skip command handling and template expansion.\n\t// The private delivery hook lets workflow routing report and gate the branch\n\t// selected after asynchronous input/compaction extension preflight.\n\tawait this.prompt(text, {\n\t\texpandPromptTemplates: false,\n\t\tstreamingBehavior: options?.deliverAs,\n\t\timages,\n\t\tsource: \"extension\",\n\t\t__workflowDelivery: options?.__workflowDelivery,\n\t} as PromptOptionsWithWorkflowDelivery);\n}\n\n/**\n * Clear all queued messages and return them.\n * Useful for restoring to editor when user aborts.\n * @returns Object with steering and followUp arrays\n */\n\nexport const agentSessionPromptMethods = {\n\tprompt,\n\t_runAgentPrompt,\n\t_runAgentContinue,\n\t_continueQueuedAgentMessages,\n\t_tryExecuteBuiltinSlashCommand,\n\t_tryExecuteExtensionCommand,\n\t_expandSkillCommand,\n\tsteer,\n\tfollowUp,\n\tsendUserMessage,\n};\n"]}
|
|
@@ -8,7 +8,7 @@ function modelLabel(model) {
|
|
|
8
8
|
return model ? `${model.provider}/${model.id}` : "unknown model";
|
|
9
9
|
}
|
|
10
10
|
function resolveFallbackModel(value) {
|
|
11
|
-
return resolveConfiguredFallbackModel(value, this.
|
|
11
|
+
return resolveConfiguredFallbackModel(value, this._modelRuntime, this.model?.provider ?? this.settingsManager.getDefaultProvider());
|
|
12
12
|
}
|
|
13
13
|
function hasProviderTransportDiagnostic(value, seen = new Set(), includeMessageFields = false) {
|
|
14
14
|
if (value === null || value === undefined || seen.has(value))
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-retry.js","sourceRoot":"","sources":["../../src/core/agent-session-retry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAElE,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACrG,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,oBAAoB,IAAI,8BAA8B,EAAE,MAAM,sBAAsB,CAAC;AAC3G,OAAO,EAAE,6BAA6B,EAAE,MAAM,mBAAmB,CAAC;AAIlE,SAAS,UAAU,CAAC,KAA6B;IAChD,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,eAAe,CAAC;AAClE,CAAC;AAED,SAAS,oBAAoB,CAAqB,KAAa;IAC9D,OAAO,8BAA8B,CACpC,KAAK,EACL,IAAI,CAAC,cAAc,EACnB,IAA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AAC,aAAa,EAAE,CAAC;QACzB,OAAO;IACR,CAAC;IAED,MAAM,IAAI,CAAC,aAAa,CAAC;IACzB,MAAM,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;AAChC,CAAC;AAED,kDAAkD;AAElD,MAAM,UAAU,mBAAmB,CAAqB,OAAgB;IACvE,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;AAC/C,CAAC;AAED,4EAA4E;AAC5E,iBAAiB;AACjB,4EAA4E;AAE5E;;;;;;;GAOG;AAEH,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACvC,iBAAiB;IACjB,kBAAkB;IAClB,gBAAgB;IAChB,qBAAqB;IACrB,yBAAyB;IACzB,UAAU;IACV,YAAY;IACZ,mBAAmB;CACnB,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { isRetryableAssistantError } from \"@earendil-works/pi-ai\";\nimport type { Api, AssistantMessage, Model } from \"@earendil-works/pi-ai/compat\";\nimport { clampThinkingLevel, isContextOverflow, modelsAreEqual } from \"@earendil-works/pi-ai/compat\";\nimport { sleep } from \"../utils/sleep.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport { fallbackKey, resolveFallbackModel as resolveConfiguredFallbackModel } from \"./fallback-models.ts\";\nimport { isCodexTokenInvalidationError } from \"./codex-errors.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\n\nfunction modelLabel(model: Model<Api> | undefined): string {\n\treturn model ? `${model.provider}/${model.id}` : \"unknown model\";\n}\n\nfunction resolveFallbackModel(this: AgentSession, value: string): { model: Model<Api>; thinkingLevel?: ThinkingLevel } | undefined {\n\treturn resolveConfiguredFallbackModel(\n\t\tvalue,\n\t\tthis._modelRegistry,\n\t\tthis.model?.provider ?? this.settingsManager.getDefaultProvider(),\n\t);\n}\n\nfunction hasProviderTransportDiagnostic(value: unknown, seen = new Set<unknown>(), includeMessageFields = false): boolean {\n\tif (value === null || value === undefined || seen.has(value)) return false;\n\tif (typeof value !== \"object\") {\n\t\treturn /provider_transport_failure|websocket.*error|sse.*404/i.test(String(value));\n\t}\n\tseen.add(value);\n\tconst record = value as Record<string, unknown>;\n\tconst fields = includeMessageFields\n\t\t? [record.type, record.code, record.name, record.message, record.errorMessage, record.status, record.statusCode]\n\t\t: [record.type, record.code, record.name, record.status, record.statusCode];\n\tfor (const field of fields) {\n\t\t if (typeof field === \"string\" || typeof field === \"number\") {\n\t\t\tif (/provider_transport_failure|websocket.*error|sse.*404|\\b404\\b/i.test(String(field))) return true;\n\t\t}\n\t}\n\tfor (const nested of [record.error, record.cause, ...(Array.isArray(record.diagnostics) ? record.diagnostics : [])]) {\n\t\tif (hasProviderTransportDiagnostic(nested, seen, true)) return true;\n\t}\n\treturn false;\n}\n\nfunction hasProviderModelUnavailableDiagnostic(value: unknown, seen = new Set<unknown>(), includeMessageFields = false): boolean {\n\tif (value === null || value === undefined || seen.has(value)) return false;\n\tif (typeof value !== \"object\") return false;\n\tseen.add(value);\n\tconst record = value as Record<string, unknown>;\n\tconst fields = includeMessageFields\n\t\t? [record.type, record.code, record.name, record.message, record.errorMessage]\n\t\t: [record.type, record.code, record.name, record.errorMessage];\n\tfor (const field of fields) {\n\t\tif (typeof field === \"string\" && /model(?:[_\\s-].*)?(?:not[_\\s-]?found|unavailable|unknown|disabled)|model[_-]?not[_-]?found/i.test(field)) return true;\n\t}\n\tfor (const nested of [record.error, record.cause, ...(Array.isArray(record.diagnostics) ? record.diagnostics : [])]) {\n\t\tif (hasProviderModelUnavailableDiagnostic(nested, seen, true)) return true;\n\t}\n\treturn false;\n}\nexport function _isRetryableError(this: AgentSession, message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\") return false;\n\n\t// Context overflow is handled by compaction, not retry\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\n\t// A definitive Codex authentication rejection is terminal. It takes\n\t// precedence over transport diagnostics recorded during WebSocket-to-SSE\n\t// fallback so those earlier diagnostics cannot trigger a pointless retry.\n\tconst provider = message.provider || this.model?.provider;\n\tif (provider && isCodexTokenInvalidationError(provider, message.errorMessage)) return false;\n\n\tif (hasProviderTransportDiagnostic(message) || hasProviderModelUnavailableDiagnostic(message)) return true;\n\t// Keep Atomic-specific terminal exclusions above, then inherit pi-ai's\n\t// transport classifier (including getaddrinfo, ENOTFOUND, and EAI_AGAIN).\n\tif (isRetryableAssistantError(message)) return true;\n\tif (!message.errorMessage) return false;\n\n\tconst err = message.errorMessage;\n\n\t// Safety triggers surface through structured API signals that pi-ai maps to\n\t// stopReason \"error\":\n\t// - Anthropic `refusal` stops become pi-ai's canned \"The model refused to\n\t// complete the request\" error message;\n\t// - OpenAI-style APIs (and github-copilot CAPI, which also maps spurious\n\t// Gemini RECITATION/safety blocks this way) surface\n\t// `finish_reason: content_filter`.\n\t// Spurious safety triggers are common in agentic settings, so these are\n\t// re-requested like transient failures, bounded by maxRetries (issue #1608).\n\tif (/refused to complete the request|finish.?reason:?\\s*content.?filter/i.test(err)) {\n\t\treturn true;\n\t}\n\n\t// Match: overloaded_error, provider returned error, rate limit, quota/usage-limit exhaustion (e.g. \"Codex error: The usage limit has been reached\" — retryable so configured fallbackModels can advance to a provider/model with remaining headroom), 429, 500, 502, 503, 504, service unavailable, network/connection errors (including connection lost), WebSocket transport closes/errors, fetch failed, premature stream endings, HTTP/2 closed before response, terminated, retry delay exceeded, and a bare/transient provider finish_reason \"error\" (e.g. github-copilot Gemini's CAPI mapping of MALFORMED_FUNCTION_CALL/OTHER/UNEXPECTED_TOOL_CALL). These are provider-agnostic transient failures.\n\treturn /overloaded|provider.?returned.?error|rate.?limit|usage.?limit|quota|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?lost|websocket.?closed|websocket.?error|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|stream ended before message_stop|http2 request did not get a response|timed? out|timeout|terminated|retry delay|finish.?reason:?\\s*error/i.test(\n\t\terr,\n\t);\n}\n\n/**\n * Detect a degenerate empty completion: the provider ended the stream with no\n * usable content and zero output tokens. Seen with github-copilot Gemini models\n * that emit finish_reason \"stop\" (or a tool-use stop) with an empty content array\n * and 0 output tokens, leaving the turn dead instead of producing the next step.\n *\n * These are treated as retryable so the harness re-issues the request rather than\n * silently stopping mid-task. Guarded tightly (no text, no tool call, no thinking,\n * and output === 0) so legitimate non-empty turns are never matched.\n *\n * Intentionally provider-agnostic (not gated to Copilot Gemini): a degenerate\n * empty turn is a transient failure for any provider. It is bounded by\n * `maxRetries` and falls through to normal handling on exhaustion.\n */\n\nexport function _isEmptyCompletion(this: AgentSession, message: AssistantMessage): boolean {\n\t// Only \"completed\" stop reasons can be deceptively empty. Real errors are handled\n\t// by _isRetryableError; aborted/length turns are intentional outcomes.\n\tif (message.stopReason !== \"stop\" && message.stopReason !== \"toolUse\") return false;\n\n\tconst content = message.content;\n\tif (Array.isArray(content)) {\n\t\tconst hasContent = content.some((part) => {\n\t\t\tif (part.type === \"text\") return part.text.trim().length > 0;\n\t\t\tif (part.type === \"toolCall\") return true;\n\t\t\tif (part.type === \"thinking\") return part.redacted === true || part.thinking.trim().length > 0;\n\t\t\treturn true; // unknown part types count as content\n\t\t});\n\t\tif (hasContent) return false;\n\t}\n\n\t// A turn that produced output tokens but no surfaced content is not \"empty\"\n\t// (e.g. reasoning-only responses); leave those alone. Note: a provider that\n\t// fails to report `usage` (output defaults to 0) would make every\n\t// content-less turn match here; the dual requirement (empty content AND zero\n\t// output) keeps that false-positive risk low in practice.\n\treturn (message.usage?.output ?? 0) === 0;\n}\n\n/**\n * Detect a canned provider-side safety refusal that arrives as a *successful*\n * completion instead of an error. Seen with github-copilot GPT models under\n * heavy contexts: the endpoint intercepts the request and returns exactly\n * \"I'm sorry, but I cannot assist with that request.\" with zero usage and a\n * spurious stopReason of \"length\" (or \"stop\"), which the agent would otherwise\n * accept as the final answer and dead-end the turn (issue #1608).\n *\n * A text heuristic is unavoidable here: the OpenAI Responses API does signal\n * these interceptions structurally (`refusal` content parts plus\n * `incomplete_details.reason: \"content_filter\"`), but pi-ai's normalization\n * folds refusal parts into plain text blocks and collapses the `incomplete`\n * status to stopReason \"length\", discarding the reason — so no structured\n * refusal marker survives on the AssistantMessage. Providers whose safety\n * signals DO survive as structured errors (Anthropic refusal stops, OpenAI\n * `finish_reason: content_filter`) are matched in _isRetryableError instead.\n *\n * Guarded tightly so legitimate turns are never matched:\n * - only non-error completion stops (\"stop\" | \"length\" | \"toolUse\");\n * - content must be a single short canned refusal text — any tool call,\n * thinking block, or additional prose disqualifies the message;\n * - usage.output must be 0: a genuine model-authored refusal bills output\n * tokens, while the intercepted canned refusal reports zero usage.\n *\n * Treated as retryable so the harness re-requests the model call rather than\n * accepting the refusal; bounded by `maxRetries` like every other retry path.\n */\n\nconst CANNED_SAFETY_REFUSAL_PATTERN =\n\t/^(?:i['’]?m sorry[,.]?\\s+(?:but\\s+)?|sorry[,.]?\\s+(?:but\\s+)?)?i\\s+(?:cannot|can['’]?t|can\\s+not|am\\s+unable\\s+to|am\\s+not\\s+able\\s+to)\\s+(?:assist|help|comply|continue)(?:\\s+with)?(?:\\s+(?:that|this))?(?:\\s+(?:request|task))?\\.?$/i;\n\nconst CANNED_SAFETY_REFUSAL_MAX_LENGTH = 120;\n\nexport function _isSafetyRefusal(this: AgentSession, message: AssistantMessage): boolean {\n\t// Real errors are handled by _isRetryableError; aborts are user-initiated.\n\tif (message.stopReason !== \"stop\" && message.stopReason !== \"length\" && message.stopReason !== \"toolUse\") {\n\t\treturn false;\n\t}\n\n\tconst content = message.content;\n\tif (!Array.isArray(content) || content.length === 0) return false;\n\n\tlet text = \"\";\n\tfor (const part of content) {\n\t\tif (part.type === \"toolCall\") return false;\n\t\tif (part.type === \"thinking\" && (part.redacted === true || part.thinking.trim().length > 0)) return false;\n\t\tif (part.type === \"text\") text += part.text;\n\t}\n\ttext = text.trim();\n\tif (text.length === 0 || text.length > CANNED_SAFETY_REFUSAL_MAX_LENGTH) return false;\n\tif (!CANNED_SAFETY_REFUSAL_PATTERN.test(text)) return false;\n\n\t// Zero billed output distinguishes a provider interception from legitimate\n\t// model-authored refusal prose, which is never auto-retried.\n\treturn (message.usage?.output ?? 0) === 0;\n}\n\n/**\n * Handle retryable errors with exponential backoff.\n * @returns true if retry was initiated, false if max retries exceeded or disabled\n */\n\nexport async function _trySwitchToFallbackModel(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tif (this._fallbackModels.length === 0 || !this.model) return false;\n\n\tthis._fallbackAttemptedKeys.add(fallbackKey(this.model, this.thinkingLevel));\n\tconst fromModel = this.model;\n\tfor (const rawCandidate of this._fallbackModels) {\n\t\tconst candidate = resolveFallbackModel.call(this, rawCandidate);\n\t\tif (!candidate) continue;\n\t\tconst key = fallbackKey(candidate.model, candidate.thinkingLevel);\n\t\tif (this._fallbackAttemptedKeys.has(key)) continue;\n\t\tconst nextModel = candidate.model;\n\t\tconst nextLevel = clampThinkingLevel(\n\t\t\tnextModel,\n\t\t\tcandidate.thinkingLevel ?? this.settingsManager.getDefaultThinkingLevel() ?? this.thinkingLevel ?? DEFAULT_THINKING_LEVEL,\n\t\t) as ThinkingLevel;\n\t\tif (modelsAreEqual(candidate.model, fromModel) && nextLevel === this.thinkingLevel) continue;\n\t\tif (this._retryAttempt > 0) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\tsuccess: true,\n\t\t\t\tattempt: Math.max(0, this._retryAttempt - 1),\n\t\t\t});\n\t\t}\n\t\tthis._fallbackAttemptedKeys.add(key);\n\t\tthis._emit({\n\t\t\ttype: \"model_fallback_start\",\n\t\t\tfrom: modelLabel(fromModel),\n\t\t\tto: `${nextModel.provider}/${nextModel.id}`,\n\t\t\treason: message.errorMessage || \"Retryable model error\",\n\t\t\tattempt: this._fallbackAttemptedKeys.size - 1,\n\t\t});\n\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1]?.role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tthis.agent.state.model = nextModel;\n\t\tthis.sessionManager.appendModelChange(nextModel.provider, nextModel.id);\n\t\tthis.agent.state.thinkingLevel = nextLevel;\n\t\tthis.sessionManager.appendThinkingLevelChange(nextLevel);\n\t\tthis._refreshBaseSystemPromptFromActiveTools();\n\t\tthis._emitModelChanged(nextModel, fromModel, \"fallback\");\n\t\tawait this._emitModelSelect(nextModel, fromModel, \"fallback\");\n\t\tthis._retryAttempt = 0;\n\n\t\tsetTimeout(() => {\n\t\t\tthis.agent.continue().then(\n\t\t\t\t() => {\n\t\t\t\t\t// A resolved continuation may still have produced an assistant\n\t\t\t\t\t// error that will be classified by agent_end and may advance to\n\t\t\t\t\t// the next fallback. Do not emit a successful fallback end here;\n\t\t\t\t\t// agent_end/turn_end clear UI state for successful turns, while\n\t\t\t\t\t// fallback exhaustion emits the failure end event.\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tconst finalError = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tthis._emit({ type: \"model_fallback_end\", success: false, from: modelLabel(fromModel), to: modelLabel(nextModel), finalError });\n\t\t\t\t\tthis._retryAttempt = 0;\n\t\t\t\t\tthis._resolveRetry();\n\t\t\t\t},\n\t\t\t);\n\t\t}, 0);\n\t\treturn true;\n\t}\n\tthis._emit({ type: \"model_fallback_end\", success: false, from: modelLabel(fromModel), finalError: message.errorMessage });\n\treturn false;\n}\n\nexport async function _handleRetryableError(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tconst settings = this.settingsManager.getRetrySettings();\n\tif (!settings.enabled) {\n\t\treturn this._trySwitchToFallbackModel(message);\n\t}\n\n\t// Retry promise is created synchronously in _handleAgentEvent for agent_end.\n\t// Keep a defensive fallback here in case a future refactor bypasses that path.\n\tif (!this._retryPromise) {\n\t\tthis._retryPromise = new Promise((resolve) => {\n\t\t\tthis._retryResolve = resolve;\n\t\t});\n\t}\n\n\tthis._retryAttempt++;\n\n\tif (this._retryAttempt > settings.maxRetries) {\n\t\tif (await this._trySwitchToFallbackModel(message)) {\n\t\t\treturn true;\n\t\t}\n\t\t// Max retries exceeded, emit final failure and reset\n\t\tthis._emit({\n\t\t\ttype: \"auto_retry_end\",\n\t\t\tsuccess: false,\n\t\t\tattempt: this._retryAttempt - 1,\n\t\t\tfinalError: message.errorMessage,\n\t\t});\n\t\tthis._retryAttempt = 0;\n\t\tthis._resolveRetry(); // Resolve so waitForRetry() completes\n\t\treturn false;\n\t}\n\n\tconst delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);\n\n\tthis._emit({\n\t\ttype: \"auto_retry_start\",\n\t\tattempt: this._retryAttempt,\n\t\tmaxAttempts: settings.maxRetries,\n\t\tdelayMs,\n\t\terrorMessage: message.errorMessage || \"Unknown error\",\n\t});\n\n\t// Remove error message from agent state (keep in session for history)\n\tconst messages = this.agent.state.messages;\n\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n\n\t// Wait with exponential backoff (abortable)\n\tthis._retryAbortController = new AbortController();\n\ttry {\n\t\tawait sleep(delayMs, this._retryAbortController.signal);\n\t} catch {\n\t\t// Aborted during sleep - emit end event so UI can clean up\n\t\tconst attempt = this._retryAttempt;\n\t\tthis._retryAttempt = 0;\n\t\tthis._retryAbortController = undefined;\n\t\tthis._emit({\n\t\t\ttype: \"auto_retry_end\",\n\t\t\tsuccess: false,\n\t\t\tattempt,\n\t\t\tfinalError: \"Retry cancelled\",\n\t\t});\n\t\tthis._resolveRetry();\n\t\treturn false;\n\t}\n\tthis._retryAbortController = undefined;\n\n\t// Retry via continue() - use setTimeout to break out of event handler chain\n\tsetTimeout(() => {\n\t\tthis.agent.continue().catch(() => {\n\t\t\t// Retry failed - will be caught by next agent_end\n\t\t});\n\t}, 0);\n\n\treturn true;\n}\n\n/**\n * Cancel in-progress retry.\n */\n\nexport function abortRetry(this: AgentSession): void {\n\tthis._retryAbortController?.abort();\n\t// Note: _retryAttempt is reset in the catch block of _autoRetry\n\tthis._resolveRetry();\n}\n\n/**\n * Wait for any in-progress retry to complete.\n * Returns immediately if no retry is in progress.\n */\n\nexport async function waitForRetry(this: AgentSession): Promise<void> {\n\tif (!this._retryPromise) {\n\t\treturn;\n\t}\n\n\tawait this._retryPromise;\n\tawait this.agent.waitForIdle();\n}\n\n/** Whether auto-retry is currently in progress */\n\nexport function setAutoRetryEnabled(this: AgentSession, enabled: boolean): void {\n\tthis.settingsManager.setRetryEnabled(enabled);\n}\n\n// =========================================================================\n// Bash Execution\n// =========================================================================\n\n/**\n * Execute a bash command.\n * Adds result to agent context and session.\n * @param command The bash command to execute\n * @param onChunk Optional streaming callback for output\n * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)\n * @param options.operations Custom BashOperations for remote execution\n */\n\nexport const agentSessionRetryMethods = {\n\t_isRetryableError,\n\t_isEmptyCompletion,\n\t_isSafetyRefusal,\n\t_handleRetryableError,\n\t_trySwitchToFallbackModel,\n\tabortRetry,\n\twaitForRetry,\n\tsetAutoRetryEnabled,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-retry.js","sourceRoot":"","sources":["../../src/core/agent-session-retry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAElE,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACrG,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,oBAAoB,IAAI,8BAA8B,EAAE,MAAM,sBAAsB,CAAC;AAC3G,OAAO,EAAE,6BAA6B,EAAE,MAAM,mBAAmB,CAAC;AAIl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;IAEN,OAAO,IAAI,CAAC;AACb,CAAC;AAED;;GAEG;AAEH,MAAM,UAAU,UAAU;IACzB,IAAI,CAAC,qBAAqB,EAAE,KAAK,EAAE,CAAC;IACpC,gEAAgE;IAChE,IAAI,CAAC,aAAa,EAAE,CAAC;AACtB,CAAC;AAED;;;GAGG;AAEH,MAAM,CAAC,KAAK,UAAU,YAAY;IACjC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;QACzB,OAAO;IACR,CAAC;IAED,MAAM,IAAI,CAAC,aAAa,CAAC;IACzB,MAAM,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;AAChC,CAAC;AAED,kDAAkD;AAElD,MAAM,UAAU,mBAAmB,CAAqB,OAAgB;IACvE,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;AAC/C,CAAC;AAED,4EAA4E;AAC5E,iBAAiB;AACjB,4EAA4E;AAE5E;;;;;;;GAOG;AAEH,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACvC,iBAAiB;IACjB,kBAAkB;IAClB,gBAAgB;IAChB,qBAAqB;IACrB,yBAAyB;IACzB,UAAU;IACV,YAAY;IACZ,mBAAmB;CACnB,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { isRetryableAssistantError } from \"@earendil-works/pi-ai\";\nimport type { Api, AssistantMessage, Model } from \"@earendil-works/pi-ai/compat\";\nimport { clampThinkingLevel, isContextOverflow, modelsAreEqual } from \"@earendil-works/pi-ai/compat\";\nimport { sleep } from \"../utils/sleep.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport { fallbackKey, resolveFallbackModel as resolveConfiguredFallbackModel } from \"./fallback-models.ts\";\nimport { isCodexTokenInvalidationError } from \"./codex-errors.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\n\nfunction modelLabel(model: Model<Api> | undefined): string {\n\treturn model ? `${model.provider}/${model.id}` : \"unknown model\";\n}\n\nfunction resolveFallbackModel(this: AgentSession, value: string): { model: Model<Api>; thinkingLevel?: ThinkingLevel } | undefined {\n\treturn resolveConfiguredFallbackModel(\n\t\tvalue,\n\t\tthis._modelRuntime,\n\t\tthis.model?.provider ?? this.settingsManager.getDefaultProvider(),\n\t);\n}\n\nfunction hasProviderTransportDiagnostic(value: unknown, seen = new Set<unknown>(), includeMessageFields = false): boolean {\n\tif (value === null || value === undefined || seen.has(value)) return false;\n\tif (typeof value !== \"object\") {\n\t\treturn /provider_transport_failure|websocket.*error|sse.*404/i.test(String(value));\n\t}\n\tseen.add(value);\n\tconst record = value as Record<string, unknown>;\n\tconst fields = includeMessageFields\n\t\t? [record.type, record.code, record.name, record.message, record.errorMessage, record.status, record.statusCode]\n\t\t: [record.type, record.code, record.name, record.status, record.statusCode];\n\tfor (const field of fields) {\n\t\t if (typeof field === \"string\" || typeof field === \"number\") {\n\t\t\tif (/provider_transport_failure|websocket.*error|sse.*404|\\b404\\b/i.test(String(field))) return true;\n\t\t}\n\t}\n\tfor (const nested of [record.error, record.cause, ...(Array.isArray(record.diagnostics) ? record.diagnostics : [])]) {\n\t\tif (hasProviderTransportDiagnostic(nested, seen, true)) return true;\n\t}\n\treturn false;\n}\n\nfunction hasProviderModelUnavailableDiagnostic(value: unknown, seen = new Set<unknown>(), includeMessageFields = false): boolean {\n\tif (value === null || value === undefined || seen.has(value)) return false;\n\tif (typeof value !== \"object\") return false;\n\tseen.add(value);\n\tconst record = value as Record<string, unknown>;\n\tconst fields = includeMessageFields\n\t\t? [record.type, record.code, record.name, record.message, record.errorMessage]\n\t\t: [record.type, record.code, record.name, record.errorMessage];\n\tfor (const field of fields) {\n\t\tif (typeof field === \"string\" && /model(?:[_\\s-].*)?(?:not[_\\s-]?found|unavailable|unknown|disabled)|model[_-]?not[_-]?found/i.test(field)) return true;\n\t}\n\tfor (const nested of [record.error, record.cause, ...(Array.isArray(record.diagnostics) ? record.diagnostics : [])]) {\n\t\tif (hasProviderModelUnavailableDiagnostic(nested, seen, true)) return true;\n\t}\n\treturn false;\n}\nexport function _isRetryableError(this: AgentSession, message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\") return false;\n\n\t// Context overflow is handled by compaction, not retry\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\n\t// A definitive Codex authentication rejection is terminal. It takes\n\t// precedence over transport diagnostics recorded during WebSocket-to-SSE\n\t// fallback so those earlier diagnostics cannot trigger a pointless retry.\n\tconst provider = message.provider || this.model?.provider;\n\tif (provider && isCodexTokenInvalidationError(provider, message.errorMessage)) return false;\n\n\tif (hasProviderTransportDiagnostic(message) || hasProviderModelUnavailableDiagnostic(message)) return true;\n\t// Keep Atomic-specific terminal exclusions above, then inherit pi-ai's\n\t// transport classifier (including getaddrinfo, ENOTFOUND, and EAI_AGAIN).\n\tif (isRetryableAssistantError(message)) return true;\n\tif (!message.errorMessage) return false;\n\n\tconst err = message.errorMessage;\n\n\t// Safety triggers surface through structured API signals that pi-ai maps to\n\t// stopReason \"error\":\n\t// - Anthropic `refusal` stops become pi-ai's canned \"The model refused to\n\t// complete the request\" error message;\n\t// - OpenAI-style APIs (and github-copilot CAPI, which also maps spurious\n\t// Gemini RECITATION/safety blocks this way) surface\n\t// `finish_reason: content_filter`.\n\t// Spurious safety triggers are common in agentic settings, so these are\n\t// re-requested like transient failures, bounded by maxRetries (issue #1608).\n\tif (/refused to complete the request|finish.?reason:?\\s*content.?filter/i.test(err)) {\n\t\treturn true;\n\t}\n\n\t// Match: overloaded_error, provider returned error, rate limit, quota/usage-limit exhaustion (e.g. \"Codex error: The usage limit has been reached\" — retryable so configured fallbackModels can advance to a provider/model with remaining headroom), 429, 500, 502, 503, 504, service unavailable, network/connection errors (including connection lost), WebSocket transport closes/errors, fetch failed, premature stream endings, HTTP/2 closed before response, terminated, retry delay exceeded, and a bare/transient provider finish_reason \"error\" (e.g. github-copilot Gemini's CAPI mapping of MALFORMED_FUNCTION_CALL/OTHER/UNEXPECTED_TOOL_CALL). These are provider-agnostic transient failures.\n\treturn /overloaded|provider.?returned.?error|rate.?limit|usage.?limit|quota|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?lost|websocket.?closed|websocket.?error|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|stream ended before message_stop|http2 request did not get a response|timed? out|timeout|terminated|retry delay|finish.?reason:?\\s*error/i.test(\n\t\terr,\n\t);\n}\n\n/**\n * Detect a degenerate empty completion: the provider ended the stream with no\n * usable content and zero output tokens. Seen with github-copilot Gemini models\n * that emit finish_reason \"stop\" (or a tool-use stop) with an empty content array\n * and 0 output tokens, leaving the turn dead instead of producing the next step.\n *\n * These are treated as retryable so the harness re-issues the request rather than\n * silently stopping mid-task. Guarded tightly (no text, no tool call, no thinking,\n * and output === 0) so legitimate non-empty turns are never matched.\n *\n * Intentionally provider-agnostic (not gated to Copilot Gemini): a degenerate\n * empty turn is a transient failure for any provider. It is bounded by\n * `maxRetries` and falls through to normal handling on exhaustion.\n */\n\nexport function _isEmptyCompletion(this: AgentSession, message: AssistantMessage): boolean {\n\t// Only \"completed\" stop reasons can be deceptively empty. Real errors are handled\n\t// by _isRetryableError; aborted/length turns are intentional outcomes.\n\tif (message.stopReason !== \"stop\" && message.stopReason !== \"toolUse\") return false;\n\n\tconst content = message.content;\n\tif (Array.isArray(content)) {\n\t\tconst hasContent = content.some((part) => {\n\t\t\tif (part.type === \"text\") return part.text.trim().length > 0;\n\t\t\tif (part.type === \"toolCall\") return true;\n\t\t\tif (part.type === \"thinking\") return part.redacted === true || part.thinking.trim().length > 0;\n\t\t\treturn true; // unknown part types count as content\n\t\t});\n\t\tif (hasContent) return false;\n\t}\n\n\t// A turn that produced output tokens but no surfaced content is not \"empty\"\n\t// (e.g. reasoning-only responses); leave those alone. Note: a provider that\n\t// fails to report `usage` (output defaults to 0) would make every\n\t// content-less turn match here; the dual requirement (empty content AND zero\n\t// output) keeps that false-positive risk low in practice.\n\treturn (message.usage?.output ?? 0) === 0;\n}\n\n/**\n * Detect a canned provider-side safety refusal that arrives as a *successful*\n * completion instead of an error. Seen with github-copilot GPT models under\n * heavy contexts: the endpoint intercepts the request and returns exactly\n * \"I'm sorry, but I cannot assist with that request.\" with zero usage and a\n * spurious stopReason of \"length\" (or \"stop\"), which the agent would otherwise\n * accept as the final answer and dead-end the turn (issue #1608).\n *\n * A text heuristic is unavoidable here: the OpenAI Responses API does signal\n * these interceptions structurally (`refusal` content parts plus\n * `incomplete_details.reason: \"content_filter\"`), but pi-ai's normalization\n * folds refusal parts into plain text blocks and collapses the `incomplete`\n * status to stopReason \"length\", discarding the reason — so no structured\n * refusal marker survives on the AssistantMessage. Providers whose safety\n * signals DO survive as structured errors (Anthropic refusal stops, OpenAI\n * `finish_reason: content_filter`) are matched in _isRetryableError instead.\n *\n * Guarded tightly so legitimate turns are never matched:\n * - only non-error completion stops (\"stop\" | \"length\" | \"toolUse\");\n * - content must be a single short canned refusal text — any tool call,\n * thinking block, or additional prose disqualifies the message;\n * - usage.output must be 0: a genuine model-authored refusal bills output\n * tokens, while the intercepted canned refusal reports zero usage.\n *\n * Treated as retryable so the harness re-requests the model call rather than\n * accepting the refusal; bounded by `maxRetries` like every other retry path.\n */\n\nconst CANNED_SAFETY_REFUSAL_PATTERN =\n\t/^(?:i['’]?m sorry[,.]?\\s+(?:but\\s+)?|sorry[,.]?\\s+(?:but\\s+)?)?i\\s+(?:cannot|can['’]?t|can\\s+not|am\\s+unable\\s+to|am\\s+not\\s+able\\s+to)\\s+(?:assist|help|comply|continue)(?:\\s+with)?(?:\\s+(?:that|this))?(?:\\s+(?:request|task))?\\.?$/i;\n\nconst CANNED_SAFETY_REFUSAL_MAX_LENGTH = 120;\n\nexport function _isSafetyRefusal(this: AgentSession, message: AssistantMessage): boolean {\n\t// Real errors are handled by _isRetryableError; aborts are user-initiated.\n\tif (message.stopReason !== \"stop\" && message.stopReason !== \"length\" && message.stopReason !== \"toolUse\") {\n\t\treturn false;\n\t}\n\n\tconst content = message.content;\n\tif (!Array.isArray(content) || content.length === 0) return false;\n\n\tlet text = \"\";\n\tfor (const part of content) {\n\t\tif (part.type === \"toolCall\") return false;\n\t\tif (part.type === \"thinking\" && (part.redacted === true || part.thinking.trim().length > 0)) return false;\n\t\tif (part.type === \"text\") text += part.text;\n\t}\n\ttext = text.trim();\n\tif (text.length === 0 || text.length > CANNED_SAFETY_REFUSAL_MAX_LENGTH) return false;\n\tif (!CANNED_SAFETY_REFUSAL_PATTERN.test(text)) return false;\n\n\t// Zero billed output distinguishes a provider interception from legitimate\n\t// model-authored refusal prose, which is never auto-retried.\n\treturn (message.usage?.output ?? 0) === 0;\n}\n\n/**\n * Handle retryable errors with exponential backoff.\n * @returns true if retry was initiated, false if max retries exceeded or disabled\n */\n\nexport async function _trySwitchToFallbackModel(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tif (this._fallbackModels.length === 0 || !this.model) return false;\n\n\tthis._fallbackAttemptedKeys.add(fallbackKey(this.model, this.thinkingLevel));\n\tconst fromModel = this.model;\n\tfor (const rawCandidate of this._fallbackModels) {\n\t\tconst candidate = resolveFallbackModel.call(this, rawCandidate);\n\t\tif (!candidate) continue;\n\t\tconst key = fallbackKey(candidate.model, candidate.thinkingLevel);\n\t\tif (this._fallbackAttemptedKeys.has(key)) continue;\n\t\tconst nextModel = candidate.model;\n\t\tconst nextLevel = clampThinkingLevel(\n\t\t\tnextModel,\n\t\t\tcandidate.thinkingLevel ?? this.settingsManager.getDefaultThinkingLevel() ?? this.thinkingLevel ?? DEFAULT_THINKING_LEVEL,\n\t\t) as ThinkingLevel;\n\t\tif (modelsAreEqual(candidate.model, fromModel) && nextLevel === this.thinkingLevel) continue;\n\t\tif (this._retryAttempt > 0) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\tsuccess: true,\n\t\t\t\tattempt: Math.max(0, this._retryAttempt - 1),\n\t\t\t});\n\t\t}\n\t\tthis._fallbackAttemptedKeys.add(key);\n\t\tthis._emit({\n\t\t\ttype: \"model_fallback_start\",\n\t\t\tfrom: modelLabel(fromModel),\n\t\t\tto: `${nextModel.provider}/${nextModel.id}`,\n\t\t\treason: message.errorMessage || \"Retryable model error\",\n\t\t\tattempt: this._fallbackAttemptedKeys.size - 1,\n\t\t});\n\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1]?.role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tthis.agent.state.model = nextModel;\n\t\tthis.sessionManager.appendModelChange(nextModel.provider, nextModel.id);\n\t\tthis.agent.state.thinkingLevel = nextLevel;\n\t\tthis.sessionManager.appendThinkingLevelChange(nextLevel);\n\t\tthis._refreshBaseSystemPromptFromActiveTools();\n\t\tthis._emitModelChanged(nextModel, fromModel, \"fallback\");\n\t\tawait this._emitModelSelect(nextModel, fromModel, \"fallback\");\n\t\tthis._retryAttempt = 0;\n\n\t\tsetTimeout(() => {\n\t\t\tthis.agent.continue().then(\n\t\t\t\t() => {\n\t\t\t\t\t// A resolved continuation may still have produced an assistant\n\t\t\t\t\t// error that will be classified by agent_end and may advance to\n\t\t\t\t\t// the next fallback. Do not emit a successful fallback end here;\n\t\t\t\t\t// agent_end/turn_end clear UI state for successful turns, while\n\t\t\t\t\t// fallback exhaustion emits the failure end event.\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tconst finalError = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tthis._emit({ type: \"model_fallback_end\", success: false, from: modelLabel(fromModel), to: modelLabel(nextModel), finalError });\n\t\t\t\t\tthis._retryAttempt = 0;\n\t\t\t\t\tthis._resolveRetry();\n\t\t\t\t},\n\t\t\t);\n\t\t}, 0);\n\t\treturn true;\n\t}\n\tthis._emit({ type: \"model_fallback_end\", success: false, from: modelLabel(fromModel), finalError: message.errorMessage });\n\treturn false;\n}\n\nexport async function _handleRetryableError(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tconst settings = this.settingsManager.getRetrySettings();\n\tif (!settings.enabled) {\n\t\treturn this._trySwitchToFallbackModel(message);\n\t}\n\n\t// Retry promise is created synchronously in _handleAgentEvent for agent_end.\n\t// Keep a defensive fallback here in case a future refactor bypasses that path.\n\tif (!this._retryPromise) {\n\t\tthis._retryPromise = new Promise((resolve) => {\n\t\t\tthis._retryResolve = resolve;\n\t\t});\n\t}\n\n\tthis._retryAttempt++;\n\n\tif (this._retryAttempt > settings.maxRetries) {\n\t\tif (await this._trySwitchToFallbackModel(message)) {\n\t\t\treturn true;\n\t\t}\n\t\t// Max retries exceeded, emit final failure and reset\n\t\tthis._emit({\n\t\t\ttype: \"auto_retry_end\",\n\t\t\tsuccess: false,\n\t\t\tattempt: this._retryAttempt - 1,\n\t\t\tfinalError: message.errorMessage,\n\t\t});\n\t\tthis._retryAttempt = 0;\n\t\tthis._resolveRetry(); // Resolve so waitForRetry() completes\n\t\treturn false;\n\t}\n\n\tconst delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);\n\n\tthis._emit({\n\t\ttype: \"auto_retry_start\",\n\t\tattempt: this._retryAttempt,\n\t\tmaxAttempts: settings.maxRetries,\n\t\tdelayMs,\n\t\terrorMessage: message.errorMessage || \"Unknown error\",\n\t});\n\n\t// Remove error message from agent state (keep in session for history)\n\tconst messages = this.agent.state.messages;\n\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n\n\t// Wait with exponential backoff (abortable)\n\tthis._retryAbortController = new AbortController();\n\ttry {\n\t\tawait sleep(delayMs, this._retryAbortController.signal);\n\t} catch {\n\t\t// Aborted during sleep - emit end event so UI can clean up\n\t\tconst attempt = this._retryAttempt;\n\t\tthis._retryAttempt = 0;\n\t\tthis._retryAbortController = undefined;\n\t\tthis._emit({\n\t\t\ttype: \"auto_retry_end\",\n\t\t\tsuccess: false,\n\t\t\tattempt,\n\t\t\tfinalError: \"Retry cancelled\",\n\t\t});\n\t\tthis._resolveRetry();\n\t\treturn false;\n\t}\n\tthis._retryAbortController = undefined;\n\n\t// Retry via continue() - use setTimeout to break out of event handler chain\n\tsetTimeout(() => {\n\t\tthis.agent.continue().catch(() => {\n\t\t\t// Retry failed - will be caught by next agent_end\n\t\t});\n\t}, 0);\n\n\treturn true;\n}\n\n/**\n * Cancel in-progress retry.\n */\n\nexport function abortRetry(this: AgentSession): void {\n\tthis._retryAbortController?.abort();\n\t// Note: _retryAttempt is reset in the catch block of _autoRetry\n\tthis._resolveRetry();\n}\n\n/**\n * Wait for any in-progress retry to complete.\n * Returns immediately if no retry is in progress.\n */\n\nexport async function waitForRetry(this: AgentSession): Promise<void> {\n\tif (!this._retryPromise) {\n\t\treturn;\n\t}\n\n\tawait this._retryPromise;\n\tawait this.agent.waitForIdle();\n}\n\n/** Whether auto-retry is currently in progress */\n\nexport function setAutoRetryEnabled(this: AgentSession, enabled: boolean): void {\n\tthis.settingsManager.setRetryEnabled(enabled);\n}\n\n// =========================================================================\n// Bash Execution\n// =========================================================================\n\n/**\n * Execute a bash command.\n * Adds result to agent context and session.\n * @param command The bash command to execute\n * @param onChunk Optional streaming callback for output\n * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)\n * @param options.operations Custom BashOperations for remote execution\n */\n\nexport const agentSessionRetryMethods = {\n\t_isRetryableError,\n\t_isEmptyCompletion,\n\t_isSafetyRefusal,\n\t_handleRetryableError,\n\t_trySwitchToFallbackModel,\n\tabortRetry,\n\twaitForRetry,\n\tsetAutoRetryEnabled,\n};\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { AgentSession } from "./agent-session.ts";
|
|
2
|
-
import { type AtomicOAuthLoginCallbacks } from "./oauth-
|
|
3
|
-
export type { AtomicOAuthLoginCallbacks } from "./oauth-
|
|
4
|
-
/** Authenticate through provider-owned metadata
|
|
2
|
+
import { type AtomicOAuthLoginCallbacks } from "./oauth-login.ts";
|
|
3
|
+
export type { AtomicOAuthLoginCallbacks } from "./oauth-login.ts";
|
|
4
|
+
/** Authenticate through provider-owned OAuth metadata. */
|
|
5
5
|
export declare function loginRuntimeOAuthProvider(session: AgentSession, provider: string, callbacks: AtomicOAuthLoginCallbacks): Promise<void>;
|
|
6
6
|
//# sourceMappingURL=agent-session-runtime-auth.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-runtime-auth.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-runtime-auth.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,
|
|
1
|
+
{"version":3,"file":"agent-session-runtime-auth.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-runtime-auth.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAIN,KAAK,yBAAyB,EAC9B,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAElE,0DAA0D;AAC1D,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,YAAY,EACrB,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,yBAAyB,GAClC,OAAO,CAAC,IAAI,CAAC,CAWf"}
|
|
@@ -1,20 +1,10 @@
|
|
|
1
1
|
import { ModelsError } from "@earendil-works/pi-ai";
|
|
2
|
-
import { createAuthInteraction,
|
|
3
|
-
/** Authenticate through provider-owned metadata
|
|
2
|
+
import { createAuthInteraction, normalizeOAuthLoginError, OAuthLoginTransactionError, } from "./oauth-login.js";
|
|
3
|
+
/** Authenticate through provider-owned OAuth metadata. */
|
|
4
4
|
export async function loginRuntimeOAuthProvider(session, provider, callbacks) {
|
|
5
|
-
const
|
|
6
|
-
if (getLegacyOAuthProvider(provider)) {
|
|
7
|
-
const credential = await loginOAuthProvider(provider, callbacks);
|
|
8
|
-
try {
|
|
9
|
-
await registry.authStorage.asCredentialStore().modify(provider, async () => credential);
|
|
10
|
-
}
|
|
11
|
-
catch (error) {
|
|
12
|
-
throw new OAuthLoginTransactionError(error);
|
|
13
|
-
}
|
|
14
|
-
return;
|
|
15
|
-
}
|
|
5
|
+
const runtime = session.modelRuntime;
|
|
16
6
|
try {
|
|
17
|
-
await
|
|
7
|
+
await runtime.login(provider, "oauth", createAuthInteraction(callbacks));
|
|
18
8
|
}
|
|
19
9
|
catch (error) {
|
|
20
10
|
if (error instanceof ModelsError && error.code === "auth" && error.message.startsWith("Credential store modify failed")) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-runtime-auth.js","sourceRoot":"","sources":["../../src/core/agent-session-runtime-auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEpD,OAAO,EACN,qBAAqB,EACrB,
|
|
1
|
+
{"version":3,"file":"agent-session-runtime-auth.js","sourceRoot":"","sources":["../../src/core/agent-session-runtime-auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEpD,OAAO,EACN,qBAAqB,EACrB,wBAAwB,EACxB,0BAA0B,GAE1B,MAAM,kBAAkB,CAAC;AAG1B,0DAA0D;AAC1D,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,OAAqB,EACrB,QAAgB,EAChB,SAAoC;IAEpC,MAAM,OAAO,GAAG,OAAO,CAAC,YAAY,CAAC;IACrC,IAAI,CAAC;QACJ,MAAM,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,OAAO,EAAE,qBAAqB,CAAC,SAAS,CAAC,CAAC,CAAC;IAC1E,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,KAAK,YAAY,WAAW,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,gCAAgC,CAAC,EAAE,CAAC;YACzH,MAAM,IAAI,0BAA0B,CAAC,KAAK,CAAC,CAAC;QAC7C,CAAC;QACD,MAAM,wBAAwB,CAAC,KAAK,EAAE,SAAS,CAAC,MAAM,EAAE,EAAE,mBAAmB,EAAE,KAAK,EAAE,CAAC,CAAC;IACzF,CAAC;AAEF,CAAC","sourcesContent":["import { ModelsError } from \"@earendil-works/pi-ai\";\nimport type { AgentSession } from \"./agent-session.ts\";\nimport {\n\tcreateAuthInteraction,\n\tnormalizeOAuthLoginError,\n\tOAuthLoginTransactionError,\n\ttype AtomicOAuthLoginCallbacks,\n} from \"./oauth-login.ts\";\nexport type { AtomicOAuthLoginCallbacks } from \"./oauth-login.ts\";\n\n/** Authenticate through provider-owned OAuth metadata. */\nexport async function loginRuntimeOAuthProvider(\n\tsession: AgentSession,\n\tprovider: string,\n\tcallbacks: AtomicOAuthLoginCallbacks,\n): Promise<void> {\n\tconst runtime = session.modelRuntime;\n\ttry {\n\t\tawait runtime.login(provider, \"oauth\", createAuthInteraction(callbacks));\n\t} catch (error) {\n\t\tif (error instanceof ModelsError && error.code === \"auth\" && error.message.startsWith(\"Credential store modify failed\")) {\n\t\t\tthrow new OAuthLoginTransactionError(error);\n\t\t}\n\t\tthrow normalizeOAuthLoginError(error, callbacks.signal, { includeActiveSignal: false });\n\t}\n\n}\n"]}
|