gsd-pi 2.78.0-dev.aeeb2ca00 → 2.78.1-dev.0fdacd524
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/README.md +8 -7
- package/dist/bundled-resource-path.d.ts +7 -0
- package/dist/bundled-resource-path.js +34 -2
- package/dist/claude-cli-check.js +77 -38
- package/dist/cli-policy.d.ts +13 -0
- package/dist/cli-policy.js +17 -0
- package/dist/cli.js +95 -55
- package/dist/headless-query.d.ts +22 -0
- package/dist/headless-query.js +43 -8
- package/dist/headless.d.ts +10 -0
- package/dist/headless.js +16 -1
- package/dist/loader.js +9 -13
- package/dist/onboarding.d.ts +10 -0
- package/dist/onboarding.js +2 -2
- package/dist/provider-migrations.d.ts +2 -2
- package/dist/provider-migrations.js +5 -2
- package/dist/resource-loader.d.ts +5 -2
- package/dist/resource-loader.js +30 -13
- package/dist/resources/.managed-resources-content-hash +1 -0
- package/dist/resources/extensions/claude-code-cli/readiness.js +90 -46
- package/dist/resources/extensions/google-search/index.js +2 -6
- package/dist/resources/extensions/gsd/auto/loop.js +23 -0
- package/dist/resources/extensions/gsd/auto/phases.js +5 -13
- package/dist/resources/extensions/gsd/auto/run-unit.js +26 -12
- package/dist/resources/extensions/gsd/auto/session.js +5 -6
- package/dist/resources/extensions/gsd/auto-dashboard.js +3 -2
- package/dist/resources/extensions/gsd/auto-direct-dispatch.js +55 -21
- package/dist/resources/extensions/gsd/auto-dispatch.js +18 -6
- package/dist/resources/extensions/gsd/auto-prompts.js +69 -2
- package/dist/resources/extensions/gsd/auto-recovery.js +43 -4
- package/dist/resources/extensions/gsd/auto-runtime-state.js +31 -0
- package/dist/resources/extensions/gsd/auto-start.js +1 -1
- package/dist/resources/extensions/gsd/auto-tool-tracking.js +2 -2
- package/dist/resources/extensions/gsd/auto-worktree.js +60 -13
- package/dist/resources/extensions/gsd/auto.js +39 -14
- package/dist/resources/extensions/gsd/bootstrap/db-tools.js +14 -2
- package/dist/resources/extensions/gsd/bootstrap/exec-tools.js +7 -5
- package/dist/resources/extensions/gsd/bootstrap/query-tools.js +2 -2
- package/dist/resources/extensions/gsd/bootstrap/register-extension.js +5 -4
- package/dist/resources/extensions/gsd/bootstrap/register-hooks.js +112 -31
- package/dist/resources/extensions/gsd/bootstrap/register-shortcuts.js +11 -6
- package/dist/resources/extensions/gsd/bootstrap/subagent-input.js +22 -0
- package/dist/resources/extensions/gsd/bootstrap/system-context.js +45 -8
- package/dist/resources/extensions/gsd/bootstrap/write-gate.js +121 -3
- package/dist/resources/extensions/gsd/commands/catalog.js +76 -5
- package/dist/resources/extensions/gsd/commands/handlers/core.js +23 -1
- package/dist/resources/extensions/gsd/commands/handlers/ops.js +8 -0
- package/dist/resources/extensions/gsd/commands-config.js +3 -2
- package/dist/resources/extensions/gsd/commands-extensions.js +46 -3
- package/dist/resources/extensions/gsd/commands-handlers.js +3 -2
- package/dist/resources/extensions/gsd/commands-mcp-status.js +3 -1
- package/dist/resources/extensions/gsd/commands-prefs-wizard.js +10 -1
- package/dist/resources/extensions/gsd/commands-worktree.js +309 -0
- package/dist/resources/extensions/gsd/dashboard-overlay.js +1 -1
- package/dist/resources/extensions/gsd/docs/preferences-reference.md +10 -0
- package/dist/resources/extensions/gsd/doctor-providers.js +2 -1
- package/dist/resources/extensions/gsd/doctor-runtime-checks.js +39 -1
- package/dist/resources/extensions/gsd/error-classifier.js +1 -1
- package/dist/resources/extensions/gsd/forensics.js +10 -8
- package/dist/resources/extensions/gsd/git-service.js +12 -5
- package/dist/resources/extensions/gsd/gsd-db.js +11 -2
- package/dist/resources/extensions/gsd/guided-flow.js +25 -24
- package/dist/resources/extensions/gsd/home-dir.js +16 -0
- package/dist/resources/extensions/gsd/key-manager.js +2 -1
- package/dist/resources/extensions/gsd/memory-store.js +66 -31
- package/dist/resources/extensions/gsd/migrate/command.js +3 -2
- package/dist/resources/extensions/gsd/milestone-id-reservation.js +36 -0
- package/dist/resources/extensions/gsd/model-router.js +114 -9
- package/dist/resources/extensions/gsd/native-git-bridge.js +7 -1
- package/dist/resources/extensions/gsd/preferences-models.js +91 -15
- package/dist/resources/extensions/gsd/preferences-types.js +2 -0
- package/dist/resources/extensions/gsd/preferences-validation.js +32 -0
- package/dist/resources/extensions/gsd/preferences.js +5 -3
- package/dist/resources/extensions/gsd/prompt-loader.js +23 -12
- package/dist/resources/extensions/gsd/prompts/complete-milestone.md +10 -0
- package/dist/resources/extensions/gsd/prompts/complete-slice.md +10 -0
- package/dist/resources/extensions/gsd/prompts/guided-discuss-milestone.md +2 -0
- package/dist/resources/extensions/gsd/prompts/parallel-research-slices.md +2 -0
- package/dist/resources/extensions/gsd/prompts/plan-slice.md +10 -0
- package/dist/resources/extensions/gsd/prompts/refine-slice.md +10 -0
- package/dist/resources/extensions/gsd/prompts/rewrite-docs.md +2 -0
- package/dist/resources/extensions/gsd/slice-parallel-orchestrator.js +9 -3
- package/dist/resources/extensions/gsd/state.js +42 -0
- package/dist/resources/extensions/gsd/templates/PREFERENCES.md +1 -0
- package/dist/resources/extensions/gsd/tools/memory-tools.js +18 -1
- package/dist/resources/extensions/gsd/unit-context-manifest.js +29 -4
- package/dist/resources/extensions/gsd/visualizer-overlay.js +1 -1
- package/dist/resources/extensions/gsd/watch/header-renderer.js +3 -1
- package/dist/resources/extensions/gsd/worktree-command.js +26 -46
- package/dist/resources/extensions/gsd/worktree-manager.js +20 -1
- package/dist/resources/extensions/gsd/worktree-resolver.js +4 -13
- package/dist/resources/extensions/gsd/worktree-root.js +124 -0
- package/dist/resources/extensions/gsd/worktree-session-state.js +33 -0
- package/dist/resources/extensions/gsd/worktree.js +4 -115
- package/dist/resources/extensions/mcp-client/index.js +6 -9
- package/dist/resources/extensions/ollama/index.js +15 -2
- package/dist/resources/extensions/ollama/model-capabilities.js +31 -0
- package/dist/resources/extensions/ollama/ollama-client.js +40 -4
- package/dist/resources/extensions/slash-commands/create-extension.js +36 -22
- package/dist/resources/extensions/subagent/index.js +324 -178
- package/dist/resources/skills/create-gsd-extension/SKILL.md +9 -5
- package/dist/resources/skills/create-gsd-extension/references/custom-commands.md +1 -1
- package/dist/resources/skills/create-gsd-extension/references/custom-rendering.md +5 -5
- package/dist/resources/skills/create-gsd-extension/references/custom-tools.md +4 -4
- package/dist/resources/skills/create-gsd-extension/references/custom-ui.md +6 -6
- package/dist/resources/skills/create-gsd-extension/references/events-reference.md +3 -3
- package/dist/resources/skills/create-gsd-extension/references/packaging-distribution.md +1 -1
- package/dist/resources/skills/create-gsd-extension/references/remote-execution-overrides.md +3 -3
- package/dist/resources/skills/create-gsd-extension/workflows/create-extension.md +32 -12
- package/dist/resources/skills/lint/SKILL.md +4 -0
- package/dist/resources/skills/review/SKILL.md +4 -0
- package/dist/resources/skills/test/SKILL.md +3 -0
- package/dist/rtk-shared.d.ts +3 -0
- package/dist/rtk-shared.js +17 -0
- package/dist/rtk.d.ts +2 -5
- package/dist/rtk.js +3 -20
- package/dist/runtime-checks.d.ts +27 -0
- package/dist/runtime-checks.js +38 -0
- 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 +13 -13
- 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 +44 -4
- package/dist/web/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +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/page_client-reference-manifest.js +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/git/route.js +1 -1
- package/dist/web/standalone/.next/server/app/api/session/events/route.js +4 -2
- package/dist/web/standalone/.next/server/app/api/shutdown/route.js +1 -1
- package/dist/web/standalone/.next/server/app/index.html +1 -1
- package/dist/web/standalone/.next/server/app/index.rsc +2 -2
- package/dist/web/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
- package/dist/web/standalone/.next/server/app/index.segments/_full.segment.rsc +2 -2
- 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/page_client-reference-manifest.js +1 -1
- package/dist/web/standalone/.next/server/app-paths-manifest.json +13 -13
- 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/server/webpack-runtime.js +1 -1
- package/dist/web/standalone/.next/static/chunks/2556.0527fea66e123b7f.js +1 -0
- package/dist/web/standalone/.next/static/chunks/2824.08296bc2f9654698.js +1 -0
- package/dist/web/standalone/.next/static/chunks/3026.3af53b279375f082.js +1 -0
- package/dist/web/standalone/.next/static/chunks/315.6f68ae79b67d25cf.js +1 -0
- package/dist/web/standalone/.next/static/chunks/3497.4bfc60a3b3dea717.js +1 -0
- package/dist/web/standalone/.next/static/chunks/5516.4a07c872b5c3a663.js +1 -0
- package/dist/web/standalone/.next/static/chunks/8336.31b019697882acfb.js +10 -0
- package/dist/web/standalone/.next/static/chunks/8845.c9702695e8c5a9c5.js +2 -0
- package/dist/web/standalone/.next/static/chunks/9058.01ef3a463bda88f1.js +20 -0
- package/dist/web/standalone/.next/static/chunks/9441.1081da1125d1764f.js +1 -0
- package/dist/web/standalone/.next/static/chunks/app/{page-5b113fd32bc2a1c3.js → page-9bf2e0c50fb2ca05.js} +1 -1
- package/dist/web/standalone/.next/static/chunks/webpack-f9f0dc45e4f3ac10.js +1 -0
- package/dist/web/standalone/package.json +2 -1
- package/dist/welcome-screen.js +27 -1
- package/dist/worktree-cli.d.ts +1 -0
- package/dist/worktree-cli.js +9 -3
- package/dist/worktree-status-banner.d.ts +1 -0
- package/dist/worktree-status-banner.js +132 -0
- package/package.json +1 -3
- package/packages/daemon/package.json +2 -2
- package/packages/mcp-server/dist/alias-telemetry.d.ts +8 -0
- package/packages/mcp-server/dist/alias-telemetry.d.ts.map +1 -0
- package/packages/mcp-server/dist/alias-telemetry.js +30 -0
- package/packages/mcp-server/dist/alias-telemetry.js.map +1 -0
- package/packages/mcp-server/dist/workflow-tools.d.ts.map +1 -1
- package/packages/mcp-server/dist/workflow-tools.js +74 -46
- package/packages/mcp-server/dist/workflow-tools.js.map +1 -1
- package/packages/mcp-server/package.json +2 -2
- package/packages/mcp-server/src/alias-telemetry.test.ts +78 -0
- package/packages/mcp-server/src/alias-telemetry.ts +30 -0
- package/packages/mcp-server/src/workflow-tools.test.ts +78 -0
- package/packages/mcp-server/src/workflow-tools.ts +93 -58
- package/packages/mcp-server/tsconfig.tsbuildinfo +1 -1
- package/packages/native/package.json +1 -1
- package/packages/native/tsconfig.tsbuildinfo +1 -1
- package/packages/pi-agent-core/package.json +1 -1
- package/packages/pi-agent-core/tsconfig.tsbuildinfo +1 -1
- package/packages/pi-ai/dist/providers/anthropic-shared.cache-breakpoint.test.d.ts +2 -0
- package/packages/pi-ai/dist/providers/anthropic-shared.cache-breakpoint.test.d.ts.map +1 -0
- package/packages/pi-ai/dist/providers/anthropic-shared.cache-breakpoint.test.js +231 -0
- package/packages/pi-ai/dist/providers/anthropic-shared.cache-breakpoint.test.js.map +1 -0
- package/packages/pi-ai/dist/providers/anthropic-shared.d.ts.map +1 -1
- package/packages/pi-ai/dist/providers/anthropic-shared.js +48 -19
- package/packages/pi-ai/dist/providers/anthropic-shared.js.map +1 -1
- package/packages/pi-ai/dist/types.d.ts +13 -0
- package/packages/pi-ai/dist/types.d.ts.map +1 -1
- package/packages/pi-ai/dist/types.js.map +1 -1
- package/packages/pi-ai/dist/utils/repair-tool-json.d.ts.map +1 -1
- package/packages/pi-ai/dist/utils/repair-tool-json.js +24 -3
- package/packages/pi-ai/dist/utils/repair-tool-json.js.map +1 -1
- package/packages/pi-ai/dist/utils/tests/repair-tool-json.test.js +26 -0
- package/packages/pi-ai/dist/utils/tests/repair-tool-json.test.js.map +1 -1
- package/packages/pi-ai/package.json +1 -1
- package/packages/pi-ai/src/providers/anthropic-shared.cache-breakpoint.test.ts +289 -0
- package/packages/pi-ai/src/providers/anthropic-shared.ts +52 -20
- package/packages/pi-ai/src/types.ts +13 -0
- package/packages/pi-ai/src/utils/repair-tool-json.ts +24 -3
- package/packages/pi-ai/src/utils/tests/repair-tool-json.test.ts +32 -0
- package/packages/pi-ai/tsconfig.tsbuildinfo +1 -1
- package/packages/pi-coding-agent/dist/core/agent-session.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/agent-session.js +6 -0
- package/packages/pi-coding-agent/dist/core/agent-session.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/messages.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/messages.js +4 -0
- package/packages/pi-coding-agent/dist/core/messages.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/model-registry-auth-mode.test.js +19 -2
- package/packages/pi-coding-agent/dist/core/model-registry-auth-mode.test.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/model-registry.d.ts +10 -0
- package/packages/pi-coding-agent/dist/core/model-registry.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/model-registry.js +18 -0
- package/packages/pi-coding-agent/dist/core/model-registry.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/system-prompt.d.ts +13 -0
- package/packages/pi-coding-agent/dist/core/system-prompt.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/system-prompt.js +20 -16
- package/packages/pi-coding-agent/dist/core/system-prompt.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/token-telemetry.d.ts +37 -0
- package/packages/pi-coding-agent/dist/core/token-telemetry.d.ts.map +1 -0
- package/packages/pi-coding-agent/dist/core/token-telemetry.js +49 -0
- package/packages/pi-coding-agent/dist/core/token-telemetry.js.map +1 -0
- package/packages/pi-coding-agent/dist/modes/interactive/components/tool-card-cleanup-and-success-runtime.test.d.ts +2 -0
- package/packages/pi-coding-agent/dist/modes/interactive/components/tool-card-cleanup-and-success-runtime.test.d.ts.map +1 -0
- package/packages/pi-coding-agent/dist/modes/interactive/components/tool-card-cleanup-and-success-runtime.test.js +133 -0
- package/packages/pi-coding-agent/dist/modes/interactive/components/tool-card-cleanup-and-success-runtime.test.js.map +1 -0
- package/packages/pi-coding-agent/dist/modes/interactive/controllers/input-controller.js +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/controllers/input-controller.js.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/controllers/input-controller.test.js +14 -1
- package/packages/pi-coding-agent/dist/modes/interactive/controllers/input-controller.test.js.map +1 -1
- package/packages/pi-coding-agent/dist/tests/system-prompt-cache-stability.test.d.ts +2 -0
- package/packages/pi-coding-agent/dist/tests/system-prompt-cache-stability.test.d.ts.map +1 -0
- package/packages/pi-coding-agent/dist/tests/system-prompt-cache-stability.test.js +78 -0
- package/packages/pi-coding-agent/dist/tests/system-prompt-cache-stability.test.js.map +1 -0
- package/packages/pi-coding-agent/dist/tests/token-telemetry.test.d.ts +2 -0
- package/packages/pi-coding-agent/dist/tests/token-telemetry.test.d.ts.map +1 -0
- package/packages/pi-coding-agent/dist/tests/token-telemetry.test.js +181 -0
- package/packages/pi-coding-agent/dist/tests/token-telemetry.test.js.map +1 -0
- package/packages/pi-coding-agent/package.json +1 -1
- package/packages/pi-coding-agent/src/core/agent-session.ts +7 -0
- package/packages/pi-coding-agent/src/core/messages.ts +4 -0
- package/packages/pi-coding-agent/src/core/model-registry-auth-mode.test.ts +32 -2
- package/packages/pi-coding-agent/src/core/model-registry.ts +21 -0
- package/packages/pi-coding-agent/src/core/system-prompt.ts +33 -15
- package/packages/pi-coding-agent/src/core/token-telemetry.ts +77 -0
- package/packages/pi-coding-agent/src/modes/interactive/components/tool-card-cleanup-and-success-runtime.test.ts +212 -0
- package/packages/pi-coding-agent/src/modes/interactive/controllers/input-controller.test.ts +17 -1
- package/packages/pi-coding-agent/src/modes/interactive/controllers/input-controller.ts +1 -1
- package/packages/pi-coding-agent/src/tests/system-prompt-cache-stability.test.ts +102 -0
- package/packages/pi-coding-agent/src/tests/token-telemetry.test.ts +200 -0
- package/packages/pi-coding-agent/tsconfig.tsbuildinfo +1 -1
- package/packages/pi-tui/dist/__tests__/autocomplete.test.js +17 -3
- package/packages/pi-tui/dist/__tests__/autocomplete.test.js.map +1 -1
- package/packages/pi-tui/dist/components/__tests__/leak-fixes-runtime.test.d.ts +2 -0
- package/packages/pi-tui/dist/components/__tests__/leak-fixes-runtime.test.d.ts.map +1 -0
- package/packages/pi-tui/dist/components/__tests__/leak-fixes-runtime.test.js +161 -0
- package/packages/pi-tui/dist/components/__tests__/leak-fixes-runtime.test.js.map +1 -0
- package/packages/pi-tui/package.json +1 -1
- package/packages/pi-tui/src/__tests__/autocomplete.test.ts +20 -3
- package/packages/pi-tui/src/components/__tests__/leak-fixes-runtime.test.ts +219 -0
- package/packages/pi-tui/tsconfig.tsbuildinfo +1 -1
- package/packages/rpc-client/package.json +1 -1
- package/pkg/package.json +1 -1
- package/src/resources/extensions/claude-code-cli/readiness.ts +92 -47
- package/src/resources/extensions/google-search/index.ts +2 -9
- package/src/resources/extensions/gsd/auto/loop.ts +24 -2
- package/src/resources/extensions/gsd/auto/phases.ts +6 -14
- package/src/resources/extensions/gsd/auto/run-unit.ts +26 -12
- package/src/resources/extensions/gsd/auto/session.ts +5 -6
- package/src/resources/extensions/gsd/auto/types.ts +1 -0
- package/src/resources/extensions/gsd/auto-dashboard.ts +3 -2
- package/src/resources/extensions/gsd/auto-direct-dispatch.ts +60 -24
- package/src/resources/extensions/gsd/auto-dispatch.ts +18 -6
- package/src/resources/extensions/gsd/auto-prompts.ts +66 -2
- package/src/resources/extensions/gsd/auto-recovery.ts +46 -8
- package/src/resources/extensions/gsd/auto-runtime-state.ts +51 -0
- package/src/resources/extensions/gsd/auto-start.ts +1 -1
- package/src/resources/extensions/gsd/auto-tool-tracking.ts +2 -4
- package/src/resources/extensions/gsd/auto-worktree.ts +82 -12
- package/src/resources/extensions/gsd/auto.ts +37 -10
- package/src/resources/extensions/gsd/bootstrap/db-tools.ts +15 -13
- package/src/resources/extensions/gsd/bootstrap/exec-tools.ts +8 -7
- package/src/resources/extensions/gsd/bootstrap/query-tools.ts +2 -2
- package/src/resources/extensions/gsd/bootstrap/register-extension.ts +10 -9
- package/src/resources/extensions/gsd/bootstrap/register-hooks.ts +121 -31
- package/src/resources/extensions/gsd/bootstrap/register-shortcuts.ts +12 -6
- package/src/resources/extensions/gsd/bootstrap/subagent-input.ts +20 -0
- package/src/resources/extensions/gsd/bootstrap/system-context.ts +50 -8
- package/src/resources/extensions/gsd/bootstrap/write-gate.ts +141 -11
- package/src/resources/extensions/gsd/commands/catalog.ts +82 -5
- package/src/resources/extensions/gsd/commands/handlers/core.ts +23 -1
- package/src/resources/extensions/gsd/commands/handlers/ops.ts +10 -0
- package/src/resources/extensions/gsd/commands-config.ts +3 -2
- package/src/resources/extensions/gsd/commands-extensions.ts +43 -3
- package/src/resources/extensions/gsd/commands-handlers.ts +3 -2
- package/src/resources/extensions/gsd/commands-mcp-status.ts +3 -1
- package/src/resources/extensions/gsd/commands-prefs-wizard.ts +15 -1
- package/src/resources/extensions/gsd/commands-worktree.ts +383 -0
- package/src/resources/extensions/gsd/dashboard-overlay.ts +1 -1
- package/src/resources/extensions/gsd/docs/preferences-reference.md +10 -0
- package/src/resources/extensions/gsd/doctor-providers.ts +2 -1
- package/src/resources/extensions/gsd/doctor-runtime-checks.ts +39 -1
- package/src/resources/extensions/gsd/doctor-types.ts +3 -1
- package/src/resources/extensions/gsd/error-classifier.ts +1 -1
- package/src/resources/extensions/gsd/forensics.ts +12 -7
- package/src/resources/extensions/gsd/git-service.ts +13 -5
- package/src/resources/extensions/gsd/gsd-db.ts +12 -2
- package/src/resources/extensions/gsd/guided-flow.ts +27 -26
- package/src/resources/extensions/gsd/home-dir.ts +19 -0
- package/src/resources/extensions/gsd/journal.ts +4 -1
- package/src/resources/extensions/gsd/key-manager.ts +2 -1
- package/src/resources/extensions/gsd/memory-store.ts +81 -28
- package/src/resources/extensions/gsd/migrate/command.ts +3 -2
- package/src/resources/extensions/gsd/milestone-id-reservation.ts +47 -0
- package/src/resources/extensions/gsd/model-router.ts +172 -9
- package/src/resources/extensions/gsd/native-git-bridge.ts +7 -1
- package/src/resources/extensions/gsd/preferences-models.ts +101 -15
- package/src/resources/extensions/gsd/preferences-types.ts +6 -0
- package/src/resources/extensions/gsd/preferences-validation.ts +35 -0
- package/src/resources/extensions/gsd/preferences.ts +16 -2
- package/src/resources/extensions/gsd/prompt-loader.ts +26 -12
- package/src/resources/extensions/gsd/prompts/complete-milestone.md +10 -0
- package/src/resources/extensions/gsd/prompts/complete-slice.md +10 -0
- package/src/resources/extensions/gsd/prompts/guided-discuss-milestone.md +2 -0
- package/src/resources/extensions/gsd/prompts/parallel-research-slices.md +2 -0
- package/src/resources/extensions/gsd/prompts/plan-slice.md +10 -0
- package/src/resources/extensions/gsd/prompts/refine-slice.md +10 -0
- package/src/resources/extensions/gsd/prompts/rewrite-docs.md +2 -0
- package/src/resources/extensions/gsd/slice-parallel-orchestrator.ts +9 -3
- package/src/resources/extensions/gsd/state.ts +42 -0
- package/src/resources/extensions/gsd/templates/PREFERENCES.md +1 -0
- package/src/resources/extensions/gsd/tests/auto-loop.test.ts +179 -1
- package/src/resources/extensions/gsd/tests/auto-recovery.test.ts +58 -0
- package/src/resources/extensions/gsd/tests/auto-session-encapsulation.test.ts +24 -5
- package/src/resources/extensions/gsd/tests/auto-supervisor.test.mjs +21 -4
- package/src/resources/extensions/gsd/tests/bootstrap-derive-state-db-open.test.ts +1 -1
- package/src/resources/extensions/gsd/tests/budget-prediction.test.ts +138 -211
- package/src/resources/extensions/gsd/tests/bundled-skill-triggers.test.ts +50 -27
- package/src/resources/extensions/gsd/tests/commands-extensions-version-compare.test.ts +58 -0
- package/src/resources/extensions/gsd/tests/commands-worktree-clean.test.ts +48 -0
- package/src/resources/extensions/gsd/tests/complete-slice-verification-gate.test.ts +142 -59
- package/src/resources/extensions/gsd/tests/complete-slice.test.ts +7 -4
- package/src/resources/extensions/gsd/tests/completed-at-reconcile.test.ts +89 -32
- package/src/resources/extensions/gsd/tests/custom-engine-loop-integration.test.ts +41 -23
- package/src/resources/extensions/gsd/tests/db-path-worktree-symlink.test.ts +3 -43
- package/src/resources/extensions/gsd/tests/debug-logger.test.ts +5 -3
- package/src/resources/extensions/gsd/tests/deferred-milestone-dir-4996.test.ts +116 -0
- package/src/resources/extensions/gsd/tests/discuss-empty-db-fallback.test.ts +22 -87
- package/src/resources/extensions/gsd/tests/discuss-queued-milestones.test.ts +7 -118
- package/src/resources/extensions/gsd/tests/discuss-tool-scope-leak.test.ts +18 -60
- package/src/resources/extensions/gsd/tests/doctor-orphan-milestone-4996.test.ts +100 -0
- package/src/resources/extensions/gsd/tests/double-merge-guard.test.ts +14 -76
- package/src/resources/extensions/gsd/tests/ensure-preconditions-guard-4996.test.ts +93 -0
- package/src/resources/extensions/gsd/tests/false-degraded-mode-warning.test.ts +22 -83
- package/src/resources/extensions/gsd/tests/finalize-timeout-guard.test.ts +1 -63
- package/src/resources/extensions/gsd/tests/find-missing-summaries-closed-runtime.test.ts +47 -0
- package/src/resources/extensions/gsd/tests/forensics-stuck-loops.test.ts +26 -1
- package/src/resources/extensions/gsd/tests/gitignore-bg-shell-runtime.test.ts +63 -0
- package/src/resources/extensions/gsd/tests/google-search-stub.test.ts +25 -65
- package/src/resources/extensions/gsd/tests/gsd-db.test.ts +30 -0
- package/src/resources/extensions/gsd/tests/gsd-no-project-error-runtime.test.ts +81 -0
- package/src/resources/extensions/gsd/tests/headless-answers.test.ts +14 -4
- package/src/resources/extensions/gsd/tests/health-widget.test.ts +22 -12
- package/src/resources/extensions/gsd/tests/help-menu-coverage.test.ts +57 -0
- package/src/resources/extensions/gsd/tests/home-dir.test.ts +52 -0
- package/src/resources/extensions/gsd/tests/import-done-milestones-runtime.test.ts +145 -0
- package/src/resources/extensions/gsd/tests/init-prefs-routing.test.ts +64 -1
- package/src/resources/extensions/gsd/tests/integration/auto-worktree.test.ts +72 -1
- package/src/resources/extensions/gsd/tests/integration/token-savings.test.ts +0 -23
- package/src/resources/extensions/gsd/tests/memory-store.test.ts +128 -0
- package/src/resources/extensions/gsd/tests/memory-tools.test.ts +33 -1
- package/src/resources/extensions/gsd/tests/merge-self-branch-guard.test.ts +124 -0
- package/src/resources/extensions/gsd/tests/milestone-id-gap-reuse-4996.test.ts +152 -0
- package/src/resources/extensions/gsd/tests/milestone-report-path.test.ts +18 -1
- package/src/resources/extensions/gsd/tests/model-router.test.ts +169 -8
- package/src/resources/extensions/gsd/tests/native-git-infra-errors.test.ts +50 -0
- package/src/resources/extensions/gsd/tests/orphaned-worktree-audit.test.ts +8 -0
- package/src/resources/extensions/gsd/tests/parallel-crash-recovery.test.ts +32 -43
- package/src/resources/extensions/gsd/tests/phases-merge-error-stops-auto.test.ts +4 -10
- package/src/resources/extensions/gsd/tests/preferences.test.ts +127 -0
- package/src/resources/extensions/gsd/tests/prompt-step-ordering.test.ts +16 -0
- package/src/resources/extensions/gsd/tests/provider-errors.test.ts +7 -0
- package/src/resources/extensions/gsd/tests/quick-turn-end-cleanup.test.ts +6 -6
- package/src/resources/extensions/gsd/tests/register-hooks-compaction-checkpoint.test.ts +93 -0
- package/src/resources/extensions/gsd/tests/safety-harness-false-positives.test.ts +34 -0
- package/src/resources/extensions/gsd/tests/session-start-footer.test.ts +168 -19
- package/src/resources/extensions/gsd/tests/slice-parallel-orchestrator.test.ts +7 -1
- package/src/resources/extensions/gsd/tests/smart-entry-complete.test.ts +23 -1
- package/src/resources/extensions/gsd/tests/steer-worktree-path.test.ts +17 -1
- package/src/resources/extensions/gsd/tests/system-context-message-routing.test.ts +101 -0
- package/src/resources/extensions/gsd/tests/token-profile.test.ts +51 -4
- package/src/resources/extensions/gsd/tests/turn-epoch.test.ts +7 -16
- package/src/resources/extensions/gsd/tests/unit-context-manifest.test.ts +38 -3
- package/src/resources/extensions/gsd/tests/unstructured-continue-context-injection.test.ts +5 -7
- package/src/resources/extensions/gsd/tests/uok-gitops-turn-action.test.ts +15 -1
- package/src/resources/extensions/gsd/tests/visualizer-overlay.test.ts +6 -6
- package/src/resources/extensions/gsd/tests/worktree-path-injection.test.ts +235 -0
- package/src/resources/extensions/gsd/tests/worktree-symlink-removal.test.ts +34 -33
- package/src/resources/extensions/gsd/tests/worktree.test.ts +8 -0
- package/src/resources/extensions/gsd/tests/write-gate-planning-unit.test.ts +131 -1
- package/src/resources/extensions/gsd/tools/memory-tools.ts +17 -1
- package/src/resources/extensions/gsd/unit-context-manifest.ts +44 -12
- package/src/resources/extensions/gsd/visualizer-overlay.ts +1 -1
- package/src/resources/extensions/gsd/watch/header-renderer.ts +3 -1
- package/src/resources/extensions/gsd/workflow-logger.ts +1 -0
- package/src/resources/extensions/gsd/worktree-command.ts +31 -44
- package/src/resources/extensions/gsd/worktree-manager.ts +40 -1
- package/src/resources/extensions/gsd/worktree-resolver.ts +4 -14
- package/src/resources/extensions/gsd/worktree-root.ts +144 -0
- package/src/resources/extensions/gsd/worktree-session-state.ts +35 -0
- package/src/resources/extensions/gsd/worktree.ts +8 -119
- package/src/resources/extensions/mcp-client/index.ts +6 -10
- package/src/resources/extensions/mcp-client/tests/global-config.test.ts +91 -0
- package/src/resources/extensions/ollama/index.ts +16 -2
- package/src/resources/extensions/ollama/model-capabilities.ts +34 -0
- package/src/resources/extensions/ollama/ollama-client.ts +41 -4
- package/src/resources/extensions/ollama/tests/model-capabilities.test.ts +96 -0
- package/src/resources/extensions/ollama/tests/ollama-client-timeout-env.test.ts +147 -0
- package/src/resources/extensions/slash-commands/create-extension.ts +38 -24
- package/src/resources/extensions/subagent/index.ts +165 -7
- package/src/resources/skills/create-gsd-extension/SKILL.md +9 -5
- package/src/resources/skills/create-gsd-extension/references/custom-commands.md +1 -1
- package/src/resources/skills/create-gsd-extension/references/custom-rendering.md +5 -5
- package/src/resources/skills/create-gsd-extension/references/custom-tools.md +4 -4
- package/src/resources/skills/create-gsd-extension/references/custom-ui.md +6 -6
- package/src/resources/skills/create-gsd-extension/references/events-reference.md +3 -3
- package/src/resources/skills/create-gsd-extension/references/packaging-distribution.md +1 -1
- package/src/resources/skills/create-gsd-extension/references/remote-execution-overrides.md +3 -3
- package/src/resources/skills/create-gsd-extension/templates/extension-skeleton.ts +2 -2
- package/src/resources/skills/create-gsd-extension/templates/stateful-tool-skeleton.ts +3 -3
- package/src/resources/skills/create-gsd-extension/templates/templates.test.ts +58 -0
- package/src/resources/skills/create-gsd-extension/workflows/create-extension.md +32 -12
- package/src/resources/skills/lint/SKILL.md +4 -0
- package/src/resources/skills/review/SKILL.md +4 -0
- package/src/resources/skills/test/SKILL.md +3 -0
- package/dist/resources/extensions/browser-tools/tests/browser-tools-integration.test.mjs +0 -601
- package/dist/resources/extensions/browser-tools/tests/browser-tools-unit.test.cjs +0 -651
- package/dist/resources/extensions/browser-tools/tests/capture-sharp-optional.test.cjs +0 -91
- package/dist/resources/extensions/gsd/tests/auto-supervisor.test.mjs +0 -53
- package/dist/resources/extensions/gsd/tests/dist-redirect.mjs +0 -112
- package/dist/resources/extensions/gsd/tests/resolve-ts-hooks.mjs +0 -23
- package/dist/resources/extensions/gsd/tests/resolve-ts.mjs +0 -5
- package/dist/resources/skills/github-workflows/references/gh/tests/__init__.py +0 -0
- package/dist/resources/skills/github-workflows/references/gh/tests/test_github_project_setup.py +0 -608
- package/dist/web/standalone/.next/static/chunks/2826.e9f5195e91f9cad2.js +0 -11
- package/dist/web/standalone/.next/static/chunks/3621.fc7480022c972438.js +0 -20
- package/dist/web/standalone/.next/static/chunks/webpack-2e68521d7c82f7c2.js +0 -1
- package/src/resources/extensions/gsd/tests/copy-planning-artifacts-samepath.test.ts +0 -22
- package/src/resources/extensions/gsd/tests/discuss-slice-structured-questions.test.ts +0 -47
- package/src/resources/extensions/gsd/tests/empty-content-abort-loop.test.ts +0 -75
- /package/dist/web/standalone/.next/static/{cAJH99yNS1UPbeSEiNRrV → 4iu6IYeYfxOq8OidlDqp6}/_buildManifest.js +0 -0
- /package/dist/web/standalone/.next/static/{cAJH99yNS1UPbeSEiNRrV → 4iu6IYeYfxOq8OidlDqp6}/_ssgManifest.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-registry.js","sourceRoot":"","sources":["../../src/core/model-registry.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAA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,EAAE;YAC9D,KAAK,EAAE,CAAC,MAAM,CAAC;YACf,aAAa,EAAE,MAAM;YACrB,SAAS,EAAE,KAAK;SAChB,CAAC;IACH,CAAC;IAEO,eAAe,CAAC,QAAgB,EAAE,YAAyB;QAClE,KAAK,MAAM,GAAG,IAAI,YAAY,EAAE,CAAC;YAChC,IAAI,uBAAuB,CAAC,GAAG,CAAC,EAAE,CAAC;gBAClC,OAAO,aAAa,CAAC,QAAQ,CAAC,CAAC;YAChC,CAAC;QACF,CAAC;QACD,OAAO,aAAa,CAAC,QAAQ,CAAC,CAAC;IAChC,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,YAAY,CAAC,KAAiB;QACpC,OAAO,YAAY,CAAC,KAAK,CAAC,CAAC;IAC5B,CAAC;IAED;;;;OAIG;IACH,eAAe;QACd,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QAC7B,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,KAAK,CAAC;QACtC,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC;IAC7C,CAAC;CACD","sourcesContent":["/**\n * Model registry - manages built-in and custom models, provides API key resolution.\n */\n\nimport {\n\ttype Api,\n\tapplyCapabilityPatches,\n\ttype AssistantMessageEventStream,\n\ttype Context,\n\tgetApiProvider,\n\tgetEnvApiKey,\n\tgetModels,\n\tgetProviders,\n\ttype KnownProvider,\n\ttype Model,\n\ttype OAuthProviderInterface,\n\ttype OpenAICompletionsCompat,\n\ttype OpenAIResponsesCompat,\n\tregisterApiProvider,\n\tresetApiProviders,\n\ttype SimpleStreamOptions,\n} from \"@gsd/pi-ai\";\nimport { registerOAuthProvider, resetOAuthProviders } from \"@gsd/pi-ai/oauth\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport AjvModule from \"ajv\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { getAgentDir } from \"../config.js\";\nimport type { AuthStorage } from \"./auth-storage.js\";\nimport { ModelDiscoveryCache } from \"./discovery-cache.js\";\nimport type { DiscoveredModel, DiscoveryResult } from \"./model-discovery.js\";\nimport { getDefaultTTL, getDiscoverableProviders, getDiscoveryAdapter, supportsDiscoveryForApi } from \"./model-discovery.js\";\nimport { clearConfigValueCache, resolveConfigValue, resolveHeaders } from \"./resolve-config-value.js\";\nimport { isLocalModel } from \"./local-model-check.js\";\n\nconst Ajv = (AjvModule as any).default || AjvModule;\nconst ajv = new Ajv();\n\n// Schema for OpenRouter routing preferences\nconst OpenRouterRoutingSchema = Type.Object({\n\tonly: Type.Optional(Type.Array(Type.String())),\n\torder: Type.Optional(Type.Array(Type.String())),\n});\n\n// Schema for Vercel AI Gateway routing preferences\nconst VercelGatewayRoutingSchema = Type.Object({\n\tonly: Type.Optional(Type.Array(Type.String())),\n\torder: Type.Optional(Type.Array(Type.String())),\n});\n\n// Schema for model capability declarations (mirrors ModelCapabilities in pi-ai types)\nconst ModelCapabilitiesSchema = Type.Object({\n\tsupportsXhigh: Type.Optional(Type.Boolean()),\n\trequiresToolCallId: Type.Optional(Type.Boolean()),\n\tsupportsServiceTier: Type.Optional(Type.Boolean()),\n\tcharsPerToken: Type.Optional(Type.Number()),\n});\n\n// Schema for OpenAI compatibility settings\nconst OpenAICompletionsCompatSchema = Type.Object({\n\tsupportsStore: Type.Optional(Type.Boolean()),\n\tsupportsDeveloperRole: Type.Optional(Type.Boolean()),\n\tsupportsReasoningEffort: Type.Optional(Type.Boolean()),\n\tsupportsUsageInStreaming: Type.Optional(Type.Boolean()),\n\tmaxTokensField: Type.Optional(Type.Union([Type.Literal(\"max_completion_tokens\"), Type.Literal(\"max_tokens\")])),\n\trequiresToolResultName: Type.Optional(Type.Boolean()),\n\trequiresAssistantAfterToolResult: Type.Optional(Type.Boolean()),\n\trequiresThinkingAsText: Type.Optional(Type.Boolean()),\n\trequiresMistralToolIds: Type.Optional(Type.Boolean()),\n\tthinkingFormat: Type.Optional(Type.Union([Type.Literal(\"openai\"), Type.Literal(\"zai\"), Type.Literal(\"qwen\")])),\n\topenRouterRouting: Type.Optional(OpenRouterRoutingSchema),\n\tvercelGatewayRouting: Type.Optional(VercelGatewayRoutingSchema),\n});\n\nconst OpenAIResponsesCompatSchema = Type.Object({\n\t// Reserved for future use\n});\n\nconst OpenAICompatSchema = Type.Union([OpenAICompletionsCompatSchema, OpenAIResponsesCompatSchema]);\n\n// Schema for custom model definition\n// Most fields are optional with sensible defaults for local models (Ollama, LM Studio, etc.)\nconst ModelDefinitionSchema = Type.Object({\n\tid: Type.String({ minLength: 1 }),\n\tname: Type.Optional(Type.String({ minLength: 1 })),\n\tapi: Type.Optional(Type.String({ minLength: 1 })),\n\tbaseUrl: Type.Optional(Type.String({ minLength: 1 })),\n\treasoning: Type.Optional(Type.Boolean()),\n\tinput: Type.Optional(Type.Array(Type.Union([Type.Literal(\"text\"), Type.Literal(\"image\")]))),\n\tcost: Type.Optional(\n\t\tType.Object({\n\t\t\tinput: Type.Number(),\n\t\t\toutput: Type.Number(),\n\t\t\tcacheRead: Type.Number(),\n\t\t\tcacheWrite: Type.Number(),\n\t\t}),\n\t),\n\tcontextWindow: Type.Optional(Type.Number()),\n\tmaxTokens: Type.Optional(Type.Number()),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tcompat: Type.Optional(OpenAICompatSchema),\n\tcapabilities: Type.Optional(ModelCapabilitiesSchema),\n});\n\n// Schema for per-model overrides (all fields optional, merged with built-in model)\nconst ModelOverrideSchema = Type.Object({\n\tname: Type.Optional(Type.String({ minLength: 1 })),\n\treasoning: Type.Optional(Type.Boolean()),\n\tinput: Type.Optional(Type.Array(Type.Union([Type.Literal(\"text\"), Type.Literal(\"image\")]))),\n\tcost: Type.Optional(\n\t\tType.Object({\n\t\t\tinput: Type.Optional(Type.Number()),\n\t\t\toutput: Type.Optional(Type.Number()),\n\t\t\tcacheRead: Type.Optional(Type.Number()),\n\t\t\tcacheWrite: Type.Optional(Type.Number()),\n\t\t}),\n\t),\n\tcontextWindow: Type.Optional(Type.Number()),\n\tmaxTokens: Type.Optional(Type.Number()),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tcompat: Type.Optional(OpenAICompatSchema),\n\tcapabilities: Type.Optional(ModelCapabilitiesSchema),\n});\n\ntype ModelOverride = Static<typeof ModelOverrideSchema>;\n\nconst ProviderConfigSchema = Type.Object({\n\tbaseUrl: Type.Optional(Type.String({ minLength: 1 })),\n\tapiKey: Type.Optional(Type.String({ minLength: 1 })),\n\tapi: Type.Optional(Type.String({ minLength: 1 })),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tauthHeader: Type.Optional(Type.Boolean()),\n\tmodels: Type.Optional(Type.Array(ModelDefinitionSchema)),\n\tmodelOverrides: Type.Optional(Type.Record(Type.String(), ModelOverrideSchema)),\n});\n\nconst ModelsConfigSchema = Type.Object({\n\tproviders: Type.Record(Type.String(), ProviderConfigSchema),\n});\n\najv.addSchema(ModelsConfigSchema, \"ModelsConfig\");\n\ntype ModelsConfig = Static<typeof ModelsConfigSchema>;\n\nexport type ProviderAuthMode = \"apiKey\" | \"oauth\" | \"externalCli\" | \"none\";\n\n/** Provider override config (baseUrl, headers, apiKey) without custom models */\ninterface ProviderOverride {\n\tbaseUrl?: string;\n\theaders?: Record<string, string>;\n\tapiKey?: string;\n}\n\n/** Result of loading custom models from models.json */\ninterface CustomModelsResult {\n\tmodels: Model<Api>[];\n\t/** Providers with baseUrl/headers/apiKey overrides for built-in models */\n\toverrides: Map<string, ProviderOverride>;\n\t/** Per-model overrides: provider -> modelId -> override */\n\tmodelOverrides: Map<string, Map<string, ModelOverride>>;\n\terror: string | undefined;\n}\n\nfunction emptyCustomModelsResult(error?: string): CustomModelsResult {\n\treturn { models: [], overrides: new Map(), modelOverrides: new Map(), error };\n}\n\nfunction mergeCompat(\n\tbaseCompat: Model<Api>[\"compat\"],\n\toverrideCompat: ModelOverride[\"compat\"],\n): Model<Api>[\"compat\"] | undefined {\n\tif (!overrideCompat) return baseCompat;\n\n\tconst base = baseCompat as OpenAICompletionsCompat | OpenAIResponsesCompat | undefined;\n\tconst override = overrideCompat as OpenAICompletionsCompat | OpenAIResponsesCompat;\n\tconst merged = { ...base, ...override } as OpenAICompletionsCompat | OpenAIResponsesCompat;\n\n\tconst baseCompletions = base as OpenAICompletionsCompat | undefined;\n\tconst overrideCompletions = override as OpenAICompletionsCompat;\n\tconst mergedCompletions = merged as OpenAICompletionsCompat;\n\n\tif (baseCompletions?.openRouterRouting || overrideCompletions.openRouterRouting) {\n\t\tmergedCompletions.openRouterRouting = {\n\t\t\t...baseCompletions?.openRouterRouting,\n\t\t\t...overrideCompletions.openRouterRouting,\n\t\t};\n\t}\n\n\tif (baseCompletions?.vercelGatewayRouting || overrideCompletions.vercelGatewayRouting) {\n\t\tmergedCompletions.vercelGatewayRouting = {\n\t\t\t...baseCompletions?.vercelGatewayRouting,\n\t\t\t...overrideCompletions.vercelGatewayRouting,\n\t\t};\n\t}\n\n\treturn merged as Model<Api>[\"compat\"];\n}\n\n/**\n * Deep merge a model override into a model.\n * Handles nested objects (cost, compat) by merging rather than replacing.\n */\nfunction applyModelOverride(model: Model<Api>, override: ModelOverride): Model<Api> {\n\tconst result = { ...model };\n\n\t// Simple field overrides\n\tif (override.name !== undefined) result.name = override.name;\n\tif (override.reasoning !== undefined) result.reasoning = override.reasoning;\n\tif (override.input !== undefined) result.input = override.input as (\"text\" | \"image\")[];\n\tif (override.contextWindow !== undefined) result.contextWindow = override.contextWindow;\n\tif (override.maxTokens !== undefined) result.maxTokens = override.maxTokens;\n\n\t// Merge cost (partial override)\n\tif (override.cost) {\n\t\tresult.cost = {\n\t\t\tinput: override.cost.input ?? model.cost.input,\n\t\t\toutput: override.cost.output ?? model.cost.output,\n\t\t\tcacheRead: override.cost.cacheRead ?? model.cost.cacheRead,\n\t\t\tcacheWrite: override.cost.cacheWrite ?? model.cost.cacheWrite,\n\t\t};\n\t}\n\n\t// Merge headers\n\tif (override.headers) {\n\t\tconst resolvedHeaders = resolveHeaders(override.headers);\n\t\tresult.headers = resolvedHeaders ? { ...model.headers, ...resolvedHeaders } : model.headers;\n\t}\n\n\t// Deep merge compat\n\tresult.compat = mergeCompat(model.compat, override.compat);\n\n\t// Merge capabilities (override wins per-field)\n\tif (override.capabilities) {\n\t\tresult.capabilities = { ...model.capabilities, ...override.capabilities };\n\t}\n\n\treturn result;\n}\n\n\n/**\n * Model registry - loads and manages models, resolves API keys via AuthStorage.\n */\nexport class ModelRegistry {\n\tprivate models: Model<Api>[] = [];\n\tprivate discoveredModels: Model<Api>[] = [];\n\tprivate discoveryCache: ModelDiscoveryCache;\n\tprivate customProviderApiKeys: Map<string, string> = new Map();\n\tprivate registeredProviders: Map<string, ProviderConfigInput> = new Map();\n\tprivate loadError: string | undefined = undefined;\n\n\tconstructor(\n\t\treadonly authStorage: AuthStorage,\n\t\treadonly modelsJsonPath: string | undefined = join(getAgentDir(), \"models.json\"),\n\t) {\n\t\tthis.discoveryCache = new ModelDiscoveryCache();\n\n\t\t// Set up fallback resolver for custom provider API keys\n\t\tthis.authStorage.setFallbackResolver((provider) => {\n\t\t\tconst keyConfig = this.customProviderApiKeys.get(provider);\n\t\t\tif (keyConfig) {\n\t\t\t\treturn resolveConfigValue(keyConfig);\n\t\t\t}\n\t\t\treturn getEnvApiKey(provider);\n\t\t});\n\n\t\t// Refresh models when credentials change (e.g., OAuth token refresh with new model limits)\n\t\tthis.authStorage.onCredentialChange(() => this.refresh());\n\n\t\t// Load models\n\t\tthis.loadModels();\n\t}\n\n\t/**\n\t * Reload models from disk (built-in + custom from models.json).\n\t */\n\trefresh(): void {\n\t\tthis.customProviderApiKeys.clear();\n\t\tthis.loadError = undefined;\n\n\t\t// Ensure dynamic API/OAuth registrations are rebuilt from current provider state.\n\t\tresetApiProviders();\n\t\tresetOAuthProviders();\n\n\t\tthis.loadModels();\n\n\t\tfor (const [providerName, config] of this.registeredProviders.entries()) {\n\t\t\tthis.applyProviderConfig(providerName, config);\n\t\t}\n\t}\n\n\t/**\n\t * Get any error from loading models.json (undefined if no error).\n\t */\n\tgetError(): string | undefined {\n\t\treturn this.loadError;\n\t}\n\n\tprivate loadModels(): void {\n\t\t// Load custom models and overrides from models.json\n\t\tconst {\n\t\t\tmodels: customModels,\n\t\t\toverrides,\n\t\t\tmodelOverrides,\n\t\t\terror,\n\t\t} = this.modelsJsonPath ? this.loadCustomModels(this.modelsJsonPath) : emptyCustomModelsResult();\n\n\t\tif (error) {\n\t\t\tthis.loadError = error;\n\t\t\t// Keep built-in models even if custom models failed to load\n\t\t}\n\n\t\tconst builtInModels = this.loadBuiltInModels(overrides, modelOverrides);\n\t\tlet combined = this.mergeCustomModels(builtInModels, customModels);\n\n\t\t// Let OAuth providers modify their models (e.g., update baseUrl)\n\t\tfor (const oauthProvider of this.authStorage.getOAuthProviders()) {\n\t\t\tconst cred = this.authStorage.get(oauthProvider.id);\n\t\t\tif (cred?.type === \"oauth\" && oauthProvider.modifyModels) {\n\t\t\t\tcombined = oauthProvider.modifyModels(combined, cred);\n\t\t\t}\n\t\t}\n\n\t\t// Apply capability patches so custom/discovered/extension models get\n\t\t// capabilities (supportsXhigh, supportsServiceTier, etc.) that the\n\t\t// static pi-ai registry applies at module load for built-in models.\n\t\tthis.models = applyCapabilityPatches(combined);\n\t}\n\n\t/** Load built-in models and apply provider/model overrides */\n\tprivate loadBuiltInModels(\n\t\toverrides: Map<string, ProviderOverride>,\n\t\tmodelOverrides: Map<string, Map<string, ModelOverride>>,\n\t): Model<Api>[] {\n\t\treturn getProviders().flatMap((provider) => {\n\t\t\tconst models = getModels(provider as KnownProvider) as Model<Api>[];\n\t\t\tconst providerOverride = overrides.get(provider);\n\t\t\tconst perModelOverrides = modelOverrides.get(provider);\n\n\t\t\treturn models.map((m) => {\n\t\t\t\tlet model = m;\n\n\t\t\t\t// Apply provider-level baseUrl/headers override\n\t\t\t\tif (providerOverride) {\n\t\t\t\t\tconst resolvedHeaders = resolveHeaders(providerOverride.headers);\n\t\t\t\t\tmodel = {\n\t\t\t\t\t\t...model,\n\t\t\t\t\t\tbaseUrl: providerOverride.baseUrl ?? model.baseUrl,\n\t\t\t\t\t\theaders: resolvedHeaders ? { ...model.headers, ...resolvedHeaders } : model.headers,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Apply per-model override\n\t\t\t\tconst modelOverride = perModelOverrides?.get(m.id);\n\t\t\t\tif (modelOverride) {\n\t\t\t\t\tmodel = applyModelOverride(model, modelOverride);\n\t\t\t\t}\n\n\t\t\t\treturn model;\n\t\t\t});\n\t\t});\n\t}\n\n\t/** Merge custom models into built-in list by provider+id (custom wins on conflicts). */\n\tprivate mergeCustomModels(builtInModels: Model<Api>[], customModels: Model<Api>[]): Model<Api>[] {\n\t\tconst merged = [...builtInModels];\n\t\tfor (const customModel of customModels) {\n\t\t\tconst existingIndex = merged.findIndex((m) => m.provider === customModel.provider && m.id === customModel.id);\n\t\t\tif (existingIndex >= 0) {\n\t\t\t\tmerged[existingIndex] = customModel;\n\t\t\t} else {\n\t\t\t\tmerged.push(customModel);\n\t\t\t}\n\t\t}\n\t\treturn merged;\n\t}\n\n\tprivate loadCustomModels(modelsJsonPath: string): CustomModelsResult {\n\t\tif (!existsSync(modelsJsonPath)) {\n\t\t\treturn emptyCustomModelsResult();\n\t\t}\n\n\t\ttry {\n\t\t\tconst content = readFileSync(modelsJsonPath, \"utf-8\");\n\t\t\tconst config: ModelsConfig = JSON.parse(content);\n\n\t\t\t// Validate schema\n\t\t\tconst validate = ajv.getSchema(\"ModelsConfig\")!;\n\t\t\tif (!validate(config)) {\n\t\t\t\tconst errors =\n\t\t\t\t\tvalidate.errors?.map((e: any) => ` - ${e.instancePath || \"root\"}: ${e.message}`).join(\"\\n\") ||\n\t\t\t\t\t\"Unknown schema error\";\n\t\t\t\treturn emptyCustomModelsResult(`Invalid models.json schema:\\n${errors}\\n\\nFile: ${modelsJsonPath}`);\n\t\t\t}\n\n\t\t\t// Additional validation\n\t\t\tthis.validateConfig(config);\n\n\t\t\tconst overrides = new Map<string, ProviderOverride>();\n\t\t\tconst modelOverrides = new Map<string, Map<string, ModelOverride>>();\n\n\t\t\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t\t\t// Apply provider-level baseUrl/headers/apiKey override to built-in models when configured.\n\t\t\t\tif (providerConfig.baseUrl || providerConfig.headers || providerConfig.apiKey) {\n\t\t\t\t\toverrides.set(providerName, {\n\t\t\t\t\t\tbaseUrl: providerConfig.baseUrl,\n\t\t\t\t\t\theaders: providerConfig.headers,\n\t\t\t\t\t\tapiKey: providerConfig.apiKey,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// Store API key for fallback resolver.\n\t\t\t\tif (providerConfig.apiKey) {\n\t\t\t\t\tthis.customProviderApiKeys.set(providerName, providerConfig.apiKey);\n\t\t\t\t}\n\n\t\t\t\tif (providerConfig.modelOverrides) {\n\t\t\t\t\tmodelOverrides.set(providerName, new Map(Object.entries(providerConfig.modelOverrides)));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn { models: this.parseModels(config), overrides, modelOverrides, error: undefined };\n\t\t} catch (error) {\n\t\t\tif (error instanceof SyntaxError) {\n\t\t\t\treturn emptyCustomModelsResult(`Failed to parse models.json: ${error.message}\\n\\nFile: ${modelsJsonPath}`);\n\t\t\t}\n\t\t\treturn emptyCustomModelsResult(\n\t\t\t\t`Failed to load models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${modelsJsonPath}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate validateConfig(config: ModelsConfig): void {\n\t\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t\tconst hasProviderApi = !!providerConfig.api;\n\t\t\tconst models = providerConfig.models ?? [];\n\t\t\tconst hasModelOverrides =\n\t\t\t\tproviderConfig.modelOverrides && Object.keys(providerConfig.modelOverrides).length > 0;\n\n\t\t\tif (models.length === 0) {\n\t\t\t\t// Override-only config: needs baseUrl OR modelOverrides (or both)\n\t\t\t\tif (!providerConfig.baseUrl && !hasModelOverrides) {\n\t\t\t\t\tthrow new Error(`Provider ${providerName}: must specify \"baseUrl\", \"modelOverrides\", or \"models\".`);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Custom models are merged into provider models and require endpoint + auth.\n\t\t\t\tif (!providerConfig.baseUrl) {\n\t\t\t\t\tthrow new Error(`Provider ${providerName}: \"baseUrl\" is required when defining custom models.`);\n\t\t\t\t}\n\t\t\t\tif (!providerConfig.apiKey) {\n\t\t\t\t\tthrow new Error(`Provider ${providerName}: \"apiKey\" is required when defining custom models.`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const modelDef of models) {\n\t\t\t\tconst hasModelApi = !!modelDef.api;\n\n\t\t\t\tif (!hasProviderApi && !hasModelApi) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Provider ${providerName}, model ${modelDef.id}: no \"api\" specified. Set at provider or model level.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (!modelDef.id) throw new Error(`Provider ${providerName}: model missing \"id\"`);\n\t\t\t\t// Validate contextWindow/maxTokens only if provided (they have defaults)\n\t\t\t\tif (modelDef.contextWindow !== undefined && modelDef.contextWindow <= 0)\n\t\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid contextWindow`);\n\t\t\t\tif (modelDef.maxTokens !== undefined && modelDef.maxTokens <= 0)\n\t\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid maxTokens`);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate parseModels(config: ModelsConfig): Model<Api>[] {\n\t\tconst models: Model<Api>[] = [];\n\n\t\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t\tconst modelDefs = providerConfig.models ?? [];\n\t\t\tif (modelDefs.length === 0) continue; // Override-only, no custom models\n\n\t\t\t// Store API key config for fallback resolver\n\t\t\tif (providerConfig.apiKey) {\n\t\t\t\tthis.customProviderApiKeys.set(providerName, providerConfig.apiKey);\n\t\t\t}\n\n\t\t\t// Register custom providers so isProviderRequestReady() can find\n\t\t\t// them (#3531). Without this, models.json providers with apiKey\n\t\t\t// fail the auth check and are invisible to the fallback resolver.\n\t\t\tif (!this.registeredProviders.has(providerName)) {\n\t\t\t\tthis.registeredProviders.set(providerName, {\n\t\t\t\t\tauthMode: providerConfig.apiKey ? \"apiKey\" : \"none\",\n\t\t\t\t\tapiKey: providerConfig.apiKey,\n\t\t\t\t\tbaseUrl: providerConfig.baseUrl,\n\t\t\t\t\tisReady: providerConfig.apiKey ? () => true : undefined,\n\t\t\t\t} as any);\n\t\t\t}\n\n\t\t\tfor (const modelDef of modelDefs) {\n\t\t\t\tconst api = modelDef.api || providerConfig.api;\n\t\t\t\tif (!api) continue;\n\n\t\t\t\t// Merge headers: provider headers are base, model headers override\n\t\t\t\t// Resolve env vars and shell commands in header values\n\t\t\t\tconst providerHeaders = resolveHeaders(providerConfig.headers);\n\t\t\t\tconst modelHeaders = resolveHeaders(modelDef.headers);\n\t\t\t\tlet headers = providerHeaders || modelHeaders ? { ...providerHeaders, ...modelHeaders } : undefined;\n\n\t\t\t\t// If authHeader is true, add Authorization header with resolved API key\n\t\t\t\tif (providerConfig.authHeader && providerConfig.apiKey) {\n\t\t\t\t\tconst resolvedKey = resolveConfigValue(providerConfig.apiKey);\n\t\t\t\t\tif (resolvedKey) {\n\t\t\t\t\t\theaders = { ...headers, Authorization: `Bearer ${resolvedKey}` };\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Provider baseUrl is required when custom models are defined.\n\t\t\t\t// Individual models can override it with modelDef.baseUrl.\n\t\t\t\tconst defaultCost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\n\t\t\t\tmodels.push({\n\t\t\t\t\tid: modelDef.id,\n\t\t\t\t\tname: modelDef.name ?? modelDef.id,\n\t\t\t\t\tapi: api as Api,\n\t\t\t\t\tprovider: providerName,\n\t\t\t\t\tbaseUrl: modelDef.baseUrl ?? providerConfig.baseUrl!,\n\t\t\t\t\treasoning: modelDef.reasoning ?? false,\n\t\t\t\t\tinput: (modelDef.input ?? [\"text\"]) as (\"text\" | \"image\")[],\n\t\t\t\t\tcost: modelDef.cost ?? defaultCost,\n\t\t\t\t\tcontextWindow: modelDef.contextWindow ?? 128000,\n\t\t\t\t\tmaxTokens: modelDef.maxTokens ?? 16384,\n\t\t\t\t\theaders,\n\t\t\t\t\tcompat: modelDef.compat,\n\t\t\t\t\tcapabilities: modelDef.capabilities,\n\t\t\t\t} as Model<Api>);\n\t\t\t}\n\t\t}\n\n\t\treturn models;\n\t}\n\n\t/**\n\t * Get all models (built-in + custom).\n\t * If models.json had errors, returns only built-in models.\n\t */\n\tgetAll(): Model<Api>[] {\n\t\treturn this.models;\n\t}\n\n\t/**\n\t * Get only models that have auth configured.\n\t * This is a fast check that doesn't refresh OAuth tokens.\n\t */\n\tgetAvailable(): Model<Api>[] {\n\t\treturn this.models.filter((m) => this.isProviderRequestReady(m.provider));\n\t}\n\n\t/**\n\t * Get auth mode for a provider.\n\t * Defaults to \"apiKey\" for built-ins and providers without explicit mode.\n\t */\n\tgetProviderAuthMode(provider: string): ProviderAuthMode {\n\t\tconst config = this.registeredProviders.get(provider);\n\t\tif (!config) return \"apiKey\";\n\t\tif (config.authMode) return config.authMode;\n\t\tif (config.oauth) return \"oauth\";\n\t\tif (config.apiKey) return \"apiKey\";\n\t\treturn \"apiKey\";\n\t}\n\n\t/**\n\t * Whether a provider can be used for requests/fallback without hard auth gating.\n\t */\n\tisProviderRequestReady(provider: string): boolean {\n\t\tconst config = this.registeredProviders.get(provider);\n\t\tif (config?.isReady) return config.isReady();\n\t\tconst authMode = this.getProviderAuthMode(provider);\n\t\tif (authMode === \"externalCli\" || authMode === \"none\") return true;\n\t\treturn this.authStorage.hasAuth(provider);\n\t}\n\n\t/**\n\t * Find a model by provider and ID.\n\t */\n\tfind(provider: string, modelId: string): Model<Api> | undefined {\n\t\treturn this.models.find((m) => m.provider === provider && m.id === modelId);\n\t}\n\n\t/**\n\t * Get API key for a model.\n\t * Returns undefined for externalCli/none providers (no key needed).\n\t * @param sessionId - Optional session ID for sticky credential selection\n\t */\n\tasync getApiKey(model: Model<Api>, sessionId?: string): Promise<string | undefined> {\n\t\tconst authMode = this.getProviderAuthMode(model.provider);\n\t\tif (authMode === \"externalCli\" || authMode === \"none\") return undefined;\n\t\treturn this.authStorage.getApiKey(model.provider, sessionId, { baseUrl: model.baseUrl });\n\t}\n\n\t/**\n\t * Get API key for a provider.\n\t * Returns undefined for externalCli/none providers (no key needed).\n\t * @param sessionId - Optional session ID for sticky credential selection\n\t */\n\tasync getApiKeyForProvider(provider: string, sessionId?: string): Promise<string | undefined> {\n\t\tconst authMode = this.getProviderAuthMode(provider);\n\t\tif (authMode === \"externalCli\" || authMode === \"none\") return undefined;\n\t\treturn this.authStorage.getApiKey(provider, sessionId);\n\t}\n\n\t/**\n\t * Check if a model is using OAuth credentials (subscription).\n\t */\n\tisUsingOAuth(model: Model<Api>): boolean {\n\t\tconst cred = this.authStorage.get(model.provider);\n\t\treturn cred?.type === \"oauth\";\n\t}\n\n\t/**\n\t * Register a provider dynamically (from extensions).\n\t *\n\t * If provider has models: replaces all existing models for this provider.\n\t * If provider has only baseUrl/headers: overrides existing models' URLs.\n\t * If provider has oauth: registers OAuth provider for /login support.\n\t */\n\tregisterProvider(providerName: string, config: ProviderConfigInput): void {\n\t\tthis.registeredProviders.set(providerName, config);\n\t\tthis.applyProviderConfig(providerName, config);\n\t}\n\n\t/**\n\t * Unregister a previously registered provider.\n\t *\n\t * Removes the provider from the registry and reloads models from disk so that\n\t * built-in models overridden by this provider are restored to their original state.\n\t * Also resets dynamic OAuth and API stream registrations before reapplying\n\t * remaining dynamic providers.\n\t * Has no effect if the provider was never registered.\n\t */\n\tunregisterProvider(providerName: string): void {\n\t\tif (!this.registeredProviders.has(providerName)) return;\n\t\tthis.registeredProviders.delete(providerName);\n\t\tthis.customProviderApiKeys.delete(providerName);\n\t\tthis.refresh();\n\t}\n\n\tprivate applyProviderConfig(providerName: string, config: ProviderConfigInput): void {\n\t\t// Register OAuth provider if provided\n\t\tif (config.oauth) {\n\t\t\t// Ensure the OAuth provider ID matches the provider name\n\t\t\tconst oauthProvider: OAuthProviderInterface = {\n\t\t\t\t...config.oauth,\n\t\t\t\tid: providerName,\n\t\t\t};\n\t\t\tregisterOAuthProvider(oauthProvider);\n\t\t}\n\n\t\tif (config.streamSimple) {\n\t\t\tif (!config.api) {\n\t\t\t\tthrow new Error(`Provider ${providerName}: \"api\" is required when registering streamSimple.`);\n\t\t\t}\n\t\t\tconst rawStreamSimple = config.streamSimple;\n\t\t\tconst authMode = config.authMode ?? \"apiKey\";\n\n\t\t\t// Keyless providers never see apiKey in options — enforced at registration,\n\t\t\t// not by convention. Prevents undefined from reaching any handler.\n\t\t\tconst streamSimple = (authMode === \"externalCli\" || authMode === \"none\")\n\t\t\t\t? ((model: Model<Api>, context: Context, options?: SimpleStreamOptions) => {\n\t\t\t\t\t\tconst { apiKey: _, ...opts } = options ?? {};\n\t\t\t\t\t\treturn rawStreamSimple(model, context, opts as SimpleStreamOptions);\n\t\t\t\t\t})\n\t\t\t\t: rawStreamSimple;\n\n\t\t\t// Guard: if there's already a handler registered for this API, wrap\n\t\t\t// the new one so it only fires for models from this provider and\n\t\t\t// delegates to the previous handler for all other providers. Without\n\t\t\t// this, a custom provider using api:\"anthropic-messages\" would clobber\n\t\t\t// the built-in Anthropic stream handler (#2536).\n\t\t\tconst existingProvider = getApiProvider(config.api as Api);\n\t\t\tconst scopedStream = existingProvider\n\t\t\t\t? (model: Model<Api>, context: Context, options?: SimpleStreamOptions): AssistantMessageEventStream => {\n\t\t\t\t\t\tif (model.provider === providerName) {\n\t\t\t\t\t\t\treturn streamSimple(model, context, options);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn existingProvider.streamSimple(model, context, options);\n\t\t\t\t\t}\n\t\t\t\t: streamSimple;\n\n\t\t\tconst newFullStream = (model: Model<Api>, context: Context, options?: SimpleStreamOptions) =>\n\t\t\t\tscopedStream(model, context, options as SimpleStreamOptions);\n\t\t\tconst scopedFullStream = existingProvider\n\t\t\t\t? (model: Model<Api>, context: Context, options?: Record<string, unknown>) => {\n\t\t\t\t\t\tif (model.provider === providerName) {\n\t\t\t\t\t\t\treturn newFullStream(model, context, options as SimpleStreamOptions);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn existingProvider.stream(model, context, options);\n\t\t\t\t\t}\n\t\t\t\t: newFullStream;\n\n\t\t\tregisterApiProvider(\n\t\t\t\t{\n\t\t\t\t\tapi: config.api,\n\t\t\t\t\tstream: scopedFullStream as any,\n\t\t\t\t\tstreamSimple: scopedStream,\n\t\t\t\t},\n\t\t\t\t`provider:${providerName}`,\n\t\t\t);\n\t\t}\n\n\t\t// Store API key for auth resolution\n\t\tif (config.apiKey) {\n\t\t\tthis.customProviderApiKeys.set(providerName, config.apiKey);\n\t\t}\n\n\t\tif (config.models && config.models.length > 0) {\n\t\t\t// Full replacement: remove existing models for this provider\n\t\t\tthis.models = this.models.filter((m) => m.provider !== providerName);\n\n\t\t\t// Validate required fields\n\t\t\tif (!config.baseUrl) {\n\t\t\t\tthrow new Error(`Provider ${providerName}: \"baseUrl\" is required when defining models.`);\n\t\t\t}\n\t\t\tconst authMode = config.authMode ?? (config.oauth ? \"oauth\" : config.apiKey ? \"apiKey\" : \"apiKey\");\n\t\t\tif (authMode === \"apiKey\" && !config.apiKey && !config.oauth) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Provider ${providerName}: \"apiKey\" or \"oauth\" is required when authMode is \"apiKey\" (the default). ` +\n\t\t\t\t\t`Set authMode to \"externalCli\" or \"none\" for keyless providers.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif ((authMode === \"externalCli\" || authMode === \"none\") && !config.streamSimple) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Provider ${providerName}: \"streamSimple\" is required when authMode is \"${authMode}\". ` +\n\t\t\t\t\t`Keyless providers must supply their own stream handler.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif ((authMode === \"externalCli\" || authMode === \"none\") && config.apiKey) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Provider ${providerName}: \"apiKey\" cannot be set when authMode is \"${authMode}\". ` +\n\t\t\t\t\t`Keyless providers should not provide API key credentials.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Parse and add new models\n\t\t\tfor (const modelDef of config.models) {\n\t\t\t\tconst api = modelDef.api || config.api;\n\t\t\t\tif (!api) {\n\t\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: no \"api\" specified.`);\n\t\t\t\t}\n\n\t\t\t\t// Merge headers\n\t\t\t\tconst providerHeaders = resolveHeaders(config.headers);\n\t\t\t\tconst modelHeaders = resolveHeaders(modelDef.headers);\n\t\t\t\tlet headers = providerHeaders || modelHeaders ? { ...providerHeaders, ...modelHeaders } : undefined;\n\n\t\t\t\t// If authHeader is true, add Authorization header\n\t\t\t\tif (config.authHeader && config.apiKey) {\n\t\t\t\t\tconst resolvedKey = resolveConfigValue(config.apiKey);\n\t\t\t\t\tif (resolvedKey) {\n\t\t\t\t\t\theaders = { ...headers, Authorization: `Bearer ${resolvedKey}` };\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthis.models.push({\n\t\t\t\t\tid: modelDef.id,\n\t\t\t\t\tname: modelDef.name,\n\t\t\t\t\tapi: api as Api,\n\t\t\t\t\tprovider: providerName,\n\t\t\t\t\tbaseUrl: config.baseUrl,\n\t\t\t\t\treasoning: modelDef.reasoning,\n\t\t\t\t\tinput: modelDef.input as (\"text\" | \"image\")[],\n\t\t\t\t\tcost: modelDef.cost,\n\t\t\t\t\tcontextWindow: modelDef.contextWindow,\n\t\t\t\t\tmaxTokens: modelDef.maxTokens,\n\t\t\t\t\theaders,\n\t\t\t\t\tcompat: modelDef.compat,\n\t\t\t\t\tproviderOptions: modelDef.providerOptions,\n\t\t\t\t} as Model<Api>);\n\t\t\t}\n\n\t\t\t// Apply OAuth modifyModels if credentials exist (e.g., to update baseUrl)\n\t\t\tif (config.oauth?.modifyModels) {\n\t\t\t\tconst cred = this.authStorage.get(providerName);\n\t\t\t\tif (cred?.type === \"oauth\") {\n\t\t\t\t\tthis.models = config.oauth.modifyModels(this.models, cred);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Ensure newly added extension models get capability patches\n\t\t\tthis.models = applyCapabilityPatches(this.models);\n\t\t} else if (config.baseUrl) {\n\t\t\t// Override-only: update baseUrl/headers for existing models\n\t\t\tconst resolvedHeaders = resolveHeaders(config.headers);\n\t\t\tthis.models = this.models.map((m) => {\n\t\t\t\tif (m.provider !== providerName) return m;\n\t\t\t\treturn {\n\t\t\t\t\t...m,\n\t\t\t\t\tbaseUrl: config.baseUrl ?? m.baseUrl,\n\t\t\t\t\theaders: resolvedHeaders ? { ...m.headers, ...resolvedHeaders } : m.headers,\n\t\t\t\t};\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Discover models from all providers that support discovery.\n\t * Results are cached and merged into the registry (never overrides existing models).\n\t */\n\tasync discoverModels(providers?: string[]): Promise<DiscoveryResult[]> {\n\t\tconst targetProviders = providers ?? this.getAutoDiscoverableProviders();\n\t\tconst results: DiscoveryResult[] = [];\n\n\t\tfor (const providerName of targetProviders) {\n\t\t\tconst providerApis = this.getProviderApis(providerName);\n\t\t\tconst adapter = getDiscoveryAdapter(providerName, providerApis);\n\t\t\tif (!adapter.supportsDiscovery) continue;\n\n\t\t\t// Skip if cache is still fresh\n\t\t\tif (!this.discoveryCache.isStale(providerName)) {\n\t\t\t\tconst cached = this.discoveryCache.get(providerName);\n\t\t\t\tif (cached) {\n\t\t\t\t\tresults.push({\n\t\t\t\t\t\tprovider: providerName,\n\t\t\t\t\t\tmodels: cached.models,\n\t\t\t\t\t\tfetchedAt: cached.fetchedAt,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst apiKey = await this.authStorage.getApiKey(providerName);\n\t\t\t\tif (!apiKey && !this.isProviderRequestReady(providerName)) continue;\n\n\t\t\t\tconst baseUrl = this.getProviderBaseUrl(providerName);\n\t\t\t\tconst models = await adapter.fetchModels(apiKey ?? \"\", baseUrl);\n\t\t\t\tconst ttlMs = this.getDiscoveryTtl(providerName, providerApis);\n\t\t\t\tthis.discoveryCache.set(providerName, models, ttlMs);\n\t\t\t\tresults.push({\n\t\t\t\t\tprovider: providerName,\n\t\t\t\t\tmodels,\n\t\t\t\t\tfetchedAt: Date.now(),\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tresults.push({\n\t\t\t\t\tprovider: providerName,\n\t\t\t\t\tmodels: [],\n\t\t\t\t\tfetchedAt: Date.now(),\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Convert and merge discovered models, then apply capability patches\n\t\tthis.discoveredModels = applyCapabilityPatches(this.convertDiscoveredModels(results));\n\t\treturn results;\n\t}\n\n\t/**\n\t * Get all models including discovered ones.\n\t * Discovered models are appended but never override existing models.\n\t */\n\tgetAllWithDiscovered(): Model<Api>[] {\n\t\tconst existingIds = new Set(this.models.map((m) => `${m.provider}/${m.id}`));\n\t\tconst unique = this.discoveredModels.filter((m) => !existingIds.has(`${m.provider}/${m.id}`));\n\t\treturn [...this.models, ...unique];\n\t}\n\n\t/**\n\t * Check if a model was added via discovery (not built-in or custom).\n\t */\n\tisDiscovered(model: Model<Api>): boolean {\n\t\treturn this.discoveredModels.some((m) => m.provider === model.provider && m.id === model.id);\n\t}\n\n\t/**\n\t * Get the discovery cache instance.\n\t */\n\tgetDiscoveryCache(): ModelDiscoveryCache {\n\t\treturn this.discoveryCache;\n\t}\n\n\t/**\n\t * Convert DiscoveryResult[] into Model<Api>[] with default values.\n\t */\n\tprivate convertDiscoveredModels(results: DiscoveryResult[]): Model<Api>[] {\n\t\tconst converted: Model<Api>[] = [];\n\t\tfor (const result of results) {\n\t\t\tif (result.error) continue;\n\t\t\tconst providerDefaults = this.getDiscoveryProviderDefaults(result.provider);\n\t\t\tfor (const dm of result.models) {\n\t\t\t\tconverted.push({\n\t\t\t\t\tid: dm.id,\n\t\t\t\t\tname: dm.name ?? dm.id,\n\t\t\t\t\tapi: providerDefaults.api,\n\t\t\t\t\tprovider: result.provider,\n\t\t\t\t\tbaseUrl: providerDefaults.baseUrl,\n\t\t\t\t\treasoning: dm.reasoning ?? false,\n\t\t\t\t\tinput: dm.input ?? providerDefaults.input,\n\t\t\t\t\tcost: dm.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\t\t\t\tcontextWindow: dm.contextWindow ?? providerDefaults.contextWindow,\n\t\t\t\t\tmaxTokens: dm.maxTokens ?? providerDefaults.maxTokens,\n\t\t\t\t} as Model<Api>);\n\t\t\t}\n\t\t}\n\t\treturn converted;\n\t}\n\n\tprivate getProviderApis(provider: string): Set<string> {\n\t\tconst apis = new Set<string>();\n\t\tfor (const model of this.models) {\n\t\t\tif (model.provider === provider && typeof model.api === \"string\" && model.api.length > 0) {\n\t\t\t\tapis.add(model.api);\n\t\t\t}\n\t\t}\n\n\t\tconst providerConfig = this.registeredProviders.get(provider);\n\t\tif (providerConfig?.api) apis.add(providerConfig.api);\n\t\tfor (const modelDef of providerConfig?.models ?? []) {\n\t\t\tif (modelDef.api) apis.add(modelDef.api);\n\t\t}\n\t\treturn apis;\n\t}\n\n\tprivate getAutoDiscoverableProviders(): string[] {\n\t\tconst discoverable = new Set<string>(getDiscoverableProviders());\n\t\tfor (const provider of new Set(this.models.map((m) => m.provider))) {\n\t\t\tconst apis = this.getProviderApis(provider);\n\t\t\tfor (const api of apis) {\n\t\t\t\tif (supportsDiscoveryForApi(api)) {\n\t\t\t\t\tdiscoverable.add(provider);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn [...discoverable];\n\t}\n\n\tprivate getProviderBaseUrl(provider: string): string | undefined {\n\t\tconst fromModels = this.models.find((m) => m.provider === provider && typeof m.baseUrl === \"string\" && m.baseUrl.length > 0);\n\t\tif (fromModels?.baseUrl) return fromModels.baseUrl;\n\t\treturn this.registeredProviders.get(provider)?.baseUrl;\n\t}\n\n\tprivate getDiscoveryProviderDefaults(provider: string): {\n\t\tapi: Api;\n\t\tbaseUrl: string;\n\t\tinput: (\"text\" | \"image\")[];\n\t\tcontextWindow: number;\n\t\tmaxTokens: number;\n\t} {\n\t\tconst first = this.models.find((m) => m.provider === provider);\n\t\tif (first) {\n\t\t\treturn {\n\t\t\t\tapi: first.api,\n\t\t\t\tbaseUrl: first.baseUrl,\n\t\t\t\tinput: first.input,\n\t\t\t\tcontextWindow: first.contextWindow,\n\t\t\t\tmaxTokens: first.maxTokens,\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tapi: \"openai-completions\",\n\t\t\tbaseUrl: this.registeredProviders.get(provider)?.baseUrl ?? \"\",\n\t\t\tinput: [\"text\"],\n\t\t\tcontextWindow: 128000,\n\t\t\tmaxTokens: 16384,\n\t\t};\n\t}\n\n\tprivate getDiscoveryTtl(provider: string, providerApis: Set<string>): number {\n\t\tfor (const api of providerApis) {\n\t\t\tif (supportsDiscoveryForApi(api)) {\n\t\t\t\treturn getDefaultTTL(\"openai\");\n\t\t\t}\n\t\t}\n\t\treturn getDefaultTTL(provider);\n\t}\n\n\t/**\n\t * Check if a model's baseUrl points to a local endpoint.\n\t * Delegates to standalone isLocalModel() function.\n\t */\n\tstatic isLocalModel(model: Model<Api>): boolean {\n\t\treturn isLocalModel(model);\n\t}\n\n\t/**\n\t * Check if all models in the registry are local.\n\t * Returns true only if every model passes isLocalModel().\n\t * Returns false if there are no models.\n\t */\n\tisAllLocalChain(): boolean {\n\t\tconst models = this.getAll();\n\t\tif (models.length === 0) return false;\n\t\treturn models.every((m) => isLocalModel(m));\n\t}\n}\n\n/**\n * Input type for registerProvider API.\n */\nexport interface ProviderConfigInput {\n\tauthMode?: ProviderAuthMode;\n\t/** Optional readiness check. Called by isProviderRequestReady() before default auth checks.\n\t * Trusted at the same level as extension code — extensions already have arbitrary code execution. */\n\tisReady?: () => boolean;\n\tbaseUrl?: string;\n\tapiKey?: string;\n\tapi?: Api;\n\tstreamSimple?: (model: Model<Api>, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\theaders?: Record<string, string>;\n\tauthHeader?: boolean;\n\t/** OAuth provider for /login support */\n\toauth?: Omit<OAuthProviderInterface, \"id\">;\n\tmodels?: Array<{\n\t\tid: string;\n\t\tname: string;\n\t\tapi?: Api;\n\t\tbaseUrl?: string;\n\t\treasoning: boolean;\n\t\tinput: (\"text\" | \"image\")[];\n\t\tcost: { input: number; output: number; cacheRead: number; cacheWrite: number };\n\t\tcontextWindow: number;\n\t\tmaxTokens: number;\n\t\theaders?: Record<string, string>;\n\t\tcompat?: Model<Api>[\"compat\"];\n\t\tproviderOptions?: Record<string, unknown>;\n\t}>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"model-registry.js","sourceRoot":"","sources":["../../src/core/model-registry.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAEN,sBAAsB,EAGtB,cAAc,EACd,YAAY,EACZ,SAAS,EACT,YAAY,EAMZ,mBAAmB,EACnB,iBAAiB,GAEjB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EAAe,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,SAAS,MAAM,KAAK,CAAC;AAC5B,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,WAAW,EAA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E,KAAK,CAAC,SAAS;aAC1B,CAAC;QACH,CAAC;QAED,OAAO;YACN,GAAG,EAAE,oBAAoB;YACzB,OAAO,EAAE,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,OAAO,IAAI,EAAE;YAC9D,KAAK,EAAE,CAAC,MAAM,CAAC;YACf,aAAa,EAAE,MAAM;YACrB,SAAS,EAAE,KAAK;SAChB,CAAC;IACH,CAAC;IAEO,eAAe,CAAC,QAAgB,EAAE,YAAyB;QAClE,KAAK,MAAM,GAAG,IAAI,YAAY,EAAE,CAAC;YAChC,IAAI,uBAAuB,CAAC,GAAG,CAAC,EAAE,CAAC;gBAClC,OAAO,aAAa,CAAC,QAAQ,CAAC,CAAC;YAChC,CAAC;QACF,CAAC;QACD,OAAO,aAAa,CAAC,QAAQ,CAAC,CAAC;IAChC,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,YAAY,CAAC,KAAiB;QACpC,OAAO,YAAY,CAAC,KAAK,CAAC,CAAC;IAC5B,CAAC;IAED;;;;OAIG;IACH,eAAe;QACd,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QAC7B,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,KAAK,CAAC;QACtC,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC;IAC7C,CAAC;CACD","sourcesContent":["/**\n * Model registry - manages built-in and custom models, provides API key resolution.\n */\n\nimport {\n\ttype Api,\n\tapplyCapabilityPatches,\n\ttype AssistantMessageEventStream,\n\ttype Context,\n\tgetApiProvider,\n\tgetEnvApiKey,\n\tgetModels,\n\tgetProviders,\n\ttype KnownProvider,\n\ttype Model,\n\ttype OAuthProviderInterface,\n\ttype OpenAICompletionsCompat,\n\ttype OpenAIResponsesCompat,\n\tregisterApiProvider,\n\tresetApiProviders,\n\ttype SimpleStreamOptions,\n} from \"@gsd/pi-ai\";\nimport { registerOAuthProvider, resetOAuthProviders } from \"@gsd/pi-ai/oauth\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport AjvModule from \"ajv\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { getAgentDir } from \"../config.js\";\nimport type { AuthStorage } from \"./auth-storage.js\";\nimport { ModelDiscoveryCache } from \"./discovery-cache.js\";\nimport type { DiscoveredModel, DiscoveryResult } from \"./model-discovery.js\";\nimport { getDefaultTTL, getDiscoverableProviders, getDiscoveryAdapter, supportsDiscoveryForApi } from \"./model-discovery.js\";\nimport { clearConfigValueCache, resolveConfigValue, resolveHeaders } from \"./resolve-config-value.js\";\nimport { isLocalModel } from \"./local-model-check.js\";\n\nconst Ajv = (AjvModule as any).default || AjvModule;\nconst ajv = new Ajv();\n\n// Schema for OpenRouter routing preferences\nconst OpenRouterRoutingSchema = Type.Object({\n\tonly: Type.Optional(Type.Array(Type.String())),\n\torder: Type.Optional(Type.Array(Type.String())),\n});\n\n// Schema for Vercel AI Gateway routing preferences\nconst VercelGatewayRoutingSchema = Type.Object({\n\tonly: Type.Optional(Type.Array(Type.String())),\n\torder: Type.Optional(Type.Array(Type.String())),\n});\n\n// Schema for model capability declarations (mirrors ModelCapabilities in pi-ai types)\nconst ModelCapabilitiesSchema = Type.Object({\n\tsupportsXhigh: Type.Optional(Type.Boolean()),\n\trequiresToolCallId: Type.Optional(Type.Boolean()),\n\tsupportsServiceTier: Type.Optional(Type.Boolean()),\n\tcharsPerToken: Type.Optional(Type.Number()),\n});\n\n// Schema for OpenAI compatibility settings\nconst OpenAICompletionsCompatSchema = Type.Object({\n\tsupportsStore: Type.Optional(Type.Boolean()),\n\tsupportsDeveloperRole: Type.Optional(Type.Boolean()),\n\tsupportsReasoningEffort: Type.Optional(Type.Boolean()),\n\tsupportsUsageInStreaming: Type.Optional(Type.Boolean()),\n\tmaxTokensField: Type.Optional(Type.Union([Type.Literal(\"max_completion_tokens\"), Type.Literal(\"max_tokens\")])),\n\trequiresToolResultName: Type.Optional(Type.Boolean()),\n\trequiresAssistantAfterToolResult: Type.Optional(Type.Boolean()),\n\trequiresThinkingAsText: Type.Optional(Type.Boolean()),\n\trequiresMistralToolIds: Type.Optional(Type.Boolean()),\n\tthinkingFormat: Type.Optional(Type.Union([Type.Literal(\"openai\"), Type.Literal(\"zai\"), Type.Literal(\"qwen\")])),\n\topenRouterRouting: Type.Optional(OpenRouterRoutingSchema),\n\tvercelGatewayRouting: Type.Optional(VercelGatewayRoutingSchema),\n});\n\nconst OpenAIResponsesCompatSchema = Type.Object({\n\t// Reserved for future use\n});\n\nconst OpenAICompatSchema = Type.Union([OpenAICompletionsCompatSchema, OpenAIResponsesCompatSchema]);\n\n// Schema for custom model definition\n// Most fields are optional with sensible defaults for local models (Ollama, LM Studio, etc.)\nconst ModelDefinitionSchema = Type.Object({\n\tid: Type.String({ minLength: 1 }),\n\tname: Type.Optional(Type.String({ minLength: 1 })),\n\tapi: Type.Optional(Type.String({ minLength: 1 })),\n\tbaseUrl: Type.Optional(Type.String({ minLength: 1 })),\n\treasoning: Type.Optional(Type.Boolean()),\n\tinput: Type.Optional(Type.Array(Type.Union([Type.Literal(\"text\"), Type.Literal(\"image\")]))),\n\tcost: Type.Optional(\n\t\tType.Object({\n\t\t\tinput: Type.Number(),\n\t\t\toutput: Type.Number(),\n\t\t\tcacheRead: Type.Number(),\n\t\t\tcacheWrite: Type.Number(),\n\t\t}),\n\t),\n\tcontextWindow: Type.Optional(Type.Number()),\n\tmaxTokens: Type.Optional(Type.Number()),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tcompat: Type.Optional(OpenAICompatSchema),\n\tcapabilities: Type.Optional(ModelCapabilitiesSchema),\n});\n\n// Schema for per-model overrides (all fields optional, merged with built-in model)\nconst ModelOverrideSchema = Type.Object({\n\tname: Type.Optional(Type.String({ minLength: 1 })),\n\treasoning: Type.Optional(Type.Boolean()),\n\tinput: Type.Optional(Type.Array(Type.Union([Type.Literal(\"text\"), Type.Literal(\"image\")]))),\n\tcost: Type.Optional(\n\t\tType.Object({\n\t\t\tinput: Type.Optional(Type.Number()),\n\t\t\toutput: Type.Optional(Type.Number()),\n\t\t\tcacheRead: Type.Optional(Type.Number()),\n\t\t\tcacheWrite: Type.Optional(Type.Number()),\n\t\t}),\n\t),\n\tcontextWindow: Type.Optional(Type.Number()),\n\tmaxTokens: Type.Optional(Type.Number()),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tcompat: Type.Optional(OpenAICompatSchema),\n\tcapabilities: Type.Optional(ModelCapabilitiesSchema),\n});\n\ntype ModelOverride = Static<typeof ModelOverrideSchema>;\n\nconst ProviderConfigSchema = Type.Object({\n\tbaseUrl: Type.Optional(Type.String({ minLength: 1 })),\n\tapiKey: Type.Optional(Type.String({ minLength: 1 })),\n\tapi: Type.Optional(Type.String({ minLength: 1 })),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tauthHeader: Type.Optional(Type.Boolean()),\n\tmodels: Type.Optional(Type.Array(ModelDefinitionSchema)),\n\tmodelOverrides: Type.Optional(Type.Record(Type.String(), ModelOverrideSchema)),\n});\n\nconst ModelsConfigSchema = Type.Object({\n\tproviders: Type.Record(Type.String(), ProviderConfigSchema),\n});\n\najv.addSchema(ModelsConfigSchema, \"ModelsConfig\");\n\ntype ModelsConfig = Static<typeof ModelsConfigSchema>;\n\nexport type ProviderAuthMode = \"apiKey\" | \"oauth\" | \"externalCli\" | \"none\";\n\n/** Provider override config (baseUrl, headers, apiKey) without custom models */\ninterface ProviderOverride {\n\tbaseUrl?: string;\n\theaders?: Record<string, string>;\n\tapiKey?: string;\n}\n\n/** Result of loading custom models from models.json */\ninterface CustomModelsResult {\n\tmodels: Model<Api>[];\n\t/** Providers with baseUrl/headers/apiKey overrides for built-in models */\n\toverrides: Map<string, ProviderOverride>;\n\t/** Per-model overrides: provider -> modelId -> override */\n\tmodelOverrides: Map<string, Map<string, ModelOverride>>;\n\terror: string | undefined;\n}\n\nfunction emptyCustomModelsResult(error?: string): CustomModelsResult {\n\treturn { models: [], overrides: new Map(), modelOverrides: new Map(), error };\n}\n\nfunction mergeCompat(\n\tbaseCompat: Model<Api>[\"compat\"],\n\toverrideCompat: ModelOverride[\"compat\"],\n): Model<Api>[\"compat\"] | undefined {\n\tif (!overrideCompat) return baseCompat;\n\n\tconst base = baseCompat as OpenAICompletionsCompat | OpenAIResponsesCompat | undefined;\n\tconst override = overrideCompat as OpenAICompletionsCompat | OpenAIResponsesCompat;\n\tconst merged = { ...base, ...override } as OpenAICompletionsCompat | OpenAIResponsesCompat;\n\n\tconst baseCompletions = base as OpenAICompletionsCompat | undefined;\n\tconst overrideCompletions = override as OpenAICompletionsCompat;\n\tconst mergedCompletions = merged as OpenAICompletionsCompat;\n\n\tif (baseCompletions?.openRouterRouting || overrideCompletions.openRouterRouting) {\n\t\tmergedCompletions.openRouterRouting = {\n\t\t\t...baseCompletions?.openRouterRouting,\n\t\t\t...overrideCompletions.openRouterRouting,\n\t\t};\n\t}\n\n\tif (baseCompletions?.vercelGatewayRouting || overrideCompletions.vercelGatewayRouting) {\n\t\tmergedCompletions.vercelGatewayRouting = {\n\t\t\t...baseCompletions?.vercelGatewayRouting,\n\t\t\t...overrideCompletions.vercelGatewayRouting,\n\t\t};\n\t}\n\n\treturn merged as Model<Api>[\"compat\"];\n}\n\n/**\n * Deep merge a model override into a model.\n * Handles nested objects (cost, compat) by merging rather than replacing.\n */\nfunction applyModelOverride(model: Model<Api>, override: ModelOverride): Model<Api> {\n\tconst result = { ...model };\n\n\t// Simple field overrides\n\tif (override.name !== undefined) result.name = override.name;\n\tif (override.reasoning !== undefined) result.reasoning = override.reasoning;\n\tif (override.input !== undefined) result.input = override.input as (\"text\" | \"image\")[];\n\tif (override.contextWindow !== undefined) result.contextWindow = override.contextWindow;\n\tif (override.maxTokens !== undefined) result.maxTokens = override.maxTokens;\n\n\t// Merge cost (partial override)\n\tif (override.cost) {\n\t\tresult.cost = {\n\t\t\tinput: override.cost.input ?? model.cost.input,\n\t\t\toutput: override.cost.output ?? model.cost.output,\n\t\t\tcacheRead: override.cost.cacheRead ?? model.cost.cacheRead,\n\t\t\tcacheWrite: override.cost.cacheWrite ?? model.cost.cacheWrite,\n\t\t};\n\t}\n\n\t// Merge headers\n\tif (override.headers) {\n\t\tconst resolvedHeaders = resolveHeaders(override.headers);\n\t\tresult.headers = resolvedHeaders ? { ...model.headers, ...resolvedHeaders } : model.headers;\n\t}\n\n\t// Deep merge compat\n\tresult.compat = mergeCompat(model.compat, override.compat);\n\n\t// Merge capabilities (override wins per-field)\n\tif (override.capabilities) {\n\t\tresult.capabilities = { ...model.capabilities, ...override.capabilities };\n\t}\n\n\treturn result;\n}\n\n\n/**\n * Model registry - loads and manages models, resolves API keys via AuthStorage.\n */\nexport class ModelRegistry {\n\tprivate models: Model<Api>[] = [];\n\tprivate discoveredModels: Model<Api>[] = [];\n\tprivate discoveryCache: ModelDiscoveryCache;\n\tprivate customProviderApiKeys: Map<string, string> = new Map();\n\tprivate registeredProviders: Map<string, ProviderConfigInput> = new Map();\n\tprivate disabledModelProviders: Set<string> = new Set();\n\tprivate loadError: string | undefined = undefined;\n\n\tconstructor(\n\t\treadonly authStorage: AuthStorage,\n\t\treadonly modelsJsonPath: string | undefined = join(getAgentDir(), \"models.json\"),\n\t) {\n\t\tthis.discoveryCache = new ModelDiscoveryCache();\n\n\t\t// Set up fallback resolver for custom provider API keys\n\t\tthis.authStorage.setFallbackResolver((provider) => {\n\t\t\tconst keyConfig = this.customProviderApiKeys.get(provider);\n\t\t\tif (keyConfig) {\n\t\t\t\treturn resolveConfigValue(keyConfig);\n\t\t\t}\n\t\t\treturn getEnvApiKey(provider);\n\t\t});\n\n\t\t// Refresh models when credentials change (e.g., OAuth token refresh with new model limits)\n\t\tthis.authStorage.onCredentialChange(() => this.refresh());\n\n\t\t// Load models\n\t\tthis.loadModels();\n\t}\n\n\t/**\n\t * Reload models from disk (built-in + custom from models.json).\n\t */\n\trefresh(): void {\n\t\tthis.customProviderApiKeys.clear();\n\t\tthis.loadError = undefined;\n\n\t\t// Ensure dynamic API/OAuth registrations are rebuilt from current provider state.\n\t\tresetApiProviders();\n\t\tresetOAuthProviders();\n\n\t\tthis.loadModels();\n\n\t\tfor (const [providerName, config] of this.registeredProviders.entries()) {\n\t\t\tthis.applyProviderConfig(providerName, config);\n\t\t}\n\t}\n\n\t/**\n\t * Get any error from loading models.json (undefined if no error).\n\t */\n\tgetError(): string | undefined {\n\t\treturn this.loadError;\n\t}\n\n\tprivate loadModels(): void {\n\t\t// Load custom models and overrides from models.json\n\t\tconst {\n\t\t\tmodels: customModels,\n\t\t\toverrides,\n\t\t\tmodelOverrides,\n\t\t\terror,\n\t\t} = this.modelsJsonPath ? this.loadCustomModels(this.modelsJsonPath) : emptyCustomModelsResult();\n\n\t\tif (error) {\n\t\t\tthis.loadError = error;\n\t\t\t// Keep built-in models even if custom models failed to load\n\t\t}\n\n\t\tconst builtInModels = this.loadBuiltInModels(overrides, modelOverrides);\n\t\tlet combined = this.mergeCustomModels(builtInModels, customModels);\n\n\t\t// Let OAuth providers modify their models (e.g., update baseUrl)\n\t\tfor (const oauthProvider of this.authStorage.getOAuthProviders()) {\n\t\t\tconst cred = this.authStorage.get(oauthProvider.id);\n\t\t\tif (cred?.type === \"oauth\" && oauthProvider.modifyModels) {\n\t\t\t\tcombined = oauthProvider.modifyModels(combined, cred);\n\t\t\t}\n\t\t}\n\n\t\t// Apply capability patches so custom/discovered/extension models get\n\t\t// capabilities (supportsXhigh, supportsServiceTier, etc.) that the\n\t\t// static pi-ai registry applies at module load for built-in models.\n\t\tthis.models = applyCapabilityPatches(combined);\n\t}\n\n\t/** Load built-in models and apply provider/model overrides */\n\tprivate loadBuiltInModels(\n\t\toverrides: Map<string, ProviderOverride>,\n\t\tmodelOverrides: Map<string, Map<string, ModelOverride>>,\n\t): Model<Api>[] {\n\t\treturn getProviders().flatMap((provider) => {\n\t\t\tconst models = getModels(provider as KnownProvider) as Model<Api>[];\n\t\t\tconst providerOverride = overrides.get(provider);\n\t\t\tconst perModelOverrides = modelOverrides.get(provider);\n\n\t\t\treturn models.map((m) => {\n\t\t\t\tlet model = m;\n\n\t\t\t\t// Apply provider-level baseUrl/headers override\n\t\t\t\tif (providerOverride) {\n\t\t\t\t\tconst resolvedHeaders = resolveHeaders(providerOverride.headers);\n\t\t\t\t\tmodel = {\n\t\t\t\t\t\t...model,\n\t\t\t\t\t\tbaseUrl: providerOverride.baseUrl ?? model.baseUrl,\n\t\t\t\t\t\theaders: resolvedHeaders ? { ...model.headers, ...resolvedHeaders } : model.headers,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Apply per-model override\n\t\t\t\tconst modelOverride = perModelOverrides?.get(m.id);\n\t\t\t\tif (modelOverride) {\n\t\t\t\t\tmodel = applyModelOverride(model, modelOverride);\n\t\t\t\t}\n\n\t\t\t\treturn model;\n\t\t\t});\n\t\t});\n\t}\n\n\t/** Merge custom models into built-in list by provider+id (custom wins on conflicts). */\n\tprivate mergeCustomModels(builtInModels: Model<Api>[], customModels: Model<Api>[]): Model<Api>[] {\n\t\tconst merged = [...builtInModels];\n\t\tfor (const customModel of customModels) {\n\t\t\tconst existingIndex = merged.findIndex((m) => m.provider === customModel.provider && m.id === customModel.id);\n\t\t\tif (existingIndex >= 0) {\n\t\t\t\tmerged[existingIndex] = customModel;\n\t\t\t} else {\n\t\t\t\tmerged.push(customModel);\n\t\t\t}\n\t\t}\n\t\treturn merged;\n\t}\n\n\tprivate loadCustomModels(modelsJsonPath: string): CustomModelsResult {\n\t\tif (!existsSync(modelsJsonPath)) {\n\t\t\treturn emptyCustomModelsResult();\n\t\t}\n\n\t\ttry {\n\t\t\tconst content = readFileSync(modelsJsonPath, \"utf-8\");\n\t\t\tconst config: ModelsConfig = JSON.parse(content);\n\n\t\t\t// Validate schema\n\t\t\tconst validate = ajv.getSchema(\"ModelsConfig\")!;\n\t\t\tif (!validate(config)) {\n\t\t\t\tconst errors =\n\t\t\t\t\tvalidate.errors?.map((e: any) => ` - ${e.instancePath || \"root\"}: ${e.message}`).join(\"\\n\") ||\n\t\t\t\t\t\"Unknown schema error\";\n\t\t\t\treturn emptyCustomModelsResult(`Invalid models.json schema:\\n${errors}\\n\\nFile: ${modelsJsonPath}`);\n\t\t\t}\n\n\t\t\t// Additional validation\n\t\t\tthis.validateConfig(config);\n\n\t\t\tconst overrides = new Map<string, ProviderOverride>();\n\t\t\tconst modelOverrides = new Map<string, Map<string, ModelOverride>>();\n\n\t\t\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t\t\t// Apply provider-level baseUrl/headers/apiKey override to built-in models when configured.\n\t\t\t\tif (providerConfig.baseUrl || providerConfig.headers || providerConfig.apiKey) {\n\t\t\t\t\toverrides.set(providerName, {\n\t\t\t\t\t\tbaseUrl: providerConfig.baseUrl,\n\t\t\t\t\t\theaders: providerConfig.headers,\n\t\t\t\t\t\tapiKey: providerConfig.apiKey,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// Store API key for fallback resolver.\n\t\t\t\tif (providerConfig.apiKey) {\n\t\t\t\t\tthis.customProviderApiKeys.set(providerName, providerConfig.apiKey);\n\t\t\t\t}\n\n\t\t\t\tif (providerConfig.modelOverrides) {\n\t\t\t\t\tmodelOverrides.set(providerName, new Map(Object.entries(providerConfig.modelOverrides)));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn { models: this.parseModels(config), overrides, modelOverrides, error: undefined };\n\t\t} catch (error) {\n\t\t\tif (error instanceof SyntaxError) {\n\t\t\t\treturn emptyCustomModelsResult(`Failed to parse models.json: ${error.message}\\n\\nFile: ${modelsJsonPath}`);\n\t\t\t}\n\t\t\treturn emptyCustomModelsResult(\n\t\t\t\t`Failed to load models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${modelsJsonPath}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate validateConfig(config: ModelsConfig): void {\n\t\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t\tconst hasProviderApi = !!providerConfig.api;\n\t\t\tconst models = providerConfig.models ?? [];\n\t\t\tconst hasModelOverrides =\n\t\t\t\tproviderConfig.modelOverrides && Object.keys(providerConfig.modelOverrides).length > 0;\n\n\t\t\tif (models.length === 0) {\n\t\t\t\t// Override-only config: needs baseUrl OR modelOverrides (or both)\n\t\t\t\tif (!providerConfig.baseUrl && !hasModelOverrides) {\n\t\t\t\t\tthrow new Error(`Provider ${providerName}: must specify \"baseUrl\", \"modelOverrides\", or \"models\".`);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Custom models are merged into provider models and require endpoint + auth.\n\t\t\t\tif (!providerConfig.baseUrl) {\n\t\t\t\t\tthrow new Error(`Provider ${providerName}: \"baseUrl\" is required when defining custom models.`);\n\t\t\t\t}\n\t\t\t\tif (!providerConfig.apiKey) {\n\t\t\t\t\tthrow new Error(`Provider ${providerName}: \"apiKey\" is required when defining custom models.`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const modelDef of models) {\n\t\t\t\tconst hasModelApi = !!modelDef.api;\n\n\t\t\t\tif (!hasProviderApi && !hasModelApi) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Provider ${providerName}, model ${modelDef.id}: no \"api\" specified. Set at provider or model level.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (!modelDef.id) throw new Error(`Provider ${providerName}: model missing \"id\"`);\n\t\t\t\t// Validate contextWindow/maxTokens only if provided (they have defaults)\n\t\t\t\tif (modelDef.contextWindow !== undefined && modelDef.contextWindow <= 0)\n\t\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid contextWindow`);\n\t\t\t\tif (modelDef.maxTokens !== undefined && modelDef.maxTokens <= 0)\n\t\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid maxTokens`);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate parseModels(config: ModelsConfig): Model<Api>[] {\n\t\tconst models: Model<Api>[] = [];\n\n\t\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t\tconst modelDefs = providerConfig.models ?? [];\n\t\t\tif (modelDefs.length === 0) continue; // Override-only, no custom models\n\n\t\t\t// Store API key config for fallback resolver\n\t\t\tif (providerConfig.apiKey) {\n\t\t\t\tthis.customProviderApiKeys.set(providerName, providerConfig.apiKey);\n\t\t\t}\n\n\t\t\t// Register custom providers so isProviderRequestReady() can find\n\t\t\t// them (#3531). Without this, models.json providers with apiKey\n\t\t\t// fail the auth check and are invisible to the fallback resolver.\n\t\t\tif (!this.registeredProviders.has(providerName)) {\n\t\t\t\tthis.registeredProviders.set(providerName, {\n\t\t\t\t\tauthMode: providerConfig.apiKey ? \"apiKey\" : \"none\",\n\t\t\t\t\tapiKey: providerConfig.apiKey,\n\t\t\t\t\tbaseUrl: providerConfig.baseUrl,\n\t\t\t\t\tisReady: providerConfig.apiKey ? () => true : undefined,\n\t\t\t\t} as any);\n\t\t\t}\n\n\t\t\tfor (const modelDef of modelDefs) {\n\t\t\t\tconst api = modelDef.api || providerConfig.api;\n\t\t\t\tif (!api) continue;\n\n\t\t\t\t// Merge headers: provider headers are base, model headers override\n\t\t\t\t// Resolve env vars and shell commands in header values\n\t\t\t\tconst providerHeaders = resolveHeaders(providerConfig.headers);\n\t\t\t\tconst modelHeaders = resolveHeaders(modelDef.headers);\n\t\t\t\tlet headers = providerHeaders || modelHeaders ? { ...providerHeaders, ...modelHeaders } : undefined;\n\n\t\t\t\t// If authHeader is true, add Authorization header with resolved API key\n\t\t\t\tif (providerConfig.authHeader && providerConfig.apiKey) {\n\t\t\t\t\tconst resolvedKey = resolveConfigValue(providerConfig.apiKey);\n\t\t\t\t\tif (resolvedKey) {\n\t\t\t\t\t\theaders = { ...headers, Authorization: `Bearer ${resolvedKey}` };\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Provider baseUrl is required when custom models are defined.\n\t\t\t\t// Individual models can override it with modelDef.baseUrl.\n\t\t\t\tconst defaultCost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\n\t\t\t\tmodels.push({\n\t\t\t\t\tid: modelDef.id,\n\t\t\t\t\tname: modelDef.name ?? modelDef.id,\n\t\t\t\t\tapi: api as Api,\n\t\t\t\t\tprovider: providerName,\n\t\t\t\t\tbaseUrl: modelDef.baseUrl ?? providerConfig.baseUrl!,\n\t\t\t\t\treasoning: modelDef.reasoning ?? false,\n\t\t\t\t\tinput: (modelDef.input ?? [\"text\"]) as (\"text\" | \"image\")[],\n\t\t\t\t\tcost: modelDef.cost ?? defaultCost,\n\t\t\t\t\tcontextWindow: modelDef.contextWindow ?? 128000,\n\t\t\t\t\tmaxTokens: modelDef.maxTokens ?? 16384,\n\t\t\t\t\theaders,\n\t\t\t\t\tcompat: modelDef.compat,\n\t\t\t\t\tcapabilities: modelDef.capabilities,\n\t\t\t\t} as Model<Api>);\n\t\t\t}\n\t\t}\n\n\t\treturn models;\n\t}\n\n\t/**\n\t * Get all models (built-in + custom).\n\t * If models.json had errors, returns only built-in models.\n\t */\n\tgetAll(): Model<Api>[] {\n\t\treturn this.models;\n\t}\n\n\t/**\n\t * Get only models that have auth configured.\n\t * This is a fast check that doesn't refresh OAuth tokens.\n\t */\n\tgetAvailable(): Model<Api>[] {\n\t\treturn this.models.filter((m) => this.isProviderRequestReady(m.provider));\n\t}\n\n\t/**\n\t * Set provider IDs that should be excluded from model selection/routing.\n\t * This does not affect direct tool auth flows that resolve provider keys.\n\t */\n\tsetDisabledModelProviders(providers: string[]): void {\n\t\tthis.disabledModelProviders = new Set(\n\t\t\tproviders\n\t\t\t\t.map((provider) => provider.trim().toLowerCase())\n\t\t\t\t.filter((provider) => provider.length > 0),\n\t\t);\n\t}\n\n\t/**\n\t * Get current provider denylist used for model selection/routing.\n\t */\n\tgetDisabledModelProviders(): string[] {\n\t\treturn Array.from(this.disabledModelProviders);\n\t}\n\n\t/**\n\t * Get auth mode for a provider.\n\t * Defaults to \"apiKey\" for built-ins and providers without explicit mode.\n\t */\n\tgetProviderAuthMode(provider: string): ProviderAuthMode {\n\t\tconst config = this.registeredProviders.get(provider);\n\t\tif (!config) return \"apiKey\";\n\t\tif (config.authMode) return config.authMode;\n\t\tif (config.oauth) return \"oauth\";\n\t\tif (config.apiKey) return \"apiKey\";\n\t\treturn \"apiKey\";\n\t}\n\n\t/**\n\t * Whether a provider can be used for requests/fallback without hard auth gating.\n\t */\n\tisProviderRequestReady(provider: string): boolean {\n\t\tif (this.disabledModelProviders.has(provider.trim().toLowerCase())) return false;\n\t\tconst config = this.registeredProviders.get(provider);\n\t\tif (config?.isReady) return config.isReady();\n\t\tconst authMode = this.getProviderAuthMode(provider);\n\t\tif (authMode === \"externalCli\" || authMode === \"none\") return true;\n\t\treturn this.authStorage.hasAuth(provider);\n\t}\n\n\t/**\n\t * Find a model by provider and ID.\n\t */\n\tfind(provider: string, modelId: string): Model<Api> | undefined {\n\t\treturn this.models.find((m) => m.provider === provider && m.id === modelId);\n\t}\n\n\t/**\n\t * Get API key for a model.\n\t * Returns undefined for externalCli/none providers (no key needed).\n\t * @param sessionId - Optional session ID for sticky credential selection\n\t */\n\tasync getApiKey(model: Model<Api>, sessionId?: string): Promise<string | undefined> {\n\t\tconst authMode = this.getProviderAuthMode(model.provider);\n\t\tif (authMode === \"externalCli\" || authMode === \"none\") return undefined;\n\t\treturn this.authStorage.getApiKey(model.provider, sessionId, { baseUrl: model.baseUrl });\n\t}\n\n\t/**\n\t * Get API key for a provider.\n\t * Returns undefined for externalCli/none providers (no key needed).\n\t * @param sessionId - Optional session ID for sticky credential selection\n\t */\n\tasync getApiKeyForProvider(provider: string, sessionId?: string): Promise<string | undefined> {\n\t\tconst authMode = this.getProviderAuthMode(provider);\n\t\tif (authMode === \"externalCli\" || authMode === \"none\") return undefined;\n\t\treturn this.authStorage.getApiKey(provider, sessionId);\n\t}\n\n\t/**\n\t * Check if a model is using OAuth credentials (subscription).\n\t */\n\tisUsingOAuth(model: Model<Api>): boolean {\n\t\tconst cred = this.authStorage.get(model.provider);\n\t\treturn cred?.type === \"oauth\";\n\t}\n\n\t/**\n\t * Register a provider dynamically (from extensions).\n\t *\n\t * If provider has models: replaces all existing models for this provider.\n\t * If provider has only baseUrl/headers: overrides existing models' URLs.\n\t * If provider has oauth: registers OAuth provider for /login support.\n\t */\n\tregisterProvider(providerName: string, config: ProviderConfigInput): void {\n\t\tthis.registeredProviders.set(providerName, config);\n\t\tthis.applyProviderConfig(providerName, config);\n\t}\n\n\t/**\n\t * Unregister a previously registered provider.\n\t *\n\t * Removes the provider from the registry and reloads models from disk so that\n\t * built-in models overridden by this provider are restored to their original state.\n\t * Also resets dynamic OAuth and API stream registrations before reapplying\n\t * remaining dynamic providers.\n\t * Has no effect if the provider was never registered.\n\t */\n\tunregisterProvider(providerName: string): void {\n\t\tif (!this.registeredProviders.has(providerName)) return;\n\t\tthis.registeredProviders.delete(providerName);\n\t\tthis.customProviderApiKeys.delete(providerName);\n\t\tthis.refresh();\n\t}\n\n\tprivate applyProviderConfig(providerName: string, config: ProviderConfigInput): void {\n\t\t// Register OAuth provider if provided\n\t\tif (config.oauth) {\n\t\t\t// Ensure the OAuth provider ID matches the provider name\n\t\t\tconst oauthProvider: OAuthProviderInterface = {\n\t\t\t\t...config.oauth,\n\t\t\t\tid: providerName,\n\t\t\t};\n\t\t\tregisterOAuthProvider(oauthProvider);\n\t\t}\n\n\t\tif (config.streamSimple) {\n\t\t\tif (!config.api) {\n\t\t\t\tthrow new Error(`Provider ${providerName}: \"api\" is required when registering streamSimple.`);\n\t\t\t}\n\t\t\tconst rawStreamSimple = config.streamSimple;\n\t\t\tconst authMode = config.authMode ?? \"apiKey\";\n\n\t\t\t// Keyless providers never see apiKey in options — enforced at registration,\n\t\t\t// not by convention. Prevents undefined from reaching any handler.\n\t\t\tconst streamSimple = (authMode === \"externalCli\" || authMode === \"none\")\n\t\t\t\t? ((model: Model<Api>, context: Context, options?: SimpleStreamOptions) => {\n\t\t\t\t\t\tconst { apiKey: _, ...opts } = options ?? {};\n\t\t\t\t\t\treturn rawStreamSimple(model, context, opts as SimpleStreamOptions);\n\t\t\t\t\t})\n\t\t\t\t: rawStreamSimple;\n\n\t\t\t// Guard: if there's already a handler registered for this API, wrap\n\t\t\t// the new one so it only fires for models from this provider and\n\t\t\t// delegates to the previous handler for all other providers. Without\n\t\t\t// this, a custom provider using api:\"anthropic-messages\" would clobber\n\t\t\t// the built-in Anthropic stream handler (#2536).\n\t\t\tconst existingProvider = getApiProvider(config.api as Api);\n\t\t\tconst scopedStream = existingProvider\n\t\t\t\t? (model: Model<Api>, context: Context, options?: SimpleStreamOptions): AssistantMessageEventStream => {\n\t\t\t\t\t\tif (model.provider === providerName) {\n\t\t\t\t\t\t\treturn streamSimple(model, context, options);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn existingProvider.streamSimple(model, context, options);\n\t\t\t\t\t}\n\t\t\t\t: streamSimple;\n\n\t\t\tconst newFullStream = (model: Model<Api>, context: Context, options?: SimpleStreamOptions) =>\n\t\t\t\tscopedStream(model, context, options as SimpleStreamOptions);\n\t\t\tconst scopedFullStream = existingProvider\n\t\t\t\t? (model: Model<Api>, context: Context, options?: Record<string, unknown>) => {\n\t\t\t\t\t\tif (model.provider === providerName) {\n\t\t\t\t\t\t\treturn newFullStream(model, context, options as SimpleStreamOptions);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn existingProvider.stream(model, context, options);\n\t\t\t\t\t}\n\t\t\t\t: newFullStream;\n\n\t\t\tregisterApiProvider(\n\t\t\t\t{\n\t\t\t\t\tapi: config.api,\n\t\t\t\t\tstream: scopedFullStream as any,\n\t\t\t\t\tstreamSimple: scopedStream,\n\t\t\t\t},\n\t\t\t\t`provider:${providerName}`,\n\t\t\t);\n\t\t}\n\n\t\t// Store API key for auth resolution\n\t\tif (config.apiKey) {\n\t\t\tthis.customProviderApiKeys.set(providerName, config.apiKey);\n\t\t}\n\n\t\tif (config.models && config.models.length > 0) {\n\t\t\t// Full replacement: remove existing models for this provider\n\t\t\tthis.models = this.models.filter((m) => m.provider !== providerName);\n\n\t\t\t// Validate required fields\n\t\t\tif (!config.baseUrl) {\n\t\t\t\tthrow new Error(`Provider ${providerName}: \"baseUrl\" is required when defining models.`);\n\t\t\t}\n\t\t\tconst authMode = config.authMode ?? (config.oauth ? \"oauth\" : config.apiKey ? \"apiKey\" : \"apiKey\");\n\t\t\tif (authMode === \"apiKey\" && !config.apiKey && !config.oauth) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Provider ${providerName}: \"apiKey\" or \"oauth\" is required when authMode is \"apiKey\" (the default). ` +\n\t\t\t\t\t`Set authMode to \"externalCli\" or \"none\" for keyless providers.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif ((authMode === \"externalCli\" || authMode === \"none\") && !config.streamSimple) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Provider ${providerName}: \"streamSimple\" is required when authMode is \"${authMode}\". ` +\n\t\t\t\t\t`Keyless providers must supply their own stream handler.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif ((authMode === \"externalCli\" || authMode === \"none\") && config.apiKey) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Provider ${providerName}: \"apiKey\" cannot be set when authMode is \"${authMode}\". ` +\n\t\t\t\t\t`Keyless providers should not provide API key credentials.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Parse and add new models\n\t\t\tfor (const modelDef of config.models) {\n\t\t\t\tconst api = modelDef.api || config.api;\n\t\t\t\tif (!api) {\n\t\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: no \"api\" specified.`);\n\t\t\t\t}\n\n\t\t\t\t// Merge headers\n\t\t\t\tconst providerHeaders = resolveHeaders(config.headers);\n\t\t\t\tconst modelHeaders = resolveHeaders(modelDef.headers);\n\t\t\t\tlet headers = providerHeaders || modelHeaders ? { ...providerHeaders, ...modelHeaders } : undefined;\n\n\t\t\t\t// If authHeader is true, add Authorization header\n\t\t\t\tif (config.authHeader && config.apiKey) {\n\t\t\t\t\tconst resolvedKey = resolveConfigValue(config.apiKey);\n\t\t\t\t\tif (resolvedKey) {\n\t\t\t\t\t\theaders = { ...headers, Authorization: `Bearer ${resolvedKey}` };\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthis.models.push({\n\t\t\t\t\tid: modelDef.id,\n\t\t\t\t\tname: modelDef.name,\n\t\t\t\t\tapi: api as Api,\n\t\t\t\t\tprovider: providerName,\n\t\t\t\t\tbaseUrl: config.baseUrl,\n\t\t\t\t\treasoning: modelDef.reasoning,\n\t\t\t\t\tinput: modelDef.input as (\"text\" | \"image\")[],\n\t\t\t\t\tcost: modelDef.cost,\n\t\t\t\t\tcontextWindow: modelDef.contextWindow,\n\t\t\t\t\tmaxTokens: modelDef.maxTokens,\n\t\t\t\t\theaders,\n\t\t\t\t\tcompat: modelDef.compat,\n\t\t\t\t\tproviderOptions: modelDef.providerOptions,\n\t\t\t\t} as Model<Api>);\n\t\t\t}\n\n\t\t\t// Apply OAuth modifyModels if credentials exist (e.g., to update baseUrl)\n\t\t\tif (config.oauth?.modifyModels) {\n\t\t\t\tconst cred = this.authStorage.get(providerName);\n\t\t\t\tif (cred?.type === \"oauth\") {\n\t\t\t\t\tthis.models = config.oauth.modifyModels(this.models, cred);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Ensure newly added extension models get capability patches\n\t\t\tthis.models = applyCapabilityPatches(this.models);\n\t\t} else if (config.baseUrl) {\n\t\t\t// Override-only: update baseUrl/headers for existing models\n\t\t\tconst resolvedHeaders = resolveHeaders(config.headers);\n\t\t\tthis.models = this.models.map((m) => {\n\t\t\t\tif (m.provider !== providerName) return m;\n\t\t\t\treturn {\n\t\t\t\t\t...m,\n\t\t\t\t\tbaseUrl: config.baseUrl ?? m.baseUrl,\n\t\t\t\t\theaders: resolvedHeaders ? { ...m.headers, ...resolvedHeaders } : m.headers,\n\t\t\t\t};\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Discover models from all providers that support discovery.\n\t * Results are cached and merged into the registry (never overrides existing models).\n\t */\n\tasync discoverModels(providers?: string[]): Promise<DiscoveryResult[]> {\n\t\tconst targetProviders = providers ?? this.getAutoDiscoverableProviders();\n\t\tconst results: DiscoveryResult[] = [];\n\n\t\tfor (const providerName of targetProviders) {\n\t\t\tconst providerApis = this.getProviderApis(providerName);\n\t\t\tconst adapter = getDiscoveryAdapter(providerName, providerApis);\n\t\t\tif (!adapter.supportsDiscovery) continue;\n\n\t\t\t// Skip if cache is still fresh\n\t\t\tif (!this.discoveryCache.isStale(providerName)) {\n\t\t\t\tconst cached = this.discoveryCache.get(providerName);\n\t\t\t\tif (cached) {\n\t\t\t\t\tresults.push({\n\t\t\t\t\t\tprovider: providerName,\n\t\t\t\t\t\tmodels: cached.models,\n\t\t\t\t\t\tfetchedAt: cached.fetchedAt,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst apiKey = await this.authStorage.getApiKey(providerName);\n\t\t\t\tif (!apiKey && !this.isProviderRequestReady(providerName)) continue;\n\n\t\t\t\tconst baseUrl = this.getProviderBaseUrl(providerName);\n\t\t\t\tconst models = await adapter.fetchModels(apiKey ?? \"\", baseUrl);\n\t\t\t\tconst ttlMs = this.getDiscoveryTtl(providerName, providerApis);\n\t\t\t\tthis.discoveryCache.set(providerName, models, ttlMs);\n\t\t\t\tresults.push({\n\t\t\t\t\tprovider: providerName,\n\t\t\t\t\tmodels,\n\t\t\t\t\tfetchedAt: Date.now(),\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tresults.push({\n\t\t\t\t\tprovider: providerName,\n\t\t\t\t\tmodels: [],\n\t\t\t\t\tfetchedAt: Date.now(),\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Convert and merge discovered models, then apply capability patches\n\t\tthis.discoveredModels = applyCapabilityPatches(this.convertDiscoveredModels(results));\n\t\treturn results;\n\t}\n\n\t/**\n\t * Get all models including discovered ones.\n\t * Discovered models are appended but never override existing models.\n\t */\n\tgetAllWithDiscovered(): Model<Api>[] {\n\t\tconst existingIds = new Set(this.models.map((m) => `${m.provider}/${m.id}`));\n\t\tconst unique = this.discoveredModels.filter((m) => !existingIds.has(`${m.provider}/${m.id}`));\n\t\treturn [...this.models, ...unique];\n\t}\n\n\t/**\n\t * Check if a model was added via discovery (not built-in or custom).\n\t */\n\tisDiscovered(model: Model<Api>): boolean {\n\t\treturn this.discoveredModels.some((m) => m.provider === model.provider && m.id === model.id);\n\t}\n\n\t/**\n\t * Get the discovery cache instance.\n\t */\n\tgetDiscoveryCache(): ModelDiscoveryCache {\n\t\treturn this.discoveryCache;\n\t}\n\n\t/**\n\t * Convert DiscoveryResult[] into Model<Api>[] with default values.\n\t */\n\tprivate convertDiscoveredModels(results: DiscoveryResult[]): Model<Api>[] {\n\t\tconst converted: Model<Api>[] = [];\n\t\tfor (const result of results) {\n\t\t\tif (result.error) continue;\n\t\t\tconst providerDefaults = this.getDiscoveryProviderDefaults(result.provider);\n\t\t\tfor (const dm of result.models) {\n\t\t\t\tconverted.push({\n\t\t\t\t\tid: dm.id,\n\t\t\t\t\tname: dm.name ?? dm.id,\n\t\t\t\t\tapi: providerDefaults.api,\n\t\t\t\t\tprovider: result.provider,\n\t\t\t\t\tbaseUrl: providerDefaults.baseUrl,\n\t\t\t\t\treasoning: dm.reasoning ?? false,\n\t\t\t\t\tinput: dm.input ?? providerDefaults.input,\n\t\t\t\t\tcost: dm.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\t\t\t\tcontextWindow: dm.contextWindow ?? providerDefaults.contextWindow,\n\t\t\t\t\tmaxTokens: dm.maxTokens ?? providerDefaults.maxTokens,\n\t\t\t\t} as Model<Api>);\n\t\t\t}\n\t\t}\n\t\treturn converted;\n\t}\n\n\tprivate getProviderApis(provider: string): Set<string> {\n\t\tconst apis = new Set<string>();\n\t\tfor (const model of this.models) {\n\t\t\tif (model.provider === provider && typeof model.api === \"string\" && model.api.length > 0) {\n\t\t\t\tapis.add(model.api);\n\t\t\t}\n\t\t}\n\n\t\tconst providerConfig = this.registeredProviders.get(provider);\n\t\tif (providerConfig?.api) apis.add(providerConfig.api);\n\t\tfor (const modelDef of providerConfig?.models ?? []) {\n\t\t\tif (modelDef.api) apis.add(modelDef.api);\n\t\t}\n\t\treturn apis;\n\t}\n\n\tprivate getAutoDiscoverableProviders(): string[] {\n\t\tconst discoverable = new Set<string>(getDiscoverableProviders());\n\t\tfor (const provider of new Set(this.models.map((m) => m.provider))) {\n\t\t\tconst apis = this.getProviderApis(provider);\n\t\t\tfor (const api of apis) {\n\t\t\t\tif (supportsDiscoveryForApi(api)) {\n\t\t\t\t\tdiscoverable.add(provider);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn [...discoverable];\n\t}\n\n\tprivate getProviderBaseUrl(provider: string): string | undefined {\n\t\tconst fromModels = this.models.find((m) => m.provider === provider && typeof m.baseUrl === \"string\" && m.baseUrl.length > 0);\n\t\tif (fromModels?.baseUrl) return fromModels.baseUrl;\n\t\treturn this.registeredProviders.get(provider)?.baseUrl;\n\t}\n\n\tprivate getDiscoveryProviderDefaults(provider: string): {\n\t\tapi: Api;\n\t\tbaseUrl: string;\n\t\tinput: (\"text\" | \"image\")[];\n\t\tcontextWindow: number;\n\t\tmaxTokens: number;\n\t} {\n\t\tconst first = this.models.find((m) => m.provider === provider);\n\t\tif (first) {\n\t\t\treturn {\n\t\t\t\tapi: first.api,\n\t\t\t\tbaseUrl: first.baseUrl,\n\t\t\t\tinput: first.input,\n\t\t\t\tcontextWindow: first.contextWindow,\n\t\t\t\tmaxTokens: first.maxTokens,\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tapi: \"openai-completions\",\n\t\t\tbaseUrl: this.registeredProviders.get(provider)?.baseUrl ?? \"\",\n\t\t\tinput: [\"text\"],\n\t\t\tcontextWindow: 128000,\n\t\t\tmaxTokens: 16384,\n\t\t};\n\t}\n\n\tprivate getDiscoveryTtl(provider: string, providerApis: Set<string>): number {\n\t\tfor (const api of providerApis) {\n\t\t\tif (supportsDiscoveryForApi(api)) {\n\t\t\t\treturn getDefaultTTL(\"openai\");\n\t\t\t}\n\t\t}\n\t\treturn getDefaultTTL(provider);\n\t}\n\n\t/**\n\t * Check if a model's baseUrl points to a local endpoint.\n\t * Delegates to standalone isLocalModel() function.\n\t */\n\tstatic isLocalModel(model: Model<Api>): boolean {\n\t\treturn isLocalModel(model);\n\t}\n\n\t/**\n\t * Check if all models in the registry are local.\n\t * Returns true only if every model passes isLocalModel().\n\t * Returns false if there are no models.\n\t */\n\tisAllLocalChain(): boolean {\n\t\tconst models = this.getAll();\n\t\tif (models.length === 0) return false;\n\t\treturn models.every((m) => isLocalModel(m));\n\t}\n}\n\n/**\n * Input type for registerProvider API.\n */\nexport interface ProviderConfigInput {\n\tauthMode?: ProviderAuthMode;\n\t/** Optional readiness check. Called by isProviderRequestReady() before default auth checks.\n\t * Trusted at the same level as extension code — extensions already have arbitrary code execution. */\n\tisReady?: () => boolean;\n\tbaseUrl?: string;\n\tapiKey?: string;\n\tapi?: Api;\n\tstreamSimple?: (model: Model<Api>, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\theaders?: Record<string, string>;\n\tauthHeader?: boolean;\n\t/** OAuth provider for /login support */\n\toauth?: Omit<OAuthProviderInterface, \"id\">;\n\tmodels?: Array<{\n\t\tid: string;\n\t\tname: string;\n\t\tapi?: Api;\n\t\tbaseUrl?: string;\n\t\treasoning: boolean;\n\t\tinput: (\"text\" | \"image\")[];\n\t\tcost: { input: number; output: number; cacheRead: number; cacheWrite: number };\n\t\tcontextWindow: number;\n\t\tmaxTokens: number;\n\t\theaders?: Record<string, string>;\n\t\tcompat?: Model<Api>[\"compat\"];\n\t\tproviderOptions?: Record<string, unknown>;\n\t}>;\n}\n"]}
|
|
@@ -42,6 +42,19 @@ export interface BuildSystemPromptOptions {
|
|
|
42
42
|
* exception and the session stays consistent.
|
|
43
43
|
*/
|
|
44
44
|
skillFilter?: (skill: Skill) => boolean;
|
|
45
|
+
/**
|
|
46
|
+
* Append a `Current date and time: <toLocaleString>` line to the system
|
|
47
|
+
* prompt. Default: `false`.
|
|
48
|
+
*
|
|
49
|
+
* Anthropic prompt caching matches on byte-for-byte prefix equality.
|
|
50
|
+
* Embedding a per-call timestamp in the system prompt invalidates the
|
|
51
|
+
* cache on every request, forcing a full re-write that costs *more*
|
|
52
|
+
* than an uncached call (cache-write premium). Most agentic flows do
|
|
53
|
+
* not need wall-clock awareness in the system prompt — opt in only
|
|
54
|
+
* when the consumer genuinely needs it (e.g. a clock-sensitive agent),
|
|
55
|
+
* and inject it via a non-cached channel (user message) when possible.
|
|
56
|
+
*/
|
|
57
|
+
includeDateTime?: boolean;
|
|
45
58
|
}
|
|
46
59
|
/** Build the system prompt with tools, guidelines, and context */
|
|
47
60
|
export declare function buildSystemPrompt(options?: BuildSystemPromptOptions): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAchE,MAAM,WAAW,wBAAwB;IACxC,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,qEAAqE;IACrE,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,MAAM,CA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AkE;AAClE,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,wBAA6B,GAAG,MAAM,CAgOhF"}
|
|
@@ -17,19 +17,23 @@ const toolDescriptions = {
|
|
|
17
17
|
};
|
|
18
18
|
/** Build the system prompt with tools, guidelines, and context */
|
|
19
19
|
export function buildSystemPrompt(options = {}) {
|
|
20
|
-
const { customPrompt, selectedTools, toolSnippets, promptGuidelines, appendSystemPrompt, cwd, contextFiles: providedContextFiles, skills: providedSkills, skillFilter, } = options;
|
|
20
|
+
const { customPrompt, selectedTools, toolSnippets, promptGuidelines, appendSystemPrompt, cwd, contextFiles: providedContextFiles, skills: providedSkills, skillFilter, includeDateTime = false, } = options;
|
|
21
21
|
const resolvedCwd = toPosixPath(cwd ?? process.cwd());
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
22
|
+
// Per-call timestamps invalidate Anthropic prompt caching (the cache
|
|
23
|
+
// matches on byte-for-byte prefix equality). Compute lazily and only
|
|
24
|
+
// when explicitly opted in via `includeDateTime`.
|
|
25
|
+
const dateTimeLine = includeDateTime
|
|
26
|
+
? `\nCurrent date and time: ${new Date().toLocaleString("en-US", {
|
|
27
|
+
weekday: "long",
|
|
28
|
+
year: "numeric",
|
|
29
|
+
month: "long",
|
|
30
|
+
day: "numeric",
|
|
31
|
+
hour: "2-digit",
|
|
32
|
+
minute: "2-digit",
|
|
33
|
+
second: "2-digit",
|
|
34
|
+
timeZoneName: "short",
|
|
35
|
+
})}`
|
|
36
|
+
: "";
|
|
33
37
|
const appendSection = appendSystemPrompt ? `\n\n${appendSystemPrompt}` : "";
|
|
34
38
|
const contextFiles = providedContextFiles ?? [];
|
|
35
39
|
const skillsBase = providedSkills ?? [];
|
|
@@ -65,8 +69,8 @@ export function buildSystemPrompt(options = {}) {
|
|
|
65
69
|
if (customPromptHasSkillAccess && skills.length > 0) {
|
|
66
70
|
prompt += formatSkillsForPrompt(skills);
|
|
67
71
|
}
|
|
68
|
-
// Add date/time and working directory last
|
|
69
|
-
prompt +=
|
|
72
|
+
// Add date/time (only when opted in — see includeDateTime docs) and working directory last
|
|
73
|
+
prompt += dateTimeLine;
|
|
70
74
|
prompt += `\nCurrent working directory: ${resolvedCwd}`;
|
|
71
75
|
// Append promptGuidelines from extension-registered tools.
|
|
72
76
|
// Without this, tools registered via pi.registerTool() with promptGuidelines
|
|
@@ -189,8 +193,8 @@ Pi documentation (read only when the user asks about pi itself, its SDK, extensi
|
|
|
189
193
|
if ((hasRead || hasSkill) && skills.length > 0) {
|
|
190
194
|
prompt += formatSkillsForPrompt(skills);
|
|
191
195
|
}
|
|
192
|
-
// Add date/time and working directory last
|
|
193
|
-
prompt +=
|
|
196
|
+
// Add date/time (only when opted in — see includeDateTime docs) and working directory last
|
|
197
|
+
prompt += dateTimeLine;
|
|
194
198
|
prompt += `\nCurrent working directory: ${resolvedCwd}`;
|
|
195
199
|
return prompt;
|
|
196
200
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAEhE,0CAA0C;AAC1C,MAAM,gBAAgB,GAA2B;IAChD,IAAI,EAAE,oBAAoB;IAC1B,IAAI,EAAE,8CAA8C;IACpD,IAAI,EAAE,4DAA4D;IAClE,KAAK,EAAE,2BAA2B;IAClC,IAAI,EAAE,yDAAyD;IAC/D,IAAI,EAAE,kDAAkD;IACxD,EAAE,EAAE,yBAAyB;IAC7B,GAAG,EAAE,oHAAoH;CACzH,CAAC;AAyCF,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, getReadmePath } from \"../config.js\";\nimport { toPosixPath } from \"../utils/path-display.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.js\";\n\n/** Tool descriptions for system prompt */\nconst toolDescriptions: Record<string, string> = {\n\tread: \"Read file contents\",\n\tbash: \"Execute bash commands (ls, grep, find, etc.)\",\n\tedit: \"Make surgical edits to files (find exact text and replace)\",\n\twrite: \"Create or overwrite files\",\n\tgrep: \"Search file contents for patterns (respects .gitignore)\",\n\tfind: \"Find files by glob pattern (respects .gitignore)\",\n\tls: \"List directory contents\",\n\tlsp: \"Code intelligence via Language Server Protocol (go-to-definition, references, diagnostics, hover, rename, symbols)\",\n};\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. Default: process.cwd() */\n\tcwd?: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n\t/**\n\t * Optional predicate applied to the `skills` list before rendering the\n\t * <available_skills> catalog. Returning `false` omits a skill from the\n\t * prompt (the skill remains loaded and invocable by name — only the\n\t * catalog listing is suppressed).\n\t *\n\t * Intended for consumers that can narrow the relevant skill surface\n\t * (e.g. per-unit-type manifests) to reduce cached system-prompt bloat.\n\t * When omitted, all non-`disableModelInvocation` skills render — i.e.\n\t * behavior is unchanged from before this option existed.\n\t *\n\t * Contract: the predicate must be **pure and synchronous**. It may be\n\t * invoked on every system-prompt rebuild (tool-set changes and\n\t * runtime resource-loader extensions both trigger one), so any state\n\t * the closure captures should be stable across the rebuild window.\n\t * If the predicate throws, `buildSystemPrompt` logs a warning and\n\t * falls back to the unfiltered skill list — callers never see the\n\t * exception and the session stays consistent.\n\t */\n\tskillFilter?: (skill: Skill) => boolean;\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions = {}): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t\tskillFilter,\n\t} = options;\n\tconst resolvedCwd = toPosixPath(cwd ?? process.cwd());\n\n\tconst now = new Date();\n\tconst dateTime = now.toLocaleString(\"en-US\", {\n\t\tweekday: \"long\",\n\t\tyear: \"numeric\",\n\t\tmonth: \"long\",\n\t\tday: \"numeric\",\n\t\thour: \"2-digit\",\n\t\tminute: \"2-digit\",\n\t\tsecond: \"2-digit\",\n\t\ttimeZoneName: \"short\",\n\t});\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skillsBase = providedSkills ?? [];\n\tlet skills = skillsBase;\n\tif (skillFilter) {\n\t\ttry {\n\t\t\tskills = skillsBase.filter(skillFilter);\n\t\t} catch (error) {\n\t\t\t// A consumer's predicate threw. Fall back to the unfiltered list so\n\t\t\t// the session stays consistent — callers (e.g. AgentSession.setTools)\n\t\t\t// must not be left with updated tools but a stale system prompt.\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconsole.warn(`buildSystemPrompt: skillFilter threw; falling back to unfiltered skills. Error: ${message}`);\n\t\t\tskills = skillsBase;\n\t\t}\n\t}\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Append skills section (if read or Skill tool is available)\n\t\tconst customPromptHasSkillAccess = !selectedTools || selectedTools.includes(\"read\") || selectedTools.includes(\"Skill\");\n\t\tif (customPromptHasSkillAccess && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Add date/time and working directory last\n\t\tprompt += `\\nCurrent date and time: ${dateTime}`;\n\t\tprompt += `\\nCurrent working directory: ${resolvedCwd}`;\n\n\t\t// Append promptGuidelines from extension-registered tools.\n\t\t// Without this, tools registered via pi.registerTool() with promptGuidelines\n\t\t// have their definitions reach the API but the model has no guidance on when\n\t\t// to use them (#1184).\n\t\tif (promptGuidelines && promptGuidelines.length > 0) {\n\t\t\tprompt += \"\\n\\n\";\n\t\t\tfor (const guideline of promptGuidelines) {\n\t\t\t\tprompt += guideline + \"\\n\";\n\t\t\t}\n\t\t}\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = toPosixPath(getReadmePath());\n\tconst docsPath = toPosixPath(getDocsPath());\n\tconst examplesPath = toPosixPath(getExamplesPath());\n\n\t// Build tools list based on selected tools.\n\t// Built-ins use toolDescriptions. Custom tools can provide one-line snippets.\n\tconst tools = selectedTools || [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst toolsList =\n\t\ttools.length > 0\n\t\t\t? tools\n\t\t\t\t\t.map((name) => {\n\t\t\t\t\t\tconst snippet = toolSnippets?.[name] ?? toolDescriptions[name] ?? name;\n\t\t\t\t\t\treturn `- ${name}: ${snippet}`;\n\t\t\t\t\t})\n\t\t\t\t\t.join(\"\\n\")\n\t\t\t: \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasEdit = tools.includes(\"edit\");\n\tconst hasWrite = tools.includes(\"write\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst hasRead = tools.includes(\"read\");\n\tconst hasLsp = tools.includes(\"lsp\");\n\n\t// File exploration guidelines\n\tif (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t} else if (hasBash && (hasGrep || hasFind || hasLs)) {\n\t\taddGuideline(\"Prefer grep/find/ls tools over bash for file exploration (faster, respects .gitignore)\");\n\t}\n\n\t// Read before edit guideline\n\tif (hasRead && hasEdit) {\n\t\taddGuideline(\"Use read to examine files before editing. You must use this tool instead of cat or sed.\");\n\t}\n\n\t// Edit guideline\n\tif (hasEdit) {\n\t\taddGuideline(\"Use edit for precise changes (old text must match exactly)\");\n\t}\n\n\t// Write guideline\n\tif (hasWrite) {\n\t\taddGuideline(\"Use write only for new files or complete rewrites\");\n\t}\n\n\t// LSP guideline\n\tif (hasLsp) {\n\t\taddGuideline(\n\t\t\t`Use lsp as the primary tool for code navigation in typed codebases:\n- Navigation: definition, type_definition, implementation, references, incoming_calls, outgoing_calls\n- Understanding: hover (types + docs), signature (parameter info), symbols (file/workspace search)\n- Refactoring: rename (project-wide), code_actions (quick-fixes, imports, refactors), format (formatter)\n- Verification: diagnostics after edits to catch type errors immediately\n- Never grep for a symbol definition when lsp can resolve it semantically\n- Never shell out to a formatter when lsp format is available`,\n\t\t);\n\t}\n\n\t// Output guideline (only when actually writing or executing)\n\tif (hasEdit || hasWrite) {\n\t\taddGuideline(\n\t\t\t\"When summarizing your actions, output plain text directly - do NOT use cat or bash to display what you did\",\n\t\t);\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}\n\nPi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md)\n- When working on pi topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\n\t}\n\n\t// Append skills section (if read or Skill tool is available)\n\tconst hasSkill = tools.includes(\"Skill\");\n\tif ((hasRead || hasSkill) && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Add date/time and working directory last\n\tprompt += `\\nCurrent date and time: ${dateTime}`;\n\tprompt += `\\nCurrent working directory: ${resolvedCwd}`;\n\n\treturn prompt;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAEhE,0CAA0C;AAC1C,MAAM,gBAAgB,GAA2B;IAChD,IAAI,EAAE,oBAAoB;IAC1B,IAAI,EAAE,8CAA8C;IACpD,IAAI,EAAE,4DAA4D;IAClE,KAAK,EAAE,2BAA2B;IAClC,IAAI,EAAE,yDAAyD;IAC/D,IAAI,EAAE,kDAAkD;IACxD,EAAE,EAAE,yBAAyB;IAC7B,GAAG,EAAE,oHAAoH;CACzH,CAAC;AAsDF,kEAAkE;AAClE,MAAM,UAAU,iBAAiB,CAAC,UAAoC,EAAE;IACvE,MAAM,EACL,YAAY,EACZ,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,GAAG,EACH,YAAY,EAAE,oBAAoB,EAClC,MAAM,EAAE,cAAc,EACtB,WAAW,EACX,eAAe,GAAG,KAAK,GACvB,GAAG,OAAO,CAAC;IACZ,MAAM,WAAW,GAAG,WAAW,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;IAEtD,qEAAqE;IACrE,qEAAqE;IACrE,kDAAkD;IAClD,MAAM,YAAY,GAAG,eAAe;QACnC,CAAC,CAAC,4BAA4B,IAAI,IAAI,EAAE,CAAC,cAAc,CAAC,OAAO,EAAE;YAChE,OAAO,EAAE,MAAM;YACf,IAAI,EAAE,SAAS;YACf,KAAK,EAAE,MAAM;YACb,GAAG,EAAE,SAAS;YACd,IAAI,EAAE,SAAS;YACf,MAAM,EAAE,SAAS;YACjB,MAA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AAE,CAAC;QAC7B,MAAM,IAAI,2BAA2B,CAAC;QACtC,MAAM,IAAI,mDAAmD,CAAC;QAC9D,KAAK,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,YAAY,EAAE,CAAC;YACxD,MAAM,IAAI,MAAM,QAAQ,OAAO,OAAO,MAAM,CAAC;QAC9C,CAAC;IACF,CAAC;IAED,6DAA6D;IAC7D,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACzC,IAAI,CAAC,OAAO,IAAI,QAAQ,CAAC,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAChD,MAAM,IAAI,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACzC,CAAC;IAED,2FAA2F;IAC3F,MAAM,IAAI,YAAY,CAAC;IACvB,MAAM,IAAI,gCAAgC,WAAW,EAAE,CAAC;IAExD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.js\";\nimport { toPosixPath } from \"../utils/path-display.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.js\";\n\n/** Tool descriptions for system prompt */\nconst toolDescriptions: Record<string, string> = {\n\tread: \"Read file contents\",\n\tbash: \"Execute bash commands (ls, grep, find, etc.)\",\n\tedit: \"Make surgical edits to files (find exact text and replace)\",\n\twrite: \"Create or overwrite files\",\n\tgrep: \"Search file contents for patterns (respects .gitignore)\",\n\tfind: \"Find files by glob pattern (respects .gitignore)\",\n\tls: \"List directory contents\",\n\tlsp: \"Code intelligence via Language Server Protocol (go-to-definition, references, diagnostics, hover, rename, symbols)\",\n};\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. Default: process.cwd() */\n\tcwd?: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n\t/**\n\t * Optional predicate applied to the `skills` list before rendering the\n\t * <available_skills> catalog. Returning `false` omits a skill from the\n\t * prompt (the skill remains loaded and invocable by name — only the\n\t * catalog listing is suppressed).\n\t *\n\t * Intended for consumers that can narrow the relevant skill surface\n\t * (e.g. per-unit-type manifests) to reduce cached system-prompt bloat.\n\t * When omitted, all non-`disableModelInvocation` skills render — i.e.\n\t * behavior is unchanged from before this option existed.\n\t *\n\t * Contract: the predicate must be **pure and synchronous**. It may be\n\t * invoked on every system-prompt rebuild (tool-set changes and\n\t * runtime resource-loader extensions both trigger one), so any state\n\t * the closure captures should be stable across the rebuild window.\n\t * If the predicate throws, `buildSystemPrompt` logs a warning and\n\t * falls back to the unfiltered skill list — callers never see the\n\t * exception and the session stays consistent.\n\t */\n\tskillFilter?: (skill: Skill) => boolean;\n\t/**\n\t * Append a `Current date and time: <toLocaleString>` line to the system\n\t * prompt. Default: `false`.\n\t *\n\t * Anthropic prompt caching matches on byte-for-byte prefix equality.\n\t * Embedding a per-call timestamp in the system prompt invalidates the\n\t * cache on every request, forcing a full re-write that costs *more*\n\t * than an uncached call (cache-write premium). Most agentic flows do\n\t * not need wall-clock awareness in the system prompt — opt in only\n\t * when the consumer genuinely needs it (e.g. a clock-sensitive agent),\n\t * and inject it via a non-cached channel (user message) when possible.\n\t */\n\tincludeDateTime?: boolean;\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions = {}): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t\tskillFilter,\n\t\tincludeDateTime = false,\n\t} = options;\n\tconst resolvedCwd = toPosixPath(cwd ?? process.cwd());\n\n\t// Per-call timestamps invalidate Anthropic prompt caching (the cache\n\t// matches on byte-for-byte prefix equality). Compute lazily and only\n\t// when explicitly opted in via `includeDateTime`.\n\tconst dateTimeLine = includeDateTime\n\t\t? `\\nCurrent date and time: ${new Date().toLocaleString(\"en-US\", {\n\t\t\tweekday: \"long\",\n\t\t\tyear: \"numeric\",\n\t\t\tmonth: \"long\",\n\t\t\tday: \"numeric\",\n\t\t\thour: \"2-digit\",\n\t\t\tminute: \"2-digit\",\n\t\t\tsecond: \"2-digit\",\n\t\t\ttimeZoneName: \"short\",\n\t\t})}`\n\t\t: \"\";\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skillsBase = providedSkills ?? [];\n\tlet skills = skillsBase;\n\tif (skillFilter) {\n\t\ttry {\n\t\t\tskills = skillsBase.filter(skillFilter);\n\t\t} catch (error) {\n\t\t\t// A consumer's predicate threw. Fall back to the unfiltered list so\n\t\t\t// the session stays consistent — callers (e.g. AgentSession.setTools)\n\t\t\t// must not be left with updated tools but a stale system prompt.\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconsole.warn(`buildSystemPrompt: skillFilter threw; falling back to unfiltered skills. Error: ${message}`);\n\t\t\tskills = skillsBase;\n\t\t}\n\t}\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Append skills section (if read or Skill tool is available)\n\t\tconst customPromptHasSkillAccess = !selectedTools || selectedTools.includes(\"read\") || selectedTools.includes(\"Skill\");\n\t\tif (customPromptHasSkillAccess && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Add date/time (only when opted in — see includeDateTime docs) and working directory last\n\t\tprompt += dateTimeLine;\n\t\tprompt += `\\nCurrent working directory: ${resolvedCwd}`;\n\n\t\t// Append promptGuidelines from extension-registered tools.\n\t\t// Without this, tools registered via pi.registerTool() with promptGuidelines\n\t\t// have their definitions reach the API but the model has no guidance on when\n\t\t// to use them (#1184).\n\t\tif (promptGuidelines && promptGuidelines.length > 0) {\n\t\t\tprompt += \"\\n\\n\";\n\t\t\tfor (const guideline of promptGuidelines) {\n\t\t\t\tprompt += guideline + \"\\n\";\n\t\t\t}\n\t\t}\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = toPosixPath(getReadmePath());\n\tconst docsPath = toPosixPath(getDocsPath());\n\tconst examplesPath = toPosixPath(getExamplesPath());\n\n\t// Build tools list based on selected tools.\n\t// Built-ins use toolDescriptions. Custom tools can provide one-line snippets.\n\tconst tools = selectedTools || [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst toolsList =\n\t\ttools.length > 0\n\t\t\t? tools\n\t\t\t\t\t.map((name) => {\n\t\t\t\t\t\tconst snippet = toolSnippets?.[name] ?? toolDescriptions[name] ?? name;\n\t\t\t\t\t\treturn `- ${name}: ${snippet}`;\n\t\t\t\t\t})\n\t\t\t\t\t.join(\"\\n\")\n\t\t\t: \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasEdit = tools.includes(\"edit\");\n\tconst hasWrite = tools.includes(\"write\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst hasRead = tools.includes(\"read\");\n\tconst hasLsp = tools.includes(\"lsp\");\n\n\t// File exploration guidelines\n\tif (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t} else if (hasBash && (hasGrep || hasFind || hasLs)) {\n\t\taddGuideline(\"Prefer grep/find/ls tools over bash for file exploration (faster, respects .gitignore)\");\n\t}\n\n\t// Read before edit guideline\n\tif (hasRead && hasEdit) {\n\t\taddGuideline(\"Use read to examine files before editing. You must use this tool instead of cat or sed.\");\n\t}\n\n\t// Edit guideline\n\tif (hasEdit) {\n\t\taddGuideline(\"Use edit for precise changes (old text must match exactly)\");\n\t}\n\n\t// Write guideline\n\tif (hasWrite) {\n\t\taddGuideline(\"Use write only for new files or complete rewrites\");\n\t}\n\n\t// LSP guideline\n\tif (hasLsp) {\n\t\taddGuideline(\n\t\t\t`Use lsp as the primary tool for code navigation in typed codebases:\n- Navigation: definition, type_definition, implementation, references, incoming_calls, outgoing_calls\n- Understanding: hover (types + docs), signature (parameter info), symbols (file/workspace search)\n- Refactoring: rename (project-wide), code_actions (quick-fixes, imports, refactors), format (formatter)\n- Verification: diagnostics after edits to catch type errors immediately\n- Never grep for a symbol definition when lsp can resolve it semantically\n- Never shell out to a formatter when lsp format is available`,\n\t\t);\n\t}\n\n\t// Output guideline (only when actually writing or executing)\n\tif (hasEdit || hasWrite) {\n\t\taddGuideline(\n\t\t\t\"When summarizing your actions, output plain text directly - do NOT use cat or bash to display what you did\",\n\t\t);\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}\n\nPi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md)\n- When working on pi topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\n\t}\n\n\t// Append skills section (if read or Skill tool is available)\n\tconst hasSkill = tools.includes(\"Skill\");\n\tif ((hasRead || hasSkill) && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Add date/time (only when opted in — see includeDateTime docs) and working directory last\n\tprompt += dateTimeLine;\n\tprompt += `\\nCurrent working directory: ${resolvedCwd}`;\n\n\treturn prompt;\n}\n"]}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { AssistantMessage } from "@gsd/pi-ai";
|
|
2
|
+
/** Schema of one telemetry line. JSON-stable for downstream ingestion. */
|
|
3
|
+
export interface TokenTelemetryRecord {
|
|
4
|
+
ts: number;
|
|
5
|
+
model: string;
|
|
6
|
+
stopReason: string;
|
|
7
|
+
input: number;
|
|
8
|
+
output: number;
|
|
9
|
+
cacheRead: number;
|
|
10
|
+
cacheWrite: number;
|
|
11
|
+
/**
|
|
12
|
+
* `usage.cost.total` from the provider. `0` when the provider's cost
|
|
13
|
+
* registry has no rates for this model (e.g. unknown third-party providers)
|
|
14
|
+
* — distinguish from a true zero-cost call by checking your model registry.
|
|
15
|
+
*/
|
|
16
|
+
costTotal: number;
|
|
17
|
+
/**
|
|
18
|
+
* Fraction of new prompt tokens served from cache:
|
|
19
|
+
* `cacheRead / (cacheRead + input)`. Range [0, 1].
|
|
20
|
+
* - `0` when neither cacheRead nor input is present (no division by zero).
|
|
21
|
+
* - `1` on a full cache hit (input = 0, cacheRead > 0).
|
|
22
|
+
* Note: `input` here is `input_tokens` from the API, which already excludes
|
|
23
|
+
* cache reads/writes — the denominator is total prompt tokens consumed.
|
|
24
|
+
*/
|
|
25
|
+
cacheHitRatio: number;
|
|
26
|
+
}
|
|
27
|
+
/** Build a telemetry record from a finished assistant message. */
|
|
28
|
+
export declare function buildTokenTelemetryRecord(msg: AssistantMessage): TokenTelemetryRecord;
|
|
29
|
+
/**
|
|
30
|
+
* Emit a token-telemetry line if `PI_TOKEN_TELEMETRY=1`. No-op otherwise.
|
|
31
|
+
*
|
|
32
|
+
* Writes to stderr so it doesn't interfere with TUI/stdout. One JSON object
|
|
33
|
+
* per line. Errors during emission are swallowed — telemetry must never
|
|
34
|
+
* break the agent loop.
|
|
35
|
+
*/
|
|
36
|
+
export declare function emitTokenTelemetry(msg: AssistantMessage): void;
|
|
37
|
+
//# sourceMappingURL=token-telemetry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"token-telemetry.d.ts","sourceRoot":"","sources":["../../src/core/token-telemetry.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD,0EAA0E;AAC1E,MAAM,WAAW,oBAAoB;IACpC,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,SAAS,EAAE,MAAM,CAAC;IAClB;;;;;;;OAOG;IACH,aAAa,EAAE,MAAM,CAAC;CACtB;AAED,kEAAkE;AAClE,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,gBAAgB,GAAG,oBAAoB,CAoBrF;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,gBAAgB,GAAG,IAAI,CAQ9D"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// @gsd/pi-coding-agent + token-telemetry — opt-in per-call token observability
|
|
2
|
+
//
|
|
3
|
+
// Emits a single JSON line per assistant message to stderr when
|
|
4
|
+
// `PI_TOKEN_TELEMETRY=1` is set. Captures the cache_read_input_tokens and
|
|
5
|
+
// cache_creation_input_tokens fields the providers already extract — so we
|
|
6
|
+
// can empirically measure prompt-cache effectiveness (e.g. for #5019 and
|
|
7
|
+
// future cache strategy work). Off by default — no behavior change.
|
|
8
|
+
//
|
|
9
|
+
// Capture pattern: `PI_TOKEN_TELEMETRY=1 npm start 2> token-telemetry.jsonl`
|
|
10
|
+
/** Build a telemetry record from a finished assistant message. */
|
|
11
|
+
export function buildTokenTelemetryRecord(msg) {
|
|
12
|
+
const input = msg.usage?.input ?? 0;
|
|
13
|
+
const output = msg.usage?.output ?? 0;
|
|
14
|
+
const cacheRead = msg.usage?.cacheRead ?? 0;
|
|
15
|
+
const cacheWrite = msg.usage?.cacheWrite ?? 0;
|
|
16
|
+
const costTotal = msg.usage?.cost?.total ?? 0;
|
|
17
|
+
const denom = cacheRead + input;
|
|
18
|
+
const cacheHitRatio = denom > 0 ? cacheRead / denom : 0;
|
|
19
|
+
return {
|
|
20
|
+
ts: msg.timestamp,
|
|
21
|
+
model: msg.model,
|
|
22
|
+
stopReason: msg.stopReason,
|
|
23
|
+
input,
|
|
24
|
+
output,
|
|
25
|
+
cacheRead,
|
|
26
|
+
cacheWrite,
|
|
27
|
+
costTotal,
|
|
28
|
+
cacheHitRatio,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Emit a token-telemetry line if `PI_TOKEN_TELEMETRY=1`. No-op otherwise.
|
|
33
|
+
*
|
|
34
|
+
* Writes to stderr so it doesn't interfere with TUI/stdout. One JSON object
|
|
35
|
+
* per line. Errors during emission are swallowed — telemetry must never
|
|
36
|
+
* break the agent loop.
|
|
37
|
+
*/
|
|
38
|
+
export function emitTokenTelemetry(msg) {
|
|
39
|
+
if (process.env.PI_TOKEN_TELEMETRY !== "1")
|
|
40
|
+
return;
|
|
41
|
+
try {
|
|
42
|
+
const record = buildTokenTelemetryRecord(msg);
|
|
43
|
+
process.stderr.write(`${JSON.stringify(record)}\n`);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
// Telemetry must never break the agent loop. Swallow.
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=token-telemetry.js.map
|