@draht/coding-agent 2026.5.12 → 2026.7.7-1
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 +47 -0
- package/README.md +1 -4
- package/bin/draht-tools.cjs +3756 -1
- package/dist/bun/cli.d.ts.map +1 -1
- package/dist/bun/cli.js +4 -2
- package/dist/bun/cli.js.map +1 -1
- package/dist/bun/register-bedrock.d.ts.map +1 -1
- package/dist/bun/register-bedrock.js +1 -1
- package/dist/bun/register-bedrock.js.map +1 -1
- package/dist/bun/restore-sandbox-env.d.ts +17 -0
- package/dist/bun/restore-sandbox-env.d.ts.map +1 -0
- package/dist/bun/restore-sandbox-env.js +36 -0
- package/dist/bun/restore-sandbox-env.js.map +1 -0
- package/dist/cli/args.d.ts +9 -4
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +91 -38
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/config-selector.d.ts +5 -3
- package/dist/cli/config-selector.d.ts.map +1 -1
- package/dist/cli/config-selector.js +1 -1
- package/dist/cli/config-selector.js.map +1 -1
- package/dist/cli/file-processor.d.ts.map +1 -1
- package/dist/cli/file-processor.js +13 -26
- 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 +1 -1
- package/dist/cli/list-models.d.ts.map +1 -1
- package/dist/cli/list-models.js +7 -1
- package/dist/cli/list-models.js.map +1 -1
- package/dist/cli/project-trust.d.ts +10 -0
- package/dist/cli/project-trust.d.ts.map +1 -0
- package/dist/cli/project-trust.js +48 -0
- package/dist/cli/project-trust.js.map +1 -0
- package/dist/cli/session-picker.d.ts +3 -2
- package/dist/cli/session-picker.d.ts.map +1 -1
- package/dist/cli/session-picker.js +5 -4
- package/dist/cli/session-picker.js.map +1 -1
- package/dist/cli/startup-ui.d.ts +20 -0
- package/dist/cli/startup-ui.d.ts.map +1 -0
- package/dist/cli/startup-ui.js +184 -0
- package/dist/cli/startup-ui.js.map +1 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +7 -4
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +27 -13
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +284 -63
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +45 -9
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +100 -33
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +6 -4
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +7 -4
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +55 -33
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +560 -492
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-guidance.d.ts +5 -0
- package/dist/core/auth-guidance.d.ts.map +1 -0
- package/dist/core/auth-guidance.js +21 -0
- package/dist/core/auth-guidance.js.map +1 -0
- package/dist/core/auth-storage.d.ts +21 -13
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +48 -28
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/bash-executor.d.ts +1 -15
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +10 -24
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/builtins/subagent.d.ts.map +1 -1
- package/dist/core/builtins/subagent.js +1 -2
- package/dist/core/builtins/subagent.js.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts +9 -5
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +10 -4
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +8 -7
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +56 -47
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/index.d.ts +3 -3
- package/dist/core/compaction/index.d.ts.map +1 -1
- package/dist/core/compaction/index.js.map +1 -1
- package/dist/core/compaction/utils.d.ts +1 -1
- package/dist/core/compaction/utils.d.ts.map +1 -1
- package/dist/core/compaction/utils.js +1 -1
- package/dist/core/compaction/utils.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 +2 -0
- package/dist/core/experimental.d.ts.map +1 -0
- package/dist/core/experimental.js +4 -0
- package/dist/core/experimental.js.map +1 -0
- package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
- package/dist/core/export-html/ansi-to-html.js +1 -1
- package/dist/core/export-html/ansi-to-html.js.map +1 -1
- package/dist/core/export-html/index.d.ts +1 -1
- package/dist/core/export-html/index.d.ts.map +1 -1
- package/dist/core/export-html/index.js +13 -11
- package/dist/core/export-html/index.js.map +1 -1
- package/dist/core/export-html/template.css +69 -4
- package/dist/core/export-html/template.js +231 -57
- package/dist/core/export-html/tool-renderer.d.ts +0 -6
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +15 -2
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/export-html/vendor/marked.min.js +75 -3
- package/dist/core/extensions/index.d.ts +8 -8
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts +5 -6
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +98 -43
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +31 -12
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +248 -33
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +191 -36
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/extensions/wrapper.d.ts.map +1 -1
- package/dist/core/extensions/wrapper.js +2 -2
- package/dist/core/extensions/wrapper.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts +7 -1
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js +78 -54
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/http-dispatcher.d.ts +22 -0
- package/dist/core/http-dispatcher.d.ts.map +1 -0
- package/dist/core/http-dispatcher.js +91 -0
- package/dist/core/http-dispatcher.js.map +1 -0
- package/dist/core/index.d.ts +9 -8
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +2 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/keybindings.d.ts +67 -2
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +59 -7
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/model-registry.d.ts +24 -5
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +188 -51
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts +12 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +84 -39
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/output-guard.d.ts +1 -0
- package/dist/core/output-guard.d.ts.map +1 -1
- package/dist/core/output-guard.js +52 -22
- package/dist/core/output-guard.js.map +1 -1
- package/dist/core/package-manager.d.ts +22 -4
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +455 -157
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/project-trust.d.ts +15 -0
- package/dist/core/project-trust.d.ts.map +1 -0
- package/dist/core/project-trust.js +59 -0
- package/dist/core/project-trust.js.map +1 -0
- package/dist/core/prompt-templates.d.ts +13 -11
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +67 -76
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/provider-attribution.d.ts +4 -0
- package/dist/core/provider-attribution.d.ts.map +1 -0
- package/dist/core/provider-attribution.js +72 -0
- package/dist/core/provider-attribution.js.map +1 -0
- package/dist/core/provider-display-names.d.ts +2 -0
- package/dist/core/provider-display-names.d.ts.map +1 -0
- package/dist/core/provider-display-names.js +36 -0
- package/dist/core/provider-display-names.js.map +1 -0
- package/dist/core/resolve-config-value.d.ts +13 -6
- package/dist/core/resolve-config-value.d.ts.map +1 -1
- package/dist/core/resolve-config-value.js +143 -22
- package/dist/core/resolve-config-value.js.map +1 -1
- package/dist/core/resource-loader.d.ts +36 -15
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +178 -79
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/sdk.d.ts +34 -18
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +47 -16
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts +32 -14
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +366 -209
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +62 -6
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +230 -40
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/skills.d.ts +10 -10
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +13 -35
- package/dist/core/skills.js.map +1 -1
- package/dist/core/slash-commands.d.ts +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +7 -4
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/source-info.d.ts +1 -1
- package/dist/core/source-info.d.ts.map +1 -1
- package/dist/core/source-info.js.map +1 -1
- package/dist/core/system-prompt.d.ts +4 -4
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +20 -16
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/telemetry.d.ts +3 -0
- package/dist/core/telemetry.d.ts.map +1 -0
- package/dist/core/telemetry.js +9 -0
- package/dist/core/telemetry.js.map +1 -0
- package/dist/core/timings.d.ts +4 -2
- package/dist/core/timings.d.ts.map +1 -1
- package/dist/core/timings.js +24 -14
- package/dist/core/timings.js.map +1 -1
- package/dist/core/tools/bash.d.ts +11 -16
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +187 -178
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts +26 -5
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +110 -23
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts +22 -24
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +201 -113
- 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 +27 -12
- package/dist/core/tools/file-mutation-queue.js.map +1 -1
- package/dist/core/tools/find.d.ts +7 -18
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +148 -101
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts +11 -30
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +23 -12
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts +26 -101
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +78 -52
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/ls.d.ts +6 -15
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +12 -17
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +52 -0
- package/dist/core/tools/output-accumulator.d.ts.map +1 -0
- package/dist/core/tools/output-accumulator.js +184 -0
- package/dist/core/tools/output-accumulator.js.map +1 -0
- package/dist/core/tools/path-utils.d.ts +2 -0
- package/dist/core/tools/path-utils.d.ts.map +1 -1
- package/dist/core/tools/path-utils.js +40 -22
- package/dist/core/tools/path-utils.js.map +1 -1
- package/dist/core/tools/read.d.ts +7 -18
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +103 -52
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/render-utils.d.ts +5 -2
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/render-utils.js +18 -2
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js +2 -0
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/tools/truncate.d.ts.map +1 -1
- package/dist/core/tools/truncate.js +12 -2
- package/dist/core/tools/truncate.js.map +1 -1
- package/dist/core/tools/write.d.ts +5 -14
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +27 -46
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/trust-manager.d.ts +36 -0
- package/dist/core/trust-manager.d.ts.map +1 -0
- package/dist/core/trust-manager.js +202 -0
- package/dist/core/trust-manager.js.map +1 -0
- package/dist/index.d.ts +33 -29
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -9
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts +5 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +208 -93
- package/dist/main.js.map +1 -1
- package/dist/migrations.d.ts +2 -2
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +4 -4
- package/dist/migrations.js.map +1 -1
- package/dist/modes/index.d.ts +5 -5
- package/dist/modes/index.d.ts.map +1 -1
- package/dist/modes/index.js.map +1 -1
- package/dist/modes/interactive/assets/clankolas.png +0 -0
- package/dist/modes/interactive/components/assistant-message.d.ts +5 -1
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +37 -15
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/bash-execution.d.ts +1 -1
- package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js +3 -3
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.js +3 -0
- package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
- package/dist/modes/interactive/components/config-selector.d.ts +36 -5
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector.js +318 -36
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/countdown-timer.d.ts +2 -2
- package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -1
- package/dist/modes/interactive/components/countdown-timer.js +2 -2
- package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-editor.js.map +1 -1
- package/dist/modes/interactive/components/custom-entry.d.ts +19 -0
- package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -0
- package/dist/modes/interactive/components/custom-entry.js +52 -0
- package/dist/modes/interactive/components/custom-entry.js.map +1 -0
- package/dist/modes/interactive/components/custom-message.d.ts +2 -2
- package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-message.js.map +1 -1
- package/dist/modes/interactive/components/diff.d.ts.map +1 -1
- package/dist/modes/interactive/components/diff.js.map +1 -1
- package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -1
- package/dist/modes/interactive/components/earendil-announcement.js.map +1 -1
- package/dist/modes/interactive/components/extension-editor.d.ts +3 -1
- package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-editor.js +26 -9
- package/dist/modes/interactive/components/extension-editor.js.map +1 -1
- package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-input.js.map +1 -1
- package/dist/modes/interactive/components/extension-selector.d.ts +2 -0
- package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-selector.js +8 -3
- package/dist/modes/interactive/components/extension-selector.js.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.d.ts +25 -0
- package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -0
- package/dist/modes/interactive/components/first-time-setup.js +103 -0
- package/dist/modes/interactive/components/first-time-setup.js.map +1 -0
- package/dist/modes/interactive/components/footer.d.ts +4 -3
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +27 -7
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/index.d.ts +33 -31
- package/dist/modes/interactive/components/index.d.ts.map +1 -1
- package/dist/modes/interactive/components/index.js +2 -0
- package/dist/modes/interactive/components/index.js.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts +5 -0
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.js +19 -5
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +12 -2
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +45 -11
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +2 -2
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +10 -6
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +18 -6
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +93 -25
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts +5 -12
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +49 -31
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +2 -2
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +33 -14
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +17 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +301 -20
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.d.ts +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
- package/dist/modes/interactive/components/status-indicator.d.ts +28 -0
- package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -0
- package/dist/modes/interactive/components/status-indicator.js +60 -0
- package/dist/modes/interactive/components/status-indicator.js.map +1 -0
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +1 -1
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +6 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +57 -14
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector.js +137 -13
- package/dist/modes/interactive/components/tree-selector.js.map +1 -1
- package/dist/modes/interactive/components/trust-selector.d.ts +23 -0
- package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/trust-selector.js +91 -0
- package/dist/modes/interactive/components/trust-selector.js.map +1 -0
- package/dist/modes/interactive/components/user-message-selector.d.ts +2 -2
- package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.js +8 -7
- package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message.d.ts +6 -1
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message.js +22 -8
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +76 -19
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +1294 -494
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/model-search.d.ts +12 -0
- package/dist/modes/interactive/model-search.d.ts.map +1 -0
- package/dist/modes/interactive/model-search.js +15 -0
- package/dist/modes/interactive/model-search.js.map +1 -0
- package/dist/modes/interactive/theme/dark.json +5 -4
- package/dist/modes/interactive/theme/light.json +5 -4
- package/dist/modes/interactive/theme/theme-controller.d.ts +29 -0
- package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -0
- package/dist/modes/interactive/theme/theme-controller.js +102 -0
- package/dist/modes/interactive/theme/theme-controller.js.map +1 -0
- package/dist/modes/interactive/theme/theme-schema.json +2 -1
- package/dist/modes/interactive/theme/theme.d.ts +41 -3
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +183 -106
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +40 -20
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +30 -5
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +87 -8
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts +2 -2
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +113 -31
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +42 -4
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/package-manager-cli.d.ts +6 -2
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +504 -25
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/prompts/agents/build.md +38 -0
- package/dist/prompts/agents/plan.md +36 -0
- package/dist/prompts/agents/verify.md +36 -4
- package/dist/prompts/commands/brainstorm.md +162 -0
- package/dist/prompts/commands/discuss-phase.md +1 -1
- package/dist/prompts/commands/execute-phase.md +4 -1
- package/dist/prompts/commands/fix.md +12 -0
- package/dist/prompts/commands/init-project.md +1 -0
- package/dist/prompts/commands/map-codebase.md +15 -1
- package/dist/prompts/commands/new-project.md +1 -0
- package/dist/prompts/commands/next-milestone.md +2 -0
- package/dist/prompts/commands/orchestrate.md +4 -4
- package/dist/prompts/commands/plan-phase.md +5 -0
- package/dist/prompts/commands/quick.md +4 -0
- package/dist/prompts/commands/review.md +4 -1
- package/dist/prompts/commands/verify-work.md +10 -8
- package/dist/rpc-entry.d.ts +3 -0
- package/dist/rpc-entry.d.ts.map +1 -0
- package/dist/rpc-entry.js +10 -0
- package/dist/rpc-entry.js.map +1 -0
- package/dist/utils/ansi.d.ts +2 -0
- package/dist/utils/ansi.d.ts.map +1 -0
- package/dist/utils/ansi.js +52 -0
- package/dist/utils/ansi.js.map +1 -0
- package/dist/utils/changelog.d.ts +2 -1
- package/dist/utils/changelog.d.ts.map +1 -1
- package/dist/utils/changelog.js +78 -0
- package/dist/utils/changelog.js.map +1 -1
- package/dist/utils/child-process.d.ts +12 -5
- package/dist/utils/child-process.d.ts.map +1 -1
- package/dist/utils/child-process.js +33 -5
- package/dist/utils/child-process.js.map +1 -1
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +2 -2
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/clipboard-native.d.ts +3 -1
- package/dist/utils/clipboard-native.d.ts.map +1 -1
- package/dist/utils/clipboard-native.js +14 -8
- package/dist/utils/clipboard-native.js.map +1 -1
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +84 -45
- package/dist/utils/clipboard.js.map +1 -1
- package/dist/utils/deprecation.d.ts +4 -0
- package/dist/utils/deprecation.d.ts.map +1 -0
- package/dist/utils/deprecation.js +13 -0
- package/dist/utils/deprecation.js.map +1 -0
- package/dist/utils/exif-orientation.d.ts +1 -1
- package/dist/utils/exif-orientation.d.ts.map +1 -1
- package/dist/utils/exif-orientation.js.map +1 -1
- package/dist/utils/fs-watch.d.ts +5 -0
- package/dist/utils/fs-watch.d.ts.map +1 -0
- package/dist/utils/fs-watch.js +25 -0
- package/dist/utils/fs-watch.js.map +1 -0
- package/dist/utils/git.d.ts.map +1 -1
- package/dist/utils/git.js +54 -22
- package/dist/utils/git.js.map +1 -1
- package/dist/utils/html.d.ts +7 -0
- package/dist/utils/html.d.ts.map +1 -0
- package/dist/utils/html.js +40 -0
- package/dist/utils/html.js.map +1 -0
- package/dist/utils/image-convert.d.ts +1 -0
- package/dist/utils/image-convert.d.ts.map +1 -1
- package/dist/utils/image-convert.js +21 -15
- package/dist/utils/image-convert.js.map +1 -1
- package/dist/utils/image-process.d.ts +18 -0
- package/dist/utils/image-process.d.ts.map +1 -0
- package/dist/utils/image-process.js +83 -0
- package/dist/utils/image-process.js.map +1 -0
- package/dist/utils/image-resize-core.d.ts +30 -0
- package/dist/utils/image-resize-core.d.ts.map +1 -0
- package/dist/utils/image-resize-core.js +124 -0
- package/dist/utils/image-resize-core.js.map +1 -0
- package/dist/utils/image-resize-worker.d.ts +2 -0
- package/dist/utils/image-resize-worker.d.ts.map +1 -0
- package/dist/utils/image-resize-worker.js +31 -0
- package/dist/utils/image-resize-worker.js.map +1 -0
- package/dist/utils/image-resize.d.ts +7 -27
- package/dist/utils/image-resize.d.ts.map +1 -1
- package/dist/utils/image-resize.js +75 -115
- package/dist/utils/image-resize.js.map +1 -1
- package/dist/utils/json.d.ts +3 -0
- package/dist/utils/json.d.ts.map +1 -0
- package/dist/utils/json.js +7 -0
- package/dist/utils/json.js.map +1 -0
- package/dist/utils/mime.d.ts +1 -0
- package/dist/utils/mime.d.ts.map +1 -1
- package/dist/utils/mime.js +100 -16
- package/dist/utils/mime.js.map +1 -1
- package/dist/utils/open-browser.d.ts +9 -0
- package/dist/utils/open-browser.d.ts.map +1 -0
- package/dist/utils/open-browser.js +22 -0
- package/dist/utils/open-browser.js.map +1 -0
- package/dist/utils/paths.d.ts +25 -1
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +75 -2
- package/dist/utils/paths.js.map +1 -1
- package/dist/utils/pi-user-agent.d.ts +2 -0
- package/dist/utils/pi-user-agent.d.ts.map +1 -0
- package/dist/utils/pi-user-agent.js +5 -0
- package/dist/utils/pi-user-agent.js.map +1 -0
- package/dist/utils/shell.d.ts +11 -6
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +42 -26
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/syntax-highlight.d.ts +12 -0
- package/dist/utils/syntax-highlight.d.ts.map +1 -0
- package/dist/utils/syntax-highlight.js +118 -0
- package/dist/utils/syntax-highlight.js.map +1 -0
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +86 -10
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/version-check.d.ts +15 -0
- package/dist/utils/version-check.d.ts.map +1 -0
- package/dist/utils/version-check.js +59 -0
- package/dist/utils/version-check.js.map +1 -0
- package/dist/utils/windows-self-update.d.ts +3 -0
- package/dist/utils/windows-self-update.d.ts.map +1 -0
- package/dist/utils/windows-self-update.js +77 -0
- package/dist/utils/windows-self-update.js.map +1 -0
- package/docs/compaction.md +12 -12
- package/docs/containerization.md +111 -0
- package/docs/custom-provider.md +187 -47
- package/docs/development.md +5 -5
- package/docs/docs.json +156 -0
- package/docs/extensions.md +520 -79
- package/docs/index.md +82 -0
- package/docs/json.md +4 -4
- package/docs/keybindings.md +24 -2
- package/docs/models.md +119 -17
- package/docs/packages.md +19 -11
- package/docs/prompt-templates.md +30 -2
- package/docs/providers.md +85 -23
- package/docs/quickstart.md +165 -0
- package/docs/rpc.md +99 -10
- package/docs/sdk.md +118 -50
- package/docs/security.md +55 -0
- package/docs/{session.md → session-format.md} +29 -19
- package/docs/sessions.md +145 -0
- package/docs/settings.md +71 -11
- package/docs/skills.md +16 -17
- package/docs/terminal-setup.md +44 -2
- package/docs/termux.md +4 -4
- package/docs/themes.md +3 -3
- package/docs/tmux.md +4 -2
- package/docs/tui.md +44 -4
- package/docs/usage.md +305 -0
- package/examples/extensions/README.md +1 -0
- package/examples/extensions/border-status-editor.ts +145 -0
- package/examples/extensions/built-in-tool-renderer.ts +3 -0
- package/examples/extensions/custom-compaction.ts +2 -1
- package/examples/extensions/custom-header.ts +1 -1
- package/examples/extensions/custom-provider-anthropic/index.ts +2 -2
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +2 -2
- package/examples/extensions/custom-provider-gitlab-duo/index.ts +63 -8
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/test.ts +2 -2
- package/examples/extensions/doom-overlay/doom-component.ts +2 -2
- package/examples/extensions/doom-overlay/index.ts +1 -1
- package/examples/extensions/dynamic-resources/dynamic.json +1 -1
- package/examples/extensions/dynamic-tools.ts +2 -2
- package/examples/extensions/entry-renderer.ts +41 -0
- package/examples/extensions/git-merge-and-resolve.ts +115 -0
- package/examples/extensions/github-issue-autocomplete.ts +185 -0
- package/examples/extensions/gondolin/index.ts +531 -0
- package/examples/extensions/gondolin/package-lock.json +185 -0
- package/examples/extensions/gondolin/package.json +19 -0
- package/examples/extensions/handoff.ts +52 -14
- package/examples/extensions/input-transform-streaming.ts +39 -0
- package/examples/extensions/interactive-shell.ts +1 -1
- package/examples/extensions/notify.ts +2 -9
- package/examples/extensions/overlay-qa-tests.ts +240 -138
- package/examples/extensions/overlay-test.ts +7 -4
- package/examples/extensions/plan-mode/index.ts +87 -37
- package/examples/extensions/plan-mode/utils.ts +1 -1
- package/examples/extensions/preset.ts +46 -7
- package/examples/extensions/project-trust.ts +64 -0
- package/examples/extensions/prompt-customizer.ts +97 -0
- package/examples/extensions/provider-payload.ts +8 -4
- package/examples/extensions/qna.ts +3 -3
- package/examples/extensions/question.ts +34 -20
- package/examples/extensions/questionnaire.ts +43 -30
- package/examples/extensions/reload-runtime.ts +1 -1
- package/examples/extensions/sandbox/index.ts +6 -6
- package/examples/extensions/sandbox/package-lock.json +5 -5
- package/examples/extensions/sandbox/package.json +2 -2
- package/examples/extensions/shutdown-command.ts +1 -1
- package/examples/extensions/snake.ts +1 -1
- package/examples/extensions/space-invaders.ts +1 -1
- package/examples/extensions/structured-output.ts +65 -0
- package/examples/extensions/subagent/agents.ts +2 -2
- package/examples/extensions/subagent/index.ts +58 -29
- package/examples/extensions/summarize.ts +3 -2
- package/examples/extensions/tic-tac-toe.ts +1008 -0
- package/examples/extensions/titlebar-spinner.ts +2 -2
- package/examples/extensions/todo.ts +2 -2
- package/examples/extensions/tool-override.ts +1 -1
- package/examples/extensions/tools.ts +5 -0
- package/examples/extensions/truncated-tool.ts +1 -1
- package/examples/extensions/with-deps/index.ts +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +3 -3
- package/examples/extensions/working-indicator.ts +123 -0
- package/examples/extensions/working-message-test.ts +25 -0
- package/examples/sdk/01-minimal.ts +14 -10
- package/examples/sdk/02-custom-model.ts +13 -9
- package/examples/sdk/03-custom-prompt.ts +32 -17
- package/examples/sdk/04-skills.ts +5 -2
- package/examples/sdk/05-tools.ts +23 -31
- package/examples/sdk/06-extensions.ts +14 -8
- package/examples/sdk/07-context-files.ts +5 -3
- package/examples/sdk/08-prompt-templates.ts +5 -2
- package/examples/sdk/09-api-keys-and-oauth.ts +8 -4
- package/examples/sdk/10-settings.ts +8 -6
- package/examples/sdk/11-sessions.ts +4 -0
- package/examples/sdk/12-full-control.ts +15 -19
- package/package.json +22 -16
- package/prompts/agents/build.md +38 -0
- package/prompts/agents/plan.md +36 -0
- package/prompts/agents/verify.md +36 -4
- package/prompts/commands/brainstorm.md +162 -0
- package/prompts/commands/discuss-phase.md +1 -1
- package/prompts/commands/execute-phase.md +4 -1
- package/prompts/commands/fix.md +12 -0
- package/prompts/commands/init-project.md +1 -0
- package/prompts/commands/map-codebase.md +15 -1
- package/prompts/commands/new-project.md +1 -0
- package/prompts/commands/next-milestone.md +2 -0
- package/prompts/commands/orchestrate.md +4 -4
- package/prompts/commands/plan-phase.md +5 -0
- package/prompts/commands/quick.md +4 -0
- package/prompts/commands/review.md +4 -1
- package/prompts/commands/verify-work.md +10 -8
|
@@ -13,25 +13,27 @@
|
|
|
13
13
|
* Modes use this class and add their own I/O layer on top.
|
|
14
14
|
*/
|
|
15
15
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
16
|
-
import { basename, dirname
|
|
17
|
-
import { isContextOverflow, modelsAreEqual, resetApiProviders,
|
|
18
|
-
import {
|
|
19
|
-
import { theme } from "../modes/interactive/theme/theme.js";
|
|
16
|
+
import { basename, dirname } from "node:path";
|
|
17
|
+
import { clampThinkingLevel, cleanupSessionResources, getSupportedThinkingLevels, isContextOverflow, isRetryableAssistantError, modelsAreEqual, resetApiProviders, streamSimple, } from "@draht/ai/compat";
|
|
18
|
+
import { getThemeByName, theme } from "../modes/interactive/theme/theme.js";
|
|
20
19
|
import { stripFrontmatter } from "../utils/frontmatter.js";
|
|
20
|
+
import { resolvePath } from "../utils/paths.js";
|
|
21
21
|
import { sleep } from "../utils/sleep.js";
|
|
22
|
+
import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.js";
|
|
22
23
|
import { executeBashWithOperations } from "./bash-executor.js";
|
|
23
|
-
import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
|
|
24
|
+
import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, estimateTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
|
|
24
25
|
import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
|
|
25
26
|
import { exportSessionToHtml } from "./export-html/index.js";
|
|
26
27
|
import { createToolHtmlRenderer } from "./export-html/tool-renderer.js";
|
|
27
28
|
import { ExtensionRunner, wrapRegisteredTools, } from "./extensions/index.js";
|
|
29
|
+
import { emitSessionShutdownEvent } from "./extensions/runner.js";
|
|
28
30
|
import { expandPromptTemplate } from "./prompt-templates.js";
|
|
29
31
|
import { CURRENT_SESSION_VERSION, getLatestCompactionEntry } from "./session-manager.js";
|
|
30
32
|
import { createSyntheticSourceInfo } from "./source-info.js";
|
|
31
33
|
import { buildSystemPrompt } from "./system-prompt.js";
|
|
32
34
|
import { createLocalBashOperations } from "./tools/bash.js";
|
|
33
35
|
import { createAllToolDefinitions } from "./tools/index.js";
|
|
34
|
-
import { createToolDefinitionFromAgentTool
|
|
36
|
+
import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";
|
|
35
37
|
/**
|
|
36
38
|
* Parse a skill block from message text.
|
|
37
39
|
* Returns null if the text doesn't contain a skill block.
|
|
@@ -47,15 +49,18 @@ export function parseSkillBlock(text) {
|
|
|
47
49
|
userMessage: match[4]?.trim() || undefined,
|
|
48
50
|
};
|
|
49
51
|
}
|
|
52
|
+
function estimateMessagesTokens(messages) {
|
|
53
|
+
let tokens = 0;
|
|
54
|
+
for (const message of messages) {
|
|
55
|
+
tokens += estimateTokens(message);
|
|
56
|
+
}
|
|
57
|
+
return tokens;
|
|
58
|
+
}
|
|
50
59
|
// ============================================================================
|
|
51
60
|
// Constants
|
|
52
61
|
// ============================================================================
|
|
53
62
|
/** Standard thinking levels */
|
|
54
63
|
const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high"];
|
|
55
|
-
/** Thinking levels including xhigh (for supported models) */
|
|
56
|
-
const THINKING_LEVELS_WITH_XHIGH = ["off", "minimal", "low", "medium", "high", "xhigh"];
|
|
57
|
-
/** Thinking levels including xhigh and max (Anthropic Opus only) */
|
|
58
|
-
const THINKING_LEVELS_WITH_MAX = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
59
64
|
// ============================================================================
|
|
60
65
|
// AgentSession Class
|
|
61
66
|
// ============================================================================
|
|
@@ -67,7 +72,6 @@ export class AgentSession {
|
|
|
67
72
|
// Event subscription state
|
|
68
73
|
_unsubscribeAgent;
|
|
69
74
|
_eventListeners = [];
|
|
70
|
-
_agentEventQueue = Promise.resolve();
|
|
71
75
|
/** Tracks pending steering messages for UI display. Removed when delivered. */
|
|
72
76
|
_steeringMessages = [];
|
|
73
77
|
/** Tracks pending follow-up messages for UI display. Removed when delivered. */
|
|
@@ -83,13 +87,11 @@ export class AgentSession {
|
|
|
83
87
|
// Retry state
|
|
84
88
|
_retryAbortController = undefined;
|
|
85
89
|
_retryAttempt = 0;
|
|
86
|
-
_retryPromise = undefined;
|
|
87
|
-
_retryResolve = undefined;
|
|
88
90
|
// Bash execution state
|
|
89
91
|
_bashAbortController = undefined;
|
|
90
92
|
_pendingBashMessages = [];
|
|
91
93
|
// Extension system
|
|
92
|
-
_extensionRunner
|
|
94
|
+
_extensionRunner;
|
|
93
95
|
_turnIndex = 0;
|
|
94
96
|
_resourceLoader;
|
|
95
97
|
_customTools;
|
|
@@ -97,10 +99,14 @@ export class AgentSession {
|
|
|
97
99
|
_cwd;
|
|
98
100
|
_extensionRunnerRef;
|
|
99
101
|
_initialActiveToolNames;
|
|
102
|
+
_allowedToolNames;
|
|
103
|
+
_excludedToolNames;
|
|
100
104
|
_baseToolsOverride;
|
|
101
105
|
_sessionStartEvent;
|
|
102
106
|
_extensionUIContext;
|
|
107
|
+
_extensionMode = "print";
|
|
103
108
|
_extensionCommandContextActions;
|
|
109
|
+
_extensionAbortHandler;
|
|
104
110
|
_extensionShutdownHandler;
|
|
105
111
|
_extensionErrorListener;
|
|
106
112
|
_extensionErrorUnsubscriber;
|
|
@@ -113,6 +119,8 @@ export class AgentSession {
|
|
|
113
119
|
_toolPromptGuidelines = new Map();
|
|
114
120
|
// Base system prompt (without extension appends) - used to apply fresh appends each turn
|
|
115
121
|
_baseSystemPrompt = "";
|
|
122
|
+
_baseSystemPromptOptions;
|
|
123
|
+
_systemPromptOverride;
|
|
116
124
|
constructor(config) {
|
|
117
125
|
this.agent = config.agent;
|
|
118
126
|
this.sessionManager = config.sessionManager;
|
|
@@ -124,12 +132,15 @@ export class AgentSession {
|
|
|
124
132
|
this._modelRegistry = config.modelRegistry;
|
|
125
133
|
this._extensionRunnerRef = config.extensionRunnerRef;
|
|
126
134
|
this._initialActiveToolNames = config.initialActiveToolNames;
|
|
135
|
+
this._allowedToolNames = config.allowedToolNames ? new Set(config.allowedToolNames) : undefined;
|
|
136
|
+
this._excludedToolNames = config.excludedToolNames ? new Set(config.excludedToolNames) : undefined;
|
|
127
137
|
this._baseToolsOverride = config.baseToolsOverride;
|
|
128
138
|
this._sessionStartEvent = config.sessionStartEvent ?? { type: "session_start", reason: "startup" };
|
|
129
139
|
// Always subscribe to agent events for internal handling
|
|
130
140
|
// (session persistence, extensions, auto-compaction, retry logic)
|
|
131
141
|
this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
|
|
132
142
|
this._installAgentToolHooks();
|
|
143
|
+
this._installAgentNextTurnRefresh();
|
|
133
144
|
this._buildRuntime({
|
|
134
145
|
activeToolNames: this._initialActiveToolNames,
|
|
135
146
|
includeAllExtensionTools: true,
|
|
@@ -142,10 +153,13 @@ export class AgentSession {
|
|
|
142
153
|
async _getRequiredRequestAuth(model) {
|
|
143
154
|
const result = await this._modelRegistry.getApiKeyAndHeaders(model);
|
|
144
155
|
if (!result.ok) {
|
|
156
|
+
if (result.error.startsWith("No API key found")) {
|
|
157
|
+
throw new Error(formatNoApiKeyFoundMessage(model.provider));
|
|
158
|
+
}
|
|
145
159
|
throw new Error(result.error);
|
|
146
160
|
}
|
|
147
161
|
if (result.apiKey) {
|
|
148
|
-
return { apiKey: result.apiKey, headers: result.headers };
|
|
162
|
+
return { apiKey: result.apiKey, headers: result.headers, env: result.env };
|
|
149
163
|
}
|
|
150
164
|
const isOAuth = this._modelRegistry.isUsingOAuth(model);
|
|
151
165
|
if (isOAuth) {
|
|
@@ -153,8 +167,14 @@ export class AgentSession {
|
|
|
153
167
|
`Credentials may have expired or network is unavailable. ` +
|
|
154
168
|
`Run '/login ${model.provider}' to re-authenticate.`);
|
|
155
169
|
}
|
|
156
|
-
throw new Error(
|
|
157
|
-
|
|
170
|
+
throw new Error(formatNoApiKeyFoundMessage(model.provider));
|
|
171
|
+
}
|
|
172
|
+
async _getCompactionRequestAuth(model) {
|
|
173
|
+
if (this.agent.streamFn === streamSimple) {
|
|
174
|
+
return this._getRequiredRequestAuth(model);
|
|
175
|
+
}
|
|
176
|
+
const result = await this._modelRegistry.getApiKeyAndHeaders(model);
|
|
177
|
+
return result.ok ? { apiKey: result.apiKey, headers: result.headers, env: result.env } : {};
|
|
158
178
|
}
|
|
159
179
|
/**
|
|
160
180
|
* Install tool hooks once on the Agent instance.
|
|
@@ -167,10 +187,9 @@ export class AgentSession {
|
|
|
167
187
|
_installAgentToolHooks() {
|
|
168
188
|
this.agent.beforeToolCall = async ({ toolCall, args }) => {
|
|
169
189
|
const runner = this._extensionRunner;
|
|
170
|
-
if (!runner
|
|
190
|
+
if (!runner.hasHandlers("tool_call")) {
|
|
171
191
|
return undefined;
|
|
172
192
|
}
|
|
173
|
-
await this._agentEventQueue;
|
|
174
193
|
try {
|
|
175
194
|
return await runner.emitToolCall({
|
|
176
195
|
type: "tool_call",
|
|
@@ -188,7 +207,7 @@ export class AgentSession {
|
|
|
188
207
|
};
|
|
189
208
|
this.agent.afterToolCall = async ({ toolCall, args, result, isError }) => {
|
|
190
209
|
const runner = this._extensionRunner;
|
|
191
|
-
if (!runner
|
|
210
|
+
if (!runner.hasHandlers("tool_result")) {
|
|
192
211
|
return undefined;
|
|
193
212
|
}
|
|
194
213
|
const hookResult = await runner.emitToolResult({
|
|
@@ -197,15 +216,36 @@ export class AgentSession {
|
|
|
197
216
|
toolCallId: toolCall.id,
|
|
198
217
|
input: args,
|
|
199
218
|
content: result.content,
|
|
200
|
-
details:
|
|
219
|
+
details: result.details,
|
|
201
220
|
isError,
|
|
202
221
|
});
|
|
203
|
-
if (!hookResult
|
|
222
|
+
if (!hookResult) {
|
|
204
223
|
return undefined;
|
|
205
224
|
}
|
|
206
225
|
return {
|
|
207
226
|
content: hookResult.content,
|
|
208
227
|
details: hookResult.details,
|
|
228
|
+
isError: hookResult.isError ?? isError,
|
|
229
|
+
};
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
_installAgentNextTurnRefresh() {
|
|
233
|
+
const previousPrepareNextTurnWithContext = this.agent.prepareNextTurnWithContext ??
|
|
234
|
+
(this.agent.prepareNextTurn
|
|
235
|
+
? async (_turn, signal) => await this.agent.prepareNextTurn?.(signal)
|
|
236
|
+
: undefined);
|
|
237
|
+
this.agent.prepareNextTurnWithContext = async (turn, signal) => {
|
|
238
|
+
const previousSnapshot = await previousPrepareNextTurnWithContext?.(turn, signal);
|
|
239
|
+
const previousContext = previousSnapshot?.context ?? turn.context;
|
|
240
|
+
return {
|
|
241
|
+
...previousSnapshot,
|
|
242
|
+
context: {
|
|
243
|
+
...previousContext,
|
|
244
|
+
systemPrompt: this._systemPromptOverride ?? this._baseSystemPrompt,
|
|
245
|
+
tools: this.agent.state.tools.slice(),
|
|
246
|
+
},
|
|
247
|
+
model: this.agent.state.model,
|
|
248
|
+
thinkingLevel: this.agent.state.thinkingLevel,
|
|
209
249
|
};
|
|
210
250
|
};
|
|
211
251
|
}
|
|
@@ -228,43 +268,7 @@ export class AgentSession {
|
|
|
228
268
|
// Track last assistant message for auto-compaction check
|
|
229
269
|
_lastAssistantMessage = undefined;
|
|
230
270
|
/** Internal handler for agent events - shared by subscribe and reconnect */
|
|
231
|
-
_handleAgentEvent = (event) => {
|
|
232
|
-
// Create retry promise synchronously before queueing async processing.
|
|
233
|
-
// Agent.emit() calls this handler synchronously, and prompt() calls waitForRetry()
|
|
234
|
-
// as soon as agent.prompt() resolves. If _retryPromise is created only inside
|
|
235
|
-
// _processAgentEvent, slow earlier queued events can delay agent_end processing
|
|
236
|
-
// and waitForRetry() can miss the in-flight retry.
|
|
237
|
-
this._createRetryPromiseForAgentEnd(event);
|
|
238
|
-
this._agentEventQueue = this._agentEventQueue.then(() => this._processAgentEvent(event), () => this._processAgentEvent(event));
|
|
239
|
-
// Keep queue alive if an event handler fails
|
|
240
|
-
this._agentEventQueue.catch(() => { });
|
|
241
|
-
};
|
|
242
|
-
_createRetryPromiseForAgentEnd(event) {
|
|
243
|
-
if (event.type !== "agent_end" || this._retryPromise) {
|
|
244
|
-
return;
|
|
245
|
-
}
|
|
246
|
-
const settings = this.settingsManager.getRetrySettings();
|
|
247
|
-
if (!settings.enabled) {
|
|
248
|
-
return;
|
|
249
|
-
}
|
|
250
|
-
const lastAssistant = this._findLastAssistantInMessages(event.messages);
|
|
251
|
-
if (!lastAssistant || !this._isRetryableError(lastAssistant)) {
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
this._retryPromise = new Promise((resolve) => {
|
|
255
|
-
this._retryResolve = resolve;
|
|
256
|
-
});
|
|
257
|
-
}
|
|
258
|
-
_findLastAssistantInMessages(messages) {
|
|
259
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
260
|
-
const message = messages[i];
|
|
261
|
-
if (message.role === "assistant") {
|
|
262
|
-
return message;
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
return undefined;
|
|
266
|
-
}
|
|
267
|
-
async _processAgentEvent(event) {
|
|
271
|
+
_handleAgentEvent = async (event) => {
|
|
268
272
|
// When a user message starts, check if it's from either queue and remove it BEFORE emitting
|
|
269
273
|
// This ensures the UI sees the updated queue state
|
|
270
274
|
if (event.type === "message_start" && event.message.role === "user") {
|
|
@@ -290,7 +294,7 @@ export class AgentSession {
|
|
|
290
294
|
// Emit to extensions first
|
|
291
295
|
await this._emitExtensionEvent(event);
|
|
292
296
|
// Notify all listeners
|
|
293
|
-
this._emit(event);
|
|
297
|
+
this._emit(event.type === "agent_end" ? { ...event, willRetry: this._willRetryAfterAgentEnd(event) } : event);
|
|
294
298
|
// Handle session persistence
|
|
295
299
|
if (event.type === "message_end") {
|
|
296
300
|
// Check if this is a custom message from extensions
|
|
@@ -324,27 +328,19 @@ export class AgentSession {
|
|
|
324
328
|
}
|
|
325
329
|
}
|
|
326
330
|
}
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
if (this._isRetryableError(msg)) {
|
|
333
|
-
const didRetry = await this._handleRetryableError(msg);
|
|
334
|
-
if (didRetry)
|
|
335
|
-
return; // Retry was initiated, don't proceed to compaction
|
|
336
|
-
}
|
|
337
|
-
this._resolveRetry();
|
|
338
|
-
await this._checkCompaction(msg);
|
|
331
|
+
};
|
|
332
|
+
_willRetryAfterAgentEnd(event) {
|
|
333
|
+
const settings = this.settingsManager.getRetrySettings();
|
|
334
|
+
if (!settings.enabled || this._retryAttempt >= settings.maxRetries) {
|
|
335
|
+
return false;
|
|
339
336
|
}
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
this._retryResolve = undefined;
|
|
346
|
-
this._retryPromise = undefined;
|
|
337
|
+
for (let i = event.messages.length - 1; i >= 0; i--) {
|
|
338
|
+
const message = event.messages[i];
|
|
339
|
+
if (message.role === "assistant") {
|
|
340
|
+
return this._isRetryableError(message);
|
|
341
|
+
}
|
|
347
342
|
}
|
|
343
|
+
return false;
|
|
348
344
|
}
|
|
349
345
|
/** Extract text content from a message */
|
|
350
346
|
_getUserMessageText(message) {
|
|
@@ -367,10 +363,22 @@ export class AgentSession {
|
|
|
367
363
|
}
|
|
368
364
|
return undefined;
|
|
369
365
|
}
|
|
366
|
+
_replaceMessageInPlace(target, replacement) {
|
|
367
|
+
// Agent-core stores the finalized message object in its state before emitting message_end.
|
|
368
|
+
// SessionManager persistence happens later in _handleAgentEvent() with event.message.
|
|
369
|
+
// Mutating this object in place keeps agent state, later turn/agent events, listeners,
|
|
370
|
+
// and the eventual SessionManager.appendMessage(event.message) persistence in sync.
|
|
371
|
+
if (target === replacement) {
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
const targetRecord = target;
|
|
375
|
+
for (const key of Object.keys(targetRecord)) {
|
|
376
|
+
delete targetRecord[key];
|
|
377
|
+
}
|
|
378
|
+
Object.assign(targetRecord, replacement);
|
|
379
|
+
}
|
|
370
380
|
/** Emit extension events based on agent events */
|
|
371
381
|
async _emitExtensionEvent(event) {
|
|
372
|
-
if (!this._extensionRunner)
|
|
373
|
-
return;
|
|
374
382
|
if (event.type === "agent_start") {
|
|
375
383
|
this._turnIndex = 0;
|
|
376
384
|
await this._extensionRunner.emit({ type: "agent_start" });
|
|
@@ -416,7 +424,19 @@ export class AgentSession {
|
|
|
416
424
|
type: "message_end",
|
|
417
425
|
message: event.message,
|
|
418
426
|
};
|
|
419
|
-
await this._extensionRunner.
|
|
427
|
+
const replacement = await this._extensionRunner.emitMessageEnd(extensionEvent);
|
|
428
|
+
if (replacement) {
|
|
429
|
+
// Untyped extension handlers can return messages with null/missing content;
|
|
430
|
+
// normalize so it never enters agent state or session history.
|
|
431
|
+
const normalized = (replacement.role === "user" ||
|
|
432
|
+
replacement.role === "assistant" ||
|
|
433
|
+
replacement.role === "toolResult" ||
|
|
434
|
+
replacement.role === "custom") &&
|
|
435
|
+
replacement.content == null
|
|
436
|
+
? { ...replacement, content: [] }
|
|
437
|
+
: replacement;
|
|
438
|
+
this._replaceMessageInPlace(event.message, normalized);
|
|
439
|
+
}
|
|
420
440
|
}
|
|
421
441
|
else if (event.type === "tool_execution_start") {
|
|
422
442
|
const extensionEvent = {
|
|
@@ -488,8 +508,20 @@ export class AgentSession {
|
|
|
488
508
|
* Call this when completely done with the session.
|
|
489
509
|
*/
|
|
490
510
|
dispose() {
|
|
511
|
+
try {
|
|
512
|
+
this.abortRetry();
|
|
513
|
+
this.abortCompaction();
|
|
514
|
+
this.abortBranchSummary();
|
|
515
|
+
this.abortBash();
|
|
516
|
+
this.agent.abort();
|
|
517
|
+
}
|
|
518
|
+
catch {
|
|
519
|
+
// Dispose must succeed even if an abort hook throws.
|
|
520
|
+
}
|
|
521
|
+
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().");
|
|
491
522
|
this._disconnectFromAgent();
|
|
492
523
|
this._eventListeners = [];
|
|
524
|
+
cleanupSessionResources(this.sessionId);
|
|
493
525
|
}
|
|
494
526
|
// =========================================================================
|
|
495
527
|
// Read-only State Access
|
|
@@ -526,13 +558,14 @@ export class AgentSession {
|
|
|
526
558
|
return this.agent.state.tools.map((t) => t.name);
|
|
527
559
|
}
|
|
528
560
|
/**
|
|
529
|
-
* Get all configured tools with name, description, parameter schema, and source metadata.
|
|
561
|
+
* Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata.
|
|
530
562
|
*/
|
|
531
563
|
getAllTools() {
|
|
532
564
|
return Array.from(this._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({
|
|
533
565
|
name: definition.name,
|
|
534
566
|
description: definition.description,
|
|
535
567
|
parameters: definition.parameters,
|
|
568
|
+
promptGuidelines: definition.promptGuidelines,
|
|
536
569
|
sourceInfo,
|
|
537
570
|
}));
|
|
538
571
|
}
|
|
@@ -558,7 +591,7 @@ export class AgentSession {
|
|
|
558
591
|
this.agent.state.tools = tools;
|
|
559
592
|
// Rebuild base system prompt with new tool set
|
|
560
593
|
this._baseSystemPrompt = this._rebuildSystemPrompt(validToolNames);
|
|
561
|
-
this.agent.state.systemPrompt = this._baseSystemPrompt;
|
|
594
|
+
this.agent.state.systemPrompt = this._systemPromptOverride ?? this._baseSystemPrompt;
|
|
562
595
|
}
|
|
563
596
|
/** Whether compaction or branch summarization is currently running */
|
|
564
597
|
get isCompacting() {
|
|
@@ -643,7 +676,7 @@ export class AgentSession {
|
|
|
643
676
|
const appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : undefined;
|
|
644
677
|
const loadedSkills = this._resourceLoader.getSkills().skills;
|
|
645
678
|
const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
|
|
646
|
-
|
|
679
|
+
this._baseSystemPromptOptions = {
|
|
647
680
|
cwd: this._cwd,
|
|
648
681
|
skills: loadedSkills,
|
|
649
682
|
contextFiles: loadedContextFiles,
|
|
@@ -652,11 +685,49 @@ export class AgentSession {
|
|
|
652
685
|
selectedTools: validToolNames,
|
|
653
686
|
toolSnippets,
|
|
654
687
|
promptGuidelines,
|
|
655
|
-
}
|
|
688
|
+
};
|
|
689
|
+
return buildSystemPrompt(this._baseSystemPromptOptions);
|
|
656
690
|
}
|
|
657
691
|
// =========================================================================
|
|
658
692
|
// Prompting
|
|
659
693
|
// =========================================================================
|
|
694
|
+
async _runAgentPrompt(messages) {
|
|
695
|
+
try {
|
|
696
|
+
await this.agent.prompt(messages);
|
|
697
|
+
while (await this._handlePostAgentRun()) {
|
|
698
|
+
await this.agent.continue();
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
finally {
|
|
702
|
+
this._systemPromptOverride = undefined;
|
|
703
|
+
this._flushPendingBashMessages();
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
async _handlePostAgentRun() {
|
|
707
|
+
const msg = this._lastAssistantMessage;
|
|
708
|
+
this._lastAssistantMessage = undefined;
|
|
709
|
+
if (!msg) {
|
|
710
|
+
return false;
|
|
711
|
+
}
|
|
712
|
+
if (this._isRetryableError(msg) && (await this._prepareRetry(msg))) {
|
|
713
|
+
return true;
|
|
714
|
+
}
|
|
715
|
+
if (msg.stopReason === "error" && this._retryAttempt > 0) {
|
|
716
|
+
this._emit({
|
|
717
|
+
type: "auto_retry_end",
|
|
718
|
+
success: false,
|
|
719
|
+
attempt: this._retryAttempt,
|
|
720
|
+
finalError: msg.errorMessage,
|
|
721
|
+
});
|
|
722
|
+
this._retryAttempt = 0;
|
|
723
|
+
}
|
|
724
|
+
if (await this._checkCompaction(msg)) {
|
|
725
|
+
return true;
|
|
726
|
+
}
|
|
727
|
+
// The agent loop drains both queues before emitting agent_end. Any messages
|
|
728
|
+
// here were queued by agent_end extension handlers and need a continuation.
|
|
729
|
+
return this.agent.hasQueuedMessages();
|
|
730
|
+
}
|
|
660
731
|
/**
|
|
661
732
|
* Send a prompt to the agent.
|
|
662
733
|
* - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming
|
|
@@ -668,97 +739,101 @@ export class AgentSession {
|
|
|
668
739
|
*/
|
|
669
740
|
async prompt(text, options) {
|
|
670
741
|
const expandPromptTemplates = options?.expandPromptTemplates ?? true;
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
if (this._extensionRunner?.hasHandlers("input")) {
|
|
684
|
-
const inputResult = await this._extensionRunner.emitInput(currentText, currentImages, options?.source ?? "interactive");
|
|
685
|
-
if (inputResult.action === "handled") {
|
|
686
|
-
return;
|
|
742
|
+
const preflightResult = options?.preflightResult;
|
|
743
|
+
let messages;
|
|
744
|
+
try {
|
|
745
|
+
// Handle extension commands first (execute immediately, even during streaming)
|
|
746
|
+
// Extension commands manage their own LLM interaction via pi.sendMessage()
|
|
747
|
+
if (expandPromptTemplates && text.startsWith("/")) {
|
|
748
|
+
const handled = await this._tryExecuteExtensionCommand(text);
|
|
749
|
+
if (handled) {
|
|
750
|
+
// Extension command executed, no prompt to send
|
|
751
|
+
preflightResult?.(true);
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
687
754
|
}
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
755
|
+
// Emit input event for extension interception (before skill/template expansion)
|
|
756
|
+
let currentText = text;
|
|
757
|
+
let currentImages = options?.images;
|
|
758
|
+
if (this._extensionRunner.hasHandlers("input")) {
|
|
759
|
+
const inputResult = await this._extensionRunner.emitInput(currentText, currentImages, options?.source ?? "interactive", this.isStreaming ? options?.streamingBehavior : undefined);
|
|
760
|
+
if (inputResult.action === "handled") {
|
|
761
|
+
preflightResult?.(true);
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
if (inputResult.action === "transform") {
|
|
765
|
+
currentText = inputResult.text;
|
|
766
|
+
currentImages = inputResult.images ?? currentImages;
|
|
767
|
+
}
|
|
691
768
|
}
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
|
|
698
|
-
}
|
|
699
|
-
// If streaming, queue via steer() or followUp() based on option
|
|
700
|
-
if (this.isStreaming) {
|
|
701
|
-
if (!options?.streamingBehavior) {
|
|
702
|
-
throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
|
|
769
|
+
// Expand skill commands (/skill:name args) and prompt templates (/template args)
|
|
770
|
+
let expandedText = currentText;
|
|
771
|
+
if (expandPromptTemplates) {
|
|
772
|
+
expandedText = this._expandSkillCommand(expandedText);
|
|
773
|
+
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
|
|
703
774
|
}
|
|
704
|
-
|
|
705
|
-
|
|
775
|
+
// If streaming, queue via steer() or followUp() based on option
|
|
776
|
+
if (this.isStreaming) {
|
|
777
|
+
if (!options?.streamingBehavior) {
|
|
778
|
+
throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
|
|
779
|
+
}
|
|
780
|
+
if (options.streamingBehavior === "followUp") {
|
|
781
|
+
await this._queueFollowUp(expandedText, currentImages);
|
|
782
|
+
}
|
|
783
|
+
else {
|
|
784
|
+
await this._queueSteer(expandedText, currentImages);
|
|
785
|
+
}
|
|
786
|
+
preflightResult?.(true);
|
|
787
|
+
return;
|
|
706
788
|
}
|
|
707
|
-
|
|
708
|
-
|
|
789
|
+
// Flush any pending bash messages before the new prompt
|
|
790
|
+
this._flushPendingBashMessages();
|
|
791
|
+
// Validate model
|
|
792
|
+
if (!this.model) {
|
|
793
|
+
throw new Error(formatNoModelSelectedMessage());
|
|
794
|
+
}
|
|
795
|
+
if (!this._modelRegistry.hasConfiguredAuth(this.model)) {
|
|
796
|
+
const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
|
|
797
|
+
if (isOAuth) {
|
|
798
|
+
throw new Error(`Authentication failed for "${this.model.provider}". ` +
|
|
799
|
+
`Credentials may have expired or network is unavailable. ` +
|
|
800
|
+
`Run '/login ${this.model.provider}' to re-authenticate.`);
|
|
801
|
+
}
|
|
802
|
+
throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
|
|
803
|
+
}
|
|
804
|
+
// Check if we need to compact before sending (catches aborted responses).
|
|
805
|
+
// The user's new prompt is sent below, so do not call agent.continue() here.
|
|
806
|
+
const lastAssistant = this._findLastAssistantMessage();
|
|
807
|
+
if (lastAssistant) {
|
|
808
|
+
await this._checkCompaction(lastAssistant, false);
|
|
809
|
+
}
|
|
810
|
+
// Build messages array (custom message if any, then user message)
|
|
811
|
+
messages = [];
|
|
812
|
+
// Add user message
|
|
813
|
+
const userContent = [{ type: "text", text: expandedText }];
|
|
814
|
+
if (currentImages) {
|
|
815
|
+
userContent.push(...currentImages);
|
|
816
|
+
}
|
|
817
|
+
messages.push({
|
|
818
|
+
role: "user",
|
|
819
|
+
content: userContent,
|
|
820
|
+
timestamp: Date.now(),
|
|
821
|
+
});
|
|
822
|
+
// Inject any pending "nextTurn" messages as context alongside the user message
|
|
823
|
+
for (const msg of this._pendingNextTurnMessages) {
|
|
824
|
+
messages.push(msg);
|
|
709
825
|
}
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
this._flushPendingBashMessages();
|
|
714
|
-
// Validate model
|
|
715
|
-
if (!this.model) {
|
|
716
|
-
throw new Error("No model selected.\n\n" +
|
|
717
|
-
`Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}\n\n` +
|
|
718
|
-
"Then use /model to select a model.");
|
|
719
|
-
}
|
|
720
|
-
if (!this._modelRegistry.hasConfiguredAuth(this.model)) {
|
|
721
|
-
const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
|
|
722
|
-
if (isOAuth) {
|
|
723
|
-
throw new Error(`Authentication failed for "${this.model.provider}". ` +
|
|
724
|
-
`Credentials may have expired or network is unavailable. ` +
|
|
725
|
-
`Run '/login ${this.model.provider}' to re-authenticate.`);
|
|
726
|
-
}
|
|
727
|
-
throw new Error(`No API key found for ${this.model.provider}.\n\n` +
|
|
728
|
-
`Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}`);
|
|
729
|
-
}
|
|
730
|
-
// Check if we need to compact before sending (catches aborted responses)
|
|
731
|
-
const lastAssistant = this._findLastAssistantMessage();
|
|
732
|
-
if (lastAssistant) {
|
|
733
|
-
await this._checkCompaction(lastAssistant, false);
|
|
734
|
-
}
|
|
735
|
-
// Build messages array (custom message if any, then user message)
|
|
736
|
-
const messages = [];
|
|
737
|
-
// Add user message
|
|
738
|
-
const userContent = [{ type: "text", text: expandedText }];
|
|
739
|
-
if (currentImages) {
|
|
740
|
-
userContent.push(...currentImages);
|
|
741
|
-
}
|
|
742
|
-
messages.push({
|
|
743
|
-
role: "user",
|
|
744
|
-
content: userContent,
|
|
745
|
-
timestamp: Date.now(),
|
|
746
|
-
});
|
|
747
|
-
// Inject any pending "nextTurn" messages as context alongside the user message
|
|
748
|
-
for (const msg of this._pendingNextTurnMessages) {
|
|
749
|
-
messages.push(msg);
|
|
750
|
-
}
|
|
751
|
-
this._pendingNextTurnMessages = [];
|
|
752
|
-
// Emit before_agent_start extension event
|
|
753
|
-
if (this._extensionRunner) {
|
|
754
|
-
const result = await this._extensionRunner.emitBeforeAgentStart(expandedText, currentImages, this._baseSystemPrompt);
|
|
826
|
+
this._pendingNextTurnMessages = [];
|
|
827
|
+
// Emit before_agent_start extension event
|
|
828
|
+
const result = await this._extensionRunner.emitBeforeAgentStart(expandedText, currentImages, this._baseSystemPrompt, this._baseSystemPromptOptions);
|
|
755
829
|
// Add all custom messages from extensions
|
|
756
830
|
if (result?.messages) {
|
|
757
831
|
for (const msg of result.messages) {
|
|
758
832
|
messages.push({
|
|
759
833
|
role: "custom",
|
|
760
834
|
customType: msg.customType,
|
|
761
|
-
content
|
|
835
|
+
// Untyped extensions can pass null/missing content; normalize at ingestion.
|
|
836
|
+
content: msg.content ?? [],
|
|
762
837
|
display: msg.display,
|
|
763
838
|
details: msg.details,
|
|
764
839
|
timestamp: Date.now(),
|
|
@@ -766,23 +841,30 @@ export class AgentSession {
|
|
|
766
841
|
}
|
|
767
842
|
}
|
|
768
843
|
// Apply extension-modified system prompt, or reset to base
|
|
769
|
-
if (result?.systemPrompt) {
|
|
844
|
+
if (result?.systemPrompt !== undefined) {
|
|
845
|
+
this._systemPromptOverride = result.systemPrompt;
|
|
770
846
|
this.agent.state.systemPrompt = result.systemPrompt;
|
|
771
847
|
}
|
|
772
848
|
else {
|
|
773
849
|
// Ensure we're using the base prompt (in case previous turn had modifications)
|
|
850
|
+
this._systemPromptOverride = undefined;
|
|
774
851
|
this.agent.state.systemPrompt = this._baseSystemPrompt;
|
|
775
852
|
}
|
|
776
853
|
}
|
|
777
|
-
|
|
778
|
-
|
|
854
|
+
catch (error) {
|
|
855
|
+
preflightResult?.(false);
|
|
856
|
+
throw error;
|
|
857
|
+
}
|
|
858
|
+
if (!messages) {
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
preflightResult?.(true);
|
|
862
|
+
await this._runAgentPrompt(messages);
|
|
779
863
|
}
|
|
780
864
|
/**
|
|
781
865
|
* Try to execute an extension command. Returns true if command was found and executed.
|
|
782
866
|
*/
|
|
783
867
|
async _tryExecuteExtensionCommand(text) {
|
|
784
|
-
if (!this._extensionRunner)
|
|
785
|
-
return false;
|
|
786
868
|
// Parse command name and args
|
|
787
869
|
const spaceIndex = text.indexOf(" ");
|
|
788
870
|
const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
|
|
@@ -828,7 +910,7 @@ export class AgentSession {
|
|
|
828
910
|
}
|
|
829
911
|
catch (err) {
|
|
830
912
|
// Emit error like extension commands do
|
|
831
|
-
this._extensionRunner
|
|
913
|
+
this._extensionRunner.emitError({
|
|
832
914
|
extensionPath: skill.filePath,
|
|
833
915
|
event: "skill_expansion",
|
|
834
916
|
error: err instanceof Error ? err.message : String(err),
|
|
@@ -907,8 +989,6 @@ export class AgentSession {
|
|
|
907
989
|
* Throw an error if the text is an extension command.
|
|
908
990
|
*/
|
|
909
991
|
_throwIfExtensionCommand(text) {
|
|
910
|
-
if (!this._extensionRunner)
|
|
911
|
-
return;
|
|
912
992
|
const spaceIndex = text.indexOf(" ");
|
|
913
993
|
const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
|
|
914
994
|
const command = this._extensionRunner.getCommand(commandName);
|
|
@@ -932,7 +1012,8 @@ export class AgentSession {
|
|
|
932
1012
|
const appMessage = {
|
|
933
1013
|
role: "custom",
|
|
934
1014
|
customType: message.customType,
|
|
935
|
-
content
|
|
1015
|
+
// Untyped extensions can pass null/missing content; normalize at ingestion.
|
|
1016
|
+
content: message.content ?? [],
|
|
936
1017
|
display: message.display,
|
|
937
1018
|
details: message.details,
|
|
938
1019
|
timestamp: Date.now(),
|
|
@@ -949,7 +1030,7 @@ export class AgentSession {
|
|
|
949
1030
|
}
|
|
950
1031
|
}
|
|
951
1032
|
else if (options?.triggerTurn) {
|
|
952
|
-
await this.
|
|
1033
|
+
await this._runAgentPrompt(appMessage);
|
|
953
1034
|
}
|
|
954
1035
|
else {
|
|
955
1036
|
this.agent.state.messages.push(appMessage);
|
|
@@ -1036,8 +1117,6 @@ export class AgentSession {
|
|
|
1036
1117
|
// Model Management
|
|
1037
1118
|
// =========================================================================
|
|
1038
1119
|
async _emitModelSelect(nextModel, previousModel, source) {
|
|
1039
|
-
if (!this._extensionRunner)
|
|
1040
|
-
return;
|
|
1041
1120
|
if (modelsAreEqual(previousModel, nextModel))
|
|
1042
1121
|
return;
|
|
1043
1122
|
await this._extensionRunner.emit({
|
|
@@ -1133,13 +1212,20 @@ export class AgentSession {
|
|
|
1133
1212
|
const availableLevels = this.getAvailableThinkingLevels();
|
|
1134
1213
|
const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
|
|
1135
1214
|
// Only persist if actually changing
|
|
1136
|
-
const
|
|
1215
|
+
const previousLevel = this.agent.state.thinkingLevel;
|
|
1216
|
+
const isChanging = effectiveLevel !== previousLevel;
|
|
1137
1217
|
this.agent.state.thinkingLevel = effectiveLevel;
|
|
1138
1218
|
if (isChanging) {
|
|
1139
1219
|
this.sessionManager.appendThinkingLevelChange(effectiveLevel);
|
|
1140
1220
|
if (this.supportsThinking() || effectiveLevel !== "off") {
|
|
1141
1221
|
this.settingsManager.setDefaultThinkingLevel(effectiveLevel);
|
|
1142
1222
|
}
|
|
1223
|
+
this._emit({ type: "thinking_level_changed", level: effectiveLevel });
|
|
1224
|
+
void this._extensionRunner.emit({
|
|
1225
|
+
type: "thinking_level_select",
|
|
1226
|
+
level: effectiveLevel,
|
|
1227
|
+
previousLevel,
|
|
1228
|
+
});
|
|
1143
1229
|
}
|
|
1144
1230
|
}
|
|
1145
1231
|
/**
|
|
@@ -1161,23 +1247,9 @@ export class AgentSession {
|
|
|
1161
1247
|
* The provider will clamp to what the specific model supports internally.
|
|
1162
1248
|
*/
|
|
1163
1249
|
getAvailableThinkingLevels() {
|
|
1164
|
-
if (!this.
|
|
1165
|
-
return
|
|
1166
|
-
|
|
1167
|
-
return THINKING_LEVELS_WITH_MAX;
|
|
1168
|
-
return this.supportsXhighThinking() ? THINKING_LEVELS_WITH_XHIGH : THINKING_LEVELS;
|
|
1169
|
-
}
|
|
1170
|
-
/**
|
|
1171
|
-
* Check if current model supports xhigh thinking level.
|
|
1172
|
-
*/
|
|
1173
|
-
supportsXhighThinking() {
|
|
1174
|
-
return this.model ? supportsXhigh(this.model) : false;
|
|
1175
|
-
}
|
|
1176
|
-
/**
|
|
1177
|
-
* Check if current model supports the `max` thinking level (Anthropic Opus 4.6/4.7 only).
|
|
1178
|
-
*/
|
|
1179
|
-
supportsMaxThinking() {
|
|
1180
|
-
return this.model ? supportsMax(this.model) : false;
|
|
1250
|
+
if (!this.model)
|
|
1251
|
+
return THINKING_LEVELS;
|
|
1252
|
+
return getSupportedThinkingLevels(this.model);
|
|
1181
1253
|
}
|
|
1182
1254
|
/**
|
|
1183
1255
|
* Check if current model supports thinking/reasoning.
|
|
@@ -1194,28 +1266,16 @@ export class AgentSession {
|
|
|
1194
1266
|
}
|
|
1195
1267
|
return this.thinkingLevel;
|
|
1196
1268
|
}
|
|
1197
|
-
_clampThinkingLevel(level,
|
|
1198
|
-
|
|
1199
|
-
const available = new Set(availableLevels);
|
|
1200
|
-
const requestedIndex = ordered.indexOf(level);
|
|
1201
|
-
if (requestedIndex === -1) {
|
|
1202
|
-
return availableLevels[0] ?? "off";
|
|
1203
|
-
}
|
|
1204
|
-
for (let i = requestedIndex; i < ordered.length; i++) {
|
|
1205
|
-
const candidate = ordered[i];
|
|
1206
|
-
if (available.has(candidate))
|
|
1207
|
-
return candidate;
|
|
1208
|
-
}
|
|
1209
|
-
for (let i = requestedIndex - 1; i >= 0; i--) {
|
|
1210
|
-
const candidate = ordered[i];
|
|
1211
|
-
if (available.has(candidate))
|
|
1212
|
-
return candidate;
|
|
1213
|
-
}
|
|
1214
|
-
return availableLevels[0] ?? "off";
|
|
1269
|
+
_clampThinkingLevel(level, _availableLevels) {
|
|
1270
|
+
return this.model ? clampThinkingLevel(this.model, level) : "off";
|
|
1215
1271
|
}
|
|
1216
1272
|
// =========================================================================
|
|
1217
1273
|
// Queue Mode Management
|
|
1218
1274
|
// =========================================================================
|
|
1275
|
+
syncQueueModesFromSettings() {
|
|
1276
|
+
this.agent.steeringMode = this.settingsManager.getSteeringMode();
|
|
1277
|
+
this.agent.followUpMode = this.settingsManager.getFollowUpMode();
|
|
1278
|
+
}
|
|
1219
1279
|
/**
|
|
1220
1280
|
* Set steering message mode.
|
|
1221
1281
|
* Saves to settings.
|
|
@@ -1247,9 +1307,9 @@ export class AgentSession {
|
|
|
1247
1307
|
this._emit({ type: "compaction_start", reason: "manual" });
|
|
1248
1308
|
try {
|
|
1249
1309
|
if (!this.model) {
|
|
1250
|
-
throw new Error(
|
|
1310
|
+
throw new Error(formatNoModelSelectedMessage());
|
|
1251
1311
|
}
|
|
1252
|
-
const { apiKey, headers } = await this.
|
|
1312
|
+
const { apiKey, headers, env } = await this._getCompactionRequestAuth(this.model);
|
|
1253
1313
|
const pathEntries = this.sessionManager.getBranch();
|
|
1254
1314
|
const settings = this.settingsManager.getCompactionSettings();
|
|
1255
1315
|
const preparation = prepareCompaction(pathEntries, settings);
|
|
@@ -1263,12 +1323,14 @@ export class AgentSession {
|
|
|
1263
1323
|
}
|
|
1264
1324
|
let extensionCompaction;
|
|
1265
1325
|
let fromExtension = false;
|
|
1266
|
-
if (this._extensionRunner
|
|
1326
|
+
if (this._extensionRunner.hasHandlers("session_before_compact")) {
|
|
1267
1327
|
const result = (await this._extensionRunner.emit({
|
|
1268
1328
|
type: "session_before_compact",
|
|
1269
1329
|
preparation,
|
|
1270
1330
|
branchEntries: pathEntries,
|
|
1271
1331
|
customInstructions,
|
|
1332
|
+
reason: "manual",
|
|
1333
|
+
willRetry: false,
|
|
1272
1334
|
signal: this._compactionAbortController.signal,
|
|
1273
1335
|
}));
|
|
1274
1336
|
if (result?.cancel) {
|
|
@@ -1292,7 +1354,7 @@ export class AgentSession {
|
|
|
1292
1354
|
}
|
|
1293
1355
|
else {
|
|
1294
1356
|
// Generate compaction result
|
|
1295
|
-
const result = await compact(preparation, this.model, apiKey, headers, customInstructions, this._compactionAbortController.signal);
|
|
1357
|
+
const result = await compact(preparation, this.model, apiKey, headers, customInstructions, this._compactionAbortController.signal, this.thinkingLevel, this.agent.streamFn, env);
|
|
1296
1358
|
summary = result.summary;
|
|
1297
1359
|
firstKeptEntryId = result.firstKeptEntryId;
|
|
1298
1360
|
tokensBefore = result.tokensBefore;
|
|
@@ -1305,6 +1367,7 @@ export class AgentSession {
|
|
|
1305
1367
|
const newEntries = this.sessionManager.getEntries();
|
|
1306
1368
|
const sessionContext = this.sessionManager.buildSessionContext();
|
|
1307
1369
|
this.agent.state.messages = sessionContext.messages;
|
|
1370
|
+
const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
|
|
1308
1371
|
// Get the saved compaction entry for the extension event
|
|
1309
1372
|
const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
|
|
1310
1373
|
if (this._extensionRunner && savedCompactionEntry) {
|
|
@@ -1312,12 +1375,15 @@ export class AgentSession {
|
|
|
1312
1375
|
type: "session_compact",
|
|
1313
1376
|
compactionEntry: savedCompactionEntry,
|
|
1314
1377
|
fromExtension,
|
|
1378
|
+
reason: "manual",
|
|
1379
|
+
willRetry: false,
|
|
1315
1380
|
});
|
|
1316
1381
|
}
|
|
1317
1382
|
const compactionResult = {
|
|
1318
1383
|
summary,
|
|
1319
1384
|
firstKeptEntryId,
|
|
1320
1385
|
tokensBefore,
|
|
1386
|
+
estimatedTokensAfter,
|
|
1321
1387
|
details,
|
|
1322
1388
|
};
|
|
1323
1389
|
this._emit({
|
|
@@ -1374,10 +1440,10 @@ export class AgentSession {
|
|
|
1374
1440
|
async _checkCompaction(assistantMessage, skipAbortedCheck = true) {
|
|
1375
1441
|
const settings = this.settingsManager.getCompactionSettings();
|
|
1376
1442
|
if (!settings.enabled)
|
|
1377
|
-
return;
|
|
1443
|
+
return false;
|
|
1378
1444
|
// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
|
|
1379
1445
|
if (skipAbortedCheck && assistantMessage.stopReason === "aborted")
|
|
1380
|
-
return;
|
|
1446
|
+
return false;
|
|
1381
1447
|
const contextWindow = this.model?.contextWindow ?? 0;
|
|
1382
1448
|
// Skip overflow check if the message came from a different model.
|
|
1383
1449
|
// This handles the case where user switched from a smaller-context model (e.g. opus)
|
|
@@ -1390,10 +1456,17 @@ export class AgentSession {
|
|
|
1390
1456
|
const compactionEntry = getLatestCompactionEntry(this.sessionManager.getBranch());
|
|
1391
1457
|
const assistantIsFromBeforeCompaction = compactionEntry !== null && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime();
|
|
1392
1458
|
if (assistantIsFromBeforeCompaction) {
|
|
1393
|
-
return;
|
|
1459
|
+
return false;
|
|
1394
1460
|
}
|
|
1395
|
-
// Case 1: Overflow - LLM returned context overflow error
|
|
1461
|
+
// Case 1: Overflow - LLM returned context overflow error, or reported usage exceeded
|
|
1462
|
+
// the configured window. A successful response over the configured window should compact
|
|
1463
|
+
// but must not retry: the assistant answer already completed and agent.continue() cannot
|
|
1464
|
+
// continue from an assistant message.
|
|
1396
1465
|
if (sameModel && isContextOverflow(assistantMessage, contextWindow)) {
|
|
1466
|
+
const willRetry = assistantMessage.stopReason !== "stop";
|
|
1467
|
+
if (!willRetry) {
|
|
1468
|
+
return await this._runAutoCompaction("overflow", false);
|
|
1469
|
+
}
|
|
1397
1470
|
if (this._overflowRecoveryAttempted) {
|
|
1398
1471
|
this._emit({
|
|
1399
1472
|
type: "compaction_end",
|
|
@@ -1403,7 +1476,7 @@ export class AgentSession {
|
|
|
1403
1476
|
willRetry: false,
|
|
1404
1477
|
errorMessage: "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.",
|
|
1405
1478
|
});
|
|
1406
|
-
return;
|
|
1479
|
+
return false;
|
|
1407
1480
|
}
|
|
1408
1481
|
this._overflowRecoveryAttempted = true;
|
|
1409
1482
|
// Remove the error message from agent state (it IS saved to session for history,
|
|
@@ -1412,18 +1485,19 @@ export class AgentSession {
|
|
|
1412
1485
|
if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
|
|
1413
1486
|
this.agent.state.messages = messages.slice(0, -1);
|
|
1414
1487
|
}
|
|
1415
|
-
await this._runAutoCompaction("overflow",
|
|
1416
|
-
return;
|
|
1488
|
+
return await this._runAutoCompaction("overflow", willRetry);
|
|
1417
1489
|
}
|
|
1418
1490
|
// Case 2: Threshold - context is getting large
|
|
1419
|
-
// For error messages
|
|
1420
|
-
// This ensures sessions that hit persistent API errors (e.g. 529)
|
|
1491
|
+
// For error messages or all-zero usage messages, estimate from the last valid response.
|
|
1492
|
+
// This ensures sessions that hit persistent API errors (e.g. 529) or malformed zero-usage
|
|
1493
|
+
// responses can still compact and do not reset context accounting.
|
|
1421
1494
|
let contextTokens;
|
|
1422
|
-
|
|
1495
|
+
const directContextTokens = assistantMessage.usage ? calculateContextTokens(assistantMessage.usage) : 0;
|
|
1496
|
+
if (assistantMessage.stopReason === "error" || directContextTokens === 0) {
|
|
1423
1497
|
const messages = this.agent.state.messages;
|
|
1424
1498
|
const estimate = estimateContextTokens(messages);
|
|
1425
1499
|
if (estimate.lastUsageIndex === null)
|
|
1426
|
-
return; // No usage data at all
|
|
1500
|
+
return false; // No usage data at all
|
|
1427
1501
|
// Verify the usage source is post-compaction. Kept pre-compaction messages
|
|
1428
1502
|
// have stale usage reflecting the old (larger) context and would falsely
|
|
1429
1503
|
// trigger compaction right after one just finished.
|
|
@@ -1431,67 +1505,61 @@ export class AgentSession {
|
|
|
1431
1505
|
if (compactionEntry &&
|
|
1432
1506
|
usageMsg.role === "assistant" &&
|
|
1433
1507
|
usageMsg.timestamp <= new Date(compactionEntry.timestamp).getTime()) {
|
|
1434
|
-
return;
|
|
1508
|
+
return false;
|
|
1435
1509
|
}
|
|
1436
1510
|
contextTokens = estimate.tokens;
|
|
1437
1511
|
}
|
|
1438
1512
|
else {
|
|
1439
|
-
contextTokens =
|
|
1513
|
+
contextTokens = directContextTokens;
|
|
1440
1514
|
}
|
|
1441
1515
|
if (shouldCompact(contextTokens, contextWindow, settings)) {
|
|
1442
|
-
await this._runAutoCompaction("threshold", false);
|
|
1516
|
+
return await this._runAutoCompaction("threshold", false);
|
|
1443
1517
|
}
|
|
1518
|
+
return false;
|
|
1444
1519
|
}
|
|
1445
1520
|
/**
|
|
1446
1521
|
* Internal: Run auto-compaction with events.
|
|
1447
1522
|
*/
|
|
1448
1523
|
async _runAutoCompaction(reason, willRetry) {
|
|
1449
1524
|
const settings = this.settingsManager.getCompactionSettings();
|
|
1450
|
-
|
|
1451
|
-
this._autoCompactionAbortController = new AbortController();
|
|
1525
|
+
let started = false;
|
|
1452
1526
|
try {
|
|
1453
1527
|
if (!this.model) {
|
|
1454
|
-
|
|
1455
|
-
type: "compaction_end",
|
|
1456
|
-
reason,
|
|
1457
|
-
result: undefined,
|
|
1458
|
-
aborted: false,
|
|
1459
|
-
willRetry: false,
|
|
1460
|
-
});
|
|
1461
|
-
return;
|
|
1528
|
+
return false;
|
|
1462
1529
|
}
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1530
|
+
let apiKey;
|
|
1531
|
+
let headers;
|
|
1532
|
+
let env;
|
|
1533
|
+
if (this.agent.streamFn === streamSimple) {
|
|
1534
|
+
const authResult = await this._modelRegistry.getApiKeyAndHeaders(this.model);
|
|
1535
|
+
if (!authResult.ok || !authResult.apiKey) {
|
|
1536
|
+
return false;
|
|
1537
|
+
}
|
|
1538
|
+
apiKey = authResult.apiKey;
|
|
1539
|
+
headers = authResult.headers;
|
|
1540
|
+
env = authResult.env;
|
|
1541
|
+
}
|
|
1542
|
+
else {
|
|
1543
|
+
({ apiKey, headers, env } = await this._getCompactionRequestAuth(this.model));
|
|
1473
1544
|
}
|
|
1474
|
-
const { apiKey, headers } = authResult;
|
|
1475
1545
|
const pathEntries = this.sessionManager.getBranch();
|
|
1476
1546
|
const preparation = prepareCompaction(pathEntries, settings);
|
|
1477
1547
|
if (!preparation) {
|
|
1478
|
-
|
|
1479
|
-
type: "compaction_end",
|
|
1480
|
-
reason,
|
|
1481
|
-
result: undefined,
|
|
1482
|
-
aborted: false,
|
|
1483
|
-
willRetry: false,
|
|
1484
|
-
});
|
|
1485
|
-
return;
|
|
1548
|
+
return false;
|
|
1486
1549
|
}
|
|
1550
|
+
this._emit({ type: "compaction_start", reason });
|
|
1551
|
+
this._autoCompactionAbortController = new AbortController();
|
|
1552
|
+
started = true;
|
|
1487
1553
|
let extensionCompaction;
|
|
1488
1554
|
let fromExtension = false;
|
|
1489
|
-
if (this._extensionRunner
|
|
1555
|
+
if (this._extensionRunner.hasHandlers("session_before_compact")) {
|
|
1490
1556
|
const extensionResult = (await this._extensionRunner.emit({
|
|
1491
1557
|
type: "session_before_compact",
|
|
1492
1558
|
preparation,
|
|
1493
1559
|
branchEntries: pathEntries,
|
|
1494
1560
|
customInstructions: undefined,
|
|
1561
|
+
reason,
|
|
1562
|
+
willRetry,
|
|
1495
1563
|
signal: this._autoCompactionAbortController.signal,
|
|
1496
1564
|
}));
|
|
1497
1565
|
if (extensionResult?.cancel) {
|
|
@@ -1502,7 +1570,7 @@ export class AgentSession {
|
|
|
1502
1570
|
aborted: true,
|
|
1503
1571
|
willRetry: false,
|
|
1504
1572
|
});
|
|
1505
|
-
return;
|
|
1573
|
+
return false;
|
|
1506
1574
|
}
|
|
1507
1575
|
if (extensionResult?.compaction) {
|
|
1508
1576
|
extensionCompaction = extensionResult.compaction;
|
|
@@ -1522,7 +1590,7 @@ export class AgentSession {
|
|
|
1522
1590
|
}
|
|
1523
1591
|
else {
|
|
1524
1592
|
// Generate compaction result
|
|
1525
|
-
const compactResult = await compact(preparation, this.model, apiKey, headers, undefined, this._autoCompactionAbortController.signal);
|
|
1593
|
+
const compactResult = await compact(preparation, this.model, apiKey, headers, undefined, this._autoCompactionAbortController.signal, this.thinkingLevel, this.agent.streamFn, env);
|
|
1526
1594
|
summary = compactResult.summary;
|
|
1527
1595
|
firstKeptEntryId = compactResult.firstKeptEntryId;
|
|
1528
1596
|
tokensBefore = compactResult.tokensBefore;
|
|
@@ -1536,12 +1604,13 @@ export class AgentSession {
|
|
|
1536
1604
|
aborted: true,
|
|
1537
1605
|
willRetry: false,
|
|
1538
1606
|
});
|
|
1539
|
-
return;
|
|
1607
|
+
return false;
|
|
1540
1608
|
}
|
|
1541
1609
|
this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension);
|
|
1542
1610
|
const newEntries = this.sessionManager.getEntries();
|
|
1543
1611
|
const sessionContext = this.sessionManager.buildSessionContext();
|
|
1544
1612
|
this.agent.state.messages = sessionContext.messages;
|
|
1613
|
+
const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
|
|
1545
1614
|
// Get the saved compaction entry for the extension event
|
|
1546
1615
|
const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
|
|
1547
1616
|
if (this._extensionRunner && savedCompactionEntry) {
|
|
@@ -1549,12 +1618,15 @@ export class AgentSession {
|
|
|
1549
1618
|
type: "session_compact",
|
|
1550
1619
|
compactionEntry: savedCompactionEntry,
|
|
1551
1620
|
fromExtension,
|
|
1621
|
+
reason,
|
|
1622
|
+
willRetry,
|
|
1552
1623
|
});
|
|
1553
1624
|
}
|
|
1554
1625
|
const result = {
|
|
1555
1626
|
summary,
|
|
1556
1627
|
firstKeptEntryId,
|
|
1557
1628
|
tokensBefore,
|
|
1629
|
+
estimatedTokensAfter,
|
|
1558
1630
|
details,
|
|
1559
1631
|
};
|
|
1560
1632
|
this._emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
|
|
@@ -1564,30 +1636,27 @@ export class AgentSession {
|
|
|
1564
1636
|
if (lastMsg?.role === "assistant" && lastMsg.stopReason === "error") {
|
|
1565
1637
|
this.agent.state.messages = messages.slice(0, -1);
|
|
1566
1638
|
}
|
|
1567
|
-
|
|
1568
|
-
this.agent.continue().catch(() => { });
|
|
1569
|
-
}, 100);
|
|
1570
|
-
}
|
|
1571
|
-
else if (this.agent.hasQueuedMessages()) {
|
|
1572
|
-
// Auto-compaction can complete while follow-up/steering/custom messages are waiting.
|
|
1573
|
-
// Kick the loop so queued messages are actually delivered.
|
|
1574
|
-
setTimeout(() => {
|
|
1575
|
-
this.agent.continue().catch(() => { });
|
|
1576
|
-
}, 100);
|
|
1639
|
+
return true;
|
|
1577
1640
|
}
|
|
1641
|
+
// Auto-compaction can complete while follow-up/steering/custom messages are waiting.
|
|
1642
|
+
// Continue once so queued messages are delivered.
|
|
1643
|
+
return this.agent.hasQueuedMessages();
|
|
1578
1644
|
}
|
|
1579
1645
|
catch (error) {
|
|
1580
1646
|
const errorMessage = error instanceof Error ? error.message : "compaction failed";
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1647
|
+
if (started) {
|
|
1648
|
+
this._emit({
|
|
1649
|
+
type: "compaction_end",
|
|
1650
|
+
reason,
|
|
1651
|
+
result: undefined,
|
|
1652
|
+
aborted: false,
|
|
1653
|
+
willRetry: false,
|
|
1654
|
+
errorMessage: reason === "overflow"
|
|
1655
|
+
? `Context overflow recovery failed: ${errorMessage}`
|
|
1656
|
+
: `Auto-compaction failed: ${errorMessage}`,
|
|
1657
|
+
});
|
|
1658
|
+
}
|
|
1659
|
+
return false;
|
|
1591
1660
|
}
|
|
1592
1661
|
finally {
|
|
1593
1662
|
this._autoCompactionAbortController = undefined;
|
|
@@ -1607,23 +1676,27 @@ export class AgentSession {
|
|
|
1607
1676
|
if (bindings.uiContext !== undefined) {
|
|
1608
1677
|
this._extensionUIContext = bindings.uiContext;
|
|
1609
1678
|
}
|
|
1679
|
+
if (bindings.mode !== undefined) {
|
|
1680
|
+
this._extensionMode = bindings.mode;
|
|
1681
|
+
}
|
|
1610
1682
|
if (bindings.commandContextActions !== undefined) {
|
|
1611
1683
|
this._extensionCommandContextActions = bindings.commandContextActions;
|
|
1612
1684
|
}
|
|
1685
|
+
if (bindings.abortHandler !== undefined) {
|
|
1686
|
+
this._extensionAbortHandler = bindings.abortHandler;
|
|
1687
|
+
}
|
|
1613
1688
|
if (bindings.shutdownHandler !== undefined) {
|
|
1614
1689
|
this._extensionShutdownHandler = bindings.shutdownHandler;
|
|
1615
1690
|
}
|
|
1616
1691
|
if (bindings.onError !== undefined) {
|
|
1617
1692
|
this._extensionErrorListener = bindings.onError;
|
|
1618
1693
|
}
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
|
|
1623
|
-
}
|
|
1694
|
+
this._applyExtensionBindings(this._extensionRunner);
|
|
1695
|
+
await this._extensionRunner.emit(this._sessionStartEvent);
|
|
1696
|
+
await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
|
|
1624
1697
|
}
|
|
1625
1698
|
async extendResourcesFromExtensions(reason) {
|
|
1626
|
-
if (!this._extensionRunner
|
|
1699
|
+
if (!this._extensionRunner.hasHandlers("resources_discover")) {
|
|
1627
1700
|
return;
|
|
1628
1701
|
}
|
|
1629
1702
|
const { skillPaths, promptPaths, themePaths } = await this._extensionRunner.emitResourcesDiscover(this._cwd, reason);
|
|
@@ -1663,7 +1736,7 @@ export class AgentSession {
|
|
|
1663
1736
|
return `extension:${name}`;
|
|
1664
1737
|
}
|
|
1665
1738
|
_applyExtensionBindings(runner) {
|
|
1666
|
-
runner.setUIContext(this._extensionUIContext);
|
|
1739
|
+
runner.setUIContext(this._extensionUIContext, this._extensionMode);
|
|
1667
1740
|
runner.bindCommandContext(this._extensionCommandContextActions);
|
|
1668
1741
|
this._extensionErrorUnsubscriber?.();
|
|
1669
1742
|
this._extensionErrorUnsubscriber = this._extensionErrorListener
|
|
@@ -1723,10 +1796,14 @@ export class AgentSession {
|
|
|
1723
1796
|
});
|
|
1724
1797
|
},
|
|
1725
1798
|
appendEntry: (customType, data) => {
|
|
1726
|
-
this.sessionManager.appendCustomEntry(customType, data);
|
|
1799
|
+
const entryId = this.sessionManager.appendCustomEntry(customType, data);
|
|
1800
|
+
const entry = this.sessionManager.getEntry(entryId);
|
|
1801
|
+
if (entry) {
|
|
1802
|
+
this._emit({ type: "entry_appended", entry });
|
|
1803
|
+
}
|
|
1727
1804
|
},
|
|
1728
1805
|
setSessionName: (name) => {
|
|
1729
|
-
this.
|
|
1806
|
+
this.setSessionName(name);
|
|
1730
1807
|
},
|
|
1731
1808
|
getSessionName: () => {
|
|
1732
1809
|
return this.sessionManager.getSessionName();
|
|
@@ -1750,8 +1827,15 @@ export class AgentSession {
|
|
|
1750
1827
|
}, {
|
|
1751
1828
|
getModel: () => this.model,
|
|
1752
1829
|
isIdle: () => !this.isStreaming,
|
|
1830
|
+
isProjectTrusted: () => this.settingsManager.isProjectTrusted(),
|
|
1753
1831
|
getSignal: () => this.agent.signal,
|
|
1754
|
-
abort: () =>
|
|
1832
|
+
abort: () => {
|
|
1833
|
+
if (this._extensionAbortHandler) {
|
|
1834
|
+
this._extensionAbortHandler();
|
|
1835
|
+
return;
|
|
1836
|
+
}
|
|
1837
|
+
void this.abort();
|
|
1838
|
+
},
|
|
1755
1839
|
hasPendingMessages: () => this.pendingMessageCount > 0,
|
|
1756
1840
|
shutdown: () => {
|
|
1757
1841
|
this._extensionShutdownHandler?.();
|
|
@@ -1770,6 +1854,7 @@ export class AgentSession {
|
|
|
1770
1854
|
})();
|
|
1771
1855
|
},
|
|
1772
1856
|
getSystemPrompt: () => this.systemPrompt,
|
|
1857
|
+
getSystemPromptOptions: () => this._baseSystemPromptOptions,
|
|
1773
1858
|
}, {
|
|
1774
1859
|
registerProvider: (name, config) => {
|
|
1775
1860
|
this._modelRegistry.registerProvider(name, config);
|
|
@@ -1784,15 +1869,20 @@ export class AgentSession {
|
|
|
1784
1869
|
_refreshToolRegistry(options) {
|
|
1785
1870
|
const previousRegistryNames = new Set(this._toolRegistry.keys());
|
|
1786
1871
|
const previousActiveToolNames = this.getActiveToolNames();
|
|
1787
|
-
const
|
|
1872
|
+
const allowedToolNames = this._allowedToolNames;
|
|
1873
|
+
const excludedToolNames = this._excludedToolNames;
|
|
1874
|
+
const isAllowedTool = (name) => (!allowedToolNames || allowedToolNames.has(name)) && !excludedToolNames?.has(name);
|
|
1875
|
+
const registeredTools = this._extensionRunner.getAllRegisteredTools();
|
|
1788
1876
|
const allCustomTools = [
|
|
1789
1877
|
...registeredTools,
|
|
1790
1878
|
...this._customTools.map((definition) => ({
|
|
1791
1879
|
definition,
|
|
1792
1880
|
sourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: "sdk" }),
|
|
1793
1881
|
})),
|
|
1794
|
-
];
|
|
1795
|
-
const definitionRegistry = new Map(Array.from(this._baseToolDefinitions.entries())
|
|
1882
|
+
].filter((tool) => isAllowedTool(tool.definition.name));
|
|
1883
|
+
const definitionRegistry = new Map(Array.from(this._baseToolDefinitions.entries())
|
|
1884
|
+
.filter(([name]) => isAllowedTool(name))
|
|
1885
|
+
.map(([name, definition]) => [
|
|
1796
1886
|
name,
|
|
1797
1887
|
{
|
|
1798
1888
|
definition,
|
|
@@ -1818,21 +1908,28 @@ export class AgentSession {
|
|
|
1818
1908
|
return guidelines.length > 0 ? [definition.name, guidelines] : undefined;
|
|
1819
1909
|
})
|
|
1820
1910
|
.filter((entry) => entry !== undefined));
|
|
1821
|
-
const
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
definition
|
|
1826
|
-
|
|
1827
|
-
|
|
1911
|
+
const runner = this._extensionRunner;
|
|
1912
|
+
const wrappedExtensionTools = wrapRegisteredTools(allCustomTools, runner);
|
|
1913
|
+
const wrappedBuiltInTools = wrapRegisteredTools(Array.from(this._baseToolDefinitions.values())
|
|
1914
|
+
.filter((definition) => isAllowedTool(definition.name))
|
|
1915
|
+
.map((definition) => ({
|
|
1916
|
+
definition,
|
|
1917
|
+
sourceInfo: createSyntheticSourceInfo(`<builtin:${definition.name}>`, { source: "builtin" }),
|
|
1918
|
+
})), runner);
|
|
1919
|
+
const toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));
|
|
1828
1920
|
for (const tool of wrappedExtensionTools) {
|
|
1829
1921
|
toolRegistry.set(tool.name, tool);
|
|
1830
1922
|
}
|
|
1831
1923
|
this._toolRegistry = toolRegistry;
|
|
1832
|
-
const nextActiveToolNames = options?.activeToolNames
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1924
|
+
const nextActiveToolNames = (options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]).filter((name) => isAllowedTool(name));
|
|
1925
|
+
if (allowedToolNames) {
|
|
1926
|
+
for (const toolName of this._toolRegistry.keys()) {
|
|
1927
|
+
if (allowedToolNames.has(toolName)) {
|
|
1928
|
+
nextActiveToolNames.push(toolName);
|
|
1929
|
+
}
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
else if (options?.includeAllExtensionTools) {
|
|
1836
1933
|
for (const tool of wrappedExtensionTools) {
|
|
1837
1934
|
nextActiveToolNames.push(tool.name);
|
|
1838
1935
|
}
|
|
@@ -1849,6 +1946,7 @@ export class AgentSession {
|
|
|
1849
1946
|
_buildRuntime(options) {
|
|
1850
1947
|
const autoResizeImages = this.settingsManager.getImageAutoResize();
|
|
1851
1948
|
const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
|
|
1949
|
+
const shellPath = this.settingsManager.getShellPath();
|
|
1852
1950
|
const baseToolDefinitions = this._baseToolsOverride
|
|
1853
1951
|
? Object.fromEntries(Object.entries(this._baseToolsOverride).map(([name, tool]) => [
|
|
1854
1952
|
name,
|
|
@@ -1856,7 +1954,7 @@ export class AgentSession {
|
|
|
1856
1954
|
]))
|
|
1857
1955
|
: createAllToolDefinitions(this._cwd, {
|
|
1858
1956
|
read: { autoResizeImages },
|
|
1859
|
-
bash: { commandPrefix: shellCommandPrefix },
|
|
1957
|
+
bash: { commandPrefix: shellCommandPrefix, shellPath },
|
|
1860
1958
|
});
|
|
1861
1959
|
this._baseToolDefinitions = new Map(Object.entries(baseToolDefinitions).map(([name, tool]) => [name, tool]));
|
|
1862
1960
|
const extensionsResult = this._resourceLoader.getExtensions();
|
|
@@ -1865,19 +1963,12 @@ export class AgentSession {
|
|
|
1865
1963
|
extensionsResult.runtime.flagValues.set(name, value);
|
|
1866
1964
|
}
|
|
1867
1965
|
}
|
|
1868
|
-
|
|
1869
|
-
const hasCustomTools = this._customTools.length > 0;
|
|
1870
|
-
this._extensionRunner =
|
|
1871
|
-
hasExtensions || hasCustomTools
|
|
1872
|
-
? new ExtensionRunner(extensionsResult.extensions, extensionsResult.runtime, this._cwd, this.sessionManager, this._modelRegistry)
|
|
1873
|
-
: undefined;
|
|
1966
|
+
this._extensionRunner = new ExtensionRunner(extensionsResult.extensions, extensionsResult.runtime, this._cwd, this.sessionManager, this._modelRegistry);
|
|
1874
1967
|
if (this._extensionRunnerRef) {
|
|
1875
1968
|
this._extensionRunnerRef.current = this._extensionRunner;
|
|
1876
1969
|
}
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
this._applyExtensionBindings(this._extensionRunner);
|
|
1880
|
-
}
|
|
1970
|
+
this._bindExtensionCore(this._extensionRunner);
|
|
1971
|
+
this._applyExtensionBindings(this._extensionRunner);
|
|
1881
1972
|
const defaultActiveToolNames = this._baseToolsOverride
|
|
1882
1973
|
? Object.keys(this._baseToolsOverride)
|
|
1883
1974
|
: ["read", "bash", "edit", "write"];
|
|
@@ -1887,10 +1978,11 @@ export class AgentSession {
|
|
|
1887
1978
|
includeAllExtensionTools: options.includeAllExtensionTools,
|
|
1888
1979
|
});
|
|
1889
1980
|
}
|
|
1890
|
-
async reload() {
|
|
1891
|
-
const previousFlagValues = this._extensionRunner
|
|
1892
|
-
await this._extensionRunner
|
|
1981
|
+
async reload(options) {
|
|
1982
|
+
const previousFlagValues = this._extensionRunner.getFlagValues();
|
|
1983
|
+
await emitSessionShutdownEvent(this._extensionRunner, { type: "session_shutdown", reason: "reload" });
|
|
1893
1984
|
await this.settingsManager.reload();
|
|
1985
|
+
this.syncQueueModesFromSettings();
|
|
1894
1986
|
resetApiProviders();
|
|
1895
1987
|
await this._resourceLoader.reload();
|
|
1896
1988
|
this._buildRuntime({
|
|
@@ -1902,7 +1994,8 @@ export class AgentSession {
|
|
|
1902
1994
|
this._extensionCommandContextActions ||
|
|
1903
1995
|
this._extensionShutdownHandler ||
|
|
1904
1996
|
this._extensionErrorListener;
|
|
1905
|
-
if (
|
|
1997
|
+
if (hasBindings) {
|
|
1998
|
+
await options?.beforeSessionStart?.();
|
|
1906
1999
|
await this._extensionRunner.emit({ type: "session_start", reason: "reload" });
|
|
1907
2000
|
await this.extendResourcesFromExtensions("reload");
|
|
1908
2001
|
}
|
|
@@ -1915,44 +2008,24 @@ export class AgentSession {
|
|
|
1915
2008
|
* Context overflow errors are NOT retryable (handled by compaction instead).
|
|
1916
2009
|
*/
|
|
1917
2010
|
_isRetryableError(message) {
|
|
1918
|
-
|
|
2011
|
+
// Context overflow is handled by compaction, not retry.
|
|
2012
|
+
if (isContextOverflow(message, this.model?.contextWindow ?? 0))
|
|
1919
2013
|
return false;
|
|
1920
|
-
|
|
1921
|
-
const contextWindow = this.model?.contextWindow ?? 0;
|
|
1922
|
-
if (isContextOverflow(message, contextWindow))
|
|
1923
|
-
return false;
|
|
1924
|
-
const err = message.errorMessage;
|
|
1925
|
-
// Match: overloaded_error, provider returned error, rate limit, 429, 500, 502, 503, 504, service unavailable, network/connection errors, fetch failed, request ended without sending chunks, terminated, retry delay exceeded, peer-closed/incomplete-chunked stream truncations
|
|
1926
|
-
return /overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?reset|peer closed|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|incomplete.?chunked.?read|chunked.?read|premature.?close|timed? out|timeout|terminated|retry delay/i.test(err);
|
|
2014
|
+
return isRetryableAssistantError(message);
|
|
1927
2015
|
}
|
|
1928
2016
|
/**
|
|
1929
|
-
*
|
|
1930
|
-
* @returns true if
|
|
2017
|
+
* Prepare a retryable error for continuation with exponential backoff.
|
|
2018
|
+
* @returns true if the caller should continue the agent, false otherwise
|
|
1931
2019
|
*/
|
|
1932
|
-
async
|
|
2020
|
+
async _prepareRetry(message) {
|
|
1933
2021
|
const settings = this.settingsManager.getRetrySettings();
|
|
1934
2022
|
if (!settings.enabled) {
|
|
1935
|
-
this._resolveRetry();
|
|
1936
2023
|
return false;
|
|
1937
2024
|
}
|
|
1938
|
-
// Retry promise is created synchronously in _handleAgentEvent for agent_end.
|
|
1939
|
-
// Keep a defensive fallback here in case a future refactor bypasses that path.
|
|
1940
|
-
if (!this._retryPromise) {
|
|
1941
|
-
this._retryPromise = new Promise((resolve) => {
|
|
1942
|
-
this._retryResolve = resolve;
|
|
1943
|
-
});
|
|
1944
|
-
}
|
|
1945
2025
|
this._retryAttempt++;
|
|
1946
2026
|
if (this._retryAttempt > settings.maxRetries) {
|
|
1947
|
-
//
|
|
1948
|
-
this.
|
|
1949
|
-
type: "auto_retry_end",
|
|
1950
|
-
success: false,
|
|
1951
|
-
attempt: this._retryAttempt - 1,
|
|
1952
|
-
finalError: message.errorMessage,
|
|
1953
|
-
});
|
|
1954
|
-
this._retryAttempt = 0;
|
|
1955
|
-
this._resolveRetry(); // Resolve so waitForRetry() completes
|
|
2027
|
+
// Preserve the completed attempt count so post-run handling can emit the final failure.
|
|
2028
|
+
this._retryAttempt--;
|
|
1956
2029
|
return false;
|
|
1957
2030
|
}
|
|
1958
2031
|
const delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);
|
|
@@ -1977,23 +2050,17 @@ export class AgentSession {
|
|
|
1977
2050
|
// Aborted during sleep - emit end event so UI can clean up
|
|
1978
2051
|
const attempt = this._retryAttempt;
|
|
1979
2052
|
this._retryAttempt = 0;
|
|
1980
|
-
this._retryAbortController = undefined;
|
|
1981
2053
|
this._emit({
|
|
1982
2054
|
type: "auto_retry_end",
|
|
1983
2055
|
success: false,
|
|
1984
2056
|
attempt,
|
|
1985
2057
|
finalError: "Retry cancelled",
|
|
1986
2058
|
});
|
|
1987
|
-
this._resolveRetry();
|
|
1988
2059
|
return false;
|
|
1989
2060
|
}
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
this.agent.continue().catch(() => {
|
|
1994
|
-
// Retry failed - will be caught by next agent_end
|
|
1995
|
-
});
|
|
1996
|
-
}, 0);
|
|
2061
|
+
finally {
|
|
2062
|
+
this._retryAbortController = undefined;
|
|
2063
|
+
}
|
|
1997
2064
|
return true;
|
|
1998
2065
|
}
|
|
1999
2066
|
/**
|
|
@@ -2001,23 +2068,10 @@ export class AgentSession {
|
|
|
2001
2068
|
*/
|
|
2002
2069
|
abortRetry() {
|
|
2003
2070
|
this._retryAbortController?.abort();
|
|
2004
|
-
// Note: _retryAttempt is reset in the catch block of _autoRetry
|
|
2005
|
-
this._resolveRetry();
|
|
2006
|
-
}
|
|
2007
|
-
/**
|
|
2008
|
-
* Wait for any in-progress retry to complete.
|
|
2009
|
-
* Returns immediately if no retry is in progress.
|
|
2010
|
-
*/
|
|
2011
|
-
async waitForRetry() {
|
|
2012
|
-
if (!this._retryPromise) {
|
|
2013
|
-
return;
|
|
2014
|
-
}
|
|
2015
|
-
await this._retryPromise;
|
|
2016
|
-
await this.agent.waitForIdle();
|
|
2017
2071
|
}
|
|
2018
2072
|
/** Whether auto-retry is currently in progress */
|
|
2019
2073
|
get isRetrying() {
|
|
2020
|
-
return this.
|
|
2074
|
+
return this._retryAbortController !== undefined;
|
|
2021
2075
|
}
|
|
2022
2076
|
/** Whether auto-retry is enabled */
|
|
2023
2077
|
get autoRetryEnabled() {
|
|
@@ -2044,9 +2098,10 @@ export class AgentSession {
|
|
|
2044
2098
|
this._bashAbortController = new AbortController();
|
|
2045
2099
|
// Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
|
|
2046
2100
|
const prefix = this.settingsManager.getShellCommandPrefix();
|
|
2101
|
+
const shellPath = this.settingsManager.getShellPath();
|
|
2047
2102
|
const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
|
|
2048
2103
|
try {
|
|
2049
|
-
const result = await executeBashWithOperations(resolvedCommand, this.sessionManager.getCwd(), options?.operations ?? createLocalBashOperations(), {
|
|
2104
|
+
const result = await executeBashWithOperations(resolvedCommand, this.sessionManager.getCwd(), options?.operations ?? createLocalBashOperations({ shellPath }), {
|
|
2050
2105
|
onChunk,
|
|
2051
2106
|
signal: this._bashAbortController.signal,
|
|
2052
2107
|
});
|
|
@@ -2122,6 +2177,9 @@ export class AgentSession {
|
|
|
2122
2177
|
*/
|
|
2123
2178
|
setSessionName(name) {
|
|
2124
2179
|
this.sessionManager.appendSessionInfo(name);
|
|
2180
|
+
const event = { type: "session_info_changed", name: this.sessionManager.getSessionName() };
|
|
2181
|
+
this._emit(event);
|
|
2182
|
+
void this._extensionRunner.emit(event);
|
|
2125
2183
|
}
|
|
2126
2184
|
// =========================================================================
|
|
2127
2185
|
// Tree Navigation
|
|
@@ -2169,118 +2227,119 @@ export class AgentSession {
|
|
|
2169
2227
|
};
|
|
2170
2228
|
// Set up abort controller for summarization
|
|
2171
2229
|
this._branchSummaryAbortController = new AbortController();
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
customInstructions
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
replaceInstructions
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
label
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
// Run default summarizer if needed
|
|
2200
|
-
let summaryText;
|
|
2201
|
-
let summaryDetails;
|
|
2202
|
-
if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
|
|
2203
|
-
const model = this.model;
|
|
2204
|
-
const { apiKey, headers } = await this._getRequiredRequestAuth(model);
|
|
2205
|
-
const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
|
|
2206
|
-
const result = await generateBranchSummary(entriesToSummarize, {
|
|
2207
|
-
model,
|
|
2208
|
-
apiKey,
|
|
2209
|
-
headers,
|
|
2210
|
-
signal: this._branchSummaryAbortController.signal,
|
|
2211
|
-
customInstructions,
|
|
2212
|
-
replaceInstructions,
|
|
2213
|
-
reserveTokens: branchSummarySettings.reserveTokens,
|
|
2214
|
-
});
|
|
2215
|
-
this._branchSummaryAbortController = undefined;
|
|
2216
|
-
if (result.aborted) {
|
|
2217
|
-
return { cancelled: true, aborted: true };
|
|
2230
|
+
try {
|
|
2231
|
+
let extensionSummary;
|
|
2232
|
+
let fromExtension = false;
|
|
2233
|
+
// Emit session_before_tree event
|
|
2234
|
+
if (this._extensionRunner.hasHandlers("session_before_tree")) {
|
|
2235
|
+
const result = (await this._extensionRunner.emit({
|
|
2236
|
+
type: "session_before_tree",
|
|
2237
|
+
preparation,
|
|
2238
|
+
signal: this._branchSummaryAbortController.signal,
|
|
2239
|
+
}));
|
|
2240
|
+
if (result?.cancel) {
|
|
2241
|
+
return { cancelled: true };
|
|
2242
|
+
}
|
|
2243
|
+
if (result?.summary && options.summarize) {
|
|
2244
|
+
extensionSummary = result.summary;
|
|
2245
|
+
fromExtension = true;
|
|
2246
|
+
}
|
|
2247
|
+
// Allow extensions to override instructions and label
|
|
2248
|
+
if (result?.customInstructions !== undefined) {
|
|
2249
|
+
customInstructions = result.customInstructions;
|
|
2250
|
+
}
|
|
2251
|
+
if (result?.replaceInstructions !== undefined) {
|
|
2252
|
+
replaceInstructions = result.replaceInstructions;
|
|
2253
|
+
}
|
|
2254
|
+
if (result?.label !== undefined) {
|
|
2255
|
+
label = result.label;
|
|
2256
|
+
}
|
|
2218
2257
|
}
|
|
2219
|
-
if
|
|
2220
|
-
|
|
2258
|
+
// Run default summarizer if needed
|
|
2259
|
+
let summaryText;
|
|
2260
|
+
let summaryDetails;
|
|
2261
|
+
if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
|
|
2262
|
+
const model = this.model;
|
|
2263
|
+
const { apiKey, headers, env } = await this._getRequiredRequestAuth(model);
|
|
2264
|
+
const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
|
|
2265
|
+
const result = await generateBranchSummary(entriesToSummarize, {
|
|
2266
|
+
model,
|
|
2267
|
+
apiKey,
|
|
2268
|
+
headers,
|
|
2269
|
+
env,
|
|
2270
|
+
signal: this._branchSummaryAbortController.signal,
|
|
2271
|
+
customInstructions,
|
|
2272
|
+
replaceInstructions,
|
|
2273
|
+
reserveTokens: branchSummarySettings.reserveTokens,
|
|
2274
|
+
streamFn: this.agent.streamFn,
|
|
2275
|
+
});
|
|
2276
|
+
if (result.aborted) {
|
|
2277
|
+
return { cancelled: true, aborted: true };
|
|
2278
|
+
}
|
|
2279
|
+
if (result.error) {
|
|
2280
|
+
throw new Error(result.error);
|
|
2281
|
+
}
|
|
2282
|
+
summaryText = result.summary;
|
|
2283
|
+
summaryDetails = {
|
|
2284
|
+
readFiles: result.readFiles || [],
|
|
2285
|
+
modifiedFiles: result.modifiedFiles || [],
|
|
2286
|
+
};
|
|
2287
|
+
}
|
|
2288
|
+
else if (extensionSummary) {
|
|
2289
|
+
summaryText = extensionSummary.summary;
|
|
2290
|
+
summaryDetails = extensionSummary.details;
|
|
2291
|
+
}
|
|
2292
|
+
// Determine the new leaf position based on target type
|
|
2293
|
+
let newLeafId;
|
|
2294
|
+
let editorText;
|
|
2295
|
+
if (targetEntry.type === "message" && targetEntry.message.role === "user") {
|
|
2296
|
+
// User message: leaf = parent (null if root), text goes to editor
|
|
2297
|
+
newLeafId = targetEntry.parentId;
|
|
2298
|
+
editorText = this._extractUserMessageText(targetEntry.message.content);
|
|
2299
|
+
}
|
|
2300
|
+
else if (targetEntry.type === "custom_message") {
|
|
2301
|
+
// Custom message: leaf = parent (null if root), text goes to editor
|
|
2302
|
+
newLeafId = targetEntry.parentId;
|
|
2303
|
+
editorText =
|
|
2304
|
+
typeof targetEntry.content === "string"
|
|
2305
|
+
? targetEntry.content
|
|
2306
|
+
: targetEntry.content
|
|
2307
|
+
.filter((c) => c.type === "text")
|
|
2308
|
+
.map((c) => c.text)
|
|
2309
|
+
.join("");
|
|
2221
2310
|
}
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
summaryText
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
newLeafId = targetEntry.parentId;
|
|
2238
|
-
editorText = this._extractUserMessageText(targetEntry.message.content);
|
|
2239
|
-
}
|
|
2240
|
-
else if (targetEntry.type === "custom_message") {
|
|
2241
|
-
// Custom message: leaf = parent (null if root), text goes to editor
|
|
2242
|
-
newLeafId = targetEntry.parentId;
|
|
2243
|
-
editorText =
|
|
2244
|
-
typeof targetEntry.content === "string"
|
|
2245
|
-
? targetEntry.content
|
|
2246
|
-
: targetEntry.content
|
|
2247
|
-
.filter((c) => c.type === "text")
|
|
2248
|
-
.map((c) => c.text)
|
|
2249
|
-
.join("");
|
|
2250
|
-
}
|
|
2251
|
-
else {
|
|
2252
|
-
// Non-user message: leaf = selected node
|
|
2253
|
-
newLeafId = targetId;
|
|
2254
|
-
}
|
|
2255
|
-
// Switch leaf (with or without summary)
|
|
2256
|
-
// Summary is attached at the navigation target position (newLeafId), not the old branch
|
|
2257
|
-
let summaryEntry;
|
|
2258
|
-
if (summaryText) {
|
|
2259
|
-
// Create summary at target position (can be null for root)
|
|
2260
|
-
const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension);
|
|
2261
|
-
summaryEntry = this.sessionManager.getEntry(summaryId);
|
|
2262
|
-
// Attach label to the summary entry
|
|
2263
|
-
if (label) {
|
|
2264
|
-
this.sessionManager.appendLabelChange(summaryId, label);
|
|
2311
|
+
else {
|
|
2312
|
+
// Non-user message: leaf = selected node
|
|
2313
|
+
newLeafId = targetId;
|
|
2314
|
+
}
|
|
2315
|
+
// Switch leaf (with or without summary)
|
|
2316
|
+
// Summary is attached at the navigation target position (newLeafId), not the old branch
|
|
2317
|
+
let summaryEntry;
|
|
2318
|
+
if (summaryText) {
|
|
2319
|
+
// Create summary at target position (can be null for root)
|
|
2320
|
+
const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension);
|
|
2321
|
+
summaryEntry = this.sessionManager.getEntry(summaryId);
|
|
2322
|
+
// Attach label to the summary entry
|
|
2323
|
+
if (label) {
|
|
2324
|
+
this.sessionManager.appendLabelChange(summaryId, label);
|
|
2325
|
+
}
|
|
2265
2326
|
}
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
// Emit session_tree event
|
|
2283
|
-
if (this._extensionRunner) {
|
|
2327
|
+
else if (newLeafId === null) {
|
|
2328
|
+
// No summary, navigating to root - reset leaf
|
|
2329
|
+
this.sessionManager.resetLeaf();
|
|
2330
|
+
}
|
|
2331
|
+
else {
|
|
2332
|
+
// No summary, navigating to non-root
|
|
2333
|
+
this.sessionManager.branch(newLeafId);
|
|
2334
|
+
}
|
|
2335
|
+
// Attach label to target entry when not summarizing (no summary entry to label)
|
|
2336
|
+
if (label && !summaryText) {
|
|
2337
|
+
this.sessionManager.appendLabelChange(targetId, label);
|
|
2338
|
+
}
|
|
2339
|
+
// Update agent state
|
|
2340
|
+
const sessionContext = this.sessionManager.buildSessionContext();
|
|
2341
|
+
this.agent.state.messages = sessionContext.messages;
|
|
2342
|
+
// Emit session_tree event
|
|
2284
2343
|
await this._extensionRunner.emit({
|
|
2285
2344
|
type: "session_tree",
|
|
2286
2345
|
newLeafId: this.sessionManager.getLeafId(),
|
|
@@ -2288,10 +2347,12 @@ export class AgentSession {
|
|
|
2288
2347
|
summaryEntry,
|
|
2289
2348
|
fromExtension: summaryText ? fromExtension : undefined,
|
|
2290
2349
|
});
|
|
2350
|
+
// Emit to custom tools
|
|
2351
|
+
return { editorText, cancelled: false, summaryEntry };
|
|
2352
|
+
}
|
|
2353
|
+
finally {
|
|
2354
|
+
this._branchSummaryAbortController = undefined;
|
|
2291
2355
|
}
|
|
2292
|
-
// Emit to custom tools
|
|
2293
|
-
this._branchSummaryAbortController = undefined;
|
|
2294
|
-
return { editorText, cancelled: false, summaryEntry };
|
|
2295
2356
|
}
|
|
2296
2357
|
/**
|
|
2297
2358
|
* Get all user messages from session for fork selector.
|
|
@@ -2390,8 +2451,8 @@ export class AgentSession {
|
|
|
2390
2451
|
const contextTokens = calculateContextTokens(assistant.usage);
|
|
2391
2452
|
if (contextTokens > 0) {
|
|
2392
2453
|
hasPostCompactionUsage = true;
|
|
2454
|
+
break;
|
|
2393
2455
|
}
|
|
2394
|
-
break;
|
|
2395
2456
|
}
|
|
2396
2457
|
}
|
|
2397
2458
|
}
|
|
@@ -2413,7 +2474,8 @@ export class AgentSession {
|
|
|
2413
2474
|
* @returns Path to exported file
|
|
2414
2475
|
*/
|
|
2415
2476
|
async exportToHtml(outputPath) {
|
|
2416
|
-
const
|
|
2477
|
+
const configuredThemeName = this.settingsManager.getTheme();
|
|
2478
|
+
const themeName = configuredThemeName && getThemeByName(configuredThemeName) ? configuredThemeName : undefined;
|
|
2417
2479
|
// Create tool renderer if we have an extension runner (for custom tool HTML rendering)
|
|
2418
2480
|
const toolRenderer = createToolHtmlRenderer({
|
|
2419
2481
|
getToolDefinition: (name) => this.getToolDefinition(name),
|
|
@@ -2433,7 +2495,7 @@ export class AgentSession {
|
|
|
2433
2495
|
* @returns The resolved output file path.
|
|
2434
2496
|
*/
|
|
2435
2497
|
exportToJsonl(outputPath) {
|
|
2436
|
-
const filePath =
|
|
2498
|
+
const filePath = resolvePath(outputPath ?? `session-${new Date().toISOString().replace(/[:.]/g, "-")}.jsonl`, process.cwd());
|
|
2437
2499
|
const dir = dirname(filePath);
|
|
2438
2500
|
if (!existsSync(dir)) {
|
|
2439
2501
|
mkdirSync(dir, { recursive: true });
|
|
@@ -2491,11 +2553,17 @@ export class AgentSession {
|
|
|
2491
2553
|
// =========================================================================
|
|
2492
2554
|
// Extension System
|
|
2493
2555
|
// =========================================================================
|
|
2556
|
+
createReplacedSessionContext() {
|
|
2557
|
+
const context = Object.defineProperties({}, Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()));
|
|
2558
|
+
context.sendMessage = (message, options) => this.sendCustomMessage(message, options);
|
|
2559
|
+
context.sendUserMessage = (content, options) => this.sendUserMessage(content, options);
|
|
2560
|
+
return context;
|
|
2561
|
+
}
|
|
2494
2562
|
/**
|
|
2495
2563
|
* Check if extensions have handlers for a specific event type.
|
|
2496
2564
|
*/
|
|
2497
2565
|
hasExtensionHandlers(eventType) {
|
|
2498
|
-
return this._extensionRunner
|
|
2566
|
+
return this._extensionRunner.hasHandlers(eventType);
|
|
2499
2567
|
}
|
|
2500
2568
|
/**
|
|
2501
2569
|
* Get the extension runner (for setting UI context and error handlers).
|