@vandeepunk/pi-coding-agent 0.0.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 +2564 -0
- package/README.md +555 -0
- package/dist/cli/args.d.ts +47 -0
- package/dist/cli/args.d.ts.map +1 -0
- package/dist/cli/args.js +286 -0
- package/dist/cli/args.js.map +1 -0
- package/dist/cli/config-selector.d.ts +14 -0
- package/dist/cli/config-selector.d.ts.map +1 -0
- package/dist/cli/config-selector.js +31 -0
- package/dist/cli/config-selector.js.map +1 -0
- package/dist/cli/file-processor.d.ts +15 -0
- package/dist/cli/file-processor.d.ts.map +1 -0
- package/dist/cli/file-processor.js +79 -0
- package/dist/cli/file-processor.js.map +1 -0
- package/dist/cli/list-models.d.ts +9 -0
- package/dist/cli/list-models.d.ts.map +1 -0
- package/dist/cli/list-models.js +92 -0
- package/dist/cli/list-models.js.map +1 -0
- package/dist/cli/session-picker.d.ts +9 -0
- package/dist/cli/session-picker.d.ts.map +1 -0
- package/dist/cli/session-picker.js +34 -0
- package/dist/cli/session-picker.js.map +1 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +11 -0
- package/dist/cli.js.map +1 -0
- package/dist/config.d.ts +68 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +203 -0
- package/dist/config.js.map +1 -0
- package/dist/core/agent-session.d.ts +574 -0
- package/dist/core/agent-session.d.ts.map +1 -0
- package/dist/core/agent-session.js +2260 -0
- package/dist/core/agent-session.js.map +1 -0
- package/dist/core/auth-storage.d.ts +102 -0
- package/dist/core/auth-storage.d.ts.map +1 -0
- package/dist/core/auth-storage.js +282 -0
- package/dist/core/auth-storage.js.map +1 -0
- package/dist/core/bash-executor.d.ts +47 -0
- package/dist/core/bash-executor.d.ts.map +1 -0
- package/dist/core/bash-executor.js +212 -0
- package/dist/core/bash-executor.js.map +1 -0
- package/dist/core/compaction/branch-summarization.d.ts +86 -0
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -0
- package/dist/core/compaction/branch-summarization.js +242 -0
- package/dist/core/compaction/branch-summarization.js.map +1 -0
- package/dist/core/compaction/compaction.d.ts +121 -0
- package/dist/core/compaction/compaction.d.ts.map +1 -0
- package/dist/core/compaction/compaction.js +607 -0
- package/dist/core/compaction/compaction.js.map +1 -0
- package/dist/core/compaction/index.d.ts +7 -0
- package/dist/core/compaction/index.d.ts.map +1 -0
- package/dist/core/compaction/index.js +7 -0
- package/dist/core/compaction/index.js.map +1 -0
- package/dist/core/compaction/utils.d.ts +35 -0
- package/dist/core/compaction/utils.d.ts.map +1 -0
- package/dist/core/compaction/utils.js +138 -0
- package/dist/core/compaction/utils.js.map +1 -0
- package/dist/core/defaults.d.ts +3 -0
- package/dist/core/defaults.d.ts.map +1 -0
- package/dist/core/defaults.js +2 -0
- package/dist/core/defaults.js.map +1 -0
- package/dist/core/diagnostics.d.ts +15 -0
- package/dist/core/diagnostics.d.ts.map +1 -0
- package/dist/core/diagnostics.js +2 -0
- package/dist/core/diagnostics.js.map +1 -0
- package/dist/core/event-bus.d.ts +9 -0
- package/dist/core/event-bus.d.ts.map +1 -0
- package/dist/core/event-bus.js +25 -0
- package/dist/core/event-bus.js.map +1 -0
- package/dist/core/exec.d.ts +29 -0
- package/dist/core/exec.d.ts.map +1 -0
- package/dist/core/exec.js +71 -0
- package/dist/core/exec.js.map +1 -0
- package/dist/core/export-html/ansi-to-html.d.ts +22 -0
- package/dist/core/export-html/ansi-to-html.d.ts.map +1 -0
- package/dist/core/export-html/ansi-to-html.js +249 -0
- package/dist/core/export-html/ansi-to-html.js.map +1 -0
- package/dist/core/export-html/index.d.ts +34 -0
- package/dist/core/export-html/index.d.ts.map +1 -0
- package/dist/core/export-html/index.js +222 -0
- package/dist/core/export-html/index.js.map +1 -0
- package/dist/core/export-html/template.css +909 -0
- package/dist/core/export-html/template.html +54 -0
- package/dist/core/export-html/template.js +1549 -0
- package/dist/core/export-html/tool-renderer.d.ts +35 -0
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -0
- package/dist/core/export-html/tool-renderer.js +57 -0
- package/dist/core/export-html/tool-renderer.js.map +1 -0
- package/dist/core/export-html/vendor/highlight.min.js +1213 -0
- package/dist/core/export-html/vendor/marked.min.js +6 -0
- package/dist/core/extensions/index.d.ts +11 -0
- package/dist/core/extensions/index.d.ts.map +1 -0
- package/dist/core/extensions/index.js +9 -0
- package/dist/core/extensions/index.js.map +1 -0
- package/dist/core/extensions/loader.d.ts +25 -0
- package/dist/core/extensions/loader.d.ts.map +1 -0
- package/dist/core/extensions/loader.js +400 -0
- package/dist/core/extensions/loader.js.map +1 -0
- package/dist/core/extensions/runner.d.ts +129 -0
- package/dist/core/extensions/runner.d.ts.map +1 -0
- package/dist/core/extensions/runner.js +576 -0
- package/dist/core/extensions/runner.js.map +1 -0
- package/dist/core/extensions/types.d.ts +928 -0
- package/dist/core/extensions/types.d.ts.map +1 -0
- package/dist/core/extensions/types.js +35 -0
- package/dist/core/extensions/types.js.map +1 -0
- package/dist/core/extensions/wrapper.d.ts +27 -0
- package/dist/core/extensions/wrapper.d.ts.map +1 -0
- package/dist/core/extensions/wrapper.js +102 -0
- package/dist/core/extensions/wrapper.js.map +1 -0
- package/dist/core/footer-data-provider.d.ts +32 -0
- package/dist/core/footer-data-provider.d.ts.map +1 -0
- package/dist/core/footer-data-provider.js +134 -0
- package/dist/core/footer-data-provider.js.map +1 -0
- package/dist/core/index.d.ts +9 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/index.js +9 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/keybindings.d.ts +55 -0
- package/dist/core/keybindings.d.ts.map +1 -0
- package/dist/core/keybindings.js +153 -0
- package/dist/core/keybindings.js.map +1 -0
- package/dist/core/messages.d.ts +77 -0
- package/dist/core/messages.d.ts.map +1 -0
- package/dist/core/messages.js +123 -0
- package/dist/core/messages.js.map +1 -0
- package/dist/core/model-registry.d.ts +100 -0
- package/dist/core/model-registry.d.ts.map +1 -0
- package/dist/core/model-registry.js +419 -0
- package/dist/core/model-registry.js.map +1 -0
- package/dist/core/model-resolver.d.ts +76 -0
- package/dist/core/model-resolver.d.ts.map +1 -0
- package/dist/core/model-resolver.js +313 -0
- package/dist/core/model-resolver.js.map +1 -0
- package/dist/core/package-manager.d.ts +131 -0
- package/dist/core/package-manager.d.ts.map +1 -0
- package/dist/core/package-manager.js +1290 -0
- package/dist/core/package-manager.js.map +1 -0
- package/dist/core/prompt-templates.d.ts +50 -0
- package/dist/core/prompt-templates.d.ts.map +1 -0
- package/dist/core/prompt-templates.js +251 -0
- package/dist/core/prompt-templates.js.map +1 -0
- package/dist/core/resolve-config-value.d.ts +17 -0
- package/dist/core/resolve-config-value.d.ts.map +1 -0
- package/dist/core/resolve-config-value.js +59 -0
- package/dist/core/resolve-config-value.js.map +1 -0
- package/dist/core/resource-loader.d.ts +184 -0
- package/dist/core/resource-loader.d.ts.map +1 -0
- package/dist/core/resource-loader.js +673 -0
- package/dist/core/resource-loader.js.map +1 -0
- package/dist/core/sdk.d.ts +90 -0
- package/dist/core/sdk.d.ts.map +1 -0
- package/dist/core/sdk.js +234 -0
- package/dist/core/sdk.js.map +1 -0
- package/dist/core/session-manager.d.ts +323 -0
- package/dist/core/session-manager.d.ts.map +1 -0
- package/dist/core/session-manager.js +1091 -0
- package/dist/core/session-manager.js.map +1 -0
- package/dist/core/settings-manager.d.ts +187 -0
- package/dist/core/settings-manager.d.ts.map +1 -0
- package/dist/core/settings-manager.js +552 -0
- package/dist/core/settings-manager.js.map +1 -0
- package/dist/core/skills.d.ts +58 -0
- package/dist/core/skills.d.ts.map +1 -0
- package/dist/core/skills.js +310 -0
- package/dist/core/skills.js.map +1 -0
- package/dist/core/slash-commands.d.ts +15 -0
- package/dist/core/slash-commands.d.ts.map +1 -0
- package/dist/core/slash-commands.js +21 -0
- package/dist/core/slash-commands.js.map +1 -0
- package/dist/core/system-prompt.d.ts +24 -0
- package/dist/core/system-prompt.d.ts.map +1 -0
- package/dist/core/system-prompt.js +137 -0
- package/dist/core/system-prompt.js.map +1 -0
- package/dist/core/timings.d.ts +7 -0
- package/dist/core/timings.d.ts.map +1 -0
- package/dist/core/timings.js +25 -0
- package/dist/core/timings.js.map +1 -0
- package/dist/core/tools/bash.d.ts +55 -0
- package/dist/core/tools/bash.d.ts.map +1 -0
- package/dist/core/tools/bash.js +242 -0
- package/dist/core/tools/bash.js.map +1 -0
- package/dist/core/tools/edit-diff.d.ts +63 -0
- package/dist/core/tools/edit-diff.d.ts.map +1 -0
- package/dist/core/tools/edit-diff.js +243 -0
- package/dist/core/tools/edit-diff.js.map +1 -0
- package/dist/core/tools/edit.d.ts +39 -0
- package/dist/core/tools/edit.d.ts.map +1 -0
- package/dist/core/tools/edit.js +146 -0
- package/dist/core/tools/edit.js.map +1 -0
- package/dist/core/tools/find.d.ts +39 -0
- package/dist/core/tools/find.d.ts.map +1 -0
- package/dist/core/tools/find.js +206 -0
- package/dist/core/tools/find.js.map +1 -0
- package/dist/core/tools/grep.d.ts +45 -0
- package/dist/core/tools/grep.d.ts.map +1 -0
- package/dist/core/tools/grep.js +239 -0
- package/dist/core/tools/grep.js.map +1 -0
- package/dist/core/tools/index.d.ts +73 -0
- package/dist/core/tools/index.d.ts.map +1 -0
- package/dist/core/tools/index.js +61 -0
- package/dist/core/tools/index.js.map +1 -0
- package/dist/core/tools/ls.d.ts +40 -0
- package/dist/core/tools/ls.d.ts.map +1 -0
- package/dist/core/tools/ls.js +118 -0
- package/dist/core/tools/ls.js.map +1 -0
- package/dist/core/tools/path-utils.d.ts +8 -0
- package/dist/core/tools/path-utils.d.ts.map +1 -0
- package/dist/core/tools/path-utils.js +81 -0
- package/dist/core/tools/path-utils.js.map +1 -0
- package/dist/core/tools/read.d.ts +39 -0
- package/dist/core/tools/read.d.ts.map +1 -0
- package/dist/core/tools/read.js +166 -0
- package/dist/core/tools/read.js.map +1 -0
- package/dist/core/tools/truncate.d.ts +70 -0
- package/dist/core/tools/truncate.d.ts.map +1 -0
- package/dist/core/tools/truncate.js +205 -0
- package/dist/core/tools/truncate.js.map +1 -0
- package/dist/core/tools/write.d.ts +29 -0
- package/dist/core/tools/write.d.ts.map +1 -0
- package/dist/core/tools/write.js +78 -0
- package/dist/core/tools/write.js.map +1 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +42 -0
- package/dist/index.js.map +1 -0
- package/dist/main.d.ts +8 -0
- package/dist/main.d.ts.map +1 -0
- package/dist/main.js +623 -0
- package/dist/main.js.map +1 -0
- package/dist/migrations.d.ts +33 -0
- package/dist/migrations.d.ts.map +1 -0
- package/dist/migrations.js +261 -0
- package/dist/migrations.js.map +1 -0
- package/dist/modes/index.d.ts +9 -0
- package/dist/modes/index.d.ts.map +1 -0
- package/dist/modes/index.js +8 -0
- package/dist/modes/index.js.map +1 -0
- package/dist/modes/interactive/components/armin.d.ts +34 -0
- package/dist/modes/interactive/components/armin.d.ts.map +1 -0
- package/dist/modes/interactive/components/armin.js +333 -0
- package/dist/modes/interactive/components/armin.js.map +1 -0
- package/dist/modes/interactive/components/assistant-message.d.ts +16 -0
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -0
- package/dist/modes/interactive/components/assistant-message.js +91 -0
- package/dist/modes/interactive/components/assistant-message.js.map +1 -0
- package/dist/modes/interactive/components/bash-execution.d.ts +35 -0
- package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -0
- package/dist/modes/interactive/components/bash-execution.js +162 -0
- package/dist/modes/interactive/components/bash-execution.js.map +1 -0
- package/dist/modes/interactive/components/bordered-loader.d.ts +16 -0
- package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -0
- package/dist/modes/interactive/components/bordered-loader.js +51 -0
- package/dist/modes/interactive/components/bordered-loader.js.map +1 -0
- package/dist/modes/interactive/components/branch-summary-message.d.ts +16 -0
- package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -0
- package/dist/modes/interactive/components/branch-summary-message.js +44 -0
- package/dist/modes/interactive/components/branch-summary-message.js.map +1 -0
- package/dist/modes/interactive/components/compaction-summary-message.d.ts +16 -0
- package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -0
- package/dist/modes/interactive/components/compaction-summary-message.js +45 -0
- package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -0
- package/dist/modes/interactive/components/config-selector.d.ts +71 -0
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/config-selector.js +479 -0
- package/dist/modes/interactive/components/config-selector.js.map +1 -0
- package/dist/modes/interactive/components/countdown-timer.d.ts +14 -0
- package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -0
- package/dist/modes/interactive/components/countdown-timer.js +33 -0
- package/dist/modes/interactive/components/countdown-timer.js.map +1 -0
- package/dist/modes/interactive/components/custom-editor.d.ts +21 -0
- package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -0
- package/dist/modes/interactive/components/custom-editor.js +70 -0
- package/dist/modes/interactive/components/custom-editor.js.map +1 -0
- package/dist/modes/interactive/components/custom-message.d.ts +20 -0
- package/dist/modes/interactive/components/custom-message.d.ts.map +1 -0
- package/dist/modes/interactive/components/custom-message.js +79 -0
- package/dist/modes/interactive/components/custom-message.js.map +1 -0
- package/dist/modes/interactive/components/daxnuts.d.ts +23 -0
- package/dist/modes/interactive/components/daxnuts.d.ts.map +1 -0
- package/dist/modes/interactive/components/daxnuts.js +140 -0
- package/dist/modes/interactive/components/daxnuts.js.map +1 -0
- package/dist/modes/interactive/components/diff.d.ts +12 -0
- package/dist/modes/interactive/components/diff.d.ts.map +1 -0
- package/dist/modes/interactive/components/diff.js +133 -0
- package/dist/modes/interactive/components/diff.js.map +1 -0
- package/dist/modes/interactive/components/dynamic-border.d.ts +15 -0
- package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -0
- package/dist/modes/interactive/components/dynamic-border.js +21 -0
- package/dist/modes/interactive/components/dynamic-border.js.map +1 -0
- package/dist/modes/interactive/components/extension-editor.d.ts +17 -0
- package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -0
- package/dist/modes/interactive/components/extension-editor.js +102 -0
- package/dist/modes/interactive/components/extension-editor.js.map +1 -0
- package/dist/modes/interactive/components/extension-input.d.ts +23 -0
- package/dist/modes/interactive/components/extension-input.d.ts.map +1 -0
- package/dist/modes/interactive/components/extension-input.js +61 -0
- package/dist/modes/interactive/components/extension-input.js.map +1 -0
- package/dist/modes/interactive/components/extension-selector.d.ts +24 -0
- package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/extension-selector.js +78 -0
- package/dist/modes/interactive/components/extension-selector.js.map +1 -0
- package/dist/modes/interactive/components/footer.d.ts +26 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -0
- package/dist/modes/interactive/components/footer.js +220 -0
- package/dist/modes/interactive/components/footer.js.map +1 -0
- package/dist/modes/interactive/components/index.d.ts +32 -0
- package/dist/modes/interactive/components/index.d.ts.map +1 -0
- package/dist/modes/interactive/components/index.js +33 -0
- package/dist/modes/interactive/components/index.js.map +1 -0
- package/dist/modes/interactive/components/keybinding-hints.d.ts +41 -0
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -0
- package/dist/modes/interactive/components/keybinding-hints.js +61 -0
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -0
- package/dist/modes/interactive/components/login-dialog.d.ts +42 -0
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -0
- package/dist/modes/interactive/components/login-dialog.js +145 -0
- package/dist/modes/interactive/components/login-dialog.js.map +1 -0
- package/dist/modes/interactive/components/model-selector.d.ts +47 -0
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/model-selector.js +266 -0
- package/dist/modes/interactive/components/model-selector.js.map +1 -0
- package/dist/modes/interactive/components/oauth-selector.d.ts +19 -0
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/oauth-selector.js +97 -0
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -0
- package/dist/modes/interactive/components/scoped-models-selector.d.ts +49 -0
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/scoped-models-selector.js +270 -0
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -0
- package/dist/modes/interactive/components/session-selector-search.d.ts +23 -0
- package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -0
- package/dist/modes/interactive/components/session-selector-search.js +155 -0
- package/dist/modes/interactive/components/session-selector-search.js.map +1 -0
- package/dist/modes/interactive/components/session-selector.d.ts +95 -0
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/session-selector.js +851 -0
- package/dist/modes/interactive/components/session-selector.js.map +1 -0
- package/dist/modes/interactive/components/settings-selector.d.ts +53 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/settings-selector.js +277 -0
- package/dist/modes/interactive/components/settings-selector.js.map +1 -0
- package/dist/modes/interactive/components/show-images-selector.d.ts +10 -0
- package/dist/modes/interactive/components/show-images-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/show-images-selector.js +35 -0
- package/dist/modes/interactive/components/show-images-selector.js.map +1 -0
- package/dist/modes/interactive/components/skill-invocation-message.d.ts +17 -0
- package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -0
- package/dist/modes/interactive/components/skill-invocation-message.js +47 -0
- package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -0
- package/dist/modes/interactive/components/theme-selector.d.ts +11 -0
- package/dist/modes/interactive/components/theme-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/theme-selector.js +46 -0
- package/dist/modes/interactive/components/theme-selector.js.map +1 -0
- package/dist/modes/interactive/components/thinking-selector.d.ts +11 -0
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/thinking-selector.js +47 -0
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -0
- package/dist/modes/interactive/components/tool-execution.d.ts +70 -0
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -0
- package/dist/modes/interactive/components/tool-execution.js +621 -0
- package/dist/modes/interactive/components/tool-execution.js.map +1 -0
- package/dist/modes/interactive/components/tree-selector.d.ts +68 -0
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/tree-selector.js +934 -0
- package/dist/modes/interactive/components/tree-selector.js.map +1 -0
- package/dist/modes/interactive/components/user-message-selector.d.ts +30 -0
- package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/user-message-selector.js +113 -0
- package/dist/modes/interactive/components/user-message-selector.js.map +1 -0
- package/dist/modes/interactive/components/user-message.d.ts +8 -0
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -0
- package/dist/modes/interactive/components/user-message.js +16 -0
- package/dist/modes/interactive/components/user-message.js.map +1 -0
- package/dist/modes/interactive/components/visual-truncate.d.ts +24 -0
- package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -0
- package/dist/modes/interactive/components/visual-truncate.js +33 -0
- package/dist/modes/interactive/components/visual-truncate.js.map +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts +313 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -0
- package/dist/modes/interactive/interactive-mode.js +3664 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -0
- package/dist/modes/interactive/theme/dark.json +85 -0
- package/dist/modes/interactive/theme/light.json +84 -0
- package/dist/modes/interactive/theme/theme-schema.json +335 -0
- package/dist/modes/interactive/theme/theme.d.ts +78 -0
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -0
- package/dist/modes/interactive/theme/theme.js +944 -0
- package/dist/modes/interactive/theme/theme.js.map +1 -0
- package/dist/modes/print-mode.d.ts +28 -0
- package/dist/modes/print-mode.d.ts.map +1 -0
- package/dist/modes/print-mode.js +98 -0
- package/dist/modes/print-mode.js.map +1 -0
- package/dist/modes/rpc/rpc-client.d.ts +217 -0
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -0
- package/dist/modes/rpc/rpc-client.js +405 -0
- package/dist/modes/rpc/rpc-client.js.map +1 -0
- package/dist/modes/rpc/rpc-mode.d.ts +20 -0
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -0
- package/dist/modes/rpc/rpc-mode.js +500 -0
- package/dist/modes/rpc/rpc-mode.js.map +1 -0
- package/dist/modes/rpc/rpc-types.d.ts +409 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -0
- package/dist/modes/rpc/rpc-types.js +8 -0
- package/dist/modes/rpc/rpc-types.js.map +1 -0
- package/dist/utils/changelog.d.ts +21 -0
- package/dist/utils/changelog.d.ts.map +1 -0
- package/dist/utils/changelog.js +87 -0
- package/dist/utils/changelog.js.map +1 -0
- package/dist/utils/clipboard-image.d.ts +11 -0
- package/dist/utils/clipboard-image.d.ts.map +1 -0
- package/dist/utils/clipboard-image.js +162 -0
- package/dist/utils/clipboard-image.js.map +1 -0
- package/dist/utils/clipboard-native.d.ts +7 -0
- package/dist/utils/clipboard-native.d.ts.map +1 -0
- package/dist/utils/clipboard-native.js +14 -0
- package/dist/utils/clipboard-native.js.map +1 -0
- package/dist/utils/clipboard.d.ts +2 -0
- package/dist/utils/clipboard.d.ts.map +1 -0
- package/dist/utils/clipboard.js +67 -0
- package/dist/utils/clipboard.js.map +1 -0
- package/dist/utils/frontmatter.d.ts +8 -0
- package/dist/utils/frontmatter.d.ts.map +1 -0
- package/dist/utils/frontmatter.js +26 -0
- package/dist/utils/frontmatter.js.map +1 -0
- package/dist/utils/git.d.ts +2 -0
- package/dist/utils/git.d.ts.map +1 -0
- package/dist/utils/git.js +6 -0
- package/dist/utils/git.js.map +1 -0
- package/dist/utils/image-convert.d.ts +9 -0
- package/dist/utils/image-convert.d.ts.map +1 -0
- package/dist/utils/image-convert.js +35 -0
- package/dist/utils/image-convert.js.map +1 -0
- package/dist/utils/image-resize.d.ts +36 -0
- package/dist/utils/image-resize.d.ts.map +1 -0
- package/dist/utils/image-resize.js +181 -0
- package/dist/utils/image-resize.js.map +1 -0
- package/dist/utils/mime.d.ts +2 -0
- package/dist/utils/mime.d.ts.map +1 -0
- package/dist/utils/mime.js +26 -0
- package/dist/utils/mime.js.map +1 -0
- package/dist/utils/photon.d.ts +21 -0
- package/dist/utils/photon.d.ts.map +1 -0
- package/dist/utils/photon.js +121 -0
- package/dist/utils/photon.js.map +1 -0
- package/dist/utils/shell.d.ts +26 -0
- package/dist/utils/shell.d.ts.map +1 -0
- package/dist/utils/shell.js +186 -0
- package/dist/utils/shell.js.map +1 -0
- package/dist/utils/sleep.d.ts +5 -0
- package/dist/utils/sleep.d.ts.map +1 -0
- package/dist/utils/sleep.js +17 -0
- package/dist/utils/sleep.js.map +1 -0
- package/dist/utils/tools-manager.d.ts +3 -0
- package/dist/utils/tools-manager.d.ts.map +1 -0
- package/dist/utils/tools-manager.js +201 -0
- package/dist/utils/tools-manager.js.map +1 -0
- package/docs/compaction.md +390 -0
- package/docs/custom-provider.md +539 -0
- package/docs/development.md +69 -0
- package/docs/extensions.md +1827 -0
- package/docs/images/doom-extension.png +0 -0
- package/docs/images/exy.png +0 -0
- package/docs/images/interactive-mode.png +0 -0
- package/docs/images/tree-view.png +0 -0
- package/docs/json.md +79 -0
- package/docs/keybindings.md +174 -0
- package/docs/models.md +254 -0
- package/docs/packages.md +191 -0
- package/docs/prompt-templates.md +67 -0
- package/docs/providers.md +168 -0
- package/docs/rpc.md +1311 -0
- package/docs/sdk.md +957 -0
- package/docs/session.md +412 -0
- package/docs/settings.md +221 -0
- package/docs/shell-aliases.md +13 -0
- package/docs/skills.md +227 -0
- package/docs/terminal-setup.md +70 -0
- package/docs/termux.md +127 -0
- package/docs/themes.md +295 -0
- package/docs/tree.md +219 -0
- package/docs/tui.md +887 -0
- package/docs/windows.md +17 -0
- package/examples/README.md +25 -0
- package/examples/extensions/README.md +202 -0
- package/examples/extensions/antigravity-image-gen.ts +413 -0
- package/examples/extensions/auto-commit-on-exit.ts +49 -0
- package/examples/extensions/bash-spawn-hook.ts +30 -0
- package/examples/extensions/bookmark.ts +50 -0
- package/examples/extensions/claude-rules.ts +86 -0
- package/examples/extensions/commands.ts +72 -0
- package/examples/extensions/confirm-destructive.ts +59 -0
- package/examples/extensions/custom-compaction.ts +114 -0
- package/examples/extensions/custom-footer.ts +64 -0
- package/examples/extensions/custom-header.ts +73 -0
- package/examples/extensions/custom-provider-anthropic/index.ts +604 -0
- package/examples/extensions/custom-provider-anthropic/package-lock.json +24 -0
- package/examples/extensions/custom-provider-anthropic/package.json +19 -0
- package/examples/extensions/custom-provider-gitlab-duo/index.ts +349 -0
- package/examples/extensions/custom-provider-gitlab-duo/package.json +16 -0
- package/examples/extensions/custom-provider-gitlab-duo/test.ts +82 -0
- package/examples/extensions/custom-provider-qwen-cli/index.ts +345 -0
- package/examples/extensions/custom-provider-qwen-cli/package.json +16 -0
- package/examples/extensions/dirty-repo-guard.ts +56 -0
- package/examples/extensions/doom-overlay/README.md +46 -0
- package/examples/extensions/doom-overlay/doom/build/doom.js +21 -0
- package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
- package/examples/extensions/doom-overlay/doom/build.sh +152 -0
- package/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +72 -0
- package/examples/extensions/doom-overlay/doom-component.ts +132 -0
- package/examples/extensions/doom-overlay/doom-engine.ts +173 -0
- package/examples/extensions/doom-overlay/doom-keys.ts +104 -0
- package/examples/extensions/doom-overlay/index.ts +74 -0
- package/examples/extensions/doom-overlay/wad-finder.ts +51 -0
- package/examples/extensions/dynamic-resources/SKILL.md +8 -0
- package/examples/extensions/dynamic-resources/dynamic.json +79 -0
- package/examples/extensions/dynamic-resources/dynamic.md +5 -0
- package/examples/extensions/dynamic-resources/index.ts +15 -0
- package/examples/extensions/event-bus.ts +43 -0
- package/examples/extensions/file-trigger.ts +41 -0
- package/examples/extensions/git-checkpoint.ts +53 -0
- package/examples/extensions/handoff.ts +150 -0
- package/examples/extensions/hello.ts +25 -0
- package/examples/extensions/inline-bash.ts +94 -0
- package/examples/extensions/input-transform.ts +43 -0
- package/examples/extensions/interactive-shell.ts +196 -0
- package/examples/extensions/mac-system-theme.ts +47 -0
- package/examples/extensions/message-renderer.ts +59 -0
- package/examples/extensions/minimal-mode.ts +426 -0
- package/examples/extensions/modal-editor.ts +85 -0
- package/examples/extensions/model-status.ts +31 -0
- package/examples/extensions/notify.ts +55 -0
- package/examples/extensions/overlay-qa-tests.ts +881 -0
- package/examples/extensions/overlay-test.ts +150 -0
- package/examples/extensions/permission-gate.ts +34 -0
- package/examples/extensions/pirate.ts +47 -0
- package/examples/extensions/plan-mode/README.md +65 -0
- package/examples/extensions/plan-mode/index.ts +340 -0
- package/examples/extensions/plan-mode/utils.ts +168 -0
- package/examples/extensions/preset.ts +398 -0
- package/examples/extensions/protected-paths.ts +30 -0
- package/examples/extensions/qna.ts +119 -0
- package/examples/extensions/question.ts +264 -0
- package/examples/extensions/questionnaire.ts +427 -0
- package/examples/extensions/rainbow-editor.ts +88 -0
- package/examples/extensions/rpc-demo.ts +124 -0
- package/examples/extensions/sandbox/index.ts +318 -0
- package/examples/extensions/sandbox/package-lock.json +92 -0
- package/examples/extensions/sandbox/package.json +19 -0
- package/examples/extensions/send-user-message.ts +97 -0
- package/examples/extensions/session-name.ts +27 -0
- package/examples/extensions/shutdown-command.ts +63 -0
- package/examples/extensions/snake.ts +343 -0
- package/examples/extensions/space-invaders.ts +560 -0
- package/examples/extensions/ssh.ts +220 -0
- package/examples/extensions/status-line.ts +40 -0
- package/examples/extensions/subagent/README.md +172 -0
- package/examples/extensions/subagent/agents/planner.md +37 -0
- package/examples/extensions/subagent/agents/reviewer.md +35 -0
- package/examples/extensions/subagent/agents/scout.md +50 -0
- package/examples/extensions/subagent/agents/worker.md +24 -0
- package/examples/extensions/subagent/agents.ts +127 -0
- package/examples/extensions/subagent/index.ts +963 -0
- package/examples/extensions/subagent/prompts/implement-and-review.md +10 -0
- package/examples/extensions/subagent/prompts/implement.md +10 -0
- package/examples/extensions/subagent/prompts/scout-and-plan.md +9 -0
- package/examples/extensions/summarize.ts +195 -0
- package/examples/extensions/system-prompt-header.ts +17 -0
- package/examples/extensions/timed-confirm.ts +70 -0
- package/examples/extensions/titlebar-spinner.ts +58 -0
- package/examples/extensions/todo.ts +299 -0
- package/examples/extensions/tool-override.ts +143 -0
- package/examples/extensions/tools.ts +146 -0
- package/examples/extensions/trigger-compact.ts +40 -0
- package/examples/extensions/truncated-tool.ts +192 -0
- package/examples/extensions/widget-placement.ts +17 -0
- package/examples/extensions/with-deps/index.ts +36 -0
- package/examples/extensions/with-deps/package-lock.json +31 -0
- package/examples/extensions/with-deps/package.json +22 -0
- package/examples/rpc-extension-ui.ts +632 -0
- package/examples/sdk/01-minimal.ts +22 -0
- package/examples/sdk/02-custom-model.ts +49 -0
- package/examples/sdk/03-custom-prompt.ts +55 -0
- package/examples/sdk/04-skills.ts +46 -0
- package/examples/sdk/05-tools.ts +56 -0
- package/examples/sdk/06-extensions.ts +88 -0
- package/examples/sdk/07-context-files.ts +40 -0
- package/examples/sdk/08-prompt-templates.ts +47 -0
- package/examples/sdk/09-api-keys-and-oauth.ts +48 -0
- package/examples/sdk/10-settings.ts +38 -0
- package/examples/sdk/11-sessions.ts +48 -0
- package/examples/sdk/12-full-control.ts +82 -0
- package/examples/sdk/README.md +144 -0
- package/package.json +97 -0
|
@@ -0,0 +1,2260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AgentSession - Core abstraction for agent lifecycle and session management.
|
|
3
|
+
*
|
|
4
|
+
* This class is shared between all run modes (interactive, print, rpc).
|
|
5
|
+
* It encapsulates:
|
|
6
|
+
* - Agent state access
|
|
7
|
+
* - Event subscription with automatic session persistence
|
|
8
|
+
* - Model and thinking level management
|
|
9
|
+
* - Compaction (manual and auto)
|
|
10
|
+
* - Bash execution
|
|
11
|
+
* - Session switching and branching
|
|
12
|
+
*
|
|
13
|
+
* Modes use this class and add their own I/O layer on top.
|
|
14
|
+
*/
|
|
15
|
+
import { readFileSync } from "node:fs";
|
|
16
|
+
import { basename, dirname, join } from "node:path";
|
|
17
|
+
import { isContextOverflow, modelsAreEqual, resetApiProviders, supportsXhigh } from "@mariozechner/pi-ai";
|
|
18
|
+
import { getDocsPath } from "../config.js";
|
|
19
|
+
import { theme } from "../modes/interactive/theme/theme.js";
|
|
20
|
+
import { stripFrontmatter } from "../utils/frontmatter.js";
|
|
21
|
+
import { sleep } from "../utils/sleep.js";
|
|
22
|
+
import { executeBash as executeBashCommand, executeBashWithOperations } from "./bash-executor.js";
|
|
23
|
+
import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
|
|
24
|
+
import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
|
|
25
|
+
import { exportSessionToHtml } from "./export-html/index.js";
|
|
26
|
+
import { createToolHtmlRenderer } from "./export-html/tool-renderer.js";
|
|
27
|
+
import { ExtensionRunner, wrapRegisteredTools, wrapToolsWithExtensions, } from "./extensions/index.js";
|
|
28
|
+
import { expandPromptTemplate } from "./prompt-templates.js";
|
|
29
|
+
import { BUILTIN_SLASH_COMMANDS } from "./slash-commands.js";
|
|
30
|
+
import { buildSystemPrompt } from "./system-prompt.js";
|
|
31
|
+
import { createAllTools } from "./tools/index.js";
|
|
32
|
+
/**
|
|
33
|
+
* Parse a skill block from message text.
|
|
34
|
+
* Returns null if the text doesn't contain a skill block.
|
|
35
|
+
*/
|
|
36
|
+
export function parseSkillBlock(text) {
|
|
37
|
+
const match = text.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);
|
|
38
|
+
if (!match)
|
|
39
|
+
return null;
|
|
40
|
+
return {
|
|
41
|
+
name: match[1],
|
|
42
|
+
location: match[2],
|
|
43
|
+
content: match[3],
|
|
44
|
+
userMessage: match[4]?.trim() || undefined,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
// ============================================================================
|
|
48
|
+
// Constants
|
|
49
|
+
// ============================================================================
|
|
50
|
+
/** Standard thinking levels */
|
|
51
|
+
const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high"];
|
|
52
|
+
/** Thinking levels including xhigh (for supported models) */
|
|
53
|
+
const THINKING_LEVELS_WITH_XHIGH = ["off", "minimal", "low", "medium", "high", "xhigh"];
|
|
54
|
+
// ============================================================================
|
|
55
|
+
// AgentSession Class
|
|
56
|
+
// ============================================================================
|
|
57
|
+
export class AgentSession {
|
|
58
|
+
agent;
|
|
59
|
+
sessionManager;
|
|
60
|
+
settingsManager;
|
|
61
|
+
_scopedModels;
|
|
62
|
+
// Event subscription state
|
|
63
|
+
_unsubscribeAgent;
|
|
64
|
+
_eventListeners = [];
|
|
65
|
+
/** Tracks pending steering messages for UI display. Removed when delivered. */
|
|
66
|
+
_steeringMessages = [];
|
|
67
|
+
/** Tracks pending follow-up messages for UI display. Removed when delivered. */
|
|
68
|
+
_followUpMessages = [];
|
|
69
|
+
/** Messages queued to be included with the next user prompt as context ("asides"). */
|
|
70
|
+
_pendingNextTurnMessages = [];
|
|
71
|
+
// Compaction state
|
|
72
|
+
_compactionAbortController = undefined;
|
|
73
|
+
_autoCompactionAbortController = undefined;
|
|
74
|
+
// Branch summarization state
|
|
75
|
+
_branchSummaryAbortController = undefined;
|
|
76
|
+
// Retry state
|
|
77
|
+
_retryAbortController = undefined;
|
|
78
|
+
_retryAttempt = 0;
|
|
79
|
+
_retryPromise = undefined;
|
|
80
|
+
_retryResolve = undefined;
|
|
81
|
+
// Bash execution state
|
|
82
|
+
_bashAbortController = undefined;
|
|
83
|
+
_pendingBashMessages = [];
|
|
84
|
+
// Extension system
|
|
85
|
+
_extensionRunner = undefined;
|
|
86
|
+
_turnIndex = 0;
|
|
87
|
+
_resourceLoader;
|
|
88
|
+
_customTools;
|
|
89
|
+
_baseToolRegistry = new Map();
|
|
90
|
+
_cwd;
|
|
91
|
+
_extensionRunnerRef;
|
|
92
|
+
_initialActiveToolNames;
|
|
93
|
+
_baseToolsOverride;
|
|
94
|
+
_extensionUIContext;
|
|
95
|
+
_extensionCommandContextActions;
|
|
96
|
+
_extensionShutdownHandler;
|
|
97
|
+
_extensionErrorListener;
|
|
98
|
+
_extensionErrorUnsubscriber;
|
|
99
|
+
// Model registry for API key resolution
|
|
100
|
+
_modelRegistry;
|
|
101
|
+
// Tool registry for extension getTools/setTools
|
|
102
|
+
_toolRegistry = new Map();
|
|
103
|
+
// Base system prompt (without extension appends) - used to apply fresh appends each turn
|
|
104
|
+
_baseSystemPrompt = "";
|
|
105
|
+
constructor(config) {
|
|
106
|
+
this.agent = config.agent;
|
|
107
|
+
this.sessionManager = config.sessionManager;
|
|
108
|
+
this.settingsManager = config.settingsManager;
|
|
109
|
+
this._scopedModels = config.scopedModels ?? [];
|
|
110
|
+
this._resourceLoader = config.resourceLoader;
|
|
111
|
+
this._customTools = config.customTools ?? [];
|
|
112
|
+
this._cwd = config.cwd;
|
|
113
|
+
this._modelRegistry = config.modelRegistry;
|
|
114
|
+
this._extensionRunnerRef = config.extensionRunnerRef;
|
|
115
|
+
this._initialActiveToolNames = config.initialActiveToolNames;
|
|
116
|
+
this._baseToolsOverride = config.baseToolsOverride;
|
|
117
|
+
// Always subscribe to agent events for internal handling
|
|
118
|
+
// (session persistence, extensions, auto-compaction, retry logic)
|
|
119
|
+
this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
|
|
120
|
+
this._buildRuntime({
|
|
121
|
+
activeToolNames: this._initialActiveToolNames,
|
|
122
|
+
includeAllExtensionTools: true,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
/** Model registry for API key resolution and model discovery */
|
|
126
|
+
get modelRegistry() {
|
|
127
|
+
return this._modelRegistry;
|
|
128
|
+
}
|
|
129
|
+
// =========================================================================
|
|
130
|
+
// Event Subscription
|
|
131
|
+
// =========================================================================
|
|
132
|
+
/** Emit an event to all listeners */
|
|
133
|
+
_emit(event) {
|
|
134
|
+
for (const l of this._eventListeners) {
|
|
135
|
+
l(event);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
// Track last assistant message for auto-compaction check
|
|
139
|
+
_lastAssistantMessage = undefined;
|
|
140
|
+
/** Internal handler for agent events - shared by subscribe and reconnect */
|
|
141
|
+
_handleAgentEvent = async (event) => {
|
|
142
|
+
// When a user message starts, check if it's from either queue and remove it BEFORE emitting
|
|
143
|
+
// This ensures the UI sees the updated queue state
|
|
144
|
+
if (event.type === "message_start" && event.message.role === "user") {
|
|
145
|
+
const messageText = this._getUserMessageText(event.message);
|
|
146
|
+
if (messageText) {
|
|
147
|
+
// Check steering queue first
|
|
148
|
+
const steeringIndex = this._steeringMessages.indexOf(messageText);
|
|
149
|
+
if (steeringIndex !== -1) {
|
|
150
|
+
this._steeringMessages.splice(steeringIndex, 1);
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
// Check follow-up queue
|
|
154
|
+
const followUpIndex = this._followUpMessages.indexOf(messageText);
|
|
155
|
+
if (followUpIndex !== -1) {
|
|
156
|
+
this._followUpMessages.splice(followUpIndex, 1);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
// Emit to extensions first
|
|
162
|
+
await this._emitExtensionEvent(event);
|
|
163
|
+
// Notify all listeners
|
|
164
|
+
this._emit(event);
|
|
165
|
+
// Handle session persistence
|
|
166
|
+
if (event.type === "message_end") {
|
|
167
|
+
// Check if this is a custom message from extensions
|
|
168
|
+
if (event.message.role === "custom") {
|
|
169
|
+
// Persist as CustomMessageEntry
|
|
170
|
+
this.sessionManager.appendCustomMessageEntry(event.message.customType, event.message.content, event.message.display, event.message.details);
|
|
171
|
+
}
|
|
172
|
+
else if (event.message.role === "user" ||
|
|
173
|
+
event.message.role === "assistant" ||
|
|
174
|
+
event.message.role === "toolResult") {
|
|
175
|
+
// Regular LLM message - persist as SessionMessageEntry
|
|
176
|
+
this.sessionManager.appendMessage(event.message);
|
|
177
|
+
}
|
|
178
|
+
// Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
|
|
179
|
+
// Track assistant message for auto-compaction (checked on agent_end)
|
|
180
|
+
if (event.message.role === "assistant") {
|
|
181
|
+
this._lastAssistantMessage = event.message;
|
|
182
|
+
// Reset retry counter immediately on successful assistant response
|
|
183
|
+
// This prevents accumulation across multiple LLM calls within a turn
|
|
184
|
+
const assistantMsg = event.message;
|
|
185
|
+
if (assistantMsg.stopReason !== "error" && this._retryAttempt > 0) {
|
|
186
|
+
this._emit({
|
|
187
|
+
type: "auto_retry_end",
|
|
188
|
+
success: true,
|
|
189
|
+
attempt: this._retryAttempt,
|
|
190
|
+
});
|
|
191
|
+
this._retryAttempt = 0;
|
|
192
|
+
this._resolveRetry();
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
// Check auto-retry and auto-compaction after agent completes
|
|
197
|
+
if (event.type === "agent_end" && this._lastAssistantMessage) {
|
|
198
|
+
const msg = this._lastAssistantMessage;
|
|
199
|
+
this._lastAssistantMessage = undefined;
|
|
200
|
+
// Check for retryable errors first (overloaded, rate limit, server errors)
|
|
201
|
+
if (this._isRetryableError(msg)) {
|
|
202
|
+
const didRetry = await this._handleRetryableError(msg);
|
|
203
|
+
if (didRetry)
|
|
204
|
+
return; // Retry was initiated, don't proceed to compaction
|
|
205
|
+
}
|
|
206
|
+
await this._checkCompaction(msg);
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
/** Resolve the pending retry promise */
|
|
210
|
+
_resolveRetry() {
|
|
211
|
+
if (this._retryResolve) {
|
|
212
|
+
this._retryResolve();
|
|
213
|
+
this._retryResolve = undefined;
|
|
214
|
+
this._retryPromise = undefined;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
/** Extract text content from a message */
|
|
218
|
+
_getUserMessageText(message) {
|
|
219
|
+
if (message.role !== "user")
|
|
220
|
+
return "";
|
|
221
|
+
const content = message.content;
|
|
222
|
+
if (typeof content === "string")
|
|
223
|
+
return content;
|
|
224
|
+
const textBlocks = content.filter((c) => c.type === "text");
|
|
225
|
+
return textBlocks.map((c) => c.text).join("");
|
|
226
|
+
}
|
|
227
|
+
/** Find the last assistant message in agent state (including aborted ones) */
|
|
228
|
+
_findLastAssistantMessage() {
|
|
229
|
+
const messages = this.agent.state.messages;
|
|
230
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
231
|
+
const msg = messages[i];
|
|
232
|
+
if (msg.role === "assistant") {
|
|
233
|
+
return msg;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return undefined;
|
|
237
|
+
}
|
|
238
|
+
/** Emit extension events based on agent events */
|
|
239
|
+
async _emitExtensionEvent(event) {
|
|
240
|
+
if (!this._extensionRunner)
|
|
241
|
+
return;
|
|
242
|
+
if (event.type === "agent_start") {
|
|
243
|
+
this._turnIndex = 0;
|
|
244
|
+
await this._extensionRunner.emit({ type: "agent_start" });
|
|
245
|
+
}
|
|
246
|
+
else if (event.type === "agent_end") {
|
|
247
|
+
await this._extensionRunner.emit({ type: "agent_end", messages: event.messages });
|
|
248
|
+
}
|
|
249
|
+
else if (event.type === "turn_start") {
|
|
250
|
+
const extensionEvent = {
|
|
251
|
+
type: "turn_start",
|
|
252
|
+
turnIndex: this._turnIndex,
|
|
253
|
+
timestamp: Date.now(),
|
|
254
|
+
};
|
|
255
|
+
await this._extensionRunner.emit(extensionEvent);
|
|
256
|
+
}
|
|
257
|
+
else if (event.type === "turn_end") {
|
|
258
|
+
const extensionEvent = {
|
|
259
|
+
type: "turn_end",
|
|
260
|
+
turnIndex: this._turnIndex,
|
|
261
|
+
message: event.message,
|
|
262
|
+
toolResults: event.toolResults,
|
|
263
|
+
};
|
|
264
|
+
await this._extensionRunner.emit(extensionEvent);
|
|
265
|
+
this._turnIndex++;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Subscribe to agent events.
|
|
270
|
+
* Session persistence is handled internally (saves messages on message_end).
|
|
271
|
+
* Multiple listeners can be added. Returns unsubscribe function for this listener.
|
|
272
|
+
*/
|
|
273
|
+
subscribe(listener) {
|
|
274
|
+
this._eventListeners.push(listener);
|
|
275
|
+
// Return unsubscribe function for this specific listener
|
|
276
|
+
return () => {
|
|
277
|
+
const index = this._eventListeners.indexOf(listener);
|
|
278
|
+
if (index !== -1) {
|
|
279
|
+
this._eventListeners.splice(index, 1);
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Temporarily disconnect from agent events.
|
|
285
|
+
* User listeners are preserved and will receive events again after resubscribe().
|
|
286
|
+
* Used internally during operations that need to pause event processing.
|
|
287
|
+
*/
|
|
288
|
+
_disconnectFromAgent() {
|
|
289
|
+
if (this._unsubscribeAgent) {
|
|
290
|
+
this._unsubscribeAgent();
|
|
291
|
+
this._unsubscribeAgent = undefined;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Reconnect to agent events after _disconnectFromAgent().
|
|
296
|
+
* Preserves all existing listeners.
|
|
297
|
+
*/
|
|
298
|
+
_reconnectToAgent() {
|
|
299
|
+
if (this._unsubscribeAgent)
|
|
300
|
+
return; // Already connected
|
|
301
|
+
this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Remove all listeners and disconnect from agent.
|
|
305
|
+
* Call this when completely done with the session.
|
|
306
|
+
*/
|
|
307
|
+
dispose() {
|
|
308
|
+
this._disconnectFromAgent();
|
|
309
|
+
this._eventListeners = [];
|
|
310
|
+
}
|
|
311
|
+
// =========================================================================
|
|
312
|
+
// Read-only State Access
|
|
313
|
+
// =========================================================================
|
|
314
|
+
/** Full agent state */
|
|
315
|
+
get state() {
|
|
316
|
+
return this.agent.state;
|
|
317
|
+
}
|
|
318
|
+
/** Current model (may be undefined if not yet selected) */
|
|
319
|
+
get model() {
|
|
320
|
+
return this.agent.state.model;
|
|
321
|
+
}
|
|
322
|
+
/** Current thinking level */
|
|
323
|
+
get thinkingLevel() {
|
|
324
|
+
return this.agent.state.thinkingLevel;
|
|
325
|
+
}
|
|
326
|
+
/** Whether agent is currently streaming a response */
|
|
327
|
+
get isStreaming() {
|
|
328
|
+
return this.agent.state.isStreaming;
|
|
329
|
+
}
|
|
330
|
+
/** Current effective system prompt (includes any per-turn extension modifications) */
|
|
331
|
+
get systemPrompt() {
|
|
332
|
+
return this.agent.state.systemPrompt;
|
|
333
|
+
}
|
|
334
|
+
/** Current retry attempt (0 if not retrying) */
|
|
335
|
+
get retryAttempt() {
|
|
336
|
+
return this._retryAttempt;
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Get the names of currently active tools.
|
|
340
|
+
* Returns the names of tools currently set on the agent.
|
|
341
|
+
*/
|
|
342
|
+
getActiveToolNames() {
|
|
343
|
+
return this.agent.state.tools.map((t) => t.name);
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Get all configured tools with name and description.
|
|
347
|
+
*/
|
|
348
|
+
getAllTools() {
|
|
349
|
+
return Array.from(this._toolRegistry.values()).map((t) => ({
|
|
350
|
+
name: t.name,
|
|
351
|
+
description: t.description,
|
|
352
|
+
}));
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Set active tools by name.
|
|
356
|
+
* Only tools in the registry can be enabled. Unknown tool names are ignored.
|
|
357
|
+
* Also rebuilds the system prompt to reflect the new tool set.
|
|
358
|
+
* Changes take effect on the next agent turn.
|
|
359
|
+
*/
|
|
360
|
+
setActiveToolsByName(toolNames) {
|
|
361
|
+
const tools = [];
|
|
362
|
+
const validToolNames = [];
|
|
363
|
+
for (const name of toolNames) {
|
|
364
|
+
const tool = this._toolRegistry.get(name);
|
|
365
|
+
if (tool) {
|
|
366
|
+
tools.push(tool);
|
|
367
|
+
validToolNames.push(name);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
this.agent.setTools(tools);
|
|
371
|
+
// Rebuild base system prompt with new tool set
|
|
372
|
+
this._baseSystemPrompt = this._rebuildSystemPrompt(validToolNames);
|
|
373
|
+
this.agent.setSystemPrompt(this._baseSystemPrompt);
|
|
374
|
+
}
|
|
375
|
+
/** Whether auto-compaction is currently running */
|
|
376
|
+
get isCompacting() {
|
|
377
|
+
return this._autoCompactionAbortController !== undefined || this._compactionAbortController !== undefined;
|
|
378
|
+
}
|
|
379
|
+
/** All messages including custom types like BashExecutionMessage */
|
|
380
|
+
get messages() {
|
|
381
|
+
return this.agent.state.messages;
|
|
382
|
+
}
|
|
383
|
+
/** Current steering mode */
|
|
384
|
+
get steeringMode() {
|
|
385
|
+
return this.agent.getSteeringMode();
|
|
386
|
+
}
|
|
387
|
+
/** Current follow-up mode */
|
|
388
|
+
get followUpMode() {
|
|
389
|
+
return this.agent.getFollowUpMode();
|
|
390
|
+
}
|
|
391
|
+
/** Current session file path, or undefined if sessions are disabled */
|
|
392
|
+
get sessionFile() {
|
|
393
|
+
return this.sessionManager.getSessionFile();
|
|
394
|
+
}
|
|
395
|
+
/** Current session ID */
|
|
396
|
+
get sessionId() {
|
|
397
|
+
return this.sessionManager.getSessionId();
|
|
398
|
+
}
|
|
399
|
+
/** Current session display name, if set */
|
|
400
|
+
get sessionName() {
|
|
401
|
+
return this.sessionManager.getSessionName();
|
|
402
|
+
}
|
|
403
|
+
/** Scoped models for cycling (from --models flag) */
|
|
404
|
+
get scopedModels() {
|
|
405
|
+
return this._scopedModels;
|
|
406
|
+
}
|
|
407
|
+
/** Update scoped models for cycling */
|
|
408
|
+
setScopedModels(scopedModels) {
|
|
409
|
+
this._scopedModels = scopedModels;
|
|
410
|
+
}
|
|
411
|
+
/** File-based prompt templates */
|
|
412
|
+
get promptTemplates() {
|
|
413
|
+
return this._resourceLoader.getPrompts().prompts;
|
|
414
|
+
}
|
|
415
|
+
_rebuildSystemPrompt(toolNames) {
|
|
416
|
+
const validToolNames = toolNames.filter((name) => this._baseToolRegistry.has(name));
|
|
417
|
+
const loaderSystemPrompt = this._resourceLoader.getSystemPrompt();
|
|
418
|
+
const loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();
|
|
419
|
+
const appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : undefined;
|
|
420
|
+
const loadedSkills = this._resourceLoader.getSkills().skills;
|
|
421
|
+
const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
|
|
422
|
+
return buildSystemPrompt({
|
|
423
|
+
cwd: this._cwd,
|
|
424
|
+
skills: loadedSkills,
|
|
425
|
+
contextFiles: loadedContextFiles,
|
|
426
|
+
customPrompt: loaderSystemPrompt,
|
|
427
|
+
appendSystemPrompt,
|
|
428
|
+
selectedTools: validToolNames,
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
// =========================================================================
|
|
432
|
+
// Prompting
|
|
433
|
+
// =========================================================================
|
|
434
|
+
/**
|
|
435
|
+
* Send a prompt to the agent.
|
|
436
|
+
* - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming
|
|
437
|
+
* - Expands file-based prompt templates by default
|
|
438
|
+
* - During streaming, queues via steer() or followUp() based on streamingBehavior option
|
|
439
|
+
* - Validates model and API key before sending (when not streaming)
|
|
440
|
+
* @throws Error if streaming and no streamingBehavior specified
|
|
441
|
+
* @throws Error if no model selected or no API key available (when not streaming)
|
|
442
|
+
*/
|
|
443
|
+
async prompt(text, options) {
|
|
444
|
+
const expandPromptTemplates = options?.expandPromptTemplates ?? true;
|
|
445
|
+
// Handle extension commands first (execute immediately, even during streaming)
|
|
446
|
+
// Extension commands manage their own LLM interaction via pi.sendMessage()
|
|
447
|
+
if (expandPromptTemplates && text.startsWith("/")) {
|
|
448
|
+
const handled = await this._tryExecuteExtensionCommand(text);
|
|
449
|
+
if (handled) {
|
|
450
|
+
// Extension command executed, no prompt to send
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
// Emit input event for extension interception (before skill/template expansion)
|
|
455
|
+
let currentText = text;
|
|
456
|
+
let currentImages = options?.images;
|
|
457
|
+
if (this._extensionRunner?.hasHandlers("input")) {
|
|
458
|
+
const inputResult = await this._extensionRunner.emitInput(currentText, currentImages, options?.source ?? "interactive");
|
|
459
|
+
if (inputResult.action === "handled") {
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
if (inputResult.action === "transform") {
|
|
463
|
+
currentText = inputResult.text;
|
|
464
|
+
currentImages = inputResult.images ?? currentImages;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
// Expand skill commands (/skill:name args) and prompt templates (/template args)
|
|
468
|
+
let expandedText = currentText;
|
|
469
|
+
if (expandPromptTemplates) {
|
|
470
|
+
expandedText = this._expandSkillCommand(expandedText);
|
|
471
|
+
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
|
|
472
|
+
}
|
|
473
|
+
// If streaming, queue via steer() or followUp() based on option
|
|
474
|
+
if (this.isStreaming) {
|
|
475
|
+
if (!options?.streamingBehavior) {
|
|
476
|
+
throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
|
|
477
|
+
}
|
|
478
|
+
if (options.streamingBehavior === "followUp") {
|
|
479
|
+
await this._queueFollowUp(expandedText, currentImages);
|
|
480
|
+
}
|
|
481
|
+
else {
|
|
482
|
+
await this._queueSteer(expandedText, currentImages);
|
|
483
|
+
}
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
// Flush any pending bash messages before the new prompt
|
|
487
|
+
this._flushPendingBashMessages();
|
|
488
|
+
// Validate model
|
|
489
|
+
if (!this.model) {
|
|
490
|
+
throw new Error("No model selected.\n\n" +
|
|
491
|
+
`Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}\n\n` +
|
|
492
|
+
"Then use /model to select a model.");
|
|
493
|
+
}
|
|
494
|
+
// Validate API key
|
|
495
|
+
const apiKey = await this._modelRegistry.getApiKey(this.model);
|
|
496
|
+
if (!apiKey) {
|
|
497
|
+
const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
|
|
498
|
+
if (isOAuth) {
|
|
499
|
+
throw new Error(`Authentication failed for "${this.model.provider}". ` +
|
|
500
|
+
`Credentials may have expired or network is unavailable. ` +
|
|
501
|
+
`Run '/login ${this.model.provider}' to re-authenticate.`);
|
|
502
|
+
}
|
|
503
|
+
throw new Error(`No API key found for ${this.model.provider}.\n\n` +
|
|
504
|
+
`Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}`);
|
|
505
|
+
}
|
|
506
|
+
// Check if we need to compact before sending (catches aborted responses)
|
|
507
|
+
const lastAssistant = this._findLastAssistantMessage();
|
|
508
|
+
if (lastAssistant) {
|
|
509
|
+
await this._checkCompaction(lastAssistant, false);
|
|
510
|
+
}
|
|
511
|
+
// Build messages array (custom message if any, then user message)
|
|
512
|
+
const messages = [];
|
|
513
|
+
// Add user message
|
|
514
|
+
const userContent = [{ type: "text", text: expandedText }];
|
|
515
|
+
if (currentImages) {
|
|
516
|
+
userContent.push(...currentImages);
|
|
517
|
+
}
|
|
518
|
+
messages.push({
|
|
519
|
+
role: "user",
|
|
520
|
+
content: userContent,
|
|
521
|
+
timestamp: Date.now(),
|
|
522
|
+
});
|
|
523
|
+
// Inject any pending "nextTurn" messages as context alongside the user message
|
|
524
|
+
for (const msg of this._pendingNextTurnMessages) {
|
|
525
|
+
messages.push(msg);
|
|
526
|
+
}
|
|
527
|
+
this._pendingNextTurnMessages = [];
|
|
528
|
+
// Emit before_agent_start extension event
|
|
529
|
+
if (this._extensionRunner) {
|
|
530
|
+
const result = await this._extensionRunner.emitBeforeAgentStart(expandedText, currentImages, this._baseSystemPrompt);
|
|
531
|
+
// Add all custom messages from extensions
|
|
532
|
+
if (result?.messages) {
|
|
533
|
+
for (const msg of result.messages) {
|
|
534
|
+
messages.push({
|
|
535
|
+
role: "custom",
|
|
536
|
+
customType: msg.customType,
|
|
537
|
+
content: msg.content,
|
|
538
|
+
display: msg.display,
|
|
539
|
+
details: msg.details,
|
|
540
|
+
timestamp: Date.now(),
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
// Apply extension-modified system prompt, or reset to base
|
|
545
|
+
if (result?.systemPrompt) {
|
|
546
|
+
this.agent.setSystemPrompt(result.systemPrompt);
|
|
547
|
+
}
|
|
548
|
+
else {
|
|
549
|
+
// Ensure we're using the base prompt (in case previous turn had modifications)
|
|
550
|
+
this.agent.setSystemPrompt(this._baseSystemPrompt);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
await this.agent.prompt(messages);
|
|
554
|
+
await this.waitForRetry();
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Try to execute an extension command. Returns true if command was found and executed.
|
|
558
|
+
*/
|
|
559
|
+
async _tryExecuteExtensionCommand(text) {
|
|
560
|
+
if (!this._extensionRunner)
|
|
561
|
+
return false;
|
|
562
|
+
// Parse command name and args
|
|
563
|
+
const spaceIndex = text.indexOf(" ");
|
|
564
|
+
const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
|
|
565
|
+
const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
|
|
566
|
+
const command = this._extensionRunner.getCommand(commandName);
|
|
567
|
+
if (!command)
|
|
568
|
+
return false;
|
|
569
|
+
// Get command context from extension runner (includes session control methods)
|
|
570
|
+
const ctx = this._extensionRunner.createCommandContext();
|
|
571
|
+
try {
|
|
572
|
+
await command.handler(args, ctx);
|
|
573
|
+
return true;
|
|
574
|
+
}
|
|
575
|
+
catch (err) {
|
|
576
|
+
// Emit error via extension runner
|
|
577
|
+
this._extensionRunner.emitError({
|
|
578
|
+
extensionPath: `command:${commandName}`,
|
|
579
|
+
event: "command",
|
|
580
|
+
error: err instanceof Error ? err.message : String(err),
|
|
581
|
+
});
|
|
582
|
+
return true;
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* Expand skill commands (/skill:name args) to their full content.
|
|
587
|
+
* Returns the expanded text, or the original text if not a skill command or skill not found.
|
|
588
|
+
* Emits errors via extension runner if file read fails.
|
|
589
|
+
*/
|
|
590
|
+
_expandSkillCommand(text) {
|
|
591
|
+
if (!text.startsWith("/skill:"))
|
|
592
|
+
return text;
|
|
593
|
+
const spaceIndex = text.indexOf(" ");
|
|
594
|
+
const skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);
|
|
595
|
+
const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1).trim();
|
|
596
|
+
const skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);
|
|
597
|
+
if (!skill)
|
|
598
|
+
return text; // Unknown skill, pass through
|
|
599
|
+
try {
|
|
600
|
+
const content = readFileSync(skill.filePath, "utf-8");
|
|
601
|
+
const body = stripFrontmatter(content).trim();
|
|
602
|
+
const skillBlock = `<skill name="${skill.name}" location="${skill.filePath}">\nReferences are relative to ${skill.baseDir}.\n\n${body}\n</skill>`;
|
|
603
|
+
return args ? `${skillBlock}\n\n${args}` : skillBlock;
|
|
604
|
+
}
|
|
605
|
+
catch (err) {
|
|
606
|
+
// Emit error like extension commands do
|
|
607
|
+
this._extensionRunner?.emitError({
|
|
608
|
+
extensionPath: skill.filePath,
|
|
609
|
+
event: "skill_expansion",
|
|
610
|
+
error: err instanceof Error ? err.message : String(err),
|
|
611
|
+
});
|
|
612
|
+
return text; // Return original on error
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Queue a steering message to interrupt the agent mid-run.
|
|
617
|
+
* Delivered after current tool execution, skips remaining tools.
|
|
618
|
+
* Expands skill commands and prompt templates. Errors on extension commands.
|
|
619
|
+
* @param images Optional image attachments to include with the message
|
|
620
|
+
* @throws Error if text is an extension command
|
|
621
|
+
*/
|
|
622
|
+
async steer(text, images) {
|
|
623
|
+
// Check for extension commands (cannot be queued)
|
|
624
|
+
if (text.startsWith("/")) {
|
|
625
|
+
this._throwIfExtensionCommand(text);
|
|
626
|
+
}
|
|
627
|
+
// Expand skill commands and prompt templates
|
|
628
|
+
let expandedText = this._expandSkillCommand(text);
|
|
629
|
+
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
|
|
630
|
+
await this._queueSteer(expandedText, images);
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
633
|
+
* Queue a follow-up message to be processed after the agent finishes.
|
|
634
|
+
* Delivered only when agent has no more tool calls or steering messages.
|
|
635
|
+
* Expands skill commands and prompt templates. Errors on extension commands.
|
|
636
|
+
* @param images Optional image attachments to include with the message
|
|
637
|
+
* @throws Error if text is an extension command
|
|
638
|
+
*/
|
|
639
|
+
async followUp(text, images) {
|
|
640
|
+
// Check for extension commands (cannot be queued)
|
|
641
|
+
if (text.startsWith("/")) {
|
|
642
|
+
this._throwIfExtensionCommand(text);
|
|
643
|
+
}
|
|
644
|
+
// Expand skill commands and prompt templates
|
|
645
|
+
let expandedText = this._expandSkillCommand(text);
|
|
646
|
+
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
|
|
647
|
+
await this._queueFollowUp(expandedText, images);
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Internal: Queue a steering message (already expanded, no extension command check).
|
|
651
|
+
*/
|
|
652
|
+
async _queueSteer(text, images) {
|
|
653
|
+
this._steeringMessages.push(text);
|
|
654
|
+
const content = [{ type: "text", text }];
|
|
655
|
+
if (images) {
|
|
656
|
+
content.push(...images);
|
|
657
|
+
}
|
|
658
|
+
this.agent.steer({
|
|
659
|
+
role: "user",
|
|
660
|
+
content,
|
|
661
|
+
timestamp: Date.now(),
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Internal: Queue a follow-up message (already expanded, no extension command check).
|
|
666
|
+
*/
|
|
667
|
+
async _queueFollowUp(text, images) {
|
|
668
|
+
this._followUpMessages.push(text);
|
|
669
|
+
const content = [{ type: "text", text }];
|
|
670
|
+
if (images) {
|
|
671
|
+
content.push(...images);
|
|
672
|
+
}
|
|
673
|
+
this.agent.followUp({
|
|
674
|
+
role: "user",
|
|
675
|
+
content,
|
|
676
|
+
timestamp: Date.now(),
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
/**
|
|
680
|
+
* Throw an error if the text is an extension command.
|
|
681
|
+
*/
|
|
682
|
+
_throwIfExtensionCommand(text) {
|
|
683
|
+
if (!this._extensionRunner)
|
|
684
|
+
return;
|
|
685
|
+
const spaceIndex = text.indexOf(" ");
|
|
686
|
+
const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
|
|
687
|
+
const command = this._extensionRunner.getCommand(commandName);
|
|
688
|
+
if (command) {
|
|
689
|
+
throw new Error(`Extension command "/${commandName}" cannot be queued. Use prompt() or execute the command when not streaming.`);
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* Send a custom message to the session. Creates a CustomMessageEntry.
|
|
694
|
+
*
|
|
695
|
+
* Handles three cases:
|
|
696
|
+
* - Streaming: queues message, processed when loop pulls from queue
|
|
697
|
+
* - Not streaming + triggerTurn: appends to state/session, starts new turn
|
|
698
|
+
* - Not streaming + no trigger: appends to state/session, no turn
|
|
699
|
+
*
|
|
700
|
+
* @param message Custom message with customType, content, display, details
|
|
701
|
+
* @param options.triggerTurn If true and not streaming, triggers a new LLM turn
|
|
702
|
+
* @param options.deliverAs Delivery mode: "steer", "followUp", or "nextTurn"
|
|
703
|
+
*/
|
|
704
|
+
async sendCustomMessage(message, options) {
|
|
705
|
+
const appMessage = {
|
|
706
|
+
role: "custom",
|
|
707
|
+
customType: message.customType,
|
|
708
|
+
content: message.content,
|
|
709
|
+
display: message.display,
|
|
710
|
+
details: message.details,
|
|
711
|
+
timestamp: Date.now(),
|
|
712
|
+
};
|
|
713
|
+
if (options?.deliverAs === "nextTurn") {
|
|
714
|
+
this._pendingNextTurnMessages.push(appMessage);
|
|
715
|
+
}
|
|
716
|
+
else if (this.isStreaming) {
|
|
717
|
+
if (options?.deliverAs === "followUp") {
|
|
718
|
+
this.agent.followUp(appMessage);
|
|
719
|
+
}
|
|
720
|
+
else {
|
|
721
|
+
this.agent.steer(appMessage);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
else if (options?.triggerTurn) {
|
|
725
|
+
await this.agent.prompt(appMessage);
|
|
726
|
+
}
|
|
727
|
+
else {
|
|
728
|
+
this.agent.appendMessage(appMessage);
|
|
729
|
+
this.sessionManager.appendCustomMessageEntry(message.customType, message.content, message.display, message.details);
|
|
730
|
+
this._emit({ type: "message_start", message: appMessage });
|
|
731
|
+
this._emit({ type: "message_end", message: appMessage });
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* Send a user message to the agent. Always triggers a turn.
|
|
736
|
+
* When the agent is streaming, use deliverAs to specify how to queue the message.
|
|
737
|
+
*
|
|
738
|
+
* @param content User message content (string or content array)
|
|
739
|
+
* @param options.deliverAs Delivery mode when streaming: "steer" or "followUp"
|
|
740
|
+
*/
|
|
741
|
+
async sendUserMessage(content, options) {
|
|
742
|
+
// Normalize content to text string + optional images
|
|
743
|
+
let text;
|
|
744
|
+
let images;
|
|
745
|
+
if (typeof content === "string") {
|
|
746
|
+
text = content;
|
|
747
|
+
}
|
|
748
|
+
else {
|
|
749
|
+
const textParts = [];
|
|
750
|
+
images = [];
|
|
751
|
+
for (const part of content) {
|
|
752
|
+
if (part.type === "text") {
|
|
753
|
+
textParts.push(part.text);
|
|
754
|
+
}
|
|
755
|
+
else {
|
|
756
|
+
images.push(part);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
text = textParts.join("\n");
|
|
760
|
+
if (images.length === 0)
|
|
761
|
+
images = undefined;
|
|
762
|
+
}
|
|
763
|
+
// Use prompt() with expandPromptTemplates: false to skip command handling and template expansion
|
|
764
|
+
await this.prompt(text, {
|
|
765
|
+
expandPromptTemplates: false,
|
|
766
|
+
streamingBehavior: options?.deliverAs,
|
|
767
|
+
images,
|
|
768
|
+
source: "extension",
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* Clear all queued messages and return them.
|
|
773
|
+
* Useful for restoring to editor when user aborts.
|
|
774
|
+
* @returns Object with steering and followUp arrays
|
|
775
|
+
*/
|
|
776
|
+
clearQueue() {
|
|
777
|
+
const steering = [...this._steeringMessages];
|
|
778
|
+
const followUp = [...this._followUpMessages];
|
|
779
|
+
this._steeringMessages = [];
|
|
780
|
+
this._followUpMessages = [];
|
|
781
|
+
this.agent.clearAllQueues();
|
|
782
|
+
return { steering, followUp };
|
|
783
|
+
}
|
|
784
|
+
/** Number of pending messages (includes both steering and follow-up) */
|
|
785
|
+
get pendingMessageCount() {
|
|
786
|
+
return this._steeringMessages.length + this._followUpMessages.length;
|
|
787
|
+
}
|
|
788
|
+
/** Get pending steering messages (read-only) */
|
|
789
|
+
getSteeringMessages() {
|
|
790
|
+
return this._steeringMessages;
|
|
791
|
+
}
|
|
792
|
+
/** Get pending follow-up messages (read-only) */
|
|
793
|
+
getFollowUpMessages() {
|
|
794
|
+
return this._followUpMessages;
|
|
795
|
+
}
|
|
796
|
+
get resourceLoader() {
|
|
797
|
+
return this._resourceLoader;
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Abort current operation and wait for agent to become idle.
|
|
801
|
+
*/
|
|
802
|
+
async abort() {
|
|
803
|
+
this.abortRetry();
|
|
804
|
+
this.agent.abort();
|
|
805
|
+
await this.agent.waitForIdle();
|
|
806
|
+
}
|
|
807
|
+
/**
|
|
808
|
+
* Start a new session, optionally with initial messages and parent tracking.
|
|
809
|
+
* Clears all messages and starts a new session.
|
|
810
|
+
* Listeners are preserved and will continue receiving events.
|
|
811
|
+
* @param options.parentSession - Optional parent session path for tracking
|
|
812
|
+
* @param options.setup - Optional callback to initialize session (e.g., append messages)
|
|
813
|
+
* @returns true if completed, false if cancelled by extension
|
|
814
|
+
*/
|
|
815
|
+
async newSession(options) {
|
|
816
|
+
const previousSessionFile = this.sessionFile;
|
|
817
|
+
// Emit session_before_switch event with reason "new" (can be cancelled)
|
|
818
|
+
if (this._extensionRunner?.hasHandlers("session_before_switch")) {
|
|
819
|
+
const result = (await this._extensionRunner.emit({
|
|
820
|
+
type: "session_before_switch",
|
|
821
|
+
reason: "new",
|
|
822
|
+
}));
|
|
823
|
+
if (result?.cancel) {
|
|
824
|
+
return false;
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
this._disconnectFromAgent();
|
|
828
|
+
await this.abort();
|
|
829
|
+
this.agent.reset();
|
|
830
|
+
this.sessionManager.newSession({ parentSession: options?.parentSession });
|
|
831
|
+
this.agent.sessionId = this.sessionManager.getSessionId();
|
|
832
|
+
this._steeringMessages = [];
|
|
833
|
+
this._followUpMessages = [];
|
|
834
|
+
this._pendingNextTurnMessages = [];
|
|
835
|
+
this.sessionManager.appendThinkingLevelChange(this.thinkingLevel);
|
|
836
|
+
// Run setup callback if provided (e.g., to append initial messages)
|
|
837
|
+
if (options?.setup) {
|
|
838
|
+
await options.setup(this.sessionManager);
|
|
839
|
+
// Sync agent state with session manager after setup
|
|
840
|
+
const sessionContext = this.sessionManager.buildSessionContext();
|
|
841
|
+
this.agent.replaceMessages(sessionContext.messages);
|
|
842
|
+
}
|
|
843
|
+
this._reconnectToAgent();
|
|
844
|
+
// Emit session_switch event with reason "new" to extensions
|
|
845
|
+
if (this._extensionRunner) {
|
|
846
|
+
await this._extensionRunner.emit({
|
|
847
|
+
type: "session_switch",
|
|
848
|
+
reason: "new",
|
|
849
|
+
previousSessionFile,
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
// Emit session event to custom tools
|
|
853
|
+
return true;
|
|
854
|
+
}
|
|
855
|
+
// =========================================================================
|
|
856
|
+
// Model Management
|
|
857
|
+
// =========================================================================
|
|
858
|
+
async _emitModelSelect(nextModel, previousModel, source) {
|
|
859
|
+
if (!this._extensionRunner)
|
|
860
|
+
return;
|
|
861
|
+
if (modelsAreEqual(previousModel, nextModel))
|
|
862
|
+
return;
|
|
863
|
+
await this._extensionRunner.emit({
|
|
864
|
+
type: "model_select",
|
|
865
|
+
model: nextModel,
|
|
866
|
+
previousModel,
|
|
867
|
+
source,
|
|
868
|
+
});
|
|
869
|
+
}
|
|
870
|
+
/**
|
|
871
|
+
* Set model directly.
|
|
872
|
+
* Validates API key, saves to session and settings.
|
|
873
|
+
* @throws Error if no API key available for the model
|
|
874
|
+
*/
|
|
875
|
+
async setModel(model) {
|
|
876
|
+
const apiKey = await this._modelRegistry.getApiKey(model);
|
|
877
|
+
if (!apiKey) {
|
|
878
|
+
throw new Error(`No API key for ${model.provider}/${model.id}`);
|
|
879
|
+
}
|
|
880
|
+
const previousModel = this.model;
|
|
881
|
+
this.agent.setModel(model);
|
|
882
|
+
this.sessionManager.appendModelChange(model.provider, model.id);
|
|
883
|
+
this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
|
|
884
|
+
// Re-clamp thinking level for new model's capabilities
|
|
885
|
+
this.setThinkingLevel(this.thinkingLevel);
|
|
886
|
+
await this._emitModelSelect(model, previousModel, "set");
|
|
887
|
+
}
|
|
888
|
+
/**
|
|
889
|
+
* Cycle to next/previous model.
|
|
890
|
+
* Uses scoped models (from --models flag) if available, otherwise all available models.
|
|
891
|
+
* @param direction - "forward" (default) or "backward"
|
|
892
|
+
* @returns The new model info, or undefined if only one model available
|
|
893
|
+
*/
|
|
894
|
+
async cycleModel(direction = "forward") {
|
|
895
|
+
if (this._scopedModels.length > 0) {
|
|
896
|
+
return this._cycleScopedModel(direction);
|
|
897
|
+
}
|
|
898
|
+
return this._cycleAvailableModel(direction);
|
|
899
|
+
}
|
|
900
|
+
async _getScopedModelsWithApiKey() {
|
|
901
|
+
const apiKeysByProvider = new Map();
|
|
902
|
+
const result = [];
|
|
903
|
+
for (const scoped of this._scopedModels) {
|
|
904
|
+
const provider = scoped.model.provider;
|
|
905
|
+
let apiKey;
|
|
906
|
+
if (apiKeysByProvider.has(provider)) {
|
|
907
|
+
apiKey = apiKeysByProvider.get(provider);
|
|
908
|
+
}
|
|
909
|
+
else {
|
|
910
|
+
apiKey = await this._modelRegistry.getApiKeyForProvider(provider);
|
|
911
|
+
apiKeysByProvider.set(provider, apiKey);
|
|
912
|
+
}
|
|
913
|
+
if (apiKey) {
|
|
914
|
+
result.push(scoped);
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
return result;
|
|
918
|
+
}
|
|
919
|
+
async _cycleScopedModel(direction) {
|
|
920
|
+
const scopedModels = await this._getScopedModelsWithApiKey();
|
|
921
|
+
if (scopedModels.length <= 1)
|
|
922
|
+
return undefined;
|
|
923
|
+
const currentModel = this.model;
|
|
924
|
+
let currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));
|
|
925
|
+
if (currentIndex === -1)
|
|
926
|
+
currentIndex = 0;
|
|
927
|
+
const len = scopedModels.length;
|
|
928
|
+
const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
|
|
929
|
+
const next = scopedModels[nextIndex];
|
|
930
|
+
// Apply model
|
|
931
|
+
this.agent.setModel(next.model);
|
|
932
|
+
this.sessionManager.appendModelChange(next.model.provider, next.model.id);
|
|
933
|
+
this.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);
|
|
934
|
+
// Apply thinking level (setThinkingLevel clamps to model capabilities)
|
|
935
|
+
this.setThinkingLevel(next.thinkingLevel);
|
|
936
|
+
await this._emitModelSelect(next.model, currentModel, "cycle");
|
|
937
|
+
return { model: next.model, thinkingLevel: this.thinkingLevel, isScoped: true };
|
|
938
|
+
}
|
|
939
|
+
async _cycleAvailableModel(direction) {
|
|
940
|
+
const availableModels = await this._modelRegistry.getAvailable();
|
|
941
|
+
if (availableModels.length <= 1)
|
|
942
|
+
return undefined;
|
|
943
|
+
const currentModel = this.model;
|
|
944
|
+
let currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));
|
|
945
|
+
if (currentIndex === -1)
|
|
946
|
+
currentIndex = 0;
|
|
947
|
+
const len = availableModels.length;
|
|
948
|
+
const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
|
|
949
|
+
const nextModel = availableModels[nextIndex];
|
|
950
|
+
const apiKey = await this._modelRegistry.getApiKey(nextModel);
|
|
951
|
+
if (!apiKey) {
|
|
952
|
+
throw new Error(`No API key for ${nextModel.provider}/${nextModel.id}`);
|
|
953
|
+
}
|
|
954
|
+
this.agent.setModel(nextModel);
|
|
955
|
+
this.sessionManager.appendModelChange(nextModel.provider, nextModel.id);
|
|
956
|
+
this.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);
|
|
957
|
+
// Re-clamp thinking level for new model's capabilities
|
|
958
|
+
this.setThinkingLevel(this.thinkingLevel);
|
|
959
|
+
await this._emitModelSelect(nextModel, currentModel, "cycle");
|
|
960
|
+
return { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };
|
|
961
|
+
}
|
|
962
|
+
// =========================================================================
|
|
963
|
+
// Thinking Level Management
|
|
964
|
+
// =========================================================================
|
|
965
|
+
/**
|
|
966
|
+
* Set thinking level.
|
|
967
|
+
* Clamps to model capabilities based on available thinking levels.
|
|
968
|
+
* Saves to session and settings only if the level actually changes.
|
|
969
|
+
*/
|
|
970
|
+
setThinkingLevel(level) {
|
|
971
|
+
const availableLevels = this.getAvailableThinkingLevels();
|
|
972
|
+
const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
|
|
973
|
+
// Only persist if actually changing
|
|
974
|
+
const isChanging = effectiveLevel !== this.agent.state.thinkingLevel;
|
|
975
|
+
this.agent.setThinkingLevel(effectiveLevel);
|
|
976
|
+
if (isChanging) {
|
|
977
|
+
this.sessionManager.appendThinkingLevelChange(effectiveLevel);
|
|
978
|
+
this.settingsManager.setDefaultThinkingLevel(effectiveLevel);
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
/**
|
|
982
|
+
* Cycle to next thinking level.
|
|
983
|
+
* @returns New level, or undefined if model doesn't support thinking
|
|
984
|
+
*/
|
|
985
|
+
cycleThinkingLevel() {
|
|
986
|
+
if (!this.supportsThinking())
|
|
987
|
+
return undefined;
|
|
988
|
+
const levels = this.getAvailableThinkingLevels();
|
|
989
|
+
const currentIndex = levels.indexOf(this.thinkingLevel);
|
|
990
|
+
const nextIndex = (currentIndex + 1) % levels.length;
|
|
991
|
+
const nextLevel = levels[nextIndex];
|
|
992
|
+
this.setThinkingLevel(nextLevel);
|
|
993
|
+
return nextLevel;
|
|
994
|
+
}
|
|
995
|
+
/**
|
|
996
|
+
* Get available thinking levels for current model.
|
|
997
|
+
* The provider will clamp to what the specific model supports internally.
|
|
998
|
+
*/
|
|
999
|
+
getAvailableThinkingLevels() {
|
|
1000
|
+
if (!this.supportsThinking())
|
|
1001
|
+
return ["off"];
|
|
1002
|
+
return this.supportsXhighThinking() ? THINKING_LEVELS_WITH_XHIGH : THINKING_LEVELS;
|
|
1003
|
+
}
|
|
1004
|
+
/**
|
|
1005
|
+
* Check if current model supports xhigh thinking level.
|
|
1006
|
+
*/
|
|
1007
|
+
supportsXhighThinking() {
|
|
1008
|
+
return this.model ? supportsXhigh(this.model) : false;
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* Check if current model supports thinking/reasoning.
|
|
1012
|
+
*/
|
|
1013
|
+
supportsThinking() {
|
|
1014
|
+
return !!this.model?.reasoning;
|
|
1015
|
+
}
|
|
1016
|
+
_clampThinkingLevel(level, availableLevels) {
|
|
1017
|
+
const ordered = THINKING_LEVELS_WITH_XHIGH;
|
|
1018
|
+
const available = new Set(availableLevels);
|
|
1019
|
+
const requestedIndex = ordered.indexOf(level);
|
|
1020
|
+
if (requestedIndex === -1) {
|
|
1021
|
+
return availableLevels[0] ?? "off";
|
|
1022
|
+
}
|
|
1023
|
+
for (let i = requestedIndex; i < ordered.length; i++) {
|
|
1024
|
+
const candidate = ordered[i];
|
|
1025
|
+
if (available.has(candidate))
|
|
1026
|
+
return candidate;
|
|
1027
|
+
}
|
|
1028
|
+
for (let i = requestedIndex - 1; i >= 0; i--) {
|
|
1029
|
+
const candidate = ordered[i];
|
|
1030
|
+
if (available.has(candidate))
|
|
1031
|
+
return candidate;
|
|
1032
|
+
}
|
|
1033
|
+
return availableLevels[0] ?? "off";
|
|
1034
|
+
}
|
|
1035
|
+
// =========================================================================
|
|
1036
|
+
// Queue Mode Management
|
|
1037
|
+
// =========================================================================
|
|
1038
|
+
/**
|
|
1039
|
+
* Set steering message mode.
|
|
1040
|
+
* Saves to settings.
|
|
1041
|
+
*/
|
|
1042
|
+
setSteeringMode(mode) {
|
|
1043
|
+
this.agent.setSteeringMode(mode);
|
|
1044
|
+
this.settingsManager.setSteeringMode(mode);
|
|
1045
|
+
}
|
|
1046
|
+
/**
|
|
1047
|
+
* Set follow-up message mode.
|
|
1048
|
+
* Saves to settings.
|
|
1049
|
+
*/
|
|
1050
|
+
setFollowUpMode(mode) {
|
|
1051
|
+
this.agent.setFollowUpMode(mode);
|
|
1052
|
+
this.settingsManager.setFollowUpMode(mode);
|
|
1053
|
+
}
|
|
1054
|
+
// =========================================================================
|
|
1055
|
+
// Compaction
|
|
1056
|
+
// =========================================================================
|
|
1057
|
+
/**
|
|
1058
|
+
* Manually compact the session context.
|
|
1059
|
+
* Aborts current agent operation first.
|
|
1060
|
+
* @param customInstructions Optional instructions for the compaction summary
|
|
1061
|
+
*/
|
|
1062
|
+
async compact(customInstructions) {
|
|
1063
|
+
this._disconnectFromAgent();
|
|
1064
|
+
await this.abort();
|
|
1065
|
+
this._compactionAbortController = new AbortController();
|
|
1066
|
+
try {
|
|
1067
|
+
if (!this.model) {
|
|
1068
|
+
throw new Error("No model selected");
|
|
1069
|
+
}
|
|
1070
|
+
const apiKey = await this._modelRegistry.getApiKey(this.model);
|
|
1071
|
+
if (!apiKey) {
|
|
1072
|
+
throw new Error(`No API key for ${this.model.provider}`);
|
|
1073
|
+
}
|
|
1074
|
+
const pathEntries = this.sessionManager.getBranch();
|
|
1075
|
+
const settings = this.settingsManager.getCompactionSettings();
|
|
1076
|
+
const preparation = prepareCompaction(pathEntries, settings);
|
|
1077
|
+
if (!preparation) {
|
|
1078
|
+
// Check why we can't compact
|
|
1079
|
+
const lastEntry = pathEntries[pathEntries.length - 1];
|
|
1080
|
+
if (lastEntry?.type === "compaction") {
|
|
1081
|
+
throw new Error("Already compacted");
|
|
1082
|
+
}
|
|
1083
|
+
throw new Error("Nothing to compact (session too small)");
|
|
1084
|
+
}
|
|
1085
|
+
let extensionCompaction;
|
|
1086
|
+
let fromExtension = false;
|
|
1087
|
+
if (this._extensionRunner?.hasHandlers("session_before_compact")) {
|
|
1088
|
+
const result = (await this._extensionRunner.emit({
|
|
1089
|
+
type: "session_before_compact",
|
|
1090
|
+
preparation,
|
|
1091
|
+
branchEntries: pathEntries,
|
|
1092
|
+
customInstructions,
|
|
1093
|
+
signal: this._compactionAbortController.signal,
|
|
1094
|
+
}));
|
|
1095
|
+
if (result?.cancel) {
|
|
1096
|
+
throw new Error("Compaction cancelled");
|
|
1097
|
+
}
|
|
1098
|
+
if (result?.compaction) {
|
|
1099
|
+
extensionCompaction = result.compaction;
|
|
1100
|
+
fromExtension = true;
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
let summary;
|
|
1104
|
+
let firstKeptEntryId;
|
|
1105
|
+
let tokensBefore;
|
|
1106
|
+
let details;
|
|
1107
|
+
if (extensionCompaction) {
|
|
1108
|
+
// Extension provided compaction content
|
|
1109
|
+
summary = extensionCompaction.summary;
|
|
1110
|
+
firstKeptEntryId = extensionCompaction.firstKeptEntryId;
|
|
1111
|
+
tokensBefore = extensionCompaction.tokensBefore;
|
|
1112
|
+
details = extensionCompaction.details;
|
|
1113
|
+
}
|
|
1114
|
+
else {
|
|
1115
|
+
// Generate compaction result
|
|
1116
|
+
const result = await compact(preparation, this.model, apiKey, customInstructions, this._compactionAbortController.signal);
|
|
1117
|
+
summary = result.summary;
|
|
1118
|
+
firstKeptEntryId = result.firstKeptEntryId;
|
|
1119
|
+
tokensBefore = result.tokensBefore;
|
|
1120
|
+
details = result.details;
|
|
1121
|
+
}
|
|
1122
|
+
if (this._compactionAbortController.signal.aborted) {
|
|
1123
|
+
throw new Error("Compaction cancelled");
|
|
1124
|
+
}
|
|
1125
|
+
this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension);
|
|
1126
|
+
const newEntries = this.sessionManager.getEntries();
|
|
1127
|
+
const sessionContext = this.sessionManager.buildSessionContext();
|
|
1128
|
+
this.agent.replaceMessages(sessionContext.messages);
|
|
1129
|
+
// Get the saved compaction entry for the extension event
|
|
1130
|
+
const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
|
|
1131
|
+
if (this._extensionRunner && savedCompactionEntry) {
|
|
1132
|
+
await this._extensionRunner.emit({
|
|
1133
|
+
type: "session_compact",
|
|
1134
|
+
compactionEntry: savedCompactionEntry,
|
|
1135
|
+
fromExtension,
|
|
1136
|
+
});
|
|
1137
|
+
}
|
|
1138
|
+
return {
|
|
1139
|
+
summary,
|
|
1140
|
+
firstKeptEntryId,
|
|
1141
|
+
tokensBefore,
|
|
1142
|
+
details,
|
|
1143
|
+
};
|
|
1144
|
+
}
|
|
1145
|
+
finally {
|
|
1146
|
+
this._compactionAbortController = undefined;
|
|
1147
|
+
this._reconnectToAgent();
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
/**
|
|
1151
|
+
* Cancel in-progress compaction (manual or auto).
|
|
1152
|
+
*/
|
|
1153
|
+
abortCompaction() {
|
|
1154
|
+
this._compactionAbortController?.abort();
|
|
1155
|
+
this._autoCompactionAbortController?.abort();
|
|
1156
|
+
}
|
|
1157
|
+
/**
|
|
1158
|
+
* Cancel in-progress branch summarization.
|
|
1159
|
+
*/
|
|
1160
|
+
abortBranchSummary() {
|
|
1161
|
+
this._branchSummaryAbortController?.abort();
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* Check if compaction is needed and run it.
|
|
1165
|
+
* Called after agent_end and before prompt submission.
|
|
1166
|
+
*
|
|
1167
|
+
* Two cases:
|
|
1168
|
+
* 1. Overflow: LLM returned context overflow error, remove error message from agent state, compact, auto-retry
|
|
1169
|
+
* 2. Threshold: Context over threshold, compact, NO auto-retry (user continues manually)
|
|
1170
|
+
*
|
|
1171
|
+
* @param assistantMessage The assistant message to check
|
|
1172
|
+
* @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true
|
|
1173
|
+
*/
|
|
1174
|
+
async _checkCompaction(assistantMessage, skipAbortedCheck = true) {
|
|
1175
|
+
const settings = this.settingsManager.getCompactionSettings();
|
|
1176
|
+
if (!settings.enabled)
|
|
1177
|
+
return;
|
|
1178
|
+
// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
|
|
1179
|
+
if (skipAbortedCheck && assistantMessage.stopReason === "aborted")
|
|
1180
|
+
return;
|
|
1181
|
+
const contextWindow = this.model?.contextWindow ?? 0;
|
|
1182
|
+
// Skip overflow check if the message came from a different model.
|
|
1183
|
+
// This handles the case where user switched from a smaller-context model (e.g. opus)
|
|
1184
|
+
// to a larger-context model (e.g. codex) - the overflow error from the old model
|
|
1185
|
+
// shouldn't trigger compaction for the new model.
|
|
1186
|
+
const sameModel = this.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;
|
|
1187
|
+
// Skip overflow check if the error is from before a compaction in the current path.
|
|
1188
|
+
// This handles the case where an error was kept after compaction (in the "kept" region).
|
|
1189
|
+
// The error shouldn't trigger another compaction since we already compacted.
|
|
1190
|
+
// Example: opus fails → switch to codex → compact → switch back to opus → opus error
|
|
1191
|
+
// is still in context but shouldn't trigger compaction again.
|
|
1192
|
+
const compactionEntry = this.sessionManager.getBranch().find((e) => e.type === "compaction");
|
|
1193
|
+
const errorIsFromBeforeCompaction = compactionEntry && assistantMessage.timestamp < new Date(compactionEntry.timestamp).getTime();
|
|
1194
|
+
// Case 1: Overflow - LLM returned context overflow error
|
|
1195
|
+
if (sameModel && !errorIsFromBeforeCompaction && isContextOverflow(assistantMessage, contextWindow)) {
|
|
1196
|
+
// Remove the error message from agent state (it IS saved to session for history,
|
|
1197
|
+
// but we don't want it in context for the retry)
|
|
1198
|
+
const messages = this.agent.state.messages;
|
|
1199
|
+
if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
|
|
1200
|
+
this.agent.replaceMessages(messages.slice(0, -1));
|
|
1201
|
+
}
|
|
1202
|
+
await this._runAutoCompaction("overflow", true);
|
|
1203
|
+
return;
|
|
1204
|
+
}
|
|
1205
|
+
// Case 2: Threshold - turn succeeded but context is getting large
|
|
1206
|
+
// Skip if this was an error (non-overflow errors don't have usage data)
|
|
1207
|
+
if (assistantMessage.stopReason === "error")
|
|
1208
|
+
return;
|
|
1209
|
+
const contextTokens = calculateContextTokens(assistantMessage.usage);
|
|
1210
|
+
if (shouldCompact(contextTokens, contextWindow, settings)) {
|
|
1211
|
+
await this._runAutoCompaction("threshold", false);
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
/**
|
|
1215
|
+
* Internal: Run auto-compaction with events.
|
|
1216
|
+
*/
|
|
1217
|
+
async _runAutoCompaction(reason, willRetry) {
|
|
1218
|
+
const settings = this.settingsManager.getCompactionSettings();
|
|
1219
|
+
this._emit({ type: "auto_compaction_start", reason });
|
|
1220
|
+
this._autoCompactionAbortController = new AbortController();
|
|
1221
|
+
try {
|
|
1222
|
+
if (!this.model) {
|
|
1223
|
+
this._emit({ type: "auto_compaction_end", result: undefined, aborted: false, willRetry: false });
|
|
1224
|
+
return;
|
|
1225
|
+
}
|
|
1226
|
+
const apiKey = await this._modelRegistry.getApiKey(this.model);
|
|
1227
|
+
if (!apiKey) {
|
|
1228
|
+
this._emit({ type: "auto_compaction_end", result: undefined, aborted: false, willRetry: false });
|
|
1229
|
+
return;
|
|
1230
|
+
}
|
|
1231
|
+
const pathEntries = this.sessionManager.getBranch();
|
|
1232
|
+
const preparation = prepareCompaction(pathEntries, settings);
|
|
1233
|
+
if (!preparation) {
|
|
1234
|
+
this._emit({ type: "auto_compaction_end", result: undefined, aborted: false, willRetry: false });
|
|
1235
|
+
return;
|
|
1236
|
+
}
|
|
1237
|
+
let extensionCompaction;
|
|
1238
|
+
let fromExtension = false;
|
|
1239
|
+
if (this._extensionRunner?.hasHandlers("session_before_compact")) {
|
|
1240
|
+
const extensionResult = (await this._extensionRunner.emit({
|
|
1241
|
+
type: "session_before_compact",
|
|
1242
|
+
preparation,
|
|
1243
|
+
branchEntries: pathEntries,
|
|
1244
|
+
customInstructions: undefined,
|
|
1245
|
+
signal: this._autoCompactionAbortController.signal,
|
|
1246
|
+
}));
|
|
1247
|
+
if (extensionResult?.cancel) {
|
|
1248
|
+
this._emit({ type: "auto_compaction_end", result: undefined, aborted: true, willRetry: false });
|
|
1249
|
+
return;
|
|
1250
|
+
}
|
|
1251
|
+
if (extensionResult?.compaction) {
|
|
1252
|
+
extensionCompaction = extensionResult.compaction;
|
|
1253
|
+
fromExtension = true;
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
let summary;
|
|
1257
|
+
let firstKeptEntryId;
|
|
1258
|
+
let tokensBefore;
|
|
1259
|
+
let details;
|
|
1260
|
+
if (extensionCompaction) {
|
|
1261
|
+
// Extension provided compaction content
|
|
1262
|
+
summary = extensionCompaction.summary;
|
|
1263
|
+
firstKeptEntryId = extensionCompaction.firstKeptEntryId;
|
|
1264
|
+
tokensBefore = extensionCompaction.tokensBefore;
|
|
1265
|
+
details = extensionCompaction.details;
|
|
1266
|
+
}
|
|
1267
|
+
else {
|
|
1268
|
+
// Generate compaction result
|
|
1269
|
+
const compactResult = await compact(preparation, this.model, apiKey, undefined, this._autoCompactionAbortController.signal);
|
|
1270
|
+
summary = compactResult.summary;
|
|
1271
|
+
firstKeptEntryId = compactResult.firstKeptEntryId;
|
|
1272
|
+
tokensBefore = compactResult.tokensBefore;
|
|
1273
|
+
details = compactResult.details;
|
|
1274
|
+
}
|
|
1275
|
+
if (this._autoCompactionAbortController.signal.aborted) {
|
|
1276
|
+
this._emit({ type: "auto_compaction_end", result: undefined, aborted: true, willRetry: false });
|
|
1277
|
+
return;
|
|
1278
|
+
}
|
|
1279
|
+
this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension);
|
|
1280
|
+
const newEntries = this.sessionManager.getEntries();
|
|
1281
|
+
const sessionContext = this.sessionManager.buildSessionContext();
|
|
1282
|
+
this.agent.replaceMessages(sessionContext.messages);
|
|
1283
|
+
// Get the saved compaction entry for the extension event
|
|
1284
|
+
const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
|
|
1285
|
+
if (this._extensionRunner && savedCompactionEntry) {
|
|
1286
|
+
await this._extensionRunner.emit({
|
|
1287
|
+
type: "session_compact",
|
|
1288
|
+
compactionEntry: savedCompactionEntry,
|
|
1289
|
+
fromExtension,
|
|
1290
|
+
});
|
|
1291
|
+
}
|
|
1292
|
+
const result = {
|
|
1293
|
+
summary,
|
|
1294
|
+
firstKeptEntryId,
|
|
1295
|
+
tokensBefore,
|
|
1296
|
+
details,
|
|
1297
|
+
};
|
|
1298
|
+
this._emit({ type: "auto_compaction_end", result, aborted: false, willRetry });
|
|
1299
|
+
if (willRetry) {
|
|
1300
|
+
const messages = this.agent.state.messages;
|
|
1301
|
+
const lastMsg = messages[messages.length - 1];
|
|
1302
|
+
if (lastMsg?.role === "assistant" && lastMsg.stopReason === "error") {
|
|
1303
|
+
this.agent.replaceMessages(messages.slice(0, -1));
|
|
1304
|
+
}
|
|
1305
|
+
setTimeout(() => {
|
|
1306
|
+
this.agent.continue().catch(() => { });
|
|
1307
|
+
}, 100);
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
catch (error) {
|
|
1311
|
+
const errorMessage = error instanceof Error ? error.message : "compaction failed";
|
|
1312
|
+
this._emit({
|
|
1313
|
+
type: "auto_compaction_end",
|
|
1314
|
+
result: undefined,
|
|
1315
|
+
aborted: false,
|
|
1316
|
+
willRetry: false,
|
|
1317
|
+
errorMessage: reason === "overflow"
|
|
1318
|
+
? `Context overflow recovery failed: ${errorMessage}`
|
|
1319
|
+
: `Auto-compaction failed: ${errorMessage}`,
|
|
1320
|
+
});
|
|
1321
|
+
}
|
|
1322
|
+
finally {
|
|
1323
|
+
this._autoCompactionAbortController = undefined;
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
/**
|
|
1327
|
+
* Toggle auto-compaction setting.
|
|
1328
|
+
*/
|
|
1329
|
+
setAutoCompactionEnabled(enabled) {
|
|
1330
|
+
this.settingsManager.setCompactionEnabled(enabled);
|
|
1331
|
+
}
|
|
1332
|
+
/** Whether auto-compaction is enabled */
|
|
1333
|
+
get autoCompactionEnabled() {
|
|
1334
|
+
return this.settingsManager.getCompactionEnabled();
|
|
1335
|
+
}
|
|
1336
|
+
async bindExtensions(bindings) {
|
|
1337
|
+
if (bindings.uiContext !== undefined) {
|
|
1338
|
+
this._extensionUIContext = bindings.uiContext;
|
|
1339
|
+
}
|
|
1340
|
+
if (bindings.commandContextActions !== undefined) {
|
|
1341
|
+
this._extensionCommandContextActions = bindings.commandContextActions;
|
|
1342
|
+
}
|
|
1343
|
+
if (bindings.shutdownHandler !== undefined) {
|
|
1344
|
+
this._extensionShutdownHandler = bindings.shutdownHandler;
|
|
1345
|
+
}
|
|
1346
|
+
if (bindings.onError !== undefined) {
|
|
1347
|
+
this._extensionErrorListener = bindings.onError;
|
|
1348
|
+
}
|
|
1349
|
+
if (this._extensionRunner) {
|
|
1350
|
+
this._applyExtensionBindings(this._extensionRunner);
|
|
1351
|
+
await this._extensionRunner.emit({ type: "session_start" });
|
|
1352
|
+
await this.extendResourcesFromExtensions("startup");
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
async extendResourcesFromExtensions(reason) {
|
|
1356
|
+
if (!this._extensionRunner?.hasHandlers("resources_discover")) {
|
|
1357
|
+
return;
|
|
1358
|
+
}
|
|
1359
|
+
const { skillPaths, promptPaths, themePaths } = await this._extensionRunner.emitResourcesDiscover(this._cwd, reason);
|
|
1360
|
+
if (skillPaths.length === 0 && promptPaths.length === 0 && themePaths.length === 0) {
|
|
1361
|
+
return;
|
|
1362
|
+
}
|
|
1363
|
+
const extensionPaths = {
|
|
1364
|
+
skillPaths: this.buildExtensionResourcePaths(skillPaths),
|
|
1365
|
+
promptPaths: this.buildExtensionResourcePaths(promptPaths),
|
|
1366
|
+
themePaths: this.buildExtensionResourcePaths(themePaths),
|
|
1367
|
+
};
|
|
1368
|
+
this._resourceLoader.extendResources(extensionPaths);
|
|
1369
|
+
this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());
|
|
1370
|
+
this.agent.setSystemPrompt(this._baseSystemPrompt);
|
|
1371
|
+
}
|
|
1372
|
+
buildExtensionResourcePaths(entries) {
|
|
1373
|
+
return entries.map((entry) => {
|
|
1374
|
+
const source = this.getExtensionSourceLabel(entry.extensionPath);
|
|
1375
|
+
const baseDir = entry.extensionPath.startsWith("<") ? undefined : dirname(entry.extensionPath);
|
|
1376
|
+
return {
|
|
1377
|
+
path: entry.path,
|
|
1378
|
+
metadata: {
|
|
1379
|
+
source,
|
|
1380
|
+
scope: "temporary",
|
|
1381
|
+
origin: "top-level",
|
|
1382
|
+
baseDir,
|
|
1383
|
+
},
|
|
1384
|
+
};
|
|
1385
|
+
});
|
|
1386
|
+
}
|
|
1387
|
+
getExtensionSourceLabel(extensionPath) {
|
|
1388
|
+
if (extensionPath.startsWith("<")) {
|
|
1389
|
+
return `extension:${extensionPath.replace(/[<>]/g, "")}`;
|
|
1390
|
+
}
|
|
1391
|
+
const base = basename(extensionPath);
|
|
1392
|
+
const name = base.replace(/\.(ts|js)$/, "");
|
|
1393
|
+
return `extension:${name}`;
|
|
1394
|
+
}
|
|
1395
|
+
_applyExtensionBindings(runner) {
|
|
1396
|
+
runner.setUIContext(this._extensionUIContext);
|
|
1397
|
+
runner.bindCommandContext(this._extensionCommandContextActions);
|
|
1398
|
+
this._extensionErrorUnsubscriber?.();
|
|
1399
|
+
this._extensionErrorUnsubscriber = this._extensionErrorListener
|
|
1400
|
+
? runner.onError(this._extensionErrorListener)
|
|
1401
|
+
: undefined;
|
|
1402
|
+
}
|
|
1403
|
+
_bindExtensionCore(runner) {
|
|
1404
|
+
const normalizeLocation = (source) => {
|
|
1405
|
+
if (source === "user" || source === "project" || source === "path") {
|
|
1406
|
+
return source;
|
|
1407
|
+
}
|
|
1408
|
+
return undefined;
|
|
1409
|
+
};
|
|
1410
|
+
const reservedBuiltins = new Set(BUILTIN_SLASH_COMMANDS.map((command) => command.name));
|
|
1411
|
+
const getCommands = () => {
|
|
1412
|
+
const extensionCommands = runner
|
|
1413
|
+
.getRegisteredCommandsWithPaths()
|
|
1414
|
+
.filter(({ command }) => !reservedBuiltins.has(command.name))
|
|
1415
|
+
.map(({ command, extensionPath }) => ({
|
|
1416
|
+
name: command.name,
|
|
1417
|
+
description: command.description,
|
|
1418
|
+
source: "extension",
|
|
1419
|
+
path: extensionPath,
|
|
1420
|
+
}));
|
|
1421
|
+
const templates = this.promptTemplates.map((template) => ({
|
|
1422
|
+
name: template.name,
|
|
1423
|
+
description: template.description,
|
|
1424
|
+
source: "prompt",
|
|
1425
|
+
location: normalizeLocation(template.source),
|
|
1426
|
+
path: template.filePath,
|
|
1427
|
+
}));
|
|
1428
|
+
const skills = this._resourceLoader.getSkills().skills.map((skill) => ({
|
|
1429
|
+
name: `skill:${skill.name}`,
|
|
1430
|
+
description: skill.description,
|
|
1431
|
+
source: "skill",
|
|
1432
|
+
location: normalizeLocation(skill.source),
|
|
1433
|
+
path: skill.filePath,
|
|
1434
|
+
}));
|
|
1435
|
+
return [...extensionCommands, ...templates, ...skills];
|
|
1436
|
+
};
|
|
1437
|
+
runner.bindCore({
|
|
1438
|
+
sendMessage: (message, options) => {
|
|
1439
|
+
this.sendCustomMessage(message, options).catch((err) => {
|
|
1440
|
+
runner.emitError({
|
|
1441
|
+
extensionPath: "<runtime>",
|
|
1442
|
+
event: "send_message",
|
|
1443
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1444
|
+
});
|
|
1445
|
+
});
|
|
1446
|
+
},
|
|
1447
|
+
sendUserMessage: (content, options) => {
|
|
1448
|
+
this.sendUserMessage(content, options).catch((err) => {
|
|
1449
|
+
runner.emitError({
|
|
1450
|
+
extensionPath: "<runtime>",
|
|
1451
|
+
event: "send_user_message",
|
|
1452
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1453
|
+
});
|
|
1454
|
+
});
|
|
1455
|
+
},
|
|
1456
|
+
appendEntry: (customType, data) => {
|
|
1457
|
+
this.sessionManager.appendCustomEntry(customType, data);
|
|
1458
|
+
},
|
|
1459
|
+
setSessionName: (name) => {
|
|
1460
|
+
this.sessionManager.appendSessionInfo(name);
|
|
1461
|
+
},
|
|
1462
|
+
getSessionName: () => {
|
|
1463
|
+
return this.sessionManager.getSessionName();
|
|
1464
|
+
},
|
|
1465
|
+
setLabel: (entryId, label) => {
|
|
1466
|
+
this.sessionManager.appendLabelChange(entryId, label);
|
|
1467
|
+
},
|
|
1468
|
+
getActiveTools: () => this.getActiveToolNames(),
|
|
1469
|
+
getAllTools: () => this.getAllTools(),
|
|
1470
|
+
setActiveTools: (toolNames) => this.setActiveToolsByName(toolNames),
|
|
1471
|
+
getCommands,
|
|
1472
|
+
setModel: async (model) => {
|
|
1473
|
+
const key = await this.modelRegistry.getApiKey(model);
|
|
1474
|
+
if (!key)
|
|
1475
|
+
return false;
|
|
1476
|
+
await this.setModel(model);
|
|
1477
|
+
return true;
|
|
1478
|
+
},
|
|
1479
|
+
getThinkingLevel: () => this.thinkingLevel,
|
|
1480
|
+
setThinkingLevel: (level) => this.setThinkingLevel(level),
|
|
1481
|
+
}, {
|
|
1482
|
+
getModel: () => this.model,
|
|
1483
|
+
isIdle: () => !this.isStreaming,
|
|
1484
|
+
abort: () => this.abort(),
|
|
1485
|
+
hasPendingMessages: () => this.pendingMessageCount > 0,
|
|
1486
|
+
shutdown: () => {
|
|
1487
|
+
this._extensionShutdownHandler?.();
|
|
1488
|
+
},
|
|
1489
|
+
getContextUsage: () => this.getContextUsage(),
|
|
1490
|
+
compact: (options) => {
|
|
1491
|
+
void (async () => {
|
|
1492
|
+
try {
|
|
1493
|
+
const result = await this.compact(options?.customInstructions);
|
|
1494
|
+
options?.onComplete?.(result);
|
|
1495
|
+
}
|
|
1496
|
+
catch (error) {
|
|
1497
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1498
|
+
options?.onError?.(err);
|
|
1499
|
+
}
|
|
1500
|
+
})();
|
|
1501
|
+
},
|
|
1502
|
+
getSystemPrompt: () => this.systemPrompt,
|
|
1503
|
+
});
|
|
1504
|
+
}
|
|
1505
|
+
_buildRuntime(options) {
|
|
1506
|
+
const autoResizeImages = this.settingsManager.getImageAutoResize();
|
|
1507
|
+
const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
|
|
1508
|
+
const baseTools = this._baseToolsOverride
|
|
1509
|
+
? this._baseToolsOverride
|
|
1510
|
+
: createAllTools(this._cwd, {
|
|
1511
|
+
read: { autoResizeImages },
|
|
1512
|
+
bash: { commandPrefix: shellCommandPrefix },
|
|
1513
|
+
});
|
|
1514
|
+
this._baseToolRegistry = new Map(Object.entries(baseTools).map(([name, tool]) => [name, tool]));
|
|
1515
|
+
const extensionsResult = this._resourceLoader.getExtensions();
|
|
1516
|
+
if (options.flagValues) {
|
|
1517
|
+
for (const [name, value] of options.flagValues) {
|
|
1518
|
+
extensionsResult.runtime.flagValues.set(name, value);
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
const hasExtensions = extensionsResult.extensions.length > 0;
|
|
1522
|
+
const hasCustomTools = this._customTools.length > 0;
|
|
1523
|
+
this._extensionRunner =
|
|
1524
|
+
hasExtensions || hasCustomTools
|
|
1525
|
+
? new ExtensionRunner(extensionsResult.extensions, extensionsResult.runtime, this._cwd, this.sessionManager, this._modelRegistry)
|
|
1526
|
+
: undefined;
|
|
1527
|
+
if (this._extensionRunnerRef) {
|
|
1528
|
+
this._extensionRunnerRef.current = this._extensionRunner;
|
|
1529
|
+
}
|
|
1530
|
+
if (this._extensionRunner) {
|
|
1531
|
+
this._bindExtensionCore(this._extensionRunner);
|
|
1532
|
+
this._applyExtensionBindings(this._extensionRunner);
|
|
1533
|
+
}
|
|
1534
|
+
const registeredTools = this._extensionRunner?.getAllRegisteredTools() ?? [];
|
|
1535
|
+
const allCustomTools = [
|
|
1536
|
+
...registeredTools,
|
|
1537
|
+
...this._customTools.map((def) => ({ definition: def, extensionPath: "<sdk>" })),
|
|
1538
|
+
];
|
|
1539
|
+
const wrappedExtensionTools = this._extensionRunner
|
|
1540
|
+
? wrapRegisteredTools(allCustomTools, this._extensionRunner)
|
|
1541
|
+
: [];
|
|
1542
|
+
const toolRegistry = new Map(this._baseToolRegistry);
|
|
1543
|
+
for (const tool of wrappedExtensionTools) {
|
|
1544
|
+
toolRegistry.set(tool.name, tool);
|
|
1545
|
+
}
|
|
1546
|
+
const defaultActiveToolNames = this._baseToolsOverride
|
|
1547
|
+
? Object.keys(this._baseToolsOverride)
|
|
1548
|
+
: ["read", "bash", "edit", "write"];
|
|
1549
|
+
const baseActiveToolNames = options.activeToolNames ?? defaultActiveToolNames;
|
|
1550
|
+
const activeToolNameSet = new Set(baseActiveToolNames);
|
|
1551
|
+
if (options.includeAllExtensionTools) {
|
|
1552
|
+
for (const tool of wrappedExtensionTools) {
|
|
1553
|
+
activeToolNameSet.add(tool.name);
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
const extensionToolNames = new Set(wrappedExtensionTools.map((tool) => tool.name));
|
|
1557
|
+
const activeBaseTools = Array.from(activeToolNameSet)
|
|
1558
|
+
.filter((name) => this._baseToolRegistry.has(name) && !extensionToolNames.has(name))
|
|
1559
|
+
.map((name) => this._baseToolRegistry.get(name));
|
|
1560
|
+
const activeExtensionTools = wrappedExtensionTools.filter((tool) => activeToolNameSet.has(tool.name));
|
|
1561
|
+
const activeToolsArray = [...activeBaseTools, ...activeExtensionTools];
|
|
1562
|
+
if (this._extensionRunner) {
|
|
1563
|
+
const wrappedActiveTools = wrapToolsWithExtensions(activeToolsArray, this._extensionRunner);
|
|
1564
|
+
this.agent.setTools(wrappedActiveTools);
|
|
1565
|
+
const wrappedAllTools = wrapToolsWithExtensions(Array.from(toolRegistry.values()), this._extensionRunner);
|
|
1566
|
+
this._toolRegistry = new Map(wrappedAllTools.map((tool) => [tool.name, tool]));
|
|
1567
|
+
}
|
|
1568
|
+
else {
|
|
1569
|
+
this.agent.setTools(activeToolsArray);
|
|
1570
|
+
this._toolRegistry = toolRegistry;
|
|
1571
|
+
}
|
|
1572
|
+
const systemPromptToolNames = Array.from(activeToolNameSet).filter((name) => this._baseToolRegistry.has(name));
|
|
1573
|
+
this._baseSystemPrompt = this._rebuildSystemPrompt(systemPromptToolNames);
|
|
1574
|
+
this.agent.setSystemPrompt(this._baseSystemPrompt);
|
|
1575
|
+
}
|
|
1576
|
+
async reload() {
|
|
1577
|
+
const previousFlagValues = this._extensionRunner?.getFlagValues();
|
|
1578
|
+
await this._extensionRunner?.emit({ type: "session_shutdown" });
|
|
1579
|
+
this.settingsManager.reload();
|
|
1580
|
+
resetApiProviders();
|
|
1581
|
+
await this._resourceLoader.reload();
|
|
1582
|
+
this._buildRuntime({
|
|
1583
|
+
activeToolNames: this.getActiveToolNames(),
|
|
1584
|
+
flagValues: previousFlagValues,
|
|
1585
|
+
includeAllExtensionTools: true,
|
|
1586
|
+
});
|
|
1587
|
+
const hasBindings = this._extensionUIContext ||
|
|
1588
|
+
this._extensionCommandContextActions ||
|
|
1589
|
+
this._extensionShutdownHandler ||
|
|
1590
|
+
this._extensionErrorListener;
|
|
1591
|
+
if (this._extensionRunner && hasBindings) {
|
|
1592
|
+
await this._extensionRunner.emit({ type: "session_start" });
|
|
1593
|
+
await this.extendResourcesFromExtensions("reload");
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
// =========================================================================
|
|
1597
|
+
// Auto-Retry
|
|
1598
|
+
// =========================================================================
|
|
1599
|
+
/**
|
|
1600
|
+
* Check if an error is retryable (overloaded, rate limit, server errors).
|
|
1601
|
+
* Context overflow errors are NOT retryable (handled by compaction instead).
|
|
1602
|
+
*/
|
|
1603
|
+
_isRetryableError(message) {
|
|
1604
|
+
if (message.stopReason !== "error" || !message.errorMessage)
|
|
1605
|
+
return false;
|
|
1606
|
+
// Context overflow is handled by compaction, not retry
|
|
1607
|
+
const contextWindow = this.model?.contextWindow ?? 0;
|
|
1608
|
+
if (isContextOverflow(message, contextWindow))
|
|
1609
|
+
return false;
|
|
1610
|
+
const err = message.errorMessage;
|
|
1611
|
+
// Match: overloaded_error, rate limit, 429, 500, 502, 503, 504, service unavailable, connection errors, fetch failed, terminated, retry delay exceeded
|
|
1612
|
+
return /overloaded|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server error|internal error|connection.?error|connection.?refused|other side closed|fetch failed|upstream.?connect|reset before headers|terminated|retry delay/i.test(err);
|
|
1613
|
+
}
|
|
1614
|
+
/**
|
|
1615
|
+
* Handle retryable errors with exponential backoff.
|
|
1616
|
+
* @returns true if retry was initiated, false if max retries exceeded or disabled
|
|
1617
|
+
*/
|
|
1618
|
+
async _handleRetryableError(message) {
|
|
1619
|
+
const settings = this.settingsManager.getRetrySettings();
|
|
1620
|
+
if (!settings.enabled)
|
|
1621
|
+
return false;
|
|
1622
|
+
this._retryAttempt++;
|
|
1623
|
+
// Create retry promise on first attempt so waitForRetry() can await it
|
|
1624
|
+
if (this._retryAttempt === 1 && !this._retryPromise) {
|
|
1625
|
+
this._retryPromise = new Promise((resolve) => {
|
|
1626
|
+
this._retryResolve = resolve;
|
|
1627
|
+
});
|
|
1628
|
+
}
|
|
1629
|
+
if (this._retryAttempt > settings.maxRetries) {
|
|
1630
|
+
// Max retries exceeded, emit final failure and reset
|
|
1631
|
+
this._emit({
|
|
1632
|
+
type: "auto_retry_end",
|
|
1633
|
+
success: false,
|
|
1634
|
+
attempt: this._retryAttempt - 1,
|
|
1635
|
+
finalError: message.errorMessage,
|
|
1636
|
+
});
|
|
1637
|
+
this._retryAttempt = 0;
|
|
1638
|
+
this._resolveRetry(); // Resolve so waitForRetry() completes
|
|
1639
|
+
return false;
|
|
1640
|
+
}
|
|
1641
|
+
const delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);
|
|
1642
|
+
this._emit({
|
|
1643
|
+
type: "auto_retry_start",
|
|
1644
|
+
attempt: this._retryAttempt,
|
|
1645
|
+
maxAttempts: settings.maxRetries,
|
|
1646
|
+
delayMs,
|
|
1647
|
+
errorMessage: message.errorMessage || "Unknown error",
|
|
1648
|
+
});
|
|
1649
|
+
// Remove error message from agent state (keep in session for history)
|
|
1650
|
+
const messages = this.agent.state.messages;
|
|
1651
|
+
if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
|
|
1652
|
+
this.agent.replaceMessages(messages.slice(0, -1));
|
|
1653
|
+
}
|
|
1654
|
+
// Wait with exponential backoff (abortable)
|
|
1655
|
+
this._retryAbortController = new AbortController();
|
|
1656
|
+
try {
|
|
1657
|
+
await sleep(delayMs, this._retryAbortController.signal);
|
|
1658
|
+
}
|
|
1659
|
+
catch {
|
|
1660
|
+
// Aborted during sleep - emit end event so UI can clean up
|
|
1661
|
+
const attempt = this._retryAttempt;
|
|
1662
|
+
this._retryAttempt = 0;
|
|
1663
|
+
this._retryAbortController = undefined;
|
|
1664
|
+
this._emit({
|
|
1665
|
+
type: "auto_retry_end",
|
|
1666
|
+
success: false,
|
|
1667
|
+
attempt,
|
|
1668
|
+
finalError: "Retry cancelled",
|
|
1669
|
+
});
|
|
1670
|
+
this._resolveRetry();
|
|
1671
|
+
return false;
|
|
1672
|
+
}
|
|
1673
|
+
this._retryAbortController = undefined;
|
|
1674
|
+
// Retry via continue() - use setTimeout to break out of event handler chain
|
|
1675
|
+
setTimeout(() => {
|
|
1676
|
+
this.agent.continue().catch(() => {
|
|
1677
|
+
// Retry failed - will be caught by next agent_end
|
|
1678
|
+
});
|
|
1679
|
+
}, 0);
|
|
1680
|
+
return true;
|
|
1681
|
+
}
|
|
1682
|
+
/**
|
|
1683
|
+
* Cancel in-progress retry.
|
|
1684
|
+
*/
|
|
1685
|
+
abortRetry() {
|
|
1686
|
+
this._retryAbortController?.abort();
|
|
1687
|
+
// Note: _retryAttempt is reset in the catch block of _autoRetry
|
|
1688
|
+
this._resolveRetry();
|
|
1689
|
+
}
|
|
1690
|
+
/**
|
|
1691
|
+
* Wait for any in-progress retry to complete.
|
|
1692
|
+
* Returns immediately if no retry is in progress.
|
|
1693
|
+
*/
|
|
1694
|
+
async waitForRetry() {
|
|
1695
|
+
if (this._retryPromise) {
|
|
1696
|
+
await this._retryPromise;
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
/** Whether auto-retry is currently in progress */
|
|
1700
|
+
get isRetrying() {
|
|
1701
|
+
return this._retryPromise !== undefined;
|
|
1702
|
+
}
|
|
1703
|
+
/** Whether auto-retry is enabled */
|
|
1704
|
+
get autoRetryEnabled() {
|
|
1705
|
+
return this.settingsManager.getRetryEnabled();
|
|
1706
|
+
}
|
|
1707
|
+
/**
|
|
1708
|
+
* Toggle auto-retry setting.
|
|
1709
|
+
*/
|
|
1710
|
+
setAutoRetryEnabled(enabled) {
|
|
1711
|
+
this.settingsManager.setRetryEnabled(enabled);
|
|
1712
|
+
}
|
|
1713
|
+
// =========================================================================
|
|
1714
|
+
// Bash Execution
|
|
1715
|
+
// =========================================================================
|
|
1716
|
+
/**
|
|
1717
|
+
* Execute a bash command.
|
|
1718
|
+
* Adds result to agent context and session.
|
|
1719
|
+
* @param command The bash command to execute
|
|
1720
|
+
* @param onChunk Optional streaming callback for output
|
|
1721
|
+
* @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)
|
|
1722
|
+
* @param options.operations Custom BashOperations for remote execution
|
|
1723
|
+
*/
|
|
1724
|
+
async executeBash(command, onChunk, options) {
|
|
1725
|
+
this._bashAbortController = new AbortController();
|
|
1726
|
+
// Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
|
|
1727
|
+
const prefix = this.settingsManager.getShellCommandPrefix();
|
|
1728
|
+
const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
|
|
1729
|
+
try {
|
|
1730
|
+
const result = options?.operations
|
|
1731
|
+
? await executeBashWithOperations(resolvedCommand, process.cwd(), options.operations, {
|
|
1732
|
+
onChunk,
|
|
1733
|
+
signal: this._bashAbortController.signal,
|
|
1734
|
+
})
|
|
1735
|
+
: await executeBashCommand(resolvedCommand, {
|
|
1736
|
+
onChunk,
|
|
1737
|
+
signal: this._bashAbortController.signal,
|
|
1738
|
+
});
|
|
1739
|
+
this.recordBashResult(command, result, options);
|
|
1740
|
+
return result;
|
|
1741
|
+
}
|
|
1742
|
+
finally {
|
|
1743
|
+
this._bashAbortController = undefined;
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
/**
|
|
1747
|
+
* Record a bash execution result in session history.
|
|
1748
|
+
* Used by executeBash and by extensions that handle bash execution themselves.
|
|
1749
|
+
*/
|
|
1750
|
+
recordBashResult(command, result, options) {
|
|
1751
|
+
const bashMessage = {
|
|
1752
|
+
role: "bashExecution",
|
|
1753
|
+
command,
|
|
1754
|
+
output: result.output,
|
|
1755
|
+
exitCode: result.exitCode,
|
|
1756
|
+
cancelled: result.cancelled,
|
|
1757
|
+
truncated: result.truncated,
|
|
1758
|
+
fullOutputPath: result.fullOutputPath,
|
|
1759
|
+
timestamp: Date.now(),
|
|
1760
|
+
excludeFromContext: options?.excludeFromContext,
|
|
1761
|
+
};
|
|
1762
|
+
// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
|
|
1763
|
+
if (this.isStreaming) {
|
|
1764
|
+
// Queue for later - will be flushed on agent_end
|
|
1765
|
+
this._pendingBashMessages.push(bashMessage);
|
|
1766
|
+
}
|
|
1767
|
+
else {
|
|
1768
|
+
// Add to agent state immediately
|
|
1769
|
+
this.agent.appendMessage(bashMessage);
|
|
1770
|
+
// Save to session
|
|
1771
|
+
this.sessionManager.appendMessage(bashMessage);
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
/**
|
|
1775
|
+
* Cancel running bash command.
|
|
1776
|
+
*/
|
|
1777
|
+
abortBash() {
|
|
1778
|
+
this._bashAbortController?.abort();
|
|
1779
|
+
}
|
|
1780
|
+
/** Whether a bash command is currently running */
|
|
1781
|
+
get isBashRunning() {
|
|
1782
|
+
return this._bashAbortController !== undefined;
|
|
1783
|
+
}
|
|
1784
|
+
/** Whether there are pending bash messages waiting to be flushed */
|
|
1785
|
+
get hasPendingBashMessages() {
|
|
1786
|
+
return this._pendingBashMessages.length > 0;
|
|
1787
|
+
}
|
|
1788
|
+
/**
|
|
1789
|
+
* Flush pending bash messages to agent state and session.
|
|
1790
|
+
* Called after agent turn completes to maintain proper message ordering.
|
|
1791
|
+
*/
|
|
1792
|
+
_flushPendingBashMessages() {
|
|
1793
|
+
if (this._pendingBashMessages.length === 0)
|
|
1794
|
+
return;
|
|
1795
|
+
for (const bashMessage of this._pendingBashMessages) {
|
|
1796
|
+
// Add to agent state
|
|
1797
|
+
this.agent.appendMessage(bashMessage);
|
|
1798
|
+
// Save to session
|
|
1799
|
+
this.sessionManager.appendMessage(bashMessage);
|
|
1800
|
+
}
|
|
1801
|
+
this._pendingBashMessages = [];
|
|
1802
|
+
}
|
|
1803
|
+
// =========================================================================
|
|
1804
|
+
// Session Management
|
|
1805
|
+
// =========================================================================
|
|
1806
|
+
/**
|
|
1807
|
+
* Switch to a different session file.
|
|
1808
|
+
* Aborts current operation, loads messages, restores model/thinking.
|
|
1809
|
+
* Listeners are preserved and will continue receiving events.
|
|
1810
|
+
* @returns true if switch completed, false if cancelled by extension
|
|
1811
|
+
*/
|
|
1812
|
+
async switchSession(sessionPath) {
|
|
1813
|
+
const previousSessionFile = this.sessionManager.getSessionFile();
|
|
1814
|
+
// Emit session_before_switch event (can be cancelled)
|
|
1815
|
+
if (this._extensionRunner?.hasHandlers("session_before_switch")) {
|
|
1816
|
+
const result = (await this._extensionRunner.emit({
|
|
1817
|
+
type: "session_before_switch",
|
|
1818
|
+
reason: "resume",
|
|
1819
|
+
targetSessionFile: sessionPath,
|
|
1820
|
+
}));
|
|
1821
|
+
if (result?.cancel) {
|
|
1822
|
+
return false;
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
this._disconnectFromAgent();
|
|
1826
|
+
await this.abort();
|
|
1827
|
+
this._steeringMessages = [];
|
|
1828
|
+
this._followUpMessages = [];
|
|
1829
|
+
this._pendingNextTurnMessages = [];
|
|
1830
|
+
// Set new session
|
|
1831
|
+
this.sessionManager.setSessionFile(sessionPath);
|
|
1832
|
+
this.agent.sessionId = this.sessionManager.getSessionId();
|
|
1833
|
+
// Reload messages
|
|
1834
|
+
const sessionContext = this.sessionManager.buildSessionContext();
|
|
1835
|
+
// Emit session_switch event to extensions
|
|
1836
|
+
if (this._extensionRunner) {
|
|
1837
|
+
await this._extensionRunner.emit({
|
|
1838
|
+
type: "session_switch",
|
|
1839
|
+
reason: "resume",
|
|
1840
|
+
previousSessionFile,
|
|
1841
|
+
});
|
|
1842
|
+
}
|
|
1843
|
+
// Emit session event to custom tools
|
|
1844
|
+
this.agent.replaceMessages(sessionContext.messages);
|
|
1845
|
+
// Restore model if saved
|
|
1846
|
+
if (sessionContext.model) {
|
|
1847
|
+
const previousModel = this.model;
|
|
1848
|
+
const availableModels = await this._modelRegistry.getAvailable();
|
|
1849
|
+
const match = availableModels.find((m) => m.provider === sessionContext.model.provider && m.id === sessionContext.model.modelId);
|
|
1850
|
+
if (match) {
|
|
1851
|
+
this.agent.setModel(match);
|
|
1852
|
+
await this._emitModelSelect(match, previousModel, "restore");
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
const hasThinkingEntry = this.sessionManager.getBranch().some((entry) => entry.type === "thinking_level_change");
|
|
1856
|
+
const defaultThinkingLevel = this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
|
|
1857
|
+
if (hasThinkingEntry) {
|
|
1858
|
+
// Restore thinking level if saved (setThinkingLevel clamps to model capabilities)
|
|
1859
|
+
this.setThinkingLevel(sessionContext.thinkingLevel);
|
|
1860
|
+
}
|
|
1861
|
+
else {
|
|
1862
|
+
const availableLevels = this.getAvailableThinkingLevels();
|
|
1863
|
+
const effectiveLevel = availableLevels.includes(defaultThinkingLevel)
|
|
1864
|
+
? defaultThinkingLevel
|
|
1865
|
+
: this._clampThinkingLevel(defaultThinkingLevel, availableLevels);
|
|
1866
|
+
this.agent.setThinkingLevel(effectiveLevel);
|
|
1867
|
+
this.sessionManager.appendThinkingLevelChange(effectiveLevel);
|
|
1868
|
+
}
|
|
1869
|
+
this._reconnectToAgent();
|
|
1870
|
+
return true;
|
|
1871
|
+
}
|
|
1872
|
+
/**
|
|
1873
|
+
* Set a display name for the current session.
|
|
1874
|
+
*/
|
|
1875
|
+
setSessionName(name) {
|
|
1876
|
+
this.sessionManager.appendSessionInfo(name);
|
|
1877
|
+
}
|
|
1878
|
+
/**
|
|
1879
|
+
* Create a fork from a specific entry.
|
|
1880
|
+
* Emits before_fork/fork session events to extensions.
|
|
1881
|
+
*
|
|
1882
|
+
* @param entryId ID of the entry to fork from
|
|
1883
|
+
* @returns Object with:
|
|
1884
|
+
* - selectedText: The text of the selected user message (for editor pre-fill)
|
|
1885
|
+
* - cancelled: True if an extension cancelled the fork
|
|
1886
|
+
*/
|
|
1887
|
+
async fork(entryId) {
|
|
1888
|
+
const previousSessionFile = this.sessionFile;
|
|
1889
|
+
const selectedEntry = this.sessionManager.getEntry(entryId);
|
|
1890
|
+
if (!selectedEntry || selectedEntry.type !== "message" || selectedEntry.message.role !== "user") {
|
|
1891
|
+
throw new Error("Invalid entry ID for forking");
|
|
1892
|
+
}
|
|
1893
|
+
const selectedText = this._extractUserMessageText(selectedEntry.message.content);
|
|
1894
|
+
let skipConversationRestore = false;
|
|
1895
|
+
// Emit session_before_fork event (can be cancelled)
|
|
1896
|
+
if (this._extensionRunner?.hasHandlers("session_before_fork")) {
|
|
1897
|
+
const result = (await this._extensionRunner.emit({
|
|
1898
|
+
type: "session_before_fork",
|
|
1899
|
+
entryId,
|
|
1900
|
+
}));
|
|
1901
|
+
if (result?.cancel) {
|
|
1902
|
+
return { selectedText, cancelled: true };
|
|
1903
|
+
}
|
|
1904
|
+
skipConversationRestore = result?.skipConversationRestore ?? false;
|
|
1905
|
+
}
|
|
1906
|
+
// Clear pending messages (bound to old session state)
|
|
1907
|
+
this._pendingNextTurnMessages = [];
|
|
1908
|
+
if (!selectedEntry.parentId) {
|
|
1909
|
+
this.sessionManager.newSession({ parentSession: previousSessionFile });
|
|
1910
|
+
}
|
|
1911
|
+
else {
|
|
1912
|
+
this.sessionManager.createBranchedSession(selectedEntry.parentId);
|
|
1913
|
+
}
|
|
1914
|
+
this.agent.sessionId = this.sessionManager.getSessionId();
|
|
1915
|
+
// Reload messages from entries (works for both file and in-memory mode)
|
|
1916
|
+
const sessionContext = this.sessionManager.buildSessionContext();
|
|
1917
|
+
// Emit session_fork event to extensions (after fork completes)
|
|
1918
|
+
if (this._extensionRunner) {
|
|
1919
|
+
await this._extensionRunner.emit({
|
|
1920
|
+
type: "session_fork",
|
|
1921
|
+
previousSessionFile,
|
|
1922
|
+
});
|
|
1923
|
+
}
|
|
1924
|
+
// Emit session event to custom tools (with reason "fork")
|
|
1925
|
+
if (!skipConversationRestore) {
|
|
1926
|
+
this.agent.replaceMessages(sessionContext.messages);
|
|
1927
|
+
}
|
|
1928
|
+
return { selectedText, cancelled: false };
|
|
1929
|
+
}
|
|
1930
|
+
// =========================================================================
|
|
1931
|
+
// Tree Navigation
|
|
1932
|
+
// =========================================================================
|
|
1933
|
+
/**
|
|
1934
|
+
* Navigate to a different node in the session tree.
|
|
1935
|
+
* Unlike fork() which creates a new session file, this stays in the same file.
|
|
1936
|
+
*
|
|
1937
|
+
* @param targetId The entry ID to navigate to
|
|
1938
|
+
* @param options.summarize Whether user wants to summarize abandoned branch
|
|
1939
|
+
* @param options.customInstructions Custom instructions for summarizer
|
|
1940
|
+
* @param options.replaceInstructions If true, customInstructions replaces the default prompt
|
|
1941
|
+
* @param options.label Label to attach to the branch summary entry
|
|
1942
|
+
* @returns Result with editorText (if user message) and cancelled status
|
|
1943
|
+
*/
|
|
1944
|
+
async navigateTree(targetId, options = {}) {
|
|
1945
|
+
const oldLeafId = this.sessionManager.getLeafId();
|
|
1946
|
+
// No-op if already at target
|
|
1947
|
+
if (targetId === oldLeafId) {
|
|
1948
|
+
return { cancelled: false };
|
|
1949
|
+
}
|
|
1950
|
+
// Model required for summarization
|
|
1951
|
+
if (options.summarize && !this.model) {
|
|
1952
|
+
throw new Error("No model available for summarization");
|
|
1953
|
+
}
|
|
1954
|
+
const targetEntry = this.sessionManager.getEntry(targetId);
|
|
1955
|
+
if (!targetEntry) {
|
|
1956
|
+
throw new Error(`Entry ${targetId} not found`);
|
|
1957
|
+
}
|
|
1958
|
+
// Collect entries to summarize (from old leaf to common ancestor)
|
|
1959
|
+
const { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(this.sessionManager, oldLeafId, targetId);
|
|
1960
|
+
// Prepare event data - mutable so extensions can override
|
|
1961
|
+
let customInstructions = options.customInstructions;
|
|
1962
|
+
let replaceInstructions = options.replaceInstructions;
|
|
1963
|
+
let label = options.label;
|
|
1964
|
+
const preparation = {
|
|
1965
|
+
targetId,
|
|
1966
|
+
oldLeafId,
|
|
1967
|
+
commonAncestorId,
|
|
1968
|
+
entriesToSummarize,
|
|
1969
|
+
userWantsSummary: options.summarize ?? false,
|
|
1970
|
+
customInstructions,
|
|
1971
|
+
replaceInstructions,
|
|
1972
|
+
label,
|
|
1973
|
+
};
|
|
1974
|
+
// Set up abort controller for summarization
|
|
1975
|
+
this._branchSummaryAbortController = new AbortController();
|
|
1976
|
+
let extensionSummary;
|
|
1977
|
+
let fromExtension = false;
|
|
1978
|
+
// Emit session_before_tree event
|
|
1979
|
+
if (this._extensionRunner?.hasHandlers("session_before_tree")) {
|
|
1980
|
+
const result = (await this._extensionRunner.emit({
|
|
1981
|
+
type: "session_before_tree",
|
|
1982
|
+
preparation,
|
|
1983
|
+
signal: this._branchSummaryAbortController.signal,
|
|
1984
|
+
}));
|
|
1985
|
+
if (result?.cancel) {
|
|
1986
|
+
return { cancelled: true };
|
|
1987
|
+
}
|
|
1988
|
+
if (result?.summary && options.summarize) {
|
|
1989
|
+
extensionSummary = result.summary;
|
|
1990
|
+
fromExtension = true;
|
|
1991
|
+
}
|
|
1992
|
+
// Allow extensions to override instructions and label
|
|
1993
|
+
if (result?.customInstructions !== undefined) {
|
|
1994
|
+
customInstructions = result.customInstructions;
|
|
1995
|
+
}
|
|
1996
|
+
if (result?.replaceInstructions !== undefined) {
|
|
1997
|
+
replaceInstructions = result.replaceInstructions;
|
|
1998
|
+
}
|
|
1999
|
+
if (result?.label !== undefined) {
|
|
2000
|
+
label = result.label;
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
// Run default summarizer if needed
|
|
2004
|
+
let summaryText;
|
|
2005
|
+
let summaryDetails;
|
|
2006
|
+
if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
|
|
2007
|
+
const model = this.model;
|
|
2008
|
+
const apiKey = await this._modelRegistry.getApiKey(model);
|
|
2009
|
+
if (!apiKey) {
|
|
2010
|
+
throw new Error(`No API key for ${model.provider}`);
|
|
2011
|
+
}
|
|
2012
|
+
const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
|
|
2013
|
+
const result = await generateBranchSummary(entriesToSummarize, {
|
|
2014
|
+
model,
|
|
2015
|
+
apiKey,
|
|
2016
|
+
signal: this._branchSummaryAbortController.signal,
|
|
2017
|
+
customInstructions,
|
|
2018
|
+
replaceInstructions,
|
|
2019
|
+
reserveTokens: branchSummarySettings.reserveTokens,
|
|
2020
|
+
});
|
|
2021
|
+
this._branchSummaryAbortController = undefined;
|
|
2022
|
+
if (result.aborted) {
|
|
2023
|
+
return { cancelled: true, aborted: true };
|
|
2024
|
+
}
|
|
2025
|
+
if (result.error) {
|
|
2026
|
+
throw new Error(result.error);
|
|
2027
|
+
}
|
|
2028
|
+
summaryText = result.summary;
|
|
2029
|
+
summaryDetails = {
|
|
2030
|
+
readFiles: result.readFiles || [],
|
|
2031
|
+
modifiedFiles: result.modifiedFiles || [],
|
|
2032
|
+
};
|
|
2033
|
+
}
|
|
2034
|
+
else if (extensionSummary) {
|
|
2035
|
+
summaryText = extensionSummary.summary;
|
|
2036
|
+
summaryDetails = extensionSummary.details;
|
|
2037
|
+
}
|
|
2038
|
+
// Determine the new leaf position based on target type
|
|
2039
|
+
let newLeafId;
|
|
2040
|
+
let editorText;
|
|
2041
|
+
if (targetEntry.type === "message" && targetEntry.message.role === "user") {
|
|
2042
|
+
// User message: leaf = parent (null if root), text goes to editor
|
|
2043
|
+
newLeafId = targetEntry.parentId;
|
|
2044
|
+
editorText = this._extractUserMessageText(targetEntry.message.content);
|
|
2045
|
+
}
|
|
2046
|
+
else if (targetEntry.type === "custom_message") {
|
|
2047
|
+
// Custom message: leaf = parent (null if root), text goes to editor
|
|
2048
|
+
newLeafId = targetEntry.parentId;
|
|
2049
|
+
editorText =
|
|
2050
|
+
typeof targetEntry.content === "string"
|
|
2051
|
+
? targetEntry.content
|
|
2052
|
+
: targetEntry.content
|
|
2053
|
+
.filter((c) => c.type === "text")
|
|
2054
|
+
.map((c) => c.text)
|
|
2055
|
+
.join("");
|
|
2056
|
+
}
|
|
2057
|
+
else {
|
|
2058
|
+
// Non-user message: leaf = selected node
|
|
2059
|
+
newLeafId = targetId;
|
|
2060
|
+
}
|
|
2061
|
+
// Switch leaf (with or without summary)
|
|
2062
|
+
// Summary is attached at the navigation target position (newLeafId), not the old branch
|
|
2063
|
+
let summaryEntry;
|
|
2064
|
+
if (summaryText) {
|
|
2065
|
+
// Create summary at target position (can be null for root)
|
|
2066
|
+
const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension);
|
|
2067
|
+
summaryEntry = this.sessionManager.getEntry(summaryId);
|
|
2068
|
+
// Attach label to the summary entry
|
|
2069
|
+
if (label) {
|
|
2070
|
+
this.sessionManager.appendLabelChange(summaryId, label);
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
else if (newLeafId === null) {
|
|
2074
|
+
// No summary, navigating to root - reset leaf
|
|
2075
|
+
this.sessionManager.resetLeaf();
|
|
2076
|
+
}
|
|
2077
|
+
else {
|
|
2078
|
+
// No summary, navigating to non-root
|
|
2079
|
+
this.sessionManager.branch(newLeafId);
|
|
2080
|
+
}
|
|
2081
|
+
// Attach label to target entry when not summarizing (no summary entry to label)
|
|
2082
|
+
if (label && !summaryText) {
|
|
2083
|
+
this.sessionManager.appendLabelChange(targetId, label);
|
|
2084
|
+
}
|
|
2085
|
+
// Update agent state
|
|
2086
|
+
const sessionContext = this.sessionManager.buildSessionContext();
|
|
2087
|
+
this.agent.replaceMessages(sessionContext.messages);
|
|
2088
|
+
// Emit session_tree event
|
|
2089
|
+
if (this._extensionRunner) {
|
|
2090
|
+
await this._extensionRunner.emit({
|
|
2091
|
+
type: "session_tree",
|
|
2092
|
+
newLeafId: this.sessionManager.getLeafId(),
|
|
2093
|
+
oldLeafId,
|
|
2094
|
+
summaryEntry,
|
|
2095
|
+
fromExtension: summaryText ? fromExtension : undefined,
|
|
2096
|
+
});
|
|
2097
|
+
}
|
|
2098
|
+
// Emit to custom tools
|
|
2099
|
+
this._branchSummaryAbortController = undefined;
|
|
2100
|
+
return { editorText, cancelled: false, summaryEntry };
|
|
2101
|
+
}
|
|
2102
|
+
/**
|
|
2103
|
+
* Get all user messages from session for fork selector.
|
|
2104
|
+
*/
|
|
2105
|
+
getUserMessagesForForking() {
|
|
2106
|
+
const entries = this.sessionManager.getEntries();
|
|
2107
|
+
const result = [];
|
|
2108
|
+
for (const entry of entries) {
|
|
2109
|
+
if (entry.type !== "message")
|
|
2110
|
+
continue;
|
|
2111
|
+
if (entry.message.role !== "user")
|
|
2112
|
+
continue;
|
|
2113
|
+
const text = this._extractUserMessageText(entry.message.content);
|
|
2114
|
+
if (text) {
|
|
2115
|
+
result.push({ entryId: entry.id, text });
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
return result;
|
|
2119
|
+
}
|
|
2120
|
+
_extractUserMessageText(content) {
|
|
2121
|
+
if (typeof content === "string")
|
|
2122
|
+
return content;
|
|
2123
|
+
if (Array.isArray(content)) {
|
|
2124
|
+
return content
|
|
2125
|
+
.filter((c) => c.type === "text")
|
|
2126
|
+
.map((c) => c.text)
|
|
2127
|
+
.join("");
|
|
2128
|
+
}
|
|
2129
|
+
return "";
|
|
2130
|
+
}
|
|
2131
|
+
/**
|
|
2132
|
+
* Get session statistics.
|
|
2133
|
+
*/
|
|
2134
|
+
getSessionStats() {
|
|
2135
|
+
const state = this.state;
|
|
2136
|
+
const userMessages = state.messages.filter((m) => m.role === "user").length;
|
|
2137
|
+
const assistantMessages = state.messages.filter((m) => m.role === "assistant").length;
|
|
2138
|
+
const toolResults = state.messages.filter((m) => m.role === "toolResult").length;
|
|
2139
|
+
let toolCalls = 0;
|
|
2140
|
+
let totalInput = 0;
|
|
2141
|
+
let totalOutput = 0;
|
|
2142
|
+
let totalCacheRead = 0;
|
|
2143
|
+
let totalCacheWrite = 0;
|
|
2144
|
+
let totalCost = 0;
|
|
2145
|
+
for (const message of state.messages) {
|
|
2146
|
+
if (message.role === "assistant") {
|
|
2147
|
+
const assistantMsg = message;
|
|
2148
|
+
toolCalls += assistantMsg.content.filter((c) => c.type === "toolCall").length;
|
|
2149
|
+
totalInput += assistantMsg.usage.input;
|
|
2150
|
+
totalOutput += assistantMsg.usage.output;
|
|
2151
|
+
totalCacheRead += assistantMsg.usage.cacheRead;
|
|
2152
|
+
totalCacheWrite += assistantMsg.usage.cacheWrite;
|
|
2153
|
+
totalCost += assistantMsg.usage.cost.total;
|
|
2154
|
+
}
|
|
2155
|
+
}
|
|
2156
|
+
return {
|
|
2157
|
+
sessionFile: this.sessionFile,
|
|
2158
|
+
sessionId: this.sessionId,
|
|
2159
|
+
userMessages,
|
|
2160
|
+
assistantMessages,
|
|
2161
|
+
toolCalls,
|
|
2162
|
+
toolResults,
|
|
2163
|
+
totalMessages: state.messages.length,
|
|
2164
|
+
tokens: {
|
|
2165
|
+
input: totalInput,
|
|
2166
|
+
output: totalOutput,
|
|
2167
|
+
cacheRead: totalCacheRead,
|
|
2168
|
+
cacheWrite: totalCacheWrite,
|
|
2169
|
+
total: totalInput + totalOutput + totalCacheRead + totalCacheWrite,
|
|
2170
|
+
},
|
|
2171
|
+
cost: totalCost,
|
|
2172
|
+
};
|
|
2173
|
+
}
|
|
2174
|
+
getContextUsage() {
|
|
2175
|
+
const model = this.model;
|
|
2176
|
+
if (!model)
|
|
2177
|
+
return undefined;
|
|
2178
|
+
const contextWindow = model.contextWindow ?? 0;
|
|
2179
|
+
if (contextWindow <= 0)
|
|
2180
|
+
return undefined;
|
|
2181
|
+
const estimate = estimateContextTokens(this.messages);
|
|
2182
|
+
const percent = (estimate.tokens / contextWindow) * 100;
|
|
2183
|
+
return {
|
|
2184
|
+
tokens: estimate.tokens,
|
|
2185
|
+
contextWindow,
|
|
2186
|
+
percent,
|
|
2187
|
+
usageTokens: estimate.usageTokens,
|
|
2188
|
+
trailingTokens: estimate.trailingTokens,
|
|
2189
|
+
lastUsageIndex: estimate.lastUsageIndex,
|
|
2190
|
+
};
|
|
2191
|
+
}
|
|
2192
|
+
/**
|
|
2193
|
+
* Export session to HTML.
|
|
2194
|
+
* @param outputPath Optional output path (defaults to session directory)
|
|
2195
|
+
* @returns Path to exported file
|
|
2196
|
+
*/
|
|
2197
|
+
async exportToHtml(outputPath) {
|
|
2198
|
+
const themeName = this.settingsManager.getTheme();
|
|
2199
|
+
// Create tool renderer if we have an extension runner (for custom tool HTML rendering)
|
|
2200
|
+
let toolRenderer;
|
|
2201
|
+
if (this._extensionRunner) {
|
|
2202
|
+
toolRenderer = createToolHtmlRenderer({
|
|
2203
|
+
getToolDefinition: (name) => this._extensionRunner.getToolDefinition(name),
|
|
2204
|
+
theme,
|
|
2205
|
+
});
|
|
2206
|
+
}
|
|
2207
|
+
return await exportSessionToHtml(this.sessionManager, this.state, {
|
|
2208
|
+
outputPath,
|
|
2209
|
+
themeName,
|
|
2210
|
+
toolRenderer,
|
|
2211
|
+
});
|
|
2212
|
+
}
|
|
2213
|
+
// =========================================================================
|
|
2214
|
+
// Utilities
|
|
2215
|
+
// =========================================================================
|
|
2216
|
+
/**
|
|
2217
|
+
* Get text content of last assistant message.
|
|
2218
|
+
* Useful for /copy command.
|
|
2219
|
+
* @returns Text content, or undefined if no assistant message exists
|
|
2220
|
+
*/
|
|
2221
|
+
getLastAssistantText() {
|
|
2222
|
+
const lastAssistant = this.messages
|
|
2223
|
+
.slice()
|
|
2224
|
+
.reverse()
|
|
2225
|
+
.find((m) => {
|
|
2226
|
+
if (m.role !== "assistant")
|
|
2227
|
+
return false;
|
|
2228
|
+
const msg = m;
|
|
2229
|
+
// Skip aborted messages with no content
|
|
2230
|
+
if (msg.stopReason === "aborted" && msg.content.length === 0)
|
|
2231
|
+
return false;
|
|
2232
|
+
return true;
|
|
2233
|
+
});
|
|
2234
|
+
if (!lastAssistant)
|
|
2235
|
+
return undefined;
|
|
2236
|
+
let text = "";
|
|
2237
|
+
for (const content of lastAssistant.content) {
|
|
2238
|
+
if (content.type === "text") {
|
|
2239
|
+
text += content.text;
|
|
2240
|
+
}
|
|
2241
|
+
}
|
|
2242
|
+
return text.trim() || undefined;
|
|
2243
|
+
}
|
|
2244
|
+
// =========================================================================
|
|
2245
|
+
// Extension System
|
|
2246
|
+
// =========================================================================
|
|
2247
|
+
/**
|
|
2248
|
+
* Check if extensions have handlers for a specific event type.
|
|
2249
|
+
*/
|
|
2250
|
+
hasExtensionHandlers(eventType) {
|
|
2251
|
+
return this._extensionRunner?.hasHandlers(eventType) ?? false;
|
|
2252
|
+
}
|
|
2253
|
+
/**
|
|
2254
|
+
* Get the extension runner (for setting UI context and error handlers).
|
|
2255
|
+
*/
|
|
2256
|
+
get extensionRunner() {
|
|
2257
|
+
return this._extensionRunner;
|
|
2258
|
+
}
|
|
2259
|
+
}
|
|
2260
|
+
//# sourceMappingURL=agent-session.js.map
|