@punch-bot/cli 0.85.1 → 1.3.0
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 +609 -3
- package/README.md +82 -174
- package/dist/bun/cli.d.ts.map +1 -1
- package/dist/bun/restore-sandbox-env.d.ts.map +1 -1
- package/dist/bun/restore-sandbox-env.js.map +1 -1
- package/dist/bun/runtime-setup.d.ts.map +1 -1
- package/dist/bun/runtime-setup.js +4 -1
- package/dist/bun/runtime-setup.js.map +1 -1
- package/dist/bun/sandbox-env-setup.d.ts.map +1 -1
- package/dist/bundle/chunks/anthropic-messages-BUUFZMRE.js +6 -0
- package/dist/bundle/chunks/anthropic.js +2 -2
- package/dist/bundle/chunks/azure-openai-responses-WZ4GZHD2.js +2 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +10 -2
- package/dist/bundle/chunks/chunk-22CYIUS4.js +2 -0
- package/dist/bundle/chunks/chunk-2M76JOVH.js +8 -0
- package/dist/bundle/chunks/chunk-6C5VKHGV.js +50 -0
- package/dist/bundle/chunks/chunk-6WNF4BLC.js +2 -0
- package/dist/bundle/chunks/chunk-6YKFJ7FQ.js +1188 -0
- package/dist/bundle/chunks/chunk-BYHXHV4K.js +11 -0
- package/dist/bundle/chunks/chunk-F5ZABL6Z.js +20 -0
- package/dist/bundle/chunks/chunk-HACVPRBJ.js +11 -0
- package/dist/bundle/chunks/chunk-ITZNWD4K.js +2 -0
- package/dist/bundle/chunks/chunk-J7I2NFJ7.js +82 -0
- package/dist/bundle/chunks/chunk-LPXNMA2W.js +2 -0
- package/dist/bundle/chunks/chunk-OO6DJ3CL.js +31 -0
- package/dist/bundle/chunks/chunk-OWCYH5W2.js +2 -0
- package/dist/bundle/chunks/chunk-PMRZO46Y.js +2 -0
- package/dist/bundle/chunks/{chunk-TRDNDS6A.js → chunk-PYGXRV27.js} +5 -2
- package/dist/bundle/chunks/chunk-RDZVAGPR.js +2 -0
- package/dist/bundle/chunks/{chunk-XDUWOHPL.js → chunk-S3GGRYIO.js} +2 -2
- package/dist/bundle/chunks/chunk-UTB4DTYQ.js +2 -0
- package/dist/bundle/chunks/chunk-WUIPA42N.js +14 -0
- package/dist/bundle/chunks/chunk-XIX7LUWI.js +2 -0
- package/dist/bundle/chunks/{chunk-3DNTDXPG.js → chunk-YGGF2ZM6.js} +3 -3
- package/dist/bundle/chunks/chunk-YWHGLBPB.js +2 -0
- package/dist/bundle/chunks/chunk-ZBURYEWF.js +2 -0
- package/dist/bundle/chunks/cli-QAQLORRY.js +51 -0
- package/dist/bundle/chunks/cloudflare-workers-ai-system-one-UTBL2KOF.js +2 -0
- package/dist/bundle/chunks/codemode-worker.js +478 -0
- package/dist/bundle/chunks/execute-2Z6BN5R3.js +499 -0
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/google-generative-ai-S2KXX5PQ.js +2 -0
- package/dist/bundle/chunks/google-vertex-LQOUTFJN.js +2 -0
- package/dist/bundle/chunks/image-resize-worker.js +1 -1
- package/dist/bundle/chunks/jiti-loader-C3NU2SDH.js +21 -0
- package/dist/bundle/chunks/jiti-static-loader-E6ANQD5T.js +2 -0
- package/dist/bundle/chunks/{lib-HGQMNYVT.js → lib-TEDK3E5I.js} +2 -2
- package/dist/bundle/chunks/llama-cpp-classify-FYN623RH.js +22 -0
- package/dist/bundle/chunks/meta.js +2 -0
- package/dist/bundle/chunks/mistral-conversations-VNJYBSRF.js +5 -0
- package/dist/bundle/chunks/node-N5BSDOA5.js +16 -0
- package/dist/bundle/chunks/{node-4PXJTSWH.js → node-TWVVAGPO.js} +1 -1
- package/dist/bundle/chunks/openai-chatgpt.js +75 -0
- package/dist/bundle/chunks/openai-codex-responses-E6BLZPYJ.js +10 -0
- package/dist/bundle/chunks/openai-codex.js +2 -2
- package/dist/bundle/chunks/openai-completions-LUDIAWSG.js +7 -0
- package/dist/bundle/chunks/openai-decisions-WVPMQ4JD.js +5 -0
- package/dist/bundle/chunks/openai-responses-IOCBEIVC.js +3 -0
- package/dist/bundle/chunks/{openrouter-images-N4XVVFSD.js → openrouter-images-YU24TD7D.js} +1 -1
- package/dist/bundle/chunks/openrouter.js +2 -2
- package/dist/bundle/chunks/{pi-messages-ZRYGTSON.js → pi-messages-V27DSLVC.js} +2 -2
- package/dist/bundle/chunks/radius.js +2 -2
- package/dist/bundle/chunks/runtime-R6O72Q4R.js +2 -0
- package/dist/bundle/chunks/typesafe-system-one-ZSK3RN4B.js +2 -0
- package/dist/bundle/chunks/virtual-modules-GZVZPCK3.js +2 -0
- package/dist/bundle/cli-runtime.js +3 -0
- package/dist/bundle/cli.js +4 -2
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.d.ts +1 -2
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +73 -53
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/auth-check.d.ts.map +1 -1
- package/dist/cli/auth-check.js.map +1 -1
- package/dist/cli/auth-command.d.ts.map +1 -1
- package/dist/cli/auth-command.js.map +1 -1
- package/dist/cli/credential-print.d.ts.map +1 -1
- package/dist/cli/credential-print.js +4 -4
- package/dist/cli/credential-print.js.map +1 -1
- package/dist/cli/experimental/transport-address.d.ts +21 -0
- package/dist/cli/experimental/transport-address.d.ts.map +1 -0
- package/dist/cli/experimental/transport-address.js +89 -0
- package/dist/cli/experimental/transport-address.js.map +1 -0
- package/dist/cli/file-processor.d.ts +1 -1
- package/dist/cli/file-processor.d.ts.map +1 -1
- package/dist/cli/file-processor.js.map +1 -1
- package/dist/cli/initial-message.d.ts +1 -1
- package/dist/cli/initial-message.d.ts.map +1 -1
- package/dist/cli/initial-message.js.map +1 -1
- package/dist/cli/list-models.d.ts.map +1 -1
- package/dist/cli/list-models.js +1 -1
- package/dist/cli/list-models.js.map +1 -1
- package/dist/cli/project-trust.d.ts.map +1 -1
- package/dist/cli/project-trust.js +5 -35
- package/dist/cli/project-trust.js.map +1 -1
- package/dist/cli/setup.d.ts.map +1 -1
- package/dist/cli/setup.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/config.d.ts +30 -11
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +72 -21
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +4 -3
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +37 -27
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +13 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +270 -22
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +1174 -410
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-guidance.d.ts.map +1 -1
- package/dist/core/auth-guidance.js.map +1 -1
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +20 -13
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +42 -52
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/bug-report-upload.d.ts +12 -0
- package/dist/core/bug-report-upload.d.ts.map +1 -0
- package/dist/core/bug-report-upload.js +22 -0
- package/dist/core/bug-report-upload.js.map +1 -0
- package/dist/core/bug-report.d.ts +184 -0
- package/dist/core/bug-report.d.ts.map +1 -0
- package/dist/core/bug-report.js +292 -0
- package/dist/core/bug-report.js.map +1 -0
- package/dist/core/cache-stats.d.ts.map +1 -1
- package/dist/core/cache-stats.js +12 -1
- package/dist/core/cache-stats.js.map +1 -1
- package/dist/core/cache-warmer.d.ts +103 -0
- package/dist/core/cache-warmer.d.ts.map +1 -0
- package/dist/core/cache-warmer.js +356 -0
- package/dist/core/cache-warmer.js.map +1 -0
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +2 -2
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +5 -3
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +164 -88
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/index.d.ts.map +1 -1
- package/dist/core/compaction/utils.d.ts +8 -1
- package/dist/core/compaction/utils.d.ts.map +1 -1
- package/dist/core/compaction/utils.js +32 -26
- package/dist/core/compaction/utils.js.map +1 -1
- package/dist/core/crash-log.d.ts +27 -0
- package/dist/core/crash-log.d.ts.map +1 -0
- package/dist/core/crash-log.js +140 -0
- package/dist/core/crash-log.js.map +1 -0
- package/dist/core/defaults.d.ts.map +1 -1
- package/dist/core/delivery.d.ts.map +1 -1
- package/dist/core/delivery.js.map +1 -1
- package/dist/core/diagnostics.d.ts.map +1 -1
- package/dist/core/event-bus.d.ts.map +1 -1
- package/dist/core/event-bus.js.map +1 -1
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js.map +1 -1
- package/dist/core/experimental.d.ts.map +1 -1
- package/dist/core/experimental.js.map +1 -1
- package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
- package/dist/core/export-html/ansi-to-html.js.map +1 -1
- package/dist/core/export-html/index.d.ts.map +1 -1
- package/dist/core/export-html/index.js +1 -1
- package/dist/core/export-html/index.js.map +1 -1
- package/dist/core/export-html/template.css +10 -0
- package/dist/core/export-html/template.js +93 -34
- package/dist/core/export-html/tool-renderer.d.ts +5 -11
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +8 -99
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/jiti-loader.d.ts +2 -0
- package/dist/core/extensions/jiti-loader.d.ts.map +1 -0
- package/dist/core/extensions/jiti-loader.js +4 -0
- package/dist/core/extensions/jiti-loader.js.map +1 -0
- package/dist/core/extensions/jiti-static-loader.d.ts +2 -0
- package/dist/core/extensions/jiti-static-loader.d.ts.map +1 -0
- package/dist/core/extensions/jiti-static-loader.js +4 -0
- package/dist/core/extensions/jiti-static-loader.js.map +1 -0
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +102 -74
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +44 -14
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +297 -169
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +482 -238
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/extensions/virtual-modules.d.ts +3 -0
- package/dist/core/extensions/virtual-modules.d.ts.map +1 -0
- package/dist/core/extensions/virtual-modules.js +35 -0
- package/dist/core/extensions/virtual-modules.js.map +1 -0
- package/dist/core/extensions/wrapper.d.ts +2 -2
- package/dist/core/extensions/wrapper.d.ts.map +1 -1
- package/dist/core/extensions/wrapper.js +3 -22
- package/dist/core/extensions/wrapper.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/http-dispatcher.d.ts +13 -0
- package/dist/core/http-dispatcher.d.ts.map +1 -1
- package/dist/core/http-dispatcher.js +13 -4
- package/dist/core/http-dispatcher.js.map +1 -1
- package/dist/core/index.d.ts +2 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +139 -0
- package/dist/core/mcp-servers.d.ts.map +1 -0
- package/dist/core/mcp-servers.js +232 -0
- package/dist/core/mcp-servers.js.map +1 -0
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +1 -0
- package/dist/core/messages.js.map +1 -1
- package/dist/{modes/interactive → core}/model-catalog-refresh.d.ts +2 -2
- package/dist/core/model-catalog-refresh.d.ts.map +1 -0
- package/dist/{modes/interactive → core}/model-catalog-refresh.js +2 -2
- package/dist/core/model-catalog-refresh.js.map +1 -0
- package/dist/core/model-config.d.ts +886 -80
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +33 -148
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-registry.d.ts +15 -1
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +29 -0
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts +61 -46
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +338 -363
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts +51 -3
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +211 -44
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/model-suffix-variants.d.ts +14 -0
- package/dist/core/model-suffix-variants.d.ts.map +1 -0
- package/dist/core/model-suffix-variants.js +27 -0
- package/dist/core/model-suffix-variants.js.map +1 -0
- package/dist/core/models-store.d.ts.map +1 -1
- package/dist/core/models-store.js.map +1 -1
- package/dist/core/nested-tool-calls.d.ts +103 -0
- package/dist/core/nested-tool-calls.d.ts.map +1 -0
- package/dist/core/nested-tool-calls.js +179 -0
- package/dist/core/nested-tool-calls.js.map +1 -0
- package/dist/core/output-guard.d.ts.map +1 -1
- package/dist/core/output-guard.js.map +1 -1
- package/dist/core/package-manager.d.ts +4 -0
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +62 -15
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/pi-manifest.d.ts.map +1 -1
- package/dist/core/pi-manifest.js.map +1 -1
- package/dist/core/project-trust.d.ts.map +1 -1
- package/dist/core/project-trust.js +2 -1
- package/dist/core/project-trust.js.map +1 -1
- package/dist/core/prompt-templates.d.ts +6 -1
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +68 -37
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/provider-attribution.d.ts.map +1 -1
- package/dist/core/provider-attribution.js.map +1 -1
- package/dist/core/provider-composer.d.ts +42 -20
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +126 -40
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/radius.d.ts +5 -0
- package/dist/core/radius.d.ts.map +1 -1
- package/dist/core/radius.js +8 -0
- package/dist/core/radius.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts +19 -1
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +102 -34
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/resolve-config-value.d.ts.map +1 -1
- package/dist/core/resolve-config-value.js.map +1 -1
- package/dist/core/resource-loader.d.ts +11 -2
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +170 -42
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/runtime-credentials.d.ts.map +1 -1
- package/dist/core/runtime-credentials.js.map +1 -1
- package/dist/core/sdk.d.ts +14 -5
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +108 -52
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-cwd.d.ts.map +1 -1
- package/dist/core/session-cwd.js.map +1 -1
- package/dist/core/session-export.d.ts +6 -2
- package/dist/core/session-export.d.ts.map +1 -1
- package/dist/core/session-export.js +14 -13
- package/dist/core/session-export.js.map +1 -1
- package/dist/core/session-manager.d.ts +72 -13
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +277 -124
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-defaults.d.ts +65 -0
- package/dist/core/settings-defaults.d.ts.map +1 -0
- package/dist/core/settings-defaults.js +66 -0
- package/dist/core/settings-defaults.js.map +1 -0
- package/dist/core/settings-diagnostics.d.ts.map +1 -1
- package/dist/core/settings-diagnostics.js.map +1 -1
- package/dist/core/settings-manager.d.ts +41 -126
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +165 -52
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-schema.d.ts +224 -0
- package/dist/core/settings-schema.d.ts.map +1 -0
- package/dist/core/settings-schema.js +285 -0
- package/dist/core/settings-schema.js.map +1 -0
- package/dist/core/skills.d.ts +4 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +6 -1
- package/dist/core/skills.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +3 -2
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/source-info.d.ts +8 -0
- package/dist/core/source-info.d.ts.map +1 -1
- package/dist/core/source-info.js +16 -0
- package/dist/core/source-info.js.map +1 -1
- package/dist/core/system-prompt.d.ts +55 -6
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +128 -93
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/telemetry.d.ts +2 -0
- package/dist/core/telemetry.d.ts.map +1 -1
- package/dist/core/telemetry.js +45 -0
- package/dist/core/telemetry.js.map +1 -1
- package/dist/core/theme/dark.json +78 -0
- package/dist/core/theme/light.json +78 -0
- package/dist/core/theme/system-theme.d.ts +54 -0
- package/dist/core/theme/system-theme.d.ts.map +1 -0
- package/dist/core/theme/system-theme.js +547 -0
- package/dist/core/theme/system-theme.js.map +1 -0
- package/dist/core/theme/theme-schema.d.ts +28 -0
- package/dist/core/theme/theme-schema.d.ts.map +1 -0
- package/dist/core/theme/theme-schema.js +105 -0
- package/dist/core/theme/theme-schema.js.map +1 -0
- package/dist/core/theme/theme-tokens.d.ts +257 -0
- package/dist/core/theme/theme-tokens.d.ts.map +1 -0
- package/dist/core/theme/theme-tokens.js +94 -0
- package/dist/core/theme/theme-tokens.js.map +1 -0
- package/dist/core/theme/theme.d.ts +162 -0
- package/dist/core/theme/theme.d.ts.map +1 -0
- package/dist/{modes/interactive → core}/theme/theme.js +265 -402
- package/dist/core/theme/theme.js.map +1 -0
- package/dist/core/timings.d.ts.map +1 -1
- package/dist/core/timings.js.map +1 -1
- package/dist/core/tools/bash.d.ts +14 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +43 -6
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts +1 -2
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +0 -3
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
- package/dist/core/tools/file-mutation-queue.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +0 -2
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +0 -2
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +0 -2
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +11 -0
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +40 -10
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/path-utils.d.ts.map +1 -1
- package/dist/core/tools/path-utils.js.map +1 -1
- package/dist/core/tools/powershell.d.ts.map +1 -1
- package/dist/core/tools/powershell.js.map +1 -1
- package/dist/core/tools/read.d.ts +17 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +23 -4
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts +5 -3
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js +3 -1
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/tools/truncate.d.ts +14 -0
- package/dist/core/tools/truncate.d.ts.map +1 -1
- package/dist/core/tools/truncate.js +29 -0
- package/dist/core/tools/truncate.js.map +1 -1
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +0 -2
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +1 -0
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/core/usage-totals.d.ts +3 -1
- package/dist/core/usage-totals.d.ts.map +1 -1
- package/dist/core/usage-totals.js +28 -1
- package/dist/core/usage-totals.js.map +1 -1
- package/dist/core/virtual-models.d.ts +117 -0
- package/dist/core/virtual-models.d.ts.map +1 -0
- package/dist/core/virtual-models.js +124 -0
- package/dist/core/virtual-models.js.map +1 -0
- package/dist/extensions/browser/index.d.ts.map +1 -1
- package/dist/extensions/browser/index.js.map +1 -1
- package/dist/extensions/codemode/execute.d.ts +16 -0
- package/dist/extensions/codemode/execute.d.ts.map +1 -0
- package/dist/extensions/codemode/execute.js +665 -0
- package/dist/extensions/codemode/execute.js.map +1 -0
- package/dist/extensions/codemode/execute.lazy.d.ts +3 -0
- package/dist/extensions/codemode/execute.lazy.d.ts.map +1 -0
- package/dist/extensions/codemode/execute.lazy.js +3 -0
- package/dist/extensions/codemode/execute.lazy.js.map +1 -0
- package/dist/extensions/codemode/index.d.ts +21 -0
- package/dist/extensions/codemode/index.d.ts.map +1 -0
- package/dist/extensions/codemode/index.js +33 -0
- package/dist/extensions/codemode/index.js.map +1 -0
- package/dist/extensions/codemode/tool.d.ts +124 -0
- package/dist/extensions/codemode/tool.d.ts.map +1 -0
- package/dist/extensions/codemode/tool.js +286 -0
- package/dist/extensions/codemode/tool.js.map +1 -0
- package/dist/extensions/codemode/worker.d.ts +7 -0
- package/dist/extensions/codemode/worker.d.ts.map +1 -0
- package/dist/extensions/codemode/worker.js +7 -0
- package/dist/extensions/codemode/worker.js.map +1 -0
- package/dist/extensions/context-pruning/compress_context.d.ts.map +1 -1
- package/dist/extensions/context-pruning/compress_context.js +1 -3
- package/dist/extensions/context-pruning/compress_context.js.map +1 -1
- package/dist/extensions/context-pruning/context-pruning-state.d.ts.map +1 -1
- package/dist/extensions/context-pruning/context-pruning-state.js.map +1 -1
- package/dist/extensions/index.d.ts.map +1 -1
- package/dist/extensions/index.js +6 -2
- package/dist/extensions/index.js.map +1 -1
- package/dist/extensions/llama/client.d.ts +2 -0
- package/dist/extensions/llama/client.d.ts.map +1 -1
- package/dist/extensions/llama/client.js +7 -3
- package/dist/extensions/llama/client.js.map +1 -1
- package/dist/extensions/llama/huggingface.d.ts.map +1 -1
- package/dist/extensions/llama/huggingface.js.map +1 -1
- package/dist/extensions/llama/index.d.ts.map +1 -1
- package/dist/extensions/llama/index.js +0 -4
- package/dist/extensions/llama/index.js.map +1 -1
- package/dist/extensions/llama/provider.d.ts +1 -1
- package/dist/extensions/llama/provider.d.ts.map +1 -1
- package/dist/extensions/llama/provider.js +103 -13
- package/dist/extensions/llama/provider.js.map +1 -1
- package/dist/extensions/llama/ui.d.ts +3 -2
- package/dist/extensions/llama/ui.d.ts.map +1 -1
- package/dist/extensions/llama/ui.js +106 -364
- package/dist/extensions/llama/ui.js.map +1 -1
- package/dist/extensions/mcp/cli.d.ts +21 -0
- package/dist/extensions/mcp/cli.d.ts.map +1 -0
- package/dist/extensions/mcp/cli.js +494 -0
- package/dist/extensions/mcp/cli.js.map +1 -0
- package/dist/extensions/mcp/cli.lazy.d.ts +3 -0
- package/dist/extensions/mcp/cli.lazy.d.ts.map +1 -0
- package/dist/extensions/mcp/cli.lazy.js +3 -0
- package/dist/extensions/mcp/cli.lazy.js.map +1 -0
- package/dist/extensions/mcp/config.d.ts +84 -0
- package/dist/extensions/mcp/config.d.ts.map +1 -0
- package/dist/extensions/mcp/config.js +196 -0
- package/dist/extensions/mcp/config.js.map +1 -0
- package/dist/extensions/mcp/index.d.ts +71 -2
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +839 -131
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/log.d.ts +16 -0
- package/dist/extensions/mcp/log.d.ts.map +1 -0
- package/dist/extensions/mcp/log.js +66 -0
- package/dist/extensions/mcp/log.js.map +1 -0
- package/dist/extensions/mcp/oauth.d.ts +102 -0
- package/dist/extensions/mcp/oauth.d.ts.map +1 -0
- package/dist/extensions/mcp/oauth.js +428 -0
- package/dist/extensions/mcp/oauth.js.map +1 -0
- package/dist/extensions/mcp/resources.d.ts +36 -0
- package/dist/extensions/mcp/resources.d.ts.map +1 -0
- package/dist/extensions/mcp/resources.js +261 -0
- package/dist/extensions/mcp/resources.js.map +1 -0
- package/dist/extensions/mcp/runtime.d.ts +98 -0
- package/dist/extensions/mcp/runtime.d.ts.map +1 -0
- package/dist/extensions/mcp/runtime.js +378 -0
- package/dist/extensions/mcp/runtime.js.map +1 -0
- package/dist/extensions/mcp/runtime.lazy.d.ts +3 -0
- package/dist/extensions/mcp/runtime.lazy.d.ts.map +1 -0
- package/dist/extensions/mcp/runtime.lazy.js +3 -0
- package/dist/extensions/mcp/runtime.lazy.js.map +1 -0
- package/dist/extensions/mcp/tools.d.ts +84 -0
- package/dist/extensions/mcp/tools.d.ts.map +1 -0
- package/dist/extensions/mcp/tools.js +263 -0
- package/dist/extensions/mcp/tools.js.map +1 -0
- package/dist/extensions/punch/a2a-listen.d.ts +9 -0
- package/dist/extensions/punch/a2a-listen.d.ts.map +1 -0
- package/dist/extensions/punch/a2a-listen.js +88 -0
- package/dist/extensions/punch/a2a-listen.js.map +1 -0
- package/dist/extensions/punch/a2a.d.ts +12 -0
- package/dist/extensions/punch/a2a.d.ts.map +1 -0
- package/dist/extensions/punch/a2a.js +106 -0
- package/dist/extensions/punch/a2a.js.map +1 -0
- package/dist/extensions/punch/auth.d.ts +2 -1
- package/dist/extensions/punch/auth.d.ts.map +1 -1
- package/dist/extensions/punch/auth.js +5 -1
- package/dist/extensions/punch/auth.js.map +1 -1
- package/dist/extensions/punch/collabs.d.ts.map +1 -1
- package/dist/extensions/punch/collabs.js.map +1 -1
- package/dist/extensions/punch/index.d.ts.map +1 -1
- package/dist/extensions/punch/index.js +11 -15
- package/dist/extensions/punch/index.js.map +1 -1
- package/dist/extensions/punch/routines.d.ts +1 -3
- package/dist/extensions/punch/routines.d.ts.map +1 -1
- package/dist/extensions/punch/routines.js +1 -121
- package/dist/extensions/punch/routines.js.map +1 -1
- package/dist/extensions/punch/server.d.ts +3 -0
- package/dist/extensions/punch/server.d.ts.map +1 -1
- package/dist/extensions/punch/server.js +41 -3
- package/dist/extensions/punch/server.js.map +1 -1
- package/dist/extensions/punch/timezone.d.ts.map +1 -1
- package/dist/extensions/punch/timezone.js.map +1 -1
- package/dist/extensions/punch/todo-store.d.ts +15 -0
- package/dist/extensions/punch/todo-store.d.ts.map +1 -0
- package/dist/extensions/punch/todo-store.js +208 -0
- package/dist/extensions/punch/todo-store.js.map +1 -0
- package/dist/extensions/punch/todos.d.ts +7 -3
- package/dist/extensions/punch/todos.d.ts.map +1 -1
- package/dist/extensions/punch/todos.js +40 -17
- package/dist/extensions/punch/todos.js.map +1 -1
- package/dist/extensions/report-progress/index.d.ts.map +1 -1
- package/dist/extensions/report-progress/index.js.map +1 -1
- package/dist/extensions/subagent/agents.d.ts.map +1 -1
- package/dist/extensions/subagent/agents.js.map +1 -1
- package/dist/extensions/subagent/index.d.ts.map +1 -1
- package/dist/extensions/subagent/index.js +0 -372
- package/dist/extensions/subagent/index.js.map +1 -1
- package/dist/extensions/tool-search/index.d.ts +12 -0
- package/dist/extensions/tool-search/index.d.ts.map +1 -0
- package/dist/extensions/tool-search/index.js +15 -0
- package/dist/extensions/tool-search/index.js.map +1 -0
- package/dist/extensions/tool-search/tool.d.ts +71 -0
- package/dist/extensions/tool-search/tool.d.ts.map +1 -0
- package/dist/extensions/tool-search/tool.js +187 -0
- package/dist/extensions/tool-search/tool.js.map +1 -0
- package/dist/extensions/webfetch/index.d.ts.map +1 -1
- package/dist/extensions/webfetch/index.js.map +1 -1
- package/dist/extensions/websearch/index.d.ts.map +1 -1
- package/dist/extensions/websearch/index.js.map +1 -1
- package/dist/index.d.ts +13 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -6
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +140 -173
- package/dist/main.js.map +1 -1
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +0 -20
- package/dist/migrations.js.map +1 -1
- package/dist/modes/index.d.ts +0 -1
- package/dist/modes/index.d.ts.map +1 -1
- package/dist/modes/index.js +0 -1
- package/dist/modes/index.js.map +1 -1
- package/dist/modes/json-event.d.ts.map +1 -1
- package/dist/modes/json-event.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +4 -0
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/jsonl.d.ts.map +1 -1
- package/dist/modes/rpc/jsonl.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +10 -6
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +19 -8
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +30 -48
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +21 -1
- 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 +43 -43
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/rpc-entry.d.ts.map +1 -1
- package/dist/rpc-entry.js.map +1 -1
- package/dist/server/a2a/harness-runner.d.ts.map +1 -1
- package/dist/server/a2a/harness-runner.js.map +1 -1
- package/dist/server/a2a/run-server.d.ts.map +1 -1
- package/dist/server/a2a/run-server.js.map +1 -1
- package/dist/utils/abort.d.ts.map +1 -1
- package/dist/utils/abort.js.map +1 -1
- package/dist/utils/ansi.d.ts +8 -0
- package/dist/utils/ansi.d.ts.map +1 -1
- package/dist/utils/ansi.js +30 -11
- package/dist/utils/ansi.js.map +1 -1
- package/dist/utils/changelog.d.ts.map +1 -1
- package/dist/utils/changelog.js +5 -2
- package/dist/utils/changelog.js.map +1 -1
- package/dist/utils/child-process.d.ts.map +1 -1
- package/dist/utils/child-process.js.map +1 -1
- package/dist/utils/clipboard-command.d.ts.map +1 -1
- package/dist/utils/clipboard-command.js.map +1 -1
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +15 -41
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +96 -38
- package/dist/utils/clipboard.js.map +1 -1
- package/dist/utils/colors.d.ts +73 -0
- package/dist/utils/colors.d.ts.map +1 -0
- package/dist/utils/colors.js +273 -0
- package/dist/utils/colors.js.map +1 -0
- package/dist/utils/deprecation.d.ts.map +1 -1
- package/dist/utils/deprecation.js.map +1 -1
- package/dist/utils/exif-orientation.d.ts.map +1 -1
- package/dist/utils/exif-orientation.js.map +1 -1
- package/dist/utils/frontmatter.d.ts.map +1 -1
- package/dist/utils/frontmatter.js.map +1 -1
- package/dist/utils/fs-watch.d.ts.map +1 -1
- package/dist/utils/fs-watch.js.map +1 -1
- package/dist/utils/fuzzy.d.ts +16 -0
- package/dist/utils/fuzzy.d.ts.map +1 -0
- package/dist/utils/fuzzy.js +111 -0
- package/dist/utils/fuzzy.js.map +1 -0
- package/dist/utils/git.d.ts.map +1 -1
- package/dist/utils/git.js.map +1 -1
- package/dist/utils/html.d.ts.map +1 -1
- package/dist/utils/html.js.map +1 -1
- package/dist/utils/image-convert.d.ts.map +1 -1
- package/dist/utils/image-convert.js.map +1 -1
- package/dist/utils/image-process.d.ts.map +1 -1
- package/dist/utils/image-process.js.map +1 -1
- package/dist/utils/image-resize-core.d.ts +12 -0
- package/dist/utils/image-resize-core.d.ts.map +1 -1
- package/dist/utils/image-resize-core.js +5 -0
- package/dist/utils/image-resize-core.js.map +1 -1
- package/dist/utils/image-resize-worker.d.ts.map +1 -1
- package/dist/utils/image-resize-worker.js +3 -2
- package/dist/utils/image-resize-worker.js.map +1 -1
- package/dist/utils/image-resize.d.ts.map +1 -1
- package/dist/utils/image-resize.js +9 -10
- package/dist/utils/image-resize.js.map +1 -1
- package/dist/utils/json.d.ts.map +1 -1
- package/dist/utils/json.js.map +1 -1
- package/dist/utils/management-http.d.ts.map +1 -1
- package/dist/utils/management-http.js.map +1 -1
- package/dist/utils/mime.d.ts.map +1 -1
- package/dist/utils/mime.js +1 -1
- package/dist/utils/mime.js.map +1 -1
- package/dist/utils/oklab.d.ts +43 -0
- package/dist/utils/oklab.d.ts.map +1 -0
- package/dist/utils/oklab.js +210 -0
- package/dist/utils/oklab.js.map +1 -0
- package/dist/utils/open-browser.d.ts.map +1 -1
- package/dist/utils/open-browser.js.map +1 -1
- package/dist/utils/output-files.d.ts +15 -0
- package/dist/utils/output-files.d.ts.map +1 -0
- package/dist/utils/output-files.js +30 -0
- package/dist/utils/output-files.js.map +1 -0
- package/dist/utils/paths.d.ts +3 -3
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +5 -4
- package/dist/utils/paths.js.map +1 -1
- package/dist/utils/photon.d.ts.map +1 -1
- package/dist/utils/photon.js.map +1 -1
- package/dist/utils/pi-user-agent.d.ts.map +1 -1
- package/dist/utils/pi-user-agent.js.map +1 -1
- package/dist/utils/shell.d.ts +1 -3
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +3 -30
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/sleep.d.ts.map +1 -1
- package/dist/utils/sleep.js.map +1 -1
- package/dist/utils/syntax-highlight.d.ts.map +1 -1
- package/dist/utils/syntax-highlight.js +8 -1
- package/dist/utils/syntax-highlight.js.map +1 -1
- package/dist/utils/text.d.ts.map +1 -1
- package/dist/utils/text.js.map +1 -1
- package/dist/utils/tool-result-images.d.ts +3 -1
- package/dist/utils/tool-result-images.d.ts.map +1 -1
- package/dist/utils/tool-result-images.js +4 -1
- package/dist/utils/tool-result-images.js.map +1 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/version-check.d.ts.map +1 -1
- package/dist/utils/version-check.js.map +1 -1
- package/dist/utils/windows-self-update.d.ts.map +1 -1
- package/dist/utils/windows-self-update.js.map +1 -1
- package/dist/utils/wsl.d.ts +3 -0
- package/dist/utils/wsl.d.ts.map +1 -0
- package/dist/utils/wsl.js +15 -0
- package/dist/utils/wsl.js.map +1 -0
- package/dist/utils/zip.d.ts +7 -0
- package/dist/utils/zip.d.ts.map +1 -0
- package/dist/utils/zip.js +60 -0
- package/dist/utils/zip.js.map +1 -0
- package/docs/cli-integration.md +106 -0
- package/docs/cli.md +333 -0
- package/docs/codemode.md +230 -0
- package/docs/compaction.md +47 -28
- package/docs/configuration.md +47 -0
- package/docs/containerization.md +109 -82
- package/docs/custom-provider.md +109 -713
- package/docs/docs.json +152 -96
- package/docs/environment-variables.md +18 -3
- package/docs/extensions.md +284 -604
- package/docs/how-pi-works.md +49 -0
- package/docs/images/interactive-mode.png +0 -0
- package/docs/index.md +24 -69
- package/docs/json.md +193 -65
- package/docs/keybindings.md +58 -103
- package/docs/llama-cpp.md +24 -4
- package/docs/mcp.md +272 -0
- package/docs/message-types.md +279 -0
- package/docs/models.md +124 -489
- package/docs/nvidia-rtx-llama-cpp.md +96 -0
- package/docs/packages.md +67 -166
- package/docs/prompt-templates.md +31 -68
- package/docs/providers.md +158 -228
- package/docs/punch-todos.md +24 -0
- package/docs/quickstart.md +61 -106
- package/docs/rpc-commands.md +888 -0
- package/docs/rpc-extension-ui.md +200 -0
- package/docs/rpc.md +131 -1554
- package/docs/sdk.md +79 -1158
- package/docs/security.md +72 -32
- package/docs/session-format.md +58 -215
- package/docs/sessions.md +35 -114
- package/docs/settings.md +98 -326
- package/docs/shell-aliases.md +85 -5
- package/docs/skills.md +51 -190
- package/docs/slash-commands.md +60 -0
- package/docs/subagents.md +2 -0
- package/docs/terminal-setup.md +7 -182
- package/docs/termux.md +74 -83
- package/docs/themes.md +89 -273
- package/docs/tmux.md +31 -39
- package/docs/tui.md +74 -910
- package/docs/usage.md +52 -129
- package/docs/virtual-models.md +114 -0
- package/docs/windows.md +45 -17
- package/examples/README.md +13 -5
- package/examples/extensions/README.md +4 -30
- package/examples/extensions/custom-provider-anthropic/index.ts +18 -12
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +17 -17
- package/examples/extensions/custom-provider-gitlab-duo/index.ts +2 -2
- package/examples/extensions/custom-provider-gitlab-duo/package.json +14 -14
- package/examples/extensions/custom-provider-gitlab-duo/test.ts +5 -5
- package/examples/extensions/debug-provider.ts +69 -0
- package/examples/extensions/dynamic-resources/dynamic.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +5 -5
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/jev-router.ts +113 -0
- package/examples/extensions/prompt-customizer.ts +19 -67
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +20 -20
- package/examples/rpc-client.ts +35 -0
- package/examples/sdk/14-codemode-mcp.ts +61 -0
- package/examples/sdk/README.md +3 -2
- package/npm-shrinkwrap.json +2425 -0
- package/package.json +30 -29
- package/schemas/models.schema.json +1157 -0
- package/schemas/settings.schema.json +734 -0
- package/schemas/theme.schema.json +365 -0
- package/src/extensions/punch/sqlite-bun.mjs +1 -0
- package/src/extensions/punch/sqlite-driver.d.mts +15 -0
- package/src/extensions/punch/sqlite-node.mjs +1 -0
- package/dist/bundle/chunks/anthropic-messages-ASRU76PT.js +0 -6
- package/dist/bundle/chunks/azure-openai-responses-UGF6LMEX.js +0 -2
- package/dist/bundle/chunks/chunk-5PRUVL6W.js +0 -1770
- package/dist/bundle/chunks/chunk-6R7UI4IY.js +0 -2
- package/dist/bundle/chunks/chunk-A3JYRWB6.js +0 -2
- package/dist/bundle/chunks/chunk-CHB3CEFP.js +0 -2
- package/dist/bundle/chunks/chunk-ELBMWBDG.js +0 -11
- package/dist/bundle/chunks/chunk-GMWCTUPB.js +0 -2
- package/dist/bundle/chunks/chunk-GTBU4EAF.js +0 -2
- package/dist/bundle/chunks/chunk-NUHFSC37.js +0 -25
- package/dist/bundle/chunks/chunk-UIWY7TU5.js +0 -42
- package/dist/bundle/chunks/chunk-XNGRGP62.js +0 -2
- package/dist/bundle/chunks/google-generative-ai-VCD2PGIY.js +0 -2
- package/dist/bundle/chunks/google-vertex-L6U34ZRC.js +0 -2
- package/dist/bundle/chunks/mistral-conversations-IXWQ2YKN.js +0 -5
- package/dist/bundle/chunks/node-5YXRXMVN.js +0 -16
- package/dist/bundle/chunks/openai-codex-responses-P7HKQLIT.js +0 -10
- package/dist/bundle/chunks/openai-completions-O7BFLP3U.js +0 -7
- package/dist/bundle/chunks/openai-responses-QAKWAYVG.js +0 -2
- package/dist/cli/config-selector.d.ts +0 -16
- package/dist/cli/config-selector.d.ts.map +0 -1
- package/dist/cli/config-selector.js +0 -32
- package/dist/cli/config-selector.js.map +0 -1
- package/dist/cli/session-picker.d.ts +0 -10
- package/dist/cli/session-picker.d.ts.map +0 -1
- package/dist/cli/session-picker.js +0 -36
- package/dist/cli/session-picker.js.map +0 -1
- package/dist/cli/startup-ui.d.ts +0 -20
- package/dist/cli/startup-ui.d.ts.map +0 -1
- package/dist/cli/startup-ui.js +0 -185
- package/dist/cli/startup-ui.js.map +0 -1
- package/dist/core/keybindings.d.ts +0 -428
- package/dist/core/keybindings.d.ts.map +0 -1
- package/dist/core/keybindings.js +0 -321
- package/dist/core/keybindings.js.map +0 -1
- package/dist/core/tools/render-utils.d.ts +0 -24
- package/dist/core/tools/render-utils.d.ts.map +0 -1
- package/dist/core/tools/render-utils.js +0 -65
- package/dist/core/tools/render-utils.js.map +0 -1
- package/dist/core/tools/renderers/bash.d.ts +0 -12
- package/dist/core/tools/renderers/bash.d.ts.map +0 -1
- package/dist/core/tools/renderers/bash.js +0 -130
- package/dist/core/tools/renderers/bash.js.map +0 -1
- package/dist/core/tools/renderers/edit.d.ts +0 -23
- package/dist/core/tools/renderers/edit.d.ts.map +0 -1
- package/dist/core/tools/renderers/edit.js +0 -167
- package/dist/core/tools/renderers/edit.js.map +0 -1
- package/dist/core/tools/renderers/find.d.ts +0 -10
- package/dist/core/tools/renderers/find.d.ts.map +0 -1
- package/dist/core/tools/renderers/find.js +0 -64
- package/dist/core/tools/renderers/find.js.map +0 -1
- package/dist/core/tools/renderers/grep.d.ts +0 -10
- package/dist/core/tools/renderers/grep.d.ts.map +0 -1
- package/dist/core/tools/renderers/grep.js +0 -69
- package/dist/core/tools/renderers/grep.js.map +0 -1
- package/dist/core/tools/renderers/index.d.ts +0 -28
- package/dist/core/tools/renderers/index.d.ts.map +0 -1
- package/dist/core/tools/renderers/index.js +0 -47
- package/dist/core/tools/renderers/index.js.map +0 -1
- package/dist/core/tools/renderers/ls.d.ts +0 -10
- package/dist/core/tools/renderers/ls.d.ts.map +0 -1
- package/dist/core/tools/renderers/ls.js +0 -58
- package/dist/core/tools/renderers/ls.js.map +0 -1
- package/dist/core/tools/renderers/read.d.ts +0 -11
- package/dist/core/tools/renderers/read.d.ts.map +0 -1
- package/dist/core/tools/renderers/read.js +0 -129
- package/dist/core/tools/renderers/read.js.map +0 -1
- package/dist/core/tools/renderers/write.d.ts +0 -10
- package/dist/core/tools/renderers/write.d.ts.map +0 -1
- package/dist/core/tools/renderers/write.js +0 -153
- package/dist/core/tools/renderers/write.js.map +0 -1
- package/dist/extensions/mcp/mcp-client.d.ts +0 -31
- package/dist/extensions/mcp/mcp-client.d.ts.map +0 -1
- package/dist/extensions/mcp/mcp-client.js +0 -149
- package/dist/extensions/mcp/mcp-client.js.map +0 -1
- package/dist/extensions/mcp/mcp-config.d.ts +0 -47
- package/dist/extensions/mcp/mcp-config.d.ts.map +0 -1
- package/dist/extensions/mcp/mcp-config.js +0 -281
- package/dist/extensions/mcp/mcp-config.js.map +0 -1
- package/dist/extensions/mcp/mcp-transport.d.ts +0 -65
- package/dist/extensions/mcp/mcp-transport.d.ts.map +0 -1
- package/dist/extensions/mcp/mcp-transport.js +0 -278
- package/dist/extensions/mcp/mcp-transport.js.map +0 -1
- package/dist/modes/interactive/assets/clankolas.png +0 -0
- package/dist/modes/interactive/chat-viewport.d.ts +0 -20
- package/dist/modes/interactive/chat-viewport.d.ts.map +0 -1
- package/dist/modes/interactive/chat-viewport.js +0 -28
- package/dist/modes/interactive/chat-viewport.js.map +0 -1
- package/dist/modes/interactive/components/armin.d.ts +0 -34
- package/dist/modes/interactive/components/armin.d.ts.map +0 -1
- package/dist/modes/interactive/components/armin.js +0 -333
- package/dist/modes/interactive/components/armin.js.map +0 -1
- package/dist/modes/interactive/components/assistant-message.d.ts +0 -26
- package/dist/modes/interactive/components/assistant-message.d.ts.map +0 -1
- package/dist/modes/interactive/components/assistant-message.js +0 -158
- package/dist/modes/interactive/components/assistant-message.js.map +0 -1
- package/dist/modes/interactive/components/bash-execution.d.ts +0 -34
- package/dist/modes/interactive/components/bash-execution.d.ts.map +0 -1
- package/dist/modes/interactive/components/bash-execution.js +0 -175
- package/dist/modes/interactive/components/bash-execution.js.map +0 -1
- package/dist/modes/interactive/components/bordered-loader.d.ts +0 -16
- package/dist/modes/interactive/components/bordered-loader.d.ts.map +0 -1
- package/dist/modes/interactive/components/bordered-loader.js +0 -54
- package/dist/modes/interactive/components/bordered-loader.js.map +0 -1
- package/dist/modes/interactive/components/branch-summary-message.d.ts +0 -16
- package/dist/modes/interactive/components/branch-summary-message.d.ts.map +0 -1
- package/dist/modes/interactive/components/branch-summary-message.js +0 -44
- package/dist/modes/interactive/components/branch-summary-message.js.map +0 -1
- package/dist/modes/interactive/components/compaction-summary-message.d.ts +0 -16
- package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +0 -1
- package/dist/modes/interactive/components/compaction-summary-message.js +0 -45
- package/dist/modes/interactive/components/compaction-summary-message.js.map +0 -1
- package/dist/modes/interactive/components/config-selector.d.ts +0 -102
- package/dist/modes/interactive/components/config-selector.d.ts.map +0 -1
- package/dist/modes/interactive/components/config-selector.js +0 -761
- package/dist/modes/interactive/components/config-selector.js.map +0 -1
- package/dist/modes/interactive/components/countdown-timer.d.ts +0 -14
- package/dist/modes/interactive/components/countdown-timer.d.ts.map +0 -1
- package/dist/modes/interactive/components/countdown-timer.js +0 -33
- package/dist/modes/interactive/components/countdown-timer.js.map +0 -1
- package/dist/modes/interactive/components/custom-editor.d.ts +0 -30
- package/dist/modes/interactive/components/custom-editor.d.ts.map +0 -1
- package/dist/modes/interactive/components/custom-editor.js +0 -115
- package/dist/modes/interactive/components/custom-editor.js.map +0 -1
- package/dist/modes/interactive/components/custom-entry.d.ts +0 -19
- package/dist/modes/interactive/components/custom-entry.d.ts.map +0 -1
- package/dist/modes/interactive/components/custom-entry.js +0 -52
- package/dist/modes/interactive/components/custom-entry.js.map +0 -1
- package/dist/modes/interactive/components/custom-message.d.ts +0 -22
- package/dist/modes/interactive/components/custom-message.d.ts.map +0 -1
- package/dist/modes/interactive/components/custom-message.js +0 -87
- package/dist/modes/interactive/components/custom-message.js.map +0 -1
- package/dist/modes/interactive/components/daxnuts.d.ts +0 -23
- package/dist/modes/interactive/components/daxnuts.d.ts.map +0 -1
- package/dist/modes/interactive/components/daxnuts.js +0 -140
- package/dist/modes/interactive/components/daxnuts.js.map +0 -1
- package/dist/modes/interactive/components/diff.d.ts +0 -12
- package/dist/modes/interactive/components/diff.d.ts.map +0 -1
- package/dist/modes/interactive/components/diff.js +0 -133
- package/dist/modes/interactive/components/diff.js.map +0 -1
- package/dist/modes/interactive/components/dynamic-border.d.ts +0 -15
- package/dist/modes/interactive/components/dynamic-border.d.ts.map +0 -1
- package/dist/modes/interactive/components/dynamic-border.js +0 -21
- package/dist/modes/interactive/components/dynamic-border.js.map +0 -1
- package/dist/modes/interactive/components/earendil-announcement.d.ts +0 -5
- package/dist/modes/interactive/components/earendil-announcement.d.ts.map +0 -1
- package/dist/modes/interactive/components/earendil-announcement.js +0 -40
- package/dist/modes/interactive/components/earendil-announcement.js.map +0 -1
- package/dist/modes/interactive/components/extension-editor.d.ts +0 -21
- package/dist/modes/interactive/components/extension-editor.d.ts.map +0 -1
- package/dist/modes/interactive/components/extension-editor.js +0 -98
- package/dist/modes/interactive/components/extension-editor.js.map +0 -1
- package/dist/modes/interactive/components/extension-input.d.ts +0 -23
- package/dist/modes/interactive/components/extension-input.d.ts.map +0 -1
- package/dist/modes/interactive/components/extension-input.js +0 -61
- package/dist/modes/interactive/components/extension-input.js.map +0 -1
- package/dist/modes/interactive/components/extension-selector.d.ts +0 -26
- package/dist/modes/interactive/components/extension-selector.d.ts.map +0 -1
- package/dist/modes/interactive/components/extension-selector.js +0 -83
- package/dist/modes/interactive/components/extension-selector.js.map +0 -1
- package/dist/modes/interactive/components/first-time-setup.d.ts +0 -25
- package/dist/modes/interactive/components/first-time-setup.d.ts.map +0 -1
- package/dist/modes/interactive/components/first-time-setup.js +0 -103
- package/dist/modes/interactive/components/first-time-setup.js.map +0 -1
- package/dist/modes/interactive/components/footer.d.ts +0 -32
- package/dist/modes/interactive/components/footer.d.ts.map +0 -1
- package/dist/modes/interactive/components/footer.js +0 -222
- package/dist/modes/interactive/components/footer.js.map +0 -1
- package/dist/modes/interactive/components/index.d.ts +0 -34
- package/dist/modes/interactive/components/index.d.ts.map +0 -1
- package/dist/modes/interactive/components/index.js +0 -35
- package/dist/modes/interactive/components/index.js.map +0 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts +0 -13
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +0 -1
- package/dist/modes/interactive/components/keybinding-hints.js +0 -36
- package/dist/modes/interactive/components/keybinding-hints.js.map +0 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +0 -52
- package/dist/modes/interactive/components/login-dialog.d.ts.map +0 -1
- package/dist/modes/interactive/components/login-dialog.js +0 -188
- package/dist/modes/interactive/components/login-dialog.js.map +0 -1
- package/dist/modes/interactive/components/markdown-transform.d.ts +0 -3
- package/dist/modes/interactive/components/markdown-transform.d.ts.map +0 -1
- package/dist/modes/interactive/components/markdown-transform.js +0 -19
- package/dist/modes/interactive/components/markdown-transform.js.map +0 -1
- package/dist/modes/interactive/components/mermaid.d.ts +0 -11
- package/dist/modes/interactive/components/mermaid.d.ts.map +0 -1
- package/dist/modes/interactive/components/mermaid.js +0 -75
- package/dist/modes/interactive/components/mermaid.js.map +0 -1
- package/dist/modes/interactive/components/model-selector.d.ts +0 -60
- package/dist/modes/interactive/components/model-selector.d.ts.map +0 -1
- package/dist/modes/interactive/components/model-selector.js +0 -361
- package/dist/modes/interactive/components/model-selector.js.map +0 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +0 -33
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +0 -1
- package/dist/modes/interactive/components/oauth-selector.js +0 -163
- package/dist/modes/interactive/components/oauth-selector.js.map +0 -1
- package/dist/modes/interactive/components/question-selector.d.ts +0 -24
- package/dist/modes/interactive/components/question-selector.d.ts.map +0 -1
- package/dist/modes/interactive/components/question-selector.js +0 -158
- package/dist/modes/interactive/components/question-selector.js.map +0 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts +0 -46
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +0 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +0 -326
- package/dist/modes/interactive/components/scoped-models-selector.js.map +0 -1
- package/dist/modes/interactive/components/session-selector-search.d.ts +0 -23
- package/dist/modes/interactive/components/session-selector-search.d.ts.map +0 -1
- package/dist/modes/interactive/components/session-selector-search.js +0 -155
- package/dist/modes/interactive/components/session-selector-search.js.map +0 -1
- package/dist/modes/interactive/components/session-selector.d.ts +0 -95
- package/dist/modes/interactive/components/session-selector.d.ts.map +0 -1
- package/dist/modes/interactive/components/session-selector.js +0 -867
- package/dist/modes/interactive/components/session-selector.js.map +0 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +0 -92
- package/dist/modes/interactive/components/settings-selector.d.ts.map +0 -1
- package/dist/modes/interactive/components/settings-selector.js +0 -709
- package/dist/modes/interactive/components/settings-selector.js.map +0 -1
- package/dist/modes/interactive/components/settings-submenu.d.ts +0 -72
- package/dist/modes/interactive/components/settings-submenu.d.ts.map +0 -1
- package/dist/modes/interactive/components/settings-submenu.js +0 -165
- package/dist/modes/interactive/components/settings-submenu.js.map +0 -1
- package/dist/modes/interactive/components/show-images-selector.d.ts +0 -10
- package/dist/modes/interactive/components/show-images-selector.d.ts.map +0 -1
- package/dist/modes/interactive/components/show-images-selector.js +0 -39
- package/dist/modes/interactive/components/show-images-selector.js.map +0 -1
- package/dist/modes/interactive/components/skill-invocation-message.d.ts +0 -17
- package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +0 -1
- package/dist/modes/interactive/components/skill-invocation-message.js +0 -47
- package/dist/modes/interactive/components/skill-invocation-message.js.map +0 -1
- package/dist/modes/interactive/components/status-indicator.d.ts +0 -30
- package/dist/modes/interactive/components/status-indicator.d.ts.map +0 -1
- package/dist/modes/interactive/components/status-indicator.js +0 -67
- package/dist/modes/interactive/components/status-indicator.js.map +0 -1
- package/dist/modes/interactive/components/theme-selector.d.ts +0 -11
- package/dist/modes/interactive/components/theme-selector.d.ts.map +0 -1
- package/dist/modes/interactive/components/theme-selector.js +0 -50
- package/dist/modes/interactive/components/theme-selector.js.map +0 -1
- package/dist/modes/interactive/components/thinking-selector.d.ts +0 -23
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +0 -1
- package/dist/modes/interactive/components/thinking-selector.js +0 -109
- package/dist/modes/interactive/components/thinking-selector.js.map +0 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +0 -80
- package/dist/modes/interactive/components/tool-execution.d.ts.map +0 -1
- package/dist/modes/interactive/components/tool-execution.js +0 -328
- package/dist/modes/interactive/components/tool-execution.js.map +0 -1
- package/dist/modes/interactive/components/tree-selector.d.ts +0 -94
- package/dist/modes/interactive/components/tree-selector.d.ts.map +0 -1
- package/dist/modes/interactive/components/tree-selector.js +0 -1245
- package/dist/modes/interactive/components/tree-selector.js.map +0 -1
- package/dist/modes/interactive/components/trust-selector.d.ts +0 -23
- package/dist/modes/interactive/components/trust-selector.d.ts.map +0 -1
- package/dist/modes/interactive/components/trust-selector.js +0 -91
- package/dist/modes/interactive/components/trust-selector.js.map +0 -1
- package/dist/modes/interactive/components/user-message-selector.d.ts +0 -30
- package/dist/modes/interactive/components/user-message-selector.d.ts.map +0 -1
- package/dist/modes/interactive/components/user-message-selector.js +0 -114
- package/dist/modes/interactive/components/user-message-selector.js.map +0 -1
- package/dist/modes/interactive/components/user-message.d.ts +0 -16
- package/dist/modes/interactive/components/user-message.d.ts.map +0 -1
- package/dist/modes/interactive/components/user-message.js +0 -49
- package/dist/modes/interactive/components/user-message.js.map +0 -1
- package/dist/modes/interactive/components/visual-truncate.d.ts +0 -24
- package/dist/modes/interactive/components/visual-truncate.d.ts.map +0 -1
- package/dist/modes/interactive/components/visual-truncate.js +0 -33
- package/dist/modes/interactive/components/visual-truncate.js.map +0 -1
- package/dist/modes/interactive/external-editor.d.ts +0 -12
- package/dist/modes/interactive/external-editor.d.ts.map +0 -1
- package/dist/modes/interactive/external-editor.js +0 -38
- package/dist/modes/interactive/external-editor.js.map +0 -1
- package/dist/modes/interactive/interactive-mode.d.ts +0 -443
- package/dist/modes/interactive/interactive-mode.d.ts.map +0 -1
- package/dist/modes/interactive/interactive-mode.js +0 -5604
- package/dist/modes/interactive/interactive-mode.js.map +0 -1
- package/dist/modes/interactive/model-catalog-refresh.d.ts.map +0 -1
- package/dist/modes/interactive/model-catalog-refresh.js.map +0 -1
- package/dist/modes/interactive/model-search.d.ts +0 -12
- package/dist/modes/interactive/model-search.d.ts.map +0 -1
- package/dist/modes/interactive/model-search.js +0 -15
- package/dist/modes/interactive/model-search.js.map +0 -1
- package/dist/modes/interactive/session-share.d.ts +0 -16
- package/dist/modes/interactive/session-share.d.ts.map +0 -1
- package/dist/modes/interactive/session-share.js +0 -184
- package/dist/modes/interactive/session-share.js.map +0 -1
- package/dist/modes/interactive/theme/dark.json +0 -91
- package/dist/modes/interactive/theme/light.json +0 -90
- package/dist/modes/interactive/theme/theme-controller.d.ts +0 -41
- package/dist/modes/interactive/theme/theme-controller.d.ts.map +0 -1
- package/dist/modes/interactive/theme/theme-controller.js +0 -130
- package/dist/modes/interactive/theme/theme-controller.js.map +0 -1
- package/dist/modes/interactive/theme/theme-json.d.ts +0 -84
- package/dist/modes/interactive/theme/theme-json.d.ts.map +0 -1
- package/dist/modes/interactive/theme/theme-json.js +0 -130
- package/dist/modes/interactive/theme/theme-json.js.map +0 -1
- package/dist/modes/interactive/theme/theme-schema.json +0 -356
- package/dist/modes/interactive/theme/theme.d.ts +0 -131
- package/dist/modes/interactive/theme/theme.d.ts.map +0 -1
- package/dist/modes/interactive/theme/theme.js.map +0 -1
- package/dist/modes/interactive/tui-renderer.d.ts +0 -21
- package/dist/modes/interactive/tui-renderer.d.ts.map +0 -1
- package/dist/modes/interactive/tui-renderer.js +0 -66
- package/dist/modes/interactive/tui-renderer.js.map +0 -1
- package/docs/development.md +0 -90
- package/examples/extensions/border-status-editor.ts +0 -145
- package/examples/extensions/built-in-tool-renderer.ts +0 -249
- package/examples/extensions/custom-footer.ts +0 -64
- package/examples/extensions/custom-header.ts +0 -73
- package/examples/extensions/doom-overlay/README.md +0 -46
- package/examples/extensions/doom-overlay/doom/build/doom.js +0 -21
- package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
- package/examples/extensions/doom-overlay/doom/build.sh +0 -152
- package/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +0 -72
- package/examples/extensions/doom-overlay/doom-component.ts +0 -132
- package/examples/extensions/doom-overlay/doom-engine.ts +0 -173
- package/examples/extensions/doom-overlay/doom-keys.ts +0 -104
- package/examples/extensions/doom-overlay/index.ts +0 -74
- package/examples/extensions/doom-overlay/wad-finder.ts +0 -55
- package/examples/extensions/entry-renderer.ts +0 -41
- package/examples/extensions/github-issue-autocomplete.ts +0 -185
- package/examples/extensions/handoff.ts +0 -190
- package/examples/extensions/interactive-shell.ts +0 -196
- package/examples/extensions/kimi-deferred-tools.ts +0 -61
- package/examples/extensions/message-renderer.ts +0 -59
- package/examples/extensions/minimal-mode.ts +0 -426
- package/examples/extensions/modal-editor.ts +0 -85
- package/examples/extensions/overlay-qa-tests.ts +0 -1450
- package/examples/extensions/overlay-test.ts +0 -153
- package/examples/extensions/plan-mode/README.md +0 -66
- package/examples/extensions/plan-mode/index.ts +0 -390
- package/examples/extensions/plan-mode/utils.ts +0 -168
- package/examples/extensions/preset.ts +0 -436
- package/examples/extensions/qna.ts +0 -118
- package/examples/extensions/question.ts +0 -278
- package/examples/extensions/questionnaire.ts +0 -440
- package/examples/extensions/rainbow-editor.ts +0 -88
- package/examples/extensions/snake.ts +0 -343
- package/examples/extensions/space-invaders.ts +0 -560
- package/examples/extensions/structured-output.ts +0 -65
- package/examples/extensions/summarize.ts +0 -199
- package/examples/extensions/tic-tac-toe.ts +0 -1008
- package/examples/extensions/todo.ts +0 -297
- package/examples/extensions/tools.ts +0 -146
- package/examples/extensions/truncated-tool.ts +0 -195
- package/examples/plugins/pi-example-plugin/README.md +0 -38
- package/examples/plugins/pi-example-plugin/package.json +0 -10
- package/examples/plugins/pi-example-plugin/src/contract.ts +0 -13
- package/examples/plugins/pi-example-plugin/src/session.ts +0 -23
- package/examples/plugins/pi-example-plugin/src/tui.ts +0 -31
- package/examples/rpc-extension-ui.ts +0 -641
- /package/dist/bundle/chunks/{chunk-PATAL4PO.js → chunk-7ZC4UXSL.js} +0 -0
|
@@ -14,30 +14,38 @@
|
|
|
14
14
|
*/
|
|
15
15
|
import { readFileSync } from "node:fs";
|
|
16
16
|
import { basename, dirname } from "node:path";
|
|
17
|
-
import {
|
|
17
|
+
import { runToolCall, } from "@punch-bot/agent";
|
|
18
|
+
import { contentText, getCurrentSystemMessage, retryDelayMs } from "@punch-bot/ai";
|
|
18
19
|
import { clampThinkingLevel, cleanupSessionResources, getSupportedThinkingLevels, isContextOverflow, isRecoverableLength, isRetryableAssistantError, modelsAreEqual, resetApiProviders, streamSimple, } from "@punch-bot/ai/compat";
|
|
19
|
-
import { getThemeByName, theme } from "../modes/interactive/theme/theme.js";
|
|
20
20
|
import { stripFrontmatter } from "../utils/frontmatter.js";
|
|
21
|
+
import { processImage } from "../utils/image-process.js";
|
|
21
22
|
import { sleep } from "../utils/sleep.js";
|
|
22
23
|
import { normalizeToolResultImages } from "../utils/tool-result-images.js";
|
|
23
24
|
import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.js";
|
|
24
25
|
import { executeBashWithOperations } from "./bash-executor.js";
|
|
25
|
-
import {
|
|
26
|
+
import { generateBugReportSummary } from "./bug-report.js";
|
|
27
|
+
import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, estimateProjectedContextTokens, estimateTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
|
|
26
28
|
import { DEFAULT_THINKING_LEVEL, THINKING_LEVEL_OPTIONS } from "./defaults.js";
|
|
27
29
|
import { exportSessionToHtml } from "./export-html/index.js";
|
|
28
30
|
import { createToolHtmlRenderer } from "./export-html/tool-renderer.js";
|
|
29
31
|
import { ExtensionRunner, wrapRegisteredTools, } from "./extensions/index.js";
|
|
30
32
|
import { emitSessionShutdownEvent } from "./extensions/runner.js";
|
|
33
|
+
import { createToolNameMatcher, isMcpToolName } from "./mcp-servers.js";
|
|
34
|
+
import { convertToLlm } from "./messages.js";
|
|
31
35
|
import { ModelRegistry } from "./model-registry.js";
|
|
36
|
+
import { NestedToolCallRunner } from "./nested-tool-calls.js";
|
|
32
37
|
import { expandPromptTemplate } from "./prompt-templates.js";
|
|
33
38
|
import { exportSessionToJsonl } from "./session-export.js";
|
|
34
|
-
import { getLatestCompactionEntry } from "./session-manager.js";
|
|
35
|
-
import {
|
|
36
|
-
import {
|
|
39
|
+
import { getLatestCompactionEntry, SessionManager, } from "./session-manager.js";
|
|
40
|
+
import { applyToolModifiers, DEFAULT_TOOL_NAMES, } from "./settings-manager.js";
|
|
41
|
+
import { BUILTIN_PATH_PREFIX, createSyntheticSourceInfo, isSyntheticPath } from "./source-info.js";
|
|
42
|
+
import { buildSystemPrompt, buildSystemPromptSections, diffSystemPromptSections, normalizeBuildSystemPromptOptions, } from "./system-prompt.js";
|
|
43
|
+
import { getThemeByName, theme } from "./theme/theme.js";
|
|
37
44
|
import { createLocalBashOperations } from "./tools/bash.js";
|
|
38
45
|
import { createAllToolDefinitions } from "./tools/index.js";
|
|
39
46
|
import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";
|
|
40
|
-
import { addUsageToTotals, createUsageTotals } from "./usage-totals.js";
|
|
47
|
+
import { addUsageToTotals, combineUsage, createUsageTotals } from "./usage-totals.js";
|
|
48
|
+
import { findLatestResponse, getBranchSelection, getVirtualModelState, isVirtualModel, VIRTUAL_MODEL_STATE_ENTRY, } from "./virtual-models.js";
|
|
41
49
|
/**
|
|
42
50
|
* Parse a skill block from message text.
|
|
43
51
|
* Returns null if the text doesn't contain a skill block.
|
|
@@ -80,6 +88,7 @@ export class AgentSession {
|
|
|
80
88
|
_unsubscribeAgent;
|
|
81
89
|
_eventListeners = [];
|
|
82
90
|
_isAgentRunActive = false;
|
|
91
|
+
_agentRunAbortRequested = false;
|
|
83
92
|
_idleWaitPromise;
|
|
84
93
|
_resolveIdleWait;
|
|
85
94
|
/** Tracks pending steering messages for UI display. Removed when delivered. */
|
|
@@ -99,20 +108,48 @@ export class AgentSession {
|
|
|
99
108
|
// Retry state
|
|
100
109
|
_retryAbortController = undefined;
|
|
101
110
|
_retryAttempt = 0;
|
|
111
|
+
/**
|
|
112
|
+
* Failed response that the next request repeats, set by auto-retry and overflow recovery. The
|
|
113
|
+
* retry is routed with it as `failed`, since the context no longer contains it.
|
|
114
|
+
*/
|
|
115
|
+
_failedResponse;
|
|
102
116
|
// Bash execution state
|
|
103
117
|
_bashAbortControllers = new Set();
|
|
104
118
|
_pendingBashMessages = [];
|
|
105
119
|
// Extension system
|
|
106
120
|
_extensionRunner;
|
|
107
121
|
_turnIndex = 0;
|
|
122
|
+
_entryIdsByMessage = new WeakMap();
|
|
123
|
+
_boundaryDispatchedMessages = new WeakSet();
|
|
124
|
+
_lastAssistantMessage;
|
|
125
|
+
_lastAssistantToolResults = [];
|
|
126
|
+
_lastActivityOutcome = "completed";
|
|
127
|
+
_isBeforeSettle = false;
|
|
128
|
+
_abortDuringBeforeSettle = false;
|
|
129
|
+
_isEmittingAgentSettled = false;
|
|
130
|
+
_deferredSettledActions = [];
|
|
108
131
|
_resourceLoader;
|
|
109
132
|
_customTools;
|
|
110
133
|
_baseToolDefinitions = new Map();
|
|
111
134
|
_cwd;
|
|
112
135
|
_extensionRunnerRef;
|
|
113
136
|
_initialActiveToolNames;
|
|
114
|
-
|
|
115
|
-
|
|
137
|
+
/**
|
|
138
|
+
* Tools of the restored or reloaded loadout that are not registered yet, such as tools of MCP
|
|
139
|
+
* servers that are still connecting. They are activated when they are registered, and dropped when
|
|
140
|
+
* `setActiveToolsByName()` deactivates a tool or the next agent run starts.
|
|
141
|
+
*/
|
|
142
|
+
_pendingToolNames = new Set();
|
|
143
|
+
_usesDefaultTools;
|
|
144
|
+
_defaultToolModifiers;
|
|
145
|
+
/** Matches the `--tools` entries: tool names or patterns. */
|
|
146
|
+
_allowedTools;
|
|
147
|
+
/**
|
|
148
|
+
* Whether the allowlist filters MCP tools: it is empty (`--no-tools`) or names an MCP tool
|
|
149
|
+
* (`mcp__*`). Otherwise it keeps MCP tools registered for codemode and tool_search.
|
|
150
|
+
*/
|
|
151
|
+
_allowlistFiltersMcp = false;
|
|
152
|
+
_excludedTools;
|
|
116
153
|
_baseToolsOverride;
|
|
117
154
|
_sessionStartEvent;
|
|
118
155
|
_extensionUIContext;
|
|
@@ -123,15 +160,19 @@ export class AgentSession {
|
|
|
123
160
|
_extensionErrorListener;
|
|
124
161
|
_extensionErrorUnsubscriber;
|
|
125
162
|
_modelRuntime;
|
|
163
|
+
_cacheWarmer;
|
|
126
164
|
// Tool registry for extension getTools/setTools
|
|
127
165
|
_toolRegistry = new Map();
|
|
166
|
+
/** Created on the first `ctx.executeTool()` call. */
|
|
167
|
+
_nestedToolCalls;
|
|
168
|
+
/** Declared tools whose declarations requests leave out, from `prepareLoadout` hooks. */
|
|
169
|
+
_hiddenDeclarations = new Set();
|
|
128
170
|
_toolDefinitions = new Map();
|
|
129
171
|
_toolPromptSnippets = new Map();
|
|
130
172
|
_toolPromptGuidelines = new Map();
|
|
131
|
-
// Base system prompt (without extension appends) - used to apply fresh appends each turn
|
|
132
|
-
_baseSystemPrompt = "";
|
|
133
173
|
_baseSystemPromptOptions;
|
|
134
|
-
|
|
174
|
+
/** Prompt options after before_agent_start mutations for the active run. */
|
|
175
|
+
_runSystemPromptOptions;
|
|
135
176
|
constructor(config) {
|
|
136
177
|
this.agent = config.agent;
|
|
137
178
|
this.sessionManager = config.sessionManager;
|
|
@@ -141,10 +182,20 @@ export class AgentSession {
|
|
|
141
182
|
this._customTools = config.customTools ?? [];
|
|
142
183
|
this._cwd = config.cwd;
|
|
143
184
|
this._modelRuntime = config.modelRuntime;
|
|
185
|
+
this._cacheWarmer = config.cacheWarmer;
|
|
186
|
+
if (this._cacheWarmer) {
|
|
187
|
+
this._cacheWarmer.onWarmed = (entry) => this._emit({ type: "entry_appended", entry });
|
|
188
|
+
}
|
|
144
189
|
this._extensionRunnerRef = config.extensionRunnerRef;
|
|
145
190
|
this._initialActiveToolNames = config.initialActiveToolNames;
|
|
146
|
-
this.
|
|
147
|
-
this.
|
|
191
|
+
this._usesDefaultTools = config.usesDefaultTools ?? false;
|
|
192
|
+
this._defaultToolModifiers = config.defaultToolModifiers ?? [];
|
|
193
|
+
if (config.allowedToolNames) {
|
|
194
|
+
this._allowedTools = createToolNameMatcher(config.allowedToolNames);
|
|
195
|
+
this._allowlistFiltersMcp =
|
|
196
|
+
config.allowedToolNames.length === 0 || config.allowedToolNames.some((entry) => entry.startsWith("mcp__"));
|
|
197
|
+
}
|
|
198
|
+
this._excludedTools = config.excludedToolNames ? createToolNameMatcher(config.excludedToolNames) : undefined;
|
|
148
199
|
this._baseToolsOverride = config.baseToolsOverride;
|
|
149
200
|
this._sessionStartEvent = config.sessionStartEvent ?? { type: "session_start", reason: "startup" };
|
|
150
201
|
// Always subscribe to agent events for internal handling
|
|
@@ -152,18 +203,24 @@ export class AgentSession {
|
|
|
152
203
|
this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
|
|
153
204
|
this._installAgentToolHooks();
|
|
154
205
|
this._installAgentNextTurnRefresh();
|
|
206
|
+
this._installAgentRequestProjection();
|
|
207
|
+
this._installAgentBoundaryHooks();
|
|
208
|
+
this._installHiddenDeclarationsProjection();
|
|
209
|
+
this._installAgentForcedPromptProjection();
|
|
155
210
|
this._buildRuntime({
|
|
156
211
|
activeToolNames: this._initialActiveToolNames,
|
|
157
212
|
includeAllExtensionTools: true,
|
|
158
213
|
});
|
|
214
|
+
if (this._usesDefaultTools)
|
|
215
|
+
this._restoreToolsFromTranscript(this._defaultToolModifiers);
|
|
159
216
|
}
|
|
160
217
|
get modelRuntime() {
|
|
161
218
|
return this._modelRuntime;
|
|
162
219
|
}
|
|
163
|
-
async _getRequiredRequestAuth(model) {
|
|
220
|
+
async _getRequiredRequestAuth(model, signal) {
|
|
164
221
|
let result;
|
|
165
222
|
try {
|
|
166
|
-
result = await this._modelRuntime.getAuth(model);
|
|
223
|
+
result = await this._modelRuntime.getAuth(model, { signal });
|
|
167
224
|
}
|
|
168
225
|
catch (error) {
|
|
169
226
|
const cause = error instanceof Error ? error.cause : undefined;
|
|
@@ -189,26 +246,71 @@ export class AgentSession {
|
|
|
189
246
|
}
|
|
190
247
|
throw new Error(formatNoApiKeyFoundMessage(model.provider));
|
|
191
248
|
}
|
|
192
|
-
async _getSummarizationRequestAuth(
|
|
249
|
+
async _getSummarizationRequestAuth(selectedModel, signal) {
|
|
250
|
+
// Route a virtual model first: summaries size their input and output from the model they get.
|
|
251
|
+
const { model, thinkingLevel } = isVirtualModel(selectedModel)
|
|
252
|
+
? await this._modelRuntime.resolveModel(selectedModel, convertToLlm(this.messages), {
|
|
253
|
+
reason: "direct",
|
|
254
|
+
thinkingLevel: this.thinkingLevel,
|
|
255
|
+
signal,
|
|
256
|
+
})
|
|
257
|
+
: { model: selectedModel, thinkingLevel: this.thinkingLevel };
|
|
193
258
|
if (this.agent.streamFunction === streamSimple) {
|
|
194
|
-
return this._getRequiredRequestAuth(model);
|
|
259
|
+
return { ...(await this._getRequiredRequestAuth(model, signal)), thinkingLevel };
|
|
195
260
|
}
|
|
196
261
|
try {
|
|
197
|
-
const result = await this._modelRuntime.getAuth(model);
|
|
262
|
+
const result = await this._modelRuntime.getAuth(model, { signal });
|
|
198
263
|
if (!result)
|
|
199
|
-
return { model };
|
|
264
|
+
return { model, thinkingLevel };
|
|
200
265
|
const requestModel = result.auth.baseUrl ? { ...model, baseUrl: result.auth.baseUrl } : model;
|
|
201
266
|
return {
|
|
202
267
|
model: requestModel,
|
|
203
268
|
apiKey: result.auth.apiKey,
|
|
204
269
|
headers: withoutDeletedHeaders(result.auth.headers),
|
|
205
270
|
env: result.env,
|
|
271
|
+
thinkingLevel,
|
|
206
272
|
};
|
|
207
273
|
}
|
|
208
|
-
catch {
|
|
209
|
-
|
|
274
|
+
catch (error) {
|
|
275
|
+
if (signal?.aborted)
|
|
276
|
+
throw error;
|
|
277
|
+
return { model, thinkingLevel };
|
|
210
278
|
}
|
|
211
279
|
}
|
|
280
|
+
/**
|
|
281
|
+
* The model whose limits apply to `message`, or undefined when the message came from another
|
|
282
|
+
* model. Under a virtual selection, that is the physical model that produced it.
|
|
283
|
+
*/
|
|
284
|
+
_modelForMessage(message) {
|
|
285
|
+
const model = this.model;
|
|
286
|
+
if (model && isVirtualModel(model))
|
|
287
|
+
return this._modelRuntime.getPhysicalModel(message.provider, message.model);
|
|
288
|
+
return model?.provider === message.provider && model.id === message.model ? model : undefined;
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Record the selection on the current branch when the branch implies another one, so a resume
|
|
292
|
+
* restores it. Tree navigation can leave the latest `model_change` on another branch; responses
|
|
293
|
+
* cannot record a virtual selection because they name physical models. Responses do record a
|
|
294
|
+
* physical selection unless the branch holds a virtual one; checking a physical selection against
|
|
295
|
+
* responses would record it on every prompt while `prepareRequest` redirects to another model.
|
|
296
|
+
*/
|
|
297
|
+
_recordSelection() {
|
|
298
|
+
const model = this.model;
|
|
299
|
+
if (!model)
|
|
300
|
+
return;
|
|
301
|
+
const getModel = (provider, modelId) => this._modelRuntime.getModel(provider, modelId);
|
|
302
|
+
const recorded = getBranchSelection(this.sessionManager.getBranch(), getModel);
|
|
303
|
+
if (!recorded || (recorded.provider === model.provider && recorded.modelId === model.id))
|
|
304
|
+
return;
|
|
305
|
+
const recordedModel = getModel(recorded.provider, recorded.modelId);
|
|
306
|
+
if (!isVirtualModel(model) && !(recordedModel && isVirtualModel(recordedModel)))
|
|
307
|
+
return;
|
|
308
|
+
this.sessionManager.appendModelChange(model.provider, model.id);
|
|
309
|
+
}
|
|
310
|
+
/** The model whose limits apply to the conversation. */
|
|
311
|
+
_limitsModel() {
|
|
312
|
+
return this.routedModel?.model ?? this.model;
|
|
313
|
+
}
|
|
212
314
|
/**
|
|
213
315
|
* Install tool hooks once on the Agent instance.
|
|
214
316
|
*
|
|
@@ -218,68 +320,216 @@ export class AgentSession {
|
|
|
218
320
|
* happens here instead of in wrappers.
|
|
219
321
|
*/
|
|
220
322
|
_installAgentToolHooks() {
|
|
221
|
-
this.agent.beforeToolCall =
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
}
|
|
238
|
-
throw new Error(`Extension failed, blocking execution: ${String(err)}`);
|
|
239
|
-
}
|
|
240
|
-
};
|
|
241
|
-
this.agent.afterToolCall = async ({ toolCall, args, result, isError }) => {
|
|
242
|
-
const runner = this._extensionRunner;
|
|
243
|
-
const hookResult = runner.hasHandlers("tool_result")
|
|
244
|
-
? await runner.emitToolResult({
|
|
245
|
-
type: "tool_result",
|
|
246
|
-
toolName: toolCall.name,
|
|
247
|
-
toolCallId: toolCall.id,
|
|
248
|
-
input: args,
|
|
249
|
-
content: result.content,
|
|
250
|
-
details: result.details,
|
|
251
|
-
isError,
|
|
252
|
-
usage: result.usage,
|
|
253
|
-
})
|
|
254
|
-
: undefined;
|
|
255
|
-
const content = hookResult?.content ?? result.content ?? [];
|
|
256
|
-
// Runs after the extension hook so images injected or replaced by extensions are normalized too.
|
|
257
|
-
const normalizedContent = await normalizeToolResultImages(content, {
|
|
258
|
-
autoResizeImages: this.settingsManager.getImageAutoResize(),
|
|
323
|
+
this.agent.beforeToolCall = (context) => this._beforeToolCall(context);
|
|
324
|
+
this.agent.afterToolCall = (context) => this._afterToolCall(context);
|
|
325
|
+
}
|
|
326
|
+
/** `tool_call` handlers. `parentToolCallId` is set for calls another tool made. */
|
|
327
|
+
async _beforeToolCall({ toolCall, args }, parentToolCallId) {
|
|
328
|
+
const runner = this._extensionRunner;
|
|
329
|
+
if (!runner.hasHandlers("tool_call")) {
|
|
330
|
+
return undefined;
|
|
331
|
+
}
|
|
332
|
+
try {
|
|
333
|
+
return await runner.emitToolCall({
|
|
334
|
+
type: "tool_call",
|
|
335
|
+
toolName: toolCall.name,
|
|
336
|
+
toolCallId: toolCall.id,
|
|
337
|
+
...(parentToolCallId ? { parentToolCallId } : {}),
|
|
338
|
+
input: args,
|
|
259
339
|
});
|
|
260
|
-
|
|
261
|
-
|
|
340
|
+
}
|
|
341
|
+
catch (err) {
|
|
342
|
+
if (err instanceof Error) {
|
|
343
|
+
throw err;
|
|
262
344
|
}
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
345
|
+
throw new Error(`Extension failed, blocking execution: ${String(err)}`);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
/** `tool_result` handlers and image normalization. `parentToolCallId` is set for calls another tool made. */
|
|
349
|
+
async _afterToolCall({ toolCall, args, result, isError }, parentToolCallId) {
|
|
350
|
+
const runner = this._extensionRunner;
|
|
351
|
+
const hookResult = runner.hasHandlers("tool_result")
|
|
352
|
+
? await runner.emitToolResult({
|
|
353
|
+
type: "tool_result",
|
|
354
|
+
toolName: toolCall.name,
|
|
355
|
+
toolCallId: toolCall.id,
|
|
356
|
+
...(parentToolCallId ? { parentToolCallId } : {}),
|
|
357
|
+
input: args,
|
|
358
|
+
content: result.content,
|
|
359
|
+
details: result.details,
|
|
360
|
+
...(result.structuredContent === undefined ? {} : { structuredContent: result.structuredContent }),
|
|
361
|
+
isError,
|
|
362
|
+
usage: result.usage,
|
|
363
|
+
})
|
|
364
|
+
: undefined;
|
|
365
|
+
const content = hookResult?.content ?? result.content ?? [];
|
|
366
|
+
// Runs after the extension hook so images injected or replaced by extensions are normalized too.
|
|
367
|
+
const resizeOptions = this._limitsModel()?.inputLimits?.images?.resize;
|
|
368
|
+
const normalizedContent = await normalizeToolResultImages(content, {
|
|
369
|
+
autoResizeImages: this.settingsManager.getImageAutoResize(),
|
|
370
|
+
...(resizeOptions ? { resizeOptions } : {}),
|
|
371
|
+
});
|
|
372
|
+
if (!hookResult && normalizedContent === content) {
|
|
373
|
+
return undefined;
|
|
374
|
+
}
|
|
375
|
+
// The hook result already dropped structured content that replaced content no longer matches.
|
|
376
|
+
return {
|
|
377
|
+
content: normalizedContent,
|
|
378
|
+
details: hookResult?.details,
|
|
379
|
+
structuredContent: hookResult ? hookResult.structuredContent : result.structuredContent,
|
|
380
|
+
isError: hookResult?.isError ?? isError,
|
|
381
|
+
usage: hookResult?.usage,
|
|
269
382
|
};
|
|
270
383
|
}
|
|
384
|
+
/**
|
|
385
|
+
* Run a call that the tool call `parentToolCallId` made through `ctx.executeTool()`. It goes
|
|
386
|
+
* through the agent's tool pipeline with the session's hooks, against the callable tools.
|
|
387
|
+
*/
|
|
388
|
+
async _executeNestedToolCall(parentToolCallId, name, args, options) {
|
|
389
|
+
this._nestedToolCalls ??= new NestedToolCallRunner({
|
|
390
|
+
getTools: () => this._getCallableTools(),
|
|
391
|
+
isSequential: () => this.agent.toolExecution === "sequential",
|
|
392
|
+
runToolCall: (toolCall, parentId, signal, onUpdate) => {
|
|
393
|
+
const assistantMessage = this._findLastAssistantMessage();
|
|
394
|
+
if (!assistantMessage) {
|
|
395
|
+
return Promise.resolve({
|
|
396
|
+
toolCall,
|
|
397
|
+
result: { content: [{ type: "text", text: "No assistant message issued this call" }], details: {} },
|
|
398
|
+
isError: true,
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
return runToolCall(toolCall, {
|
|
402
|
+
tools: this._getCallableTools(),
|
|
403
|
+
assistantMessage,
|
|
404
|
+
context: { messages: this.agent.state.messages, tools: this.agent.state.tools },
|
|
405
|
+
beforeToolCall: (context) => this._beforeToolCall(context, parentId),
|
|
406
|
+
afterToolCall: (context) => this._afterToolCall(context, parentId),
|
|
407
|
+
signal,
|
|
408
|
+
onUpdate,
|
|
409
|
+
});
|
|
410
|
+
},
|
|
411
|
+
emit: async (event) => {
|
|
412
|
+
await this._extensionRunner.emit(event);
|
|
413
|
+
this._emit(event);
|
|
414
|
+
},
|
|
415
|
+
});
|
|
416
|
+
return this._nestedToolCalls.execute(parentToolCallId, name, args, options);
|
|
417
|
+
}
|
|
418
|
+
/** Whether `projection`, the current session projection, exceeds the compaction threshold of `model`. */
|
|
419
|
+
_exceedsCompactionThreshold(model, projection) {
|
|
420
|
+
if (model.contextWindow <= 0)
|
|
421
|
+
return false;
|
|
422
|
+
return shouldCompact(estimateProjectedContextTokens(projection, this.sessionManager.getBranch()).tokens, model.contextWindow, this.settingsManager.getCompactionSettings(this.model));
|
|
423
|
+
}
|
|
271
424
|
async _compactBeforeNextAssistantResponse(context) {
|
|
425
|
+
const projection = this.sessionManager.buildSessionProjection();
|
|
426
|
+
// A virtual selection is checked in prepareRequest, against the model the request is routed to.
|
|
272
427
|
const model = this.model;
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
model.contextWindow <= 0 ||
|
|
276
|
-
!shouldCompact(estimateContextTokens(context.messages).tokens, model.contextWindow, settings)) {
|
|
277
|
-
return context;
|
|
428
|
+
if (!model || isVirtualModel(model) || !this._exceedsCompactionThreshold(model, projection)) {
|
|
429
|
+
return { ...context, messages: projection.messages };
|
|
278
430
|
}
|
|
279
431
|
await this._runAutoCompaction("threshold", false);
|
|
280
|
-
return {
|
|
281
|
-
|
|
282
|
-
|
|
432
|
+
return { ...context, messages: this.sessionManager.buildSessionProjection().messages };
|
|
433
|
+
}
|
|
434
|
+
_installAgentRequestProjection() {
|
|
435
|
+
const previousPrepareRequest = this.agent.prepareRequest;
|
|
436
|
+
this.agent.prepareRequest = async (request, signal) => {
|
|
437
|
+
const failed = this._failedResponse;
|
|
438
|
+
this._failedResponse = undefined;
|
|
439
|
+
const prepare = async () => {
|
|
440
|
+
const projection = this.sessionManager.buildSessionProjection();
|
|
441
|
+
const canonicalContext = {
|
|
442
|
+
...request.context,
|
|
443
|
+
messages: projection.messages,
|
|
444
|
+
// Messages declare the provider-visible loadout; context.tools keeps executable implementations.
|
|
445
|
+
tools: this.agent.state.tools.slice(),
|
|
446
|
+
};
|
|
447
|
+
const previous = await previousPrepareRequest?.({
|
|
448
|
+
...request,
|
|
449
|
+
context: canonicalContext,
|
|
450
|
+
model: this.agent.state.model,
|
|
451
|
+
thinkingLevel: this.agent.state.thinkingLevel,
|
|
452
|
+
}, signal);
|
|
453
|
+
return { previous, context: previous?.context ?? canonicalContext, projection };
|
|
454
|
+
};
|
|
455
|
+
let { previous, context, projection } = await prepare();
|
|
456
|
+
const model = previous?.model ?? this.agent.state.model;
|
|
457
|
+
const thinkingLevel = previous?.thinkingLevel ?? this.agent.state.thinkingLevel;
|
|
458
|
+
if (!isVirtualModel(model))
|
|
459
|
+
return { ...previous, context, model, thinkingLevel };
|
|
460
|
+
// The selection stays in agent state; only this request uses the routed model. A routing
|
|
461
|
+
// failure rejects, which ends the run with an error response. Only messages the user wrote
|
|
462
|
+
// start a turn; extension messages can follow them, e.g. from before_agent_start.
|
|
463
|
+
const lastResponse = context.messages.findLastIndex((message) => message.role === "assistant");
|
|
464
|
+
const userTurn = context.messages.slice(lastResponse + 1).some((message) => message.role === "user");
|
|
465
|
+
const state = getVirtualModelState(this.sessionManager.getBranch(), model.provider, model.id);
|
|
466
|
+
const route = await this._modelRuntime.resolveModel(model, convertToLlm(context.messages), {
|
|
467
|
+
reason: failed ? "retry" : userTurn ? "user" : "continuation",
|
|
468
|
+
thinkingLevel,
|
|
469
|
+
signal,
|
|
470
|
+
failed,
|
|
471
|
+
state,
|
|
472
|
+
});
|
|
473
|
+
if (route.state !== undefined && route.state !== state) {
|
|
474
|
+
const data = { provider: model.provider, modelId: model.id, state: route.state };
|
|
475
|
+
const entry = this.sessionManager.getEntry(this.sessionManager.appendCustomEntry(VIRTUAL_MODEL_STATE_ENTRY, data));
|
|
476
|
+
if (entry)
|
|
477
|
+
this._emit({ type: "entry_appended", entry });
|
|
478
|
+
}
|
|
479
|
+
// The route stands: the router already decided this request. The state entry does not change
|
|
480
|
+
// the projection.
|
|
481
|
+
if (this._exceedsCompactionThreshold(route.model, projection)) {
|
|
482
|
+
await this._runAutoCompaction("threshold", false);
|
|
483
|
+
({ previous, context } = await prepare());
|
|
484
|
+
}
|
|
485
|
+
return { ...previous, context, model: route.model, thinkingLevel: route.thinkingLevel };
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
async _dispatchTurnEndBoundary(message, toolResults) {
|
|
489
|
+
this._lastActivityOutcome =
|
|
490
|
+
message.stopReason === "aborted" ? "aborted" : message.stopReason === "error" ? "error" : "completed";
|
|
491
|
+
const messageEntryId = this._findPersistedMessageEntryId(message);
|
|
492
|
+
if (!this._extensionRunner.hasHandlers("turn_end"))
|
|
493
|
+
return false;
|
|
494
|
+
if (!messageEntryId) {
|
|
495
|
+
this._extensionRunner.emitError({
|
|
496
|
+
extensionPath: "<boundary>",
|
|
497
|
+
event: "turn_end",
|
|
498
|
+
error: "turn_end could not resolve the persisted assistant entry ID",
|
|
499
|
+
});
|
|
500
|
+
return false;
|
|
501
|
+
}
|
|
502
|
+
const toolResultEntryIds = toolResults.flatMap((result) => {
|
|
503
|
+
const entryId = this._findPersistedMessageEntryId(result);
|
|
504
|
+
return entryId ? [entryId] : [];
|
|
505
|
+
});
|
|
506
|
+
const boundary = await this._extensionRunner.emitBoundary({
|
|
507
|
+
type: "turn_end",
|
|
508
|
+
turnIndex: this._turnIndex,
|
|
509
|
+
message,
|
|
510
|
+
toolResults,
|
|
511
|
+
messageEntryId,
|
|
512
|
+
toolResultEntryIds,
|
|
513
|
+
outcome: this._lastActivityOutcome,
|
|
514
|
+
}, (entries) => this._buildBoundaryContext(entries, "turn_end"));
|
|
515
|
+
this._commitBoundaryDrafts(boundary.entries);
|
|
516
|
+
if (boundary.continue && !this._buildBoundaryContext([], "turn_end").canContinue) {
|
|
517
|
+
this._reportInvalidBoundaryContinuation("turn_end");
|
|
518
|
+
return false;
|
|
519
|
+
}
|
|
520
|
+
return boundary.continue;
|
|
521
|
+
}
|
|
522
|
+
_installAgentBoundaryHooks() {
|
|
523
|
+
const previousFinishTurn = this.agent.finishTurn;
|
|
524
|
+
this.agent.finishTurn = async (turn, signal) => {
|
|
525
|
+
this._boundaryDispatchedMessages.add(turn.message);
|
|
526
|
+
const extensionContinue = await this._dispatchTurnEndBoundary(turn.message, turn.toolResults);
|
|
527
|
+
const previousDecision = await previousFinishTurn?.(turn, signal);
|
|
528
|
+
if (previousDecision?.action === "end")
|
|
529
|
+
return previousDecision;
|
|
530
|
+
if (extensionContinue || previousDecision?.action === "continue")
|
|
531
|
+
return { action: "continue" };
|
|
532
|
+
return undefined;
|
|
283
533
|
};
|
|
284
534
|
}
|
|
285
535
|
_installAgentNextTurnRefresh() {
|
|
@@ -291,13 +541,25 @@ export class AgentSession {
|
|
|
291
541
|
const context = await this._compactBeforeNextAssistantResponse(turn.context);
|
|
292
542
|
const previousSnapshot = await previousPrepareNextTurnWithContext?.({ ...turn, context }, signal);
|
|
293
543
|
const nextContext = previousSnapshot?.context ?? context;
|
|
544
|
+
const runOptions = this._runSystemPromptOptions ?? this._baseSystemPromptOptions;
|
|
545
|
+
const options = normalizeBuildSystemPromptOptions({
|
|
546
|
+
...runOptions,
|
|
547
|
+
selectedTools: this.getActiveToolNames(),
|
|
548
|
+
toolSnippets: { ...this._baseSystemPromptOptions.toolSnippets, ...runOptions.toolSnippets },
|
|
549
|
+
toolGuidelines: { ...this._baseSystemPromptOptions.toolGuidelines, ...runOptions.toolGuidelines },
|
|
550
|
+
});
|
|
551
|
+
const updateMessage = this._preparePromptAndToolLoadout(options, nextContext.messages);
|
|
552
|
+
// Keep session.systemPrompt and ctx.getSystemPrompt() in step with what the provider sees.
|
|
553
|
+
this._runSystemPromptOptions = options;
|
|
294
554
|
return {
|
|
295
555
|
...previousSnapshot,
|
|
296
556
|
context: {
|
|
297
557
|
...nextContext,
|
|
298
|
-
systemPrompt: this._systemPromptOverride ?? this._baseSystemPrompt,
|
|
299
558
|
tools: this.agent.state.tools.slice(),
|
|
300
559
|
},
|
|
560
|
+
messages: updateMessage
|
|
561
|
+
? [...(previousSnapshot?.messages ?? []), updateMessage]
|
|
562
|
+
: previousSnapshot?.messages,
|
|
301
563
|
model: this.agent.state.model,
|
|
302
564
|
thinkingLevel: this.agent.state.thinkingLevel,
|
|
303
565
|
};
|
|
@@ -306,6 +568,84 @@ export class AgentSession {
|
|
|
306
568
|
// =========================================================================
|
|
307
569
|
// Event Subscription
|
|
308
570
|
// =========================================================================
|
|
571
|
+
_refreshFinalizedContext() {
|
|
572
|
+
const projection = this.sessionManager.buildSessionProjection();
|
|
573
|
+
for (const entry of projection.entries) {
|
|
574
|
+
for (const message of entry.messages)
|
|
575
|
+
this._entryIdsByMessage.set(message, entry.sourceEntry.id);
|
|
576
|
+
}
|
|
577
|
+
this.agent.state.messages = projection.messages;
|
|
578
|
+
}
|
|
579
|
+
_applyBoundaryDrafts(manager, drafts) {
|
|
580
|
+
const appended = [];
|
|
581
|
+
for (const draft of drafts) {
|
|
582
|
+
let entryId;
|
|
583
|
+
switch (draft.type) {
|
|
584
|
+
case "custom":
|
|
585
|
+
entryId = manager.appendCustomEntry(draft.customType, draft.data);
|
|
586
|
+
break;
|
|
587
|
+
case "custom_message":
|
|
588
|
+
entryId = manager.appendCustomMessageEntry(draft.customType, draft.content, draft.display, draft.details);
|
|
589
|
+
break;
|
|
590
|
+
case "context_edit":
|
|
591
|
+
entryId = manager.appendContextEdit(draft.targetId, draft.replacement);
|
|
592
|
+
break;
|
|
593
|
+
case "compaction": {
|
|
594
|
+
const tokensBefore = estimateProjectedContextTokens(manager.buildSessionProjection(), manager.getBranch()).tokens;
|
|
595
|
+
entryId = manager.appendCompaction(draft.summary, draft.firstKeptEntryId, tokensBefore, draft.details, true, draft.usage);
|
|
596
|
+
break;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
const entry = manager.getEntry(entryId);
|
|
600
|
+
if (entry)
|
|
601
|
+
appended.push(entry);
|
|
602
|
+
}
|
|
603
|
+
return appended;
|
|
604
|
+
}
|
|
605
|
+
_createBoundaryPreviewManager(drafts) {
|
|
606
|
+
const header = this.sessionManager.getHeader();
|
|
607
|
+
if (!header)
|
|
608
|
+
throw new Error("Session header is missing");
|
|
609
|
+
const manager = SessionManager.inMemory(this._cwd, undefined, [header, ...this.sessionManager.getBranch()]);
|
|
610
|
+
this._applyBoundaryDrafts(manager, drafts);
|
|
611
|
+
return manager;
|
|
612
|
+
}
|
|
613
|
+
_getPendingBoundaryMessages() {
|
|
614
|
+
return [...this.agent.peekQueuedMessages(), ...this._pendingCustomMessages];
|
|
615
|
+
}
|
|
616
|
+
_buildBoundaryContext(drafts, boundary) {
|
|
617
|
+
const projection = this._createBoundaryPreviewManager(drafts).buildSessionProjection();
|
|
618
|
+
const pendingMessages = this._getPendingBoundaryMessages();
|
|
619
|
+
const llmMessages = convertToLlm(projection.messages);
|
|
620
|
+
const finalRole = llmMessages[llmMessages.length - 1]?.role;
|
|
621
|
+
const hasNonSystemContext = llmMessages.some((message) => message.role !== "system");
|
|
622
|
+
const contextCanContinue = hasNonSystemContext && finalRole !== "assistant";
|
|
623
|
+
const pendingCustomContext = this._pendingCustomMessages.length > 0;
|
|
624
|
+
return {
|
|
625
|
+
contextEntries: projection.entries,
|
|
626
|
+
contextMessages: projection.messages,
|
|
627
|
+
llmMessages,
|
|
628
|
+
pendingMessages,
|
|
629
|
+
canContinue: contextCanContinue ||
|
|
630
|
+
pendingCustomContext ||
|
|
631
|
+
(boundary === "turn_end"
|
|
632
|
+
? this.agent.hasQueuedMessages()
|
|
633
|
+
: finalRole === "assistant" && this.agent.hasQueuedMessages()),
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
_commitBoundaryDrafts(drafts) {
|
|
637
|
+
const appended = this._applyBoundaryDrafts(this.sessionManager, drafts);
|
|
638
|
+
this._refreshFinalizedContext();
|
|
639
|
+
for (const entry of appended)
|
|
640
|
+
this._emit({ type: "entry_appended", entry });
|
|
641
|
+
}
|
|
642
|
+
_reportInvalidBoundaryContinuation(event) {
|
|
643
|
+
this._extensionRunner.emitError({
|
|
644
|
+
extensionPath: "<boundary>",
|
|
645
|
+
event,
|
|
646
|
+
error: `${event} requested continuation without runnable model context`,
|
|
647
|
+
});
|
|
648
|
+
}
|
|
309
649
|
/** Emit an event to all listeners */
|
|
310
650
|
_emit(event) {
|
|
311
651
|
for (const l of this._eventListeners) {
|
|
@@ -342,19 +682,51 @@ export class AgentSession {
|
|
|
342
682
|
resolve();
|
|
343
683
|
}
|
|
344
684
|
async _emitAgentSettled() {
|
|
685
|
+
this._cacheWarmer?.onAgentSettled();
|
|
345
686
|
this._isAgentRunActive = false;
|
|
687
|
+
this._isEmittingAgentSettled = true;
|
|
346
688
|
try {
|
|
347
|
-
|
|
348
|
-
this.
|
|
689
|
+
const aborted = this._agentRunAbortRequested;
|
|
690
|
+
await this._extensionRunner.emit({ type: "agent_settled", aborted });
|
|
691
|
+
this._emit({ type: "agent_settled", aborted });
|
|
349
692
|
}
|
|
350
693
|
finally {
|
|
351
|
-
this.
|
|
694
|
+
this._isEmittingAgentSettled = false;
|
|
352
695
|
}
|
|
696
|
+
const deferred = this._deferredSettledActions.splice(0);
|
|
697
|
+
if (deferred.length > 0) {
|
|
698
|
+
try {
|
|
699
|
+
for (const action of deferred)
|
|
700
|
+
await action();
|
|
701
|
+
}
|
|
702
|
+
finally {
|
|
703
|
+
this._resolveIdleWaitIfIdle();
|
|
704
|
+
}
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
707
|
+
this._resolveIdleWaitIfIdle();
|
|
353
708
|
}
|
|
354
|
-
// Track last assistant message for auto-compaction check
|
|
355
|
-
_lastAssistantMessage = undefined;
|
|
356
709
|
/** Internal handler for agent events - shared by subscribe and reconnect */
|
|
357
710
|
_handleAgentEvent = async (event) => {
|
|
711
|
+
// An abort requested while the run was starting, e.g. during before_agent_start, stops it
|
|
712
|
+
// here. agent_start is awaited before the first request.
|
|
713
|
+
if (event.type === "agent_start" && this._agentRunAbortRequested)
|
|
714
|
+
this.agent.abort();
|
|
715
|
+
// Record the calls a tool made through ctx.executeTool() and their usage on its result message.
|
|
716
|
+
if (this._nestedToolCalls) {
|
|
717
|
+
if (event.type === "message_start" && event.message.role === "toolResult") {
|
|
718
|
+
const message = event.message;
|
|
719
|
+
const summary = this._nestedToolCalls.takeRecord(message.toolCallId);
|
|
720
|
+
if (summary?.calls)
|
|
721
|
+
message.nestedCalls = summary.calls;
|
|
722
|
+
if (summary?.usage) {
|
|
723
|
+
message.usage = message.usage ? combineUsage(message.usage, summary.usage) : summary.usage;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
else if (event.type === "agent_end") {
|
|
727
|
+
this._nestedToolCalls.clear();
|
|
728
|
+
}
|
|
729
|
+
}
|
|
358
730
|
// When a user message starts, check if it's from either queue and remove it BEFORE emitting
|
|
359
731
|
// This ensures the UI sees the updated queue state
|
|
360
732
|
if (event.type === "message_start" && event.message.role === "user") {
|
|
@@ -377,28 +749,30 @@ export class AgentSession {
|
|
|
377
749
|
}
|
|
378
750
|
}
|
|
379
751
|
}
|
|
380
|
-
// Emit to extensions first
|
|
752
|
+
// Emit to extensions first, then notify public listeners.
|
|
381
753
|
await this._emitExtensionEvent(event);
|
|
382
|
-
// Notify all listeners
|
|
383
754
|
this._emit(event.type === "agent_end" ? { ...event, willRetry: this._willRetryAfterAgentEnd(event) } : event);
|
|
384
755
|
// Handle session persistence
|
|
385
756
|
if (event.type === "message_end") {
|
|
757
|
+
let entryId;
|
|
386
758
|
// Check if this is a custom message from extensions
|
|
387
759
|
if (event.message.role === "custom") {
|
|
388
760
|
// Persist as CustomMessageEntry
|
|
389
|
-
this.sessionManager.appendCustomMessageEntry(event.message.customType, event.message.content, event.message.display, event.message.details);
|
|
761
|
+
entryId = this.sessionManager.appendCustomMessageEntry(event.message.customType, event.message.content, event.message.display, event.message.details);
|
|
390
762
|
}
|
|
391
|
-
else if (event.message.role === "
|
|
763
|
+
else if (event.message.role === "system" ||
|
|
764
|
+
event.message.role === "user" ||
|
|
392
765
|
event.message.role === "assistant" ||
|
|
393
766
|
event.message.role === "toolResult") {
|
|
394
767
|
// Regular LLM message - persist as SessionMessageEntry
|
|
395
|
-
this.sessionManager.appendMessage(event.message);
|
|
768
|
+
entryId = this.sessionManager.appendMessage(event.message);
|
|
396
769
|
}
|
|
770
|
+
if (entryId)
|
|
771
|
+
this._entryIdsByMessage.set(event.message, entryId);
|
|
397
772
|
// Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
|
|
398
|
-
// Track assistant message for auto-compaction (checked on agent_end)
|
|
399
773
|
if (event.message.role === "assistant") {
|
|
400
|
-
this._lastAssistantMessage = event.message;
|
|
401
774
|
const assistantMsg = event.message;
|
|
775
|
+
this._lastAssistantMessage = assistantMsg;
|
|
402
776
|
if (assistantMsg.stopReason !== "error" && assistantMsg.stopReason !== "length") {
|
|
403
777
|
this._overflowRecoveryAttempted = false;
|
|
404
778
|
}
|
|
@@ -420,10 +794,13 @@ export class AgentSession {
|
|
|
420
794
|
// extension and listener dispatch above also picks up messages that turn_end
|
|
421
795
|
// handlers queued.
|
|
422
796
|
if (event.type === "turn_end") {
|
|
797
|
+
this._lastAssistantToolResults = event.toolResults;
|
|
423
798
|
this._flushPendingCustomMessages();
|
|
424
799
|
}
|
|
425
800
|
};
|
|
426
801
|
_willRetryAfterAgentEnd(event) {
|
|
802
|
+
if (this._agentRunAbortRequested)
|
|
803
|
+
return false;
|
|
427
804
|
const settings = this.settingsManager.getRetrySettings();
|
|
428
805
|
if (!settings.enabled || this._retryAttempt >= settings.maxRetries) {
|
|
429
806
|
return false;
|
|
@@ -436,6 +813,47 @@ export class AgentSession {
|
|
|
436
813
|
}
|
|
437
814
|
return false;
|
|
438
815
|
}
|
|
816
|
+
_findPersistedMessageEntryId(message) {
|
|
817
|
+
const mapped = this._entryIdsByMessage.get(message);
|
|
818
|
+
if (mapped)
|
|
819
|
+
return mapped;
|
|
820
|
+
for (const entry of [...this.sessionManager.getBranch()].reverse()) {
|
|
821
|
+
if (entry.type === "message" && entry.message === message)
|
|
822
|
+
return entry.id;
|
|
823
|
+
}
|
|
824
|
+
const messageIndex = this.agent.state.messages.indexOf(message);
|
|
825
|
+
if (messageIndex < 0)
|
|
826
|
+
return undefined;
|
|
827
|
+
const projection = this.sessionManager.buildSessionProjection();
|
|
828
|
+
let projectedIndex = 0;
|
|
829
|
+
for (const entry of projection.entries) {
|
|
830
|
+
for (let i = 0; i < entry.messages.length; i++) {
|
|
831
|
+
if (projectedIndex === messageIndex) {
|
|
832
|
+
this._entryIdsByMessage.set(message, entry.sourceEntry.id);
|
|
833
|
+
return entry.sourceEntry.id;
|
|
834
|
+
}
|
|
835
|
+
projectedIndex++;
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
return undefined;
|
|
839
|
+
}
|
|
840
|
+
_omitRecoveryAttempt(message, toolResults = []) {
|
|
841
|
+
const targets = [message, ...toolResults];
|
|
842
|
+
const targetIds = targets.map((target) => this._findPersistedMessageEntryId(target));
|
|
843
|
+
const unresolvedProjectedTarget = targets.some((target, index) => targetIds[index] === undefined && this.agent.state.messages.includes(target));
|
|
844
|
+
if (unresolvedProjectedTarget) {
|
|
845
|
+
throw new Error("Cannot persist recovery omission because a projected message has no source entry");
|
|
846
|
+
}
|
|
847
|
+
for (const targetId of targetIds) {
|
|
848
|
+
if (!targetId)
|
|
849
|
+
continue;
|
|
850
|
+
const editId = this.sessionManager.appendContextEdit(targetId, null);
|
|
851
|
+
const entry = this.sessionManager.getEntry(editId);
|
|
852
|
+
if (entry)
|
|
853
|
+
this._emit({ type: "entry_appended", entry });
|
|
854
|
+
}
|
|
855
|
+
this._refreshFinalizedContext();
|
|
856
|
+
}
|
|
439
857
|
/** Find the last assistant message in agent state (including aborted ones) */
|
|
440
858
|
_findLastAssistantMessage() {
|
|
441
859
|
const messages = this.agent.state.messages;
|
|
@@ -479,13 +897,9 @@ export class AgentSession {
|
|
|
479
897
|
await this._extensionRunner.emit(extensionEvent);
|
|
480
898
|
}
|
|
481
899
|
else if (event.type === "turn_end") {
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
message: event.message,
|
|
486
|
-
toolResults: event.toolResults,
|
|
487
|
-
};
|
|
488
|
-
await this._extensionRunner.emit(extensionEvent);
|
|
900
|
+
if (event.message.role === "assistant" && !this._boundaryDispatchedMessages.delete(event.message)) {
|
|
901
|
+
await this._dispatchTurnEndBoundary(event.message, event.toolResults);
|
|
902
|
+
}
|
|
489
903
|
this._turnIndex++;
|
|
490
904
|
}
|
|
491
905
|
else if (event.type === "message_start") {
|
|
@@ -548,6 +962,7 @@ export class AgentSession {
|
|
|
548
962
|
toolName: event.toolName,
|
|
549
963
|
result: event.result,
|
|
550
964
|
isError: event.isError,
|
|
965
|
+
...(event.durationMs === undefined ? {} : { durationMs: event.durationMs }),
|
|
551
966
|
};
|
|
552
967
|
await this._extensionRunner.emit(extensionEvent);
|
|
553
968
|
}
|
|
@@ -592,15 +1007,32 @@ export class AgentSession {
|
|
|
592
1007
|
this._extensionRunner.invalidate("This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().");
|
|
593
1008
|
this._disconnectFromAgent();
|
|
594
1009
|
this._eventListeners = [];
|
|
1010
|
+
if (this._cacheWarmer) {
|
|
1011
|
+
this._cacheWarmer.onWarmed = undefined;
|
|
1012
|
+
this._cacheWarmer.cancel();
|
|
1013
|
+
}
|
|
595
1014
|
cleanupSessionResources(this.sessionId);
|
|
596
1015
|
}
|
|
597
1016
|
// =========================================================================
|
|
598
1017
|
// Read-only State Access
|
|
599
1018
|
// =========================================================================
|
|
1019
|
+
/** Refresh the public finalized transcript from the canonical session projection. */
|
|
1020
|
+
refreshContext() {
|
|
1021
|
+
this._refreshFinalizedContext();
|
|
1022
|
+
}
|
|
600
1023
|
/** Full agent state */
|
|
601
1024
|
get state() {
|
|
602
1025
|
return this.agent.state;
|
|
603
1026
|
}
|
|
1027
|
+
/** Current cache-warming state and the policy inputs that produced it. */
|
|
1028
|
+
get cacheWarmingStatus() {
|
|
1029
|
+
return this._cacheWarmer?.status;
|
|
1030
|
+
}
|
|
1031
|
+
/** Persist the cache-warming mode and immediately reconcile active warming. */
|
|
1032
|
+
setCacheWarmingMode(mode) {
|
|
1033
|
+
this.settingsManager.setCacheWarmingMode(mode);
|
|
1034
|
+
this._cacheWarmer?.onModeChanged();
|
|
1035
|
+
}
|
|
604
1036
|
/** Current model (may be undefined if not yet selected) */
|
|
605
1037
|
get model() {
|
|
606
1038
|
return this.agent.state.model;
|
|
@@ -609,6 +1041,14 @@ export class AgentSession {
|
|
|
609
1041
|
get thinkingLevel() {
|
|
610
1042
|
return this.agent.state.thinkingLevel;
|
|
611
1043
|
}
|
|
1044
|
+
/** Under a virtual selection, the physical model and thinking level of the latest successful response. */
|
|
1045
|
+
get routedModel() {
|
|
1046
|
+
if (!this.model || !isVirtualModel(this.model))
|
|
1047
|
+
return undefined;
|
|
1048
|
+
const latest = findLatestResponse(this.agent.state.messages);
|
|
1049
|
+
const model = latest && this._modelRuntime.getPhysicalModel(latest.provider, latest.model);
|
|
1050
|
+
return model && { model, thinkingLevel: latest?.thinkingLevel };
|
|
1051
|
+
}
|
|
612
1052
|
/** Whether the session is currently processing an agent run or post-run continuation. */
|
|
613
1053
|
get isStreaming() {
|
|
614
1054
|
return this._isAgentRunActive;
|
|
@@ -617,21 +1057,25 @@ export class AgentSession {
|
|
|
617
1057
|
get isIdle() {
|
|
618
1058
|
return !this._isAgentRunActive && !this.isCompacting;
|
|
619
1059
|
}
|
|
620
|
-
/** Current effective system prompt
|
|
1060
|
+
/** Current effective system prompt, including changes not yet sent to the model. */
|
|
621
1061
|
get systemPrompt() {
|
|
622
|
-
return this.
|
|
1062
|
+
return buildSystemPrompt(this._runSystemPromptOptions ?? this._baseSystemPromptOptions);
|
|
623
1063
|
}
|
|
624
1064
|
/** Current retry attempt (0 if not retrying) */
|
|
625
1065
|
get retryAttempt() {
|
|
626
1066
|
return this._retryAttempt;
|
|
627
1067
|
}
|
|
628
1068
|
/**
|
|
629
|
-
* Get the names of currently active tools.
|
|
630
|
-
*
|
|
1069
|
+
* Get the names of currently active tools, which are the tools declared to the model.
|
|
1070
|
+
* Tools with `codemode` or `deferred` exposure are callable from other tools without being active.
|
|
631
1071
|
*/
|
|
632
1072
|
getActiveToolNames() {
|
|
633
1073
|
return this.agent.state.tools.map((t) => t.name);
|
|
634
1074
|
}
|
|
1075
|
+
/** Get the names of the tools that tools can call through `ctx.executeTool()`. */
|
|
1076
|
+
getCallableToolNames() {
|
|
1077
|
+
return this._getCallableTools().map((t) => t.name);
|
|
1078
|
+
}
|
|
635
1079
|
/**
|
|
636
1080
|
* Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata.
|
|
637
1081
|
*/
|
|
@@ -641,6 +1085,10 @@ export class AgentSession {
|
|
|
641
1085
|
description: definition.description,
|
|
642
1086
|
parameters: definition.parameters,
|
|
643
1087
|
promptGuidelines: definition.promptGuidelines,
|
|
1088
|
+
exposure: this._getToolExposure(definition.name),
|
|
1089
|
+
...(definition.namespace ? { namespace: definition.namespace } : {}),
|
|
1090
|
+
...(definition.annotations ? { annotations: { ...definition.annotations } } : {}),
|
|
1091
|
+
...(definition.reachesTools ? { reachesTools: definition.reachesTools } : {}),
|
|
644
1092
|
sourceInfo,
|
|
645
1093
|
}));
|
|
646
1094
|
}
|
|
@@ -649,24 +1097,113 @@ export class AgentSession {
|
|
|
649
1097
|
}
|
|
650
1098
|
/**
|
|
651
1099
|
* Set active tools by name.
|
|
652
|
-
* Only tools in the registry can be enabled. Unknown tool names are ignored.
|
|
1100
|
+
* Only tools in the registry can be enabled. Unknown and hidden tool names are ignored.
|
|
653
1101
|
* Also rebuilds the system prompt to reflect the new tool set.
|
|
654
1102
|
* Changes take effect on the next agent turn.
|
|
655
1103
|
*/
|
|
656
1104
|
setActiveToolsByName(toolNames) {
|
|
657
|
-
const
|
|
658
|
-
|
|
659
|
-
|
|
1105
|
+
const previous = this.getActiveToolNames();
|
|
1106
|
+
this._setActiveTools(toolNames);
|
|
1107
|
+
// A loadout that deactivates a tool replaces the restored one, whose pending tools are dropped.
|
|
1108
|
+
// One that only adds tools, like activating tool_search, keeps them.
|
|
1109
|
+
const active = new Set(this.getActiveToolNames());
|
|
1110
|
+
if (previous.some((name) => !active.has(name)))
|
|
1111
|
+
this._pendingToolNames.clear();
|
|
1112
|
+
}
|
|
1113
|
+
_setActiveTools(toolNames) {
|
|
1114
|
+
const tools = this._applyToolLoadout(toolNames);
|
|
1115
|
+
for (const tool of tools)
|
|
1116
|
+
this._pendingToolNames.delete(tool.name);
|
|
1117
|
+
this._rebuildSystemPrompt(tools.map((tool) => tool.name));
|
|
1118
|
+
}
|
|
1119
|
+
/**
|
|
1120
|
+
* Whether `--tools` and `--exclude-tools` keep the tool registered. MCP tools stay registered
|
|
1121
|
+
* unless the allowlist filters them (see `_allowlistFiltersMcp`).
|
|
1122
|
+
*/
|
|
1123
|
+
_isAllowedTool(name) {
|
|
1124
|
+
if (this._excludedTools?.(name))
|
|
1125
|
+
return false;
|
|
1126
|
+
if (!this._allowedTools || this._allowedTools(name))
|
|
1127
|
+
return true;
|
|
1128
|
+
return !this._allowlistFiltersMcp && isMcpToolName(name);
|
|
1129
|
+
}
|
|
1130
|
+
/**
|
|
1131
|
+
* Whether the tool may be active, which declares it to the model. MCP tools the allowlist keeps
|
|
1132
|
+
* without matching them are only for codemode and tool_search: they may be declared only when
|
|
1133
|
+
* tool_search can load them (non-`direct` exposure and tool_search registered). This also applies
|
|
1134
|
+
* to tools restored from the transcript or set by extensions.
|
|
1135
|
+
*/
|
|
1136
|
+
_isActivatable(name) {
|
|
1137
|
+
if (!this._allowedTools || this._allowedTools(name) || !isMcpToolName(name))
|
|
1138
|
+
return true;
|
|
1139
|
+
return this._getToolExposure(name) !== "direct" && this._toolRegistry.has("tool_search");
|
|
1140
|
+
}
|
|
1141
|
+
_getToolExposure(name) {
|
|
1142
|
+
return this._toolDefinitions.get(name)?.definition.exposure ?? "direct";
|
|
1143
|
+
}
|
|
1144
|
+
/**
|
|
1145
|
+
* Tools callable through `ctx.executeTool()`: the active `direct` tools and every registered
|
|
1146
|
+
* `codemode` or `deferred` tool.
|
|
1147
|
+
*/
|
|
1148
|
+
_getCallableTools(active = new Set(this.getActiveToolNames())) {
|
|
1149
|
+
return [...this._toolRegistry.values()].filter((tool) => {
|
|
1150
|
+
const exposure = this._getToolExposure(tool.name);
|
|
1151
|
+
return exposure === "codemode" || exposure === "deferred" || (exposure === "direct" && active.has(tool.name));
|
|
1152
|
+
});
|
|
1153
|
+
}
|
|
1154
|
+
/**
|
|
1155
|
+
* Set the agent's tools for the given active tool names and return them. The active tools are
|
|
1156
|
+
* the registered, non-hidden ones; they are declared to the model. Active tools with a
|
|
1157
|
+
* `prepareLoadout` hook can change the declared descriptions and hide declarations from
|
|
1158
|
+
* requests (see {@link _installHiddenDeclarationsProjection}).
|
|
1159
|
+
*/
|
|
1160
|
+
_applyToolLoadout(toolNames) {
|
|
1161
|
+
const tools = [...new Set(toolNames)].flatMap((name) => {
|
|
660
1162
|
const tool = this._toolRegistry.get(name);
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
1163
|
+
return tool && this._getToolExposure(name) !== "hidden" && this._isActivatable(name) ? [tool] : [];
|
|
1164
|
+
});
|
|
1165
|
+
const hooks = tools.flatMap((tool) => {
|
|
1166
|
+
const entry = this._toolDefinitions.get(tool.name);
|
|
1167
|
+
return entry?.definition.prepareLoadout ? [entry] : [];
|
|
1168
|
+
});
|
|
1169
|
+
const hidden = new Set();
|
|
1170
|
+
let declared = tools;
|
|
1171
|
+
if (hooks.length > 0) {
|
|
1172
|
+
const loadout = {
|
|
1173
|
+
declared: tools,
|
|
1174
|
+
callable: this._getCallableTools(new Set(tools.map((tool) => tool.name))),
|
|
1175
|
+
registered: [...this._toolRegistry.values()],
|
|
1176
|
+
getExposure: (name) => this._getToolExposure(name),
|
|
1177
|
+
getNamespace: (name) => this._toolDefinitions.get(name)?.definition.namespace,
|
|
1178
|
+
getPromptGuidelines: (name) => this._toolPromptGuidelines.get(name) ?? [],
|
|
1179
|
+
};
|
|
1180
|
+
const descriptions = new Map();
|
|
1181
|
+
for (const { definition, sourceInfo } of hooks) {
|
|
1182
|
+
try {
|
|
1183
|
+
const changes = definition.prepareLoadout?.(loadout);
|
|
1184
|
+
for (const [name, description] of Object.entries(changes?.descriptions ?? {})) {
|
|
1185
|
+
descriptions.set(name, description);
|
|
1186
|
+
}
|
|
1187
|
+
for (const name of changes?.hiddenDeclarations ?? [])
|
|
1188
|
+
hidden.add(name);
|
|
1189
|
+
}
|
|
1190
|
+
catch (error) {
|
|
1191
|
+
this._extensionRunner.emitError({
|
|
1192
|
+
extensionPath: sourceInfo.path,
|
|
1193
|
+
event: "prepare_loadout",
|
|
1194
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1195
|
+
stack: error instanceof Error ? error.stack : undefined,
|
|
1196
|
+
});
|
|
1197
|
+
}
|
|
664
1198
|
}
|
|
1199
|
+
declared = tools.map((tool) => {
|
|
1200
|
+
const description = descriptions.get(tool.name);
|
|
1201
|
+
return description === undefined ? tool : { ...tool, description };
|
|
1202
|
+
});
|
|
665
1203
|
}
|
|
666
|
-
this.
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
this.agent.state.systemPrompt = this._systemPromptOverride ?? this._baseSystemPrompt;
|
|
1204
|
+
this._hiddenDeclarations = hidden;
|
|
1205
|
+
this.agent.state.tools = declared;
|
|
1206
|
+
return declared;
|
|
670
1207
|
}
|
|
671
1208
|
/** Whether compaction or branch summarization is currently running */
|
|
672
1209
|
get isCompacting() {
|
|
@@ -735,76 +1272,291 @@ export class AgentSession {
|
|
|
735
1272
|
_rebuildSystemPrompt(toolNames) {
|
|
736
1273
|
const validToolNames = toolNames.filter((name) => this._toolRegistry.has(name));
|
|
737
1274
|
const toolSnippets = {};
|
|
738
|
-
const
|
|
739
|
-
for (const name of validToolNames) {
|
|
1275
|
+
for (const name of this._toolRegistry.keys()) {
|
|
740
1276
|
const snippet = this._toolPromptSnippets.get(name);
|
|
741
|
-
|
|
1277
|
+
// Tools without a snippet are not listed.
|
|
1278
|
+
if (snippet)
|
|
742
1279
|
toolSnippets[name] = snippet;
|
|
743
|
-
}
|
|
744
|
-
const toolGuidelines = this._toolPromptGuidelines.get(name);
|
|
745
|
-
if (toolGuidelines) {
|
|
746
|
-
promptGuidelines.push(...toolGuidelines);
|
|
747
|
-
}
|
|
748
1280
|
}
|
|
749
1281
|
const loaderSystemPrompt = this._resourceLoader.getSystemPrompt();
|
|
750
1282
|
const loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();
|
|
751
|
-
const appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") :
|
|
1283
|
+
const appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : "";
|
|
752
1284
|
const loadedSkills = this._resourceLoader.getSkills().skills;
|
|
753
1285
|
const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
|
|
754
|
-
this._baseSystemPromptOptions = {
|
|
1286
|
+
this._baseSystemPromptOptions = normalizeBuildSystemPromptOptions({
|
|
755
1287
|
cwd: this._cwd,
|
|
756
1288
|
skills: loadedSkills,
|
|
757
1289
|
contextFiles: loadedContextFiles,
|
|
758
1290
|
customPrompt: loaderSystemPrompt,
|
|
759
1291
|
appendSystemPrompt,
|
|
760
1292
|
selectedTools: validToolNames,
|
|
1293
|
+
hiddenTools: [...this._hiddenDeclarations],
|
|
761
1294
|
toolSnippets,
|
|
762
|
-
|
|
1295
|
+
toolGuidelines: Object.fromEntries(this._toolPromptGuidelines),
|
|
1296
|
+
});
|
|
1297
|
+
}
|
|
1298
|
+
/**
|
|
1299
|
+
* Apply a prompt and tool loadout for the next request. Sets the executable tools and
|
|
1300
|
+
* returns a system message patching the prompt sections the model currently has (replayed
|
|
1301
|
+
* from `messages`), or undefined when the prompt is unchanged. Tool changes are declared by
|
|
1302
|
+
* the agent loop before the request.
|
|
1303
|
+
*
|
|
1304
|
+
* A forced prompt does not affect the transcript: the structured sections are still diffed
|
|
1305
|
+
* and persisted, and the forced text is projected onto the request by
|
|
1306
|
+
* {@link _installAgentForcedPromptProjection}.
|
|
1307
|
+
*/
|
|
1308
|
+
_preparePromptAndToolLoadout(options, messages = this.agent.state.messages) {
|
|
1309
|
+
options.selectedTools = this._applyToolLoadout(options.selectedTools).map((tool) => tool.name);
|
|
1310
|
+
// The tool list and rules must match the declarations the request carries.
|
|
1311
|
+
options.hiddenTools = [...this._hiddenDeclarations];
|
|
1312
|
+
const sections = diffSystemPromptSections(getCurrentSystemMessage(messages)?.sections ?? {}, buildSystemPromptSections(options));
|
|
1313
|
+
return sections ? { role: "system", content: "", sections, timestamp: Date.now() } : undefined;
|
|
1314
|
+
}
|
|
1315
|
+
/**
|
|
1316
|
+
* Send a forced prompt as the provider's leading system prompt without recording it.
|
|
1317
|
+
*
|
|
1318
|
+
* A `before_agent_start` handler that returns `systemPrompt` needs that exact text at the
|
|
1319
|
+
* head of the request; a mid-conversation system message would leave the original prompt
|
|
1320
|
+
* in place. The forced text is a rendering of the current prompt, so the transcript keeps
|
|
1321
|
+
* its structured sections and the request is projected instead: the system messages
|
|
1322
|
+
* collapse into one head holding the forced text and the current tools. Runs after the
|
|
1323
|
+
* `context` extension handlers.
|
|
1324
|
+
*/
|
|
1325
|
+
/**
|
|
1326
|
+
* Remove the declarations that `prepareLoadout` hooks hide from every request. The whole
|
|
1327
|
+
* transcript is filtered with the current set, so the projected declarations stay consistent
|
|
1328
|
+
* across requests and only change when the loadout does.
|
|
1329
|
+
*/
|
|
1330
|
+
_installHiddenDeclarationsProjection() {
|
|
1331
|
+
const previousTransformContext = this.agent.transformContext;
|
|
1332
|
+
this.agent.transformContext = async (messages, signal) => {
|
|
1333
|
+
const transformed = previousTransformContext ? await previousTransformContext(messages, signal) : messages;
|
|
1334
|
+
const hidden = this._hiddenDeclarations;
|
|
1335
|
+
if (hidden.size === 0)
|
|
1336
|
+
return transformed;
|
|
1337
|
+
return transformed.map((message) => {
|
|
1338
|
+
if (message.role !== "system" || (!message.toolsAdded && !message.toolsRemoved))
|
|
1339
|
+
return message;
|
|
1340
|
+
const { toolsAdded, toolsRemoved, ...rest } = message;
|
|
1341
|
+
const added = toolsAdded?.filter((tool) => !hidden.has(tool.name)) ?? [];
|
|
1342
|
+
const removed = toolsRemoved?.filter((tool) => !hidden.has(tool.name)) ?? [];
|
|
1343
|
+
return {
|
|
1344
|
+
...rest,
|
|
1345
|
+
...(added.length > 0 ? { toolsAdded: added } : {}),
|
|
1346
|
+
...(removed.length > 0 ? { toolsRemoved: removed } : {}),
|
|
1347
|
+
};
|
|
1348
|
+
});
|
|
1349
|
+
};
|
|
1350
|
+
}
|
|
1351
|
+
_installAgentForcedPromptProjection() {
|
|
1352
|
+
const previousTransformContext = this.agent.transformContext;
|
|
1353
|
+
this.agent.transformContext = async (messages, signal) => {
|
|
1354
|
+
const transformed = previousTransformContext ? await previousTransformContext(messages, signal) : messages;
|
|
1355
|
+
const forced = this._runSystemPromptOptions?.forceSystemPrompt;
|
|
1356
|
+
if (forced === undefined)
|
|
1357
|
+
return transformed;
|
|
1358
|
+
const current = getCurrentSystemMessage(transformed);
|
|
1359
|
+
const head = {
|
|
1360
|
+
role: "system",
|
|
1361
|
+
content: forced,
|
|
1362
|
+
...(current?.toolsAdded ? { toolsAdded: current.toolsAdded } : {}),
|
|
1363
|
+
timestamp: current?.timestamp ?? Date.now(),
|
|
1364
|
+
};
|
|
1365
|
+
return [head, ...transformed.filter((message) => message.role !== "system")];
|
|
763
1366
|
};
|
|
764
|
-
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* Restore the active tool loadout declared by the session transcript, if it declares one.
|
|
1370
|
+
* Tools reachable only from other tools are never declared, but they do not depend on the active
|
|
1371
|
+
* set, so the transcript's declarations are the whole loadout.
|
|
1372
|
+
* @param modifiers `+name`/`-name` entries applied to the restored loadout.
|
|
1373
|
+
*/
|
|
1374
|
+
_restoreToolsFromTranscript(modifiers = []) {
|
|
1375
|
+
this._pendingToolNames.clear();
|
|
1376
|
+
const current = getCurrentSystemMessage(this.sessionManager.buildSessionContext().messages);
|
|
1377
|
+
if (!current)
|
|
1378
|
+
return;
|
|
1379
|
+
const names = applyToolModifiers((current.toolsAdded ?? []).map((tool) => tool.name), modifiers);
|
|
1380
|
+
this._pendingToolNames = new Set(names.filter((name) => this._isAllowedTool(name)));
|
|
1381
|
+
this._setActiveTools(names);
|
|
765
1382
|
}
|
|
766
1383
|
// =========================================================================
|
|
767
1384
|
// Prompting
|
|
768
1385
|
// =========================================================================
|
|
769
|
-
|
|
1386
|
+
/**
|
|
1387
|
+
* Start a run from a user or custom message. The session counts as busy from here on, so
|
|
1388
|
+
* messages sent while before_agent_start handlers run are queued into this run instead of
|
|
1389
|
+
* starting another, and an abort requested meanwhile aborts the run as soon as it exists.
|
|
1390
|
+
* @param onStarted Called once the run's messages are prepared, before the first request.
|
|
1391
|
+
*/
|
|
1392
|
+
async _startRun(trigger, onStarted) {
|
|
770
1393
|
this._isAgentRunActive = true;
|
|
1394
|
+
this._agentRunAbortRequested = false;
|
|
1395
|
+
let messages;
|
|
1396
|
+
try {
|
|
1397
|
+
messages = await this._prepareRun(trigger);
|
|
1398
|
+
}
|
|
1399
|
+
catch (error) {
|
|
1400
|
+
this._isAgentRunActive = false;
|
|
1401
|
+
this._flushPendingBashMessages();
|
|
1402
|
+
this._flushPendingCustomMessages();
|
|
1403
|
+
this._resolveIdleWaitIfIdle();
|
|
1404
|
+
throw error;
|
|
1405
|
+
}
|
|
1406
|
+
// Messages held while the run was starting go before its starting messages, as they would
|
|
1407
|
+
// have while idle. No run exists yet, so they cannot split a tool call from its result.
|
|
1408
|
+
this._flushPendingBashMessages();
|
|
1409
|
+
this._flushPendingCustomMessages();
|
|
1410
|
+
onStarted?.();
|
|
1411
|
+
// Compaction before the prompt may have scheduled a retry; the new prompt replaces it.
|
|
1412
|
+
this._failedResponse = undefined;
|
|
1413
|
+
this._recordSelection();
|
|
1414
|
+
// The run records the loadout in the transcript; restored tools that did not register by now
|
|
1415
|
+
// are dropped, so a tool that never registers does not stay pending.
|
|
1416
|
+
this._pendingToolNames.clear();
|
|
771
1417
|
try {
|
|
772
1418
|
await this.agent.prompt(messages);
|
|
773
|
-
while (
|
|
1419
|
+
while (!this._agentRunAbortRequested) {
|
|
1420
|
+
if (await this._handlePostAgentRun()) {
|
|
1421
|
+
if (this._agentRunAbortRequested)
|
|
1422
|
+
break;
|
|
1423
|
+
await this.agent.continue();
|
|
1424
|
+
continue;
|
|
1425
|
+
}
|
|
1426
|
+
if (this._agentRunAbortRequested || !(await this._runBeforeSettleBoundary()))
|
|
1427
|
+
break;
|
|
1428
|
+
if (this._agentRunAbortRequested)
|
|
1429
|
+
break;
|
|
774
1430
|
await this.agent.continue();
|
|
775
1431
|
}
|
|
776
1432
|
}
|
|
777
1433
|
finally {
|
|
778
|
-
this.
|
|
1434
|
+
if (this._agentRunAbortRequested)
|
|
1435
|
+
this._finishCancelledRetry();
|
|
1436
|
+
this._failedResponse = undefined;
|
|
1437
|
+
this._runSystemPromptOptions = undefined;
|
|
779
1438
|
this._flushPendingBashMessages();
|
|
780
1439
|
this._flushPendingCustomMessages();
|
|
781
1440
|
await this._emitAgentSettled();
|
|
782
1441
|
}
|
|
783
1442
|
}
|
|
1443
|
+
/**
|
|
1444
|
+
* Prepare a run and return its starting messages: compact first when needed, emit
|
|
1445
|
+
* before_agent_start, apply the run's prompt options and tool loadout, and build the starting
|
|
1446
|
+
* message followed by pending nextTurn messages (consumed here) and handler messages, with a
|
|
1447
|
+
* system patch first when the prompt changed.
|
|
1448
|
+
*/
|
|
1449
|
+
async _prepareRun(trigger) {
|
|
1450
|
+
// Check if we need to compact before sending (catches aborted responses).
|
|
1451
|
+
// The starting message is sent below, so do not call agent.continue() here.
|
|
1452
|
+
const lastAssistant = this._findLastAssistantMessage();
|
|
1453
|
+
if (lastAssistant) {
|
|
1454
|
+
await this._checkCompaction(lastAssistant, false);
|
|
1455
|
+
}
|
|
1456
|
+
const selectedToolsBefore = this._baseSystemPromptOptions.selectedTools;
|
|
1457
|
+
const result = await this._extensionRunner.emitBeforeAgentStart(trigger, this._baseSystemPromptOptions);
|
|
1458
|
+
// Handlers may edit event.systemPromptOptions.selectedTools or call setActiveTools(),
|
|
1459
|
+
// which updates the live loadout instead. An explicit edit wins; otherwise the live
|
|
1460
|
+
// loadout is authoritative, so a setActiveTools() call is not undone here.
|
|
1461
|
+
const handlerEditedTools = result.systemPromptOptions.selectedTools.length !== selectedToolsBefore.length ||
|
|
1462
|
+
result.systemPromptOptions.selectedTools.some((name, index) => name !== selectedToolsBefore[index]);
|
|
1463
|
+
if (!handlerEditedTools)
|
|
1464
|
+
result.systemPromptOptions.selectedTools = this.getActiveToolNames();
|
|
1465
|
+
const messages = [];
|
|
1466
|
+
if (trigger.messageType === "custom") {
|
|
1467
|
+
messages.push(trigger.message);
|
|
1468
|
+
}
|
|
1469
|
+
else {
|
|
1470
|
+
// Normalize images after before_agent_start so extension-driven model selection
|
|
1471
|
+
// determines the resize profile used for the request and history.
|
|
1472
|
+
const normalized = await this._normalizePromptImages(trigger.images);
|
|
1473
|
+
const text = normalized.hints.length > 0 ? `${trigger.prompt}\n\n${normalized.hints.join("\n")}` : trigger.prompt;
|
|
1474
|
+
messages.push({
|
|
1475
|
+
role: "user",
|
|
1476
|
+
content: [{ type: "text", text }, ...normalized.images],
|
|
1477
|
+
timestamp: Date.now(),
|
|
1478
|
+
});
|
|
1479
|
+
}
|
|
1480
|
+
// Inject any pending "nextTurn" messages as context alongside the starting message
|
|
1481
|
+
messages.push(...this._pendingNextTurnMessages);
|
|
1482
|
+
this._pendingNextTurnMessages = [];
|
|
1483
|
+
for (const msg of result.messages) {
|
|
1484
|
+
messages.push({
|
|
1485
|
+
role: "custom",
|
|
1486
|
+
customType: msg.customType,
|
|
1487
|
+
// Untyped extensions can pass null/missing content; normalize at ingestion.
|
|
1488
|
+
content: msg.content ?? [],
|
|
1489
|
+
display: msg.display,
|
|
1490
|
+
details: msg.details,
|
|
1491
|
+
timestamp: Date.now(),
|
|
1492
|
+
});
|
|
1493
|
+
}
|
|
1494
|
+
const updateMessage = this._preparePromptAndToolLoadout(result.systemPromptOptions);
|
|
1495
|
+
this._runSystemPromptOptions = result.systemPromptOptions;
|
|
1496
|
+
if (updateMessage)
|
|
1497
|
+
messages.unshift(updateMessage);
|
|
1498
|
+
return messages;
|
|
1499
|
+
}
|
|
784
1500
|
async _handlePostAgentRun() {
|
|
785
|
-
const
|
|
1501
|
+
const message = this._lastAssistantMessage;
|
|
1502
|
+
const toolResults = this._lastAssistantToolResults;
|
|
786
1503
|
this._lastAssistantMessage = undefined;
|
|
787
|
-
|
|
1504
|
+
this._lastAssistantToolResults = [];
|
|
1505
|
+
if (this._agentRunAbortRequested) {
|
|
1506
|
+
this._finishCancelledRetry();
|
|
788
1507
|
return false;
|
|
789
1508
|
}
|
|
790
|
-
if (
|
|
791
|
-
return
|
|
1509
|
+
if (!message)
|
|
1510
|
+
return this.agent.hasQueuedMessages();
|
|
1511
|
+
if (this._isRetryableError(message) && (await this._prepareRetry(message))) {
|
|
1512
|
+
if (this._agentRunAbortRequested)
|
|
1513
|
+
this._finishCancelledRetry();
|
|
1514
|
+
this._failedResponse = message;
|
|
1515
|
+
return !this._agentRunAbortRequested;
|
|
1516
|
+
}
|
|
1517
|
+
if (this._agentRunAbortRequested) {
|
|
1518
|
+
this._finishCancelledRetry();
|
|
1519
|
+
return false;
|
|
792
1520
|
}
|
|
793
|
-
if (
|
|
1521
|
+
if (message.stopReason === "error" && this._retryAttempt > 0) {
|
|
794
1522
|
this._emit({
|
|
795
1523
|
type: "auto_retry_end",
|
|
796
1524
|
success: false,
|
|
797
1525
|
attempt: this._retryAttempt,
|
|
798
|
-
finalError:
|
|
1526
|
+
finalError: message.errorMessage,
|
|
799
1527
|
});
|
|
800
1528
|
this._retryAttempt = 0;
|
|
801
1529
|
}
|
|
802
|
-
if (await this._checkCompaction(
|
|
803
|
-
return
|
|
1530
|
+
if (await this._checkCompaction(message, true, toolResults)) {
|
|
1531
|
+
return !this._agentRunAbortRequested;
|
|
1532
|
+
}
|
|
1533
|
+
// The low-level loop drains both queues before agent_end. Messages queued by
|
|
1534
|
+
// agent_end handlers require a fresh run before pre-settlement handlers fire.
|
|
1535
|
+
return !this._agentRunAbortRequested && this.agent.hasQueuedMessages();
|
|
1536
|
+
}
|
|
1537
|
+
async _runBeforeSettleBoundary() {
|
|
1538
|
+
if (!this._extensionRunner.hasHandlers("agent_before_settle"))
|
|
1539
|
+
return this.agent.hasQueuedMessages();
|
|
1540
|
+
this._isBeforeSettle = true;
|
|
1541
|
+
this._abortDuringBeforeSettle = false;
|
|
1542
|
+
try {
|
|
1543
|
+
const result = await this._extensionRunner.emitBoundary({ type: "agent_before_settle", outcome: this._lastActivityOutcome }, (entries) => this._buildBoundaryContext(entries, "agent_before_settle"));
|
|
1544
|
+
this._commitBoundaryDrafts(result.entries);
|
|
1545
|
+
this._flushPendingCustomMessages();
|
|
1546
|
+
const finalContext = this._buildBoundaryContext([], "agent_before_settle");
|
|
1547
|
+
if (this._abortDuringBeforeSettle)
|
|
1548
|
+
return false;
|
|
1549
|
+
const shouldContinue = result.continue || this.agent.hasQueuedMessages();
|
|
1550
|
+
if (shouldContinue && !finalContext.canContinue) {
|
|
1551
|
+
if (result.continue)
|
|
1552
|
+
this._reportInvalidBoundaryContinuation("agent_before_settle");
|
|
1553
|
+
return false;
|
|
1554
|
+
}
|
|
1555
|
+
return shouldContinue;
|
|
1556
|
+
}
|
|
1557
|
+
finally {
|
|
1558
|
+
this._isBeforeSettle = false;
|
|
804
1559
|
}
|
|
805
|
-
// The agent loop drains both queues before emitting agent_end. Any messages
|
|
806
|
-
// here were queued by agent_end extension handlers and need a continuation.
|
|
807
|
-
return this.agent.hasQueuedMessages();
|
|
808
1560
|
}
|
|
809
1561
|
async _runInputHandlers(text, images, source, streamingBehavior) {
|
|
810
1562
|
if (!this._extensionRunner.hasHandlers("input")) {
|
|
@@ -819,6 +1571,25 @@ export class AgentSession {
|
|
|
819
1571
|
}
|
|
820
1572
|
return { text, images };
|
|
821
1573
|
}
|
|
1574
|
+
async _normalizePromptImages(images) {
|
|
1575
|
+
if (!images)
|
|
1576
|
+
return { images: [], hints: [] };
|
|
1577
|
+
const normalizedImages = [];
|
|
1578
|
+
const hints = [];
|
|
1579
|
+
for (const image of images) {
|
|
1580
|
+
const processed = await processImage(Buffer.from(image.data, "base64"), image.mimeType, {
|
|
1581
|
+
autoResizeImages: this.settingsManager.getImageAutoResize(),
|
|
1582
|
+
resizeOptions: this._limitsModel()?.inputLimits?.images?.resize,
|
|
1583
|
+
});
|
|
1584
|
+
if (!processed.ok) {
|
|
1585
|
+
hints.push(processed.message);
|
|
1586
|
+
continue;
|
|
1587
|
+
}
|
|
1588
|
+
normalizedImages.push({ type: "image", data: processed.data, mimeType: processed.mimeType });
|
|
1589
|
+
hints.push(...processed.hints);
|
|
1590
|
+
}
|
|
1591
|
+
return { images: normalizedImages, hints };
|
|
1592
|
+
}
|
|
822
1593
|
/**
|
|
823
1594
|
* Send a prompt to the agent.
|
|
824
1595
|
* - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming
|
|
@@ -829,127 +1600,68 @@ export class AgentSession {
|
|
|
829
1600
|
* @throws Error if no model selected or no API key available (when not streaming)
|
|
830
1601
|
*/
|
|
831
1602
|
async prompt(text, options) {
|
|
1603
|
+
if (this._isEmittingAgentSettled) {
|
|
1604
|
+
this._deferredSettledActions.push(async () => await this.prompt(text, options));
|
|
1605
|
+
return;
|
|
1606
|
+
}
|
|
832
1607
|
const expandPromptTemplates = options?.expandPromptTemplates ?? true;
|
|
833
1608
|
const preflightResult = options?.preflightResult;
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
if (
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
// Extension command executed, no prompt to send
|
|
842
|
-
preflightResult?.(true);
|
|
843
|
-
return;
|
|
844
|
-
}
|
|
845
|
-
}
|
|
846
|
-
if (this._compactionAbortController !== undefined) {
|
|
847
|
-
throw new Error("Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry.");
|
|
848
|
-
}
|
|
849
|
-
// Emit input event for extension interception (before skill/template expansion)
|
|
850
|
-
const processedInput = await this._runInputHandlers(text, options?.images, options?.source ?? "interactive", this.isStreaming ? options?.streamingBehavior : undefined);
|
|
851
|
-
if (!processedInput) {
|
|
852
|
-
preflightResult?.(true);
|
|
853
|
-
return;
|
|
854
|
-
}
|
|
855
|
-
const { text: currentText, images: currentImages } = processedInput;
|
|
856
|
-
// Expand skill commands (/skill:name args) and prompt templates (/template args)
|
|
857
|
-
let expandedText = currentText;
|
|
858
|
-
if (expandPromptTemplates) {
|
|
859
|
-
expandedText = this._expandSkillCommand(expandedText);
|
|
860
|
-
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
|
|
861
|
-
}
|
|
862
|
-
// If streaming, queue via steer() or followUp() based on option
|
|
863
|
-
if (this.isStreaming) {
|
|
864
|
-
if (!options?.streamingBehavior) {
|
|
865
|
-
throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
|
|
866
|
-
}
|
|
867
|
-
if (options.streamingBehavior === "followUp") {
|
|
868
|
-
await this._queueFollowUp(expandedText, currentImages);
|
|
869
|
-
}
|
|
870
|
-
else {
|
|
871
|
-
await this._queueSteer(expandedText, currentImages);
|
|
872
|
-
}
|
|
873
|
-
preflightResult?.(true);
|
|
1609
|
+
// Handle extension commands first (execute immediately, even during streaming)
|
|
1610
|
+
// Extension commands manage their own LLM interaction via pi.sendMessage()
|
|
1611
|
+
if (expandPromptTemplates && text.startsWith("/")) {
|
|
1612
|
+
const handled = await this._tryExecuteExtensionCommand(text);
|
|
1613
|
+
if (handled) {
|
|
1614
|
+
// Extension command executed, no prompt to send
|
|
1615
|
+
preflightResult?.("handled");
|
|
874
1616
|
return;
|
|
875
1617
|
}
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
if (lastAssistant) {
|
|
898
|
-
await this._checkCompaction(lastAssistant, false);
|
|
899
|
-
}
|
|
900
|
-
// Build messages array (custom message if any, then user message)
|
|
901
|
-
messages = [];
|
|
902
|
-
// Add user message
|
|
903
|
-
const userContent = [{ type: "text", text: expandedText }];
|
|
904
|
-
if (currentImages) {
|
|
905
|
-
userContent.push(...currentImages);
|
|
906
|
-
}
|
|
907
|
-
messages.push({
|
|
908
|
-
role: "user",
|
|
909
|
-
content: userContent,
|
|
910
|
-
timestamp: Date.now(),
|
|
911
|
-
});
|
|
912
|
-
// Inject any pending "nextTurn" messages as context alongside the user message
|
|
913
|
-
for (const msg of this._pendingNextTurnMessages) {
|
|
914
|
-
messages.push(msg);
|
|
915
|
-
}
|
|
916
|
-
this._pendingNextTurnMessages = [];
|
|
917
|
-
// Emit before_agent_start extension event
|
|
918
|
-
const result = await this._extensionRunner.emitBeforeAgentStart(expandedText, currentImages, this._baseSystemPrompt, this._baseSystemPromptOptions);
|
|
919
|
-
// Add all custom messages from extensions
|
|
920
|
-
if (result?.messages) {
|
|
921
|
-
for (const msg of result.messages) {
|
|
922
|
-
messages.push({
|
|
923
|
-
role: "custom",
|
|
924
|
-
customType: msg.customType,
|
|
925
|
-
// Untyped extensions can pass null/missing content; normalize at ingestion.
|
|
926
|
-
content: msg.content ?? [],
|
|
927
|
-
display: msg.display,
|
|
928
|
-
details: msg.details,
|
|
929
|
-
timestamp: Date.now(),
|
|
930
|
-
});
|
|
931
|
-
}
|
|
1618
|
+
}
|
|
1619
|
+
if (this._compactionAbortController !== undefined) {
|
|
1620
|
+
throw new Error("Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry.");
|
|
1621
|
+
}
|
|
1622
|
+
// Emit input event for extension interception (before skill/template expansion)
|
|
1623
|
+
const processedInput = await this._runInputHandlers(text, options?.images, options?.source ?? "interactive", this.isStreaming ? options?.streamingBehavior : undefined);
|
|
1624
|
+
if (!processedInput) {
|
|
1625
|
+
preflightResult?.("handled");
|
|
1626
|
+
return;
|
|
1627
|
+
}
|
|
1628
|
+
const { text: currentText, images: currentImages } = processedInput;
|
|
1629
|
+
// Expand skill commands (/skill:name args) and prompt templates (/template args)
|
|
1630
|
+
let expandedText = currentText;
|
|
1631
|
+
if (expandPromptTemplates) {
|
|
1632
|
+
expandedText = this._expandSkillCommand(expandedText);
|
|
1633
|
+
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
|
|
1634
|
+
}
|
|
1635
|
+
// If streaming, queue via steer() or followUp() based on option
|
|
1636
|
+
if (this.isStreaming) {
|
|
1637
|
+
if (!options?.streamingBehavior) {
|
|
1638
|
+
throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
|
|
932
1639
|
}
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
this._systemPromptOverride = result.systemPrompt;
|
|
936
|
-
this.agent.state.systemPrompt = result.systemPrompt;
|
|
1640
|
+
if (options.streamingBehavior === "followUp") {
|
|
1641
|
+
await this._queueFollowUp(expandedText, currentImages);
|
|
937
1642
|
}
|
|
938
1643
|
else {
|
|
939
|
-
|
|
940
|
-
this._systemPromptOverride = undefined;
|
|
941
|
-
this.agent.state.systemPrompt = this._baseSystemPrompt;
|
|
1644
|
+
await this._queueSteer(expandedText, currentImages);
|
|
942
1645
|
}
|
|
1646
|
+
preflightResult?.("queued");
|
|
1647
|
+
return;
|
|
943
1648
|
}
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
throw
|
|
1649
|
+
// Validate model
|
|
1650
|
+
if (!this.model) {
|
|
1651
|
+
throw new Error(formatNoModelSelectedMessage());
|
|
947
1652
|
}
|
|
948
|
-
|
|
949
|
-
|
|
1653
|
+
const hasConfiguredAuth = this._modelRuntime.hasConfiguredAuth(this.model.provider) ||
|
|
1654
|
+
(await this._modelRuntime.checkAuth(this.model.provider)) !== undefined;
|
|
1655
|
+
if (!hasConfiguredAuth) {
|
|
1656
|
+
const isOAuth = this._modelRuntime.isUsingOAuth(this.model.provider);
|
|
1657
|
+
if (isOAuth) {
|
|
1658
|
+
throw new Error(`Authentication failed for "${this.model.provider}". ` +
|
|
1659
|
+
`Credentials may have expired or network is unavailable. ` +
|
|
1660
|
+
`Run '/login ${this.model.provider}' to re-authenticate.`);
|
|
1661
|
+
}
|
|
1662
|
+
throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
|
|
950
1663
|
}
|
|
951
|
-
preflightResult?.(
|
|
952
|
-
await this._runAgentPrompt(messages);
|
|
1664
|
+
await this._startRun({ messageType: "user", prompt: expandedText, images: currentImages }, () => preflightResult?.("started"));
|
|
953
1665
|
}
|
|
954
1666
|
/**
|
|
955
1667
|
* Try to execute an extension command. Returns true if command was found and executed.
|
|
@@ -1014,7 +1726,7 @@ export class AgentSession {
|
|
|
1014
1726
|
}
|
|
1015
1727
|
const processedInput = await this._runInputHandlers(text, images, source, this.isStreaming ? behavior : undefined);
|
|
1016
1728
|
if (!processedInput)
|
|
1017
|
-
return;
|
|
1729
|
+
return "handled";
|
|
1018
1730
|
let expandedText = this._expandSkillCommand(processedInput.text);
|
|
1019
1731
|
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
|
|
1020
1732
|
if (behavior === "steer") {
|
|
@@ -1023,6 +1735,7 @@ export class AgentSession {
|
|
|
1023
1735
|
else {
|
|
1024
1736
|
await this._queueFollowUp(expandedText, processedInput.images);
|
|
1025
1737
|
}
|
|
1738
|
+
return "queued";
|
|
1026
1739
|
}
|
|
1027
1740
|
/**
|
|
1028
1741
|
* Queue a steering message while the agent is running.
|
|
@@ -1034,7 +1747,7 @@ export class AgentSession {
|
|
|
1034
1747
|
* @throws Error if text is an extension command
|
|
1035
1748
|
*/
|
|
1036
1749
|
async steer(text, images, options) {
|
|
1037
|
-
|
|
1750
|
+
return this._queueUserInput(text, images, "steer", options?.source ?? "interactive");
|
|
1038
1751
|
}
|
|
1039
1752
|
/**
|
|
1040
1753
|
* Queue a follow-up message to be processed after the agent finishes.
|
|
@@ -1045,7 +1758,7 @@ export class AgentSession {
|
|
|
1045
1758
|
* @throws Error if text is an extension command
|
|
1046
1759
|
*/
|
|
1047
1760
|
async followUp(text, images, options) {
|
|
1048
|
-
|
|
1761
|
+
return this._queueUserInput(text, images, "followUp", options?.source ?? "interactive");
|
|
1049
1762
|
}
|
|
1050
1763
|
/**
|
|
1051
1764
|
* Internal: Queue a steering message (already expanded, no extension command check).
|
|
@@ -1073,11 +1786,7 @@ export class AgentSession {
|
|
|
1073
1786
|
if (images) {
|
|
1074
1787
|
content.push(...images);
|
|
1075
1788
|
}
|
|
1076
|
-
this.agent.followUp({
|
|
1077
|
-
role: "user",
|
|
1078
|
-
content,
|
|
1079
|
-
timestamp: Date.now(),
|
|
1080
|
-
});
|
|
1789
|
+
this.agent.followUp({ role: "user", content, timestamp: Date.now() });
|
|
1081
1790
|
}
|
|
1082
1791
|
/**
|
|
1083
1792
|
* Throw an error if the text is an extension command.
|
|
@@ -1125,7 +1834,11 @@ export class AgentSession {
|
|
|
1125
1834
|
}
|
|
1126
1835
|
}
|
|
1127
1836
|
else if (options?.triggerTurn) {
|
|
1128
|
-
|
|
1837
|
+
if (this._isEmittingAgentSettled) {
|
|
1838
|
+
this._deferredSettledActions.push(async () => await this.sendCustomMessage(message, options));
|
|
1839
|
+
return;
|
|
1840
|
+
}
|
|
1841
|
+
await this._startRun({ messageType: "custom", message: appMessage });
|
|
1129
1842
|
}
|
|
1130
1843
|
else if (this.isStreaming) {
|
|
1131
1844
|
// Appending now would put the message between an assistant tool call and its
|
|
@@ -1139,8 +1852,8 @@ export class AgentSession {
|
|
|
1139
1852
|
}
|
|
1140
1853
|
}
|
|
1141
1854
|
_appendCustomMessage(appMessage) {
|
|
1142
|
-
this.agent.state.messages.push(appMessage);
|
|
1143
1855
|
this.sessionManager.appendCustomMessageEntry(appMessage.customType, appMessage.content, appMessage.display, appMessage.details);
|
|
1856
|
+
this._refreshFinalizedContext();
|
|
1144
1857
|
this._emit({ type: "message_start", message: appMessage });
|
|
1145
1858
|
this._emit({ type: "message_end", message: appMessage });
|
|
1146
1859
|
}
|
|
@@ -1227,9 +1940,14 @@ export class AgentSession {
|
|
|
1227
1940
|
* Abort current operation and wait for agent to become idle.
|
|
1228
1941
|
*/
|
|
1229
1942
|
async abort() {
|
|
1943
|
+
if (this._isAgentRunActive) {
|
|
1944
|
+
this._agentRunAbortRequested = true;
|
|
1945
|
+
}
|
|
1230
1946
|
this.abortRetry();
|
|
1231
1947
|
this.abortCompaction();
|
|
1232
1948
|
this.abortBranchSummary();
|
|
1949
|
+
if (this._isBeforeSettle)
|
|
1950
|
+
this._abortDuringBeforeSettle = true;
|
|
1233
1951
|
this.agent.abort();
|
|
1234
1952
|
await this.waitForIdle();
|
|
1235
1953
|
}
|
|
@@ -1456,8 +2174,10 @@ export class AgentSession {
|
|
|
1456
2174
|
// Compaction
|
|
1457
2175
|
// =========================================================================
|
|
1458
2176
|
/** Generate Pi's built-in compaction summary for manual and automatic compaction. */
|
|
1459
|
-
async _runDefaultCompaction(preparation,
|
|
1460
|
-
|
|
2177
|
+
async _runDefaultCompaction(preparation, model, customInstructions, signal, reason) {
|
|
2178
|
+
// Resolve the request only when Pi summarizes itself: routing may call models or fail.
|
|
2179
|
+
const request = await this._getSummarizationRequestAuth(model, signal);
|
|
2180
|
+
return compact(preparation, request.model, request.apiKey, request.headers, customInstructions, signal, request.thinkingLevel, this.agent.streamFunction, request.env, this.settingsManager.getRetrySettings(), this._summarizationRetryCallbacks({ source: "compaction", reason }), undefined);
|
|
1461
2181
|
}
|
|
1462
2182
|
_clearManualCompactionState() {
|
|
1463
2183
|
this._compactionAbortController = undefined;
|
|
@@ -1483,13 +2203,13 @@ export class AgentSession {
|
|
|
1483
2203
|
this._compactionAbortController = new AbortController();
|
|
1484
2204
|
this._emit({ type: "compaction_start", reason: "manual" });
|
|
1485
2205
|
let fromExtension = false;
|
|
2206
|
+
let cancelledByExtension = false;
|
|
1486
2207
|
try {
|
|
1487
2208
|
const model = this.model;
|
|
1488
2209
|
if (!model) {
|
|
1489
2210
|
throw new Error(formatNoModelSelectedMessage());
|
|
1490
2211
|
}
|
|
1491
2212
|
const settings = this.settingsManager.getCompactionSettings(model);
|
|
1492
|
-
const { model: requestModel, apiKey, headers, env } = await this._getSummarizationRequestAuth(model);
|
|
1493
2213
|
const pathEntries = this.sessionManager.getBranch();
|
|
1494
2214
|
const preparation = prepareCompaction(pathEntries, settings);
|
|
1495
2215
|
if (!preparation) {
|
|
@@ -1512,6 +2232,7 @@ export class AgentSession {
|
|
|
1512
2232
|
signal: this._compactionAbortController.signal,
|
|
1513
2233
|
}));
|
|
1514
2234
|
if (result?.cancel) {
|
|
2235
|
+
cancelledByExtension = true;
|
|
1515
2236
|
throw new Error("Compaction cancelled");
|
|
1516
2237
|
}
|
|
1517
2238
|
if (result?.compaction) {
|
|
@@ -1534,7 +2255,7 @@ export class AgentSession {
|
|
|
1534
2255
|
}
|
|
1535
2256
|
else {
|
|
1536
2257
|
// Shared default summary generator, also used by automatic compaction.
|
|
1537
|
-
const result = await this._runDefaultCompaction(preparation,
|
|
2258
|
+
const result = await this._runDefaultCompaction(preparation, model, customInstructions, this._compactionAbortController.signal, "manual");
|
|
1538
2259
|
summary = result.summary;
|
|
1539
2260
|
firstKeptEntryId = result.firstKeptEntryId;
|
|
1540
2261
|
tokensBefore = result.tokensBefore;
|
|
@@ -1546,9 +2267,8 @@ export class AgentSession {
|
|
|
1546
2267
|
}
|
|
1547
2268
|
this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
|
|
1548
2269
|
const newEntries = this.sessionManager.getEntries();
|
|
1549
|
-
|
|
1550
|
-
this.
|
|
1551
|
-
const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
|
|
2270
|
+
this._refreshFinalizedContext();
|
|
2271
|
+
const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages);
|
|
1552
2272
|
// Get the saved compaction entry for the extension event
|
|
1553
2273
|
const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
|
|
1554
2274
|
if (this._extensionRunner && savedCompactionEntry) {
|
|
@@ -1581,7 +2301,7 @@ export class AgentSession {
|
|
|
1581
2301
|
}
|
|
1582
2302
|
catch (error) {
|
|
1583
2303
|
const message = error instanceof Error ? error.message : String(error);
|
|
1584
|
-
const aborted =
|
|
2304
|
+
const aborted = this._compactionAbortController.signal.aborted || cancelledByExtension;
|
|
1585
2305
|
const errorMessage = aborted ? undefined : `Compaction failed: ${message}`;
|
|
1586
2306
|
this._clearManualCompactionState();
|
|
1587
2307
|
this._emit({
|
|
@@ -1639,19 +2359,21 @@ export class AgentSession {
|
|
|
1639
2359
|
* @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true
|
|
1640
2360
|
* @returns Whether the post-run loop should call `agent.continue()` for overflow recovery or queued messages
|
|
1641
2361
|
*/
|
|
1642
|
-
async _checkCompaction(assistantMessage, skipAbortedCheck = true) {
|
|
2362
|
+
async _checkCompaction(assistantMessage, skipAbortedCheck = true, toolResults = []) {
|
|
1643
2363
|
const settings = this.settingsManager.getCompactionSettings(this.model);
|
|
1644
2364
|
if (!settings.enabled)
|
|
1645
2365
|
return false;
|
|
1646
2366
|
// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
|
|
1647
2367
|
if (skipAbortedCheck && assistantMessage.stopReason === "aborted")
|
|
1648
2368
|
return false;
|
|
1649
|
-
const contextWindow = this.model?.contextWindow ?? 0;
|
|
1650
2369
|
// Skip overflow check if the message came from a different model.
|
|
1651
2370
|
// This handles the case where user switched from a smaller-context model (e.g. opus)
|
|
1652
2371
|
// to a larger-context model (e.g. codex) - the overflow error from the old model
|
|
1653
|
-
// shouldn't trigger compaction for the new model.
|
|
1654
|
-
|
|
2372
|
+
// shouldn't trigger compaction for the new model. Under a virtual selection, the
|
|
2373
|
+
// physical model that produced the message supplies the limits.
|
|
2374
|
+
const messageModel = this._modelForMessage(assistantMessage);
|
|
2375
|
+
const sameModel = messageModel !== undefined;
|
|
2376
|
+
const contextWindow = (messageModel ?? this.model)?.contextWindow ?? 0;
|
|
1655
2377
|
// Skip compaction checks if this assistant message is older than the latest
|
|
1656
2378
|
// compaction boundary. This prevents a stale pre-compaction usage/error
|
|
1657
2379
|
// from retriggering compaction on the first prompt after compaction.
|
|
@@ -1663,8 +2385,27 @@ export class AgentSession {
|
|
|
1663
2385
|
// Automatic cases 1 and 2: context overflow.
|
|
1664
2386
|
// A length stop is recoverable when output ended below the model's original desired limit,
|
|
1665
2387
|
// independent of the configured context size or any context-clamped provider request limit.
|
|
1666
|
-
const
|
|
1667
|
-
const
|
|
2388
|
+
const currentProjection = this.sessionManager.buildSessionProjection();
|
|
2389
|
+
const assistantEntryId = this._findPersistedMessageEntryId(assistantMessage);
|
|
2390
|
+
const assistantIsProjected = assistantEntryId === undefined ||
|
|
2391
|
+
currentProjection.entries.some((entry) => entry.sourceEntry.id === assistantEntryId &&
|
|
2392
|
+
entry.messages.some((message) => message.role === "assistant"));
|
|
2393
|
+
const branch = this.sessionManager.getBranch();
|
|
2394
|
+
const assistantIndex = assistantEntryId ? branch.findIndex((entry) => entry.id === assistantEntryId) : -1;
|
|
2395
|
+
const entriesAfterAssistant = assistantIndex >= 0 ? branch.slice(assistantIndex + 1) : [];
|
|
2396
|
+
const hasPostAssistantContextEdit = entriesAfterAssistant.some((entry) => entry.type === "context_edit");
|
|
2397
|
+
const latestAssistantEdit = entriesAfterAssistant
|
|
2398
|
+
.filter((entry) => entry.type === "context_edit" && entry.targetId === assistantEntryId)
|
|
2399
|
+
.at(-1);
|
|
2400
|
+
const assistantRetainedForExplicitRecovery = assistantEntryId === undefined ||
|
|
2401
|
+
(!entriesAfterAssistant.some((entry) => entry.type === "compaction") &&
|
|
2402
|
+
latestAssistantEdit?.replacement !== null);
|
|
2403
|
+
const assistantUsageMatchesProjection = assistantIsProjected && !hasPostAssistantContextEdit;
|
|
2404
|
+
const explicitOverflow = assistantMessage.stopReason === "error" && isContextOverflow(assistantMessage);
|
|
2405
|
+
const contextOverflow = sameModel &&
|
|
2406
|
+
((explicitOverflow && assistantRetainedForExplicitRecovery) ||
|
|
2407
|
+
(assistantUsageMatchesProjection && isContextOverflow(assistantMessage, contextWindow)));
|
|
2408
|
+
const recoverableLength = sameModel && assistantIsProjected && isRecoverableLength(assistantMessage, messageModel.maxTokens);
|
|
1668
2409
|
if (contextOverflow || recoverableLength) {
|
|
1669
2410
|
const willRetry = assistantMessage.stopReason !== "stop";
|
|
1670
2411
|
// Case 2: the response completed successfully. Compact, but do not retry because
|
|
@@ -1693,22 +2434,26 @@ export class AgentSession {
|
|
|
1693
2434
|
});
|
|
1694
2435
|
return false;
|
|
1695
2436
|
}
|
|
1696
|
-
//
|
|
1697
|
-
// retry once. The message remains in session history but is excluded from retry context.
|
|
2437
|
+
// Persistently omit the selected final attempt before post-run recovery compaction.
|
|
1698
2438
|
this._overflowRecoveryAttempted = true;
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
return
|
|
2439
|
+
this._omitRecoveryAttempt(assistantMessage, toolResults);
|
|
2440
|
+
const retry = await this._runAutoCompaction("overflow", willRetry);
|
|
2441
|
+
if (retry)
|
|
2442
|
+
this._failedResponse = assistantMessage;
|
|
2443
|
+
return retry;
|
|
1704
2444
|
}
|
|
1705
2445
|
// Case 3: threshold compaction without retry.
|
|
1706
2446
|
// For error messages or all-zero usage messages, estimate from the last valid response.
|
|
1707
2447
|
// This ensures sessions that hit persistent API errors (e.g. 529) or malformed zero-usage
|
|
1708
2448
|
// responses can still compact and do not reset context accounting.
|
|
1709
2449
|
let contextTokens;
|
|
2450
|
+
const projection = currentProjection;
|
|
2451
|
+
const hasContextEdits = projection.entries.some((entry) => entry.sourceEntry.type === "context_edit");
|
|
1710
2452
|
const directContextTokens = assistantMessage.usage ? calculateContextTokens(assistantMessage.usage) : 0;
|
|
1711
|
-
if (
|
|
2453
|
+
if (hasContextEdits) {
|
|
2454
|
+
contextTokens = estimateProjectedContextTokens(projection, branch).tokens;
|
|
2455
|
+
}
|
|
2456
|
+
else if (assistantMessage.stopReason === "error" || directContextTokens === 0) {
|
|
1712
2457
|
const messages = this.agent.state.messages;
|
|
1713
2458
|
const estimate = estimateContextTokens(messages);
|
|
1714
2459
|
// Without provider usage, estimate.tokens is the pure message-size estimate.
|
|
@@ -1747,21 +2492,24 @@ export class AgentSession {
|
|
|
1747
2492
|
async _runAutoCompaction(reason, willRetry) {
|
|
1748
2493
|
const model = this.model;
|
|
1749
2494
|
const settings = this.settingsManager.getCompactionSettings(model);
|
|
2495
|
+
let abortController;
|
|
1750
2496
|
let started = false;
|
|
1751
2497
|
let fromExtension = false;
|
|
2498
|
+
let cancelledByExtension = false;
|
|
1752
2499
|
try {
|
|
1753
2500
|
if (!model) {
|
|
1754
2501
|
return false;
|
|
1755
2502
|
}
|
|
1756
|
-
const { model: requestModel, apiKey, headers, env } = await this._getSummarizationRequestAuth(model);
|
|
1757
2503
|
const pathEntries = this.sessionManager.getBranch();
|
|
1758
2504
|
const preparation = prepareCompaction(pathEntries, settings);
|
|
1759
2505
|
if (!preparation) {
|
|
1760
2506
|
return false;
|
|
1761
2507
|
}
|
|
1762
|
-
|
|
1763
|
-
this._autoCompactionAbortController =
|
|
2508
|
+
abortController = new AbortController();
|
|
2509
|
+
this._autoCompactionAbortController = abortController;
|
|
1764
2510
|
started = true;
|
|
2511
|
+
this._emit({ type: "compaction_start", reason });
|
|
2512
|
+
abortController.signal.throwIfAborted();
|
|
1765
2513
|
let extensionCompaction;
|
|
1766
2514
|
if (this._extensionRunner.hasHandlers("session_before_compact")) {
|
|
1767
2515
|
const extensionResult = (await this._extensionRunner.emit({
|
|
@@ -1771,29 +2519,18 @@ export class AgentSession {
|
|
|
1771
2519
|
customInstructions: undefined,
|
|
1772
2520
|
reason,
|
|
1773
2521
|
willRetry,
|
|
1774
|
-
signal:
|
|
2522
|
+
signal: abortController.signal,
|
|
1775
2523
|
}));
|
|
1776
2524
|
if (extensionResult?.cancel) {
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
reason,
|
|
1780
|
-
result: undefined,
|
|
1781
|
-
aborted: true,
|
|
1782
|
-
willRetry: false,
|
|
1783
|
-
});
|
|
1784
|
-
await this._emitSessionCompactFailed({
|
|
1785
|
-
reason,
|
|
1786
|
-
aborted: true,
|
|
1787
|
-
willRetry: false,
|
|
1788
|
-
fromExtension: false,
|
|
1789
|
-
});
|
|
1790
|
-
return false;
|
|
2525
|
+
cancelledByExtension = true;
|
|
2526
|
+
throw new Error("Compaction cancelled");
|
|
1791
2527
|
}
|
|
1792
2528
|
if (extensionResult?.compaction) {
|
|
1793
2529
|
extensionCompaction = extensionResult.compaction;
|
|
1794
2530
|
fromExtension = true;
|
|
1795
2531
|
}
|
|
1796
2532
|
}
|
|
2533
|
+
abortController.signal.throwIfAborted();
|
|
1797
2534
|
let summary;
|
|
1798
2535
|
let firstKeptEntryId;
|
|
1799
2536
|
let tokensBefore;
|
|
@@ -1809,34 +2546,18 @@ export class AgentSession {
|
|
|
1809
2546
|
}
|
|
1810
2547
|
else {
|
|
1811
2548
|
// Shared default summary generator, also used by manual compaction.
|
|
1812
|
-
const compactResult = await this._runDefaultCompaction(preparation,
|
|
2549
|
+
const compactResult = await this._runDefaultCompaction(preparation, model, undefined, abortController.signal, reason);
|
|
1813
2550
|
summary = compactResult.summary;
|
|
1814
2551
|
firstKeptEntryId = compactResult.firstKeptEntryId;
|
|
1815
2552
|
tokensBefore = compactResult.tokensBefore;
|
|
1816
2553
|
usage = compactResult.usage;
|
|
1817
2554
|
details = compactResult.details;
|
|
1818
2555
|
}
|
|
1819
|
-
|
|
1820
|
-
this._emit({
|
|
1821
|
-
type: "compaction_end",
|
|
1822
|
-
reason,
|
|
1823
|
-
result: undefined,
|
|
1824
|
-
aborted: true,
|
|
1825
|
-
willRetry: false,
|
|
1826
|
-
});
|
|
1827
|
-
await this._emitSessionCompactFailed({
|
|
1828
|
-
reason,
|
|
1829
|
-
aborted: true,
|
|
1830
|
-
willRetry: false,
|
|
1831
|
-
fromExtension,
|
|
1832
|
-
});
|
|
1833
|
-
return false;
|
|
1834
|
-
}
|
|
2556
|
+
abortController.signal.throwIfAborted();
|
|
1835
2557
|
this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
|
|
1836
2558
|
const newEntries = this.sessionManager.getEntries();
|
|
1837
|
-
|
|
1838
|
-
this.
|
|
1839
|
-
const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
|
|
2559
|
+
this._refreshFinalizedContext();
|
|
2560
|
+
const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages);
|
|
1840
2561
|
// Get the saved compaction entry for the extension event
|
|
1841
2562
|
const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
|
|
1842
2563
|
if (this._extensionRunner && savedCompactionEntry) {
|
|
@@ -1857,40 +2578,33 @@ export class AgentSession {
|
|
|
1857
2578
|
details,
|
|
1858
2579
|
};
|
|
1859
2580
|
this._emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
|
|
1860
|
-
if (willRetry)
|
|
1861
|
-
const messages = this.agent.state.messages;
|
|
1862
|
-
const lastMsg = messages[messages.length - 1];
|
|
1863
|
-
// The overflow response was persisted on message_end before _checkCompaction() removed it
|
|
1864
|
-
// from agent state. Rebuilding state from the new compaction can restore that kept entry,
|
|
1865
|
-
// leaving an assistant as the final message. agent.continue() rejects that state, so remove
|
|
1866
|
-
// the retriable error or truncated-length response again before continuing the interrupted turn.
|
|
1867
|
-
if (lastMsg?.role === "assistant" && (lastMsg.stopReason === "error" || lastMsg.stopReason === "length")) {
|
|
1868
|
-
this.agent.state.messages = messages.slice(0, -1);
|
|
1869
|
-
}
|
|
2581
|
+
if (willRetry)
|
|
1870
2582
|
return true;
|
|
1871
|
-
}
|
|
1872
2583
|
// Auto-compaction can complete while follow-up/steering/custom messages are waiting.
|
|
1873
2584
|
// Continue once so queued messages are delivered.
|
|
1874
2585
|
return this.agent.hasQueuedMessages();
|
|
1875
2586
|
}
|
|
1876
2587
|
catch (error) {
|
|
1877
|
-
const
|
|
2588
|
+
const message = error instanceof Error ? error.message : "compaction failed";
|
|
2589
|
+
const aborted = abortController?.signal.aborted === true || cancelledByExtension;
|
|
1878
2590
|
if (started) {
|
|
1879
|
-
const
|
|
1880
|
-
?
|
|
1881
|
-
:
|
|
2591
|
+
const errorMessage = aborted
|
|
2592
|
+
? undefined
|
|
2593
|
+
: reason === "overflow"
|
|
2594
|
+
? `Context overflow recovery failed: ${message}`
|
|
2595
|
+
: `Auto-compaction failed: ${message}`;
|
|
1882
2596
|
this._emit({
|
|
1883
2597
|
type: "compaction_end",
|
|
1884
2598
|
reason,
|
|
1885
2599
|
result: undefined,
|
|
1886
|
-
aborted
|
|
2600
|
+
aborted,
|
|
1887
2601
|
willRetry: false,
|
|
1888
|
-
errorMessage
|
|
2602
|
+
errorMessage,
|
|
1889
2603
|
});
|
|
1890
2604
|
await this._emitSessionCompactFailed({
|
|
1891
2605
|
reason,
|
|
1892
|
-
errorMessage
|
|
1893
|
-
aborted
|
|
2606
|
+
errorMessage,
|
|
2607
|
+
aborted,
|
|
1894
2608
|
willRetry: false,
|
|
1895
2609
|
fromExtension,
|
|
1896
2610
|
});
|
|
@@ -1898,7 +2612,9 @@ export class AgentSession {
|
|
|
1898
2612
|
return false;
|
|
1899
2613
|
}
|
|
1900
2614
|
finally {
|
|
1901
|
-
this._autoCompactionAbortController
|
|
2615
|
+
if (this._autoCompactionAbortController === abortController) {
|
|
2616
|
+
this._autoCompactionAbortController = undefined;
|
|
2617
|
+
}
|
|
1902
2618
|
this._resolveIdleWaitIfIdle();
|
|
1903
2619
|
}
|
|
1904
2620
|
}
|
|
@@ -1933,6 +2649,7 @@ export class AgentSession {
|
|
|
1933
2649
|
}
|
|
1934
2650
|
this._applyExtensionBindings(this._extensionRunner);
|
|
1935
2651
|
await this._extensionRunner.emit(this._sessionStartEvent);
|
|
2652
|
+
this._extensionRunner.reportUnhandledMcpServers();
|
|
1936
2653
|
await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
|
|
1937
2654
|
}
|
|
1938
2655
|
async extendResourcesFromExtensions(reason) {
|
|
@@ -1949,13 +2666,12 @@ export class AgentSession {
|
|
|
1949
2666
|
themePaths: this.buildExtensionResourcePaths(themePaths),
|
|
1950
2667
|
};
|
|
1951
2668
|
this._resourceLoader.extendResources(extensionPaths);
|
|
1952
|
-
this.
|
|
1953
|
-
this.agent.state.systemPrompt = this._baseSystemPrompt;
|
|
2669
|
+
this._rebuildSystemPrompt(this.getActiveToolNames());
|
|
1954
2670
|
}
|
|
1955
2671
|
buildExtensionResourcePaths(entries) {
|
|
1956
2672
|
return entries.map((entry) => {
|
|
1957
2673
|
const source = this.getExtensionSourceLabel(entry.extensionPath);
|
|
1958
|
-
const baseDir = entry.extensionPath
|
|
2674
|
+
const baseDir = isSyntheticPath(entry.extensionPath) ? undefined : dirname(entry.extensionPath);
|
|
1959
2675
|
return {
|
|
1960
2676
|
path: entry.path,
|
|
1961
2677
|
metadata: {
|
|
@@ -1968,7 +2684,7 @@ export class AgentSession {
|
|
|
1968
2684
|
});
|
|
1969
2685
|
}
|
|
1970
2686
|
getExtensionSourceLabel(extensionPath) {
|
|
1971
|
-
if (extensionPath
|
|
2687
|
+
if (isSyntheticPath(extensionPath)) {
|
|
1972
2688
|
return `extension:${extensionPath.replace(/[<>]/g, "")}`;
|
|
1973
2689
|
}
|
|
1974
2690
|
const base = basename(extensionPath);
|
|
@@ -2053,6 +2769,7 @@ export class AgentSession {
|
|
|
2053
2769
|
},
|
|
2054
2770
|
getActiveTools: () => this.getActiveToolNames(),
|
|
2055
2771
|
getAllTools: () => this.getAllTools(),
|
|
2772
|
+
getSettings: () => this.settingsManager.getSettings(),
|
|
2056
2773
|
setActiveTools: (toolNames) => this.setActiveToolsByName(toolNames),
|
|
2057
2774
|
refreshTools: () => this._refreshToolRegistry(),
|
|
2058
2775
|
getCommands,
|
|
@@ -2096,6 +2813,8 @@ export class AgentSession {
|
|
|
2096
2813
|
},
|
|
2097
2814
|
getSystemPrompt: () => this.systemPrompt,
|
|
2098
2815
|
getSystemPromptOptions: () => this._baseSystemPromptOptions,
|
|
2816
|
+
executeTool: (callerId, name, args, options) => this._executeNestedToolCall(callerId, name, args, options),
|
|
2817
|
+
getCallableTools: () => this._getCallableTools(),
|
|
2099
2818
|
}, {
|
|
2100
2819
|
registerProvider: (name, config) => {
|
|
2101
2820
|
this._modelRuntime.registerProvider(name, config);
|
|
@@ -2109,14 +2828,22 @@ export class AgentSession {
|
|
|
2109
2828
|
this._modelRuntime.unregisterProvider(name);
|
|
2110
2829
|
this._refreshCurrentModelFromRegistry();
|
|
2111
2830
|
},
|
|
2831
|
+
registerVirtualModel: (definition) => {
|
|
2832
|
+
this._modelRuntime.registerVirtualModel(definition);
|
|
2833
|
+
this._refreshCurrentModelFromRegistry();
|
|
2834
|
+
},
|
|
2835
|
+
unregisterVirtualModel: (provider, id) => {
|
|
2836
|
+
this._modelRuntime.unregisterVirtualModel(provider, id);
|
|
2837
|
+
this._refreshCurrentModelFromRegistry();
|
|
2838
|
+
},
|
|
2112
2839
|
});
|
|
2113
2840
|
}
|
|
2114
2841
|
_refreshToolRegistry(options) {
|
|
2115
|
-
|
|
2842
|
+
// Tools that were already activated on registration. A tool whose exposure changes to
|
|
2843
|
+
// `direct` or `model-only` (for example from `hidden`) is activated like a new tool.
|
|
2844
|
+
const previousActivatedOnRegistration = new Set([...this._toolRegistry.keys()].filter((name) => this._isActivatedOnRegistration(name)));
|
|
2116
2845
|
const previousActiveToolNames = this.getActiveToolNames();
|
|
2117
|
-
const
|
|
2118
|
-
const excludedToolNames = this._excludedToolNames;
|
|
2119
|
-
const isAllowedTool = (name) => (!allowedToolNames || allowedToolNames.has(name)) && !excludedToolNames?.has(name);
|
|
2846
|
+
const allowedTools = this._allowedTools;
|
|
2120
2847
|
const registeredTools = this._extensionRunner.getAllRegisteredTools();
|
|
2121
2848
|
const allCustomTools = [
|
|
2122
2849
|
...registeredTools,
|
|
@@ -2124,14 +2851,14 @@ export class AgentSession {
|
|
|
2124
2851
|
definition,
|
|
2125
2852
|
sourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: "sdk" }),
|
|
2126
2853
|
})),
|
|
2127
|
-
].filter((tool) =>
|
|
2854
|
+
].filter((tool) => this._isAllowedTool(tool.definition.name));
|
|
2128
2855
|
const definitionRegistry = new Map(Array.from(this._baseToolDefinitions.entries())
|
|
2129
|
-
.filter(([name]) =>
|
|
2856
|
+
.filter(([name]) => this._isAllowedTool(name))
|
|
2130
2857
|
.map(([name, definition]) => [
|
|
2131
2858
|
name,
|
|
2132
2859
|
{
|
|
2133
2860
|
definition,
|
|
2134
|
-
sourceInfo: createSyntheticSourceInfo(
|
|
2861
|
+
sourceInfo: createSyntheticSourceInfo(`${BUILTIN_PATH_PREFIX}${name}`, { source: "builtin" }),
|
|
2135
2862
|
},
|
|
2136
2863
|
]));
|
|
2137
2864
|
for (const tool of allCustomTools) {
|
|
@@ -2156,37 +2883,53 @@ export class AgentSession {
|
|
|
2156
2883
|
const runner = this._extensionRunner;
|
|
2157
2884
|
const wrappedExtensionTools = wrapRegisteredTools(allCustomTools, runner);
|
|
2158
2885
|
const wrappedBuiltInTools = wrapRegisteredTools(Array.from(this._baseToolDefinitions.values())
|
|
2159
|
-
.filter((definition) =>
|
|
2886
|
+
.filter((definition) => this._isAllowedTool(definition.name))
|
|
2160
2887
|
.map((definition) => ({
|
|
2161
2888
|
definition,
|
|
2162
|
-
sourceInfo: createSyntheticSourceInfo(
|
|
2889
|
+
sourceInfo: createSyntheticSourceInfo(`${BUILTIN_PATH_PREFIX}${definition.name}`, {
|
|
2890
|
+
source: "builtin",
|
|
2891
|
+
}),
|
|
2163
2892
|
})), runner);
|
|
2164
2893
|
const toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));
|
|
2165
2894
|
for (const tool of wrappedExtensionTools) {
|
|
2166
2895
|
toolRegistry.set(tool.name, tool);
|
|
2167
2896
|
}
|
|
2168
2897
|
this._toolRegistry = toolRegistry;
|
|
2169
|
-
const nextActiveToolNames = (options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]).filter((name) =>
|
|
2170
|
-
if (
|
|
2898
|
+
const nextActiveToolNames = (options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]).filter((name) => this._isAllowedTool(name));
|
|
2899
|
+
if (allowedTools) {
|
|
2171
2900
|
for (const toolName of this._toolRegistry.keys()) {
|
|
2172
|
-
|
|
2901
|
+
// Naming or matching a tool activates it even when it is not active by default. MCP tools
|
|
2902
|
+
// kept registered without being named stay inactive.
|
|
2903
|
+
if (allowedTools(toolName) && this._isDeclarable(toolName)) {
|
|
2173
2904
|
nextActiveToolNames.push(toolName);
|
|
2174
2905
|
}
|
|
2175
2906
|
}
|
|
2176
2907
|
}
|
|
2177
2908
|
else if (options?.includeAllExtensionTools) {
|
|
2178
2909
|
for (const tool of wrappedExtensionTools) {
|
|
2179
|
-
|
|
2910
|
+
if (this._isActivatedOnRegistration(tool.name))
|
|
2911
|
+
nextActiveToolNames.push(tool.name);
|
|
2180
2912
|
}
|
|
2181
2913
|
}
|
|
2182
2914
|
else if (!options?.activeToolNames) {
|
|
2183
2915
|
for (const toolName of this._toolRegistry.keys()) {
|
|
2184
|
-
if (!
|
|
2916
|
+
if (!previousActivatedOnRegistration.has(toolName) && this._isActivatedOnRegistration(toolName)) {
|
|
2185
2917
|
nextActiveToolNames.push(toolName);
|
|
2186
2918
|
}
|
|
2187
2919
|
}
|
|
2188
2920
|
}
|
|
2189
|
-
|
|
2921
|
+
// Pending tools that are registered now become active.
|
|
2922
|
+
nextActiveToolNames.push(...this._pendingToolNames);
|
|
2923
|
+
this._setActiveTools([...new Set(nextActiveToolNames)]);
|
|
2924
|
+
}
|
|
2925
|
+
/** Whether activating the tool declares it to the model. */
|
|
2926
|
+
_isDeclarable(name) {
|
|
2927
|
+
const exposure = this._getToolExposure(name);
|
|
2928
|
+
return exposure === "direct" || exposure === "model-only";
|
|
2929
|
+
}
|
|
2930
|
+
/** Whether registering the tool activates it, which declares it to the model. */
|
|
2931
|
+
_isActivatedOnRegistration(name) {
|
|
2932
|
+
return this._isDeclarable(name) && this._toolDefinitions.get(name)?.definition.defaultActive !== false;
|
|
2190
2933
|
}
|
|
2191
2934
|
_buildRuntime(options) {
|
|
2192
2935
|
const autoResizeImages = this.settingsManager.getImageAutoResize();
|
|
@@ -2228,12 +2971,22 @@ export class AgentSession {
|
|
|
2228
2971
|
const previousFlagValues = oldRunner.getFlagValues();
|
|
2229
2972
|
await emitSessionShutdownEvent(oldRunner, { type: "session_shutdown", reason: "reload" });
|
|
2230
2973
|
oldRunner.invalidate();
|
|
2974
|
+
const getDefaultTools = () => this._usesDefaultTools
|
|
2975
|
+
? applyToolModifiers(this.settingsManager.getDefaultTools() ?? DEFAULT_TOOL_NAMES, this._defaultToolModifiers)
|
|
2976
|
+
: [];
|
|
2977
|
+
const previousDefaultTools = new Set(getDefaultTools());
|
|
2231
2978
|
await this.settingsManager.reload();
|
|
2232
2979
|
this.syncQueueModesFromSettings();
|
|
2233
2980
|
resetApiProviders();
|
|
2234
2981
|
await this._resourceLoader.reload();
|
|
2982
|
+
// Activate tools newly added to defaultTools. Removed ones stay active, and tools disabled
|
|
2983
|
+
// during the session stay disabled unless the setting newly adds them.
|
|
2984
|
+
const addedDefaultTools = getDefaultTools().filter((name) => !previousDefaultTools.has(name));
|
|
2985
|
+
// Tools the new extensions register later, such as MCP tools, are pending until then.
|
|
2986
|
+
for (const name of this.getActiveToolNames())
|
|
2987
|
+
this._pendingToolNames.add(name);
|
|
2235
2988
|
this._buildRuntime({
|
|
2236
|
-
activeToolNames: this.getActiveToolNames(),
|
|
2989
|
+
activeToolNames: [...this.getActiveToolNames(), ...addedDefaultTools],
|
|
2237
2990
|
flagValues: previousFlagValues,
|
|
2238
2991
|
includeAllExtensionTools: true,
|
|
2239
2992
|
});
|
|
@@ -2244,6 +2997,7 @@ export class AgentSession {
|
|
|
2244
2997
|
if (hasBindings) {
|
|
2245
2998
|
await options?.beforeSessionStart?.();
|
|
2246
2999
|
await this._extensionRunner.emit({ type: "session_start", reason: "reload" });
|
|
3000
|
+
this._extensionRunner.reportUnhandledMcpServers();
|
|
2247
3001
|
await this.extendResourcesFromExtensions("reload");
|
|
2248
3002
|
}
|
|
2249
3003
|
}
|
|
@@ -2256,7 +3010,7 @@ export class AgentSession {
|
|
|
2256
3010
|
*/
|
|
2257
3011
|
_isRetryableError(message) {
|
|
2258
3012
|
// Context overflow is handled by compaction, not retry.
|
|
2259
|
-
if (isContextOverflow(message, this.model?.contextWindow ?? 0))
|
|
3013
|
+
if (isContextOverflow(message, (this._modelForMessage(message) ?? this.model)?.contextWindow ?? 0))
|
|
2260
3014
|
return false;
|
|
2261
3015
|
return isRetryableAssistantError(message);
|
|
2262
3016
|
}
|
|
@@ -2288,6 +3042,18 @@ export class AgentSession {
|
|
|
2288
3042
|
},
|
|
2289
3043
|
};
|
|
2290
3044
|
}
|
|
3045
|
+
_finishCancelledRetry() {
|
|
3046
|
+
if (this._retryAttempt === 0)
|
|
3047
|
+
return;
|
|
3048
|
+
const attempt = this._retryAttempt;
|
|
3049
|
+
this._retryAttempt = 0;
|
|
3050
|
+
this._emit({
|
|
3051
|
+
type: "auto_retry_end",
|
|
3052
|
+
success: false,
|
|
3053
|
+
attempt,
|
|
3054
|
+
finalError: "Retry cancelled",
|
|
3055
|
+
});
|
|
3056
|
+
}
|
|
2291
3057
|
/**
|
|
2292
3058
|
* Prepare a retryable error for continuation with exponential backoff.
|
|
2293
3059
|
* @returns true if the caller should continue the agent, false otherwise
|
|
@@ -2311,11 +3077,8 @@ export class AgentSession {
|
|
|
2311
3077
|
delayMs,
|
|
2312
3078
|
errorMessage: message.errorMessage || "Unknown error",
|
|
2313
3079
|
});
|
|
2314
|
-
//
|
|
2315
|
-
|
|
2316
|
-
if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
|
|
2317
|
-
this.agent.state.messages = messages.slice(0, -1);
|
|
2318
|
-
}
|
|
3080
|
+
// Keep the failed attempt in raw history while durably omitting it from model projection.
|
|
3081
|
+
this._omitRecoveryAttempt(message);
|
|
2319
3082
|
// Wait with exponential backoff (abortable)
|
|
2320
3083
|
this._retryAbortController = new AbortController();
|
|
2321
3084
|
try {
|
|
@@ -2323,14 +3086,7 @@ export class AgentSession {
|
|
|
2323
3086
|
}
|
|
2324
3087
|
catch {
|
|
2325
3088
|
// Aborted during sleep - emit end event so UI can clean up
|
|
2326
|
-
|
|
2327
|
-
this._retryAttempt = 0;
|
|
2328
|
-
this._emit({
|
|
2329
|
-
type: "auto_retry_end",
|
|
2330
|
-
success: false,
|
|
2331
|
-
attempt,
|
|
2332
|
-
finalError: "Retry cancelled",
|
|
2333
|
-
});
|
|
3089
|
+
this._finishCancelledRetry();
|
|
2334
3090
|
return false;
|
|
2335
3091
|
}
|
|
2336
3092
|
finally {
|
|
@@ -2414,10 +3170,8 @@ export class AgentSession {
|
|
|
2414
3170
|
this._pendingBashMessages.push(bashMessage);
|
|
2415
3171
|
}
|
|
2416
3172
|
else {
|
|
2417
|
-
// Add to agent state immediately
|
|
2418
|
-
this.agent.state.messages.push(bashMessage);
|
|
2419
|
-
// Save to session
|
|
2420
3173
|
this.sessionManager.appendMessage(bashMessage);
|
|
3174
|
+
this._refreshFinalizedContext();
|
|
2421
3175
|
}
|
|
2422
3176
|
}
|
|
2423
3177
|
/**
|
|
@@ -2444,12 +3198,10 @@ export class AgentSession {
|
|
|
2444
3198
|
if (this._pendingBashMessages.length === 0)
|
|
2445
3199
|
return;
|
|
2446
3200
|
for (const bashMessage of this._pendingBashMessages) {
|
|
2447
|
-
// Add to agent state
|
|
2448
|
-
this.agent.state.messages.push(bashMessage);
|
|
2449
|
-
// Save to session
|
|
2450
3201
|
this.sessionManager.appendMessage(bashMessage);
|
|
2451
3202
|
}
|
|
2452
3203
|
this._pendingBashMessages = [];
|
|
3204
|
+
this._refreshFinalizedContext();
|
|
2453
3205
|
}
|
|
2454
3206
|
// =========================================================================
|
|
2455
3207
|
// Session Management
|
|
@@ -2548,15 +3300,11 @@ export class AgentSession {
|
|
|
2548
3300
|
let summaryDetails;
|
|
2549
3301
|
let summaryUsage;
|
|
2550
3302
|
if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
|
|
2551
|
-
const
|
|
2552
|
-
const { model: requestModel, apiKey, headers, env } = await this._getSummarizationRequestAuth(model);
|
|
3303
|
+
const signal = this._branchSummaryAbortController.signal;
|
|
2553
3304
|
const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
|
|
2554
3305
|
const result = await generateBranchSummary(entriesToSummarize, {
|
|
2555
|
-
model
|
|
2556
|
-
|
|
2557
|
-
headers,
|
|
2558
|
-
env,
|
|
2559
|
-
signal: this._branchSummaryAbortController.signal,
|
|
3306
|
+
...(await this._getSummarizationRequestAuth(this.model, signal)),
|
|
3307
|
+
signal,
|
|
2560
3308
|
customInstructions,
|
|
2561
3309
|
replaceInstructions,
|
|
2562
3310
|
reserveTokens: branchSummarySettings.reserveTokens,
|
|
@@ -2623,9 +3371,9 @@ export class AgentSession {
|
|
|
2623
3371
|
if (label && !summaryText) {
|
|
2624
3372
|
this.sessionManager.appendLabelChange(targetId, label);
|
|
2625
3373
|
}
|
|
2626
|
-
// Update
|
|
2627
|
-
|
|
2628
|
-
this.
|
|
3374
|
+
// Update finalized context from the canonical session projection.
|
|
3375
|
+
this._refreshFinalizedContext();
|
|
3376
|
+
this._restoreToolsFromTranscript();
|
|
2629
3377
|
// Emit session_tree event
|
|
2630
3378
|
await this._extensionRunner.emit({
|
|
2631
3379
|
type: "session_tree",
|
|
@@ -2673,7 +3421,10 @@ export class AgentSession {
|
|
|
2673
3421
|
let toolCalls = 0;
|
|
2674
3422
|
const usageTotals = createUsageTotals();
|
|
2675
3423
|
for (const entry of this.sessionManager.getEntries()) {
|
|
2676
|
-
if (
|
|
3424
|
+
if (entry.type === "usage") {
|
|
3425
|
+
addUsageToTotals(usageTotals, entry.usage);
|
|
3426
|
+
}
|
|
3427
|
+
else if ((entry.type === "branch_summary" || entry.type === "compaction") && entry.usage) {
|
|
2677
3428
|
addUsageToTotals(usageTotals, entry.usage);
|
|
2678
3429
|
}
|
|
2679
3430
|
if (entry.type !== "message")
|
|
@@ -2718,7 +3469,7 @@ export class AgentSession {
|
|
|
2718
3469
|
};
|
|
2719
3470
|
}
|
|
2720
3471
|
getContextUsage() {
|
|
2721
|
-
const model = this.
|
|
3472
|
+
const model = this._limitsModel();
|
|
2722
3473
|
if (!model)
|
|
2723
3474
|
return undefined;
|
|
2724
3475
|
const contextWindow = model.contextWindow ?? 0;
|
|
@@ -2727,30 +3478,24 @@ export class AgentSession {
|
|
|
2727
3478
|
// After compaction, the last assistant usage reflects pre-compaction context size.
|
|
2728
3479
|
// We can only trust usage from an assistant that responded after the latest compaction.
|
|
2729
3480
|
// If no such assistant exists, context token count is unknown until the next LLM response.
|
|
2730
|
-
const
|
|
2731
|
-
const
|
|
3481
|
+
const projection = this.sessionManager.buildSessionProjection();
|
|
3482
|
+
const branch = this.sessionManager.getBranch();
|
|
3483
|
+
const latestCompaction = getLatestCompactionEntry(branch);
|
|
2732
3484
|
if (latestCompaction) {
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
break;
|
|
2745
|
-
}
|
|
2746
|
-
}
|
|
2747
|
-
}
|
|
2748
|
-
}
|
|
2749
|
-
if (!hasPostCompactionUsage) {
|
|
3485
|
+
const projectedAssistants = new Set(projection.entries.flatMap((entry) => entry.messages.some((message) => message.role === "assistant" &&
|
|
3486
|
+
message.stopReason !== "aborted" &&
|
|
3487
|
+
message.stopReason !== "error" &&
|
|
3488
|
+
calculateContextTokens(message.usage) > 0)
|
|
3489
|
+
? [entry.sourceEntry.id]
|
|
3490
|
+
: []));
|
|
3491
|
+
const compactionIndex = branch.findIndex((entry) => entry.id === latestCompaction.id);
|
|
3492
|
+
const hasPostCompactionUsage = branch
|
|
3493
|
+
.slice(compactionIndex + 1)
|
|
3494
|
+
.some((entry) => projectedAssistants.has(entry.id));
|
|
3495
|
+
if (!hasPostCompactionUsage)
|
|
2750
3496
|
return { tokens: null, contextWindow, percent: null };
|
|
2751
|
-
}
|
|
2752
3497
|
}
|
|
2753
|
-
const estimate =
|
|
3498
|
+
const estimate = estimateProjectedContextTokens(projection, branch);
|
|
2754
3499
|
const percent = (estimate.tokens / contextWindow) * 100;
|
|
2755
3500
|
return {
|
|
2756
3501
|
tokens: estimate.tokens,
|
|
@@ -2787,6 +3532,25 @@ export class AgentSession {
|
|
|
2787
3532
|
exportToJsonl(outputPath) {
|
|
2788
3533
|
return exportSessionToJsonl(this.sessionManager, outputPath);
|
|
2789
3534
|
}
|
|
3535
|
+
/**
|
|
3536
|
+
* Ask the current model to describe what went wrong in this session for a bug report.
|
|
3537
|
+
* Used when the user declines to share the transcript itself.
|
|
3538
|
+
*/
|
|
3539
|
+
async summarizeForBugReport(options) {
|
|
3540
|
+
const model = this.model;
|
|
3541
|
+
if (!model) {
|
|
3542
|
+
throw new Error("No model selected");
|
|
3543
|
+
}
|
|
3544
|
+
return generateBugReportSummary({
|
|
3545
|
+
...(await this._getSummarizationRequestAuth(model, options.signal)),
|
|
3546
|
+
messages: this.messages,
|
|
3547
|
+
hint: options.hint,
|
|
3548
|
+
signal: options.signal,
|
|
3549
|
+
streamFn: this.agent.streamFunction,
|
|
3550
|
+
retry: this.settingsManager.getRetrySettings(),
|
|
3551
|
+
sessionId: this.sessionId,
|
|
3552
|
+
});
|
|
3553
|
+
}
|
|
2790
3554
|
// =========================================================================
|
|
2791
3555
|
// Utilities
|
|
2792
3556
|
// =========================================================================
|