blackriver-gateway 3.8.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/.env.example +2070 -0
- package/@omniroute/opencode-plugin/LICENSE +21 -0
- package/@omniroute/opencode-plugin/README.md +296 -0
- package/@omniroute/opencode-plugin/package-lock.json +1930 -0
- package/@omniroute/opencode-plugin/package.json +73 -0
- package/@omniroute/opencode-plugin/src/index.ts +4685 -0
- package/@omniroute/opencode-plugin/src/logger.ts +74 -0
- package/@omniroute/opencode-plugin/src/naming.ts +301 -0
- package/@omniroute/opencode-plugin/tsconfig.json +20 -0
- package/@omniroute/opencode-plugin/tsup.config.ts +20 -0
- package/@omniroute/opencode-provider/LICENSE +21 -0
- package/@omniroute/opencode-provider/README.md +156 -0
- package/@omniroute/opencode-provider/package-lock.json +1514 -0
- package/@omniroute/opencode-provider/package.json +63 -0
- package/@omniroute/opencode-provider/src/index.ts +908 -0
- package/@omniroute/opencode-provider/tsconfig.json +20 -0
- package/@omniroute/opencode-provider/tsup.config.ts +18 -0
- package/LICENSE +22 -0
- package/README.md +1265 -0
- package/bin/_ops-common.sh +70 -0
- package/bin/cli/CONVENTIONS.md +224 -0
- package/bin/cli/README.md +146 -0
- package/bin/cli/api-commands/agent-skills.mjs +70 -0
- package/bin/cli/api-commands/agentbridge.mjs +155 -0
- package/bin/cli/api-commands/api-keys.mjs +42 -0
- package/bin/cli/api-commands/audio.mjs +40 -0
- package/bin/cli/api-commands/chat.mjs +58 -0
- package/bin/cli/api-commands/cli-tools.mjs +361 -0
- package/bin/cli/api-commands/cloud.mjs +81 -0
- package/bin/cli/api-commands/combos.mjs +69 -0
- package/bin/cli/api-commands/compression.mjs +128 -0
- package/bin/cli/api-commands/embedded-services.mjs +202 -0
- package/bin/cli/api-commands/embeddings.mjs +42 -0
- package/bin/cli/api-commands/fallback.mjs +49 -0
- package/bin/cli/api-commands/images.mjs +42 -0
- package/bin/cli/api-commands/memory.mjs +251 -0
- package/bin/cli/api-commands/messages.mjs +40 -0
- package/bin/cli/api-commands/models.mjs +89 -0
- package/bin/cli/api-commands/moderations.mjs +24 -0
- package/bin/cli/api-commands/oauth.mjs +114 -0
- package/bin/cli/api-commands/playground.mjs +83 -0
- package/bin/cli/api-commands/pricing.mjs +44 -0
- package/bin/cli/api-commands/provider-nodes.mjs +62 -0
- package/bin/cli/api-commands/providers.mjs +148 -0
- package/bin/cli/api-commands/quota.mjs +154 -0
- package/bin/cli/api-commands/registry.mjs +75 -0
- package/bin/cli/api-commands/rerank.mjs +24 -0
- package/bin/cli/api-commands/responses.mjs +24 -0
- package/bin/cli/api-commands/settings.mjs +228 -0
- package/bin/cli/api-commands/system.mjs +320 -0
- package/bin/cli/api-commands/telemetry.mjs +26 -0
- package/bin/cli/api-commands/traffic-inspector.mjs +307 -0
- package/bin/cli/api-commands/translator.mjs +65 -0
- package/bin/cli/api-commands/usage.mjs +117 -0
- package/bin/cli/api.mjs +269 -0
- package/bin/cli/commands/a2a.mjs +323 -0
- package/bin/cli/commands/audit.mjs +203 -0
- package/bin/cli/commands/autostart.mjs +57 -0
- package/bin/cli/commands/backup.mjs +469 -0
- package/bin/cli/commands/batches.mjs +235 -0
- package/bin/cli/commands/cache.mjs +102 -0
- package/bin/cli/commands/chat.mjs +162 -0
- package/bin/cli/commands/cloud.mjs +233 -0
- package/bin/cli/commands/combo.mjs +361 -0
- package/bin/cli/commands/completion.mjs +346 -0
- package/bin/cli/commands/compression.mjs +247 -0
- package/bin/cli/commands/config.mjs +351 -0
- package/bin/cli/commands/configure.mjs +180 -0
- package/bin/cli/commands/connect.mjs +132 -0
- package/bin/cli/commands/context-eng.mjs +182 -0
- package/bin/cli/commands/contexts.mjs +271 -0
- package/bin/cli/commands/cost.mjs +144 -0
- package/bin/cli/commands/dashboard.mjs +65 -0
- package/bin/cli/commands/doctor.mjs +527 -0
- package/bin/cli/commands/env.mjs +100 -0
- package/bin/cli/commands/eval.mjs +278 -0
- package/bin/cli/commands/files.mjs +144 -0
- package/bin/cli/commands/health.mjs +123 -0
- package/bin/cli/commands/keys.mjs +599 -0
- package/bin/cli/commands/launch-codex.mjs +201 -0
- package/bin/cli/commands/launch.mjs +155 -0
- package/bin/cli/commands/login.mjs +192 -0
- package/bin/cli/commands/logs.mjs +183 -0
- package/bin/cli/commands/mcp.mjs +273 -0
- package/bin/cli/commands/memory.mjs +244 -0
- package/bin/cli/commands/models.mjs +92 -0
- package/bin/cli/commands/nodes.mjs +177 -0
- package/bin/cli/commands/oauth.mjs +258 -0
- package/bin/cli/commands/oneproxy.mjs +120 -0
- package/bin/cli/commands/open.mjs +75 -0
- package/bin/cli/commands/openapi.mjs +168 -0
- package/bin/cli/commands/plugin.mjs +219 -0
- package/bin/cli/commands/policy.mjs +216 -0
- package/bin/cli/commands/pricing.mjs +123 -0
- package/bin/cli/commands/provider-cmd.mjs +18 -0
- package/bin/cli/commands/providers.mjs +706 -0
- package/bin/cli/commands/quota.mjs +100 -0
- package/bin/cli/commands/redis.mjs +294 -0
- package/bin/cli/commands/registry.mjs +162 -0
- package/bin/cli/commands/repl.mjs +19 -0
- package/bin/cli/commands/reset-encrypted-columns.mjs +88 -0
- package/bin/cli/commands/resilience.mjs +208 -0
- package/bin/cli/commands/restart.mjs +25 -0
- package/bin/cli/commands/runtime.mjs +98 -0
- package/bin/cli/commands/serve.mjs +426 -0
- package/bin/cli/commands/sessions.mjs +108 -0
- package/bin/cli/commands/setup-aider.mjs +146 -0
- package/bin/cli/commands/setup-claude.mjs +219 -0
- package/bin/cli/commands/setup-cline.mjs +160 -0
- package/bin/cli/commands/setup-codex.mjs +387 -0
- package/bin/cli/commands/setup-continue.mjs +173 -0
- package/bin/cli/commands/setup-crush.mjs +148 -0
- package/bin/cli/commands/setup-cursor.mjs +108 -0
- package/bin/cli/commands/setup-goose.mjs +150 -0
- package/bin/cli/commands/setup-kilo.mjs +178 -0
- package/bin/cli/commands/setup-open-code.mjs +398 -0
- package/bin/cli/commands/setup-opencode.mjs +129 -0
- package/bin/cli/commands/setup-qwen.mjs +156 -0
- package/bin/cli/commands/setup-roo.mjs +172 -0
- package/bin/cli/commands/setup.mjs +211 -0
- package/bin/cli/commands/simulate.mjs +125 -0
- package/bin/cli/commands/skills.mjs +373 -0
- package/bin/cli/commands/status.mjs +95 -0
- package/bin/cli/commands/stop.mjs +96 -0
- package/bin/cli/commands/stream.mjs +166 -0
- package/bin/cli/commands/sync.mjs +230 -0
- package/bin/cli/commands/tags.mjs +116 -0
- package/bin/cli/commands/telemetry.mjs +74 -0
- package/bin/cli/commands/test-provider.mjs +242 -0
- package/bin/cli/commands/tokens.mjs +118 -0
- package/bin/cli/commands/translator.mjs +131 -0
- package/bin/cli/commands/tray.mjs +36 -0
- package/bin/cli/commands/tunnel.mjs +347 -0
- package/bin/cli/commands/update.mjs +194 -0
- package/bin/cli/commands/usage.mjs +331 -0
- package/bin/cli/commands/webhooks.mjs +196 -0
- package/bin/cli/contexts.mjs +60 -0
- package/bin/cli/data-dir.mjs +59 -0
- package/bin/cli/encryption.mjs +67 -0
- package/bin/cli/i18n.mjs +106 -0
- package/bin/cli/io.mjs +83 -0
- package/bin/cli/locales/ar.json +32 -0
- package/bin/cli/locales/az.json +32 -0
- package/bin/cli/locales/bg.json +32 -0
- package/bin/cli/locales/bn.json +5 -0
- package/bin/cli/locales/cs.json +32 -0
- package/bin/cli/locales/da.json +32 -0
- package/bin/cli/locales/de.json +32 -0
- package/bin/cli/locales/en.json +1289 -0
- package/bin/cli/locales/es.json +32 -0
- package/bin/cli/locales/fa.json +32 -0
- package/bin/cli/locales/fi.json +32 -0
- package/bin/cli/locales/fr.json +32 -0
- package/bin/cli/locales/gu.json +5 -0
- package/bin/cli/locales/he.json +5 -0
- package/bin/cli/locales/hi.json +32 -0
- package/bin/cli/locales/hu.json +32 -0
- package/bin/cli/locales/id.json +32 -0
- package/bin/cli/locales/in.json +5 -0
- package/bin/cli/locales/it.json +32 -0
- package/bin/cli/locales/ja.json +32 -0
- package/bin/cli/locales/ko.json +32 -0
- package/bin/cli/locales/mr.json +5 -0
- package/bin/cli/locales/ms.json +5 -0
- package/bin/cli/locales/nl.json +32 -0
- package/bin/cli/locales/no.json +32 -0
- package/bin/cli/locales/phi.json +5 -0
- package/bin/cli/locales/pl.json +32 -0
- package/bin/cli/locales/pt-BR.json +1286 -0
- package/bin/cli/locales/pt.json +32 -0
- package/bin/cli/locales/ro.json +32 -0
- package/bin/cli/locales/ru.json +32 -0
- package/bin/cli/locales/sk.json +32 -0
- package/bin/cli/locales/sv.json +32 -0
- package/bin/cli/locales/sw.json +5 -0
- package/bin/cli/locales/ta.json +5 -0
- package/bin/cli/locales/te.json +5 -0
- package/bin/cli/locales/th.json +32 -0
- package/bin/cli/locales/tr.json +32 -0
- package/bin/cli/locales/uk-UA.json +32 -0
- package/bin/cli/locales/ur.json +5 -0
- package/bin/cli/locales/vi.json +32 -0
- package/bin/cli/locales/zh-CN.json +1262 -0
- package/bin/cli/output.mjs +200 -0
- package/bin/cli/plugins.mjs +90 -0
- package/bin/cli/program.mjs +40 -0
- package/bin/cli/provider-catalog.mjs +175 -0
- package/bin/cli/provider-store.mjs +312 -0
- package/bin/cli/provider-test.mjs +181 -0
- package/bin/cli/runtime/index.mjs +19 -0
- package/bin/cli/runtime/magicBytes.mjs +47 -0
- package/bin/cli/runtime/nativeDeps.mjs +137 -0
- package/bin/cli/runtime/processSupervisor.mjs +136 -0
- package/bin/cli/runtime/sqliteRuntime.mjs +129 -0
- package/bin/cli/runtime/supervisorPolicy.mjs +56 -0
- package/bin/cli/runtime/trayRuntime.ts +94 -0
- package/bin/cli/runtime.mjs +61 -0
- package/bin/cli/schemas/output-schemas.mjs +56 -0
- package/bin/cli/scripts/generate-locales.mjs +911 -0
- package/bin/cli/settings-store.mjs +45 -0
- package/bin/cli/spinner.mjs +30 -0
- package/bin/cli/sqlite.mjs +158 -0
- package/bin/cli/tray/autostart.mjs +410 -0
- package/bin/cli/tray/autostart.ts +18 -0
- package/bin/cli/tray/icon.png +0 -0
- package/bin/cli/tray/index.mjs +28 -0
- package/bin/cli/tray/tray.ps1 +99 -0
- package/bin/cli/tray/tray.ts +186 -0
- package/bin/cli/tray/traySystray.mjs +135 -0
- package/bin/cli/tray/trayWin.ts +91 -0
- package/bin/cli/tray/trayWindows.mjs +75 -0
- package/bin/cli/tui/Dashboard.jsx +70 -0
- package/bin/cli/tui/EvalWatch.jsx +171 -0
- package/bin/cli/tui/InterfaceMenu.jsx +55 -0
- package/bin/cli/tui/OAuthFlow.jsx +193 -0
- package/bin/cli/tui/ProvidersTestAll.jsx +190 -0
- package/bin/cli/tui/Repl.jsx +392 -0
- package/bin/cli/tui/session.mjs +54 -0
- package/bin/cli/tui/tabs/Combos.jsx +47 -0
- package/bin/cli/tui/tabs/Cost.jsx +52 -0
- package/bin/cli/tui/tabs/Health.jsx +53 -0
- package/bin/cli/tui/tabs/Keys.jsx +48 -0
- package/bin/cli/tui/tabs/Logs.jsx +60 -0
- package/bin/cli/tui/tabs/Overview.jsx +80 -0
- package/bin/cli/tui/tabs/Providers.jsx +48 -0
- package/bin/cli/tui-components/CodeBlock.jsx +15 -0
- package/bin/cli/tui-components/ConfirmDialog.jsx +40 -0
- package/bin/cli/tui-components/DataTable.jsx +50 -0
- package/bin/cli/tui-components/HeaderSwr.jsx +25 -0
- package/bin/cli/tui-components/KeyMaskedDisplay.jsx +12 -0
- package/bin/cli/tui-components/MarkdownView.jsx +13 -0
- package/bin/cli/tui-components/MenuSelect.jsx +38 -0
- package/bin/cli/tui-components/MultilineInput.jsx +18 -0
- package/bin/cli/tui-components/ProgressBar.jsx +15 -0
- package/bin/cli/tui-components/Sparkline.jsx +15 -0
- package/bin/cli/tui-components/StatusBadge.jsx +17 -0
- package/bin/cli/tui-components/TokenCounter.jsx +18 -0
- package/bin/cli/tui-components/theme.jsx +11 -0
- package/bin/cli/utils/cliToken.mjs +22 -0
- package/bin/cli/utils/clipboard.mjs +35 -0
- package/bin/cli/utils/environment.mjs +50 -0
- package/bin/cli/utils/pid.mjs +110 -0
- package/bin/cli/utils/storageKeyProvision.mjs +31 -0
- package/bin/cold-start-bench.sh +82 -0
- package/bin/mcp-server.mjs +71 -0
- package/bin/nodeRuntimeSupport.mjs +84 -0
- package/bin/omniroute.mjs +237 -0
- package/bin/reset-password.mjs +137 -0
- package/bin/restore-data.sh +64 -0
- package/bin/restore-policies.sh +77 -0
- package/bin/rollback.sh +102 -0
- package/bin/snapshot-data.sh +61 -0
- package/open-sse/config/agyModels.ts +157 -0
- package/open-sse/config/anthropicHeaders.ts +127 -0
- package/open-sse/config/antigravityModelAliases.ts +309 -0
- package/open-sse/config/antigravityUpstream.ts +20 -0
- package/open-sse/config/audioRegistry.ts +547 -0
- package/open-sse/config/azureAi.ts +49 -0
- package/open-sse/config/bedrock.ts +196 -0
- package/open-sse/config/cliFingerprints.ts +405 -0
- package/open-sse/config/codexClient.ts +49 -0
- package/open-sse/config/codexIdentity.ts +87 -0
- package/open-sse/config/codexInstructions.ts +122 -0
- package/open-sse/config/codexQuotaScopes.ts +87 -0
- package/open-sse/config/constants.ts +281 -0
- package/open-sse/config/contextEditing.ts +156 -0
- package/open-sse/config/credentialLoader.ts +123 -0
- package/open-sse/config/datarobot.ts +69 -0
- package/open-sse/config/defaultThinkingSignature.ts +8 -0
- package/open-sse/config/embeddingRegistry.ts +434 -0
- package/open-sse/config/errorConfig.ts +201 -0
- package/open-sse/config/freeModelCatalog.data.ts +467 -0
- package/open-sse/config/freeModelCatalog.ts +142 -0
- package/open-sse/config/freeTierCatalog.ts +101 -0
- package/open-sse/config/geminiRateLimits.json +34 -0
- package/open-sse/config/glmProvider.ts +488 -0
- package/open-sse/config/imageRegistry.ts +752 -0
- package/open-sse/config/maritalk.ts +18 -0
- package/open-sse/config/mediaServiceKinds.ts +70 -0
- package/open-sse/config/moderationRegistry.ts +89 -0
- package/open-sse/config/musicRegistry.ts +115 -0
- package/open-sse/config/oci.ts +44 -0
- package/open-sse/config/ocrRegistry.ts +82 -0
- package/open-sse/config/ollamaModels.ts +28 -0
- package/open-sse/config/providerErrorRules.ts +218 -0
- package/open-sse/config/providerFieldStrips.ts +42 -0
- package/open-sse/config/providerHeaderProfiles.ts +188 -0
- package/open-sse/config/providerModels.ts +199 -0
- package/open-sse/config/providerPluginManifest.ts +186 -0
- package/open-sse/config/providerPluginManifestRegistry.ts +31 -0
- package/open-sse/config/providerPluginManifestUrl.ts +26 -0
- package/open-sse/config/providerRegistry.ts +257 -0
- package/open-sse/config/providers/index.ts +377 -0
- package/open-sse/config/providers/registry/adapta-web/index.ts +20 -0
- package/open-sse/config/providers/registry/agentrouter/index.ts +24 -0
- package/open-sse/config/providers/registry/agy/index.ts +28 -0
- package/open-sse/config/providers/registry/ai21/index.ts +13 -0
- package/open-sse/config/providers/registry/aimlapi/index.ts +21 -0
- package/open-sse/config/providers/registry/alibaba/cn/index.ts +15 -0
- package/open-sse/config/providers/registry/alibaba/index.ts +15 -0
- package/open-sse/config/providers/registry/anthropic/index.ts +52 -0
- package/open-sse/config/providers/registry/antigravity/index.ts +28 -0
- package/open-sse/config/providers/registry/api-airforce/index.ts +57 -0
- package/open-sse/config/providers/registry/auggie/index.ts +38 -0
- package/open-sse/config/providers/registry/bai/index.ts +14 -0
- package/open-sse/config/providers/registry/baichuan/index.ts +20 -0
- package/open-sse/config/providers/registry/baidu/index.ts +31 -0
- package/open-sse/config/providers/registry/bailian-coding-plan/index.ts +27 -0
- package/open-sse/config/providers/registry/baseten/index.ts +13 -0
- package/open-sse/config/providers/registry/bazaarlink/index.ts +48 -0
- package/open-sse/config/providers/registry/bedrock/index.ts +49 -0
- package/open-sse/config/providers/registry/blackbox/index.ts +25 -0
- package/open-sse/config/providers/registry/blackbox/web/index.ts +19 -0
- package/open-sse/config/providers/registry/bluesminds/index.ts +39 -0
- package/open-sse/config/providers/registry/byteplus/index.ts +21 -0
- package/open-sse/config/providers/registry/bytez/index.ts +17 -0
- package/open-sse/config/providers/registry/cerebras/index.ts +16 -0
- package/open-sse/config/providers/registry/charm-hyper/index.ts +14 -0
- package/open-sse/config/providers/registry/chatgpt-web/index.ts +23 -0
- package/open-sse/config/providers/registry/chipotle/index.ts +14 -0
- package/open-sse/config/providers/registry/chutes/index.ts +12 -0
- package/open-sse/config/providers/registry/claude/index.ts +102 -0
- package/open-sse/config/providers/registry/claude/web/index.ts +16 -0
- package/open-sse/config/providers/registry/cline/index.ts +45 -0
- package/open-sse/config/providers/registry/clinepass/index.ts +47 -0
- package/open-sse/config/providers/registry/cloudflare-ai/index.ts +33 -0
- package/open-sse/config/providers/registry/codebuddy-cn/index.ts +151 -0
- package/open-sse/config/providers/registry/codestral/index.ts +13 -0
- package/open-sse/config/providers/registry/codex/index.ts +115 -0
- package/open-sse/config/providers/registry/cohere/index.ts +28 -0
- package/open-sse/config/providers/registry/command-code/index.ts +143 -0
- package/open-sse/config/providers/registry/copilot-m365-web/index.ts +12 -0
- package/open-sse/config/providers/registry/copilot-web/index.ts +16 -0
- package/open-sse/config/providers/registry/coze/index.ts +12 -0
- package/open-sse/config/providers/registry/crof/index.ts +38 -0
- package/open-sse/config/providers/registry/cursor/index.ts +111 -0
- package/open-sse/config/providers/registry/databricks/index.ts +13 -0
- package/open-sse/config/providers/registry/deepinfra/index.ts +13 -0
- package/open-sse/config/providers/registry/deepseek/index.ts +15 -0
- package/open-sse/config/providers/registry/deepseek/web/index.ts +35 -0
- package/open-sse/config/providers/registry/devin-cli/index.ts +68 -0
- package/open-sse/config/providers/registry/dgrid/index.ts +15 -0
- package/open-sse/config/providers/registry/dify/index.ts +12 -0
- package/open-sse/config/providers/registry/digitalocean/index.ts +11 -0
- package/open-sse/config/providers/registry/dit/index.ts +41 -0
- package/open-sse/config/providers/registry/doubao/index.ts +28 -0
- package/open-sse/config/providers/registry/doubao/web/index.ts +15 -0
- package/open-sse/config/providers/registry/duckduckgo-web/index.ts +19 -0
- package/open-sse/config/providers/registry/factory/index.ts +33 -0
- package/open-sse/config/providers/registry/featherless-ai/index.ts +13 -0
- package/open-sse/config/providers/registry/fireworks/index.ts +35 -0
- package/open-sse/config/providers/registry/freeaiapikey/index.ts +38 -0
- package/open-sse/config/providers/registry/freemodel-dev/index.ts +19 -0
- package/open-sse/config/providers/registry/friendliai/index.ts +16 -0
- package/open-sse/config/providers/registry/galadriel/index.ts +13 -0
- package/open-sse/config/providers/registry/gemini/index.ts +63 -0
- package/open-sse/config/providers/registry/gemini/web/index.ts +16 -0
- package/open-sse/config/providers/registry/gigachat/index.ts +13 -0
- package/open-sse/config/providers/registry/github/index.ts +161 -0
- package/open-sse/config/providers/registry/github/models/index.ts +38 -0
- package/open-sse/config/providers/registry/gitlab-duo/index.ts +29 -0
- package/open-sse/config/providers/registry/gitlawb/gmi/index.ts +19 -0
- package/open-sse/config/providers/registry/gitlawb/index.ts +18 -0
- package/open-sse/config/providers/registry/glhf/index.ts +12 -0
- package/open-sse/config/providers/registry/glm/cn/index.ts +17 -0
- package/open-sse/config/providers/registry/glm/index.ts +16 -0
- package/open-sse/config/providers/registry/glm/t/index.ts +16 -0
- package/open-sse/config/providers/registry/grok-cli/index.ts +32 -0
- package/open-sse/config/providers/registry/grok-web/index.ts +18 -0
- package/open-sse/config/providers/registry/groq/index.ts +25 -0
- package/open-sse/config/providers/registry/hackclub/index.ts +19 -0
- package/open-sse/config/providers/registry/haiper/index.ts +15 -0
- package/open-sse/config/providers/registry/hcnsec/index.ts +11 -0
- package/open-sse/config/providers/registry/heroku/index.ts +13 -0
- package/open-sse/config/providers/registry/huggingchat/index.ts +143 -0
- package/open-sse/config/providers/registry/huggingface/index.ts +20 -0
- package/open-sse/config/providers/registry/hyperbolic/index.ts +21 -0
- package/open-sse/config/providers/registry/ideogram/index.ts +15 -0
- package/open-sse/config/providers/registry/iflytek/index.ts +21 -0
- package/open-sse/config/providers/registry/inclusionai/index.ts +12 -0
- package/open-sse/config/providers/registry/inference-net/index.ts +13 -0
- package/open-sse/config/providers/registry/inner-ai/index.ts +43 -0
- package/open-sse/config/providers/registry/kenari/index.ts +14 -0
- package/open-sse/config/providers/registry/kie/index.ts +27 -0
- package/open-sse/config/providers/registry/kilo-gateway/index.ts +21 -0
- package/open-sse/config/providers/registry/kilocode/index.ts +43 -0
- package/open-sse/config/providers/registry/kimi/coding/index.ts +17 -0
- package/open-sse/config/providers/registry/kimi/coding-apikey/index.ts +9 -0
- package/open-sse/config/providers/registry/kimi/index.ts +17 -0
- package/open-sse/config/providers/registry/kimi/web/index.ts +27 -0
- package/open-sse/config/providers/registry/kiro/index.ts +50 -0
- package/open-sse/config/providers/registry/kluster/index.ts +12 -0
- package/open-sse/config/providers/registry/lambda-ai/index.ts +13 -0
- package/open-sse/config/providers/registry/leonardo/index.ts +15 -0
- package/open-sse/config/providers/registry/liquid/index.ts +12 -0
- package/open-sse/config/providers/registry/llamagate/index.ts +13 -0
- package/open-sse/config/providers/registry/llm7/index.ts +27 -0
- package/open-sse/config/providers/registry/longcat/index.ts +24 -0
- package/open-sse/config/providers/registry/maritalk/index.ts +13 -0
- package/open-sse/config/providers/registry/meta-llama/index.ts +13 -0
- package/open-sse/config/providers/registry/mimocode/index.ts +16 -0
- package/open-sse/config/providers/registry/minimax/cn/index.ts +24 -0
- package/open-sse/config/providers/registry/minimax/index.ts +24 -0
- package/open-sse/config/providers/registry/mistral/index.ts +18 -0
- package/open-sse/config/providers/registry/modal/index.ts +12 -0
- package/open-sse/config/providers/registry/modelscope/index.ts +24 -0
- package/open-sse/config/providers/registry/monsterapi/index.ts +17 -0
- package/open-sse/config/providers/registry/moonshot/index.ts +13 -0
- package/open-sse/config/providers/registry/morph/index.ts +13 -0
- package/open-sse/config/providers/registry/muse-spark-web/index.ts +24 -0
- package/open-sse/config/providers/registry/nanogpt/index.ts +13 -0
- package/open-sse/config/providers/registry/nebius/index.ts +9 -0
- package/open-sse/config/providers/registry/nlpcloud/index.ts +19 -0
- package/open-sse/config/providers/registry/nous-research/index.ts +15 -0
- package/open-sse/config/providers/registry/novita/index.ts +15 -0
- package/open-sse/config/providers/registry/nscale/index.ts +13 -0
- package/open-sse/config/providers/registry/nube/index.ts +17 -0
- package/open-sse/config/providers/registry/nvidia/index.ts +36 -0
- package/open-sse/config/providers/registry/ollama-cloud/index.ts +27 -0
- package/open-sse/config/providers/registry/openadapter/index.ts +25 -0
- package/open-sse/config/providers/registry/openai/index.ts +43 -0
- package/open-sse/config/providers/registry/opencode/go/index.ts +61 -0
- package/open-sse/config/providers/registry/opencode/index.ts +51 -0
- package/open-sse/config/providers/registry/opencode/zen/index.ts +98 -0
- package/open-sse/config/providers/registry/openrouter/index.ts +17 -0
- package/open-sse/config/providers/registry/orcarouter/index.ts +87 -0
- package/open-sse/config/providers/registry/ovhcloud/index.ts +13 -0
- package/open-sse/config/providers/registry/perplexity/index.ts +22 -0
- package/open-sse/config/providers/registry/perplexity/web/index.ts +23 -0
- package/open-sse/config/providers/registry/pioneer/index.ts +41 -0
- package/open-sse/config/providers/registry/pollinations/index.ts +51 -0
- package/open-sse/config/providers/registry/predibase/index.ts +13 -0
- package/open-sse/config/providers/registry/publicai/index.ts +13 -0
- package/open-sse/config/providers/registry/puter/index.ts +70 -0
- package/open-sse/config/providers/registry/qianfan/index.ts +18 -0
- package/open-sse/config/providers/registry/qiniu/index.ts +15 -0
- package/open-sse/config/providers/registry/qoder/index.ts +37 -0
- package/open-sse/config/providers/registry/qwen/index.ts +25 -0
- package/open-sse/config/providers/registry/qwen/web/index.ts +24 -0
- package/open-sse/config/providers/registry/reka/index.ts +18 -0
- package/open-sse/config/providers/registry/requesty/index.ts +11 -0
- package/open-sse/config/providers/registry/sambanova/index.ts +13 -0
- package/open-sse/config/providers/registry/scaleway/index.ts +20 -0
- package/open-sse/config/providers/registry/sensenova/index.ts +27 -0
- package/open-sse/config/providers/registry/siliconflow/index.ts +84 -0
- package/open-sse/config/providers/registry/snowflake/index.ts +13 -0
- package/open-sse/config/providers/registry/sparkdesk/index.ts +20 -0
- package/open-sse/config/providers/registry/stepfun/index.ts +20 -0
- package/open-sse/config/providers/registry/sumopod/index.ts +15 -0
- package/open-sse/config/providers/registry/suno/index.ts +18 -0
- package/open-sse/config/providers/registry/synthetic/index.ts +21 -0
- package/open-sse/config/providers/registry/t3-web/index.ts +45 -0
- package/open-sse/config/providers/registry/tencent/index.ts +25 -0
- package/open-sse/config/providers/registry/theoldllm/index.ts +51 -0
- package/open-sse/config/providers/registry/together/index.ts +20 -0
- package/open-sse/config/providers/registry/tokenrouter/index.ts +44 -0
- package/open-sse/config/providers/registry/trae/index.ts +24 -0
- package/open-sse/config/providers/registry/udio/index.ts +12 -0
- package/open-sse/config/providers/registry/uncloseai/index.ts +19 -0
- package/open-sse/config/providers/registry/upstage/index.ts +13 -0
- package/open-sse/config/providers/registry/v0-vercel/index.ts +13 -0
- package/open-sse/config/providers/registry/venice/index.ts +13 -0
- package/open-sse/config/providers/registry/veoaifree-web/index.ts +15 -0
- package/open-sse/config/providers/registry/vercel-ai-gateway/index.ts +13 -0
- package/open-sse/config/providers/registry/vertex/index.ts +33 -0
- package/open-sse/config/providers/registry/vertex/partner/index.ts +22 -0
- package/open-sse/config/providers/registry/volcengine/index.ts +13 -0
- package/open-sse/config/providers/registry/wafer/index.ts +19 -0
- package/open-sse/config/providers/registry/wandb/index.ts +13 -0
- package/open-sse/config/providers/registry/windsurf/index.ts +119 -0
- package/open-sse/config/providers/registry/x5lab/index.ts +15 -0
- package/open-sse/config/providers/registry/xai/index.ts +18 -0
- package/open-sse/config/providers/registry/xiaomi-mimo/index.ts +13 -0
- package/open-sse/config/providers/registry/yi/index.ts +12 -0
- package/open-sse/config/providers/registry/yuanbao-web/index.ts +37 -0
- package/open-sse/config/providers/registry/zai/index.ts +28 -0
- package/open-sse/config/providers/registry/zed-hosted/index.ts +35 -0
- package/open-sse/config/providers/registry/zenmux/index.ts +87 -0
- package/open-sse/config/providers/registry/zenmux-free/index.ts +40 -0
- package/open-sse/config/providers/shared.ts +766 -0
- package/open-sse/config/registryUtils.ts +134 -0
- package/open-sse/config/rerankRegistry.ts +196 -0
- package/open-sse/config/runway.ts +39 -0
- package/open-sse/config/sap.ts +58 -0
- package/open-sse/config/searchRegistry.ts +317 -0
- package/open-sse/config/toolCloaking.ts +253 -0
- package/open-sse/config/videoRegistry.ts +229 -0
- package/open-sse/config/watsonx.ts +43 -0
- package/open-sse/executors/adapta-web.ts +564 -0
- package/open-sse/executors/antigravity/sseCollect.ts +148 -0
- package/open-sse/executors/antigravity.ts +1716 -0
- package/open-sse/executors/antigravityUpstreamError.ts +25 -0
- package/open-sse/executors/auggie.ts +573 -0
- package/open-sse/executors/azure-openai.ts +48 -0
- package/open-sse/executors/base/headers.ts +93 -0
- package/open-sse/executors/base/reasoningEffort.ts +160 -0
- package/open-sse/executors/base.ts +1315 -0
- package/open-sse/executors/bedrock.ts +714 -0
- package/open-sse/executors/blackbox-web.ts +708 -0
- package/open-sse/executors/chatgpt-web/models.ts +133 -0
- package/open-sse/executors/chatgpt-web.ts +3107 -0
- package/open-sse/executors/chatgptWebErrors.ts +18 -0
- package/open-sse/executors/chatgptWebTools.ts +127 -0
- package/open-sse/executors/chipotle.ts +432 -0
- package/open-sse/executors/claude-web/payload.ts +230 -0
- package/open-sse/executors/claude-web-with-auto-refresh.ts +117 -0
- package/open-sse/executors/claude-web.ts +833 -0
- package/open-sse/executors/claudeIdentity.ts +445 -0
- package/open-sse/executors/cliproxyapi.ts +466 -0
- package/open-sse/executors/cloudflare-ai.ts +97 -0
- package/open-sse/executors/codebuddy-cn.ts +53 -0
- package/open-sse/executors/codex/quota.ts +114 -0
- package/open-sse/executors/codex/tools.ts +165 -0
- package/open-sse/executors/codex.ts +1270 -0
- package/open-sse/executors/commandCode.ts +716 -0
- package/open-sse/executors/copilot-m365-connection.ts +271 -0
- package/open-sse/executors/copilot-m365-frames.ts +279 -0
- package/open-sse/executors/copilot-m365-web.ts +341 -0
- package/open-sse/executors/copilot-web.ts +722 -0
- package/open-sse/executors/cursor/composer.ts +53 -0
- package/open-sse/executors/cursor/prompt.ts +75 -0
- package/open-sse/executors/cursor.ts +1465 -0
- package/open-sse/executors/deepseek-web/stream-format.ts +44 -0
- package/open-sse/executors/deepseek-web-with-auto-refresh.ts +184 -0
- package/open-sse/executors/deepseek-web.ts +1123 -0
- package/open-sse/executors/default/urlNormalizers.ts +64 -0
- package/open-sse/executors/default.ts +873 -0
- package/open-sse/executors/devin-cli.ts +470 -0
- package/open-sse/executors/doubao-web.ts +665 -0
- package/open-sse/executors/duckduckgo-web/challenge.ts +151 -0
- package/open-sse/executors/duckduckgo-web.ts +782 -0
- package/open-sse/executors/firecrawl-fetch.ts +177 -0
- package/open-sse/executors/forceResponsesUpstream.ts +60 -0
- package/open-sse/executors/gemini-business.ts +446 -0
- package/open-sse/executors/gemini-web.ts +413 -0
- package/open-sse/executors/github.ts +376 -0
- package/open-sse/executors/gitlab.ts +793 -0
- package/open-sse/executors/gitlabResponses.ts +191 -0
- package/open-sse/executors/glm.ts +520 -0
- package/open-sse/executors/grok-cli.ts +253 -0
- package/open-sse/executors/grok-web/native-tools.ts +182 -0
- package/open-sse/executors/grok-web/text-cleanup.ts +137 -0
- package/open-sse/executors/grok-web/tool-bridge.ts +666 -0
- package/open-sse/executors/grok-web/types.ts +47 -0
- package/open-sse/executors/grok-web.ts +883 -0
- package/open-sse/executors/huggingchat/jsonlStream.ts +221 -0
- package/open-sse/executors/huggingchat.ts +593 -0
- package/open-sse/executors/index.ts +232 -0
- package/open-sse/executors/inner-ai.ts +764 -0
- package/open-sse/executors/jina-reader-fetch.ts +119 -0
- package/open-sse/executors/kie.ts +109 -0
- package/open-sse/executors/kimi-web.ts +455 -0
- package/open-sse/executors/kimi.ts +133 -0
- package/open-sse/executors/kiro/eventstream.ts +192 -0
- package/open-sse/executors/kiro.ts +821 -0
- package/open-sse/executors/kiroThinking.ts +116 -0
- package/open-sse/executors/lmarena.ts +511 -0
- package/open-sse/executors/mimocode.ts +560 -0
- package/open-sse/executors/muse-spark-web/response-parser.ts +383 -0
- package/open-sse/executors/muse-spark-web.ts +928 -0
- package/open-sse/executors/ninerouter.ts +212 -0
- package/open-sse/executors/nlpcloud.ts +546 -0
- package/open-sse/executors/opencode.ts +336 -0
- package/open-sse/executors/perplexity-web/protocol.ts +503 -0
- package/open-sse/executors/perplexity-web.ts +545 -0
- package/open-sse/executors/poe-web.ts +158 -0
- package/open-sse/executors/pollinations.ts +119 -0
- package/open-sse/executors/puter.ts +59 -0
- package/open-sse/executors/qoder.ts +416 -0
- package/open-sse/executors/qwen-web.ts +474 -0
- package/open-sse/executors/t3-chat-web.ts +582 -0
- package/open-sse/executors/tavily-fetch.ts +103 -0
- package/open-sse/executors/theoldllm.ts +354 -0
- package/open-sse/executors/tinyfish-fetch.ts +131 -0
- package/open-sse/executors/trae.ts +481 -0
- package/open-sse/executors/v0-vercel-web.ts +164 -0
- package/open-sse/executors/venice-web.ts +165 -0
- package/open-sse/executors/veoaifree-web.ts +397 -0
- package/open-sse/executors/vertex.ts +208 -0
- package/open-sse/executors/vertexMedia.ts +341 -0
- package/open-sse/executors/windsurf.ts +706 -0
- package/open-sse/executors/xai.ts +94 -0
- package/open-sse/executors/yuanbao-web.ts +504 -0
- package/open-sse/executors/zed-hosted.ts +364 -0
- package/open-sse/executors/zenmux-free.ts +283 -0
- package/open-sse/handlers/audioSpeech.ts +1060 -0
- package/open-sse/handlers/audioTranscription.ts +554 -0
- package/open-sse/handlers/audioTranslation.ts +135 -0
- package/open-sse/handlers/chatCore/attemptLogging.ts +210 -0
- package/open-sse/handlers/chatCore/backgroundRedirect.ts +41 -0
- package/open-sse/handlers/chatCore/cacheUsageMeta.ts +65 -0
- package/open-sse/handlers/chatCore/cavemanOutputAnalytics.ts +47 -0
- package/open-sse/handlers/chatCore/claudeClassifierCompat.ts +99 -0
- package/open-sse/handlers/chatCore/claudeEffortVariant.ts +62 -0
- package/open-sse/handlers/chatCore/claudeMessageTypes.ts +15 -0
- package/open-sse/handlers/chatCore/claudeSystemRole.ts +48 -0
- package/open-sse/handlers/chatCore/claudeToolDefaults.ts +27 -0
- package/open-sse/handlers/chatCore/claudeUpstreamMessages.ts +143 -0
- package/open-sse/handlers/chatCore/clientUsageBuffer.ts +54 -0
- package/open-sse/handlers/chatCore/clineResponseEnvelope.ts +25 -0
- package/open-sse/handlers/chatCore/codexFailover.ts +41 -0
- package/open-sse/handlers/chatCore/codexQuota.ts +85 -0
- package/open-sse/handlers/chatCore/comboContextCache.ts +63 -0
- package/open-sse/handlers/chatCore/compressionAnalyticsWrite.ts +149 -0
- package/open-sse/handlers/chatCore/compressionCacheStats.ts +53 -0
- package/open-sse/handlers/chatCore/compressionComboPredicates.ts +41 -0
- package/open-sse/handlers/chatCore/compressionSettings.ts +35 -0
- package/open-sse/handlers/chatCore/compressionUsageReceipt.ts +27 -0
- package/open-sse/handlers/chatCore/contextEditingTelemetry.ts +40 -0
- package/open-sse/handlers/chatCore/cooldownClassification.ts +26 -0
- package/open-sse/handlers/chatCore/executionCredentials.ts +72 -0
- package/open-sse/handlers/chatCore/executorClientHeaders.ts +36 -0
- package/open-sse/handlers/chatCore/executorHelpers.ts +151 -0
- package/open-sse/handlers/chatCore/executorProxy.ts +117 -0
- package/open-sse/handlers/chatCore/failureUsage.ts +41 -0
- package/open-sse/handlers/chatCore/gamificationEvent.ts +28 -0
- package/open-sse/handlers/chatCore/headers.ts +65 -0
- package/open-sse/handlers/chatCore/idempotency.ts +65 -0
- package/open-sse/handlers/chatCore/jsonBodyToSse.ts +161 -0
- package/open-sse/handlers/chatCore/keyHealth.ts +113 -0
- package/open-sse/handlers/chatCore/logTruncation.ts +93 -0
- package/open-sse/handlers/chatCore/memoryExtraction.ts +131 -0
- package/open-sse/handlers/chatCore/memorySkillsInjection.ts +165 -0
- package/open-sse/handlers/chatCore/nonStreamingJsonResponse.ts +16 -0
- package/open-sse/handlers/chatCore/nonStreamingResponseBody.ts +155 -0
- package/open-sse/handlers/chatCore/nonStreamingResponseHeaders.ts +46 -0
- package/open-sse/handlers/chatCore/nonStreamingResponseParse.ts +135 -0
- package/open-sse/handlers/chatCore/nonStreamingSse.ts +171 -0
- package/open-sse/handlers/chatCore/nonStreamingUsageStats.ts +90 -0
- package/open-sse/handlers/chatCore/outputStyleTelemetry.ts +53 -0
- package/open-sse/handlers/chatCore/passthroughHelpers.ts +83 -0
- package/open-sse/handlers/chatCore/passthroughToolNames.ts +65 -0
- package/open-sse/handlers/chatCore/pluginOnRequest.ts +65 -0
- package/open-sse/handlers/chatCore/pluginOnResponse.ts +34 -0
- package/open-sse/handlers/chatCore/postCallGuardrailContext.ts +47 -0
- package/open-sse/handlers/chatCore/quotaShareConsumption.ts +41 -0
- package/open-sse/handlers/chatCore/requestFormat.ts +111 -0
- package/open-sse/handlers/chatCore/requestSetup.ts +51 -0
- package/open-sse/handlers/chatCore/responseHeaders.ts +138 -0
- package/open-sse/handlers/chatCore/sanitization.ts +63 -0
- package/open-sse/handlers/chatCore/semanticCache.ts +98 -0
- package/open-sse/handlers/chatCore/semanticCacheStore.ts +73 -0
- package/open-sse/handlers/chatCore/serviceTier.ts +70 -0
- package/open-sse/handlers/chatCore/skillsFormat.ts +33 -0
- package/open-sse/handlers/chatCore/stageTrace.ts +30 -0
- package/open-sse/handlers/chatCore/streamErrorResult.ts +58 -0
- package/open-sse/handlers/chatCore/streamFinalize.ts +48 -0
- package/open-sse/handlers/chatCore/streamingCost.ts +37 -0
- package/open-sse/handlers/chatCore/streamingPipeline.ts +99 -0
- package/open-sse/handlers/chatCore/streamingQuotaShare.ts +54 -0
- package/open-sse/handlers/chatCore/streamingResponseHeaders.ts +39 -0
- package/open-sse/handlers/chatCore/streamingSemanticCacheStore.ts +95 -0
- package/open-sse/handlers/chatCore/streamingUsageStats.ts +79 -0
- package/open-sse/handlers/chatCore/targetFormat.ts +34 -0
- package/open-sse/handlers/chatCore/telemetryHelpers.ts +78 -0
- package/open-sse/handlers/chatCore/upstreamBody.ts +168 -0
- package/open-sse/handlers/chatCore/upstreamExecuteHeaders.ts +71 -0
- package/open-sse/handlers/chatCore/upstreamTimeouts.ts +158 -0
- package/open-sse/handlers/chatCore.ts +4452 -0
- package/open-sse/handlers/embeddings.ts +378 -0
- package/open-sse/handlers/imageGeneration/providers/chatgptWeb.ts +187 -0
- package/open-sse/handlers/imageGeneration/providers/comfyUI.ts +116 -0
- package/open-sse/handlers/imageGeneration/providers/haiper.ts +120 -0
- package/open-sse/handlers/imageGeneration/providers/huggingface.ts +90 -0
- package/open-sse/handlers/imageGeneration/providers/hyperbolic.ts +100 -0
- package/open-sse/handlers/imageGeneration/providers/ideogram.ts +96 -0
- package/open-sse/handlers/imageGeneration/providers/imagen3.ts +136 -0
- package/open-sse/handlers/imageGeneration/providers/leonardo.ts +140 -0
- package/open-sse/handlers/imageGeneration/providers/nvidiaNim.ts +286 -0
- package/open-sse/handlers/imageGeneration/providers/sdWebUI.ts +94 -0
- package/open-sse/handlers/imageGeneration.ts +2880 -0
- package/open-sse/handlers/moderations.ts +82 -0
- package/open-sse/handlers/musicGeneration.ts +640 -0
- package/open-sse/handlers/ocr.ts +79 -0
- package/open-sse/handlers/rerank.ts +210 -0
- package/open-sse/handlers/responseSanitizer/reasoning.ts +149 -0
- package/open-sse/handlers/responseSanitizer.ts +1086 -0
- package/open-sse/handlers/responseTranslator.ts +640 -0
- package/open-sse/handlers/responsesHandler.ts +92 -0
- package/open-sse/handlers/search.ts +1545 -0
- package/open-sse/handlers/sseParser.ts +825 -0
- package/open-sse/handlers/usageExtractor.ts +93 -0
- package/open-sse/handlers/videoGeneration/googleFlow.ts +219 -0
- package/open-sse/handlers/videoGeneration/googleFlowHandler.ts +145 -0
- package/open-sse/handlers/videoGeneration.ts +1264 -0
- package/open-sse/handlers/webFetch.ts +130 -0
- package/open-sse/index.ts +170 -0
- package/open-sse/lib/deepseek-pow-solver.cjs +3 -0
- package/open-sse/lib/deepseek-pow.ts +189 -0
- package/open-sse/lib/sha3_wasm_bg.wasm +0 -0
- package/open-sse/mcp-server/README.md +611 -0
- package/open-sse/mcp-server/audit.ts +478 -0
- package/open-sse/mcp-server/catalog.ts +290 -0
- package/open-sse/mcp-server/descriptionCompressor.ts +243 -0
- package/open-sse/mcp-server/httpAuthContext.ts +42 -0
- package/open-sse/mcp-server/httpTransport.ts +306 -0
- package/open-sse/mcp-server/index.ts +19 -0
- package/open-sse/mcp-server/mcpCallerIdentity.ts +53 -0
- package/open-sse/mcp-server/runtimeHeartbeat.ts +162 -0
- package/open-sse/mcp-server/schemas/a2a.ts +203 -0
- package/open-sse/mcp-server/schemas/audit.ts +121 -0
- package/open-sse/mcp-server/schemas/index.ts +116 -0
- package/open-sse/mcp-server/schemas/pickFastestModel.ts +110 -0
- package/open-sse/mcp-server/schemas/toolDefinition.ts +31 -0
- package/open-sse/mcp-server/schemas/toolSearch.ts +37 -0
- package/open-sse/mcp-server/schemas/tools.ts +1481 -0
- package/open-sse/mcp-server/scopeEnforcement.ts +135 -0
- package/open-sse/mcp-server/server.ts +1370 -0
- package/open-sse/mcp-server/toolCardinality.ts +254 -0
- package/open-sse/mcp-server/toolSearch/catalog.ts +98 -0
- package/open-sse/mcp-server/toolSearch/handler.ts +18 -0
- package/open-sse/mcp-server/toolSearch/index.ts +5 -0
- package/open-sse/mcp-server/toolSearch/register.ts +36 -0
- package/open-sse/mcp-server/toolSearch/search.ts +96 -0
- package/open-sse/mcp-server/toolSearch/signature.ts +92 -0
- package/open-sse/mcp-server/tools/advancedTools.ts +1119 -0
- package/open-sse/mcp-server/tools/agentSkillTools.ts +83 -0
- package/open-sse/mcp-server/tools/compressionTools.ts +451 -0
- package/open-sse/mcp-server/tools/gamificationTools.ts +148 -0
- package/open-sse/mcp-server/tools/githubSkillTools.ts +141 -0
- package/open-sse/mcp-server/tools/memoryTools.ts +137 -0
- package/open-sse/mcp-server/tools/notionTools.ts +106 -0
- package/open-sse/mcp-server/tools/obsidianTools.ts +327 -0
- package/open-sse/mcp-server/tools/pickFastestModel.ts +293 -0
- package/open-sse/mcp-server/tools/pluginTools.ts +216 -0
- package/open-sse/mcp-server/tools/poolTools.ts +205 -0
- package/open-sse/mcp-server/tools/skillTools.ts +119 -0
- package/open-sse/package.json +17 -0
- package/open-sse/services/AGENTS.md +78 -0
- package/open-sse/services/accountFallback.ts +1863 -0
- package/open-sse/services/accountSelector.ts +80 -0
- package/open-sse/services/accountSemaphore.ts +367 -0
- package/open-sse/services/antigravity429Engine.ts +178 -0
- package/open-sse/services/antigravityClientProfile.ts +167 -0
- package/open-sse/services/antigravityCredits.ts +68 -0
- package/open-sse/services/antigravityHeaderScrub.ts +75 -0
- package/open-sse/services/antigravityHeaders.ts +121 -0
- package/open-sse/services/antigravityIdentity.ts +127 -0
- package/open-sse/services/antigravityObfuscation.ts +64 -0
- package/open-sse/services/antigravityProjectBootstrap.ts +145 -0
- package/open-sse/services/antigravityQuotaFamily.ts +56 -0
- package/open-sse/services/antigravityVersion.ts +163 -0
- package/open-sse/services/apiKeyRotator.ts +385 -0
- package/open-sse/services/autoCombo/autoPrefix.ts +61 -0
- package/open-sse/services/autoCombo/builtinCatalog.ts +126 -0
- package/open-sse/services/autoCombo/complexityRouter.ts +111 -0
- package/open-sse/services/autoCombo/engine.ts +314 -0
- package/open-sse/services/autoCombo/index.ts +18 -0
- package/open-sse/services/autoCombo/modePacks.ts +105 -0
- package/open-sse/services/autoCombo/modelFamily.ts +95 -0
- package/open-sse/services/autoCombo/paidModelFilter.ts +44 -0
- package/open-sse/services/autoCombo/persistence.ts +124 -0
- package/open-sse/services/autoCombo/pipelineRouter.ts +418 -0
- package/open-sse/services/autoCombo/providerDiversity.ts +170 -0
- package/open-sse/services/autoCombo/providerRegistryAccessor.ts +9 -0
- package/open-sse/services/autoCombo/requestControls.ts +80 -0
- package/open-sse/services/autoCombo/routerStrategy.ts +375 -0
- package/open-sse/services/autoCombo/scoring.ts +242 -0
- package/open-sse/services/autoCombo/selfHealing.ts +167 -0
- package/open-sse/services/autoCombo/speedRanking.ts +327 -0
- package/open-sse/services/autoCombo/suffixComposition.ts +147 -0
- package/open-sse/services/autoCombo/taskFitness.ts +407 -0
- package/open-sse/services/autoCombo/virtualFactory.ts +446 -0
- package/open-sse/services/autoRefreshDaemon.ts +206 -0
- package/open-sse/services/backgroundTaskDetector.ts +263 -0
- package/open-sse/services/bailianQuotaFetcher.ts +333 -0
- package/open-sse/services/batchProcessor.ts +914 -0
- package/open-sse/services/bedrock.ts +160 -0
- package/open-sse/services/browserBackedChat.ts +849 -0
- package/open-sse/services/browserPool.ts +501 -0
- package/open-sse/services/ccBridgeTransforms.ts +581 -0
- package/open-sse/services/ccWireImageBuiltins.ts +26 -0
- package/open-sse/services/chatgptImageCache.ts +143 -0
- package/open-sse/services/chatgptTlsClient.ts +628 -0
- package/open-sse/services/claudeAdaptiveThinking.ts +52 -0
- package/open-sse/services/claudeCodeCCH.ts +49 -0
- package/open-sse/services/claudeCodeCompatible.ts +1198 -0
- package/open-sse/services/claudeCodeCompatibleBeta.ts +23 -0
- package/open-sse/services/claudeCodeCompatibleThinkingDisplay.ts +34 -0
- package/open-sse/services/claudeCodeConstraints.ts +144 -0
- package/open-sse/services/claudeCodeExtraRemap.ts +18 -0
- package/open-sse/services/claudeCodeFingerprint.ts +46 -0
- package/open-sse/services/claudeCodeObfuscation.ts +116 -0
- package/open-sse/services/claudeCodeToolRemapper.ts +339 -0
- package/open-sse/services/claudeHaikuConstraints.ts +88 -0
- package/open-sse/services/claudeTlsClient.ts +590 -0
- package/open-sse/services/claudeTurnstileSolver.ts +206 -0
- package/open-sse/services/claudeUsageCooldown.ts +51 -0
- package/open-sse/services/claudeWebAutoRefresh.ts +224 -0
- package/open-sse/services/clinepassModels.ts +76 -0
- package/open-sse/services/cloudCodeHeaders.ts +41 -0
- package/open-sse/services/cloudCodeThinking.ts +71 -0
- package/open-sse/services/codeAssistSubscription.ts +83 -0
- package/open-sse/services/codexQuotaFetcher.ts +523 -0
- package/open-sse/services/codexUsageQuotas.ts +270 -0
- package/open-sse/services/codexVerbosity.ts +59 -0
- package/open-sse/services/combo/applyStrategyOrdering.ts +226 -0
- package/open-sse/services/combo/autoConfig.ts +62 -0
- package/open-sse/services/combo/autoStrategy.ts +475 -0
- package/open-sse/services/combo/comboCompatFallback.ts +82 -0
- package/open-sse/services/combo/comboCooldownRetry.ts +237 -0
- package/open-sse/services/combo/comboData.ts +24 -0
- package/open-sse/services/combo/comboPredicates.ts +211 -0
- package/open-sse/services/combo/comboSetup.ts +135 -0
- package/open-sse/services/combo/comboStructure.ts +766 -0
- package/open-sse/services/combo/concurrencyCaps.ts +76 -0
- package/open-sse/services/combo/context.ts +46 -0
- package/open-sse/services/combo/fingerprintExpansion.ts +105 -0
- package/open-sse/services/combo/headroomRanking.ts +91 -0
- package/open-sse/services/combo/providerWildcard.ts +253 -0
- package/open-sse/services/combo/quotaExhaustionCutoff.ts +140 -0
- package/open-sse/services/combo/quotaScoring.ts +311 -0
- package/open-sse/services/combo/quotaShareConcurrency.ts +74 -0
- package/open-sse/services/combo/quotaShareInflight.ts +133 -0
- package/open-sse/services/combo/quotaShareStrategy.ts +349 -0
- package/open-sse/services/combo/quotaStrategies.ts +647 -0
- package/open-sse/services/combo/resolveAutoStrategy.ts +334 -0
- package/open-sse/services/combo/responseValidation.ts +206 -0
- package/open-sse/services/combo/rrState.ts +98 -0
- package/open-sse/services/combo/runtimeUnits.ts +269 -0
- package/open-sse/services/combo/sessionStickiness.ts +301 -0
- package/open-sse/services/combo/shadowRouting.ts +179 -0
- package/open-sse/services/combo/targetExhaustion.ts +160 -0
- package/open-sse/services/combo/targetSorters.ts +174 -0
- package/open-sse/services/combo/targetTimeoutRunner.ts +91 -0
- package/open-sse/services/combo/types.ts +175 -0
- package/open-sse/services/combo/validateQuality.ts +445 -0
- package/open-sse/services/combo.ts +3085 -0
- package/open-sse/services/comboAgentMiddleware.ts +214 -0
- package/open-sse/services/comboConfig.ts +248 -0
- package/open-sse/services/comboManifestMetrics.ts +13 -0
- package/open-sse/services/comboMetrics.ts +480 -0
- package/open-sse/services/compression/adaptiveCompression/computeTarget.ts +31 -0
- package/open-sse/services/compression/adaptiveCompression/ladder.ts +59 -0
- package/open-sse/services/compression/adaptiveCompression/resolveAdaptivePlan.ts +104 -0
- package/open-sse/services/compression/adaptiveCompression/types.ts +61 -0
- package/open-sse/services/compression/aggressive.ts +204 -0
- package/open-sse/services/compression/bodyAdapter.ts +354 -0
- package/open-sse/services/compression/cacheAwareConfig.ts +60 -0
- package/open-sse/services/compression/cachingAware.ts +130 -0
- package/open-sse/services/compression/caveman.ts +602 -0
- package/open-sse/services/compression/cavemanRules.ts +432 -0
- package/open-sse/services/compression/deriveDefaultPlan.ts +59 -0
- package/open-sse/services/compression/diffHelper.ts +219 -0
- package/open-sse/services/compression/engineBreakdown.ts +29 -0
- package/open-sse/services/compression/engineCatalog.ts +91 -0
- package/open-sse/services/compression/engines/cavemanAdapter.ts +454 -0
- package/open-sse/services/compression/engines/ccr/ccrQuery.ts +110 -0
- package/open-sse/services/compression/engines/ccr/index.ts +460 -0
- package/open-sse/services/compression/engines/headroom/encoderComparison.ts +72 -0
- package/open-sse/services/compression/engines/headroom/gcf/decode_generic.ts +711 -0
- package/open-sse/services/compression/engines/headroom/gcf/generic.ts +332 -0
- package/open-sse/services/compression/engines/headroom/gcf/index.ts +9 -0
- package/open-sse/services/compression/engines/headroom/gcf/scalar.ts +336 -0
- package/open-sse/services/compression/engines/headroom/index.ts +286 -0
- package/open-sse/services/compression/engines/headroom/smartcrusher.ts +255 -0
- package/open-sse/services/compression/engines/headroom/tabular.ts +263 -0
- package/open-sse/services/compression/engines/headroom/toon.ts +43 -0
- package/open-sse/services/compression/engines/index.ts +42 -0
- package/open-sse/services/compression/engines/ionizer/index.ts +124 -0
- package/open-sse/services/compression/engines/ionizer/sample.ts +200 -0
- package/open-sse/services/compression/engines/llm/index.ts +346 -0
- package/open-sse/services/compression/engines/llmlingua/constants.ts +55 -0
- package/open-sse/services/compression/engines/llmlingua/index.ts +474 -0
- package/open-sse/services/compression/engines/llmlingua/modelStore.ts +67 -0
- package/open-sse/services/compression/engines/llmlingua/onnxWorker.ts +117 -0
- package/open-sse/services/compression/engines/llmlingua/ultraEntry.ts +109 -0
- package/open-sse/services/compression/engines/llmlingua/worker.ts +373 -0
- package/open-sse/services/compression/engines/mcpAccessibility/collapseRepeated.ts +121 -0
- package/open-sse/services/compression/engines/mcpAccessibility/constants.ts +63 -0
- package/open-sse/services/compression/engines/mcpAccessibility/index.ts +52 -0
- package/open-sse/services/compression/engines/readLifecycle/index.ts +299 -0
- package/open-sse/services/compression/engines/registry.ts +87 -0
- package/open-sse/services/compression/engines/relevance/configSchema.ts +63 -0
- package/open-sse/services/compression/engines/relevance/index.ts +185 -0
- package/open-sse/services/compression/engines/relevance/scorer.ts +85 -0
- package/open-sse/services/compression/engines/rtk/codeStripper.ts +145 -0
- package/open-sse/services/compression/engines/rtk/commandDetector.ts +482 -0
- package/open-sse/services/compression/engines/rtk/configSchema.ts +117 -0
- package/open-sse/services/compression/engines/rtk/deduplicator.ts +37 -0
- package/open-sse/services/compression/engines/rtk/discover.ts +150 -0
- package/open-sse/services/compression/engines/rtk/filterLoader.ts +245 -0
- package/open-sse/services/compression/engines/rtk/filterSchema.ts +207 -0
- package/open-sse/services/compression/engines/rtk/filters/aws.json +34 -0
- package/open-sse/services/compression/engines/rtk/filters/biome.json +35 -0
- package/open-sse/services/compression/engines/rtk/filters/build-eslint.json +37 -0
- package/open-sse/services/compression/engines/rtk/filters/build-typescript.json +33 -0
- package/open-sse/services/compression/engines/rtk/filters/build-vite.json +41 -0
- package/open-sse/services/compression/engines/rtk/filters/build-webpack.json +34 -0
- package/open-sse/services/compression/engines/rtk/filters/bundle-install.json +35 -0
- package/open-sse/services/compression/engines/rtk/filters/composer.json +81 -0
- package/open-sse/services/compression/engines/rtk/filters/curl.json +34 -0
- package/open-sse/services/compression/engines/rtk/filters/df.json +34 -0
- package/open-sse/services/compression/engines/rtk/filters/docker-build.json +78 -0
- package/open-sse/services/compression/engines/rtk/filters/docker-logs.json +42 -0
- package/open-sse/services/compression/engines/rtk/filters/docker-ps.json +33 -0
- package/open-sse/services/compression/engines/rtk/filters/dotnet.json +47 -0
- package/open-sse/services/compression/engines/rtk/filters/du.json +33 -0
- package/open-sse/services/compression/engines/rtk/filters/error-stacktrace.json +41 -0
- package/open-sse/services/compression/engines/rtk/filters/gcloud.json +34 -0
- package/open-sse/services/compression/engines/rtk/filters/generic-output.json +32 -0
- package/open-sse/services/compression/engines/rtk/filters/gh.json +98 -0
- package/open-sse/services/compression/engines/rtk/filters/git-branch.json +45 -0
- package/open-sse/services/compression/engines/rtk/filters/git-diff.json +33 -0
- package/open-sse/services/compression/engines/rtk/filters/git-log.json +33 -0
- package/open-sse/services/compression/engines/rtk/filters/git-status.json +40 -0
- package/open-sse/services/compression/engines/rtk/filters/golangci-lint.json +34 -0
- package/open-sse/services/compression/engines/rtk/filters/gradle.json +47 -0
- package/open-sse/services/compression/engines/rtk/filters/json-output.json +40 -0
- package/open-sse/services/compression/engines/rtk/filters/kubectl.json +99 -0
- package/open-sse/services/compression/engines/rtk/filters/make.json +38 -0
- package/open-sse/services/compression/engines/rtk/filters/mypy.json +34 -0
- package/open-sse/services/compression/engines/rtk/filters/npm-audit.json +43 -0
- package/open-sse/services/compression/engines/rtk/filters/npm-install.json +41 -0
- package/open-sse/services/compression/engines/rtk/filters/nx.json +34 -0
- package/open-sse/services/compression/engines/rtk/filters/pip.json +41 -0
- package/open-sse/services/compression/engines/rtk/filters/playwright.json +42 -0
- package/open-sse/services/compression/engines/rtk/filters/poetry-install.json +35 -0
- package/open-sse/services/compression/engines/rtk/filters/prettier.json +40 -0
- package/open-sse/services/compression/engines/rtk/filters/ps.json +34 -0
- package/open-sse/services/compression/engines/rtk/filters/rsync.json +33 -0
- package/open-sse/services/compression/engines/rtk/filters/rubocop.json +34 -0
- package/open-sse/services/compression/engines/rtk/filters/ruff.json +40 -0
- package/open-sse/services/compression/engines/rtk/filters/shell-find.json +33 -0
- package/open-sse/services/compression/engines/rtk/filters/shell-grep.json +37 -0
- package/open-sse/services/compression/engines/rtk/filters/shell-ls.json +33 -0
- package/open-sse/services/compression/engines/rtk/filters/ssh.json +43 -0
- package/open-sse/services/compression/engines/rtk/filters/systemctl-status.json +43 -0
- package/open-sse/services/compression/engines/rtk/filters/terraform-plan.json +34 -0
- package/open-sse/services/compression/engines/rtk/filters/test-cargo.json +42 -0
- package/open-sse/services/compression/engines/rtk/filters/test-go.json +41 -0
- package/open-sse/services/compression/engines/rtk/filters/test-jest.json +43 -0
- package/open-sse/services/compression/engines/rtk/filters/test-pytest.json +41 -0
- package/open-sse/services/compression/engines/rtk/filters/test-vitest.json +43 -0
- package/open-sse/services/compression/engines/rtk/filters/tofu-plan.json +34 -0
- package/open-sse/services/compression/engines/rtk/filters/turbo.json +34 -0
- package/open-sse/services/compression/engines/rtk/filters/uv-sync.json +35 -0
- package/open-sse/services/compression/engines/rtk/filters/wget.json +34 -0
- package/open-sse/services/compression/engines/rtk/grouper.ts +99 -0
- package/open-sse/services/compression/engines/rtk/index.ts +706 -0
- package/open-sse/services/compression/engines/rtk/learn.ts +290 -0
- package/open-sse/services/compression/engines/rtk/lineFilter.ts +178 -0
- package/open-sse/services/compression/engines/rtk/rawOutput.ts +208 -0
- package/open-sse/services/compression/engines/rtk/renderers/gitDiff.ts +39 -0
- package/open-sse/services/compression/engines/rtk/renderers/index.ts +50 -0
- package/open-sse/services/compression/engines/rtk/renderers/structuredTable.ts +96 -0
- package/open-sse/services/compression/engines/rtk/renderers/terraformPlan.ts +40 -0
- package/open-sse/services/compression/engines/rtk/renderers/testGreen.ts +70 -0
- package/open-sse/services/compression/engines/rtk/renderers/types.ts +13 -0
- package/open-sse/services/compression/engines/rtk/smartTruncate.ts +67 -0
- package/open-sse/services/compression/engines/rtk/splitCompositeCommand.ts +111 -0
- package/open-sse/services/compression/engines/rtk/verify.ts +107 -0
- package/open-sse/services/compression/engines/session-dedup/fuzzy.ts +153 -0
- package/open-sse/services/compression/engines/session-dedup/index.ts +435 -0
- package/open-sse/services/compression/engines/types.ts +77 -0
- package/open-sse/services/compression/entrypointWrap.ts +43 -0
- package/open-sse/services/compression/eval/aggregate.ts +62 -0
- package/open-sse/services/compression/eval/corpus.ts +45 -0
- package/open-sse/services/compression/eval/costMeter.ts +31 -0
- package/open-sse/services/compression/eval/executorModelClient.ts +44 -0
- package/open-sse/services/compression/eval/fidelityCheck.ts +61 -0
- package/open-sse/services/compression/eval/grader.ts +27 -0
- package/open-sse/services/compression/eval/judge.ts +68 -0
- package/open-sse/services/compression/eval/report.ts +44 -0
- package/open-sse/services/compression/eval/runner.ts +135 -0
- package/open-sse/services/compression/eval/savings.ts +30 -0
- package/open-sse/services/compression/eval/seedCorpus.ts +60 -0
- package/open-sse/services/compression/eval/types.ts +65 -0
- package/open-sse/services/compression/fidelityGate.ts +124 -0
- package/open-sse/services/compression/fidelityGateStep.ts +44 -0
- package/open-sse/services/compression/hardBudget.ts +196 -0
- package/open-sse/services/compression/harness/benchmark.ts +318 -0
- package/open-sse/services/compression/harness/budgetGate.ts +62 -0
- package/open-sse/services/compression/harness/index.ts +52 -0
- package/open-sse/services/compression/harness/measure.ts +98 -0
- package/open-sse/services/compression/harness/replay.ts +72 -0
- package/open-sse/services/compression/harness/runner.ts +58 -0
- package/open-sse/services/compression/index.ts +165 -0
- package/open-sse/services/compression/languageDetector.ts +51 -0
- package/open-sse/services/compression/lite.ts +241 -0
- package/open-sse/services/compression/messageContent.ts +89 -0
- package/open-sse/services/compression/outputMode.ts +175 -0
- package/open-sse/services/compression/outputStyles/apply.ts +135 -0
- package/open-sse/services/compression/outputStyles/backCompat.ts +29 -0
- package/open-sse/services/compression/outputStyles/catalog.ts +76 -0
- package/open-sse/services/compression/outputStyles/telemetry.ts +50 -0
- package/open-sse/services/compression/pipelineEngineBreaker.ts +139 -0
- package/open-sse/services/compression/pipelineGuards.ts +45 -0
- package/open-sse/services/compression/planResolution.ts +128 -0
- package/open-sse/services/compression/prefixFreeze.ts +124 -0
- package/open-sse/services/compression/preservation.ts +0 -0
- package/open-sse/services/compression/preserveSystemPromptMode.ts +72 -0
- package/open-sse/services/compression/progressiveAging.ts +145 -0
- package/open-sse/services/compression/quantumLock/index.ts +17 -0
- package/open-sse/services/compression/quantumLock/quantumLock.ts +58 -0
- package/open-sse/services/compression/quantumLock/quantumLockStep.ts +72 -0
- package/open-sse/services/compression/quantumLock/quantumPatterns.ts +80 -0
- package/open-sse/services/compression/quantumLock/strategyWrap.ts +72 -0
- package/open-sse/services/compression/resolveCompressionPlan.ts +28 -0
- package/open-sse/services/compression/resultMemo.ts +83 -0
- package/open-sse/services/compression/riskGate/index.ts +3 -0
- package/open-sse/services/compression/riskGate/riskGate.ts +136 -0
- package/open-sse/services/compression/riskGate/riskGateStep.ts +115 -0
- package/open-sse/services/compression/riskGate/riskPatterns.ts +61 -0
- package/open-sse/services/compression/riskGate/strategyWrap.ts +44 -0
- package/open-sse/services/compression/ruleLoader.ts +273 -0
- package/open-sse/services/compression/rules/_schema.json +31 -0
- package/open-sse/services/compression/rules/de/context.json +38 -0
- package/open-sse/services/compression/rules/de/dedup.json +38 -0
- package/open-sse/services/compression/rules/de/filler.json +70 -0
- package/open-sse/services/compression/rules/de/structural.json +30 -0
- package/open-sse/services/compression/rules/de/ultra.json +107 -0
- package/open-sse/services/compression/rules/en/context.json +88 -0
- package/open-sse/services/compression/rules/en/dedup.json +38 -0
- package/open-sse/services/compression/rules/en/filler.json +129 -0
- package/open-sse/services/compression/rules/en/structural.json +102 -0
- package/open-sse/services/compression/rules/en/ultra.json +107 -0
- package/open-sse/services/compression/rules/es/context.json +87 -0
- package/open-sse/services/compression/rules/es/dedup.json +38 -0
- package/open-sse/services/compression/rules/es/filler.json +110 -0
- package/open-sse/services/compression/rules/es/structural.json +105 -0
- package/open-sse/services/compression/rules/es/ultra.json +107 -0
- package/open-sse/services/compression/rules/fr/context.json +38 -0
- package/open-sse/services/compression/rules/fr/dedup.json +38 -0
- package/open-sse/services/compression/rules/fr/filler.json +70 -0
- package/open-sse/services/compression/rules/fr/structural.json +30 -0
- package/open-sse/services/compression/rules/fr/ultra.json +107 -0
- package/open-sse/services/compression/rules/id/context.json +113 -0
- package/open-sse/services/compression/rules/id/dedup.json +38 -0
- package/open-sse/services/compression/rules/id/filler.json +138 -0
- package/open-sse/services/compression/rules/id/structural.json +111 -0
- package/open-sse/services/compression/rules/id/ultra.json +252 -0
- package/open-sse/services/compression/rules/ja/context.json +38 -0
- package/open-sse/services/compression/rules/ja/dedup.json +38 -0
- package/open-sse/services/compression/rules/ja/filler.json +70 -0
- package/open-sse/services/compression/rules/ja/structural.json +30 -0
- package/open-sse/services/compression/rules/ja/ultra.json +86 -0
- package/open-sse/services/compression/rules/pt-BR/context.json +69 -0
- package/open-sse/services/compression/rules/pt-BR/dedup.json +51 -0
- package/open-sse/services/compression/rules/pt-BR/filler.json +151 -0
- package/open-sse/services/compression/rules/pt-BR/structural.json +78 -0
- package/open-sse/services/compression/rules/pt-BR/ultra.json +192 -0
- package/open-sse/services/compression/rules/zh/dedup.json +38 -0
- package/open-sse/services/compression/rules/zh/filler.json +54 -0
- package/open-sse/services/compression/rules/zh/ultra.json +55 -0
- package/open-sse/services/compression/stackedStepCore.ts +87 -0
- package/open-sse/services/compression/stats.ts +59 -0
- package/open-sse/services/compression/strategySelector.ts +1007 -0
- package/open-sse/services/compression/summarizer.ts +244 -0
- package/open-sse/services/compression/toolResultCompressor.ts +283 -0
- package/open-sse/services/compression/types.ts +479 -0
- package/open-sse/services/compression/ultra.ts +321 -0
- package/open-sse/services/compression/ultraHeuristic.ts +157 -0
- package/open-sse/services/compression/validation.ts +432 -0
- package/open-sse/services/contextHandoff.ts +770 -0
- package/open-sse/services/contextManager.ts +617 -0
- package/open-sse/services/credentialGate.ts +84 -0
- package/open-sse/services/crofUsageFetcher.ts +182 -0
- package/open-sse/services/cursorSessionManager.ts +208 -0
- package/open-sse/services/deepseekQuotaFetcher.ts +244 -0
- package/open-sse/services/deviceTracker.ts +307 -0
- package/open-sse/services/emergencyFallback.ts +162 -0
- package/open-sse/services/errorClassifier.ts +198 -0
- package/open-sse/services/evalRouting.ts +276 -0
- package/open-sse/services/freeWebSearch.ts +154 -0
- package/open-sse/services/fusion.ts +337 -0
- package/open-sse/services/geminiRateLimitTracker.ts +145 -0
- package/open-sse/services/geminiThoughtSignatureStore.ts +329 -0
- package/open-sse/services/genericQuotaFetcher.ts +215 -0
- package/open-sse/services/gigachatAuth.ts +113 -0
- package/open-sse/services/githubCopilotModels.ts +162 -0
- package/open-sse/services/gpt5SamplingGuard.ts +81 -0
- package/open-sse/services/grokTlsClient.ts +607 -0
- package/open-sse/services/hfModelSuggestions.ts +63 -0
- package/open-sse/services/inAppLoginService.ts +256 -0
- package/open-sse/services/intentClassifier.ts +665 -0
- package/open-sse/services/ipFilter.ts +340 -0
- package/open-sse/services/keyGroupAuth.ts +84 -0
- package/open-sse/services/kiroModels.ts +195 -0
- package/open-sse/services/manifestAdapter.ts +134 -0
- package/open-sse/services/mimoThinking.ts +54 -0
- package/open-sse/services/model.ts +738 -0
- package/open-sse/services/modelCapabilities.ts +5 -0
- package/open-sse/services/modelDeprecation.ts +173 -0
- package/open-sse/services/modelFamilyFallback.ts +240 -0
- package/open-sse/services/modelStrip.ts +60 -0
- package/open-sse/services/modelscopePolicy.ts +97 -0
- package/open-sse/services/opencodeOllamaUsage.ts +562 -0
- package/open-sse/services/opencodeQuotaFetcher.ts +351 -0
- package/open-sse/services/payloadRules.ts +474 -0
- package/open-sse/services/perplexityTlsClient.ts +593 -0
- package/open-sse/services/pipeline.ts +189 -0
- package/open-sse/services/provider.ts +460 -0
- package/open-sse/services/providerCooldownTracker.ts +198 -0
- package/open-sse/services/providerCostData.ts +52 -0
- package/open-sse/services/providerDefaultRateLimit.ts +94 -0
- package/open-sse/services/providerRequestDefaults.ts +88 -0
- package/open-sse/services/proxyAutoSelector.ts +58 -0
- package/open-sse/services/qoderCli.ts +987 -0
- package/open-sse/services/qoderCliResolve.ts +111 -0
- package/open-sse/services/quotaFetchThrottle.ts +118 -0
- package/open-sse/services/quotaMonitor.ts +377 -0
- package/open-sse/services/quotaPreflight.ts +349 -0
- package/open-sse/services/qwenThinking.ts +44 -0
- package/open-sse/services/rateLimitManager/headers.ts +94 -0
- package/open-sse/services/rateLimitManager.ts +945 -0
- package/open-sse/services/rateLimitSemaphore.ts +231 -0
- package/open-sse/services/reasoningCache.ts +514 -0
- package/open-sse/services/reasoningTokenBuffer.ts +50 -0
- package/open-sse/services/refreshSerializer.ts +131 -0
- package/open-sse/services/requestDedup.ts +127 -0
- package/open-sse/services/responseModelEcho.ts +79 -0
- package/open-sse/services/responsesInputSanitizer.ts +145 -0
- package/open-sse/services/retryAfterJson.ts +44 -0
- package/open-sse/services/roleNormalizer.ts +283 -0
- package/open-sse/services/searchCache.ts +150 -0
- package/open-sse/services/sessionManager.ts +380 -0
- package/open-sse/services/sessionPool/fingerprintRotator.ts +126 -0
- package/open-sse/services/sessionPool/index.ts +28 -0
- package/open-sse/services/sessionPool/poolRegistry.ts +93 -0
- package/open-sse/services/sessionPool/session.ts +119 -0
- package/open-sse/services/sessionPool/sessionFactory.ts +57 -0
- package/open-sse/services/sessionPool/sessionPool.ts +326 -0
- package/open-sse/services/sessionPool/types.ts +100 -0
- package/open-sse/services/sessionPool/webExecutorWrapper.ts +132 -0
- package/open-sse/services/signatureCache.ts +189 -0
- package/open-sse/services/slidingWindowLimiter.ts +84 -0
- package/open-sse/services/specificityDetector.ts +89 -0
- package/open-sse/services/specificityRules.ts +257 -0
- package/open-sse/services/specificityTypes.ts +43 -0
- package/open-sse/services/streamRecovery.ts +545 -0
- package/open-sse/services/systemPrompt.ts +187 -0
- package/open-sse/services/systemTransforms.ts +532 -0
- package/open-sse/services/taskAwareRouter.ts +326 -0
- package/open-sse/services/taskAwareRouting.ts +553 -0
- package/open-sse/services/thinkingBudget.ts +391 -0
- package/open-sse/services/tierConfig.ts +124 -0
- package/open-sse/services/tierDefaults.json +26 -0
- package/open-sse/services/tierResolver.ts +144 -0
- package/open-sse/services/tierTypes.ts +40 -0
- package/open-sse/services/tlsClientProxy.ts +30 -0
- package/open-sse/services/tokenExtractionConfig.ts +398 -0
- package/open-sse/services/tokenLimitCounter.ts +342 -0
- package/open-sse/services/tokenRefresh.ts +2180 -0
- package/open-sse/services/toolLatencyTracker.ts +89 -0
- package/open-sse/services/toolLimitDetector.ts +87 -0
- package/open-sse/services/toolSchemaSanitizer.ts +165 -0
- package/open-sse/services/usage/antigravity.ts +794 -0
- package/open-sse/services/usage/claude.ts +216 -0
- package/open-sse/services/usage/codebuddy-cn.ts +199 -0
- package/open-sse/services/usage/codex.ts +75 -0
- package/open-sse/services/usage/cursor.ts +161 -0
- package/open-sse/services/usage/glm.ts +220 -0
- package/open-sse/services/usage/kimi.ts +209 -0
- package/open-sse/services/usage/kiro.ts +243 -0
- package/open-sse/services/usage/minimax.ts +346 -0
- package/open-sse/services/usage/quota.ts +85 -0
- package/open-sse/services/usage/scalars.ts +75 -0
- package/open-sse/services/usage.ts +1058 -0
- package/open-sse/services/volumeDetector.ts +224 -0
- package/open-sse/services/webSearchFallback.ts +246 -0
- package/open-sse/services/webSearchRouting.ts +68 -0
- package/open-sse/services/webSessionPoolHealth.ts +287 -0
- package/open-sse/services/wildcardRouter.ts +136 -0
- package/open-sse/services/workflowFSM.ts +340 -0
- package/open-sse/shared/zedAuth.ts +535 -0
- package/open-sse/transformer/responsesTransformer.ts +667 -0
- package/open-sse/translator/bootstrap.ts +27 -0
- package/open-sse/translator/deepseekWebTools.ts +486 -0
- package/open-sse/translator/formats.ts +12 -0
- package/open-sse/translator/helpers/claudeHelper.ts +563 -0
- package/open-sse/translator/helpers/geminiHelper.ts +657 -0
- package/open-sse/translator/helpers/geminiToolsSanitizer.ts +255 -0
- package/open-sse/translator/helpers/jsonUtil.ts +18 -0
- package/open-sse/translator/helpers/maxTokensHelper.ts +21 -0
- package/open-sse/translator/helpers/openaiHelper.ts +244 -0
- package/open-sse/translator/helpers/responsesApiHelper.ts +9 -0
- package/open-sse/translator/helpers/schemaCoercion.ts +408 -0
- package/open-sse/translator/helpers/toolCallHelper.ts +224 -0
- package/open-sse/translator/helpers/toolCallShim.ts +113 -0
- package/open-sse/translator/image/sizeMapper.ts +22 -0
- package/open-sse/translator/index.ts +614 -0
- package/open-sse/translator/paramSupport.ts +70 -0
- package/open-sse/translator/registry.ts +41 -0
- package/open-sse/translator/request/antigravity-to-openai.ts +357 -0
- package/open-sse/translator/request/claude-to-gemini.ts +236 -0
- package/open-sse/translator/request/claude-to-openai.ts +534 -0
- package/open-sse/translator/request/gemini-to-openai.ts +193 -0
- package/open-sse/translator/request/openai-responses/helpers.ts +69 -0
- package/open-sse/translator/request/openai-responses/toResponses.ts +357 -0
- package/open-sse/translator/request/openai-responses.ts +533 -0
- package/open-sse/translator/request/openai-to-claude/thinkingBudget.ts +89 -0
- package/open-sse/translator/request/openai-to-claude/toolResultAdjacency.ts +106 -0
- package/open-sse/translator/request/openai-to-claude.ts +747 -0
- package/open-sse/translator/request/openai-to-cursor.ts +226 -0
- package/open-sse/translator/request/openai-to-gemini/helpers.ts +142 -0
- package/open-sse/translator/request/openai-to-gemini.ts +753 -0
- package/open-sse/translator/request/openai-to-kiro/messageHelpers.ts +109 -0
- package/open-sse/translator/request/openai-to-kiro.ts +889 -0
- package/open-sse/translator/response/claude-to-openai.ts +327 -0
- package/open-sse/translator/response/cursor-to-openai.ts +30 -0
- package/open-sse/translator/response/gemini-to-claude.ts +199 -0
- package/open-sse/translator/response/gemini-to-openai.ts +765 -0
- package/open-sse/translator/response/kiro-to-openai.ts +211 -0
- package/open-sse/translator/response/openai-responses/pureHelpers.ts +92 -0
- package/open-sse/translator/response/openai-responses.ts +1011 -0
- package/open-sse/translator/response/openai-to-antigravity.ts +145 -0
- package/open-sse/translator/response/openai-to-claude.ts +289 -0
- package/open-sse/translator/response/openai-to-gemini-sse.ts +431 -0
- package/open-sse/translator/webTools.ts +531 -0
- package/open-sse/tsconfig.json +25 -0
- package/open-sse/types.d.ts +139 -0
- package/open-sse/utils/agentGoalPolicy.ts +112 -0
- package/open-sse/utils/aiSdkCompat.ts +179 -0
- package/open-sse/utils/anthropicHost.ts +25 -0
- package/open-sse/utils/awsSigV4.ts +139 -0
- package/open-sse/utils/bypassHandler.ts +300 -0
- package/open-sse/utils/cacheControlPolicy.ts +374 -0
- package/open-sse/utils/claudeCodeMetaRequests.ts +87 -0
- package/open-sse/utils/clinepassEnvelope.ts +59 -0
- package/open-sse/utils/comfyuiClient.ts +126 -0
- package/open-sse/utils/composerToolCalls.ts +307 -0
- package/open-sse/utils/cors.ts +13 -0
- package/open-sse/utils/cursorAgentProtobuf/wire.ts +143 -0
- package/open-sse/utils/cursorAgentProtobuf.ts +1400 -0
- package/open-sse/utils/cursorChecksum.ts +139 -0
- package/open-sse/utils/cursorImages.ts +354 -0
- package/open-sse/utils/cursorVersionDetector.ts +74 -0
- package/open-sse/utils/diagnostics.ts +288 -0
- package/open-sse/utils/earlyStreamKeepalive.ts +228 -0
- package/open-sse/utils/error.ts +515 -0
- package/open-sse/utils/estimateSize.ts +35 -0
- package/open-sse/utils/finishReason.ts +36 -0
- package/open-sse/utils/flattenToolHistory.ts +116 -0
- package/open-sse/utils/headers.ts +61 -0
- package/open-sse/utils/heapPressure.ts +81 -0
- package/open-sse/utils/jsonToSse.ts +127 -0
- package/open-sse/utils/keepaliveThreshold.ts +62 -0
- package/open-sse/utils/kieTask.ts +127 -0
- package/open-sse/utils/kiroSanitizer.ts +127 -0
- package/open-sse/utils/logger.ts +190 -0
- package/open-sse/utils/networkProxy.ts +75 -0
- package/open-sse/utils/noThinkingAlias.ts +153 -0
- package/open-sse/utils/number.ts +4 -0
- package/open-sse/utils/ollamaTransform.ts +122 -0
- package/open-sse/utils/opencodeHeaders.ts +98 -0
- package/open-sse/utils/passthroughTailProcessor.ts +299 -0
- package/open-sse/utils/progressTracker.ts +112 -0
- package/open-sse/utils/providerRequestLogging.ts +272 -0
- package/open-sse/utils/proxyDispatcher.ts +507 -0
- package/open-sse/utils/proxyDispatcherCache.ts +124 -0
- package/open-sse/utils/proxyFallback.ts +418 -0
- package/open-sse/utils/proxyFamily.ts +24 -0
- package/open-sse/utils/proxyFamilyResolve.ts +39 -0
- package/open-sse/utils/proxyFetch.ts +666 -0
- package/open-sse/utils/publicCreds.ts +215 -0
- package/open-sse/utils/reasoningContentInjector.ts +73 -0
- package/open-sse/utils/reasoningFields.ts +72 -0
- package/open-sse/utils/requestLogger.ts +386 -0
- package/open-sse/utils/responsesInputNormalization.ts +94 -0
- package/open-sse/utils/responsesStatePolicy.ts +75 -0
- package/open-sse/utils/responsesStreamHelpers.ts +166 -0
- package/open-sse/utils/setupPolyfill.ts +33 -0
- package/open-sse/utils/sha3-512.ts +164 -0
- package/open-sse/utils/sleep.ts +9 -0
- package/open-sse/utils/socksConnectorWithFamily.ts +89 -0
- package/open-sse/utils/sseHeartbeat.ts +119 -0
- package/open-sse/utils/stream.ts +2791 -0
- package/open-sse/utils/streamFailureFinalization.ts +174 -0
- package/open-sse/utils/streamHandler.ts +680 -0
- package/open-sse/utils/streamHelpers.ts +460 -0
- package/open-sse/utils/streamPayloadCollector.ts +700 -0
- package/open-sse/utils/streamReadiness.ts +385 -0
- package/open-sse/utils/streamReadinessPolicy.ts +132 -0
- package/open-sse/utils/textualToolCall.ts +112 -0
- package/open-sse/utils/thinkCloseMarker.ts +77 -0
- package/open-sse/utils/thinkTagParser.ts +146 -0
- package/open-sse/utils/tlsClient.ts +243 -0
- package/open-sse/utils/toolCallArguments.ts +32 -0
- package/open-sse/utils/toolSources.ts +69 -0
- package/open-sse/utils/upstreamResponseHeaders.ts +47 -0
- package/open-sse/utils/urlSanitize.ts +24 -0
- package/open-sse/utils/usageTracking.ts +596 -0
- package/package.json +393 -0
- package/scripts/build/build-next-isolated.mjs +322 -0
- package/scripts/build/colocateOptionals.mjs +144 -0
- package/scripts/build/native-binary-compat.mjs +167 -0
- package/scripts/build/postinstall.mjs +357 -0
- package/scripts/build/postinstallSupport.mjs +45 -0
- package/scripts/build/runtime-env.mjs +140 -0
- package/scripts/build/sync-env.mjs +3 -0
- package/scripts/check/check-supported-node-runtime.ts +20 -0
- package/scripts/dev/responses-ws-proxy.mjs +907 -0
- package/scripts/dev/sync-env.mjs +362 -0
- package/scripts/dev/tls-options.mjs +92 -0
- package/scripts/postinstall.mjs +27 -0
- package/src/domain/assessment/assessor.ts +206 -0
- package/src/domain/assessment/categorizer.ts +118 -0
- package/src/domain/assessment/index.ts +24 -0
- package/src/domain/assessment/migration.ts +111 -0
- package/src/domain/assessment/selfHealer.ts +261 -0
- package/src/domain/assessment/types.ts +361 -0
- package/src/domain/comboResolver.ts +106 -0
- package/src/domain/configAudit.ts +285 -0
- package/src/domain/connectionModelRules.ts +82 -0
- package/src/domain/costRules.ts +631 -0
- package/src/domain/degradation.ts +253 -0
- package/src/domain/fallbackPolicy.ts +160 -0
- package/src/domain/lockoutPolicy.ts +208 -0
- package/src/domain/modelAvailability.ts +41 -0
- package/src/domain/omnirouteResponseMeta.ts +202 -0
- package/src/domain/pipeline.ts +307 -0
- package/src/domain/policyEngine.ts +195 -0
- package/src/domain/prompts.ts +103 -0
- package/src/domain/providerExpiration.ts +255 -0
- package/src/domain/quotaCache.ts +553 -0
- package/src/domain/responses.ts +139 -0
- package/src/domain/tagRouter.ts +64 -0
- package/src/domain/types.ts +123 -0
- package/src/lib/a2a/README.md +748 -0
- package/src/lib/a2a/routingLogger.ts +67 -0
- package/src/lib/a2a/skills/costAnalysis.ts +162 -0
- package/src/lib/a2a/skills/healthReport.ts +155 -0
- package/src/lib/a2a/skills/listCapabilities.ts +72 -0
- package/src/lib/a2a/skills/providerDiscovery.ts +202 -0
- package/src/lib/a2a/skills/quotaManagement.ts +121 -0
- package/src/lib/a2a/skills/smartRouting.ts +89 -0
- package/src/lib/a2a/streaming.ts +149 -0
- package/src/lib/a2a/taskExecution.ts +64 -0
- package/src/lib/a2a/taskManager.ts +240 -0
- package/src/lib/accessTokens/scopes.ts +51 -0
- package/src/lib/acp/index.ts +11 -0
- package/src/lib/acp/manager.ts +202 -0
- package/src/lib/acp/registry.ts +384 -0
- package/src/lib/agentSkills/catalog.ts +256 -0
- package/src/lib/agentSkills/cliRegistryParser.ts +242 -0
- package/src/lib/agentSkills/generator.ts +367 -0
- package/src/lib/agentSkills/openapiParser.ts +201 -0
- package/src/lib/agentSkills/schemas.ts +36 -0
- package/src/lib/agentSkills/types.ts +101 -0
- package/src/lib/api/comboErrorResponse.ts +80 -0
- package/src/lib/api/errorResponse.ts +54 -0
- package/src/lib/api/modelTestRunner.ts +390 -0
- package/src/lib/api/proxyRegistryRouteHandlers.ts +142 -0
- package/src/lib/api/requireCliToolsAuth.ts +5 -0
- package/src/lib/api/requireManagementAuth.ts +118 -0
- package/src/lib/api/serverErrorMessage.ts +36 -0
- package/src/lib/apiBridgeServer.ts +233 -0
- package/src/lib/apiKeyExposure.ts +19 -0
- package/src/lib/arenaEloSync.ts +564 -0
- package/src/lib/audit/activityIcons.ts +69 -0
- package/src/lib/audit/highLevelActions.ts +57 -0
- package/src/lib/audit/timeline.ts +132 -0
- package/src/lib/auth/managementPassword.ts +117 -0
- package/src/lib/batches/costEstimator.ts +130 -0
- package/src/lib/batches/csvToJsonl.ts +248 -0
- package/src/lib/batches/dispatch.ts +53 -0
- package/src/lib/batches/retryFailed.ts +77 -0
- package/src/lib/batches/schemas.ts +38 -0
- package/src/lib/batches/types.ts +78 -0
- package/src/lib/batches/validateJsonl.ts +154 -0
- package/src/lib/benchmarks.ts +33 -0
- package/src/lib/build-profile/featureDisabled.ts +23 -0
- package/src/lib/cacheControlSettings.ts +25 -0
- package/src/lib/cacheLayer.ts +220 -0
- package/src/lib/catalog/openrouterCatalog.ts +177 -0
- package/src/lib/cli-helper/claudeProfileAutoSync.ts +92 -0
- package/src/lib/cli-helper/codexProfileAutoSync.ts +80 -0
- package/src/lib/cli-helper/config-generator/claude.ts +25 -0
- package/src/lib/cli-helper/config-generator/cline.ts +23 -0
- package/src/lib/cli-helper/config-generator/codex.ts +34 -0
- package/src/lib/cli-helper/config-generator/continue.ts +37 -0
- package/src/lib/cli-helper/config-generator/hermes-agent.ts +210 -0
- package/src/lib/cli-helper/config-generator/hermes.ts +47 -0
- package/src/lib/cli-helper/config-generator/hermesHome.ts +40 -0
- package/src/lib/cli-helper/config-generator/index.ts +124 -0
- package/src/lib/cli-helper/config-generator/kilocode.ts +23 -0
- package/src/lib/cli-helper/config-generator/opencode.ts +443 -0
- package/src/lib/cli-helper/doctor/checks.ts +41 -0
- package/src/lib/cli-helper/log-streamer.ts +78 -0
- package/src/lib/cli-helper/tool-detector.ts +165 -0
- package/src/lib/cliTools/batchStatusCache.ts +47 -0
- package/src/lib/cliTools/checkToolConfigStatus.ts +112 -0
- package/src/lib/cloudAgent/agents/codex.ts +148 -0
- package/src/lib/cloudAgent/agents/cursor.ts +205 -0
- package/src/lib/cloudAgent/agents/devin.ts +137 -0
- package/src/lib/cloudAgent/agents/jules.ts +354 -0
- package/src/lib/cloudAgent/api.ts +86 -0
- package/src/lib/cloudAgent/baseAgent.ts +98 -0
- package/src/lib/cloudAgent/credentials.ts +89 -0
- package/src/lib/cloudAgent/db.ts +145 -0
- package/src/lib/cloudAgent/index.ts +8 -0
- package/src/lib/cloudAgent/julesApi.ts +7 -0
- package/src/lib/cloudAgent/registry.ts +29 -0
- package/src/lib/cloudAgent/types.ts +90 -0
- package/src/lib/cloudSync.stub.ts +31 -0
- package/src/lib/cloudSync.ts +210 -0
- package/src/lib/cloudflaredTunnel.ts +933 -0
- package/src/lib/combos/autoPromote.ts +92 -0
- package/src/lib/combos/builderDraft.ts +242 -0
- package/src/lib/combos/builderOptions.ts +681 -0
- package/src/lib/combos/compositeTiers.ts +200 -0
- package/src/lib/combos/controlCenter.ts +271 -0
- package/src/lib/combos/intelligentRouting.ts +192 -0
- package/src/lib/combos/steps.ts +322 -0
- package/src/lib/combos/testHealth.ts +190 -0
- package/src/lib/compliance/index.ts +637 -0
- package/src/lib/compliance/noLog.ts +86 -0
- package/src/lib/compliance/providerAudit.ts +98 -0
- package/src/lib/compression/judgeModelClient.ts +43 -0
- package/src/lib/config/hotReload.ts +115 -0
- package/src/lib/config/runtimeSettings.ts +551 -0
- package/src/lib/consoleInterceptor.ts +136 -0
- package/src/lib/container.ts +122 -0
- package/src/lib/contextWindowResolver.ts +147 -0
- package/src/lib/copilot/codegraphKnowledge.ts +229 -0
- package/src/lib/copilot/engine.ts +372 -0
- package/src/lib/copilot/systemPrompt.ts +189 -0
- package/src/lib/copilot/tools.ts +415 -0
- package/src/lib/credentialHealth/cache.ts +206 -0
- package/src/lib/credentialHealth/scheduler.ts +328 -0
- package/src/lib/dataPaths.ts +122 -0
- package/src/lib/db/AGENTS.md +70 -0
- package/src/lib/db/_rowTypes.ts +45 -0
- package/src/lib/db/accessTokens.ts +183 -0
- package/src/lib/db/adapters/betterSqliteAdapter.ts +58 -0
- package/src/lib/db/adapters/driverFactory.ts +98 -0
- package/src/lib/db/adapters/nodeSqliteAdapter.ts +60 -0
- package/src/lib/db/adapters/nodeSqliteShared.ts +148 -0
- package/src/lib/db/adapters/sqljsAdapter.ts +232 -0
- package/src/lib/db/adapters/types.ts +34 -0
- package/src/lib/db/agentBridgeBypass.ts +81 -0
- package/src/lib/db/agentBridgeMappings.ts +47 -0
- package/src/lib/db/agentBridgeState.ts +115 -0
- package/src/lib/db/apiKeyColumnFallbacks.ts +47 -0
- package/src/lib/db/apiKeyContextSources.ts +107 -0
- package/src/lib/db/apiKeyGroups.ts +318 -0
- package/src/lib/db/apiKeyUsageLimitFields.ts +65 -0
- package/src/lib/db/apiKeys/modelPermissions.ts +122 -0
- package/src/lib/db/apiKeys/rowParsers.ts +161 -0
- package/src/lib/db/apiKeys/types.ts +21 -0
- package/src/lib/db/apiKeys.ts +1492 -0
- package/src/lib/db/backup.ts +708 -0
- package/src/lib/db/batches.ts +450 -0
- package/src/lib/db/callLogStats.ts +235 -0
- package/src/lib/db/caseMapping.ts +80 -0
- package/src/lib/db/cleanup.ts +584 -0
- package/src/lib/db/cliToolState.ts +159 -0
- package/src/lib/db/comboForecast.ts +119 -0
- package/src/lib/db/combos.ts +339 -0
- package/src/lib/db/commandCodeAuth.ts +209 -0
- package/src/lib/db/compression.ts +780 -0
- package/src/lib/db/compressionAnalytics.ts +661 -0
- package/src/lib/db/compressionCacheStats.ts +112 -0
- package/src/lib/db/compressionCombos.ts +491 -0
- package/src/lib/db/compressionRunTelemetry.ts +126 -0
- package/src/lib/db/contextHandoffs.ts +233 -0
- package/src/lib/db/core.ts +1520 -0
- package/src/lib/db/creditBalance.ts +92 -0
- package/src/lib/db/databaseSettings.ts +309 -0
- package/src/lib/db/detailedLogs.ts +170 -0
- package/src/lib/db/discovery.ts +97 -0
- package/src/lib/db/discoveryResults.ts +176 -0
- package/src/lib/db/domainState.ts +630 -0
- package/src/lib/db/encryption.ts +327 -0
- package/src/lib/db/evals.ts +786 -0
- package/src/lib/db/featureFlags.ts +82 -0
- package/src/lib/db/files.ts +170 -0
- package/src/lib/db/freeProxies.ts +360 -0
- package/src/lib/db/gamification.ts +613 -0
- package/src/lib/db/healthCheck.ts +565 -0
- package/src/lib/db/inspectorCustomHosts.ts +88 -0
- package/src/lib/db/inspectorSessions.ts +161 -0
- package/src/lib/db/jsonMigration.ts +321 -0
- package/src/lib/db/memoryVec.ts +138 -0
- package/src/lib/db/middleware.ts +239 -0
- package/src/lib/db/migrationRunner/constants.ts +118 -0
- package/src/lib/db/migrationRunner.ts +1069 -0
- package/src/lib/db/migrations/001_initial_schema.sql +226 -0
- package/src/lib/db/migrations/002_mcp_a2a_tables.sql +95 -0
- package/src/lib/db/migrations/003_provider_node_custom_paths.sql +5 -0
- package/src/lib/db/migrations/004_proxy_registry.sql +31 -0
- package/src/lib/db/migrations/005_combo_agent_fields.sql +19 -0
- package/src/lib/db/migrations/006_detailed_request_logs.sql +42 -0
- package/src/lib/db/migrations/007_search_request_type.sql +4 -0
- package/src/lib/db/migrations/008_registered_keys.sql +65 -0
- package/src/lib/db/migrations/009_requested_model.sql +9 -0
- package/src/lib/db/migrations/010_model_combo_mappings.sql +19 -0
- package/src/lib/db/migrations/011_webhooks.sql +15 -0
- package/src/lib/db/migrations/012_fix_token_input_cache_tokens.sql +15 -0
- package/src/lib/db/migrations/013_quota_snapshots.sql +19 -0
- package/src/lib/db/migrations/014_unified_log_artifacts.sql +15 -0
- package/src/lib/db/migrations/015_create_memories.sql +22 -0
- package/src/lib/db/migrations/016_create_skills.sql +37 -0
- package/src/lib/db/migrations/017_version_manager_upstream_proxy.sql +56 -0
- package/src/lib/db/migrations/018_call_logs_detailed_tokens.sql +6 -0
- package/src/lib/db/migrations/019_context_handoffs.sql +28 -0
- package/src/lib/db/migrations/020_combo_sort_order.sql +16 -0
- package/src/lib/db/migrations/021_combo_call_log_targets.sql +5 -0
- package/src/lib/db/migrations/022_add_memory_fts5.sql +33 -0
- package/src/lib/db/migrations/023_fix_memory_fts_uuid.sql +55 -0
- package/src/lib/db/migrations/024_create_sync_tokens.sql +15 -0
- package/src/lib/db/migrations/025_call_logs_summary_storage.sql +145 -0
- package/src/lib/db/migrations/027_skill_mode_and_metadata.sql +10 -0
- package/src/lib/db/migrations/028_create_files_and_batches.sql +51 -0
- package/src/lib/db/migrations/029_provider_connection_max_concurrent.sql +10 -0
- package/src/lib/db/migrations/030_create_eval_runs.sql +28 -0
- package/src/lib/db/migrations/031_create_eval_suites.sql +27 -0
- package/src/lib/db/migrations/032_apikey_lifecycle.sql +24 -0
- package/src/lib/db/migrations/033_create_reasoning_cache.sql +27 -0
- package/src/lib/db/migrations/034_compression_settings.sql +10 -0
- package/src/lib/db/migrations/035_standard_compression_config.sql +9 -0
- package/src/lib/db/migrations/036_aggressive_compression.sql +4 -0
- package/src/lib/db/migrations/037_ultra_compression.sql +6 -0
- package/src/lib/db/migrations/038_compression_analytics.sql +13 -0
- package/src/lib/db/migrations/039_compression_cache_stats.sql +15 -0
- package/src/lib/db/migrations/040_oneproxy_proxy_fields.sql +24 -0
- package/src/lib/db/migrations/041_compression_receipts.sql +18 -0
- package/src/lib/db/migrations/042_compression_combos.sql +43 -0
- package/src/lib/db/migrations/043_default_compression_combo_pipeline.sql +12 -0
- package/src/lib/db/migrations/044_usage_history_api_key_backfill.sql +27 -0
- package/src/lib/db/migrations/045_compression_tokens.sql +4 -0
- package/src/lib/db/migrations/046_database_settings.sql +44 -0
- package/src/lib/db/migrations/047_aggregation_tables.sql +44 -0
- package/src/lib/db/migrations/048_summary_indexes.sql +29 -0
- package/src/lib/db/migrations/049_compression_analytics_indexes.sql +10 -0
- package/src/lib/db/migrations/050_session_account_affinity.sql +11 -0
- package/src/lib/db/migrations/051_hot_path_db_indexes.sql +10 -0
- package/src/lib/db/migrations/052_api_key_combo_throttle.sql +4 -0
- package/src/lib/db/migrations/053_remove_status_from_files.sql +2 -0
- package/src/lib/db/migrations/054_usage_history_service_tier.sql +4 -0
- package/src/lib/db/migrations/056_mcp_accessibility_compression.sql +8 -0
- package/src/lib/db/migrations/057_provider_connection_quota_window_thresholds.sql +14 -0
- package/src/lib/db/migrations/058_command_code_auth_sessions.sql +19 -0
- package/src/lib/db/migrations/059_manifest_routing.sql +21 -0
- package/src/lib/db/migrations/060_create_gamification.sql +94 -0
- package/src/lib/db/migrations/061_cloud_agent_credentials.sql +9 -0
- package/src/lib/db/migrations/062_usage_history_combo_strategy.sql +4 -0
- package/src/lib/db/migrations/063_add_last_model_to_handoffs.sql +7 -0
- package/src/lib/db/migrations/064_create_session_model_history.sql +19 -0
- package/src/lib/db/migrations/065_middleware_hooks.sql +45 -0
- package/src/lib/db/migrations/066_api_key_groups.sql +47 -0
- package/src/lib/db/migrations/067_relay_proxies.sql +56 -0
- package/src/lib/db/migrations/068_free_proxies.sql +52 -0
- package/src/lib/db/migrations/069_webhook_deliveries.sql +15 -0
- package/src/lib/db/migrations/070_webhooks_kind_metadata.sql +3 -0
- package/src/lib/db/migrations/071_services.sql +19 -0
- package/src/lib/db/migrations/072_free_proxies_fk.sql +27 -0
- package/src/lib/db/migrations/073_per_model_token_limits.sql +61 -0
- package/src/lib/db/migrations/074_discovery_results.sql +20 -0
- package/src/lib/db/migrations/075_api_key_self_service_usage_scopes.sql +51 -0
- package/src/lib/db/migrations/076_create_plugins.sql +31 -0
- package/src/lib/db/migrations/077_api_key_stream_default_mode.sql +3 -0
- package/src/lib/db/migrations/078_quota_consumption.sql +24 -0
- package/src/lib/db/migrations/079_provider_plans.sql +19 -0
- package/src/lib/db/migrations/080_agent_bridge.sql +24 -0
- package/src/lib/db/migrations/081_inspector_custom_hosts.sql +11 -0
- package/src/lib/db/migrations/082_inspector_sessions.sql +18 -0
- package/src/lib/db/migrations/083_memory_vec.sql +26 -0
- package/src/lib/db/migrations/084_playground_presets.sql +15 -0
- package/src/lib/db/migrations/085_quota_pools.sql +39 -0
- package/src/lib/db/migrations/086_api_key_allowed_quotas.sql +8 -0
- package/src/lib/db/migrations/087_quota_pool_connections.sql +21 -0
- package/src/lib/db/migrations/088_quota_groups.sql +28 -0
- package/src/lib/db/migrations/089_add_disable_non_public_to_api_keys.sql +3 -0
- package/src/lib/db/migrations/090_plugin_metrics.sql +9 -0
- package/src/lib/db/migrations/091_plugin_analytics.sql +23 -0
- package/src/lib/db/migrations/092_api_key_context_sources.sql +13 -0
- package/src/lib/db/migrations/093_proxy_enable_toggles.sql +17 -0
- package/src/lib/db/migrations/094_per_key_proxy_toggles.sql +12 -0
- package/src/lib/db/migrations/095_provider_node_custom_headers.sql +5 -0
- package/src/lib/db/migrations/096_sync_context_cache_protection.sql +9 -0
- package/src/lib/db/migrations/097_model_intelligence.sql +25 -0
- package/src/lib/db/migrations/098_clear_semantic_cache_for_key_isolation.sql +4 -0
- package/src/lib/db/migrations/099_proxy_family.sql +5 -0
- package/src/lib/db/migrations/100_cli_access_tokens.sql +18 -0
- package/src/lib/db/migrations/101_api_key_usage_limits.sql +4 -0
- package/src/lib/db/migrations/102_compression_engines_map.sql +5 -0
- package/src/lib/db/migrations/103_strip_legacy_combo_config_keys.sql +54 -0
- package/src/lib/db/migrations/104_normalize_database_cache_size.sql +10 -0
- package/src/lib/db/migrations/105_usage_history_endpoint.sql +6 -0
- package/src/lib/db/migrations/106_quota_allocation_model_caps.sql +32 -0
- package/src/lib/db/migrations/107_quota_combos_quota_share_strategy.sql +25 -0
- package/src/lib/db/migrations/108_provider_quota_reset_events.sql +26 -0
- package/src/lib/db/migrations/109_call_logs_correlation_id.sql +2 -0
- package/src/lib/db/migrations/110_model_context_overrides.sql +17 -0
- package/src/lib/db/migrations/111_memory_typed_decay.sql +10 -0
- package/src/lib/db/migrations/112_batch_item_checkpoints.sql +18 -0
- package/src/lib/db/migrations/113_provider_node_icon_url.sql +5 -0
- package/src/lib/db/migrations/114_mux_service_seed.sql +12 -0
- package/src/lib/db/migrations/115_bifrost_service.sql +9 -0
- package/src/lib/db/migrations/116_call_logs_reasoning_source.sql +13 -0
- package/src/lib/db/migrations/117_proxy_pool_rotation.sql +53 -0
- package/src/lib/db/modelComboMappings.ts +255 -0
- package/src/lib/db/modelContextOverrides.ts +133 -0
- package/src/lib/db/modelIntelligence.ts +232 -0
- package/src/lib/db/models/aliases.ts +61 -0
- package/src/lib/db/models/compat.ts +249 -0
- package/src/lib/db/models/mitmAlias.ts +32 -0
- package/src/lib/db/models/shared.ts +19 -0
- package/src/lib/db/models.ts +936 -0
- package/src/lib/db/notion.ts +48 -0
- package/src/lib/db/obsidian.ts +283 -0
- package/src/lib/db/oneproxy.ts +293 -0
- package/src/lib/db/optimizationSettings.ts +284 -0
- package/src/lib/db/playgroundPresets.ts +167 -0
- package/src/lib/db/pluginMetrics.ts +88 -0
- package/src/lib/db/plugins.ts +280 -0
- package/src/lib/db/prompts.ts +302 -0
- package/src/lib/db/providerLimits.ts +131 -0
- package/src/lib/db/providerNodeSelect.ts +48 -0
- package/src/lib/db/providerPlans.ts +149 -0
- package/src/lib/db/providerStats.ts +68 -0
- package/src/lib/db/providers/columns.ts +116 -0
- package/src/lib/db/providers/nodes.ts +169 -0
- package/src/lib/db/providers/rateLimit.ts +198 -0
- package/src/lib/db/providers.ts +803 -0
- package/src/lib/db/proxies/mappers.ts +181 -0
- package/src/lib/db/proxies/types.ts +78 -0
- package/src/lib/db/proxies.ts +1176 -0
- package/src/lib/db/proxyLogs.ts +35 -0
- package/src/lib/db/quotaConsumption.ts +274 -0
- package/src/lib/db/quotaGroups.ts +147 -0
- package/src/lib/db/quotaModelCaps.ts +128 -0
- package/src/lib/db/quotaPools.ts +548 -0
- package/src/lib/db/quotaResetEvents.ts +334 -0
- package/src/lib/db/quotaSnapshots.ts +209 -0
- package/src/lib/db/readCache.ts +202 -0
- package/src/lib/db/reasoningCache.ts +276 -0
- package/src/lib/db/recovery.ts +33 -0
- package/src/lib/db/registeredKeys.ts +532 -0
- package/src/lib/db/relayProxies.ts +364 -0
- package/src/lib/db/schemaColumns.ts +226 -0
- package/src/lib/db/secrets.ts +28 -0
- package/src/lib/db/semanticCache.ts +117 -0
- package/src/lib/db/serviceModels.ts +79 -0
- package/src/lib/db/sessionAccountAffinity.ts +212 -0
- package/src/lib/db/settings/cacheMetrics.ts +235 -0
- package/src/lib/db/settings/lkgp.ts +49 -0
- package/src/lib/db/settings/pricing.ts +254 -0
- package/src/lib/db/settings/shared.ts +9 -0
- package/src/lib/db/settings.ts +661 -0
- package/src/lib/db/skills.ts +62 -0
- package/src/lib/db/stateReset.ts +30 -0
- package/src/lib/db/stats.ts +71 -0
- package/src/lib/db/syncTokens.ts +163 -0
- package/src/lib/db/tierConfig.ts +88 -0
- package/src/lib/db/tokenLimits.ts +295 -0
- package/src/lib/db/upstreamProxy.ts +247 -0
- package/src/lib/db/usageAnalytics/sources.ts +208 -0
- package/src/lib/db/usageAnalytics.ts +723 -0
- package/src/lib/db/usageLogs.ts +94 -0
- package/src/lib/db/usageSummary.ts +18 -0
- package/src/lib/db/vacuumScheduler.ts +326 -0
- package/src/lib/db/versionManager.ts +377 -0
- package/src/lib/db/webSessionDedup.ts +57 -0
- package/src/lib/db/webhookDeliveries.ts +77 -0
- package/src/lib/db/webhooks.ts +178 -0
- package/src/lib/discovery/index.ts +137 -0
- package/src/lib/display/names.ts +73 -0
- package/src/lib/display/useProviderNodeMap.ts +68 -0
- package/src/lib/docsI18nPath.ts +33 -0
- package/src/lib/docsSanitizer.ts +42 -0
- package/src/lib/embeddings/familyGuard.ts +24 -0
- package/src/lib/embeddings/service.ts +288 -0
- package/src/lib/env/runtimeEnv.ts +166 -0
- package/src/lib/evals/evalRunner/builtinSuites.ts +676 -0
- package/src/lib/evals/evalRunner.ts +301 -0
- package/src/lib/evals/runtime.ts +311 -0
- package/src/lib/events/eventBus.ts +148 -0
- package/src/lib/events/types.ts +181 -0
- package/src/lib/freeProviderRankings.ts +340 -0
- package/src/lib/freeProxyProviders/index.ts +24 -0
- package/src/lib/freeProxyProviders/iplocate.ts +107 -0
- package/src/lib/freeProxyProviders/oneproxy.ts +127 -0
- package/src/lib/freeProxyProviders/proxifly.ts +143 -0
- package/src/lib/freeProxyProviders/types.ts +33 -0
- package/src/lib/freeProxyProviders/webshare.ts +148 -0
- package/src/lib/gamification/antiCheat.ts +160 -0
- package/src/lib/gamification/badges.ts +542 -0
- package/src/lib/gamification/events.ts +187 -0
- package/src/lib/gamification/index.ts +37 -0
- package/src/lib/gamification/invites.ts +127 -0
- package/src/lib/gamification/leaderboard.ts +64 -0
- package/src/lib/gamification/notifications.ts +118 -0
- package/src/lib/gamification/servers.ts +179 -0
- package/src/lib/gamification/sharing.ts +56 -0
- package/src/lib/gamification/streaks.ts +164 -0
- package/src/lib/gamification/xp.ts +152 -0
- package/src/lib/gracefulShutdown.ts +151 -0
- package/src/lib/guardrails/base.ts +65 -0
- package/src/lib/guardrails/index.ts +4 -0
- package/src/lib/guardrails/piiMasker.ts +208 -0
- package/src/lib/guardrails/promptInjection.ts +285 -0
- package/src/lib/guardrails/registry.ts +282 -0
- package/src/lib/guardrails/visionBridge.ts +237 -0
- package/src/lib/guardrails/visionBridgeHelpers.ts +499 -0
- package/src/lib/guardrails/visionBridgeRouter.ts +271 -0
- package/src/lib/headroom/detect.ts +214 -0
- package/src/lib/headroom/process.ts +177 -0
- package/src/lib/idempotencyLayer.ts +105 -0
- package/src/lib/images/imageRouteModel.ts +168 -0
- package/src/lib/initCloudSync.ts +52 -0
- package/src/lib/inspector/agentBridgeMaintenanceApi.ts +70 -0
- package/src/lib/inspector/captureState.ts +90 -0
- package/src/lib/inspector/configPortability.ts +86 -0
- package/src/lib/inspector/harExport.ts +188 -0
- package/src/lib/inspector/matchesTrafficFilter.ts +37 -0
- package/src/lib/inspector/secretMask.ts +6 -0
- package/src/lib/inspector/tproxyCaptureApi.ts +60 -0
- package/src/lib/ipUtils.ts +94 -0
- package/src/lib/jobs/budgetResetJob.ts +40 -0
- package/src/lib/jobs/reasoningCacheCleanupJob.ts +40 -0
- package/src/lib/localDb.ts +797 -0
- package/src/lib/localHealthCheck.ts +267 -0
- package/src/lib/logEnv.ts +164 -0
- package/src/lib/logPayloads.ts +110 -0
- package/src/lib/logRotation.ts +206 -0
- package/src/lib/machineToken.ts +53 -0
- package/src/lib/memory/cache.ts +76 -0
- package/src/lib/memory/embedding/cache.ts +77 -0
- package/src/lib/memory/embedding/index.ts +281 -0
- package/src/lib/memory/embedding/remote.ts +95 -0
- package/src/lib/memory/embedding/staticPotion.ts +253 -0
- package/src/lib/memory/embedding/transformersLocal.ts +153 -0
- package/src/lib/memory/embedding/types.ts +40 -0
- package/src/lib/memory/extraction.ts +195 -0
- package/src/lib/memory/injection.ts +211 -0
- package/src/lib/memory/qdrant.ts +521 -0
- package/src/lib/memory/reindex.ts +102 -0
- package/src/lib/memory/retrieval/scoring.ts +104 -0
- package/src/lib/memory/retrieval.ts +1072 -0
- package/src/lib/memory/schemas.ts +39 -0
- package/src/lib/memory/settings.ts +184 -0
- package/src/lib/memory/store.ts +621 -0
- package/src/lib/memory/summarization.ts +202 -0
- package/src/lib/memory/typedDecay.ts +245 -0
- package/src/lib/memory/types.ts +45 -0
- package/src/lib/memory/vectorStore.ts +425 -0
- package/src/lib/memory/verify.ts +56 -0
- package/src/lib/middleware/cliTokenAuth.ts +91 -0
- package/src/lib/middleware/registry.ts +432 -0
- package/src/lib/middleware/types.ts +129 -0
- package/src/lib/modelAliasSeed.ts +82 -0
- package/src/lib/modelCapabilities.ts +481 -0
- package/src/lib/modelMetadataRegistry.ts +574 -0
- package/src/lib/modelsDevSync/transform.ts +279 -0
- package/src/lib/modelsDevSync.ts +677 -0
- package/src/lib/monitoring/comboHealthAutopilot.ts +494 -0
- package/src/lib/monitoring/observability.ts +336 -0
- package/src/lib/monitoring/providerHealthAutopilot.ts +743 -0
- package/src/lib/monitoring/providerHealthMatrix.ts +621 -0
- package/src/lib/ngrokTunnel.ts +142 -0
- package/src/lib/notion/api.ts +247 -0
- package/src/lib/oauth/codexDeviceFlow.ts +316 -0
- package/src/lib/oauth/config/index.ts +31 -0
- package/src/lib/oauth/connectionPersistence.ts +114 -0
- package/src/lib/oauth/constants/oauth.ts +494 -0
- package/src/lib/oauth/credentialBlob.ts +105 -0
- package/src/lib/oauth/deviceFlowTickets.ts +110 -0
- package/src/lib/oauth/gitlab.ts +103 -0
- package/src/lib/oauth/pasteCredentials.ts +51 -0
- package/src/lib/oauth/providers/agy.ts +15 -0
- package/src/lib/oauth/providers/antigravity.ts +159 -0
- package/src/lib/oauth/providers/claude.ts +170 -0
- package/src/lib/oauth/providers/cline.ts +91 -0
- package/src/lib/oauth/providers/codebuddy-cn.ts +123 -0
- package/src/lib/oauth/providers/codex.ts +214 -0
- package/src/lib/oauth/providers/cursor.ts +15 -0
- package/src/lib/oauth/providers/github.ts +89 -0
- package/src/lib/oauth/providers/gitlab-duo.ts +124 -0
- package/src/lib/oauth/providers/grok-cli.ts +155 -0
- package/src/lib/oauth/providers/index.ts +59 -0
- package/src/lib/oauth/providers/kilocode.ts +77 -0
- package/src/lib/oauth/providers/kimi-coding.ts +135 -0
- package/src/lib/oauth/providers/kiro.ts +185 -0
- package/src/lib/oauth/providers/qoder.ts +81 -0
- package/src/lib/oauth/providers/qwen.ts +82 -0
- package/src/lib/oauth/providers/trae.ts +78 -0
- package/src/lib/oauth/providers/windsurf.ts +64 -0
- package/src/lib/oauth/providers/zed-hosted.ts +89 -0
- package/src/lib/oauth/providers/zed.ts +35 -0
- package/src/lib/oauth/providers.ts +278 -0
- package/src/lib/oauth/services/codexImport.ts +222 -0
- package/src/lib/oauth/services/cursor.ts +219 -0
- package/src/lib/oauth/services/kiro.ts +441 -0
- package/src/lib/oauth/utils/agyAuthImport.ts +259 -0
- package/src/lib/oauth/utils/banner.ts +62 -0
- package/src/lib/oauth/utils/claudeAuthFile.ts +334 -0
- package/src/lib/oauth/utils/claudeAuthImport.ts +259 -0
- package/src/lib/oauth/utils/claudeAuthZipExtract.ts +5 -0
- package/src/lib/oauth/utils/cliProxyAuthImport.ts +142 -0
- package/src/lib/oauth/utils/codexAuthFile.ts +352 -0
- package/src/lib/oauth/utils/codexAuthImport.ts +294 -0
- package/src/lib/oauth/utils/codexAuthZipExtract.ts +5 -0
- package/src/lib/oauth/utils/jsonZipExtract.ts +89 -0
- package/src/lib/oauth/utils/pkce.ts +37 -0
- package/src/lib/oauth/utils/server.ts +122 -0
- package/src/lib/oauth/utils/ui.ts +47 -0
- package/src/lib/obsidian/api.ts +390 -0
- package/src/lib/obsidianSync.ts +110 -0
- package/src/lib/oneproxyRotator.ts +19 -0
- package/src/lib/oneproxySync.ts +182 -0
- package/src/lib/piiSanitizer.ts +416 -0
- package/src/lib/playground/codeExport.ts +408 -0
- package/src/lib/playground/promptImprover.ts +147 -0
- package/src/lib/playground/streamMetrics.ts +61 -0
- package/src/lib/playground/types.ts +114 -0
- package/src/lib/plugins/devMode.ts +65 -0
- package/src/lib/plugins/doctor.ts +138 -0
- package/src/lib/plugins/errors.ts +38 -0
- package/src/lib/plugins/hooks.ts +322 -0
- package/src/lib/plugins/index.ts +72 -0
- package/src/lib/plugins/loader.ts +326 -0
- package/src/lib/plugins/logger.ts +50 -0
- package/src/lib/plugins/manager.ts +579 -0
- package/src/lib/plugins/manifest.ts +213 -0
- package/src/lib/plugins/marketplace.ts +202 -0
- package/src/lib/plugins/pluginWorker.ts +246 -0
- package/src/lib/plugins/sandbox.ts +29 -0
- package/src/lib/plugins/scanner.ts +110 -0
- package/src/lib/plugins/sdk.ts +88 -0
- package/src/lib/plugins/signing.ts +34 -0
- package/src/lib/plugins/testRunner.ts +95 -0
- package/src/lib/plugins/watcher.ts +90 -0
- package/src/lib/pricingSync.ts +456 -0
- package/src/lib/promptCache/index.ts +1 -0
- package/src/lib/promptCache/prefixAnalyzer.ts +81 -0
- package/src/lib/providerModels/cursorAgent.ts +166 -0
- package/src/lib/providerModels/geminiModelsParser.ts +91 -0
- package/src/lib/providerModels/managedAvailableModels.ts +165 -0
- package/src/lib/providerModels/managedModelImport.ts +349 -0
- package/src/lib/providerModels/modelDiscovery.ts +151 -0
- package/src/lib/providers/catalog.ts +246 -0
- package/src/lib/providers/claudeExtraUsage.ts +160 -0
- package/src/lib/providers/claudeFastMode.ts +75 -0
- package/src/lib/providers/codexConnectionDefaults.ts +85 -0
- package/src/lib/providers/codexFastTier.ts +210 -0
- package/src/lib/providers/imageValidation.ts +160 -0
- package/src/lib/providers/managedAvailableModels.ts +21 -0
- package/src/lib/providers/modelListingCapability.ts +26 -0
- package/src/lib/providers/nvidiaValidationModel.ts +24 -0
- package/src/lib/providers/requestDefaults.ts +318 -0
- package/src/lib/providers/serviceKindIndex.ts +0 -0
- package/src/lib/providers/staticModels.ts +170 -0
- package/src/lib/providers/validation/anthropicFormat.ts +319 -0
- package/src/lib/providers/validation/audioMiscProviders.ts +582 -0
- package/src/lib/providers/validation/cloudProviders.ts +669 -0
- package/src/lib/providers/validation/cozeError.ts +56 -0
- package/src/lib/providers/validation/directChatProbe.ts +47 -0
- package/src/lib/providers/validation/embeddingProviders.ts +143 -0
- package/src/lib/providers/validation/headers.ts +122 -0
- package/src/lib/providers/validation/metaAi.ts +117 -0
- package/src/lib/providers/validation/openaiFormat.ts +500 -0
- package/src/lib/providers/validation/searchProviders.ts +199 -0
- package/src/lib/providers/validation/transport.ts +109 -0
- package/src/lib/providers/validation/urlHelpers.ts +114 -0
- package/src/lib/providers/validation/webProvidersA.ts +808 -0
- package/src/lib/providers/validation/webProvidersB.ts +536 -0
- package/src/lib/providers/validation.ts +772 -0
- package/src/lib/providers/webCookieAuth.ts +157 -0
- package/src/lib/providers/xai/thinking.ts +127 -0
- package/src/lib/providers/xai/translators/claude.ts +368 -0
- package/src/lib/providers/xai/translators/gemini.ts +371 -0
- package/src/lib/providers/xai/translators/openai-chat.ts +310 -0
- package/src/lib/providers/xai/translators/openai-responses.ts +77 -0
- package/src/lib/proxyEgress.ts +388 -0
- package/src/lib/proxyHealth/decision.ts +77 -0
- package/src/lib/proxyHealth/scheduler.ts +207 -0
- package/src/lib/proxyHealth/statusPolicy.ts +41 -0
- package/src/lib/proxyHealth.ts +173 -0
- package/src/lib/proxyLogger.ts +240 -0
- package/src/lib/proxyRelay/cloudflareWorkerScript.ts +107 -0
- package/src/lib/quota/QuotaStore.ts +23 -0
- package/src/lib/quota/accountBuckets.ts +225 -0
- package/src/lib/quota/burnRate.ts +111 -0
- package/src/lib/quota/connectionProvider.ts +32 -0
- package/src/lib/quota/connectionRecovery.ts +303 -0
- package/src/lib/quota/dimensions.ts +61 -0
- package/src/lib/quota/enforce.ts +401 -0
- package/src/lib/quota/fairShare.ts +186 -0
- package/src/lib/quota/planRegistry.ts +107 -0
- package/src/lib/quota/planResolver.ts +78 -0
- package/src/lib/quota/quotaCombos.ts +414 -0
- package/src/lib/quota/quotaKey.ts +202 -0
- package/src/lib/quota/quotaModelNaming.ts +84 -0
- package/src/lib/quota/redisQuotaStore.ts +352 -0
- package/src/lib/quota/saturationSignals.ts +559 -0
- package/src/lib/quota/spendRecorder.ts +131 -0
- package/src/lib/quota/sqliteQuotaStore.ts +282 -0
- package/src/lib/quota/storeFactory.ts +124 -0
- package/src/lib/quota/types.ts +94 -0
- package/src/lib/resilience/modelLockoutSettings.ts +95 -0
- package/src/lib/resilience/settings/normalize.ts +359 -0
- package/src/lib/resilience/settings/types.ts +182 -0
- package/src/lib/resilience/settings.ts +386 -0
- package/src/lib/runtime/ports.ts +32 -0
- package/src/lib/search/executeWebSearch.ts +270 -0
- package/src/lib/security/localEndpoints.ts +82 -0
- package/src/lib/semanticCache.ts +377 -0
- package/src/lib/services/ServiceSupervisor.ts +243 -0
- package/src/lib/services/apiKey.ts +40 -0
- package/src/lib/services/bootstrap.ts +133 -0
- package/src/lib/services/embedPath.ts +19 -0
- package/src/lib/services/embedWsProxy.ts +285 -0
- package/src/lib/services/healthCheck.ts +79 -0
- package/src/lib/services/htmlRewriter.ts +185 -0
- package/src/lib/services/installers/bifrost.ts +145 -0
- package/src/lib/services/installers/cliproxy.ts +116 -0
- package/src/lib/services/installers/mux.ts +178 -0
- package/src/lib/services/installers/ninerouter.stub.ts +17 -0
- package/src/lib/services/installers/ninerouter.ts +157 -0
- package/src/lib/services/installers/utils.ts +167 -0
- package/src/lib/services/modelSync.ts +105 -0
- package/src/lib/services/portProbe.ts +104 -0
- package/src/lib/services/registry.ts +42 -0
- package/src/lib/services/reverseProxy.ts +180 -0
- package/src/lib/services/ringBuffer.ts +91 -0
- package/src/lib/services/types.ts +50 -0
- package/src/lib/settingsCache.ts +62 -0
- package/src/lib/skills/a2a.ts +34 -0
- package/src/lib/skills/builtin/browser.ts +22 -0
- package/src/lib/skills/builtins.ts +493 -0
- package/src/lib/skills/custom.ts +41 -0
- package/src/lib/skills/executor.ts +196 -0
- package/src/lib/skills/githubCollector.ts +426 -0
- package/src/lib/skills/hybrid.ts +67 -0
- package/src/lib/skills/injection.ts +307 -0
- package/src/lib/skills/interception.ts +343 -0
- package/src/lib/skills/providerSettings.ts +14 -0
- package/src/lib/skills/registry.ts +398 -0
- package/src/lib/skills/sandbox.ts +178 -0
- package/src/lib/skills/schemas.ts +43 -0
- package/src/lib/skills/skillssh.ts +73 -0
- package/src/lib/skills/types.ts +61 -0
- package/src/lib/source.ts +7 -0
- package/src/lib/spend/batchWriter.ts +208 -0
- package/src/lib/sseTextTransform.ts +346 -0
- package/src/lib/streamingPiiTransform.ts +350 -0
- package/src/lib/sync/bundle.ts +208 -0
- package/src/lib/sync/tokens.ts +107 -0
- package/src/lib/system/autoUpdate.ts +400 -0
- package/src/lib/system/globalPackagePath.ts +49 -0
- package/src/lib/system/versionCheck.ts +163 -0
- package/src/lib/tailscaleTunnel.ts +1201 -0
- package/src/lib/tokenHealthCheck.ts +829 -0
- package/src/lib/toolPolicy.ts +150 -0
- package/src/lib/translator/streamTransform.ts +27 -0
- package/src/lib/translatorEvents.ts +40 -0
- package/src/lib/usage/aggregateHistory.ts +212 -0
- package/src/lib/usage/apiKeySelfService.ts +420 -0
- package/src/lib/usage/apiKeyUsageLimits.ts +578 -0
- package/src/lib/usage/callLogArtifacts.ts +337 -0
- package/src/lib/usage/callLogs/format.ts +129 -0
- package/src/lib/usage/callLogs.ts +928 -0
- package/src/lib/usage/callLogsBoundedQueries.ts +42 -0
- package/src/lib/usage/codexResetCredits.ts +355 -0
- package/src/lib/usage/comboForecast.ts +441 -0
- package/src/lib/usage/comboHealth.ts +545 -0
- package/src/lib/usage/comboHealthDashboard.ts +109 -0
- package/src/lib/usage/comboScoringInspector.ts +416 -0
- package/src/lib/usage/completedRequestDetails.ts +103 -0
- package/src/lib/usage/costCalculator.ts +279 -0
- package/src/lib/usage/fetcher.ts +483 -0
- package/src/lib/usage/flatRateProviders.ts +59 -0
- package/src/lib/usage/internalUsageCommand.ts +788 -0
- package/src/lib/usage/migrations.ts +471 -0
- package/src/lib/usage/pendingRequestScope.ts +26 -0
- package/src/lib/usage/providerLimits/quotaNormalize.ts +72 -0
- package/src/lib/usage/providerLimits.ts +997 -0
- package/src/lib/usage/providerWindowCosts.ts +571 -0
- package/src/lib/usage/resilienceExplain.ts +468 -0
- package/src/lib/usage/routeExplain.ts +747 -0
- package/src/lib/usage/tokenAccounting.ts +212 -0
- package/src/lib/usage/usageEvents.ts +91 -0
- package/src/lib/usage/usageHistory/helpers.ts +85 -0
- package/src/lib/usage/usageHistory.ts +916 -0
- package/src/lib/usage/usageStats.ts +581 -0
- package/src/lib/usageAnalytics.ts +372 -0
- package/src/lib/usageDb.ts +38 -0
- package/src/lib/versionManager/binaryManager.ts +240 -0
- package/src/lib/versionManager/healthMonitor.ts +71 -0
- package/src/lib/versionManager/index.ts +155 -0
- package/src/lib/versionManager/processManager.ts +155 -0
- package/src/lib/versionManager/releaseChecker.ts +98 -0
- package/src/lib/vscode/familyFirstModelIds.ts +92 -0
- package/src/lib/vscode/modelPresentation.ts +132 -0
- package/src/lib/vscode/reasoningMetadata.ts +183 -0
- package/src/lib/vscode/serviceTierVariants.ts +202 -0
- package/src/lib/vscode/tokenizedRequest.ts +79 -0
- package/src/lib/webhookDispatcher.ts +221 -0
- package/src/lib/webhooks/eventDescriptions.ts +76 -0
- package/src/lib/webhooks/integrations/discord.ts +49 -0
- package/src/lib/webhooks/integrations/slack.ts +45 -0
- package/src/lib/webhooks/integrations/telegram.ts +67 -0
- package/src/lib/ws/handshake.ts +129 -0
- package/src/lib/zed-oauth/confirmedAccounts.ts +38 -0
- package/src/lib/zed-oauth/credentialFingerprint.ts +23 -0
- package/src/lib/zed-oauth/dockerDetect.ts +38 -0
- package/src/lib/zed-oauth/importUtils.ts +46 -0
- package/src/lib/zed-oauth/keychain-reader.stub.ts +28 -0
- package/src/lib/zed-oauth/keychain-reader.ts +231 -0
- package/src/mitm/_internal/bypass.cjs +170 -0
- package/src/mitm/_internal/forwardTarget.cjs +55 -0
- package/src/mitm/_internal/ingest.cjs +82 -0
- package/src/mitm/cert/generate.ts +41 -0
- package/src/mitm/cert/install.stub.ts +23 -0
- package/src/mitm/cert/install.ts +440 -0
- package/src/mitm/dataDir.ts +41 -0
- package/src/mitm/detection/antigravity.ts +33 -0
- package/src/mitm/detection/claudeCode.ts +25 -0
- package/src/mitm/detection/codex.ts +25 -0
- package/src/mitm/detection/copilot.ts +39 -0
- package/src/mitm/detection/cursor.ts +31 -0
- package/src/mitm/detection/index.ts +53 -0
- package/src/mitm/detection/kiro.ts +30 -0
- package/src/mitm/detection/openCode.ts +32 -0
- package/src/mitm/detection/zed.ts +26 -0
- package/src/mitm/dns/dnsConfig.ts +242 -0
- package/src/mitm/dns/provision.ts +92 -0
- package/src/mitm/handlers/antigravity.ts +192 -0
- package/src/mitm/handlers/base.ts +333 -0
- package/src/mitm/handlers/claudeCode.ts +56 -0
- package/src/mitm/handlers/codex.ts +55 -0
- package/src/mitm/handlers/copilot.ts +55 -0
- package/src/mitm/handlers/cursor.ts +55 -0
- package/src/mitm/handlers/kiro.ts +58 -0
- package/src/mitm/handlers/openCode.ts +55 -0
- package/src/mitm/handlers/trae.ts +24 -0
- package/src/mitm/handlers/zed.ts +55 -0
- package/src/mitm/inspector/agentBridgeHook.ts +137 -0
- package/src/mitm/inspector/buffer.ts +201 -0
- package/src/mitm/inspector/contextKey.ts +98 -0
- package/src/mitm/inspector/conversationNormalizer.ts +393 -0
- package/src/mitm/inspector/diagnostics.ts +67 -0
- package/src/mitm/inspector/httpProxyServer.ts +272 -0
- package/src/mitm/inspector/kindDetector.ts +87 -0
- package/src/mitm/inspector/llmMetadataExtractor.ts +183 -0
- package/src/mitm/inspector/pricing.ts +57 -0
- package/src/mitm/inspector/processAttribution.ts +107 -0
- package/src/mitm/inspector/sseMerger.ts +316 -0
- package/src/mitm/inspector/systemProxyConfig.ts +316 -0
- package/src/mitm/inspector/types.ts +112 -0
- package/src/mitm/manager.runtime.ts +5 -0
- package/src/mitm/manager.stub.ts +44 -0
- package/src/mitm/manager.ts +762 -0
- package/src/mitm/maskSecrets.ts +31 -0
- package/src/mitm/passthrough.ts +76 -0
- package/src/mitm/sanitizeHeaders.ts +61 -0
- package/src/mitm/server.cjs +786 -0
- package/src/mitm/socketTimeouts.ts +24 -0
- package/src/mitm/systemCommands.ts +280 -0
- package/src/mitm/targets/antigravity.ts +85 -0
- package/src/mitm/targets/claudeCode.ts +37 -0
- package/src/mitm/targets/codex.ts +30 -0
- package/src/mitm/targets/copilot.ts +32 -0
- package/src/mitm/targets/cursor.ts +33 -0
- package/src/mitm/targets/index.ts +75 -0
- package/src/mitm/targets/kiro.ts +64 -0
- package/src/mitm/targets/openCode.ts +34 -0
- package/src/mitm/targets/trae.ts +32 -0
- package/src/mitm/targets/zed.ts +32 -0
- package/src/mitm/tproxy/caTrust.ts +120 -0
- package/src/mitm/tproxy/captureManager.ts +118 -0
- package/src/mitm/tproxy/captureMode.ts +226 -0
- package/src/mitm/tproxy/commands.ts +122 -0
- package/src/mitm/tproxy/dynamicCert.ts +119 -0
- package/src/mitm/tproxy/native/README.md +55 -0
- package/src/mitm/tproxy/native/binding.gyp +9 -0
- package/src/mitm/tproxy/native/transparent.c +147 -0
- package/src/mitm/tproxy/setup.ts +68 -0
- package/src/mitm/tproxy/tlsCapture.ts +368 -0
- package/src/mitm/tproxy/transparentSocket.ts +131 -0
- package/src/mitm/types.ts +75 -0
- package/src/mitm/upstreamTrust.ts +40 -0
- package/src/models/index.ts +29 -0
- package/src/server/auth/loginGuard.ts +130 -0
- package/src/server/authz/accessScopes.ts +62 -0
- package/src/server/authz/accessTokenAuth.ts +67 -0
- package/src/server/authz/assertAuth.ts +88 -0
- package/src/server/authz/classify.ts +135 -0
- package/src/server/authz/context.ts +44 -0
- package/src/server/authz/csrf.ts +85 -0
- package/src/server/authz/headers.ts +76 -0
- package/src/server/authz/peerStamp.ts +99 -0
- package/src/server/authz/pipeline.ts +370 -0
- package/src/server/authz/policies/clientApi.ts +72 -0
- package/src/server/authz/policies/management.ts +298 -0
- package/src/server/authz/policies/public.ts +9 -0
- package/src/server/authz/routeGuard.ts +233 -0
- package/src/server/authz/types.ts +77 -0
- package/src/server/cors/origins.ts +172 -0
- package/src/server/origin/publicOrigin.ts +270 -0
- package/src/server/ws/liveServer.ts +630 -0
- package/src/server/ws/liveServerAllowList.ts +106 -0
- package/src/server/ws/types.ts +57 -0
- package/src/shared/components/Avatar.tsx +81 -0
- package/src/shared/components/Badge.tsx +68 -0
- package/src/shared/components/Breadcrumbs.tsx +103 -0
- package/src/shared/components/Button.tsx +85 -0
- package/src/shared/components/Card.tsx +141 -0
- package/src/shared/components/Checkbox.tsx +38 -0
- package/src/shared/components/CloudSyncStatus.tsx +104 -0
- package/src/shared/components/Collapsible.tsx +93 -0
- package/src/shared/components/CollapsibleSection.tsx +66 -0
- package/src/shared/components/ColumnToggle.tsx +100 -0
- package/src/shared/components/CommandPalette.tsx +375 -0
- package/src/shared/components/ConsoleLogViewer.tsx +326 -0
- package/src/shared/components/CursorAuthModal.tsx +198 -0
- package/src/shared/components/DataTable.tsx +195 -0
- package/src/shared/components/DegradationBadge.tsx +41 -0
- package/src/shared/components/DistributeProxiesButton.tsx +74 -0
- package/src/shared/components/EmptyState.tsx +121 -0
- package/src/shared/components/ErrorPageScaffold.tsx +91 -0
- package/src/shared/components/FilterBar.tsx +197 -0
- package/src/shared/components/Footer.tsx +169 -0
- package/src/shared/components/Header.tsx +284 -0
- package/src/shared/components/InfoTooltip.tsx +34 -0
- package/src/shared/components/Input.tsx +155 -0
- package/src/shared/components/KiroAuthModal.tsx +425 -0
- package/src/shared/components/KiroOAuthWrapper.tsx +116 -0
- package/src/shared/components/KiroSocialOAuthModal.tsx +202 -0
- package/src/shared/components/LanguageSelector.tsx +106 -0
- package/src/shared/components/LinkifiedText.tsx +30 -0
- package/src/shared/components/Loading.tsx +128 -0
- package/src/shared/components/LocaleAutoDetect.tsx +43 -0
- package/src/shared/components/MaintenanceBanner.tsx +87 -0
- package/src/shared/components/ManualConfigModal.tsx +51 -0
- package/src/shared/components/Modal.tsx +240 -0
- package/src/shared/components/ModelRoutingSection.tsx +323 -0
- package/src/shared/components/ModelSelectModal.tsx +618 -0
- package/src/shared/components/MonacoEditor.tsx +23 -0
- package/src/shared/components/NavigationProgress.tsx +105 -0
- package/src/shared/components/NoAuthAccountCard.tsx +539 -0
- package/src/shared/components/NoAuthProviderCard.tsx +40 -0
- package/src/shared/components/NoAuthProviderToggle.tsx +36 -0
- package/src/shared/components/NotificationToast.tsx +206 -0
- package/src/shared/components/OAuthModal.tsx +992 -0
- package/src/shared/components/OmniRouteLogo.tsx +86 -0
- package/src/shared/components/PresetSlider.tsx +64 -0
- package/src/shared/components/PricingModal.tsx +211 -0
- package/src/shared/components/ProviderIcon.tsx +263 -0
- package/src/shared/components/ProviderTestSlideOver.tsx +560 -0
- package/src/shared/components/ProxyConfigModal.tsx +781 -0
- package/src/shared/components/ProxyLogDetail.tsx +192 -0
- package/src/shared/components/ProxyLogger.tsx +573 -0
- package/src/shared/components/PwaRegister.tsx +22 -0
- package/src/shared/components/RequestLoggerDetail.tsx +797 -0
- package/src/shared/components/RequestLoggerV2.tsx +1628 -0
- package/src/shared/components/RiskNoticeModal.tsx +81 -0
- package/src/shared/components/SegmentedControl.tsx +69 -0
- package/src/shared/components/Select.tsx +110 -0
- package/src/shared/components/Sidebar.tsx +726 -0
- package/src/shared/components/SkillsConceptCard.tsx +84 -0
- package/src/shared/components/SystemMonitor.tsx +179 -0
- package/src/shared/components/Textarea.tsx +29 -0
- package/src/shared/components/ThemeProvider.tsx +14 -0
- package/src/shared/components/ThemeToggle.tsx +52 -0
- package/src/shared/components/Toggle.tsx +102 -0
- package/src/shared/components/TokenHealthBadge.tsx +113 -0
- package/src/shared/components/Tooltip.tsx +193 -0
- package/src/shared/components/TraeAuthModal.tsx +334 -0
- package/src/shared/components/UsageAnalytics.tsx +414 -0
- package/src/shared/components/UsageStats.tsx +693 -0
- package/src/shared/components/analytics/ApiKeyFilterDropdown.tsx +205 -0
- package/src/shared/components/analytics/CustomRangePicker.tsx +195 -0
- package/src/shared/components/analytics/TimeRangeSelector.tsx +49 -0
- package/src/shared/components/analytics/chartColors.ts +12 -0
- package/src/shared/components/analytics/charts.tsx +1023 -0
- package/src/shared/components/analytics/index.tsx +28 -0
- package/src/shared/components/analytics/rechartsCore.tsx +85 -0
- package/src/shared/components/analytics/rechartsDonuts.tsx +195 -0
- package/src/shared/components/analytics/rechartsUsageCharts.tsx +312 -0
- package/src/shared/components/cli/CliComparisonCard.tsx +82 -0
- package/src/shared/components/cli/CliConceptCard.tsx +58 -0
- package/src/shared/components/cli/CliToolCard.tsx +152 -0
- package/src/shared/components/cli/index.ts +8 -0
- package/src/shared/components/compression/CompressionPipelineEditor.tsx +175 -0
- package/src/shared/components/compression/EngineConfigForm.tsx +78 -0
- package/src/shared/components/compression/EngineConfigPage.tsx +411 -0
- package/src/shared/components/compression/compressionPipelineModel.ts +78 -0
- package/src/shared/components/docs/APIReference.stories.tsx +35 -0
- package/src/shared/components/docs/APIReference.tsx +83 -0
- package/src/shared/components/docs/Callout.stories.tsx +40 -0
- package/src/shared/components/docs/Callout.tsx +38 -0
- package/src/shared/components/docs/CodeBlock.stories.tsx +25 -0
- package/src/shared/components/docs/CodeBlock.tsx +52 -0
- package/src/shared/components/docs/DocsBreadcrumbs.stories.tsx +20 -0
- package/src/shared/components/docs/DocsBreadcrumbs.tsx +46 -0
- package/src/shared/components/docs/DocsSidebar.stories.tsx +31 -0
- package/src/shared/components/docs/DocsSidebar.tsx +77 -0
- package/src/shared/components/docs/DocsThemeProvider.tsx +21 -0
- package/src/shared/components/docs/Tabs.stories.tsx +26 -0
- package/src/shared/components/docs/Tabs.tsx +50 -0
- package/src/shared/components/docs/tokens.ts +38 -0
- package/src/shared/components/flow/FlowCanvas.tsx +151 -0
- package/src/shared/components/flow/StatusDot.tsx +36 -0
- package/src/shared/components/flow/edgeStyles.ts +32 -0
- package/src/shared/components/index.tsx +49 -0
- package/src/shared/components/layouts/AuthLayout.tsx +28 -0
- package/src/shared/components/layouts/DashboardLayout.tsx +131 -0
- package/src/shared/components/layouts/index.tsx +3 -0
- package/src/shared/components/lobeProviderIcons.ts +488 -0
- package/src/shared/components/logTableStyles.ts +7 -0
- package/src/shared/components/modelSelectModalHelpers.ts +75 -0
- package/src/shared/components/oauthBlobSubmit.ts +42 -0
- package/src/shared/components/proxyAssignment.ts +40 -0
- package/src/shared/components/requestLoggerPreferences.ts +44 -0
- package/src/shared/components/requestLoggerSignature.ts +56 -0
- package/src/shared/constants/agentSkills.ts +457 -0
- package/src/shared/constants/antigravityClientProfile.ts +29 -0
- package/src/shared/constants/apiKeyPolicyScopes.ts +5 -0
- package/src/shared/constants/appConfig.ts +12 -0
- package/src/shared/constants/batch.ts +1 -0
- package/src/shared/constants/batchEndpoints.ts +11 -0
- package/src/shared/constants/bodySize.ts +39 -0
- package/src/shared/constants/cliCompatProviders.ts +88 -0
- package/src/shared/constants/cliTools.ts +862 -0
- package/src/shared/constants/clientIdentityProfiles.ts +89 -0
- package/src/shared/constants/colors.ts +147 -0
- package/src/shared/constants/comboConfigMode.ts +9 -0
- package/src/shared/constants/config.ts +44 -0
- package/src/shared/constants/dashboardCsrf.ts +1 -0
- package/src/shared/constants/endpointCategories.ts +133 -0
- package/src/shared/constants/errorCodes.ts +245 -0
- package/src/shared/constants/featureFlagDefinitions.ts +495 -0
- package/src/shared/constants/headers.ts +16 -0
- package/src/shared/constants/homeWidgets.ts +5 -0
- package/src/shared/constants/index.ts +4 -0
- package/src/shared/constants/managementScopes.ts +31 -0
- package/src/shared/constants/mcpScopes.ts +78 -0
- package/src/shared/constants/mitmToolHosts.ts +31 -0
- package/src/shared/constants/modal.ts +5 -0
- package/src/shared/constants/modelCompat.ts +9 -0
- package/src/shared/constants/modelSpecs.ts +607 -0
- package/src/shared/constants/models.ts +40 -0
- package/src/shared/constants/openRouterPreset.ts +11 -0
- package/src/shared/constants/pricing/default-pricing.ts +16 -0
- package/src/shared/constants/pricing/frontier-labs.ts +386 -0
- package/src/shared/constants/pricing/inference-hosts.ts +208 -0
- package/src/shared/constants/pricing/oauth-subscriptions.ts +599 -0
- package/src/shared/constants/pricing/regional.ts +168 -0
- package/src/shared/constants/pricing/shared-tiers.ts +162 -0
- package/src/shared/constants/pricing.ts +40 -0
- package/src/shared/constants/providers/apikey/enterprise-cloud.ts +214 -0
- package/src/shared/constants/providers/apikey/frontier-labs.ts +253 -0
- package/src/shared/constants/providers/apikey/gateways.ts +662 -0
- package/src/shared/constants/providers/apikey/index.ts +21 -0
- package/src/shared/constants/providers/apikey/inference-hosts.ts +328 -0
- package/src/shared/constants/providers/apikey/regional.ts +372 -0
- package/src/shared/constants/providers/apikey/specialty-media.ts +266 -0
- package/src/shared/constants/providers/audio.ts +71 -0
- package/src/shared/constants/providers/cloud-agent.ts +36 -0
- package/src/shared/constants/providers/local.ts +162 -0
- package/src/shared/constants/providers/noauth.ts +123 -0
- package/src/shared/constants/providers/oauth.ts +231 -0
- package/src/shared/constants/providers/search.ts +125 -0
- package/src/shared/constants/providers/system.ts +16 -0
- package/src/shared/constants/providers/upstream-proxy.ts +36 -0
- package/src/shared/constants/providers/web-cookie.ts +364 -0
- package/src/shared/constants/providers.ts +449 -0
- package/src/shared/constants/publicApiRoutes.ts +62 -0
- package/src/shared/constants/responsesPreviousResponseId.ts +5 -0
- package/src/shared/constants/routingStrategies.ts +216 -0
- package/src/shared/constants/selfServiceScopes.ts +20 -0
- package/src/shared/constants/serviceKinds.ts +34 -0
- package/src/shared/constants/sidebarGroupVisibility.ts +31 -0
- package/src/shared/constants/sidebarVisibility/sections.ts +769 -0
- package/src/shared/constants/sidebarVisibility/types.ts +161 -0
- package/src/shared/constants/sidebarVisibility.ts +291 -0
- package/src/shared/constants/spawnCapablePrefixes.ts +35 -0
- package/src/shared/constants/statusColors.ts +17 -0
- package/src/shared/constants/upstreamHeaders.ts +42 -0
- package/src/shared/constants/visionBridgeDefaults.ts +88 -0
- package/src/shared/constants/visionModels.ts +68 -0
- package/src/shared/contracts/quota.ts +138 -0
- package/src/shared/hooks/cli/useToolBatchStatuses.ts +54 -0
- package/src/shared/hooks/index.ts +3 -0
- package/src/shared/hooks/useCopyToClipboard.ts +38 -0
- package/src/shared/hooks/useDisplayBaseUrl.ts +49 -0
- package/src/shared/hooks/useElectron.ts +197 -0
- package/src/shared/hooks/useTheme.ts +59 -0
- package/src/shared/http/apiErrorMessage.ts +19 -0
- package/src/shared/lib/persistLocale.ts +19 -0
- package/src/shared/middleware/bodySizeGuard.ts +97 -0
- package/src/shared/middleware/chatBodyAdmission.ts +161 -0
- package/src/shared/middleware/correlationId.ts +43 -0
- package/src/shared/network/outboundUrlGuard.ts +276 -0
- package/src/shared/network/remoteImageFetch.ts +182 -0
- package/src/shared/network/safeOutboundFetch.ts +372 -0
- package/src/shared/providers/webSessionCredentials.ts +308 -0
- package/src/shared/reasoning/effortStandardization.ts +124 -0
- package/src/shared/schemas/agentBridge.ts +37 -0
- package/src/shared/schemas/cliCatalog.ts +66 -0
- package/src/shared/schemas/inspector.ts +47 -0
- package/src/shared/schemas/memory.ts +142 -0
- package/src/shared/schemas/playground.ts +67 -0
- package/src/shared/schemas/qdrant.ts +39 -0
- package/src/shared/schemas/quota.ts +61 -0
- package/src/shared/schemas/searchTools.ts +39 -0
- package/src/shared/schemas/validation.ts +154 -0
- package/src/shared/services/apiKeyResolver.ts +44 -0
- package/src/shared/services/backupService.ts +233 -0
- package/src/shared/services/claudeCliConfig.ts +17 -0
- package/src/shared/services/cliRuntime.ts +1099 -0
- package/src/shared/services/cloudSyncScheduler.ts +135 -0
- package/src/shared/services/droidCustomModels.ts +118 -0
- package/src/shared/services/initializeCloudSync.ts +31 -0
- package/src/shared/services/loginShellPath.ts +87 -0
- package/src/shared/services/modelSyncScheduler.ts +225 -0
- package/src/shared/services/opencodeConfig.ts +140 -0
- package/src/shared/services/providerLimitsSyncScheduler.ts +72 -0
- package/src/shared/types/cliBatchStatus.ts +18 -0
- package/src/shared/types/index.ts +3 -0
- package/src/shared/types/pagination.ts +61 -0
- package/src/shared/types/utilization.ts +405 -0
- package/src/shared/utils/a11yAudit.ts +140 -0
- package/src/shared/utils/api.ts +112 -0
- package/src/shared/utils/apiAuth.ts +354 -0
- package/src/shared/utils/apiKey.ts +92 -0
- package/src/shared/utils/apiKeyPolicy.ts +680 -0
- package/src/shared/utils/apiResponse.ts +79 -0
- package/src/shared/utils/bulkApiKeyParser.ts +113 -0
- package/src/shared/utils/circuitBreaker.ts +611 -0
- package/src/shared/utils/classify429.ts +253 -0
- package/src/shared/utils/cliCompat.ts +5 -0
- package/src/shared/utils/clineAuth.ts +62 -0
- package/src/shared/utils/clipboard.ts +49 -0
- package/src/shared/utils/cloud.ts +41 -0
- package/src/shared/utils/cn.ts +12 -0
- package/src/shared/utils/codexBaseUrl.ts +32 -0
- package/src/shared/utils/codexConfig.ts +30 -0
- package/src/shared/utils/compressionHeaderEcho.ts +59 -0
- package/src/shared/utils/cors.ts +24 -0
- package/src/shared/utils/costEstimator.ts +126 -0
- package/src/shared/utils/dashboardCsrf.ts +196 -0
- package/src/shared/utils/featureFlags.ts +113 -0
- package/src/shared/utils/fetchError.ts +26 -0
- package/src/shared/utils/fetchTimeout.ts +78 -0
- package/src/shared/utils/formatting.ts +183 -0
- package/src/shared/utils/freeModels.ts +112 -0
- package/src/shared/utils/index.ts +39 -0
- package/src/shared/utils/inputSanitizer.ts +339 -0
- package/src/shared/utils/linkify.ts +54 -0
- package/src/shared/utils/logRedaction.ts +108 -0
- package/src/shared/utils/logger.ts +173 -0
- package/src/shared/utils/machine.ts +5 -0
- package/src/shared/utils/machineId.ts +167 -0
- package/src/shared/utils/maskEmail.ts +77 -0
- package/src/shared/utils/modelCatalogSearch.ts +84 -0
- package/src/shared/utils/noAuthProviders.ts +79 -0
- package/src/shared/utils/nodeRuntimeSupport.ts +112 -0
- package/src/shared/utils/parseApiKeys.ts +41 -0
- package/src/shared/utils/providerDisplayLabel.ts +41 -0
- package/src/shared/utils/providerHints.ts +73 -0
- package/src/shared/utils/providerModelAliases.ts +68 -0
- package/src/shared/utils/rateLimiter.ts +243 -0
- package/src/shared/utils/releaseNotes.ts +53 -0
- package/src/shared/utils/requestId.ts +102 -0
- package/src/shared/utils/requestTelemetry.ts +189 -0
- package/src/shared/utils/requestTimeout.ts +64 -0
- package/src/shared/utils/resolveOmniRouteBaseUrl.ts +24 -0
- package/src/shared/utils/runtimeTimeouts.ts +257 -0
- package/src/shared/utils/secretsValidator.ts +135 -0
- package/src/shared/utils/secureRandom.ts +66 -0
- package/src/shared/utils/serviceTierLabels.ts +42 -0
- package/src/shared/utils/shuffleDeck.ts +147 -0
- package/src/shared/utils/sidebarRouteMatch.ts +43 -0
- package/src/shared/utils/streamTracker.ts +187 -0
- package/src/shared/utils/structuredLogger.ts +219 -0
- package/src/shared/utils/tiktokenCounter.ts +21 -0
- package/src/shared/utils/turkishText.ts +66 -0
- package/src/shared/utils/upstreamError.ts +112 -0
- package/src/shared/validation/compressionConfigSchemas.ts +234 -0
- package/src/shared/validation/freeProxySchemas.ts +111 -0
- package/src/shared/validation/helpers.ts +117 -0
- package/src/shared/validation/oneproxySchemas.ts +14 -0
- package/src/shared/validation/providerSchema.ts +51 -0
- package/src/shared/validation/providerSpecificData.ts +354 -0
- package/src/shared/validation/schemas/apiV1.ts +297 -0
- package/src/shared/validation/schemas/auth.ts +200 -0
- package/src/shared/validation/schemas/cli.ts +86 -0
- package/src/shared/validation/schemas/cloud.ts +53 -0
- package/src/shared/validation/schemas/combo.ts +373 -0
- package/src/shared/validation/schemas/evals.ts +86 -0
- package/src/shared/validation/schemas/gemini.ts +59 -0
- package/src/shared/validation/schemas/keys.ts +144 -0
- package/src/shared/validation/schemas/misc.ts +203 -0
- package/src/shared/validation/schemas/payloadRules.ts +64 -0
- package/src/shared/validation/schemas/pricing.ts +40 -0
- package/src/shared/validation/schemas/provider.ts +430 -0
- package/src/shared/validation/schemas/proxy.ts +243 -0
- package/src/shared/validation/schemas/routing.ts +88 -0
- package/src/shared/validation/schemas/settings.ts +267 -0
- package/src/shared/validation/schemas/translator.ts +44 -0
- package/src/shared/validation/schemas.ts +18 -0
- package/src/shared/validation/settingsSchemas.ts +396 -0
- package/src/sse/handlers/chat.ts +1750 -0
- package/src/sse/handlers/chatHelpers.ts +859 -0
- package/src/sse/handlers/requestBody.ts +24 -0
- package/src/sse/handlers/resolveRoutingModel.ts +17 -0
- package/src/sse/services/auth.ts +2446 -0
- package/src/sse/services/cooldownAwareRetry.ts +162 -0
- package/src/sse/services/model.ts +254 -0
- package/src/sse/services/noAuthProviderSettings.ts +18 -0
- package/src/sse/services/noAuthProxyResolution.ts +111 -0
- package/src/sse/services/sessionAffinityPin.ts +247 -0
- package/src/sse/services/streamState.ts +218 -0
- package/src/sse/services/tokenRefresh.ts +275 -0
- package/src/sse/utils/logger.ts +37 -0
- package/src/types/databaseSettings.ts +124 -0
- package/src/types/global.d.ts +122 -0
- package/src/types/index.ts +10 -0
- package/src/types/provider.ts +9 -0
- package/src/types/sqljs.d.ts +32 -0
|
@@ -0,0 +1,4685 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode plugin for the OmniRoute AI Gateway.
|
|
3
|
+
*
|
|
4
|
+
* Implements the official `@opencode-ai/plugin` Plugin contract (auth +
|
|
5
|
+
* provider + config hooks) to drive a running OmniRoute instance from
|
|
6
|
+
* OpenCode without hand-curated `provider.<id>.models` blocks in
|
|
7
|
+
* opencode.json[c]:
|
|
8
|
+
*
|
|
9
|
+
* - `auth` — registers `/connect <providerId>` flow (API key prompt)
|
|
10
|
+
* - `provider` — dynamic `/v1/models` fetch with TTL cache, capabilities
|
|
11
|
+
* pass-through (OmniRoute is the source of truth — no
|
|
12
|
+
* client-side variant synthesis)
|
|
13
|
+
* - `config` — backward-compat shim for OC versions that predate the
|
|
14
|
+
* `provider.models` hook (≤ 1.14.48)
|
|
15
|
+
*
|
|
16
|
+
* Two ways to consume the plugin:
|
|
17
|
+
*
|
|
18
|
+
* 1. Single-instance (default `providerId: "omniroute"`):
|
|
19
|
+
*
|
|
20
|
+
* ```json
|
|
21
|
+
* {
|
|
22
|
+
* "$schema": "https://opencode.ai/config.json",
|
|
23
|
+
* "plugin": ["@omniroute/opencode-plugin"]
|
|
24
|
+
* }
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* 2. Multi-instance via plugin options (prod + preprod side by side):
|
|
28
|
+
*
|
|
29
|
+
* ```json
|
|
30
|
+
* {
|
|
31
|
+
* "$schema": "https://opencode.ai/config.json",
|
|
32
|
+
* "plugin": [
|
|
33
|
+
* ["@omniroute/opencode-plugin", { "providerId": "omniroute" }],
|
|
34
|
+
* ["@omniroute/opencode-plugin", { "providerId": "omniroute-preprod" }]
|
|
35
|
+
* ]
|
|
36
|
+
* }
|
|
37
|
+
* ```
|
|
38
|
+
*
|
|
39
|
+
* Then `opencode connect <providerId>` to provision the API key per instance.
|
|
40
|
+
*
|
|
41
|
+
* Companion library: `@omniroute/opencode-provider` (build-time config generator)
|
|
42
|
+
* remains supported for users who can't run plugins (CI, scripted scaffolding).
|
|
43
|
+
*
|
|
44
|
+
* @see https://opencode.ai/docs/plugins for the OpenCode plugin contract.
|
|
45
|
+
* @see https://github.com/diegosouzapw/OmniRoute for the AI Gateway.
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
import { createHash } from "node:crypto";
|
|
49
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
50
|
+
import * as os from "node:os";
|
|
51
|
+
import * as path from "node:path";
|
|
52
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
53
|
+
import { homedir } from "node:os";
|
|
54
|
+
import { join } from "node:path";
|
|
55
|
+
import { randomUUID } from "node:crypto";
|
|
56
|
+
import type { AuthHook, Config, Plugin, PluginOptions, ProviderHook } from "@opencode-ai/plugin";
|
|
57
|
+
import type { Model as ModelV2 } from "@opencode-ai/sdk/v2";
|
|
58
|
+
import { z } from "zod";
|
|
59
|
+
import { logger as _logger, setLogLevel, type LogLevel as _LogLevel } from "./logger.js";
|
|
60
|
+
import {
|
|
61
|
+
PROVIDER_TAG_SEPARATOR as _PROVIDER_TAG_SEPARATOR,
|
|
62
|
+
shortProviderLabel as _shortProviderLabel,
|
|
63
|
+
normaliseFreeLabel as _normaliseFreeLabel,
|
|
64
|
+
formatAutoComboName,
|
|
65
|
+
autoComboModelId,
|
|
66
|
+
formatFreeBudget,
|
|
67
|
+
type AutoVariant,
|
|
68
|
+
AUTO_VARIANTS,
|
|
69
|
+
AUTO_VARIANT_DESCRIPTIONS,
|
|
70
|
+
type FreeModelFreeType,
|
|
71
|
+
} from "./naming.js";
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Zod schema for plugin options accepted as the second element of the
|
|
75
|
+
* `plugin: [name, opts]` tuple in opencode.json. Strict by design — unknown
|
|
76
|
+
* keys are rejected so typos in opencode.json surface immediately at plugin
|
|
77
|
+
* construction time instead of silently being dropped.
|
|
78
|
+
*
|
|
79
|
+
* Doc per field:
|
|
80
|
+
*
|
|
81
|
+
* - `providerId` OpenCode provider id this plugin instance binds to.
|
|
82
|
+
* Multiple plugin instances coexist by giving each a
|
|
83
|
+
* different `providerId` ("omniroute", "omniroute-preprod",
|
|
84
|
+
* "omniroute-local"). Maps to `ProviderHook.id` and
|
|
85
|
+
* `AuthHook.provider` in the @opencode-ai/plugin contract.
|
|
86
|
+
* Default: "omniroute".
|
|
87
|
+
* - `displayName` Label rendered in the OpenCode UI. Default derives
|
|
88
|
+
* from providerId.
|
|
89
|
+
* - `modelCacheTtl` `/v1/models` TTL cache duration in milliseconds.
|
|
90
|
+
* Default: 300_000 (5 min).
|
|
91
|
+
* - `baseURL` Override base URL for this OmniRoute instance. When
|
|
92
|
+
* absent, the loader falls back to a credential-attached
|
|
93
|
+
* baseURL set by `/connect`.
|
|
94
|
+
*/
|
|
95
|
+
/**
|
|
96
|
+
* Optional feature toggles. Every field is opt-in/out per call; defaults
|
|
97
|
+
* mirror the v0.1.0 behaviour so existing opencode.json files do not need
|
|
98
|
+
* to change.
|
|
99
|
+
*
|
|
100
|
+
* - `combos` Discover `/api/combos` and surface them as
|
|
101
|
+
* pseudo-models with LCD capabilities. Default true.
|
|
102
|
+
* - `enrichment` Pull display names + pricing from
|
|
103
|
+
* `/api/pricing/models` and overlay them onto the
|
|
104
|
+
* ModelV2 entries derived from `/v1/models`. Solves
|
|
105
|
+
* the "raw id in UI" complaint without client-side
|
|
106
|
+
* heuristics. Default true.
|
|
107
|
+
* - `compressionMetadata` Pull `/api/context/combos` so combo entries can
|
|
108
|
+
* be tagged with their compression pipeline
|
|
109
|
+
* (e.g. `rtk:standard → caveman:full`). Off by
|
|
110
|
+
* default — adds one network call per refresh and
|
|
111
|
+
* the data is only useful for combo entries.
|
|
112
|
+
* - `geminiSanitization` Strip `$schema`/`$ref`/`additionalProperties`
|
|
113
|
+
* from `tools[].function.parameters` when the
|
|
114
|
+
* model id contains "gemini". Default true.
|
|
115
|
+
* - `mcpAutoEmit` Auto-write an `mcp.<providerId>` remote entry
|
|
116
|
+
* into the OC config pointing at
|
|
117
|
+
* `<baseURL>/api/mcp/stream` with the resolved
|
|
118
|
+
* Bearer token. Default false — keeps opencode.json
|
|
119
|
+
* in control unless explicitly opted in.
|
|
120
|
+
* - `mcpToken` Optional separate Bearer token to use in the
|
|
121
|
+
* auto-emitted MCP entry. Falls back to the
|
|
122
|
+
* provider's API key (from auth.json) when unset.
|
|
123
|
+
* Useful when a narrower-scoped MCP-only key is
|
|
124
|
+
* preferred over the chat/inference key.
|
|
125
|
+
* - `fetchInterceptor` Inject Authorization: Bearer + Content-Type on
|
|
126
|
+
* every outbound request to baseURL. Default true.
|
|
127
|
+
* - `debugLog` Capture every outbound request + response to a
|
|
128
|
+
* JSONL file at
|
|
129
|
+
* `~/.local/share/opencode/plugins/omniroute-debug-{providerId}.jsonl`.
|
|
130
|
+
* Each line: `{ reqId, ts, url, method, reqBody,
|
|
131
|
+
* resStatus, resBody, durationMs }`.
|
|
132
|
+
* Default false. Opt-in.
|
|
133
|
+
* - `apiFormat` Per-provider-prefix API format routing. Model IDs
|
|
134
|
+
* whose prefix (the part before `/`) matches an entry
|
|
135
|
+
* in `anthropicPrefixes` are served via the Anthropic
|
|
136
|
+
* SDK (`@ai-sdk/anthropic`, sends to `/v1/messages`
|
|
137
|
+
* with native cache_control, tool_choice, etc.).
|
|
138
|
+
* All other models fall back to `openai-compatible`.
|
|
139
|
+
*
|
|
140
|
+
* Default `anthropicPrefixes`:
|
|
141
|
+
* ["cc", "claude", "anthropic", "kiro", "kr"]
|
|
142
|
+
* (covers OmniRoute's canonical Anthropic aliases).
|
|
143
|
+
*
|
|
144
|
+
* Set `anthropicPrefixes: []` to disable and force
|
|
145
|
+
* everything through OpenAI-compat.
|
|
146
|
+
*
|
|
147
|
+
* Example:
|
|
148
|
+
* ```json
|
|
149
|
+
* "apiFormat": { "anthropicPrefixes": ["cc","claude","anthropic","kiro"] }
|
|
150
|
+
* ```
|
|
151
|
+
*/
|
|
152
|
+
const apiFormatSchema = z
|
|
153
|
+
.object({
|
|
154
|
+
anthropicPrefixes: z.array(z.string()).optional(),
|
|
155
|
+
})
|
|
156
|
+
.strict()
|
|
157
|
+
.optional();
|
|
158
|
+
|
|
159
|
+
const featuresSchema = z
|
|
160
|
+
.object({
|
|
161
|
+
combos: z.boolean().optional(),
|
|
162
|
+
autoCombos: z.boolean().optional(),
|
|
163
|
+
enrichment: z.boolean().optional(),
|
|
164
|
+
compressionMetadata: z.boolean().optional(),
|
|
165
|
+
geminiSanitization: z.boolean().optional(),
|
|
166
|
+
mcpAutoEmit: z.boolean().optional(),
|
|
167
|
+
mcpToken: z.string().min(1).optional(),
|
|
168
|
+
fetchInterceptor: z.boolean().optional(),
|
|
169
|
+
usableOnly: z.boolean().optional(),
|
|
170
|
+
diskCache: z.boolean().optional(),
|
|
171
|
+
providerTag: z.boolean().optional(),
|
|
172
|
+
debugLog: z.boolean().optional(),
|
|
173
|
+
startupDebug: z.boolean().optional(),
|
|
174
|
+
logLevel: z.enum(["error", "warn", "info", "debug"]).optional(),
|
|
175
|
+
apiFormat: apiFormatSchema,
|
|
176
|
+
})
|
|
177
|
+
.strict();
|
|
178
|
+
|
|
179
|
+
const optionsSchema = z
|
|
180
|
+
.object({
|
|
181
|
+
providerId: z
|
|
182
|
+
.string()
|
|
183
|
+
.min(1)
|
|
184
|
+
.regex(/^[a-z0-9-]+$/i, "providerId must be a slug")
|
|
185
|
+
.optional(),
|
|
186
|
+
displayName: z.string().min(1).optional(),
|
|
187
|
+
modelCacheTtl: z.number().positive().optional(),
|
|
188
|
+
baseURL: z.string().url().optional(),
|
|
189
|
+
features: featuresSchema.optional(),
|
|
190
|
+
})
|
|
191
|
+
.strict();
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Plugin options shape — inferred directly from the Zod schema so the
|
|
195
|
+
* validator and the static type can never drift. Replaces the standalone
|
|
196
|
+
* interface previously declared here (T-02). Every consumer continues to
|
|
197
|
+
* import `OmniRoutePluginOptions` as before; only the source of truth
|
|
198
|
+
* shifted from a hand-written interface to `z.infer<typeof optionsSchema>`.
|
|
199
|
+
*/
|
|
200
|
+
export type OmniRoutePluginOptions = z.infer<typeof optionsSchema>;
|
|
201
|
+
|
|
202
|
+
export const OMNIROUTE_PROVIDER_KEY = "omniroute" as const;
|
|
203
|
+
|
|
204
|
+
/** Deployed plugin version (injected at build time by tsup define). */
|
|
205
|
+
export const PLUGIN_VERSION: string =
|
|
206
|
+
((globalThis as Record<string, unknown>).__PLUGIN_VERSION__ as string) ?? "dev";
|
|
207
|
+
|
|
208
|
+
/** Deployed plugin git commit hash (injected at build time by tsup define). */
|
|
209
|
+
export const PLUGIN_GIT_HASH: string =
|
|
210
|
+
((globalThis as Record<string, unknown>).__PLUGIN_GIT_HASH__ as string) ?? "unknown";
|
|
211
|
+
|
|
212
|
+
export const DEFAULT_MODEL_CACHE_TTL_MS = 300_000 as const;
|
|
213
|
+
|
|
214
|
+
// Manual trim helpers avoid polynomial-regex CodeQL warnings on
|
|
215
|
+
// user-supplied baseURL strings (string.replace(/\/+$/, "")). The same
|
|
216
|
+
// behaviour, no backtracking.
|
|
217
|
+
function trimTrailingSlashes(value: string): string {
|
|
218
|
+
let i = value.length;
|
|
219
|
+
while (i > 0 && value.charCodeAt(i - 1) === 0x2f /* "/" */) i--;
|
|
220
|
+
return i === value.length ? value : value.slice(0, i);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function trimTrailingDashes(value: string): string {
|
|
224
|
+
let i = value.length;
|
|
225
|
+
while (i > 0 && value.charCodeAt(i - 1) === 0x2d /* "-" */) i--;
|
|
226
|
+
return i === value.length ? value : value.slice(0, i);
|
|
227
|
+
}
|
|
228
|
+
function trimLeadingDashes(value: string): string {
|
|
229
|
+
let i = 0;
|
|
230
|
+
while (i < value.length && value.charCodeAt(i) === 0x2d /* "-" */) i++;
|
|
231
|
+
return i === 0 ? value : value.slice(i);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Resolve effective options from the optional plugin-options object,
|
|
236
|
+
* applying defaults. Centralises the providerId fallback so every hook
|
|
237
|
+
* sees a consistent identifier.
|
|
238
|
+
*/
|
|
239
|
+
export function resolveOmniRoutePluginOptions(
|
|
240
|
+
opts?: OmniRoutePluginOptions
|
|
241
|
+
): Required<Pick<OmniRoutePluginOptions, "providerId" | "displayName" | "modelCacheTtl">> &
|
|
242
|
+
Pick<OmniRoutePluginOptions, "baseURL" | "features"> {
|
|
243
|
+
const rawProviderId = opts?.providerId ?? OMNIROUTE_PROVIDER_KEY;
|
|
244
|
+
// OC 1.17.8+ native-adapter gate rejects providerID not in
|
|
245
|
+
// {openai, anthropic, opencode*}. Silently prefix so existing
|
|
246
|
+
// configs (providerId: "omniroute") keep working.
|
|
247
|
+
const providerId = rawProviderId.startsWith("opencode-")
|
|
248
|
+
? rawProviderId
|
|
249
|
+
: `opencode-${rawProviderId}`;
|
|
250
|
+
const displayName =
|
|
251
|
+
opts?.displayName ??
|
|
252
|
+
(providerId === `opencode-${OMNIROUTE_PROVIDER_KEY}`
|
|
253
|
+
? "OmniRoute"
|
|
254
|
+
: `OmniRoute (${providerId})`);
|
|
255
|
+
const modelCacheTtl =
|
|
256
|
+
typeof opts?.modelCacheTtl === "number" && opts.modelCacheTtl > 0
|
|
257
|
+
? opts.modelCacheTtl
|
|
258
|
+
: DEFAULT_MODEL_CACHE_TTL_MS;
|
|
259
|
+
return {
|
|
260
|
+
providerId,
|
|
261
|
+
displayName,
|
|
262
|
+
modelCacheTtl,
|
|
263
|
+
baseURL: opts?.baseURL,
|
|
264
|
+
features: opts?.features,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Strict parse of raw plugin options (as received from opencode.json or a
|
|
270
|
+
* direct factory call) into the validated `OmniRoutePluginOptions` shape.
|
|
271
|
+
*
|
|
272
|
+
* - `null` / `undefined` → `{}` (no opts is valid, defaults take over).
|
|
273
|
+
* - Unknown keys → throws (strict schema catches typos in opencode.json).
|
|
274
|
+
* - Empty / malformed values (e.g. empty providerId, non-URL baseURL,
|
|
275
|
+
* negative modelCacheTtl) → throws.
|
|
276
|
+
*
|
|
277
|
+
* Validation happens at plugin invocation time (inside `OmniRoutePlugin`),
|
|
278
|
+
* NOT at module import — so a bad opencode.json fails the affected plugin
|
|
279
|
+
* instance with an actionable message instead of crashing the whole TUI on
|
|
280
|
+
* startup.
|
|
281
|
+
*
|
|
282
|
+
* Exported so callers and tests can validate options independent of the
|
|
283
|
+
* full plugin factory invocation.
|
|
284
|
+
*/
|
|
285
|
+
export function parseOmniRoutePluginOptions(opts: unknown): OmniRoutePluginOptions {
|
|
286
|
+
if (opts === null || opts === undefined) return {};
|
|
287
|
+
const result = optionsSchema.safeParse(opts);
|
|
288
|
+
if (!result.success) {
|
|
289
|
+
const errs = result.error.issues
|
|
290
|
+
.map((i) => {
|
|
291
|
+
const path = i.path.length > 0 ? i.path.join(".") : "<root>";
|
|
292
|
+
return `${path}: ${i.message}`;
|
|
293
|
+
})
|
|
294
|
+
.join("; ");
|
|
295
|
+
throw new Error(`Invalid @omniroute/opencode-plugin options: ${errs}`);
|
|
296
|
+
}
|
|
297
|
+
return result.data;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Internal coercion shim. Delegates to `parseOmniRoutePluginOptions` to keep
|
|
302
|
+
* the public surface stable while routing all validation through the Zod
|
|
303
|
+
* schema. Always returns an object (never undefined) so downstream hooks see
|
|
304
|
+
* the same shape regardless of whether opencode.json passed `null`,
|
|
305
|
+
* `undefined`, or an empty bag.
|
|
306
|
+
*/
|
|
307
|
+
function coercePluginOptions(opts?: PluginOptions): OmniRoutePluginOptions {
|
|
308
|
+
return parseOmniRoutePluginOptions(opts);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
312
|
+
// Per-prefix API format routing (apiFormat feature)
|
|
313
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Default provider-prefix list that triggers the Anthropic SDK format.
|
|
317
|
+
* Covers OmniRoute's canonical Anthropic aliases: `cc/`, `claude/`,
|
|
318
|
+
* `anthropic/`, plus the user-configured `kiro/` and `kr/` upstream
|
|
319
|
+
* connections that proxy Anthropic models.
|
|
320
|
+
*/
|
|
321
|
+
export const DEFAULT_ANTHROPIC_PREFIXES = ["cc", "claude", "anthropic", "kiro", "kr"];
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Ensure a baseURL ends with `/v1` so the OpenAI-compat SDK constructs
|
|
325
|
+
* `/v1/chat/completions` correctly. The Anthropic SDK does NOT want `/v1`
|
|
326
|
+
* (it appends `/v1/messages` automatically), so callers should branch on
|
|
327
|
+
* format first.
|
|
328
|
+
*/
|
|
329
|
+
export function ensureV1Suffix(url: string): string {
|
|
330
|
+
const trimmed = trimTrailingSlashes(url);
|
|
331
|
+
return trimmed.endsWith("/v1") ? trimmed : `${trimmed}/v1`;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Resolve the API block (id + url + npm package) for a given model id.
|
|
336
|
+
*
|
|
337
|
+
* Decision matrix:
|
|
338
|
+
* - If the model id's prefix (the substring before the first `/`) is in
|
|
339
|
+
* `apiFormat.anthropicPrefixes` (or the default list), return the
|
|
340
|
+
* Anthropic SDK block: `id: "anthropic"`, `url: baseURL` (no `/v1`),
|
|
341
|
+
* `npm: "@ai-sdk/anthropic"`.
|
|
342
|
+
* - Otherwise return the OpenAI-compat block: `id: "openai-compatible"`,
|
|
343
|
+
* `url: baseURL + "/v1"`, `npm: "@ai-sdk/openai-compatible"`.
|
|
344
|
+
*
|
|
345
|
+
* Combos span multiple providers. Callers should pass each combo member's
|
|
346
|
+
* id through this function and pick the LCD format (lowest common
|
|
347
|
+
* denominator that every upstream actually understands).
|
|
348
|
+
*/
|
|
349
|
+
export function resolveApiBlock(
|
|
350
|
+
modelId: string,
|
|
351
|
+
baseURL: string,
|
|
352
|
+
apiFormat?: { anthropicPrefixes?: string[] }
|
|
353
|
+
): { id: string; url: string; npm: string } {
|
|
354
|
+
const prefixes = apiFormat?.anthropicPrefixes ?? DEFAULT_ANTHROPIC_PREFIXES;
|
|
355
|
+
const slash = modelId.indexOf("/");
|
|
356
|
+
const prefix = slash === -1 ? modelId : modelId.slice(0, slash);
|
|
357
|
+
const isAnthropic = prefixes.includes(prefix);
|
|
358
|
+
return isAnthropic
|
|
359
|
+
? {
|
|
360
|
+
id: "anthropic",
|
|
361
|
+
url: trimTrailingSlashes(baseURL),
|
|
362
|
+
npm: "@ai-sdk/anthropic",
|
|
363
|
+
}
|
|
364
|
+
: {
|
|
365
|
+
id: "openai-compatible",
|
|
366
|
+
url: ensureV1Suffix(baseURL),
|
|
367
|
+
npm: "@ai-sdk/openai-compatible",
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Build the AuthHook portion of the plugin for a given options bag. Exported
|
|
373
|
+
* standalone so the auth contract can be unit-tested without faking the full
|
|
374
|
+
* PluginInput / Hooks surface.
|
|
375
|
+
*
|
|
376
|
+
* Contract notes:
|
|
377
|
+
* - `provider` binds to `providerId` (NOT a hardcoded module constant — fixes
|
|
378
|
+
* the multi-instance bug in opencode-omniroute-auth@1.2.1 which pinned
|
|
379
|
+
* `OMNIROUTE_PROVIDER_ID = "omniroute"` at module scope).
|
|
380
|
+
* - `methods[0]` is the `api` flavor (no OAuth flow; OmniRoute issues bearer
|
|
381
|
+
* keys directly). Label includes the resolved displayName so multi-instance
|
|
382
|
+
* setups stay distinguishable in the OC TUI.
|
|
383
|
+
* - `methods[0].prompts` uses the official `{type:"text", key, message}`
|
|
384
|
+
* shape from `@opencode-ai/plugin@1.15.6`. The contract does NOT expose
|
|
385
|
+
* a `mask: true` flag on text prompts — the OC TUI is expected to handle
|
|
386
|
+
* credential masking by itself (per OC's `auth login` UX).
|
|
387
|
+
* - `loader` reads the stored credentials via `getAuth()` and projects them
|
|
388
|
+
* into the AI-SDK `openai-compatible` options shape (`apiKey`, `baseURL`).
|
|
389
|
+
* The fetch interceptor (`fetch`) is wired in T-04; left absent here so
|
|
390
|
+
* downstream code falls back to the SDK default fetch.
|
|
391
|
+
* - The loader rejects non-`api` auth flavors (oauth / wellknown) and empty
|
|
392
|
+
* keys by returning `{}` — OC then surfaces the `/connect` flow to the
|
|
393
|
+
* user instead of dispatching a request with bogus credentials.
|
|
394
|
+
*/
|
|
395
|
+
export function createOmniRouteAuthHook(opts?: OmniRoutePluginOptions): AuthHook {
|
|
396
|
+
const { providerId, displayName, baseURL, features } = resolveOmniRoutePluginOptions(opts);
|
|
397
|
+
// Both fetch-layer features default ON (parity with the rest of the plugin's
|
|
398
|
+
// `features.X !== false` convention). Honoring them here lets users disable
|
|
399
|
+
// the interceptor/sanitizer from opencode.json — previously these flags were
|
|
400
|
+
// documented and schema-validated but silently ignored.
|
|
401
|
+
const wantFetchInterceptor = (features ?? {}).fetchInterceptor !== false;
|
|
402
|
+
const wantGeminiSanitization = (features ?? {}).geminiSanitization !== false;
|
|
403
|
+
const wantDebugLog = (features ?? {}).debugLog === true;
|
|
404
|
+
|
|
405
|
+
const hook: AuthHook = {
|
|
406
|
+
provider: providerId,
|
|
407
|
+
methods: [
|
|
408
|
+
{
|
|
409
|
+
type: "api",
|
|
410
|
+
label: `${displayName} API Key`,
|
|
411
|
+
prompts: [
|
|
412
|
+
{
|
|
413
|
+
type: "text",
|
|
414
|
+
key: "apiKey",
|
|
415
|
+
message: `OmniRoute API key (${providerId})`,
|
|
416
|
+
},
|
|
417
|
+
],
|
|
418
|
+
},
|
|
419
|
+
],
|
|
420
|
+
loader: async (getAuth, _provider) => {
|
|
421
|
+
const auth = await getAuth();
|
|
422
|
+
if (
|
|
423
|
+
auth &&
|
|
424
|
+
typeof auth === "object" &&
|
|
425
|
+
(auth as { type?: unknown }).type === "api" &&
|
|
426
|
+
typeof (auth as { key?: unknown }).key === "string" &&
|
|
427
|
+
(auth as { key: string }).key.length > 0
|
|
428
|
+
) {
|
|
429
|
+
const apiKey = (auth as { key: string }).key;
|
|
430
|
+
// baseURL resolution: plugin opts win, then a credential-attached
|
|
431
|
+
// baseURL (some auth backends stash it alongside the key), else empty.
|
|
432
|
+
// Re-cast through `unknown` first: Auth is a discriminated union
|
|
433
|
+
// (api | oauth | wellknown) and TS refuses a direct narrowing to a
|
|
434
|
+
// hypothetical `{ baseURL: string }` shape because WellKnownAuth has
|
|
435
|
+
// no `baseURL`. We've already checked the runtime type via typeof so
|
|
436
|
+
// the unknown-bridge is a safe assertion, not a lie.
|
|
437
|
+
const authBaseURL = (auth as unknown as { baseURL?: unknown }).baseURL;
|
|
438
|
+
const resolvedBaseURL = baseURL ?? (typeof authBaseURL === "string" ? authBaseURL : "");
|
|
439
|
+
// Without a baseURL the interceptor can't tell which requests to
|
|
440
|
+
// intercept (it would either gate-keep nothing or, worse, all
|
|
441
|
+
// outbound traffic). Fall back to apiKey-only and let the SDK use
|
|
442
|
+
// its default fetch. The /connect flow + plugin opts should make
|
|
443
|
+
// this branch unreachable in practice.
|
|
444
|
+
if (!resolvedBaseURL) {
|
|
445
|
+
return { apiKey };
|
|
446
|
+
}
|
|
447
|
+
// Composition: sanitise Gemini tool schemas FIRST (T-06), then inject
|
|
448
|
+
// Bearer (T-04). Both layers are pure with respect to the other's
|
|
449
|
+
// concern (body vs headers) so order is logically free; wrapping the
|
|
450
|
+
// pure body-transform around the header-injecting interceptor reads
|
|
451
|
+
// cleaner and keeps T-06 testable in isolation against any inner fetch
|
|
452
|
+
// (real or stub). Each layer is gated by its feature flag; when both
|
|
453
|
+
// are disabled we fall back to the SDK's default fetch (apiKey only).
|
|
454
|
+
let composedFetch: typeof fetch | undefined;
|
|
455
|
+
if (wantFetchInterceptor) {
|
|
456
|
+
composedFetch = createOmniRouteFetchInterceptor({
|
|
457
|
+
apiKey,
|
|
458
|
+
baseURL: resolvedBaseURL,
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
if (wantGeminiSanitization) {
|
|
462
|
+
composedFetch = createGeminiSanitizingFetch(composedFetch ?? fetch);
|
|
463
|
+
}
|
|
464
|
+
if (wantDebugLog || debugLogEnabled(providerId)) {
|
|
465
|
+
composedFetch = createDebugLoggingFetch(composedFetch ?? fetch, providerId, wantDebugLog);
|
|
466
|
+
}
|
|
467
|
+
return composedFetch
|
|
468
|
+
? { apiKey, baseURL: resolvedBaseURL, fetch: composedFetch }
|
|
469
|
+
: { apiKey, baseURL: resolvedBaseURL };
|
|
470
|
+
}
|
|
471
|
+
return {};
|
|
472
|
+
},
|
|
473
|
+
};
|
|
474
|
+
|
|
475
|
+
return hook;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Plugin factory. Returns the OpenCode Plugin object wired with the three
|
|
480
|
+
* hooks. Concrete hook bodies land in subsequent tickets (T-03 provider.models,
|
|
481
|
+
* T-04 fetch interceptor, T-06 Gemini sanitization, T-07 config backward-compat).
|
|
482
|
+
*
|
|
483
|
+
* Per `@opencode-ai/plugin@1.15.6`, the Plugin signature is
|
|
484
|
+
* `(input: PluginInput, options?: PluginOptions) => Promise<Hooks>` — opts
|
|
485
|
+
* arrive as the SECOND argument (from the `[name, opts]` tuple in
|
|
486
|
+
* opencode.json), NOT as a closure binding. Multi-instance support follows
|
|
487
|
+
* from each plugin tuple invoking the factory with its own opts.
|
|
488
|
+
*/
|
|
489
|
+
export const OmniRoutePlugin: Plugin = async (_input, options) => {
|
|
490
|
+
const resolved = coercePluginOptions(options);
|
|
491
|
+
// T-07: a single per-plugin-instance cache shared between the provider
|
|
492
|
+
// hook (T-03/T-05) and the config-shim hook (T-07). On OC ≥1.14.49 both
|
|
493
|
+
// hooks fire within the same Plugin invocation, so a shared cache keeps
|
|
494
|
+
// /v1/models + /api/combos at exactly one round-trip per TTL refresh
|
|
495
|
+
// instead of two. On OC ≤1.14.48 only the config hook runs; the cache
|
|
496
|
+
// still works (single producer + single consumer through the same map).
|
|
497
|
+
// Each `OmniRoutePlugin(...)` invocation gets its OWN cache via closure,
|
|
498
|
+
// so prod + preprod side-by-side instances do NOT collide.
|
|
499
|
+
const sharedCache: OmniRouteFetchCache = new Map();
|
|
500
|
+
// Debug breadcrumb: confirm server() invocation + resolved options.
|
|
501
|
+
// Useful when diagnosing "is the plugin even running" from OC logs.
|
|
502
|
+
const _ver: string =
|
|
503
|
+
((globalThis as Record<string, unknown>).__PLUGIN_VERSION__ as string) ?? "dev";
|
|
504
|
+
const _hash: string =
|
|
505
|
+
((globalThis as Record<string, unknown>).__PLUGIN_GIT_HASH__ as string) ?? "unknown";
|
|
506
|
+
const _prefixes = resolved.features?.apiFormat?.anthropicPrefixes ?? DEFAULT_ANTHROPIC_PREFIXES;
|
|
507
|
+
_logger.always(
|
|
508
|
+
`v${_ver} (${_hash}) initialized` +
|
|
509
|
+
` providerId=${resolved.providerId}` +
|
|
510
|
+
` baseURL=${resolved.baseURL ?? "(from auth.json)"}` +
|
|
511
|
+
` modelCacheTtl=${resolved.modelCacheTtl}ms` +
|
|
512
|
+
` apiFormat=anthropic:[${_prefixes.join(",")}]` +
|
|
513
|
+
` debugLog=${resolved.features?.debugLog ?? false}` +
|
|
514
|
+
` logLevel=${resolved.features?.startupDebug ? "debug" : (resolved.features?.logLevel ?? "warn")}`
|
|
515
|
+
);
|
|
516
|
+
|
|
517
|
+
// Wire log level: startupDebug:true → "debug", explicit logLevel wins.
|
|
518
|
+
setLogLevel(resolved.features?.startupDebug ? "debug" : (resolved.features?.logLevel ?? "warn"));
|
|
519
|
+
return {
|
|
520
|
+
auth: createOmniRouteAuthHook(resolved),
|
|
521
|
+
provider: createOmniRouteProviderHook(resolved, { cache: sharedCache }),
|
|
522
|
+
config: createOmniRouteConfigHook(resolved, { cache: sharedCache }),
|
|
523
|
+
};
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* v1 plugin shape per OC plugin loader (`packages/opencode/src/plugin/shared.ts:readV1Plugin`).
|
|
528
|
+
* OC checks the default export for an object with `{id, server}` shape FIRST.
|
|
529
|
+
* If that fails it falls back to legacy `getLegacyPlugins` which walks every
|
|
530
|
+
* named export and rejects any non-function value — our package has
|
|
531
|
+
* constants (OMNIROUTE_PROVIDER_KEY, DEFAULT_MODEL_CACHE_TTL_MS) + types +
|
|
532
|
+
* schemas as named exports, so the legacy path always fails for us.
|
|
533
|
+
*
|
|
534
|
+
* Using v1 shape skips the legacy walk entirely. The `id` field is the
|
|
535
|
+
* plugin MODULE identifier (one per published package); per-instance
|
|
536
|
+
* `providerId` still flows through `options.providerId` as before.
|
|
537
|
+
*/
|
|
538
|
+
const OmniRouteV1Plugin = {
|
|
539
|
+
id: "@omniroute/opencode-plugin",
|
|
540
|
+
server: OmniRoutePlugin,
|
|
541
|
+
};
|
|
542
|
+
|
|
543
|
+
export default OmniRouteV1Plugin;
|
|
544
|
+
|
|
545
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
546
|
+
// Provider hook (T-03) — /v1/models pass-through with TTL cache
|
|
547
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Raw shape of a `/v1/models` entry from OmniRoute. Captured verbatim from
|
|
551
|
+
* the prod gateway response (sample at /tmp/prod-v1-models.json: 455 entries).
|
|
552
|
+
* STRICT source-of-truth (OQ-3): every field that lands in ModelV2 traces
|
|
553
|
+
* back to this shape — no client-side variant synthesis.
|
|
554
|
+
*/
|
|
555
|
+
export interface OmniRouteRawModelEntry {
|
|
556
|
+
id: string;
|
|
557
|
+
object?: string;
|
|
558
|
+
owned_by?: string;
|
|
559
|
+
root?: string | null;
|
|
560
|
+
parent?: string | null;
|
|
561
|
+
context_length?: number;
|
|
562
|
+
max_input_tokens?: number;
|
|
563
|
+
max_output_tokens?: number;
|
|
564
|
+
input_modalities?: string[];
|
|
565
|
+
output_modalities?: string[];
|
|
566
|
+
capabilities?: {
|
|
567
|
+
tool_calling?: boolean;
|
|
568
|
+
reasoning?: boolean;
|
|
569
|
+
vision?: boolean;
|
|
570
|
+
thinking?: boolean;
|
|
571
|
+
attachment?: boolean;
|
|
572
|
+
structured_output?: boolean;
|
|
573
|
+
temperature?: boolean;
|
|
574
|
+
};
|
|
575
|
+
release_date?: string;
|
|
576
|
+
last_updated?: string;
|
|
577
|
+
api_format?: string;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/**
|
|
581
|
+
* Fetcher contract: returns the raw `/v1/models` entry list from a running
|
|
582
|
+
* OmniRoute instance. Surfaced as a dependency so unit tests can inject a
|
|
583
|
+
* stub without monkey-patching global `fetch`.
|
|
584
|
+
*
|
|
585
|
+
* Why we inline this instead of using `@omniroute/opencode-provider`'s
|
|
586
|
+
* `fetchLiveModels`: the sibling helper returns a stripped `{id, name,
|
|
587
|
+
* contextLength?}` shape (see opencode-provider/src/index.ts:480-569) that
|
|
588
|
+
* drops the `capabilities` / `*_modalities` / `max_*_tokens` blocks T-03
|
|
589
|
+
* needs for ModelV2 pass-through. Adopting the sibling here would force a
|
|
590
|
+
* client-side re-fetch or re-introduce the synthesis we explicitly rejected
|
|
591
|
+
* in OQ-3. A 30-line raw fetcher is cheaper than mutating the sibling's
|
|
592
|
+
* stable v0.1.0 contract.
|
|
593
|
+
*/
|
|
594
|
+
export type OmniRouteModelsFetcher = (
|
|
595
|
+
baseURL: string,
|
|
596
|
+
apiKey: string,
|
|
597
|
+
timeoutMs?: number
|
|
598
|
+
) => Promise<OmniRouteRawModelEntry[]>;
|
|
599
|
+
|
|
600
|
+
/**
|
|
601
|
+
* Default fetcher: `GET <baseURL>/v1/models` with bearer auth + AbortController
|
|
602
|
+
* timeout. Accepts both the `{object:"list", data:[…]}` envelope OmniRoute
|
|
603
|
+
* emits today and a bare-array envelope (defensive — keeps the plugin
|
|
604
|
+
* working if a future OmniRoute build trims the wrapper). Anything that
|
|
605
|
+
* isn't an object with a string `id` is filtered out silently.
|
|
606
|
+
*/
|
|
607
|
+
export const defaultOmniRouteModelsFetcher: OmniRouteModelsFetcher = async (
|
|
608
|
+
baseURL,
|
|
609
|
+
apiKey,
|
|
610
|
+
timeoutMs = 10_000
|
|
611
|
+
) => {
|
|
612
|
+
if (!apiKey) throw new Error("@omniroute/opencode-plugin: apiKey required to fetch /v1/models");
|
|
613
|
+
if (!baseURL) throw new Error("@omniroute/opencode-plugin: baseURL required to fetch /v1/models");
|
|
614
|
+
|
|
615
|
+
const trimmed = trimTrailingSlashes(baseURL);
|
|
616
|
+
// Tolerate both `https://host` and `https://host/v1` forms — the gateway
|
|
617
|
+
// exposes /v1/models either way; we just don't want a double `/v1/v1`.
|
|
618
|
+
const url = /\/v\d+$/.test(trimmed) ? `${trimmed}/models` : `${trimmed}/v1/models`;
|
|
619
|
+
|
|
620
|
+
const controller = new AbortController();
|
|
621
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
622
|
+
try {
|
|
623
|
+
const res = await fetch(url, {
|
|
624
|
+
method: "GET",
|
|
625
|
+
headers: {
|
|
626
|
+
Authorization: `Bearer ${apiKey}`,
|
|
627
|
+
Accept: "application/json",
|
|
628
|
+
},
|
|
629
|
+
signal: controller.signal,
|
|
630
|
+
});
|
|
631
|
+
if (!res.ok) {
|
|
632
|
+
throw new Error(
|
|
633
|
+
`@omniroute/opencode-plugin: GET ${url} failed: ${res.status} ${res.statusText}`
|
|
634
|
+
);
|
|
635
|
+
}
|
|
636
|
+
const body = (await res.json()) as unknown;
|
|
637
|
+
const rawList: unknown[] = Array.isArray(body)
|
|
638
|
+
? body
|
|
639
|
+
: body && typeof body === "object" && Array.isArray((body as { data?: unknown }).data)
|
|
640
|
+
? ((body as { data: unknown[] }).data as unknown[])
|
|
641
|
+
: [];
|
|
642
|
+
const out: OmniRouteRawModelEntry[] = [];
|
|
643
|
+
for (const r of rawList) {
|
|
644
|
+
if (r && typeof r === "object" && typeof (r as { id?: unknown }).id === "string") {
|
|
645
|
+
out.push(r as OmniRouteRawModelEntry);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
return out;
|
|
649
|
+
} finally {
|
|
650
|
+
clearTimeout(timer);
|
|
651
|
+
}
|
|
652
|
+
};
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* Map a raw `/v1/models` entry → `ModelV2` (the type @opencode-ai/sdk/v2
|
|
656
|
+
* exports as `Model`, re-exported by @opencode-ai/plugin as `ModelV2`).
|
|
657
|
+
*
|
|
658
|
+
* ModelV2 (as of @opencode-ai/sdk@v2 — see node_modules path
|
|
659
|
+
* `@opencode-ai/sdk/dist/v2/gen/types.gen.d.ts:964-1043`) requires a much
|
|
660
|
+
* richer shape than the T-03 spec's mapping table assumed. Concretely it
|
|
661
|
+
* expects:
|
|
662
|
+
* - flat `id`, `name`, `providerID`, `api: {id,url,npm}`
|
|
663
|
+
* - nested `capabilities: { temperature, reasoning, attachment, toolcall,
|
|
664
|
+
* input:{text,audio,image,video,pdf}, output:{…}, interleaved }`
|
|
665
|
+
* - `cost: { input, output, cache:{read,write} }` (NOT optional)
|
|
666
|
+
* - `limit: { context, input?, output }`
|
|
667
|
+
* - `status: "alpha"|"beta"|"deprecated"|"active"`, `options:{}`, `headers:{}`
|
|
668
|
+
* - `release_date: string`
|
|
669
|
+
*
|
|
670
|
+
* Deviations from the T-03 spec (documented per ticket §2 "CRITICAL: Check
|
|
671
|
+
* the actual ModelV2 type and adapt if field names differ"):
|
|
672
|
+
* 1. Spec's flat `tool_call` / `reasoning` / `attachment` / `modalities`
|
|
673
|
+
* top-level fields don't exist in ModelV2 — folded into
|
|
674
|
+
* `capabilities.{toolcall, reasoning, attachment, input.*, output.*}`.
|
|
675
|
+
* 2. `cost: undefined` is illegal (cost is required). OmniRoute doesn't
|
|
676
|
+
* surface pricing on /v1/models, so we emit a zeroed cost block.
|
|
677
|
+
* Downstream OC reads this for display only — the live pricing is
|
|
678
|
+
* OmniRoute's responsibility at routing time.
|
|
679
|
+
* 3. `tool_call` (spec) → `toolcall` (ModelV2 field name; one word).
|
|
680
|
+
* 4. `attachment` (spec) maps from `capabilities.vision` per OmniRoute
|
|
681
|
+
* convention: vision = ability to receive image attachments. If the
|
|
682
|
+
* raw entry happens to expose an explicit `capabilities.attachment`
|
|
683
|
+
* (some combo entries do), that wins.
|
|
684
|
+
* 5. `thinking` from OmniRoute has no 1:1 ModelV2 slot. We OR it into
|
|
685
|
+
* `reasoning` so thinking-only models still surface a non-false
|
|
686
|
+
* reasoning flag.
|
|
687
|
+
* 6. `last_updated` from OmniRoute has no ModelV2 slot — dropped (the
|
|
688
|
+
* spec also flagged this as "may not exist", and the prod sample
|
|
689
|
+
* confirms it's optional). `release_date` lands in ModelV2.release_date
|
|
690
|
+
* with `""` fallback (the field is required as `string`).
|
|
691
|
+
* 7. `temperature: true` per OmniRoute convention (OpenAI-compat mode
|
|
692
|
+
* always supports the temperature knob). If a raw entry sets
|
|
693
|
+
* `capabilities.temperature` explicitly, that wins.
|
|
694
|
+
* 8. Input/output modality arrays: each known modality flips its boolean.
|
|
695
|
+
* Unknown strings (future OmniRoute additions) are ignored — when the
|
|
696
|
+
* server adds new modalities we can map them here without breaking
|
|
697
|
+
* existing entries.
|
|
698
|
+
* 9. `status: "active"` — OmniRoute doesn't tier models alpha/beta on
|
|
699
|
+
* /v1/models, and OC needs a non-deprecated status to expose the
|
|
700
|
+
* model in the picker. If a future entry surfaces an explicit
|
|
701
|
+
* lifecycle hint we can map it then.
|
|
702
|
+
* 10. `options: {}` and `headers: {}` left empty — they're escape hatches
|
|
703
|
+
* for OC users to attach per-model overrides; the provider plugin
|
|
704
|
+
* must not preempt them.
|
|
705
|
+
* 11. `limit.input` is OPTIONAL on ModelV2 (the `?` modifier). We only
|
|
706
|
+
* emit it when OmniRoute supplies `max_input_tokens` — keeps the
|
|
707
|
+
* shape clean for combo entries that only carry context_length.
|
|
708
|
+
*/
|
|
709
|
+
|
|
710
|
+
export function mapRawModelToModelV2(
|
|
711
|
+
raw: OmniRouteRawModelEntry,
|
|
712
|
+
ctx: { providerId: string; baseURL: string; apiFormat?: { anthropicPrefixes?: string[] } }
|
|
713
|
+
): ModelV2 {
|
|
714
|
+
const caps = raw.capabilities ?? {};
|
|
715
|
+
const inMods = new Set(raw.input_modalities ?? ["text"]);
|
|
716
|
+
const outMods = new Set(raw.output_modalities ?? ["text"]);
|
|
717
|
+
|
|
718
|
+
return {
|
|
719
|
+
// OC's static-catalog reader parses the key on `/` to recover
|
|
720
|
+
// `(providerID, modelID)`. If the raw id is already provider-prefixed
|
|
721
|
+
// (e.g. `cc/claude-opus-4-7` from the `cc` Claude Code alias, or
|
|
722
|
+
// `nvidia/llama-3-70b` from a provider that ships prefixed ids), leave
|
|
723
|
+
// it as-is — double-prefixing breaks OC's lookup. Otherwise prefix with
|
|
724
|
+
// the resolved `providerId` so a bare key like `claude-opus-4` parses as
|
|
725
|
+
// `(omniroute, claude-opus-4)` and the credentials resolve correctly.
|
|
726
|
+
id: raw.id.includes("/") ? raw.id : `${ctx.providerId}/${raw.id}`,
|
|
727
|
+
/**
|
|
728
|
+
* Display name. Falls back to raw.id when no enrichment is available;
|
|
729
|
+
* the caller (`createOmniRouteProviderHook`) overlays
|
|
730
|
+
* `/api/pricing/models` data via `applyEnrichment` when
|
|
731
|
+
* `features.enrichment` is true.
|
|
732
|
+
*/
|
|
733
|
+
name: _normaliseFreeLabel(raw.id),
|
|
734
|
+
capabilities: {
|
|
735
|
+
temperature: caps.temperature ?? true,
|
|
736
|
+
reasoning: Boolean(caps.reasoning || caps.thinking),
|
|
737
|
+
attachment: Boolean(caps.attachment ?? caps.vision ?? false),
|
|
738
|
+
toolcall: Boolean(caps.tool_calling ?? false),
|
|
739
|
+
input: {
|
|
740
|
+
text: inMods.has("text"),
|
|
741
|
+
audio: inMods.has("audio"),
|
|
742
|
+
image: inMods.has("image"),
|
|
743
|
+
video: inMods.has("video"),
|
|
744
|
+
pdf: inMods.has("pdf"),
|
|
745
|
+
},
|
|
746
|
+
output: {
|
|
747
|
+
text: outMods.has("text"),
|
|
748
|
+
audio: outMods.has("audio"),
|
|
749
|
+
image: outMods.has("image"),
|
|
750
|
+
video: outMods.has("video"),
|
|
751
|
+
pdf: outMods.has("pdf"),
|
|
752
|
+
},
|
|
753
|
+
interleaved: Boolean(caps.thinking),
|
|
754
|
+
},
|
|
755
|
+
cost: {
|
|
756
|
+
input: 0,
|
|
757
|
+
output: 0,
|
|
758
|
+
cache: { read: 0, write: 0 },
|
|
759
|
+
},
|
|
760
|
+
limit: {
|
|
761
|
+
context: typeof raw.context_length === "number" ? raw.context_length : 0,
|
|
762
|
+
...(typeof raw.max_input_tokens === "number" ? { input: raw.max_input_tokens } : {}),
|
|
763
|
+
output: typeof raw.max_output_tokens === "number" ? raw.max_output_tokens : 0,
|
|
764
|
+
},
|
|
765
|
+
status: "active",
|
|
766
|
+
options: {},
|
|
767
|
+
headers: {},
|
|
768
|
+
release_date: raw.release_date ?? "",
|
|
769
|
+
providerID: ctx.providerId,
|
|
770
|
+
api: resolveApiBlock(raw.id, ctx.baseURL, ctx.apiFormat),
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
775
|
+
// Combo discovery (T-05) — /api/combos pass-through with LCD capability roll-up
|
|
776
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
777
|
+
|
|
778
|
+
/**
|
|
779
|
+
* Raw shape of a single combo entry as returned by OmniRoute's `/api/combos`.
|
|
780
|
+
*
|
|
781
|
+
* Schema established via a live probe against
|
|
782
|
+
* an OmniRoute `/api/combos` endpoint with a management-scoped key
|
|
783
|
+
* (response saved at /tmp/t05-combos.json) cross-referenced against the
|
|
784
|
+
* source-of-truth in this repo:
|
|
785
|
+
*
|
|
786
|
+
* - `src/app/api/combos/route.ts` GET handler — emits `{combos: [...]}`
|
|
787
|
+
* envelope after `getCombos()`.
|
|
788
|
+
* - `src/lib/db/combos.ts` `getCombos()` — returns rows persisted via
|
|
789
|
+
* `createCombo` / `updateCombo`, each shaped by `normalizeStoredCombo`.
|
|
790
|
+
* - `src/lib/combos/steps.ts` `ComboModelStep` + `ComboRefStep` — define
|
|
791
|
+
* the `models[]` array entry shape (a step references a member model
|
|
792
|
+
* by its full provider-prefixed id, e.g. `"claude-opus-4-5-thinking"`).
|
|
793
|
+
*
|
|
794
|
+
* Note: the preprod gateway returned `{combos: []}` at probe time (no combos
|
|
795
|
+
* provisioned). The defensive parser accepts both `{combos:[...]}` and a
|
|
796
|
+
* bare array envelope so the plugin keeps working if a future OmniRoute
|
|
797
|
+
* build trims the wrapper (mirrors the same pattern in the sibling
|
|
798
|
+
* `@omniroute/opencode-provider#listCombos`).
|
|
799
|
+
*
|
|
800
|
+
* STRICT source-of-truth (OQ-3, per T-03): every ModelV2 field a combo
|
|
801
|
+
* surfaces traces back to either (a) this raw combo entry or (b) the LCD
|
|
802
|
+
* roll-up across its raw member models. No client-side variant synthesis.
|
|
803
|
+
*/
|
|
804
|
+
export interface OmniRouteRawComboMemberRef {
|
|
805
|
+
/** Step kind: "model" references a raw model id; "combo-ref" nests another combo. */
|
|
806
|
+
kind?: "model" | "combo-ref";
|
|
807
|
+
/** Full model id referenced by this step (when kind === "model"). */
|
|
808
|
+
model?: string;
|
|
809
|
+
/** Nested combo name (when kind === "combo-ref"). */
|
|
810
|
+
comboName?: string;
|
|
811
|
+
/** Routing weight inside the combo (0–100, advisory at LCD time). */
|
|
812
|
+
weight?: number;
|
|
813
|
+
/** Step-local label, distinct from the parent combo's display name. */
|
|
814
|
+
label?: string;
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
export interface OmniRouteRawCombo {
|
|
818
|
+
id: string;
|
|
819
|
+
name?: string;
|
|
820
|
+
/** Routing strategy. Surfaced for forward-compat but not consumed by LCD. */
|
|
821
|
+
strategy?: string;
|
|
822
|
+
/** Member step list. Only `kind: "model"` steps participate in LCD. */
|
|
823
|
+
models?: OmniRouteRawComboMemberRef[];
|
|
824
|
+
/** Hidden combos are excluded from the OC model picker. */
|
|
825
|
+
isHidden?: boolean;
|
|
826
|
+
/** When OmniRoute attaches a lifecycle hint we forward it; today it doesn't. */
|
|
827
|
+
release_date?: string;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* Fetcher contract for `/api/combos`. Same DI shape as
|
|
832
|
+
* `OmniRouteModelsFetcher` so unit tests can inject a stub instead of
|
|
833
|
+
* monkey-patching global `fetch`.
|
|
834
|
+
*/
|
|
835
|
+
export type OmniRouteCombosFetcher = (
|
|
836
|
+
baseURL: string,
|
|
837
|
+
apiKey: string,
|
|
838
|
+
timeoutMs?: number
|
|
839
|
+
) => Promise<OmniRouteRawCombo[]>;
|
|
840
|
+
|
|
841
|
+
/**
|
|
842
|
+
* Default fetcher: `GET <baseURL>/api/combos` with bearer auth +
|
|
843
|
+
* AbortController timeout. Accepts both the `{combos: [...]}` envelope the
|
|
844
|
+
* gateway emits today and a bare-array envelope (defensive — keeps the
|
|
845
|
+
* plugin working if a future OmniRoute build trims the wrapper).
|
|
846
|
+
*
|
|
847
|
+
* Differences from `defaultOmniRouteModelsFetcher`:
|
|
848
|
+
* - URL is `/api/combos`, NOT `/v1/combos`. The `/v1/...` namespace is the
|
|
849
|
+
* OpenAI-compatible surface (chat completions, models); combo discovery
|
|
850
|
+
* lives on the management plane under `/api/...`. We tolerate both
|
|
851
|
+
* `https://host` and `https://host/v1` baseURL forms by stripping the
|
|
852
|
+
* trailing `/v1` segment before appending `/api/combos`.
|
|
853
|
+
* - Combos endpoint requires a management-scoped API key when
|
|
854
|
+
* `REQUIRE_API_KEY` is enabled. We don't enforce that here; the
|
|
855
|
+
* gateway returns 401/403 with an actionable error which we propagate.
|
|
856
|
+
*
|
|
857
|
+
* Anything that isn't an object with a string `id` is filtered out silently.
|
|
858
|
+
*/
|
|
859
|
+
export const defaultOmniRouteCombosFetcher: OmniRouteCombosFetcher = async (
|
|
860
|
+
baseURL,
|
|
861
|
+
apiKey,
|
|
862
|
+
timeoutMs = 10_000
|
|
863
|
+
) => {
|
|
864
|
+
if (!apiKey) throw new Error("@omniroute/opencode-plugin: apiKey required to fetch /api/combos");
|
|
865
|
+
if (!baseURL)
|
|
866
|
+
throw new Error("@omniroute/opencode-plugin: baseURL required to fetch /api/combos");
|
|
867
|
+
|
|
868
|
+
// Strip trailing slashes, then strip a trailing `/v1` so we land on the
|
|
869
|
+
// management plane. Models live under `/v1/models`; combos live under
|
|
870
|
+
// `/api/combos` from the same gateway root.
|
|
871
|
+
const trimmed = trimTrailingSlashes(baseURL);
|
|
872
|
+
const root = trimmed.replace(/\/v\d+$/, "");
|
|
873
|
+
const url = `${root}/api/combos`;
|
|
874
|
+
|
|
875
|
+
const controller = new AbortController();
|
|
876
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
877
|
+
try {
|
|
878
|
+
const res = await fetch(url, {
|
|
879
|
+
method: "GET",
|
|
880
|
+
headers: {
|
|
881
|
+
Authorization: `Bearer ${apiKey}`,
|
|
882
|
+
Accept: "application/json",
|
|
883
|
+
},
|
|
884
|
+
signal: controller.signal,
|
|
885
|
+
});
|
|
886
|
+
if (!res.ok) {
|
|
887
|
+
throw new Error(
|
|
888
|
+
`@omniroute/opencode-plugin: GET ${url} failed: ${res.status} ${res.statusText}`
|
|
889
|
+
);
|
|
890
|
+
}
|
|
891
|
+
const body = (await res.json()) as unknown;
|
|
892
|
+
const rawList: unknown[] = Array.isArray(body)
|
|
893
|
+
? body
|
|
894
|
+
: body && typeof body === "object" && Array.isArray((body as { combos?: unknown }).combos)
|
|
895
|
+
? ((body as { combos: unknown[] }).combos as unknown[])
|
|
896
|
+
: [];
|
|
897
|
+
const out: OmniRouteRawCombo[] = [];
|
|
898
|
+
for (const r of rawList) {
|
|
899
|
+
if (r && typeof r === "object" && typeof (r as { id?: unknown }).id === "string") {
|
|
900
|
+
out.push(r as OmniRouteRawCombo);
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
return out;
|
|
904
|
+
} finally {
|
|
905
|
+
clearTimeout(timer);
|
|
906
|
+
}
|
|
907
|
+
};
|
|
908
|
+
|
|
909
|
+
/**
|
|
910
|
+
* Map a raw combo entry → `ModelV2` by computing the lowest-common-denominator
|
|
911
|
+
* (LCD) of its underlying member models. The LCD policy is the only way to
|
|
912
|
+
* surface a single capability vector to OpenCode without lying: if any member
|
|
913
|
+
* lacks a capability, the combo as a whole cannot guarantee it.
|
|
914
|
+
*
|
|
915
|
+
* LCD rules:
|
|
916
|
+
* - `limit.context` = `min(...members.context_length)`.
|
|
917
|
+
* - `limit.output` = `min(...members.max_output_tokens)`.
|
|
918
|
+
* - `limit.input` = `min(...members.max_input_tokens)` ONLY when every
|
|
919
|
+
* member declares one (ModelV2.limit.input is optional — better to
|
|
920
|
+
* omit than to fabricate a min over partial data).
|
|
921
|
+
* - `capabilities.toolcall` / `reasoning` / `attachment` / `temperature`:
|
|
922
|
+
* `every(member ⇒ supports?)`. The `reasoning` axis ORs across
|
|
923
|
+
* `reasoning` and `thinking` per member before AND-ing across the
|
|
924
|
+
* combo (mirrors `mapRawModelToModelV2`). The `attachment` axis ORs
|
|
925
|
+
* across `attachment` and `vision` per member. The `temperature` axis
|
|
926
|
+
* uses default-true semantics: a member supports temperature unless
|
|
927
|
+
* it explicitly declares `temperature: false`.
|
|
928
|
+
* - `capabilities.input.*` / `output.*`: flattened AND across members'
|
|
929
|
+
* modality flags. Missing arrays default to `["text"]` (same default
|
|
930
|
+
* as `mapRawModelToModelV2`).
|
|
931
|
+
*
|
|
932
|
+
* Defensive: empty members array → ALL capabilities `false`, limits zero.
|
|
933
|
+
* That's an intentional safety posture (you can't route through an empty
|
|
934
|
+
* combo, so OC should grey it out in the picker).
|
|
935
|
+
*
|
|
936
|
+
* Spec mapping (T-05 §Scope.3): `cost` zeroed; `status = "active"`;
|
|
937
|
+
* `release_date = combo.release_date ?? ""`; `api.id = "openai-compatible"`;
|
|
938
|
+
* `name = combo.name ?? combo.id`.
|
|
939
|
+
*
|
|
940
|
+
* @param combo Raw `/api/combos` entry.
|
|
941
|
+
* @param members Raw `/v1/models` entries for THIS combo's member ids.
|
|
942
|
+
* Caller resolves `combo.models[].model` ids; unknown ids
|
|
943
|
+
* are silently dropped before this call.
|
|
944
|
+
* @param providerId OpenCode provider id (multi-instance aware).
|
|
945
|
+
* @param baseURL Resolved gateway base URL for ModelV2.api.url.
|
|
946
|
+
*/
|
|
947
|
+
export function mapComboToModelV2(
|
|
948
|
+
combo: OmniRouteRawCombo,
|
|
949
|
+
members: OmniRouteRawModelEntry[],
|
|
950
|
+
providerId: string,
|
|
951
|
+
baseURL: string,
|
|
952
|
+
apiFormat?: { anthropicPrefixes?: string[] }
|
|
953
|
+
): ModelV2 {
|
|
954
|
+
// `every` over an empty array returns true (would lie about an empty
|
|
955
|
+
// combo's capabilities) — short-circuit to all-false when no members.
|
|
956
|
+
const hasMembers = members.length > 0;
|
|
957
|
+
|
|
958
|
+
const memberInMods = members.map((m) => new Set(m.input_modalities ?? ["text"]));
|
|
959
|
+
const memberOutMods = members.map((m) => new Set(m.output_modalities ?? ["text"]));
|
|
960
|
+
|
|
961
|
+
const modalityAllHave = (sets: Array<Set<string>>, key: string): boolean =>
|
|
962
|
+
hasMembers && sets.every((s) => s.has(key));
|
|
963
|
+
|
|
964
|
+
const contextValues = members
|
|
965
|
+
.map((m) => m.context_length)
|
|
966
|
+
.filter((v): v is number => typeof v === "number" && v > 0);
|
|
967
|
+
const outputValues = members
|
|
968
|
+
.map((m) => m.max_output_tokens)
|
|
969
|
+
.filter((v): v is number => typeof v === "number" && v > 0);
|
|
970
|
+
const inputValues = members
|
|
971
|
+
.map((m) => m.max_input_tokens)
|
|
972
|
+
.filter((v): v is number => typeof v === "number" && v > 0);
|
|
973
|
+
|
|
974
|
+
const everyDeclaresInput = hasMembers && inputValues.length === members.length;
|
|
975
|
+
|
|
976
|
+
const capabilities: ModelV2["capabilities"] = {
|
|
977
|
+
temperature:
|
|
978
|
+
hasMembers && members.every((m) => (m.capabilities?.temperature ?? true) !== false),
|
|
979
|
+
reasoning:
|
|
980
|
+
hasMembers &&
|
|
981
|
+
members.every((m) => Boolean(m.capabilities?.reasoning || m.capabilities?.thinking)),
|
|
982
|
+
attachment:
|
|
983
|
+
hasMembers &&
|
|
984
|
+
members.every((m) => Boolean(m.capabilities?.attachment ?? m.capabilities?.vision ?? false)),
|
|
985
|
+
toolcall: hasMembers && members.every((m) => Boolean(m.capabilities?.tool_calling ?? false)),
|
|
986
|
+
input: {
|
|
987
|
+
text: modalityAllHave(memberInMods, "text"),
|
|
988
|
+
audio: modalityAllHave(memberInMods, "audio"),
|
|
989
|
+
image: modalityAllHave(memberInMods, "image"),
|
|
990
|
+
video: modalityAllHave(memberInMods, "video"),
|
|
991
|
+
pdf: modalityAllHave(memberInMods, "pdf"),
|
|
992
|
+
},
|
|
993
|
+
output: {
|
|
994
|
+
text: modalityAllHave(memberOutMods, "text"),
|
|
995
|
+
audio: modalityAllHave(memberOutMods, "audio"),
|
|
996
|
+
image: modalityAllHave(memberOutMods, "image"),
|
|
997
|
+
video: modalityAllHave(memberOutMods, "video"),
|
|
998
|
+
pdf: modalityAllHave(memberOutMods, "pdf"),
|
|
999
|
+
},
|
|
1000
|
+
interleaved: hasMembers && members.every((m) => Boolean(m.capabilities?.thinking)),
|
|
1001
|
+
};
|
|
1002
|
+
|
|
1003
|
+
// Combos span multiple providers. Use Anthropic format only when ALL
|
|
1004
|
+
// members resolve to Anthropic — otherwise fall back to OpenAI-compat
|
|
1005
|
+
// (lowest common denominator that every upstream understands).
|
|
1006
|
+
const comboApiBlock = (() => {
|
|
1007
|
+
if (!hasMembers) return resolveApiBlock("", baseURL, apiFormat);
|
|
1008
|
+
const allAnthropic = members.every(
|
|
1009
|
+
(m) => resolveApiBlock(m.id, baseURL, apiFormat).id === "anthropic"
|
|
1010
|
+
);
|
|
1011
|
+
return allAnthropic
|
|
1012
|
+
? resolveApiBlock(members[0].id, baseURL, apiFormat)
|
|
1013
|
+
: {
|
|
1014
|
+
id: "openai-compatible",
|
|
1015
|
+
url: ensureV1Suffix(baseURL),
|
|
1016
|
+
npm: "@ai-sdk/openai-compatible",
|
|
1017
|
+
};
|
|
1018
|
+
})();
|
|
1019
|
+
|
|
1020
|
+
return {
|
|
1021
|
+
id: combo.id,
|
|
1022
|
+
providerID: providerId,
|
|
1023
|
+
api: comboApiBlock,
|
|
1024
|
+
name: combo.name && combo.name.trim().length > 0 ? combo.name : combo.id,
|
|
1025
|
+
capabilities,
|
|
1026
|
+
cost: {
|
|
1027
|
+
input: 0,
|
|
1028
|
+
output: 0,
|
|
1029
|
+
cache: { read: 0, write: 0 },
|
|
1030
|
+
},
|
|
1031
|
+
limit: {
|
|
1032
|
+
context: contextValues.length > 0 ? Math.min(...contextValues) : 0,
|
|
1033
|
+
...(everyDeclaresInput ? { input: Math.min(...inputValues) } : {}),
|
|
1034
|
+
output: outputValues.length > 0 ? Math.min(...outputValues) : 0,
|
|
1035
|
+
},
|
|
1036
|
+
status: "active",
|
|
1037
|
+
options: {},
|
|
1038
|
+
headers: {},
|
|
1039
|
+
release_date: combo.release_date ?? "",
|
|
1040
|
+
};
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
1044
|
+
// AUTO COMBOS — virtual server-side combos exposed via /api/combos/auto
|
|
1045
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
1046
|
+
|
|
1047
|
+
/**
|
|
1048
|
+
* Raw shape of an auto combo entry as returned by OmniRoute's
|
|
1049
|
+
* `/api/combos/auto` endpoint. Auto combos are virtual — they self-manage
|
|
1050
|
+
* provider selection via scoring/bandit exploration at runtime.
|
|
1051
|
+
*/
|
|
1052
|
+
export interface OmniRouteRawAutoCombo {
|
|
1053
|
+
/** Stable id (e.g. "auto", "auto/coding"). */
|
|
1054
|
+
id: string;
|
|
1055
|
+
/** Human-readable name (e.g. "Auto", "Auto Coding"). */
|
|
1056
|
+
name: string;
|
|
1057
|
+
/** Variant key or undefined for the default auto. */
|
|
1058
|
+
variant?: AutoVariant;
|
|
1059
|
+
/** Provider names eligible for this auto combo. */
|
|
1060
|
+
candidatePool?: string[];
|
|
1061
|
+
/** Number of candidates resolved at fetch time. */
|
|
1062
|
+
candidateCount?: number;
|
|
1063
|
+
/** MAX of candidates' context windows, served by newer OmniRoute builds.
|
|
1064
|
+
* Absent on older servers — mapper falls back to a safe positive default. */
|
|
1065
|
+
context_length?: number;
|
|
1066
|
+
/** MAX of candidates' max output tokens (same provenance as context_length). */
|
|
1067
|
+
max_output_tokens?: number;
|
|
1068
|
+
/** Whether this auto combo should be hidden from the picker. */
|
|
1069
|
+
isHidden?: boolean;
|
|
1070
|
+
/** Auto-combo configuration. */
|
|
1071
|
+
config?: {
|
|
1072
|
+
auto?: {
|
|
1073
|
+
candidatePool?: string[];
|
|
1074
|
+
explorationRate?: number;
|
|
1075
|
+
routerStrategy?: string;
|
|
1076
|
+
};
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
/**
|
|
1081
|
+
* Fetcher contract for `/api/combos/auto`. Returns the list of virtual
|
|
1082
|
+
* auto combos the server can create. Same DI pattern as other fetchers.
|
|
1083
|
+
*/
|
|
1084
|
+
export type OmniRouteAutoCombosFetcher = (
|
|
1085
|
+
baseURL: string,
|
|
1086
|
+
apiKey: string,
|
|
1087
|
+
timeoutMs?: number
|
|
1088
|
+
) => Promise<OmniRouteRawAutoCombo[]>;
|
|
1089
|
+
|
|
1090
|
+
/**
|
|
1091
|
+
* Default auto combos fetcher: `GET <baseURL>/api/combos/auto`.
|
|
1092
|
+
*
|
|
1093
|
+
* Fault-tolerant: returns empty array on 404 (endpoint doesn't exist yet)
|
|
1094
|
+
* or any non-2xx / network error. Logs a warning in those cases.
|
|
1095
|
+
*/
|
|
1096
|
+
export const defaultOmniRouteAutoCombosFetcher: OmniRouteAutoCombosFetcher = async (
|
|
1097
|
+
baseURL,
|
|
1098
|
+
apiKey,
|
|
1099
|
+
timeoutMs = 5_000
|
|
1100
|
+
) => {
|
|
1101
|
+
if (!apiKey || !baseURL) return [];
|
|
1102
|
+
|
|
1103
|
+
const trimmed = trimTrailingSlashes(baseURL);
|
|
1104
|
+
const root = trimmed.replace(/\/v\d+$/, "");
|
|
1105
|
+
const url = `${root}/api/combos/auto`;
|
|
1106
|
+
|
|
1107
|
+
const controller = new AbortController();
|
|
1108
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
1109
|
+
try {
|
|
1110
|
+
const res = await fetch(url, {
|
|
1111
|
+
method: "GET",
|
|
1112
|
+
headers: {
|
|
1113
|
+
Authorization: `Bearer ${apiKey}`,
|
|
1114
|
+
Accept: "application/json",
|
|
1115
|
+
},
|
|
1116
|
+
signal: controller.signal,
|
|
1117
|
+
});
|
|
1118
|
+
// 404 = endpoint not deployed yet — expected during rollout
|
|
1119
|
+
if (res.status === 404) {
|
|
1120
|
+
console.warn(
|
|
1121
|
+
`[omniroute-plugin] /api/combos/auto not available (404) — auto combos disabled`
|
|
1122
|
+
);
|
|
1123
|
+
return [];
|
|
1124
|
+
}
|
|
1125
|
+
if (!res.ok) {
|
|
1126
|
+
console.warn(
|
|
1127
|
+
`[omniroute-plugin] /api/combos/auto failed: ${res.status} ${res.statusText} — auto combos disabled`
|
|
1128
|
+
);
|
|
1129
|
+
return [];
|
|
1130
|
+
}
|
|
1131
|
+
const body = (await res.json()) as unknown;
|
|
1132
|
+
const rawList: unknown[] = Array.isArray(body)
|
|
1133
|
+
? body
|
|
1134
|
+
: body && typeof body === "object" && Array.isArray((body as { combos?: unknown }).combos)
|
|
1135
|
+
? ((body as { combos: unknown[] }).combos as unknown[])
|
|
1136
|
+
: [];
|
|
1137
|
+
const out: OmniRouteRawAutoCombo[] = [];
|
|
1138
|
+
for (const r of rawList) {
|
|
1139
|
+
if (r && typeof r === "object" && typeof (r as { id?: unknown }).id === "string") {
|
|
1140
|
+
out.push(r as OmniRouteRawAutoCombo);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
return out;
|
|
1144
|
+
} catch (err) {
|
|
1145
|
+
// Network error, timeout, abort — all non-fatal
|
|
1146
|
+
console.warn(
|
|
1147
|
+
`[omniroute-plugin] /api/combos/auto fetch failed: ${err instanceof Error ? err.message : String(err)} — auto combos disabled`
|
|
1148
|
+
);
|
|
1149
|
+
return [];
|
|
1150
|
+
} finally {
|
|
1151
|
+
clearTimeout(timer);
|
|
1152
|
+
}
|
|
1153
|
+
};
|
|
1154
|
+
|
|
1155
|
+
/** Fallbacks when the server does not advertise auto-combo limits (older
|
|
1156
|
+
* OmniRoute builds). MUST be positive: OpenCode's overflow guard treats
|
|
1157
|
+
* `limit.context === 0` as "never overflow" and silently DISABLES smart
|
|
1158
|
+
* auto-compaction, letting the session grow until the gateway's destructive
|
|
1159
|
+
* history purge kicks in (the "agent keeps forgetting things" bug). */
|
|
1160
|
+
const AUTO_COMBO_FALLBACK_CONTEXT = 128_000;
|
|
1161
|
+
const AUTO_COMBO_FALLBACK_OUTPUT = 8_192;
|
|
1162
|
+
|
|
1163
|
+
/**
|
|
1164
|
+
* Convert a raw auto combo into a static model entry for the OpenCode picker.
|
|
1165
|
+
* Auto combos have tool_call=true, reasoning=true by default (they route
|
|
1166
|
+
* to capable models). Context/output limits come from the server (MAX of
|
|
1167
|
+
* the candidate pool's windows — the gateway's context pre-filter routes
|
|
1168
|
+
* oversized requests to large-window candidates); a safe positive fallback
|
|
1169
|
+
* applies when the server omits them. Never 0.
|
|
1170
|
+
*/
|
|
1171
|
+
export function mapAutoComboToStaticEntry(
|
|
1172
|
+
autoCombo: OmniRouteRawAutoCombo
|
|
1173
|
+
): OmniRouteStaticModelEntry {
|
|
1174
|
+
const variant = autoCombo.variant;
|
|
1175
|
+
const name = formatAutoComboName(variant, autoCombo.candidateCount);
|
|
1176
|
+
const context =
|
|
1177
|
+
typeof autoCombo.context_length === "number" && autoCombo.context_length > 0
|
|
1178
|
+
? autoCombo.context_length
|
|
1179
|
+
: AUTO_COMBO_FALLBACK_CONTEXT;
|
|
1180
|
+
const output =
|
|
1181
|
+
typeof autoCombo.max_output_tokens === "number" && autoCombo.max_output_tokens > 0
|
|
1182
|
+
? autoCombo.max_output_tokens
|
|
1183
|
+
: AUTO_COMBO_FALLBACK_OUTPUT;
|
|
1184
|
+
// No `providerID` field on static-catalog entries — OC ignores it on the static
|
|
1185
|
+
// path, and stamping it on auto-combos but not on raw/combo entries was an
|
|
1186
|
+
// internal inconsistency. The dynamic-hook path builds its ModelV2 from the
|
|
1187
|
+
// individual fields below and never read this field either.
|
|
1188
|
+
return {
|
|
1189
|
+
name,
|
|
1190
|
+
attachment: false,
|
|
1191
|
+
reasoning: true,
|
|
1192
|
+
temperature: true,
|
|
1193
|
+
tool_call: true,
|
|
1194
|
+
limit: { context, output },
|
|
1195
|
+
modalities: {
|
|
1196
|
+
input: ["text"],
|
|
1197
|
+
output: ["text"],
|
|
1198
|
+
},
|
|
1199
|
+
cost: { input: 0, output: 0, cache_read: 0, cache_write: 0 },
|
|
1200
|
+
};
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
1204
|
+
// ENRICHMENT — pull display names + pricing from /api/pricing/models so
|
|
1205
|
+
// the UI doesn't have to render raw model ids. Gated by features.enrichment.
|
|
1206
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
1207
|
+
|
|
1208
|
+
/**
|
|
1209
|
+
* Per-model enrichment overlay derived from OmniRoute's
|
|
1210
|
+
* `/api/pricing/models` endpoint. The endpoint returns a per-provider
|
|
1211
|
+
* catalog with curated `name` strings (e.g. `Claude 4.7 Opus`,
|
|
1212
|
+
* `GPT 5.5 Pro`, `Gemini 3.1 Pro`) and per-million-token pricing
|
|
1213
|
+
* (`pricing.input`, `pricing.output`, `pricing.cacheRead`,
|
|
1214
|
+
* `pricing.cacheWrite`). These overlay the ModelV2 entries produced by
|
|
1215
|
+
* `mapRawModelToModelV2`.
|
|
1216
|
+
*/
|
|
1217
|
+
export interface OmniRouteEnrichmentEntry {
|
|
1218
|
+
/** Human-readable display name. Replaces ModelV2.name when present. */
|
|
1219
|
+
name?: string;
|
|
1220
|
+
/** Per-million-token cost overlay onto ModelV2.cost. */
|
|
1221
|
+
pricing?: {
|
|
1222
|
+
input?: number;
|
|
1223
|
+
output?: number;
|
|
1224
|
+
cacheRead?: number;
|
|
1225
|
+
cacheWrite?: number;
|
|
1226
|
+
};
|
|
1227
|
+
/**
|
|
1228
|
+
* Provider alias prefix seen in `/v1/models` ids (e.g. `cc`, `gemini`).
|
|
1229
|
+
* Populated by `defaultOmniRouteEnrichmentFetcher` from
|
|
1230
|
+
* `/api/pricing/models` keys. Drives the `usableOnly` alias↔canonical
|
|
1231
|
+
* resolution.
|
|
1232
|
+
*/
|
|
1233
|
+
providerAlias?: string;
|
|
1234
|
+
/**
|
|
1235
|
+
* Canonical provider id used by `/api/providers` connections (e.g.
|
|
1236
|
+
* `claude`, `gemini`, `kiro`). Populated from the per-provider
|
|
1237
|
+
* `entry.id` field inside `/api/pricing/models`.
|
|
1238
|
+
*/
|
|
1239
|
+
providerCanonical?: string;
|
|
1240
|
+
/**
|
|
1241
|
+
* Human-readable upstream provider label (e.g. `Claude`, `Kiro`,
|
|
1242
|
+
* `Windsurf`, `GitHub Models`). Populated from the per-provider
|
|
1243
|
+
* `entry.name` field inside `/api/pricing/models`. Used by the
|
|
1244
|
+
* `providerTag` feature to suffix `ModelV2.name` with the routing
|
|
1245
|
+
* destination so the OC TUI picker can differentiate the same
|
|
1246
|
+
* model id sold through different upstream connections.
|
|
1247
|
+
*/
|
|
1248
|
+
providerDisplayName?: string;
|
|
1249
|
+
/** Free-model budget type (from freeModelCatalog). */
|
|
1250
|
+
freeType?: FreeModelFreeType;
|
|
1251
|
+
/** Monthly token budget for recurring free models. */
|
|
1252
|
+
monthlyTokens?: number;
|
|
1253
|
+
/** Credit token budget for credit-based free models. */
|
|
1254
|
+
creditTokens?: number;
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
/** Map keyed by full model id (possibly namespaced, e.g. `cc/claude-sonnet-4-6`). */
|
|
1258
|
+
export type OmniRouteEnrichmentMap = Map<string, OmniRouteEnrichmentEntry>;
|
|
1259
|
+
|
|
1260
|
+
export type OmniRouteEnrichmentFetcher = (
|
|
1261
|
+
baseURL: string,
|
|
1262
|
+
apiKey: string,
|
|
1263
|
+
timeoutMs?: number
|
|
1264
|
+
) => Promise<OmniRouteEnrichmentMap>;
|
|
1265
|
+
|
|
1266
|
+
/**
|
|
1267
|
+
* Default enrichment fetcher — pulls nice display names from
|
|
1268
|
+
* `GET /api/pricing/models` and merges per-million-token pricing from
|
|
1269
|
+
* `GET /api/pricing` (the actual pricing source — `/api/pricing/models` is
|
|
1270
|
+
* a catalog endpoint whose entries are `{id, name, custom}` only).
|
|
1271
|
+
*
|
|
1272
|
+
* `/api/pricing/models` shape (catalog):
|
|
1273
|
+
* - `{ [providerAlias]: { id, alias, name, models: [{ id, name, custom }] } }`
|
|
1274
|
+
*
|
|
1275
|
+
* `/api/pricing` shape (pricing only):
|
|
1276
|
+
* - `{ [providerAlias]: { [modelId]: { input, output, cached, reasoning, cache_creation } } }`
|
|
1277
|
+
* where values are USD per million tokens.
|
|
1278
|
+
*
|
|
1279
|
+
* The two responses are joined on `(providerAlias, modelId)` and the merged
|
|
1280
|
+
* entries are stored under both `${providerAlias}/${modelId}` and bare
|
|
1281
|
+
* `${modelId}` keys so downstream lookups against either form succeed.
|
|
1282
|
+
*
|
|
1283
|
+
* Soft-fails (returns whatever was collected) on non-2xx or parse errors;
|
|
1284
|
+
* the two fetches are independent so one missing source still surfaces the
|
|
1285
|
+
* other.
|
|
1286
|
+
*/
|
|
1287
|
+
export const defaultOmniRouteEnrichmentFetcher: OmniRouteEnrichmentFetcher = async (
|
|
1288
|
+
baseURL,
|
|
1289
|
+
apiKey,
|
|
1290
|
+
timeoutMs = 10_000
|
|
1291
|
+
) => {
|
|
1292
|
+
const out: OmniRouteEnrichmentMap = new Map();
|
|
1293
|
+
if (!baseURL || !apiKey) return out;
|
|
1294
|
+
const root = baseURL.replace(/\/v1\/?$/, "").replace(/\/$/, "");
|
|
1295
|
+
const headers = {
|
|
1296
|
+
Authorization: `Bearer ${apiKey}`,
|
|
1297
|
+
Accept: "application/json",
|
|
1298
|
+
};
|
|
1299
|
+
|
|
1300
|
+
// ── 1. Catalog with nice display names ────────────────────────────────
|
|
1301
|
+
const catalogAc = new AbortController();
|
|
1302
|
+
const catalogTimer = setTimeout(() => catalogAc.abort(), timeoutMs);
|
|
1303
|
+
try {
|
|
1304
|
+
const res = await fetch(`${root}/api/pricing/models`, {
|
|
1305
|
+
method: "GET",
|
|
1306
|
+
headers,
|
|
1307
|
+
signal: catalogAc.signal,
|
|
1308
|
+
});
|
|
1309
|
+
if (res.ok) {
|
|
1310
|
+
const body = (await res.json()) as unknown;
|
|
1311
|
+
const providers =
|
|
1312
|
+
(body as { providers?: Record<string, { models?: unknown[] }> })?.providers ??
|
|
1313
|
+
(body as Record<string, { models?: unknown[] }>);
|
|
1314
|
+
if (providers && typeof providers === "object") {
|
|
1315
|
+
for (const [providerAlias, slot] of Object.entries(providers)) {
|
|
1316
|
+
if (!slot || typeof slot !== "object") continue;
|
|
1317
|
+
const models = (slot as { models?: unknown[] }).models;
|
|
1318
|
+
if (!Array.isArray(models)) continue;
|
|
1319
|
+
// Canonical id sits at the per-provider top level (e.g.
|
|
1320
|
+
// `pricing-models.cc.id === 'claude'`). Falls back to the alias
|
|
1321
|
+
// itself when missing — common case alias===canonical.
|
|
1322
|
+
const canonicalRaw = (slot as { id?: unknown }).id;
|
|
1323
|
+
const providerCanonical =
|
|
1324
|
+
typeof canonicalRaw === "string" && canonicalRaw.length > 0
|
|
1325
|
+
? canonicalRaw
|
|
1326
|
+
: providerAlias;
|
|
1327
|
+
// Upstream provider human label (e.g. `Claude`, `Kiro`,
|
|
1328
|
+
// `GitHub Models`). Optional — falls back to undefined when
|
|
1329
|
+
// OmniRoute hasn't curated a label for this slot.
|
|
1330
|
+
const slotNameRaw = (slot as { name?: unknown }).name;
|
|
1331
|
+
const providerDisplayName =
|
|
1332
|
+
typeof slotNameRaw === "string" && slotNameRaw.trim().length > 0
|
|
1333
|
+
? slotNameRaw.trim()
|
|
1334
|
+
: undefined;
|
|
1335
|
+
for (const m of models) {
|
|
1336
|
+
if (!m || typeof m !== "object") continue;
|
|
1337
|
+
const id = (m as { id?: unknown }).id;
|
|
1338
|
+
if (typeof id !== "string" || id.length === 0) continue;
|
|
1339
|
+
const name = (m as { name?: unknown }).name;
|
|
1340
|
+
const entry: OmniRouteEnrichmentEntry = {
|
|
1341
|
+
providerAlias,
|
|
1342
|
+
providerCanonical,
|
|
1343
|
+
};
|
|
1344
|
+
if (providerDisplayName) entry.providerDisplayName = providerDisplayName;
|
|
1345
|
+
if (typeof name === "string" && name.trim().length > 0) entry.name = name;
|
|
1346
|
+
const namespaced = `${providerAlias}/${id}`;
|
|
1347
|
+
if (!out.has(namespaced)) out.set(namespaced, entry);
|
|
1348
|
+
if (!out.has(id)) out.set(id, entry);
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
} catch {
|
|
1354
|
+
// Soft-fail; keep going to pricing fetch.
|
|
1355
|
+
} finally {
|
|
1356
|
+
clearTimeout(catalogTimer);
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
// ── 2. Pricing values from /api/pricing ───────────────────────────────
|
|
1360
|
+
const priceAc = new AbortController();
|
|
1361
|
+
const priceTimer = setTimeout(() => priceAc.abort(), timeoutMs);
|
|
1362
|
+
try {
|
|
1363
|
+
const res = await fetch(`${root}/api/pricing`, {
|
|
1364
|
+
method: "GET",
|
|
1365
|
+
headers,
|
|
1366
|
+
signal: priceAc.signal,
|
|
1367
|
+
});
|
|
1368
|
+
if (res.ok) {
|
|
1369
|
+
const body = (await res.json()) as unknown;
|
|
1370
|
+
if (body && typeof body === "object" && !Array.isArray(body)) {
|
|
1371
|
+
for (const [providerAlias, slot] of Object.entries(body as Record<string, unknown>)) {
|
|
1372
|
+
if (!slot || typeof slot !== "object" || Array.isArray(slot)) continue;
|
|
1373
|
+
for (const [modelId, raw] of Object.entries(slot as Record<string, unknown>)) {
|
|
1374
|
+
if (!raw || typeof raw !== "object") continue;
|
|
1375
|
+
const p = raw as Record<string, unknown>;
|
|
1376
|
+
const parsed: NonNullable<OmniRouteEnrichmentEntry["pricing"]> = {};
|
|
1377
|
+
// OmniRoute `/api/pricing` keys:
|
|
1378
|
+
// input → cost.input
|
|
1379
|
+
// output → cost.output
|
|
1380
|
+
// cached → cost.cache.read (alias: cacheRead)
|
|
1381
|
+
// cache_creation → cost.cache.write (alias: cacheWrite)
|
|
1382
|
+
// Tolerate alternative spellings for forward-compat.
|
|
1383
|
+
if (typeof p.input === "number") parsed.input = p.input;
|
|
1384
|
+
if (typeof p.output === "number") parsed.output = p.output;
|
|
1385
|
+
const cacheRead =
|
|
1386
|
+
typeof p.cached === "number"
|
|
1387
|
+
? p.cached
|
|
1388
|
+
: typeof p.cacheRead === "number"
|
|
1389
|
+
? p.cacheRead
|
|
1390
|
+
: undefined;
|
|
1391
|
+
if (typeof cacheRead === "number") parsed.cacheRead = cacheRead;
|
|
1392
|
+
const cacheWrite =
|
|
1393
|
+
typeof p.cache_creation === "number"
|
|
1394
|
+
? p.cache_creation
|
|
1395
|
+
: typeof p.cacheWrite === "number"
|
|
1396
|
+
? p.cacheWrite
|
|
1397
|
+
: undefined;
|
|
1398
|
+
if (typeof cacheWrite === "number") parsed.cacheWrite = cacheWrite;
|
|
1399
|
+
if (Object.keys(parsed).length === 0) continue;
|
|
1400
|
+
const namespaced = `${providerAlias}/${modelId}`;
|
|
1401
|
+
const existingNs = out.get(namespaced);
|
|
1402
|
+
if (existingNs)
|
|
1403
|
+
existingNs.pricing = {
|
|
1404
|
+
...(existingNs.pricing ?? {}),
|
|
1405
|
+
...parsed,
|
|
1406
|
+
};
|
|
1407
|
+
else out.set(namespaced, { pricing: parsed });
|
|
1408
|
+
const existingBare = out.get(modelId);
|
|
1409
|
+
if (existingBare)
|
|
1410
|
+
existingBare.pricing = {
|
|
1411
|
+
...(existingBare.pricing ?? {}),
|
|
1412
|
+
...parsed,
|
|
1413
|
+
};
|
|
1414
|
+
else out.set(modelId, { pricing: parsed });
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
} catch {
|
|
1420
|
+
// Soft-fail; return whatever names we collected.
|
|
1421
|
+
} finally {
|
|
1422
|
+
clearTimeout(priceTimer);
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
// ── 3. Free model budgets from /api/free-tier/summary ──────────────────
|
|
1426
|
+
// Best-effort fetch: populates freeType/monthlyTokens/creditTokens on
|
|
1427
|
+
// enrichment entries that match. 404 = endpoint doesn't exist — skip.
|
|
1428
|
+
// Uses the EXISTING /api/free-tier/summary endpoint (no new server code).
|
|
1429
|
+
const freeAc = new AbortController();
|
|
1430
|
+
const freeTimer = setTimeout(() => freeAc.abort(), timeoutMs);
|
|
1431
|
+
try {
|
|
1432
|
+
const res = await fetch(`${root}/api/free-tier/summary`, {
|
|
1433
|
+
method: "GET",
|
|
1434
|
+
headers,
|
|
1435
|
+
signal: freeAc.signal,
|
|
1436
|
+
});
|
|
1437
|
+
if (res.ok) {
|
|
1438
|
+
const body = (await res.json()) as unknown;
|
|
1439
|
+
// Response shape: { perModel: FreeModelBudget[], ... }
|
|
1440
|
+
const perModel: unknown[] =
|
|
1441
|
+
body && typeof body === "object" && Array.isArray((body as { perModel?: unknown }).perModel)
|
|
1442
|
+
? ((body as { perModel: unknown[] }).perModel as unknown[])
|
|
1443
|
+
: Array.isArray(body)
|
|
1444
|
+
? (body as unknown[])
|
|
1445
|
+
: [];
|
|
1446
|
+
let matched = 0;
|
|
1447
|
+
for (const fm of perModel) {
|
|
1448
|
+
if (!fm || typeof fm !== "object") continue;
|
|
1449
|
+
const fmObj = fm as Record<string, unknown>;
|
|
1450
|
+
const provider = typeof fmObj.provider === "string" ? fmObj.provider : "";
|
|
1451
|
+
const modelId = typeof fmObj.modelId === "string" ? fmObj.modelId : "";
|
|
1452
|
+
const freeType = typeof fmObj.freeType === "string" ? fmObj.freeType : "";
|
|
1453
|
+
if (!modelId || !freeType) continue;
|
|
1454
|
+
const monthlyTokens =
|
|
1455
|
+
typeof fmObj.monthlyTokens === "number" ? fmObj.monthlyTokens : undefined;
|
|
1456
|
+
const creditTokens =
|
|
1457
|
+
typeof fmObj.creditTokens === "number" ? fmObj.creditTokens : undefined;
|
|
1458
|
+
// Match against enrichment entries: namespaced, bare, and displayName
|
|
1459
|
+
const displayName = typeof fmObj.displayName === "string" ? fmObj.displayName : "";
|
|
1460
|
+
const candidates = [
|
|
1461
|
+
`${provider}/${modelId}`,
|
|
1462
|
+
modelId,
|
|
1463
|
+
...(displayName ? [displayName] : []),
|
|
1464
|
+
];
|
|
1465
|
+
for (const key of candidates) {
|
|
1466
|
+
const entry = out.get(key);
|
|
1467
|
+
if (entry) {
|
|
1468
|
+
entry.freeType = freeType as FreeModelFreeType;
|
|
1469
|
+
if (monthlyTokens !== undefined) entry.monthlyTokens = monthlyTokens;
|
|
1470
|
+
if (creditTokens !== undefined) entry.creditTokens = creditTokens;
|
|
1471
|
+
matched++;
|
|
1472
|
+
break;
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
_logger.debug(
|
|
1477
|
+
`free-tier/summary: ${perModel.length} models returned, ${matched} matched enrichment entries`
|
|
1478
|
+
);
|
|
1479
|
+
}
|
|
1480
|
+
} catch {
|
|
1481
|
+
// Soft-fail; free metadata is optional.
|
|
1482
|
+
} finally {
|
|
1483
|
+
clearTimeout(freeTimer);
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
return out;
|
|
1487
|
+
};
|
|
1488
|
+
|
|
1489
|
+
// ── Startup diagnostics writer (file-based) ──────────────────────────────
|
|
1490
|
+
// OC doesn't capture plugin console.warn in its log file. Write diagnostics
|
|
1491
|
+
// to a file so they're readable after session starts. Capped at 64KB.
|
|
1492
|
+
async function writeStartupDiagnostics(params: {
|
|
1493
|
+
providerId: string;
|
|
1494
|
+
baseURL: string;
|
|
1495
|
+
modelCount: number;
|
|
1496
|
+
comboCount: number;
|
|
1497
|
+
enrichmentSize: number;
|
|
1498
|
+
autoComboCount: number;
|
|
1499
|
+
enrichment: OmniRouteEnrichmentMap;
|
|
1500
|
+
autoCombos: OmniRouteRawAutoCombo[];
|
|
1501
|
+
}): Promise<void> {
|
|
1502
|
+
const {
|
|
1503
|
+
providerId,
|
|
1504
|
+
baseURL,
|
|
1505
|
+
modelCount,
|
|
1506
|
+
comboCount,
|
|
1507
|
+
enrichmentSize,
|
|
1508
|
+
autoComboCount,
|
|
1509
|
+
enrichment,
|
|
1510
|
+
autoCombos,
|
|
1511
|
+
} = params;
|
|
1512
|
+
const enriched = [...enrichment.entries()];
|
|
1513
|
+
const withName = enriched.filter(([, e]) => e.name);
|
|
1514
|
+
const withPricing = enriched.filter(([, e]) => e.pricing);
|
|
1515
|
+
const withFree = enriched.filter(([, e]) => e.freeType);
|
|
1516
|
+
|
|
1517
|
+
const lines: string[] = [];
|
|
1518
|
+
lines.push(`=== startupDebug ${new Date().toISOString()} ===`);
|
|
1519
|
+
lines.push(`providerId=${providerId} baseURL=${baseURL}`);
|
|
1520
|
+
lines.push(
|
|
1521
|
+
`models=${modelCount} combos=${comboCount} enrichment=${enrichmentSize} autoCombos=${autoComboCount}`
|
|
1522
|
+
);
|
|
1523
|
+
lines.push(
|
|
1524
|
+
`enrichment: ${withName.length} with name, ${withPricing.length} with pricing, ${withFree.length} free`
|
|
1525
|
+
);
|
|
1526
|
+
if (withFree.length > 0) {
|
|
1527
|
+
lines.push(`free models (${withFree.length}):`);
|
|
1528
|
+
for (const [k, e] of withFree.slice(0, 10)) {
|
|
1529
|
+
lines.push(
|
|
1530
|
+
` ${k} → name=${e.name ?? "(none)"}, freeType=${e.freeType}, monthly=${e.monthlyTokens ?? 0}, credits=${e.creditTokens ?? 0}`
|
|
1531
|
+
);
|
|
1532
|
+
}
|
|
1533
|
+
} else {
|
|
1534
|
+
lines.push(
|
|
1535
|
+
`NO free models detected. ` +
|
|
1536
|
+
(enrichmentSize === 0
|
|
1537
|
+
? "Enrichment map is EMPTY."
|
|
1538
|
+
: `Enrichment has ${enrichmentSize} entries but none have freeType.`)
|
|
1539
|
+
);
|
|
1540
|
+
}
|
|
1541
|
+
const sampleNames = enriched
|
|
1542
|
+
.filter(([, e]) => e.name)
|
|
1543
|
+
.slice(0, 5)
|
|
1544
|
+
.map(([k, e]) => ` ${k} → "${e.name}"`);
|
|
1545
|
+
if (sampleNames.length > 0) {
|
|
1546
|
+
lines.push(`sample enriched names:`);
|
|
1547
|
+
lines.push(sampleNames.join("\n"));
|
|
1548
|
+
}
|
|
1549
|
+
if (autoCombos.length > 0) {
|
|
1550
|
+
lines.push(
|
|
1551
|
+
`auto combos: ${autoCombos.length} — ${autoCombos.map((ac) => `${ac.id}(${ac.candidateCount ?? "?"}p)`).join(", ")}`
|
|
1552
|
+
);
|
|
1553
|
+
}
|
|
1554
|
+
lines.push(`=== end startupDebug ===\n`);
|
|
1555
|
+
|
|
1556
|
+
const diagnostics = lines.join("\n");
|
|
1557
|
+
_logger.debug(diagnostics);
|
|
1558
|
+
|
|
1559
|
+
try {
|
|
1560
|
+
const diagDir =
|
|
1561
|
+
process.env.OPENCODE_DATA_DIR ?? path.join(os.homedir(), ".local/share/opencode");
|
|
1562
|
+
const diagPath = path.join(diagDir, "plugins", "omniroute-startup-diagnostics.log");
|
|
1563
|
+
let existing = "";
|
|
1564
|
+
try {
|
|
1565
|
+
existing = await readFile(diagPath, "utf8");
|
|
1566
|
+
} catch {
|
|
1567
|
+
/* first write */
|
|
1568
|
+
}
|
|
1569
|
+
const KEEP = 65_536;
|
|
1570
|
+
const combined = existing + diagnostics;
|
|
1571
|
+
const trimmed = combined.length > KEEP ? combined.slice(combined.length - KEEP) : combined;
|
|
1572
|
+
await writeFile(diagPath, trimmed, "utf8");
|
|
1573
|
+
} catch {
|
|
1574
|
+
/* best effort */
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
/**
|
|
1579
|
+
* Separator used by `applyProviderTag` between the upstream provider
|
|
1580
|
+
* label (prefix) and the enriched model name. ASCII hyphen with
|
|
1581
|
+
* surrounding spaces — terminal-safe everywhere, never collides with
|
|
1582
|
+
* a model id (those use slashes / dots / underscores).
|
|
1583
|
+
*
|
|
1584
|
+
* Layout: `<short-label> - <model name>` (label leads so column scans
|
|
1585
|
+
* group by provider — e.g. `Claude - Claude Opus 4.7`,
|
|
1586
|
+
* `Kiro - Claude Opus 4.7`).
|
|
1587
|
+
*/
|
|
1588
|
+
export const PROVIDER_TAG_SEPARATOR = _PROVIDER_TAG_SEPARATOR;
|
|
1589
|
+
|
|
1590
|
+
// Re-export from naming.ts — thin wrapper preserving OmniRouteEnrichmentEntry signature
|
|
1591
|
+
export function shortProviderLabel(
|
|
1592
|
+
enrichment: OmniRouteEnrichmentEntry | undefined
|
|
1593
|
+
): string | undefined {
|
|
1594
|
+
return _shortProviderLabel(enrichment);
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
/**
|
|
1598
|
+
* Prepend the upstream provider label to `model.name` so the OC TUI
|
|
1599
|
+
* picker can differentiate the same model id sold through different
|
|
1600
|
+
* upstream connections (e.g. `cc/claude-opus-4-7` via Anthropic
|
|
1601
|
+
* vs `kr/claude-opus-4-7` via Kiro). Result shape:
|
|
1602
|
+
*
|
|
1603
|
+
* `<label>${PROVIDER_TAG_SEPARATOR}<enriched name>`
|
|
1604
|
+
* → `Claude - Claude Opus 4.7`
|
|
1605
|
+
* → `Kiro - Claude Opus 4.7`
|
|
1606
|
+
* → `AssemblyAI - Universal 2 (Transcription)` (slot.name fits, used verbatim)
|
|
1607
|
+
* → `GHM - GPT 5` (slot.name "GitHub Models" > 12 chars → UPPER(alias))
|
|
1608
|
+
*
|
|
1609
|
+
* Mutates the model in place and is idempotent — running twice never
|
|
1610
|
+
* double-prefixes. No-op when:
|
|
1611
|
+
*
|
|
1612
|
+
* - `enrichment` is undefined,
|
|
1613
|
+
* - {@link shortProviderLabel} returns `undefined`
|
|
1614
|
+
* (no `providerDisplayName` AND no `providerAlias`),
|
|
1615
|
+
* - the current `model.name` already starts with the prefix.
|
|
1616
|
+
*
|
|
1617
|
+
* Combos are intentionally skipped by callers (they're multi-upstream
|
|
1618
|
+
* by definition; the `Combo: ` prefix conveys that). Raw models call
|
|
1619
|
+
* this after `applyEnrichment` so the tag layers on top of the
|
|
1620
|
+
* friendly name.
|
|
1621
|
+
*/
|
|
1622
|
+
export function applyProviderTag(
|
|
1623
|
+
model: ModelV2,
|
|
1624
|
+
enrichment: OmniRouteEnrichmentEntry | undefined
|
|
1625
|
+
): ModelV2 {
|
|
1626
|
+
const label = shortProviderLabel(enrichment);
|
|
1627
|
+
if (!label) return model;
|
|
1628
|
+
const prefix = `${label}${PROVIDER_TAG_SEPARATOR}`;
|
|
1629
|
+
if (model.name.startsWith(prefix)) return model;
|
|
1630
|
+
// When enrichment already prepended [Free], move it before the provider
|
|
1631
|
+
// tag: "[Free] GPT-4.1" → "[Free] GHM - GPT-4.1" not "GHM - [Free] GPT-4.1"
|
|
1632
|
+
if (model.name.startsWith("[Free] ")) {
|
|
1633
|
+
model.name = `[Free] ${prefix}${model.name.slice(7)}`;
|
|
1634
|
+
} else {
|
|
1635
|
+
model.name = `${prefix}${model.name}`;
|
|
1636
|
+
}
|
|
1637
|
+
return model;
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1640
|
+
/**
|
|
1641
|
+
* Reverse-index the enrichment map from `providerCanonical → providerAlias`.
|
|
1642
|
+
*
|
|
1643
|
+
* OmniRoute's `/api/pricing/models` is keyed by short ALIAS (`cc`, `cx`,
|
|
1644
|
+
* `pol`). But `/v1/models` exposes some models a SECOND time under their
|
|
1645
|
+
* CANONICAL name (`claude/claude-opus-4-7`, `codex/gpt-5.5`,
|
|
1646
|
+
* `pollinations/midjourney`). Without a reverse map, those canonical
|
|
1647
|
+
* rows miss enrichment entirely and surface as raw ids in the picker.
|
|
1648
|
+
*
|
|
1649
|
+
* Built once per refresh from the enrichment entries themselves — no
|
|
1650
|
+
* hardcoded registry. Only records `canonical → alias` mappings when
|
|
1651
|
+
* both are present AND distinct (skips slots where alias === canonical
|
|
1652
|
+
* like `kiro`).
|
|
1653
|
+
*/
|
|
1654
|
+
export function buildCanonicalToAliasMap(
|
|
1655
|
+
enrichment: OmniRouteEnrichmentMap | undefined
|
|
1656
|
+
): Map<string, string> {
|
|
1657
|
+
const out = new Map<string, string>();
|
|
1658
|
+
if (!enrichment) return out;
|
|
1659
|
+
for (const entry of enrichment.values()) {
|
|
1660
|
+
const alias = typeof entry.providerAlias === "string" ? entry.providerAlias.trim() : "";
|
|
1661
|
+
const canonical =
|
|
1662
|
+
typeof entry.providerCanonical === "string" ? entry.providerCanonical.trim() : "";
|
|
1663
|
+
if (alias.length === 0 || canonical.length === 0) continue;
|
|
1664
|
+
if (alias === canonical) continue;
|
|
1665
|
+
if (!out.has(canonical)) out.set(canonical, alias);
|
|
1666
|
+
}
|
|
1667
|
+
return out;
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
/**
|
|
1671
|
+
* Enrichment lookup with alias-fallback chain.
|
|
1672
|
+
*
|
|
1673
|
+
* Resolution order (first hit wins):
|
|
1674
|
+
*
|
|
1675
|
+
* 1. `enrichment.get(rawId)` — direct hit on `<prefix>/<modelId>` or
|
|
1676
|
+
* bare id (the fetcher writes under both forms).
|
|
1677
|
+
* 2. If `rawId` is `<canonical>/<modelId>` and `canonicalToAlias` has
|
|
1678
|
+
* a mapping for `canonical`, try `<alias>/<modelId>`. This rescues
|
|
1679
|
+
* duplicate rows like `claude/claude-opus-4-7` (canonical) when
|
|
1680
|
+
* enrichment only indexed under `cc/claude-opus-4-7` (alias).
|
|
1681
|
+
* 3. Bare `<modelId>` as a last resort. Already covered by step 1 in
|
|
1682
|
+
* practice (fetcher writes bare keys), but kept defensive.
|
|
1683
|
+
*
|
|
1684
|
+
* Returns `undefined` when no lookup hits.
|
|
1685
|
+
*/
|
|
1686
|
+
export function lookupEnrichment(
|
|
1687
|
+
rawId: string,
|
|
1688
|
+
enrichment: OmniRouteEnrichmentMap | undefined,
|
|
1689
|
+
canonicalToAlias: Map<string, string>
|
|
1690
|
+
): OmniRouteEnrichmentEntry | undefined {
|
|
1691
|
+
if (!enrichment) return undefined;
|
|
1692
|
+
const direct = enrichment.get(rawId);
|
|
1693
|
+
if (direct) return direct;
|
|
1694
|
+
const slash = rawId.indexOf("/");
|
|
1695
|
+
if (slash > 0) {
|
|
1696
|
+
const prefix = rawId.slice(0, slash);
|
|
1697
|
+
const modelId = rawId.slice(slash + 1);
|
|
1698
|
+
const alias = canonicalToAlias.get(prefix);
|
|
1699
|
+
if (alias && alias !== prefix) {
|
|
1700
|
+
const viaAlias = enrichment.get(`${alias}/${modelId}`);
|
|
1701
|
+
if (viaAlias) return viaAlias;
|
|
1702
|
+
}
|
|
1703
|
+
const bare = enrichment.get(modelId);
|
|
1704
|
+
if (bare) return bare;
|
|
1705
|
+
}
|
|
1706
|
+
return undefined;
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
/**
|
|
1710
|
+
* Pre-pass: detect raw rows that are the CANONICAL twin of an ALIAS row
|
|
1711
|
+
* already in the catalog. Returns the set of canonical-keyed ids to skip
|
|
1712
|
+
* during the raw-model loop so each model surfaces exactly once under
|
|
1713
|
+
* its enriched alias key.
|
|
1714
|
+
*
|
|
1715
|
+
* Example: `/v1/models` returns BOTH `cc/claude-opus-4-7` and
|
|
1716
|
+
* `claude/claude-opus-4-7`. The former is enriched (alias `cc` exists
|
|
1717
|
+
* in `/api/pricing/models`); the latter is raw. We keep `cc/...` and
|
|
1718
|
+
* drop `claude/...`.
|
|
1719
|
+
*
|
|
1720
|
+
* Built once per refresh. Cheap — O(M) where M = raw model count.
|
|
1721
|
+
*/
|
|
1722
|
+
export function canonicalDedupSet(
|
|
1723
|
+
rawModels: ReadonlyArray<OmniRouteRawModelEntry>,
|
|
1724
|
+
canonicalToAlias: Map<string, string>
|
|
1725
|
+
): Set<string> {
|
|
1726
|
+
const drop = new Set<string>();
|
|
1727
|
+
if (canonicalToAlias.size === 0) return drop;
|
|
1728
|
+
// Index every alias key present in the raw catalog.
|
|
1729
|
+
const aliasKeys = new Set<string>();
|
|
1730
|
+
for (const m of rawModels) {
|
|
1731
|
+
if (typeof m.id === "string" && m.id.length > 0) aliasKeys.add(m.id);
|
|
1732
|
+
}
|
|
1733
|
+
for (const m of rawModels) {
|
|
1734
|
+
if (typeof m.id !== "string" || m.id.length === 0) continue;
|
|
1735
|
+
const slash = m.id.indexOf("/");
|
|
1736
|
+
if (slash <= 0) continue;
|
|
1737
|
+
const prefix = m.id.slice(0, slash);
|
|
1738
|
+
const modelId = m.id.slice(slash + 1);
|
|
1739
|
+
const alias = canonicalToAlias.get(prefix);
|
|
1740
|
+
if (!alias || alias === prefix) continue;
|
|
1741
|
+
// Canonical row only gets suppressed if the alias row actually
|
|
1742
|
+
// exists — otherwise we'd hide the model entirely.
|
|
1743
|
+
if (aliasKeys.has(`${alias}/${modelId}`)) drop.add(m.id);
|
|
1744
|
+
}
|
|
1745
|
+
return drop;
|
|
1746
|
+
}
|
|
1747
|
+
|
|
1748
|
+
/**
|
|
1749
|
+
* Build a per-alias index of enrichment metadata so we can render the
|
|
1750
|
+
* provider prefix even for raw models that don't have their own
|
|
1751
|
+
* curated `/api/pricing/models` entry.
|
|
1752
|
+
*
|
|
1753
|
+
* Real example: OmniRoute's `pricing['cohere']` slot lists 10 curated
|
|
1754
|
+
* models but `/v1/models` also returns `cohere/rerank-multilingual-v3.0`
|
|
1755
|
+
* and `cohere/rerank-v4.0-fast` (not in the curated 10). Without this
|
|
1756
|
+
* index, those rows surface in the picker as `cohere/...` with no
|
|
1757
|
+
* `Cohere - ` prefix because the per-model enrichment lookup misses.
|
|
1758
|
+
*
|
|
1759
|
+
* This index records the first non-empty `providerDisplayName` seen
|
|
1760
|
+
* for each alias, plus the alias itself. Callers use it to synthesize
|
|
1761
|
+
* a minimal `OmniRouteEnrichmentEntry` whenever the direct lookup
|
|
1762
|
+
* misses but the raw id's prefix matches a known alias.
|
|
1763
|
+
*
|
|
1764
|
+
* Built once per refresh; first-wins on duplicate alias (matches
|
|
1765
|
+
* `buildCanonicalToAliasMap` semantics).
|
|
1766
|
+
*/
|
|
1767
|
+
export function buildAliasIndex(
|
|
1768
|
+
enrichment: OmniRouteEnrichmentMap | undefined
|
|
1769
|
+
): Map<string, OmniRouteEnrichmentEntry> {
|
|
1770
|
+
const out = new Map<string, OmniRouteEnrichmentEntry>();
|
|
1771
|
+
if (!enrichment) return out;
|
|
1772
|
+
for (const entry of enrichment.values()) {
|
|
1773
|
+
const alias = typeof entry.providerAlias === "string" ? entry.providerAlias.trim() : "";
|
|
1774
|
+
if (alias.length === 0) continue;
|
|
1775
|
+
if (out.has(alias)) {
|
|
1776
|
+
// First-wins, but upgrade to the first entry that carries a
|
|
1777
|
+
// non-empty providerDisplayName so the prefix renders nicely.
|
|
1778
|
+
const existing = out.get(alias);
|
|
1779
|
+
if (
|
|
1780
|
+
existing &&
|
|
1781
|
+
(!existing.providerDisplayName || existing.providerDisplayName.trim().length === 0) &&
|
|
1782
|
+
typeof entry.providerDisplayName === "string" &&
|
|
1783
|
+
entry.providerDisplayName.trim().length > 0
|
|
1784
|
+
) {
|
|
1785
|
+
out.set(alias, entry);
|
|
1786
|
+
}
|
|
1787
|
+
continue;
|
|
1788
|
+
}
|
|
1789
|
+
out.set(alias, entry);
|
|
1790
|
+
}
|
|
1791
|
+
return out;
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
/**
|
|
1795
|
+
* Resolve a synthesised enrichment entry for `applyProviderTag` /
|
|
1796
|
+
* `shortProviderLabel` consumption, combining two sources:
|
|
1797
|
+
*
|
|
1798
|
+
* 1. The direct per-model enrichment match (if present).
|
|
1799
|
+
* 2. A per-alias fallback derived from `buildAliasIndex` — covers raw
|
|
1800
|
+
* ids whose prefix matches a known alias but the specific model
|
|
1801
|
+
* id wasn't curated in `/api/pricing/models`. Example:
|
|
1802
|
+
* `cohere/rerank-multilingual-v3.0` falls back to the cohere slot's
|
|
1803
|
+
* `providerDisplayName='Cohere'` even though that specific id
|
|
1804
|
+
* isn't in the curated 10-model list.
|
|
1805
|
+
*
|
|
1806
|
+
* Returns `undefined` when neither source surfaces an alias.
|
|
1807
|
+
*
|
|
1808
|
+
* NOTE: this function is read-only over its inputs; it never mutates
|
|
1809
|
+
* the underlying `direct` entry. When it falls back to the alias
|
|
1810
|
+
* index, it constructs a fresh minimal entry exposing only the
|
|
1811
|
+
* provider-prefix fields (`providerAlias`, `providerCanonical`,
|
|
1812
|
+
* `providerDisplayName`). Other fields (name, pricing) are explicitly
|
|
1813
|
+
* left undefined so `applyEnrichment` won't accidentally overwrite a
|
|
1814
|
+
* model name with the alias-slot label.
|
|
1815
|
+
*/
|
|
1816
|
+
export function resolveProviderTagEntry(
|
|
1817
|
+
rawId: string,
|
|
1818
|
+
direct: OmniRouteEnrichmentEntry | undefined,
|
|
1819
|
+
aliasIndex: Map<string, OmniRouteEnrichmentEntry>,
|
|
1820
|
+
canonicalToAlias?: Map<string, string>
|
|
1821
|
+
): OmniRouteEnrichmentEntry | undefined {
|
|
1822
|
+
if (direct) {
|
|
1823
|
+
const alias = typeof direct.providerAlias === "string" ? direct.providerAlias.trim() : "";
|
|
1824
|
+
const display =
|
|
1825
|
+
typeof direct.providerDisplayName === "string" ? direct.providerDisplayName.trim() : "";
|
|
1826
|
+
if (alias.length > 0 || display.length > 0) return direct;
|
|
1827
|
+
}
|
|
1828
|
+
const slash = rawId.indexOf("/");
|
|
1829
|
+
if (slash <= 0) return direct;
|
|
1830
|
+
const prefix = rawId.slice(0, slash);
|
|
1831
|
+
// 1. Direct alias lookup (`cohere/...` → cohere slot keyed by alias=cohere).
|
|
1832
|
+
let fromAlias = aliasIndex.get(prefix);
|
|
1833
|
+
// 2. Canonical fallback (`pollinations/...` → look up via alias `pol`).
|
|
1834
|
+
if (!fromAlias && canonicalToAlias) {
|
|
1835
|
+
const alias = canonicalToAlias.get(prefix);
|
|
1836
|
+
if (alias) fromAlias = aliasIndex.get(alias);
|
|
1837
|
+
}
|
|
1838
|
+
if (!fromAlias) return direct;
|
|
1839
|
+
// Synthesize: borrow only the provider-prefix metadata.
|
|
1840
|
+
return {
|
|
1841
|
+
providerAlias: fromAlias.providerAlias,
|
|
1842
|
+
providerCanonical: fromAlias.providerCanonical,
|
|
1843
|
+
providerDisplayName: fromAlias.providerDisplayName,
|
|
1844
|
+
};
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
/**
|
|
1848
|
+
* Apply enrichment overlay onto a ModelV2 entry. Mutates and returns the
|
|
1849
|
+
* passed entry for convenience.
|
|
1850
|
+
*/
|
|
1851
|
+
/**
|
|
1852
|
+
* Normalise a model display name so free-tier models always carry a
|
|
1853
|
+
* consistent `[Free] ` prefix instead of a trailing `(Free)` suffix or an
|
|
1854
|
+
* ad-hoc `free` word anywhere in the name.
|
|
1855
|
+
*
|
|
1856
|
+
* Examples:
|
|
1857
|
+
* "GPT-4.1 (Free)" → "[Free] GPT-4.1"
|
|
1858
|
+
* "DeepSeek V4 Flash Free" → "[Free] DeepSeek V4 Flash"
|
|
1859
|
+
* "Claude Opus 4.7" → "Claude Opus 4.7" (unchanged)
|
|
1860
|
+
*/
|
|
1861
|
+
export { _normaliseFreeLabel as normaliseFreeLabel };
|
|
1862
|
+
|
|
1863
|
+
export function applyEnrichment(
|
|
1864
|
+
model: ModelV2,
|
|
1865
|
+
enrichment: OmniRouteEnrichmentEntry | undefined
|
|
1866
|
+
): ModelV2 {
|
|
1867
|
+
if (!enrichment) return model;
|
|
1868
|
+
if (enrichment.name && enrichment.name.trim().length > 0) {
|
|
1869
|
+
model.name = _normaliseFreeLabel(enrichment.name);
|
|
1870
|
+
}
|
|
1871
|
+
if (enrichment.pricing) {
|
|
1872
|
+
if (typeof enrichment.pricing.input === "number") {
|
|
1873
|
+
model.cost.input = enrichment.pricing.input;
|
|
1874
|
+
}
|
|
1875
|
+
if (typeof enrichment.pricing.output === "number") {
|
|
1876
|
+
model.cost.output = enrichment.pricing.output;
|
|
1877
|
+
}
|
|
1878
|
+
if (typeof enrichment.pricing.cacheRead === "number") {
|
|
1879
|
+
model.cost.cache.read = enrichment.pricing.cacheRead;
|
|
1880
|
+
}
|
|
1881
|
+
if (typeof enrichment.pricing.cacheWrite === "number") {
|
|
1882
|
+
model.cost.cache.write = enrichment.pricing.cacheWrite;
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
return model;
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1888
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
1889
|
+
// COMPRESSION METADATA — pull /api/context/combos so combo entries can be
|
|
1890
|
+
// tagged with their compression pipeline. Gated by
|
|
1891
|
+
// features.compressionMetadata (off by default).
|
|
1892
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
1893
|
+
|
|
1894
|
+
/** Single step in a compression combo's pipeline. */
|
|
1895
|
+
export interface OmniRouteCompressionStep {
|
|
1896
|
+
engine: string; // "rtk" | "caveman" | "aggressive" | ...
|
|
1897
|
+
intensity?: string; // "minimal" | "lite" | "standard" | "full" | "ultra" | "aggressive"
|
|
1898
|
+
}
|
|
1899
|
+
|
|
1900
|
+
/** Compression combo as returned by /api/context/combos. */
|
|
1901
|
+
export interface OmniRouteCompressionCombo {
|
|
1902
|
+
id: string;
|
|
1903
|
+
name?: string;
|
|
1904
|
+
description?: string;
|
|
1905
|
+
pipeline: OmniRouteCompressionStep[];
|
|
1906
|
+
isDefault?: boolean;
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
export type OmniRouteCompressionMetaFetcher = (
|
|
1910
|
+
baseURL: string,
|
|
1911
|
+
apiKey: string,
|
|
1912
|
+
timeoutMs?: number
|
|
1913
|
+
) => Promise<OmniRouteCompressionCombo[]>;
|
|
1914
|
+
|
|
1915
|
+
/**
|
|
1916
|
+
* Default compression-metadata fetcher — calls `GET /api/context/combos`.
|
|
1917
|
+
* Tolerates envelope shapes `{ combos: [...] }`, `[...]`, or
|
|
1918
|
+
* `{ data: [...] }`. Soft-fails (returns []) on non-2xx or parse errors.
|
|
1919
|
+
*/
|
|
1920
|
+
export const defaultOmniRouteCompressionMetaFetcher: OmniRouteCompressionMetaFetcher = async (
|
|
1921
|
+
baseURL,
|
|
1922
|
+
apiKey,
|
|
1923
|
+
timeoutMs = 10_000
|
|
1924
|
+
) => {
|
|
1925
|
+
const empty: OmniRouteCompressionCombo[] = [];
|
|
1926
|
+
if (!baseURL || !apiKey) return empty;
|
|
1927
|
+
const root = baseURL.replace(/\/v1\/?$/, "").replace(/\/$/, "");
|
|
1928
|
+
const url = `${root}/api/context/combos`;
|
|
1929
|
+
const ac = new AbortController();
|
|
1930
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
1931
|
+
try {
|
|
1932
|
+
const res = await fetch(url, {
|
|
1933
|
+
method: "GET",
|
|
1934
|
+
headers: {
|
|
1935
|
+
Authorization: `Bearer ${apiKey}`,
|
|
1936
|
+
Accept: "application/json",
|
|
1937
|
+
},
|
|
1938
|
+
signal: ac.signal,
|
|
1939
|
+
});
|
|
1940
|
+
if (!res.ok) return empty;
|
|
1941
|
+
const body = (await res.json()) as unknown;
|
|
1942
|
+
const list = Array.isArray(body)
|
|
1943
|
+
? body
|
|
1944
|
+
: Array.isArray((body as { combos?: unknown[] })?.combos)
|
|
1945
|
+
? (body as { combos: unknown[] }).combos
|
|
1946
|
+
: Array.isArray((body as { data?: unknown[] })?.data)
|
|
1947
|
+
? (body as { data: unknown[] }).data
|
|
1948
|
+
: [];
|
|
1949
|
+
const out: OmniRouteCompressionCombo[] = [];
|
|
1950
|
+
for (const raw of list) {
|
|
1951
|
+
if (!raw || typeof raw !== "object") continue;
|
|
1952
|
+
const id = (raw as { id?: unknown }).id;
|
|
1953
|
+
const pipeline = (raw as { pipeline?: unknown }).pipeline;
|
|
1954
|
+
if (typeof id !== "string" || id.length === 0) continue;
|
|
1955
|
+
if (!Array.isArray(pipeline)) continue;
|
|
1956
|
+
const steps: OmniRouteCompressionStep[] = [];
|
|
1957
|
+
for (const step of pipeline) {
|
|
1958
|
+
if (!step || typeof step !== "object") continue;
|
|
1959
|
+
const engine = (step as { engine?: unknown }).engine;
|
|
1960
|
+
if (typeof engine !== "string" || engine.length === 0) continue;
|
|
1961
|
+
const intensity = (step as { intensity?: unknown }).intensity;
|
|
1962
|
+
const entry: OmniRouteCompressionStep = { engine };
|
|
1963
|
+
if (typeof intensity === "string" && intensity.length > 0) {
|
|
1964
|
+
entry.intensity = intensity;
|
|
1965
|
+
}
|
|
1966
|
+
steps.push(entry);
|
|
1967
|
+
}
|
|
1968
|
+
const combo: OmniRouteCompressionCombo = { id, pipeline: steps };
|
|
1969
|
+
const name = (raw as { name?: unknown }).name;
|
|
1970
|
+
if (typeof name === "string" && name.length > 0) combo.name = name;
|
|
1971
|
+
const description = (raw as { description?: unknown }).description;
|
|
1972
|
+
if (typeof description === "string") combo.description = description;
|
|
1973
|
+
const isDefault = (raw as { isDefault?: unknown }).isDefault;
|
|
1974
|
+
if (typeof isDefault === "boolean") combo.isDefault = isDefault;
|
|
1975
|
+
out.push(combo);
|
|
1976
|
+
}
|
|
1977
|
+
return out;
|
|
1978
|
+
} catch {
|
|
1979
|
+
return empty;
|
|
1980
|
+
} finally {
|
|
1981
|
+
clearTimeout(timer);
|
|
1982
|
+
}
|
|
1983
|
+
};
|
|
1984
|
+
|
|
1985
|
+
/**
|
|
1986
|
+
* Map of well-known compression-intensity tokens to a single emoji
|
|
1987
|
+
* conveying "how much" compression is applied. Traffic-light palette:
|
|
1988
|
+
*
|
|
1989
|
+
* 🟢 minimal / lite — almost no loss
|
|
1990
|
+
* 🟡 standard — balanced
|
|
1991
|
+
* 🟠 aggressive / full — heavy
|
|
1992
|
+
* 🔴 ultra — extreme
|
|
1993
|
+
*
|
|
1994
|
+
* Lookup is case-insensitive. Unknown intensities fall through to the
|
|
1995
|
+
* raw text form (`engine:<intensity>`) so we never hide a value that
|
|
1996
|
+
* OmniRoute knows but the plugin doesn't.
|
|
1997
|
+
*
|
|
1998
|
+
* Exported for callers (and tests) that want to assemble their own
|
|
1999
|
+
* pipeline strings.
|
|
2000
|
+
*/
|
|
2001
|
+
export const COMPRESSION_INTENSITY_EMOJI: Record<string, string> = {
|
|
2002
|
+
minimal: "🟢",
|
|
2003
|
+
lite: "🟢",
|
|
2004
|
+
standard: "🟡",
|
|
2005
|
+
aggressive: "🟠",
|
|
2006
|
+
full: "🟠",
|
|
2007
|
+
ultra: "🔴",
|
|
2008
|
+
};
|
|
2009
|
+
|
|
2010
|
+
/**
|
|
2011
|
+
* Format a compression pipeline as a short human-readable string for
|
|
2012
|
+
* combo `name` decoration. Intensity tokens render as a traffic-light
|
|
2013
|
+
* emoji so a column scan reveals "how compressed" the combo is at a
|
|
2014
|
+
* glance:
|
|
2015
|
+
*
|
|
2016
|
+
* `[rtk🟡 → caveman🟠]` (rtk:standard → caveman:full)
|
|
2017
|
+
* `[rtk🔴]` (rtk:ultra, single-step)
|
|
2018
|
+
* `[caveman]` (engine without intensity, no emoji)
|
|
2019
|
+
* `[rtk:custom-thing]` (unknown intensity, raw-text fallback)
|
|
2020
|
+
*/
|
|
2021
|
+
export function formatCompressionPipeline(pipeline: OmniRouteCompressionStep[]): string {
|
|
2022
|
+
if (!pipeline || pipeline.length === 0) return "";
|
|
2023
|
+
return (
|
|
2024
|
+
"[" +
|
|
2025
|
+
pipeline
|
|
2026
|
+
.map((s) => {
|
|
2027
|
+
if (!s.intensity) return s.engine;
|
|
2028
|
+
const emoji = COMPRESSION_INTENSITY_EMOJI[s.intensity.toLowerCase()];
|
|
2029
|
+
return emoji ? `${s.engine}${emoji}` : `${s.engine}:${s.intensity}`;
|
|
2030
|
+
})
|
|
2031
|
+
.join(" → ") +
|
|
2032
|
+
"]"
|
|
2033
|
+
);
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
2037
|
+
// /api/providers (provider-connection status) — optional read used by the
|
|
2038
|
+
// `features.usableOnly` filter. Returns the operator's installed OmniRoute
|
|
2039
|
+
// provider connections, each with `provider` (canonical id), `isActive`,
|
|
2040
|
+
// `testStatus`. We treat a provider as USABLE when at least one of its
|
|
2041
|
+
// connections is `isActive: true && testStatus: 'active'`. Aliases (e.g.
|
|
2042
|
+
// `cc → claude`) are resolved through the enrichment map.
|
|
2043
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
2044
|
+
|
|
2045
|
+
/** Subset of `/api/providers/connections[]` we read. Other fields are kept as a permissive index signature. */
|
|
2046
|
+
export interface OmniRouteProviderConnection {
|
|
2047
|
+
/** Connection UUID. */
|
|
2048
|
+
id: string;
|
|
2049
|
+
/** Canonical provider id, e.g. `claude`, `gemini`, `kiro`. Matches `entry.id` in `/api/pricing/models`. */
|
|
2050
|
+
provider: string;
|
|
2051
|
+
/** Connection auth flavor, e.g. `apikey`, `oauth`, `cookie`. */
|
|
2052
|
+
authType?: string;
|
|
2053
|
+
/** Operator-visible label. */
|
|
2054
|
+
name?: string;
|
|
2055
|
+
/** Operator toggle — when false, the connection is provisioned but disabled. */
|
|
2056
|
+
isActive?: boolean;
|
|
2057
|
+
/** Health-check verdict — `active` means routable; `expired`/`error`/`unavailable` mean not. */
|
|
2058
|
+
testStatus?: string;
|
|
2059
|
+
/** Permissive bag — additional fields (priority, backoffLevel, etc.) pass through untouched. */
|
|
2060
|
+
[k: string]: unknown;
|
|
2061
|
+
}
|
|
2062
|
+
|
|
2063
|
+
export type OmniRouteProvidersFetcher = (
|
|
2064
|
+
baseURL: string,
|
|
2065
|
+
apiKey: string,
|
|
2066
|
+
timeoutMs?: number
|
|
2067
|
+
) => Promise<OmniRouteProviderConnection[]>;
|
|
2068
|
+
|
|
2069
|
+
/**
|
|
2070
|
+
* Default providers fetcher — calls `GET /api/providers`. Tolerates envelope
|
|
2071
|
+
* shapes `{ connections: [...] }`, `[...]`, or `{ data: [...] }`. Soft-fails
|
|
2072
|
+
* (returns []) on non-2xx or parse errors so the `usableOnly` filter
|
|
2073
|
+
* gracefully degrades to "no filter" instead of hiding the whole catalog.
|
|
2074
|
+
*/
|
|
2075
|
+
export const defaultOmniRouteProvidersFetcher: OmniRouteProvidersFetcher = async (
|
|
2076
|
+
baseURL,
|
|
2077
|
+
apiKey,
|
|
2078
|
+
timeoutMs = 10_000
|
|
2079
|
+
) => {
|
|
2080
|
+
const empty: OmniRouteProviderConnection[] = [];
|
|
2081
|
+
if (!baseURL || !apiKey) return empty;
|
|
2082
|
+
const root = baseURL.replace(/\/v1\/?$/, "").replace(/\/$/, "");
|
|
2083
|
+
const url = `${root}/api/providers`;
|
|
2084
|
+
const ac = new AbortController();
|
|
2085
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
2086
|
+
try {
|
|
2087
|
+
const res = await fetch(url, {
|
|
2088
|
+
method: "GET",
|
|
2089
|
+
headers: {
|
|
2090
|
+
Authorization: `Bearer ${apiKey}`,
|
|
2091
|
+
Accept: "application/json",
|
|
2092
|
+
},
|
|
2093
|
+
signal: ac.signal,
|
|
2094
|
+
});
|
|
2095
|
+
if (!res.ok) return empty;
|
|
2096
|
+
const body = (await res.json()) as unknown;
|
|
2097
|
+
const list = Array.isArray(body)
|
|
2098
|
+
? body
|
|
2099
|
+
: Array.isArray((body as { connections?: unknown[] })?.connections)
|
|
2100
|
+
? (body as { connections: unknown[] }).connections
|
|
2101
|
+
: Array.isArray((body as { data?: unknown[] })?.data)
|
|
2102
|
+
? (body as { data: unknown[] }).data
|
|
2103
|
+
: [];
|
|
2104
|
+
const out: OmniRouteProviderConnection[] = [];
|
|
2105
|
+
for (const raw of list) {
|
|
2106
|
+
if (!raw || typeof raw !== "object") continue;
|
|
2107
|
+
const provider = (raw as { provider?: unknown }).provider;
|
|
2108
|
+
if (typeof provider !== "string" || provider.length === 0) continue;
|
|
2109
|
+
const id = (raw as { id?: unknown }).id;
|
|
2110
|
+
const idStr = typeof id === "string" && id.length > 0 ? id : provider;
|
|
2111
|
+
out.push({ ...(raw as Record<string, unknown>), id: idStr, provider });
|
|
2112
|
+
}
|
|
2113
|
+
return out;
|
|
2114
|
+
} catch {
|
|
2115
|
+
return empty;
|
|
2116
|
+
} finally {
|
|
2117
|
+
clearTimeout(timer);
|
|
2118
|
+
}
|
|
2119
|
+
};
|
|
2120
|
+
|
|
2121
|
+
/**
|
|
2122
|
+
* Compute the set of provider aliases that have at least one healthy,
|
|
2123
|
+
* active connection. Resolves alias → canonical id through the enrichment
|
|
2124
|
+
* map (which is keyed under both `${alias}/${id}` and bare `${id}` — we
|
|
2125
|
+
* walk only the namespaced keys to derive the alias↔canonical mapping).
|
|
2126
|
+
*
|
|
2127
|
+
* Returns:
|
|
2128
|
+
* - `aliases`: set of alias prefixes safe to keep (e.g. `cc`, `gemini`).
|
|
2129
|
+
* - `canonicals`: set of canonical provider ids (e.g. `claude`, `kiro`).
|
|
2130
|
+
*
|
|
2131
|
+
* Callers should treat membership in EITHER set as "usable" — raw model
|
|
2132
|
+
* ids may be `<alias>/<model>` (`cc/claude-opus-4-7`) OR `<canonical>/<model>`
|
|
2133
|
+
* (`claude/sonnet-4`) depending on the OmniRoute deployment's `/v1/models`
|
|
2134
|
+
* surface shape.
|
|
2135
|
+
*
|
|
2136
|
+
* Subtract-filter semantics: callers MUST also keep models whose prefix is
|
|
2137
|
+
* unknown to BOTH `/api/pricing/models` and `/api/providers` (e.g.
|
|
2138
|
+
* agentrouter-style synthetic prefixes). The right boolean is "if I see this
|
|
2139
|
+
* prefix in EITHER catalog table AND it's not usable, drop; otherwise keep".
|
|
2140
|
+
*/
|
|
2141
|
+
export function usableProviderAliasSet(
|
|
2142
|
+
connections: OmniRouteProviderConnection[],
|
|
2143
|
+
enrichment: OmniRouteEnrichmentMap | undefined
|
|
2144
|
+
): {
|
|
2145
|
+
aliases: Set<string>;
|
|
2146
|
+
canonicals: Set<string>;
|
|
2147
|
+
knownAliases: Set<string>;
|
|
2148
|
+
} {
|
|
2149
|
+
const usableCanonicals = new Set<string>();
|
|
2150
|
+
for (const c of connections) {
|
|
2151
|
+
if (!c || c.isActive !== true) continue;
|
|
2152
|
+
if (typeof c.testStatus === "string" && c.testStatus !== "active") continue;
|
|
2153
|
+
if (typeof c.provider === "string" && c.provider.length > 0) {
|
|
2154
|
+
usableCanonicals.add(c.provider);
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
const aliases = new Set<string>();
|
|
2158
|
+
const knownAliases = new Set<string>();
|
|
2159
|
+
if (enrichment) {
|
|
2160
|
+
// Walk enrichment entries to map alias → canonical via the metadata
|
|
2161
|
+
// populated by `defaultOmniRouteEnrichmentFetcher`. Every entry carries
|
|
2162
|
+
// its providerAlias + providerCanonical so the namespaced/bare key
|
|
2163
|
+
// duplication is harmless. Collect EVERY alias we encounter (regardless
|
|
2164
|
+
// of usability) into `knownAliases` so the downstream filter can decide
|
|
2165
|
+
// "this prefix was in /api/pricing/models" in O(1) instead of O(E).
|
|
2166
|
+
for (const entry of enrichment.values()) {
|
|
2167
|
+
const alias = entry.providerAlias;
|
|
2168
|
+
const canonical = entry.providerCanonical;
|
|
2169
|
+
if (typeof alias !== "string" || alias.length === 0) continue;
|
|
2170
|
+
knownAliases.add(alias);
|
|
2171
|
+
if (typeof canonical !== "string" || canonical.length === 0) continue;
|
|
2172
|
+
if (usableCanonicals.has(canonical)) aliases.add(alias);
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
// Always include every usable canonical as an alias too — handles the
|
|
2176
|
+
// common case where `/v1/models` ids use the canonical id directly
|
|
2177
|
+
// (e.g. `gemini/gemini-1.5-pro`).
|
|
2178
|
+
for (const canonical of usableCanonicals) aliases.add(canonical);
|
|
2179
|
+
return { aliases, canonicals: usableCanonicals, knownAliases };
|
|
2180
|
+
}
|
|
2181
|
+
|
|
2182
|
+
/**
|
|
2183
|
+
* Decide whether a raw `/v1/models` id passes the `usableOnly` filter.
|
|
2184
|
+
*
|
|
2185
|
+
* Rules (subtract-filter — bias toward keep):
|
|
2186
|
+
* - id has no `/` → keep (combos/synthetic entries handled separately).
|
|
2187
|
+
* - prefix matches a known usable alias OR canonical → keep.
|
|
2188
|
+
* - prefix is unknown to BOTH the connection table AND the enrichment
|
|
2189
|
+
* map → keep (we can't prove it's NOT usable; could be agentrouter).
|
|
2190
|
+
* - prefix is known to the enrichment map BUT not in usable set → drop.
|
|
2191
|
+
*
|
|
2192
|
+
* Pure function — exported so static + dynamic hooks share the same
|
|
2193
|
+
* verdict logic without divergence.
|
|
2194
|
+
*/
|
|
2195
|
+
export function isUsableRawModelId(
|
|
2196
|
+
id: string,
|
|
2197
|
+
usable: {
|
|
2198
|
+
aliases: Set<string>;
|
|
2199
|
+
canonicals: Set<string>;
|
|
2200
|
+
knownAliases: Set<string>;
|
|
2201
|
+
},
|
|
2202
|
+
enrichment: OmniRouteEnrichmentMap | undefined
|
|
2203
|
+
): boolean {
|
|
2204
|
+
const slash = id.indexOf("/");
|
|
2205
|
+
if (slash <= 0) return true;
|
|
2206
|
+
const prefix = id.slice(0, slash);
|
|
2207
|
+
if (usable.aliases.has(prefix) || usable.canonicals.has(prefix)) return true;
|
|
2208
|
+
// O(1) "known prefix" check via pre-calculated knownAliases set.
|
|
2209
|
+
// If prefix was in /api/pricing/models but is NOT in usable set,
|
|
2210
|
+
// drop the model. Unknown prefixes (e.g. agentrouter-style synthetic)
|
|
2211
|
+
// pass through (subtract-filter semantics).
|
|
2212
|
+
if (usable.knownAliases.has(prefix)) return false;
|
|
2213
|
+
return true;
|
|
2214
|
+
}
|
|
2215
|
+
|
|
2216
|
+
/**
|
|
2217
|
+
* Decide whether a combo passes the `usableOnly` filter. A combo keeps
|
|
2218
|
+
* when AT LEAST ONE of its members maps to a usable canonical provider.
|
|
2219
|
+
* Combos with zero resolvable members pass through (already degraded to
|
|
2220
|
+
* all-false LCD posture and surfaced as cosmetic-only entries).
|
|
2221
|
+
*/
|
|
2222
|
+
export function isUsableCombo(
|
|
2223
|
+
combo: OmniRouteRawCombo,
|
|
2224
|
+
usable: {
|
|
2225
|
+
aliases: Set<string>;
|
|
2226
|
+
canonicals: Set<string>;
|
|
2227
|
+
knownAliases: Set<string>;
|
|
2228
|
+
}
|
|
2229
|
+
): boolean {
|
|
2230
|
+
const steps = Array.isArray(combo.models) ? combo.models : [];
|
|
2231
|
+
if (steps.length === 0) return true;
|
|
2232
|
+
// The provider id is folded INTO the full model string by OmniRoute's
|
|
2233
|
+
// `normalizeComboRecord` (e.g. "cc/claude-opus-4-7") — combo member refs do
|
|
2234
|
+
// NOT carry a separate `providerId` field. Derive the prefix from `step.model`
|
|
2235
|
+
// and apply the same subtract-filter verdict as `isUsableRawModelId`.
|
|
2236
|
+
let sawResolvableMember = false;
|
|
2237
|
+
for (const step of steps) {
|
|
2238
|
+
// Nested combo refs carry no model id we can resolve to a provider here.
|
|
2239
|
+
if (step?.kind === "combo-ref") continue;
|
|
2240
|
+
const modelId = typeof step?.model === "string" ? step.model : "";
|
|
2241
|
+
const slash = modelId.indexOf("/");
|
|
2242
|
+
if (slash <= 0) continue; // no provider prefix to evaluate
|
|
2243
|
+
sawResolvableMember = true;
|
|
2244
|
+
const prefix = modelId.slice(0, slash);
|
|
2245
|
+
if (usable.aliases.has(prefix) || usable.canonicals.has(prefix)) return true;
|
|
2246
|
+
// Unknown prefix (not in the known-alias universe) → can't prove
|
|
2247
|
+
// unroutable; keep. Known-but-not-usable prefixes keep scanning.
|
|
2248
|
+
if (!usable.knownAliases.has(prefix)) return true;
|
|
2249
|
+
}
|
|
2250
|
+
// No member resolved to a provider prefix → can't prove unroutable; keep.
|
|
2251
|
+
if (!sawResolvableMember) return true;
|
|
2252
|
+
// Every resolvable member used a known-but-non-usable prefix → drop.
|
|
2253
|
+
return false;
|
|
2254
|
+
}
|
|
2255
|
+
|
|
2256
|
+
/**
|
|
2257
|
+
* Slugify a combo display name into a copy/paste-friendly URL-safe segment.
|
|
2258
|
+
* Lowercases, replaces any run of non-alphanumeric chars with a single dash,
|
|
2259
|
+
* trims leading/trailing dashes. Empty input or all-special input returns
|
|
2260
|
+
* the empty string (caller must fall back to the combo's UUID id).
|
|
2261
|
+
*
|
|
2262
|
+
* Example: `Claude Tier` → `claude-tier`, `GPT 5.5 / Pro` → `gpt-5-5-pro`.
|
|
2263
|
+
*/
|
|
2264
|
+
export function slugifyComboName(name: string): string {
|
|
2265
|
+
if (typeof name !== "string") return "";
|
|
2266
|
+
return trimLeadingDashes(trimTrailingDashes(name.toLowerCase().replace(/[^a-z0-9]+/g, "-")));
|
|
2267
|
+
}
|
|
2268
|
+
|
|
2269
|
+
/**
|
|
2270
|
+
* Build a combo's static-block key, provider-prefixed as `<providerId>/<slug>`
|
|
2271
|
+
* (e.g. `omniroute/MASTER`, `omniroute/MASTER-LIGHT`), guaranteeing uniqueness
|
|
2272
|
+
* across an entire static catalog. If `<providerId>/<slug>` is already present in
|
|
2273
|
+
* `used`, suffixes a short UUID-prefix disambiguator from `combo.id` so the second
|
|
2274
|
+
* combo doesn't silently overwrite the first. Mutates `used` in place by recording
|
|
2275
|
+
* the chosen key. Returns the final `<providerId>/<slug>` key.
|
|
2276
|
+
*
|
|
2277
|
+
* NOTE: the key MUST carry the OWNING provider prefix (`omniroute/…`), never a
|
|
2278
|
+
* `combo/` namespace — OpenCode parses model IDs on `/` to extract the provider,
|
|
2279
|
+
* so `combo/MASTER` would resolve provider=`combo` (no credentials) and fail with
|
|
2280
|
+
* "Unable to determine provider", whereas `omniroute/MASTER` resolves provider=
|
|
2281
|
+
* `omniroute` and the openai-compatible adapter strips the prefix and sends the
|
|
2282
|
+
* bare slug upstream, which the server resolves via getComboByName. See PR #4184.
|
|
2283
|
+
*
|
|
2284
|
+
* Falls back to `<providerId>/<id>` when the friendly name slugifies to the empty
|
|
2285
|
+
* string (e.g. a combo named just punctuation).
|
|
2286
|
+
*/
|
|
2287
|
+
export function buildComboKey(
|
|
2288
|
+
combo: OmniRouteRawCombo,
|
|
2289
|
+
used: Set<string>,
|
|
2290
|
+
providerId: string
|
|
2291
|
+
): string {
|
|
2292
|
+
const friendlyName = combo.name && combo.name.trim().length > 0 ? combo.name.trim() : combo.id;
|
|
2293
|
+
let slug = slugifyComboName(friendlyName);
|
|
2294
|
+
if (slug.length === 0) slug = combo.id;
|
|
2295
|
+
let key = `${providerId}/${slug}`;
|
|
2296
|
+
if (used.has(key)) {
|
|
2297
|
+
const tail = combo.id.split("-")[0] ?? combo.id;
|
|
2298
|
+
key = `${providerId}/${slug}-${tail}`;
|
|
2299
|
+
// Defensive: in the (impossible) event the disambiguated key also
|
|
2300
|
+
// collides, append the full id.
|
|
2301
|
+
if (used.has(key)) key = `${providerId}/${slug}-${combo.id}`;
|
|
2302
|
+
}
|
|
2303
|
+
used.add(key);
|
|
2304
|
+
return key;
|
|
2305
|
+
}
|
|
2306
|
+
|
|
2307
|
+
/**
|
|
2308
|
+
* Internal cache key: `${baseURL}::sha256(apiKey)`. We hash the apiKey so
|
|
2309
|
+
* the key is safe to log / inspect via debugger without leaking the secret.
|
|
2310
|
+
* Different (baseURL, apiKey) tuples MUST keep independent cache entries:
|
|
2311
|
+
* a single OC user may register prod + preprod OmniRoute side-by-side with
|
|
2312
|
+
* distinct keys, and serving one's catalog from the other's cache would be
|
|
2313
|
+
* a correctness bug, not just a privacy one.
|
|
2314
|
+
*/
|
|
2315
|
+
// codeql[js/insufficient-password-hash]: the input here is an API-key
|
|
2316
|
+
// identifier we use solely to derive an in-memory cache lookup key — it is
|
|
2317
|
+
// never stored, transmitted, compared against a hash, or used as a password.
|
|
2318
|
+
// SHA-256 is intentional: cheap + deterministic, prevents the raw secret
|
|
2319
|
+
// from sitting in memory dumps alongside the cache map. Slow KDFs (bcrypt/
|
|
2320
|
+
// argon2) would defeat the purpose (sub-ms lookups on every request).
|
|
2321
|
+
function modelsCacheKey(baseURL: string, credentialId: string): string {
|
|
2322
|
+
const h = createHash("sha256").update(credentialId).digest("hex");
|
|
2323
|
+
return `${baseURL}::${h}`;
|
|
2324
|
+
}
|
|
2325
|
+
|
|
2326
|
+
/**
|
|
2327
|
+
* Shared fetch-result cache entry. Holds the RAW `/v1/models` + `/api/combos`
|
|
2328
|
+
* responses (NOT a pre-derived ModelV2 / static-entry shape) so the provider
|
|
2329
|
+
* hook (T-03/T-05) and the config-shim hook (T-07) can derive their own
|
|
2330
|
+
* output shapes from the same source without re-fetching.
|
|
2331
|
+
*
|
|
2332
|
+
* Why raw instead of derived:
|
|
2333
|
+
* - provider hook emits ModelV2 (rich nested capabilities + cost + limits).
|
|
2334
|
+
* - config hook emits the stripped sibling shape
|
|
2335
|
+
* (`{name, attachment, reasoning, tool_call, temperature, limit?}`).
|
|
2336
|
+
* - These overlap but neither is a superset of the other (ModelV2 has no
|
|
2337
|
+
* `tool_call` field — it's `toolcall`; the stripped shape has no
|
|
2338
|
+
* `cost`/`status`/`headers`). Caching the raw responses is the only
|
|
2339
|
+
* lossless option.
|
|
2340
|
+
* - On OC ≥1.14.49 cold start BOTH hooks fire within the same
|
|
2341
|
+
* OmniRoutePlugin instance — sharing the cache means /v1/models +
|
|
2342
|
+
* /api/combos each hit the gateway exactly ONCE per TTL refresh, not
|
|
2343
|
+
* twice.
|
|
2344
|
+
*/
|
|
2345
|
+
export interface OmniRouteFetchCacheEntry {
|
|
2346
|
+
rawModels: OmniRouteRawModelEntry[];
|
|
2347
|
+
rawCombos: OmniRouteRawCombo[];
|
|
2348
|
+
rawAutoCombos: OmniRouteRawAutoCombo[];
|
|
2349
|
+
/** Display-name + pricing overlay from /api/pricing/models. Empty Map when feature is disabled or fetch failed. */
|
|
2350
|
+
rawEnrichment: OmniRouteEnrichmentMap;
|
|
2351
|
+
/** Compression combos from /api/context/combos. Empty array when feature is disabled or fetch failed. */
|
|
2352
|
+
rawCompressionCombos: OmniRouteCompressionCombo[];
|
|
2353
|
+
/** Provider connections from /api/providers. Empty array when feature is disabled or fetch failed. */
|
|
2354
|
+
rawConnections: OmniRouteProviderConnection[];
|
|
2355
|
+
expiresAt: number;
|
|
2356
|
+
}
|
|
2357
|
+
|
|
2358
|
+
export type OmniRouteFetchCache = Map<string, OmniRouteFetchCacheEntry>;
|
|
2359
|
+
|
|
2360
|
+
/**
|
|
2361
|
+
* Build the ProviderHook portion of the plugin for a given options bag.
|
|
2362
|
+
* Exported standalone so the contract is unit-testable without faking the
|
|
2363
|
+
* full PluginInput / Hooks surface, and so multi-instance setups can each
|
|
2364
|
+
* own their own cache (a fresh hook closure per plugin tuple).
|
|
2365
|
+
*
|
|
2366
|
+
* Behavioural contract:
|
|
2367
|
+
* - `id` binds to the resolved `providerId` (multi-instance: each plugin
|
|
2368
|
+
* tuple's hook lists models under its own provider id).
|
|
2369
|
+
* - `models(provider, ctx)` extracts the api key from `ctx.auth` (rejecting
|
|
2370
|
+
* non-`api` flavors with `{}` — same posture as the auth loader); calls
|
|
2371
|
+
* both `/v1/models` and `/api/combos` fetchers; maps raw `/v1/models`
|
|
2372
|
+
* entries through `mapRawModelToModelV2`; maps each `/api/combos` entry
|
|
2373
|
+
* through `mapComboToModelV2` (LCD across its member models); merges
|
|
2374
|
+
* combos into the same map under their combo id; caches the unified
|
|
2375
|
+
* result by `(baseURL, sha256(apiKey))` for `modelCacheTtl`.
|
|
2376
|
+
* - **Combo / model ID collisions: combos win.** OmniRoute treats combos
|
|
2377
|
+
* as the curated routing surface; if a combo and a raw model share an
|
|
2378
|
+
* id the operator's intent is clearly the combo. We emit a
|
|
2379
|
+
* `console.warn` exactly once per `(baseURL, apiKey, comboId)`
|
|
2380
|
+
* collision so the operator can spot the unusual naming choice
|
|
2381
|
+
* without log spam on every cache refresh.
|
|
2382
|
+
* - **Combos fetch failure does NOT break the catalog**: soft-fail with
|
|
2383
|
+
* a `console.warn` and fall back to a models-only catalog. Rationale:
|
|
2384
|
+
* `/api/combos` requires a management-scoped key and OmniRoute may
|
|
2385
|
+
* not have any combos provisioned (preprod returned `{combos: []}`
|
|
2386
|
+
* at probe time). Hard-failing the entire catalog when combos are
|
|
2387
|
+
* optional would silently hide the whole provider from OC's model
|
|
2388
|
+
* picker.
|
|
2389
|
+
* - **`/v1/models` fetch failure DOES propagate.** Without models
|
|
2390
|
+
* there's no catalog at all, so an empty `{}` would just mask the
|
|
2391
|
+
* error.
|
|
2392
|
+
* - Cache is in-memory per hook instance, shared between models and
|
|
2393
|
+
* combos (one fetch pair per (baseURL, apiKey) per TTL refresh).
|
|
2394
|
+
*
|
|
2395
|
+
* @param opts Plugin options (providerId, baseURL, modelCacheTtl, …).
|
|
2396
|
+
* @param deps Dependency injection. `fetcher` defaults to the live
|
|
2397
|
+
* `/v1/models` HTTP fetcher; `combosFetcher` defaults to the
|
|
2398
|
+
* live `/api/combos` HTTP fetcher (override for tests / to
|
|
2399
|
+
* disable combos by injecting one that returns `[]`). `now`
|
|
2400
|
+
* defaults to `Date.now` (overridable for TTL tests). `cache`
|
|
2401
|
+
* lets the caller share state across reconstructions (unused
|
|
2402
|
+
* outside tests today).
|
|
2403
|
+
*/
|
|
2404
|
+
export function createOmniRouteProviderHook(
|
|
2405
|
+
opts?: OmniRoutePluginOptions,
|
|
2406
|
+
deps: {
|
|
2407
|
+
fetcher?: OmniRouteModelsFetcher;
|
|
2408
|
+
combosFetcher?: OmniRouteCombosFetcher;
|
|
2409
|
+
autoCombosFetcher?: OmniRouteAutoCombosFetcher;
|
|
2410
|
+
enrichmentFetcher?: OmniRouteEnrichmentFetcher;
|
|
2411
|
+
compressionMetaFetcher?: OmniRouteCompressionMetaFetcher;
|
|
2412
|
+
providersFetcher?: OmniRouteProvidersFetcher;
|
|
2413
|
+
now?: () => number;
|
|
2414
|
+
cache?: OmniRouteFetchCache;
|
|
2415
|
+
} = {}
|
|
2416
|
+
): ProviderHook {
|
|
2417
|
+
const resolved = resolveOmniRoutePluginOptions(opts);
|
|
2418
|
+
const fetcher = deps.fetcher ?? defaultOmniRouteModelsFetcher;
|
|
2419
|
+
// T-05: combo discovery merges `/api/combos` entries into the same map as
|
|
2420
|
+
// `/v1/models`. Default fetcher is declared further down the file; the
|
|
2421
|
+
// reference resolves at hook-invocation time, not at hook-construction
|
|
2422
|
+
// time, so source-order beyond hoisting rules has no semantic effect.
|
|
2423
|
+
const combosFetcher = deps.combosFetcher ?? defaultOmniRouteCombosFetcher;
|
|
2424
|
+
const autoCombosFetcher = deps.autoCombosFetcher ?? defaultOmniRouteAutoCombosFetcher;
|
|
2425
|
+
const enrichmentFetcher = deps.enrichmentFetcher ?? defaultOmniRouteEnrichmentFetcher;
|
|
2426
|
+
const compressionMetaFetcher =
|
|
2427
|
+
deps.compressionMetaFetcher ?? defaultOmniRouteCompressionMetaFetcher;
|
|
2428
|
+
const providersFetcher = deps.providersFetcher ?? defaultOmniRouteProvidersFetcher;
|
|
2429
|
+
// Features defaults (mirror v0.1.0 behavior when unset).
|
|
2430
|
+
const features = resolved.features ?? {};
|
|
2431
|
+
const wantCombos = features.combos !== false;
|
|
2432
|
+
const wantAutoCombos = features.autoCombos !== false;
|
|
2433
|
+
const wantEnrichment = features.enrichment !== false;
|
|
2434
|
+
const wantCompressionMeta = features.compressionMetadata === true;
|
|
2435
|
+
const wantUsableOnly = features.usableOnly === true;
|
|
2436
|
+
const wantProviderTag = features.providerTag !== false;
|
|
2437
|
+
const now = deps.now ?? Date.now;
|
|
2438
|
+
// T-07: cache holds RAW fetch results (not pre-derived ModelV2) so that
|
|
2439
|
+
// the config-shim hook can share the same cache and derive its stripped
|
|
2440
|
+
// sibling shape from the same source without a second round-trip.
|
|
2441
|
+
const cache: OmniRouteFetchCache = deps.cache ?? new Map();
|
|
2442
|
+
// T-05: collision-warning deduper. Emit warn once per (cacheKey, comboId)
|
|
2443
|
+
// tuple per hook instance so the operator sees the unusual naming choice
|
|
2444
|
+
// once per session, not once per cache refresh.
|
|
2445
|
+
const collisionWarned = new Set<string>();
|
|
2446
|
+
|
|
2447
|
+
return {
|
|
2448
|
+
id: resolved.providerId,
|
|
2449
|
+
async models(_provider, ctx) {
|
|
2450
|
+
// Auth narrowing — same posture as the auth loader (T-02). Non-api
|
|
2451
|
+
// flavors and empty keys → empty catalog. OC then exposes the
|
|
2452
|
+
// /connect flow rather than spamming /v1/models with bad creds.
|
|
2453
|
+
const auth = ctx?.auth;
|
|
2454
|
+
if (
|
|
2455
|
+
!auth ||
|
|
2456
|
+
typeof auth !== "object" ||
|
|
2457
|
+
(auth as { type?: unknown }).type !== "api" ||
|
|
2458
|
+
typeof (auth as { key?: unknown }).key !== "string" ||
|
|
2459
|
+
(auth as { key: string }).key.length === 0
|
|
2460
|
+
) {
|
|
2461
|
+
return {};
|
|
2462
|
+
}
|
|
2463
|
+
const apiKey = (auth as { key: string }).key;
|
|
2464
|
+
|
|
2465
|
+
// baseURL resolution: plugin opts first, then credential-attached
|
|
2466
|
+
// baseURL (auth backends sometimes stash it next to the key), then the
|
|
2467
|
+
// provider config itself — a baseURL set via opencode.json provider
|
|
2468
|
+
// options (or a config hook) lands on `provider.options` and is not
|
|
2469
|
+
// visible through either of the first two links. No silent default to
|
|
2470
|
+
// localhost: a misconfigured plugin should surface a clear warning,
|
|
2471
|
+
// not phantom /v1/models calls. Cast through unknown because the Auth
|
|
2472
|
+
// union (OAuth | ApiAuth | WellKnownAuth) doesn't declare baseURL on
|
|
2473
|
+
// any branch — we duck-type it as a defensive extension point.
|
|
2474
|
+
const authBaseURL = (auth as unknown as { baseURL?: unknown }).baseURL;
|
|
2475
|
+
const providerBaseURL = (_provider as { options?: { baseURL?: unknown } } | undefined)
|
|
2476
|
+
?.options?.baseURL;
|
|
2477
|
+
const baseURL =
|
|
2478
|
+
resolved.baseURL ??
|
|
2479
|
+
(typeof authBaseURL === "string" && authBaseURL.length > 0 ? authBaseURL : undefined) ??
|
|
2480
|
+
(typeof providerBaseURL === "string" && providerBaseURL.length > 0
|
|
2481
|
+
? providerBaseURL
|
|
2482
|
+
: undefined) ??
|
|
2483
|
+
"";
|
|
2484
|
+
if (!baseURL) {
|
|
2485
|
+
console.warn(
|
|
2486
|
+
`[omniroute-plugin] provider.models(${resolved.providerId}): ` +
|
|
2487
|
+
`no baseURL resolvable — checked plugin opts, auth.json, and provider config. ` +
|
|
2488
|
+
`Set baseURL in opencode.json plugin options or run \`opencode connect ${resolved.providerId}\` with a baseURL.`
|
|
2489
|
+
);
|
|
2490
|
+
return {};
|
|
2491
|
+
}
|
|
2492
|
+
|
|
2493
|
+
const cacheKey = modelsCacheKey(baseURL, apiKey);
|
|
2494
|
+
const t = now();
|
|
2495
|
+
const cached = cache.get(cacheKey);
|
|
2496
|
+
|
|
2497
|
+
let rawModels: OmniRouteRawModelEntry[];
|
|
2498
|
+
let rawCombos: OmniRouteRawCombo[];
|
|
2499
|
+
let rawAutoCombos: OmniRouteRawAutoCombo[];
|
|
2500
|
+
let rawEnrichment: OmniRouteEnrichmentMap;
|
|
2501
|
+
let rawCompressionCombos: OmniRouteCompressionCombo[];
|
|
2502
|
+
let rawConnections: OmniRouteProviderConnection[];
|
|
2503
|
+
if (cached && cached.expiresAt > t) {
|
|
2504
|
+
rawModels = cached.rawModels;
|
|
2505
|
+
rawCombos = cached.rawCombos;
|
|
2506
|
+
rawAutoCombos = cached.rawAutoCombos;
|
|
2507
|
+
rawEnrichment = cached.rawEnrichment;
|
|
2508
|
+
rawCompressionCombos = cached.rawCompressionCombos;
|
|
2509
|
+
rawConnections = cached.rawConnections;
|
|
2510
|
+
} else {
|
|
2511
|
+
// Models fetch is required (no catalog otherwise → silent provider
|
|
2512
|
+
// disappearance). We do NOT wrap this in a try; let the error
|
|
2513
|
+
// propagate to OC's UI.
|
|
2514
|
+
rawModels = await fetcher(baseURL, apiKey, 10_000);
|
|
2515
|
+
|
|
2516
|
+
// T-05: combos fetch is best-effort, gated by features.combos.
|
|
2517
|
+
// Soft-fail on any error: emit a console.warn and fall back to a
|
|
2518
|
+
// models-only catalog. Rationale: /api/combos requires a
|
|
2519
|
+
// management-scoped key and OmniRoute may not have any combos
|
|
2520
|
+
// provisioned. Hard-failing when combos are optional would
|
|
2521
|
+
// silently hide the whole provider from OC's picker.
|
|
2522
|
+
rawCombos = [];
|
|
2523
|
+
if (wantCombos) {
|
|
2524
|
+
try {
|
|
2525
|
+
rawCombos = await combosFetcher(baseURL, apiKey, 10_000);
|
|
2526
|
+
} catch (err) {
|
|
2527
|
+
console.warn(
|
|
2528
|
+
"[omniroute-plugin] combos fetch failed, falling back to models-only catalog",
|
|
2529
|
+
err
|
|
2530
|
+
);
|
|
2531
|
+
}
|
|
2532
|
+
}
|
|
2533
|
+
|
|
2534
|
+
// Auto combos fetch — virtual server-side combos. Best-effort,
|
|
2535
|
+
// gated by features.autoCombos. Soft-fails silently (the endpoint
|
|
2536
|
+
// may not exist yet on older OmniRoute versions).
|
|
2537
|
+
rawAutoCombos = [];
|
|
2538
|
+
if (wantAutoCombos) {
|
|
2539
|
+
try {
|
|
2540
|
+
rawAutoCombos = await autoCombosFetcher(baseURL, apiKey, 5_000);
|
|
2541
|
+
} catch {
|
|
2542
|
+
// Already handled inside the default fetcher — this catch
|
|
2543
|
+
// is belt-and-suspenders for injected stubs.
|
|
2544
|
+
}
|
|
2545
|
+
}
|
|
2546
|
+
|
|
2547
|
+
// Enrichment fetch (nice names + pricing). Best-effort, gated by
|
|
2548
|
+
// features.enrichment. Soft-fails to empty map.
|
|
2549
|
+
rawEnrichment = new Map();
|
|
2550
|
+
if (wantEnrichment) {
|
|
2551
|
+
try {
|
|
2552
|
+
rawEnrichment = await enrichmentFetcher(baseURL, apiKey, 10_000);
|
|
2553
|
+
} catch (err) {
|
|
2554
|
+
console.warn(
|
|
2555
|
+
"[omniroute-plugin] enrichment fetch failed, falling back to raw ids",
|
|
2556
|
+
err
|
|
2557
|
+
);
|
|
2558
|
+
}
|
|
2559
|
+
}
|
|
2560
|
+
|
|
2561
|
+
// Compression metadata fetch. Off by default, gated by
|
|
2562
|
+
// features.compressionMetadata. Soft-fails to empty array.
|
|
2563
|
+
rawCompressionCombos = [];
|
|
2564
|
+
if (wantCompressionMeta) {
|
|
2565
|
+
try {
|
|
2566
|
+
rawCompressionCombos = await compressionMetaFetcher(baseURL, apiKey, 10_000);
|
|
2567
|
+
} catch (err) {
|
|
2568
|
+
console.warn("[omniroute-plugin] compression-metadata fetch failed", err);
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2571
|
+
|
|
2572
|
+
// Provider-connections fetch. Off by default, gated by
|
|
2573
|
+
// features.usableOnly. Soft-fails to empty array — when the
|
|
2574
|
+
// connection table is unreadable we skip the filter entirely
|
|
2575
|
+
// (subtract-filter semantics: don't drop everything we couldn't
|
|
2576
|
+
// verify).
|
|
2577
|
+
rawConnections = [];
|
|
2578
|
+
if (wantUsableOnly) {
|
|
2579
|
+
try {
|
|
2580
|
+
rawConnections = await providersFetcher(baseURL, apiKey, 10_000);
|
|
2581
|
+
} catch (err) {
|
|
2582
|
+
console.warn(
|
|
2583
|
+
"[omniroute-plugin] /api/providers fetch failed; usableOnly filter disabled for this refresh",
|
|
2584
|
+
err
|
|
2585
|
+
);
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
|
|
2589
|
+
cache.set(cacheKey, {
|
|
2590
|
+
rawModels,
|
|
2591
|
+
rawCombos,
|
|
2592
|
+
rawAutoCombos,
|
|
2593
|
+
rawEnrichment,
|
|
2594
|
+
rawCompressionCombos,
|
|
2595
|
+
rawConnections,
|
|
2596
|
+
expiresAt: t + resolved.modelCacheTtl,
|
|
2597
|
+
});
|
|
2598
|
+
|
|
2599
|
+
// Debug breadcrumb: surface fetch result so operators can confirm
|
|
2600
|
+
// the dynamic pipeline fired and how much catalog OmniRoute returned.
|
|
2601
|
+
// Emitted once per cache miss (TTL refresh) — quiet on cache hits.
|
|
2602
|
+
console.warn(
|
|
2603
|
+
`[omniroute-plugin] catalog refreshed for providerId=${resolved.providerId} baseURL=${baseURL}: ` +
|
|
2604
|
+
`${rawModels.length} models + ${rawCombos.length} combos + ` +
|
|
2605
|
+
`${rawEnrichment.size} enrichment entries + ` +
|
|
2606
|
+
`${rawCompressionCombos.length} compression combos + ` +
|
|
2607
|
+
`${rawConnections.length} connections ` +
|
|
2608
|
+
`(TTL=${resolved.modelCacheTtl}ms)`
|
|
2609
|
+
);
|
|
2610
|
+
|
|
2611
|
+
// ── Startup debug: deep-dive into enrichment + auto combos ──────
|
|
2612
|
+
if (resolved.features?.startupDebug === true) {
|
|
2613
|
+
await writeStartupDiagnostics({
|
|
2614
|
+
providerId: resolved.providerId,
|
|
2615
|
+
baseURL,
|
|
2616
|
+
modelCount: rawModels.length,
|
|
2617
|
+
comboCount: rawCombos.length,
|
|
2618
|
+
enrichmentSize: rawEnrichment.size,
|
|
2619
|
+
autoComboCount: rawAutoCombos.length,
|
|
2620
|
+
enrichment: rawEnrichment,
|
|
2621
|
+
autoCombos: rawAutoCombos,
|
|
2622
|
+
});
|
|
2623
|
+
}
|
|
2624
|
+
}
|
|
2625
|
+
|
|
2626
|
+
// Lookup index for LCD member resolution: O(1) per member lookup.
|
|
2627
|
+
// Indexed by raw model `id` — combo steps reference this exact
|
|
2628
|
+
// string per ComboModelStep in src/lib/combos/steps.ts.
|
|
2629
|
+
const rawModelById = new Map<string, OmniRouteRawModelEntry>();
|
|
2630
|
+
for (const entry of rawModels) {
|
|
2631
|
+
if (entry.id) rawModelById.set(entry.id, entry);
|
|
2632
|
+
}
|
|
2633
|
+
|
|
2634
|
+
// usableOnly filter — compute the set of usable alias prefixes once
|
|
2635
|
+
// per refresh. Empty when feature is off OR connection fetch failed
|
|
2636
|
+
// OR no connections returned, in which case we keep everything
|
|
2637
|
+
// (subtract-filter semantics: only drop when we can prove a prefix
|
|
2638
|
+
// is NOT usable; never hide the catalog on a soft-fail).
|
|
2639
|
+
const usable =
|
|
2640
|
+
wantUsableOnly && rawConnections.length > 0
|
|
2641
|
+
? usableProviderAliasSet(rawConnections, rawEnrichment)
|
|
2642
|
+
: undefined;
|
|
2643
|
+
|
|
2644
|
+
// Build the canonical→alias reverse map AND the canonical-dedup
|
|
2645
|
+
// set once per refresh. Together they fix the dual-keyed
|
|
2646
|
+
// `/v1/models` problem where the same model surfaces under BOTH
|
|
2647
|
+
// `<alias>/<id>` (enriched) AND `<canonical>/<id>` (raw): we keep
|
|
2648
|
+
// the alias key and skip the canonical twin entirely.
|
|
2649
|
+
const canonicalToAlias = buildCanonicalToAliasMap(rawEnrichment);
|
|
2650
|
+
const canonicalDedup = canonicalDedupSet(rawModels, canonicalToAlias);
|
|
2651
|
+
const aliasIndex = buildAliasIndex(rawEnrichment);
|
|
2652
|
+
|
|
2653
|
+
// Map raw models → ModelV2 keyed by id. When enrichment data is
|
|
2654
|
+
// present (features.enrichment, default on), overlay the nicer
|
|
2655
|
+
// display name + pricing from /api/pricing/models via the
|
|
2656
|
+
// alias-fallback lookup chain (covers canonical rows lacking
|
|
2657
|
+
// direct pricing entries).
|
|
2658
|
+
const models: Record<string, ModelV2> = {};
|
|
2659
|
+
for (const entry of rawModels) {
|
|
2660
|
+
if (!entry.id) continue;
|
|
2661
|
+
if (canonicalDedup.has(entry.id)) continue;
|
|
2662
|
+
if (usable && !isUsableRawModelId(entry.id, usable, rawEnrichment)) continue;
|
|
2663
|
+
const model = mapRawModelToModelV2(entry, {
|
|
2664
|
+
providerId: resolved.providerId,
|
|
2665
|
+
baseURL,
|
|
2666
|
+
apiFormat: resolved.features?.apiFormat,
|
|
2667
|
+
});
|
|
2668
|
+
const enrichEntry = lookupEnrichment(entry.id, rawEnrichment, canonicalToAlias);
|
|
2669
|
+
applyEnrichment(model, enrichEntry);
|
|
2670
|
+
// Prepend upstream provider label (e.g. `Claude - Claude Opus 4.7`)
|
|
2671
|
+
// so the picker groups same-model rows by upstream connection.
|
|
2672
|
+
// Idempotent + gated by `features.providerTag` (default-on).
|
|
2673
|
+
// Combos skip this on purpose. The alias-index fallback rescues
|
|
2674
|
+
// raw rows like `cohere/rerank-multilingual-v3.0` whose specific
|
|
2675
|
+
// model id isn't in `/api/pricing/models` but whose slot is.
|
|
2676
|
+
if (wantProviderTag) {
|
|
2677
|
+
const tagEntry = resolveProviderTagEntry(
|
|
2678
|
+
entry.id,
|
|
2679
|
+
enrichEntry,
|
|
2680
|
+
aliasIndex,
|
|
2681
|
+
canonicalToAlias
|
|
2682
|
+
);
|
|
2683
|
+
applyProviderTag(model, tagEntry);
|
|
2684
|
+
}
|
|
2685
|
+
// OC's static-catalog reader parses the key on `/` to recover
|
|
2686
|
+
// (providerID, modelID). `mapRawModelToModelV2` already stamps the
|
|
2687
|
+
// prefixed id on `model.id` (e.g. `omniroute/claude-primary`), so we
|
|
2688
|
+
// must key by `model.id` — not by the raw `entry.id` which would be
|
|
2689
|
+
// a bare slug and parse as `providerID=slug, modelID=""`.
|
|
2690
|
+
models[model.id] = model;
|
|
2691
|
+
}
|
|
2692
|
+
|
|
2693
|
+
// Default compression combo (used to decorate ALL combo names when
|
|
2694
|
+
// compression metadata is present). OmniRoute returns at most one
|
|
2695
|
+
// entry with `isDefault: true` per /api/context/combos.
|
|
2696
|
+
const defaultCompression = wantCompressionMeta
|
|
2697
|
+
? rawCompressionCombos.find((c) => c.isDefault === true)
|
|
2698
|
+
: undefined;
|
|
2699
|
+
|
|
2700
|
+
// T-05: map raw combos → ModelV2. Skip hidden combos (operator
|
|
2701
|
+
// preference — provisioned but intentionally not surfaced).
|
|
2702
|
+
// Resolve each combo's member step list into the matching raw
|
|
2703
|
+
// model entries; unknown member ids are silently dropped before
|
|
2704
|
+
// mapComboToModelV2 sees them, which then degrades to the
|
|
2705
|
+
// all-false LCD posture if zero members remain.
|
|
2706
|
+
//
|
|
2707
|
+
// Combos are keyed under the `combo/<slug>` namespace so the TUI
|
|
2708
|
+
// picker separates them from provider/model pairs and the UUID
|
|
2709
|
+
// never surfaces. This mirrors `buildStaticProviderEntry` so the
|
|
2710
|
+
// static + dynamic catalogs publish identical keys.
|
|
2711
|
+
const comboNames = new Set<string>();
|
|
2712
|
+
for (const combo of rawCombos) {
|
|
2713
|
+
if (!combo || combo.isHidden === true) continue;
|
|
2714
|
+
const n = combo.name && combo.name.trim().length > 0 ? combo.name.trim() : combo.id;
|
|
2715
|
+
if (typeof n === "string" && n.length > 0) comboNames.add(n);
|
|
2716
|
+
}
|
|
2717
|
+
for (const key of Object.keys(models)) {
|
|
2718
|
+
if (comboNames.has(key)) delete models[key];
|
|
2719
|
+
}
|
|
2720
|
+
|
|
2721
|
+
// ── Combo LCD across nested combo-refs (T-NN) ───────────────────────
|
|
2722
|
+
// Combos can nest other combos via `kind: "combo-ref"` members
|
|
2723
|
+
// (e.g. MASTER-LIGHT contains OldLLM, KIRO, Opecode Zen FREE). The
|
|
2724
|
+
// nested combo's own `limit.context` is computed below in this same
|
|
2725
|
+
// loop, so we need a fixpoint iteration: if a combo-ref points at a
|
|
2726
|
+
// combo not yet processed, defer this combo and try again after the
|
|
2727
|
+
// sibling combos catch up. We bound the retries so a circular combo
|
|
2728
|
+
// graph can't deadlock the picker.
|
|
2729
|
+
const MAX_COMBO_PASSES = 8;
|
|
2730
|
+
const usedComboKeys = new Set<string>();
|
|
2731
|
+
// Combos in `rawCombos` that still need (re)processing this round.
|
|
2732
|
+
// Shrinks as combos resolve.
|
|
2733
|
+
let pending = rawCombos.filter((combo) => {
|
|
2734
|
+
if (!combo.id) return false;
|
|
2735
|
+
if (combo.isHidden === true) return false;
|
|
2736
|
+
if (usable && !isUsableCombo(combo, usable)) return false;
|
|
2737
|
+
return true;
|
|
2738
|
+
});
|
|
2739
|
+
// Resolved nested combos keyed by their friendly name, so parent
|
|
2740
|
+
// combos that reference them via combo-ref can lift the full
|
|
2741
|
+
// capability vector (not just the context window) into their own
|
|
2742
|
+
// LCD pass.
|
|
2743
|
+
const resolvedComboModelsByName = new Map<string, ModelV2>();
|
|
2744
|
+
|
|
2745
|
+
for (let pass = 0; pass < MAX_COMBO_PASSES && pending.length > 0; pass++) {
|
|
2746
|
+
const stillPending: typeof pending = [];
|
|
2747
|
+
for (const combo of pending) {
|
|
2748
|
+
const memberSteps = Array.isArray(combo.models) ? combo.models : [];
|
|
2749
|
+
const memberEntries: OmniRouteRawModelEntry[] = [];
|
|
2750
|
+
let deferredThisPass = false;
|
|
2751
|
+
|
|
2752
|
+
for (const step of memberSteps) {
|
|
2753
|
+
// Unknown-bridge: ComboMemberRef's DTS type only declares
|
|
2754
|
+
// `model?: string`, so verify the runtime shape before reading
|
|
2755
|
+
// either `model` (raw member) or `comboName` (nested combo).
|
|
2756
|
+
const stepKind = (step as unknown as { kind?: unknown }).kind;
|
|
2757
|
+
|
|
2758
|
+
if (stepKind === "combo-ref") {
|
|
2759
|
+
const comboName = (step as unknown as { comboName?: unknown }).comboName;
|
|
2760
|
+
if (typeof comboName !== "string" || comboName.length === 0) {
|
|
2761
|
+
continue;
|
|
2762
|
+
}
|
|
2763
|
+
const nestedModel = resolvedComboModelsByName.get(comboName);
|
|
2764
|
+
if (!nestedModel) {
|
|
2765
|
+
// Nested combo hasn't been processed yet. Defer this
|
|
2766
|
+
// combo to the next pass.
|
|
2767
|
+
deferredThisPass = true;
|
|
2768
|
+
break;
|
|
2769
|
+
}
|
|
2770
|
+
// Synthesize a member entry that contributes only the
|
|
2771
|
+
// nested combo's pre-computed context_length + max_output.
|
|
2772
|
+
// Other capability axes default conservatively (no tool
|
|
2773
|
+
// calls, no vision) — a nested combo's modalities are an
|
|
2774
|
+
// OR, but if we let raw-model defaults leak in we'd
|
|
2775
|
+
// over-claim. The combo's own LCD (computed by
|
|
2776
|
+
// mapComboToModelV2 from the synthesized entries) will only
|
|
2777
|
+
// further restrict capabilities, so this is safe.
|
|
2778
|
+
// Synthesize a member entry carrying the nested combo's
|
|
2779
|
+
// pre-computed context + capabilities + modalities so the
|
|
2780
|
+
// parent combo's LCD is accurate across the whole graph
|
|
2781
|
+
// (not just its direct raw-model members).
|
|
2782
|
+
const inputModalities: string[] = [];
|
|
2783
|
+
if (nestedModel.capabilities.input.text) inputModalities.push("text");
|
|
2784
|
+
if (nestedModel.capabilities.input.audio) inputModalities.push("audio");
|
|
2785
|
+
if (nestedModel.capabilities.input.image) inputModalities.push("image");
|
|
2786
|
+
if (nestedModel.capabilities.input.video) inputModalities.push("video");
|
|
2787
|
+
if (nestedModel.capabilities.input.pdf) inputModalities.push("pdf");
|
|
2788
|
+
|
|
2789
|
+
const outputModalities: string[] = [];
|
|
2790
|
+
if (nestedModel.capabilities.output.text) outputModalities.push("text");
|
|
2791
|
+
if (nestedModel.capabilities.output.audio) outputModalities.push("audio");
|
|
2792
|
+
if (nestedModel.capabilities.output.image) outputModalities.push("image");
|
|
2793
|
+
if (nestedModel.capabilities.output.video) outputModalities.push("video");
|
|
2794
|
+
if (nestedModel.capabilities.output.pdf) outputModalities.push("pdf");
|
|
2795
|
+
|
|
2796
|
+
memberEntries.push({
|
|
2797
|
+
id: `combo-ref:${comboName}`,
|
|
2798
|
+
context_length: nestedModel.limit.context,
|
|
2799
|
+
max_output_tokens: nestedModel.limit.output,
|
|
2800
|
+
max_input_tokens: nestedModel.limit.input ?? 0,
|
|
2801
|
+
owned_by: "combo",
|
|
2802
|
+
input_modalities: inputModalities,
|
|
2803
|
+
output_modalities: outputModalities,
|
|
2804
|
+
capabilities: {
|
|
2805
|
+
temperature: nestedModel.capabilities.temperature,
|
|
2806
|
+
reasoning: nestedModel.capabilities.reasoning,
|
|
2807
|
+
thinking: nestedModel.capabilities.interleaved,
|
|
2808
|
+
attachment: nestedModel.capabilities.attachment,
|
|
2809
|
+
tool_calling: nestedModel.capabilities.toolcall,
|
|
2810
|
+
},
|
|
2811
|
+
} as unknown as OmniRouteRawModelEntry);
|
|
2812
|
+
continue;
|
|
2813
|
+
}
|
|
2814
|
+
|
|
2815
|
+
const modelId = (step as unknown as { model?: unknown }).model;
|
|
2816
|
+
if (typeof modelId !== "string" || modelId.length === 0) continue;
|
|
2817
|
+
const member = rawModelById.get(modelId);
|
|
2818
|
+
if (member) memberEntries.push(member);
|
|
2819
|
+
}
|
|
2820
|
+
|
|
2821
|
+
if (deferredThisPass) {
|
|
2822
|
+
stillPending.push(combo);
|
|
2823
|
+
continue;
|
|
2824
|
+
}
|
|
2825
|
+
|
|
2826
|
+
const mapped = mapComboToModelV2(
|
|
2827
|
+
combo,
|
|
2828
|
+
memberEntries,
|
|
2829
|
+
resolved.providerId,
|
|
2830
|
+
baseURL,
|
|
2831
|
+
features.apiFormat
|
|
2832
|
+
);
|
|
2833
|
+
const hasMembers = memberEntries.length > 0;
|
|
2834
|
+
|
|
2835
|
+
// Apply enrichment overlay to combos too (OmniRoute's
|
|
2836
|
+
// /api/pricing/models surfaces combos alongside provider-scoped
|
|
2837
|
+
// models with curated names).
|
|
2838
|
+
applyEnrichment(mapped, rawEnrichment.get(combo.id));
|
|
2839
|
+
|
|
2840
|
+
// unroutable combo would mislead the picker.
|
|
2841
|
+
if (hasMembers && defaultCompression && defaultCompression.pipeline.length > 0) {
|
|
2842
|
+
const tag = formatCompressionPipeline(defaultCompression.pipeline);
|
|
2843
|
+
if (tag.length > 0 && !mapped.name.includes(tag)) {
|
|
2844
|
+
mapped.name = `${mapped.name} ${tag}`;
|
|
2845
|
+
}
|
|
2846
|
+
}
|
|
2847
|
+
|
|
2848
|
+
const comboKey = buildComboKey(combo, usedComboKeys, resolved.providerId);
|
|
2849
|
+
|
|
2850
|
+
// Collision policy: combos win. Warn ONCE per (cacheKey, comboKey)
|
|
2851
|
+
// when overwriting a same-key raw model so the operator can spot
|
|
2852
|
+
// the unusual naming choice without log spam. Suppress the warning
|
|
2853
|
+
// when the collision is the intentional dedup pattern (combo.name
|
|
2854
|
+
// exactly matches an existing raw model's id) — /v1/models
|
|
2855
|
+
// pre-mirrors combos as raw entries and the operator's intent is
|
|
2856
|
+
// always "combo wins" in that case.
|
|
2857
|
+
if (Object.prototype.hasOwnProperty.call(models, comboKey)) {
|
|
2858
|
+
const existing = models[comboKey];
|
|
2859
|
+
// Intentional dedup: `/v1/models` pre-mirrors combos as raw
|
|
2860
|
+
// entries, so the bare combo name appears as the model id in
|
|
2861
|
+
// `rawModels`. After our prefixing the existing entry's id is
|
|
2862
|
+
// `${providerId}/${raw.id}` — the combo name is a substring of
|
|
2863
|
+
// that prefixed id (or, for already-prefixed raw models, the
|
|
2864
|
+
// exact id). Use `endsWith` to avoid matching substrings of
|
|
2865
|
+
// unrelated prefixed ids.
|
|
2866
|
+
const isIntentionalDedup =
|
|
2867
|
+
existing &&
|
|
2868
|
+
combo.name &&
|
|
2869
|
+
combo.name.trim().length > 0 &&
|
|
2870
|
+
(existing.id === combo.name.trim() || existing.id.endsWith(`/${combo.name.trim()}`));
|
|
2871
|
+
if (!isIntentionalDedup) {
|
|
2872
|
+
const dedupeKey = `${cacheKey}::${comboKey}`;
|
|
2873
|
+
if (!collisionWarned.has(dedupeKey)) {
|
|
2874
|
+
collisionWarned.add(dedupeKey);
|
|
2875
|
+
console.warn(
|
|
2876
|
+
`[omniroute-plugin] combo key "${comboKey}" collides with a model id; combo wins.`
|
|
2877
|
+
);
|
|
2878
|
+
}
|
|
2879
|
+
}
|
|
2880
|
+
}
|
|
2881
|
+
models[comboKey] = mapped;
|
|
2882
|
+
|
|
2883
|
+
// Make this combo's resolved model available to parent combos
|
|
2884
|
+
// that reference it via combo-ref. Use the friendly name
|
|
2885
|
+
// (combo.name) since that's the lookup key on the parent side.
|
|
2886
|
+
const lookupName =
|
|
2887
|
+
combo.name && combo.name.trim().length > 0 ? combo.name.trim() : combo.id;
|
|
2888
|
+
resolvedComboModelsByName.set(lookupName, mapped);
|
|
2889
|
+
}
|
|
2890
|
+
if (stillPending.length === pending.length) break;
|
|
2891
|
+
pending = stillPending;
|
|
2892
|
+
}
|
|
2893
|
+
|
|
2894
|
+
if (pending.length > 0) {
|
|
2895
|
+
console.warn(
|
|
2896
|
+
`[omniroute-plugin] ${pending.length} combo(s) could not resolve all nested combo-refs after ${MAX_COMBO_PASSES} passes; they will advertise context=0 to avoid over-claiming.`
|
|
2897
|
+
);
|
|
2898
|
+
}
|
|
2899
|
+
|
|
2900
|
+
// ── Auto combos in dynamic catalog ────────────────────────────────
|
|
2901
|
+
// Convert virtual auto combos from /api/combos/auto into ModelV2
|
|
2902
|
+
// entries so they appear in the dynamic provider.models() path
|
|
2903
|
+
// (used by OpenCode ≥1.14.49).
|
|
2904
|
+
if (rawAutoCombos.length > 0) {
|
|
2905
|
+
for (const autoCombo of rawAutoCombos) {
|
|
2906
|
+
if (!autoCombo || !autoCombo.id) continue;
|
|
2907
|
+
if (autoCombo.isHidden === true) continue;
|
|
2908
|
+
const entry = mapAutoComboToStaticEntry(autoCombo);
|
|
2909
|
+
const key = autoComboModelId(autoCombo.variant);
|
|
2910
|
+
const mapped: ModelV2 = {
|
|
2911
|
+
id: key,
|
|
2912
|
+
name: entry.name,
|
|
2913
|
+
capabilities: {
|
|
2914
|
+
temperature: entry.temperature ?? true,
|
|
2915
|
+
reasoning: entry.reasoning ?? false,
|
|
2916
|
+
attachment: entry.attachment ?? false,
|
|
2917
|
+
toolcall: entry.tool_call ?? false,
|
|
2918
|
+
input: {
|
|
2919
|
+
text: true,
|
|
2920
|
+
audio: false,
|
|
2921
|
+
image: false,
|
|
2922
|
+
video: false,
|
|
2923
|
+
pdf: false,
|
|
2924
|
+
},
|
|
2925
|
+
output: {
|
|
2926
|
+
text: true,
|
|
2927
|
+
audio: false,
|
|
2928
|
+
image: false,
|
|
2929
|
+
video: false,
|
|
2930
|
+
pdf: false,
|
|
2931
|
+
},
|
|
2932
|
+
interleaved: false,
|
|
2933
|
+
},
|
|
2934
|
+
cost: {
|
|
2935
|
+
input: 0,
|
|
2936
|
+
output: 0,
|
|
2937
|
+
cache: { read: 0, write: 0 },
|
|
2938
|
+
},
|
|
2939
|
+
limit: {
|
|
2940
|
+
context: entry.limit?.context ?? 0,
|
|
2941
|
+
output: entry.limit?.output ?? 0,
|
|
2942
|
+
},
|
|
2943
|
+
api: {
|
|
2944
|
+
id: "openai-compatible",
|
|
2945
|
+
url: ensureV1Suffix(baseURL),
|
|
2946
|
+
npm: "@ai-sdk/openai-compatible",
|
|
2947
|
+
},
|
|
2948
|
+
status: "active",
|
|
2949
|
+
release_date: "",
|
|
2950
|
+
providerID: resolved.providerId,
|
|
2951
|
+
options: {},
|
|
2952
|
+
headers: {},
|
|
2953
|
+
};
|
|
2954
|
+
models[key] = mapped;
|
|
2955
|
+
}
|
|
2956
|
+
}
|
|
2957
|
+
|
|
2958
|
+
return models;
|
|
2959
|
+
},
|
|
2960
|
+
};
|
|
2961
|
+
}
|
|
2962
|
+
|
|
2963
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
2964
|
+
// Fetch interceptor (T-04) — Bearer + Content-Type injection on outbound
|
|
2965
|
+
// provider requests targeting the configured OmniRoute baseURL
|
|
2966
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
2967
|
+
|
|
2968
|
+
/**
|
|
2969
|
+
* Build a `fetch`-compatible interceptor that injects `Authorization: Bearer`
|
|
2970
|
+
* (and a default `Content-Type`) onto outbound requests targeting the given
|
|
2971
|
+
* `baseURL`. Requests to any other host pass through untouched — the apiKey
|
|
2972
|
+
* is treated as a secret bound to the configured OmniRoute instance and
|
|
2973
|
+
* MUST NOT leak to third-party endpoints (a vector AI-SDKs occasionally
|
|
2974
|
+
* exercise when a tool call rewrites the URL mid-flight).
|
|
2975
|
+
*
|
|
2976
|
+
* Ported from Alph4d0g's `opencode-omniroute-auth@1.2.1` `createFetchInterceptor`
|
|
2977
|
+
* (their `dist/src/plugin.js:477-516`) with these intentional deviations:
|
|
2978
|
+
*
|
|
2979
|
+
* - **`baseURL` is required** here (no `localhost:20128/v1` fallback). T-04
|
|
2980
|
+
* callers always have an authoritative baseURL (from plugin opts or
|
|
2981
|
+
* auth.json); a silent local default would be a footgun.
|
|
2982
|
+
* - **Content-Type defaulting is gated on `init.body` presence**. Their
|
|
2983
|
+
* version unconditionally sets `application/json` even on `GET /v1/models`,
|
|
2984
|
+
* which is harmless but noisy; we only set it when there's a body to
|
|
2985
|
+
* describe.
|
|
2986
|
+
* - **Gemini schema sanitisation is NOT applied here** — that's T-06's
|
|
2987
|
+
* responsibility and will land as a body-transform step inside this
|
|
2988
|
+
* same function (or as a thin wrapper around it).
|
|
2989
|
+
* - **Header merge strategy mirrors theirs**: Request-attached headers
|
|
2990
|
+
* first, then `init.headers` overlay, then our injected
|
|
2991
|
+
* Authorization/Content-Type — so the apiKey we own ALWAYS wins over
|
|
2992
|
+
* any caller-supplied Bearer for the same OmniRoute provider.
|
|
2993
|
+
*
|
|
2994
|
+
* @see https://opencode.ai/docs/plugins for the AuthLoaderResult.fetch contract
|
|
2995
|
+
* (the returned function is invoked by the AI-SDK in lieu of global fetch).
|
|
2996
|
+
*/
|
|
2997
|
+
export function createOmniRouteFetchInterceptor(config: {
|
|
2998
|
+
apiKey: string;
|
|
2999
|
+
baseURL: string;
|
|
3000
|
+
}): typeof fetch {
|
|
3001
|
+
const trimmed = trimTrailingSlashes(config.baseURL);
|
|
3002
|
+
// Use `<base>/` for prefix matching to prevent suffix-spoof attacks
|
|
3003
|
+
// (e.g. baseURL `https://or.example.com/v1` should NOT match
|
|
3004
|
+
// `https://or.example.com/v1-attacker.evil/...`).
|
|
3005
|
+
const prefix = `${trimmed}/`;
|
|
3006
|
+
return async (input, init = {}) => {
|
|
3007
|
+
const url =
|
|
3008
|
+
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
|
3009
|
+
|
|
3010
|
+
const targetsOmniRoute = url === trimmed || url.startsWith(prefix);
|
|
3011
|
+
if (!targetsOmniRoute) {
|
|
3012
|
+
return fetch(input, init);
|
|
3013
|
+
}
|
|
3014
|
+
|
|
3015
|
+
// Merge order: Request-attached headers (when input is a Request) →
|
|
3016
|
+
// init.headers overlay → our injected headers last (so we win).
|
|
3017
|
+
const headers = new Headers(input instanceof Request ? input.headers : undefined);
|
|
3018
|
+
if (init.headers) {
|
|
3019
|
+
const initHeaders = new Headers(init.headers);
|
|
3020
|
+
initHeaders.forEach((value, key) => {
|
|
3021
|
+
headers.set(key, value);
|
|
3022
|
+
});
|
|
3023
|
+
}
|
|
3024
|
+
|
|
3025
|
+
headers.set("Authorization", `Bearer ${config.apiKey}`);
|
|
3026
|
+
// Only default Content-Type when the caller actually has a body AND
|
|
3027
|
+
// hasn't already declared the media type themselves.
|
|
3028
|
+
const hasBody = init.body != null || input instanceof Request;
|
|
3029
|
+
if (!headers.has("Content-Type") && hasBody) {
|
|
3030
|
+
headers.set("Content-Type", "application/json");
|
|
3031
|
+
}
|
|
3032
|
+
|
|
3033
|
+
return fetch(input, { ...init, headers });
|
|
3034
|
+
};
|
|
3035
|
+
}
|
|
3036
|
+
|
|
3037
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
3038
|
+
// Gemini tool-schema sanitisation (T-06) — strip JSON-schema keywords that
|
|
3039
|
+
// the Gemini API rejects from outbound chat-completion / responses bodies
|
|
3040
|
+
// when the target model is a Gemini variant.
|
|
3041
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
3042
|
+
|
|
3043
|
+
/**
|
|
3044
|
+
* JSON-Schema keywords that the Gemini API rejects when present anywhere in
|
|
3045
|
+
* a function-calling tool definition. Standard OpenAI / Anthropic clients
|
|
3046
|
+
* happily emit these (they're valid Draft-07 schema) but Gemini's tool
|
|
3047
|
+
* validator throws on them, breaking OmniRoute → Gemini chains transparently.
|
|
3048
|
+
*
|
|
3049
|
+
* Source: behavioural reverse-engineering from Alph4d0g's
|
|
3050
|
+
* opencode-omniroute-auth@1.2.1 (dist/src/plugin.js:517).
|
|
3051
|
+
*/
|
|
3052
|
+
const GEMINI_SCHEMA_KEYS_TO_REMOVE = new Set(["$schema", "$ref", "ref", "additionalProperties"]);
|
|
3053
|
+
|
|
3054
|
+
function isRecord(v: unknown): v is Record<string, unknown> {
|
|
3055
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
3056
|
+
}
|
|
3057
|
+
|
|
3058
|
+
/**
|
|
3059
|
+
* Recursively strip `GEMINI_SCHEMA_KEYS_TO_REMOVE` from an arbitrary
|
|
3060
|
+
* JSON-Schema-shaped record. Walks both the record's own properties and
|
|
3061
|
+
* any nested objects / arrays so deeply nested `properties.x.properties.y`
|
|
3062
|
+
* trees are reached without a separate traversal pass. Mutates in place
|
|
3063
|
+
* and reports whether any key was deleted so callers can skip a
|
|
3064
|
+
* `JSON.stringify` round-trip when nothing changed.
|
|
3065
|
+
*/
|
|
3066
|
+
function stripSchemaKeys(schema: Record<string, unknown>): boolean {
|
|
3067
|
+
let changed = false;
|
|
3068
|
+
for (const key of Object.keys(schema)) {
|
|
3069
|
+
if (GEMINI_SCHEMA_KEYS_TO_REMOVE.has(key)) {
|
|
3070
|
+
delete schema[key];
|
|
3071
|
+
changed = true;
|
|
3072
|
+
continue;
|
|
3073
|
+
}
|
|
3074
|
+
const value = schema[key];
|
|
3075
|
+
if (Array.isArray(value)) {
|
|
3076
|
+
for (const item of value) {
|
|
3077
|
+
if (isRecord(item)) {
|
|
3078
|
+
changed = stripSchemaKeys(item) || changed;
|
|
3079
|
+
}
|
|
3080
|
+
}
|
|
3081
|
+
continue;
|
|
3082
|
+
}
|
|
3083
|
+
if (isRecord(value)) {
|
|
3084
|
+
changed = stripSchemaKeys(value) || changed;
|
|
3085
|
+
}
|
|
3086
|
+
}
|
|
3087
|
+
return changed;
|
|
3088
|
+
}
|
|
3089
|
+
|
|
3090
|
+
/**
|
|
3091
|
+
* Walk every tool definition in the payload and strip Gemini-incompatible
|
|
3092
|
+
* schema keywords. Handles both chat-completion shape
|
|
3093
|
+
* (`tools[].function.parameters`) and Responses-API shape
|
|
3094
|
+
* (`tools[].input_schema`), plus the Gemini-native `function_declaration`
|
|
3095
|
+
* variant some adapters use.
|
|
3096
|
+
*
|
|
3097
|
+
* Also strips top-level schema keywords from the payload itself — clients
|
|
3098
|
+
* occasionally attach a top-level `$schema` declaration when re-serialising
|
|
3099
|
+
* tool bundles, and Gemini rejects those too.
|
|
3100
|
+
*/
|
|
3101
|
+
function sanitizeToolSchemaContainer(payload: Record<string, unknown>): boolean {
|
|
3102
|
+
let changed = false;
|
|
3103
|
+
// Top-level keyword strip — covers payload-level `$schema` etc.
|
|
3104
|
+
for (const key of Object.keys(payload)) {
|
|
3105
|
+
if (GEMINI_SCHEMA_KEYS_TO_REMOVE.has(key)) {
|
|
3106
|
+
delete payload[key];
|
|
3107
|
+
changed = true;
|
|
3108
|
+
}
|
|
3109
|
+
}
|
|
3110
|
+
const tools = (payload as { tools?: unknown }).tools;
|
|
3111
|
+
if (!Array.isArray(tools)) {
|
|
3112
|
+
return changed;
|
|
3113
|
+
}
|
|
3114
|
+
for (const tool of tools) {
|
|
3115
|
+
if (!isRecord(tool)) continue;
|
|
3116
|
+
const fn = (tool as { function?: unknown }).function;
|
|
3117
|
+
if (isRecord(fn) && isRecord((fn as { parameters?: unknown }).parameters)) {
|
|
3118
|
+
changed = stripSchemaKeys(fn.parameters as Record<string, unknown>) || changed;
|
|
3119
|
+
}
|
|
3120
|
+
const fnDecl = (tool as { function_declaration?: unknown }).function_declaration;
|
|
3121
|
+
if (isRecord(fnDecl) && isRecord((fnDecl as { parameters?: unknown }).parameters)) {
|
|
3122
|
+
changed = stripSchemaKeys(fnDecl.parameters as Record<string, unknown>) || changed;
|
|
3123
|
+
}
|
|
3124
|
+
const inputSchema = (tool as { input_schema?: unknown }).input_schema;
|
|
3125
|
+
if (isRecord(inputSchema)) {
|
|
3126
|
+
changed = stripSchemaKeys(inputSchema) || changed;
|
|
3127
|
+
}
|
|
3128
|
+
}
|
|
3129
|
+
return changed;
|
|
3130
|
+
}
|
|
3131
|
+
|
|
3132
|
+
/**
|
|
3133
|
+
* Pure function — recursively strip Gemini-incompatible JSON-Schema
|
|
3134
|
+
* keywords (`$schema`, `$ref`, `ref`, `additionalProperties`) from the
|
|
3135
|
+
* tool definitions on a chat-completions / responses payload.
|
|
3136
|
+
*
|
|
3137
|
+
* Walks:
|
|
3138
|
+
* - `payload.tools[].function.parameters` (OpenAI chat-completions shape)
|
|
3139
|
+
* - `payload.tools[].function_declaration.parameters` (Gemini-native shape
|
|
3140
|
+
* some adapters round-trip)
|
|
3141
|
+
* - `payload.tools[].input_schema` (Responses-API shape)
|
|
3142
|
+
* - all `properties.<x>` (and `properties.<x>.properties.<y>`…) inside
|
|
3143
|
+
* each container, recursing through nested objects and arrays.
|
|
3144
|
+
* - top-level payload keys (some clients attach a payload-level `$schema`).
|
|
3145
|
+
*
|
|
3146
|
+
* Returns the cleaned payload. Does NOT mutate input — clones first via
|
|
3147
|
+
* `structuredClone` so callers can keep a reference to the original. If
|
|
3148
|
+
* the payload is not a record, or carries no tools and no top-level
|
|
3149
|
+
* stripped keys, returns a (still cloned) equivalent.
|
|
3150
|
+
*
|
|
3151
|
+
* Exported so the body-transform layer is unit-testable independent of the
|
|
3152
|
+
* fetch wrapper.
|
|
3153
|
+
*/
|
|
3154
|
+
export function sanitizeGeminiToolSchemas(payload: unknown): unknown {
|
|
3155
|
+
if (!isRecord(payload)) {
|
|
3156
|
+
// Non-record payloads (string, array, number, null) can't carry tool
|
|
3157
|
+
// schemas. Pass back the same value — there's nothing to clone-and-strip
|
|
3158
|
+
// and propagating the original keeps caller semantics simple.
|
|
3159
|
+
return payload;
|
|
3160
|
+
}
|
|
3161
|
+
// structuredClone is available in Node 18+; the package's engines field
|
|
3162
|
+
// already requires Node >=22.22.3 so we can rely on it without a
|
|
3163
|
+
// JSON round-trip fallback.
|
|
3164
|
+
const cloned = structuredClone(payload) as Record<string, unknown>;
|
|
3165
|
+
sanitizeToolSchemaContainer(cloned);
|
|
3166
|
+
return cloned;
|
|
3167
|
+
}
|
|
3168
|
+
|
|
3169
|
+
/**
|
|
3170
|
+
* Detect whether a payload is bound for a Gemini model. Returns true if
|
|
3171
|
+
* `payload.model` is a string AND matches any known Gemini routing pattern:
|
|
3172
|
+
*
|
|
3173
|
+
* - case-insensitive substring `gemini` (covers bare `gemini-1.5-pro`,
|
|
3174
|
+
* `gemini-2.5-flash`, etc.)
|
|
3175
|
+
* - `models/gemini-…` (Google Generative AI canonical id form)
|
|
3176
|
+
* - `google-vertex/gemini-…` (OpenCode + AI-SDK Vertex routing prefix)
|
|
3177
|
+
*
|
|
3178
|
+
* Liberal by design: a false positive (cleaning a payload that didn't
|
|
3179
|
+
* need cleaning) costs only a structuredClone + one walk; a false negative
|
|
3180
|
+
* breaks the whole chain by forwarding $schema/additionalProperties to
|
|
3181
|
+
* Gemini which throws 400 INVALID_ARGUMENT. The first three checks
|
|
3182
|
+
* collapse into the case-insensitive substring check, but they're
|
|
3183
|
+
* documented separately so future maintainers see the intent.
|
|
3184
|
+
*
|
|
3185
|
+
* Exported so callers and tests can probe detection independent of the
|
|
3186
|
+
* fetch wrapper.
|
|
3187
|
+
*/
|
|
3188
|
+
export function shouldSanitizeForGemini(payload: unknown): boolean {
|
|
3189
|
+
if (!isRecord(payload)) return false;
|
|
3190
|
+
const model = (payload as { model?: unknown }).model;
|
|
3191
|
+
if (typeof model !== "string") return false;
|
|
3192
|
+
return /gemini/i.test(model);
|
|
3193
|
+
}
|
|
3194
|
+
|
|
3195
|
+
/**
|
|
3196
|
+
* Module-level latch so the streaming-body warning fires AT MOST once per
|
|
3197
|
+
* Node process. ReadableStream bodies can't be safely cloned + JSON-parsed
|
|
3198
|
+
* without consuming the stream (and re-creating a stream that survives both
|
|
3199
|
+
* read paths is non-trivial), so the sanitiser skips them — but we want
|
|
3200
|
+
* the operator to see one heads-up that schema stripping won't run on
|
|
3201
|
+
* those requests.
|
|
3202
|
+
*/
|
|
3203
|
+
let geminiStreamingWarningEmitted = false;
|
|
3204
|
+
|
|
3205
|
+
/**
|
|
3206
|
+
* Wrapper over an inner `fetch` that applies Gemini schema sanitisation to
|
|
3207
|
+
* outbound chat-completion / responses request bodies.
|
|
3208
|
+
*
|
|
3209
|
+
* Behaviour:
|
|
3210
|
+
* - URL gate: only inspects requests whose URL path contains
|
|
3211
|
+
* `/chat/completions` or `/responses` (lenient about prefix — works for
|
|
3212
|
+
* `/v1/chat/completions`, `/openai/v1/chat/completions`, …).
|
|
3213
|
+
* - Body extraction handles `string`, `Buffer` / `Uint8Array`,
|
|
3214
|
+
* `URLSearchParams` (calls `.toString()`), `Blob` (`await .text()`),
|
|
3215
|
+
* AND `Request` input where the body lives on the Request not init.
|
|
3216
|
+
* `ReadableStream` bodies are skipped (see below).
|
|
3217
|
+
* - Body must JSON.parse to a record; otherwise pass-through.
|
|
3218
|
+
* - `shouldSanitizeForGemini` gates the actual transform — non-Gemini
|
|
3219
|
+
* payloads pass through unchanged regardless of endpoint.
|
|
3220
|
+
* - Fail-open: ANY error during extraction / parse / sanitise falls back
|
|
3221
|
+
* to forwarding the original `(input, init)` to the inner fetch.
|
|
3222
|
+
* Sanitisation is a best-effort guard, never a hard failure mode.
|
|
3223
|
+
* - `ReadableStream` bodies → skipped with a ONE-TIME `console.warn`.
|
|
3224
|
+
* The Gemini-quirk only manifests with tool calls in the body, and
|
|
3225
|
+
* OC streams plain text deltas; the operator should still know.
|
|
3226
|
+
*
|
|
3227
|
+
* @param inner The next fetch in the chain (typically the Bearer-injecting
|
|
3228
|
+
* interceptor from `createOmniRouteFetchInterceptor`).
|
|
3229
|
+
*/
|
|
3230
|
+
export function createGeminiSanitizingFetch(inner: typeof fetch): typeof fetch {
|
|
3231
|
+
return async (input, init) => {
|
|
3232
|
+
try {
|
|
3233
|
+
const url =
|
|
3234
|
+
typeof input === "string"
|
|
3235
|
+
? input
|
|
3236
|
+
: input instanceof URL
|
|
3237
|
+
? input.toString()
|
|
3238
|
+
: input instanceof Request
|
|
3239
|
+
? input.url
|
|
3240
|
+
: "";
|
|
3241
|
+
|
|
3242
|
+
// URL gate — match the path substring with prefix tolerance.
|
|
3243
|
+
const targetsCompletions = url.includes("/chat/completions") || url.includes("/responses");
|
|
3244
|
+
if (!targetsCompletions) {
|
|
3245
|
+
return inner(input, init);
|
|
3246
|
+
}
|
|
3247
|
+
|
|
3248
|
+
// Body extraction. Cover the body shapes the AI-SDK + adapter layer
|
|
3249
|
+
// actually emit; bail to pass-through on anything we can't read
|
|
3250
|
+
// synchronously without consuming a stream.
|
|
3251
|
+
let rawBody: string | undefined;
|
|
3252
|
+
const initBody = init?.body as unknown;
|
|
3253
|
+
|
|
3254
|
+
if (typeof initBody === "string") {
|
|
3255
|
+
rawBody = initBody;
|
|
3256
|
+
} else if (initBody instanceof URLSearchParams) {
|
|
3257
|
+
// Form-encoded bodies are never chat-completion JSON; pass-through.
|
|
3258
|
+
return inner(input, init);
|
|
3259
|
+
} else if (typeof Buffer !== "undefined" && initBody instanceof Buffer) {
|
|
3260
|
+
rawBody = initBody.toString("utf8");
|
|
3261
|
+
} else if (initBody instanceof Uint8Array) {
|
|
3262
|
+
rawBody = new TextDecoder().decode(initBody);
|
|
3263
|
+
} else if (initBody instanceof ReadableStream) {
|
|
3264
|
+
// Streaming body — skip with one-shot warning.
|
|
3265
|
+
if (!geminiStreamingWarningEmitted) {
|
|
3266
|
+
geminiStreamingWarningEmitted = true;
|
|
3267
|
+
|
|
3268
|
+
console.warn(
|
|
3269
|
+
"[omniroute-plugin] sanitizeGemini: streaming Request body, skipping schema strip (Gemini may reject)"
|
|
3270
|
+
);
|
|
3271
|
+
}
|
|
3272
|
+
return inner(input, init);
|
|
3273
|
+
} else if (
|
|
3274
|
+
initBody !== null &&
|
|
3275
|
+
initBody !== undefined &&
|
|
3276
|
+
typeof (initBody as { text?: unknown }).text === "function"
|
|
3277
|
+
) {
|
|
3278
|
+
// Blob-like (has .text(): Promise<string>). Streaming was already
|
|
3279
|
+
// matched above — anything left with a `.text` method we can buffer.
|
|
3280
|
+
try {
|
|
3281
|
+
rawBody = await (initBody as { text(): Promise<string> }).text();
|
|
3282
|
+
} catch {
|
|
3283
|
+
return inner(input, init);
|
|
3284
|
+
}
|
|
3285
|
+
} else if (initBody === undefined && input instanceof Request) {
|
|
3286
|
+
// Body lives on the Request object itself, not init. Clone before
|
|
3287
|
+
// reading — consuming the original Request body would make it
|
|
3288
|
+
// unreadable downstream.
|
|
3289
|
+
try {
|
|
3290
|
+
rawBody = await (input as Request).clone().text();
|
|
3291
|
+
} catch {
|
|
3292
|
+
return inner(input, init);
|
|
3293
|
+
}
|
|
3294
|
+
}
|
|
3295
|
+
|
|
3296
|
+
if (rawBody === undefined || rawBody.length === 0) {
|
|
3297
|
+
return inner(input, init);
|
|
3298
|
+
}
|
|
3299
|
+
|
|
3300
|
+
let payload: unknown;
|
|
3301
|
+
try {
|
|
3302
|
+
payload = JSON.parse(rawBody);
|
|
3303
|
+
} catch {
|
|
3304
|
+
// Non-JSON body → pass-through, never throw.
|
|
3305
|
+
return inner(input, init);
|
|
3306
|
+
}
|
|
3307
|
+
|
|
3308
|
+
if (!shouldSanitizeForGemini(payload)) {
|
|
3309
|
+
return inner(input, init);
|
|
3310
|
+
}
|
|
3311
|
+
|
|
3312
|
+
const cleaned = sanitizeGeminiToolSchemas(payload);
|
|
3313
|
+
const newBody = JSON.stringify(cleaned);
|
|
3314
|
+
// Cloning init: we need to replace `body` without mutating the caller's
|
|
3315
|
+
// init bag. If init was undefined (Request-input path), construct one.
|
|
3316
|
+
const newInit: RequestInit = { ...(init ?? {}), body: newBody };
|
|
3317
|
+
return inner(input, newInit);
|
|
3318
|
+
} catch {
|
|
3319
|
+
// Total fail-open — never let a sanitiser bug break the request path.
|
|
3320
|
+
return inner(input, init);
|
|
3321
|
+
}
|
|
3322
|
+
};
|
|
3323
|
+
}
|
|
3324
|
+
|
|
3325
|
+
/**
|
|
3326
|
+
* Test-only hook: reset the module-level streaming-warning latch so each
|
|
3327
|
+
* test can independently assert the one-shot semantics. Not part of the
|
|
3328
|
+
* public stability contract — prefixed with `__` per convention to signal
|
|
3329
|
+
* "do not depend on this from production code".
|
|
3330
|
+
*/
|
|
3331
|
+
export function __resetGeminiStreamingWarning(): void {
|
|
3332
|
+
geminiStreamingWarningEmitted = false;
|
|
3333
|
+
}
|
|
3334
|
+
|
|
3335
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
3336
|
+
// Config hook (T-07) — backward-compat shim for OC ≤1.14.48
|
|
3337
|
+
//
|
|
3338
|
+
// OC ≤1.14.48 does NOT call `provider.models()` at startup; it reads the
|
|
3339
|
+
// catalog from the static `provider.<id>` config block instead. OC ≥1.14.49
|
|
3340
|
+
// calls `provider.models()` dynamically AND merges the dynamic catalog over
|
|
3341
|
+
// any static block (dynamic wins on collision). To support both, the plugin
|
|
3342
|
+
// publishes a static block via `config` AND a dynamic one via `provider.models`
|
|
3343
|
+
// — OC's resolution order picks the right one per OC version. This module
|
|
3344
|
+
// implements the static-publish half.
|
|
3345
|
+
//
|
|
3346
|
+
// Sibling shape source-of-truth: see
|
|
3347
|
+
// `@omniroute/opencode-provider/src/index.ts` (`createOmniRouteProvider`,
|
|
3348
|
+
// `OpenCodeProviderEntry`, `OpenCodeModelEntry`). We replicate that shape
|
|
3349
|
+
// here rather than depending on the sibling package — the plugin must stay
|
|
3350
|
+
// self-contained (npm-installable on its own, no peer dep on the provider
|
|
3351
|
+
// builder).
|
|
3352
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
3353
|
+
|
|
3354
|
+
/**
|
|
3355
|
+
* Per-model entry shape under `provider.<id>.models[modelId]`. Mirrors
|
|
3356
|
+
* `OpenCodeModelEntry` exported by `@omniroute/opencode-provider`. Stripped
|
|
3357
|
+
* down to the fields OC's static catalog reader actually consumes — NOT a
|
|
3358
|
+
* full ModelV2 (that's the dynamic-hook shape). Optional fields are omitted
|
|
3359
|
+
* when OmniRoute didn't surface a value, NOT emitted as `undefined` — the
|
|
3360
|
+
* resulting JSON must be diffable across OmniRoute deployments without
|
|
3361
|
+
* `undefined` noise.
|
|
3362
|
+
*/
|
|
3363
|
+
/** Modalities accepted by OC's static catalog reader (see `@opencode-ai/sdk`). */
|
|
3364
|
+
export type OmniRouteModalityKind = "text" | "audio" | "image" | "video" | "pdf";
|
|
3365
|
+
|
|
3366
|
+
const STATIC_MODALITY_VALUES: ReadonlySet<OmniRouteModalityKind> = new Set([
|
|
3367
|
+
"text",
|
|
3368
|
+
"audio",
|
|
3369
|
+
"image",
|
|
3370
|
+
"video",
|
|
3371
|
+
"pdf",
|
|
3372
|
+
]);
|
|
3373
|
+
|
|
3374
|
+
/** Normalise + filter raw modality list to the values OC accepts. Deduped. */
|
|
3375
|
+
function normaliseModalities(raw: unknown): OmniRouteModalityKind[] {
|
|
3376
|
+
if (!Array.isArray(raw)) return [];
|
|
3377
|
+
const out: OmniRouteModalityKind[] = [];
|
|
3378
|
+
const seen = new Set<string>();
|
|
3379
|
+
for (const v of raw) {
|
|
3380
|
+
if (typeof v !== "string") continue;
|
|
3381
|
+
const lower = v.toLowerCase() as OmniRouteModalityKind;
|
|
3382
|
+
if (!STATIC_MODALITY_VALUES.has(lower)) continue;
|
|
3383
|
+
if (seen.has(lower)) continue;
|
|
3384
|
+
seen.add(lower);
|
|
3385
|
+
out.push(lower);
|
|
3386
|
+
}
|
|
3387
|
+
return out;
|
|
3388
|
+
}
|
|
3389
|
+
|
|
3390
|
+
export interface OmniRouteStaticModelEntry {
|
|
3391
|
+
/** Owning provider id. SHOULD match the parent `provider.<id>` key so OC's
|
|
3392
|
+
* static-catalog reader resolves credentials via `providerID` instead of
|
|
3393
|
+
* parsing the model key on `/`. Optional: OC's schema validator may
|
|
3394
|
+
* reject the entire provider block when this field is present but the
|
|
3395
|
+
* model KEY already carries the provider prefix (e.g. `omniroute/MASTER`),
|
|
3396
|
+
* since the prefix makes the field redundant and the field is not part of
|
|
3397
|
+
* OC's expected schema. We omit it from entries and rely on the prefix
|
|
3398
|
+
* on the KEY alone. See PR #4184. */
|
|
3399
|
+
providerID?: string;
|
|
3400
|
+
/** Display label rendered in OC's model picker. Defaults to the model id. */
|
|
3401
|
+
name: string;
|
|
3402
|
+
|
|
3403
|
+
/** ISO date the model was released. Surfaces in OC's model card when present. */
|
|
3404
|
+
release_date?: string;
|
|
3405
|
+
/** Model accepts image / file attachments. */
|
|
3406
|
+
attachment?: boolean;
|
|
3407
|
+
/** Model exposes a reasoning / extended-thinking surface. */
|
|
3408
|
+
reasoning?: boolean;
|
|
3409
|
+
/** Model honours the `temperature` parameter. */
|
|
3410
|
+
temperature?: boolean;
|
|
3411
|
+
/** Model supports function / tool calling. */
|
|
3412
|
+
tool_call?: boolean;
|
|
3413
|
+
/**
|
|
3414
|
+
* Per-million-token cost. Maps from OmniRoute `/api/pricing` shape:
|
|
3415
|
+
* `input`/`output` pass through; `cached` → `cache_read`;
|
|
3416
|
+
* `cache_creation` → `cache_write`. Omitted when no pricing slot resolves.
|
|
3417
|
+
*/
|
|
3418
|
+
cost?: {
|
|
3419
|
+
input: number;
|
|
3420
|
+
output: number;
|
|
3421
|
+
cache_read?: number;
|
|
3422
|
+
cache_write?: number;
|
|
3423
|
+
};
|
|
3424
|
+
/**
|
|
3425
|
+
* Context-window limits. OC's static reader requires both `context` AND
|
|
3426
|
+
* `output` when `limit` is present, so the field is only emitted when
|
|
3427
|
+
* BOTH are known.
|
|
3428
|
+
*/
|
|
3429
|
+
limit?: {
|
|
3430
|
+
context: number;
|
|
3431
|
+
output: number;
|
|
3432
|
+
};
|
|
3433
|
+
/**
|
|
3434
|
+
* Modality lists the model accepts (input) and emits (output). Maps from
|
|
3435
|
+
* OmniRoute's `input_modalities` / `output_modalities` on `/v1/models`.
|
|
3436
|
+
* Emitted only when at least one modality is known — without this field
|
|
3437
|
+
* OC's runtime catalog defaults `input.image: false` even when the model
|
|
3438
|
+
* card has `attachment: true`, which blocks clipboard image paste in the
|
|
3439
|
+
* TUI for vision-capable models.
|
|
3440
|
+
*/
|
|
3441
|
+
modalities?: {
|
|
3442
|
+
input: OmniRouteModalityKind[];
|
|
3443
|
+
output: OmniRouteModalityKind[];
|
|
3444
|
+
};
|
|
3445
|
+
}
|
|
3446
|
+
|
|
3447
|
+
/**
|
|
3448
|
+
* Static `provider.<id>` block written to `input.provider` by the config hook.
|
|
3449
|
+
* Mirrors `OpenCodeProviderEntry` from `@omniroute/opencode-provider`.
|
|
3450
|
+
*
|
|
3451
|
+
* - `npm` is always `"@ai-sdk/openai-compatible"` — OmniRoute exposes an
|
|
3452
|
+
* OpenAI-compatible surface and that's the AI-SDK adapter that speaks it.
|
|
3453
|
+
* - `options.baseURL` MUST be the fully-qualified `/v1` URL (the AI-SDK
|
|
3454
|
+
* appends paths like `/chat/completions` directly under it).
|
|
3455
|
+
* - `options.apiKey` is the bearer token; the fetch interceptor (T-04)
|
|
3456
|
+
* also injects it on the dynamic path, but the static block needs it
|
|
3457
|
+
* embedded too so OC ≤1.14.48 can construct the SDK client without
|
|
3458
|
+
* going through the auth hook.
|
|
3459
|
+
*/
|
|
3460
|
+
export interface OmniRouteStaticProviderEntry {
|
|
3461
|
+
npm: "@ai-sdk/openai-compatible";
|
|
3462
|
+
name: string;
|
|
3463
|
+
options: {
|
|
3464
|
+
baseURL: string;
|
|
3465
|
+
apiKey: string;
|
|
3466
|
+
};
|
|
3467
|
+
models: Record<string, OmniRouteStaticModelEntry>;
|
|
3468
|
+
}
|
|
3469
|
+
|
|
3470
|
+
/**
|
|
3471
|
+
* Build the static `provider.<id>` block from raw `/v1/models` + `/api/combos`
|
|
3472
|
+
* responses. Pure function — no I/O, no side effects, no dependency on the
|
|
3473
|
+
* sibling provider package. Exported so callers and tests can construct the
|
|
3474
|
+
* block independently of the auth.json + fetch pipeline.
|
|
3475
|
+
*
|
|
3476
|
+
* Mapping rules (per the sibling `createOmniRouteProvider` output spec):
|
|
3477
|
+
*
|
|
3478
|
+
* - One entry per raw model AND one entry per non-hidden combo.
|
|
3479
|
+
* - `name` = model id (no separate display name on `/v1/models`).
|
|
3480
|
+
* - `attachment` = `caps.attachment ?? caps.vision ?? false` — same
|
|
3481
|
+
* convention as `mapRawModelToModelV2` (T-03).
|
|
3482
|
+
* - `reasoning` = `caps.reasoning || caps.thinking`. Booleans only — we
|
|
3483
|
+
* do NOT emit the field when both source flags are absent (keeps the
|
|
3484
|
+
* stripped shape minimal).
|
|
3485
|
+
* - `temperature` = `caps.temperature ?? true` — OpenAI-compat surface
|
|
3486
|
+
* supports temperature by default; only an explicit `false` suppresses.
|
|
3487
|
+
* - `tool_call` = `caps.tool_calling ?? false`.
|
|
3488
|
+
* - `limit.context` = raw `context_length` when > 0; omitted otherwise.
|
|
3489
|
+
* - `limit.input` = raw `max_input_tokens` when present.
|
|
3490
|
+
* - `limit.output` = raw `max_output_tokens` when present.
|
|
3491
|
+
*
|
|
3492
|
+
* For combos: LCD across member raw models (matches `mapComboToModelV2`):
|
|
3493
|
+
*
|
|
3494
|
+
* - `attachment`, `reasoning`, `tool_call`, `temperature`: `every` member.
|
|
3495
|
+
* - `limit.context` = min(member context_lengths).
|
|
3496
|
+
* - `limit.input` = min(member max_input_tokens) ONLY when every member
|
|
3497
|
+
* declares one.
|
|
3498
|
+
* - `limit.output` = min(member max_output_tokens).
|
|
3499
|
+
* - Empty members → all-false / limits omitted.
|
|
3500
|
+
*
|
|
3501
|
+
* Collision: combos win (matches the dynamic provider hook).
|
|
3502
|
+
*
|
|
3503
|
+
* @param rawModels Raw `/v1/models` entries (may be empty).
|
|
3504
|
+
* @param rawCombos Raw `/api/combos` entries (may be empty).
|
|
3505
|
+
* @param opts Resolved plugin options (we read `displayName` + `providerId`).
|
|
3506
|
+
* @param baseURL Fully-qualified `/v1` base URL — written verbatim to
|
|
3507
|
+
* `options.baseURL`. Caller is responsible for `/v1`
|
|
3508
|
+
* normalisation; we do NOT touch it here.
|
|
3509
|
+
* @param apiKey Bearer token — written verbatim to `options.apiKey`.
|
|
3510
|
+
*/
|
|
3511
|
+
export function buildStaticProviderEntry(
|
|
3512
|
+
rawModels: OmniRouteRawModelEntry[],
|
|
3513
|
+
rawCombos: OmniRouteRawCombo[],
|
|
3514
|
+
opts: ReturnType<typeof resolveOmniRoutePluginOptions>,
|
|
3515
|
+
baseURL: string,
|
|
3516
|
+
apiKey: string,
|
|
3517
|
+
enrichment?: OmniRouteEnrichmentMap,
|
|
3518
|
+
compressionCombos?: OmniRouteCompressionCombo[],
|
|
3519
|
+
connections?: OmniRouteProviderConnection[],
|
|
3520
|
+
rawAutoCombos?: OmniRouteRawAutoCombo[]
|
|
3521
|
+
): OmniRouteStaticProviderEntry {
|
|
3522
|
+
const models: Record<string, OmniRouteStaticModelEntry> = {};
|
|
3523
|
+
|
|
3524
|
+
// usableOnly filter — compute once when feature enabled AND we have
|
|
3525
|
+
// connection data to filter against. Soft-fail (empty connections list)
|
|
3526
|
+
// disables the filter rather than hiding the catalog.
|
|
3527
|
+
const wantUsableOnly = opts.features?.usableOnly === true;
|
|
3528
|
+
const usable =
|
|
3529
|
+
wantUsableOnly && connections && connections.length > 0
|
|
3530
|
+
? usableProviderAliasSet(connections, enrichment)
|
|
3531
|
+
: undefined;
|
|
3532
|
+
// Provider-tag suffix — default-on, opt-out via `features.providerTag: false`.
|
|
3533
|
+
// Prepends e.g. `Claude - ` to enriched raw-model names so the picker
|
|
3534
|
+
// can tell `cc/claude-opus-4-7` (Anthropic) apart from `kr/claude-opus-4-7`
|
|
3535
|
+
// (Kiro). Combos skip this by design.
|
|
3536
|
+
const wantProviderTag = opts.features?.providerTag !== false;
|
|
3537
|
+
|
|
3538
|
+
// Build a name-set of every non-hidden combo from `/api/combos`. OmniRoute
|
|
3539
|
+
// pre-mirrors combos into `/v1/models` with the friendly name as the raw
|
|
3540
|
+
// id (e.g. `claude-primary`, `gemini-pro`), so without dedup the static
|
|
3541
|
+
// catalog ends up with both `claude-primary` (raw, opaque) AND the same
|
|
3542
|
+
// combo under `combo/claude-primary` (rich LCD). We suppress the raw twin
|
|
3543
|
+
// so each combo surfaces exactly once, under the `combo/` namespace.
|
|
3544
|
+
const comboNames = new Set<string>();
|
|
3545
|
+
for (const combo of rawCombos) {
|
|
3546
|
+
if (!combo || combo.isHidden === true) continue;
|
|
3547
|
+
const name = combo.name && combo.name.trim().length > 0 ? combo.name.trim() : combo.id;
|
|
3548
|
+
if (typeof name === "string" && name.length > 0) comboNames.add(name);
|
|
3549
|
+
}
|
|
3550
|
+
|
|
3551
|
+
// Build the canonical→alias reverse map AND the canonical-dedup set
|
|
3552
|
+
// once per static-block construction. Same shape as the dynamic hook
|
|
3553
|
+
// so both catalogs publish identical keys (no `claude/X` raw twin
|
|
3554
|
+
// shadowing the enriched `cc/X` row).
|
|
3555
|
+
const canonicalToAlias = buildCanonicalToAliasMap(enrichment);
|
|
3556
|
+
const canonicalDedup = canonicalDedupSet(rawModels, canonicalToAlias);
|
|
3557
|
+
const aliasIndex = buildAliasIndex(enrichment);
|
|
3558
|
+
|
|
3559
|
+
// Raw model entries → stripped per-model shape.
|
|
3560
|
+
for (const raw of rawModels) {
|
|
3561
|
+
if (!raw.id) continue;
|
|
3562
|
+
// Skip the 20 named no-slash entries that shadow combos under the
|
|
3563
|
+
// `combo/<name>` namespace. We keep `codex-auto-review` and any other
|
|
3564
|
+
// future no-slash raw entry that doesn't have a matching combo.
|
|
3565
|
+
if (comboNames.has(raw.id)) continue;
|
|
3566
|
+
// Skip canonical-named twins when the alias-keyed enriched row exists.
|
|
3567
|
+
if (canonicalDedup.has(raw.id)) continue;
|
|
3568
|
+
if (usable && !isUsableRawModelId(raw.id, usable, enrichment)) continue;
|
|
3569
|
+
const caps = raw.capabilities ?? {};
|
|
3570
|
+
// Enrichment overlay: `/api/pricing/models` carries human display names
|
|
3571
|
+
// (e.g. "Claude Opus 4.7" for raw id "cc/claude-opus-4-7"). The OC TUI
|
|
3572
|
+
// model picker reads this `name` straight from the static block on
|
|
3573
|
+
// OC ≤1.15.5 where the dynamic provider hook never fires. Falls back
|
|
3574
|
+
// to the raw id when no enrichment entry is found. The alias-fallback
|
|
3575
|
+
// lookup rescues `<canonical>/<id>` rows whose enrichment indexed only
|
|
3576
|
+
// under `<alias>/<id>`.
|
|
3577
|
+
const enrichmentEntry = lookupEnrichment(raw.id, enrichment, canonicalToAlias);
|
|
3578
|
+
const enrichmentName = enrichmentEntry?.name;
|
|
3579
|
+
let displayName = enrichmentName && enrichmentName.length > 0 ? enrichmentName : raw.id;
|
|
3580
|
+
// Provider-tag PREFIX — `<label> - <name>` so the picker groups by
|
|
3581
|
+
// upstream provider when scanning a column of model names. Mirrors
|
|
3582
|
+
// `applyProviderTag` used in the dynamic hook. Idempotent: skip
|
|
3583
|
+
// when the name already starts with the prefix. The alias-index
|
|
3584
|
+
// fallback rescues raw rows like `cohere/rerank-multilingual-v3.0`
|
|
3585
|
+
// whose specific model id isn't in `/api/pricing/models` but whose
|
|
3586
|
+
// slot is.
|
|
3587
|
+
if (wantProviderTag) {
|
|
3588
|
+
const tagEntry = resolveProviderTagEntry(
|
|
3589
|
+
raw.id,
|
|
3590
|
+
enrichmentEntry,
|
|
3591
|
+
aliasIndex,
|
|
3592
|
+
canonicalToAlias
|
|
3593
|
+
);
|
|
3594
|
+
const label = shortProviderLabel(tagEntry);
|
|
3595
|
+
if (label) {
|
|
3596
|
+
const prefix = `${label}${PROVIDER_TAG_SEPARATOR}`;
|
|
3597
|
+
if (!displayName.startsWith(prefix)) displayName = `${prefix}${displayName}`;
|
|
3598
|
+
}
|
|
3599
|
+
}
|
|
3600
|
+
// OC's static-catalog schema doesn't expect a `providerID` field on
|
|
3601
|
+
// individual entries — the parent block ID is the provider. Adding
|
|
3602
|
+
// unknown fields here can cause OC's schema validator to reject the
|
|
3603
|
+
// entire provider block, hiding ALL models. The provider prefix on the
|
|
3604
|
+
// model KEY (e.g. `omniroute/claude-opus-4`) is what OC uses to recover
|
|
3605
|
+
// (providerID, modelID) when the user selects a model.
|
|
3606
|
+
const entry: OmniRouteStaticModelEntry = { name: displayName };
|
|
3607
|
+
|
|
3608
|
+
const attachment = caps.attachment ?? caps.vision;
|
|
3609
|
+
if (typeof attachment === "boolean") entry.attachment = attachment;
|
|
3610
|
+
|
|
3611
|
+
if (typeof caps.reasoning === "boolean" || typeof caps.thinking === "boolean") {
|
|
3612
|
+
entry.reasoning = Boolean(caps.reasoning || caps.thinking);
|
|
3613
|
+
}
|
|
3614
|
+
|
|
3615
|
+
if (typeof caps.temperature === "boolean") {
|
|
3616
|
+
entry.temperature = caps.temperature;
|
|
3617
|
+
}
|
|
3618
|
+
|
|
3619
|
+
if (typeof caps.tool_calling === "boolean") {
|
|
3620
|
+
entry.tool_call = caps.tool_calling;
|
|
3621
|
+
}
|
|
3622
|
+
|
|
3623
|
+
// OC's SDK schema requires BOTH `context` and `output` when `limit` is
|
|
3624
|
+
// present. We previously emitted `limit.input` too, but the SDK reader
|
|
3625
|
+
// doesn't accept it — drop it. Only emit `limit` when both required
|
|
3626
|
+
// values are known.
|
|
3627
|
+
if (
|
|
3628
|
+
typeof raw.context_length === "number" &&
|
|
3629
|
+
raw.context_length > 0 &&
|
|
3630
|
+
typeof raw.max_output_tokens === "number" &&
|
|
3631
|
+
raw.max_output_tokens > 0
|
|
3632
|
+
) {
|
|
3633
|
+
entry.limit = {
|
|
3634
|
+
context: raw.context_length,
|
|
3635
|
+
output: raw.max_output_tokens,
|
|
3636
|
+
};
|
|
3637
|
+
}
|
|
3638
|
+
|
|
3639
|
+
// Modalities — emit when OmniRoute surfaced any. Without this field
|
|
3640
|
+
// OC's runtime model defaults `input.image: false` even for vision-
|
|
3641
|
+
// capable models, blocking clipboard image paste in the TUI.
|
|
3642
|
+
const inModalities = normaliseModalities(raw.input_modalities);
|
|
3643
|
+
const outModalities = normaliseModalities(raw.output_modalities);
|
|
3644
|
+
if (inModalities.length > 0 || outModalities.length > 0) {
|
|
3645
|
+
entry.modalities = {
|
|
3646
|
+
input: inModalities.length > 0 ? inModalities : ["text"],
|
|
3647
|
+
output: outModalities.length > 0 ? outModalities : ["text"],
|
|
3648
|
+
};
|
|
3649
|
+
}
|
|
3650
|
+
|
|
3651
|
+
// Cost from enrichment pricing (sourced from `/api/pricing`). Map
|
|
3652
|
+
// OmniRoute field names to OC's static-schema field names.
|
|
3653
|
+
const pricing = enrichmentEntry?.pricing;
|
|
3654
|
+
if (pricing && (typeof pricing.input === "number" || typeof pricing.output === "number")) {
|
|
3655
|
+
const cost: NonNullable<OmniRouteStaticModelEntry["cost"]> = {
|
|
3656
|
+
input: typeof pricing.input === "number" ? pricing.input : 0,
|
|
3657
|
+
output: typeof pricing.output === "number" ? pricing.output : 0,
|
|
3658
|
+
};
|
|
3659
|
+
if (typeof pricing.cacheRead === "number") cost.cache_read = pricing.cacheRead;
|
|
3660
|
+
if (typeof pricing.cacheWrite === "number") cost.cache_write = pricing.cacheWrite;
|
|
3661
|
+
entry.cost = cost;
|
|
3662
|
+
}
|
|
3663
|
+
|
|
3664
|
+
// release_date from /v1/models — surfaces in OC's model card when present.
|
|
3665
|
+
if (typeof raw.release_date === "string" && raw.release_date.length > 0) {
|
|
3666
|
+
entry.release_date = raw.release_date;
|
|
3667
|
+
}
|
|
3668
|
+
|
|
3669
|
+
// OC's static-catalog reader parses each key on `/` and rejects the
|
|
3670
|
+
// entire provider block if ANY key resolves to a parsed providerID that
|
|
3671
|
+
// has no corresponding provider block. So bare keys (no `/`) MUST be
|
|
3672
|
+
// prefixed with the resolved providerId. Already-prefixed keys
|
|
3673
|
+
// (e.g. `cc/claude-opus-4-7`) are left as-is to avoid double-prefixing.
|
|
3674
|
+
models[raw.id.includes("/") ? raw.id : `${opts.providerId}/${raw.id}`] = entry;
|
|
3675
|
+
}
|
|
3676
|
+
|
|
3677
|
+
// Combo entries → stripped LCD shape. Each combo is keyed as
|
|
3678
|
+
// `combo/<friendly-name>` so the OC TUI model picker shows them under a
|
|
3679
|
+
// distinct namespace (e.g. `combo/claude-primary`) instead of the opaque
|
|
3680
|
+
// upstream UUID id (e.g. `b4a0211e-e3e1-472d-b252-fb9bf6d1c935`).
|
|
3681
|
+
const rawModelById = new Map<string, OmniRouteRawModelEntry>();
|
|
3682
|
+
for (const m of rawModels) {
|
|
3683
|
+
if (m.id) rawModelById.set(m.id, m);
|
|
3684
|
+
}
|
|
3685
|
+
|
|
3686
|
+
// Resolve the default compression pipeline once — its short signature
|
|
3687
|
+
// (e.g. `[rtk:standard → caveman:full]`) is appended to every routable
|
|
3688
|
+
// combo `name` so operators can see what compression a combo applies
|
|
3689
|
+
// at a glance. Provider hook does the same decoration when feature is
|
|
3690
|
+
// on. Suffix is suppressed for combos with no resolvable members —
|
|
3691
|
+
// claiming compression on an unroutable combo would mislead the
|
|
3692
|
+
// picker.
|
|
3693
|
+
let compressionSuffix = "";
|
|
3694
|
+
if (compressionCombos && compressionCombos.length > 0) {
|
|
3695
|
+
const def = compressionCombos.find((c) => c.isDefault === true);
|
|
3696
|
+
if (def) {
|
|
3697
|
+
const sig = formatCompressionPipeline(def.pipeline);
|
|
3698
|
+
if (sig.length > 0) compressionSuffix = ` ${sig}`;
|
|
3699
|
+
}
|
|
3700
|
+
}
|
|
3701
|
+
|
|
3702
|
+
// Track combo keys to detect slug collisions across the catalog.
|
|
3703
|
+
const usedComboKeys = new Set<string>();
|
|
3704
|
+
const reportedCollisions = new Set<string>();
|
|
3705
|
+
|
|
3706
|
+
// ── Combo LCD across nested combo-refs (T-NN mirror) ─────────────────
|
|
3707
|
+
// Mirror of the dynamic-catalog fixpoint iteration: combos can nest
|
|
3708
|
+
// other combos via `kind: "combo-ref"` members (e.g. MASTER-LIGHT
|
|
3709
|
+
// contains OldLLM, KIRO, Opecode Zen FREE). The nested combo's own
|
|
3710
|
+
// capabilities and limits are computed in this same loop, so we need
|
|
3711
|
+
// a fixpoint pass: if a combo-ref points at a combo not yet processed,
|
|
3712
|
+
// defer this combo and try again after the sibling combos catch up.
|
|
3713
|
+
// We bound the retries so a circular combo graph can't deadlock the
|
|
3714
|
+
// picker, and we break early when a pass makes no progress.
|
|
3715
|
+
const MAX_STATIC_COMBO_PASSES = 8;
|
|
3716
|
+
const resolvedStaticCombosByName = new Map<string, OmniRouteStaticModelEntry>();
|
|
3717
|
+
let pendingStatic = rawCombos.filter((combo) => {
|
|
3718
|
+
if (!combo.id) return false;
|
|
3719
|
+
if (combo.isHidden === true) return false;
|
|
3720
|
+
if (usable && !isUsableCombo(combo, usable)) return false;
|
|
3721
|
+
return true;
|
|
3722
|
+
});
|
|
3723
|
+
|
|
3724
|
+
for (let pass = 0; pass < MAX_STATIC_COMBO_PASSES && pendingStatic.length > 0; pass++) {
|
|
3725
|
+
const stillPendingStatic: typeof pendingStatic = [];
|
|
3726
|
+
for (const combo of pendingStatic) {
|
|
3727
|
+
const memberSteps = Array.isArray(combo.models) ? combo.models : [];
|
|
3728
|
+
const memberEntries: OmniRouteRawModelEntry[] = [];
|
|
3729
|
+
let deferredThisPass = false;
|
|
3730
|
+
|
|
3731
|
+
for (const step of memberSteps) {
|
|
3732
|
+
const stepKind = (step as unknown as { kind?: unknown }).kind;
|
|
3733
|
+
|
|
3734
|
+
if (stepKind === "combo-ref") {
|
|
3735
|
+
const comboName = (step as unknown as { comboName?: unknown }).comboName;
|
|
3736
|
+
if (typeof comboName !== "string" || comboName.length === 0) {
|
|
3737
|
+
continue;
|
|
3738
|
+
}
|
|
3739
|
+
const nestedEntry = resolvedStaticCombosByName.get(comboName);
|
|
3740
|
+
if (!nestedEntry) {
|
|
3741
|
+
deferredThisPass = true;
|
|
3742
|
+
break;
|
|
3743
|
+
}
|
|
3744
|
+
// Synthesize a raw-model-shaped member entry carrying the
|
|
3745
|
+
// nested combo's pre-computed context + capabilities +
|
|
3746
|
+
// modalities. Mirrors the dynamic path so the static catalog
|
|
3747
|
+
// stays in lockstep with the dynamic one.
|
|
3748
|
+
const inputModalities = (nestedEntry.modalities?.input ?? ["text"]) as string[];
|
|
3749
|
+
const outputModalities = (nestedEntry.modalities?.output ?? ["text"]) as string[];
|
|
3750
|
+
memberEntries.push({
|
|
3751
|
+
id: `combo-ref:${comboName}`,
|
|
3752
|
+
context_length: nestedEntry.limit?.context ?? 0,
|
|
3753
|
+
max_output_tokens: nestedEntry.limit?.output ?? 0,
|
|
3754
|
+
max_input_tokens: 0,
|
|
3755
|
+
owned_by: "combo",
|
|
3756
|
+
input_modalities: inputModalities,
|
|
3757
|
+
output_modalities: outputModalities,
|
|
3758
|
+
capabilities: {
|
|
3759
|
+
temperature: nestedEntry.temperature,
|
|
3760
|
+
reasoning: nestedEntry.reasoning,
|
|
3761
|
+
thinking: nestedEntry.reasoning,
|
|
3762
|
+
attachment: nestedEntry.attachment,
|
|
3763
|
+
tool_calling: nestedEntry.tool_call,
|
|
3764
|
+
},
|
|
3765
|
+
} as unknown as OmniRouteRawModelEntry);
|
|
3766
|
+
continue;
|
|
3767
|
+
}
|
|
3768
|
+
|
|
3769
|
+
const modelId = (step as unknown as { model?: unknown }).model;
|
|
3770
|
+
if (typeof modelId !== "string" || modelId.length === 0) continue;
|
|
3771
|
+
const member = rawModelById.get(modelId);
|
|
3772
|
+
if (member) memberEntries.push(member);
|
|
3773
|
+
}
|
|
3774
|
+
|
|
3775
|
+
if (deferredThisPass) {
|
|
3776
|
+
stillPendingStatic.push(combo);
|
|
3777
|
+
continue;
|
|
3778
|
+
}
|
|
3779
|
+
|
|
3780
|
+
const hasMembers = memberEntries.length > 0;
|
|
3781
|
+
const friendlyName =
|
|
3782
|
+
combo.name && combo.name.trim().length > 0 ? combo.name.trim() : combo.id;
|
|
3783
|
+
const displayName =
|
|
3784
|
+
hasMembers && compressionSuffix ? `${friendlyName} ${compressionSuffix}` : friendlyName;
|
|
3785
|
+
// See the raw-model entry comment above — `providerID` on entries is
|
|
3786
|
+
// not part of OC's static-catalog schema; the parent block ID is the
|
|
3787
|
+
// provider and the KEY prefix (`omniroute/<slug>`) is what OC parses.
|
|
3788
|
+
const entry: OmniRouteStaticModelEntry = { name: displayName };
|
|
3789
|
+
|
|
3790
|
+
if (hasMembers) {
|
|
3791
|
+
// LCD across capabilities — every member must support for the combo
|
|
3792
|
+
// to support. Mirrors mapComboToModelV2.
|
|
3793
|
+
entry.attachment = memberEntries.every((m) =>
|
|
3794
|
+
Boolean(m.capabilities?.attachment ?? m.capabilities?.vision ?? false)
|
|
3795
|
+
);
|
|
3796
|
+
entry.reasoning = memberEntries.every((m) =>
|
|
3797
|
+
Boolean(m.capabilities?.reasoning || m.capabilities?.thinking)
|
|
3798
|
+
);
|
|
3799
|
+
entry.temperature = memberEntries.every(
|
|
3800
|
+
(m) => (m.capabilities?.temperature ?? true) !== false
|
|
3801
|
+
);
|
|
3802
|
+
entry.tool_call = memberEntries.every((m) =>
|
|
3803
|
+
Boolean(m.capabilities?.tool_calling ?? false)
|
|
3804
|
+
);
|
|
3805
|
+
|
|
3806
|
+
// LCD across limits — min over declared values. OC's SDK static schema
|
|
3807
|
+
// accepts only `context` + `output` on `limit`, so we drop the legacy
|
|
3808
|
+
// `input` emission. Emit only when BOTH context AND output are known
|
|
3809
|
+
// across at least one member (mirrors the required-field constraint).
|
|
3810
|
+
const contextValues = memberEntries
|
|
3811
|
+
.map((m) => m.context_length)
|
|
3812
|
+
.filter((v): v is number => typeof v === "number" && v > 0);
|
|
3813
|
+
const outputValues = memberEntries
|
|
3814
|
+
.map((m) => m.max_output_tokens)
|
|
3815
|
+
.filter((v): v is number => typeof v === "number" && v > 0);
|
|
3816
|
+
|
|
3817
|
+
if (contextValues.length > 0 && outputValues.length > 0) {
|
|
3818
|
+
entry.limit = {
|
|
3819
|
+
context: Math.min(...contextValues),
|
|
3820
|
+
output: Math.min(...outputValues),
|
|
3821
|
+
};
|
|
3822
|
+
}
|
|
3823
|
+
|
|
3824
|
+
// LCD across modalities — combo accepts modality M iff every member
|
|
3825
|
+
// accepts M. Same intersection rule as runtime capabilities.
|
|
3826
|
+
const inSets = memberEntries.map((m) => new Set(normaliseModalities(m.input_modalities)));
|
|
3827
|
+
const outSets = memberEntries.map((m) => new Set(normaliseModalities(m.output_modalities)));
|
|
3828
|
+
const intersect = (sets: Set<OmniRouteModalityKind>[]): OmniRouteModalityKind[] => {
|
|
3829
|
+
if (sets.length === 0) return [];
|
|
3830
|
+
const [first, ...rest] = sets;
|
|
3831
|
+
const out: OmniRouteModalityKind[] = [];
|
|
3832
|
+
for (const v of first) {
|
|
3833
|
+
if (rest.every((s) => s.has(v))) out.push(v);
|
|
3834
|
+
}
|
|
3835
|
+
return out;
|
|
3836
|
+
};
|
|
3837
|
+
const inModalities = intersect(inSets);
|
|
3838
|
+
const outModalities = intersect(outSets);
|
|
3839
|
+
if (inModalities.length > 0 || outModalities.length > 0) {
|
|
3840
|
+
entry.modalities = {
|
|
3841
|
+
input: inModalities.length > 0 ? inModalities : ["text"],
|
|
3842
|
+
output: outModalities.length > 0 ? outModalities : ["text"],
|
|
3843
|
+
};
|
|
3844
|
+
}
|
|
3845
|
+
} else {
|
|
3846
|
+
// Empty members → safety posture: all caps false. Caller's OC picker
|
|
3847
|
+
// will grey out an unroutable combo rather than promise capabilities
|
|
3848
|
+
// we can't honour.
|
|
3849
|
+
entry.attachment = false;
|
|
3850
|
+
entry.reasoning = false;
|
|
3851
|
+
entry.temperature = false;
|
|
3852
|
+
entry.tool_call = false;
|
|
3853
|
+
}
|
|
3854
|
+
|
|
3855
|
+
// Key under bare slug (e.g. `claude-primary`) — no `combo/` prefix
|
|
3856
|
+
// because OpenCode parses model IDs on `/` and would treat
|
|
3857
|
+
// `combo/MASTER` as provider=`combo`. Slug collisions across
|
|
3858
|
+
// combos are disambiguated with a short UUID-prefix suffix; see
|
|
3859
|
+
// `buildComboKey` for the policy.
|
|
3860
|
+
models[buildComboKey(combo, usedComboKeys, opts.providerId)] = entry;
|
|
3861
|
+
|
|
3862
|
+
// Make this combo's resolved entry available to parent combos
|
|
3863
|
+
// that reference it via combo-ref. Use the friendly name since
|
|
3864
|
+
// that's the lookup key on the parent side.
|
|
3865
|
+
resolvedStaticCombosByName.set(friendlyName, entry);
|
|
3866
|
+
}
|
|
3867
|
+
|
|
3868
|
+
if (stillPendingStatic.length === pendingStatic.length) {
|
|
3869
|
+
// No progress in this pass — remaining combos have unresolvable
|
|
3870
|
+
// refs (missing nested combo, circular graph, or nested combo
|
|
3871
|
+
// with no members). Break early to avoid wasting the pass budget.
|
|
3872
|
+
break;
|
|
3873
|
+
}
|
|
3874
|
+
pendingStatic = stillPendingStatic;
|
|
3875
|
+
}
|
|
3876
|
+
|
|
3877
|
+
if (pendingStatic.length > 0) {
|
|
3878
|
+
console.warn(
|
|
3879
|
+
`[omniroute-plugin] ${pendingStatic.length} combo(s) in the static catalog could not resolve all nested combo-refs after ${MAX_STATIC_COMBO_PASSES} passes; they will be omitted.`
|
|
3880
|
+
);
|
|
3881
|
+
}
|
|
3882
|
+
|
|
3883
|
+
// ── Auto combos ────────────────────────────────────────────────────────
|
|
3884
|
+
// Virtual server-side combos (auto/coding, auto/fast, etc.) are fetched
|
|
3885
|
+
// from /api/combos/auto and added as model entries. They self-manage
|
|
3886
|
+
// provider selection at runtime via scoring/bandit exploration.
|
|
3887
|
+
if (rawAutoCombos && rawAutoCombos.length > 0) {
|
|
3888
|
+
for (const autoCombo of rawAutoCombos) {
|
|
3889
|
+
if (!autoCombo || !autoCombo.id) continue;
|
|
3890
|
+
if (autoCombo.isHidden === true) continue;
|
|
3891
|
+
const entry = mapAutoComboToStaticEntry(autoCombo);
|
|
3892
|
+
// Use the variant as the key: "auto", "auto/coding", etc.
|
|
3893
|
+
const key = autoComboModelId(autoCombo.variant);
|
|
3894
|
+
if (models[key]) {
|
|
3895
|
+
// Collision with a raw model or DB combo — auto combo wins (log once)
|
|
3896
|
+
if (!reportedCollisions.has(key)) {
|
|
3897
|
+
reportedCollisions.add(key);
|
|
3898
|
+
console.warn(
|
|
3899
|
+
`[omniroute-plugin] auto combo key "${key}" collides with an existing model; auto combo wins.`
|
|
3900
|
+
);
|
|
3901
|
+
}
|
|
3902
|
+
}
|
|
3903
|
+
models[key] = entry;
|
|
3904
|
+
}
|
|
3905
|
+
}
|
|
3906
|
+
|
|
3907
|
+
return {
|
|
3908
|
+
npm: "@ai-sdk/openai-compatible",
|
|
3909
|
+
name: opts.displayName,
|
|
3910
|
+
options: { baseURL, apiKey },
|
|
3911
|
+
models,
|
|
3912
|
+
};
|
|
3913
|
+
}
|
|
3914
|
+
|
|
3915
|
+
/**
|
|
3916
|
+
* Shape we expect inside `auth.json`. The file is keyed by providerId, with
|
|
3917
|
+
* each entry being a flavor-tagged credential. Today only the `api` flavor
|
|
3918
|
+
* is consumed by this plugin (OAuth + WellKnown flavors are passed through
|
|
3919
|
+
* but never decoded into a static block).
|
|
3920
|
+
*/
|
|
3921
|
+
interface AuthJsonApiEntry {
|
|
3922
|
+
type: "api";
|
|
3923
|
+
key: string;
|
|
3924
|
+
baseURL?: string;
|
|
3925
|
+
}
|
|
3926
|
+
|
|
3927
|
+
type AuthJsonShape = Record<string, AuthJsonApiEntry | { type?: string; [k: string]: unknown }>;
|
|
3928
|
+
|
|
3929
|
+
/**
|
|
3930
|
+
* Read & parse `auth.json` from OC's data dir. The path resolution mirrors
|
|
3931
|
+
* OC core's:
|
|
3932
|
+
*
|
|
3933
|
+
* `${OPENCODE_DATA_DIR ?? path.join(os.homedir(), ".local/share/opencode")}/auth.json`
|
|
3934
|
+
*
|
|
3935
|
+
* Returns `undefined` when the file is missing (most-common case on a fresh
|
|
3936
|
+
* install — silent no-op). Returns `null` when the file exists but doesn't
|
|
3937
|
+
* parse as JSON (logs ONE warn so the operator sees the corruption).
|
|
3938
|
+
*
|
|
3939
|
+
* Exported as a dependency-injectable function on `createOmniRouteConfigHook`
|
|
3940
|
+
* so tests can stub it without monkey-patching `node:fs/promises`.
|
|
3941
|
+
*/
|
|
3942
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
3943
|
+
// Disk-cache fallback. Persists the last successful raw-fetch snapshot to
|
|
3944
|
+
// `${OPENCODE_DATA_DIR ?? ~/.local/share/opencode}/plugins/omniroute-<providerId>.json`.
|
|
3945
|
+
// When `/v1/models` is unreachable (e.g. IP whitelist drop, offline laptop)
|
|
3946
|
+
// AND the in-memory cache is cold, the config hook reads from disk so the
|
|
3947
|
+
// last-known catalog still surfaces in OC's model picker. Feature-flagged:
|
|
3948
|
+
// `features.diskCache !== false` (default-on).
|
|
3949
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
3950
|
+
|
|
3951
|
+
/** Disk snapshot envelope. Versioned for forward-compat. */
|
|
3952
|
+
interface OmniRouteDiskSnapshot {
|
|
3953
|
+
v: 1;
|
|
3954
|
+
rawModels: OmniRouteRawModelEntry[];
|
|
3955
|
+
rawCombos: OmniRouteRawCombo[];
|
|
3956
|
+
rawAutoCombos?: OmniRouteRawAutoCombo[];
|
|
3957
|
+
/** Serialised as array-of-pairs (Map is not JSON-friendly). */
|
|
3958
|
+
rawEnrichment: Array<[string, OmniRouteEnrichmentEntry]>;
|
|
3959
|
+
rawCompressionCombos: OmniRouteCompressionCombo[];
|
|
3960
|
+
rawConnections: OmniRouteProviderConnection[];
|
|
3961
|
+
/** When the snapshot was written (epoch ms). */
|
|
3962
|
+
writtenAt: number;
|
|
3963
|
+
}
|
|
3964
|
+
|
|
3965
|
+
/** Resolve the disk-snapshot path for a given providerId. */
|
|
3966
|
+
export function diskSnapshotPath(providerId: string): string {
|
|
3967
|
+
const dir = process.env.OPENCODE_DATA_DIR ?? path.join(os.homedir(), ".local/share/opencode");
|
|
3968
|
+
return path.join(dir, "plugins", `omniroute-${providerId}.json`);
|
|
3969
|
+
}
|
|
3970
|
+
|
|
3971
|
+
export type OmniRouteDiskSnapshotWriter = (
|
|
3972
|
+
providerId: string,
|
|
3973
|
+
entry: Omit<OmniRouteFetchCacheEntry, "expiresAt">
|
|
3974
|
+
) => Promise<void>;
|
|
3975
|
+
|
|
3976
|
+
export type OmniRouteDiskSnapshotReader = (
|
|
3977
|
+
providerId: string
|
|
3978
|
+
) => Promise<Omit<OmniRouteFetchCacheEntry, "expiresAt"> | undefined>;
|
|
3979
|
+
|
|
3980
|
+
/** Best-effort disk write. Soft-fails on any I/O error (no exception thrown). */
|
|
3981
|
+
export const defaultDiskSnapshotWriter: OmniRouteDiskSnapshotWriter = async (providerId, entry) => {
|
|
3982
|
+
try {
|
|
3983
|
+
const file = diskSnapshotPath(providerId);
|
|
3984
|
+
// Restrict perms to the owner: the snapshot lives alongside auth.json
|
|
3985
|
+
// (0o600) and embeds provider topology + masked connection records.
|
|
3986
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
3987
|
+
const snapshot: OmniRouteDiskSnapshot = {
|
|
3988
|
+
v: 1,
|
|
3989
|
+
rawModels: entry.rawModels,
|
|
3990
|
+
rawCombos: entry.rawCombos,
|
|
3991
|
+
rawAutoCombos: entry.rawAutoCombos,
|
|
3992
|
+
rawEnrichment: Array.from(entry.rawEnrichment.entries()),
|
|
3993
|
+
rawCompressionCombos: entry.rawCompressionCombos,
|
|
3994
|
+
rawConnections: entry.rawConnections,
|
|
3995
|
+
writtenAt: Date.now(),
|
|
3996
|
+
};
|
|
3997
|
+
await writeFile(file, JSON.stringify(snapshot), {
|
|
3998
|
+
encoding: "utf8",
|
|
3999
|
+
mode: 0o600,
|
|
4000
|
+
});
|
|
4001
|
+
} catch {
|
|
4002
|
+
// Soft-fail; caller already has the in-memory cache.
|
|
4003
|
+
}
|
|
4004
|
+
};
|
|
4005
|
+
|
|
4006
|
+
/** Best-effort disk read. Returns `undefined` when missing/corrupt/unreadable. */
|
|
4007
|
+
export const defaultDiskSnapshotReader: OmniRouteDiskSnapshotReader = async (providerId) => {
|
|
4008
|
+
try {
|
|
4009
|
+
const file = diskSnapshotPath(providerId);
|
|
4010
|
+
const body = await readFile(file, "utf8");
|
|
4011
|
+
const parsed = JSON.parse(body) as Partial<OmniRouteDiskSnapshot>;
|
|
4012
|
+
if (!parsed || parsed.v !== 1) return undefined;
|
|
4013
|
+
return {
|
|
4014
|
+
rawModels: Array.isArray(parsed.rawModels) ? parsed.rawModels : [],
|
|
4015
|
+
rawCombos: Array.isArray(parsed.rawCombos) ? parsed.rawCombos : [],
|
|
4016
|
+
rawAutoCombos: Array.isArray(parsed.rawAutoCombos) ? parsed.rawAutoCombos : [],
|
|
4017
|
+
rawEnrichment: new Map(Array.isArray(parsed.rawEnrichment) ? parsed.rawEnrichment : []),
|
|
4018
|
+
rawCompressionCombos: Array.isArray(parsed.rawCompressionCombos)
|
|
4019
|
+
? parsed.rawCompressionCombos
|
|
4020
|
+
: [],
|
|
4021
|
+
rawConnections: Array.isArray(parsed.rawConnections) ? parsed.rawConnections : [],
|
|
4022
|
+
};
|
|
4023
|
+
} catch {
|
|
4024
|
+
return undefined;
|
|
4025
|
+
}
|
|
4026
|
+
};
|
|
4027
|
+
|
|
4028
|
+
/** No-op disk-cache pair — used by tests to avoid filesystem side effects. */
|
|
4029
|
+
export const noopDiskSnapshotWriter: OmniRouteDiskSnapshotWriter = async () => {};
|
|
4030
|
+
|
|
4031
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
4032
|
+
// Debug logging (features.debugLog)
|
|
4033
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
4034
|
+
|
|
4035
|
+
/**
|
|
4036
|
+
* One captured request/response pair written to the debug JSONL log.
|
|
4037
|
+
* Schema documented in the schema-aware `DebugLogEntry` interface below.
|
|
4038
|
+
*/
|
|
4039
|
+
export interface DebugLogEntry {
|
|
4040
|
+
reqId: string;
|
|
4041
|
+
providerId: string;
|
|
4042
|
+
ts: number;
|
|
4043
|
+
url: string;
|
|
4044
|
+
method: string;
|
|
4045
|
+
reqHeaders: Record<string, string>;
|
|
4046
|
+
reqBody: unknown;
|
|
4047
|
+
resStatus: number | null;
|
|
4048
|
+
resHeaders: Record<string, string>;
|
|
4049
|
+
resBody: unknown;
|
|
4050
|
+
durationMs: number | null;
|
|
4051
|
+
error?: string;
|
|
4052
|
+
}
|
|
4053
|
+
|
|
4054
|
+
function debugLogDir(): string {
|
|
4055
|
+
return join(
|
|
4056
|
+
process.env.OPENCODE_DATA_DIR ?? join(homedir(), ".local", "share", "opencode"),
|
|
4057
|
+
"plugins"
|
|
4058
|
+
);
|
|
4059
|
+
}
|
|
4060
|
+
|
|
4061
|
+
function debugLogPath(providerId: string): string {
|
|
4062
|
+
return join(debugLogDir(), `omniroute-debug-${providerId}.jsonl`);
|
|
4063
|
+
}
|
|
4064
|
+
|
|
4065
|
+
function debugStatePath(providerId: string): string {
|
|
4066
|
+
return join(debugLogDir(), `omniroute-debug-${providerId}.state.json`);
|
|
4067
|
+
}
|
|
4068
|
+
|
|
4069
|
+
export function debugLogEnabled(providerId: string): boolean {
|
|
4070
|
+
try {
|
|
4071
|
+
const p = debugStatePath(providerId);
|
|
4072
|
+
if (!existsSync(p)) return false;
|
|
4073
|
+
const s = JSON.parse(readFileSync(p, "utf8")) as { enabled?: boolean };
|
|
4074
|
+
return s.enabled === true;
|
|
4075
|
+
} catch {
|
|
4076
|
+
return false;
|
|
4077
|
+
}
|
|
4078
|
+
}
|
|
4079
|
+
|
|
4080
|
+
export function debugLogSetEnabled(providerId: string, enabled: boolean): void {
|
|
4081
|
+
try {
|
|
4082
|
+
const dir = debugLogDir();
|
|
4083
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
4084
|
+
writeFileSync(debugStatePath(providerId), JSON.stringify({ enabled, ts: Date.now() }, null, 2));
|
|
4085
|
+
} catch (err) {
|
|
4086
|
+
// best-effort; never break the auth flow
|
|
4087
|
+
console.warn(`[omniroute-plugin] debugLogSetEnabled failed: ${(err as Error).message}`);
|
|
4088
|
+
}
|
|
4089
|
+
}
|
|
4090
|
+
|
|
4091
|
+
export function debugLogAppend(entry: DebugLogEntry): void {
|
|
4092
|
+
try {
|
|
4093
|
+
const dir = debugLogDir();
|
|
4094
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
4095
|
+
appendFileSync(debugLogPath(entry.providerId), JSON.stringify(entry) + "\n", "utf8");
|
|
4096
|
+
} catch (err) {
|
|
4097
|
+
console.warn(`[omniroute-plugin] debugLogAppend failed: ${(err as Error).message}`);
|
|
4098
|
+
}
|
|
4099
|
+
}
|
|
4100
|
+
|
|
4101
|
+
export function debugLogRead(providerId: string, limit = 20): DebugLogEntry[] {
|
|
4102
|
+
try {
|
|
4103
|
+
const p = debugLogPath(providerId);
|
|
4104
|
+
if (!existsSync(p)) return [];
|
|
4105
|
+
const lines = readFileSync(p, "utf8").trim().split("\n").filter(Boolean);
|
|
4106
|
+
return lines
|
|
4107
|
+
.slice(-limit)
|
|
4108
|
+
.map((line) => {
|
|
4109
|
+
try {
|
|
4110
|
+
return JSON.parse(line) as DebugLogEntry;
|
|
4111
|
+
} catch {
|
|
4112
|
+
return null;
|
|
4113
|
+
}
|
|
4114
|
+
})
|
|
4115
|
+
.filter((e): e is DebugLogEntry => e !== null);
|
|
4116
|
+
} catch {
|
|
4117
|
+
return [];
|
|
4118
|
+
}
|
|
4119
|
+
}
|
|
4120
|
+
|
|
4121
|
+
export function debugLogGetById(providerId: string, reqId: string): DebugLogEntry | null {
|
|
4122
|
+
try {
|
|
4123
|
+
const p = debugLogPath(providerId);
|
|
4124
|
+
if (!existsSync(p)) return null;
|
|
4125
|
+
const lines = readFileSync(p, "utf8").trim().split("\n").filter(Boolean);
|
|
4126
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
4127
|
+
try {
|
|
4128
|
+
const e = JSON.parse(lines[i]) as DebugLogEntry;
|
|
4129
|
+
if (e.reqId === reqId) return e;
|
|
4130
|
+
} catch {
|
|
4131
|
+
// skip malformed
|
|
4132
|
+
}
|
|
4133
|
+
}
|
|
4134
|
+
return null;
|
|
4135
|
+
} catch {
|
|
4136
|
+
return null;
|
|
4137
|
+
}
|
|
4138
|
+
}
|
|
4139
|
+
|
|
4140
|
+
export function debugLogClear(providerId: string): void {
|
|
4141
|
+
try {
|
|
4142
|
+
const p = debugLogPath(providerId);
|
|
4143
|
+
if (existsSync(p)) writeFileSync(p, "", "utf8");
|
|
4144
|
+
} catch (err) {
|
|
4145
|
+
console.warn(`[omniroute-plugin] debugLogClear failed: ${(err as Error).message}`);
|
|
4146
|
+
}
|
|
4147
|
+
}
|
|
4148
|
+
|
|
4149
|
+
/**
|
|
4150
|
+
* Wrap a fetch function to capture request/response pairs into the debug
|
|
4151
|
+
* JSONL log. Honours the `featureDefault` opt-in flag and the on-disk
|
|
4152
|
+
* runtime toggle (`debugLogEnabled`).
|
|
4153
|
+
*/
|
|
4154
|
+
export function createDebugLoggingFetch(
|
|
4155
|
+
inner: typeof fetch,
|
|
4156
|
+
providerId: string,
|
|
4157
|
+
featureDefault: boolean
|
|
4158
|
+
): typeof fetch {
|
|
4159
|
+
return async (input, init) => {
|
|
4160
|
+
const active = featureDefault || debugLogEnabled(providerId);
|
|
4161
|
+
if (!active) return inner(input, init);
|
|
4162
|
+
const reqId = randomUUID();
|
|
4163
|
+
const url =
|
|
4164
|
+
typeof input === "string"
|
|
4165
|
+
? input
|
|
4166
|
+
: input instanceof URL
|
|
4167
|
+
? input.toString()
|
|
4168
|
+
: input instanceof Request
|
|
4169
|
+
? input.url
|
|
4170
|
+
: String(input);
|
|
4171
|
+
const method = (
|
|
4172
|
+
init?.method ?? (typeof input === "string" ? "GET" : ((input as Request).method ?? "GET"))
|
|
4173
|
+
).toUpperCase();
|
|
4174
|
+
const reqHeaders: Record<string, string> = {};
|
|
4175
|
+
if (input instanceof Request) {
|
|
4176
|
+
input.headers.forEach((v, k) => (reqHeaders[k] = v));
|
|
4177
|
+
}
|
|
4178
|
+
if (init?.headers) {
|
|
4179
|
+
const h = init.headers;
|
|
4180
|
+
if (h instanceof Headers) h.forEach((v, k) => (reqHeaders[k] = v));
|
|
4181
|
+
else if (Array.isArray(h)) for (const [k, v] of h) reqHeaders[k] = v;
|
|
4182
|
+
else Object.assign(reqHeaders, h);
|
|
4183
|
+
}
|
|
4184
|
+
let reqBody: unknown = undefined;
|
|
4185
|
+
if (init?.body) {
|
|
4186
|
+
if (typeof init.body === "string") {
|
|
4187
|
+
try {
|
|
4188
|
+
reqBody = JSON.parse(init.body);
|
|
4189
|
+
} catch {
|
|
4190
|
+
reqBody = init.body.slice(0, 4096);
|
|
4191
|
+
}
|
|
4192
|
+
} else {
|
|
4193
|
+
reqBody = "[non-string body]";
|
|
4194
|
+
}
|
|
4195
|
+
} else if (input instanceof Request) {
|
|
4196
|
+
try {
|
|
4197
|
+
const clonedReq = input.clone();
|
|
4198
|
+
const text = await clonedReq.text();
|
|
4199
|
+
try {
|
|
4200
|
+
reqBody = JSON.parse(text);
|
|
4201
|
+
} catch {
|
|
4202
|
+
reqBody = text.slice(0, 4096);
|
|
4203
|
+
}
|
|
4204
|
+
} catch {
|
|
4205
|
+
reqBody = "[body unreadable]";
|
|
4206
|
+
}
|
|
4207
|
+
}
|
|
4208
|
+
const t0 = Date.now();
|
|
4209
|
+
try {
|
|
4210
|
+
const res = await inner(input, init);
|
|
4211
|
+
const durationMs = Date.now() - t0;
|
|
4212
|
+
const resHeaders: Record<string, string> = {};
|
|
4213
|
+
res.headers.forEach((v, k) => (resHeaders[k] = v));
|
|
4214
|
+
let resBody: unknown = undefined;
|
|
4215
|
+
try {
|
|
4216
|
+
const clone = res.clone();
|
|
4217
|
+
const ct = clone.headers.get("content-type") ?? "";
|
|
4218
|
+
if (ct.includes("application/json")) {
|
|
4219
|
+
resBody = await clone.json();
|
|
4220
|
+
} else if (ct.includes("text/event-stream")) {
|
|
4221
|
+
resBody = "[stream]";
|
|
4222
|
+
} else if (ct.includes("text/")) {
|
|
4223
|
+
const txt = await clone.text();
|
|
4224
|
+
resBody = txt.length > 4096 ? txt.slice(0, 4096) + "...[truncated]" : txt;
|
|
4225
|
+
} else {
|
|
4226
|
+
resBody = `[${ct || "unknown"} body, status ${res.status}]`;
|
|
4227
|
+
}
|
|
4228
|
+
} catch {
|
|
4229
|
+
resBody = "[body unparseable]";
|
|
4230
|
+
}
|
|
4231
|
+
debugLogAppend({
|
|
4232
|
+
reqId,
|
|
4233
|
+
providerId,
|
|
4234
|
+
ts: t0,
|
|
4235
|
+
url,
|
|
4236
|
+
method,
|
|
4237
|
+
reqHeaders,
|
|
4238
|
+
reqBody,
|
|
4239
|
+
resStatus: res.status,
|
|
4240
|
+
resHeaders,
|
|
4241
|
+
resBody,
|
|
4242
|
+
durationMs,
|
|
4243
|
+
});
|
|
4244
|
+
return res;
|
|
4245
|
+
} catch (err) {
|
|
4246
|
+
const durationMs = Date.now() - t0;
|
|
4247
|
+
debugLogAppend({
|
|
4248
|
+
reqId,
|
|
4249
|
+
providerId,
|
|
4250
|
+
ts: t0,
|
|
4251
|
+
url,
|
|
4252
|
+
method,
|
|
4253
|
+
reqHeaders,
|
|
4254
|
+
reqBody,
|
|
4255
|
+
resStatus: null,
|
|
4256
|
+
resHeaders: {},
|
|
4257
|
+
resBody: undefined,
|
|
4258
|
+
durationMs,
|
|
4259
|
+
error: (err as Error).message,
|
|
4260
|
+
});
|
|
4261
|
+
throw err;
|
|
4262
|
+
}
|
|
4263
|
+
};
|
|
4264
|
+
}
|
|
4265
|
+
export const noopDiskSnapshotReader: OmniRouteDiskSnapshotReader = async () => undefined;
|
|
4266
|
+
|
|
4267
|
+
export type OmniRouteReadAuthJson = () => Promise<AuthJsonShape | undefined | null>;
|
|
4268
|
+
|
|
4269
|
+
export const defaultReadAuthJson: OmniRouteReadAuthJson = async () => {
|
|
4270
|
+
const dir = process.env.OPENCODE_DATA_DIR ?? path.join(os.homedir(), ".local/share/opencode");
|
|
4271
|
+
const file = path.join(dir, "auth.json");
|
|
4272
|
+
let body: string;
|
|
4273
|
+
try {
|
|
4274
|
+
body = await readFile(file, "utf8");
|
|
4275
|
+
} catch {
|
|
4276
|
+
// File missing or unreadable — silent no-op. This is the expected path
|
|
4277
|
+
// on a fresh install BEFORE `/connect` has been run.
|
|
4278
|
+
return undefined;
|
|
4279
|
+
}
|
|
4280
|
+
try {
|
|
4281
|
+
const parsed = JSON.parse(body) as unknown;
|
|
4282
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
4283
|
+
return parsed as AuthJsonShape;
|
|
4284
|
+
}
|
|
4285
|
+
return null;
|
|
4286
|
+
} catch {
|
|
4287
|
+
return null;
|
|
4288
|
+
}
|
|
4289
|
+
};
|
|
4290
|
+
|
|
4291
|
+
/**
|
|
4292
|
+
* Build the config-hook portion of the plugin for a given options bag.
|
|
4293
|
+
* Exported standalone so the contract is unit-testable without faking the
|
|
4294
|
+
* full PluginInput / Hooks surface, and so multi-instance setups can each
|
|
4295
|
+
* own their own (auth.json reader, fetch cache, fetcher) trio.
|
|
4296
|
+
*
|
|
4297
|
+
* Behavioural contract:
|
|
4298
|
+
* - Runs BEFORE `auth.loader` in the OC startup sequence (per the
|
|
4299
|
+
* @opencode-ai/plugin contract). `getAuth()` is NOT available here,
|
|
4300
|
+
* so we read `auth.json` directly via the injected reader.
|
|
4301
|
+
* - No-op when:
|
|
4302
|
+
* (a) `auth.json` is missing / unreadable (fresh install before
|
|
4303
|
+
* `/connect`),
|
|
4304
|
+
* (b) `auth.json[providerId]` is missing or not type-api,
|
|
4305
|
+
* (c) `apiKey` is empty after extraction,
|
|
4306
|
+
* (d) `baseURL` is unresolvable (neither opts.baseURL nor
|
|
4307
|
+
* `auth.json[providerId].baseURL`),
|
|
4308
|
+
* (e) `input.provider[providerId]` is ALREADY set (operator override
|
|
4309
|
+
* wins — we never clobber manually-curated catalogs).
|
|
4310
|
+
* Each no-op path emits ONE debug-level breadcrumb to `console.warn`
|
|
4311
|
+
* so the operator can diagnose without log spam. Malformed `auth.json`
|
|
4312
|
+
* warns once and continues as if the file were missing.
|
|
4313
|
+
* - Fail-open on fetcher errors: a `/v1/models` failure → still publish
|
|
4314
|
+
* a stub `{models: {}}` provider block (so OC has a complete-shape
|
|
4315
|
+
* entry to render). A `/api/combos` failure → publish models-only.
|
|
4316
|
+
* Both paths emit ONE `console.warn`.
|
|
4317
|
+
* - When the provider hook (T-03/T-05) has ALREADY populated the shared
|
|
4318
|
+
* cache for this (baseURL, apiKey) tuple, we reuse the raw payloads
|
|
4319
|
+
* directly — no second fetch. (And vice-versa: the config hook fires
|
|
4320
|
+
* first on OC ≥1.14.49 cold start, populating the cache for the
|
|
4321
|
+
* provider hook moments later.)
|
|
4322
|
+
* - DUAL-PUBLISH SAFE: on OC ≥1.14.49 BOTH this static block and the
|
|
4323
|
+
* dynamic `provider.models()` result will land in OC's catalog
|
|
4324
|
+
* reducer. The dynamic block wins by OC's own merge rule — see
|
|
4325
|
+
* OpenCode core's provider resolution order — so emitting both is a
|
|
4326
|
+
* correctness-positive: ≤1.14.48 reads static, ≥1.14.49 prefers
|
|
4327
|
+
* dynamic but the static one keeps things responsive during the
|
|
4328
|
+
* ~50ms window before the dynamic fetch resolves.
|
|
4329
|
+
*
|
|
4330
|
+
* @param opts Plugin options (validated, resolved with defaults).
|
|
4331
|
+
* @param deps Dependency injection.
|
|
4332
|
+
* - `readAuthJson` — replaces `defaultReadAuthJson` (test stub).
|
|
4333
|
+
* - `fetcher` — replaces `defaultOmniRouteModelsFetcher`.
|
|
4334
|
+
* - `combosFetcher` — replaces `defaultOmniRouteCombosFetcher`.
|
|
4335
|
+
* - `now` — clock for cache TTL (default `Date.now`).
|
|
4336
|
+
* - `cache` — shared fetch-result cache (see
|
|
4337
|
+
* `OmniRouteFetchCache`). Pass the same Map the
|
|
4338
|
+
* provider hook owns to dedupe round-trips.
|
|
4339
|
+
* - `logger` — `{warn}` sink for breadcrumb capture in tests.
|
|
4340
|
+
* Defaults to `console`.
|
|
4341
|
+
*/
|
|
4342
|
+
export function createOmniRouteConfigHook(
|
|
4343
|
+
opts?: OmniRoutePluginOptions,
|
|
4344
|
+
deps: {
|
|
4345
|
+
readAuthJson?: OmniRouteReadAuthJson;
|
|
4346
|
+
fetcher?: OmniRouteModelsFetcher;
|
|
4347
|
+
combosFetcher?: OmniRouteCombosFetcher;
|
|
4348
|
+
autoCombosFetcher?: OmniRouteAutoCombosFetcher;
|
|
4349
|
+
enrichmentFetcher?: OmniRouteEnrichmentFetcher;
|
|
4350
|
+
compressionMetaFetcher?: OmniRouteCompressionMetaFetcher;
|
|
4351
|
+
providersFetcher?: OmniRouteProvidersFetcher;
|
|
4352
|
+
diskSnapshotReader?: OmniRouteDiskSnapshotReader;
|
|
4353
|
+
diskSnapshotWriter?: OmniRouteDiskSnapshotWriter;
|
|
4354
|
+
now?: () => number;
|
|
4355
|
+
cache?: OmniRouteFetchCache;
|
|
4356
|
+
logger?: { warn: (...args: unknown[]) => void };
|
|
4357
|
+
} = {}
|
|
4358
|
+
): (input: Config) => Promise<void> {
|
|
4359
|
+
const resolved = resolveOmniRoutePluginOptions(opts);
|
|
4360
|
+
const readAuthJson = deps.readAuthJson ?? defaultReadAuthJson;
|
|
4361
|
+
const fetcher = deps.fetcher ?? defaultOmniRouteModelsFetcher;
|
|
4362
|
+
const combosFetcher = deps.combosFetcher ?? defaultOmniRouteCombosFetcher;
|
|
4363
|
+
const autoCombosFetcher = deps.autoCombosFetcher ?? defaultOmniRouteAutoCombosFetcher;
|
|
4364
|
+
const enrichmentFetcher = deps.enrichmentFetcher ?? defaultOmniRouteEnrichmentFetcher;
|
|
4365
|
+
const compressionMetaFetcher =
|
|
4366
|
+
deps.compressionMetaFetcher ?? defaultOmniRouteCompressionMetaFetcher;
|
|
4367
|
+
const providersFetcher = deps.providersFetcher ?? defaultOmniRouteProvidersFetcher;
|
|
4368
|
+
const diskSnapshotReader = deps.diskSnapshotReader ?? defaultDiskSnapshotReader;
|
|
4369
|
+
const diskSnapshotWriter = deps.diskSnapshotWriter ?? defaultDiskSnapshotWriter;
|
|
4370
|
+
const now = deps.now ?? Date.now;
|
|
4371
|
+
const cache: OmniRouteFetchCache = deps.cache ?? new Map();
|
|
4372
|
+
const logger = deps.logger ?? console;
|
|
4373
|
+
const features = resolved.features ?? {};
|
|
4374
|
+
const wantAutoCombos = features.autoCombos !== false;
|
|
4375
|
+
const wantEnrichment = features.enrichment !== false;
|
|
4376
|
+
const wantCompressionMeta = features.compressionMetadata === true;
|
|
4377
|
+
const wantUsableOnly = features.usableOnly === true;
|
|
4378
|
+
const wantDiskCache = features.diskCache !== false;
|
|
4379
|
+
const wantProviderTag = features.providerTag !== false;
|
|
4380
|
+
|
|
4381
|
+
return async (input: Config) => {
|
|
4382
|
+
// (e) operator override — `input.provider[providerId]` already set →
|
|
4383
|
+
// leave it alone. Manually curated catalogs ALWAYS win over the plugin's
|
|
4384
|
+
// generated block. Detect-and-respect before any I/O.
|
|
4385
|
+
const existingProviders = (input as { provider?: Record<string, unknown> }).provider;
|
|
4386
|
+
if (existingProviders && existingProviders[resolved.providerId] !== undefined) {
|
|
4387
|
+
logger.warn(
|
|
4388
|
+
`[omniroute-plugin] config shim skipped: provider.${resolved.providerId} already set by user`
|
|
4389
|
+
);
|
|
4390
|
+
return;
|
|
4391
|
+
}
|
|
4392
|
+
|
|
4393
|
+
// Read auth.json. `undefined` = missing file (silent path), `null` =
|
|
4394
|
+
// malformed JSON (warn once and treat as missing).
|
|
4395
|
+
let authJson: AuthJsonShape | undefined | null;
|
|
4396
|
+
try {
|
|
4397
|
+
authJson = await readAuthJson();
|
|
4398
|
+
} catch {
|
|
4399
|
+
// Reader threw — be conservative and treat like a missing file.
|
|
4400
|
+
authJson = undefined;
|
|
4401
|
+
}
|
|
4402
|
+
|
|
4403
|
+
if (authJson === null) {
|
|
4404
|
+
logger.warn("[omniroute-plugin] config shim: auth.json failed to parse; treating as missing");
|
|
4405
|
+
authJson = undefined;
|
|
4406
|
+
}
|
|
4407
|
+
|
|
4408
|
+
// Try both prefixed (e.g. opencode-omniroute) and unprefixed (e.g. omniroute)
|
|
4409
|
+
// keys so a user who ran `/connect omniroute` before the auto-prefix fix
|
|
4410
|
+
// does not need to re-auth. Also handles dual-key for auth.json entries
|
|
4411
|
+
// written by a newer OC dispatcher with the prefixed key.
|
|
4412
|
+
const bareKey = resolved.providerId.startsWith("opencode-")
|
|
4413
|
+
? resolved.providerId.slice("opencode-".length)
|
|
4414
|
+
: resolved.providerId;
|
|
4415
|
+
const lookupKeys = [resolved.providerId];
|
|
4416
|
+
if (bareKey !== resolved.providerId) lookupKeys.push(bareKey);
|
|
4417
|
+
let entry;
|
|
4418
|
+
for (const k of lookupKeys) {
|
|
4419
|
+
const e = authJson?.[k];
|
|
4420
|
+
if (e?.type === "api" && typeof e.key === "string" && e.key.length > 0) {
|
|
4421
|
+
entry = e;
|
|
4422
|
+
break;
|
|
4423
|
+
}
|
|
4424
|
+
}
|
|
4425
|
+
const apiKey = entry?.type === "api" && typeof entry.key === "string" ? entry.key : "";
|
|
4426
|
+
|
|
4427
|
+
if (!apiKey) {
|
|
4428
|
+
// (c) no apiKey — silent no-op (with debug breadcrumb). The operator
|
|
4429
|
+
// hasn't run `/connect <providerId>` yet, OR the stored credential
|
|
4430
|
+
// isn't api-flavored. OC will handle the `/connect` flow at runtime.
|
|
4431
|
+
logger.warn(
|
|
4432
|
+
`[omniroute-plugin] config shim skipped: no apiKey for providerId=${resolved.providerId}`
|
|
4433
|
+
);
|
|
4434
|
+
return;
|
|
4435
|
+
}
|
|
4436
|
+
|
|
4437
|
+
// baseURL resolution: opts.baseURL wins, then auth.json's stored baseURL.
|
|
4438
|
+
// No silent localhost default — a misconfigured plugin should surface a
|
|
4439
|
+
// breadcrumb and skip, not phantom requests.
|
|
4440
|
+
const storedBaseURL = entry && typeof entry.baseURL === "string" ? entry.baseURL : undefined;
|
|
4441
|
+
const baseURL = resolved.baseURL ?? storedBaseURL ?? "";
|
|
4442
|
+
if (!baseURL) {
|
|
4443
|
+
logger.warn(
|
|
4444
|
+
`[omniroute-plugin] config shim skipped: no baseURL for providerId=${resolved.providerId}`
|
|
4445
|
+
);
|
|
4446
|
+
return;
|
|
4447
|
+
}
|
|
4448
|
+
|
|
4449
|
+
// Try the shared cache first. On OC ≥1.14.49 the provider hook may have
|
|
4450
|
+
// populated it moments earlier; on OC ≤1.14.48 only this hook runs but
|
|
4451
|
+
// the cache still works (single producer + consumer through one Map).
|
|
4452
|
+
const cacheKey = modelsCacheKey(baseURL, apiKey);
|
|
4453
|
+
const t = now();
|
|
4454
|
+
const cached = cache.get(cacheKey);
|
|
4455
|
+
|
|
4456
|
+
let rawModels: OmniRouteRawModelEntry[];
|
|
4457
|
+
let rawCombos: OmniRouteRawCombo[];
|
|
4458
|
+
let rawAutoCombos: OmniRouteRawAutoCombo[];
|
|
4459
|
+
let rawEnrichment: OmniRouteEnrichmentMap;
|
|
4460
|
+
let rawCompressionCombos: OmniRouteCompressionCombo[];
|
|
4461
|
+
let rawConnections: OmniRouteProviderConnection[];
|
|
4462
|
+
|
|
4463
|
+
if (cached && cached.expiresAt > t) {
|
|
4464
|
+
rawModels = cached.rawModels;
|
|
4465
|
+
rawCombos = cached.rawCombos;
|
|
4466
|
+
rawAutoCombos = cached.rawAutoCombos;
|
|
4467
|
+
rawEnrichment = cached.rawEnrichment;
|
|
4468
|
+
rawCompressionCombos = cached.rawCompressionCombos;
|
|
4469
|
+
rawConnections = cached.rawConnections;
|
|
4470
|
+
} else {
|
|
4471
|
+
// Fail-open fetcher errors: on /v1/models throw, fall back to empty
|
|
4472
|
+
// catalog (still publish a stub block so OC has a complete-shape
|
|
4473
|
+
// entry); on /api/combos throw, publish models-only. Disk-cache
|
|
4474
|
+
// fallback below recovers the last-known-good catalog when the
|
|
4475
|
+
// fetcher threw (network down / 403 / timeout) AND features.diskCache
|
|
4476
|
+
// !== false. A 0-entry SUCCESS (fresh tenant) does NOT trigger
|
|
4477
|
+
// disk fallback — that's a valid empty catalog.
|
|
4478
|
+
let modelsFetchThrew = false;
|
|
4479
|
+
try {
|
|
4480
|
+
rawModels = await fetcher(baseURL, apiKey, 10_000);
|
|
4481
|
+
} catch (err) {
|
|
4482
|
+
logger.warn(
|
|
4483
|
+
"[omniroute-plugin] config shim: /v1/models fetch failed; publishing stub provider entry",
|
|
4484
|
+
err
|
|
4485
|
+
);
|
|
4486
|
+
rawModels = [];
|
|
4487
|
+
modelsFetchThrew = true;
|
|
4488
|
+
}
|
|
4489
|
+
const modelsFetchOk = !modelsFetchThrew && rawModels.length > 0;
|
|
4490
|
+
|
|
4491
|
+
rawCombos = [];
|
|
4492
|
+
try {
|
|
4493
|
+
rawCombos = await combosFetcher(baseURL, apiKey, 10_000);
|
|
4494
|
+
} catch (err) {
|
|
4495
|
+
logger.warn(
|
|
4496
|
+
"[omniroute-plugin] config shim: /api/combos fetch failed; publishing models-only static catalog",
|
|
4497
|
+
err
|
|
4498
|
+
);
|
|
4499
|
+
}
|
|
4500
|
+
|
|
4501
|
+
rawAutoCombos = [];
|
|
4502
|
+
if (wantAutoCombos) {
|
|
4503
|
+
try {
|
|
4504
|
+
rawAutoCombos = await autoCombosFetcher(baseURL, apiKey, 5_000);
|
|
4505
|
+
} catch {
|
|
4506
|
+
// Already handled inside the default fetcher
|
|
4507
|
+
}
|
|
4508
|
+
}
|
|
4509
|
+
|
|
4510
|
+
// Eagerly fetch enrichment so the static block can overlay human
|
|
4511
|
+
// display names on raw model ids. On OC ≤1.15.5 the dynamic
|
|
4512
|
+
// `provider.models` hook never fires in `serve` mode, so the static
|
|
4513
|
+
// block IS what reaches `/provider` and the TUI model picker.
|
|
4514
|
+
// Gated by `features.enrichment` (default-on). Soft-fail on error —
|
|
4515
|
+
// we still publish a name-less catalog if /api/pricing/models is
|
|
4516
|
+
// unreachable.
|
|
4517
|
+
rawEnrichment = new Map();
|
|
4518
|
+
if (wantEnrichment) {
|
|
4519
|
+
try {
|
|
4520
|
+
rawEnrichment = await enrichmentFetcher(baseURL, apiKey, 10_000);
|
|
4521
|
+
} catch (err) {
|
|
4522
|
+
logger.warn(
|
|
4523
|
+
"[omniroute-plugin] config shim: /api/pricing/models fetch failed; publishing raw-id static catalog",
|
|
4524
|
+
err
|
|
4525
|
+
);
|
|
4526
|
+
}
|
|
4527
|
+
}
|
|
4528
|
+
|
|
4529
|
+
// Compression-metadata fetch — opt-in via features.compressionMetadata.
|
|
4530
|
+
// When on, the default pipeline is appended to every combo `name` so
|
|
4531
|
+
// the TUI picker advertises which compression a combo applies.
|
|
4532
|
+
rawCompressionCombos = [];
|
|
4533
|
+
if (wantCompressionMeta) {
|
|
4534
|
+
try {
|
|
4535
|
+
rawCompressionCombos = await compressionMetaFetcher(baseURL, apiKey, 10_000);
|
|
4536
|
+
} catch (err) {
|
|
4537
|
+
logger.warn(
|
|
4538
|
+
"[omniroute-plugin] config shim: /api/context/combos fetch failed; publishing combos without compression suffix",
|
|
4539
|
+
err
|
|
4540
|
+
);
|
|
4541
|
+
}
|
|
4542
|
+
}
|
|
4543
|
+
|
|
4544
|
+
// Provider-connections fetch — opt-in via features.usableOnly. When
|
|
4545
|
+
// on, the static catalog filters out models/combos whose canonical
|
|
4546
|
+
// provider has no active connection. Soft-fail (empty list) disables
|
|
4547
|
+
// the filter for this refresh, never hiding the whole catalog.
|
|
4548
|
+
rawConnections = [];
|
|
4549
|
+
if (wantUsableOnly) {
|
|
4550
|
+
try {
|
|
4551
|
+
rawConnections = await providersFetcher(baseURL, apiKey, 10_000);
|
|
4552
|
+
} catch (err) {
|
|
4553
|
+
logger.warn(
|
|
4554
|
+
"[omniroute-plugin] config shim: /api/providers fetch failed; usableOnly filter disabled for this refresh",
|
|
4555
|
+
err
|
|
4556
|
+
);
|
|
4557
|
+
}
|
|
4558
|
+
}
|
|
4559
|
+
|
|
4560
|
+
// Disk-cache fallback: when the live fetch returned no models AND
|
|
4561
|
+
// features.diskCache !== false, hydrate from the last-known-good
|
|
4562
|
+
// snapshot so OC still surfaces a usable catalog (e.g. IP whitelist
|
|
4563
|
+
// drop, offline laptop). The snapshot is whatever we last wrote on
|
|
4564
|
+
// a healthy refresh; staleness is bounded only by how recently the
|
|
4565
|
+
// user was online.
|
|
4566
|
+
if (modelsFetchThrew && wantDiskCache) {
|
|
4567
|
+
const snapshot = await diskSnapshotReader(resolved.providerId);
|
|
4568
|
+
if (snapshot && snapshot.rawModels.length > 0) {
|
|
4569
|
+
logger.warn(
|
|
4570
|
+
`[omniroute-plugin] config shim: /v1/models unreachable; using stale disk cache (${snapshot.rawModels.length} models)`
|
|
4571
|
+
);
|
|
4572
|
+
rawModels = snapshot.rawModels;
|
|
4573
|
+
rawCombos = snapshot.rawCombos;
|
|
4574
|
+
rawAutoCombos = snapshot.rawAutoCombos ?? [];
|
|
4575
|
+
rawEnrichment = snapshot.rawEnrichment;
|
|
4576
|
+
rawCompressionCombos = snapshot.rawCompressionCombos;
|
|
4577
|
+
rawConnections = snapshot.rawConnections;
|
|
4578
|
+
}
|
|
4579
|
+
}
|
|
4580
|
+
|
|
4581
|
+
// Cache even partial results — a subsequent provider-hook call should
|
|
4582
|
+
// not re-burn the timeout window on the same broken endpoint.
|
|
4583
|
+
cache.set(cacheKey, {
|
|
4584
|
+
rawModels,
|
|
4585
|
+
rawCombos,
|
|
4586
|
+
rawAutoCombos,
|
|
4587
|
+
rawEnrichment,
|
|
4588
|
+
rawCompressionCombos,
|
|
4589
|
+
rawConnections,
|
|
4590
|
+
expiresAt: t + resolved.modelCacheTtl,
|
|
4591
|
+
});
|
|
4592
|
+
|
|
4593
|
+
// Startup diagnostics (file-based) — fires at startup via config hook
|
|
4594
|
+
if (resolved.features?.startupDebug === true) {
|
|
4595
|
+
await writeStartupDiagnostics({
|
|
4596
|
+
providerId: resolved.providerId,
|
|
4597
|
+
baseURL,
|
|
4598
|
+
modelCount: rawModels.length,
|
|
4599
|
+
comboCount: rawCombos.length,
|
|
4600
|
+
enrichmentSize: rawEnrichment.size,
|
|
4601
|
+
autoComboCount: rawAutoCombos.length,
|
|
4602
|
+
enrichment: rawEnrichment,
|
|
4603
|
+
autoCombos: rawAutoCombos,
|
|
4604
|
+
});
|
|
4605
|
+
}
|
|
4606
|
+
|
|
4607
|
+
// Disk-cache write: persist the last successful (or any non-empty)
|
|
4608
|
+
// catalog so a subsequent cold start with a failed fetch can recover.
|
|
4609
|
+
// Best-effort; soft-fail keeps us moving when the data dir isn't
|
|
4610
|
+
// writable (e.g. read-only container).
|
|
4611
|
+
if (modelsFetchOk && wantDiskCache) {
|
|
4612
|
+
await diskSnapshotWriter(resolved.providerId, {
|
|
4613
|
+
rawModels,
|
|
4614
|
+
rawCombos,
|
|
4615
|
+
rawAutoCombos,
|
|
4616
|
+
rawEnrichment,
|
|
4617
|
+
rawCompressionCombos,
|
|
4618
|
+
rawConnections,
|
|
4619
|
+
});
|
|
4620
|
+
}
|
|
4621
|
+
}
|
|
4622
|
+
|
|
4623
|
+
const block = buildStaticProviderEntry(
|
|
4624
|
+
rawModels,
|
|
4625
|
+
rawCombos,
|
|
4626
|
+
resolved,
|
|
4627
|
+
baseURL,
|
|
4628
|
+
apiKey,
|
|
4629
|
+
rawEnrichment,
|
|
4630
|
+
rawCompressionCombos,
|
|
4631
|
+
rawConnections,
|
|
4632
|
+
rawAutoCombos
|
|
4633
|
+
);
|
|
4634
|
+
|
|
4635
|
+
// Mutate the input.provider map. The Config type declares
|
|
4636
|
+
// `provider?: {[key: string]: ProviderConfig}` — we initialise the
|
|
4637
|
+
// bag when absent so users who never set `provider` in opencode.json
|
|
4638
|
+
// still get the static block.
|
|
4639
|
+
const inputWithProvider = input as { provider?: Record<string, unknown> };
|
|
4640
|
+
if (!inputWithProvider.provider) {
|
|
4641
|
+
inputWithProvider.provider = {};
|
|
4642
|
+
}
|
|
4643
|
+
inputWithProvider.provider[resolved.providerId] = block;
|
|
4644
|
+
|
|
4645
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
4646
|
+
// MCP auto-emit — opt-in via features.mcpAutoEmit. When enabled, writes
|
|
4647
|
+
// an `input.mcp[<providerId>]` remote entry pointing at
|
|
4648
|
+
// `<baseURL>/api/mcp/stream` with the resolved Bearer token. Token
|
|
4649
|
+
// resolution: features.mcpToken wins if set; otherwise falls back to
|
|
4650
|
+
// the same apiKey used for chat. Operator overrides win (same posture
|
|
4651
|
+
// as provider-block emit): if input.mcp[providerId] is already set,
|
|
4652
|
+
// we leave it alone.
|
|
4653
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
4654
|
+
if (features.mcpAutoEmit === true) {
|
|
4655
|
+
const mcpKey = features.mcpToken ?? apiKey;
|
|
4656
|
+
if (!mcpKey) {
|
|
4657
|
+
logger.warn(
|
|
4658
|
+
`[omniroute-plugin] mcp auto-emit skipped: no Bearer token for providerId=${resolved.providerId}`
|
|
4659
|
+
);
|
|
4660
|
+
} else {
|
|
4661
|
+
const inputWithMcp = input as { mcp?: Record<string, unknown> };
|
|
4662
|
+
if (!inputWithMcp.mcp) {
|
|
4663
|
+
inputWithMcp.mcp = {};
|
|
4664
|
+
}
|
|
4665
|
+
if (inputWithMcp.mcp[resolved.providerId] !== undefined) {
|
|
4666
|
+
logger.warn(
|
|
4667
|
+
`[omniroute-plugin] mcp auto-emit skipped: mcp.${resolved.providerId} already set by user`
|
|
4668
|
+
);
|
|
4669
|
+
} else {
|
|
4670
|
+
// Strip a trailing `/v1` from baseURL when present so we land on
|
|
4671
|
+
// the MCP transport at /api/mcp/stream, not /v1/api/mcp/stream.
|
|
4672
|
+
const mcpRoot = baseURL.replace(/\/v1\/?$/, "").replace(/\/$/, "");
|
|
4673
|
+
inputWithMcp.mcp[resolved.providerId] = {
|
|
4674
|
+
type: "remote",
|
|
4675
|
+
url: `${mcpRoot}/api/mcp/stream`,
|
|
4676
|
+
enabled: true,
|
|
4677
|
+
headers: {
|
|
4678
|
+
Authorization: `Bearer ${mcpKey}`,
|
|
4679
|
+
},
|
|
4680
|
+
};
|
|
4681
|
+
}
|
|
4682
|
+
}
|
|
4683
|
+
}
|
|
4684
|
+
};
|
|
4685
|
+
}
|