gsd-pi 2.77.0-dev.538325aea → 2.77.0-dev.eaa4973bc
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/dist/cli-web-branch.d.ts +1 -0
- package/dist/cli-web-branch.js +3 -0
- package/dist/cli.js +59 -15
- package/dist/extension-discovery.d.ts +6 -0
- package/dist/extension-discovery.js +37 -0
- package/dist/extension-registry.d.ts +3 -0
- package/dist/extension-registry.js +1 -1
- package/dist/extension-sort.d.ts +18 -0
- package/dist/extension-sort.js +114 -0
- package/dist/extension-validator.d.ts +47 -0
- package/dist/extension-validator.js +127 -0
- package/dist/headless-ui.d.ts +1 -1
- package/dist/headless.js +4 -2
- package/dist/loader.js +36 -7
- package/dist/onboarding.js +5 -5
- package/dist/provider-migrations.d.ts +20 -2
- package/dist/provider-migrations.js +15 -2
- package/dist/remote-questions-config.js +1 -1
- package/dist/resources/extensions/async-jobs/async-bash-tool.js +1 -1
- package/dist/resources/extensions/aws-auth/index.js +1 -2
- package/dist/resources/extensions/bg-shell/bg-shell-lifecycle.js +9 -6
- package/dist/resources/extensions/bg-shell/process-manager.js +1 -2
- package/dist/resources/extensions/browser-tools/index.js +1 -0
- package/dist/resources/extensions/claude-code-cli/index.js +1 -1
- package/dist/resources/extensions/claude-code-cli/partial-builder.js +17 -106
- package/dist/resources/extensions/claude-code-cli/stream-adapter.js +71 -57
- package/dist/resources/extensions/cmux/index.js +20 -0
- package/dist/resources/extensions/google-search/extension-manifest.json +5 -4
- package/dist/resources/extensions/google-search/index.js +2 -375
- package/dist/resources/extensions/gsd/abandon-detect.js +44 -0
- package/dist/resources/extensions/gsd/auto/resolve.js +24 -0
- package/dist/resources/extensions/gsd/auto/run-unit.js +10 -2
- package/dist/resources/extensions/gsd/auto/turn-epoch.js +95 -0
- package/dist/resources/extensions/gsd/auto-dispatch.js +24 -0
- package/dist/resources/extensions/gsd/auto-loop.js +1 -1
- package/dist/resources/extensions/gsd/auto-post-unit.js +31 -0
- package/dist/resources/extensions/gsd/auto-timeout-recovery.js +11 -5
- package/dist/resources/extensions/gsd/auto-unit-closeout.js +11 -2
- package/dist/resources/extensions/gsd/auto-worktree.js +58 -8
- package/dist/resources/extensions/gsd/auto.js +31 -14
- package/dist/resources/extensions/gsd/bootstrap/provider-error-resume.js +4 -2
- package/dist/resources/extensions/gsd/bootstrap/register-extension.js +11 -0
- package/dist/resources/extensions/gsd/bootstrap/system-context.js +11 -6
- package/dist/resources/extensions/gsd/commands/handlers/workflow.js +31 -4
- package/dist/resources/extensions/gsd/commands-cmux.js +9 -6
- package/dist/resources/extensions/gsd/commands-extensions.js +634 -43
- package/dist/resources/extensions/gsd/file-lock.js +49 -9
- package/dist/resources/extensions/gsd/git-service.js +1 -0
- package/dist/resources/extensions/gsd/gitignore.js +1 -0
- package/dist/resources/extensions/gsd/guided-flow-queue.js +4 -1
- package/dist/resources/extensions/gsd/guided-flow.js +1 -1
- package/dist/resources/extensions/gsd/journal.js +17 -2
- package/dist/resources/extensions/gsd/milestone-actions.js +15 -0
- package/dist/resources/extensions/gsd/notifications.js +30 -16
- package/dist/resources/extensions/gsd/reports.js +5 -4
- package/dist/resources/extensions/gsd/tools/complete-slice.js +21 -0
- package/dist/resources/extensions/gsd/tools/complete-task.js +31 -0
- package/dist/resources/extensions/gsd/uok/audit.js +18 -2
- package/dist/resources/extensions/gsd/workflow-logger.js +10 -2
- package/dist/resources/extensions/gsd/worktree-manager.js +1 -0
- package/dist/resources/extensions/mcp-client/auth.js +10 -1
- package/dist/resources/extensions/mcp-client/index.js +119 -10
- package/dist/resources/extensions/ollama/index.js +2 -1
- package/dist/resources/extensions/ollama/ollama-chat-provider.js +15 -5
- package/dist/resources/extensions/remote-questions/config.js +1 -12
- package/dist/resources/extensions/shared/cmux-events.js +12 -0
- package/dist/resources/extensions/shared/rtk-session-stats.js +1 -2
- package/dist/resources/extensions/universal-config/index.js +1 -1
- package/dist/resources/skills/create-skill/SKILL.md +2 -2
- package/dist/resources/skills/create-skill/references/gsd-skill-ecosystem.md +4 -4
- package/dist/resources/skills/create-skill/workflows/audit-skill.md +4 -4
- package/dist/resources/skills/create-skill/workflows/create-new-skill.md +5 -5
- package/dist/security-overrides.d.ts +1 -4
- package/dist/security-overrides.js +3 -16
- package/dist/tsconfig.extensions.tsbuildinfo +1 -1
- package/dist/web/standalone/.next/BUILD_ID +1 -1
- package/dist/web/standalone/.next/app-path-routes-manifest.json +11 -11
- package/dist/web/standalone/.next/build-manifest.json +3 -3
- package/dist/web/standalone/.next/prerender-manifest.json +3 -3
- package/dist/web/standalone/.next/react-loadable-manifest.json +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.html +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.html +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/api/boot/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/boot/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/bridge-terminal/input/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/bridge-terminal/input/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/bridge-terminal/resize/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/bridge-terminal/resize/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/bridge-terminal/stream/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/bridge-terminal/stream/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/captures/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/captures/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/cleanup/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/cleanup/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/doctor/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/doctor/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/export-data/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/export-data/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/files/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/files/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/forensics/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/forensics/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/git/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/git/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/history/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/history/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/hooks/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/hooks/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/inspect/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/inspect/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/knowledge/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/knowledge/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/live-state/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/live-state/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/notifications/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/notifications/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/onboarding/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/onboarding/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/projects/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/projects/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/recovery/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/recovery/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/session/browser/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/session/browser/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/session/command/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/session/command/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/session/events/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/session/events/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/session/manage/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/session/manage/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/settings-data/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/settings-data/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/skill-health/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/skill-health/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/steer/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/steer/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/switch-root/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/switch-root/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/terminal/input/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/terminal/resize/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/terminal/sessions/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/terminal/sessions/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/terminal/stream/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/terminal/stream/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/undo/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/undo/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/visualizer/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/visualizer/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/index.html +1 -1
- package/dist/web/standalone/.next/server/app/index.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/_full.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/_index.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app-paths-manifest.json +11 -11
- package/dist/web/standalone/.next/server/chunks/1926.js +1 -0
- package/dist/web/standalone/.next/server/chunks/6897.js +2 -2
- package/dist/web/standalone/.next/server/middleware-build-manifest.js +1 -1
- package/dist/web/standalone/.next/server/middleware-manifest.json +5 -5
- package/dist/web/standalone/.next/server/middleware-react-loadable-manifest.js +1 -1
- package/dist/web/standalone/.next/server/pages/404.html +1 -1
- package/dist/web/standalone/.next/server/pages/500.html +1 -1
- package/dist/web/standalone/.next/server/server-reference-manifest.json +1 -1
- package/dist/web/standalone/.next/static/chunks/2826.e9f5195e91f9cad2.js +11 -0
- package/dist/web/standalone/.next/static/chunks/{webpack-1832629448831fdc.js → webpack-2e68521d7c82f7c2.js} +1 -1
- package/dist/web-mode.js +1 -1
- package/dist/welcome-screen.js +20 -19
- package/dist/wizard.js +5 -2
- package/package.json +16 -32
- package/packages/mcp-server/README.md +3 -3
- package/packages/mcp-server/dist/env-writer.d.ts +1 -0
- package/packages/mcp-server/dist/env-writer.d.ts.map +1 -1
- package/packages/mcp-server/dist/env-writer.js +74 -6
- package/packages/mcp-server/dist/env-writer.js.map +1 -1
- package/packages/mcp-server/dist/server.d.ts.map +1 -1
- package/packages/mcp-server/dist/server.js +36 -17
- package/packages/mcp-server/dist/server.js.map +1 -1
- package/packages/mcp-server/package.json +5 -0
- package/packages/mcp-server/src/env-writer.test.ts +79 -1
- package/packages/mcp-server/src/env-writer.ts +76 -6
- package/packages/mcp-server/src/readers/readers.test.ts +5 -1
- package/packages/mcp-server/src/server.ts +45 -19
- package/packages/mcp-server/tsconfig.tsbuildinfo +1 -1
- package/packages/native/package.json +5 -0
- package/packages/native/src/__tests__/clipboard.test.mjs +69 -23
- package/packages/native/tsconfig.json +1 -2
- package/packages/native/tsconfig.tsbuildinfo +1 -0
- package/packages/pi-agent-core/package.json +5 -0
- package/packages/pi-agent-core/src/agent-loop.test.ts +220 -15
- package/packages/pi-ai/package.json +5 -0
- package/packages/pi-ai/tsconfig.tsbuildinfo +1 -1
- package/packages/pi-coding-agent/dist/core/compaction/compaction.d.ts +25 -0
- package/packages/pi-coding-agent/dist/core/compaction/compaction.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/compaction/compaction.js +105 -6
- package/packages/pi-coding-agent/dist/core/compaction/compaction.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/compaction/compaction.test.js +230 -28
- package/packages/pi-coding-agent/dist/core/compaction/compaction.test.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/compaction/utils.d.ts +30 -2
- package/packages/pi-coding-agent/dist/core/compaction/utils.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/compaction/utils.js +113 -12
- package/packages/pi-coding-agent/dist/core/compaction/utils.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/compaction-orchestrator.d.ts +1 -0
- package/packages/pi-coding-agent/dist/core/compaction-orchestrator.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/compaction-orchestrator.js +29 -18
- package/packages/pi-coding-agent/dist/core/compaction-orchestrator.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/compaction-orchestrator.test.d.ts +2 -0
- package/packages/pi-coding-agent/dist/core/compaction-orchestrator.test.d.ts.map +1 -0
- package/packages/pi-coding-agent/dist/core/compaction-orchestrator.test.js +130 -0
- package/packages/pi-coding-agent/dist/core/compaction-orchestrator.test.js.map +1 -0
- package/packages/pi-coding-agent/dist/core/compaction-utils.test.js +56 -1
- package/packages/pi-coding-agent/dist/core/compaction-utils.test.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/discovery-cache.test.js +8 -15
- package/packages/pi-coding-agent/dist/core/discovery-cache.test.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/extensions/extension-discovery.d.ts +25 -0
- package/packages/pi-coding-agent/dist/core/extensions/extension-discovery.d.ts.map +1 -0
- package/packages/pi-coding-agent/dist/core/extensions/extension-discovery.js +109 -0
- package/packages/pi-coding-agent/dist/core/extensions/extension-discovery.js.map +1 -0
- package/packages/pi-coding-agent/dist/core/extensions/extension-registry.d.ts +67 -0
- package/packages/pi-coding-agent/dist/core/extensions/extension-registry.d.ts.map +1 -0
- package/packages/pi-coding-agent/dist/core/extensions/extension-registry.js +167 -0
- package/packages/pi-coding-agent/dist/core/extensions/extension-registry.js.map +1 -0
- package/packages/pi-coding-agent/dist/core/extensions/loader.d.ts +3 -2
- package/packages/pi-coding-agent/dist/core/extensions/loader.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/extensions/loader.js +24 -8
- package/packages/pi-coding-agent/dist/core/extensions/loader.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/extensions/types.d.ts +7 -0
- package/packages/pi-coding-agent/dist/core/extensions/types.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/extensions/types.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/lsp/lsp-integration.test.js +11 -0
- package/packages/pi-coding-agent/dist/core/lsp/lsp-integration.test.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/model-registry-auth-mode.test.js +2 -2
- package/packages/pi-coding-agent/dist/core/model-registry-auth-mode.test.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/resource-loader.js +1 -1
- package/packages/pi-coding-agent/dist/core/resource-loader.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/sdk.d.ts +1 -0
- package/packages/pi-coding-agent/dist/core/sdk.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/sdk.js +4 -1
- package/packages/pi-coding-agent/dist/core/sdk.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/sdk.test.js +19 -1
- package/packages/pi-coding-agent/dist/core/sdk.test.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/system-prompt.js +3 -3
- package/packages/pi-coding-agent/dist/core/system-prompt.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/tools/path-utils.test.js +2 -1
- package/packages/pi-coding-agent/dist/core/tools/path-utils.test.js.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/components/__tests__/provider-display-name.test.js +15 -6
- package/packages/pi-coding-agent/dist/modes/interactive/components/__tests__/provider-display-name.test.js.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/components/footer.js +14 -5
- package/packages/pi-coding-agent/dist/modes/interactive/components/footer.js.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/components/model-selector.d.ts +7 -1
- package/packages/pi-coding-agent/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/components/model-selector.js +31 -9
- package/packages/pi-coding-agent/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/controllers/input-controller.test.js +14 -0
- package/packages/pi-coding-agent/dist/modes/interactive/controllers/input-controller.test.js.map +1 -1
- package/packages/pi-coding-agent/package.json +5 -0
- package/packages/pi-coding-agent/src/core/compaction/compaction.test.ts +368 -28
- package/packages/pi-coding-agent/src/core/compaction/compaction.ts +122 -6
- package/packages/pi-coding-agent/src/core/compaction/utils.ts +111 -13
- package/packages/pi-coding-agent/src/core/compaction-orchestrator.test.ts +154 -0
- package/packages/pi-coding-agent/src/core/compaction-orchestrator.ts +32 -18
- package/packages/pi-coding-agent/src/core/compaction-utils.test.ts +68 -1
- package/packages/pi-coding-agent/src/core/discovery-cache.test.ts +9 -18
- package/packages/pi-coding-agent/src/core/extensions/extension-discovery.ts +119 -0
- package/packages/pi-coding-agent/src/core/extensions/extension-registry.ts +222 -0
- package/packages/pi-coding-agent/src/core/extensions/loader.ts +24 -11
- package/packages/pi-coding-agent/src/core/extensions/types.ts +8 -0
- package/packages/pi-coding-agent/src/core/lsp/lsp-integration.test.ts +13 -0
- package/packages/pi-coding-agent/src/core/model-registry-auth-mode.test.ts +2 -2
- package/packages/pi-coding-agent/src/core/resource-loader.ts +1 -1
- package/packages/pi-coding-agent/src/core/sdk.test.ts +25 -1
- package/packages/pi-coding-agent/src/core/sdk.ts +10 -3
- package/packages/pi-coding-agent/src/core/system-prompt.ts +3 -3
- package/packages/pi-coding-agent/src/core/tools/path-utils.test.ts +2 -1
- package/packages/pi-coding-agent/src/modes/interactive/components/__tests__/provider-display-name.test.ts +17 -7
- package/packages/pi-coding-agent/src/modes/interactive/components/footer.ts +14 -5
- package/packages/pi-coding-agent/src/modes/interactive/components/model-selector.ts +45 -11
- package/packages/pi-coding-agent/src/modes/interactive/controllers/input-controller.test.ts +14 -0
- package/packages/pi-coding-agent/tsconfig.tsbuildinfo +1 -1
- package/packages/pi-tui/dist/__tests__/autocomplete.test.js +12 -5
- package/packages/pi-tui/dist/__tests__/autocomplete.test.js.map +1 -1
- package/packages/pi-tui/dist/__tests__/stdin-buffer.test.js +19 -0
- package/packages/pi-tui/dist/__tests__/stdin-buffer.test.js.map +1 -1
- package/packages/pi-tui/dist/stdin-buffer.d.ts +7 -0
- package/packages/pi-tui/dist/stdin-buffer.d.ts.map +1 -1
- package/packages/pi-tui/dist/stdin-buffer.js +20 -0
- package/packages/pi-tui/dist/stdin-buffer.js.map +1 -1
- package/packages/pi-tui/package.json +5 -0
- package/packages/pi-tui/src/__tests__/autocomplete.test.ts +20 -5
- package/packages/pi-tui/src/__tests__/stdin-buffer.test.ts +25 -0
- package/packages/pi-tui/src/stdin-buffer.ts +26 -0
- package/packages/pi-tui/tsconfig.tsbuildinfo +1 -1
- package/packages/rpc-client/package.json +5 -0
- package/pkg/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
- package/pkg/dist/core/export-html/ansi-to-html.js +0 -1
- package/pkg/dist/core/export-html/ansi-to-html.js.map +1 -1
- package/pkg/dist/core/export-html/index.d.ts +1 -1
- package/pkg/dist/core/export-html/index.d.ts.map +1 -1
- package/pkg/dist/core/export-html/index.js +5 -39
- package/pkg/dist/core/export-html/index.js.map +1 -1
- package/pkg/dist/core/export-html/tool-renderer.d.ts +2 -2
- package/pkg/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/pkg/dist/core/export-html/tool-renderer.js.map +1 -1
- package/scripts/ensure-workspace-builds.cjs +0 -2
- package/scripts/lib/workspace-manifest.cjs +86 -0
- package/scripts/link-workspace-packages.cjs +5 -19
- package/src/resources/extensions/async-jobs/async-bash-tool.ts +1 -1
- package/src/resources/extensions/aws-auth/index.ts +1 -2
- package/src/resources/extensions/bg-shell/bg-shell-lifecycle.ts +7 -4
- package/src/resources/extensions/bg-shell/index.ts +1 -2
- package/src/resources/extensions/bg-shell/process-manager.ts +1 -2
- package/src/resources/extensions/browser-tools/index.ts +1 -2
- package/src/resources/extensions/claude-code-cli/index.ts +1 -1
- package/src/resources/extensions/claude-code-cli/partial-builder.ts +23 -115
- package/src/resources/extensions/claude-code-cli/stream-adapter.ts +81 -61
- package/src/resources/extensions/claude-code-cli/tests/stream-adapter.test.ts +91 -22
- package/src/resources/extensions/cmux/index.ts +35 -10
- package/src/resources/extensions/google-search/extension-manifest.json +5 -4
- package/src/resources/extensions/google-search/index.ts +8 -470
- package/src/resources/extensions/gsd/abandon-detect.ts +62 -0
- package/src/resources/extensions/gsd/auto/loop-deps.ts +1 -1
- package/src/resources/extensions/gsd/auto/resolve.ts +29 -0
- package/src/resources/extensions/gsd/auto/run-unit.ts +16 -2
- package/src/resources/extensions/gsd/auto/turn-epoch.ts +108 -0
- package/src/resources/extensions/gsd/auto/types.ts +1 -1
- package/src/resources/extensions/gsd/auto-dispatch.ts +20 -0
- package/src/resources/extensions/gsd/auto-loop.ts +1 -1
- package/src/resources/extensions/gsd/auto-post-unit.ts +30 -0
- package/src/resources/extensions/gsd/auto-timeout-recovery.ts +12 -5
- package/src/resources/extensions/gsd/auto-unit-closeout.ts +14 -3
- package/src/resources/extensions/gsd/auto-worktree.ts +60 -5
- package/src/resources/extensions/gsd/auto.ts +37 -18
- package/src/resources/extensions/gsd/bootstrap/provider-error-resume.ts +6 -2
- package/src/resources/extensions/gsd/bootstrap/register-extension.ts +11 -0
- package/src/resources/extensions/gsd/bootstrap/system-context.ts +13 -9
- package/src/resources/extensions/gsd/commands/handlers/workflow.ts +27 -8
- package/src/resources/extensions/gsd/commands-cmux.ts +10 -6
- package/src/resources/extensions/gsd/commands-extensions.ts +747 -41
- package/src/resources/extensions/gsd/file-lock.ts +84 -11
- package/src/resources/extensions/gsd/git-service.ts +1 -0
- package/src/resources/extensions/gsd/gitignore.ts +1 -0
- package/src/resources/extensions/gsd/guided-flow-queue.ts +4 -1
- package/src/resources/extensions/gsd/guided-flow.ts +1 -1
- package/src/resources/extensions/gsd/journal.ts +27 -2
- package/src/resources/extensions/gsd/milestone-actions.ts +18 -0
- package/src/resources/extensions/gsd/notifications.ts +27 -15
- package/src/resources/extensions/gsd/reports.ts +5 -4
- package/src/resources/extensions/gsd/tests/auto-loop.test.ts +11 -2
- package/src/resources/extensions/gsd/tests/auto-mode-guards.test.ts +79 -0
- package/src/resources/extensions/gsd/tests/cmux.test.ts +5 -9
- package/src/resources/extensions/gsd/tests/file-lock.test.ts +86 -12
- package/src/resources/extensions/gsd/tests/google-search-stub.test.ts +121 -0
- package/src/resources/extensions/gsd/tests/integration/auto-worktree-milestone-merge.test.ts +30 -0
- package/src/resources/extensions/gsd/tests/integration/git-service.test.ts +3 -2
- package/src/resources/extensions/gsd/tests/mcp-client-security.test.ts +76 -0
- package/src/resources/extensions/gsd/tests/milestone-transition-state-rebuild.test.ts +4 -2
- package/src/resources/extensions/gsd/tests/parallel-commit-scope.test.ts +5 -0
- package/src/resources/extensions/gsd/tests/parallel-skill-prompt-integration.test.ts +150 -0
- package/src/resources/extensions/gsd/tests/provider-errors.test.ts +39 -25
- package/src/resources/extensions/gsd/tests/queue-auto-guard.test.ts +181 -0
- package/src/resources/extensions/gsd/tests/quick-auto-guard.test.ts +13 -7
- package/src/resources/extensions/gsd/tests/require-slice-discussion-dispatch.test.ts +170 -0
- package/src/resources/extensions/gsd/tests/rewrite-docs-abandon-detect.test.ts +195 -0
- package/src/resources/extensions/gsd/tests/stuck-detection-coverage.test.ts +2 -2
- package/src/resources/extensions/gsd/tests/triage-resolution.test.ts +50 -2
- package/src/resources/extensions/gsd/tests/turn-epoch.test.ts +162 -0
- package/src/resources/extensions/gsd/tests/validate-extension-package.test.ts +168 -0
- package/src/resources/extensions/gsd/tests/workflow-mcp.test.ts +25 -2
- package/src/resources/extensions/gsd/tools/complete-slice.ts +38 -0
- package/src/resources/extensions/gsd/tools/complete-task.ts +49 -0
- package/src/resources/extensions/gsd/uok/audit.ts +20 -2
- package/src/resources/extensions/gsd/workflow-logger.ts +22 -3
- package/src/resources/extensions/gsd/worktree-manager.ts +1 -0
- package/src/resources/extensions/mcp-client/auth.ts +12 -1
- package/src/resources/extensions/mcp-client/index.ts +130 -11
- package/src/resources/extensions/ollama/index.ts +3 -3
- package/src/resources/extensions/ollama/ollama-chat-provider.ts +18 -6
- package/src/resources/extensions/remote-questions/config.ts +4 -15
- package/src/resources/extensions/search-the-web/index.ts +1 -2
- package/src/resources/extensions/shared/cmux-events.ts +59 -0
- package/src/resources/extensions/shared/rtk-session-stats.ts +1 -2
- package/src/resources/extensions/shared/tests/format-utils.test.ts +3 -5
- package/src/resources/extensions/universal-config/index.ts +1 -1
- package/src/resources/skills/create-skill/SKILL.md +2 -2
- package/src/resources/skills/create-skill/references/gsd-skill-ecosystem.md +4 -4
- package/src/resources/skills/create-skill/workflows/audit-skill.md +4 -4
- package/src/resources/skills/create-skill/workflows/create-new-skill.md +5 -5
- package/dist/web/standalone/.next/server/chunks/7461.js +0 -1
- package/dist/web/standalone/.next/static/chunks/2826.d445fb428ef41fa1.js +0 -9
- package/packages/gsd-agent-core/dist/agent-session.d.ts +0 -716
- package/packages/gsd-agent-core/dist/agent-session.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/agent-session.js +0 -2595
- package/packages/gsd-agent-core/dist/agent-session.js.map +0 -1
- package/packages/gsd-agent-core/dist/artifact-manager.d.ts +0 -52
- package/packages/gsd-agent-core/dist/artifact-manager.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/artifact-manager.js +0 -118
- package/packages/gsd-agent-core/dist/artifact-manager.js.map +0 -1
- package/packages/gsd-agent-core/dist/bash-executor.d.ts +0 -57
- package/packages/gsd-agent-core/dist/bash-executor.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/bash-executor.js +0 -282
- package/packages/gsd-agent-core/dist/bash-executor.js.map +0 -1
- package/packages/gsd-agent-core/dist/blob-store.d.ts +0 -39
- package/packages/gsd-agent-core/dist/blob-store.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/blob-store.js +0 -151
- package/packages/gsd-agent-core/dist/blob-store.js.map +0 -1
- package/packages/gsd-agent-core/dist/compaction/branch-summarization.d.ts +0 -90
- package/packages/gsd-agent-core/dist/compaction/branch-summarization.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/compaction/branch-summarization.js +0 -207
- package/packages/gsd-agent-core/dist/compaction/branch-summarization.js.map +0 -1
- package/packages/gsd-agent-core/dist/compaction/compaction.d.ts +0 -137
- package/packages/gsd-agent-core/dist/compaction/compaction.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/compaction/compaction.js +0 -621
- package/packages/gsd-agent-core/dist/compaction/compaction.js.map +0 -1
- package/packages/gsd-agent-core/dist/compaction/index.d.ts +0 -7
- package/packages/gsd-agent-core/dist/compaction/index.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/compaction/index.js +0 -7
- package/packages/gsd-agent-core/dist/compaction/index.js.map +0 -1
- package/packages/gsd-agent-core/dist/compaction/utils.d.ts +0 -78
- package/packages/gsd-agent-core/dist/compaction/utils.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/compaction/utils.js +0 -263
- package/packages/gsd-agent-core/dist/compaction/utils.js.map +0 -1
- package/packages/gsd-agent-core/dist/compaction-orchestrator.d.ts +0 -90
- package/packages/gsd-agent-core/dist/compaction-orchestrator.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/compaction-orchestrator.js +0 -338
- package/packages/gsd-agent-core/dist/compaction-orchestrator.js.map +0 -1
- package/packages/gsd-agent-core/dist/contextual-tips.d.ts +0 -43
- package/packages/gsd-agent-core/dist/contextual-tips.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/contextual-tips.js +0 -208
- package/packages/gsd-agent-core/dist/contextual-tips.js.map +0 -1
- package/packages/gsd-agent-core/dist/export-html/ansi-to-html.d.ts +0 -18
- package/packages/gsd-agent-core/dist/export-html/ansi-to-html.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/export-html/ansi-to-html.js +0 -250
- package/packages/gsd-agent-core/dist/export-html/ansi-to-html.js.map +0 -1
- package/packages/gsd-agent-core/dist/export-html/index.d.ts +0 -37
- package/packages/gsd-agent-core/dist/export-html/index.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/export-html/index.js +0 -257
- package/packages/gsd-agent-core/dist/export-html/index.js.map +0 -1
- package/packages/gsd-agent-core/dist/export-html/template.css +0 -971
- package/packages/gsd-agent-core/dist/export-html/template.html +0 -54
- package/packages/gsd-agent-core/dist/export-html/template.js +0 -1583
- package/packages/gsd-agent-core/dist/export-html/tool-renderer.d.ts +0 -38
- package/packages/gsd-agent-core/dist/export-html/tool-renderer.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/export-html/tool-renderer.js +0 -70
- package/packages/gsd-agent-core/dist/export-html/tool-renderer.js.map +0 -1
- package/packages/gsd-agent-core/dist/export-html/vendor/highlight.min.js +0 -1213
- package/packages/gsd-agent-core/dist/export-html/vendor/marked.min.js +0 -6
- package/packages/gsd-agent-core/dist/fallback-resolver.d.ts +0 -75
- package/packages/gsd-agent-core/dist/fallback-resolver.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/fallback-resolver.js +0 -118
- package/packages/gsd-agent-core/dist/fallback-resolver.js.map +0 -1
- package/packages/gsd-agent-core/dist/image-overflow-recovery.d.ts +0 -44
- package/packages/gsd-agent-core/dist/image-overflow-recovery.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/image-overflow-recovery.js +0 -99
- package/packages/gsd-agent-core/dist/image-overflow-recovery.js.map +0 -1
- package/packages/gsd-agent-core/dist/index.d.ts +0 -14
- package/packages/gsd-agent-core/dist/index.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/index.js +0 -19
- package/packages/gsd-agent-core/dist/index.js.map +0 -1
- package/packages/gsd-agent-core/dist/keybindings.d.ts +0 -47
- package/packages/gsd-agent-core/dist/keybindings.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/keybindings.js +0 -156
- package/packages/gsd-agent-core/dist/keybindings.js.map +0 -1
- package/packages/gsd-agent-core/dist/lifecycle-hooks.d.ts +0 -42
- package/packages/gsd-agent-core/dist/lifecycle-hooks.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/lifecycle-hooks.js +0 -204
- package/packages/gsd-agent-core/dist/lifecycle-hooks.js.map +0 -1
- package/packages/gsd-agent-core/dist/retry-handler.d.ts +0 -128
- package/packages/gsd-agent-core/dist/retry-handler.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/retry-handler.js +0 -518
- package/packages/gsd-agent-core/dist/retry-handler.js.map +0 -1
- package/packages/gsd-agent-core/dist/sdk.d.ts +0 -159
- package/packages/gsd-agent-core/dist/sdk.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/sdk.js +0 -375
- package/packages/gsd-agent-core/dist/sdk.js.map +0 -1
- package/packages/gsd-agent-core/dist/system-prompt.d.ts +0 -28
- package/packages/gsd-agent-core/dist/system-prompt.d.ts.map +0 -1
- package/packages/gsd-agent-core/dist/system-prompt.js +0 -201
- package/packages/gsd-agent-core/dist/system-prompt.js.map +0 -1
- package/packages/gsd-agent-core/package.json +0 -25
- package/packages/gsd-agent-core/scripts/copy-assets.cjs +0 -43
- package/packages/gsd-agent-core/src/agent-session.test.ts +0 -169
- package/packages/gsd-agent-core/src/agent-session.ts +0 -3358
- package/packages/gsd-agent-core/src/artifact-manager.ts +0 -126
- package/packages/gsd-agent-core/src/bash-executor.ts +0 -352
- package/packages/gsd-agent-core/src/blob-store.ts +0 -154
- package/packages/gsd-agent-core/src/compaction/branch-summarization.ts +0 -317
- package/packages/gsd-agent-core/src/compaction/compaction.ts +0 -855
- package/packages/gsd-agent-core/src/compaction/index.ts +0 -7
- package/packages/gsd-agent-core/src/compaction/utils.ts +0 -312
- package/packages/gsd-agent-core/src/compaction-orchestrator.ts +0 -449
- package/packages/gsd-agent-core/src/contextual-tips.ts +0 -232
- package/packages/gsd-agent-core/src/export-html/ansi-to-html.ts +0 -259
- package/packages/gsd-agent-core/src/export-html/index.ts +0 -345
- package/packages/gsd-agent-core/src/export-html/template.css +0 -971
- package/packages/gsd-agent-core/src/export-html/template.html +0 -54
- package/packages/gsd-agent-core/src/export-html/template.js +0 -1583
- package/packages/gsd-agent-core/src/export-html/tool-renderer.ts +0 -114
- package/packages/gsd-agent-core/src/export-html/vendor/highlight.min.js +0 -1213
- package/packages/gsd-agent-core/src/export-html/vendor/marked.min.js +0 -6
- package/packages/gsd-agent-core/src/fallback-resolver.ts +0 -193
- package/packages/gsd-agent-core/src/image-overflow-recovery.ts +0 -120
- package/packages/gsd-agent-core/src/index.ts +0 -68
- package/packages/gsd-agent-core/src/keybindings.ts +0 -220
- package/packages/gsd-agent-core/src/lifecycle-hooks.ts +0 -284
- package/packages/gsd-agent-core/src/retry-handler.ts +0 -620
- package/packages/gsd-agent-core/src/sdk.ts +0 -550
- package/packages/gsd-agent-core/src/system-prompt.ts +0 -270
- package/packages/gsd-agent-core/tsconfig.json +0 -28
- package/packages/gsd-agent-core/tsconfig.tsbuildinfo +0 -1
- package/packages/gsd-agent-modes/dist/cli/args.d.ts +0 -58
- package/packages/gsd-agent-modes/dist/cli/args.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/cli/args.js +0 -324
- package/packages/gsd-agent-modes/dist/cli/args.js.map +0 -1
- package/packages/gsd-agent-modes/dist/cli/config-selector.d.ts +0 -13
- package/packages/gsd-agent-modes/dist/cli/config-selector.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/cli/config-selector.js +0 -32
- package/packages/gsd-agent-modes/dist/cli/config-selector.js.map +0 -1
- package/packages/gsd-agent-modes/dist/cli/file-processor.d.ts +0 -15
- package/packages/gsd-agent-modes/dist/cli/file-processor.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/cli/file-processor.js +0 -86
- package/packages/gsd-agent-modes/dist/cli/file-processor.js.map +0 -1
- package/packages/gsd-agent-modes/dist/cli/list-models.d.ts +0 -21
- package/packages/gsd-agent-modes/dist/cli/list-models.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/cli/list-models.js +0 -114
- package/packages/gsd-agent-modes/dist/cli/list-models.js.map +0 -1
- package/packages/gsd-agent-modes/dist/cli/session-picker.d.ts +0 -10
- package/packages/gsd-agent-modes/dist/cli/session-picker.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/cli/session-picker.js +0 -37
- package/packages/gsd-agent-modes/dist/cli/session-picker.js.map +0 -1
- package/packages/gsd-agent-modes/dist/index.d.ts +0 -7
- package/packages/gsd-agent-modes/dist/index.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/index.js +0 -7
- package/packages/gsd-agent-modes/dist/index.js.map +0 -1
- package/packages/gsd-agent-modes/dist/main.d.ts +0 -8
- package/packages/gsd-agent-modes/dist/main.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/main.js +0 -491
- package/packages/gsd-agent-modes/dist/main.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/armin.d.ts +0 -34
- package/packages/gsd-agent-modes/dist/modes/interactive/components/armin.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/armin.js +0 -330
- package/packages/gsd-agent-modes/dist/modes/interactive/components/armin.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/assistant-message.d.ts +0 -29
- package/packages/gsd-agent-modes/dist/modes/interactive/components/assistant-message.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/assistant-message.js +0 -141
- package/packages/gsd-agent-modes/dist/modes/interactive/components/assistant-message.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/bash-execution.d.ts +0 -36
- package/packages/gsd-agent-modes/dist/modes/interactive/components/bash-execution.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/bash-execution.js +0 -157
- package/packages/gsd-agent-modes/dist/modes/interactive/components/bash-execution.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/bordered-loader.d.ts +0 -16
- package/packages/gsd-agent-modes/dist/modes/interactive/components/bordered-loader.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/bordered-loader.js +0 -48
- package/packages/gsd-agent-modes/dist/modes/interactive/components/bordered-loader.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/branch-summary-message.d.ts +0 -16
- package/packages/gsd-agent-modes/dist/modes/interactive/components/branch-summary-message.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/branch-summary-message.js +0 -43
- package/packages/gsd-agent-modes/dist/modes/interactive/components/branch-summary-message.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/chat-frame.d.ts +0 -11
- package/packages/gsd-agent-modes/dist/modes/interactive/components/chat-frame.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/chat-frame.js +0 -47
- package/packages/gsd-agent-modes/dist/modes/interactive/components/chat-frame.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/compaction-summary-message.d.ts +0 -16
- package/packages/gsd-agent-modes/dist/modes/interactive/components/compaction-summary-message.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/compaction-summary-message.js +0 -44
- package/packages/gsd-agent-modes/dist/modes/interactive/components/compaction-summary-message.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/config-selector.d.ts +0 -71
- package/packages/gsd-agent-modes/dist/modes/interactive/components/config-selector.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/config-selector.js +0 -474
- package/packages/gsd-agent-modes/dist/modes/interactive/components/config-selector.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/countdown-timer.d.ts +0 -15
- package/packages/gsd-agent-modes/dist/modes/interactive/components/countdown-timer.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/countdown-timer.js +0 -32
- package/packages/gsd-agent-modes/dist/modes/interactive/components/countdown-timer.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/custom-editor.d.ts +0 -22
- package/packages/gsd-agent-modes/dist/modes/interactive/components/custom-editor.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/custom-editor.js +0 -70
- package/packages/gsd-agent-modes/dist/modes/interactive/components/custom-editor.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/custom-message.d.ts +0 -20
- package/packages/gsd-agent-modes/dist/modes/interactive/components/custom-message.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/custom-message.js +0 -75
- package/packages/gsd-agent-modes/dist/modes/interactive/components/custom-message.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/daxnuts.d.ts +0 -23
- package/packages/gsd-agent-modes/dist/modes/interactive/components/daxnuts.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/daxnuts.js +0 -140
- package/packages/gsd-agent-modes/dist/modes/interactive/components/daxnuts.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/diff.d.ts +0 -12
- package/packages/gsd-agent-modes/dist/modes/interactive/components/diff.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/diff.js +0 -133
- package/packages/gsd-agent-modes/dist/modes/interactive/components/diff.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/dynamic-border.d.ts +0 -33
- package/packages/gsd-agent-modes/dist/modes/interactive/components/dynamic-border.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/dynamic-border.js +0 -82
- package/packages/gsd-agent-modes/dist/modes/interactive/components/dynamic-border.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/extension-editor.d.ts +0 -20
- package/packages/gsd-agent-modes/dist/modes/interactive/components/extension-editor.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/extension-editor.js +0 -111
- package/packages/gsd-agent-modes/dist/modes/interactive/components/extension-editor.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/extension-input.d.ts +0 -24
- package/packages/gsd-agent-modes/dist/modes/interactive/components/extension-input.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/extension-input.js +0 -63
- package/packages/gsd-agent-modes/dist/modes/interactive/components/extension-input.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/extension-selector.d.ts +0 -33
- package/packages/gsd-agent-modes/dist/modes/interactive/components/extension-selector.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/extension-selector.js +0 -118
- package/packages/gsd-agent-modes/dist/modes/interactive/components/extension-selector.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/footer.d.ts +0 -32
- package/packages/gsd-agent-modes/dist/modes/interactive/components/footer.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/footer.js +0 -230
- package/packages/gsd-agent-modes/dist/modes/interactive/components/footer.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/index.d.ts +0 -34
- package/packages/gsd-agent-modes/dist/modes/interactive/components/index.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/index.js +0 -36
- package/packages/gsd-agent-modes/dist/modes/interactive/components/index.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/keybinding-hints.d.ts +0 -48
- package/packages/gsd-agent-modes/dist/modes/interactive/components/keybinding-hints.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/keybinding-hints.js +0 -72
- package/packages/gsd-agent-modes/dist/modes/interactive/components/keybinding-hints.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/login-dialog.d.ts +0 -63
- package/packages/gsd-agent-modes/dist/modes/interactive/components/login-dialog.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/login-dialog.js +0 -213
- package/packages/gsd-agent-modes/dist/modes/interactive/components/login-dialog.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/model-selector.d.ts +0 -86
- package/packages/gsd-agent-modes/dist/modes/interactive/components/model-selector.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/model-selector.js +0 -536
- package/packages/gsd-agent-modes/dist/modes/interactive/components/model-selector.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/oauth-selector.d.ts +0 -19
- package/packages/gsd-agent-modes/dist/modes/interactive/components/oauth-selector.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/oauth-selector.js +0 -93
- package/packages/gsd-agent-modes/dist/modes/interactive/components/oauth-selector.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/provider-manager.d.ts +0 -30
- package/packages/gsd-agent-modes/dist/modes/interactive/components/provider-manager.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/provider-manager.js +0 -169
- package/packages/gsd-agent-modes/dist/modes/interactive/components/provider-manager.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/scoped-models-selector.d.ts +0 -49
- package/packages/gsd-agent-modes/dist/modes/interactive/components/scoped-models-selector.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/scoped-models-selector.js +0 -267
- package/packages/gsd-agent-modes/dist/modes/interactive/components/scoped-models-selector.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/session-selector-search.d.ts +0 -21
- package/packages/gsd-agent-modes/dist/modes/interactive/components/session-selector-search.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/session-selector-search.js +0 -155
- package/packages/gsd-agent-modes/dist/modes/interactive/components/session-selector-search.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/session-selector.d.ts +0 -97
- package/packages/gsd-agent-modes/dist/modes/interactive/components/session-selector.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/session-selector.js +0 -810
- package/packages/gsd-agent-modes/dist/modes/interactive/components/session-selector.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/settings-selector.d.ts +0 -71
- package/packages/gsd-agent-modes/dist/modes/interactive/components/settings-selector.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/settings-selector.js +0 -320
- package/packages/gsd-agent-modes/dist/modes/interactive/components/settings-selector.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/show-images-selector.d.ts +0 -10
- package/packages/gsd-agent-modes/dist/modes/interactive/components/show-images-selector.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/show-images-selector.js +0 -34
- package/packages/gsd-agent-modes/dist/modes/interactive/components/show-images-selector.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/skill-invocation-message.d.ts +0 -17
- package/packages/gsd-agent-modes/dist/modes/interactive/components/skill-invocation-message.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/skill-invocation-message.js +0 -46
- package/packages/gsd-agent-modes/dist/modes/interactive/components/skill-invocation-message.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/theme-selector.d.ts +0 -11
- package/packages/gsd-agent-modes/dist/modes/interactive/components/theme-selector.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/theme-selector.js +0 -45
- package/packages/gsd-agent-modes/dist/modes/interactive/components/theme-selector.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/thinking-selector.d.ts +0 -11
- package/packages/gsd-agent-modes/dist/modes/interactive/components/thinking-selector.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/thinking-selector.js +0 -46
- package/packages/gsd-agent-modes/dist/modes/interactive/components/thinking-selector.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/timestamp.d.ts +0 -15
- package/packages/gsd-agent-modes/dist/modes/interactive/components/timestamp.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/timestamp.js +0 -40
- package/packages/gsd-agent-modes/dist/modes/interactive/components/timestamp.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/tool-execution.d.ts +0 -111
- package/packages/gsd-agent-modes/dist/modes/interactive/components/tool-execution.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/tool-execution.js +0 -984
- package/packages/gsd-agent-modes/dist/modes/interactive/components/tool-execution.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/tree-render-utils.d.ts +0 -44
- package/packages/gsd-agent-modes/dist/modes/interactive/components/tree-render-utils.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/tree-render-utils.js +0 -61
- package/packages/gsd-agent-modes/dist/modes/interactive/components/tree-render-utils.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/tree-selector.d.ts +0 -109
- package/packages/gsd-agent-modes/dist/modes/interactive/components/tree-selector.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/tree-selector.js +0 -1035
- package/packages/gsd-agent-modes/dist/modes/interactive/components/tree-selector.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/user-message-selector.d.ts +0 -30
- package/packages/gsd-agent-modes/dist/modes/interactive/components/user-message-selector.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/user-message-selector.js +0 -112
- package/packages/gsd-agent-modes/dist/modes/interactive/components/user-message-selector.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/user-message.d.ts +0 -12
- package/packages/gsd-agent-modes/dist/modes/interactive/components/user-message.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/user-message.js +0 -38
- package/packages/gsd-agent-modes/dist/modes/interactive/components/user-message.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/visual-truncate.d.ts +0 -24
- package/packages/gsd-agent-modes/dist/modes/interactive/components/visual-truncate.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/components/visual-truncate.js +0 -33
- package/packages/gsd-agent-modes/dist/modes/interactive/components/visual-truncate.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/controllers/chat-controller.d.ts +0 -27
- package/packages/gsd-agent-modes/dist/modes/interactive/controllers/chat-controller.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/controllers/chat-controller.js +0 -793
- package/packages/gsd-agent-modes/dist/modes/interactive/controllers/chat-controller.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/controllers/extension-ui-controller.d.ts +0 -4
- package/packages/gsd-agent-modes/dist/modes/interactive/controllers/extension-ui-controller.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/controllers/extension-ui-controller.js +0 -62
- package/packages/gsd-agent-modes/dist/modes/interactive/controllers/extension-ui-controller.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/controllers/input-controller.d.ts +0 -22
- package/packages/gsd-agent-modes/dist/modes/interactive/controllers/input-controller.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/controllers/input-controller.js +0 -118
- package/packages/gsd-agent-modes/dist/modes/interactive/controllers/input-controller.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/controllers/model-controller.d.ts +0 -7
- package/packages/gsd-agent-modes/dist/modes/interactive/controllers/model-controller.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/controllers/model-controller.js +0 -68
- package/packages/gsd-agent-modes/dist/modes/interactive/controllers/model-controller.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/interactive-mode-state.d.ts +0 -50
- package/packages/gsd-agent-modes/dist/modes/interactive/interactive-mode-state.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/interactive-mode-state.js +0 -2
- package/packages/gsd-agent-modes/dist/modes/interactive/interactive-mode-state.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/interactive-mode.d.ts +0 -358
- package/packages/gsd-agent-modes/dist/modes/interactive/interactive-mode.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/interactive-mode.js +0 -3409
- package/packages/gsd-agent-modes/dist/modes/interactive/interactive-mode.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/slash-command-handlers.d.ts +0 -77
- package/packages/gsd-agent-modes/dist/modes/interactive/slash-command-handlers.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/slash-command-handlers.js +0 -529
- package/packages/gsd-agent-modes/dist/modes/interactive/slash-command-handlers.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/utils/shorten-path.d.ts +0 -6
- package/packages/gsd-agent-modes/dist/modes/interactive/utils/shorten-path.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/interactive/utils/shorten-path.js +0 -15
- package/packages/gsd-agent-modes/dist/modes/interactive/utils/shorten-path.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/print-mode.d.ts +0 -28
- package/packages/gsd-agent-modes/dist/modes/print-mode.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/print-mode.js +0 -84
- package/packages/gsd-agent-modes/dist/modes/print-mode.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/rpc/jsonl.d.ts +0 -17
- package/packages/gsd-agent-modes/dist/modes/rpc/jsonl.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/rpc/jsonl.js +0 -49
- package/packages/gsd-agent-modes/dist/modes/rpc/jsonl.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/rpc/remote-terminal.d.ts +0 -37
- package/packages/gsd-agent-modes/dist/modes/rpc/remote-terminal.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/rpc/remote-terminal.js +0 -84
- package/packages/gsd-agent-modes/dist/modes/rpc/remote-terminal.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/rpc/rpc-client.d.ts +0 -243
- package/packages/gsd-agent-modes/dist/modes/rpc/rpc-client.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/rpc/rpc-client.js +0 -464
- package/packages/gsd-agent-modes/dist/modes/rpc/rpc-client.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/rpc/rpc-mode.d.ts +0 -25
- package/packages/gsd-agent-modes/dist/modes/rpc/rpc-mode.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/rpc/rpc-mode.js +0 -750
- package/packages/gsd-agent-modes/dist/modes/rpc/rpc-mode.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/rpc/rpc-types.d.ts +0 -511
- package/packages/gsd-agent-modes/dist/modes/rpc/rpc-types.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/rpc/rpc-types.js +0 -8
- package/packages/gsd-agent-modes/dist/modes/rpc/rpc-types.js.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/shared/command-context-actions.d.ts +0 -19
- package/packages/gsd-agent-modes/dist/modes/shared/command-context-actions.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/modes/shared/command-context-actions.js +0 -45
- package/packages/gsd-agent-modes/dist/modes/shared/command-context-actions.js.map +0 -1
- package/packages/gsd-agent-modes/dist/pi-coding-agent-compat.d.ts +0 -22
- package/packages/gsd-agent-modes/dist/pi-coding-agent-compat.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/pi-coding-agent-compat.js +0 -21
- package/packages/gsd-agent-modes/dist/pi-coding-agent-compat.js.map +0 -1
- package/packages/gsd-agent-modes/dist/pi-tui-compat.d.ts +0 -4
- package/packages/gsd-agent-modes/dist/pi-tui-compat.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/pi-tui-compat.js +0 -3
- package/packages/gsd-agent-modes/dist/pi-tui-compat.js.map +0 -1
- package/packages/gsd-agent-modes/dist/theme.d.ts +0 -15
- package/packages/gsd-agent-modes/dist/theme.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/theme.js +0 -23
- package/packages/gsd-agent-modes/dist/theme.js.map +0 -1
- package/packages/gsd-agent-modes/dist/utils/theme.d.ts +0 -16
- package/packages/gsd-agent-modes/dist/utils/theme.d.ts.map +0 -1
- package/packages/gsd-agent-modes/dist/utils/theme.js +0 -11
- package/packages/gsd-agent-modes/dist/utils/theme.js.map +0 -1
- package/packages/gsd-agent-modes/package.json +0 -23
- package/packages/gsd-agent-modes/src/cli/args.ts +0 -350
- package/packages/gsd-agent-modes/src/cli/config-selector.ts +0 -54
- package/packages/gsd-agent-modes/src/cli/file-processor.ts +0 -107
- package/packages/gsd-agent-modes/src/cli/list-models.ts +0 -141
- package/packages/gsd-agent-modes/src/cli/session-picker.ts +0 -59
- package/packages/gsd-agent-modes/src/index.ts +0 -6
- package/packages/gsd-agent-modes/src/main.ts +0 -614
- package/packages/gsd-agent-modes/src/modes/interactive/components/__tests__/login-dialog.test.ts +0 -24
- package/packages/gsd-agent-modes/src/modes/interactive/components/__tests__/provider-display-name.test.ts +0 -18
- package/packages/gsd-agent-modes/src/modes/interactive/components/__tests__/timestamp.test.ts +0 -38
- package/packages/gsd-agent-modes/src/modes/interactive/components/__tests__/tool-execution.test.ts +0 -171
- package/packages/gsd-agent-modes/src/modes/interactive/components/armin.ts +0 -382
- package/packages/gsd-agent-modes/src/modes/interactive/components/assistant-message.ts +0 -178
- package/packages/gsd-agent-modes/src/modes/interactive/components/bash-execution.ts +0 -212
- package/packages/gsd-agent-modes/src/modes/interactive/components/bordered-loader.ts +0 -66
- package/packages/gsd-agent-modes/src/modes/interactive/components/branch-summary-message.ts +0 -59
- package/packages/gsd-agent-modes/src/modes/interactive/components/chat-frame.ts +0 -67
- package/packages/gsd-agent-modes/src/modes/interactive/components/compaction-summary-message.ts +0 -60
- package/packages/gsd-agent-modes/src/modes/interactive/components/config-selector.ts +0 -597
- package/packages/gsd-agent-modes/src/modes/interactive/components/countdown-timer.ts +0 -41
- package/packages/gsd-agent-modes/src/modes/interactive/components/custom-editor.ts +0 -88
- package/packages/gsd-agent-modes/src/modes/interactive/components/custom-message.ts +0 -100
- package/packages/gsd-agent-modes/src/modes/interactive/components/daxnuts.ts +0 -165
- package/packages/gsd-agent-modes/src/modes/interactive/components/diff.ts +0 -147
- package/packages/gsd-agent-modes/src/modes/interactive/components/dynamic-border.test.ts +0 -73
- package/packages/gsd-agent-modes/src/modes/interactive/components/dynamic-border.ts +0 -89
- package/packages/gsd-agent-modes/src/modes/interactive/components/extension-editor.ts +0 -151
- package/packages/gsd-agent-modes/src/modes/interactive/components/extension-input.ts +0 -100
- package/packages/gsd-agent-modes/src/modes/interactive/components/extension-selector.ts +0 -156
- package/packages/gsd-agent-modes/src/modes/interactive/components/footer.ts +0 -257
- package/packages/gsd-agent-modes/src/modes/interactive/components/index.ts +0 -35
- package/packages/gsd-agent-modes/src/modes/interactive/components/keybinding-hints.ts +0 -84
- package/packages/gsd-agent-modes/src/modes/interactive/components/login-dialog.ts +0 -257
- package/packages/gsd-agent-modes/src/modes/interactive/components/model-selector.ts +0 -656
- package/packages/gsd-agent-modes/src/modes/interactive/components/oauth-selector.ts +0 -122
- package/packages/gsd-agent-modes/src/modes/interactive/components/provider-manager.ts +0 -210
- package/packages/gsd-agent-modes/src/modes/interactive/components/scoped-models-selector.ts +0 -342
- package/packages/gsd-agent-modes/src/modes/interactive/components/session-selector-search.ts +0 -194
- package/packages/gsd-agent-modes/src/modes/interactive/components/session-selector.ts +0 -1011
- package/packages/gsd-agent-modes/src/modes/interactive/components/settings-selector.ts +0 -452
- package/packages/gsd-agent-modes/src/modes/interactive/components/show-images-selector.ts +0 -45
- package/packages/gsd-agent-modes/src/modes/interactive/components/skill-invocation-message.ts +0 -56
- package/packages/gsd-agent-modes/src/modes/interactive/components/theme-selector.ts +0 -63
- package/packages/gsd-agent-modes/src/modes/interactive/components/thinking-selector.ts +0 -64
- package/packages/gsd-agent-modes/src/modes/interactive/components/timestamp.ts +0 -48
- package/packages/gsd-agent-modes/src/modes/interactive/components/tool-execution.ts +0 -1157
- package/packages/gsd-agent-modes/src/modes/interactive/components/tree-render-utils.ts +0 -81
- package/packages/gsd-agent-modes/src/modes/interactive/components/tree-selector.ts +0 -1208
- package/packages/gsd-agent-modes/src/modes/interactive/components/user-message-selector.ts +0 -145
- package/packages/gsd-agent-modes/src/modes/interactive/components/user-message.ts +0 -44
- package/packages/gsd-agent-modes/src/modes/interactive/components/visual-truncate.ts +0 -50
- package/packages/gsd-agent-modes/src/modes/interactive/controllers/chat-controller-ordering.test.ts +0 -1430
- package/packages/gsd-agent-modes/src/modes/interactive/controllers/chat-controller.test.ts +0 -71
- package/packages/gsd-agent-modes/src/modes/interactive/controllers/chat-controller.ts +0 -957
- package/packages/gsd-agent-modes/src/modes/interactive/controllers/extension-ui-controller.ts +0 -63
- package/packages/gsd-agent-modes/src/modes/interactive/controllers/input-controller.test.ts +0 -183
- package/packages/gsd-agent-modes/src/modes/interactive/controllers/input-controller.ts +0 -140
- package/packages/gsd-agent-modes/src/modes/interactive/controllers/model-controller.ts +0 -77
- package/packages/gsd-agent-modes/src/modes/interactive/interactive-mode-ordering.test.ts +0 -44
- package/packages/gsd-agent-modes/src/modes/interactive/interactive-mode-state.ts +0 -49
- package/packages/gsd-agent-modes/src/modes/interactive/interactive-mode.ts +0 -4195
- package/packages/gsd-agent-modes/src/modes/interactive/slash-command-handlers.ts +0 -670
- package/packages/gsd-agent-modes/src/modes/interactive/utils/shorten-path.ts +0 -14
- package/packages/gsd-agent-modes/src/modes/print-mode.ts +0 -106
- package/packages/gsd-agent-modes/src/modes/rpc/jsonl.ts +0 -58
- package/packages/gsd-agent-modes/src/modes/rpc/remote-terminal.ts +0 -109
- package/packages/gsd-agent-modes/src/modes/rpc/rpc-client.ts +0 -572
- package/packages/gsd-agent-modes/src/modes/rpc/rpc-mode.ts +0 -902
- package/packages/gsd-agent-modes/src/modes/rpc/rpc-protocol-v2.test.ts +0 -971
- package/packages/gsd-agent-modes/src/modes/rpc/rpc-types.ts +0 -335
- package/packages/gsd-agent-modes/src/modes/shared/command-context-actions.ts +0 -53
- package/packages/gsd-agent-modes/src/pi-coding-agent-compat.ts +0 -42
- package/packages/gsd-agent-modes/src/pi-tui-compat.ts +0 -4
- package/packages/gsd-agent-modes/src/theme.ts +0 -25
- package/packages/gsd-agent-modes/src/utils/theme.ts +0 -24
- package/packages/gsd-agent-modes/tsconfig.json +0 -28
- package/packages/gsd-agent-modes/tsconfig.tsbuildinfo +0 -1
- package/packages/gsd-agent-types/dist/index.d.ts +0 -176
- package/packages/gsd-agent-types/dist/index.d.ts.map +0 -1
- package/packages/gsd-agent-types/dist/index.js +0 -24
- package/packages/gsd-agent-types/dist/index.js.map +0 -1
- package/packages/gsd-agent-types/package.json +0 -24
- package/packages/gsd-agent-types/src/index.ts +0 -206
- package/packages/gsd-agent-types/tsconfig.json +0 -25
- package/packages/gsd-agent-types/tsconfig.tsbuildinfo +0 -1
- package/packages/native/dist/tsconfig.tsbuildinfo +0 -1
- package/src/resources/extensions/claude-code-cli/tests/provider-registration.test.ts +0 -27
- /package/dist/web/standalone/.next/static/{gy6_foLMsEzdGBT19c3hr → 5wbu35_C2_MQ3Jj1lEVDx}/_buildManifest.js +0 -0
- /package/dist/web/standalone/.next/static/{gy6_foLMsEzdGBT19c3hr → 5wbu35_C2_MQ3Jj1lEVDx}/_ssgManifest.js +0 -0
|
@@ -1,3358 +0,0 @@
|
|
|
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
|
-
|
|
16
|
-
import { readFileSync } from "node:fs";
|
|
17
|
-
import { createRequire } from "node:module";
|
|
18
|
-
import { basename, dirname, join } from "node:path";
|
|
19
|
-
import type {
|
|
20
|
-
Agent,
|
|
21
|
-
AgentEvent,
|
|
22
|
-
AgentMessage,
|
|
23
|
-
AgentState,
|
|
24
|
-
AgentTool,
|
|
25
|
-
ThinkingLevel,
|
|
26
|
-
} from "@gsd/pi-agent-core";
|
|
27
|
-
import type { Api, AssistantMessage, ImageContent, Message, Model, TextContent } from "@gsd/pi-ai";
|
|
28
|
-
import { modelsAreEqual, resetApiProviders, supportsXhigh } from "@gsd/pi-ai";
|
|
29
|
-
import { Type } from "@sinclair/typebox";
|
|
30
|
-
import {
|
|
31
|
-
getAgentDir,
|
|
32
|
-
stripFrontmatter,
|
|
33
|
-
createReadTool,
|
|
34
|
-
createBashTool,
|
|
35
|
-
createEditTool,
|
|
36
|
-
createWriteTool,
|
|
37
|
-
createGrepTool,
|
|
38
|
-
createFindTool,
|
|
39
|
-
createLsTool,
|
|
40
|
-
createHashlineEditTool,
|
|
41
|
-
createHashlineReadTool,
|
|
42
|
-
type BashToolOptions,
|
|
43
|
-
type ReadToolOptions,
|
|
44
|
-
} from "@gsd/pi-coding-agent";
|
|
45
|
-
|
|
46
|
-
/** Extract a human-readable error message from an unknown thrown value. */
|
|
47
|
-
function getErrorMessage(e: unknown): string {
|
|
48
|
-
return e instanceof Error ? e.message : String(e);
|
|
49
|
-
}
|
|
50
|
-
import { type BashResult, executeBash as executeBashCommand, executeBashWithOperations } from "./bash-executor.js";
|
|
51
|
-
import {
|
|
52
|
-
type CompactionResult,
|
|
53
|
-
calculateContextTokens,
|
|
54
|
-
collectEntriesForBranchSummary,
|
|
55
|
-
estimateContextTokens,
|
|
56
|
-
generateBranchSummary,
|
|
57
|
-
} from "./compaction/index.js";
|
|
58
|
-
import { CompactionOrchestrator } from "./compaction-orchestrator.js";
|
|
59
|
-
import { exportSessionToHtml } from "./export-html/index.js";
|
|
60
|
-
import {
|
|
61
|
-
type ContextUsage,
|
|
62
|
-
type ExtensionCommandContextActions,
|
|
63
|
-
ExtensionRunner,
|
|
64
|
-
type ExtensionUIContext,
|
|
65
|
-
type InputSource,
|
|
66
|
-
type ToolDefinition,
|
|
67
|
-
type ToolInfo,
|
|
68
|
-
type TurnEndEvent,
|
|
69
|
-
type TurnStartEvent,
|
|
70
|
-
wrapRegisteredTools,
|
|
71
|
-
} from "@gsd/pi-coding-agent";
|
|
72
|
-
import type { BashExecutionMessage, CustomMessage } from "@gsd/agent-types";
|
|
73
|
-
import {
|
|
74
|
-
FallbackResolver,
|
|
75
|
-
type SettingsManagerWithFallback,
|
|
76
|
-
type AuthStorageWithFallback,
|
|
77
|
-
type ModelRegistryWithFallback,
|
|
78
|
-
} from "./fallback-resolver.js";
|
|
79
|
-
import type { ModelRegistry } from "@gsd/agent-types";
|
|
80
|
-
import type { PromptTemplate } from "@gsd/agent-types";
|
|
81
|
-
import type { ResourceExtensionPaths, ResourceLoader } from "@gsd/agent-types";
|
|
82
|
-
import type { Skill } from "@gsd/agent-types";
|
|
83
|
-
import { RetryHandler } from "./retry-handler.js";
|
|
84
|
-
import { isImageDimensionError, downsizeConversationImages } from "./image-overflow-recovery.js";
|
|
85
|
-
import type { BranchSummaryEntry, SessionManager } from "@gsd/agent-types";
|
|
86
|
-
import { getLatestCompactionEntry } from "@gsd/pi-coding-agent";
|
|
87
|
-
import type { SettingsManager } from "@gsd/agent-types";
|
|
88
|
-
import type { SlashCommandInfo } from "@gsd/agent-types";
|
|
89
|
-
import { buildSystemPrompt } from "./system-prompt.js";
|
|
90
|
-
import type { BashOperations } from "@gsd/agent-types";
|
|
91
|
-
|
|
92
|
-
const require = createRequire(import.meta.url);
|
|
93
|
-
const DEFAULT_THINKING_LEVEL: ThinkingLevel = "medium";
|
|
94
|
-
|
|
95
|
-
const BUILTIN_SLASH_COMMANDS: ReadonlyArray<{ name: string; description: string }> = [
|
|
96
|
-
{ name: "settings", description: "Open settings menu" },
|
|
97
|
-
{ name: "model", description: "Select model (opens selector UI)" },
|
|
98
|
-
{ name: "scoped-models", description: "Enable/disable models for Ctrl+P cycling" },
|
|
99
|
-
{ name: "export", description: "Export session to HTML file" },
|
|
100
|
-
{ name: "share", description: "Share session as a secret GitHub gist" },
|
|
101
|
-
{ name: "copy", description: "Copy last agent message to clipboard" },
|
|
102
|
-
{ name: "name", description: "Set session display name" },
|
|
103
|
-
{ name: "session", description: "Show session info and stats" },
|
|
104
|
-
{ name: "changelog", description: "Show changelog entries" },
|
|
105
|
-
{ name: "hotkeys", description: "Show all keyboard shortcuts" },
|
|
106
|
-
{ name: "fork", description: "Create a new fork from a previous message" },
|
|
107
|
-
{ name: "tree", description: "Navigate session tree (switch branches)" },
|
|
108
|
-
{ name: "provider", description: "Manage provider configuration" },
|
|
109
|
-
{ name: "login", description: "Login with OAuth provider" },
|
|
110
|
-
{ name: "logout", description: "Logout from OAuth provider" },
|
|
111
|
-
{ name: "new", description: "Start a new session" },
|
|
112
|
-
{ name: "compact", description: "Manually compact the session context" },
|
|
113
|
-
{ name: "resume", description: "Resume a different session" },
|
|
114
|
-
{ name: "reload", description: "Reload extensions, skills, prompts, and themes" },
|
|
115
|
-
{ name: "thinking", description: "Set thinking level (off/minimal/low/medium/high/xhigh)" },
|
|
116
|
-
{ name: "edit-mode", description: "Toggle edit mode (standard/hashline)" },
|
|
117
|
-
{ name: "terminal", description: "Run a shell command directly (e.g. /terminal ping -c3 1.1.1.1)" },
|
|
118
|
-
{ name: "quit", description: "Quit pi" },
|
|
119
|
-
];
|
|
120
|
-
|
|
121
|
-
function getDocsPath(): string {
|
|
122
|
-
const piEntryPath = require.resolve("@gsd/pi-coding-agent");
|
|
123
|
-
return join(dirname(piEntryPath), "..", "docs");
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
function parsePromptArgs(argsString: string): string[] {
|
|
127
|
-
const args: string[] = [];
|
|
128
|
-
let current = "";
|
|
129
|
-
let inQuote: string | null = null;
|
|
130
|
-
|
|
131
|
-
for (let i = 0; i < argsString.length; i++) {
|
|
132
|
-
const char = argsString[i];
|
|
133
|
-
if (inQuote) {
|
|
134
|
-
if (char === inQuote) {
|
|
135
|
-
inQuote = null;
|
|
136
|
-
} else {
|
|
137
|
-
current += char;
|
|
138
|
-
}
|
|
139
|
-
} else if (char === '"' || char === "'") {
|
|
140
|
-
inQuote = char;
|
|
141
|
-
} else if (char === " " || char === "\t") {
|
|
142
|
-
if (current) {
|
|
143
|
-
args.push(current);
|
|
144
|
-
current = "";
|
|
145
|
-
}
|
|
146
|
-
} else {
|
|
147
|
-
current += char;
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
if (current) {
|
|
152
|
-
args.push(current);
|
|
153
|
-
}
|
|
154
|
-
return args;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
function substituteTemplateArgs(content: string, args: string[]): string {
|
|
158
|
-
let result = content;
|
|
159
|
-
result = result.replace(/\$(\d+)/g, (_, num: string) => {
|
|
160
|
-
const index = Number.parseInt(num, 10) - 1;
|
|
161
|
-
return args[index] ?? "";
|
|
162
|
-
});
|
|
163
|
-
result = result.replace(/\$ARGUMENTS/g, args.join(" "));
|
|
164
|
-
result = result.replace(/\$@/g, args.join(" "));
|
|
165
|
-
return result;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
function expandPromptTemplate(text: string, templates: PromptTemplate[]): string {
|
|
169
|
-
if (!text.startsWith("/")) return text;
|
|
170
|
-
const spaceIndex = text.indexOf(" ");
|
|
171
|
-
const templateName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
|
|
172
|
-
const argsString = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
|
|
173
|
-
const template = templates.find((candidate) => candidate.name === templateName);
|
|
174
|
-
if (!template) return text;
|
|
175
|
-
const args = parsePromptArgs(argsString);
|
|
176
|
-
return substituteTemplateArgs(template.content, args);
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
function createAllTools(
|
|
180
|
-
cwd: string,
|
|
181
|
-
options?: { read?: ReadToolOptions; bash?: BashToolOptions },
|
|
182
|
-
): Record<string, AgentTool> {
|
|
183
|
-
return {
|
|
184
|
-
read: createReadTool(cwd, options?.read) as unknown as AgentTool,
|
|
185
|
-
bash: createBashTool(cwd, options?.bash) as unknown as AgentTool,
|
|
186
|
-
edit: createEditTool(cwd) as unknown as AgentTool,
|
|
187
|
-
write: createWriteTool(cwd) as unknown as AgentTool,
|
|
188
|
-
grep: createGrepTool(cwd) as unknown as AgentTool,
|
|
189
|
-
find: createFindTool(cwd) as unknown as AgentTool,
|
|
190
|
-
ls: createLsTool(cwd) as unknown as AgentTool,
|
|
191
|
-
hashline_edit: createHashlineEditTool(cwd) as unknown as AgentTool,
|
|
192
|
-
hashline_read: createHashlineReadTool(cwd, options?.read) as unknown as AgentTool,
|
|
193
|
-
};
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
// ============================================================================
|
|
197
|
-
// Local type shims for types absent from @gsd/pi-coding-agent 0.67.2 public API.
|
|
198
|
-
// Phase 09 moves these to @gsd/agent-types or resolves via upstream PR.
|
|
199
|
-
// ============================================================================
|
|
200
|
-
|
|
201
|
-
/** Handler called when extension requests session shutdown. */
|
|
202
|
-
export type ShutdownHandler = () => void;
|
|
203
|
-
|
|
204
|
-
/** Listener for extension errors. */
|
|
205
|
-
export type ExtensionErrorListener = (error: { extensionPath: string; event: string; error: string }) => void;
|
|
206
|
-
|
|
207
|
-
/** Fired when tool starts executing (not in 0.67.2 public API). */
|
|
208
|
-
export interface ToolExecutionStartEvent {
|
|
209
|
-
type: "tool_execution_start";
|
|
210
|
-
toolCallId: string;
|
|
211
|
-
toolName: string;
|
|
212
|
-
args: unknown;
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
/** Fired during tool execution with partial/streaming output (not in 0.67.2 public API). */
|
|
216
|
-
export interface ToolExecutionUpdateEvent {
|
|
217
|
-
type: "tool_execution_update";
|
|
218
|
-
toolCallId: string;
|
|
219
|
-
toolName: string;
|
|
220
|
-
args: unknown;
|
|
221
|
-
partialResult: unknown;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
/** Fired when a tool finishes executing (not in 0.67.2 public API). */
|
|
225
|
-
export interface ToolExecutionEndEvent {
|
|
226
|
-
type: "tool_execution_end";
|
|
227
|
-
toolCallId: string;
|
|
228
|
-
toolName: string;
|
|
229
|
-
result: unknown;
|
|
230
|
-
isError: boolean;
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
/** Fired when a message starts (user, assistant, toolResult) — not in 0.67.2 public API. */
|
|
234
|
-
interface MessageStartEvent {
|
|
235
|
-
type: "message_start";
|
|
236
|
-
message: AgentMessage;
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
/** Fired during assistant streaming with partial updates — not in 0.67.2 public API. */
|
|
240
|
-
interface MessageUpdateEvent {
|
|
241
|
-
type: "message_update";
|
|
242
|
-
message: AgentMessage;
|
|
243
|
-
assistantMessageEvent: import("@gsd/pi-ai").AssistantMessageEvent;
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
/** Fired when a message ends — not in 0.67.2 public API. */
|
|
247
|
-
interface MessageEndEvent {
|
|
248
|
-
type: "message_end";
|
|
249
|
-
message: AgentMessage;
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
/** Result from session_before_switch extension handler — not in 0.67.2 public API. */
|
|
253
|
-
interface SessionBeforeSwitchResult {
|
|
254
|
-
cancel?: boolean;
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
/** Result from session_before_fork extension handler — not in 0.67.2 public API. */
|
|
258
|
-
interface SessionBeforeForkResult {
|
|
259
|
-
cancel?: boolean;
|
|
260
|
-
skipConversationRestore?: boolean;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
/** Result from session_before_tree extension handler — not in 0.67.2 public API. */
|
|
264
|
-
interface SessionBeforeTreeResult {
|
|
265
|
-
cancel?: boolean;
|
|
266
|
-
summary?: { summary: string; details?: unknown };
|
|
267
|
-
customInstructions?: string;
|
|
268
|
-
replaceInstructions?: boolean;
|
|
269
|
-
label?: string;
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
/** Tree navigation preparation data (not in 0.67.2 public API). */
|
|
273
|
-
export interface TreePreparation {
|
|
274
|
-
targetId: string;
|
|
275
|
-
oldLeafId: string | null;
|
|
276
|
-
commonAncestorId: string | null;
|
|
277
|
-
entriesToSummarize: import("@gsd/pi-coding-agent").SessionEntry[];
|
|
278
|
-
userWantsSummary: boolean;
|
|
279
|
-
customInstructions?: string;
|
|
280
|
-
replaceInstructions?: boolean;
|
|
281
|
-
label?: string;
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
/** Extended SettingsManager with GSD edit mode support (absent from 0.67.2). */
|
|
285
|
-
interface SettingsManagerWithEditMode extends SettingsManager {
|
|
286
|
-
setEditMode(mode: "standard" | "hashline"): void;
|
|
287
|
-
getEditMode(): "standard" | "hashline";
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
/** Extended ModelRegistry with GSD provider readiness and API key access. */
|
|
291
|
-
interface ModelRegistryWithReadiness extends ModelRegistry {
|
|
292
|
-
isProviderRequestReady(provider: string): boolean;
|
|
293
|
-
getApiKeyAndHeaders(model: import("@gsd/pi-ai").Model<import("@gsd/pi-ai").Api>): Promise<{
|
|
294
|
-
ok: true;
|
|
295
|
-
apiKey?: string;
|
|
296
|
-
headers?: Record<string, string>;
|
|
297
|
-
} | { ok: false; error: string }>;
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
interface SessionStartEventCompat {
|
|
301
|
-
type: "session_start";
|
|
302
|
-
reason?: "new" | "resume" | "fork";
|
|
303
|
-
previousSessionFile?: string;
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
interface CreateRuntimeOptionsCompat {
|
|
307
|
-
cwd: string;
|
|
308
|
-
agentDir: string;
|
|
309
|
-
sessionManager: SessionManager;
|
|
310
|
-
sessionStartEvent?: SessionStartEventCompat;
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
interface AgentSessionServices {
|
|
314
|
-
cwd: string;
|
|
315
|
-
agentDir: string;
|
|
316
|
-
authStorage: unknown;
|
|
317
|
-
settingsManager: SettingsManager;
|
|
318
|
-
modelRegistry: ModelRegistry;
|
|
319
|
-
resourceLoader: ResourceLoader;
|
|
320
|
-
diagnostics: unknown[];
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
interface CreateAgentSessionRuntimeResult {
|
|
324
|
-
session: import("@gsd/pi-coding-agent").AgentSession;
|
|
325
|
-
services: AgentSessionServices;
|
|
326
|
-
diagnostics: unknown[];
|
|
327
|
-
extensionsResult: ReturnType<ResourceLoader["getExtensions"]>;
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
type CreateAgentSessionRuntimeFactory = (
|
|
331
|
-
options: CreateRuntimeOptionsCompat,
|
|
332
|
-
) => Promise<CreateAgentSessionRuntimeResult>;
|
|
333
|
-
|
|
334
|
-
interface AgentSessionRuntime {
|
|
335
|
-
createRuntime: CreateAgentSessionRuntimeFactory;
|
|
336
|
-
newSession(options?: {
|
|
337
|
-
parentSession?: string;
|
|
338
|
-
setup?: (sessionManager: SessionManager) => Promise<void>;
|
|
339
|
-
}): Promise<{ cancelled: boolean }>;
|
|
340
|
-
switchSession(sessionPath: string): Promise<{ cancelled: boolean }>;
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
async function createAgentSessionRuntime(
|
|
344
|
-
factory: CreateAgentSessionRuntimeFactory,
|
|
345
|
-
initial: CreateRuntimeOptionsCompat,
|
|
346
|
-
): Promise<AgentSessionRuntime> {
|
|
347
|
-
const runtime: AgentSessionRuntime = {
|
|
348
|
-
createRuntime: factory,
|
|
349
|
-
async newSession(options) {
|
|
350
|
-
if (options?.setup) {
|
|
351
|
-
await options.setup(initial.sessionManager);
|
|
352
|
-
}
|
|
353
|
-
await runtime.createRuntime({
|
|
354
|
-
...initial,
|
|
355
|
-
sessionStartEvent: { type: "session_start", reason: "new" },
|
|
356
|
-
});
|
|
357
|
-
return { cancelled: false };
|
|
358
|
-
},
|
|
359
|
-
async switchSession(sessionPath) {
|
|
360
|
-
const previousSessionFile = initial.sessionManager.getSessionFile();
|
|
361
|
-
initial.sessionManager.setSessionFile(sessionPath);
|
|
362
|
-
await runtime.createRuntime({
|
|
363
|
-
...initial,
|
|
364
|
-
sessionStartEvent: {
|
|
365
|
-
type: "session_start",
|
|
366
|
-
reason: "resume",
|
|
367
|
-
previousSessionFile,
|
|
368
|
-
},
|
|
369
|
-
});
|
|
370
|
-
return { cancelled: false };
|
|
371
|
-
},
|
|
372
|
-
};
|
|
373
|
-
|
|
374
|
-
await runtime.createRuntime(initial);
|
|
375
|
-
return runtime;
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
// ============================================================================
|
|
379
|
-
// Skill Block Parsing
|
|
380
|
-
// ============================================================================
|
|
381
|
-
|
|
382
|
-
/** Parsed skill block from a user message */
|
|
383
|
-
export interface ParsedSkillBlock {
|
|
384
|
-
name: string;
|
|
385
|
-
location: string;
|
|
386
|
-
content: string;
|
|
387
|
-
userMessage: string | undefined;
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
/**
|
|
391
|
-
* Parse a skill block from message text.
|
|
392
|
-
* Returns null if the text doesn't contain a skill block.
|
|
393
|
-
*/
|
|
394
|
-
export function parseSkillBlock(text: string): ParsedSkillBlock | null {
|
|
395
|
-
const match = text.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);
|
|
396
|
-
if (!match) return null;
|
|
397
|
-
return {
|
|
398
|
-
name: match[1],
|
|
399
|
-
location: match[2],
|
|
400
|
-
content: match[3],
|
|
401
|
-
userMessage: match[4]?.trim() || undefined,
|
|
402
|
-
};
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
/** Session-specific events that extend the core AgentEvent */
|
|
406
|
-
export type SessionStateChangeReason =
|
|
407
|
-
| "set_model"
|
|
408
|
-
| "set_thinking_level"
|
|
409
|
-
| "set_steering_mode"
|
|
410
|
-
| "set_follow_up_mode"
|
|
411
|
-
| "set_auto_compaction"
|
|
412
|
-
| "set_auto_retry"
|
|
413
|
-
| "abort_retry"
|
|
414
|
-
| "new_session"
|
|
415
|
-
| "switch_session"
|
|
416
|
-
| "set_session_name"
|
|
417
|
-
| "fork";
|
|
418
|
-
|
|
419
|
-
export type AgentSessionEvent =
|
|
420
|
-
| AgentEvent
|
|
421
|
-
| { type: "session_state_changed"; reason: SessionStateChangeReason }
|
|
422
|
-
| { type: "auto_compaction_start"; reason: "threshold" | "overflow" }
|
|
423
|
-
| {
|
|
424
|
-
type: "auto_compaction_end";
|
|
425
|
-
result: CompactionResult | undefined;
|
|
426
|
-
aborted: boolean;
|
|
427
|
-
willRetry: boolean;
|
|
428
|
-
errorMessage?: string;
|
|
429
|
-
}
|
|
430
|
-
| { type: "auto_retry_start"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }
|
|
431
|
-
| { type: "auto_retry_end"; success: boolean; attempt: number; finalError?: string }
|
|
432
|
-
| { type: "fallback_provider_switch"; from: string; to: string; reason: string }
|
|
433
|
-
| { type: "fallback_provider_restored"; provider: string; reason: string }
|
|
434
|
-
| { type: "fallback_chain_exhausted"; reason: string }
|
|
435
|
-
| { type: "image_overflow_recovery"; strippedCount: number; imageCount: number };
|
|
436
|
-
|
|
437
|
-
/** Listener function for agent session events */
|
|
438
|
-
export type AgentSessionEventListener = (event: AgentSessionEvent) => void;
|
|
439
|
-
|
|
440
|
-
// ============================================================================
|
|
441
|
-
// Types
|
|
442
|
-
// ============================================================================
|
|
443
|
-
|
|
444
|
-
export interface AgentSessionConfig {
|
|
445
|
-
agent: Agent;
|
|
446
|
-
sessionManager: SessionManager;
|
|
447
|
-
settingsManager: SettingsManager;
|
|
448
|
-
cwd: string;
|
|
449
|
-
/** Models to cycle through with Ctrl+P (from --models flag) */
|
|
450
|
-
scopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;
|
|
451
|
-
/** Resource loader for skills, prompts, themes, context files, system prompt */
|
|
452
|
-
resourceLoader: ResourceLoader;
|
|
453
|
-
/** SDK custom tools registered outside extensions */
|
|
454
|
-
customTools?: ToolDefinition[];
|
|
455
|
-
/** Model registry for API key resolution and model discovery */
|
|
456
|
-
modelRegistry: ModelRegistry;
|
|
457
|
-
/** Initial active built-in tool names. Default: [read, bash, edit, write] */
|
|
458
|
-
initialActiveToolNames?: string[];
|
|
459
|
-
/** Override base tools (useful for custom runtimes). */
|
|
460
|
-
baseToolsOverride?: Record<string, AgentTool>;
|
|
461
|
-
/** Mutable ref used by Agent to access the current ExtensionRunner */
|
|
462
|
-
extensionRunnerRef?: { current?: ExtensionRunner };
|
|
463
|
-
/** Optional: check if the claude-code CLI provider is ready (installed + authed).
|
|
464
|
-
* Passed through to RetryHandler for third-party block recovery (#3772). */
|
|
465
|
-
isClaudeCodeReady?: () => boolean;
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
export interface ExtensionBindings {
|
|
469
|
-
uiContext?: ExtensionUIContext;
|
|
470
|
-
commandContextActions?: ExtensionCommandContextActions;
|
|
471
|
-
shutdownHandler?: ShutdownHandler;
|
|
472
|
-
onError?: ExtensionErrorListener;
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
/** Options for AgentSession.prompt() */
|
|
476
|
-
export interface PromptOptions {
|
|
477
|
-
/** Whether to expand file-based prompt templates (default: true) */
|
|
478
|
-
expandPromptTemplates?: boolean;
|
|
479
|
-
/** Image attachments */
|
|
480
|
-
images?: ImageContent[];
|
|
481
|
-
/** When streaming, how to queue the message: "steer" (interrupt) or "followUp" (wait). Required if streaming. */
|
|
482
|
-
streamingBehavior?: "steer" | "followUp";
|
|
483
|
-
/** Source of input for extension input event handlers. Defaults to "interactive". */
|
|
484
|
-
source?: InputSource;
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
/** Result from cycleModel() */
|
|
488
|
-
export interface ModelCycleResult {
|
|
489
|
-
model: Model<Api>;
|
|
490
|
-
thinkingLevel: ThinkingLevel;
|
|
491
|
-
/** Whether cycling through scoped models (--models flag) or all available */
|
|
492
|
-
isScoped: boolean;
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
/** Session statistics for /session command */
|
|
496
|
-
export interface SessionStats {
|
|
497
|
-
sessionFile: string | undefined;
|
|
498
|
-
sessionId: string;
|
|
499
|
-
userMessages: number;
|
|
500
|
-
assistantMessages: number;
|
|
501
|
-
toolCalls: number;
|
|
502
|
-
toolResults: number;
|
|
503
|
-
totalMessages: number;
|
|
504
|
-
tokens: {
|
|
505
|
-
input: number;
|
|
506
|
-
output: number;
|
|
507
|
-
cacheRead: number;
|
|
508
|
-
cacheWrite: number;
|
|
509
|
-
total: number;
|
|
510
|
-
};
|
|
511
|
-
cost: number;
|
|
512
|
-
}
|
|
513
|
-
|
|
514
|
-
// ============================================================================
|
|
515
|
-
// Constants
|
|
516
|
-
// ============================================================================
|
|
517
|
-
|
|
518
|
-
/** Standard thinking levels */
|
|
519
|
-
const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high"];
|
|
520
|
-
|
|
521
|
-
/** Thinking levels including xhigh (for supported models) */
|
|
522
|
-
const THINKING_LEVELS_WITH_XHIGH: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh"];
|
|
523
|
-
|
|
524
|
-
// ============================================================================
|
|
525
|
-
// AgentSession Class
|
|
526
|
-
// ============================================================================
|
|
527
|
-
|
|
528
|
-
export class AgentSession {
|
|
529
|
-
readonly agent: Agent;
|
|
530
|
-
readonly sessionManager: SessionManager;
|
|
531
|
-
readonly settingsManager: SettingsManager;
|
|
532
|
-
|
|
533
|
-
private _scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;
|
|
534
|
-
|
|
535
|
-
// Event subscription state
|
|
536
|
-
private _unsubscribeAgent?: () => void;
|
|
537
|
-
private _eventListeners: AgentSessionEventListener[] = [];
|
|
538
|
-
private _agentEventQueue: Promise<void> = Promise.resolve();
|
|
539
|
-
|
|
540
|
-
/** Tracks pending steering messages for UI display. Removed when delivered. */
|
|
541
|
-
private _steeringMessages: string[] = [];
|
|
542
|
-
/** Tracks pending follow-up messages for UI display. Removed when delivered. */
|
|
543
|
-
private _followUpMessages: string[] = [];
|
|
544
|
-
/** Messages queued to be included with the next user prompt as context ("asides"). */
|
|
545
|
-
private _pendingNextTurnMessages: CustomMessage[] = [];
|
|
546
|
-
|
|
547
|
-
// Delegated subsystems
|
|
548
|
-
private _retryHandler: RetryHandler;
|
|
549
|
-
private _compactionOrchestrator: CompactionOrchestrator;
|
|
550
|
-
|
|
551
|
-
// Cumulative session stats — survives compaction (#1423)
|
|
552
|
-
private _cumulativeCost = 0;
|
|
553
|
-
private _cumulativeInputTokens = 0;
|
|
554
|
-
private _cumulativeOutputTokens = 0;
|
|
555
|
-
private _cumulativeToolCalls = 0;
|
|
556
|
-
|
|
557
|
-
/** Cost of the most recent assistant response (for per-prompt display). */
|
|
558
|
-
private _lastTurnCost = 0;
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
// Bash execution state
|
|
562
|
-
private _bashAbortController: AbortController | undefined = undefined;
|
|
563
|
-
private _pendingBashMessages: BashExecutionMessage[] = [];
|
|
564
|
-
|
|
565
|
-
// Extension system
|
|
566
|
-
private _extensionRunner: ExtensionRunner | undefined = undefined;
|
|
567
|
-
private _turnIndex = 0;
|
|
568
|
-
|
|
569
|
-
private _resourceLoader: ResourceLoader;
|
|
570
|
-
private _customTools: ToolDefinition[];
|
|
571
|
-
private _baseToolRegistry: Map<string, AgentTool> = new Map();
|
|
572
|
-
private _cwd: string;
|
|
573
|
-
private _extensionRunnerRef?: { current?: ExtensionRunner };
|
|
574
|
-
private _initialActiveToolNames?: string[];
|
|
575
|
-
private _baseToolsOverride?: Record<string, AgentTool>;
|
|
576
|
-
private _extensionUIContext?: ExtensionUIContext;
|
|
577
|
-
private _extensionCommandContextActions?: ExtensionCommandContextActions;
|
|
578
|
-
private _extensionShutdownHandler?: ShutdownHandler;
|
|
579
|
-
private _extensionErrorListener?: ExtensionErrorListener;
|
|
580
|
-
private _extensionErrorUnsubscriber?: () => void;
|
|
581
|
-
|
|
582
|
-
// Model registry for API key resolution
|
|
583
|
-
private _modelRegistry: ModelRegistryWithReadiness;
|
|
584
|
-
|
|
585
|
-
// Provider fallback resolver
|
|
586
|
-
private _fallbackResolver: FallbackResolver;
|
|
587
|
-
|
|
588
|
-
// AgentSessionRuntime for coordinating session lifecycle transitions (D-12)
|
|
589
|
-
private _runtime: AgentSessionRuntime | undefined;
|
|
590
|
-
|
|
591
|
-
// Tool registry for extension getTools/setTools
|
|
592
|
-
private _toolRegistry: Map<string, AgentTool> = new Map();
|
|
593
|
-
private _toolPromptSnippets: Map<string, string> = new Map();
|
|
594
|
-
private _toolPromptGuidelines: Map<string, string[]> = new Map();
|
|
595
|
-
|
|
596
|
-
// Base system prompt (without extension appends) - used to apply fresh appends each turn
|
|
597
|
-
private _baseSystemPrompt = "";
|
|
598
|
-
|
|
599
|
-
constructor(config: AgentSessionConfig) {
|
|
600
|
-
this.agent = config.agent;
|
|
601
|
-
this.sessionManager = config.sessionManager;
|
|
602
|
-
this.settingsManager = config.settingsManager;
|
|
603
|
-
this._scopedModels = config.scopedModels ?? [];
|
|
604
|
-
this._resourceLoader = config.resourceLoader;
|
|
605
|
-
this._customTools = config.customTools ?? [];
|
|
606
|
-
this._cwd = config.cwd;
|
|
607
|
-
this._modelRegistry = config.modelRegistry as ModelRegistryWithReadiness;
|
|
608
|
-
this._fallbackResolver = new FallbackResolver(
|
|
609
|
-
this.settingsManager as SettingsManagerWithFallback,
|
|
610
|
-
this._modelRegistry.authStorage as AuthStorageWithFallback,
|
|
611
|
-
this._modelRegistry as ModelRegistryWithFallback,
|
|
612
|
-
);
|
|
613
|
-
this._extensionRunnerRef = config.extensionRunnerRef;
|
|
614
|
-
this._initialActiveToolNames = config.initialActiveToolNames;
|
|
615
|
-
this._baseToolsOverride = config.baseToolsOverride;
|
|
616
|
-
|
|
617
|
-
// Initialize delegated subsystems
|
|
618
|
-
this._retryHandler = new RetryHandler({
|
|
619
|
-
agent: this.agent,
|
|
620
|
-
settingsManager: this.settingsManager,
|
|
621
|
-
modelRegistry: this._modelRegistry,
|
|
622
|
-
fallbackResolver: this._fallbackResolver,
|
|
623
|
-
getModel: () => this.model,
|
|
624
|
-
getSessionId: () => this.sessionId,
|
|
625
|
-
emit: (event) => this._emit(event),
|
|
626
|
-
onModelChange: (model) => this.sessionManager.appendModelChange(model.provider, model.id),
|
|
627
|
-
isClaudeCodeReady: config.isClaudeCodeReady,
|
|
628
|
-
});
|
|
629
|
-
|
|
630
|
-
this._compactionOrchestrator = new CompactionOrchestrator({
|
|
631
|
-
agent: this.agent,
|
|
632
|
-
sessionManager: this.sessionManager,
|
|
633
|
-
settingsManager: this.settingsManager,
|
|
634
|
-
modelRegistry: this._modelRegistry,
|
|
635
|
-
getModel: () => this.model,
|
|
636
|
-
getSessionId: () => this.sessionId,
|
|
637
|
-
getExtensionRunner: () => this._extensionRunner,
|
|
638
|
-
emit: (event) => this._emit(event),
|
|
639
|
-
disconnectFromAgent: () => this._disconnectFromAgent(),
|
|
640
|
-
reconnectToAgent: () => this._reconnectToAgent(),
|
|
641
|
-
abort: () => this.abort(),
|
|
642
|
-
});
|
|
643
|
-
|
|
644
|
-
// Always subscribe to agent events for internal handling
|
|
645
|
-
// (session persistence, extensions, auto-compaction, retry logic)
|
|
646
|
-
this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
|
|
647
|
-
|
|
648
|
-
// Install tool hooks that await the event queue before emitting extension events.
|
|
649
|
-
// This ensures extensions always see settled state (e.g., assistant message appended)
|
|
650
|
-
// even when tools execute in parallel.
|
|
651
|
-
this._installAgentToolHooks();
|
|
652
|
-
|
|
653
|
-
this._buildRuntime({
|
|
654
|
-
activeToolNames: this._initialActiveToolNames,
|
|
655
|
-
includeAllExtensionTools: true,
|
|
656
|
-
});
|
|
657
|
-
}
|
|
658
|
-
|
|
659
|
-
/** Model registry for API key resolution and model discovery */
|
|
660
|
-
get modelRegistry(): ModelRegistry {
|
|
661
|
-
return this._modelRegistry;
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
/** Fallback resolver for cross-provider fallback */
|
|
665
|
-
get fallbackResolver(): FallbackResolver {
|
|
666
|
-
return this._fallbackResolver;
|
|
667
|
-
}
|
|
668
|
-
|
|
669
|
-
// =========================================================================
|
|
670
|
-
// Event Subscription
|
|
671
|
-
// =========================================================================
|
|
672
|
-
|
|
673
|
-
/** Emit an event to all listeners */
|
|
674
|
-
private _emit(event: AgentSessionEvent): void {
|
|
675
|
-
for (const l of this._eventListeners) {
|
|
676
|
-
l(event);
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
private _emitSessionStateChanged(reason: SessionStateChangeReason): void {
|
|
681
|
-
this._emit({ type: "session_state_changed", reason });
|
|
682
|
-
}
|
|
683
|
-
|
|
684
|
-
// Track last assistant message for auto-compaction check
|
|
685
|
-
private _lastAssistantMessage: AssistantMessage | undefined = undefined;
|
|
686
|
-
|
|
687
|
-
/** Internal handler for agent events - shared by subscribe and reconnect */
|
|
688
|
-
private _handleAgentEvent = (event: AgentEvent): void => {
|
|
689
|
-
// Create retry promise synchronously before queueing async processing.
|
|
690
|
-
// Agent.emit() calls this handler synchronously, and prompt() calls waitForRetry()
|
|
691
|
-
// as soon as agent.prompt() resolves. If the retry promise is created only inside
|
|
692
|
-
// _processAgentEvent, slow earlier queued events can delay agent_end processing
|
|
693
|
-
// and waitForRetry() can miss the in-flight retry.
|
|
694
|
-
this._createRetryPromiseForAgentEnd(event);
|
|
695
|
-
|
|
696
|
-
this._agentEventQueue = this._agentEventQueue.then(
|
|
697
|
-
() => this._processAgentEvent(event),
|
|
698
|
-
() => this._processAgentEvent(event),
|
|
699
|
-
);
|
|
700
|
-
|
|
701
|
-
// Keep queue alive if an event handler fails
|
|
702
|
-
this._agentEventQueue.catch(() => {});
|
|
703
|
-
};
|
|
704
|
-
|
|
705
|
-
private _createRetryPromiseForAgentEnd(event: AgentEvent): void {
|
|
706
|
-
if (event.type !== "agent_end") return;
|
|
707
|
-
// AgentMessage[] satisfies the { role: string; [key: string]: unknown }[] shape at runtime.
|
|
708
|
-
this._retryHandler.createRetryPromiseForAgentEnd(event.messages as unknown as ReadonlyArray<{ role: string; [key: string]: unknown }>);
|
|
709
|
-
}
|
|
710
|
-
|
|
711
|
-
private async _processAgentEvent(event: AgentEvent): Promise<void> {
|
|
712
|
-
// When a user message starts, check if it's from either queue and remove it BEFORE emitting
|
|
713
|
-
// This ensures the UI sees the updated queue state
|
|
714
|
-
if (event.type === "message_start" && event.message.role === "user") {
|
|
715
|
-
this._compactionOrchestrator.resetOverflowRecovery();
|
|
716
|
-
const messageText = this._getUserMessageText(event.message);
|
|
717
|
-
if (messageText) {
|
|
718
|
-
// Check steering queue first
|
|
719
|
-
const steeringIndex = this._steeringMessages.indexOf(messageText);
|
|
720
|
-
if (steeringIndex !== -1) {
|
|
721
|
-
this._steeringMessages.splice(steeringIndex, 1);
|
|
722
|
-
} else {
|
|
723
|
-
// Check follow-up queue
|
|
724
|
-
const followUpIndex = this._followUpMessages.indexOf(messageText);
|
|
725
|
-
if (followUpIndex !== -1) {
|
|
726
|
-
this._followUpMessages.splice(followUpIndex, 1);
|
|
727
|
-
}
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
// Emit to extensions first
|
|
733
|
-
await this._emitExtensionEvent(event);
|
|
734
|
-
|
|
735
|
-
// Notify all listeners
|
|
736
|
-
this._emit(event);
|
|
737
|
-
|
|
738
|
-
// Handle session persistence
|
|
739
|
-
if (event.type === "message_end") {
|
|
740
|
-
// Check if this is a custom message from extensions
|
|
741
|
-
if (event.message.role === "custom") {
|
|
742
|
-
// Persist as CustomMessageEntry
|
|
743
|
-
this.sessionManager.appendCustomMessageEntry(
|
|
744
|
-
event.message.customType,
|
|
745
|
-
event.message.content,
|
|
746
|
-
event.message.display,
|
|
747
|
-
event.message.details,
|
|
748
|
-
);
|
|
749
|
-
} else if (
|
|
750
|
-
event.message.role === "user" ||
|
|
751
|
-
event.message.role === "assistant" ||
|
|
752
|
-
event.message.role === "toolResult"
|
|
753
|
-
) {
|
|
754
|
-
// Regular LLM message - persist as SessionMessageEntry
|
|
755
|
-
this.sessionManager.appendMessage(event.message);
|
|
756
|
-
}
|
|
757
|
-
// Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
|
|
758
|
-
|
|
759
|
-
// Track assistant message for auto-compaction (checked on agent_end)
|
|
760
|
-
if (event.message.role === "assistant") {
|
|
761
|
-
this._lastAssistantMessage = event.message;
|
|
762
|
-
|
|
763
|
-
// Accumulate session stats that survive compaction (#1423)
|
|
764
|
-
const assistantMsg = event.message as AssistantMessage;
|
|
765
|
-
this._lastTurnCost = assistantMsg.usage?.cost?.total ?? 0;
|
|
766
|
-
this._cumulativeCost += assistantMsg.usage?.cost?.total ?? 0;
|
|
767
|
-
this._cumulativeInputTokens += assistantMsg.usage?.input ?? 0;
|
|
768
|
-
this._cumulativeOutputTokens += assistantMsg.usage?.output ?? 0;
|
|
769
|
-
this._cumulativeToolCalls += assistantMsg.content.filter((c) => c.type === "toolCall").length;
|
|
770
|
-
|
|
771
|
-
if (assistantMsg.stopReason !== "error") {
|
|
772
|
-
this._compactionOrchestrator.clearOverflowRecovery();
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
// Reset retry counter immediately on successful assistant response
|
|
776
|
-
// This prevents accumulation across multiple LLM calls within a turn
|
|
777
|
-
if (assistantMsg.stopReason !== "error") {
|
|
778
|
-
this._retryHandler.handleSuccessfulResponse();
|
|
779
|
-
}
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
|
|
783
|
-
// Check auto-retry and auto-compaction after agent completes
|
|
784
|
-
if (event.type === "agent_end" && this._lastAssistantMessage) {
|
|
785
|
-
const msg = this._lastAssistantMessage;
|
|
786
|
-
this._lastAssistantMessage = undefined;
|
|
787
|
-
|
|
788
|
-
// Check for retryable errors first (overloaded, rate limit, server errors)
|
|
789
|
-
if (this._retryHandler.isRetryableError(msg)) {
|
|
790
|
-
const didRetry = await this._retryHandler.handleRetryableError(msg);
|
|
791
|
-
if (didRetry) return; // Retry was initiated, don't proceed to compaction
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
// Check for image dimension overflow (many-image 400 error).
|
|
795
|
-
// When a session accumulates many images, the API rejects requests
|
|
796
|
-
// whose images exceed the many-image dimension limit. Strip older
|
|
797
|
-
// images from the conversation and auto-retry. (#2874)
|
|
798
|
-
if (
|
|
799
|
-
msg.stopReason === "error" &&
|
|
800
|
-
isImageDimensionError(msg.errorMessage)
|
|
801
|
-
) {
|
|
802
|
-
const messages = this.agent.state.messages;
|
|
803
|
-
const result = downsizeConversationImages(messages as Message[]);
|
|
804
|
-
if (result.processed) {
|
|
805
|
-
// Remove the trailing error assistant message, then replace
|
|
806
|
-
if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
|
|
807
|
-
this.agent.state.messages = messages.slice(0, -1);
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
this._emit({
|
|
811
|
-
type: "image_overflow_recovery",
|
|
812
|
-
strippedCount: result.strippedCount,
|
|
813
|
-
imageCount: result.imageCount,
|
|
814
|
-
});
|
|
815
|
-
|
|
816
|
-
// Auto-retry after downsizing
|
|
817
|
-
setTimeout(() => {
|
|
818
|
-
this.agent.continue().catch(() => {});
|
|
819
|
-
}, 0);
|
|
820
|
-
return;
|
|
821
|
-
}
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
await this._compactionOrchestrator.checkCompaction(msg);
|
|
825
|
-
}
|
|
826
|
-
}
|
|
827
|
-
|
|
828
|
-
/**
|
|
829
|
-
* Install beforeToolCall/afterToolCall hooks on the Agent.
|
|
830
|
-
*
|
|
831
|
-
* These hooks await `_agentEventQueue` before emitting extension events,
|
|
832
|
-
* ensuring that all prior events (including `message_end` which appends
|
|
833
|
-
* the assistant message) have fully settled. This prevents a race condition
|
|
834
|
-
* in parallel tool execution where extension `tool_call` handlers could
|
|
835
|
-
* see stale agent state.
|
|
836
|
-
*/
|
|
837
|
-
private _installAgentToolHooks(): void {
|
|
838
|
-
this.agent.setBeforeToolCall(
|
|
839
|
-
async ({ toolCall, args }: { toolCall: { name: string; id: string }; args: unknown }) => {
|
|
840
|
-
// Wait for all queued agent events to settle before emitting to extensions
|
|
841
|
-
await this._agentEventQueue;
|
|
842
|
-
|
|
843
|
-
if (!this._extensionRunner?.hasHandlers("tool_call")) return undefined;
|
|
844
|
-
|
|
845
|
-
try {
|
|
846
|
-
const callResult = await this._extensionRunner.emitToolCall({
|
|
847
|
-
type: "tool_call",
|
|
848
|
-
toolName: toolCall.name,
|
|
849
|
-
toolCallId: toolCall.id,
|
|
850
|
-
input: args as Record<string, unknown>,
|
|
851
|
-
});
|
|
852
|
-
|
|
853
|
-
if (callResult?.block) {
|
|
854
|
-
return {
|
|
855
|
-
block: true,
|
|
856
|
-
reason: callResult.reason || "Tool execution was blocked by an extension",
|
|
857
|
-
};
|
|
858
|
-
}
|
|
859
|
-
} catch (err) {
|
|
860
|
-
return { block: true, reason: err instanceof Error ? err.message : `Extension failed, blocking execution: ${String(err)}` };
|
|
861
|
-
}
|
|
862
|
-
|
|
863
|
-
return undefined;
|
|
864
|
-
},
|
|
865
|
-
);
|
|
866
|
-
|
|
867
|
-
this.agent.setAfterToolCall(
|
|
868
|
-
async ({ toolCall, args, result, isError }: { toolCall: { name: string; id: string }; args: unknown; result: { content: unknown; details?: unknown }; isError: boolean }) => {
|
|
869
|
-
// Wait for all queued agent events to settle
|
|
870
|
-
await this._agentEventQueue;
|
|
871
|
-
|
|
872
|
-
if (!this._extensionRunner?.hasHandlers("tool_result")) return undefined;
|
|
873
|
-
|
|
874
|
-
const resultResult = await this._extensionRunner.emitToolResult({
|
|
875
|
-
type: "tool_result",
|
|
876
|
-
toolName: toolCall.name,
|
|
877
|
-
toolCallId: toolCall.id,
|
|
878
|
-
input: args as Record<string, unknown>,
|
|
879
|
-
content: result.content as (import("@gsd/pi-ai").ImageContent | import("@gsd/pi-ai").TextContent)[],
|
|
880
|
-
details: result.details,
|
|
881
|
-
isError,
|
|
882
|
-
});
|
|
883
|
-
|
|
884
|
-
if (resultResult) {
|
|
885
|
-
return {
|
|
886
|
-
content: resultResult.content ?? undefined,
|
|
887
|
-
details: resultResult.details ?? undefined,
|
|
888
|
-
};
|
|
889
|
-
}
|
|
890
|
-
|
|
891
|
-
return undefined;
|
|
892
|
-
},
|
|
893
|
-
);
|
|
894
|
-
}
|
|
895
|
-
|
|
896
|
-
/** Extract text content from a message */
|
|
897
|
-
private _getUserMessageText(message: Message): string {
|
|
898
|
-
if (message.role !== "user") return "";
|
|
899
|
-
const content = message.content;
|
|
900
|
-
if (typeof content === "string") return content;
|
|
901
|
-
const textBlocks = content.filter((c) => c.type === "text");
|
|
902
|
-
return textBlocks.map((c) => (c as TextContent).text).join("");
|
|
903
|
-
}
|
|
904
|
-
|
|
905
|
-
/** Find the last assistant message in agent state (including aborted ones) */
|
|
906
|
-
private _findLastAssistantMessage(): AssistantMessage | undefined {
|
|
907
|
-
const messages = this.agent.state.messages;
|
|
908
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
909
|
-
const msg = messages[i];
|
|
910
|
-
if (msg.role === "assistant") {
|
|
911
|
-
return msg as AssistantMessage;
|
|
912
|
-
}
|
|
913
|
-
}
|
|
914
|
-
return undefined;
|
|
915
|
-
}
|
|
916
|
-
|
|
917
|
-
/** Emit extension events based on agent events */
|
|
918
|
-
private async _emitExtensionEvent(event: AgentEvent): Promise<void> {
|
|
919
|
-
if (!this._extensionRunner) return;
|
|
920
|
-
|
|
921
|
-
if (event.type === "agent_start") {
|
|
922
|
-
this._turnIndex = 0;
|
|
923
|
-
await this._extensionRunner.emit({ type: "agent_start" });
|
|
924
|
-
} else if (event.type === "agent_end") {
|
|
925
|
-
await this._extensionRunner.emit({ type: "agent_end", messages: event.messages });
|
|
926
|
-
} else if (event.type === "turn_start") {
|
|
927
|
-
const extensionEvent: TurnStartEvent = {
|
|
928
|
-
type: "turn_start",
|
|
929
|
-
turnIndex: this._turnIndex,
|
|
930
|
-
timestamp: Date.now(),
|
|
931
|
-
};
|
|
932
|
-
await this._extensionRunner.emit(extensionEvent);
|
|
933
|
-
} else if (event.type === "turn_end") {
|
|
934
|
-
const extensionEvent: TurnEndEvent = {
|
|
935
|
-
type: "turn_end",
|
|
936
|
-
turnIndex: this._turnIndex,
|
|
937
|
-
message: event.message,
|
|
938
|
-
toolResults: event.toolResults,
|
|
939
|
-
};
|
|
940
|
-
await this._extensionRunner.emit(extensionEvent);
|
|
941
|
-
this._turnIndex++;
|
|
942
|
-
} else if (event.type === "message_start") {
|
|
943
|
-
const extensionEvent: MessageStartEvent = {
|
|
944
|
-
type: "message_start",
|
|
945
|
-
message: event.message,
|
|
946
|
-
};
|
|
947
|
-
await this._extensionRunner.emit(extensionEvent);
|
|
948
|
-
} else if (event.type === "message_update") {
|
|
949
|
-
const extensionEvent: MessageUpdateEvent = {
|
|
950
|
-
type: "message_update",
|
|
951
|
-
message: event.message,
|
|
952
|
-
assistantMessageEvent: event.assistantMessageEvent,
|
|
953
|
-
};
|
|
954
|
-
await this._extensionRunner.emit(extensionEvent);
|
|
955
|
-
} else if (event.type === "message_end") {
|
|
956
|
-
const extensionEvent: MessageEndEvent = {
|
|
957
|
-
type: "message_end",
|
|
958
|
-
message: event.message,
|
|
959
|
-
};
|
|
960
|
-
await this._extensionRunner.emit(extensionEvent);
|
|
961
|
-
} else if (event.type === "tool_execution_start") {
|
|
962
|
-
const extensionEvent: ToolExecutionStartEvent = {
|
|
963
|
-
type: "tool_execution_start",
|
|
964
|
-
toolCallId: event.toolCallId,
|
|
965
|
-
toolName: event.toolName,
|
|
966
|
-
args: event.args,
|
|
967
|
-
};
|
|
968
|
-
await this._extensionRunner.emit(extensionEvent);
|
|
969
|
-
} else if (event.type === "tool_execution_update") {
|
|
970
|
-
const extensionEvent: ToolExecutionUpdateEvent = {
|
|
971
|
-
type: "tool_execution_update",
|
|
972
|
-
toolCallId: event.toolCallId,
|
|
973
|
-
toolName: event.toolName,
|
|
974
|
-
args: event.args,
|
|
975
|
-
partialResult: event.partialResult,
|
|
976
|
-
};
|
|
977
|
-
await this._extensionRunner.emit(extensionEvent);
|
|
978
|
-
} else if (event.type === "tool_execution_end") {
|
|
979
|
-
const extensionEvent: ToolExecutionEndEvent = {
|
|
980
|
-
type: "tool_execution_end",
|
|
981
|
-
toolCallId: event.toolCallId,
|
|
982
|
-
toolName: event.toolName,
|
|
983
|
-
result: event.result,
|
|
984
|
-
isError: event.isError,
|
|
985
|
-
};
|
|
986
|
-
await this._extensionRunner.emit(extensionEvent);
|
|
987
|
-
}
|
|
988
|
-
}
|
|
989
|
-
|
|
990
|
-
// =========================================================================
|
|
991
|
-
// Session State Snapshot / Restore (D-14)
|
|
992
|
-
// =========================================================================
|
|
993
|
-
|
|
994
|
-
/**
|
|
995
|
-
* Capture a shallow snapshot of listener and message state before a session transition.
|
|
996
|
-
* Used by _restoreState() to re-attach listeners and message arrays after the transition
|
|
997
|
-
* tears down and recreates the runtime.
|
|
998
|
-
*/
|
|
999
|
-
private _snapshotState(): {
|
|
1000
|
-
listeners: AgentSessionEventListener[];
|
|
1001
|
-
steering: string[];
|
|
1002
|
-
followUp: string[];
|
|
1003
|
-
pending: CustomMessage[];
|
|
1004
|
-
} {
|
|
1005
|
-
return {
|
|
1006
|
-
listeners: [...this._eventListeners],
|
|
1007
|
-
steering: [...this._steeringMessages],
|
|
1008
|
-
followUp: [...this._followUpMessages],
|
|
1009
|
-
pending: [...this._pendingNextTurnMessages],
|
|
1010
|
-
};
|
|
1011
|
-
}
|
|
1012
|
-
|
|
1013
|
-
/**
|
|
1014
|
-
* Restore listener and message state after a session transition has completed.
|
|
1015
|
-
* Re-registers all event listeners captured by _snapshotState() on this session
|
|
1016
|
-
* and restores the pending message arrays.
|
|
1017
|
-
*/
|
|
1018
|
-
private _restoreState(snapshot: ReturnType<AgentSession["_snapshotState"]>): void {
|
|
1019
|
-
this._eventListeners = snapshot.listeners;
|
|
1020
|
-
this._steeringMessages = snapshot.steering;
|
|
1021
|
-
this._followUpMessages = snapshot.followUp;
|
|
1022
|
-
this._pendingNextTurnMessages = snapshot.pending;
|
|
1023
|
-
}
|
|
1024
|
-
|
|
1025
|
-
// =========================================================================
|
|
1026
|
-
// AgentSessionRuntime Factory (D-12)
|
|
1027
|
-
// =========================================================================
|
|
1028
|
-
|
|
1029
|
-
/**
|
|
1030
|
-
* Create and return a CreateAgentSessionRuntimeFactory closure that captures this
|
|
1031
|
-
* AgentSession. When the factory is called by AgentSessionRuntime (after teardown),
|
|
1032
|
-
* it re-initialises this session's internal state to match the incoming sessionManager
|
|
1033
|
-
* and sessionStartEvent, then returns a CreateAgentSessionRuntimeResult wrapping this
|
|
1034
|
-
* session so AgentSessionRuntime can track it.
|
|
1035
|
-
*
|
|
1036
|
-
* The factory is kept alive on _runtime and reused for all subsequent transitions.
|
|
1037
|
-
*/
|
|
1038
|
-
private _createRuntimeFactory(): CreateAgentSessionRuntimeFactory {
|
|
1039
|
-
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
1040
|
-
const gsdSession = this;
|
|
1041
|
-
|
|
1042
|
-
return async (options: {
|
|
1043
|
-
cwd: string;
|
|
1044
|
-
agentDir: string;
|
|
1045
|
-
sessionManager: SessionManager;
|
|
1046
|
-
sessionStartEvent?: SessionStartEventCompat;
|
|
1047
|
-
}): Promise<CreateAgentSessionRuntimeResult> => {
|
|
1048
|
-
const reason = options.sessionStartEvent?.reason ?? "new";
|
|
1049
|
-
const previousCwd = gsdSession._cwd;
|
|
1050
|
-
gsdSession._cwd = options.cwd;
|
|
1051
|
-
|
|
1052
|
-
// Apply the incoming sessionManager state to the GSD session's readonly SM.
|
|
1053
|
-
// options.sessionManager has already been wired up by the runtime caller
|
|
1054
|
-
// (SessionManager.create / open / createBranchedSession). Mirror the same
|
|
1055
|
-
// state into gsdSession.sessionManager so GSD's SM stays authoritative.
|
|
1056
|
-
if (reason === "resume") {
|
|
1057
|
-
const targetFile = options.sessionManager.getSessionFile();
|
|
1058
|
-
if (targetFile) {
|
|
1059
|
-
gsdSession.sessionManager.setSessionFile(targetFile);
|
|
1060
|
-
}
|
|
1061
|
-
}
|
|
1062
|
-
// For "new" and "fork" the sessionManager was already mutated by the GSD
|
|
1063
|
-
// transition method before calling _runtime (see newSession / fork callers).
|
|
1064
|
-
// No extra SM mutation is needed here.
|
|
1065
|
-
|
|
1066
|
-
gsdSession.agent.sessionId = gsdSession.sessionManager.getSessionId();
|
|
1067
|
-
|
|
1068
|
-
// Rebuild tools if cwd changed, otherwise refresh registry (#633, #3616).
|
|
1069
|
-
if (gsdSession._cwd !== previousCwd) {
|
|
1070
|
-
gsdSession._buildRuntime({
|
|
1071
|
-
activeToolNames: gsdSession.getActiveToolNames(),
|
|
1072
|
-
includeAllExtensionTools: true,
|
|
1073
|
-
});
|
|
1074
|
-
} else {
|
|
1075
|
-
gsdSession._refreshToolRegistry({
|
|
1076
|
-
activeToolNames: gsdSession.getActiveToolNames(),
|
|
1077
|
-
includeAllExtensionTools: true,
|
|
1078
|
-
});
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
gsdSession._reconnectToAgent();
|
|
1082
|
-
|
|
1083
|
-
// Emit session_start to extensions (Pitfall 7: single emission point).
|
|
1084
|
-
if (options.sessionStartEvent && gsdSession._extensionRunner) {
|
|
1085
|
-
await gsdSession._extensionRunner.emit(options.sessionStartEvent);
|
|
1086
|
-
}
|
|
1087
|
-
|
|
1088
|
-
// Build a minimal AgentSessionServices compatible object from what GSD
|
|
1089
|
-
// already holds — pi's runtime uses this for cwd tracking and process.chdir.
|
|
1090
|
-
const services: AgentSessionServices = {
|
|
1091
|
-
cwd: options.cwd,
|
|
1092
|
-
agentDir: options.agentDir,
|
|
1093
|
-
authStorage: gsdSession._modelRegistry.authStorage,
|
|
1094
|
-
settingsManager: gsdSession.settingsManager,
|
|
1095
|
-
modelRegistry: gsdSession._modelRegistry,
|
|
1096
|
-
resourceLoader: gsdSession._resourceLoader,
|
|
1097
|
-
diagnostics: [],
|
|
1098
|
-
};
|
|
1099
|
-
|
|
1100
|
-
return {
|
|
1101
|
-
// Cast: GSD's AgentSession is structurally compatible with pi's AgentSession
|
|
1102
|
-
// (same fields: agent, sessionManager, extensionRunner, sessionFile, dispose).
|
|
1103
|
-
// Nominal incompatibility arises only from different module paths.
|
|
1104
|
-
session: gsdSession as unknown as import("@gsd/pi-coding-agent").AgentSession,
|
|
1105
|
-
services,
|
|
1106
|
-
diagnostics: [],
|
|
1107
|
-
extensionsResult: gsdSession._resourceLoader.getExtensions(),
|
|
1108
|
-
};
|
|
1109
|
-
};
|
|
1110
|
-
}
|
|
1111
|
-
|
|
1112
|
-
/**
|
|
1113
|
-
* Ensure _runtime is initialised. Creates it lazily on first session transition
|
|
1114
|
-
* using createAgentSessionRuntime so that the runtime's factory is wired once
|
|
1115
|
-
* and reused for all subsequent newSession / switchSession / fork calls.
|
|
1116
|
-
*
|
|
1117
|
-
* The initial call uses the current session state — no actual session reset occurs
|
|
1118
|
-
* on first init because the session is already live.
|
|
1119
|
-
*/
|
|
1120
|
-
private async _ensureRuntime(): Promise<AgentSessionRuntime> {
|
|
1121
|
-
if (this._runtime) return this._runtime;
|
|
1122
|
-
|
|
1123
|
-
const factory = this._createRuntimeFactory();
|
|
1124
|
-
// Prefer the agentDir stored on DefaultResourceLoader (runtime property) or
|
|
1125
|
-
// fall back to the global getAgentDir() helper imported from @gsd/pi-coding-agent.
|
|
1126
|
-
const agentDir: string = (this._resourceLoader as unknown as { agentDir?: string }).agentDir ?? getAgentDir();
|
|
1127
|
-
|
|
1128
|
-
// Build minimal services for the initial runtime construction.
|
|
1129
|
-
const services: AgentSessionServices = {
|
|
1130
|
-
cwd: this._cwd,
|
|
1131
|
-
agentDir,
|
|
1132
|
-
authStorage: this._modelRegistry.authStorage,
|
|
1133
|
-
settingsManager: this.settingsManager,
|
|
1134
|
-
modelRegistry: this._modelRegistry,
|
|
1135
|
-
resourceLoader: this._resourceLoader,
|
|
1136
|
-
diagnostics: [],
|
|
1137
|
-
};
|
|
1138
|
-
|
|
1139
|
-
// createAgentSessionRuntime calls factory once to build the initial result.
|
|
1140
|
-
// We pass a factory that short-circuits on the first call (init-only) because
|
|
1141
|
-
// the session is already live — no teardown/rebuild needed.
|
|
1142
|
-
let initDone = false;
|
|
1143
|
-
const initFactory: CreateAgentSessionRuntimeFactory = async (opts) => {
|
|
1144
|
-
if (!initDone) {
|
|
1145
|
-
initDone = true;
|
|
1146
|
-
// First call: session already live, just return current state.
|
|
1147
|
-
return {
|
|
1148
|
-
session: this as unknown as import("@gsd/pi-coding-agent").AgentSession,
|
|
1149
|
-
services,
|
|
1150
|
-
diagnostics: [],
|
|
1151
|
-
extensionsResult: this._resourceLoader.getExtensions(),
|
|
1152
|
-
};
|
|
1153
|
-
}
|
|
1154
|
-
// Subsequent calls: delegate to the real factory.
|
|
1155
|
-
return factory(opts);
|
|
1156
|
-
};
|
|
1157
|
-
|
|
1158
|
-
this._runtime = await createAgentSessionRuntime(initFactory, {
|
|
1159
|
-
cwd: this._cwd,
|
|
1160
|
-
agentDir,
|
|
1161
|
-
sessionManager: this.sessionManager,
|
|
1162
|
-
});
|
|
1163
|
-
|
|
1164
|
-
// Replace the one-shot initFactory with the real factory so all future
|
|
1165
|
-
// transitions go through the proper path.
|
|
1166
|
-
// vendor-seam: dual-module-path — AgentSessionRuntime does not expose a public
|
|
1167
|
-
// createRuntime setter. Required for one-shot init to factory transition.
|
|
1168
|
-
// Bounded to this single call site.
|
|
1169
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- vendor-seam: dual-module-path, no public setter available
|
|
1170
|
-
(this._runtime as any /* vendor-seam: dual-module-path */)["createRuntime"] = factory;
|
|
1171
|
-
|
|
1172
|
-
return this._runtime;
|
|
1173
|
-
}
|
|
1174
|
-
|
|
1175
|
-
/**
|
|
1176
|
-
* Subscribe to agent events.
|
|
1177
|
-
* Session persistence is handled internally (saves messages on message_end).
|
|
1178
|
-
* Multiple listeners can be added. Returns unsubscribe function for this listener.
|
|
1179
|
-
*/
|
|
1180
|
-
subscribe(listener: AgentSessionEventListener): () => void {
|
|
1181
|
-
this._eventListeners.push(listener);
|
|
1182
|
-
|
|
1183
|
-
// Return unsubscribe function for this specific listener
|
|
1184
|
-
return () => {
|
|
1185
|
-
const index = this._eventListeners.indexOf(listener);
|
|
1186
|
-
if (index !== -1) {
|
|
1187
|
-
this._eventListeners.splice(index, 1);
|
|
1188
|
-
}
|
|
1189
|
-
};
|
|
1190
|
-
}
|
|
1191
|
-
|
|
1192
|
-
/**
|
|
1193
|
-
* Temporarily disconnect from agent events.
|
|
1194
|
-
* User listeners are preserved and will receive events again after resubscribe().
|
|
1195
|
-
* Used internally during operations that need to pause event processing.
|
|
1196
|
-
*/
|
|
1197
|
-
private _disconnectFromAgent(): void {
|
|
1198
|
-
if (this._unsubscribeAgent) {
|
|
1199
|
-
this._unsubscribeAgent();
|
|
1200
|
-
this._unsubscribeAgent = undefined;
|
|
1201
|
-
}
|
|
1202
|
-
}
|
|
1203
|
-
|
|
1204
|
-
/**
|
|
1205
|
-
* Reconnect to agent events after _disconnectFromAgent().
|
|
1206
|
-
* Preserves all existing listeners.
|
|
1207
|
-
*/
|
|
1208
|
-
private _reconnectToAgent(): void {
|
|
1209
|
-
if (this._unsubscribeAgent) return; // Already connected
|
|
1210
|
-
this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
|
|
1211
|
-
}
|
|
1212
|
-
|
|
1213
|
-
/**
|
|
1214
|
-
* Remove all listeners and disconnect from agent.
|
|
1215
|
-
* Call this when completely done with the session.
|
|
1216
|
-
*/
|
|
1217
|
-
dispose(): void {
|
|
1218
|
-
this._extensionErrorUnsubscriber?.();
|
|
1219
|
-
this._extensionErrorUnsubscriber = undefined;
|
|
1220
|
-
this._disconnectFromAgent();
|
|
1221
|
-
this._eventListeners = [];
|
|
1222
|
-
}
|
|
1223
|
-
|
|
1224
|
-
// =========================================================================
|
|
1225
|
-
// Read-only State Access
|
|
1226
|
-
// =========================================================================
|
|
1227
|
-
|
|
1228
|
-
/** Full agent state */
|
|
1229
|
-
get state(): AgentState {
|
|
1230
|
-
return this.agent.state;
|
|
1231
|
-
}
|
|
1232
|
-
|
|
1233
|
-
/** Current model (may be undefined if not yet selected) */
|
|
1234
|
-
get model(): Model<Api> | undefined {
|
|
1235
|
-
return this.agent.state.model;
|
|
1236
|
-
}
|
|
1237
|
-
|
|
1238
|
-
/** Current thinking level */
|
|
1239
|
-
get thinkingLevel(): ThinkingLevel {
|
|
1240
|
-
return this.agent.state.thinkingLevel;
|
|
1241
|
-
}
|
|
1242
|
-
|
|
1243
|
-
/** Whether agent is currently streaming a response */
|
|
1244
|
-
get isStreaming(): boolean {
|
|
1245
|
-
return this.agent.state.isStreaming;
|
|
1246
|
-
}
|
|
1247
|
-
|
|
1248
|
-
/** Current effective system prompt (includes any per-turn extension modifications) */
|
|
1249
|
-
get systemPrompt(): string {
|
|
1250
|
-
return this.agent.state.systemPrompt;
|
|
1251
|
-
}
|
|
1252
|
-
|
|
1253
|
-
/** Current retry attempt (0 if not retrying) */
|
|
1254
|
-
get retryAttempt(): number {
|
|
1255
|
-
return this._retryHandler.retryAttempt;
|
|
1256
|
-
}
|
|
1257
|
-
|
|
1258
|
-
/**
|
|
1259
|
-
* Get the names of currently active tools.
|
|
1260
|
-
* Returns the names of tools currently set on the agent.
|
|
1261
|
-
*/
|
|
1262
|
-
getActiveToolNames(): string[] {
|
|
1263
|
-
return this.agent.state.tools.map((t) => t.name);
|
|
1264
|
-
}
|
|
1265
|
-
|
|
1266
|
-
/**
|
|
1267
|
-
* Get all configured tools with name, description, and parameter schema.
|
|
1268
|
-
*/
|
|
1269
|
-
getAllTools(): ToolInfo[] {
|
|
1270
|
-
return Array.from(this._toolRegistry.values()).map((t) => ({
|
|
1271
|
-
name: t.name,
|
|
1272
|
-
description: t.description,
|
|
1273
|
-
parameters: t.parameters,
|
|
1274
|
-
sourceInfo: { path: "", source: "builtin", scope: "temporary" as const, origin: "top-level" as const },
|
|
1275
|
-
}));
|
|
1276
|
-
}
|
|
1277
|
-
|
|
1278
|
-
/**
|
|
1279
|
-
* Set active tools by name.
|
|
1280
|
-
* Only tools in the registry can be enabled. Unknown tool names are ignored.
|
|
1281
|
-
* Also rebuilds the system prompt to reflect the new tool set.
|
|
1282
|
-
* Changes take effect on the next agent turn.
|
|
1283
|
-
*/
|
|
1284
|
-
setActiveToolsByName(toolNames: string[]): void {
|
|
1285
|
-
const requestedToolNames = [...new Set([...toolNames, ...this._getBuiltinToolNames()])];
|
|
1286
|
-
const tools: AgentTool[] = [];
|
|
1287
|
-
const validToolNames: string[] = [];
|
|
1288
|
-
for (const name of requestedToolNames) {
|
|
1289
|
-
const tool = this._toolRegistry.get(name);
|
|
1290
|
-
if (tool) {
|
|
1291
|
-
tools.push(tool);
|
|
1292
|
-
validToolNames.push(name);
|
|
1293
|
-
}
|
|
1294
|
-
}
|
|
1295
|
-
this.agent.state.tools = tools;
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
// Rebuild base system prompt with new tool set
|
|
1299
|
-
this._baseSystemPrompt = this._rebuildSystemPrompt(validToolNames);
|
|
1300
|
-
this.agent.state.systemPrompt = this._baseSystemPrompt;
|
|
1301
|
-
}
|
|
1302
|
-
|
|
1303
|
-
/** Whether compaction or branch summarization is currently running */
|
|
1304
|
-
get isCompacting(): boolean {
|
|
1305
|
-
return this._compactionOrchestrator.isCompacting;
|
|
1306
|
-
}
|
|
1307
|
-
|
|
1308
|
-
/**
|
|
1309
|
-
* Switch edit mode between standard (text-match) and hashline (LINE#ID anchors).
|
|
1310
|
-
* Swaps the active read/edit tools and rebuilds the system prompt.
|
|
1311
|
-
*/
|
|
1312
|
-
setEditMode(mode: "standard" | "hashline"): void {
|
|
1313
|
-
(this.settingsManager as SettingsManagerWithEditMode).setEditMode(mode);
|
|
1314
|
-
|
|
1315
|
-
// Get current active tool registry keys
|
|
1316
|
-
const currentKeys = new Set<string>();
|
|
1317
|
-
for (const [key, tool] of this._toolRegistry.entries()) {
|
|
1318
|
-
if (this.agent.state.tools.includes(tool)) {
|
|
1319
|
-
currentKeys.add(key);
|
|
1320
|
-
}
|
|
1321
|
-
}
|
|
1322
|
-
|
|
1323
|
-
// Swap read tools
|
|
1324
|
-
if (mode === "hashline") {
|
|
1325
|
-
currentKeys.delete("read");
|
|
1326
|
-
currentKeys.add("hashline_read");
|
|
1327
|
-
currentKeys.delete("edit");
|
|
1328
|
-
currentKeys.add("hashline_edit");
|
|
1329
|
-
} else {
|
|
1330
|
-
currentKeys.delete("hashline_read");
|
|
1331
|
-
currentKeys.add("read");
|
|
1332
|
-
currentKeys.delete("hashline_edit");
|
|
1333
|
-
currentKeys.add("edit");
|
|
1334
|
-
}
|
|
1335
|
-
|
|
1336
|
-
this.setActiveToolsByName([...currentKeys]);
|
|
1337
|
-
}
|
|
1338
|
-
|
|
1339
|
-
/** Current edit mode */
|
|
1340
|
-
get editMode(): "standard" | "hashline" {
|
|
1341
|
-
return (this.settingsManager as SettingsManagerWithEditMode).getEditMode();
|
|
1342
|
-
}
|
|
1343
|
-
|
|
1344
|
-
/** All messages including custom types like BashExecutionMessage */
|
|
1345
|
-
get messages(): AgentMessage[] {
|
|
1346
|
-
return this.agent.state.messages;
|
|
1347
|
-
}
|
|
1348
|
-
|
|
1349
|
-
/** Current steering mode */
|
|
1350
|
-
get steeringMode(): "all" | "one-at-a-time" {
|
|
1351
|
-
return this.agent.getSteeringMode();
|
|
1352
|
-
}
|
|
1353
|
-
|
|
1354
|
-
/** Current follow-up mode */
|
|
1355
|
-
get followUpMode(): "all" | "one-at-a-time" {
|
|
1356
|
-
return this.agent.getFollowUpMode();
|
|
1357
|
-
}
|
|
1358
|
-
|
|
1359
|
-
/** Current session file path, or undefined if sessions are disabled */
|
|
1360
|
-
get sessionFile(): string | undefined {
|
|
1361
|
-
return this.sessionManager.getSessionFile();
|
|
1362
|
-
}
|
|
1363
|
-
|
|
1364
|
-
/** Current session ID */
|
|
1365
|
-
get sessionId(): string {
|
|
1366
|
-
return this.sessionManager.getSessionId();
|
|
1367
|
-
}
|
|
1368
|
-
|
|
1369
|
-
/** Current session display name, if set */
|
|
1370
|
-
get sessionName(): string | undefined {
|
|
1371
|
-
return this.sessionManager.getSessionName();
|
|
1372
|
-
}
|
|
1373
|
-
|
|
1374
|
-
/** Scoped models for cycling (from --models flag) */
|
|
1375
|
-
get scopedModels(): ReadonlyArray<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }> {
|
|
1376
|
-
return this._scopedModels;
|
|
1377
|
-
}
|
|
1378
|
-
|
|
1379
|
-
/** Update scoped models for cycling */
|
|
1380
|
-
setScopedModels(scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>): void {
|
|
1381
|
-
this._scopedModels = scopedModels;
|
|
1382
|
-
}
|
|
1383
|
-
|
|
1384
|
-
/** File-based prompt templates */
|
|
1385
|
-
get promptTemplates(): ReadonlyArray<PromptTemplate> {
|
|
1386
|
-
return this._resourceLoader.getPrompts().prompts;
|
|
1387
|
-
}
|
|
1388
|
-
|
|
1389
|
-
private _normalizePromptSnippet(text: string | undefined): string | undefined {
|
|
1390
|
-
if (!text) return undefined;
|
|
1391
|
-
const oneLine = text
|
|
1392
|
-
.replace(/[\r\n]+/g, " ")
|
|
1393
|
-
.replace(/\s+/g, " ")
|
|
1394
|
-
.trim();
|
|
1395
|
-
return oneLine.length > 0 ? oneLine : undefined;
|
|
1396
|
-
}
|
|
1397
|
-
|
|
1398
|
-
private _normalizePromptGuidelines(guidelines: string[] | undefined): string[] {
|
|
1399
|
-
if (!guidelines || guidelines.length === 0) {
|
|
1400
|
-
return [];
|
|
1401
|
-
}
|
|
1402
|
-
|
|
1403
|
-
const unique = new Set<string>();
|
|
1404
|
-
for (const guideline of guidelines) {
|
|
1405
|
-
const normalized = guideline.trim();
|
|
1406
|
-
if (normalized.length > 0) {
|
|
1407
|
-
unique.add(normalized);
|
|
1408
|
-
}
|
|
1409
|
-
}
|
|
1410
|
-
return Array.from(unique);
|
|
1411
|
-
}
|
|
1412
|
-
|
|
1413
|
-
private _findSkillByName(skillName: string): Skill | undefined {
|
|
1414
|
-
return this.resourceLoader.getSkills().skills.find((skill) => skill.name === skillName);
|
|
1415
|
-
}
|
|
1416
|
-
|
|
1417
|
-
private _formatMissingSkillMessage(skillName: string): string {
|
|
1418
|
-
const availableSkills = this.resourceLoader.getSkills().skills.map((skill) => skill.name).join(", ") || "(none)";
|
|
1419
|
-
return `Skill "${skillName}" not found. Available skills: ${availableSkills}`;
|
|
1420
|
-
}
|
|
1421
|
-
|
|
1422
|
-
private _emitSkillExpansionError(skillFilePath: string, err: unknown): void {
|
|
1423
|
-
this._extensionRunner?.emitError({
|
|
1424
|
-
extensionPath: skillFilePath,
|
|
1425
|
-
event: "skill_expansion",
|
|
1426
|
-
error: getErrorMessage(err),
|
|
1427
|
-
});
|
|
1428
|
-
}
|
|
1429
|
-
|
|
1430
|
-
private _renderSkillInvocation(skill: { name: string; filePath: string; baseDir: string }, args?: string): string {
|
|
1431
|
-
const content = readFileSync(skill.filePath, "utf-8");
|
|
1432
|
-
const body = stripFrontmatter(content).trim();
|
|
1433
|
-
const skillBlock = `<skill name="${skill.name}" location="${skill.filePath}">\nReferences are relative to ${skill.baseDir}.\n\n${body}\n</skill>`;
|
|
1434
|
-
return args && args.trim() ? `${skillBlock}\n\n${args.trim()}` : skillBlock;
|
|
1435
|
-
}
|
|
1436
|
-
|
|
1437
|
-
private _expandSkillByName(skillName: string, args?: string): string {
|
|
1438
|
-
const skill = this._findSkillByName(skillName);
|
|
1439
|
-
if (!skill) {
|
|
1440
|
-
throw new Error(this._formatMissingSkillMessage(skillName));
|
|
1441
|
-
}
|
|
1442
|
-
|
|
1443
|
-
try {
|
|
1444
|
-
return this._renderSkillInvocation(skill, args);
|
|
1445
|
-
} catch (err) {
|
|
1446
|
-
this._emitSkillExpansionError(skill.filePath, err);
|
|
1447
|
-
throw err;
|
|
1448
|
-
}
|
|
1449
|
-
}
|
|
1450
|
-
|
|
1451
|
-
private _formatSkillInvocation(skillName: string, args?: string): string {
|
|
1452
|
-
return this._expandSkillByName(skillName, args);
|
|
1453
|
-
}
|
|
1454
|
-
|
|
1455
|
-
private _rebuildSystemPrompt(toolNames: string[]): string {
|
|
1456
|
-
const validToolNames = toolNames.filter((name) => this._toolRegistry.has(name));
|
|
1457
|
-
const toolSnippets: Record<string, string> = {};
|
|
1458
|
-
const promptGuidelines: string[] = [];
|
|
1459
|
-
for (const name of validToolNames) {
|
|
1460
|
-
const snippet = this._toolPromptSnippets.get(name);
|
|
1461
|
-
if (snippet) {
|
|
1462
|
-
toolSnippets[name] = snippet;
|
|
1463
|
-
}
|
|
1464
|
-
|
|
1465
|
-
const toolGuidelines = this._toolPromptGuidelines.get(name);
|
|
1466
|
-
if (toolGuidelines) {
|
|
1467
|
-
promptGuidelines.push(...toolGuidelines);
|
|
1468
|
-
}
|
|
1469
|
-
}
|
|
1470
|
-
|
|
1471
|
-
const loaderSystemPrompt = this._resourceLoader.getSystemPrompt();
|
|
1472
|
-
const loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();
|
|
1473
|
-
const appendSystemPrompt =
|
|
1474
|
-
loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : undefined;
|
|
1475
|
-
const loadedSkills = this._resourceLoader.getSkills().skills;
|
|
1476
|
-
const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
|
|
1477
|
-
|
|
1478
|
-
return buildSystemPrompt({
|
|
1479
|
-
cwd: this._cwd,
|
|
1480
|
-
skills: loadedSkills,
|
|
1481
|
-
contextFiles: loadedContextFiles,
|
|
1482
|
-
customPrompt: loaderSystemPrompt,
|
|
1483
|
-
appendSystemPrompt,
|
|
1484
|
-
selectedTools: validToolNames,
|
|
1485
|
-
toolSnippets,
|
|
1486
|
-
promptGuidelines,
|
|
1487
|
-
});
|
|
1488
|
-
}
|
|
1489
|
-
|
|
1490
|
-
// =========================================================================
|
|
1491
|
-
// Prompting
|
|
1492
|
-
// =========================================================================
|
|
1493
|
-
|
|
1494
|
-
/**
|
|
1495
|
-
* Send a prompt to the agent.
|
|
1496
|
-
* - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming
|
|
1497
|
-
* - Expands file-based prompt templates by default
|
|
1498
|
-
* - During streaming, queues via steer() or followUp() based on streamingBehavior option
|
|
1499
|
-
* - Validates model and API key before sending (when not streaming)
|
|
1500
|
-
* @throws Error if streaming and no streamingBehavior specified
|
|
1501
|
-
* @throws Error if no model selected or no API key available (when not streaming)
|
|
1502
|
-
*/
|
|
1503
|
-
async prompt(text: string, options?: PromptOptions): Promise<void> {
|
|
1504
|
-
const expandPromptTemplates = options?.expandPromptTemplates ?? true;
|
|
1505
|
-
|
|
1506
|
-
// Handle extension commands first (execute immediately, even during streaming)
|
|
1507
|
-
// Extension commands manage their own LLM interaction via pi.sendMessage()
|
|
1508
|
-
if (expandPromptTemplates && text.startsWith("/")) {
|
|
1509
|
-
const handled = await this._tryExecuteExtensionCommand(text);
|
|
1510
|
-
if (handled) {
|
|
1511
|
-
// Extension command executed, no prompt to send
|
|
1512
|
-
return;
|
|
1513
|
-
}
|
|
1514
|
-
}
|
|
1515
|
-
|
|
1516
|
-
// Emit input event for extension interception (before skill/template expansion)
|
|
1517
|
-
let currentText = text;
|
|
1518
|
-
let currentImages = options?.images;
|
|
1519
|
-
if (this._extensionRunner?.hasHandlers("input")) {
|
|
1520
|
-
const inputResult = await this._extensionRunner.emitInput(
|
|
1521
|
-
currentText,
|
|
1522
|
-
currentImages,
|
|
1523
|
-
options?.source ?? "interactive",
|
|
1524
|
-
);
|
|
1525
|
-
if (inputResult.action === "handled") {
|
|
1526
|
-
return;
|
|
1527
|
-
}
|
|
1528
|
-
if (inputResult.action === "transform") {
|
|
1529
|
-
currentText = inputResult.text;
|
|
1530
|
-
currentImages = inputResult.images ?? currentImages;
|
|
1531
|
-
}
|
|
1532
|
-
}
|
|
1533
|
-
|
|
1534
|
-
// Expand skill commands (/skill:name args) and prompt templates (/template args)
|
|
1535
|
-
let expandedText = currentText;
|
|
1536
|
-
if (expandPromptTemplates) {
|
|
1537
|
-
expandedText = this._expandSkillCommand(expandedText);
|
|
1538
|
-
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
|
|
1539
|
-
}
|
|
1540
|
-
|
|
1541
|
-
// If streaming, queue via steer() or followUp() based on option
|
|
1542
|
-
if (this.isStreaming) {
|
|
1543
|
-
if (!options?.streamingBehavior) {
|
|
1544
|
-
throw new Error(
|
|
1545
|
-
"Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.",
|
|
1546
|
-
);
|
|
1547
|
-
}
|
|
1548
|
-
if (options.streamingBehavior === "followUp") {
|
|
1549
|
-
await this._queueFollowUp(expandedText, currentImages);
|
|
1550
|
-
} else {
|
|
1551
|
-
await this._queueSteer(expandedText, currentImages);
|
|
1552
|
-
}
|
|
1553
|
-
return;
|
|
1554
|
-
}
|
|
1555
|
-
|
|
1556
|
-
// Flush any pending bash messages before the new prompt
|
|
1557
|
-
this._flushPendingBashMessages();
|
|
1558
|
-
|
|
1559
|
-
// Validate model
|
|
1560
|
-
if (!this.model) {
|
|
1561
|
-
throw new Error(
|
|
1562
|
-
"No model selected.\n\n" +
|
|
1563
|
-
`Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}\n\n` +
|
|
1564
|
-
"Then use /model to select a model.",
|
|
1565
|
-
);
|
|
1566
|
-
}
|
|
1567
|
-
|
|
1568
|
-
// Check if a higher-priority provider in the fallback chain has recovered
|
|
1569
|
-
const restoration = await this._fallbackResolver.checkForRestoration(this.model);
|
|
1570
|
-
if (restoration) {
|
|
1571
|
-
const previousProvider = `${this.model.provider}/${this.model.id}`;
|
|
1572
|
-
this.agent.state.model = restoration.model;
|
|
1573
|
-
this.sessionManager.appendModelChange(restoration.model.provider, restoration.model.id);
|
|
1574
|
-
this._emit({
|
|
1575
|
-
type: "fallback_provider_restored",
|
|
1576
|
-
provider: `${restoration.model.provider}/${restoration.model.id}`,
|
|
1577
|
-
reason: `Restored from ${previousProvider}`,
|
|
1578
|
-
});
|
|
1579
|
-
}
|
|
1580
|
-
|
|
1581
|
-
// Validate provider readiness
|
|
1582
|
-
if (!this._modelRegistry.isProviderRequestReady(this.model.provider)) {
|
|
1583
|
-
const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
|
|
1584
|
-
if (isOAuth) {
|
|
1585
|
-
throw new Error(
|
|
1586
|
-
`Authentication failed for "${this.model.provider}". ` +
|
|
1587
|
-
`Credentials may have expired or network is unavailable. ` +
|
|
1588
|
-
`Run '/login ${this.model.provider}' to re-authenticate.`,
|
|
1589
|
-
);
|
|
1590
|
-
}
|
|
1591
|
-
throw new Error(
|
|
1592
|
-
`No API key found for ${this.model.provider}.\n\n` +
|
|
1593
|
-
`Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}`,
|
|
1594
|
-
);
|
|
1595
|
-
}
|
|
1596
|
-
|
|
1597
|
-
// Check if we need to compact before sending (catches aborted responses)
|
|
1598
|
-
const lastAssistant = this._findLastAssistantMessage();
|
|
1599
|
-
if (lastAssistant) {
|
|
1600
|
-
await this._compactionOrchestrator.checkCompaction(lastAssistant, false);
|
|
1601
|
-
}
|
|
1602
|
-
|
|
1603
|
-
// Build messages array (custom message if any, then user message)
|
|
1604
|
-
const messages: AgentMessage[] = [];
|
|
1605
|
-
|
|
1606
|
-
// Add user message
|
|
1607
|
-
const userContent: (TextContent | ImageContent)[] = [{ type: "text", text: expandedText }];
|
|
1608
|
-
if (currentImages) {
|
|
1609
|
-
userContent.push(...currentImages);
|
|
1610
|
-
}
|
|
1611
|
-
messages.push({
|
|
1612
|
-
role: "user",
|
|
1613
|
-
content: userContent,
|
|
1614
|
-
timestamp: Date.now(),
|
|
1615
|
-
});
|
|
1616
|
-
|
|
1617
|
-
// Inject any pending "nextTurn" messages as context alongside the user message
|
|
1618
|
-
for (const msg of this._pendingNextTurnMessages) {
|
|
1619
|
-
messages.push(msg);
|
|
1620
|
-
}
|
|
1621
|
-
this._pendingNextTurnMessages = [];
|
|
1622
|
-
|
|
1623
|
-
// Emit before_agent_start extension event
|
|
1624
|
-
if (this._extensionRunner) {
|
|
1625
|
-
const result = await this._extensionRunner.emitBeforeAgentStart(
|
|
1626
|
-
expandedText,
|
|
1627
|
-
currentImages,
|
|
1628
|
-
this._baseSystemPrompt,
|
|
1629
|
-
);
|
|
1630
|
-
// Add all custom messages from extensions
|
|
1631
|
-
if (result?.messages) {
|
|
1632
|
-
for (const msg of result.messages) {
|
|
1633
|
-
messages.push({
|
|
1634
|
-
role: "custom",
|
|
1635
|
-
customType: msg.customType,
|
|
1636
|
-
content: msg.content,
|
|
1637
|
-
display: msg.display,
|
|
1638
|
-
details: msg.details,
|
|
1639
|
-
timestamp: Date.now(),
|
|
1640
|
-
});
|
|
1641
|
-
}
|
|
1642
|
-
}
|
|
1643
|
-
// Apply extension-modified system prompt, or reset to base
|
|
1644
|
-
if (result?.systemPrompt) {
|
|
1645
|
-
this.agent.state.systemPrompt = result.systemPrompt;
|
|
1646
|
-
} else {
|
|
1647
|
-
// Ensure we're using the base prompt (in case previous turn had modifications)
|
|
1648
|
-
this.agent.state.systemPrompt = this._baseSystemPrompt;
|
|
1649
|
-
}
|
|
1650
|
-
}
|
|
1651
|
-
|
|
1652
|
-
await this.agent.prompt(messages);
|
|
1653
|
-
await this._retryHandler.waitForRetry();
|
|
1654
|
-
}
|
|
1655
|
-
|
|
1656
|
-
/**
|
|
1657
|
-
* Try to execute an extension command. Returns true if command was found and executed.
|
|
1658
|
-
*/
|
|
1659
|
-
private async _tryExecuteExtensionCommand(text: string): Promise<boolean> {
|
|
1660
|
-
if (!this._extensionRunner) return false;
|
|
1661
|
-
|
|
1662
|
-
// Parse command name and args
|
|
1663
|
-
const spaceIndex = text.indexOf(" ");
|
|
1664
|
-
const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
|
|
1665
|
-
const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
|
|
1666
|
-
|
|
1667
|
-
const command = this._extensionRunner.getCommand(commandName);
|
|
1668
|
-
if (!command) return false;
|
|
1669
|
-
|
|
1670
|
-
// Get command context from extension runner (includes session control methods)
|
|
1671
|
-
const ctx = this._extensionRunner.createCommandContext();
|
|
1672
|
-
|
|
1673
|
-
try {
|
|
1674
|
-
await command.handler(args, ctx);
|
|
1675
|
-
return true;
|
|
1676
|
-
} catch (err) {
|
|
1677
|
-
// Emit error via extension runner
|
|
1678
|
-
this._extensionRunner.emitError({
|
|
1679
|
-
extensionPath: `command:${commandName}`,
|
|
1680
|
-
event: "command",
|
|
1681
|
-
error: getErrorMessage(err),
|
|
1682
|
-
});
|
|
1683
|
-
return true;
|
|
1684
|
-
}
|
|
1685
|
-
}
|
|
1686
|
-
|
|
1687
|
-
/**
|
|
1688
|
-
* Expand skill commands (/skill:name args) to their full content.
|
|
1689
|
-
* Returns the expanded text, or the original text if not a skill command or skill not found.
|
|
1690
|
-
* Emits errors via extension runner if file read fails.
|
|
1691
|
-
*/
|
|
1692
|
-
private _expandSkillCommand(text: string): string {
|
|
1693
|
-
if (!text.startsWith("/skill:")) return text;
|
|
1694
|
-
|
|
1695
|
-
const spaceIndex = text.indexOf(" ");
|
|
1696
|
-
const skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);
|
|
1697
|
-
const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1).trim();
|
|
1698
|
-
|
|
1699
|
-
if (!this._findSkillByName(skillName)) return text;
|
|
1700
|
-
|
|
1701
|
-
try {
|
|
1702
|
-
return this._formatSkillInvocation(skillName, args);
|
|
1703
|
-
} catch {
|
|
1704
|
-
return text;
|
|
1705
|
-
}
|
|
1706
|
-
}
|
|
1707
|
-
|
|
1708
|
-
private _createBuiltInSkillTool(): AgentTool {
|
|
1709
|
-
const skillSchema = Type.Object({
|
|
1710
|
-
skill: Type.String({ description: "The skill name. E.g., 'commit', 'review-pr', or 'pdf'" }),
|
|
1711
|
-
args: Type.Optional(Type.String({ description: "Optional arguments for the skill" })),
|
|
1712
|
-
});
|
|
1713
|
-
|
|
1714
|
-
return {
|
|
1715
|
-
name: "Skill",
|
|
1716
|
-
label: "Skill",
|
|
1717
|
-
description:
|
|
1718
|
-
"Execute a skill within the main conversation. Use this tool when users ask for a slash command or reference a skill by name. Returns the expanded skill block and appends args after it.",
|
|
1719
|
-
parameters: skillSchema,
|
|
1720
|
-
execute: async (_toolCallId, params: unknown) => {
|
|
1721
|
-
const input = params as { skill: string; args?: string };
|
|
1722
|
-
try {
|
|
1723
|
-
return {
|
|
1724
|
-
content: [
|
|
1725
|
-
{
|
|
1726
|
-
type: "text",
|
|
1727
|
-
text: this._expandSkillByName(input.skill, input.args),
|
|
1728
|
-
},
|
|
1729
|
-
],
|
|
1730
|
-
details: undefined,
|
|
1731
|
-
};
|
|
1732
|
-
} catch (err) {
|
|
1733
|
-
return {
|
|
1734
|
-
content: [{ type: "text", text: getErrorMessage(err) }],
|
|
1735
|
-
details: undefined,
|
|
1736
|
-
};
|
|
1737
|
-
}
|
|
1738
|
-
},
|
|
1739
|
-
};
|
|
1740
|
-
}
|
|
1741
|
-
|
|
1742
|
-
private _getBuiltinToolNames(): string[] {
|
|
1743
|
-
return this._getBuiltinTools().map((tool) => tool.name);
|
|
1744
|
-
}
|
|
1745
|
-
|
|
1746
|
-
private _getBuiltinTools(): AgentTool[] {
|
|
1747
|
-
return [this._createBuiltInSkillTool()];
|
|
1748
|
-
}
|
|
1749
|
-
|
|
1750
|
-
private _getRegisteredToolDefinitions(): ToolDefinition[] {
|
|
1751
|
-
const registeredTools = this._extensionRunner?.getAllRegisteredTools() ?? [];
|
|
1752
|
-
return registeredTools.map((tool) => tool.definition);
|
|
1753
|
-
}
|
|
1754
|
-
|
|
1755
|
-
private _getBuiltinToolDefinitions(): ToolDefinition[] {
|
|
1756
|
-
return this._getBuiltinTools().map((tool) => ({
|
|
1757
|
-
name: tool.name,
|
|
1758
|
-
label: tool.label,
|
|
1759
|
-
description: tool.description,
|
|
1760
|
-
parameters: tool.parameters,
|
|
1761
|
-
execute: async () => ({ content: [], details: undefined }),
|
|
1762
|
-
}));
|
|
1763
|
-
}
|
|
1764
|
-
|
|
1765
|
-
getRenderableToolDefinition(toolName: string): ToolDefinition | undefined {
|
|
1766
|
-
const normalizedToolName = toolName.toLowerCase();
|
|
1767
|
-
return [...this._getBuiltinToolDefinitions(), ...this._getRegisteredToolDefinitions()].find(
|
|
1768
|
-
(tool) => tool.name.toLowerCase() === normalizedToolName,
|
|
1769
|
-
);
|
|
1770
|
-
}
|
|
1771
|
-
|
|
1772
|
-
/**
|
|
1773
|
-
* Queue a steering message to interrupt the agent mid-run.
|
|
1774
|
-
* Delivered after current tool execution, skips remaining tools.
|
|
1775
|
-
* Expands skill commands and prompt templates. Errors on extension commands.
|
|
1776
|
-
* @param images Optional image attachments to include with the message
|
|
1777
|
-
* @throws Error if text is an extension command
|
|
1778
|
-
*/
|
|
1779
|
-
async steer(text: string, images?: ImageContent[]): Promise<void> {
|
|
1780
|
-
// Check for extension commands (cannot be queued)
|
|
1781
|
-
if (text.startsWith("/")) {
|
|
1782
|
-
this._throwIfExtensionCommand(text);
|
|
1783
|
-
}
|
|
1784
|
-
|
|
1785
|
-
// Expand skill commands and prompt templates
|
|
1786
|
-
let expandedText = this._expandSkillCommand(text);
|
|
1787
|
-
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
|
|
1788
|
-
|
|
1789
|
-
await this._queueSteer(expandedText, images);
|
|
1790
|
-
}
|
|
1791
|
-
|
|
1792
|
-
/**
|
|
1793
|
-
* Queue a follow-up message to be processed after the agent finishes.
|
|
1794
|
-
* Delivered only when agent has no more tool calls or steering messages.
|
|
1795
|
-
* Expands skill commands and prompt templates. Errors on extension commands.
|
|
1796
|
-
* @param images Optional image attachments to include with the message
|
|
1797
|
-
* @throws Error if text is an extension command
|
|
1798
|
-
*/
|
|
1799
|
-
async followUp(text: string, images?: ImageContent[]): Promise<void> {
|
|
1800
|
-
// Check for extension commands (cannot be queued)
|
|
1801
|
-
if (text.startsWith("/")) {
|
|
1802
|
-
this._throwIfExtensionCommand(text);
|
|
1803
|
-
}
|
|
1804
|
-
|
|
1805
|
-
// Expand skill commands and prompt templates
|
|
1806
|
-
let expandedText = this._expandSkillCommand(text);
|
|
1807
|
-
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
|
|
1808
|
-
|
|
1809
|
-
await this._queueFollowUp(expandedText, images);
|
|
1810
|
-
}
|
|
1811
|
-
|
|
1812
|
-
/**
|
|
1813
|
-
* Internal: Queue a steering message (already expanded, no extension command check).
|
|
1814
|
-
*/
|
|
1815
|
-
private async _queueSteer(text: string, images?: ImageContent[]): Promise<void> {
|
|
1816
|
-
this._steeringMessages.push(text);
|
|
1817
|
-
const content: (TextContent | ImageContent)[] = [{ type: "text", text }];
|
|
1818
|
-
if (images) {
|
|
1819
|
-
content.push(...images);
|
|
1820
|
-
}
|
|
1821
|
-
this.agent.steer({
|
|
1822
|
-
role: "user",
|
|
1823
|
-
content,
|
|
1824
|
-
timestamp: Date.now(),
|
|
1825
|
-
});
|
|
1826
|
-
}
|
|
1827
|
-
|
|
1828
|
-
/**
|
|
1829
|
-
* Internal: Queue a follow-up message (already expanded, no extension command check).
|
|
1830
|
-
*/
|
|
1831
|
-
private async _queueFollowUp(text: string, images?: ImageContent[]): Promise<void> {
|
|
1832
|
-
this._followUpMessages.push(text);
|
|
1833
|
-
const content: (TextContent | ImageContent)[] = [{ type: "text", text }];
|
|
1834
|
-
if (images) {
|
|
1835
|
-
content.push(...images);
|
|
1836
|
-
}
|
|
1837
|
-
this.agent.followUp({
|
|
1838
|
-
role: "user",
|
|
1839
|
-
content,
|
|
1840
|
-
timestamp: Date.now(),
|
|
1841
|
-
});
|
|
1842
|
-
}
|
|
1843
|
-
|
|
1844
|
-
/**
|
|
1845
|
-
* Throw an error if the text is an extension command.
|
|
1846
|
-
*/
|
|
1847
|
-
private _throwIfExtensionCommand(text: string): void {
|
|
1848
|
-
if (!this._extensionRunner) return;
|
|
1849
|
-
|
|
1850
|
-
const spaceIndex = text.indexOf(" ");
|
|
1851
|
-
const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
|
|
1852
|
-
const command = this._extensionRunner.getCommand(commandName);
|
|
1853
|
-
|
|
1854
|
-
if (command) {
|
|
1855
|
-
throw new Error(
|
|
1856
|
-
`Extension command "/${commandName}" cannot be queued. Use prompt() or execute the command when not streaming.`,
|
|
1857
|
-
);
|
|
1858
|
-
}
|
|
1859
|
-
}
|
|
1860
|
-
|
|
1861
|
-
/**
|
|
1862
|
-
* Send a custom message to the session. Creates a CustomMessageEntry.
|
|
1863
|
-
*
|
|
1864
|
-
* Handles three cases:
|
|
1865
|
-
* - Streaming: queues message, processed when loop pulls from queue
|
|
1866
|
-
* - Not streaming + triggerTurn: appends to state/session, starts new turn
|
|
1867
|
-
* - Not streaming + no trigger: appends to state/session, no turn
|
|
1868
|
-
*
|
|
1869
|
-
* @param message Custom message with customType, content, display, details
|
|
1870
|
-
* @param options.triggerTurn If true and not streaming, triggers a new LLM turn
|
|
1871
|
-
* @param options.deliverAs Delivery mode: "steer", "followUp", or "nextTurn"
|
|
1872
|
-
*/
|
|
1873
|
-
async sendCustomMessage<T = unknown>(
|
|
1874
|
-
message: Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">,
|
|
1875
|
-
options?: { triggerTurn?: boolean; deliverAs?: "steer" | "followUp" | "nextTurn" },
|
|
1876
|
-
): Promise<void> {
|
|
1877
|
-
const appMessage = {
|
|
1878
|
-
role: "custom" as const,
|
|
1879
|
-
customType: message.customType,
|
|
1880
|
-
content: message.content,
|
|
1881
|
-
display: message.display,
|
|
1882
|
-
details: message.details,
|
|
1883
|
-
timestamp: Date.now(),
|
|
1884
|
-
} satisfies CustomMessage<T>;
|
|
1885
|
-
if (options?.deliverAs === "nextTurn") {
|
|
1886
|
-
this._pendingNextTurnMessages.push(appMessage);
|
|
1887
|
-
} else if (this.isStreaming) {
|
|
1888
|
-
if (options?.deliverAs === "followUp") {
|
|
1889
|
-
this.agent.followUp(appMessage);
|
|
1890
|
-
} else {
|
|
1891
|
-
this.agent.steer(appMessage);
|
|
1892
|
-
}
|
|
1893
|
-
} else if (options?.triggerTurn) {
|
|
1894
|
-
await this.agent.prompt(appMessage);
|
|
1895
|
-
} else {
|
|
1896
|
-
this.agent.state.messages = [...this.agent.state.messages, appMessage];
|
|
1897
|
-
this.sessionManager.appendCustomMessageEntry(
|
|
1898
|
-
message.customType,
|
|
1899
|
-
message.content,
|
|
1900
|
-
message.display,
|
|
1901
|
-
message.details,
|
|
1902
|
-
);
|
|
1903
|
-
this._emit({ type: "message_start", message: appMessage });
|
|
1904
|
-
this._emit({ type: "message_end", message: appMessage });
|
|
1905
|
-
}
|
|
1906
|
-
}
|
|
1907
|
-
|
|
1908
|
-
/**
|
|
1909
|
-
* Send a user message to the agent. Always triggers a turn.
|
|
1910
|
-
* When the agent is streaming, use deliverAs to specify how to queue the message.
|
|
1911
|
-
*
|
|
1912
|
-
* @param content User message content (string or content array)
|
|
1913
|
-
* @param options.deliverAs Delivery mode when streaming: "steer" or "followUp"
|
|
1914
|
-
*/
|
|
1915
|
-
async sendUserMessage(
|
|
1916
|
-
content: string | (TextContent | ImageContent)[],
|
|
1917
|
-
options?: { deliverAs?: "steer" | "followUp" },
|
|
1918
|
-
): Promise<void> {
|
|
1919
|
-
// Normalize content to text string + optional images
|
|
1920
|
-
let text: string;
|
|
1921
|
-
let images: ImageContent[] | undefined;
|
|
1922
|
-
|
|
1923
|
-
if (typeof content === "string") {
|
|
1924
|
-
text = content;
|
|
1925
|
-
} else {
|
|
1926
|
-
const textParts: string[] = [];
|
|
1927
|
-
images = [];
|
|
1928
|
-
for (const part of content) {
|
|
1929
|
-
if (part.type === "text") {
|
|
1930
|
-
textParts.push(part.text);
|
|
1931
|
-
} else {
|
|
1932
|
-
images.push(part);
|
|
1933
|
-
}
|
|
1934
|
-
}
|
|
1935
|
-
text = textParts.join("\n");
|
|
1936
|
-
if (images.length === 0) images = undefined;
|
|
1937
|
-
}
|
|
1938
|
-
|
|
1939
|
-
// Use prompt() with expandPromptTemplates: false to skip command handling and template expansion
|
|
1940
|
-
await this.prompt(text, {
|
|
1941
|
-
expandPromptTemplates: false,
|
|
1942
|
-
streamingBehavior: options?.deliverAs,
|
|
1943
|
-
images,
|
|
1944
|
-
source: "extension",
|
|
1945
|
-
});
|
|
1946
|
-
}
|
|
1947
|
-
|
|
1948
|
-
/**
|
|
1949
|
-
* Clear all queued messages and return them.
|
|
1950
|
-
* Useful for restoring to editor when user aborts.
|
|
1951
|
-
* @returns Object with steering and followUp arrays
|
|
1952
|
-
*/
|
|
1953
|
-
clearQueue(): { steering: string[]; followUp: string[] } {
|
|
1954
|
-
// In 0.67.2, drainUserMessages() was removed. Agent queues no longer distinguish
|
|
1955
|
-
// user-origin messages from system messages. Clear all queues and return
|
|
1956
|
-
// the session-tracked string arrays for display purposes.
|
|
1957
|
-
const steering = [...this._steeringMessages];
|
|
1958
|
-
const followUp = [...this._followUpMessages];
|
|
1959
|
-
this._steeringMessages = [];
|
|
1960
|
-
this._followUpMessages = [];
|
|
1961
|
-
|
|
1962
|
-
// Clear all agent queues
|
|
1963
|
-
this.agent.clearAllQueues();
|
|
1964
|
-
return { steering, followUp };
|
|
1965
|
-
}
|
|
1966
|
-
|
|
1967
|
-
/** Number of pending messages (includes both steering and follow-up) */
|
|
1968
|
-
get pendingMessageCount(): number {
|
|
1969
|
-
return this._steeringMessages.length + this._followUpMessages.length;
|
|
1970
|
-
}
|
|
1971
|
-
|
|
1972
|
-
/** Get pending steering messages (read-only) */
|
|
1973
|
-
getSteeringMessages(): readonly string[] {
|
|
1974
|
-
return this._steeringMessages;
|
|
1975
|
-
}
|
|
1976
|
-
|
|
1977
|
-
/** Get pending follow-up messages (read-only) */
|
|
1978
|
-
getFollowUpMessages(): readonly string[] {
|
|
1979
|
-
return this._followUpMessages;
|
|
1980
|
-
}
|
|
1981
|
-
|
|
1982
|
-
get resourceLoader(): ResourceLoader {
|
|
1983
|
-
return this._resourceLoader;
|
|
1984
|
-
}
|
|
1985
|
-
|
|
1986
|
-
/**
|
|
1987
|
-
* Abort current operation and wait for agent to become idle.
|
|
1988
|
-
*/
|
|
1989
|
-
async abort(): Promise<void> {
|
|
1990
|
-
this._retryHandler.abortRetry();
|
|
1991
|
-
this.agent.abort();
|
|
1992
|
-
await this.agent.waitForIdle();
|
|
1993
|
-
// Ensure agent_end is emitted even when abort interrupts a tool call (#1414).
|
|
1994
|
-
// The agent may go idle without emitting agent_end if the abort happens
|
|
1995
|
-
// between tool execution and response processing.
|
|
1996
|
-
if (!this.isStreaming && this._extensionRunner) {
|
|
1997
|
-
await this._extensionRunner.emit({
|
|
1998
|
-
type: "agent_end",
|
|
1999
|
-
messages: this.agent.state.messages,
|
|
2000
|
-
});
|
|
2001
|
-
}
|
|
2002
|
-
}
|
|
2003
|
-
|
|
2004
|
-
/**
|
|
2005
|
-
* Start a new session, optionally with initial messages and parent tracking.
|
|
2006
|
-
* Clears all messages and starts a new session.
|
|
2007
|
-
* Listeners are preserved and will continue receiving events.
|
|
2008
|
-
* @param options.parentSession - Optional parent session path for tracking
|
|
2009
|
-
* @param options.setup - Optional callback to initialize session (e.g., append messages)
|
|
2010
|
-
* @returns true if completed, false if cancelled by extension
|
|
2011
|
-
*/
|
|
2012
|
-
async newSession(options?: {
|
|
2013
|
-
parentSession?: string;
|
|
2014
|
-
setup?: (sessionManager: SessionManager) => Promise<void>;
|
|
2015
|
-
}): Promise<boolean> {
|
|
2016
|
-
// Snapshot state before transition so listeners and message queues survive (D-14).
|
|
2017
|
-
const snapshot = this._snapshotState();
|
|
2018
|
-
|
|
2019
|
-
const _previousSessionFile = this.sessionFile;
|
|
2020
|
-
|
|
2021
|
-
// Emit session_before_switch event with reason "new" (can be cancelled)
|
|
2022
|
-
if (this._extensionRunner?.hasHandlers("session_before_switch")) {
|
|
2023
|
-
const result = (await this._extensionRunner.emit({
|
|
2024
|
-
type: "session_before_switch",
|
|
2025
|
-
reason: "new",
|
|
2026
|
-
})) as SessionBeforeSwitchResult | undefined;
|
|
2027
|
-
|
|
2028
|
-
if (result?.cancel) {
|
|
2029
|
-
return false;
|
|
2030
|
-
}
|
|
2031
|
-
}
|
|
2032
|
-
|
|
2033
|
-
// Mutate sessionManager in place BEFORE calling the runtime so the factory
|
|
2034
|
-
// can call getSessionId() on the already-updated SM.
|
|
2035
|
-
this.sessionManager.newSession({ parentSession: options?.parentSession });
|
|
2036
|
-
this.sessionManager.appendThinkingLevelChange(this.thinkingLevel);
|
|
2037
|
-
|
|
2038
|
-
// #4243: Must call abort() BEFORE _disconnectFromAgent() so that
|
|
2039
|
-
// message_end/agent_end events fire and the #4216 finalization code
|
|
2040
|
-
// can run before we unsubscribe from the event bus.
|
|
2041
|
-
await this.abort();
|
|
2042
|
-
this._disconnectFromAgent();
|
|
2043
|
-
this.agent.reset();
|
|
2044
|
-
|
|
2045
|
-
// Delegate to AgentSessionRuntime for lifecycle coordination (D-12).
|
|
2046
|
-
// The factory (_createRuntimeFactory) re-initialises this session's internals
|
|
2047
|
-
// (cwd update, tool rebuild, agent reconnect, session_start emission).
|
|
2048
|
-
const runtime = await this._ensureRuntime();
|
|
2049
|
-
const result = await runtime.newSession({
|
|
2050
|
-
parentSession: options?.parentSession,
|
|
2051
|
-
setup: options?.setup,
|
|
2052
|
-
});
|
|
2053
|
-
|
|
2054
|
-
if (result.cancelled) {
|
|
2055
|
-
return false;
|
|
2056
|
-
}
|
|
2057
|
-
|
|
2058
|
-
// Restore listener and message queue state that survived the transition (D-14).
|
|
2059
|
-
this._restoreState(snapshot);
|
|
2060
|
-
|
|
2061
|
-
// Emit session event to custom tools
|
|
2062
|
-
this._emitSessionStateChanged("new_session");
|
|
2063
|
-
return true;
|
|
2064
|
-
}
|
|
2065
|
-
|
|
2066
|
-
// =========================================================================
|
|
2067
|
-
// Model Management
|
|
2068
|
-
// =========================================================================
|
|
2069
|
-
|
|
2070
|
-
private async _emitModelSelect(
|
|
2071
|
-
nextModel: Model<Api>,
|
|
2072
|
-
previousModel: Model<Api> | undefined,
|
|
2073
|
-
source: "set" | "cycle" | "restore",
|
|
2074
|
-
): Promise<void> {
|
|
2075
|
-
if (!this._extensionRunner) return;
|
|
2076
|
-
if (modelsAreEqual(previousModel, nextModel)) return;
|
|
2077
|
-
await this._extensionRunner.emit({
|
|
2078
|
-
type: "model_select",
|
|
2079
|
-
model: nextModel,
|
|
2080
|
-
previousModel,
|
|
2081
|
-
source,
|
|
2082
|
-
});
|
|
2083
|
-
}
|
|
2084
|
-
|
|
2085
|
-
/**
|
|
2086
|
-
* Apply a model change: set the model on the agent, persist to session/settings,
|
|
2087
|
-
* re-clamp thinking level, and emit the model_select event.
|
|
2088
|
-
*/
|
|
2089
|
-
private async _applyModelChange(
|
|
2090
|
-
model: Model<Api>,
|
|
2091
|
-
thinkingLevel: ThinkingLevel,
|
|
2092
|
-
source: "set" | "cycle" | "restore",
|
|
2093
|
-
options?: { persist?: boolean },
|
|
2094
|
-
): Promise<void> {
|
|
2095
|
-
const previousModel = this.model;
|
|
2096
|
-
// Explicit model switches must cancel any in-flight retry loop from the
|
|
2097
|
-
// previous provider/model. Otherwise stale provider backoff errors can
|
|
2098
|
-
// continue to land after the user or runtime has already switched models.
|
|
2099
|
-
this._retryHandler.abortRetry();
|
|
2100
|
-
this.agent.state.model = model;
|
|
2101
|
-
this.sessionManager.appendModelChange(model.provider, model.id);
|
|
2102
|
-
if (options?.persist !== false) {
|
|
2103
|
-
this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
|
|
2104
|
-
}
|
|
2105
|
-
this.setThinkingLevel(thinkingLevel);
|
|
2106
|
-
await this._emitModelSelect(model, previousModel, source);
|
|
2107
|
-
this._emitSessionStateChanged("set_model");
|
|
2108
|
-
}
|
|
2109
|
-
|
|
2110
|
-
/**
|
|
2111
|
-
* Set model directly.
|
|
2112
|
-
* Validates provider readiness, saves to session and settings.
|
|
2113
|
-
* @throws Error if provider is not ready (missing credentials for apiKey/oauth providers)
|
|
2114
|
-
*/
|
|
2115
|
-
async setModel(model: Model<Api>, options?: { persist?: boolean }): Promise<void> {
|
|
2116
|
-
if (!this._modelRegistry.isProviderRequestReady(model.provider)) {
|
|
2117
|
-
throw new Error(`No API key for ${model.provider}/${model.id}`);
|
|
2118
|
-
}
|
|
2119
|
-
|
|
2120
|
-
const thinkingLevel = this._getThinkingLevelForModelSwitch();
|
|
2121
|
-
await this._applyModelChange(model, thinkingLevel, "set", options);
|
|
2122
|
-
}
|
|
2123
|
-
|
|
2124
|
-
/**
|
|
2125
|
-
* Cycle to next/previous model.
|
|
2126
|
-
* Uses scoped models (from --models flag) if available, otherwise all available models.
|
|
2127
|
-
* @param direction - "forward" (default) or "backward"
|
|
2128
|
-
* @returns The new model info, or undefined if only one model available
|
|
2129
|
-
*/
|
|
2130
|
-
async cycleModel(direction: "forward" | "backward" = "forward", options?: { persist?: boolean }): Promise<ModelCycleResult | undefined> {
|
|
2131
|
-
if (this._scopedModels.length > 0) {
|
|
2132
|
-
return this._cycleScopedModel(direction, options);
|
|
2133
|
-
}
|
|
2134
|
-
return this._cycleAvailableModel(direction, options);
|
|
2135
|
-
}
|
|
2136
|
-
|
|
2137
|
-
private _getReadyScopedModels(): Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }> {
|
|
2138
|
-
return this._scopedModels.filter((scoped) =>
|
|
2139
|
-
this._modelRegistry.isProviderRequestReady(scoped.model.provider),
|
|
2140
|
-
);
|
|
2141
|
-
}
|
|
2142
|
-
|
|
2143
|
-
private async _cycleScopedModel(direction: "forward" | "backward", options?: { persist?: boolean }): Promise<ModelCycleResult | undefined> {
|
|
2144
|
-
const scopedModels = this._getReadyScopedModels();
|
|
2145
|
-
if (scopedModels.length <= 1) return undefined;
|
|
2146
|
-
|
|
2147
|
-
const currentModel = this.model;
|
|
2148
|
-
let currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));
|
|
2149
|
-
|
|
2150
|
-
if (currentIndex === -1) currentIndex = 0;
|
|
2151
|
-
const len = scopedModels.length;
|
|
2152
|
-
const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
|
|
2153
|
-
const next = scopedModels[nextIndex];
|
|
2154
|
-
|
|
2155
|
-
// Explicit scoped model thinking level overrides current session level;
|
|
2156
|
-
// undefined scoped model thinking level inherits the current session preference.
|
|
2157
|
-
const thinkingLevel = this._getThinkingLevelForModelSwitch(next.thinkingLevel);
|
|
2158
|
-
await this._applyModelChange(next.model, thinkingLevel, "cycle", options);
|
|
2159
|
-
|
|
2160
|
-
return { model: next.model, thinkingLevel: this.thinkingLevel, isScoped: true };
|
|
2161
|
-
}
|
|
2162
|
-
|
|
2163
|
-
private async _cycleAvailableModel(direction: "forward" | "backward", options?: { persist?: boolean }): Promise<ModelCycleResult | undefined> {
|
|
2164
|
-
const availableModels = await this._modelRegistry.getAvailable();
|
|
2165
|
-
if (availableModels.length <= 1) return undefined;
|
|
2166
|
-
|
|
2167
|
-
const currentModel = this.model;
|
|
2168
|
-
let currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));
|
|
2169
|
-
|
|
2170
|
-
if (currentIndex === -1) currentIndex = 0;
|
|
2171
|
-
const len = availableModels.length;
|
|
2172
|
-
const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
|
|
2173
|
-
const nextModel = availableModels[nextIndex];
|
|
2174
|
-
|
|
2175
|
-
const thinkingLevel = this._getThinkingLevelForModelSwitch();
|
|
2176
|
-
await this._applyModelChange(nextModel, thinkingLevel, "cycle", options);
|
|
2177
|
-
|
|
2178
|
-
return { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };
|
|
2179
|
-
}
|
|
2180
|
-
|
|
2181
|
-
// =========================================================================
|
|
2182
|
-
// Thinking Level Management
|
|
2183
|
-
// =========================================================================
|
|
2184
|
-
|
|
2185
|
-
/**
|
|
2186
|
-
* Set thinking level.
|
|
2187
|
-
* Clamps to model capabilities based on available thinking levels.
|
|
2188
|
-
* Saves to session and settings only if the level actually changes.
|
|
2189
|
-
*/
|
|
2190
|
-
setThinkingLevel(level: ThinkingLevel): void {
|
|
2191
|
-
const availableLevels = this.getAvailableThinkingLevels();
|
|
2192
|
-
const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
|
|
2193
|
-
|
|
2194
|
-
// Only persist if actually changing
|
|
2195
|
-
const isChanging = effectiveLevel !== this.agent.state.thinkingLevel;
|
|
2196
|
-
|
|
2197
|
-
this.agent.state.thinkingLevel = effectiveLevel;
|
|
2198
|
-
|
|
2199
|
-
if (isChanging) {
|
|
2200
|
-
this.sessionManager.appendThinkingLevelChange(effectiveLevel);
|
|
2201
|
-
if (this.supportsThinking() || effectiveLevel !== "off") {
|
|
2202
|
-
this.settingsManager.setDefaultThinkingLevel(effectiveLevel);
|
|
2203
|
-
}
|
|
2204
|
-
this._emitSessionStateChanged("set_thinking_level");
|
|
2205
|
-
}
|
|
2206
|
-
}
|
|
2207
|
-
|
|
2208
|
-
/**
|
|
2209
|
-
* Cycle to next thinking level.
|
|
2210
|
-
* @returns New level, or undefined if model doesn't support thinking
|
|
2211
|
-
*/
|
|
2212
|
-
cycleThinkingLevel(): ThinkingLevel | undefined {
|
|
2213
|
-
if (!this.supportsThinking()) return undefined;
|
|
2214
|
-
|
|
2215
|
-
const levels = this.getAvailableThinkingLevels();
|
|
2216
|
-
const currentIndex = levels.indexOf(this.thinkingLevel);
|
|
2217
|
-
const nextIndex = (currentIndex + 1) % levels.length;
|
|
2218
|
-
const nextLevel = levels[nextIndex];
|
|
2219
|
-
|
|
2220
|
-
this.setThinkingLevel(nextLevel);
|
|
2221
|
-
return nextLevel;
|
|
2222
|
-
}
|
|
2223
|
-
|
|
2224
|
-
/**
|
|
2225
|
-
* Get available thinking levels for current model.
|
|
2226
|
-
* The provider will clamp to what the specific model supports internally.
|
|
2227
|
-
*/
|
|
2228
|
-
getAvailableThinkingLevels(): ThinkingLevel[] {
|
|
2229
|
-
if (!this.supportsThinking()) return ["off"];
|
|
2230
|
-
return this.supportsXhighThinking() ? THINKING_LEVELS_WITH_XHIGH : THINKING_LEVELS;
|
|
2231
|
-
}
|
|
2232
|
-
|
|
2233
|
-
/**
|
|
2234
|
-
* Check if current model supports xhigh thinking level.
|
|
2235
|
-
*/
|
|
2236
|
-
supportsXhighThinking(): boolean {
|
|
2237
|
-
return this.model ? supportsXhigh(this.model) : false;
|
|
2238
|
-
}
|
|
2239
|
-
|
|
2240
|
-
/**
|
|
2241
|
-
* Check if current model supports thinking/reasoning.
|
|
2242
|
-
*/
|
|
2243
|
-
supportsThinking(): boolean {
|
|
2244
|
-
return !!this.model?.reasoning;
|
|
2245
|
-
}
|
|
2246
|
-
|
|
2247
|
-
private _getThinkingLevelForModelSwitch(explicitLevel?: ThinkingLevel): ThinkingLevel {
|
|
2248
|
-
if (explicitLevel !== undefined) {
|
|
2249
|
-
return explicitLevel;
|
|
2250
|
-
}
|
|
2251
|
-
if (!this.supportsThinking()) {
|
|
2252
|
-
return this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
|
|
2253
|
-
}
|
|
2254
|
-
return this.thinkingLevel;
|
|
2255
|
-
}
|
|
2256
|
-
|
|
2257
|
-
private _clampThinkingLevel(level: ThinkingLevel, availableLevels: ThinkingLevel[]): ThinkingLevel {
|
|
2258
|
-
const ordered = THINKING_LEVELS_WITH_XHIGH;
|
|
2259
|
-
const available = new Set(availableLevels);
|
|
2260
|
-
const requestedIndex = ordered.indexOf(level);
|
|
2261
|
-
if (requestedIndex === -1) {
|
|
2262
|
-
return availableLevels[0] ?? "off";
|
|
2263
|
-
}
|
|
2264
|
-
for (let i = requestedIndex; i < ordered.length; i++) {
|
|
2265
|
-
const candidate = ordered[i];
|
|
2266
|
-
if (available.has(candidate)) return candidate;
|
|
2267
|
-
}
|
|
2268
|
-
for (let i = requestedIndex - 1; i >= 0; i--) {
|
|
2269
|
-
const candidate = ordered[i];
|
|
2270
|
-
if (available.has(candidate)) return candidate;
|
|
2271
|
-
}
|
|
2272
|
-
return availableLevels[0] ?? "off";
|
|
2273
|
-
}
|
|
2274
|
-
|
|
2275
|
-
// =========================================================================
|
|
2276
|
-
// Queue Mode Management
|
|
2277
|
-
// =========================================================================
|
|
2278
|
-
|
|
2279
|
-
/**
|
|
2280
|
-
* Set steering message mode.
|
|
2281
|
-
* Saves to settings.
|
|
2282
|
-
*/
|
|
2283
|
-
setSteeringMode(mode: "all" | "one-at-a-time"): void {
|
|
2284
|
-
this.agent.setSteeringMode(mode);
|
|
2285
|
-
this.settingsManager.setSteeringMode(mode);
|
|
2286
|
-
this._emitSessionStateChanged("set_steering_mode");
|
|
2287
|
-
}
|
|
2288
|
-
|
|
2289
|
-
/**
|
|
2290
|
-
* Set follow-up message mode.
|
|
2291
|
-
* Saves to settings.
|
|
2292
|
-
*/
|
|
2293
|
-
setFollowUpMode(mode: "all" | "one-at-a-time"): void {
|
|
2294
|
-
this.agent.setFollowUpMode(mode);
|
|
2295
|
-
this.settingsManager.setFollowUpMode(mode);
|
|
2296
|
-
this._emitSessionStateChanged("set_follow_up_mode");
|
|
2297
|
-
}
|
|
2298
|
-
|
|
2299
|
-
// =========================================================================
|
|
2300
|
-
// Compaction
|
|
2301
|
-
// =========================================================================
|
|
2302
|
-
|
|
2303
|
-
/**
|
|
2304
|
-
* Manually compact the session context.
|
|
2305
|
-
* Aborts current agent operation first.
|
|
2306
|
-
* @param customInstructions Optional instructions for the compaction summary
|
|
2307
|
-
*/
|
|
2308
|
-
async compact(customInstructions?: string): Promise<CompactionResult> {
|
|
2309
|
-
return this._compactionOrchestrator.compact(customInstructions);
|
|
2310
|
-
}
|
|
2311
|
-
|
|
2312
|
-
/** Cancel in-progress compaction (manual or auto) */
|
|
2313
|
-
abortCompaction(): void {
|
|
2314
|
-
this._compactionOrchestrator.abortCompaction();
|
|
2315
|
-
}
|
|
2316
|
-
|
|
2317
|
-
/** Cancel in-progress branch summarization */
|
|
2318
|
-
abortBranchSummary(): void {
|
|
2319
|
-
this._compactionOrchestrator.abortBranchSummary();
|
|
2320
|
-
}
|
|
2321
|
-
|
|
2322
|
-
/** Toggle auto-compaction setting */
|
|
2323
|
-
setAutoCompactionEnabled(enabled: boolean): void {
|
|
2324
|
-
this._compactionOrchestrator.setAutoCompactionEnabled(enabled);
|
|
2325
|
-
this._emitSessionStateChanged("set_auto_compaction");
|
|
2326
|
-
}
|
|
2327
|
-
|
|
2328
|
-
/** Whether auto-compaction is enabled */
|
|
2329
|
-
get autoCompactionEnabled(): boolean {
|
|
2330
|
-
return this._compactionOrchestrator.autoCompactionEnabled;
|
|
2331
|
-
}
|
|
2332
|
-
|
|
2333
|
-
async bindExtensions(bindings: ExtensionBindings): Promise<void> {
|
|
2334
|
-
if (bindings.uiContext !== undefined) {
|
|
2335
|
-
this._extensionUIContext = bindings.uiContext;
|
|
2336
|
-
}
|
|
2337
|
-
if (bindings.commandContextActions !== undefined) {
|
|
2338
|
-
this._extensionCommandContextActions = bindings.commandContextActions;
|
|
2339
|
-
}
|
|
2340
|
-
if (bindings.shutdownHandler !== undefined) {
|
|
2341
|
-
this._extensionShutdownHandler = bindings.shutdownHandler;
|
|
2342
|
-
}
|
|
2343
|
-
if (bindings.onError !== undefined) {
|
|
2344
|
-
this._extensionErrorListener = bindings.onError;
|
|
2345
|
-
}
|
|
2346
|
-
|
|
2347
|
-
if (this._extensionRunner) {
|
|
2348
|
-
this._applyExtensionBindings(this._extensionRunner);
|
|
2349
|
-
await this._extensionRunner.emit({ type: "session_start", reason: "new" });
|
|
2350
|
-
await this.extendResourcesFromExtensions("startup");
|
|
2351
|
-
}
|
|
2352
|
-
}
|
|
2353
|
-
|
|
2354
|
-
private async extendResourcesFromExtensions(reason: "startup" | "reload"): Promise<void> {
|
|
2355
|
-
if (!this._extensionRunner?.hasHandlers("resources_discover")) {
|
|
2356
|
-
return;
|
|
2357
|
-
}
|
|
2358
|
-
|
|
2359
|
-
const { skillPaths, promptPaths, themePaths } = await this._extensionRunner.emitResourcesDiscover(
|
|
2360
|
-
this._cwd,
|
|
2361
|
-
reason,
|
|
2362
|
-
);
|
|
2363
|
-
|
|
2364
|
-
if (skillPaths.length === 0 && promptPaths.length === 0 && themePaths.length === 0) {
|
|
2365
|
-
return;
|
|
2366
|
-
}
|
|
2367
|
-
|
|
2368
|
-
const extensionPaths: ResourceExtensionPaths = {
|
|
2369
|
-
skillPaths: this.buildExtensionResourcePaths(skillPaths),
|
|
2370
|
-
promptPaths: this.buildExtensionResourcePaths(promptPaths),
|
|
2371
|
-
themePaths: this.buildExtensionResourcePaths(themePaths),
|
|
2372
|
-
};
|
|
2373
|
-
|
|
2374
|
-
this._resourceLoader.extendResources(extensionPaths);
|
|
2375
|
-
this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());
|
|
2376
|
-
this.agent.state.systemPrompt = this._baseSystemPrompt;
|
|
2377
|
-
}
|
|
2378
|
-
|
|
2379
|
-
private buildExtensionResourcePaths(entries: Array<{ path: string; extensionPath: string }>): Array<{
|
|
2380
|
-
path: string;
|
|
2381
|
-
metadata: { source: string; scope: "temporary"; origin: "top-level"; baseDir?: string };
|
|
2382
|
-
}> {
|
|
2383
|
-
return entries.map((entry) => {
|
|
2384
|
-
const source = this.getExtensionSourceLabel(entry.extensionPath);
|
|
2385
|
-
const baseDir = entry.extensionPath.startsWith("<") ? undefined : dirname(entry.extensionPath);
|
|
2386
|
-
return {
|
|
2387
|
-
path: entry.path,
|
|
2388
|
-
metadata: {
|
|
2389
|
-
source,
|
|
2390
|
-
scope: "temporary",
|
|
2391
|
-
origin: "top-level",
|
|
2392
|
-
baseDir,
|
|
2393
|
-
},
|
|
2394
|
-
};
|
|
2395
|
-
});
|
|
2396
|
-
}
|
|
2397
|
-
|
|
2398
|
-
private getExtensionSourceLabel(extensionPath: string): string {
|
|
2399
|
-
if (extensionPath.startsWith("<")) {
|
|
2400
|
-
return `extension:${extensionPath.replace(/[<>]/g, "")}`;
|
|
2401
|
-
}
|
|
2402
|
-
const base = basename(extensionPath);
|
|
2403
|
-
const name = base.replace(/\.(ts|js)$/, "");
|
|
2404
|
-
return `extension:${name}`;
|
|
2405
|
-
}
|
|
2406
|
-
|
|
2407
|
-
private _applyExtensionBindings(runner: ExtensionRunner): void {
|
|
2408
|
-
runner.setUIContext(this._extensionUIContext);
|
|
2409
|
-
runner.bindCommandContext(this._extensionCommandContextActions);
|
|
2410
|
-
|
|
2411
|
-
try {
|
|
2412
|
-
this._extensionErrorUnsubscriber?.();
|
|
2413
|
-
} catch {
|
|
2414
|
-
// Ignore errors from previous unsubscriber
|
|
2415
|
-
}
|
|
2416
|
-
this._extensionErrorUnsubscriber = this._extensionErrorListener
|
|
2417
|
-
? runner.onError(this._extensionErrorListener)
|
|
2418
|
-
: undefined;
|
|
2419
|
-
}
|
|
2420
|
-
|
|
2421
|
-
private _bindExtensionCore(runner: ExtensionRunner): void {
|
|
2422
|
-
const reservedBuiltins = new Set(BUILTIN_SLASH_COMMANDS.map((command) => command.name));
|
|
2423
|
-
|
|
2424
|
-
const getCommands = (): SlashCommandInfo[] => {
|
|
2425
|
-
const extensionCommands: SlashCommandInfo[] = runner
|
|
2426
|
-
.getRegisteredCommands()
|
|
2427
|
-
.filter((command) => !reservedBuiltins.has(command.name))
|
|
2428
|
-
.map((command) => ({
|
|
2429
|
-
name: command.name,
|
|
2430
|
-
description: command.description,
|
|
2431
|
-
source: "extension" as const,
|
|
2432
|
-
sourceInfo: (command as { sourceInfo?: unknown }).sourceInfo,
|
|
2433
|
-
}));
|
|
2434
|
-
|
|
2435
|
-
const templates: SlashCommandInfo[] = this.promptTemplates.map((template) => ({
|
|
2436
|
-
name: template.name,
|
|
2437
|
-
description: template.description,
|
|
2438
|
-
source: "prompt" as const,
|
|
2439
|
-
sourceInfo: (template as { sourceInfo?: unknown }).sourceInfo,
|
|
2440
|
-
}));
|
|
2441
|
-
|
|
2442
|
-
const skills: SlashCommandInfo[] = this._resourceLoader.getSkills().skills.map((skill) => ({
|
|
2443
|
-
name: `skill:${skill.name}`,
|
|
2444
|
-
description: skill.description,
|
|
2445
|
-
source: "skill" as const,
|
|
2446
|
-
sourceInfo: (skill as { sourceInfo?: unknown }).sourceInfo,
|
|
2447
|
-
}));
|
|
2448
|
-
|
|
2449
|
-
return [...extensionCommands, ...templates, ...skills];
|
|
2450
|
-
};
|
|
2451
|
-
|
|
2452
|
-
runner.bindCore(
|
|
2453
|
-
{
|
|
2454
|
-
sendMessage: (message, options) => {
|
|
2455
|
-
this.sendCustomMessage(message, options).catch((err) => {
|
|
2456
|
-
runner.emitError({
|
|
2457
|
-
extensionPath: "<runtime>",
|
|
2458
|
-
event: "send_message",
|
|
2459
|
-
error: getErrorMessage(err),
|
|
2460
|
-
});
|
|
2461
|
-
});
|
|
2462
|
-
},
|
|
2463
|
-
sendUserMessage: (content, options) => {
|
|
2464
|
-
this.sendUserMessage(content, options).catch((err) => {
|
|
2465
|
-
runner.emitError({
|
|
2466
|
-
extensionPath: "<runtime>",
|
|
2467
|
-
event: "send_user_message",
|
|
2468
|
-
error: getErrorMessage(err),
|
|
2469
|
-
});
|
|
2470
|
-
});
|
|
2471
|
-
},
|
|
2472
|
-
appendEntry: (customType, data) => {
|
|
2473
|
-
this.sessionManager.appendCustomEntry(customType, data);
|
|
2474
|
-
},
|
|
2475
|
-
setSessionName: (name) => {
|
|
2476
|
-
this.sessionManager.appendSessionInfo(name);
|
|
2477
|
-
},
|
|
2478
|
-
getSessionName: () => {
|
|
2479
|
-
return this.sessionManager.getSessionName();
|
|
2480
|
-
},
|
|
2481
|
-
setLabel: (entryId, label) => {
|
|
2482
|
-
this.sessionManager.appendLabelChange(entryId, label);
|
|
2483
|
-
},
|
|
2484
|
-
getActiveTools: () => this.getActiveToolNames(),
|
|
2485
|
-
getAllTools: () => this.getAllTools(),
|
|
2486
|
-
setActiveTools: (toolNames) => this.setActiveToolsByName(toolNames),
|
|
2487
|
-
refreshTools: () => this._refreshToolRegistry(),
|
|
2488
|
-
getCommands,
|
|
2489
|
-
setModel: async (model) => {
|
|
2490
|
-
if (!(this.modelRegistry as ModelRegistryWithReadiness).isProviderRequestReady(model.provider)) return false;
|
|
2491
|
-
await this.setModel(model);
|
|
2492
|
-
return true;
|
|
2493
|
-
},
|
|
2494
|
-
getThinkingLevel: () => this.thinkingLevel,
|
|
2495
|
-
setThinkingLevel: (level) => this.setThinkingLevel(level),
|
|
2496
|
-
retryLastTurn: () => {
|
|
2497
|
-
void this.agent.continue();
|
|
2498
|
-
},
|
|
2499
|
-
},
|
|
2500
|
-
{
|
|
2501
|
-
getModel: () => this.model,
|
|
2502
|
-
isIdle: () => !this.isStreaming,
|
|
2503
|
-
abort: () => this.abort(),
|
|
2504
|
-
hasPendingMessages: () => this.pendingMessageCount > 0,
|
|
2505
|
-
shutdown: () => {
|
|
2506
|
-
this._extensionShutdownHandler?.();
|
|
2507
|
-
},
|
|
2508
|
-
getContextUsage: () => this.getContextUsage(),
|
|
2509
|
-
compact: (options) => {
|
|
2510
|
-
void (async () => {
|
|
2511
|
-
try {
|
|
2512
|
-
const result = await this.compact(options?.customInstructions);
|
|
2513
|
-
options?.onComplete?.(result);
|
|
2514
|
-
} catch (error) {
|
|
2515
|
-
const err = error instanceof Error ? error : new Error(String(error));
|
|
2516
|
-
options?.onError?.(err);
|
|
2517
|
-
}
|
|
2518
|
-
})();
|
|
2519
|
-
},
|
|
2520
|
-
getSystemPrompt: () => this.systemPrompt,
|
|
2521
|
-
},
|
|
2522
|
-
);
|
|
2523
|
-
}
|
|
2524
|
-
|
|
2525
|
-
private _refreshToolRegistry(options?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean }): void {
|
|
2526
|
-
const previousRegistryNames = new Set(this._toolRegistry.keys());
|
|
2527
|
-
const previousActiveToolNames = this.getActiveToolNames();
|
|
2528
|
-
|
|
2529
|
-
const registeredTools = this._extensionRunner?.getAllRegisteredTools() ?? [];
|
|
2530
|
-
const allCustomTools = [
|
|
2531
|
-
...registeredTools,
|
|
2532
|
-
...this._customTools.map((def) => ({
|
|
2533
|
-
definition: def,
|
|
2534
|
-
extensionPath: "<sdk>",
|
|
2535
|
-
})),
|
|
2536
|
-
];
|
|
2537
|
-
this._toolPromptSnippets = new Map(
|
|
2538
|
-
allCustomTools
|
|
2539
|
-
.map((registeredTool) => {
|
|
2540
|
-
const snippet = this._normalizePromptSnippet(
|
|
2541
|
-
registeredTool.definition.promptSnippet ?? registeredTool.definition.description,
|
|
2542
|
-
);
|
|
2543
|
-
return snippet ? ([registeredTool.definition.name, snippet] as const) : undefined;
|
|
2544
|
-
})
|
|
2545
|
-
.filter((entry): entry is readonly [string, string] => entry !== undefined),
|
|
2546
|
-
);
|
|
2547
|
-
this._toolPromptGuidelines = new Map(
|
|
2548
|
-
allCustomTools
|
|
2549
|
-
.map((registeredTool) => {
|
|
2550
|
-
const guidelines = this._normalizePromptGuidelines(registeredTool.definition.promptGuidelines);
|
|
2551
|
-
return guidelines.length > 0 ? ([registeredTool.definition.name, guidelines] as const) : undefined;
|
|
2552
|
-
})
|
|
2553
|
-
.filter((entry): entry is readonly [string, string[]] => entry !== undefined),
|
|
2554
|
-
);
|
|
2555
|
-
const wrappedExtensionTools = this._extensionRunner
|
|
2556
|
-
? wrapRegisteredTools(allCustomTools, this._extensionRunner)
|
|
2557
|
-
: [];
|
|
2558
|
-
const builtinTools = this._getBuiltinTools();
|
|
2559
|
-
|
|
2560
|
-
const toolRegistry = new Map(this._baseToolRegistry);
|
|
2561
|
-
for (const tool of builtinTools) {
|
|
2562
|
-
toolRegistry.set(tool.name, tool);
|
|
2563
|
-
}
|
|
2564
|
-
for (const tool of wrappedExtensionTools as AgentTool[]) {
|
|
2565
|
-
toolRegistry.set(tool.name, tool);
|
|
2566
|
-
}
|
|
2567
|
-
|
|
2568
|
-
// Tool interception (tool_call/tool_result extension events) is handled by
|
|
2569
|
-
// beforeToolCall/afterToolCall hooks installed in _installAgentToolHooks(),
|
|
2570
|
-
// which await _agentEventQueue for safe parallel execution.
|
|
2571
|
-
this._toolRegistry = toolRegistry;
|
|
2572
|
-
|
|
2573
|
-
const nextActiveToolNames = options?.activeToolNames
|
|
2574
|
-
? [...options.activeToolNames]
|
|
2575
|
-
: [...previousActiveToolNames];
|
|
2576
|
-
|
|
2577
|
-
if (options?.includeAllExtensionTools) {
|
|
2578
|
-
for (const tool of wrappedExtensionTools) {
|
|
2579
|
-
nextActiveToolNames.push(tool.name);
|
|
2580
|
-
}
|
|
2581
|
-
} else if (!options?.activeToolNames) {
|
|
2582
|
-
for (const toolName of this._toolRegistry.keys()) {
|
|
2583
|
-
if (!previousRegistryNames.has(toolName)) {
|
|
2584
|
-
nextActiveToolNames.push(toolName);
|
|
2585
|
-
}
|
|
2586
|
-
}
|
|
2587
|
-
}
|
|
2588
|
-
|
|
2589
|
-
this.setActiveToolsByName([...new Set(nextActiveToolNames)]);
|
|
2590
|
-
}
|
|
2591
|
-
|
|
2592
|
-
private _buildRuntime(options: {
|
|
2593
|
-
activeToolNames?: string[];
|
|
2594
|
-
flagValues?: Map<string, boolean | string>;
|
|
2595
|
-
includeAllExtensionTools?: boolean;
|
|
2596
|
-
}): void {
|
|
2597
|
-
const autoResizeImages = this.settingsManager.getImageAutoResize();
|
|
2598
|
-
const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
|
|
2599
|
-
const baseTools = this._baseToolsOverride
|
|
2600
|
-
? this._baseToolsOverride
|
|
2601
|
-
: createAllTools(this._cwd, {
|
|
2602
|
-
read: { autoResizeImages },
|
|
2603
|
-
bash: {
|
|
2604
|
-
commandPrefix: shellCommandPrefix,
|
|
2605
|
-
},
|
|
2606
|
-
});
|
|
2607
|
-
|
|
2608
|
-
this._baseToolRegistry = new Map(Object.entries(baseTools).map(([name, tool]) => [name, tool as AgentTool]));
|
|
2609
|
-
|
|
2610
|
-
const extensionsResult = this._resourceLoader.getExtensions();
|
|
2611
|
-
if (options.flagValues) {
|
|
2612
|
-
for (const [name, value] of options.flagValues) {
|
|
2613
|
-
extensionsResult.runtime.flagValues.set(name, value);
|
|
2614
|
-
}
|
|
2615
|
-
}
|
|
2616
|
-
|
|
2617
|
-
const hasExtensions = extensionsResult.extensions.length > 0;
|
|
2618
|
-
const hasCustomTools = this._customTools.length > 0;
|
|
2619
|
-
this._extensionRunner =
|
|
2620
|
-
hasExtensions || hasCustomTools
|
|
2621
|
-
? new ExtensionRunner(
|
|
2622
|
-
extensionsResult.extensions,
|
|
2623
|
-
extensionsResult.runtime,
|
|
2624
|
-
this._cwd,
|
|
2625
|
-
this.sessionManager,
|
|
2626
|
-
this._modelRegistry,
|
|
2627
|
-
)
|
|
2628
|
-
: undefined;
|
|
2629
|
-
if (this._extensionRunnerRef) {
|
|
2630
|
-
this._extensionRunnerRef.current = this._extensionRunner;
|
|
2631
|
-
}
|
|
2632
|
-
if (this._extensionRunner) {
|
|
2633
|
-
this._bindExtensionCore(this._extensionRunner);
|
|
2634
|
-
this._applyExtensionBindings(this._extensionRunner);
|
|
2635
|
-
}
|
|
2636
|
-
|
|
2637
|
-
const defaultActiveToolNames = this._baseToolsOverride
|
|
2638
|
-
? Object.keys(this._baseToolsOverride)
|
|
2639
|
-
: ["read", "bash", "edit", "write", "lsp"];
|
|
2640
|
-
const baseActiveToolNames = options.activeToolNames ?? defaultActiveToolNames;
|
|
2641
|
-
this._refreshToolRegistry({
|
|
2642
|
-
activeToolNames: baseActiveToolNames,
|
|
2643
|
-
includeAllExtensionTools: options.includeAllExtensionTools,
|
|
2644
|
-
});
|
|
2645
|
-
}
|
|
2646
|
-
|
|
2647
|
-
async reload(): Promise<void> {
|
|
2648
|
-
const previousFlagValues = this._extensionRunner?.getFlagValues();
|
|
2649
|
-
await this._extensionRunner?.emit({ type: "session_shutdown" });
|
|
2650
|
-
this.settingsManager.reload();
|
|
2651
|
-
resetApiProviders();
|
|
2652
|
-
await this._resourceLoader.reload();
|
|
2653
|
-
this._buildRuntime({
|
|
2654
|
-
activeToolNames: this.getActiveToolNames(),
|
|
2655
|
-
flagValues: previousFlagValues,
|
|
2656
|
-
includeAllExtensionTools: true,
|
|
2657
|
-
});
|
|
2658
|
-
|
|
2659
|
-
const hasBindings =
|
|
2660
|
-
this._extensionUIContext ||
|
|
2661
|
-
this._extensionCommandContextActions ||
|
|
2662
|
-
this._extensionShutdownHandler ||
|
|
2663
|
-
this._extensionErrorListener;
|
|
2664
|
-
if (this._extensionRunner && hasBindings) {
|
|
2665
|
-
await this._extensionRunner.emit({ type: "session_start", reason: "resume" });
|
|
2666
|
-
await this.extendResourcesFromExtensions("reload");
|
|
2667
|
-
}
|
|
2668
|
-
}
|
|
2669
|
-
|
|
2670
|
-
// =========================================================================
|
|
2671
|
-
// Auto-Retry (delegated to RetryHandler)
|
|
2672
|
-
// =========================================================================
|
|
2673
|
-
|
|
2674
|
-
/** Cancel in-progress retry */
|
|
2675
|
-
abortRetry(): void {
|
|
2676
|
-
const hadRetry = this._retryHandler.isRetrying;
|
|
2677
|
-
this._retryHandler.abortRetry();
|
|
2678
|
-
if (hadRetry) {
|
|
2679
|
-
this._emitSessionStateChanged("abort_retry");
|
|
2680
|
-
}
|
|
2681
|
-
}
|
|
2682
|
-
|
|
2683
|
-
/** Whether auto-retry is currently in progress */
|
|
2684
|
-
get isRetrying(): boolean {
|
|
2685
|
-
return this._retryHandler.isRetrying;
|
|
2686
|
-
}
|
|
2687
|
-
|
|
2688
|
-
/** Whether auto-retry is enabled */
|
|
2689
|
-
get autoRetryEnabled(): boolean {
|
|
2690
|
-
return this._retryHandler.autoRetryEnabled;
|
|
2691
|
-
}
|
|
2692
|
-
|
|
2693
|
-
/** Toggle auto-retry setting */
|
|
2694
|
-
setAutoRetryEnabled(enabled: boolean): void {
|
|
2695
|
-
this._retryHandler.setAutoRetryEnabled(enabled);
|
|
2696
|
-
this._emitSessionStateChanged("set_auto_retry");
|
|
2697
|
-
}
|
|
2698
|
-
|
|
2699
|
-
// =========================================================================
|
|
2700
|
-
// Bash Execution
|
|
2701
|
-
// =========================================================================
|
|
2702
|
-
|
|
2703
|
-
/**
|
|
2704
|
-
* Execute a bash command.
|
|
2705
|
-
* Adds result to agent context and session.
|
|
2706
|
-
* @param command The bash command to execute
|
|
2707
|
-
* @param onChunk Optional streaming callback for output
|
|
2708
|
-
* @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)
|
|
2709
|
-
* @param options.operations Custom BashOperations for remote execution
|
|
2710
|
-
*/
|
|
2711
|
-
async executeBash(
|
|
2712
|
-
command: string,
|
|
2713
|
-
onChunk?: (chunk: string) => void,
|
|
2714
|
-
options?: { excludeFromContext?: boolean; operations?: BashOperations; loginShell?: boolean },
|
|
2715
|
-
): Promise<BashResult> {
|
|
2716
|
-
this._bashAbortController = new AbortController();
|
|
2717
|
-
|
|
2718
|
-
// Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
|
|
2719
|
-
const prefix = this.settingsManager.getShellCommandPrefix();
|
|
2720
|
-
const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
|
|
2721
|
-
|
|
2722
|
-
try {
|
|
2723
|
-
const result = options?.operations
|
|
2724
|
-
? await executeBashWithOperations(resolvedCommand, process.cwd(), options.operations, {
|
|
2725
|
-
onChunk,
|
|
2726
|
-
signal: this._bashAbortController.signal,
|
|
2727
|
-
})
|
|
2728
|
-
: await executeBashCommand(resolvedCommand, {
|
|
2729
|
-
onChunk,
|
|
2730
|
-
signal: this._bashAbortController.signal,
|
|
2731
|
-
loginShell: options?.loginShell,
|
|
2732
|
-
});
|
|
2733
|
-
|
|
2734
|
-
this.recordBashResult(command, result, options);
|
|
2735
|
-
return result;
|
|
2736
|
-
} finally {
|
|
2737
|
-
this._bashAbortController = undefined;
|
|
2738
|
-
}
|
|
2739
|
-
}
|
|
2740
|
-
|
|
2741
|
-
/**
|
|
2742
|
-
* Record a bash execution result in session history.
|
|
2743
|
-
* Used by executeBash and by extensions that handle bash execution themselves.
|
|
2744
|
-
*/
|
|
2745
|
-
recordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean }): void {
|
|
2746
|
-
const bashMessage: BashExecutionMessage = {
|
|
2747
|
-
role: "bashExecution",
|
|
2748
|
-
command,
|
|
2749
|
-
output: result.output,
|
|
2750
|
-
exitCode: result.exitCode,
|
|
2751
|
-
cancelled: result.cancelled,
|
|
2752
|
-
truncated: result.truncated,
|
|
2753
|
-
fullOutputPath: result.fullOutputPath,
|
|
2754
|
-
timestamp: Date.now(),
|
|
2755
|
-
excludeFromContext: options?.excludeFromContext,
|
|
2756
|
-
};
|
|
2757
|
-
|
|
2758
|
-
// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
|
|
2759
|
-
if (this.isStreaming) {
|
|
2760
|
-
// Queue for later - will be flushed on agent_end
|
|
2761
|
-
this._pendingBashMessages.push(bashMessage);
|
|
2762
|
-
} else {
|
|
2763
|
-
// Add to agent state immediately
|
|
2764
|
-
this.agent.state.messages = [...this.agent.state.messages, bashMessage];
|
|
2765
|
-
|
|
2766
|
-
// Save to session
|
|
2767
|
-
this.sessionManager.appendMessage(bashMessage);
|
|
2768
|
-
}
|
|
2769
|
-
}
|
|
2770
|
-
|
|
2771
|
-
/**
|
|
2772
|
-
* Cancel running bash command.
|
|
2773
|
-
*/
|
|
2774
|
-
abortBash(): void {
|
|
2775
|
-
this._bashAbortController?.abort();
|
|
2776
|
-
}
|
|
2777
|
-
|
|
2778
|
-
/** Whether a bash command is currently running */
|
|
2779
|
-
get isBashRunning(): boolean {
|
|
2780
|
-
return this._bashAbortController !== undefined;
|
|
2781
|
-
}
|
|
2782
|
-
|
|
2783
|
-
/** Whether there are pending bash messages waiting to be flushed */
|
|
2784
|
-
get hasPendingBashMessages(): boolean {
|
|
2785
|
-
return this._pendingBashMessages.length > 0;
|
|
2786
|
-
}
|
|
2787
|
-
|
|
2788
|
-
/**
|
|
2789
|
-
* Flush pending bash messages to agent state and session.
|
|
2790
|
-
* Called after agent turn completes to maintain proper message ordering.
|
|
2791
|
-
*/
|
|
2792
|
-
private _flushPendingBashMessages(): void {
|
|
2793
|
-
if (this._pendingBashMessages.length === 0) return;
|
|
2794
|
-
|
|
2795
|
-
for (const bashMessage of this._pendingBashMessages) {
|
|
2796
|
-
// Add to agent state
|
|
2797
|
-
this.agent.state.messages = [...this.agent.state.messages, bashMessage];
|
|
2798
|
-
|
|
2799
|
-
// Save to session
|
|
2800
|
-
this.sessionManager.appendMessage(bashMessage);
|
|
2801
|
-
}
|
|
2802
|
-
|
|
2803
|
-
this._pendingBashMessages = [];
|
|
2804
|
-
}
|
|
2805
|
-
|
|
2806
|
-
// =========================================================================
|
|
2807
|
-
// Session Management
|
|
2808
|
-
// =========================================================================
|
|
2809
|
-
|
|
2810
|
-
/**
|
|
2811
|
-
* Switch to a different session file.
|
|
2812
|
-
* Aborts current operation, loads messages, restores model/thinking.
|
|
2813
|
-
* Listeners are preserved and will continue receiving events.
|
|
2814
|
-
* @returns true if switch completed, false if cancelled by extension
|
|
2815
|
-
*/
|
|
2816
|
-
async switchSession(sessionPath: string): Promise<boolean> {
|
|
2817
|
-
// Snapshot state before transition so listeners and message queues survive (D-14).
|
|
2818
|
-
const snapshot = this._snapshotState();
|
|
2819
|
-
|
|
2820
|
-
const _previousSessionFile = this.sessionManager.getSessionFile();
|
|
2821
|
-
|
|
2822
|
-
// Emit session_before_switch event (can be cancelled)
|
|
2823
|
-
if (this._extensionRunner?.hasHandlers("session_before_switch")) {
|
|
2824
|
-
const result = (await this._extensionRunner.emit({
|
|
2825
|
-
type: "session_before_switch",
|
|
2826
|
-
reason: "resume",
|
|
2827
|
-
targetSessionFile: sessionPath,
|
|
2828
|
-
})) as SessionBeforeSwitchResult | undefined;
|
|
2829
|
-
|
|
2830
|
-
if (result?.cancel) {
|
|
2831
|
-
return false;
|
|
2832
|
-
}
|
|
2833
|
-
}
|
|
2834
|
-
|
|
2835
|
-
// #4243: Must call abort() BEFORE _disconnectFromAgent() so that
|
|
2836
|
-
// message_end/agent_end events fire and the #4216 finalization code
|
|
2837
|
-
// can run before we unsubscribe from the event bus.
|
|
2838
|
-
await this.abort();
|
|
2839
|
-
this._disconnectFromAgent();
|
|
2840
|
-
|
|
2841
|
-
// Delegate to AgentSessionRuntime for lifecycle coordination (D-12).
|
|
2842
|
-
// The factory (_createRuntimeFactory) handles setSessionFile, agent reconnect,
|
|
2843
|
-
// and session_start emission for the "resume" reason.
|
|
2844
|
-
const runtime = await this._ensureRuntime();
|
|
2845
|
-
const result = await runtime.switchSession(sessionPath);
|
|
2846
|
-
|
|
2847
|
-
if (result.cancelled) {
|
|
2848
|
-
return false;
|
|
2849
|
-
}
|
|
2850
|
-
|
|
2851
|
-
// Reload messages and restore model/thinking level (GSD-specific logic not in pi runtime).
|
|
2852
|
-
const sessionContext = this.sessionManager.buildSessionContext();
|
|
2853
|
-
this.agent.state.messages = sessionContext.messages;
|
|
2854
|
-
|
|
2855
|
-
if (sessionContext.model) {
|
|
2856
|
-
const previousModel = this.model;
|
|
2857
|
-
const availableModels = await this._modelRegistry.getAvailable();
|
|
2858
|
-
const match = availableModels.find(
|
|
2859
|
-
(m) => m.provider === sessionContext.model!.provider && m.id === sessionContext.model!.modelId,
|
|
2860
|
-
);
|
|
2861
|
-
if (match) {
|
|
2862
|
-
this.agent.state.model = match;
|
|
2863
|
-
await this._emitModelSelect(match, previousModel, "restore");
|
|
2864
|
-
}
|
|
2865
|
-
}
|
|
2866
|
-
|
|
2867
|
-
const hasThinkingEntry = this.sessionManager.getBranch().some((entry) => entry.type === "thinking_level_change");
|
|
2868
|
-
const defaultThinkingLevel = this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
|
|
2869
|
-
|
|
2870
|
-
if (hasThinkingEntry) {
|
|
2871
|
-
// Restore thinking level if saved (setThinkingLevel clamps to model capabilities)
|
|
2872
|
-
this.setThinkingLevel(sessionContext.thinkingLevel as ThinkingLevel);
|
|
2873
|
-
} else {
|
|
2874
|
-
const availableLevels = this.getAvailableThinkingLevels();
|
|
2875
|
-
const effectiveLevel = availableLevels.includes(defaultThinkingLevel)
|
|
2876
|
-
? defaultThinkingLevel
|
|
2877
|
-
: this._clampThinkingLevel(defaultThinkingLevel, availableLevels);
|
|
2878
|
-
this.agent.state.thinkingLevel = effectiveLevel;
|
|
2879
|
-
this.sessionManager.appendThinkingLevelChange(effectiveLevel);
|
|
2880
|
-
}
|
|
2881
|
-
|
|
2882
|
-
// Restore listener and message queue state that survived the transition (D-14).
|
|
2883
|
-
this._restoreState(snapshot);
|
|
2884
|
-
|
|
2885
|
-
this._emitSessionStateChanged("switch_session");
|
|
2886
|
-
return true;
|
|
2887
|
-
}
|
|
2888
|
-
|
|
2889
|
-
/**
|
|
2890
|
-
* Set a display name for the current session.
|
|
2891
|
-
*/
|
|
2892
|
-
setSessionName(name: string): void {
|
|
2893
|
-
this.sessionManager.appendSessionInfo(name);
|
|
2894
|
-
this._emitSessionStateChanged("set_session_name");
|
|
2895
|
-
}
|
|
2896
|
-
|
|
2897
|
-
/**
|
|
2898
|
-
* Create a fork from a specific entry.
|
|
2899
|
-
* Emits before_fork/fork session events to extensions.
|
|
2900
|
-
*
|
|
2901
|
-
* @param entryId ID of the entry to fork from
|
|
2902
|
-
* @returns Object with:
|
|
2903
|
-
* - selectedText: The text of the selected user message (for editor pre-fill)
|
|
2904
|
-
* - cancelled: True if an extension cancelled the fork
|
|
2905
|
-
*/
|
|
2906
|
-
async fork(entryId: string): Promise<{ selectedText: string; cancelled: boolean }> {
|
|
2907
|
-
// Snapshot state before transition so listeners and message queues survive (D-14).
|
|
2908
|
-
const snapshot = this._snapshotState();
|
|
2909
|
-
|
|
2910
|
-
const _previousSessionFile = this.sessionFile;
|
|
2911
|
-
const selectedEntry = this.sessionManager.getEntry(entryId);
|
|
2912
|
-
|
|
2913
|
-
if (!selectedEntry || selectedEntry.type !== "message" || selectedEntry.message.role !== "user") {
|
|
2914
|
-
throw new Error("Invalid entry ID for forking");
|
|
2915
|
-
}
|
|
2916
|
-
|
|
2917
|
-
const selectedText = this._extractUserMessageText(selectedEntry.message.content);
|
|
2918
|
-
|
|
2919
|
-
let skipConversationRestore = false;
|
|
2920
|
-
|
|
2921
|
-
// Emit session_before_fork event (can be cancelled)
|
|
2922
|
-
if (this._extensionRunner?.hasHandlers("session_before_fork")) {
|
|
2923
|
-
const result = (await this._extensionRunner.emit({
|
|
2924
|
-
type: "session_before_fork",
|
|
2925
|
-
entryId,
|
|
2926
|
-
})) as SessionBeforeForkResult | undefined;
|
|
2927
|
-
|
|
2928
|
-
if (result?.cancel) {
|
|
2929
|
-
return { selectedText, cancelled: true };
|
|
2930
|
-
}
|
|
2931
|
-
skipConversationRestore = result?.skipConversationRestore ?? false;
|
|
2932
|
-
}
|
|
2933
|
-
|
|
2934
|
-
// Mutate sessionManager in place BEFORE calling the runtime (same pattern as newSession).
|
|
2935
|
-
if (!selectedEntry.parentId) {
|
|
2936
|
-
this.sessionManager.newSession({ parentSession: _previousSessionFile });
|
|
2937
|
-
} else {
|
|
2938
|
-
this.sessionManager.createBranchedSession(selectedEntry.parentId);
|
|
2939
|
-
}
|
|
2940
|
-
this.agent.sessionId = this.sessionManager.getSessionId();
|
|
2941
|
-
|
|
2942
|
-
// Reload messages from entries (works for both file and in-memory mode)
|
|
2943
|
-
const sessionContext = this.sessionManager.buildSessionContext();
|
|
2944
|
-
|
|
2945
|
-
// Emit session_start event with reason "fork" to extensions (after fork completes).
|
|
2946
|
-
// Ensure _runtime is initialised so the field is live (D-12).
|
|
2947
|
-
await this._ensureRuntime();
|
|
2948
|
-
if (this._extensionRunner) {
|
|
2949
|
-
await this._extensionRunner.emit({
|
|
2950
|
-
type: "session_start",
|
|
2951
|
-
});
|
|
2952
|
-
}
|
|
2953
|
-
|
|
2954
|
-
if (!skipConversationRestore) {
|
|
2955
|
-
this.agent.state.messages = sessionContext.messages;
|
|
2956
|
-
}
|
|
2957
|
-
|
|
2958
|
-
// Restore listener and message queue state that survived the transition (D-14).
|
|
2959
|
-
this._restoreState(snapshot);
|
|
2960
|
-
|
|
2961
|
-
this._emitSessionStateChanged("fork");
|
|
2962
|
-
return { selectedText, cancelled: false };
|
|
2963
|
-
}
|
|
2964
|
-
|
|
2965
|
-
// =========================================================================
|
|
2966
|
-
// Tree Navigation
|
|
2967
|
-
// =========================================================================
|
|
2968
|
-
|
|
2969
|
-
/**
|
|
2970
|
-
* Navigate to a different node in the session tree.
|
|
2971
|
-
* Unlike fork() which creates a new session file, this stays in the same file.
|
|
2972
|
-
*
|
|
2973
|
-
* @param targetId The entry ID to navigate to
|
|
2974
|
-
* @param options.summarize Whether user wants to summarize abandoned branch
|
|
2975
|
-
* @param options.customInstructions Custom instructions for summarizer
|
|
2976
|
-
* @param options.replaceInstructions If true, customInstructions replaces the default prompt
|
|
2977
|
-
* @param options.label Label to attach to the branch summary entry
|
|
2978
|
-
* @returns Result with editorText (if user message) and cancelled status
|
|
2979
|
-
*/
|
|
2980
|
-
async navigateTree(
|
|
2981
|
-
targetId: string,
|
|
2982
|
-
options: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string } = {},
|
|
2983
|
-
): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }> {
|
|
2984
|
-
const oldLeafId = this.sessionManager.getLeafId();
|
|
2985
|
-
|
|
2986
|
-
// No-op if already at target
|
|
2987
|
-
if (targetId === oldLeafId) {
|
|
2988
|
-
return { cancelled: false };
|
|
2989
|
-
}
|
|
2990
|
-
|
|
2991
|
-
// Model required for summarization
|
|
2992
|
-
if (options.summarize && !this.model) {
|
|
2993
|
-
throw new Error("No model available for summarization");
|
|
2994
|
-
}
|
|
2995
|
-
|
|
2996
|
-
const targetEntry = this.sessionManager.getEntry(targetId);
|
|
2997
|
-
if (!targetEntry) {
|
|
2998
|
-
throw new Error(`Entry ${targetId} not found`);
|
|
2999
|
-
}
|
|
3000
|
-
|
|
3001
|
-
// Collect entries to summarize (from old leaf to common ancestor)
|
|
3002
|
-
const { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(
|
|
3003
|
-
this.sessionManager,
|
|
3004
|
-
oldLeafId,
|
|
3005
|
-
targetId,
|
|
3006
|
-
);
|
|
3007
|
-
|
|
3008
|
-
// Prepare event data - mutable so extensions can override
|
|
3009
|
-
let customInstructions = options.customInstructions;
|
|
3010
|
-
let replaceInstructions = options.replaceInstructions;
|
|
3011
|
-
let label = options.label;
|
|
3012
|
-
|
|
3013
|
-
const preparation: TreePreparation = {
|
|
3014
|
-
targetId,
|
|
3015
|
-
oldLeafId,
|
|
3016
|
-
commonAncestorId,
|
|
3017
|
-
entriesToSummarize,
|
|
3018
|
-
userWantsSummary: options.summarize ?? false,
|
|
3019
|
-
customInstructions,
|
|
3020
|
-
replaceInstructions,
|
|
3021
|
-
label,
|
|
3022
|
-
};
|
|
3023
|
-
|
|
3024
|
-
// Set up abort controller for summarization
|
|
3025
|
-
this._compactionOrchestrator.branchSummaryAbortController = new AbortController();
|
|
3026
|
-
let extensionSummary: { summary: string; details?: unknown } | undefined;
|
|
3027
|
-
let fromExtension = false;
|
|
3028
|
-
|
|
3029
|
-
// Emit session_before_tree event
|
|
3030
|
-
if (this._extensionRunner?.hasHandlers("session_before_tree")) {
|
|
3031
|
-
const result = (await this._extensionRunner.emit({
|
|
3032
|
-
type: "session_before_tree",
|
|
3033
|
-
preparation,
|
|
3034
|
-
signal: this._compactionOrchestrator.branchSummaryAbortController.signal,
|
|
3035
|
-
})) as SessionBeforeTreeResult | undefined;
|
|
3036
|
-
|
|
3037
|
-
if (result?.cancel) {
|
|
3038
|
-
return { cancelled: true };
|
|
3039
|
-
}
|
|
3040
|
-
|
|
3041
|
-
if (result?.summary && options.summarize) {
|
|
3042
|
-
extensionSummary = result.summary;
|
|
3043
|
-
fromExtension = true;
|
|
3044
|
-
}
|
|
3045
|
-
|
|
3046
|
-
// Allow extensions to override instructions and label
|
|
3047
|
-
if (result?.customInstructions !== undefined) {
|
|
3048
|
-
customInstructions = result.customInstructions;
|
|
3049
|
-
}
|
|
3050
|
-
if (result?.replaceInstructions !== undefined) {
|
|
3051
|
-
replaceInstructions = result.replaceInstructions;
|
|
3052
|
-
}
|
|
3053
|
-
if (result?.label !== undefined) {
|
|
3054
|
-
label = result.label;
|
|
3055
|
-
}
|
|
3056
|
-
}
|
|
3057
|
-
|
|
3058
|
-
// Run default summarizer if needed
|
|
3059
|
-
let summaryText: string | undefined;
|
|
3060
|
-
let summaryDetails: unknown;
|
|
3061
|
-
if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
|
|
3062
|
-
const model = this.model!;
|
|
3063
|
-
if (!this._modelRegistry.isProviderRequestReady(model.provider)) {
|
|
3064
|
-
throw new Error(`No API key for ${model.provider}`);
|
|
3065
|
-
}
|
|
3066
|
-
const authResult = await this._modelRegistry.getApiKeyAndHeaders(model);
|
|
3067
|
-
const apiKey = authResult.ok ? authResult.apiKey : undefined;
|
|
3068
|
-
const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
|
|
3069
|
-
const result = await generateBranchSummary(entriesToSummarize, {
|
|
3070
|
-
model,
|
|
3071
|
-
apiKey,
|
|
3072
|
-
signal: this._compactionOrchestrator.branchSummaryAbortController.signal,
|
|
3073
|
-
customInstructions,
|
|
3074
|
-
replaceInstructions,
|
|
3075
|
-
reserveTokens: branchSummarySettings.reserveTokens,
|
|
3076
|
-
});
|
|
3077
|
-
this._compactionOrchestrator.branchSummaryAbortController = undefined;
|
|
3078
|
-
if (result.aborted) {
|
|
3079
|
-
return { cancelled: true, aborted: true };
|
|
3080
|
-
}
|
|
3081
|
-
if (result.error) {
|
|
3082
|
-
throw new Error(result.error);
|
|
3083
|
-
}
|
|
3084
|
-
summaryText = result.summary;
|
|
3085
|
-
summaryDetails = {
|
|
3086
|
-
readFiles: result.readFiles || [],
|
|
3087
|
-
modifiedFiles: result.modifiedFiles || [],
|
|
3088
|
-
};
|
|
3089
|
-
} else if (extensionSummary) {
|
|
3090
|
-
summaryText = extensionSummary.summary;
|
|
3091
|
-
summaryDetails = extensionSummary.details;
|
|
3092
|
-
}
|
|
3093
|
-
|
|
3094
|
-
// Determine the new leaf position based on target type
|
|
3095
|
-
let newLeafId: string | null;
|
|
3096
|
-
let editorText: string | undefined;
|
|
3097
|
-
|
|
3098
|
-
if (targetEntry.type === "message" && targetEntry.message.role === "user") {
|
|
3099
|
-
// User message: leaf = parent (null if root), text goes to editor
|
|
3100
|
-
newLeafId = targetEntry.parentId;
|
|
3101
|
-
editorText = this._extractUserMessageText(targetEntry.message.content);
|
|
3102
|
-
} else if (targetEntry.type === "custom_message") {
|
|
3103
|
-
// Custom message: leaf = parent (null if root), text goes to editor
|
|
3104
|
-
newLeafId = targetEntry.parentId;
|
|
3105
|
-
editorText =
|
|
3106
|
-
typeof targetEntry.content === "string"
|
|
3107
|
-
? targetEntry.content
|
|
3108
|
-
: targetEntry.content
|
|
3109
|
-
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
|
3110
|
-
.map((c) => c.text)
|
|
3111
|
-
.join("");
|
|
3112
|
-
} else {
|
|
3113
|
-
// Non-user message: leaf = selected node
|
|
3114
|
-
newLeafId = targetId;
|
|
3115
|
-
}
|
|
3116
|
-
|
|
3117
|
-
// Switch leaf (with or without summary)
|
|
3118
|
-
// Summary is attached at the navigation target position (newLeafId), not the old branch
|
|
3119
|
-
let summaryEntry: BranchSummaryEntry | undefined;
|
|
3120
|
-
if (summaryText) {
|
|
3121
|
-
// Create summary at target position (can be null for root)
|
|
3122
|
-
const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension);
|
|
3123
|
-
summaryEntry = this.sessionManager.getEntry(summaryId) as BranchSummaryEntry;
|
|
3124
|
-
|
|
3125
|
-
// Attach label to the summary entry
|
|
3126
|
-
if (label) {
|
|
3127
|
-
this.sessionManager.appendLabelChange(summaryId, label);
|
|
3128
|
-
}
|
|
3129
|
-
} else if (newLeafId === null) {
|
|
3130
|
-
// No summary, navigating to root - reset leaf
|
|
3131
|
-
this.sessionManager.resetLeaf();
|
|
3132
|
-
} else {
|
|
3133
|
-
// No summary, navigating to non-root
|
|
3134
|
-
this.sessionManager.branch(newLeafId);
|
|
3135
|
-
}
|
|
3136
|
-
|
|
3137
|
-
// Attach label to target entry when not summarizing (no summary entry to label)
|
|
3138
|
-
if (label && !summaryText) {
|
|
3139
|
-
this.sessionManager.appendLabelChange(targetId, label);
|
|
3140
|
-
}
|
|
3141
|
-
|
|
3142
|
-
// Update agent state
|
|
3143
|
-
const sessionContext = this.sessionManager.buildSessionContext();
|
|
3144
|
-
this.agent.state.messages = sessionContext.messages;
|
|
3145
|
-
|
|
3146
|
-
// Emit session_tree event
|
|
3147
|
-
if (this._extensionRunner) {
|
|
3148
|
-
await this._extensionRunner.emit({
|
|
3149
|
-
type: "session_tree",
|
|
3150
|
-
newLeafId: this.sessionManager.getLeafId(),
|
|
3151
|
-
oldLeafId,
|
|
3152
|
-
summaryEntry,
|
|
3153
|
-
fromExtension: summaryText ? fromExtension : undefined,
|
|
3154
|
-
});
|
|
3155
|
-
}
|
|
3156
|
-
|
|
3157
|
-
// Emit to custom tools
|
|
3158
|
-
|
|
3159
|
-
this._compactionOrchestrator.branchSummaryAbortController = undefined;
|
|
3160
|
-
return { editorText, cancelled: false, summaryEntry };
|
|
3161
|
-
}
|
|
3162
|
-
|
|
3163
|
-
/**
|
|
3164
|
-
* Get all user messages from session for fork selector.
|
|
3165
|
-
*/
|
|
3166
|
-
getUserMessagesForForking(): Array<{ entryId: string; text: string }> {
|
|
3167
|
-
const entries = this.sessionManager.getEntries();
|
|
3168
|
-
const result: Array<{ entryId: string; text: string }> = [];
|
|
3169
|
-
|
|
3170
|
-
for (const entry of entries) {
|
|
3171
|
-
if (entry.type !== "message") continue;
|
|
3172
|
-
if (entry.message.role !== "user") continue;
|
|
3173
|
-
|
|
3174
|
-
const text = this._extractUserMessageText(entry.message.content);
|
|
3175
|
-
if (text) {
|
|
3176
|
-
result.push({ entryId: entry.id, text });
|
|
3177
|
-
}
|
|
3178
|
-
}
|
|
3179
|
-
|
|
3180
|
-
return result;
|
|
3181
|
-
}
|
|
3182
|
-
|
|
3183
|
-
private _extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string {
|
|
3184
|
-
if (typeof content === "string") return content;
|
|
3185
|
-
if (Array.isArray(content)) {
|
|
3186
|
-
return content
|
|
3187
|
-
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
|
3188
|
-
.map((c) => c.text)
|
|
3189
|
-
.join("");
|
|
3190
|
-
}
|
|
3191
|
-
return "";
|
|
3192
|
-
}
|
|
3193
|
-
|
|
3194
|
-
/**
|
|
3195
|
-
* Get session statistics.
|
|
3196
|
-
*/
|
|
3197
|
-
getSessionStats(): SessionStats {
|
|
3198
|
-
const state = this.state;
|
|
3199
|
-
const userMessages = state.messages.filter((m) => m.role === "user").length;
|
|
3200
|
-
const assistantMessages = state.messages.filter((m) => m.role === "assistant").length;
|
|
3201
|
-
const toolResults = state.messages.filter((m) => m.role === "toolResult").length;
|
|
3202
|
-
|
|
3203
|
-
let toolCalls = 0;
|
|
3204
|
-
let totalInput = 0;
|
|
3205
|
-
let totalOutput = 0;
|
|
3206
|
-
let totalCacheRead = 0;
|
|
3207
|
-
let totalCacheWrite = 0;
|
|
3208
|
-
let totalCost = 0;
|
|
3209
|
-
|
|
3210
|
-
for (const message of state.messages) {
|
|
3211
|
-
if (message.role === "assistant") {
|
|
3212
|
-
const assistantMsg = message as AssistantMessage;
|
|
3213
|
-
toolCalls += assistantMsg.content.filter((c) => c.type === "toolCall").length;
|
|
3214
|
-
totalInput += assistantMsg.usage.input;
|
|
3215
|
-
totalOutput += assistantMsg.usage.output;
|
|
3216
|
-
totalCacheRead += assistantMsg.usage.cacheRead;
|
|
3217
|
-
totalCacheWrite += assistantMsg.usage.cacheWrite;
|
|
3218
|
-
totalCost += assistantMsg.usage.cost.total;
|
|
3219
|
-
}
|
|
3220
|
-
}
|
|
3221
|
-
|
|
3222
|
-
return {
|
|
3223
|
-
sessionFile: this.sessionFile,
|
|
3224
|
-
sessionId: this.sessionId,
|
|
3225
|
-
userMessages,
|
|
3226
|
-
assistantMessages,
|
|
3227
|
-
toolCalls: Math.max(toolCalls, this._cumulativeToolCalls),
|
|
3228
|
-
toolResults,
|
|
3229
|
-
totalMessages: state.messages.length,
|
|
3230
|
-
tokens: {
|
|
3231
|
-
input: Math.max(totalInput, this._cumulativeInputTokens),
|
|
3232
|
-
output: Math.max(totalOutput, this._cumulativeOutputTokens),
|
|
3233
|
-
cacheRead: totalCacheRead,
|
|
3234
|
-
cacheWrite: totalCacheWrite,
|
|
3235
|
-
total: Math.max(totalInput + totalOutput, this._cumulativeInputTokens + this._cumulativeOutputTokens) + totalCacheRead + totalCacheWrite,
|
|
3236
|
-
},
|
|
3237
|
-
cost: Math.max(totalCost, this._cumulativeCost),
|
|
3238
|
-
};
|
|
3239
|
-
}
|
|
3240
|
-
|
|
3241
|
-
/**
|
|
3242
|
-
* Get the cost of the most recent assistant response.
|
|
3243
|
-
* Returns 0 if no assistant message has been received yet.
|
|
3244
|
-
*/
|
|
3245
|
-
getLastTurnCost(): number {
|
|
3246
|
-
return this._lastTurnCost;
|
|
3247
|
-
}
|
|
3248
|
-
|
|
3249
|
-
getContextUsage(): ContextUsage | undefined {
|
|
3250
|
-
const model = this.model;
|
|
3251
|
-
if (!model) return undefined;
|
|
3252
|
-
|
|
3253
|
-
const contextWindow = model.contextWindow ?? 0;
|
|
3254
|
-
if (contextWindow <= 0) return undefined;
|
|
3255
|
-
|
|
3256
|
-
// After compaction, the last assistant usage reflects pre-compaction context size.
|
|
3257
|
-
// We can only trust usage from an assistant that responded after the latest compaction.
|
|
3258
|
-
// If no such assistant exists, context token count is unknown until the next LLM response.
|
|
3259
|
-
const branchEntries = this.sessionManager.getBranch();
|
|
3260
|
-
const latestCompaction = getLatestCompactionEntry(branchEntries);
|
|
3261
|
-
|
|
3262
|
-
if (latestCompaction) {
|
|
3263
|
-
// Check if there's a valid assistant usage after the compaction boundary
|
|
3264
|
-
const compactionIndex = branchEntries.lastIndexOf(latestCompaction);
|
|
3265
|
-
let hasPostCompactionUsage = false;
|
|
3266
|
-
for (let i = branchEntries.length - 1; i > compactionIndex; i--) {
|
|
3267
|
-
const entry = branchEntries[i];
|
|
3268
|
-
if (entry.type === "message" && entry.message.role === "assistant") {
|
|
3269
|
-
const assistant = entry.message;
|
|
3270
|
-
if (assistant.stopReason !== "aborted" && assistant.stopReason !== "error") {
|
|
3271
|
-
const contextTokens = calculateContextTokens(assistant.usage);
|
|
3272
|
-
if (contextTokens > 0) {
|
|
3273
|
-
hasPostCompactionUsage = true;
|
|
3274
|
-
}
|
|
3275
|
-
break;
|
|
3276
|
-
}
|
|
3277
|
-
}
|
|
3278
|
-
}
|
|
3279
|
-
|
|
3280
|
-
if (!hasPostCompactionUsage) {
|
|
3281
|
-
return { tokens: null, contextWindow, percent: null };
|
|
3282
|
-
}
|
|
3283
|
-
}
|
|
3284
|
-
|
|
3285
|
-
const estimate = estimateContextTokens(this.messages);
|
|
3286
|
-
const percent = (estimate.tokens / contextWindow) * 100;
|
|
3287
|
-
|
|
3288
|
-
return {
|
|
3289
|
-
tokens: estimate.tokens,
|
|
3290
|
-
contextWindow,
|
|
3291
|
-
percent,
|
|
3292
|
-
};
|
|
3293
|
-
}
|
|
3294
|
-
|
|
3295
|
-
/**
|
|
3296
|
-
* Export session to HTML.
|
|
3297
|
-
* @param outputPath Optional output path (defaults to session directory)
|
|
3298
|
-
* @returns Path to exported file
|
|
3299
|
-
*/
|
|
3300
|
-
async exportToHtml(outputPath?: string): Promise<string> {
|
|
3301
|
-
const themeName = this.settingsManager.getTheme();
|
|
3302
|
-
return await exportSessionToHtml(this.sessionManager, this.state, {
|
|
3303
|
-
outputPath,
|
|
3304
|
-
themeName,
|
|
3305
|
-
});
|
|
3306
|
-
}
|
|
3307
|
-
|
|
3308
|
-
// =========================================================================
|
|
3309
|
-
// Utilities
|
|
3310
|
-
// =========================================================================
|
|
3311
|
-
|
|
3312
|
-
/**
|
|
3313
|
-
* Get text content of last assistant message.
|
|
3314
|
-
* Useful for /copy command.
|
|
3315
|
-
* @returns Text content, or undefined if no assistant message exists
|
|
3316
|
-
*/
|
|
3317
|
-
getLastAssistantText(): string | undefined {
|
|
3318
|
-
const lastAssistant = this.messages
|
|
3319
|
-
.slice()
|
|
3320
|
-
.reverse()
|
|
3321
|
-
.find((m) => {
|
|
3322
|
-
if (m.role !== "assistant") return false;
|
|
3323
|
-
const msg = m as AssistantMessage;
|
|
3324
|
-
// Skip aborted messages with no content
|
|
3325
|
-
if (msg.stopReason === "aborted" && msg.content.length === 0) return false;
|
|
3326
|
-
return true;
|
|
3327
|
-
});
|
|
3328
|
-
|
|
3329
|
-
if (!lastAssistant) return undefined;
|
|
3330
|
-
|
|
3331
|
-
let text = "";
|
|
3332
|
-
for (const content of (lastAssistant as AssistantMessage).content) {
|
|
3333
|
-
if (content.type === "text") {
|
|
3334
|
-
text += content.text;
|
|
3335
|
-
}
|
|
3336
|
-
}
|
|
3337
|
-
|
|
3338
|
-
return text.trim() || undefined;
|
|
3339
|
-
}
|
|
3340
|
-
|
|
3341
|
-
// =========================================================================
|
|
3342
|
-
// Extension System
|
|
3343
|
-
// =========================================================================
|
|
3344
|
-
|
|
3345
|
-
/**
|
|
3346
|
-
* Check if extensions have handlers for a specific event type.
|
|
3347
|
-
*/
|
|
3348
|
-
hasExtensionHandlers(eventType: string): boolean {
|
|
3349
|
-
return this._extensionRunner?.hasHandlers(eventType) ?? false;
|
|
3350
|
-
}
|
|
3351
|
-
|
|
3352
|
-
/**
|
|
3353
|
-
* Get the extension runner (for setting UI context and error handlers).
|
|
3354
|
-
*/
|
|
3355
|
-
get extensionRunner(): ExtensionRunner | undefined {
|
|
3356
|
-
return this._extensionRunner;
|
|
3357
|
-
}
|
|
3358
|
-
}
|