dal-code 1.0.45 → 1.0.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +76 -0
- package/NOTICE +49 -1
- package/dist/bun/register-bedrock.js +1 -0
- package/dist/cli/args.js +2 -2
- package/dist/cli/auth-check.js +1 -1
- package/dist/cli/auth-command.js +6 -5
- package/dist/cli/experimental/auth.js +1 -0
- package/dist/cli/experimental/cli.js +1 -0
- package/dist/cli/experimental/command-options.js +1 -0
- package/dist/cli/experimental/command.js +1 -0
- package/dist/cli/experimental/commands/client.js +1 -0
- package/dist/cli/experimental/commands/pi.js +1 -0
- package/dist/cli/experimental/commands/server.js +1 -0
- package/dist/cli/experimental/transport-address.js +1 -0
- package/dist/cli/list-models.js +2 -2
- package/dist/cli/piped-stdin.js +2 -0
- package/dist/cli/startup-diagnostics.js +1 -0
- package/dist/client/index.js +1 -0
- package/dist/client/remote-session.js +1 -0
- package/dist/client/transcript.js +1 -0
- package/dist/core/agent-log.d.ts +6 -0
- package/dist/core/agent-log.js +3 -0
- package/dist/core/agent-session-services.d.ts +0 -1
- package/dist/core/agent-session-services.js +1 -1
- package/dist/core/agent-session.d.ts +19 -2
- package/dist/core/agent-session.js +8 -8
- package/dist/core/client-identity.js +1 -0
- package/dist/core/compaction/branch-summarization.js +3 -3
- package/dist/core/compaction/compaction.d.ts +2 -2
- package/dist/core/compaction/compaction.js +11 -9
- package/dist/core/compaction-backoff.js +1 -0
- package/dist/core/dal-session-headers.js +1 -0
- package/dist/core/export-html/index.js +2 -2
- package/dist/core/export-html/template.html +1 -0
- package/dist/core/export-html/template.js +6 -6
- package/dist/core/export-html/vendor/marked-cjk-friendly.min.js +6 -0
- package/dist/core/export-html/vendor/marked.min.js +30 -29
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/extensions/runner.d.ts +6 -0
- package/dist/core/extensions/runner.js +1 -1
- package/dist/core/extensions/types.d.ts +1 -0
- package/dist/core/extensions/virtual-modules.js +1 -1
- package/dist/core/http-dispatcher.js +1 -1
- package/dist/core/model-config.d.ts +984 -0
- package/dist/core/model-config.js +5 -5
- package/dist/core/model-identity.js +2 -0
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-runtime.d.ts +2 -0
- package/dist/core/model-runtime.js +2 -2
- package/dist/core/package-manager.d.ts +2 -0
- package/dist/core/package-manager.js +2 -2
- package/dist/core/provider-attribution.js +1 -1
- package/dist/core/provider-composer.d.ts +2 -1
- package/dist/core/provider-composer.js +1 -1
- package/dist/core/sandbox/bwrap-placeholders.js +1 -1
- package/dist/core/sandbox/index.d.ts +1 -1
- package/dist/core/sandbox/index.js +1 -1
- package/dist/core/sandbox/policy.d.ts +4 -0
- package/dist/core/sandbox/policy.js +1 -1
- package/dist/core/sandbox/runtime.d.ts +2 -0
- package/dist/core/sandbox/runtime.js +1 -1
- package/dist/core/sandbox/shell-sandbox.d.ts +2 -0
- package/dist/core/sandbox/shell-sandbox.js +6 -6
- package/dist/core/sdk.js +1 -1
- package/dist/core/session-stall-monitor.d.ts +41 -0
- package/dist/core/session-stall-monitor.js +2 -0
- package/dist/core/settings-manager.d.ts +4 -0
- package/dist/core/settings-manager.js +1 -1
- package/dist/core/settings-schema.d.ts +2 -0
- package/dist/core/settings-schema.js +1 -1
- package/dist/core/stall-watchdog.d.ts +55 -0
- package/dist/core/stall-watchdog.js +1 -0
- package/dist/core/system-prompt.js +10 -10
- package/dist/core/tools/bash.d.ts +1 -0
- package/dist/core/tools/bash.js +14 -14
- package/dist/core/tools/edit.d.ts +1 -1
- package/dist/core/tools/edit.js +3 -3
- package/dist/core/tools/grep.js +1 -1
- package/dist/core/tools/path-utils.d.ts +1 -0
- package/dist/core/tools/path-utils.js +1 -1
- package/dist/dal/builtins.js +2 -2
- package/dist/dal/manifest.d.ts +1 -0
- package/dist/dal/manifest.js +1 -1
- package/dist/dal/safety-net.js +3 -1
- package/dist/extensions/codemode/execute.js +22 -16
- package/dist/extensions/mcp/config.js +2 -2
- package/dist/extensions/mcp/oauth.js +2 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/main.js +4 -4
- package/dist/migrations.js +3 -5
- package/dist/modes/interactive/components/daxnuts.js +1 -0
- package/dist/modes/interactive/external-editor.js +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +7 -7
- package/dist/modes/interactive/interactive-mode.js +25 -25
- package/dist/modes/interactive/session-share.js +1 -1
- package/dist/modes/interactive/theme/theme-json.js +12 -0
- package/dist/modes/interactive/theme/theme-schema.json +356 -0
- package/dist/modes/print-mode.d.ts +1 -0
- package/dist/modes/print-mode.js +8 -7
- package/dist/modes/rpc/rpc-client.js +3 -3
- package/dist/modes/rpc/rpc-mode.js +1 -1
- package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-capabilities/src/catalogue.js +1 -1
- package/dist/node_modules/@dalcode/dal-capabilities/src/index.js +10 -10
- package/dist/node_modules/@dalcode/dal-capabilities/src/match.js +1 -1
- package/dist/node_modules/@dalcode/dal-capabilities/src/state.js +3 -3
- package/dist/node_modules/@dalcode/dal-codeindex/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-codeindex/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-dap/src/install.js +2 -2
- package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-guard/package.json +5 -4
- package/dist/node_modules/@dalcode/dal-guard/src/credentials.js +7 -1
- package/dist/node_modules/@dalcode/dal-guard/src/edit-anchor-core.js +25 -23
- package/dist/node_modules/@dalcode/dal-guard/src/edit-anchor.js +4 -4
- package/dist/node_modules/@dalcode/dal-guard/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-guard/src/policy.js +1 -1
- package/dist/node_modules/@dalcode/dal-guard/src/session-files.js +1 -0
- package/dist/node_modules/@dalcode/dal-guard/src/suspicion.js +1 -0
- package/dist/node_modules/@dalcode/dal-guard/src/workspace.js +2 -2
- package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-learn/package.json +4 -2
- package/dist/node_modules/@dalcode/dal-learn/src/engine.js +4 -4
- package/dist/node_modules/@dalcode/dal-learn/src/index.js +15 -14
- package/dist/node_modules/@dalcode/dal-learn/src/revisions.js +3 -0
- package/dist/node_modules/@dalcode/dal-learn/src/safety.js +1 -1
- package/dist/node_modules/@dalcode/dal-learn/src/skill-evolution.js +14 -14
- package/dist/node_modules/@dalcode/dal-lsp/package.json +5 -3
- package/dist/node_modules/@dalcode/dal-lsp/src/config.js +1 -1
- package/dist/node_modules/@dalcode/dal-lsp/src/index.js +14 -13
- package/dist/node_modules/@dalcode/dal-lsp/src/managed.js +1 -0
- package/dist/node_modules/@dalcode/dal-mcp/package.json +7 -6
- package/dist/node_modules/@dalcode/dal-mcp/src/child-env.js +3 -0
- package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.d.ts +1 -0
- package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.js +3 -3
- package/dist/node_modules/@dalcode/dal-office/package.json +3 -2
- package/dist/node_modules/@dalcode/dal-office/src/extract/cell.js +1 -0
- package/dist/node_modules/@dalcode/dal-office/src/extract/index.js +2 -2
- package/dist/node_modules/@dalcode/dal-office/src/extract/ooxml.js +4 -4
- package/dist/node_modules/@dalcode/dal-office/src/extract/pdf.js +4 -4
- package/dist/node_modules/@dalcode/dal-office/src/facts.d.ts +15 -0
- package/dist/node_modules/@dalcode/dal-office/src/facts.js +4 -0
- package/dist/node_modules/@dalcode/dal-office/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-office/src/lazy.js +1 -0
- package/dist/node_modules/@dalcode/dal-office/src/{index.d.ts → office.d.ts} +2 -3
- package/dist/node_modules/@dalcode/dal-office/src/office.js +1 -0
- package/dist/node_modules/@dalcode/dal-office/src/render/capture.d.ts +21 -0
- package/dist/node_modules/@dalcode/dal-office/src/render/capture.js +13 -0
- package/dist/node_modules/@dalcode/dal-office/src/render/chart.d.ts +15 -0
- package/dist/node_modules/@dalcode/dal-office/src/render/chart.js +3 -3
- package/dist/node_modules/@dalcode/dal-office/src/render/docx.d.ts +4 -0
- package/dist/node_modules/@dalcode/dal-office/src/render/docx.js +1 -1
- package/dist/node_modules/@dalcode/dal-office/src/render/pptx.d.ts +2 -0
- package/dist/node_modules/@dalcode/dal-office/src/render/pptx.js +4 -3
- package/dist/node_modules/@dalcode/dal-office/src/render/table-layout.js +1 -0
- package/dist/node_modules/@dalcode/dal-office/src/render/xlsx-chart.d.ts +24 -0
- package/dist/node_modules/@dalcode/dal-office/src/render/xlsx-chart.js +1 -0
- package/dist/node_modules/@dalcode/dal-office/src/render/xlsx.d.ts +9 -0
- package/dist/node_modules/@dalcode/dal-office/src/render/xlsx.js +1 -1
- package/dist/node_modules/@dalcode/dal-office/src/scratchpad.d.ts +2 -0
- package/dist/node_modules/@dalcode/dal-office/src/scratchpad.js +1 -1
- package/dist/node_modules/@dalcode/dal-office/src/table-stats.js +2 -0
- package/dist/node_modules/@dalcode/dal-office/src/tools/chart-generate.js +4 -3
- package/dist/node_modules/@dalcode/dal-office/src/tools/doc-generate.js +2 -3
- package/dist/node_modules/@dalcode/dal-office/src/tools/docx-edit.js +5 -5
- package/dist/node_modules/@dalcode/dal-office/src/tools/drawio-generate.js +2 -3
- package/dist/node_modules/@dalcode/dal-office/src/tools/md-generate.js +2 -3
- package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-generate.js +5 -3
- package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-plan.js +4 -2
- package/dist/node_modules/@dalcode/dal-office/src/tools/pptx-edit.js +5 -5
- package/dist/node_modules/@dalcode/dal-office/src/tools/read-file.js +4 -3
- package/dist/node_modules/@dalcode/dal-office/src/tools/render-page.js +4 -0
- package/dist/node_modules/@dalcode/dal-office/src/tools/sheet-generate.js +3 -3
- package/dist/node_modules/@dalcode/dal-office/src/tools/xlsx-edit.js +3 -3
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +15 -15
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/project-size.js +1 -0
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +15 -15
- package/dist/node_modules/@dalcode/dal-pi-kit/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/project-size.js +1 -0
- package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -5
- package/dist/node_modules/@dalcode/dal-plugins/src/index.js +11 -11
- package/dist/node_modules/@dalcode/dal-plugins/src/manage.js +7 -7
- package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-recall/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-remote/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-rewind/src/commands.js +1 -1
- package/dist/node_modules/@dalcode/dal-rewind/src/core.d.ts +2 -0
- package/dist/node_modules/@dalcode/dal-rewind/src/core.js +6 -6
- package/dist/node_modules/@dalcode/dal-rewind/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-rewind/src/state.js +1 -1
- package/dist/node_modules/@dalcode/dal-router/package.json +8 -9
- package/dist/node_modules/@dalcode/dal-router/src/commands.js +8 -9
- package/dist/node_modules/@dalcode/dal-router/src/config.d.ts +3 -36
- package/dist/node_modules/@dalcode/dal-router/src/config.js +2 -2
- package/dist/node_modules/@dalcode/dal-router/src/index.js +2 -4
- package/dist/node_modules/@dalcode/dal-router/src/notice.js +1 -0
- package/dist/node_modules/@dalcode/dal-router/src/roles/deliverables.js +4 -0
- package/dist/node_modules/@dalcode/dal-router/src/roles/index.js +10 -8
- package/dist/node_modules/@dalcode/dal-router/src/roles/planner.js +4 -0
- package/dist/node_modules/@dalcode/dal-router/src/roles/prompts.js +18 -16
- package/dist/node_modules/@dalcode/dal-router/src/roles/signals.js +2 -2
- package/dist/node_modules/@dalcode/dal-router/src/runtime.d.ts +0 -13
- package/dist/node_modules/@dalcode/dal-router/src/runtime.js +1 -1
- package/dist/node_modules/@dalcode/dal-router/src/subagent.js +1 -1
- package/dist/node_modules/@dalcode/dal-router/src/task-shape.d.ts +8 -0
- package/dist/node_modules/@dalcode/dal-router/src/task-shape.js +1 -0
- package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-skills/package.json +4 -3
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/chart-design/SKILL.md +35 -0
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/dal-slides/SKILL.md +17 -9
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/diagram-design/SKILL.md +7 -5
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/poster-design/SKILL.md +8 -6
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/print-design/SKILL.md +21 -8
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/diagram.html +1 -1
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/mindmap.html +1 -1
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/event-poster.html +1 -1
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/poster.css +1 -1
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/square-card.html +1 -1
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/wechat-cover.html +1 -1
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/xhs-card.html +1 -1
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/posters/xhs-cover.html +8 -5
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/letter.html +1 -1
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/report.html +1 -1
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/visual-kit/print/resume.html +7 -3
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/web-design/SKILL.md +4 -4
- package/dist/node_modules/@dalcode/dal-skills/src/bundled.js +1 -1
- package/dist/node_modules/@dalcode/dal-skills/src/catalog.js +3 -2
- package/dist/node_modules/@dalcode/dal-skills/src/hint.js +1 -0
- package/dist/node_modules/@dalcode/dal-skills/src/index.js +13 -14
- package/dist/node_modules/@dalcode/dal-skills/src/search.js +1 -1
- package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-subagent/src/background.js +10 -10
- package/dist/node_modules/@dalcode/dal-subagent/src/index.js +18 -20
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-tool-catalog/src/groups.js +1 -1
- package/dist/node_modules/@dalcode/dal-tool-catalog/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-workflow/src/announce-check.js +3 -1
- package/dist/node_modules/@dalcode/dal-workflow/src/deliverable-scope.js +1 -0
- package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-workflow/src/test-proof-note.js +3 -0
- package/dist/node_modules/@dalcode/dal-workflow/src/todo-snapshot.js +2 -2
- package/dist/node_modules/@dalcode/dal-workflow/src/todo.js +4 -4
- package/dist/node_modules/@dalcode/dal-workflow/src/truncation-check.js +1 -0
- package/dist/node_modules/@dalcode/dal-workflow/src/working-contract.js +1 -1
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@dalcode/deepailab/src/index.js +3 -3
- package/dist/node_modules/@earendil-works/pi-agent-core/README.md +5 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts +2 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent.d.ts +3 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent.js +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/branch-summarization.js +37 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/compaction.js +104 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/utils.js +16 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/config.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/context.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.js +10 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/events.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/assistant.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/effect-gate.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/tools.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/hooks.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/messages.js +17 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/bash.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/bounded.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/chord.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/context.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/harness.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/hooks.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/index.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/jsonl.js +4 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/collapse.js +3 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/entries.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/frames.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/generation.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/job.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/plugin.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/post-tools.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/task-api.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/tool.js +3 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/membrane.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/memory.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/scheduler.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/session.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/system.js +8 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/types.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/view.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/prompt-templates.js +5 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/reducer.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/result.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/boundary.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/checkpoint.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/deferred.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/generation.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/reconcile.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/recovery.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/response.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/retry.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/structural.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/terminal.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/tool-placement.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/tools.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/harness.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/index.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/lane.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/progress.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/reducer.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/restore.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/transcript.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/types.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/commit.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/context.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/fork-policy.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/fork.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/in-memory-storage-state.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/index.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/codec.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/errors.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/fork.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/index.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/io.js +3 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/legacy-v3.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/repo.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/storage.js +8 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/types.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl-repo.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl-storage.js +5 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory-repo.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory-storage.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/mutation-line.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/repo-utils.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/session.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/state.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/datasets.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/session-repo.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/storage.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance/session-repo.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance/storage.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/gating-storage.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/index.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/instrumented-storage.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/storage-decorator.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/types.js +0 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/types.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/values.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/skills.js +10 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/system-prompt.js +2 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/telemetry.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/bash.js +12 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit-diff.js +16 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/file-mutation-queue.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/image.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/path-utils.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/read.js +14 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.js +0 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/types.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/adaptive-publisher.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/output-capture.js +5 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/shell-output.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/truncate.js +5 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/usage.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/node.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/search/index.js +0 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/search/scanning.js +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts +2 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-ai/README.md +78 -3
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +5 -5
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/azure-openai-responses.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/bedrock-converse-stream.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/classifier-shared.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/cloudflare-gateway-binding.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/cloudflare-workers-ai-system-one.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/google-generative-ai.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/google-shared.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/google-vertex.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/lazy.d.ts +6 -2
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/lazy.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/llama-cpp-classify.js +5 -5
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js +2 -2
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js +6 -6
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +5 -5
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js +10 -5
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +3 -2
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/openrouter-images.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/pi-messages.js +4 -4
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/simple-options.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/system-one-shared.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/typesafe-system-one.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/auth/oauth/oauth-page.js +74 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/cli.js +0 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/images-models.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/index.d.ts +2 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/index.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/models.d.ts +4 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/models.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/azure-openai-responses.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/azure-openai-responses.models.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/compat-schema.d.ts +180 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/compat-schema.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax-cn.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openai-codex.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/typesafe.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/model-schema.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/openrouter-images.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/telemetry.d.ts +286 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/telemetry.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/types.d.ts +20 -4
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/assistant-message-frame.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/deferred-tools.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/event-stream.d.ts +4 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/event-stream.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/identity.d.ts +27 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/identity.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/provider-retry.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/transcript.d.ts +3 -2
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/transcript.js +2 -2
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.d.ts +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/CHANGELOG.md +2 -0
- package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-telemetry/README.md +167 -21
- package/dist/node_modules/@earendil-works/pi-telemetry/dist/index.d.ts +77 -2
- package/dist/node_modules/@earendil-works/pi-telemetry/dist/index.js +1 -1
- package/dist/node_modules/@earendil-works/pi-telemetry/dist/memory.d.ts +35 -2
- package/dist/node_modules/@earendil-works/pi-telemetry/dist/memory.js +1 -1
- package/dist/node_modules/@earendil-works/pi-telemetry/dist/metrics.d.ts +70 -0
- package/dist/node_modules/@earendil-works/pi-telemetry/dist/metrics.js +1 -0
- package/dist/node_modules/@earendil-works/pi-telemetry/dist/noop.d.ts +5 -2
- package/dist/node_modules/@earendil-works/pi-telemetry/dist/noop.js +1 -1
- package/dist/node_modules/@earendil-works/pi-telemetry/dist/render.js +2 -0
- package/dist/node_modules/@earendil-works/pi-telemetry/dist/testing/conformance.js +1 -1
- package/dist/node_modules/@earendil-works/pi-telemetry/package.json +6 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/autocomplete.js +2 -2
- package/dist/node_modules/@earendil-works/pi-tui/dist/components/markdown.js +8 -7
- package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.d.ts +3 -0
- package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/terminal-image.js +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts +3 -0
- package/dist/node_modules/@earendil-works/pi-tui/dist/terminal.js +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.d.ts +2 -0
- package/dist/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js +4 -4
- package/dist/node_modules/@earendil-works/pi-tui/dist/tui.d.ts +3 -0
- package/dist/node_modules/@earendil-works/pi-tui/dist/tui.js +2 -2
- package/dist/node_modules/@earendil-works/pi-tui/package.json +3 -2
- package/dist/package-manager-cli.js +9 -9
- package/dist/sdk/office.d.ts +1 -1
- package/dist/sdk/office.js +1 -1
- package/dist/sdk/router.d.ts +4 -4
- package/dist/sdk/router.js +1 -1
- package/dist/server/create-harness.js +1 -0
- package/dist/utils/clipboard-command.js +1 -1
- package/dist/utils/clipboard-native.js +1 -0
- package/dist/utils/pi-user-agent.js +1 -1
- package/dist/utils/shell.js +2 -2
- package/dist/utils/tools-manager.js +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +15 -2
- package/package.json +6 -2
- package/dist/node_modules/@dalcode/dal-guard/src/review.js +0 -3
- package/dist/node_modules/@dalcode/dal-office/src/scenes.js +0 -1
- package/dist/node_modules/@dalcode/dal-plugins/src/rank.js +0 -4
- package/dist/node_modules/@dalcode/dal-router/src/assist.js +0 -4
- package/dist/node_modules/@dalcode/dal-router/src/compact-defer.js +0 -3
- package/dist/node_modules/@dalcode/dal-router/src/jev.d.ts +0 -52
- package/dist/node_modules/@dalcode/dal-router/src/jev.js +0 -5
- package/dist/node_modules/@dalcode/dal-router/src/router.d.ts +0 -32
- package/dist/node_modules/@dalcode/dal-router/src/router.js +0 -1
- package/dist/node_modules/@dalcode/dal-router/src/services.js +0 -1
- package/dist/node_modules/@dalcode/dal-subagent/src/role-pick.js +0 -2
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var L=Object.defineProperty;var
|
|
1
|
+
var L=Object.defineProperty;var c=(i,t)=>L(i,"name",{value:t,configurable:!0});import{readFile as j}from"node:fs/promises";import{ProviderCompatSchema as d}from"@earendil-works/pi-ai/providers/compat-schema";import{ModelCostSchema as O,ModelInputLimitsSchema as u,ModelInputModalitySchema as v,ModelPromptCacheSchema as f,ThinkingLevelMapSchema as S}from"@earendil-works/pi-ai/providers/model-schema";import{Type as e}from"typebox";import{Compile as A}from"typebox/compile";import{stripJsonComments as I}from"../utils/json.js";import{normalizePath as $}from"../utils/paths.js";import{stripBom as F}from"../utils/text.js";const s=e.Record(e.String(),e.Unknown()),P=e.Object({off:e.Optional(s),minimal:e.Optional(s),low:e.Optional(s),medium:e.Optional(s),high:e.Optional(s),xhigh:e.Optional(s),max:e.Optional(s)},{description:"samplingParams per thinking level, merged over samplingParams."}),w=e.Record(e.String(),e.Unknown(),{description:"Fields merged into every request body. Applies only to OpenAI-compatible APIs."}),h=e.Record(e.String(),e.String(),{description:"Request headers. Values resolve like apiKey."}),o={name:"Display name, also matched by --model patterns.",reasoning:"Whether the model supports thinking.",contextWindow:"Context window in tokens.",maxTokens:"Maximum output tokens."},y=e.Object({id:e.String({minLength:1,description:"Model ID sent to the API."}),name:e.Optional(e.String({minLength:1,description:o.name})),api:e.Optional(e.String({minLength:1,description:"Overrides the provider api."})),baseUrl:e.Optional(e.String({minLength:1,description:"Overrides the provider baseUrl."})),reasoning:e.Optional(e.Boolean({default:!1,description:o.reasoning})),thinkingLevelMap:e.Optional(S),input:e.Optional(e.Array(v,{default:["text"]})),inputLimits:e.Optional(u),cost:e.Optional(O),promptCache:e.Optional(f),contextWindow:e.Optional(e.Number({exclusiveMinimum:0,default:128e3,description:o.contextWindow})),maxTokens:e.Optional(e.Number({exclusiveMinimum:0,default:16384,description:o.maxTokens})),samplingParams:e.Optional(w),samplingParamsByThinkingLevel:e.Optional(P),headers:e.Optional(h),compat:e.Optional(d)}),b=e.Object({name:e.Optional(e.String({minLength:1,description:o.name})),reasoning:e.Optional(e.Boolean({description:o.reasoning})),thinkingLevelMap:e.Optional(S),input:e.Optional(e.Array(v)),inputLimits:e.Optional(u),cost:e.Optional(e.Partial(O)),promptCache:e.Optional(f),contextWindow:e.Optional(e.Number({exclusiveMinimum:0,description:o.contextWindow})),maxTokens:e.Optional(e.Number({exclusiveMinimum:0,description:o.maxTokens})),samplingParams:e.Optional(w),samplingParamsByThinkingLevel:e.Optional(P),headers:e.Optional(h),compat:e.Optional(d)}),k=e.Object({name:e.Optional(e.String({minLength:1,description:"Display name."})),baseUrl:e.Optional(e.String({minLength:1,description:"API base URL. Also applies to the provider's built-in models."})),apiKey:e.Optional(e.String({minLength:1,description:'Literal key, "$NAME" environment interpolation, or "!command" output.'})),api:e.Optional(e.String({minLength:1,description:`API for the provider's models, such as "openai-completions", "openai-responses", "anthropic-messages", or "google-generative-ai".`})),oauth:e.Optional(e.Literal("radius",{description:"OAuth login flow. Requires baseUrl."})),headers:e.Optional(h),compat:e.Optional(d),authHeader:e.Optional(e.Boolean({default:!1,description:"Whether to send the resolved API key as Authorization: Bearer."})),models:e.Optional(e.Array(y)),modelOverrides:e.Optional(e.Record(e.String(),b))}),T={providers:e.Record(e.String(),k)},C=e.Object({$schema:e.Optional(e.String()),...T}),J={provider:k,model:y,modelOverride:b},M=A(C);function q(i){if(i.keyword==="required"){const l=i.params.requiredProperties?.[0];if(l){const a=i.instancePath.replace(/^\//,"").replace(/\//g,".");return a?`${a}.${l}`:l}}return i.instancePath.replace(/^\//,"").replace(/\//g,".")||"root"}c(q,"formatValidationPath");function x(i){if(typeof i!="object"||i===null||Object.isFrozen(i))return i;for(const t of Object.values(i))x(t);return Object.freeze(i)}c(x,"deepFreeze");class p{static{c(this,"ModelConfig")}providers;error;constructor(t,r){this.providers=t,this.error=r}static async load(t){if(!t)return new p(new Map);const r=$(t);let l;try{l=await j(r,"utf-8")}catch(n){return n.code==="ENOENT"?new p(new Map):new p(new Map,`Failed to load models.json: ${n instanceof Error?n.message:n}
|
|
2
2
|
|
|
3
|
-
File: ${
|
|
3
|
+
File: ${r}`)}let a;try{a=JSON.parse(I(F(l)))}catch(n){return new p(new Map,`Failed to parse models.json: ${n instanceof Error?n.message:n}
|
|
4
4
|
|
|
5
|
-
File: ${
|
|
5
|
+
File: ${r}`)}if(!M.Check(a)){const n=M.Errors(a).map(m=>` - ${q(m)}: ${m.message}`).join(`
|
|
6
6
|
`)||"Unknown schema error";return new p(new Map,`Invalid models.json schema:
|
|
7
|
-
${
|
|
7
|
+
${n}
|
|
8
8
|
|
|
9
|
-
File: ${
|
|
9
|
+
File: ${r}`)}const g=new Map;for(const[n,m]of Object.entries(a.providers))g.set(n,x(structuredClone(m)));return new p(g)}getProvider(t){return this.providers.get(t)}getProviderIds(){return[...this.providers.keys()]}getError(){return this.error}}export{p as ModelConfig,C as ModelsConfigSchema,J as ModelsJsonSchemas};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var c=Object.defineProperty;var o=(t,e)=>c(t,"name",{value:e,configurable:!0});const r="model_identity";function u(t,e){return t.id==="auto"||t.id.endsWith("/auto")||e!==void 0}o(u,"isRouterModel");function d(t,e){for(let s=t.length-1;s>=0;s--){const n=t[s];if(n?.role==="assistant"&&!(n.provider!==e.provider||n.model!==e.id)&&n.responseModel&&n.responseModel!==e.id)return n.responseModel}}o(d,"latestResponseModel");function p(t,e){const s=t[0];if(!s||s.role!=="system"||!s.sections)return t;const n=e.name&&e.name!==e.id?`${e.name} (${e.provider}/${e.id})`:`${e.provider}/${e.id}`,i=d(t,e),a=u(e,i)?i?`This conversation uses ${n}: the DAL gateway picks the concrete model for each request, and only the response says which. The previous reply was answered by ${e.provider}/${i}; this one most likely is too, but that is not certain. If the user asks which model you are, say exactly that.`:`This conversation uses ${n}: the DAL gateway picks the concrete model for each request, and only the response says which, so you do not know which model you are. If the user asks, say so; do not guess a name.`:`This reply is generated by the model ${n}, running inside DAL (by DeepAILab). If the user asks which model you are, answer with this name.`,h=[`<${r}>`,`${a} You were not told your training-data cutoff: if asked, say you are not sure instead of naming a date.`,`</${r}>`].join(`
|
|
2
|
+
`);return[{...s,sections:{...s.sections,[r]:h}},...t.slice(1)]}o(p,"withModelIdentity");export{r as MODEL_IDENTITY_SECTION,p as withModelIdentity};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var I=Object.defineProperty;var c=(e,o)=>I(e,"name",{value:o,configurable:!0});import{modelsAreEqual as F}from"@earendil-works/pi-ai";import x from"chalk";import{minimatch as $}from"minimatch";import{isValidThinkingLevel as E}from"../cli/args.js";import{fill as h,t as g}from"../dal/i18n.js";import{DEFAULT_THINKING_LEVEL as b}from"./defaults.js";const w={"amazon-bedrock":"us.anthropic.claude-opus-4-6-v1","ant-ling":"Ring-2.6-1T",anthropic:"claude-opus-4-8",openai:"gpt-5.5",azure:"gpt-5.4","openai-codex":"gpt-6.1-sol",radius:"balanced",nvidia:"nvidia/nemotron-3-ultra-550b-a55b",deepseek:"deepseek-v4-pro",google:"gemini-3.1-pro-preview","google-vertex":"gemini-3.1-pro-preview","github-copilot":"gpt-5.4",openrouter:"moonshotai/kimi-k2.6","vercel-ai-gateway":"zai/glm-5.1",xai:"grok-4.7",groq:"openai/gpt-oss-120b",cerebras:"gpt-oss-120b",zai:"glm-5.3","zai-coding-cn":"glm-5.3",mistral:"devstral-medium-latest",minimax:"MiniMax-M2.7","minimax-cn":"MiniMax-M2.7",moonshotai:"kimi-k2.6","moonshotai-cn":"kimi-k2.6",huggingface:"moonshotai/Kimi-K2.6",fireworks:"accounts/fireworks/models/kimi-k3",together:"moonshotai/Kimi-K3",baseten:"zai-org/GLM-5.2",opencode:"kimi-k2.6","opencode-go":"kimi-k3","kimi-coding":"kimi-for-coding",meta:"muse-spark-1.3","cloudflare-workers-ai":"@cf/moonshotai/kimi-k2.6","cloudflare-ai-gateway":"claude-sonnet-5","qwen-token-plan":"qwen3.7-max","qwen-token-plan-cn":"qwen3.7-max","qwen-token-plan-individual":"qwen3.8-max",xiaomi:"mimo-v2.5-pro","xiaomi-token-plan-cn":"mimo-v2.5-pro","xiaomi-token-plan-ams":"mimo-v2.5-pro","xiaomi-token-plan-sgp":"mimo-v2.5-pro"},O={};function P(e){return O[e]??w[e]}c(P,"preferredModelIdForProvider");function X(e){return!e||e.provider==="unknown"||e.id==="unknown"||e.api==="unknown"}c(X,"isPlaceholderModel");function Y(e,o){const i=o.filter(l=>l.provider===e),t=P(e);return(t?i.find(l=>l.id===t):void 0)??i[0]}c(Y,"pickDefaultModelForProvider");const D=/^deepseek-v4[.-]1-flash(?:-\d{6,8})?$/;function K(e){const o=e.filter(n=>n.provider==="deepailab"),i=o.find(n=>n.id==="deepseek-flash");if(i)return i;const t=o.filter(n=>D.test(n.id)).sort((n,r)=>r.id.localeCompare(n.id));if(t[0])return t[0];const l=c(n=>(n.cost?.input??0)+(n.cost?.output??0),"rate"),d=o.filter(n=>l(n)>0);return[...d.length>0?d:o].sort((n,r)=>l(n)-l(r)||n.id.localeCompare(r.id))[0]??e[0]}c(K,"pickHouseModel");function z(e){const o=e.lastIndexOf(":"),i=e.substring(o+1);if(!(o===-1||!E(i)))return{base:e.substring(0,o),thinkingLevel:i}}c(z,"splitThinkingSuffix");function y(e,o){const i=e.indexOf("/");if(i===-1)return;const t=e.substring(0,i).trim().toLowerCase(),l=e.substring(i+1).trim();if(!t||!l)return;const d=o.find(u=>u.provider.toLowerCase()===t)?.provider;return d?{provider:d,modelText:l}:void 0}c(y,"splitProviderPrefix");function L(e,o,i){const t=e.text.trim();if(!t)return{status:"not-found"};const l=e.provider?.toLowerCase(),d=l?o.filter(a=>a.provider.toLowerCase()===l):o,u=C(t,e,d,i);if(u.status!=="not-found")return u;const n=y(t,d),r=l?d[0]:d.find(a=>a.provider===n?.provider);if(!r)return u;const s=n?.modelText??t,f=e.thinkingSuffix==="none"?void 0:z(s);return{status:"not-found",target:{provider:r.provider,providerModels:[r,...d.filter(a=>a.provider===r.provider&&a!==r)],modelText:s,modelId:f?.base??s,thinkingLevel:f?.thinkingLevel}}}c(L,"resolveModelReference");function Z(e,o){const i=L({text:e,thinkingSuffix:"none",fuzzy:!1},o,()=>!0);return i.status==="resolved"?i.model:void 0}c(Z,"findExactModelReferenceMatch");function C(e,o,i,t){const l=j(e,i,o.fuzzy,t);if(l)return l;if(o.fuzzy){const s=U(T(e,i),t);if(s)return s}if(o.thinkingSuffix==="none")return{status:"not-found"};const d=z(e);if(d){const s=C(d.base,o,i,t);return s.status==="not-found"?s:{...s,thinkingLevel:s.warning?void 0:d.thinkingLevel}}if(o.thinkingSuffix==="strict")return{status:"not-found"};const u=e.lastIndexOf(":");if(u===-1)return{status:"not-found"};const n=e.substring(u+1),r=C(e.substring(0,u),o,i,t);return r.status==="not-found"?r:{...r,thinkingLevel:void 0,warning:h(g("\u6A21\u578B\u300C{pattern}\u300D\u91CC\u7684\u601D\u8003\u6DF1\u5EA6\u300C{level}\u300D\u65E0\u6548\uFF0C\u5C06\u4F7F\u7528\u9ED8\u8BA4\u503C\u3002"),{level:n,pattern:e})}}c(C,"resolveText");function j(e,o,i,t){const l=e.toLowerCase(),d=o.filter(a=>a.id.toLowerCase()===l),u=y(e,o);let n;if(u){const a=o.filter(m=>m.provider===u.provider),p=u.modelText.toLowerCase();n=a.find(m=>m.id.toLowerCase()===p)??d.find(m=>m.provider===u.provider)??(i?S(T(u.modelText,a)):void 0)}const r=d.filter(a=>a!==n),s=n?[n,...r]:r;if(s.length===0)return;if(new Set(s.map(a=>a.provider)).size===1)return{status:"resolved",model:s[0]};if(n&&t(n.provider))return{status:"resolved",model:n};const f=r.filter(a=>t(a.provider));return f.length===1?{status:"resolved",model:f[0]}:f.length===0&&n?{status:"resolved",model:n}:{status:"ambiguous",candidates:s,usableCount:f.length}}c(j,"selectReference");function T(e,o){const i=e.toLowerCase();return o.filter(t=>t.id.toLowerCase().includes(i)||t.name?.toLowerCase().includes(i))}c(T,"fuzzyMatches");function U(e,o){if(e.length===0)return;const t=new Set(e.map(n=>n.provider)).size>1?e.filter(n=>o(n.provider)):[],l=t.length>0?t:e,d=S(l);if(!d)return;const u=l.filter(n=>n.id===d.id);return new Set(u.map(n=>n.provider)).size===1?{status:"resolved",model:d}:{status:"ambiguous",candidates:u,usableCount:t.length>0?u.length:0}}c(U,"selectFuzzy");function S(e){const o=e.filter(i=>H(i.id));return[...o.length>0?o:e].sort((i,t)=>t.id.localeCompare(i.id))[0]}c(S,"bestFuzzyMatch");function H(e){return e.endsWith("-latest")||!/-\d{8}$/.test(e)}c(H,"isAlias");function R(e,o){const i=w[e[0].provider];return{...i?e.find(l=>l.id===i)??e[0]:e[0],id:o,name:o}}c(R,"buildFallbackModel");function _(e,o){const i=[],t=[],l=c((n,r)=>{i.some(s=>F(s.model,n))||i.push({model:n,thinkingLevel:r})},"add"),d=c(n=>t.push({type:"warning",code:"no-match",message:h(g("\u6CA1\u6709\u6A21\u578B\u5339\u914D\u300C{pattern}\u300D"),{pattern:n}),pattern:n}),"noMatch"),u=c((n,r)=>{const s=[...new Set(r.map(f=>f.provider))].sort((f,a)=>f.localeCompare(a));t.push({type:"warning",code:"ambiguous",message:h(g("\u300C{pattern}\u300D\u5339\u914D\u5230\u591A\u4E2A\u63D0\u4F9B\u65B9\uFF1A{providers}\u3002\u8BF7\u7528 provider/id \u6307\u5B9A\u5176\u4E2D\u4E00\u4E2A\u3002"),{pattern:n,providers:s.join(", ")}),pattern:n})},"ambiguous");for(const n of e){if(n.includes("*")||n.includes("?")||n.includes("[")){const f=z(n),a=f?.base??n,p=f?.thinkingLevel,m=L({text:a,thinkingSuffix:"none",fuzzy:!1},o,()=>!0);let v=[];m.status==="resolved"?v=[m.model]:m.status==="ambiguous"?(v=m.candidates,u(n,v)):v=o.filter(k=>$(`${k.provider}/${k.id}`,a,{nocase:!0})||$(k.id,a,{nocase:!0})),v.length===0&&d(n);for(const k of v)l(k,p);continue}const r=L({text:n,thinkingSuffix:"lenient",fuzzy:!0},o,()=>!0);if(r.status==="not-found"){d(n);continue}r.warning&&t.push({type:"warning",code:"invalid-thinking-level",message:r.warning,pattern:n}),r.status==="ambiguous"&&u(n,r.candidates);const s=r.status==="resolved"?[r.model]:r.candidates;for(const f of s)l(f,r.thinkingLevel)}return{scopedModels:i,diagnostics:t}}c(_,"resolveModelScopeFromModels");async function G(e,o,i){return _(e,await o.getAvailable(void 0,i))}c(G,"resolveModelScopeWithDiagnostics");async function ee(e,o,i){const{scopedModels:t,diagnostics:l}=await G(e,o,i);for(const d of l)console.warn(x.yellow(h(g("\u8B66\u544A\uFF1A{message}"),{message:d.message})));return t}c(ee,"resolveModelScope");function ne(e){const{cliProvider:o,cliModel:i,cliThinking:t,inlineApiKey:l,modelRuntime:d}=e;if(!i)return{model:void 0,warning:void 0,error:void 0};const u=[...d.getModels()];if(u.length===0)return{model:void 0,warning:void 0,error:g("\u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B\u3002\u8BF7\u68C0\u67E5\u5B89\u88C5\uFF0C\u6216\u5728 models.json \u91CC\u6DFB\u52A0\u6A21\u578B\u3002")};const n=o?u.find(v=>v.provider.toLowerCase()===o.toLowerCase())?.provider:void 0;if(o&&!n)return{model:void 0,warning:void 0,error:h(g("\u672A\u77E5\u7684\u63D0\u4F9B\u65B9\u300C{provider}\u300D\u3002\u53EF\u7528 --list-models \u67E5\u770B\u6709\u54EA\u4E9B\u63D0\u4F9B\u65B9\u548C\u6A21\u578B\u3002"),{provider:o})};const r=L({text:i,provider:n,thinkingSuffix:"strict",fuzzy:!0},u,l?()=>!1:v=>d.hasConfiguredAuth(v));if(r.status==="resolved")return{model:r.model,thinkingLevel:r.thinkingLevel,warning:r.warning,error:void 0};if(r.status==="ambiguous"){const v=r.candidates.map(M=>`${M.provider}/${M.id}`).sort((M,A)=>M.localeCompare(A)).join(", "),k=l?g("--api-key \u4E0D\u80FD\u7528\u6765\u9009\u62E9\u63D0\u4F9B\u65B9\u3002"):r.usableCount===0?g("\u5339\u914D\u7684\u63D0\u4F9B\u65B9\u90FD\u8FD8\u6CA1\u6709\u767B\u5F55\u3002"):g("\u6709\u4E0D\u6B62\u4E00\u4E2A\u5339\u914D\u7684\u63D0\u4F9B\u65B9\u5DF2\u7ECF\u767B\u5F55\u3002");return{model:void 0,warning:void 0,error:h(g("\u6A21\u578B\u300C{model}\u300D\u5728\u591A\u4E2A\u63D0\u4F9B\u65B9\u4E2D\u90FD\u6709\uFF1A{matches}\u3002{hint}\u8BF7\u7528 --provider \u6216 provider/model \u6307\u5B9A\u3002"),{model:i,matches:v,hint:k})}}const{target:s}=r;if(!s)return{model:void 0,warning:void 0,error:h(g("\u627E\u4E0D\u5230\u6A21\u578B\u300C{model}\u300D\u3002\u53EF\u7528 --list-models \u67E5\u770B\u6709\u54EA\u4E9B\u6A21\u578B\u3002"),{model:i})};const f=t?s.modelText:s.modelId,a=t?void 0:s.thinkingLevel,p=R(s.providerModels,f),m=t??a;return{model:m&&m!=="off"?{...p,reasoning:!0}:p,thinkingLevel:a,warning:h(g("\u63D0\u4F9B\u65B9\u300C{provider}\u300D\u91CC\u6CA1\u6709\u6A21\u578B\u300C{model}\u300D\uFF0C\u6309\u81EA\u5B9A\u4E49\u6A21\u578B id \u4F7F\u7528\u3002"),{model:f,provider:s.provider}),error:void 0}}c(ne,"resolveCliModel");async function oe(e){const{scopedModels:o,isContinuing:i,defaultProvider:t,defaultModelId:l,defaultThinkingLevel:d,modelThinkingLevels:u,modelRuntime:n}=e;let r,s=b;if(o.length>0&&!i){const a=o[0],p=u?.[`${a.model.provider}/${a.model.id}`];return{model:a.model,thinkingLevel:a.thinkingLevel??p??d??b,fallbackMessage:void 0}}if(t&&l){const a=n.getModel(t,l);if(a&&n.hasConfiguredAuth(a.provider)){r=a;const p=u?.[`${t}/${l}`];return p?s=p:d&&(s=d),{model:r,thinkingLevel:s,fallbackMessage:void 0}}}const f=[...n.getAvailableSnapshot()];if(f.length>0){const a=f.some(p=>p.provider==="deepailab")?K(f):void 0;if(a)return{model:a,thinkingLevel:b,fallbackMessage:void 0};if(n.getProviderAuthStatus("deepailab").configured)return{model:void 0,thinkingLevel:b,fallbackMessage:void 0};for(const p of Object.keys(w)){const m=w[p],v=f.find(k=>k.provider===p&&k.id===m);if(v)return{model:v,thinkingLevel:b,fallbackMessage:void 0}}return{model:f[0],thinkingLevel:b,fallbackMessage:void 0}}return{model:void 0,thinkingLevel:b,fallbackMessage:void 0}}c(oe,"findInitialModel");async function ie(e,o,i,t,l){const d=l.getModel(e,o),u=d?l.hasConfiguredAuth(d.provider):!1;if(d&&u)return t&&console.log(x.dim(h(g("\u5DF2\u6062\u590D\u6A21\u578B\uFF1A{model}"),{model:`${e}/${o}`}))),{model:d,fallbackMessage:void 0};const n=d?"no auth configured":"model no longer exists";if(t&&console.error(x.yellow(h(d?g("\u8B66\u544A\uFF1A\u65E0\u6CD5\u6062\u590D\u6A21\u578B {model}\uFF08\u6CA1\u6709\u914D\u7F6E\u767B\u5F55\uFF09\u3002"):g("\u8B66\u544A\uFF1A\u65E0\u6CD5\u6062\u590D\u6A21\u578B {model}\uFF08\u8BE5\u6A21\u578B\u5DF2\u4E0D\u5B58\u5728\uFF09\u3002"),{model:`${e}/${o}`}))),i)return t&&console.log(x.dim(h(g("\u6539\u7528\uFF1A{model}"),{model:`${i.provider}/${i.id}`}))),{model:i,fallbackMessage:`Could not restore model ${e}/${o} (${n}). Using ${i.provider}/${i.id}.`};const r=[...l.getAvailableSnapshot()];if(r.length>0){let s;for(const f of Object.keys(w)){const a=w[f],p=r.find(m=>m.provider===f&&m.id===a);if(p){s=p;break}}return s||(s=r[0]),t&&console.log(x.dim(h(g("\u6539\u7528\uFF1A{model}"),{model:`${s.provider}/${s.id}`}))),{model:s,fallbackMessage:`Could not restore model ${e}/${o} (${n}). Using ${s.provider}/${s.id}.`}}return{model:void 0,fallbackMessage:void 0}}c(ie,"restoreModelFromSession");export{w as defaultModelPerProvider,O as extensionDefaultModelPerProvider,Z as findExactModelReferenceMatch,oe as findInitialModel,X as isPlaceholderModel,Y as pickDefaultModelForProvider,K as pickHouseModel,P as preferredModelIdForProvider,ne as resolveCliModel,L as resolveModelReference,ee as resolveModelScope,_ as resolveModelScopeFromModels,G as resolveModelScopeWithDiagnostics,ie as restoreModelFromSession};
|
|
1
|
+
var I=Object.defineProperty;var c=(e,o)=>I(e,"name",{value:o,configurable:!0});import{modelsAreEqual as F}from"@earendil-works/pi-ai";import x from"chalk";import{minimatch as $}from"minimatch";import{isValidThinkingLevel as E}from"../cli/args.js";import{fill as h,t as g}from"../dal/i18n.js";import{DEFAULT_THINKING_LEVEL as b}from"./defaults.js";const w={"amazon-bedrock":"us.anthropic.claude-opus-4-6-v1","ant-ling":"Ring-2.6-1T",anthropic:"claude-opus-4-8",openai:"gpt-5.5",azure:"gpt-5.4","openai-codex":"gpt-6.1-sol",radius:"balanced",nvidia:"nvidia/nemotron-3.5-super-vl-120b-a12b",deepseek:"deepseek-v4-pro",google:"gemini-3.1-pro-preview","google-vertex":"gemini-3.1-pro-preview","github-copilot":"gpt-6.1-sol",openrouter:"moonshotai/kimi-k2.6","vercel-ai-gateway":"zai/glm-5.1",xai:"grok-4.7",groq:"openai/gpt-oss-120b",cerebras:"gpt-oss-120b",zai:"glm-5.3","zai-coding-cn":"glm-5.3",mistral:"devstral-medium-latest",minimax:"MiniMax-M2.7","minimax-cn":"MiniMax-M2.7",moonshotai:"kimi-k2.6","moonshotai-cn":"kimi-k2.6",huggingface:"moonshotai/Kimi-K2.6",fireworks:"accounts/fireworks/models/kimi-k3",together:"moonshotai/Kimi-K3",baseten:"zai-org/GLM-5.2",opencode:"kimi-k2.6","opencode-go":"kimi-k3","kimi-coding":"kimi-for-coding",meta:"muse-spark-1.3","cloudflare-workers-ai":"@cf/moonshotai/kimi-k2.6","cloudflare-ai-gateway":"claude-sonnet-5","qwen-token-plan":"qwen3.7-max","qwen-token-plan-cn":"qwen3.7-max","qwen-token-plan-individual":"qwen3.8-max",xiaomi:"mimo-v2.6-pro","xiaomi-token-plan-cn":"mimo-v2.6-pro","xiaomi-token-plan-ams":"mimo-v2.6-pro","xiaomi-token-plan-sgp":"mimo-v2.6-pro"},O={};function P(e){return O[e]??w[e]}c(P,"preferredModelIdForProvider");function X(e){return!e||e.provider==="unknown"||e.id==="unknown"||e.api==="unknown"}c(X,"isPlaceholderModel");function Y(e,o){const i=o.filter(l=>l.provider===e),t=P(e);return(t?i.find(l=>l.id===t):void 0)??i[0]}c(Y,"pickDefaultModelForProvider");const D=/^deepseek-v4[.-]1-flash(?:-\d{6,8})?$/;function K(e){const o=e.filter(n=>n.provider==="deepailab"),i=o.find(n=>n.id==="deepseek-flash");if(i)return i;const t=o.filter(n=>D.test(n.id)).sort((n,r)=>r.id.localeCompare(n.id));if(t[0])return t[0];const l=c(n=>(n.cost?.input??0)+(n.cost?.output??0),"rate"),d=o.filter(n=>l(n)>0);return[...d.length>0?d:o].sort((n,r)=>l(n)-l(r)||n.id.localeCompare(r.id))[0]??e[0]}c(K,"pickHouseModel");function z(e){const o=e.lastIndexOf(":"),i=e.substring(o+1);if(!(o===-1||!E(i)))return{base:e.substring(0,o),thinkingLevel:i}}c(z,"splitThinkingSuffix");function y(e,o){const i=e.indexOf("/");if(i===-1)return;const t=e.substring(0,i).trim().toLowerCase(),l=e.substring(i+1).trim();if(!t||!l)return;const d=o.find(u=>u.provider.toLowerCase()===t)?.provider;return d?{provider:d,modelText:l}:void 0}c(y,"splitProviderPrefix");function L(e,o,i){const t=e.text.trim();if(!t)return{status:"not-found"};const l=e.provider?.toLowerCase(),d=l?o.filter(a=>a.provider.toLowerCase()===l):o,u=C(t,e,d,i);if(u.status!=="not-found")return u;const n=y(t,d),r=l?d[0]:d.find(a=>a.provider===n?.provider);if(!r)return u;const s=n?.modelText??t,f=e.thinkingSuffix==="none"?void 0:z(s);return{status:"not-found",target:{provider:r.provider,providerModels:[r,...d.filter(a=>a.provider===r.provider&&a!==r)],modelText:s,modelId:f?.base??s,thinkingLevel:f?.thinkingLevel}}}c(L,"resolveModelReference");function Z(e,o){const i=L({text:e,thinkingSuffix:"none",fuzzy:!1},o,()=>!0);return i.status==="resolved"?i.model:void 0}c(Z,"findExactModelReferenceMatch");function C(e,o,i,t){const l=j(e,i,o.fuzzy,t);if(l)return l;if(o.fuzzy){const s=U(T(e,i),t);if(s)return s}if(o.thinkingSuffix==="none")return{status:"not-found"};const d=z(e);if(d){const s=C(d.base,o,i,t);return s.status==="not-found"?s:{...s,thinkingLevel:s.warning?void 0:d.thinkingLevel}}if(o.thinkingSuffix==="strict")return{status:"not-found"};const u=e.lastIndexOf(":");if(u===-1)return{status:"not-found"};const n=e.substring(u+1),r=C(e.substring(0,u),o,i,t);return r.status==="not-found"?r:{...r,thinkingLevel:void 0,warning:h(g("\u6A21\u578B\u300C{pattern}\u300D\u91CC\u7684\u601D\u8003\u6DF1\u5EA6\u300C{level}\u300D\u65E0\u6548\uFF0C\u5C06\u4F7F\u7528\u9ED8\u8BA4\u503C\u3002"),{level:n,pattern:e})}}c(C,"resolveText");function j(e,o,i,t){const l=e.toLowerCase(),d=o.filter(a=>a.id.toLowerCase()===l),u=y(e,o);let n;if(u){const a=o.filter(m=>m.provider===u.provider),p=u.modelText.toLowerCase();n=a.find(m=>m.id.toLowerCase()===p)??d.find(m=>m.provider===u.provider)??(i?S(T(u.modelText,a)):void 0)}const r=d.filter(a=>a!==n),s=n?[n,...r]:r;if(s.length===0)return;if(new Set(s.map(a=>a.provider)).size===1)return{status:"resolved",model:s[0]};if(n&&t(n.provider))return{status:"resolved",model:n};const f=r.filter(a=>t(a.provider));return f.length===1?{status:"resolved",model:f[0]}:f.length===0&&n?{status:"resolved",model:n}:{status:"ambiguous",candidates:s,usableCount:f.length}}c(j,"selectReference");function T(e,o){const i=e.toLowerCase();return o.filter(t=>t.id.toLowerCase().includes(i)||t.name?.toLowerCase().includes(i))}c(T,"fuzzyMatches");function U(e,o){if(e.length===0)return;const t=new Set(e.map(n=>n.provider)).size>1?e.filter(n=>o(n.provider)):[],l=t.length>0?t:e,d=S(l);if(!d)return;const u=l.filter(n=>n.id===d.id);return new Set(u.map(n=>n.provider)).size===1?{status:"resolved",model:d}:{status:"ambiguous",candidates:u,usableCount:t.length>0?u.length:0}}c(U,"selectFuzzy");function S(e){const o=e.filter(i=>H(i.id));return[...o.length>0?o:e].sort((i,t)=>t.id.localeCompare(i.id))[0]}c(S,"bestFuzzyMatch");function H(e){return e.endsWith("-latest")||!/-\d{8}$/.test(e)}c(H,"isAlias");function R(e,o){const i=w[e[0].provider];return{...i?e.find(l=>l.id===i)??e[0]:e[0],id:o,name:o}}c(R,"buildFallbackModel");function _(e,o){const i=[],t=[],l=c((n,r)=>{i.some(s=>F(s.model,n))||i.push({model:n,thinkingLevel:r})},"add"),d=c(n=>t.push({type:"warning",code:"no-match",message:h(g("\u6CA1\u6709\u6A21\u578B\u5339\u914D\u300C{pattern}\u300D"),{pattern:n}),pattern:n}),"noMatch"),u=c((n,r)=>{const s=[...new Set(r.map(f=>f.provider))].sort((f,a)=>f.localeCompare(a));t.push({type:"warning",code:"ambiguous",message:h(g("\u300C{pattern}\u300D\u5339\u914D\u5230\u591A\u4E2A\u63D0\u4F9B\u65B9\uFF1A{providers}\u3002\u8BF7\u7528 provider/id \u6307\u5B9A\u5176\u4E2D\u4E00\u4E2A\u3002"),{pattern:n,providers:s.join(", ")}),pattern:n})},"ambiguous");for(const n of e){if(n.includes("*")||n.includes("?")||n.includes("[")){const f=z(n),a=f?.base??n,p=f?.thinkingLevel,m=L({text:a,thinkingSuffix:"none",fuzzy:!1},o,()=>!0);let v=[];m.status==="resolved"?v=[m.model]:m.status==="ambiguous"?(v=m.candidates,u(n,v)):v=o.filter(k=>$(`${k.provider}/${k.id}`,a,{nocase:!0})||$(k.id,a,{nocase:!0})),v.length===0&&d(n);for(const k of v)l(k,p);continue}const r=L({text:n,thinkingSuffix:"lenient",fuzzy:!0},o,()=>!0);if(r.status==="not-found"){d(n);continue}r.warning&&t.push({type:"warning",code:"invalid-thinking-level",message:r.warning,pattern:n}),r.status==="ambiguous"&&u(n,r.candidates);const s=r.status==="resolved"?[r.model]:r.candidates;for(const f of s)l(f,r.thinkingLevel)}return{scopedModels:i,diagnostics:t}}c(_,"resolveModelScopeFromModels");async function G(e,o,i){return _(e,await o.getAvailable(void 0,i))}c(G,"resolveModelScopeWithDiagnostics");async function ee(e,o,i){const{scopedModels:t,diagnostics:l}=await G(e,o,i);for(const d of l)console.warn(x.yellow(h(g("\u8B66\u544A\uFF1A{message}"),{message:d.message})));return t}c(ee,"resolveModelScope");function ne(e){const{cliProvider:o,cliModel:i,cliThinking:t,inlineApiKey:l,modelRuntime:d}=e;if(!i)return{model:void 0,warning:void 0,error:void 0};const u=[...d.getModels()];if(u.length===0)return{model:void 0,warning:void 0,error:g("\u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B\u3002\u8BF7\u68C0\u67E5\u5B89\u88C5\uFF0C\u6216\u5728 models.json \u91CC\u6DFB\u52A0\u6A21\u578B\u3002")};const n=o?u.find(v=>v.provider.toLowerCase()===o.toLowerCase())?.provider:void 0;if(o&&!n)return{model:void 0,warning:void 0,error:h(g("\u672A\u77E5\u7684\u63D0\u4F9B\u65B9\u300C{provider}\u300D\u3002\u53EF\u7528 --list-models \u67E5\u770B\u6709\u54EA\u4E9B\u63D0\u4F9B\u65B9\u548C\u6A21\u578B\u3002"),{provider:o})};const r=L({text:i,provider:n,thinkingSuffix:"strict",fuzzy:!0},u,l?()=>!1:v=>d.hasConfiguredAuth(v));if(r.status==="resolved")return{model:r.model,thinkingLevel:r.thinkingLevel,warning:r.warning,error:void 0};if(r.status==="ambiguous"){const v=r.candidates.map(M=>`${M.provider}/${M.id}`).sort((M,A)=>M.localeCompare(A)).join(", "),k=l?g("--api-key \u4E0D\u80FD\u7528\u6765\u9009\u62E9\u63D0\u4F9B\u65B9\u3002"):r.usableCount===0?g("\u5339\u914D\u7684\u63D0\u4F9B\u65B9\u90FD\u8FD8\u6CA1\u6709\u767B\u5F55\u3002"):g("\u6709\u4E0D\u6B62\u4E00\u4E2A\u5339\u914D\u7684\u63D0\u4F9B\u65B9\u5DF2\u7ECF\u767B\u5F55\u3002");return{model:void 0,warning:void 0,error:h(g("\u6A21\u578B\u300C{model}\u300D\u5728\u591A\u4E2A\u63D0\u4F9B\u65B9\u4E2D\u90FD\u6709\uFF1A{matches}\u3002{hint}\u8BF7\u7528 --provider \u6216 provider/model \u6307\u5B9A\u3002"),{model:i,matches:v,hint:k})}}const{target:s}=r;if(!s)return{model:void 0,warning:void 0,error:h(g("\u627E\u4E0D\u5230\u6A21\u578B\u300C{model}\u300D\u3002\u53EF\u7528 --list-models \u67E5\u770B\u6709\u54EA\u4E9B\u6A21\u578B\u3002"),{model:i})};const f=t?s.modelText:s.modelId,a=t?void 0:s.thinkingLevel,p=R(s.providerModels,f),m=t??a;return{model:m&&m!=="off"?{...p,reasoning:!0}:p,thinkingLevel:a,warning:h(g("\u63D0\u4F9B\u65B9\u300C{provider}\u300D\u91CC\u6CA1\u6709\u6A21\u578B\u300C{model}\u300D\uFF0C\u6309\u81EA\u5B9A\u4E49\u6A21\u578B id \u4F7F\u7528\u3002"),{model:f,provider:s.provider}),error:void 0}}c(ne,"resolveCliModel");async function oe(e){const{scopedModels:o,isContinuing:i,defaultProvider:t,defaultModelId:l,defaultThinkingLevel:d,modelThinkingLevels:u,modelRuntime:n}=e;let r,s=b;if(o.length>0&&!i){const a=o[0],p=u?.[`${a.model.provider}/${a.model.id}`];return{model:a.model,thinkingLevel:a.thinkingLevel??p??d??b,fallbackMessage:void 0}}if(t&&l){const a=n.getModel(t,l);if(a&&n.hasConfiguredAuth(a.provider)){r=a;const p=u?.[`${t}/${l}`];return p?s=p:d&&(s=d),{model:r,thinkingLevel:s,fallbackMessage:void 0}}}const f=[...n.getAvailableSnapshot()];if(f.length>0){const a=f.some(p=>p.provider==="deepailab")?K(f):void 0;if(a)return{model:a,thinkingLevel:b,fallbackMessage:void 0};if(n.getProviderAuthStatus("deepailab").configured)return{model:void 0,thinkingLevel:b,fallbackMessage:void 0};for(const p of Object.keys(w)){const m=w[p],v=f.find(k=>k.provider===p&&k.id===m);if(v)return{model:v,thinkingLevel:b,fallbackMessage:void 0}}return{model:f[0],thinkingLevel:b,fallbackMessage:void 0}}return{model:void 0,thinkingLevel:b,fallbackMessage:void 0}}c(oe,"findInitialModel");async function ie(e,o,i,t,l){const d=l.getModel(e,o),u=d?l.hasConfiguredAuth(d.provider):!1;if(d&&u)return t&&console.log(x.dim(h(g("\u5DF2\u6062\u590D\u6A21\u578B\uFF1A{model}"),{model:`${e}/${o}`}))),{model:d,fallbackMessage:void 0};const n=d?"no auth configured":"model no longer exists";if(t&&console.error(x.yellow(h(d?g("\u8B66\u544A\uFF1A\u65E0\u6CD5\u6062\u590D\u6A21\u578B {model}\uFF08\u6CA1\u6709\u914D\u7F6E\u767B\u5F55\uFF09\u3002"):g("\u8B66\u544A\uFF1A\u65E0\u6CD5\u6062\u590D\u6A21\u578B {model}\uFF08\u8BE5\u6A21\u578B\u5DF2\u4E0D\u5B58\u5728\uFF09\u3002"),{model:`${e}/${o}`}))),i)return t&&console.log(x.dim(h(g("\u6539\u7528\uFF1A{model}"),{model:`${i.provider}/${i.id}`}))),{model:i,fallbackMessage:`Could not restore model ${e}/${o} (${n}). Using ${i.provider}/${i.id}.`};const r=[...l.getAvailableSnapshot()];if(r.length>0){let s;for(const f of Object.keys(w)){const a=w[f],p=r.find(m=>m.provider===f&&m.id===a);if(p){s=p;break}}return s||(s=r[0]),t&&console.log(x.dim(h(g("\u6539\u7528\uFF1A{model}"),{model:`${s.provider}/${s.id}`}))),{model:s,fallbackMessage:`Could not restore model ${e}/${o} (${n}). Using ${s.provider}/${s.id}.`}}return{model:void 0,fallbackMessage:void 0}}c(ie,"restoreModelFromSession");export{w as defaultModelPerProvider,O as extensionDefaultModelPerProvider,Z as findExactModelReferenceMatch,oe as findInitialModel,X as isPlaceholderModel,Y as pickDefaultModelForProvider,K as pickHouseModel,P as preferredModelIdForProvider,ne as resolveCliModel,L as resolveModelReference,ee as resolveModelScope,_ as resolveModelScopeFromModels,G as resolveModelScopeWithDiagnostics,ie as restoreModelFromSession};
|
|
@@ -38,6 +38,7 @@ export declare class ModelRuntime implements Models {
|
|
|
38
38
|
private readonly modelsPath;
|
|
39
39
|
private readonly modelsStore;
|
|
40
40
|
private readonly refreshesInFlight;
|
|
41
|
+
private readonly inPlaceRefreshesInFlight;
|
|
41
42
|
private compositionTail;
|
|
42
43
|
private readonly modelNetworkEnabled;
|
|
43
44
|
private config;
|
|
@@ -106,6 +107,7 @@ export declare class ModelRuntime implements Models {
|
|
|
106
107
|
providers: readonly string[];
|
|
107
108
|
signal?: AbortSignal;
|
|
108
109
|
}): Promise<ModelsRefreshResult>;
|
|
110
|
+
whenCatalogRefreshesSettle(signal?: AbortSignal): Promise<void>;
|
|
109
111
|
registerNativeProvider(provider: Provider): void;
|
|
110
112
|
private markProvisionallyConfigured;
|
|
111
113
|
registerProvider(providerId: string, config: ProviderConfigInput): void;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
1
|
+
var x=Object.defineProperty;var v=(g,e)=>x(g,"name",{value:e,configurable:!0});import{dirname as T,join as E}from"node:path";import{clampThinkingLevel as $,createModels as O,getOpenCodeSessionHeaders as N,lazyStream as w,ModelsError as m,normalizeContext as A,withFirstTokenTimeout as k}from"@earendil-works/pi-ai";import*as P from"@earendil-works/pi-ai/providers/all";import{personalizeOpenRouterCatalog as z}from"@earendil-works/pi-ai/providers/openrouter";import{assertChatModel as y,assertClassifierInputSupported as L,assertClassifierModel as F,assertImageModel as K,classifierErrorResult as D,imageErrorResult as U}from"@earendil-works/pi-ai/utils/model-operations";import{APP_NAME as q,getAgentDir as B}from"../config.js";import{operationSignal as p,raceWithAbortSignal as j}from"../utils/abort.js";import{isOfflineModeEnabled as V}from"../utils/offline.js";import{AuthStorage as H}from"./auth-storage.js";import{houseProvidersEnforced as _,isLoginProviderOffered as G,protectedHouseFieldsTouched as W}from"./house-providers.js";import{ModelConfig as C}from"./model-config.js";import{withModelIdentity as J}from"./model-identity.js";import{FileModelsStore as Q,InMemoryCodingAgentModelsStore as X}from"./models-store.js";import{composeModelProvider as Y,configuredRequestAuthStatus as b,resolveCompatibilityRequestConfig as Z,resolveConfiguredModelHeaders as I,validateExtensionProvider as ee}from"./provider-composer.js";import{getDefaultCatalogBaseUrl as te,withPersonalizedCatalog as ie,withRemoteCatalog as re}from"./remote-catalog-provider.js";import{RuntimeCredentials as se}from"./runtime-credentials.js";import{createVirtualModel as oe,findLatestResponse as ae,isVirtualModel as S,withVirtualModels as ne}from"./virtual-models.js";class le extends Error{static{v(this,"CredentialSynchronizationError")}providerId;operation;credential;constructor(e,t,i,r){super(`Credential ${t} committed for ${e}, but local synchronization failed`,r),this.name="CredentialSynchronizationError",this.providerId=e,this.operation=t,this.credential=i}}function M(g,e){if(!g&&!e)return;const t={...g};for(const[i,r]of Object.entries(e??{})){const s=i.toLowerCase();for(const o of Object.keys(t))o.toLowerCase()===s&&delete t[o];t[i]=r}return t}v(M,"mergeHeaders");function he(g,e=q){return e==="pi"||g!=="radius"}v(he,"isBuiltinProviderEnabled");class R{static{v(this,"ModelRuntime")}models;credentials;defaultBuiltins;builtins=new Map;nativeExtensionProviders=new Map;extensionProviders=new Map;virtualModels=new Map;compositionErrors=new Map;modelsPath;modelsStore;refreshesInFlight=new Set;inPlaceRefreshesInFlight=new Set;compositionTail=Promise.resolve();modelNetworkEnabled;config;snapshot={all:[],available:[],configuredProviders:new Set,storedProviders:new Set,auth:new Map};availabilityRefreshSeq=0;availabilityErrorSeq=0;providerAvailabilitySeq=new Map;availabilityError;credentialOperations=new Map;constructor(e,t,i,r,s,o){this.credentials=e,this.config=t,this.modelsPath=i,this.modelsStore=r,this.modelNetworkEnabled=o,this.defaultBuiltins=new Map(s.map(a=>[a.id,a]));for(const[a,n]of this.defaultBuiltins)this.builtins.set(a,n);this.models=O({credentials:e,modelsStore:r}),this.rebuildProviders()}static async create(e={}){const t=new se(e.credentials??H.create(e.authPath)),i=e.modelsPath===null?void 0:e.modelsPath??E(B(),"models.json"),r=await C.load(i),s=e.modelsStore??(i?new Q(e.modelsStorePath??E(T(i),"models-store.json")):new X),o=P.getBuiltinModelDataGeneratedAt(),a=e.catalogBaseUrl??te(),n=P.builtinProviders().filter(f=>he(f.id)).map(f=>f.id==="radius"?f:f.id==="openrouter"?ie(f,z,a,o):a===void 0?f:re(f,a,o)),d=new R(t,r,i,s,n,!V());d.configureRadiusProviders(),d.rebuildProviders();const l=d.modelNetworkEnabled&&e.allowModelNetwork===!0,h=l&&e.modelRefreshTimeoutMs!==void 0?new AbortController:void 0,c=h?setTimeout(()=>h.abort(),e.modelRefreshTimeoutMs):void 0,u=h?e.signal?AbortSignal.any([e.signal,h.signal]):h.signal:e.signal;try{e.refreshOnCreate!==!1&&await d.refresh({allowNetwork:l,signal:u})}finally{c&&clearTimeout(c)}return d}configureRadiusProviders(){this.builtins.clear();for(const[e,t]of this.defaultBuiltins)this.builtins.set(e,t);for(const e of this.config.getProviderIds()){const t=this.config.getProvider(e);t?.oauth!=="radius"||!t.baseUrl||this.builtins.set(e,P.radiusProvider({id:e,name:t.name??e,gateway:t.baseUrl.replace(/\/v1\/?$/u,"")}))}}providerIds(){return new Set([...this.builtins.keys(),...this.nativeExtensionProviders.keys(),...this.config.getProviderIds(),...this.extensionProviders.keys(),...this.virtualModels.keys()])}recomposeProvider(e){const t=this.composeProvider(e),i=[...this.virtualModels.get(e)?.values()??[]].map(r=>r.model);return i.length>0?this.models.setProvider(ne(e,t,i)):t?this.models.setProvider(t):this.models.deleteProvider(e),t}composeProvider(e){const t=this.nativeExtensionProviders.get(e)??this.builtins.get(e),i=this.extensionProviders.get(e);if(!this.config.getProvider(e)&&!i)return this.compositionErrors.delete(e),t;const r=W(e,t,this.config.getProvider(e)??i);if(r.length>0)return this.compositionErrors.set(e,`\u5DF2\u5FFD\u7565\u5BF9 ${e} \u7684 ${r.join(" / ")} \u8986\u76D6\uFF1A\u81EA\u5BB6\u7F51\u5173\u7684\u5730\u5740\u548C\u51ED\u636E\u4E0D\u53EF\u6539\u5199\u3002`),t;try{const s=Y(e,t,this.config,i,o=>{const a=this.extensionProviders.get(e);a&&this.extensionProviders.set(e,{...a,models:o})});return this.compositionErrors.delete(e),s}catch(s){return this.compositionErrors.set(e,s instanceof Error?s.message:String(s)),t}}rebuildProviders(){this.models.clearProviders(),this.compositionErrors.clear();for(const e of this.providerIds())this.recomposeProvider(e);this.updateModelSnapshot()}updateModelSnapshot(){const e=[...this.models.getModels()];this.snapshot={...this.snapshot,all:e,available:e.filter(t=>this.snapshot.configuredProviders.has(t.provider))}}async runAvailabilityRefresh(e,t,i){const r=this.models.getProviders(),[s,o,a]=await Promise.all([this.models.getAvailable(void 0,{signal:i}),Promise.all(r.map(async l=>[l.id,await this.models.checkAuth(l.id,{signal:i})])),this.credentials.list({signal:i})]);if(e!==this.availabilityRefreshSeq)return;const n=new Map(o),d=new Set(o.filter(l=>l[1]!==void 0).map(([l])=>l));this.snapshot={all:[...this.models.getModels()],available:[...s],configuredProviders:d,storedProviders:new Set(a.map(l=>l.providerId)),auth:n},t===this.availabilityErrorSeq&&(this.availabilityError=void 0)}queueAvailabilityRefresh(e){const t=++this.availabilityRefreshSeq;for(const[s,o]of this.providerAvailabilitySeq)this.providerAvailabilitySeq.set(s,o+1);const i=++this.availabilityErrorSeq,r=p(e);return this.runAvailabilityRefresh(t,i,r).catch(s=>{throw i===this.availabilityErrorSeq&&!r.aborted&&(this.availabilityError=s instanceof Error?s.message:String(s)),s})}async refreshProviderAvailability(e,t){++this.availabilityRefreshSeq;const i=(this.providerAvailabilitySeq.get(e)??0)+1;this.providerAvailabilitySeq.set(e,i);const r=++this.availabilityErrorSeq;try{const[s,o,a]=await Promise.all([this.models.getAvailable(e,{signal:t}),this.models.checkAuth(e,{signal:t}),this.credentials.read(e,{signal:t})]);if(t.throwIfAborted(),this.providerAvailabilitySeq.get(e)!==i)return;const n=new Set(this.snapshot.configuredProviders),d=new Set(this.snapshot.storedProviders),l=new Map(this.snapshot.auth);o?(n.add(e),l.set(e,o)):(n.delete(e),l.delete(e)),a?d.add(e):d.delete(e);const h=[...this.models.getModels()],c=new Map([...this.snapshot.available.filter(u=>u.provider!==e),...s].map(u=>[`${u.provider}\0${u.id}`,u]));this.snapshot={all:h,available:h.flatMap(u=>c.get(`${u.provider}\0${u.id}`)??[]),configuredProviders:n,storedProviders:d,auth:l},r===this.availabilityErrorSeq&&(this.availabilityError=void 0)}catch(s){throw this.providerAvailabilitySeq.get(e)===i&&r===this.availabilityErrorSeq&&!t.aborted&&(this.availabilityError=s instanceof Error?s.message:String(s)),s}}getProviders(){return this.models.getProviders()}getProvider(e){return this.models.getProvider(e)}getModels(e){return this.models.getModels(e)}getModel(e,t){return this.models.getModel(e,t)}async getPersistedCatalogCheckedAt(e,t){const i=await this.modelsStore.read(e,{signal:t});if(!(!i||i.models.length===0))return i.checkedAt??0}getModelsOfType(e,t){return this.models.getModelsOfType(e,t)}getModelOfType(e,t,i){return this.models.getModelOfType(e,t,i)}getAllModels(e){return this.models.getAllModels(e)}getAvailableOfType(e,t,i){return this.models.getAvailableOfType(e,t,i)}getAllAvailable(e,t){return this.models.getAllAvailable(e,t)}async checkAuth(e,t){return this.models.checkAuth(e,t)}async getAvailable(e,t){if(e){const i=++this.availabilityErrorSeq;try{const r=await this.models.getAvailable(e,t);return i===this.availabilityErrorSeq&&(this.availabilityError=void 0),r}catch(r){throw i===this.availabilityErrorSeq&&!t?.signal?.aborted&&(this.availabilityError=r instanceof Error?r.message:String(r)),r}}return await this.queueAvailabilityRefresh(t?.signal),this.snapshot.available}getAvailableSnapshot(){return this.snapshot.available}getError(){const e=[],t=this.config.getError();t&&e.push(t);for(const[i,r]of this.compositionErrors)e.push(`Provider "${i}": ${r}`);return this.availabilityError&&e.push(`Availability refresh: ${this.availabilityError}`),e.length>0?e.join(`
|
|
2
2
|
|
|
3
|
-
`):void 0}getRegisteredProviderConfig(e){return this.extensionProviders.get(e)}getRegisteredProviderIds(){return[...new Set([...this.extensionProviders.keys(),...this.nativeExtensionProviders.keys()])]}getRegisteredNativeProvider(e){return this.nativeExtensionProviders.get(e)}getCompatibilityRequestConfig(e){return Q(e,this.config.getProvider(e.provider),this.extensionProviders.get(e.provider))}isUsingOAuth(e){return this.snapshot.auth.get(e)?.type==="oauth"}isUsingSubscription(e){return this.isUsingOAuth(e)&&this.models.getProvider(e)?.auth.oauth?.isSubscription===!0}hasConfiguredAuth(e){return this.snapshot.configuredProviders.has(e)}async getAuth(e,t={}){if(typeof e=="string")return this.models.getAuth(e,t);const r=await this.models.getAuth(e,t);if(!r)return;const i=X(e,this.config.getProvider(e.provider),this.extensionProviders.get(e.provider),{...r.env??{},...t.env??{}});return{...r,auth:{...r.auth,headers:q(r.auth.headers,i)}}}enqueueCredentialOperation(e,t,r){const i=this.credentialOperations.get(e)??Promise.resolve();let s;const o=new Promise(h=>{s=h}),a=(async()=>(await i.catch(()=>{}),t.throwIfAborted(),s?.(),r()))(),l=a.catch(()=>{});return this.credentialOperations.set(e,l),l.then(()=>{this.credentialOperations.get(e)===l&&this.credentialOperations.delete(e)}),B(o,t).then(()=>a)}async synchronizeCredentialState(e,t,r,i){try{i.throwIfAborted(),this.recomposeProvider(e);const s=this.compositionErrors.get(e);if(s)throw new Error(s);const o=await this.models.refresh({allowNetwork:!1,providers:[e],signal:i});o.aborted&&i.throwIfAborted();const a=o.errors.get(e);if(a)throw a;this.updateModelSnapshot(),await this.refreshProviderAvailability(e,i)}catch(s){throw new oe(e,t,r,{cause:s})}}setRuntimeApiKey(e,t,r={}){const i=p(r.signal);return this.enqueueCredentialOperation(e,i,async()=>{this.credentials.setRuntimeApiKey(e,t),await this.synchronizeCredentialState(e,"setRuntimeApiKey",{type:"api_key",key:t},i)})}removeRuntimeApiKey(e,t={}){const r=p(t.signal);return this.enqueueCredentialOperation(e,r,async()=>{this.credentials.removeRuntimeApiKey(e),await this.synchronizeCredentialState(e,"removeRuntimeApiKey",void 0,r)})}listCredentials(e){return this.credentials.list(e)}getProviderAuthStatus(e){if(this.credentials.hasRuntimeApiKey(e))return{configured:!0,source:"runtime"};if(this.snapshot.storedProviders.has(e))return{configured:!0,source:"stored"};const t=b(this.config.getProvider(e),this.extensionProviders.get(e));if(t)return t;const r=this.snapshot.auth.get(e);return r?{configured:!0,source:"environment",label:r.source}:{configured:!1}}async prepareRequest(e,t){const r=this.models.getProvider(e.provider);if(!r)throw new m("provider",`Unknown provider: ${e.provider}`);const i=await this.getAuth(e,{apiKey:t?.apiKey,env:t?.env,signal:t?.signal});if(!i)throw new m("auth",`Provider is not configured: ${e.provider}`);const{transformHeaders:s,...o}=t??{},a=o;let l=q(i.auth.headers,a.headers);s&&(l=await s(l??{}));const h=i.env||a.env?{...i.env??{},...a.env??{}}:void 0,n=i.auth.baseUrl?{...e,baseUrl:i.auth.baseUrl}:e;return{provider:r,model:n,options:{...a,apiKey:a.apiKey??i.auth.apiKey,headers:l,env:h}}}stream(e,t,r){const i=E(t);return w(e,async()=>{y(e);const s=await this.prepareRequest(e,r);return s.provider.stream(s.model,i,s.options)})}complete(e,t,r){return this.stream(e,t,r).result()}streamSimple(e,t,r){const i=E(t);return S(e)?w(e,async()=>{const s=await this.resolveModel(e,i.messages,{reason:"direct",thinkingLevel:r?.reasoning??"off",signal:r?.signal}),{maxTokens:o}=s.model,a=r?.maxTokens&&o>0?Math.min(r.maxTokens,o):r?.maxTokens,l=s.thinkingLevel==="off"?void 0:s.thinkingLevel,{apiKey:h,headers:n,env:d,...c}=r??{},u=s.model.provider===e.provider?{apiKey:h,headers:n,env:d}:{};return this.streamSimple(s.model,t,{...c,...u,maxTokens:a,reasoning:l})}):w(e,async()=>{y(e);const s=await this.prepareRequest(e,r);return s.provider.streamSimple(s.model,i,s.options)})}completeSimple(e,t,r){return this.streamSimple(e,t,r).result()}streamDeferred(e,t,r){return w(e,async()=>{y(e);const i=await this.prepareRequest(e,r);if(!i.provider.fetchDeferred)throw new m("provider",`Provider ${e.provider} does not support deferred responses`);return i.provider.fetchDeferred(i.model,t,i.options)})}async fetchDeferred(e,t,r){return this.streamDeferred(e,t,r).result()}async cancelDeferred(e,t,r){y(e);const i=await this.prepareRequest(e,r);if(!i.provider.cancelDeferred)throw new m("provider",`Provider ${e.provider} does not support deferred responses`);await i.provider.cancelDeferred(i.model,t,i.options)}async generateImages(e,t,r){try{K(e);const i=await this.prepareRequest(e,r);if(!i.provider.generateImages)throw new m("provider",`Provider ${e.provider} does not support image generation`);return await i.provider.generateImages(i.model,t,i.options)}catch(i){return D(e,i,r?.signal?.aborted)}}async classify(e,t,r){try{z(e),T(e,t);const i=await this.prepareRequest(e,r);if(!i.provider.classify)throw new m("provider",`Provider ${e.provider} does not support classification`);return await i.provider.classify(i.model,t,i.options)}catch(i){return L(e,i,r?.signal?.aborted)}}login(e,t,r,i){if(V()&&t==="oauth"&&!H(e))return Promise.reject(new Error(`OAuth sign-in for "${e}" is not available in ${A}.`));const s=p(r.signal);return this.enqueueCredentialOperation(e,s,async()=>{const o=await this.models.login(e,t,{...r,signal:s},i);return await this.synchronizeCredentialState(e,"login",o,s),o})}logout(e,t={}){const r=p(t.signal);return this.enqueueCredentialOperation(e,r,async()=>{await this.models.logout(e,{signal:r}),await this.synchronizeCredentialState(e,"logout",void 0,r)})}async settled(){for(;this.refreshesInFlight.size>0||this.credentialOperations.size>0;)await Promise.allSettled([...this.refreshesInFlight,...this.credentialOperations.values()])}async refresh(e={}){const t=this.refreshNow(e);this.refreshesInFlight.add(t);try{return await t}finally{this.refreshesInFlight.delete(t)}}async refreshNow(e){const t={...e,allowNetwork:e.allowNetwork??this.modelNetworkEnabled},r=k.load(this.modelsPath),i=this.compositionTail;let s;const o=new Promise(n=>{s=n});this.compositionTail=Promise.all([i,o]).then(()=>{});let a;try{const n=await r;if(await i,this.config=n,this.configureRadiusProviders(),e.providers){for(const d of new Set(e.providers))this.recomposeProvider(d);this.updateModelSnapshot()}else this.rebuildProviders();a=this.models.refresh(t)}finally{s()}const l=await a??{aborted:t.signal?.aborted??!1,errors:new Map},h=new Map(l.errors);if(this.updateModelSnapshot(),e.providers)await Promise.all([...new Set(e.providers)].map(async n=>{try{await this.refreshProviderAvailability(n,p(e.signal))}catch(d){e.signal?.aborted||h.set(n,d instanceof Error?d:new Error(String(d)))}}));else try{await this.queueAvailabilityRefresh(e.signal)}catch{}return{aborted:l.aborted||(e.signal?.aborted??!1),errors:h}}async refreshCatalogsInPlace(e){await Promise.allSettled([...this.refreshesInFlight]);const t=await this.models.refresh({providers:e.providers,signal:e.signal,allowNetwork:this.modelNetworkEnabled});return this.updateModelSnapshot(),t}registerNativeProvider(e){if(!e.id.trim())throw new Error("Provider id must not be empty.");this.extensionProviders.delete(e.id),this.nativeExtensionProviders.set(e.id,e),this.recomposeProvider(e.id),this.updateModelSnapshot(),this.markProvisionallyConfigured(e.id,b(this.config.getProvider(e.id),void 0),e.auth.oauth&&!e.auth.apiKey?"oauth":"api_key"),this.refresh({allowNetwork:!1})}markProvisionallyConfigured(e,t,r){if(!this.snapshot.storedProviders.has(e)&&!t?.configured)return;const i=new Set(this.snapshot.configuredProviders).add(e),s=new Map(this.snapshot.auth);s.get(e)||s.set(e,{type:r,source:"configured provider"}),this.snapshot={...this.snapshot,auth:s,configuredProviders:i,available:this.snapshot.all.filter(o=>i.has(o.provider))}}registerProvider(e,t){Y(e,this.builtins.get(e),this.config.getProvider(e),t),this.nativeExtensionProviders.delete(e);const i={...this.extensionProviders.get(e)};for(const[s,o]of Object.entries(t))o!==void 0&&(i[s]=o);this.extensionProviders.set(e,i),this.recomposeProvider(e),this.updateModelSnapshot(),this.markProvisionallyConfigured(e,b(this.config.getProvider(e),i),i.oauth&&!i.apiKey?"oauth":"api_key"),this.refresh({allowNetwork:!1})}unregisterProvider(e){this.extensionProviders.delete(e),this.nativeExtensionProviders.delete(e),this.recomposeProvider(e),this.updateModelSnapshot(),this.refresh({allowNetwork:!1})}registerVirtualModel(e){const{provider:t,id:r}=e;if(!t.trim()||!r.trim())throw new Error("Virtual model provider and id must not be empty.");const i=this.models.getModel(t,r);if(i&&!S(i))throw new Error(`Virtual model ${t}/${r} conflicts with a physical model.`);const s=this.virtualModels.get(t)??new Map;if(s.set(r,{model:re(e),route:v(o=>e.route(o),"route")}),this.virtualModels.set(t,s),!this.recomposeProvider(t)&&!this.snapshot.configuredProviders.has(t)){const o=new Map(this.snapshot.auth).set(t,{type:"api_key",source:"virtual"}),a=new Set(this.snapshot.configuredProviders).add(t);this.snapshot={...this.snapshot,auth:o,configuredProviders:a}}this.updateModelSnapshot(),this.refresh({allowNetwork:!1})}unregisterVirtualModel(e,t){const r=this.virtualModels.get(e);r?.delete(t)&&(r.size===0&&this.virtualModels.delete(e),this.recomposeProvider(e),this.updateModelSnapshot(),this.refresh({allowNetwork:!1}))}async resolveModel(e,t,r){const i=`Virtual model ${e.provider}/${e.id}`,s=this.virtualModels.get(e.provider)?.get(e.id);if(!s)throw new Error(`${i} is not registered.`);const{failed:o,...a}=r,l=ie(t),h=l&&this.getPhysicalModel(l.provider,l.model),n=o&&this.getPhysicalModel(o.provider,o.model),d=await s.route({...a,model:e,previous:h&&{model:h,thinkingLevel:l?.thinkingLevel},failed:n&&o&&{model:n,thinkingLevel:o.thinkingLevel,message:o},messages:t}),c=this.getPhysicalModel(d.model.provider,d.model.id),u=`${i} routed to ${d.model.provider}/${d.model.id}`;if(!c)throw new Error(`${u}, which is not a physical model.`);if(!this.hasConfiguredAuth(c.provider))throw new Error(`${u}, which has no credentials.`);return{model:c,thinkingLevel:$(c,d.thinkingLevel),state:d.state}}getPhysicalModel(e,t){const r=this.models.getModel(e,t);return r&&!S(r)?r:void 0}}export{oe as CredentialSynchronizationError,C as ModelRuntime,ae as isBuiltinProviderEnabled};
|
|
3
|
+
`):void 0}getRegisteredProviderConfig(e){return this.extensionProviders.get(e)}getRegisteredProviderIds(){return[...new Set([...this.extensionProviders.keys(),...this.nativeExtensionProviders.keys()])]}getRegisteredNativeProvider(e){return this.nativeExtensionProviders.get(e)}getCompatibilityRequestConfig(e){return Z(e,this.config.getProvider(e.provider),this.extensionProviders.get(e.provider))}isUsingOAuth(e){return this.snapshot.auth.get(e)?.type==="oauth"}isUsingSubscription(e){return this.isUsingOAuth(e)&&this.models.getProvider(e)?.auth.oauth?.isSubscription===!0}hasConfiguredAuth(e){return this.snapshot.configuredProviders.has(e)}async getAuth(e,t={}){if(typeof e=="string")return this.models.getAuth(e,t);const i=await this.models.getAuth(e,t);if(!i)return;const r=I(e,this.config.getProvider(e.provider),this.extensionProviders.get(e.provider),{...i.env??{},...t.env??{}});return{...i,auth:{...i.auth,headers:M(i.auth.headers,r)}}}enqueueCredentialOperation(e,t,i){const r=this.credentialOperations.get(e)??Promise.resolve();let s;const o=new Promise(d=>{s=d}),a=(async()=>(await r.catch(()=>{}),t.throwIfAborted(),s?.(),i()))(),n=a.catch(()=>{});return this.credentialOperations.set(e,n),n.then(()=>{this.credentialOperations.get(e)===n&&this.credentialOperations.delete(e)}),j(o,t).then(()=>a)}async synchronizeCredentialState(e,t,i,r){try{r.throwIfAborted(),this.recomposeProvider(e);const s=this.compositionErrors.get(e);if(s)throw new Error(s);const o=await this.models.refresh({allowNetwork:!1,providers:[e],signal:r});o.aborted&&r.throwIfAborted();const a=o.errors.get(e);if(a)throw a;this.updateModelSnapshot(),await this.refreshProviderAvailability(e,r)}catch(s){throw new le(e,t,i,{cause:s})}}setRuntimeApiKey(e,t,i={}){const r=p(i.signal);return this.enqueueCredentialOperation(e,r,async()=>{this.credentials.setRuntimeApiKey(e,t),await this.synchronizeCredentialState(e,"setRuntimeApiKey",{type:"api_key",key:t},r)})}removeRuntimeApiKey(e,t={}){const i=p(t.signal);return this.enqueueCredentialOperation(e,i,async()=>{this.credentials.removeRuntimeApiKey(e),await this.synchronizeCredentialState(e,"removeRuntimeApiKey",void 0,i)})}listCredentials(e){return this.credentials.list(e)}getProviderAuthStatus(e){if(this.credentials.hasRuntimeApiKey(e))return{configured:!0,source:"runtime"};if(this.snapshot.storedProviders.has(e))return{configured:!0,source:"stored"};const t=b(this.config.getProvider(e),this.extensionProviders.get(e));if(t)return t;const i=this.snapshot.auth.get(e);return i?{configured:!0,source:"environment",label:i.source}:{configured:!1}}async prepareRequest(e,t){const i=this.models.getProvider(e.provider);if(!i)throw new m("provider",`Unknown provider: ${e.provider}`);const r=await this.getAuth(e,{apiKey:t?.apiKey,env:t?.env,signal:t?.signal});if(!r)throw new m("auth",`Provider is not configured: ${e.provider}`);const{transformHeaders:s,firstTokenTimeoutMs:o,...a}=t??{},n=a,d=r.auth.baseUrl?{...e,baseUrl:r.auth.baseUrl}:e,l="sessionId"in n&&typeof n.sessionId=="string"?n.sessionId:void 0;let h=M(M(N(d,l),r.auth.headers),n.headers);s&&(h=await s(h??{}));const c=r.env||n.env?{...r.env??{},...n.env??{}}:void 0;return{provider:i,model:d,options:{...n,apiKey:n.apiKey??r.auth.apiKey,headers:h,env:c}}}stream(e,t,i){const r=A(t);return k(i,i?.firstTokenTimeoutMs,s=>w(e,async()=>{y(e);const o=await this.prepareRequest(e,s);return o.provider.stream(o.model,r,o.options)}))}complete(e,t,i){return this.stream(e,t,i).result()}streamSimple(e,t,i){const r=A(t);return S(e)?w(e,async()=>{const s=await this.resolveModel(e,r.messages,{reason:"direct",thinkingLevel:i?.reasoning??"off",signal:i?.signal}),{maxTokens:o}=s.model,a=i?.maxTokens&&o>0?Math.min(i.maxTokens,o):i?.maxTokens,n=s.thinkingLevel==="off"?void 0:s.thinkingLevel,{apiKey:d,headers:l,env:h,...c}=i??{},u=s.model.provider===e.provider?{apiKey:d,headers:l,env:h}:{};return this.streamSimple(s.model,t,{...c,...u,maxTokens:a,reasoning:n})}):k(i,i?.firstTokenTimeoutMs,s=>w(e,async()=>{y(e);const o=await this.prepareRequest(e,s),a={...r,messages:J(r.messages,o.model)};return o.provider.streamSimple(o.model,a,o.options)}))}completeSimple(e,t,i){return this.streamSimple(e,t,i).result()}streamDeferred(e,t,i){return w(e,async()=>{y(e);const r=await this.prepareRequest(e,i);if(!r.provider.fetchDeferred)throw new m("provider",`Provider ${e.provider} does not support deferred responses`);return r.provider.fetchDeferred(r.model,t,r.options)})}async fetchDeferred(e,t,i){return this.streamDeferred(e,t,i).result()}async cancelDeferred(e,t,i){y(e);const r=await this.prepareRequest(e,i);if(!r.provider.cancelDeferred)throw new m("provider",`Provider ${e.provider} does not support deferred responses`);await r.provider.cancelDeferred(r.model,t,r.options)}async generateImages(e,t,i){try{K(e);const r=await this.prepareRequest(e,i);if(!r.provider.generateImages)throw new m("provider",`Provider ${e.provider} does not support image generation`);return await r.provider.generateImages(r.model,t,r.options)}catch(r){return U(e,r,i?.signal?.aborted)}}async classify(e,t,i){try{F(e),L(e,t);const r=await this.prepareRequest(e,i);if(!r.provider.classify)throw new m("provider",`Provider ${e.provider} does not support classification`);return await r.provider.classify(r.model,t,r.options)}catch(r){return D(e,r,i?.signal?.aborted)}}login(e,t,i,r){if(_()&&t==="oauth"&&!G(e))return Promise.reject(new Error(`OAuth sign-in for "${e}" is not available in ${q}.`));const s=p(i.signal);return this.enqueueCredentialOperation(e,s,async()=>{const o=await this.models.login(e,t,{...i,signal:s},r);return await this.synchronizeCredentialState(e,"login",o,s),o})}logout(e,t={}){const i=p(t.signal);return this.enqueueCredentialOperation(e,i,async()=>{await this.models.logout(e,{signal:i}),await this.synchronizeCredentialState(e,"logout",void 0,i)})}async settled(){for(;this.refreshesInFlight.size>0||this.credentialOperations.size>0;)await Promise.allSettled([...this.refreshesInFlight,...this.credentialOperations.values()])}async refresh(e={}){const t=this.refreshNow(e);this.refreshesInFlight.add(t);try{return await t}finally{this.refreshesInFlight.delete(t)}}async refreshNow(e){const t={...e,allowNetwork:e.allowNetwork??this.modelNetworkEnabled},i=C.load(this.modelsPath),r=this.compositionTail;let s;const o=new Promise(l=>{s=l});this.compositionTail=Promise.all([r,o]).then(()=>{});let a;try{const l=await i;if(await r,this.config=l,this.configureRadiusProviders(),e.providers){for(const h of new Set(e.providers))this.recomposeProvider(h);this.updateModelSnapshot()}else this.rebuildProviders();a=this.models.refresh(t)}finally{s()}const n=await a??{aborted:t.signal?.aborted??!1,errors:new Map},d=new Map(n.errors);if(this.updateModelSnapshot(),e.providers)await Promise.all([...new Set(e.providers)].map(async l=>{try{await this.refreshProviderAvailability(l,p(e.signal))}catch(h){e.signal?.aborted||d.set(l,h instanceof Error?h:new Error(String(h)))}}));else try{await this.queueAvailabilityRefresh(e.signal)}catch{}return{aborted:n.aborted||(e.signal?.aborted??!1),errors:d}}async refreshCatalogsInPlace(e){const t=(async()=>{await Promise.allSettled([...this.refreshesInFlight]);const i=await this.models.refresh({providers:e.providers,signal:e.signal,allowNetwork:this.modelNetworkEnabled});return this.updateModelSnapshot(),i})();this.inPlaceRefreshesInFlight.add(t);try{return await t}finally{this.inPlaceRefreshesInFlight.delete(t)}}async whenCatalogRefreshesSettle(e){if(this.inPlaceRefreshesInFlight.size===0||e?.aborted)return;const t=Promise.allSettled([...this.inPlaceRefreshesInFlight]).then(()=>{});if(!e)return t;await new Promise(i=>{const r=v(()=>{e.removeEventListener("abort",r),i()},"done");e.addEventListener("abort",r,{once:!0}),t.then(r)})}registerNativeProvider(e){if(!e.id.trim())throw new Error("Provider id must not be empty.");this.extensionProviders.delete(e.id),this.nativeExtensionProviders.set(e.id,e),this.recomposeProvider(e.id),this.updateModelSnapshot(),this.markProvisionallyConfigured(e.id,b(this.config.getProvider(e.id),void 0),e.auth.oauth&&!e.auth.apiKey?"oauth":"api_key"),this.refresh({allowNetwork:!1})}markProvisionallyConfigured(e,t,i){if(!this.snapshot.storedProviders.has(e)&&!t?.configured)return;const r=new Set(this.snapshot.configuredProviders).add(e),s=new Map(this.snapshot.auth);s.get(e)||s.set(e,{type:i,source:"configured provider"}),this.snapshot={...this.snapshot,auth:s,configuredProviders:r,available:this.snapshot.all.filter(o=>r.has(o.provider))}}registerProvider(e,t){ee(e,this.builtins.get(e),this.config.getProvider(e),t),this.nativeExtensionProviders.delete(e);const r={...this.extensionProviders.get(e)};for(const[s,o]of Object.entries(t))o!==void 0&&(r[s]=o);this.extensionProviders.set(e,r),this.recomposeProvider(e),this.updateModelSnapshot(),this.markProvisionallyConfigured(e,b(this.config.getProvider(e),r),r.oauth&&!r.apiKey?"oauth":"api_key"),this.refresh({allowNetwork:!1})}unregisterProvider(e){this.extensionProviders.delete(e),this.nativeExtensionProviders.delete(e),this.recomposeProvider(e),this.updateModelSnapshot(),this.refresh({allowNetwork:!1})}registerVirtualModel(e){const{provider:t,id:i}=e;if(!t.trim()||!i.trim())throw new Error("Virtual model provider and id must not be empty.");const r=this.models.getModel(t,i);if(r&&!S(r))throw new Error(`Virtual model ${t}/${i} conflicts with a physical model.`);const s=this.virtualModels.get(t)??new Map;if(s.set(i,{model:oe(e),route:v(o=>e.route(o),"route")}),this.virtualModels.set(t,s),!this.recomposeProvider(t)&&!this.snapshot.configuredProviders.has(t)){const o=new Map(this.snapshot.auth).set(t,{type:"api_key",source:"virtual"}),a=new Set(this.snapshot.configuredProviders).add(t);this.snapshot={...this.snapshot,auth:o,configuredProviders:a}}this.updateModelSnapshot(),this.refresh({allowNetwork:!1})}unregisterVirtualModel(e,t){const i=this.virtualModels.get(e);i?.delete(t)&&(i.size===0&&this.virtualModels.delete(e),this.recomposeProvider(e),this.updateModelSnapshot(),this.refresh({allowNetwork:!1}))}async resolveModel(e,t,i){const r=`Virtual model ${e.provider}/${e.id}`,s=this.virtualModels.get(e.provider)?.get(e.id);if(!s)throw new Error(`${r} is not registered.`);const{failed:o,...a}=i,n=ae(t),d=n&&this.getPhysicalModel(n.provider,n.model),l=o&&this.getPhysicalModel(o.provider,o.model),h=await s.route({...a,model:e,previous:d&&{model:d,thinkingLevel:n?.thinkingLevel},failed:l&&o&&{model:l,thinkingLevel:o.thinkingLevel,message:o},messages:t}),c=this.getPhysicalModel(h.model.provider,h.model.id),u=`${r} routed to ${h.model.provider}/${h.model.id}`;if(!c)throw new Error(`${u}, which is not a physical model.`);if(!this.hasConfiguredAuth(c.provider))throw new Error(`${u}, which has no credentials.`);return{model:c,thinkingLevel:$(c,h.thinkingLevel),state:h.state}}getPhysicalModel(e,t){const i=this.models.getModel(e,t);return i&&!S(i)?i:void 0}}export{le as CredentialSynchronizationError,R as ModelRuntime,he as isBuiltinProviderEnabled};
|
|
@@ -83,6 +83,7 @@ interface PackageManagerOptions {
|
|
|
83
83
|
agentDir: string;
|
|
84
84
|
settingsManager: SettingsManager;
|
|
85
85
|
builtinExtensions?: string[];
|
|
86
|
+
quiet?: boolean;
|
|
86
87
|
}
|
|
87
88
|
type SourceScope = "user" | "project" | "temporary";
|
|
88
89
|
export declare const PROJECT_PACKAGES_DIR_NAME = "project-packages";
|
|
@@ -92,6 +93,7 @@ export declare class DefaultPackageManager implements PackageManager {
|
|
|
92
93
|
private agentDir;
|
|
93
94
|
private settingsManager;
|
|
94
95
|
private builtinExtensions;
|
|
96
|
+
private readonly quiet;
|
|
95
97
|
private globalNpmRoot;
|
|
96
98
|
private globalNpmRootCommandKey;
|
|
97
99
|
private progressCallback;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var vt=Object.defineProperty;var g=(c,t)=>vt(c,"name",{value:t,configurable:!0});import{createHash as nt}from"node:crypto";import{chmodSync as Mt,existsSync as f,globSync as Ct,mkdirSync as W,readdirSync as j,readFileSync as A,rmSync as F,statSync as N,writeFileSync as V}from"node:fs";import{homedir as Nt}from"node:os";function z(){if(process.platform!=="linux"||Object.keys(process.env).length>0)return process.env;try{const c=A("/proc/self/environ","utf-8"),t={};for(const e of c.split("\0")){const s=e.indexOf("=");s>0&&(t[e.slice(0,s)]=e.slice(s+1))}return t}catch{return process.env}}g(z,"getEnv");import{basename as I,dirname as w,join as h,relative as k,resolve as S,sep as H}from"node:path";import G from"ignore";import{minimatch as x}from"minimatch";import{gt as rt,maxSatisfying as Et,rcompare as bt,satisfies as Rt,valid as jt,validRange as Ft}from"semver";import{CONFIG_DIR_NAME as Y,getProjectPromptsDir as It,isOfficialExtensionsPackage as xt,SHARED_SKILL_CONFIG_DIRS as it}from"../config.js";import{spawnProcess as ot,spawnProcessSync as $t}from"../utils/child-process.js";import{parseGitUrl as At}from"../utils/git.js";import{isOfflineModeEnabled as b}from"../utils/offline.js";import{canonicalizePath as at,isLocalPath as Gt,markPathIgnoredByCloudSync as Dt,normalizePath as ct,resolvePath as U}from"../utils/paths.js";import{stripBom as X}from"../utils/text.js";import{isStdoutTakenOver as Tt}from"./output-guard.js";import{findNearestPiManifest as Wt,readPiManifest as _}from"./pi-manifest.js";import{BUILTIN_PATH_PREFIX as q}from"./source-info.js";const v=1e4,lt=4,Ht=4,Ut=Symbol.for("dalcode.packageManager.npmArgsHook");function _t(c){return jt(c??"")!==null}g(_t,"isExactNpmVersion");function Lt(c){return c?Ft(c)??void 0:void 0}g(Lt,"getNpmVersionRange");function ut(c){return c.source==="builtin"?5:c.origin==="package"?4:(c.scope==="project"?0:2)+(c.source==="local"?0:1)}g(ut,"resourcePrecedenceRank");const L=["extensions","skills","prompts","themes"],Ot={extensions:/\.(ts|js)$/,skills:/\.md$/,prompts:/\.md$/,themes:/\.json$/},Bt=[".gitignore",".ignore",".fdignore"],Jt="project-packages";function y(c){return c.split(H).join("/")}g(y,"toPosixPath");function Q(){return process.env.HOME||Nt()}g(Q,"getHomeDir");function Kt(c){const t=h(c,"tmp","extensions");return W(t,{recursive:!0,mode:448}),Mt(t,448),t}g(Kt,"getExtensionTempFolder");function Vt(c,t){const e=c.trim();if(!e||e.startsWith("#")&&!e.startsWith("\\#"))return null;let s=c,n=!1;s.startsWith("!")?(n=!0,s=s.slice(1)):s.startsWith("\\!")&&(s=s.slice(1)),s.startsWith("/")&&(s=s.slice(1));const r=t?`${t}${s}`:s;return n?`!${r}`:r}g(Vt,"prefixIgnorePattern");function D(c,t,e){const s=k(e,t),n=s?`${y(s)}/`:"";for(const r of Bt){const i=h(t,r);if(f(i))try{const a=A(i,"utf-8").split(/\r?\n/).map(l=>Vt(l,n)).filter(l=>!!l);a.length>0&&c.add(a)}catch{}}}g(D,"addIgnoreRules");function zt(c){return c.startsWith("!")||c.startsWith("+")||c.startsWith("-")||c.includes("*")||c.includes("?")}g(zt,"isPattern");function Z(c){return c.startsWith("!")||c.startsWith("+")||c.startsWith("-")}g(Z,"isOverridePattern");function Yt(c){return c.includes("*")||c.includes("?")}g(Yt,"hasGlobPattern");function Xt(c,t){return Ct(c,{cwd:t}).map(e=>S(t,e)).filter(e=>k(t,e).split(H).every(s=>s===".."||!s.startsWith("."))).sort((e,s)=>e<s?-1:e>s?1:0)}g(Xt,"expandPackageGlob");function qt(c){const t=[],e=[];for(const s of c)zt(s)?e.push(s):t.push(s);return{plain:t,patterns:e}}g(qt,"splitPatterns");function pt(c,t,e=!0,s,n){const r=[];if(!f(c))return r;const i=n??c,o=s??G();D(o,c,i);try{const a=j(c,{withFileTypes:!0});for(const l of a){if(l.name.startsWith(".")||e&&l.name==="node_modules")continue;const p=h(c,l.name);let u=l.isDirectory(),m=l.isFile();if(l.isSymbolicLink())try{const R=N(p);u=R.isDirectory(),m=R.isFile()}catch{continue}const P=y(k(i,p)),d=u?`${P}/`:P;o.ignores(d)||(u?r.push(...pt(p,t,e,o,i)):m&&t.test(l.name)&&r.push(p))}}catch{}return r}g(pt,"collectFiles");function tt(c,t,e,s){const n=[];if(!f(c))return n;const r=s??c,i=e??G();D(i,c,r);try{const o=j(c,{withFileTypes:!0});for(const a of o){if(a.name!=="SKILL.md")continue;const l=h(c,a.name);let p=a.isFile();if(a.isSymbolicLink())try{p=N(l).isFile()}catch{continue}const u=y(k(r,l));if(p&&!i.ignores(u))return n.push(l),n}for(const a of o){if(a.name.startsWith(".")||a.name==="node_modules")continue;const l=h(c,a.name);let p=a.isDirectory(),u=a.isFile();if(a.isSymbolicLink())try{const d=N(l);p=d.isDirectory(),u=d.isFile()}catch{continue}const m=y(k(r,l));if(u&&a.name.endsWith(".md")&&!i.ignores(m)&&(t==="pi"&&c===r||t==="agents"&&c!==r)){n.push(l);continue}p&&(i.ignores(`${m}/`)||n.push(...tt(l,t,i,r)))}}catch{}return n}g(tt,"collectSkillEntries");function O(c,t){return tt(c,t)}g(O,"collectAutoSkillEntries");function Qt(c){let t=S(c);for(;;){if(f(h(t,".git")))return t;const e=w(t);if(e===t)return null;t=e}}g(Qt,"findGitRepoRoot");function Zt(c=Q()){return it.map(t=>h(c,t,"skills"))}g(Zt,"userSharedSkillDirs");function te(c){const t=[],e=S(c),s=Qt(e);let n=e;for(;;){for(const i of it)t.push(h(n,i,"skills"));if(s&&n===s)break;const r=w(n);if(r===n)break;n=r}return t}g(te,"collectAncestorAgentsSkillDirs");function ht(c){const t=[];if(!f(c))return t;const e=G();D(e,c,c);try{const s=j(c,{withFileTypes:!0});for(const n of s){if(n.name.startsWith(".")||n.name==="node_modules")continue;const r=h(c,n.name);let i=n.isFile();if(n.isSymbolicLink())try{i=N(r).isFile()}catch{continue}const o=y(k(c,r));e.ignores(o)||i&&n.name.endsWith(".md")&&t.push(r)}}catch{}return t}g(ht,"collectAutoPromptEntries");function ft(c){const t=[];if(!f(c))return t;const e=G();D(e,c,c);try{const s=j(c,{withFileTypes:!0});for(const n of s){if(n.name.startsWith(".")||n.name==="node_modules")continue;const r=h(c,n.name);let i=n.isFile();if(n.isSymbolicLink())try{i=N(r).isFile()}catch{continue}const o=y(k(c,r));e.ignores(o)||i&&n.name.endsWith(".json")&&t.push(r)}}catch{}return t}g(ft,"collectAutoThemeEntries");function gt(c){const t=h(c,"package.json");if(f(t)){const n=_(t);if(n?.extensions?.length){const r=[];for(const i of n.extensions){const o=S(c,i);f(o)&&r.push(o)}if(r.length>0)return r}}const e=h(c,"index.ts"),s=h(c,"index.js");return f(e)?[e]:f(s)?[s]:null}g(gt,"resolveExtensionEntries");function et(c){const t=[];if(!f(c))return t;const e=gt(c);if(e)return e;const s=G();D(s,c,c);try{const n=j(c,{withFileTypes:!0});for(const r of n){if(r.name.startsWith(".")||r.name==="node_modules")continue;const i=h(c,r.name);let o=r.isDirectory(),a=r.isFile();if(r.isSymbolicLink())try{const u=N(i);o=u.isDirectory(),a=u.isFile()}catch{continue}const l=y(k(c,i)),p=o?`${l}/`:l;if(!s.ignores(p)){if(a&&(r.name.endsWith(".ts")||r.name.endsWith(".js")))t.push(i);else if(o){const u=gt(i);u&&t.push(...u)}}}}catch{}return t}g(et,"collectAutoExtensionEntries");function B(c,t){return t==="skills"?tt(c,"pi"):t==="extensions"?et(c):pt(c,Ot[t])}g(B,"collectResourceFiles");function J(c,t,e){const s=y(k(e,c)),n=I(c),r=y(c),i=n==="SKILL.md",o=i?w(c):void 0,a=i?y(k(e,o)):void 0,l=i?I(o):void 0,p=i?y(o):void 0;return t.some(u=>{const m=y(ct(u));return x(s,m)||x(n,m)||x(r,m)?!0:i?x(a,m)||x(l,m)||x(p,m):!1})}g(J,"matchesAnyPattern");function ee(c){const t=c.startsWith("./")||c.startsWith(".\\")?c.slice(2):c;return y(ct(t))}g(ee,"normalizeExactPattern");function T(c,t,e){if(t.length===0)return!1;const s=y(k(e,c)),n=I(c),r=y(c),i=n==="SKILL.md",o=i?w(c):void 0,a=i?y(k(e,o)):void 0,l=i?y(o):void 0;return t.some(p=>{const u=ee(p);return u===s||u===r?!0:i?u===a||u===l:!1})}g(T,"matchesAnyExactPattern");function mt(c){return c.filter(t=>t.startsWith("!")||t.startsWith("+")||t.startsWith("-"))}g(mt,"getOverridePatterns");function dt(c,t,e){const s=mt(t),n=s.filter(a=>a.startsWith("!")).map(a=>a.slice(1)),r=s.filter(a=>a.startsWith("+")).map(a=>a.slice(1)),i=s.filter(a=>a.startsWith("-")).map(a=>a.slice(1));let o=!0;return n.length>0&&J(c,n,e)&&(o=!1),r.length>0&&T(c,r,e)&&(o=!0),i.length>0&&T(c,i,e)&&(o=!1),o}g(dt,"isEnabledByOverrides");function K(c,t,e){const s=[],n=[],r=[],i=[];for(const a of t)a.startsWith("+")?r.push(a.slice(1)):a.startsWith("-")?i.push(a.slice(1)):a.startsWith("!")?n.push(a.slice(1)):s.push(a);let o;if(s.length===0?o=[...c]:o=c.filter(a=>J(a,s,e)),n.length>0&&(o=o.filter(a=>!J(a,n,e))),r.length>0)for(const a of c)!o.includes(a)&&T(a,r,e)&&o.push(a);return i.length>0&&(o=o.filter(a=>!T(a,i,e))),new Set(o)}g(K,"applyPatterns");function yt(c,t,e){const s=new Map;for(const n of t){const r=n.slice(n.startsWith("+")||n.startsWith("-")||n.startsWith("!")?1:0),i=!n.startsWith("-")&&!n.startsWith("!"),o=n.startsWith("+")||n.startsWith("-");for(const a of c)(o?T(a,[r],e):J(a,[r],e))&&s.set(a,i)}return s}g(yt,"applyAutoloadDisabledPatterns");class we{static{g(this,"DefaultPackageManager")}cwd;agentDir;settingsManager;builtinExtensions;globalNpmRoot;globalNpmRootCommandKey;progressCallback;constructor(t){this.cwd=U(t.cwd),this.agentDir=U(t.agentDir),this.settingsManager=t.settingsManager,this.builtinExtensions=t.builtinExtensions??[]}setProgressCallback(t){this.progressCallback=t}addSourceToSettings(t,e){const s=e?.local?"project":"user",r=(s==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],i=this.normalizePackageSourceForSettings(t,s),o=g(p=>{const u=e?.resolvedCommit;return!u&&!p?i:typeof p=="string"||p===void 0?u?{source:i,resolvedCommit:u}:i:u?{...p,source:i,resolvedCommit:u}:{...p,source:i}},"toEntry"),a=r.findIndex(p=>this.packageSourcesMatch(p,t,s));if(a!==-1){const p=r[a];if(this.getPackageSourceString(p)===i&&!e?.resolvedCommit)return!1;const u=[...r];return u[a]=o(p),s==="project"?this.settingsManager.setProjectPackages(u):this.settingsManager.setPackages(u),!0}const l=[...r,o()];return s==="project"?this.settingsManager.setProjectPackages(l):this.settingsManager.setPackages(l),!0}removeSourceFromSettings(t,e){const s=e?.local?"project":"user",r=(s==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],i=r.filter(a=>!this.packageSourcesMatch(a,t,s));return i.length!==r.length?(s==="project"?this.settingsManager.setProjectPackages(i):this.settingsManager.setPackages(i),!0):!1}getInstalledPath(t,e){const s=this.parseSource(t);if(s.type==="npm"){const n=this.getNpmInstallPath(s,e);return f(n)?n:void 0}if(s.type==="git"){const n=this.getGitReadPath(s,e);return f(n)?n:void 0}if(s.type==="local"){const n=this.getBaseDirForScope(e),r=this.resolvePathFromBase(s.path,n);return f(r)?r:void 0}}async getRegistryIntegrity(t){const e=this.parseSource(t);if(e.type!=="npm"||!e.pinned)return;const s=this.getNpmCommand(),n=await this.applyNpmArgsHook(["view",e.spec,"dist.integrity","--json"],this.cwd),i=(await this.runCommandCapture(s.command,[...s.args,...n],{cwd:this.cwd,timeoutMs:v})).trim();if(!i)return;const o=JSON.parse(i);return typeof o=="string"&&o.length>0?o:void 0}getRecordedIntegrity(t,e){const s=this.getNpmReadRoot(t,e),n=h(s,"package-lock.json");if(!f(n))return;let r;try{r=JSON.parse(X(A(n,"utf-8")))}catch{return null}if(!r||typeof r!="object")return null;const o=r.packages?.[`node_modules/${t}`];if(!o||typeof o!="object")return null;const a=o.integrity;return typeof a=="string"&&a.length>0?a:null}readDeclaredPermissions(t){if(!t)return;const s=Wt(t)?.manifest.permissions;return s&&s.length>0?[...s]:void 0}async readGitHead(t){if(t)try{const s=(await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:v})).trim();return/^[0-9a-f]{7,40}$/i.test(s)?s:void 0}catch{return}}getStoredResolvedCommit(t,e){const s=e==="project"?this.settingsManager.getProjectSettings().packages??[]:this.settingsManager.getGlobalSettings().packages??[];for(const n of s)if(typeof n!="string"&&this.packageSourcesMatch(n,t,e))return n.resolvedCommit}emitProgress(t){this.progressCallback?.(t)}async withProgress(t,e,s,n){this.emitProgress({type:"start",action:t,source:e,message:s});try{await n(),this.emitProgress({type:"complete",action:t,source:e})}catch(r){const i=r instanceof Error?r.message:String(r);throw this.emitProgress({type:"error",action:t,source:e,message:i}),r}}async resolve(t){const e=this.createAccumulator(),s=this.settingsManager.getGlobalSettings(),n=this.settingsManager.getProjectSettings(),r=[];for(const l of n.packages??[])r.push({pkg:l,scope:"project"});for(const l of s.packages??[])r.push({pkg:l,scope:"user"});const i=this.dedupePackages(r);await this.resolvePackageSources(i,e,t);const o=this.agentDir,a=h(this.cwd,Y);for(const l of L){const p=this.getTargetMap(e,l),u=s[l]??[],m=n[l]??[];this.resolveLocalEntries(m,l,p,{source:"local",scope:"project",origin:"top-level"},a),this.resolveLocalEntries(u,l,p,{source:"local",scope:"user",origin:"top-level"},o)}this.addAutoDiscoveredResources(e,s,n,o,a);for(const l of this.builtinExtensions){const p=`${q}${l}`,u=yt([p],mt(n.extensions??[]),a).get(p);this.addResource(e.extensions,p,{source:"builtin",scope:u===void 0?"user":"project",origin:"top-level"},u??dt(p,s.extensions??[],o))}return this.toResolvedPaths(e)}async resolveExtensionSources(t,e){const s=this.createAccumulator(),n=e?.temporary?"temporary":e?.local?"project":"user";for(const i of t.filter(o=>o.startsWith(q)))this.addResource(s.extensions,i,{source:"builtin",scope:n,origin:"top-level"},!0);const r=t.filter(i=>!i.startsWith(q)).map(i=>({pkg:i,scope:n}));return await this.resolvePackageSources(r,s),this.toResolvedPaths(s)}listConfiguredPackages(){const t=this.settingsManager.getGlobalSettings(),e=this.settingsManager.getProjectSettings(),s=[];for(const n of t.packages??[]){const r=typeof n=="string"?n:n.source,i=this.getInstalledPath(r,"user");s.push({source:r,scope:"user",filtered:typeof n=="object",installedPath:i,resolvedCommit:typeof n=="object"?n.resolvedCommit:void 0,permissions:this.readDeclaredPermissions(i)})}for(const n of e.packages??[]){const r=typeof n=="string"?n:n.source,i=this.getInstalledPath(r,"project");s.push({source:r,scope:"project",filtered:typeof n=="object",installedPath:i,resolvedCommit:typeof n=="object"?n.resolvedCommit:void 0,permissions:this.readDeclaredPermissions(i)})}return s}async install(t,e){const s=this.parseSource(t),n=e?.local?"project":"user";this.assertProjectTrustedForScope(n),await this.withProgress("install",t,`Installing ${t}...`,async()=>{if(s.type==="npm"){await this.installNpm(s,n,!1);return}if(s.type==="git"){await this.installGit(s,n);return}if(s.type==="local"){const r=this.resolvePath(s.path);if(!f(r))throw new Error(`Path does not exist: ${r}`);return}throw new Error(`Unsupported install source: ${t}`)})}async installAndPersist(t,e){await this.install(t,e);const s=e?.local?"project":"user",n=this.getInstalledPath(t,s),r=await this.readGitHead(n);this.addSourceToSettings(t,{...e,resolvedCommit:r})}async remove(t,e){const s=this.parseSource(t),n=e?.local?"project":"user";this.assertProjectTrustedForScope(n),await this.withProgress("remove",t,`Removing ${t}...`,async()=>{if(s.type==="npm"){await this.uninstallNpm(s,n);return}if(s.type==="git"){await this.removeGit(s,n);return}if(s.type!=="local")throw new Error(`Unsupported remove source: ${t}`)})}async removeAndPersist(t,e){return await this.remove(t,e),this.removeSourceFromSettings(t,e)}async update(t,e){const s=e?.latest===!0,n=this.settingsManager.getGlobalSettings(),r=this.settingsManager.getProjectSettings(),i=t?this.getPackageIdentity(t):void 0;let o=!1;const a=[];for(const l of n.packages??[]){const p=typeof l=="string"?l:l.source;i&&this.getPackageIdentity(p,"user")!==i||(o=!0,a.push({source:p,scope:"user"}))}for(const l of r.packages??[]){const p=typeof l=="string"?l:l.source;i&&this.getPackageIdentity(p,"project")!==i||(o=!0,a.push({source:p,scope:"project"}))}if(t&&!o)throw new Error(this.buildNoMatchingPackageMessage(t,[...n.packages??[],...r.packages??[]]));await this.updateConfiguredSources(a,s)}async updateConfiguredSources(t,e=!1){if(b()||t.length===0)return;const s=[],n=[];for(const p of t){const u=this.parseSource(p.source);if(u.type==="npm")u.pinned||s.push({...p,parsed:u});else if(u.type==="git"){const m=this.getStoredResolvedCommit(p.source,p.scope);if(!u.ref&&m&&!e)continue;n.push({...p,parsed:u})}}const r=s.map(p=>async()=>({entry:p,shouldUpdate:await this.shouldUpdateNpmSource(p.parsed,p.scope)})),i=await this.runWithConcurrency(r,lt),o=[],a=[];for(const p of i)p.shouldUpdate&&(p.entry.scope==="user"?o.push(p.entry):a.push(p.entry));const l=[];if(o.length>0&&l.push(this.updateNpmBatch(o,"user")),a.length>0&&l.push(this.updateNpmBatch(a,"project")),n.length>0){const p=n.map(u=>async()=>this.withProgress("update",u.source,`Updating ${u.source}...`,async()=>{if(await this.updateGit(u.parsed,u.scope),!this.getStoredResolvedCommit(u.source,u.scope))return;const P=this.getInstalledPath(u.source,u.scope),d=await this.readGitHead(P);d&&this.addSourceToSettings(u.source,{local:u.scope==="project",resolvedCommit:d})}));l.push(this.runWithConcurrency(p,Ht).then(()=>{}))}await Promise.all(l)}async shouldUpdateNpmSource(t,e){const s=this.getManagedNpmInstallPath(t,e),n=f(s)?this.getInstalledNpmVersion(s):void 0;if(!n)return!0;try{const r=await this.getLatestNpmVersion(t.version?t.spec:t.name,t.range);return rt(r,n)}catch{return!0}}async updateNpmBatch(t,e){if(t.length===0)return;const s=t.length===1?t[0].source:`${e} npm packages`,n=t.length===1?`Updating ${t[0].source}...`:`Updating ${e} npm packages...`,r=t.map(i=>i.parsed.version?i.parsed.spec:`${i.parsed.name}@latest`);await this.withProgress("update",s,n,async()=>{await this.installNpmBatch(r,e)})}async installNpmBatch(t,e){const s=this.getNpmInstallRoot(e,!1);this.ensureNpmProject(s),await this.runNpmCommand(this.getNpmInstallArgs(t,s))}async checkForAvailableUpdates(){if(b())return[];const t=this.settingsManager.getGlobalSettings(),e=this.settingsManager.getProjectSettings(),s=[];for(const o of e.packages??[])s.push({pkg:o,scope:"project"});for(const o of t.packages??[])s.push({pkg:o,scope:"user"});const r=this.dedupePackages(s).filter(o=>o.scope!=="temporary").map(o=>async()=>{const a=typeof o.pkg=="string"?o.pkg:o.pkg.source,l=this.parseSource(a);if(l.type==="local"||l.pinned)return;if(l.type==="npm"){const m=this.getNpmInstallPath(l,o.scope);return!f(m)||!await this.npmHasAvailableUpdate(l,m)?void 0:{source:a,displayName:l.name,type:"npm",scope:o.scope}}const p=this.getGitReadPath(l,o.scope);if(!(!f(p)||!await this.gitHasAvailableUpdate(p)))return{source:a,displayName:`${l.host}/${l.path}`,type:"git",scope:o.scope}});return(await this.runWithConcurrency(r,lt)).filter(o=>o!==void 0)}async resolvePackageSources(t,e,s){for(const{pkg:n,scope:r}of t){const i=typeof n=="string"?n:n.source,o=typeof n=="object"?n:void 0,a=this.findAutoloadDeltaBase(n,r,t),l=a?.source??i,p=a?.scope??r,u=this.parseSource(l),m={source:i,scope:r,origin:"package"};if(u.type==="local"){const d=this.getBaseDirForScope(p);this.resolveLocalExtensionSource(u,e,o,m,d);continue}const P=g(async()=>{if(b())return!1;if(!s)return await this.installParsedSource(u,p),!0;const d=await s(l);if(d==="skip")return!1;if(d==="error")throw new Error(`Missing source: ${l}`);return await this.installParsedSource(u,p),!0},"installMissing");if(u.type==="npm"){let d=this.getNpmInstallPath(u,p);if(!f(d)||!await this.installedNpmMatchesConfiguredVersion(u,d)){if(!await P())continue;d=this.getNpmInstallPath(u,p)}m.baseDir=d,m.packageRoot=d,this.collectPackageResources(d,e,o,m);continue}if(u.type==="git"){const d=this.getGitReadPath(u,p);if(f(d))p==="temporary"&&!u.pinned&&!b()&&await this.refreshTemporaryGitSource(u,l);else if(!await P())continue;m.baseDir=d,m.packageRoot=d,this.collectPackageResources(d,e,o,m)}}}findAutoloadDeltaBase(t,e,s){if(e!=="project"||typeof t!="object"||t.autoload!==!1)return;const n=this.getPackageIdentity(t.source,e),r=s.find(i=>i.scope==="user"&&this.getPackageIdentity(this.getPackageSourceString(i.pkg),"user")===n);return r?{source:this.getPackageSourceString(r.pkg),scope:"user"}:void 0}resolveLocalExtensionSource(t,e,s,n,r){const i=this.resolvePathFromBase(t.path,r);if(f(i))try{const o=N(i);if(o.isFile()){n.baseDir=w(i),this.addResource(e.extensions,i,n,!0);return}o.isDirectory()&&(n.baseDir=i,n.packageRoot=i,this.collectPackageResources(i,e,s,n)||this.addResource(e.extensions,i,n,!0))}catch{return}}async installParsedSource(t,e){if(t.type==="npm"){await this.installNpm(t,e,e==="temporary");return}if(t.type==="git"){await this.installGit(t,e);return}}getPackageSourceString(t){return typeof t=="string"?t:t.source}getSourceMatchKeyForInput(t){const e=this.parseSource(t);return e.type==="npm"?`npm:${e.name}`:e.type==="git"?`git:${e.host}/${e.path}`:`local:${this.resolvePath(e.path)}`}getSourceMatchKeyForSettings(t,e){const s=this.parseSource(t);if(s.type==="npm")return`npm:${s.name}`;if(s.type==="git")return`git:${s.host}/${s.path}`;const n=this.getBaseDirForScope(e);return`local:${this.resolvePathFromBase(s.path,n)}`}buildNoMatchingPackageMessage(t,e){const s=this.findSuggestedConfiguredSource(t,e);return s?`No matching package found for ${t}. Did you mean ${s}?`:`No matching package found for ${t}`}findSuggestedConfiguredSource(t,e){const s=t.trim(),n=new Set;for(const r of e){const i=this.getPackageSourceString(r),o=this.parseSource(i);if(o.type==="npm"){(s===o.name||s===o.spec)&&n.add(i);continue}if(o.type==="git"){const a=`${o.host}/${o.path}`,l=o.ref?`${a}@${o.ref}`:void 0;(s===a||l&&s===l)&&n.add(i)}}return n.values().next().value}packageSourcesMatch(t,e,s){const n=this.getSourceMatchKeyForSettings(this.getPackageSourceString(t),s),r=this.getSourceMatchKeyForInput(e);return n===r}normalizePackageSourceForSettings(t,e){const s=this.parseSource(t);if(s.type!=="local")return t;const n=this.getBaseDirForScope(e),r=this.resolvePath(s.path);return k(n,r)||"."}parseSource(t){if(t.startsWith("npm:")){const s=t.slice(4).trim(),{name:n,version:r}=this.parseNpmSpec(s);return{type:"npm",spec:s,name:n,version:r,range:Lt(r),pinned:_t(r)}}if(Gt(t))return{type:"local",path:t};const e=At(t);return e||{type:"local",path:t}}async installedNpmMatchesConfiguredVersion(t,e){const s=this.getInstalledNpmVersion(e);return s?t.range?Rt(s,t.range):!0:!1}async npmHasAvailableUpdate(t,e){if(b())return!1;const s=this.getInstalledNpmVersion(e);if(!s)return!1;try{const n=await this.getLatestNpmVersion(t.version?t.spec:t.name,t.range);return rt(n,s)}catch{return!1}}getInstalledNpmVersion(t){const e=h(t,"package.json");if(f(e))try{const s=A(e,"utf-8");return JSON.parse(X(s)).version}catch{return}}async getLatestNpmVersion(t,e){const s=this.getNpmCommand(),n=await this.applyNpmArgsHook(["view",t,"version","--json"],this.cwd),i=(await this.runCommandCapture(s.command,[...s.args,...n],{cwd:this.cwd,timeoutMs:v})).trim();if(!i)throw new Error("Empty response from npm view");const o=JSON.parse(i);if(typeof o=="string")return o;if(Array.isArray(o)){const a=o.filter(p=>typeof p=="string"&&p.length>0),l=e?Et(a,e):[...a].sort(bt)[0];if(l)return l}throw new Error("Unexpected response from npm view")}async gitHasAvailableUpdate(t){if(b())return!1;try{const e=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:v}),s=await this.getRemoteGitHead(t);return e.trim()!==s.trim()}catch{return!1}}async getRemoteGitHead(t){const e=await this.getGitUpstreamRef(t);if(e){const i=(await this.runGitRemoteCommand(t,["ls-remote","origin",e])).match(/^([0-9a-f]{40})\s+/m);if(i?.[1])return i[1]}const n=(await this.runGitRemoteCommand(t,["ls-remote","origin","HEAD"])).match(/^([0-9a-f]{40})\s+HEAD$/m);if(!n?.[1])throw new Error("Failed to determine remote HEAD");return n[1]}async getLocalGitUpdateTarget(t){try{const s=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:t,timeoutMs:v})).trim();if(!s.startsWith("origin/"))throw new Error(`Unsupported upstream remote: ${s}`);const n=s.slice(7);if(!n)throw new Error("Missing upstream branch name");return{ref:"@{upstream}",head:await this.runCommandCapture("git",["rev-parse","@{upstream}"],{cwd:t,timeoutMs:v}),fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${n}:refs/remotes/origin/${n}`]}}catch{await this.runCommand("git",["remote","set-head","origin","-a"],{cwd:t}).catch(()=>{});const e=await this.runCommandCapture("git",["rev-parse","origin/HEAD"],{cwd:t,timeoutMs:v}),n=(await this.runCommandCapture("git",["symbolic-ref","refs/remotes/origin/HEAD"],{cwd:t,timeoutMs:v}).catch(()=>"")).trim().replace(/^refs\/remotes\/origin\//,"");return n?{ref:"origin/HEAD",head:e,fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${n}:refs/remotes/origin/${n}`]}:{ref:"origin/HEAD",head:e,fetchArgs:["fetch","--prune","--no-tags","origin","+HEAD:refs/remotes/origin/HEAD"]}}}async getGitUpstreamRef(t){try{const s=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:t,timeoutMs:v})).trim();if(!s.startsWith("origin/"))return;const n=s.slice(7);return n?`refs/heads/${n}`:void 0}catch{return}}runGitRemoteCommand(t,e){return this.runCommandCapture("git",e,{cwd:t,timeoutMs:v,env:{GIT_TERMINAL_PROMPT:"0"}})}async runWithConcurrency(t,e){if(t.length===0)return[];const s=new Array(t.length);let n=0;const r=Math.max(1,Math.min(e,t.length)),i=g(async()=>{for(;;){const o=n;if(n+=1,o>=t.length)return;s[o]=await t[o]()}},"worker");return await Promise.all(Array.from({length:r},()=>i())),s}getPackageIdentity(t,e){const s=this.parseSource(t);if(s.type==="npm")return`npm:${s.name}`;if(s.type==="git")return`git:${s.host}/${s.path}`;if(e){const n=this.getBaseDirForScope(e);return`local:${this.resolvePathFromBase(s.path,n)}`}return`local:${this.resolvePath(s.path)}`}dedupePackages(t){const e=[],s=new Map;for(const n of t){const r=this.getPackageIdentity(this.getPackageSourceString(n.pkg),n.scope),i=s.get(r);if(i===void 0){s.set(r,e.length),e.push(n);continue}const o=e[i];o?.scope==="project"&&n.scope==="user"?typeof o.pkg=="object"&&o.pkg.autoload===!1&&e.push(n):n.scope==="project"&&(e[i]=n)}return e}parseNpmSpec(t){const e=t.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/);if(!e)return{name:t};const s=e[1]??t,n=e[2];return{name:s,version:n}}assertProjectTrustedForScope(t){if(t==="project"&&!this.settingsManager.isProjectTrusted())throw new Error("Project is not trusted; refusing to access project package storage")}getNpmCommand(){const t=this.settingsManager.getNpmCommand();if(!t||t.length===0)return{command:"npm",args:[]};const[e,...s]=t;if(!e)throw new Error("Invalid npmCommand: first array entry must be a non-empty command");return{command:e,args:s}}getPackageManagerName(){const t=this.getNpmCommand(),e=g(o=>I(o).replace(/\.(cmd|exe)$/i,""),"normalizeCommandName"),s=new Set(["npm","pnpm","bun"]),n=e(t.command),r=t.args.lastIndexOf("--");if(r>=0){const o=t.args[r+1];return o?e(o):n}if(s.has(n))return n;const i=[...new Set(t.args.map(e).filter(o=>s.has(o)))];if(i.length>1)throw new Error(`Ambiguous npmCommand package managers: ${i.join(", ")}`);return i[0]??n}async runNpmCommand(t,e){const s=this.getNpmCommand(),n=await this.applyNpmArgsHook(t,e?.cwd);await this.runCommand(s.command,[...s.args,...n],e)}async applyNpmArgsHook(t,e){const s=globalThis[Ut];return typeof s!="function"?t:s(t,{cwd:e,packageManager:this.getPackageManagerName()})}getGitDependencyInstallArgs(){switch(this.getPackageManagerName()){case"bun":return["install","--omit=dev","--omit=peer"];case"pnpm":return["install","--prod","--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"];case"npm":return["install","--omit=dev","--legacy-peer-deps"];default:return["install"]}}runNpmCommandSync(t){const e=this.getNpmCommand();return this.runCommandSync(e.command,[...e.args,...t])}getNpmInstallArgs(t,e){const s=this.getPackageManagerName();return s==="bun"?["install",...t,"--cwd",e,"--omit=peer"]:s==="pnpm"?["install",...t,"--prefix",e,"--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"]:["install",...t,"--prefix",e,"--legacy-peer-deps"]}async installNpm(t,e,s){const n=this.getNpmInstallRoot(e,s);this.ensureNpmProject(n),await this.runNpmCommand(this.getNpmInstallArgs([t.spec],n))}async uninstallNpm(t,e){const s=this.getNpmInstallRoot(e,!1);if(!f(s))return;const n=this.getPackageManagerName();if(n==="bun"){await this.runNpmCommand(["uninstall",t.name,"--cwd",s]);return}const r=["uninstall",t.name,"--prefix",s];n!=="pnpm"&&r.push("--legacy-peer-deps"),await this.runNpmCommand(r)}async installGit(t,e){const s=this.getGitInstallPath(t,e);if(f(s)){if(t.ref){await this.ensureGitRef(s,["fetch","origin",t.ref],"FETCH_HEAD");return}const r=await this.getLocalGitUpdateTarget(s);await this.ensureGitRef(s,r.fetchArgs,r.ref);return}const n=this.getGitInstallRoot(e);n&&this.ensureGitIgnore(n),W(w(s),{recursive:!0}),F(this.getGitUpdateMarkerPath(s),{force:!0});try{await this.runCommand("git",["clone",t.repo,s]),t.ref&&await this.runCommand("git",["checkout",t.ref],{cwd:s});const r=h(s,"package.json");f(r)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:s})}catch(r){throw F(s,{recursive:!0,force:!0}),this.pruneEmptyGitParents(s,n),r}}async updateGit(t,e){const s=this.getGitInstallPath(t,e);if(!f(s)){await this.installGit(t,e);return}if(t.ref){await this.ensureGitRef(s,["fetch","origin",t.ref],"FETCH_HEAD");return}const n=await this.getLocalGitUpdateTarget(s);await this.ensureGitRef(s,n.fetchArgs,n.ref)}hasMissingGitDependencies(t){const e=h(t,"package.json");if(!f(e))return!1;try{const s=JSON.parse(X(A(e,"utf-8")));if(!s.dependencies||typeof s.dependencies!="object"||Array.isArray(s.dependencies))return!1;const n=S(t,"node_modules");return Object.keys(s.dependencies).some(r=>{const i=S(n,r);return i.startsWith(`${n}${H}`)?!f(i):!1})}catch{return!1}}async repairMissingGitDependencies(t){this.hasMissingGitDependencies(t)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:t})}getGitUpdateMarkerPath(t){return h(w(t),`.${I(t)}.pi-update-incomplete`)}async cleanAndInstallGitDependencies(t,e){try{await this.runCommand("git",["clean","-fdx"],{cwd:t})}catch(n){throw await this.repairMissingGitDependencies(t).catch(()=>{}),n}const s=h(t,"package.json");f(s)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:t}),F(e,{force:!0})}async ensureGitRef(t,e,s){await this.runCommand("git",e,{cwd:t});const n=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:v}),r=`${s}^{commit}`,i=await this.runCommandCapture("git",["rev-parse",r],{cwd:t,timeoutMs:v}),o=this.getGitUpdateMarkerPath(t);if(n.trim()===i.trim()){f(o)?await this.cleanAndInstallGitDependencies(t,o):await this.repairMissingGitDependencies(t);return}V(o,"","utf-8"),await this.runCommand("git",["reset","--hard",r],{cwd:t}),await this.cleanAndInstallGitDependencies(t,o)}async refreshTemporaryGitSource(t,e){if(!b())try{await this.withProgress("pull",e,`Refreshing ${e}...`,async()=>{await this.updateGit(t,"temporary")})}catch{}}async removeGit(t,e){const s=this.getGitInstallPath(t,e);F(s,{recursive:!0,force:!0}),F(this.getGitUpdateMarkerPath(s),{force:!0}),this.pruneEmptyGitParents(s,this.getGitInstallRoot(e))}pruneEmptyGitParents(t,e){if(!e)return;const s=S(e);let n=w(t);for(;n.startsWith(s)&&n!==s;){if(!f(n)){n=w(n);continue}if(j(n).length>0)break;try{F(n,{recursive:!0,force:!0})}catch{break}n=w(n)}}ensureNpmProject(t){f(t)||W(t,{recursive:!0}),Dt(t),this.ensureGitIgnore(t);const e=h(t,"package.json");f(e)||V(e,JSON.stringify({name:"pi-extensions",private:!0},null,2),"utf-8")}ensureGitIgnore(t){f(t)||W(t,{recursive:!0});const e=h(t,".gitignore");f(e)||V(e,`*
|
|
1
|
+
var vt=Object.defineProperty;var g=(c,t)=>vt(c,"name",{value:t,configurable:!0});import{createHash as nt}from"node:crypto";import{chmodSync as Mt,existsSync as f,globSync as Ct,mkdirSync as W,readdirSync as j,readFileSync as A,rmSync as F,statSync as N,writeFileSync as V}from"node:fs";import{homedir as Nt}from"node:os";function z(){if(process.platform!=="linux"||Object.keys(process.env).length>0)return process.env;try{const c=A("/proc/self/environ","utf-8"),t={};for(const e of c.split("\0")){const s=e.indexOf("=");s>0&&(t[e.slice(0,s)]=e.slice(s+1))}return t}catch{return process.env}}g(z,"getEnv");import{basename as I,dirname as w,join as h,relative as k,resolve as S,sep as H}from"node:path";import G from"ignore";import{minimatch as x}from"minimatch";import{gt as rt,maxSatisfying as Et,rcompare as bt,satisfies as Rt,valid as jt,validRange as Ft}from"semver";import{CONFIG_DIR_NAME as q,getProjectPromptsDir as It,isOfficialExtensionsPackage as xt,SHARED_SKILL_CONFIG_DIRS as it}from"../config.js";import{spawnProcess as ot,spawnProcessSync as $t}from"../utils/child-process.js";import{parseGitUrl as At}from"../utils/git.js";import{isOfflineModeEnabled as b}from"../utils/offline.js";import{canonicalizePath as at,isLocalPath as Gt,markPathIgnoredByCloudSync as Dt,normalizePath as ct,resolvePath as U}from"../utils/paths.js";import{stripBom as Y}from"../utils/text.js";import{isStdoutTakenOver as Tt}from"./output-guard.js";import{findNearestPiManifest as Wt,readPiManifest as _}from"./pi-manifest.js";import{BUILTIN_PATH_PREFIX as X}from"./source-info.js";const v=1e4,lt=4,Ht=4,Ut=Symbol.for("dalcode.packageManager.npmArgsHook");function _t(c){return jt(c??"")!==null}g(_t,"isExactNpmVersion");function Lt(c){return c?Ft(c)??void 0:void 0}g(Lt,"getNpmVersionRange");function ut(c){return c.source==="builtin"?5:c.origin==="package"?4:(c.scope==="project"?0:2)+(c.source==="local"?0:1)}g(ut,"resourcePrecedenceRank");const L=["extensions","skills","prompts","themes"],Ot={extensions:/\.(ts|js)$/,skills:/\.md$/,prompts:/\.md$/,themes:/\.json$/},Bt=[".gitignore",".ignore",".fdignore"],Jt="project-packages";function y(c){return c.split(H).join("/")}g(y,"toPosixPath");function Q(){return process.env.HOME||Nt()}g(Q,"getHomeDir");function Kt(c){const t=h(c,"tmp","extensions");return W(t,{recursive:!0,mode:448}),Mt(t,448),t}g(Kt,"getExtensionTempFolder");function Vt(c,t){const e=c.trim();if(!e||e.startsWith("#")&&!e.startsWith("\\#"))return null;let s=c,n=!1;s.startsWith("!")?(n=!0,s=s.slice(1)):s.startsWith("\\!")&&(s=s.slice(1)),s.startsWith("/")&&(s=s.slice(1));const r=t?`${t}${s}`:s;return n?`!${r}`:r}g(Vt,"prefixIgnorePattern");function D(c,t,e){const s=k(e,t),n=s?`${y(s)}/`:"";for(const r of Bt){const i=h(t,r);if(f(i))try{const a=A(i,"utf-8").split(/\r?\n/).map(l=>Vt(l,n)).filter(l=>!!l);a.length>0&&c.add(a)}catch{}}}g(D,"addIgnoreRules");function zt(c){return c.startsWith("!")||c.startsWith("+")||c.startsWith("-")||c.includes("*")||c.includes("?")}g(zt,"isPattern");function Z(c){return c.startsWith("!")||c.startsWith("+")||c.startsWith("-")}g(Z,"isOverridePattern");function qt(c){return c.includes("*")||c.includes("?")}g(qt,"hasGlobPattern");function Yt(c,t){return Ct(c,{cwd:t}).map(e=>S(t,e)).filter(e=>k(t,e).split(H).every(s=>s===".."||!s.startsWith("."))).sort((e,s)=>e<s?-1:e>s?1:0)}g(Yt,"expandPackageGlob");function Xt(c){const t=[],e=[];for(const s of c)zt(s)?e.push(s):t.push(s);return{plain:t,patterns:e}}g(Xt,"splitPatterns");function pt(c,t,e=!0,s,n){const r=[];if(!f(c))return r;const i=n??c,o=s??G();D(o,c,i);try{const a=j(c,{withFileTypes:!0});for(const l of a){if(l.name.startsWith(".")||e&&l.name==="node_modules")continue;const p=h(c,l.name);let u=l.isDirectory(),m=l.isFile();if(l.isSymbolicLink())try{const R=N(p);u=R.isDirectory(),m=R.isFile()}catch{continue}const P=y(k(i,p)),d=u?`${P}/`:P;o.ignores(d)||(u?r.push(...pt(p,t,e,o,i)):m&&t.test(l.name)&&r.push(p))}}catch{}return r}g(pt,"collectFiles");function tt(c,t,e,s){const n=[];if(!f(c))return n;const r=s??c,i=e??G();D(i,c,r);try{const o=j(c,{withFileTypes:!0});for(const a of o){if(a.name!=="SKILL.md")continue;const l=h(c,a.name);let p=a.isFile();if(a.isSymbolicLink())try{p=N(l).isFile()}catch{continue}const u=y(k(r,l));if(p&&!i.ignores(u))return n.push(l),n}for(const a of o){if(a.name.startsWith(".")||a.name==="node_modules")continue;const l=h(c,a.name);let p=a.isDirectory(),u=a.isFile();if(a.isSymbolicLink())try{const d=N(l);p=d.isDirectory(),u=d.isFile()}catch{continue}const m=y(k(r,l));if(u&&a.name.endsWith(".md")&&!i.ignores(m)&&(t==="pi"&&c===r||t==="agents"&&c!==r)){n.push(l);continue}p&&(i.ignores(`${m}/`)||n.push(...tt(l,t,i,r)))}}catch{}return n}g(tt,"collectSkillEntries");function O(c,t){return tt(c,t)}g(O,"collectAutoSkillEntries");function Qt(c){let t=S(c);for(;;){if(f(h(t,".git")))return t;const e=w(t);if(e===t)return null;t=e}}g(Qt,"findGitRepoRoot");function Zt(c=Q()){return it.map(t=>h(c,t,"skills"))}g(Zt,"userSharedSkillDirs");function te(c){const t=[],e=S(c),s=Qt(e);let n=e;for(;;){for(const i of it)t.push(h(n,i,"skills"));if(s&&n===s)break;const r=w(n);if(r===n)break;n=r}return t}g(te,"collectAncestorAgentsSkillDirs");function ht(c){const t=[];if(!f(c))return t;const e=G();D(e,c,c);try{const s=j(c,{withFileTypes:!0});for(const n of s){if(n.name.startsWith(".")||n.name==="node_modules")continue;const r=h(c,n.name);let i=n.isFile();if(n.isSymbolicLink())try{i=N(r).isFile()}catch{continue}const o=y(k(c,r));e.ignores(o)||i&&n.name.endsWith(".md")&&t.push(r)}}catch{}return t}g(ht,"collectAutoPromptEntries");function ft(c){const t=[];if(!f(c))return t;const e=G();D(e,c,c);try{const s=j(c,{withFileTypes:!0});for(const n of s){if(n.name.startsWith(".")||n.name==="node_modules")continue;const r=h(c,n.name);let i=n.isFile();if(n.isSymbolicLink())try{i=N(r).isFile()}catch{continue}const o=y(k(c,r));e.ignores(o)||i&&n.name.endsWith(".json")&&t.push(r)}}catch{}return t}g(ft,"collectAutoThemeEntries");function gt(c){const t=h(c,"package.json");if(f(t)){const n=_(t);if(n?.extensions?.length){const r=[];for(const i of n.extensions){const o=S(c,i);f(o)&&r.push(o)}if(r.length>0)return r}}const e=h(c,"index.ts"),s=h(c,"index.js");return f(e)?[e]:f(s)?[s]:null}g(gt,"resolveExtensionEntries");function et(c){const t=[];if(!f(c))return t;const e=gt(c);if(e)return e;const s=G();D(s,c,c);try{const n=j(c,{withFileTypes:!0});for(const r of n){if(r.name.startsWith(".")||r.name==="node_modules")continue;const i=h(c,r.name);let o=r.isDirectory(),a=r.isFile();if(r.isSymbolicLink())try{const u=N(i);o=u.isDirectory(),a=u.isFile()}catch{continue}const l=y(k(c,i)),p=o?`${l}/`:l;if(!s.ignores(p)){if(a&&(r.name.endsWith(".ts")||r.name.endsWith(".js")))t.push(i);else if(o){const u=gt(i);u&&t.push(...u)}}}}catch{}return t}g(et,"collectAutoExtensionEntries");function B(c,t){return t==="skills"?tt(c,"pi"):t==="extensions"?et(c):pt(c,Ot[t])}g(B,"collectResourceFiles");function J(c,t,e){const s=y(k(e,c)),n=I(c),r=y(c),i=n==="SKILL.md",o=i?w(c):void 0,a=i?y(k(e,o)):void 0,l=i?I(o):void 0,p=i?y(o):void 0;return t.some(u=>{const m=y(ct(u));return x(s,m)||x(n,m)||x(r,m)?!0:i?x(a,m)||x(l,m)||x(p,m):!1})}g(J,"matchesAnyPattern");function ee(c){const t=c.startsWith("./")||c.startsWith(".\\")?c.slice(2):c;return y(ct(t))}g(ee,"normalizeExactPattern");function T(c,t,e){if(t.length===0)return!1;const s=y(k(e,c)),n=I(c),r=y(c),i=n==="SKILL.md",o=i?w(c):void 0,a=i?y(k(e,o)):void 0,l=i?y(o):void 0;return t.some(p=>{const u=ee(p);return u===s||u===r?!0:i?u===a||u===l:!1})}g(T,"matchesAnyExactPattern");function mt(c){return c.filter(t=>t.startsWith("!")||t.startsWith("+")||t.startsWith("-"))}g(mt,"getOverridePatterns");function dt(c,t,e){const s=mt(t),n=s.filter(a=>a.startsWith("!")).map(a=>a.slice(1)),r=s.filter(a=>a.startsWith("+")).map(a=>a.slice(1)),i=s.filter(a=>a.startsWith("-")).map(a=>a.slice(1));let o=!0;return n.length>0&&J(c,n,e)&&(o=!1),r.length>0&&T(c,r,e)&&(o=!0),i.length>0&&T(c,i,e)&&(o=!1),o}g(dt,"isEnabledByOverrides");function K(c,t,e){const s=[],n=[],r=[],i=[];for(const a of t)a.startsWith("+")?r.push(a.slice(1)):a.startsWith("-")?i.push(a.slice(1)):a.startsWith("!")?n.push(a.slice(1)):s.push(a);let o;if(s.length===0?o=[...c]:o=c.filter(a=>J(a,s,e)),n.length>0&&(o=o.filter(a=>!J(a,n,e))),r.length>0)for(const a of c)!o.includes(a)&&T(a,r,e)&&o.push(a);return i.length>0&&(o=o.filter(a=>!T(a,i,e))),new Set(o)}g(K,"applyPatterns");function yt(c,t,e){const s=new Map;for(const n of t){const r=n.slice(n.startsWith("+")||n.startsWith("-")||n.startsWith("!")?1:0),i=!n.startsWith("-")&&!n.startsWith("!"),o=n.startsWith("+")||n.startsWith("-");for(const a of c)(o?T(a,[r],e):J(a,[r],e))&&s.set(a,i)}return s}g(yt,"applyAutoloadDisabledPatterns");class we{static{g(this,"DefaultPackageManager")}cwd;agentDir;settingsManager;builtinExtensions;quiet;globalNpmRoot;globalNpmRootCommandKey;progressCallback;constructor(t){this.cwd=U(t.cwd),this.agentDir=U(t.agentDir),this.settingsManager=t.settingsManager,this.builtinExtensions=t.builtinExtensions??[],this.quiet=t.quiet===!0}setProgressCallback(t){this.progressCallback=t}addSourceToSettings(t,e){const s=e?.local?"project":"user",r=(s==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],i=this.normalizePackageSourceForSettings(t,s),o=g(p=>{const u=e?.resolvedCommit;return!u&&!p?i:typeof p=="string"||p===void 0?u?{source:i,resolvedCommit:u}:i:u?{...p,source:i,resolvedCommit:u}:{...p,source:i}},"toEntry"),a=r.findIndex(p=>this.packageSourcesMatch(p,t,s));if(a!==-1){const p=r[a];if(this.getPackageSourceString(p)===i&&!e?.resolvedCommit)return!1;const u=[...r];return u[a]=o(p),s==="project"?this.settingsManager.setProjectPackages(u):this.settingsManager.setPackages(u),!0}const l=[...r,o()];return s==="project"?this.settingsManager.setProjectPackages(l):this.settingsManager.setPackages(l),!0}removeSourceFromSettings(t,e){const s=e?.local?"project":"user",r=(s==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[],i=r.filter(a=>!this.packageSourcesMatch(a,t,s));return i.length!==r.length?(s==="project"?this.settingsManager.setProjectPackages(i):this.settingsManager.setPackages(i),!0):!1}getInstalledPath(t,e){const s=this.parseSource(t);if(s.type==="npm"){const n=this.getNpmInstallPath(s,e);return f(n)?n:void 0}if(s.type==="git"){const n=this.getGitReadPath(s,e);return f(n)?n:void 0}if(s.type==="local"){const n=this.getBaseDirForScope(e),r=this.resolvePathFromBase(s.path,n);return f(r)?r:void 0}}async getRegistryIntegrity(t){const e=this.parseSource(t);if(e.type!=="npm"||!e.pinned)return;const s=this.getNpmCommand(),n=await this.applyNpmArgsHook(["view",e.spec,"dist.integrity","--json"],this.cwd),i=(await this.runCommandCapture(s.command,[...s.args,...n],{cwd:this.cwd,timeoutMs:v})).trim();if(!i)return;const o=JSON.parse(i);return typeof o=="string"&&o.length>0?o:void 0}getRecordedIntegrity(t,e){const s=this.getNpmReadRoot(t,e),n=h(s,"package-lock.json");if(!f(n))return;let r;try{r=JSON.parse(Y(A(n,"utf-8")))}catch{return null}if(!r||typeof r!="object")return null;const o=r.packages?.[`node_modules/${t}`];if(!o||typeof o!="object")return null;const a=o.integrity;return typeof a=="string"&&a.length>0?a:null}readDeclaredPermissions(t){if(!t)return;const s=Wt(t)?.manifest.permissions;return s&&s.length>0?[...s]:void 0}async readGitHead(t){if(t)try{const s=(await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:v})).trim();return/^[0-9a-f]{7,40}$/i.test(s)?s:void 0}catch{return}}getStoredResolvedCommit(t,e){const s=e==="project"?this.settingsManager.getProjectSettings().packages??[]:this.settingsManager.getGlobalSettings().packages??[];for(const n of s)if(typeof n!="string"&&this.packageSourcesMatch(n,t,e))return n.resolvedCommit}emitProgress(t){this.progressCallback?.(t)}async withProgress(t,e,s,n){this.emitProgress({type:"start",action:t,source:e,message:s});try{await n(),this.emitProgress({type:"complete",action:t,source:e})}catch(r){const i=r instanceof Error?r.message:String(r);throw this.emitProgress({type:"error",action:t,source:e,message:i}),r}}async resolve(t){const e=this.createAccumulator(),s=this.settingsManager.getGlobalSettings(),n=this.settingsManager.getProjectSettings(),r=[];for(const l of n.packages??[])r.push({pkg:l,scope:"project"});for(const l of s.packages??[])r.push({pkg:l,scope:"user"});const i=this.dedupePackages(r);await this.resolvePackageSources(i,e,t);const o=this.agentDir,a=h(this.cwd,q);for(const l of L){const p=this.getTargetMap(e,l),u=s[l]??[],m=n[l]??[];this.resolveLocalEntries(m,l,p,{source:"local",scope:"project",origin:"top-level"},a),this.resolveLocalEntries(u,l,p,{source:"local",scope:"user",origin:"top-level"},o)}this.addAutoDiscoveredResources(e,s,n,o,a);for(const l of this.builtinExtensions){const p=`${X}${l}`,u=yt([p],mt(n.extensions??[]),a).get(p);this.addResource(e.extensions,p,{source:"builtin",scope:u===void 0?"user":"project",origin:"top-level"},u??dt(p,s.extensions??[],o))}return this.toResolvedPaths(e)}async resolveExtensionSources(t,e){const s=this.createAccumulator(),n=e?.temporary?"temporary":e?.local?"project":"user";for(const i of t.filter(o=>o.startsWith(X)))this.addResource(s.extensions,i,{source:"builtin",scope:n,origin:"top-level"},!0);const r=t.filter(i=>!i.startsWith(X)).map(i=>({pkg:i,scope:n}));return await this.resolvePackageSources(r,s),this.toResolvedPaths(s)}listConfiguredPackages(){const t=this.settingsManager.getGlobalSettings(),e=this.settingsManager.getProjectSettings(),s=[];for(const n of t.packages??[]){const r=typeof n=="string"?n:n.source,i=this.getInstalledPath(r,"user");s.push({source:r,scope:"user",filtered:typeof n=="object",installedPath:i,resolvedCommit:typeof n=="object"?n.resolvedCommit:void 0,permissions:this.readDeclaredPermissions(i)})}for(const n of e.packages??[]){const r=typeof n=="string"?n:n.source,i=this.getInstalledPath(r,"project");s.push({source:r,scope:"project",filtered:typeof n=="object",installedPath:i,resolvedCommit:typeof n=="object"?n.resolvedCommit:void 0,permissions:this.readDeclaredPermissions(i)})}return s}async install(t,e){const s=this.parseSource(t),n=e?.local?"project":"user";this.assertProjectTrustedForScope(n),await this.withProgress("install",t,`Installing ${t}...`,async()=>{if(s.type==="npm"){await this.installNpm(s,n,!1);return}if(s.type==="git"){await this.installGit(s,n);return}if(s.type==="local"){const r=this.resolvePath(s.path);if(!f(r))throw new Error(`Path does not exist: ${r}`);return}throw new Error(`Unsupported install source: ${t}`)})}async installAndPersist(t,e){await this.install(t,e);const s=e?.local?"project":"user",n=this.getInstalledPath(t,s),r=await this.readGitHead(n);this.addSourceToSettings(t,{...e,resolvedCommit:r})}async remove(t,e){const s=this.parseSource(t),n=e?.local?"project":"user";this.assertProjectTrustedForScope(n),await this.withProgress("remove",t,`Removing ${t}...`,async()=>{if(s.type==="npm"){await this.uninstallNpm(s,n);return}if(s.type==="git"){await this.removeGit(s,n);return}if(s.type!=="local")throw new Error(`Unsupported remove source: ${t}`)})}async removeAndPersist(t,e){return await this.remove(t,e),this.removeSourceFromSettings(t,e)}async update(t,e){const s=e?.latest===!0,n=this.settingsManager.getGlobalSettings(),r=this.settingsManager.getProjectSettings(),i=t?this.getPackageIdentity(t):void 0;let o=!1;const a=[];for(const l of n.packages??[]){const p=typeof l=="string"?l:l.source;i&&this.getPackageIdentity(p,"user")!==i||(o=!0,a.push({source:p,scope:"user"}))}for(const l of r.packages??[]){const p=typeof l=="string"?l:l.source;i&&this.getPackageIdentity(p,"project")!==i||(o=!0,a.push({source:p,scope:"project"}))}if(t&&!o)throw new Error(this.buildNoMatchingPackageMessage(t,[...n.packages??[],...r.packages??[]]));await this.updateConfiguredSources(a,s)}async updateConfiguredSources(t,e=!1){if(b()||t.length===0)return;const s=[],n=[];for(const p of t){const u=this.parseSource(p.source);if(u.type==="npm")u.pinned||s.push({...p,parsed:u});else if(u.type==="git"){const m=this.getStoredResolvedCommit(p.source,p.scope);if(!u.ref&&m&&!e)continue;n.push({...p,parsed:u})}}const r=s.map(p=>async()=>({entry:p,shouldUpdate:await this.shouldUpdateNpmSource(p.parsed,p.scope)})),i=await this.runWithConcurrency(r,lt),o=[],a=[];for(const p of i)p.shouldUpdate&&(p.entry.scope==="user"?o.push(p.entry):a.push(p.entry));const l=[];if(o.length>0&&l.push(this.updateNpmBatch(o,"user")),a.length>0&&l.push(this.updateNpmBatch(a,"project")),n.length>0){const p=n.map(u=>async()=>this.withProgress("update",u.source,`Updating ${u.source}...`,async()=>{if(await this.updateGit(u.parsed,u.scope),!this.getStoredResolvedCommit(u.source,u.scope))return;const P=this.getInstalledPath(u.source,u.scope),d=await this.readGitHead(P);d&&this.addSourceToSettings(u.source,{local:u.scope==="project",resolvedCommit:d})}));l.push(this.runWithConcurrency(p,Ht).then(()=>{}))}await Promise.all(l)}async shouldUpdateNpmSource(t,e){const s=this.getManagedNpmInstallPath(t,e),n=f(s)?this.getInstalledNpmVersion(s):void 0;if(!n)return!0;try{const r=await this.getLatestNpmVersion(t.version?t.spec:t.name,t.range);return rt(r,n)}catch{return!0}}async updateNpmBatch(t,e){if(t.length===0)return;const s=t.length===1?t[0].source:`${e} npm packages`,n=t.length===1?`Updating ${t[0].source}...`:`Updating ${e} npm packages...`,r=t.map(i=>i.parsed.version?i.parsed.spec:`${i.parsed.name}@latest`);await this.withProgress("update",s,n,async()=>{await this.installNpmBatch(r,e)})}async installNpmBatch(t,e){const s=this.getNpmInstallRoot(e,!1);this.ensureNpmProject(s),await this.runNpmCommand(this.getNpmInstallArgs(t,s))}async checkForAvailableUpdates(){if(b())return[];const t=this.settingsManager.getGlobalSettings(),e=this.settingsManager.getProjectSettings(),s=[];for(const o of e.packages??[])s.push({pkg:o,scope:"project"});for(const o of t.packages??[])s.push({pkg:o,scope:"user"});const r=this.dedupePackages(s).filter(o=>o.scope!=="temporary").map(o=>async()=>{const a=typeof o.pkg=="string"?o.pkg:o.pkg.source,l=this.parseSource(a);if(l.type==="local"||l.pinned)return;if(l.type==="npm"){const m=this.getNpmInstallPath(l,o.scope);return!f(m)||!await this.npmHasAvailableUpdate(l,m)?void 0:{source:a,displayName:l.name,type:"npm",scope:o.scope}}const p=this.getGitReadPath(l,o.scope);if(!(!f(p)||!await this.gitHasAvailableUpdate(p)))return{source:a,displayName:`${l.host}/${l.path}`,type:"git",scope:o.scope}});return(await this.runWithConcurrency(r,lt)).filter(o=>o!==void 0)}async resolvePackageSources(t,e,s){for(const{pkg:n,scope:r}of t){const i=typeof n=="string"?n:n.source,o=typeof n=="object"?n:void 0,a=this.findAutoloadDeltaBase(n,r,t),l=a?.source??i,p=a?.scope??r,u=this.parseSource(l),m={source:i,scope:r,origin:"package"};if(u.type==="local"){const d=this.getBaseDirForScope(p);this.resolveLocalExtensionSource(u,e,o,m,d);continue}const P=g(async()=>{if(b())return!1;if(!s)return await this.installParsedSource(u,p),!0;const d=await s(l);if(d==="skip")return!1;if(d==="error")throw new Error(`Missing source: ${l}`);return await this.installParsedSource(u,p),!0},"installMissing");if(u.type==="npm"){let d=this.getNpmInstallPath(u,p);if(!f(d)||!await this.installedNpmMatchesConfiguredVersion(u,d)){if(!await P())continue;d=this.getNpmInstallPath(u,p)}m.baseDir=d,m.packageRoot=d,this.collectPackageResources(d,e,o,m);continue}if(u.type==="git"){const d=this.getGitReadPath(u,p);if(f(d))p==="temporary"&&!u.pinned&&!b()&&await this.refreshTemporaryGitSource(u,l);else if(!await P())continue;m.baseDir=d,m.packageRoot=d,this.collectPackageResources(d,e,o,m)}}}findAutoloadDeltaBase(t,e,s){if(e!=="project"||typeof t!="object"||t.autoload!==!1)return;const n=this.getPackageIdentity(t.source,e),r=s.find(i=>i.scope==="user"&&this.getPackageIdentity(this.getPackageSourceString(i.pkg),"user")===n);return r?{source:this.getPackageSourceString(r.pkg),scope:"user"}:void 0}resolveLocalExtensionSource(t,e,s,n,r){const i=this.resolvePathFromBase(t.path,r);if(f(i))try{const o=N(i);if(o.isFile()){n.baseDir=w(i),this.addResource(e.extensions,i,n,!0);return}o.isDirectory()&&(n.baseDir=i,n.packageRoot=i,this.collectPackageResources(i,e,s,n)||this.addResource(e.extensions,i,n,!0))}catch{return}}async installParsedSource(t,e){if(t.type==="npm"){await this.installNpm(t,e,e==="temporary");return}if(t.type==="git"){await this.installGit(t,e);return}}getPackageSourceString(t){return typeof t=="string"?t:t.source}getSourceMatchKeyForInput(t){const e=this.parseSource(t);return e.type==="npm"?`npm:${e.name}`:e.type==="git"?`git:${e.host}/${e.path}`:`local:${this.resolvePath(e.path)}`}getSourceMatchKeyForSettings(t,e){const s=this.parseSource(t);if(s.type==="npm")return`npm:${s.name}`;if(s.type==="git")return`git:${s.host}/${s.path}`;const n=this.getBaseDirForScope(e);return`local:${this.resolvePathFromBase(s.path,n)}`}buildNoMatchingPackageMessage(t,e){const s=this.findSuggestedConfiguredSource(t,e);return s?`No matching package found for ${t}. Did you mean ${s}?`:`No matching package found for ${t}`}findSuggestedConfiguredSource(t,e){const s=t.trim(),n=new Set;for(const r of e){const i=this.getPackageSourceString(r),o=this.parseSource(i);if(o.type==="npm"){(s===o.name||s===o.spec)&&n.add(i);continue}if(o.type==="git"){const a=`${o.host}/${o.path}`,l=o.ref?`${a}@${o.ref}`:void 0;(s===a||l&&s===l)&&n.add(i)}}return n.values().next().value}packageSourcesMatch(t,e,s){const n=this.getSourceMatchKeyForSettings(this.getPackageSourceString(t),s),r=this.getSourceMatchKeyForInput(e);return n===r}normalizePackageSourceForSettings(t,e){const s=this.parseSource(t);if(s.type!=="local")return t;const n=this.getBaseDirForScope(e),r=this.resolvePath(s.path);return k(n,r)||"."}parseSource(t){if(t.startsWith("npm:")){const s=t.slice(4).trim(),{name:n,version:r}=this.parseNpmSpec(s);return{type:"npm",spec:s,name:n,version:r,range:Lt(r),pinned:_t(r)}}if(Gt(t))return{type:"local",path:t};const e=At(t);return e||{type:"local",path:t}}async installedNpmMatchesConfiguredVersion(t,e){const s=this.getInstalledNpmVersion(e);return s?t.range?Rt(s,t.range):!0:!1}async npmHasAvailableUpdate(t,e){if(b())return!1;const s=this.getInstalledNpmVersion(e);if(!s)return!1;try{const n=await this.getLatestNpmVersion(t.version?t.spec:t.name,t.range);return rt(n,s)}catch{return!1}}getInstalledNpmVersion(t){const e=h(t,"package.json");if(f(e))try{const s=A(e,"utf-8");return JSON.parse(Y(s)).version}catch{return}}async getLatestNpmVersion(t,e){const s=this.getNpmCommand(),n=await this.applyNpmArgsHook(["view",t,"version","--json"],this.cwd),i=(await this.runCommandCapture(s.command,[...s.args,...n],{cwd:this.cwd,timeoutMs:v})).trim();if(!i)throw new Error("Empty response from npm view");const o=JSON.parse(i);if(typeof o=="string")return o;if(Array.isArray(o)){const a=o.filter(p=>typeof p=="string"&&p.length>0),l=e?Et(a,e):[...a].sort(bt)[0];if(l)return l}throw new Error("Unexpected response from npm view")}async gitHasAvailableUpdate(t){if(b())return!1;try{const e=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:v}),s=await this.getRemoteGitHead(t);return e.trim()!==s.trim()}catch{return!1}}async getRemoteGitHead(t){const e=await this.getGitUpstreamRef(t);if(e){const i=(await this.runGitRemoteCommand(t,["ls-remote","origin",e])).match(/^([0-9a-f]{40})\s+/m);if(i?.[1])return i[1]}const n=(await this.runGitRemoteCommand(t,["ls-remote","origin","HEAD"])).match(/^([0-9a-f]{40})\s+HEAD$/m);if(!n?.[1])throw new Error("Failed to determine remote HEAD");return n[1]}async getLocalGitUpdateTarget(t){try{const s=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:t,timeoutMs:v})).trim();if(!s.startsWith("origin/"))throw new Error(`Unsupported upstream remote: ${s}`);const n=s.slice(7);if(!n)throw new Error("Missing upstream branch name");return{ref:"@{upstream}",head:await this.runCommandCapture("git",["rev-parse","@{upstream}"],{cwd:t,timeoutMs:v}),fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${n}:refs/remotes/origin/${n}`]}}catch{await this.runCommand("git",["remote","set-head","origin","-a"],{cwd:t}).catch(()=>{});const e=await this.runCommandCapture("git",["rev-parse","origin/HEAD"],{cwd:t,timeoutMs:v}),n=(await this.runCommandCapture("git",["symbolic-ref","refs/remotes/origin/HEAD"],{cwd:t,timeoutMs:v}).catch(()=>"")).trim().replace(/^refs\/remotes\/origin\//,"");return n?{ref:"origin/HEAD",head:e,fetchArgs:["fetch","--prune","--no-tags","origin",`+refs/heads/${n}:refs/remotes/origin/${n}`]}:{ref:"origin/HEAD",head:e,fetchArgs:["fetch","--prune","--no-tags","origin","+HEAD:refs/remotes/origin/HEAD"]}}}async getGitUpstreamRef(t){try{const s=(await this.runCommandCapture("git",["rev-parse","--abbrev-ref","@{upstream}"],{cwd:t,timeoutMs:v})).trim();if(!s.startsWith("origin/"))return;const n=s.slice(7);return n?`refs/heads/${n}`:void 0}catch{return}}runGitRemoteCommand(t,e){return this.runCommandCapture("git",e,{cwd:t,timeoutMs:v,env:{GIT_TERMINAL_PROMPT:"0"}})}async runWithConcurrency(t,e){if(t.length===0)return[];const s=new Array(t.length);let n=0;const r=Math.max(1,Math.min(e,t.length)),i=g(async()=>{for(;;){const o=n;if(n+=1,o>=t.length)return;s[o]=await t[o]()}},"worker");return await Promise.all(Array.from({length:r},()=>i())),s}getPackageIdentity(t,e){const s=this.parseSource(t);if(s.type==="npm")return`npm:${s.name}`;if(s.type==="git")return`git:${s.host}/${s.path}`;if(e){const n=this.getBaseDirForScope(e);return`local:${this.resolvePathFromBase(s.path,n)}`}return`local:${this.resolvePath(s.path)}`}dedupePackages(t){const e=[],s=new Map;for(const n of t){const r=this.getPackageIdentity(this.getPackageSourceString(n.pkg),n.scope),i=s.get(r);if(i===void 0){s.set(r,e.length),e.push(n);continue}const o=e[i];o?.scope==="project"&&n.scope==="user"?typeof o.pkg=="object"&&o.pkg.autoload===!1&&e.push(n):n.scope==="project"&&(e[i]=n)}return e}parseNpmSpec(t){const e=t.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/);if(!e)return{name:t};const s=e[1]??t,n=e[2];return{name:s,version:n}}assertProjectTrustedForScope(t){if(t==="project"&&!this.settingsManager.isProjectTrusted())throw new Error("Project is not trusted; refusing to access project package storage")}getNpmCommand(){const t=this.settingsManager.getNpmCommand();if(!t||t.length===0)return{command:"npm",args:[]};const[e,...s]=t;if(!e)throw new Error("Invalid npmCommand: first array entry must be a non-empty command");return{command:e,args:s}}getPackageManagerName(){const t=this.getNpmCommand(),e=g(o=>I(o).replace(/\.(cmd|exe)$/i,""),"normalizeCommandName"),s=new Set(["npm","pnpm","bun"]),n=e(t.command),r=t.args.lastIndexOf("--");if(r>=0){const o=t.args[r+1];return o?e(o):n}if(s.has(n))return n;const i=[...new Set(t.args.map(e).filter(o=>s.has(o)))];if(i.length>1)throw new Error(`Ambiguous npmCommand package managers: ${i.join(", ")}`);return i[0]??n}async runNpmCommand(t,e){const s=this.getNpmCommand(),n=await this.applyNpmArgsHook(t,e?.cwd);await this.runCommand(s.command,[...s.args,...n],e)}async applyNpmArgsHook(t,e){const s=globalThis[Ut];return typeof s!="function"?t:s(t,{cwd:e,packageManager:this.getPackageManagerName()})}getGitDependencyInstallArgs(){switch(this.getPackageManagerName()){case"bun":return["install","--omit=dev","--omit=peer"];case"pnpm":return["install","--prod","--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"];case"npm":return["install","--omit=dev","--legacy-peer-deps"];default:return["install"]}}runNpmCommandSync(t){const e=this.getNpmCommand();return this.runCommandSync(e.command,[...e.args,...t])}getNpmInstallArgs(t,e){const s=this.getPackageManagerName();return s==="bun"?["install",...t,"--cwd",e,"--omit=peer"]:s==="pnpm"?["install",...t,"--prefix",e,"--config.auto-install-peers=false","--config.strict-peer-dependencies=false","--config.strict-dep-builds=false"]:["install",...t,"--prefix",e,"--legacy-peer-deps"]}async installNpm(t,e,s){const n=this.getNpmInstallRoot(e,s);this.ensureNpmProject(n),await this.runNpmCommand(this.getNpmInstallArgs([t.spec],n))}async uninstallNpm(t,e){const s=this.getNpmInstallRoot(e,!1);if(!f(s))return;const n=this.getPackageManagerName();if(n==="bun"){await this.runNpmCommand(["uninstall",t.name,"--cwd",s]);return}const r=["uninstall",t.name,"--prefix",s];n!=="pnpm"&&r.push("--legacy-peer-deps"),await this.runNpmCommand(r)}async installGit(t,e){const s=this.getGitInstallPath(t,e);if(f(s)){if(t.ref){await this.ensureGitRef(s,["fetch","origin",t.ref],"FETCH_HEAD");return}const r=await this.getLocalGitUpdateTarget(s);await this.ensureGitRef(s,r.fetchArgs,r.ref);return}const n=this.getGitInstallRoot(e);n&&this.ensureGitIgnore(n),W(w(s),{recursive:!0}),F(this.getGitUpdateMarkerPath(s),{force:!0});try{await this.runCommand("git",["clone",t.repo,s]),t.ref&&await this.runCommand("git",["checkout",t.ref],{cwd:s});const r=h(s,"package.json");f(r)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:s})}catch(r){throw F(s,{recursive:!0,force:!0}),this.pruneEmptyGitParents(s,n),r}}async updateGit(t,e){const s=this.getGitInstallPath(t,e);if(!f(s)){await this.installGit(t,e);return}if(t.ref){await this.ensureGitRef(s,["fetch","origin",t.ref],"FETCH_HEAD");return}const n=await this.getLocalGitUpdateTarget(s);await this.ensureGitRef(s,n.fetchArgs,n.ref)}hasMissingGitDependencies(t){const e=h(t,"package.json");if(!f(e))return!1;try{const s=JSON.parse(Y(A(e,"utf-8")));if(!s.dependencies||typeof s.dependencies!="object"||Array.isArray(s.dependencies))return!1;const n=S(t,"node_modules");return Object.keys(s.dependencies).some(r=>{const i=S(n,r);return i.startsWith(`${n}${H}`)?!f(i):!1})}catch{return!1}}async repairMissingGitDependencies(t){this.hasMissingGitDependencies(t)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:t})}getGitUpdateMarkerPath(t){return h(w(t),`.${I(t)}.pi-update-incomplete`)}async cleanAndInstallGitDependencies(t,e){try{await this.runCommand("git",["clean","-fdx"],{cwd:t})}catch(n){throw await this.repairMissingGitDependencies(t).catch(()=>{}),n}const s=h(t,"package.json");f(s)&&await this.runNpmCommand(this.getGitDependencyInstallArgs(),{cwd:t}),F(e,{force:!0})}async ensureGitRef(t,e,s){await this.runCommand("git",e,{cwd:t});const n=await this.runCommandCapture("git",["rev-parse","HEAD"],{cwd:t,timeoutMs:v}),r=`${s}^{commit}`,i=await this.runCommandCapture("git",["rev-parse",r],{cwd:t,timeoutMs:v}),o=this.getGitUpdateMarkerPath(t);if(n.trim()===i.trim()){f(o)?await this.cleanAndInstallGitDependencies(t,o):await this.repairMissingGitDependencies(t);return}V(o,"","utf-8"),await this.runCommand("git",["reset","--hard",r],{cwd:t}),await this.cleanAndInstallGitDependencies(t,o)}async refreshTemporaryGitSource(t,e){if(!b())try{await this.withProgress("pull",e,`Refreshing ${e}...`,async()=>{await this.updateGit(t,"temporary")})}catch{}}async removeGit(t,e){const s=this.getGitInstallPath(t,e);F(s,{recursive:!0,force:!0}),F(this.getGitUpdateMarkerPath(s),{force:!0}),this.pruneEmptyGitParents(s,this.getGitInstallRoot(e))}pruneEmptyGitParents(t,e){if(!e)return;const s=S(e);let n=w(t);for(;n.startsWith(s)&&n!==s;){if(!f(n)){n=w(n);continue}if(j(n).length>0)break;try{F(n,{recursive:!0,force:!0})}catch{break}n=w(n)}}ensureNpmProject(t){f(t)||W(t,{recursive:!0}),Dt(t),this.ensureGitIgnore(t);const e=h(t,"package.json");f(e)||V(e,JSON.stringify({name:"pi-extensions",private:!0},null,2),"utf-8")}ensureGitIgnore(t){f(t)||W(t,{recursive:!0});const e=h(t,".gitignore");f(e)||V(e,`*
|
|
2
2
|
!.gitignore
|
|
3
|
-
`,"utf-8")}getProjectInstallBase(){const t=at(S(this.cwd)),e=nt("sha256").update(t).digest("hex").slice(0,16),s=I(t).replace(/[^\w.-]/g,"_").slice(0,40)||"project";return h(this.agentDir,Jt,`${s}-${e}`)}getLegacyProjectInstallRoot(t){return h(this.cwd,
|
|
3
|
+
`,"utf-8")}getProjectInstallBase(){const t=at(S(this.cwd)),e=nt("sha256").update(t).digest("hex").slice(0,16),s=I(t).replace(/[^\w.-]/g,"_").slice(0,40)||"project";return h(this.agentDir,Jt,`${s}-${e}`)}getLegacyProjectInstallRoot(t){return h(this.cwd,q,t)}getNpmInstallRoot(t,e){return e?this.getTemporaryDir("npm"):t==="project"?(this.assertProjectTrustedForScope(t),h(this.getProjectInstallBase(),"npm")):h(this.agentDir,"npm")}getNpmReadRoot(t,e){const s=this.getNpmInstallRoot(e,!1);if(e!=="project")return s;const n=this.getLegacyProjectInstallRoot("npm");return!f(h(s,"node_modules",t))&&f(h(n,"node_modules",t))?n:s}getGlobalNpmRoot(){const t=this.getNpmCommand(),e=[t.command,...t.args].join("\0");if(this.globalNpmRoot&&this.globalNpmRootCommandKey===e)return this.globalNpmRoot;if(this.getPackageManagerName()==="bun"){const s=this.runNpmCommandSync(["pm","bin","-g"]).trim();this.globalNpmRoot=h(w(s),"install","global","node_modules")}else this.globalNpmRoot=this.runNpmCommandSync(["root","-g"]).trim();return this.globalNpmRootCommandKey=e,this.globalNpmRoot}getPnpmGlobalPackagePath(t){if(this.getPackageManagerName()!=="pnpm")return;const e=this.runNpmCommandSync(["list","-g","--depth","0","--json"]),s=JSON.parse(e);for(const n of s){const r=n.dependencies?.[t]?.path;if(r)return r}}getManagedNpmInstallPath(t,e){return e==="temporary"?h(this.getTemporaryDir("npm"),"node_modules",t.name):e==="project"?h(this.getNpmReadRoot(t.name,e),"node_modules",t.name):h(this.agentDir,"npm","node_modules",t.name)}getLegacyGlobalNpmInstallPath(t){try{return this.getPnpmGlobalPackagePath(t.name)??h(this.getGlobalNpmRoot(),t.name)}catch{return}}getNpmInstallPath(t,e){const s=this.getManagedNpmInstallPath(t,e);if(e!=="user"||f(s))return s;const n=this.getLegacyGlobalNpmInstallPath(t);return n&&f(n)?n:s}getGitInstallPath(t,e){if(e==="temporary")return this.getTemporaryDir(`git-${t.host}`,t.path,t.ref);const s=this.getGitInstallRoot(e);if(!s)throw new Error("Missing git install root");return this.resolveManagedPath(s,t.host,t.path)}getGitReadPath(t,e){const s=this.getGitInstallPath(t,e);if(e!=="project"||f(s))return s;const n=this.resolveManagedPath(this.getLegacyProjectInstallRoot("git"),t.host,t.path);return f(n)?n:s}getGitInstallRoot(t){if(t!=="temporary")return t==="project"?(this.assertProjectTrustedForScope(t),h(this.getProjectInstallBase(),"git")):h(this.agentDir,"git")}getTemporaryDir(t,e,s){const n=this.resolveManagedPath(Kt(this.agentDir),t),r=nt("sha256").update(`${t}-${e??""}${s?`@${s}`:""}`).digest("hex").slice(0,8);return this.resolveManagedPath(n,r,e??"")}resolveManagedPath(t,...e){const s=S(t),n=S(s,...e);if(n!==s&&!n.startsWith(`${s}${H}`))throw new Error(`Refusing to use path outside package install root: ${n}`);return n}getBaseDirForScope(t){return t==="project"?(this.assertProjectTrustedForScope(t),h(this.cwd,q)):t==="user"?this.agentDir:this.cwd}resolvePath(t){return U(t,this.cwd,{homeDir:Q(),trim:!0})}resolvePathFromBase(t,e){return U(t,e,{homeDir:Q(),trim:!0})}collectPackageResources(t,e,s,n){if(xt(t))return!0;if(s){for(const o of L){const a=s[o],l=this.getTargetMap(e,o);s.autoload===!1?this.applyPackageDeltaFilter(t,a??[],o,l,n):a!==void 0?this.applyPackageFilter(t,a,o,l,n):this.collectDefaultResources(t,o,l,n)}return!0}const r=_(h(t,"package.json"));if(r){for(const o of L){const a=r[o];this.addManifestEntries(a,t,o,this.getTargetMap(e,o),n)}return!0}let i=!1;for(const o of L){const a=h(t,o);if(f(a)){const l=B(a,o);for(const p of l)this.addResource(this.getTargetMap(e,o),p,n,!0);i=!0}}return i}collectDefaultResources(t,e,s,n){const i=_(h(t,"package.json"))?.[e];if(i){this.addManifestEntries(i,t,e,s,n);return}const o=h(t,e);if(f(o)){const a=B(o,e);for(const l of a)this.addResource(s,l,n,!0)}}applyPackageFilter(t,e,s,n,r){const{allFiles:i}=this.collectManifestFiles(t,s);if(e.length===0){for(const a of i)this.addResource(n,a,r,!1);return}const o=K(i,e,t);for(const a of i){const l=o.has(a);this.addResource(n,a,r,l)}}applyPackageDeltaFilter(t,e,s,n,r){if(e.length===0)return;const{allFiles:i}=this.collectManifestFiles(t,s),o=yt(i,e,t);for(const[a,l]of o)this.addResource(n,a,r,l)}collectManifestFiles(t,e){const n=_(h(t,"package.json"))?.[e];if(n&&n.length>0){const o=this.collectFilesFromManifestEntries(n,t,e),a=n.filter(Z),l=a.length>0?K(o,a,t):new Set(o);return{allFiles:Array.from(l),enabledByManifest:l}}const r=h(t,e);if(!f(r))return{allFiles:[],enabledByManifest:new Set};const i=B(r,e);return{allFiles:i,enabledByManifest:new Set(i)}}addManifestEntries(t,e,s,n,r){if(!t)return;const i=this.collectFilesFromManifestEntries(t,e,s),o=t.filter(Z),a=K(i,o,e);for(const l of i)a.has(l)&&this.addResource(n,l,r,!0)}collectFilesFromManifestEntries(t,e,s){const r=t.filter(i=>!Z(i)).flatMap(i=>qt(i)?Yt(i,e):[S(e,i)]);return this.collectFilesFromPaths(r,s)}resolveLocalEntries(t,e,s,n,r){if(t.length===0)return;const{plain:i,patterns:o}=Xt(t),a=i.map(u=>this.resolvePathFromBase(u,r)),l=this.collectFilesFromPaths(a,e),p=K(l,o,r);for(const u of l)this.addResource(s,u,n,p.has(u))}addAutoDiscoveredResources(t,e,s,n,r){const i={source:"auto",scope:"user",origin:"top-level",baseDir:n},o={source:"auto",scope:"project",origin:"top-level",baseDir:r},a={extensions:e.extensions??[],skills:e.skills??[],prompts:e.prompts??[],themes:e.themes??[]},l={extensions:s.extensions??[],skills:s.skills??[],prompts:s.prompts??[],themes:s.themes??[]},p={extensions:h(n,"extensions"),skills:h(n,"skills"),prompts:h(n,"prompts"),themes:h(n,"themes")},u={extensions:h(r,"extensions"),skills:h(r,"skills"),prompts:It(r),themes:h(r,"themes")},m=Zt(),P=new Set(m.map(C=>S(C))),d=this.settingsManager.isProjectTrusted(),R=d?te(this.cwd).filter(C=>!P.has(S(C))):[],M=g((C,E,$,Pt,wt)=>{const kt=this.getTargetMap(t,C);for(const st of E){const St=dt(st,Pt,wt);this.addResource(kt,st,$,St)}},"addResources");d&&(M("extensions",et(u.extensions),o,l.extensions,r),M("skills",O(u.skills,"pi"),o,l.skills,r));for(const C of R){const E=w(C),$={...o,baseDir:E};M("skills",O(C,"agents"),$,l.skills,E)}d&&(M("prompts",ht(u.prompts),o,l.prompts,r),M("themes",ft(u.themes),o,l.themes,r)),M("extensions",et(p.extensions),i,a.extensions,n),M("skills",O(p.skills,"pi"),i,a.skills,n);for(const C of m){const E=w(C),$={...i,baseDir:E};M("skills",O(C,"agents"),$,a.skills,E)}M("prompts",ht(p.prompts),i,a.prompts,n),M("themes",ft(p.themes),i,a.themes,n)}collectFilesFromPaths(t,e){const s=[];for(const n of t)if(f(n))try{const r=N(n);r.isFile()?s.push(n):r.isDirectory()&&s.push(...B(n,e))}catch{}return s}getTargetMap(t,e){switch(e){case"extensions":return t.extensions;case"skills":return t.skills;case"prompts":return t.prompts;case"themes":return t.themes;default:throw new Error(`Unknown resource type: ${e}`)}}addResource(t,e,s,n){e&&(t.has(e)||t.set(e,{metadata:s,enabled:n}))}createAccumulator(){return{extensions:new Map,skills:new Map,prompts:new Map,themes:new Map}}toResolvedPaths(t){const e=g(s=>{const n=Array.from(s.entries()).map(([i,{metadata:o,enabled:a}])=>({path:i,enabled:a,metadata:o}));n.sort((i,o)=>ut(i.metadata)-ut(o.metadata));const r=new Set;return n.filter(i=>{const o=at(i.path);return r.has(o)?!1:(r.add(o),!0)})},"mapToResolved");return{extensions:e(t.extensions),skills:e(t.skills),prompts:e(t.prompts),themes:e(t.themes)}}spawnCommand(t,e,s){const n=z();return ot(t,e,{cwd:s?.cwd,stdio:this.quiet?"ignore":Tt()?["ignore",2,2]:"inherit",env:n})}spawnCaptureCommand(t,e,s){const n=z(),r=s?.env?{...n,...s.env}:n;return ot(t,e,{cwd:s?.cwd,stdio:["ignore","pipe","pipe"],env:r})}runCommandCapture(t,e,s){return new Promise((n,r)=>{const i=this.spawnCaptureCommand(t,e,s);let o="",a="",l=!1;const p=typeof s?.timeoutMs=="number"?setTimeout(()=>{l=!0,i.kill()},s.timeoutMs):void 0;i.stdout?.on("data",u=>{o+=u.toString()}),i.stderr?.on("data",u=>{a+=u.toString()}),i.once("error",u=>{p&&clearTimeout(p),r(u)}),i.once("close",(u,m)=>{if(p&&clearTimeout(p),l){r(new Error(`${t} ${e.join(" ")} timed out after ${s?.timeoutMs}ms`));return}if(u===0){n(o.trim());return}const P=u===null?`signal ${m??"unknown"}`:`code ${u}`;r(new Error(`${t} ${e.join(" ")} failed with ${P}: ${a||o}`))})})}runCommand(t,e,s){return new Promise((n,r)=>{const i=this.spawnCommand(t,e,s);i.on("error",r),i.on("exit",o=>{o===0?n():r(new Error(`${t} ${e.join(" ")} failed with code ${o}`))})})}runCommandSync(t,e){const s=z(),n=$t(t,e,{stdio:["ignore","pipe","pipe"],encoding:"utf-8",env:s});if(n.error||n.status!==0)throw new Error(`Failed to run ${t} ${e.join(" ")}: ${n.error?.message||n.stderr||n.stdout}`);return(n.stdout||n.stderr||"").trim()}}export{we as DefaultPackageManager,Ut as NPM_ARGS_HOOK_SLOT,Jt as PROJECT_PACKAGES_DIR_NAME,Kt as getExtensionTempFolder};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var c=Object.defineProperty;var n=(e,r)=>c(e,"name",{value:r,configurable:!0});import{isInstallTelemetryEnabled as d}from"./telemetry.js";const s="openrouter.ai",f="integrate.api.nvidia.com",l="api.cloudflare.com",p="gateway.ai.cloudflare.com",O="opencode.ai";function t(e,r){try{return new URL(e).hostname===r}catch{return!1}}n(t,"matchesHost");function g(e){return e.provider==="openrouter"||e.baseUrl.includes(s)}n(g,"isOpenRouterModel");function b(e){return e.provider==="nvidia"||t(e.baseUrl,f)}n(b,"isNvidiaNimModel");function T(e){return e.provider==="cloudflare-workers-ai"||e.provider==="cloudflare-ai-gateway"||t(e.baseUrl,l)||t(e.baseUrl,p)}n(T,"isCloudflareModel");function v(e,r){if(d(r)){if(g(e))return{"HTTP-Referer":"https://deepailab.ai","X-OpenRouter-Title":"dal","X-OpenRouter-Categories":"cli-agent"};if(b(e))return{"X-BILLING-INVOKE-ORIGIN":"dal"};if(T(e))return{"User-Agent":"dal-coding-agent"}}}n(v,"getDefaultAttributionHeaders");function A(e,r){if(r&&!(e.provider!=="opencode"&&e.provider!=="opencode-go"&&!t(e.baseUrl,O)))return{"x-opencode-session":r,"x-opencode-client":"dal"}}n(A,"getSessionHeaders");function R(e,r,a,...u){const i={...A(e,a),...v(e,r)};for(const o of u)o&&Object.assign(i,o);return Object.keys(i).length>0?i:void 0}n(R,"mergeProviderAttributionHeaders");export{R as mergeProviderAttributionHeaders};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type AnyModel, type Api, type AssistantMessageEventStream, type ClassifierApi, type ImageApi, type Model, type OAuthCredentials, type OAuthLoginCallbacks, type Provider, type ProviderClassifier, type ProviderHeaders, type ProviderImages, type RefreshModelsContext, type SimpleStreamOptions, type TranscriptContext } from "@earendil-works/pi-ai";
|
|
1
|
+
import { type AnyModel, type Api, type AssistantMessageEventStream, type ClassifierApi, type ClassifierModel, type ImageApi, type Model, type OAuthCredentials, type OAuthLoginCallbacks, type Provider, type ProviderClassifier, type ProviderHeaders, type ProviderImages, type RefreshModelsContext, type SimpleStreamOptions, type TranscriptContext } from "@earendil-works/pi-ai";
|
|
2
2
|
import type { ModelConfig, ModelsJsonProvider } from "./model-config.ts";
|
|
3
3
|
import { clearConfigValueCache } from "./resolve-config-value.ts";
|
|
4
4
|
export interface ExtensionOAuthConfig {
|
|
@@ -41,6 +41,7 @@ export interface ProviderClassifierModelConfig extends ProviderModelConfigBase {
|
|
|
41
41
|
type: "classifier";
|
|
42
42
|
api?: ClassifierApi;
|
|
43
43
|
contextWindow: number;
|
|
44
|
+
compat?: ClassifierModel<ClassifierApi>["compat"];
|
|
44
45
|
}
|
|
45
46
|
export type ProviderModelConfig = ProviderChatModelConfig | ProviderImageModelConfig | ProviderClassifierModelConfig;
|
|
46
47
|
export interface ProviderConfigInput {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var B=Object.defineProperty;var i=(r,e)=>B(r,"name",{value:e,configurable:!0});import{isModelType as y,lazyStream as V}from"@earendil-works/pi-ai";import{getApiProvider as q}from"@earendil-works/pi-ai/compat";import{classifierErrorResult as N,imageErrorResult as b}from"@earendil-works/pi-ai/utils/model-operations";import{clearConfigValueCache as x,getConfigValueEnvVarNames as C,isCommandConfigValue as W,isConfigValueConfigured as F,resolveConfigValueOrThrow as J,resolveHeadersOrThrow as M}from"./resolve-config-value.js";const ce=x;function U(r){return r?r.getAllModels?.()??r.getModels():[]}i(U,"getAllProviderModels");function T(r,e){if(!e)return r;const a={...r,...e},t=r,n=e,o=a;for(const l of["openRouterRouting","vercelGatewayRouting","chatTemplateKwargs","chatTemplateArgs"]){const h=t?.[l],f=n[l];(typeof h=="object"&&h!==null||typeof f=="object"&&f!==null)&&(o[l]={...h,...f})}return a}i(T,"mergeCompat");function G(r,e){return e?{...r,...e,images:e.images?{...r?.images,...e.images,resize:e.images.resize?{...r?.images?.resize,...e.images.resize}:r?.images?.resize}:r?.images}:r}i(G,"mergeInputLimits");function Q(r,e){if(!e)return r;const a={...r};for(const t of["off","minimal","low","medium","high","xhigh","max"]){const n=e[t];n&&(a[t]={...r?.[t],...n})}return a}i(Q,"mergeSamplingParamsByThinkingLevel");function X(r,e){return{...r,name:e.name??r.name,reasoning:e.reasoning??r.reasoning,thinkingLevelMap:e.thinkingLevelMap?{...r.thinkingLevelMap,...e.thinkingLevelMap}:r.thinkingLevelMap,input:e.input??r.input,inputLimits:G(r.inputLimits,e.inputLimits),cost:e.cost?{input:e.cost.input??r.cost.input,output:e.cost.output??r.cost.output,cacheRead:e.cost.cacheRead??r.cost.cacheRead,cacheWrite:e.cost.cacheWrite??r.cost.cacheWrite,tiers:e.cost.tiers??r.cost.tiers}:r.cost,promptCache:e.promptCache?{...r.promptCache,...e.promptCache}:r.promptCache,contextWindow:e.contextWindow??r.contextWindow,maxTokens:e.maxTokens??r.maxTokens,samplingParams:e.samplingParams?{...r.samplingParams,...e.samplingParams}:r.samplingParams,samplingParamsByThinkingLevel:Q(r.samplingParamsByThinkingLevel,e.samplingParamsByThinkingLevel),compat:T(r.compat,e.compat)}}i(X,"applyModelOverride");function Y(r,e,a,t){const n=e.api??a.api??t?.api;if(!n)throw new Error(`Provider ${r}, model ${e.id}: no "api" specified. Set at provider or model level.`);const o=e.baseUrl??a.baseUrl??t?.baseUrl;if(!o)throw new Error(`Provider ${r}: "baseUrl" is required when defining custom models.`);if(e.contextWindow!==void 0&&e.contextWindow<=0)throw new Error(`Provider ${r}, model ${e.id}: invalid contextWindow`);if(e.maxTokens!==void 0&&e.maxTokens<=0)throw new Error(`Provider ${r}, model ${e.id}: invalid maxTokens`);return{id:e.id,name:e.name??e.id,api:n,provider:r,baseUrl:o,reasoning:e.reasoning??!1,thinkingLevelMap:e.thinkingLevelMap,input:e.input??["text"],inputLimits:e.inputLimits,cost:e.cost??{input:0,output:0,cacheRead:0,cacheWrite:0},promptCache:e.promptCache,contextWindow:e.contextWindow??128e3,maxTokens:e.maxTokens??16384,samplingParams:e.samplingParams,samplingParamsByThinkingLevel:e.samplingParamsByThinkingLevel,headers:void 0,compat:T(a.compat,e.compat)}}i(Y,"modelFromJson");function Z(r,e,a){const t=r.filter(n=>y(n,"chat"));return t.find(n=>n.id===e)??(a?t.find(n=>n.api===a):void 0)??t.find(n=>n.api==="openai-completions")??t[0]}i(Z,"findModelDefaults");function I(r,e){const a=e.type??"chat",t=r.filter(n=>y(n,a));return t.find(n=>n.id===e.id)??(e.api?t.find(n=>n.api===e.api):void 0)??(a==="chat"?t.find(n=>n.api==="openai-completions"):void 0)??t[0]}i(I,"findExtensionModelDefaults");function ee(r,e,a,t){const n=t.type??"chat",o=I(e,t),l=t.api??(n==="chat"?a.api:void 0)??o?.api;if(!l)throw new Error(`Provider ${r}, model ${t.id}: no "api" specified. Set it at model level${n==="chat"?" or provider level":""}.`);const h=t.baseUrl??a.baseUrl??o?.baseUrl;if(!h)throw new Error(`Provider ${r}: "baseUrl" is required when defining custom models.`);return t.type==="image"?{...t,api:l,provider:r,baseUrl:h,headers:void 0}:t.type==="classifier"?{...t,api:l,provider:r,baseUrl:h,headers:void 0}:{...t,api:l,provider:r,baseUrl:h,headers:void 0}}i(ee,"extensionModelFromDefinition");function L(r,e,a){if(!a)return[...e];if(a.oauth&&!a.baseUrl)throw new Error(`Provider ${r}: "baseUrl" is required when "oauth" is set.`);const t=a.modelOverrides&&Object.keys(a.modelOverrides).length>0;if(!a.models?.length&&!a.baseUrl&&!a.headers&&!a.compat&&!t&&!a.apiKey&&!a.oauth&&a.authHeader===void 0)throw new Error(`Provider ${r}: must specify "baseUrl", "headers", "compat", "modelOverrides", or "models".`);const n=e.map(o=>{const l=a.oauth==="radius"?o.baseUrl:a.baseUrl??o.baseUrl;return y(o,"chat")?{...o,baseUrl:l,compat:T(o.compat,a.compat)}:{...o,baseUrl:l}});for(const o of a.models??[]){const l=n.findIndex(c=>y(c,"chat")&&c.id===o.id),h=Z(n,o.id,o.api??a.api),f=Y(r,o,a,h);l>=0?n[l]=f:n.push(f)}return n}i(L,"applyModelsJson");function H(r,e,a){return a?a.models?a.models.map(t=>ee(r,e,a,t)):a.baseUrl?e.map(t=>({...t,baseUrl:a.baseUrl})):[...e]:[...e]}i(H,"applyExtension");function re(r){return{name:r.name,isSubscription:r.isSubscription,login:i(async e=>({...await r.login({onAuth:i(t=>e.notify({type:"auth_url",...t}),"onAuth"),onDeviceCode:i(t=>e.notify({type:"device_code",...t}),"onDeviceCode"),onPrompt:i(t=>e.prompt({type:"text",...t}),"onPrompt"),onProgress:i(t=>e.notify({type:"progress",message:t}),"onProgress"),onManualCodeInput:i(()=>e.prompt({type:"manual_code",message:"Paste the authorization code"}),"onManualCodeInput"),onSelect:i(t=>e.prompt({type:"select",...t}),"onSelect"),signal:e.signal}),type:"oauth"}),"login"),refresh:i(async(e,a)=>({...await r.refreshToken(e,a),type:"oauth"}),"refresh"),toAuth:i(async e=>({apiKey:r.getApiKey(e)}),"toAuth")}}i(re,"adaptOAuth");function j(r,e,a){let t=r.headers||e?{...r.headers,...e}:void 0;if(a){if(!r.apiKey)throw new Error("authHeader requires a resolved API key");t={...t,Authorization:`Bearer ${r.apiKey}`}}return{...r,headers:t}}i(j,"withConfiguredAuth");function D(r,e){return e?.apiKey??r?.apiKey}i(D,"configuredApiKey");function O(r,e){if(!(!r?.headers&&!e?.headers))return{...r?.headers,...e?.headers}}i(O,"configuredHeaders");async function R(r,e,a){const t={...a};for(const n of new Set(r.flatMap(C))){if(t[n]!==void 0)continue;const o=await e.env(n);o!==void 0&&(t[n]=o)}return Object.keys(t).length>0?t:void 0}i(R,"configContextEnv");function te(r,e,a,t){const n=e?.auth.apiKey,o=D(a,t),l=t?.oauth??e?.auth.oauth;if(!n&&o===void 0&&l)return;const h=O(a,t),f=t?.authHeader??a?.authHeader??!1;return{name:n?.name??"API key",login:n?.login??(async c=>({type:"api_key",key:await c.prompt({type:"secret",message:"Enter API key"})})),check:i(async c=>{if(c.credential){if(n?.check)return n.check(c);if(c.credential.key)return{type:"api_key",source:"stored credential"};const m=await n?.resolve(c);return m?{type:"api_key",source:m.source}:void 0}if(o!==void 0){if(W(o))return{type:"api_key",source:"configured API key"};const m=C(o);for(const k of m)if(await c.ctx.env(k)===void 0)return;return{type:"api_key",source:"configured API key"}}if(n?.check)return n.check(c);const d=await n?.resolve(c);return d?{type:"api_key",source:d.source}:void 0},"check"),resolve:i(async c=>{let d;if(c.credential)d=n?await n.resolve(c):c.credential.key?{auth:{apiKey:c.credential.key},env:c.credential.env,source:"stored credential"}:void 0;else if(o!==void 0){const w=await R([o],c.ctx),P=J(o,`API key for provider "${r}"`,w);d=n?await n.resolve({...c,credential:{type:"api_key",key:P}}):{auth:{apiKey:P},source:"configured API key"}}else d=await n?.resolve(c);if(!d)return;const m={...c.credential?.env??{},...d.env??{}},k=await R(Object.values(h??{}),c.ctx,m),v=M(h,`provider "${r}"`,k);return{...d,auth:j(d.auth,v,f)}},"resolve")}}i(te,"composeApiKeyAuth");function ae(r,e,a,t){const n=t?.oauth?re(t.oauth):e?.auth.oauth;if(!n)return;const o=O(a,t),l=t?.authHeader??a?.authHeader??!1;return{...n,toAuth:i(async h=>{const f=await n.toAuth(h),c=h.env,d=M(o,`provider "${r}"`,typeof c=="object"&&c!==null?c:void 0);return j(f,d,l)},"toAuth")}}i(ae,"composeOAuthAuth");function z(r,e,a){const t=y(r,"chat")?e?.models?.find(l=>l.id===r.id):void 0,n=a?.models?.find(l=>(l.type??"chat")===(r.type??"chat")&&l.id===r.id),o={...y(r,"chat")?e?.modelOverrides?.[r.id]?.headers:void 0,...t?.headers,...n?.headers};return Object.keys(o).length>0?o:void 0}i(z,"rawModelHeaders");function le(r,e,a,t){if(t.streamSimple&&!t.api)throw new Error(`Provider ${r}: "api" is required when registering streamSimple.`);H(r,L(r,U(e),a),t)}i(le,"validateExtensionProvider");function pe(r,e,a,t,n){const o=a.getProvider(r);let l,h;const f=i(()=>t&&h?{...t,models:h}:t,"currentExtension"),c=i(()=>{let s=H(r,L(r,U(e),o),f());return l&&t?.oauth?.modifyModels&&(s=[...t.oauth.modifyModels(s.filter(u=>y(u,"chat")),l),...s.filter(u=>!y(u,"chat"))]),s.map(u=>{const p=o?.modelOverrides?.[u.id];return p&&y(u,"chat")?X(u,p):u})},"getAllModels");c();const d=te(r,e,o,t),m=ae(r,e,o,t);if(!d&&!m)throw new Error(`Provider ${r}: no authentication method configured.`);const k=i(s=>e?.supportsApi?.(s.api)??e?.getModels().some(u=>u.api===s.api)??!1,"supportsBaseApi"),v=i((s,u,p,g)=>V(s,async()=>{if(t?.streamSimple&&s.api===t.api)return t.streamSimple(s,u,p);if(e&&k(s))return g?e.streamSimple(s,u,p):e.stream(s,u,p);const E=q(s.api);if(!E)throw new Error(`No API provider registered for api: ${s.api}`);return g?E.streamSimple(s,u,p):E.stream(s,u,p)}),"streamWith"),w={id:r,name:t?.name??o?.name??e?.name??t?.oauth?.name??r,baseUrl:t?.baseUrl??o?.baseUrl??e?.baseUrl,headers:e?.headers,auth:{...d?{apiKey:d}:{},...m?{oauth:m}:{}},getModels:i(()=>c().filter(s=>y(s,"chat")),"getModels"),getAllModels:c,refreshModels:e?.refreshModels||t?.refreshModels||t?.oauth?.modifyModels?async s=>{await e?.refreshModels?.(s);let u;if(t?.refreshModels&&(u=await t.refreshModels(s)),s.signal.aborted)return;const p=s.credential?.type==="oauth"?s.credential:void 0;await s.publish({update:i(()=>{u&&(H(r,L(r,U(e),o),{...t,models:u}),h=u,n?.(u)),l=p},"update")})}:void 0,filterModels:e?.filterModels?(s,u)=>e.filterModels(s,u):void 0,filterAllModels:e?.filterAllModels?(s,u)=>e.filterAllModels(s,u):void 0,stream:i((s,u,p)=>v(s,u,p,!1),"stream"),streamSimple:i((s,u,p)=>v(s,u,p,!0),"streamSimple")},P=e?.fetchDeferred;P&&(w.fetchDeferred=(s,u,p)=>P(s,u,p));const K=e?.cancelDeferred;K&&(w.cancelDeferred=(s,u,p)=>K(s,u,p));const S=t?.images,A=e?.generateImages;(A||Object.keys(S??{}).length>0)&&(w.generateImages=(s,u,p)=>{const g=S?.[s.api];return g?g.generateImages(s,u,p):A?A(s,u,p):Promise.resolve(b(s,new Error(`Provider ${r} has no image implementation for "${s.api}"`)))});const _=t?.classifiers,$=e?.classify;return($||Object.keys(_??{}).length>0)&&(w.classify=(s,u,p)=>{const g=_?.[s.api];return g?g.classify(s,u,p):$?$(s,u,p):Promise.resolve(N(s,new Error(`Provider ${r} has no classifier implementation for "${s.api}"`)))}),w}i(pe,"composeModelProvider");function he(r,e,a,t){return M(z(r,e,a),`model "${r.provider}/${r.id}"`,t)}i(he,"resolveConfiguredModelHeaders");function de(r,e,a){const t=M({...O(e,a),...z(r,e,a)},`model "${r.provider}/${r.id}"`);return{headers:r.headers||t?{...r.headers,...t}:void 0,authHeader:a?.authHeader??e?.authHeader??!1}}i(de,"resolveCompatibilityRequestConfig");function fe(r,e){const a=D(r,e);if(a===void 0)return;if(W(a))return{configured:!0,source:"models_json_command"};const t=C(a);return t.length>0?F(a)?{configured:!0,source:"environment",label:t.join(", ")}:{configured:!1}:{configured:!0,source:e?.apiKey!==void 0?"fallback":"models_json_key"}}i(fe,"configuredRequestAuthStatus");export{ce as clearApiKeyCache,pe as composeModelProvider,fe as configuredRequestAuthStatus,de as resolveCompatibilityRequestConfig,he as resolveConfiguredModelHeaders,le as validateExtensionProvider};
|
|
1
|
+
var B=Object.defineProperty;var u=(r,e)=>B(r,"name",{value:e,configurable:!0});import{isModelType as m,lazyStream as V}from"@earendil-works/pi-ai";import{getApiProvider as q}from"@earendil-works/pi-ai/compat";import{classifierErrorResult as N,imageErrorResult as b}from"@earendil-works/pi-ai/utils/model-operations";import{clearConfigValueCache as x,getConfigValueEnvVarNames as C,isCommandConfigValue as W,isConfigValueConfigured as F,resolveConfigValueOrThrow as J,resolveHeadersOrThrow as M}from"./resolve-config-value.js";const ce=x;function U(r){return r?r.getAllModels?.()??r.getModels():[]}u(U,"getAllProviderModels");function T(r,e){if(!e)return r;const a={...r,...e},t=r,n=e,i=a;for(const l of["openRouterRouting","vercelGatewayRouting","chatTemplateKwargs","chatTemplateArgs"]){const h=t?.[l],f=n[l];(typeof h=="object"&&h!==null||typeof f=="object"&&f!==null)&&(i[l]={...h,...f})}return a}u(T,"mergeCompat");function G(r,e){return e?{...r,...e,images:e.images?{...r?.images,...e.images,resize:e.images.resize?{...r?.images?.resize,...e.images.resize}:r?.images?.resize}:r?.images}:r}u(G,"mergeInputLimits");function Q(r,e){if(!e)return r;const a={...r};for(const t of["off","minimal","low","medium","high","xhigh","max"]){const n=e[t];n&&(a[t]={...r?.[t],...n})}return a}u(Q,"mergeSamplingParamsByThinkingLevel");function X(r,e){return{...r,name:e.name??r.name,reasoning:e.reasoning??r.reasoning,thinkingLevelMap:e.thinkingLevelMap?{...r.thinkingLevelMap,...e.thinkingLevelMap}:r.thinkingLevelMap,input:e.input??r.input,inputLimits:G(r.inputLimits,e.inputLimits),cost:e.cost?{input:e.cost.input??r.cost.input,output:e.cost.output??r.cost.output,cacheRead:e.cost.cacheRead??r.cost.cacheRead,cacheWrite:e.cost.cacheWrite??r.cost.cacheWrite,tiers:e.cost.tiers??r.cost.tiers}:r.cost,promptCache:e.promptCache?{...r.promptCache,...e.promptCache}:r.promptCache,contextWindow:e.contextWindow??r.contextWindow,maxTokens:e.maxTokens??r.maxTokens,samplingParams:e.samplingParams?{...r.samplingParams,...e.samplingParams}:r.samplingParams,samplingParamsByThinkingLevel:Q(r.samplingParamsByThinkingLevel,e.samplingParamsByThinkingLevel),compat:T(r.compat,e.compat)}}u(X,"applyModelOverride");function Y(r,e,a,t){const n=e.api??a.api??t?.api;if(!n)throw new Error(`Provider ${r}, model ${e.id}: no "api" specified. Set at provider or model level.`);const i=e.baseUrl??a.baseUrl??t?.baseUrl;if(!i)throw new Error(`Provider ${r}: "baseUrl" is required when defining custom models.`);if(e.contextWindow!==void 0&&e.contextWindow<=0)throw new Error(`Provider ${r}, model ${e.id}: invalid contextWindow`);if(e.maxTokens!==void 0&&e.maxTokens<=0)throw new Error(`Provider ${r}, model ${e.id}: invalid maxTokens`);return{id:e.id,name:e.name??e.id,api:n,provider:r,baseUrl:i,reasoning:e.reasoning??!1,thinkingLevelMap:e.thinkingLevelMap,input:e.input??["text"],inputLimits:e.inputLimits,cost:e.cost??{input:0,output:0,cacheRead:0,cacheWrite:0},promptCache:e.promptCache,contextWindow:e.contextWindow??128e3,maxTokens:e.maxTokens??16384,samplingParams:e.samplingParams,samplingParamsByThinkingLevel:e.samplingParamsByThinkingLevel,headers:void 0,compat:T(a.compat,e.compat)}}u(Y,"modelFromJson");function Z(r,e,a){const t=r.filter(n=>m(n,"chat"));return t.find(n=>n.id===e)??(a?t.find(n=>n.api===a):void 0)??t.find(n=>n.api==="openai-completions")??t[0]}u(Z,"findModelDefaults");function I(r,e){const a=e.type??"chat",t=r.filter(n=>m(n,a));return t.find(n=>n.id===e.id)??(e.api?t.find(n=>n.api===e.api):void 0)??(a==="chat"?t.find(n=>n.api==="openai-completions"):void 0)??t[0]}u(I,"findExtensionModelDefaults");function ee(r,e,a,t){const n=t.type??"chat",i=I(e,t),l=t.api??(n==="chat"?a.api:void 0)??i?.api;if(!l)throw new Error(`Provider ${r}, model ${t.id}: no "api" specified. Set it at model level${n==="chat"?" or provider level":""}.`);const h=t.baseUrl??a.baseUrl??i?.baseUrl;if(!h)throw new Error(`Provider ${r}: "baseUrl" is required when defining custom models.`);return t.type==="image"?{...t,api:l,provider:r,baseUrl:h,headers:void 0}:t.type==="classifier"?{...t,api:l,provider:r,baseUrl:h,headers:void 0}:{...t,api:l,provider:r,baseUrl:h,headers:void 0}}u(ee,"extensionModelFromDefinition");function L(r,e,a){if(!a)return[...e];if(a.oauth&&!a.baseUrl)throw new Error(`Provider ${r}: "baseUrl" is required when "oauth" is set.`);const t=a.modelOverrides&&Object.keys(a.modelOverrides).length>0;if(!a.models?.length&&!a.baseUrl&&!a.headers&&!a.compat&&!t&&!a.apiKey&&!a.oauth&&a.authHeader===void 0)throw new Error(`Provider ${r}: must specify "baseUrl", "headers", "compat", "modelOverrides", or "models".`);const n=e.map(i=>{const l=a.oauth==="radius"?i.baseUrl:a.baseUrl??i.baseUrl;return m(i,"chat")?{...i,baseUrl:l,compat:T(i.compat,a.compat)}:m(i,"classifier")&&a.compat?{...i,baseUrl:l,compat:{...i.compat,...a.compat}}:{...i,baseUrl:l}});for(const i of a.models??[]){const l=n.findIndex(c=>m(c,"chat")&&c.id===i.id),h=Z(n,i.id,i.api??a.api),f=Y(r,i,a,h);l>=0?n[l]=f:n.push(f)}return n}u(L,"applyModelsJson");function H(r,e,a){return a?a.models?a.models.map(t=>ee(r,e,a,t)):a.baseUrl?e.map(t=>({...t,baseUrl:a.baseUrl})):[...e]:[...e]}u(H,"applyExtension");function re(r){return{name:r.name,isSubscription:r.isSubscription,login:u(async e=>({...await r.login({onAuth:u(t=>e.notify({type:"auth_url",...t}),"onAuth"),onDeviceCode:u(t=>e.notify({type:"device_code",...t}),"onDeviceCode"),onPrompt:u(t=>e.prompt({type:"text",...t}),"onPrompt"),onProgress:u(t=>e.notify({type:"progress",message:t}),"onProgress"),onManualCodeInput:u(()=>e.prompt({type:"manual_code",message:"Paste the authorization code"}),"onManualCodeInput"),onSelect:u(t=>e.prompt({type:"select",...t}),"onSelect"),signal:e.signal}),type:"oauth"}),"login"),refresh:u(async(e,a)=>({...await r.refreshToken(e,a),type:"oauth"}),"refresh"),toAuth:u(async e=>({apiKey:r.getApiKey(e)}),"toAuth")}}u(re,"adaptOAuth");function j(r,e,a){let t=r.headers||e?{...r.headers,...e}:void 0;if(a){if(!r.apiKey)throw new Error("authHeader requires a resolved API key");t={...t,Authorization:`Bearer ${r.apiKey}`}}return{...r,headers:t}}u(j,"withConfiguredAuth");function D(r,e){return e?.apiKey??r?.apiKey}u(D,"configuredApiKey");function O(r,e){if(!(!r?.headers&&!e?.headers))return{...r?.headers,...e?.headers}}u(O,"configuredHeaders");async function R(r,e,a){const t={...a};for(const n of new Set(r.flatMap(C))){if(t[n]!==void 0)continue;const i=await e.env(n);i!==void 0&&(t[n]=i)}return Object.keys(t).length>0?t:void 0}u(R,"configContextEnv");function te(r,e,a,t){const n=e?.auth.apiKey,i=D(a,t),l=t?.oauth??e?.auth.oauth;if(!n&&i===void 0&&l)return;const h=O(a,t),f=t?.authHeader??a?.authHeader??!1;return{name:n?.name??"API key",login:n?.login??(async c=>({type:"api_key",key:await c.prompt({type:"secret",message:"Enter API key"})})),check:u(async c=>{if(c.credential){if(n?.check)return n.check(c);if(c.credential.key)return{type:"api_key",source:"stored credential"};const y=await n?.resolve(c);return y?{type:"api_key",source:y.source}:void 0}if(i!==void 0){if(W(i))return{type:"api_key",source:"configured API key"};const y=C(i);for(const k of y)if(await c.ctx.env(k)===void 0)return;return{type:"api_key",source:"configured API key"}}if(n?.check)return n.check(c);const d=await n?.resolve(c);return d?{type:"api_key",source:d.source}:void 0},"check"),resolve:u(async c=>{let d;if(c.credential)d=n?await n.resolve(c):c.credential.key?{auth:{apiKey:c.credential.key},env:c.credential.env,source:"stored credential"}:void 0;else if(i!==void 0){const w=await R([i],c.ctx),P=J(i,`API key for provider "${r}"`,w);d=n?await n.resolve({...c,credential:{type:"api_key",key:P}}):{auth:{apiKey:P},source:"configured API key"}}else d=await n?.resolve(c);if(!d)return;const y={...c.credential?.env??{},...d.env??{}},k=await R(Object.values(h??{}),c.ctx,y),v=M(h,`provider "${r}"`,k);return{...d,auth:j(d.auth,v,f)}},"resolve")}}u(te,"composeApiKeyAuth");function ae(r,e,a,t){const n=t?.oauth?re(t.oauth):e?.auth.oauth;if(!n)return;const i=O(a,t),l=t?.authHeader??a?.authHeader??!1;return{...n,toAuth:u(async h=>{const f=await n.toAuth(h),c=h.env,d=M(i,`provider "${r}"`,typeof c=="object"&&c!==null?c:void 0);return j(f,d,l)},"toAuth")}}u(ae,"composeOAuthAuth");function z(r,e,a){const t=m(r,"chat")?e?.models?.find(l=>l.id===r.id):void 0,n=a?.models?.find(l=>(l.type??"chat")===(r.type??"chat")&&l.id===r.id),i={...m(r,"chat")?e?.modelOverrides?.[r.id]?.headers:void 0,...t?.headers,...n?.headers};return Object.keys(i).length>0?i:void 0}u(z,"rawModelHeaders");function le(r,e,a,t){if(t.streamSimple&&!t.api)throw new Error(`Provider ${r}: "api" is required when registering streamSimple.`);H(r,L(r,U(e),a),t)}u(le,"validateExtensionProvider");function pe(r,e,a,t,n){const i=a.getProvider(r);let l,h;const f=u(()=>t&&h?{...t,models:h}:t,"currentExtension"),c=u(()=>{let s=H(r,L(r,U(e),i),f());return l&&t?.oauth?.modifyModels&&(s=[...t.oauth.modifyModels(s.filter(o=>m(o,"chat")),l),...s.filter(o=>!m(o,"chat"))]),s.map(o=>{const p=i?.modelOverrides?.[o.id];return p&&m(o,"chat")?X(o,p):o})},"getAllModels");c();const d=te(r,e,i,t),y=ae(r,e,i,t);if(!d&&!y)throw new Error(`Provider ${r}: no authentication method configured.`);const k=u(s=>e?.supportsApi?.(s.api)??e?.getModels().some(o=>o.api===s.api)??!1,"supportsBaseApi"),v=u((s,o,p,g)=>V(s,async()=>{if(t?.streamSimple&&s.api===t.api)return t.streamSimple(s,o,p);if(e&&k(s))return g?e.streamSimple(s,o,p):e.stream(s,o,p);const E=q(s.api);if(!E)throw new Error(`No API provider registered for api: ${s.api}`);return g?E.streamSimple(s,o,p):E.stream(s,o,p)}),"streamWith"),w={id:r,name:t?.name??i?.name??e?.name??t?.oauth?.name??r,baseUrl:t?.baseUrl??i?.baseUrl??e?.baseUrl,headers:e?.headers,auth:{...d?{apiKey:d}:{},...y?{oauth:y}:{}},getModels:u(()=>c().filter(s=>m(s,"chat")),"getModels"),getAllModels:c,refreshModels:e?.refreshModels||t?.refreshModels||t?.oauth?.modifyModels?async s=>{await e?.refreshModels?.(s);let o;if(t?.refreshModels&&(o=await t.refreshModels(s)),s.signal.aborted)return;const p=s.credential?.type==="oauth"?s.credential:void 0;await s.publish({update:u(()=>{o&&(H(r,L(r,U(e),i),{...t,models:o}),h=o,n?.(o)),l=p},"update")})}:void 0,filterModels:e?.filterModels?(s,o)=>e.filterModels(s,o):void 0,filterAllModels:e?.filterAllModels?(s,o)=>e.filterAllModels(s,o):void 0,stream:u((s,o,p)=>v(s,o,p,!1),"stream"),streamSimple:u((s,o,p)=>v(s,o,p,!0),"streamSimple")},P=e?.fetchDeferred;P&&(w.fetchDeferred=(s,o,p)=>P(s,o,p));const K=e?.cancelDeferred;K&&(w.cancelDeferred=(s,o,p)=>K(s,o,p));const S=t?.images,A=e?.generateImages;(A||Object.keys(S??{}).length>0)&&(w.generateImages=(s,o,p)=>{const g=S?.[s.api];return g?g.generateImages(s,o,p):A?A(s,o,p):Promise.resolve(b(s,new Error(`Provider ${r} has no image implementation for "${s.api}"`)))});const _=t?.classifiers,$=e?.classify;return($||Object.keys(_??{}).length>0)&&(w.classify=(s,o,p)=>{const g=_?.[s.api];return g?g.classify(s,o,p):$?$(s,o,p):Promise.resolve(N(s,new Error(`Provider ${r} has no classifier implementation for "${s.api}"`)))}),w}u(pe,"composeModelProvider");function he(r,e,a,t){return M(z(r,e,a),`model "${r.provider}/${r.id}"`,t)}u(he,"resolveConfiguredModelHeaders");function de(r,e,a){const t=M({...O(e,a),...z(r,e,a)},`model "${r.provider}/${r.id}"`);return{headers:r.headers||t?{...r.headers,...t}:void 0,authHeader:a?.authHeader??e?.authHeader??!1}}u(de,"resolveCompatibilityRequestConfig");function fe(r,e){const a=D(r,e);if(a===void 0)return;if(W(a))return{configured:!0,source:"models_json_command"};const t=C(a);return t.length>0?F(a)?{configured:!0,source:"environment",label:t.join(", ")}:{configured:!1}:{configured:!0,source:e?.apiKey!==void 0?"fallback":"models_json_key"}}u(fe,"configuredRequestAuthStatus");export{ce as clearApiKeyCache,pe as composeModelProvider,fe as configuredRequestAuthStatus,de as resolveCompatibilityRequestConfig,he as resolveConfiguredModelHeaders,le as validateExtensionProvider};
|