@yansigit/opencodex 2.31.0
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/AGENTS_INSTALL.md +109 -0
- package/LICENSE +21 -0
- package/README.md +303 -0
- package/assets/architecture.png +0 -0
- package/assets/banner.png +0 -0
- package/assets/claude-code-models.gif +0 -0
- package/assets/codex-app-picker.png +0 -0
- package/bin/ocx.mjs +587 -0
- package/bin/package-main.mjs +9 -0
- package/gui/dist/assets/index-BNJ7r4Gd.js +102 -0
- package/gui/dist/assets/index-CGoDO3uO.css +1 -0
- package/gui/dist/favicon.png +0 -0
- package/gui/dist/icons.svg +24 -0
- package/gui/dist/index.html +25 -0
- package/gui/dist/logo.png +0 -0
- package/gui/dist/provider-icons/alibaba-color.svg +1 -0
- package/gui/dist/provider-icons/antigravity-color.svg +1 -0
- package/gui/dist/provider-icons/claude-color.svg +1 -0
- package/gui/dist/provider-icons/cline-color.svg +16 -0
- package/gui/dist/provider-icons/cloudflare-ai-gateway-color.svg +1 -0
- package/gui/dist/provider-icons/commandcode-color.svg +1 -0
- package/gui/dist/provider-icons/copilot-color.svg +1 -0
- package/gui/dist/provider-icons/cursor-color.svg +2 -0
- package/gui/dist/provider-icons/deepseek-color.svg +1 -0
- package/gui/dist/provider-icons/discord.svg +1 -0
- package/gui/dist/provider-icons/firepass-color.svg +1 -0
- package/gui/dist/provider-icons/fireworks-color.svg +1 -0
- package/gui/dist/provider-icons/gemini-color.svg +1 -0
- package/gui/dist/provider-icons/github-copilot-color.svg +1 -0
- package/gui/dist/provider-icons/gitlab-duo-color.svg +1 -0
- package/gui/dist/provider-icons/grok.svg +1 -0
- package/gui/dist/provider-icons/groq-color.svg +1 -0
- package/gui/dist/provider-icons/huggingface-color.svg +1 -0
- package/gui/dist/provider-icons/kimi-color.svg +1 -0
- package/gui/dist/provider-icons/kiro-color.svg +15 -0
- package/gui/dist/provider-icons/lm-studio-color.svg +1 -0
- package/gui/dist/provider-icons/mistral-color.svg +1 -0
- package/gui/dist/provider-icons/moonshot-color.svg +1 -0
- package/gui/dist/provider-icons/nvidia-color.svg +1 -0
- package/gui/dist/provider-icons/ollama-color.svg +1 -0
- package/gui/dist/provider-icons/openai.svg +1 -0
- package/gui/dist/provider-icons/opencode.svg +2 -0
- package/gui/dist/provider-icons/openrouter-color.svg +1 -0
- package/gui/dist/provider-icons/pi.svg +21 -0
- package/gui/dist/provider-icons/qianfan-color.svg +1 -0
- package/gui/dist/provider-icons/qwen-portal-color.svg +1 -0
- package/gui/dist/provider-icons/telegram.svg +1 -0
- package/gui/dist/provider-icons/vercel-ai-gateway-color.svg +1 -0
- package/gui/dist/provider-icons/vllm-color.svg +1 -0
- package/gui/dist/provider-icons/xiaomi-color.svg +1 -0
- package/package.json +108 -0
- package/src/AGENTS.md +28 -0
- package/src/adapters/anthropic-image-guard.ts +251 -0
- package/src/adapters/anthropic-image-normalize.ts +518 -0
- package/src/adapters/anthropic-output-schema.ts +137 -0
- package/src/adapters/anthropic.ts +1327 -0
- package/src/adapters/azure.ts +36 -0
- package/src/adapters/base.ts +121 -0
- package/src/adapters/client-fingerprint.ts +65 -0
- package/src/adapters/cline-pass-deepseek-v4-tool-replay.ts +69 -0
- package/src/adapters/command-code.ts +601 -0
- package/src/adapters/cursor/arg-codec.ts +38 -0
- package/src/adapters/cursor/arg-normalize.ts +104 -0
- package/src/adapters/cursor/checkpoint-store.ts +303 -0
- package/src/adapters/cursor/cursor-errors.ts +288 -0
- package/src/adapters/cursor/discovery.ts +333 -0
- package/src/adapters/cursor/effort-map.ts +151 -0
- package/src/adapters/cursor/exec-policy.ts +88 -0
- package/src/adapters/cursor/framing.ts +250 -0
- package/src/adapters/cursor/gen/agent_pb.ts +15274 -0
- package/src/adapters/cursor/h2-pool.ts +123 -0
- package/src/adapters/cursor/http1-bidi.ts +361 -0
- package/src/adapters/cursor/images.ts +704 -0
- package/src/adapters/cursor/kv-store.ts +52 -0
- package/src/adapters/cursor/live-models.ts +269 -0
- package/src/adapters/cursor/live-smoke-gate.ts +41 -0
- package/src/adapters/cursor/live-transport.ts +1653 -0
- package/src/adapters/cursor/mcp-config.ts +42 -0
- package/src/adapters/cursor/mcp-manager.ts +333 -0
- package/src/adapters/cursor/message-mapper.ts +49 -0
- package/src/adapters/cursor/native-exec-common.ts +76 -0
- package/src/adapters/cursor/native-exec-desktop.ts +184 -0
- package/src/adapters/cursor/native-exec-fs.ts +332 -0
- package/src/adapters/cursor/native-exec-mcp.ts +153 -0
- package/src/adapters/cursor/native-exec-network.ts +43 -0
- package/src/adapters/cursor/native-exec-shell.ts +547 -0
- package/src/adapters/cursor/native-exec-tools.ts +118 -0
- package/src/adapters/cursor/native-exec.ts +663 -0
- package/src/adapters/cursor/protobuf-events.ts +1381 -0
- package/src/adapters/cursor/protobuf-request.ts +1032 -0
- package/src/adapters/cursor/request-builder.ts +461 -0
- package/src/adapters/cursor/thread-continuity.ts +67 -0
- package/src/adapters/cursor/tool-definitions.ts +735 -0
- package/src/adapters/cursor/tool-result-normalize.ts +92 -0
- package/src/adapters/cursor/transport-retry.ts +132 -0
- package/src/adapters/cursor/transport.ts +79 -0
- package/src/adapters/cursor/types.ts +79 -0
- package/src/adapters/cursor.ts +322 -0
- package/src/adapters/google-antigravity-hosts.ts +48 -0
- package/src/adapters/google-antigravity-replay.ts +827 -0
- package/src/adapters/google-antigravity-tools.ts +105 -0
- package/src/adapters/google-antigravity-wire.ts +141 -0
- package/src/adapters/google-errors.ts +92 -0
- package/src/adapters/google-http.ts +460 -0
- package/src/adapters/google-tool-schema.ts +238 -0
- package/src/adapters/google-truncation.ts +24 -0
- package/src/adapters/google-wire-compiler.ts +232 -0
- package/src/adapters/google.ts +1377 -0
- package/src/adapters/identity.ts +77 -0
- package/src/adapters/image.ts +23 -0
- package/src/adapters/kiro-constants.ts +16 -0
- package/src/adapters/kiro-errors.ts +208 -0
- package/src/adapters/kiro-events.ts +197 -0
- package/src/adapters/kiro-images.ts +129 -0
- package/src/adapters/kiro-retry.ts +312 -0
- package/src/adapters/kiro-thinking.ts +112 -0
- package/src/adapters/kiro-tool-fallback.ts +36 -0
- package/src/adapters/kiro-tools.ts +224 -0
- package/src/adapters/kiro-truncation.ts +33 -0
- package/src/adapters/kiro-wire.ts +129 -0
- package/src/adapters/kiro.ts +1936 -0
- package/src/adapters/mimo-free.ts +280 -0
- package/src/adapters/openai-chat-url.ts +11 -0
- package/src/adapters/openai-chat.ts +1980 -0
- package/src/adapters/openai-responses-url.ts +16 -0
- package/src/adapters/openai-responses.ts +1911 -0
- package/src/adapters/registry.ts +175 -0
- package/src/adapters/responses-tool-schema.ts +67 -0
- package/src/adapters/run-turn-queue.ts +114 -0
- package/src/adapters/tool-call-id.ts +119 -0
- package/src/adapters/tool-catalog-nudge.ts +154 -0
- package/src/adapters/upstream-http-error.ts +48 -0
- package/src/adapters/xai-web-search.ts +185 -0
- package/src/bridge.ts +1986 -0
- package/src/chat/inbound.ts +319 -0
- package/src/chat/outbound.ts +821 -0
- package/src/claude/agents-inject.ts +266 -0
- package/src/claude/alias.ts +149 -0
- package/src/claude/auth-detect.ts +229 -0
- package/src/claude/auth-mode-migration.ts +32 -0
- package/src/claude/auth-mode.ts +62 -0
- package/src/claude/context-windows.ts +205 -0
- package/src/claude/desktop-3p-guard.ts +35 -0
- package/src/claude/desktop-3p-paths.ts +84 -0
- package/src/claude/desktop-3p.ts +615 -0
- package/src/claude/desktop-health.ts +26 -0
- package/src/claude/desktop-profile.ts +263 -0
- package/src/claude/gateway-cache.ts +107 -0
- package/src/claude/inbound-debug.ts +163 -0
- package/src/claude/inbound.ts +578 -0
- package/src/claude/model-info.ts +174 -0
- package/src/claude/outbound.ts +926 -0
- package/src/cli/access.ts +108 -0
- package/src/cli/account-api.ts +302 -0
- package/src/cli/account-auth.ts +250 -0
- package/src/cli/account-catalog-refresh.ts +14 -0
- package/src/cli/account-extended.ts +737 -0
- package/src/cli/account-main.ts +317 -0
- package/src/cli/account.ts +299 -0
- package/src/cli/agent-driven.ts +70 -0
- package/src/cli/agent.ts +290 -0
- package/src/cli/catalog-prewarm.ts +27 -0
- package/src/cli/claude-agent-startup-sync.ts +73 -0
- package/src/cli/claude-desktop.ts +213 -0
- package/src/cli/claude.ts +355 -0
- package/src/cli/codex-log-guard-doctor.ts +103 -0
- package/src/cli/codex-shim-autorestore.ts +47 -0
- package/src/cli/codex-shim-readiness.ts +76 -0
- package/src/cli/combo.ts +127 -0
- package/src/cli/config-command.ts +209 -0
- package/src/cli/debug.ts +228 -0
- package/src/cli/dispatch.ts +585 -0
- package/src/cli/doctor.ts +1202 -0
- package/src/cli/ensure-desired-integrations.ts +152 -0
- package/src/cli/export-command.ts +213 -0
- package/src/cli/help.ts +101 -0
- package/src/cli/index.ts +973 -0
- package/src/cli/init.ts +211 -0
- package/src/cli/integrations.ts +260 -0
- package/src/cli/interactive-confirm.ts +133 -0
- package/src/cli/lab.ts +607 -0
- package/src/cli/launcher-context.ts +77 -0
- package/src/cli/minimax.ts +497 -0
- package/src/cli/models-runtime.ts +245 -0
- package/src/cli/models.ts +422 -0
- package/src/cli/observe.ts +206 -0
- package/src/cli/opencode.ts +588 -0
- package/src/cli/provider-replit.ts +232 -0
- package/src/cli/provider-runtime.ts +179 -0
- package/src/cli/provider.ts +492 -0
- package/src/cli/ready.ts +301 -0
- package/src/cli/registry.ts +422 -0
- package/src/cli/replit-gateway-key-input.ts +138 -0
- package/src/cli/root.ts +86 -0
- package/src/cli/route-policy.ts +92 -0
- package/src/cli/runtime-api.ts +328 -0
- package/src/cli/star-prompt.ts +211 -0
- package/src/cli/status-oauth.ts +78 -0
- package/src/cli/status.ts +328 -0
- package/src/cli/system-command.ts +112 -0
- package/src/cli/system-restart-client.ts +146 -0
- package/src/cli/tray-proxy.ts +199 -0
- package/src/cli/v2.ts +268 -0
- package/src/cli.ts +10 -0
- package/src/clients/config-export.ts +1704 -0
- package/src/codex/account-id.ts +34 -0
- package/src/codex/account-label.ts +47 -0
- package/src/codex/account-lifecycle.ts +172 -0
- package/src/codex/account-namespace-match.ts +63 -0
- package/src/codex/account-namespaces.ts +195 -0
- package/src/codex/account-pause.ts +20 -0
- package/src/codex/account-priority.ts +83 -0
- package/src/codex/account-runtime-state.ts +31 -0
- package/src/codex/account-store.ts +544 -0
- package/src/codex/account-usability.ts +43 -0
- package/src/codex/admission.ts +256 -0
- package/src/codex/affinity-debug.ts +162 -0
- package/src/codex/agent-roles-sync.ts +225 -0
- package/src/codex/agent-roles.ts +238 -0
- package/src/codex/app-server-processes.ts +1143 -0
- package/src/codex/app-server-restart-service.ts +232 -0
- package/src/codex/auth-api.ts +2147 -0
- package/src/codex/auth-collision.ts +109 -0
- package/src/codex/auth-context.ts +665 -0
- package/src/codex/autostart-health.ts +156 -0
- package/src/codex/catalog/account-models.ts +67 -0
- package/src/codex/catalog/aggregation.ts +436 -0
- package/src/codex/catalog/bundled.ts +549 -0
- package/src/codex/catalog/effort.ts +446 -0
- package/src/codex/catalog/filesystem-evidence.ts +302 -0
- package/src/codex/catalog/kinds.ts +2 -0
- package/src/codex/catalog/metadata.ts +664 -0
- package/src/codex/catalog/native-models.ts +72 -0
- package/src/codex/catalog/parsing.ts +650 -0
- package/src/codex/catalog/provider-fetch.ts +2064 -0
- package/src/codex/catalog/sync.ts +1883 -0
- package/src/codex/catalog-admission.ts +199 -0
- package/src/codex/catalog-refresh-status.ts +105 -0
- package/src/codex/catalog-write-serialization.ts +242 -0
- package/src/codex/catalog.ts +14 -0
- package/src/codex/codex-write-lock.ts +384 -0
- package/src/codex/convergence-types.ts +614 -0
- package/src/codex/convergence.ts +651 -0
- package/src/codex/coordinator-doctor.ts +332 -0
- package/src/codex/custom-model-catalog-migration.ts +176 -0
- package/src/codex/data/upstream-models.json +830 -0
- package/src/codex/desired-state.ts +230 -0
- package/src/codex/exec-invocation.ts +22 -0
- package/src/codex/features.ts +1566 -0
- package/src/codex/generation.ts +202 -0
- package/src/codex/history-job.ts +407 -0
- package/src/codex/history-lock.ts +242 -0
- package/src/codex/history-migration-guardian.ts +108 -0
- package/src/codex/history-provider.ts +979 -0
- package/src/codex/history-transition.ts +105 -0
- package/src/codex/history-worker.ts +220 -0
- package/src/codex/home.ts +206 -0
- package/src/codex/inject-coordination.ts +290 -0
- package/src/codex/inject.ts +1733 -0
- package/src/codex/injected-marker.ts +106 -0
- package/src/codex/integration-record.ts +266 -0
- package/src/codex/internal/catalog-writer.ts +203 -0
- package/src/codex/internal/history-writer.ts +80 -0
- package/src/codex/journal.ts +225 -0
- package/src/codex/log-guard/inspect.ts +506 -0
- package/src/codex/log-guard/lock.ts +150 -0
- package/src/codex/log-guard/maintenance.ts +403 -0
- package/src/codex/log-guard/path-safety.ts +88 -0
- package/src/codex/log-guard/policy.ts +44 -0
- package/src/codex/log-guard/processes.ts +205 -0
- package/src/codex/log-guard/protection.ts +489 -0
- package/src/codex/log-guard/sqlite-errors.ts +9 -0
- package/src/codex/main-account-cache.ts +56 -0
- package/src/codex/main-account.ts +68 -0
- package/src/codex/management-convergence.ts +167 -0
- package/src/codex/model-cache.ts +273 -0
- package/src/codex/model-entitlements.ts +353 -0
- package/src/codex/native-main-admission.ts +47 -0
- package/src/codex/native-main-auth-temp.ts +187 -0
- package/src/codex/native-main-claim.ts +178 -0
- package/src/codex/native-main-lock-file.ts +162 -0
- package/src/codex/native-main-owner.ts +329 -0
- package/src/codex/native-profile-api.ts +247 -0
- package/src/codex/native-profile-manager.ts +1531 -0
- package/src/codex/native-profile-processes.ts +121 -0
- package/src/codex/native-profile-recovery.ts +99 -0
- package/src/codex/native-profile-stage-store.ts +387 -0
- package/src/codex/native-profile-startup.ts +492 -0
- package/src/codex/native-profile-store.ts +855 -0
- package/src/codex/native-profile-types.ts +120 -0
- package/src/codex/native-residue.ts +682 -0
- package/src/codex/paths.ts +144 -0
- package/src/codex/plan-from-token.ts +140 -0
- package/src/codex/plan.ts +40 -0
- package/src/codex/plugins-doctor.ts +242 -0
- package/src/codex/pool-rotation.ts +295 -0
- package/src/codex/project-config-warnings.ts +425 -0
- package/src/codex/prompt-journal.ts +352 -0
- package/src/codex/prompt-layers.ts +967 -0
- package/src/codex/prompt-lock.ts +143 -0
- package/src/codex/quota-rejection.ts +298 -0
- package/src/codex/quota.ts +573 -0
- package/src/codex/refresh.ts +62 -0
- package/src/codex/reset-credit-recovery.ts +1044 -0
- package/src/codex/routing.ts +1888 -0
- package/src/codex/runtime.ts +659 -0
- package/src/codex/shim.ts +2170 -0
- package/src/codex/subagent-defaults.ts +550 -0
- package/src/codex/subagent-model-fallback.ts +784 -0
- package/src/codex/sync.ts +319 -0
- package/src/codex/transition-state.ts +612 -0
- package/src/codex/upstream-host-health.ts +368 -0
- package/src/codex/user-identity.ts +557 -0
- package/src/codex/warmup.ts +298 -0
- package/src/codex/websocket-registry.ts +100 -0
- package/src/codex/write-coordination.ts +114 -0
- package/src/combos/failover.ts +160 -0
- package/src/combos/index.ts +45 -0
- package/src/combos/request.ts +94 -0
- package/src/combos/resolve.ts +232 -0
- package/src/combos/types.ts +398 -0
- package/src/config/provider-name.ts +24 -0
- package/src/config.ts +4041 -0
- package/src/fork/register.ts +3 -0
- package/src/generated/compatibility-version.json +3116 -0
- package/src/generated/model-metadata.ts +106 -0
- package/src/github/star-state.ts +203 -0
- package/src/grok/inject.ts +530 -0
- package/src/grok/inspect.ts +45 -0
- package/src/grok/status.ts +121 -0
- package/src/grok/sync.ts +66 -0
- package/src/images/artifacts.ts +516 -0
- package/src/images/fulfill-video.ts +163 -0
- package/src/images/fulfill.ts +149 -0
- package/src/images/index.ts +4 -0
- package/src/images/loop.ts +955 -0
- package/src/images/plan.ts +143 -0
- package/src/images/synthetic-tool.ts +133 -0
- package/src/images/types.ts +41 -0
- package/src/images/xai-client.ts +141 -0
- package/src/images/xai-video-client.ts +163 -0
- package/src/index.ts +22 -0
- package/src/integrations/config-io.ts +269 -0
- package/src/integrations/journal.ts +315 -0
- package/src/integrations/merge.ts +135 -0
- package/src/integrations/mutation-flight.ts +71 -0
- package/src/integrations/native/ownership-preflight.ts +202 -0
- package/src/integrations/omp-yaml-source.ts +358 -0
- package/src/integrations/owned-refresh.ts +74 -0
- package/src/integrations/ownership.ts +111 -0
- package/src/integrations/registry.ts +159 -0
- package/src/integrations/serialize.ts +314 -0
- package/src/integrations/state.ts +361 -0
- package/src/integrations/store.ts +103 -0
- package/src/integrations/writer-lock.ts +98 -0
- package/src/integrations/writer.ts +691 -0
- package/src/lab/artifacts/sanitize.ts +586 -0
- package/src/lab/artifacts/secure-fs.ts +475 -0
- package/src/lab/artifacts/store.ts +310 -0
- package/src/lab/automation/budgets.ts +78 -0
- package/src/lab/automation/config-persistence.ts +256 -0
- package/src/lab/automation/constants.ts +39 -0
- package/src/lab/automation/cooldown.ts +103 -0
- package/src/lab/automation/dispatch.ts +211 -0
- package/src/lab/automation/index.ts +13 -0
- package/src/lab/automation/orchestrator.ts +499 -0
- package/src/lab/automation/persistence.ts +512 -0
- package/src/lab/automation/planner.ts +371 -0
- package/src/lab/automation/policy.ts +136 -0
- package/src/lab/automation/queue.ts +191 -0
- package/src/lab/automation/recovery.ts +24 -0
- package/src/lab/automation/route-context.ts +21 -0
- package/src/lab/automation/run-key.ts +44 -0
- package/src/lab/automation/runs-query.ts +34 -0
- package/src/lab/automation/types.ts +160 -0
- package/src/lab/conformance/assertion.ts +325 -0
- package/src/lab/conformance/digest.ts +22 -0
- package/src/lab/conformance/executor.ts +741 -0
- package/src/lab/conformance/fixture-provider.ts +27 -0
- package/src/lab/conformance/fixtures/live-v1-cases.json +175 -0
- package/src/lab/conformance/fixtures/protocol-v1-cases.json +461 -0
- package/src/lab/conformance/harness-budget.ts +47 -0
- package/src/lab/conformance/index.ts +5 -0
- package/src/lab/conformance/jcs.ts +64 -0
- package/src/lab/conformance/json-pointer.ts +39 -0
- package/src/lab/conformance/manifest.ts +180 -0
- package/src/lab/conformance/mcp-stub.ts +179 -0
- package/src/lab/conformance/negative-controls.ts +164 -0
- package/src/lab/conformance/observation.ts +355 -0
- package/src/lab/conformance/runner.ts +68 -0
- package/src/lab/conformance/sse-normalize.ts +59 -0
- package/src/lab/conformance/suite-manifest.ts +78 -0
- package/src/lab/conformance/types.ts +214 -0
- package/src/lab/constants.ts +126 -0
- package/src/lab/digest.ts +64 -0
- package/src/lab/events/errors.ts +9 -0
- package/src/lab/events/limits.ts +117 -0
- package/src/lab/events/types.ts +229 -0
- package/src/lab/events/validate.ts +781 -0
- package/src/lab/fabric/constants.ts +40 -0
- package/src/lab/fabric/executor.ts +492 -0
- package/src/lab/fabric/index.ts +80 -0
- package/src/lab/fabric/manifest.ts +222 -0
- package/src/lab/fabric/observe.ts +489 -0
- package/src/lab/fabric/patch.ts +79 -0
- package/src/lab/fabric/producer-child.ts +139 -0
- package/src/lab/fabric/producer-isolate.ts +276 -0
- package/src/lab/fabric/producer-protocol.ts +61 -0
- package/src/lab/fabric/scratch.ts +439 -0
- package/src/lab/fabric/subject.ts +106 -0
- package/src/lab/fabric/types.ts +134 -0
- package/src/lab/fabric/verifier.ts +98 -0
- package/src/lab/index.ts +54 -0
- package/src/lab/ledger/artifact-refs.ts +127 -0
- package/src/lab/ledger/invalidation.ts +136 -0
- package/src/lab/ledger/purge.ts +310 -0
- package/src/lab/ledger/store.ts +532 -0
- package/src/lab/live/credential-lease.ts +53 -0
- package/src/lab/live/destination.ts +155 -0
- package/src/lab/live/executor.ts +336 -0
- package/src/lab/live/inert-tools.ts +56 -0
- package/src/lab/live/manifest.ts +85 -0
- package/src/lab/live/mcp-loopback.ts +57 -0
- package/src/lab/live/runner.ts +19 -0
- package/src/lab/live/sandbox.ts +61 -0
- package/src/lab/live/suite-manifest.ts +41 -0
- package/src/lab/live/transport.ts +118 -0
- package/src/lab/live/types.ts +197 -0
- package/src/lab/observe/from-conformance.ts +301 -0
- package/src/lab/observe/from-live.ts +117 -0
- package/src/lab/paths.ts +153 -0
- package/src/lab/projection/rebuild.ts +495 -0
- package/src/lab/projection/schema.ts +135 -0
- package/src/lab/projection/verdicts.ts +474 -0
- package/src/lab/projection/verification.ts +412 -0
- package/src/lab/public/bundle.ts +217 -0
- package/src/lab/public/community-authority.ts +175 -0
- package/src/lab/public/community-files.ts +29 -0
- package/src/lab/public/community.ts +479 -0
- package/src/lab/public/file-safety.ts +155 -0
- package/src/lab/public/ids.ts +26 -0
- package/src/lab/public/index.ts +16 -0
- package/src/lab/public/mutation-lock.ts +424 -0
- package/src/lab/public/operator.ts +353 -0
- package/src/lab/public/origin-purge.ts +79 -0
- package/src/lab/public/origin.ts +203 -0
- package/src/lab/public/privacy.ts +143 -0
- package/src/lab/public/private-file.ts +261 -0
- package/src/lab/public/project.ts +124 -0
- package/src/lab/public/purge-test-fault.ts +21 -0
- package/src/lab/public/purge.ts +223 -0
- package/src/lab/public/registry.ts +44 -0
- package/src/lab/public/revocation.ts +252 -0
- package/src/lab/public/signature.ts +243 -0
- package/src/lab/public/storage.ts +105 -0
- package/src/lab/public/strict-json.ts +206 -0
- package/src/lab/public/time.ts +26 -0
- package/src/lab/public/types.ts +172 -0
- package/src/lab/public/validate.ts +391 -0
- package/src/lab/query/catalog.ts +101 -0
- package/src/lab/query/connection.ts +107 -0
- package/src/lab/query/constants.ts +4 -0
- package/src/lab/query/cursor.ts +132 -0
- package/src/lab/query/dto-map.ts +277 -0
- package/src/lab/query/errors.ts +22 -0
- package/src/lab/query/freshness.ts +53 -0
- package/src/lab/query/index.ts +45 -0
- package/src/lab/query/latest-observation.ts +59 -0
- package/src/lab/query/passive-production.ts +159 -0
- package/src/lab/query/queries.ts +444 -0
- package/src/lab/query/types.ts +266 -0
- package/src/lab/subject/behavior-fingerprint.ts +77 -0
- package/src/lab/subject/installation-salt.ts +112 -0
- package/src/lab/subject/protocol-subject.ts +80 -0
- package/src/lab/subject/route-subject.ts +74 -0
- package/src/lib/abort.ts +146 -0
- package/src/lib/admin-secrets.ts +25 -0
- package/src/lib/admission.ts +83 -0
- package/src/lib/app-owned-memory-stores.ts +195 -0
- package/src/lib/app-owned-memory.ts +265 -0
- package/src/lib/bounded-body.ts +346 -0
- package/src/lib/bun-binary-validator.d.mts +3 -0
- package/src/lib/bun-binary-validator.mjs +18 -0
- package/src/lib/bun-runtime.ts +184 -0
- package/src/lib/bun-stream-caps.ts +130 -0
- package/src/lib/codex-restart-contract.ts +120 -0
- package/src/lib/config-ownership.ts +364 -0
- package/src/lib/crash-guard.ts +344 -0
- package/src/lib/debug-log-buffer.ts +83 -0
- package/src/lib/debug-settings.ts +108 -0
- package/src/lib/debug.ts +31 -0
- package/src/lib/destination-policy.ts +380 -0
- package/src/lib/errors.ts +406 -0
- package/src/lib/eventstream-decoder.ts +253 -0
- package/src/lib/fabric-task-execution-authority.ts +7 -0
- package/src/lib/fabric-task-host.ts +29 -0
- package/src/lib/gcp-adc.ts +341 -0
- package/src/lib/injection-debug-log.ts +58 -0
- package/src/lib/lab-activation.ts +223 -0
- package/src/lib/lab-live-execution-authority.ts +13 -0
- package/src/lib/lab-live-host.ts +30 -0
- package/src/lib/lab-live-pinned-sender.ts +56 -0
- package/src/lib/lab-live-route-production.ts +130 -0
- package/src/lib/lab-passive-linker-registration.ts +26 -0
- package/src/lib/local-management-attestation.ts +51 -0
- package/src/lib/local-management-capability.ts +100 -0
- package/src/lib/local-provider-reload-contract.ts +100 -0
- package/src/lib/open-url.ts +25 -0
- package/src/lib/optional-shutdown-hooks.ts +57 -0
- package/src/lib/pinned-http.ts +270 -0
- package/src/lib/privacy.ts +20 -0
- package/src/lib/process-control.ts +168 -0
- package/src/lib/provider-outbound.ts +210 -0
- package/src/lib/provider-url.ts +14 -0
- package/src/lib/proxy-env.ts +18 -0
- package/src/lib/redact.ts +521 -0
- package/src/lib/retry-after.ts +55 -0
- package/src/lib/self-launch-argv.ts +15 -0
- package/src/lib/server-resource-ownership.ts +71 -0
- package/src/lib/service-secrets.ts +25 -0
- package/src/lib/shadow-call.ts +61 -0
- package/src/lib/sidecar-tracker.ts +52 -0
- package/src/lib/sse-decoder.ts +364 -0
- package/src/lib/state-store-registrations.ts +119 -0
- package/src/lib/state-store-sweeper.ts +184 -0
- package/src/lib/system-restart-contract.ts +73 -0
- package/src/lib/test-home-guard.ts +90 -0
- package/src/lib/token-estimate.ts +86 -0
- package/src/lib/tool-argument-integers.ts +202 -0
- package/src/lib/translator-budget.ts +400 -0
- package/src/lib/upstream-http-version.ts +57 -0
- package/src/lib/upstream-reachability.ts +95 -0
- package/src/lib/upstream-retry.ts +392 -0
- package/src/lib/win-exec.ts +115 -0
- package/src/lib/win-paths.ts +68 -0
- package/src/lib/windows-atomic-replace.ts +156 -0
- package/src/lib/windows-elevation.ts +773 -0
- package/src/lib/windows-secret-acl.ts +854 -0
- package/src/lib/windows-service-wrappers.ts +72 -0
- package/src/lib/windows-text.ts +106 -0
- package/src/lib/windows-user-principal.ts +341 -0
- package/src/lib/winsw.ts +403 -0
- package/src/oauth/account-import/google-antigravity-adapter.ts +74 -0
- package/src/oauth/account-import/index.ts +15 -0
- package/src/oauth/account-import/parser.ts +83 -0
- package/src/oauth/account-import/registry.ts +18 -0
- package/src/oauth/account-import/service.ts +75 -0
- package/src/oauth/account-import/types.ts +91 -0
- package/src/oauth/anthropic-routing.ts +594 -0
- package/src/oauth/anthropic.ts +188 -0
- package/src/oauth/antigravity-routing.ts +151 -0
- package/src/oauth/callback-server.ts +300 -0
- package/src/oauth/chatgpt.ts +161 -0
- package/src/oauth/command-code.ts +239 -0
- package/src/oauth/cursor.ts +252 -0
- package/src/oauth/github-copilot.ts +428 -0
- package/src/oauth/google-antigravity.ts +262 -0
- package/src/oauth/health.ts +407 -0
- package/src/oauth/index.ts +1504 -0
- package/src/oauth/key-providers.ts +124 -0
- package/src/oauth/kimi.ts +227 -0
- package/src/oauth/kiro-credentials.ts +726 -0
- package/src/oauth/kiro.ts +621 -0
- package/src/oauth/local-token-detect.ts +130 -0
- package/src/oauth/log.ts +50 -0
- package/src/oauth/login-cli.ts +223 -0
- package/src/oauth/nous.ts +798 -0
- package/src/oauth/pkce.ts +15 -0
- package/src/oauth/store.ts +728 -0
- package/src/oauth/token-guardian.ts +309 -0
- package/src/oauth/types.ts +62 -0
- package/src/oauth/xai.ts +241 -0
- package/src/providers/alibaba-region-backup.ts +75 -0
- package/src/providers/alibaba-region-migration.ts +156 -0
- package/src/providers/alibaba-region-startup.ts +36 -0
- package/src/providers/antigravity-models.ts +695 -0
- package/src/providers/antigravity-quota.ts +216 -0
- package/src/providers/api-keys.ts +140 -0
- package/src/providers/base-url-choices.ts +74 -0
- package/src/providers/codex-capacity.ts +292 -0
- package/src/providers/command-code-efforts.ts +144 -0
- package/src/providers/context-cap.ts +82 -0
- package/src/providers/cursor-pool.ts +72 -0
- package/src/providers/derive.ts +586 -0
- package/src/providers/fastwire.ts +501 -0
- package/src/providers/free-directory.ts +187 -0
- package/src/providers/github-copilot-transport.ts +56 -0
- package/src/providers/google-vertex-location.ts +14 -0
- package/src/providers/key-failover.ts +271 -0
- package/src/providers/kiro-models.ts +67 -0
- package/src/providers/label.ts +19 -0
- package/src/providers/model-discovery-limits.ts +16 -0
- package/src/providers/model-discovery.ts +449 -0
- package/src/providers/model-rename-migration.ts +255 -0
- package/src/providers/model-rename-startup.ts +28 -0
- package/src/providers/openai-sidecar.ts +243 -0
- package/src/providers/openai-tier-startup.ts +56 -0
- package/src/providers/openai-tiers.ts +423 -0
- package/src/providers/openai-virtual-models.ts +83 -0
- package/src/providers/opencode-zen-rate-limit.ts +102 -0
- package/src/providers/openrouter-routing.ts +102 -0
- package/src/providers/provider-id-rewrite.ts +185 -0
- package/src/providers/quota.ts +2345 -0
- package/src/providers/registry.ts +2918 -0
- package/src/providers/replit/constants.ts +27 -0
- package/src/providers/replit/derive.ts +85 -0
- package/src/providers/replit/headers.ts +28 -0
- package/src/providers/replit/origin.ts +55 -0
- package/src/providers/replit/pair-install-response.ts +72 -0
- package/src/providers/replit/probe.ts +199 -0
- package/src/providers/replit/setup.ts +350 -0
- package/src/providers/request-pacing.ts +310 -0
- package/src/providers/service-tier.ts +277 -0
- package/src/providers/slug-codec.ts +103 -0
- package/src/providers/static-model-discovery.ts +86 -0
- package/src/providers/xai-responses-opt-in.ts +15 -0
- package/src/providers/xai-transport.ts +148 -0
- package/src/reasoning-effort.ts +183 -0
- package/src/responses/compaction.ts +142 -0
- package/src/responses/custom-tool-compat.ts +266 -0
- package/src/responses/hosted-tool-policy.ts +9 -0
- package/src/responses/namespace-tool-compat.ts +355 -0
- package/src/responses/parser.ts +838 -0
- package/src/responses/provider-continuation.ts +98 -0
- package/src/responses/provider-opaque-metadata.ts +73 -0
- package/src/responses/reasoning-envelope.ts +60 -0
- package/src/responses/reasoning-replay-cache.ts +426 -0
- package/src/responses/schema.ts +165 -0
- package/src/responses/spill-store.ts +459 -0
- package/src/responses/state.ts +1433 -0
- package/src/responses/thought-signature-replay.ts +347 -0
- package/src/responses/tool-groups.ts +19 -0
- package/src/responses/tool-search-compat.ts +301 -0
- package/src/responses/truncated-stop-reason.ts +60 -0
- package/src/router.ts +761 -0
- package/src/routing/analytics.ts +378 -0
- package/src/routing/capability.ts +244 -0
- package/src/routing/compatibility/assemble.ts +73 -0
- package/src/routing/compatibility/behavior.ts +278 -0
- package/src/routing/compatibility/catalog.ts +99 -0
- package/src/routing/compatibility/endpoint.ts +52 -0
- package/src/routing/compatibility/lab-evidence-provider.ts +130 -0
- package/src/routing/compatibility/policy.ts +181 -0
- package/src/routing/compatibility/provider-slot.ts +56 -0
- package/src/routing/compatibility/reader.ts +110 -0
- package/src/routing/compatibility/subject.ts +191 -0
- package/src/routing/compatibility/types.ts +64 -0
- package/src/routing/compatibility/version.ts +104 -0
- package/src/routing/cost.ts +77 -0
- package/src/routing/evaluator.ts +495 -0
- package/src/routing/health.ts +412 -0
- package/src/routing/history/cursor.ts +43 -0
- package/src/routing/history/indexer.ts +605 -0
- package/src/routing/history/schema.ts +72 -0
- package/src/routing/profile-namespace.ts +15 -0
- package/src/routing/profile.ts +547 -0
- package/src/routing/quota.ts +145 -0
- package/src/routing/request-evidence.ts +45 -0
- package/src/routing/trace.ts +776 -0
- package/src/server/adapter-resolve.ts +53 -0
- package/src/server/auth-cors.ts +751 -0
- package/src/server/background-lifecycle.ts +182 -0
- package/src/server/chat-completions.ts +442 -0
- package/src/server/chat-native-sse.ts +331 -0
- package/src/server/chat-native.ts +426 -0
- package/src/server/claude-messages.ts +1030 -0
- package/src/server/direct-local-http.ts +347 -0
- package/src/server/effort-policy.ts +190 -0
- package/src/server/github-copilot-responses-repair.ts +338 -0
- package/src/server/gui-static.ts +152 -0
- package/src/server/image-retry.ts +42 -0
- package/src/server/images.ts +568 -0
- package/src/server/index.ts +1813 -0
- package/src/server/lifecycle.ts +498 -0
- package/src/server/live.ts +717 -0
- package/src/server/local-management-read-client.ts +90 -0
- package/src/server/local-provider-reload-client.ts +137 -0
- package/src/server/management/agent-settings-routes.ts +1433 -0
- package/src/server/management/api-access.ts +141 -0
- package/src/server/management/api-key-usage.ts +193 -0
- package/src/server/management/body.ts +41 -0
- package/src/server/management/combo-routes.ts +263 -0
- package/src/server/management/config-routes.ts +835 -0
- package/src/server/management/context.ts +113 -0
- package/src/server/management/integration-routes.ts +498 -0
- package/src/server/management/lab-automation-routes.ts +206 -0
- package/src/server/management/lab-routes.ts +563 -0
- package/src/server/management/logs-usage-routes.ts +586 -0
- package/src/server/management/model-routes.ts +560 -0
- package/src/server/management/model-rows.ts +163 -0
- package/src/server/management/native-integration-routes.ts +769 -0
- package/src/server/management/oauth-account-routes.ts +637 -0
- package/src/server/management/provider-capability-config.ts +48 -0
- package/src/server/management/provider-routes.ts +1033 -0
- package/src/server/management/replit-provider-routes.ts +86 -0
- package/src/server/management/request-history-routes.ts +191 -0
- package/src/server/management/routing-analytics-routes.ts +74 -0
- package/src/server/management/routing-profile-routes.ts +385 -0
- package/src/server/management/shared.ts +286 -0
- package/src/server/management/sidebar-routes.ts +106 -0
- package/src/server/management/storage-log-guard-routes.ts +186 -0
- package/src/server/management/sync-response.ts +69 -0
- package/src/server/management/system-restart.ts +435 -0
- package/src/server/management/system-routes.ts +194 -0
- package/src/server/management/usage-summary-cache.ts +94 -0
- package/src/server/management/vision-sidecar-options.ts +167 -0
- package/src/server/management/web-search-sidecar-options.ts +120 -0
- package/src/server/management-api.ts +314 -0
- package/src/server/management-auth.ts +482 -0
- package/src/server/memory-watchdog.ts +156 -0
- package/src/server/passive-route-linker.ts +66 -0
- package/src/server/port-reclaim.ts +307 -0
- package/src/server/ports.ts +156 -0
- package/src/server/proxy-liveness.ts +328 -0
- package/src/server/readiness.ts +99 -0
- package/src/server/relay-eager.ts +353 -0
- package/src/server/relay.ts +1209 -0
- package/src/server/request-decompress.ts +239 -0
- package/src/server/request-log-conversation.ts +168 -0
- package/src/server/request-log.ts +1259 -0
- package/src/server/responses/agent-task-recovery-cache.ts +143 -0
- package/src/server/responses/agent-task-recovery.ts +465 -0
- package/src/server/responses/collaboration.ts +551 -0
- package/src/server/responses/compact.ts +771 -0
- package/src/server/responses/core.ts +5389 -0
- package/src/server/responses/empty-completion-guard.ts +276 -0
- package/src/server/responses/encrypted-payload.ts +331 -0
- package/src/server/responses/fetch-helpers.ts +232 -0
- package/src/server/responses/input-admission.ts +185 -0
- package/src/server/responses/pacing-overload.ts +13 -0
- package/src/server/responses/passthrough-error.ts +78 -0
- package/src/server/responses/policy-fallback.ts +178 -0
- package/src/server/responses/responses-field-backfill.ts +251 -0
- package/src/server/responses/terminal-guard.ts +251 -0
- package/src/server/responses/upstream-error.ts +53 -0
- package/src/server/responses/ws-upstream.ts +308 -0
- package/src/server/responses-custom-tool-repair.ts +282 -0
- package/src/server/responses-image-gen-repair.ts +132 -0
- package/src/server/responses-item-id-repair.ts +272 -0
- package/src/server/responses-json-events.ts +90 -0
- package/src/server/responses-model-rewrite.ts +29 -0
- package/src/server/responses-reasoning-summary-rewrite.ts +178 -0
- package/src/server/responses-snapshot-repair.ts +621 -0
- package/src/server/responses-terminal-repair.ts +342 -0
- package/src/server/responses-tool-search-repair.ts +267 -0
- package/src/server/responses-undeclared-tool-guard.ts +153 -0
- package/src/server/responses.ts +25 -0
- package/src/server/search.ts +201 -0
- package/src/server/sse-frame-buffer.ts +292 -0
- package/src/server/sse-payload-rewrite.ts +263 -0
- package/src/server/startup-action-control.ts +315 -0
- package/src/server/startup-health-cache.ts +131 -0
- package/src/server/system-env.ts +484 -0
- package/src/server/windows-tcp-drop.ts +184 -0
- package/src/server/windows-tray-control.ts +41 -0
- package/src/server/ws-bridge.ts +472 -0
- package/src/service-manager-probe.ts +892 -0
- package/src/service.ts +3575 -0
- package/src/sidecar/auth.ts +92 -0
- package/src/sidecar/candidates.ts +83 -0
- package/src/stall-timeout.ts +20 -0
- package/src/storage/cleanup-job.ts +57 -0
- package/src/storage/cleanup.ts +3085 -0
- package/src/storage/policy-job.ts +457 -0
- package/src/storage/policy-scheduler.ts +40 -0
- package/src/storage/policy-worker.ts +59 -0
- package/src/storage/policy.ts +527 -0
- package/src/storage/restore-job.ts +299 -0
- package/src/storage/restore-worker.ts +58 -0
- package/src/storage/scanner.ts +238 -0
- package/src/storage/storage-mutation-coordinator.ts +139 -0
- package/src/storage/worker-lifecycle.ts +215 -0
- package/src/tray/assets/opencodex-tray-offline.ico +0 -0
- package/src/tray/assets/opencodex-tray-online.ico +0 -0
- package/src/tray/assets/opencodex-tray-warning.ico +0 -0
- package/src/tray/assets/opencodex-tray.png +0 -0
- package/src/tray/windows-tray.ps1 +364 -0
- package/src/tray/windows.ts +757 -0
- package/src/types/accounts.ts +37 -0
- package/src/types/config.ts +876 -0
- package/src/types/provider.ts +545 -0
- package/src/types/request.ts +384 -0
- package/src/types/tools.ts +131 -0
- package/src/types/wire.ts +80 -0
- package/src/types.ts +106 -0
- package/src/update/badge.ts +72 -0
- package/src/update/index.ts +415 -0
- package/src/update/job.ts +1887 -0
- package/src/update/notify.ts +263 -0
- package/src/update/npm-cache-preflight.d.mts +47 -0
- package/src/update/npm-cache-preflight.mjs +201 -0
- package/src/update/npm-invocation.d.mts +23 -0
- package/src/update/npm-invocation.mjs +94 -0
- package/src/update/transactional-install.d.mts +22 -0
- package/src/update/transactional-install.mjs +259 -0
- package/src/update/tray-update-plan.d.mts +18 -0
- package/src/update/tray-update-plan.mjs +38 -0
- package/src/usage/cost.ts +625 -0
- package/src/usage/debug.ts +97 -0
- package/src/usage/expected-prices.ts +416 -0
- package/src/usage/log.ts +1223 -0
- package/src/usage/summary.ts +753 -0
- package/src/usage/totals.ts +14 -0
- package/src/usage/user-cost-overlay-reconciler.ts +313 -0
- package/src/usage/user-cost-overlays.ts +314 -0
- package/src/vision/anthropic-describe.ts +189 -0
- package/src/vision/backends.ts +97 -0
- package/src/vision/describe.ts +131 -0
- package/src/vision/eligibility.ts +250 -0
- package/src/vision/index.ts +681 -0
- package/src/vision/reasoning.ts +55 -0
- package/src/vision/routed-describe.ts +175 -0
- package/src/vision/timeout-bounds.ts +9 -0
- package/src/web-search/anthropic-executor.ts +195 -0
- package/src/web-search/backends.ts +108 -0
- package/src/web-search/exa-executor.ts +88 -0
- package/src/web-search/executor.ts +113 -0
- package/src/web-search/format-result.ts +89 -0
- package/src/web-search/gemini-executor.ts +141 -0
- package/src/web-search/index.ts +331 -0
- package/src/web-search/loop.ts +896 -0
- package/src/web-search/parse.ts +315 -0
- package/src/web-search/progress-stream.ts +342 -0
- package/src/web-search/sources.ts +60 -0
- package/src/web-search/synthetic-tool.ts +47 -0
- package/src/web-search/xai-executor.ts +219 -0
|
@@ -0,0 +1,2064 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { createHash, createHmac, randomBytes } from "node:crypto";
|
|
3
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync } from "node:fs";
|
|
4
|
+
import { delimiter, dirname, join, resolve } from "node:path";
|
|
5
|
+
import { atomicWriteFile, expandUserPath, getConfigDir, resolveEnvValue, websocketsEnabled } from "../../config";
|
|
6
|
+
import { CODEX_CONFIG_PATH, CODEX_MODELS_CACHE_PATH, DEFAULT_CATALOG_PATH, readRootTomlString, resolveCodexConfigPath } from "../paths";
|
|
7
|
+
import {
|
|
8
|
+
clearModelCache,
|
|
9
|
+
clearProviderDiscoveryStatus,
|
|
10
|
+
captureModelCacheGeneration,
|
|
11
|
+
DEFAULT_MODEL_CACHE_TTL_MS,
|
|
12
|
+
getFreshCached,
|
|
13
|
+
getStaleCached,
|
|
14
|
+
isModelsFetchCoolingDown,
|
|
15
|
+
isModelCacheGenerationCurrent,
|
|
16
|
+
markModelsFetchFailure,
|
|
17
|
+
markProviderDiscoveryFailed,
|
|
18
|
+
markProviderDiscoveryOk,
|
|
19
|
+
shouldLogDiscoveryFailure,
|
|
20
|
+
setCached,
|
|
21
|
+
type ProviderModelDiscoveryFailure,
|
|
22
|
+
} from "../model-cache";
|
|
23
|
+
import {
|
|
24
|
+
buildModelsRequest,
|
|
25
|
+
getValidAccessTokenSnapshot,
|
|
26
|
+
observeActiveOAuthAccessToken,
|
|
27
|
+
resolveModelsAuthToken,
|
|
28
|
+
type OAuthActiveTokenObservation,
|
|
29
|
+
} from "../../oauth";
|
|
30
|
+
import type { OcxConfig, OcxProviderConfig } from "../../types";
|
|
31
|
+
import { modelInList } from "../../types";
|
|
32
|
+
import { CODEX_REASONING_LEVELS, codexEffortRank, configuredReasoningEfforts, modelRecordValue, sanitizeCodexReasoningEfforts } from "../../reasoning-effort";
|
|
33
|
+
import { getModelMetadata, getModelMetadataCaseInsensitive, listModelMetadata, resolveMetadataProvider } from "../../generated/model-metadata";
|
|
34
|
+
import { enrichProviderFromRegistry, shouldCaseFoldMetadataModelId } from "../../providers/derive";
|
|
35
|
+
import {
|
|
36
|
+
captureFastPolicyAuthority,
|
|
37
|
+
fastPolicyForModel,
|
|
38
|
+
serviceTierSupportFromPolicy,
|
|
39
|
+
} from "../../providers/service-tier";
|
|
40
|
+
import type { FastPolicyAuthority } from "../../providers/fastwire";
|
|
41
|
+
import { effectiveGoogleMode, getProviderRegistryEntry, providerMatchesRegistryTransport } from "../../providers/registry";
|
|
42
|
+
import { parseAntigravityAvailableModels, registerAntigravityDiscoveredWireModels } from "../../providers/antigravity-models";
|
|
43
|
+
import { applyProviderContextCap, providerContextCap, resolveUnknownRoutedContextWindow } from "../../providers/context-cap";
|
|
44
|
+
import { routedSlug, slugEquals, slugsEquivalent } from "../../providers/slug-codec";
|
|
45
|
+
import { CODEX_GPT5_IDENTITY_LINE } from "../../adapters/identity";
|
|
46
|
+
import { filterCursorConfiguredModelsByLiveDiscovery } from "../../adapters/cursor/discovery";
|
|
47
|
+
import { fetchCursorUsableModels } from "../../adapters/cursor/live-models";
|
|
48
|
+
import { isCanonicalOpenAiForwardProvider, OPENAI_API_PROVIDER_ID, OPENAI_CODEX_PROVIDER_ID } from "../../providers/openai-tiers";
|
|
49
|
+
import {
|
|
50
|
+
COMBO_NAMESPACE,
|
|
51
|
+
comboModelId,
|
|
52
|
+
getCombo,
|
|
53
|
+
listComboIds,
|
|
54
|
+
targetKey,
|
|
55
|
+
} from "../../combos";
|
|
56
|
+
import type { NormalizedComboConfig } from "../../combos/types";
|
|
57
|
+
import {
|
|
58
|
+
ProviderOutboundPolicyError,
|
|
59
|
+
providerOutboundGet,
|
|
60
|
+
providerOutboundPost,
|
|
61
|
+
providerRedirectError,
|
|
62
|
+
} from "../../lib/provider-outbound";
|
|
63
|
+
import { redactSecretString } from "../../lib/redact";
|
|
64
|
+
import {
|
|
65
|
+
extractProviderModelItems,
|
|
66
|
+
readBoundedDiscoveryJson,
|
|
67
|
+
resolveProviderModelDiscovery,
|
|
68
|
+
type ModelDiscoveryResponseFailure,
|
|
69
|
+
type ProviderModelsApiItem,
|
|
70
|
+
type ResolvedProviderModelDiscovery,
|
|
71
|
+
} from "../../providers/model-discovery";
|
|
72
|
+
import upstreamModelsSnapshot from "../data/upstream-models.json";
|
|
73
|
+
import { createAdmissionGate, ResourceAdmissionError, type AdmissionMetrics } from "../../lib/admission";
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
import { CODEX_CUSTOM_MODEL_CATALOG_KIND, JAWCODE_CATALOG_AUGMENT_PROVIDERS, catalogModelSlug, shouldExposeRoutedModel } from "./parsing";
|
|
77
|
+
import type { CatalogModel } from "./parsing";
|
|
78
|
+
import { disabledNativeSlugs, hasComboTargets, isNativeOpenAiCapabilityAliasModel, NATIVE_GPT56_MAX_INPUT_TOKENS, nativeContextLimits, nativeDefaultReasoningEffort, nativeInputModalities, nativeOpenAiContextWindow, nativeOpenAiMaxInputTokens, nativeOpenAiSlugs, nativeParallelToolCalls, nativeReasoningEfforts } from "./metadata";
|
|
79
|
+
import { deriveComboCatalogModel, normalizedOpenAiApiSignature, openAiApiCollisionWarnings, replaceLastComboCatalogOmissions, warnUncataloguedComboOnce } from "./aggregation";
|
|
80
|
+
import type { ComboCatalogOmission } from "./aggregation";
|
|
81
|
+
import type { CatalogGatherProviderAuthEvidence } from "./filesystem-evidence";
|
|
82
|
+
import type {
|
|
83
|
+
CatalogAdmissionSnapshot,
|
|
84
|
+
CatalogDiscoveryPolicyField,
|
|
85
|
+
CatalogGatherAuthorityIdentity,
|
|
86
|
+
CatalogProviderDiscoveryPolicySnapshot,
|
|
87
|
+
CatalogProcessLocalEvidence,
|
|
88
|
+
CatalogSourceEvidence,
|
|
89
|
+
CatalogTrustedOpenAiApiPolicySnapshot,
|
|
90
|
+
} from "../convergence-types";
|
|
91
|
+
|
|
92
|
+
export type { CatalogGatherProviderAuthEvidence } from "./filesystem-evidence";
|
|
93
|
+
|
|
94
|
+
/** Concurrent gatherRoutedModels callers with the same catalog identity share one live discovery.
|
|
95
|
+
* Keyed by gatherFlightKey so a different config cannot join or evict the wrong flight. */
|
|
96
|
+
export interface CatalogGatherProviderAuthOutcome {
|
|
97
|
+
readonly provider: string;
|
|
98
|
+
readonly state: OAuthActiveTokenObservation["kind"];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface CatalogGatherProviderModelOutcome {
|
|
102
|
+
readonly provider: string;
|
|
103
|
+
readonly state: "authoritative" | "degraded";
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface GatherRoutedModelsOptions {
|
|
107
|
+
comboOmissions?: ComboCatalogOmission[];
|
|
108
|
+
providerAuthOutcomes?: CatalogGatherProviderAuthOutcome[];
|
|
109
|
+
/** Flight-local authority of each provider's returned model rows. */
|
|
110
|
+
providerModelOutcomes?: CatalogGatherProviderModelOutcome[];
|
|
111
|
+
/** Internal convergence sink for the immutable policy that produced the returned rows. */
|
|
112
|
+
discoveryPolicySnapshots?: CatalogProviderDiscoveryPolicySnapshot[];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
interface GatherFlightResult {
|
|
116
|
+
models: CatalogModel[];
|
|
117
|
+
comboOmissions: ComboCatalogOmission[];
|
|
118
|
+
providerAuthOutcomes: readonly CatalogGatherProviderAuthOutcome[];
|
|
119
|
+
providerModelOutcomes: readonly CatalogGatherProviderModelOutcome[];
|
|
120
|
+
discoveryPolicySnapshots: readonly CatalogProviderDiscoveryPolicySnapshot[];
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
interface ProviderModelsResult {
|
|
124
|
+
readonly models: CatalogModel[];
|
|
125
|
+
readonly outcome: CatalogGatherProviderModelOutcome;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
interface ModelsAuthResolution {
|
|
129
|
+
readonly apiKey: string | undefined;
|
|
130
|
+
readonly observed: boolean;
|
|
131
|
+
readonly oauthApiBaseUrl?: string;
|
|
132
|
+
readonly oauthProjectId?: string;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
type ModelsAuthResolver =
|
|
136
|
+
| { readonly kind: "refreshing" }
|
|
137
|
+
| {
|
|
138
|
+
readonly kind: "observed";
|
|
139
|
+
readonly resolve: (name: string, provider: OcxProviderConfig) => ModelsAuthResolution;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
type ModelsAuthResolverFactory = (
|
|
143
|
+
outcomes: CatalogGatherProviderAuthOutcome[],
|
|
144
|
+
) => ModelsAuthResolver;
|
|
145
|
+
|
|
146
|
+
interface CapturedModelsRequest {
|
|
147
|
+
readonly method: "GET" | "POST";
|
|
148
|
+
readonly url: string;
|
|
149
|
+
readonly headersWithoutCredential: Readonly<Record<string, string>>;
|
|
150
|
+
readonly headersWithCredential: Readonly<Record<string, string>>;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
interface CapturedProviderGather {
|
|
154
|
+
readonly name: string;
|
|
155
|
+
readonly provider: OcxProviderConfig;
|
|
156
|
+
readonly discovery: ResolvedProviderModelDiscovery;
|
|
157
|
+
readonly policy: CatalogProviderDiscoveryPolicySnapshot;
|
|
158
|
+
readonly request: CapturedModelsRequest;
|
|
159
|
+
readonly fastPolicyAuthority: FastPolicyAuthority;
|
|
160
|
+
readonly observedAuth?: ModelsAuthResolution;
|
|
161
|
+
/**
|
|
162
|
+
* Configured model ids this provider must keep even when live discovery omits
|
|
163
|
+
* them — combo targets that are also listed in providers.*.models (OCX-111).
|
|
164
|
+
* Combo-only ids (not in models[]) stay out of the public catalog and are
|
|
165
|
+
* synthesized for combo derivation instead (#1305).
|
|
166
|
+
*/
|
|
167
|
+
readonly retainConfiguredModelIds?: ReadonlySet<string>;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
interface GatherFlightCapture {
|
|
171
|
+
readonly discoveryPolicyIdentity: string;
|
|
172
|
+
readonly authIdentity: string;
|
|
173
|
+
readonly providerGraphIdentity: string;
|
|
174
|
+
readonly discoveryPolicySnapshots: readonly CatalogProviderDiscoveryPolicySnapshot[];
|
|
175
|
+
readonly providers: readonly CapturedProviderGather[];
|
|
176
|
+
readonly authResolver: ModelsAuthResolver;
|
|
177
|
+
readonly providerAuthOutcomes: readonly CatalogGatherProviderAuthOutcome[];
|
|
178
|
+
readonly openAiApiPolicy: CatalogTrustedOpenAiApiPolicySnapshot;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
interface GatherInflightEntry {
|
|
182
|
+
readonly discoveryPolicyIdentity: string;
|
|
183
|
+
/**
|
|
184
|
+
* The credential half of the join decision.
|
|
185
|
+
*
|
|
186
|
+
* `gatherFlightKey`'s fingerprint carries endpoints and model lists but no
|
|
187
|
+
* `authMode`, key or headers, and discovery policy does not carry them either.
|
|
188
|
+
* Two admissions differing ONLY in credential therefore produced the same key
|
|
189
|
+
* and the same policy, so the second joined the first and published rows the
|
|
190
|
+
* old key had fetched — reproduced against the real routes by rotating a key
|
|
191
|
+
* through `/api/providers/keys` mid-flight.
|
|
192
|
+
*
|
|
193
|
+
* Now REDUNDANT with `providerGraphIdentity`, which hashes the whole provider
|
|
194
|
+
* row and therefore covers `apiKey` too: removing this term alone leaves the
|
|
195
|
+
* credential regression green. It is kept deliberately, for two reasons. It
|
|
196
|
+
* covers what the graph cannot — the RESOLVED auth (`observedAuth`) and the
|
|
197
|
+
* final materialized headers, which are derived rather than stored, so an
|
|
198
|
+
* OAuth token that changes while the row is byte-identical still separates
|
|
199
|
+
* admissions. And it states the credential rule where a reader looks for it,
|
|
200
|
+
* instead of leaving it as an emergent property of hashing everything.
|
|
201
|
+
*/
|
|
202
|
+
readonly authIdentity: string;
|
|
203
|
+
/**
|
|
204
|
+
* The whole admitted provider graph, not a chosen subset.
|
|
205
|
+
*
|
|
206
|
+
* `providerCatalogFingerprint` is an ALLOW-LIST, so every field it forgot was
|
|
207
|
+
* silently treated as equivalence: credentials leaked a flight until
|
|
208
|
+
* `authIdentity` landed, and `reasoningEfforts` leaked one after that — both
|
|
209
|
+
* reproduced against real routes. Enumerating fields cannot converge, because
|
|
210
|
+
* the next field added to a provider row inherits the same defect. This
|
|
211
|
+
* identity therefore covers the enriched, frozen provider objects the flight
|
|
212
|
+
* actually gathered from, so a join is refused unless the admissions agree on
|
|
213
|
+
* everything rather than on everything somebody remembered to list.
|
|
214
|
+
*/
|
|
215
|
+
readonly providerGraphIdentity: string;
|
|
216
|
+
readonly promise: Promise<GatherFlightResult>;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function withCanonicalOpenAiForwardAuthDefault(
|
|
220
|
+
name: string,
|
|
221
|
+
provider: OcxProviderConfig,
|
|
222
|
+
): OcxProviderConfig {
|
|
223
|
+
if (name !== OPENAI_CODEX_PROVIDER_ID || provider.authMode !== undefined) return provider;
|
|
224
|
+
const candidate = { ...provider, authMode: "forward" as const };
|
|
225
|
+
return isCanonicalOpenAiForwardProvider(candidate) ? candidate : provider;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const gatherInflight = new Map<string, GatherInflightEntry[]>();
|
|
229
|
+
const CATALOG_GATHER_AUTHORITY_KEY = randomBytes(32);
|
|
230
|
+
const REQUEST_CREDENTIAL_SENTINEL = `ocx-catalog-credential-${randomBytes(16).toString("hex")}`;
|
|
231
|
+
const MAX_CONCURRENT_CATALOG_GATHERS = 8;
|
|
232
|
+
const gatherGate = createAdmissionGate("catalog_gathers", MAX_CONCURRENT_CATALOG_GATHERS);
|
|
233
|
+
|
|
234
|
+
export class CatalogGatherBusyError extends ResourceAdmissionError {
|
|
235
|
+
override readonly code = "catalog_busy";
|
|
236
|
+
readonly retryAfterSeconds = 1;
|
|
237
|
+
constructor() {
|
|
238
|
+
super("catalog_gathers", MAX_CONCURRENT_CATALOG_GATHERS);
|
|
239
|
+
this.name = "CatalogGatherBusyError";
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export function catalogGatherAdmissionMetrics(): AdmissionMetrics {
|
|
244
|
+
return gatherGate.metrics();
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function stableJson(value: unknown): string {
|
|
248
|
+
return JSON.stringify(value, (_key, nested) => {
|
|
249
|
+
if (nested && typeof nested === "object" && !Array.isArray(nested)) {
|
|
250
|
+
return Object.fromEntries(Object.entries(nested as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b)));
|
|
251
|
+
}
|
|
252
|
+
return nested;
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function framed(value: string): string {
|
|
257
|
+
return `${Buffer.byteLength(value, "utf8")}:${value}`;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function canonicalAuthorityEncoding(value: unknown): string {
|
|
261
|
+
if (value === null) return "null";
|
|
262
|
+
if (value === undefined) return "undefined";
|
|
263
|
+
if (typeof value === "string") return `string${framed(value)}`;
|
|
264
|
+
if (typeof value === "boolean") return value ? "boolean1" : "boolean0";
|
|
265
|
+
if (typeof value === "number") {
|
|
266
|
+
if (!Number.isFinite(value)) throw new TypeError("Catalog authority cannot encode a non-finite number.");
|
|
267
|
+
const encoded = Object.is(value, -0) ? "-0" : String(value);
|
|
268
|
+
return `number${framed(encoded)}`;
|
|
269
|
+
}
|
|
270
|
+
if (Array.isArray(value)) {
|
|
271
|
+
return `array${value.length}:${value.map(item => framed(canonicalAuthorityEncoding(item))).join("")}`;
|
|
272
|
+
}
|
|
273
|
+
if (typeof value === "object") {
|
|
274
|
+
const record = value as Record<string, unknown>;
|
|
275
|
+
const keys = Object.keys(record).sort((left, right) => left.localeCompare(right));
|
|
276
|
+
return `object${keys.length}:${keys.map(key => (
|
|
277
|
+
`${framed(key)}${framed(canonicalAuthorityEncoding(record[key]))}`
|
|
278
|
+
)).join("")}`;
|
|
279
|
+
}
|
|
280
|
+
throw new TypeError(`Catalog authority cannot encode ${typeof value}.`);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function keyedGatherIdentity(domain: string, value: unknown): string {
|
|
284
|
+
return createHmac("sha256", CATALOG_GATHER_AUTHORITY_KEY)
|
|
285
|
+
.update(framed(domain))
|
|
286
|
+
.update(framed(canonicalAuthorityEncoding(value)))
|
|
287
|
+
.digest("hex");
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function keyedGatherBytesIdentity(domain: string, value: Uint8Array): string {
|
|
291
|
+
return createHmac("sha256", CATALOG_GATHER_AUTHORITY_KEY)
|
|
292
|
+
.update(framed(domain))
|
|
293
|
+
.update(`${value.byteLength}:`)
|
|
294
|
+
.update(value)
|
|
295
|
+
.digest("hex");
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export function createCatalogGatherAuthorityIdentity(
|
|
299
|
+
snapshot: CatalogAdmissionSnapshot,
|
|
300
|
+
sourceEvidence: CatalogSourceEvidence,
|
|
301
|
+
processLocal: CatalogProcessLocalEvidence,
|
|
302
|
+
discoveryPolicies: readonly CatalogProviderDiscoveryPolicySnapshot[],
|
|
303
|
+
): CatalogGatherAuthorityIdentity {
|
|
304
|
+
const sourceEvidenceIdentity = keyedGatherIdentity("catalog-source-evidence-v1", sourceEvidence);
|
|
305
|
+
const processLocalEvidenceIdentity = keyedGatherIdentity("catalog-process-local-v1", processLocal);
|
|
306
|
+
const discoveryPolicyIdentity = keyedGatherIdentity("catalog-discovery-policy-v1", discoveryPolicies);
|
|
307
|
+
return Object.freeze({
|
|
308
|
+
version: 1 as const,
|
|
309
|
+
authorityId: keyedGatherIdentity("catalog-authority-v1", {
|
|
310
|
+
admittedConfig: snapshot.configIdentity,
|
|
311
|
+
discoveryPolicyIdentity,
|
|
312
|
+
sourceEvidenceIdentity,
|
|
313
|
+
processLocalEvidenceIdentity,
|
|
314
|
+
}),
|
|
315
|
+
admittedConfig: Object.freeze({
|
|
316
|
+
...snapshot.configIdentity,
|
|
317
|
+
generation: Object.freeze({ ...snapshot.configIdentity.generation }),
|
|
318
|
+
}),
|
|
319
|
+
authSnapshotIdentity: keyedGatherIdentity(
|
|
320
|
+
"catalog-auth-v1",
|
|
321
|
+
sourceEvidence.conditional["provider-auth-selection"],
|
|
322
|
+
),
|
|
323
|
+
discoveryPolicyIdentity,
|
|
324
|
+
nativeCatalogSourceIdentity: keyedGatherIdentity(
|
|
325
|
+
"catalog-native-v1",
|
|
326
|
+
sourceEvidence.conditional["native-catalog-selection"],
|
|
327
|
+
),
|
|
328
|
+
sourceEvidenceIdentity,
|
|
329
|
+
processLocalEvidenceIdentity,
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function detachedClone<T>(value: T): T {
|
|
334
|
+
if (Array.isArray(value)) return value.map(item => detachedClone(item)) as T;
|
|
335
|
+
if (value && typeof value === "object") {
|
|
336
|
+
const clone: Record<string, unknown> = {};
|
|
337
|
+
for (const key of Object.keys(value)) {
|
|
338
|
+
clone[key] = detachedClone((value as Record<string, unknown>)[key]);
|
|
339
|
+
}
|
|
340
|
+
return clone as T;
|
|
341
|
+
}
|
|
342
|
+
return value;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function recursivelyFreeze<T>(value: T): T {
|
|
346
|
+
if (!value || typeof value !== "object" || Object.isFrozen(value)) return value;
|
|
347
|
+
for (const nested of Object.values(value as Record<string, unknown>)) recursivelyFreeze(nested);
|
|
348
|
+
return Object.freeze(value);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function detachedFrozen<T>(value: T): T {
|
|
352
|
+
return recursivelyFreeze(detachedClone(value));
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function capturedField<T extends object, K extends keyof T>(
|
|
356
|
+
value: T | undefined,
|
|
357
|
+
key: K,
|
|
358
|
+
): CatalogDiscoveryPolicyField<T[K]> {
|
|
359
|
+
if (!value || !Object.hasOwn(value, key)) return Object.freeze({ state: "absent" });
|
|
360
|
+
return detachedFrozen({ state: "present" as const, value: value[key] });
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function captureTrustedOpenAiApiPolicy(
|
|
364
|
+
name: string,
|
|
365
|
+
registryTransportMatch: boolean,
|
|
366
|
+
): CatalogTrustedOpenAiApiPolicySnapshot {
|
|
367
|
+
if (name !== OPENAI_API_PROVIDER_ID) return Object.freeze({ state: "unused" });
|
|
368
|
+
if (!registryTransportMatch) return Object.freeze({ state: "transport-mismatch" });
|
|
369
|
+
const entry = getProviderRegistryEntry(name);
|
|
370
|
+
if (!entry?.models) return Object.freeze({ state: "registry-models-absent" });
|
|
371
|
+
return detachedFrozen({
|
|
372
|
+
state: "captured" as const,
|
|
373
|
+
models: entry.models,
|
|
374
|
+
...(entry.modelContextWindows ? { modelContextWindows: entry.modelContextWindows } : {}),
|
|
375
|
+
...(entry.modelMaxInputTokens ? { modelMaxInputTokens: entry.modelMaxInputTokens } : {}),
|
|
376
|
+
...(entry.modelInputModalities ? { modelInputModalities: entry.modelInputModalities } : {}),
|
|
377
|
+
...(entry.modelReasoningEfforts ? { modelReasoningEfforts: entry.modelReasoningEfforts } : {}),
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function captureModelsRequest(
|
|
382
|
+
name: string,
|
|
383
|
+
provider: OcxProviderConfig,
|
|
384
|
+
observedAuth: ModelsAuthResolution | undefined,
|
|
385
|
+
): CapturedModelsRequest {
|
|
386
|
+
const observed = observedAuth
|
|
387
|
+
? { oauthApiBaseUrl: observedAuth.oauthApiBaseUrl }
|
|
388
|
+
: undefined;
|
|
389
|
+
const withoutCredential = buildModelsRequest(provider, undefined, name, observed);
|
|
390
|
+
const withCredential = buildModelsRequest(provider, REQUEST_CREDENTIAL_SENTINEL, name, observed);
|
|
391
|
+
const method = withoutCredential.method ?? "GET";
|
|
392
|
+
if (withoutCredential.url !== withCredential.url || method !== (withCredential.method ?? "GET")) {
|
|
393
|
+
throw new TypeError(`Provider model discovery URL for ${name} depends on credential bytes.`);
|
|
394
|
+
}
|
|
395
|
+
return detachedFrozen({
|
|
396
|
+
method,
|
|
397
|
+
url: withoutCredential.url,
|
|
398
|
+
headersWithoutCredential: withoutCredential.headers,
|
|
399
|
+
headersWithCredential: withCredential.headers,
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function captureProviderGather(
|
|
404
|
+
name: string,
|
|
405
|
+
configured: OcxProviderConfig,
|
|
406
|
+
authResolver: ModelsAuthResolver,
|
|
407
|
+
retainConfiguredModelIds?: ReadonlySet<string>,
|
|
408
|
+
): CapturedProviderGather {
|
|
409
|
+
const enriched = detachedClone(withCanonicalOpenAiForwardAuthDefault(name, configured));
|
|
410
|
+
enrichProviderFromRegistry(name, enriched);
|
|
411
|
+
const registryTransportMatch = providerMatchesRegistryTransport(name, enriched);
|
|
412
|
+
const provider = recursivelyFreeze(enriched);
|
|
413
|
+
const fastPolicyAuthority = captureFastPolicyAuthority(
|
|
414
|
+
name,
|
|
415
|
+
provider,
|
|
416
|
+
registryTransportMatch,
|
|
417
|
+
configured,
|
|
418
|
+
);
|
|
419
|
+
const observedAuth = authResolver.kind === "observed"
|
|
420
|
+
&& provider.authMode !== "forward"
|
|
421
|
+
&& provider.liveModels !== false
|
|
422
|
+
? authResolver.resolve(name, provider)
|
|
423
|
+
: undefined;
|
|
424
|
+
const request = captureModelsRequest(name, provider, observedAuth);
|
|
425
|
+
const resolved = resolveProviderModelDiscovery(name, provider);
|
|
426
|
+
const discovery = detachedFrozen({
|
|
427
|
+
...(resolved.spec ? { spec: resolved.spec } : {}),
|
|
428
|
+
maxResponseBytes: resolved.maxResponseBytes,
|
|
429
|
+
maxModels: resolved.maxModels,
|
|
430
|
+
});
|
|
431
|
+
const trustedOpenAiApi = captureTrustedOpenAiApiPolicy(name, registryTransportMatch);
|
|
432
|
+
const policy = detachedFrozen({
|
|
433
|
+
provider: name,
|
|
434
|
+
registryTransportMatch,
|
|
435
|
+
location: {
|
|
436
|
+
spec: discovery.spec ? "present" as const : "absent" as const,
|
|
437
|
+
url: capturedField(discovery.spec, "url"),
|
|
438
|
+
path: capturedField(discovery.spec, "path"),
|
|
439
|
+
query: capturedField(discovery.spec, "query"),
|
|
440
|
+
},
|
|
441
|
+
finalMethod: request.method,
|
|
442
|
+
finalUrl: request.url,
|
|
443
|
+
filter: capturedField(discovery.spec, "filter"),
|
|
444
|
+
maxResponseBytes: discovery.maxResponseBytes,
|
|
445
|
+
maxModels: discovery.maxModels,
|
|
446
|
+
trustedOpenAiApi,
|
|
447
|
+
});
|
|
448
|
+
return Object.freeze({
|
|
449
|
+
name,
|
|
450
|
+
provider,
|
|
451
|
+
discovery,
|
|
452
|
+
policy,
|
|
453
|
+
request,
|
|
454
|
+
fastPolicyAuthority,
|
|
455
|
+
...(observedAuth ? { observedAuth: Object.freeze({ ...observedAuth }) } : {}),
|
|
456
|
+
...(retainConfiguredModelIds && retainConfiguredModelIds.size > 0
|
|
457
|
+
? { retainConfiguredModelIds }
|
|
458
|
+
: {}),
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** Model ids each provider must retain for combo catalog derivation (OCX-111). */
|
|
463
|
+
export function configuredComboTargetModelsByProvider(
|
|
464
|
+
config: Pick<OcxConfig, "combos">,
|
|
465
|
+
): Map<string, ReadonlySet<string>> {
|
|
466
|
+
const byProvider = new Map<string, Set<string>>();
|
|
467
|
+
for (const id of listComboIds(config)) {
|
|
468
|
+
const combo = getCombo(config, id);
|
|
469
|
+
if (!combo) continue;
|
|
470
|
+
for (const target of combo.targets) {
|
|
471
|
+
let models = byProvider.get(target.provider);
|
|
472
|
+
if (!models) {
|
|
473
|
+
models = new Set();
|
|
474
|
+
byProvider.set(target.provider, models);
|
|
475
|
+
}
|
|
476
|
+
models.add(target.model);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
return byProvider;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function captureGatherFlight(
|
|
483
|
+
config: OcxConfig,
|
|
484
|
+
createAuthResolver: ModelsAuthResolverFactory,
|
|
485
|
+
): GatherFlightCapture {
|
|
486
|
+
const providerAuthOutcomes: CatalogGatherProviderAuthOutcome[] = [];
|
|
487
|
+
const authResolver = createAuthResolver(providerAuthOutcomes);
|
|
488
|
+
const comboTargetsByProvider = configuredComboTargetModelsByProvider(config);
|
|
489
|
+
const providers = Object.entries(config.providers)
|
|
490
|
+
.filter(([, provider]) => provider.disabled !== true)
|
|
491
|
+
.map(([name, provider]) => captureProviderGather(
|
|
492
|
+
name,
|
|
493
|
+
provider,
|
|
494
|
+
authResolver,
|
|
495
|
+
comboTargetsByProvider.get(name),
|
|
496
|
+
));
|
|
497
|
+
const discoveryPolicySnapshots = Object.freeze(providers.map(provider => provider.policy));
|
|
498
|
+
return Object.freeze({
|
|
499
|
+
discoveryPolicyIdentity: keyedGatherIdentity("catalog-discovery-policy-v1", discoveryPolicySnapshots),
|
|
500
|
+
// Credentials are hashed under the same unexported per-process key, never
|
|
501
|
+
// stored or compared in the clear: this value can reach a map key and must
|
|
502
|
+
// not disclose a token. The final headers are included because a static
|
|
503
|
+
// header can carry authority just as an `apiKey` can.
|
|
504
|
+
authIdentity: keyedGatherIdentity("catalog-gather-auth-v1", providers.map(provider => ({
|
|
505
|
+
name: provider.name,
|
|
506
|
+
authMode: provider.provider.authMode ?? null,
|
|
507
|
+
liveModels: provider.provider.liveModels ?? null,
|
|
508
|
+
credential: provider.provider.apiKey ?? null,
|
|
509
|
+
observedAuth: provider.observedAuth ?? null,
|
|
510
|
+
headers: provider.request.headersWithCredential,
|
|
511
|
+
url: provider.request.url,
|
|
512
|
+
}))),
|
|
513
|
+
// Every enriched provider row the flight will gather from, in admission order.
|
|
514
|
+
// Anything that can change a catalog row lives in here by construction.
|
|
515
|
+
providerGraphIdentity: keyedGatherIdentity("catalog-gather-provider-graph-v1",
|
|
516
|
+
providers.map(provider => ({
|
|
517
|
+
name: provider.name,
|
|
518
|
+
// `fetch` is a caller-owned transport executor, not admitted state: the
|
|
519
|
+
// outbound transport honors it so a caller can supply its own HTTP path.
|
|
520
|
+
// It is the one member of a provider row that is legitimately a function,
|
|
521
|
+
// so it is dropped here rather than allowed to break every encode.
|
|
522
|
+
provider: omitProviderTransportExecutor(provider.provider),
|
|
523
|
+
fastPolicyAuthority: provider.fastPolicyAuthority,
|
|
524
|
+
// Combo retention is capture-time state, not a provider-row field. Two
|
|
525
|
+
// gathers that share providers but differ in combo targets must not join.
|
|
526
|
+
retainConfiguredModelIds: [...(provider.retainConfiguredModelIds ?? [])].sort(),
|
|
527
|
+
}))),
|
|
528
|
+
discoveryPolicySnapshots,
|
|
529
|
+
providers: Object.freeze(providers),
|
|
530
|
+
authResolver,
|
|
531
|
+
providerAuthOutcomes: Object.freeze([...providerAuthOutcomes]),
|
|
532
|
+
openAiApiPolicy: providers.find(provider => provider.name === OPENAI_API_PROVIDER_ID)?.policy.trustedOpenAiApi
|
|
533
|
+
?? Object.freeze({ state: "unused" as const }),
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* Drop the caller-owned transport executor before hashing a provider row.
|
|
539
|
+
*
|
|
540
|
+
* Fails closed on anything ELSE that cannot be encoded: the point of hashing the
|
|
541
|
+
* whole row is that no field escapes the comparison, so a second function member
|
|
542
|
+
* must surface as an encode error rather than being quietly skipped here.
|
|
543
|
+
*/
|
|
544
|
+
function omitProviderTransportExecutor(provider: OcxProviderConfig): Record<string, unknown> {
|
|
545
|
+
const entries = Object.entries(provider).filter(([key]) => key !== "fetch");
|
|
546
|
+
return Object.fromEntries(entries);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
function materializeCapturedHeaders(
|
|
550
|
+
request: CapturedModelsRequest,
|
|
551
|
+
apiKey: string | undefined,
|
|
552
|
+
): Record<string, string> {
|
|
553
|
+
const source = apiKey ? request.headersWithCredential : request.headersWithoutCredential;
|
|
554
|
+
return Object.fromEntries(Object.entries(source).map(([name, value]) => [
|
|
555
|
+
name,
|
|
556
|
+
apiKey ? value.split(REQUEST_CREDENTIAL_SENTINEL).join(apiKey) : value,
|
|
557
|
+
]));
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function providerCatalogFingerprint(name: string, prov: OcxProviderConfig): Record<string, unknown> {
|
|
561
|
+
return {
|
|
562
|
+
n: name,
|
|
563
|
+
// Preserve the persisted tri-state. Registry enrichment may turn an omitted value into
|
|
564
|
+
// `false` while an explicit `true` stays live, so those callers must not share a flight.
|
|
565
|
+
live: prov.liveModels ?? null,
|
|
566
|
+
base: prov.baseUrl ?? "",
|
|
567
|
+
adapter: prov.adapter ?? "",
|
|
568
|
+
models: [...(prov.models ?? [])].sort(),
|
|
569
|
+
selected: [...(prov.selectedModels ?? [])].sort(),
|
|
570
|
+
defaultModel: prov.defaultModel ?? null,
|
|
571
|
+
ctx: prov.contextWindow ?? null,
|
|
572
|
+
ctxW: prov.modelContextWindows ?? null,
|
|
573
|
+
maxIn: prov.modelMaxInputTokens ?? null,
|
|
574
|
+
inMod: prov.modelInputModalities ?? null,
|
|
575
|
+
re: prov.modelReasoningEfforts ?? null,
|
|
576
|
+
defRe: prov.modelDefaultReasoningEfforts ?? null,
|
|
577
|
+
rsSum: prov.modelSupportsReasoningSummaries ?? null,
|
|
578
|
+
rsDel: prov.modelReasoningSummaryDelivery ?? null,
|
|
579
|
+
serviceTier: prov.modelSupportsServiceTier ?? null,
|
|
580
|
+
noVis: [...(prov.noVisionModels ?? [])].sort(),
|
|
581
|
+
ptc: prov.parallelToolCalls ?? null,
|
|
582
|
+
gMode: prov.googleMode ?? null,
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
function gatherFlightKey(config: OcxConfig): string {
|
|
587
|
+
const providers = Object.entries(config.providers)
|
|
588
|
+
.filter(([, prov]) => prov.disabled !== true)
|
|
589
|
+
.map(([name, prov]) => providerCatalogFingerprint(name, prov))
|
|
590
|
+
.sort((a, b) => String(a.n).localeCompare(String(b.n)));
|
|
591
|
+
const assembly = stableJson({
|
|
592
|
+
providers,
|
|
593
|
+
disabledModels: [...(config.disabledModels ?? [])].sort(),
|
|
594
|
+
combos: config.combos ?? {},
|
|
595
|
+
customModels: (config.customModels ?? []).map((cm) => ({
|
|
596
|
+
p: cm.provider,
|
|
597
|
+
m: cm.modelId,
|
|
598
|
+
d: cm.displayName ?? null,
|
|
599
|
+
cw: cm.contextWindow ?? null,
|
|
600
|
+
im: cm.inputModalities ?? null,
|
|
601
|
+
})),
|
|
602
|
+
caps: config.providerContextCaps ?? null,
|
|
603
|
+
});
|
|
604
|
+
const digest = createHash("sha256").update(assembly).digest("hex").slice(0, 16);
|
|
605
|
+
return `${digest}#${config.modelCacheTtlMs ?? DEFAULT_MODEL_CACHE_TTL_MS}`;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/** Drop in-flight gather so tests / full cache clears do not reuse a stale promise. */
|
|
609
|
+
export function clearGatherRoutedModelsInflight(): void {
|
|
610
|
+
gatherInflight.clear();
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
export function configuredContextWindow(prov: OcxProviderConfig, id: string): number | undefined {
|
|
614
|
+
const configured = modelRecordValue(prov.modelContextWindows, id) ?? prov.contextWindow;
|
|
615
|
+
return typeof configured === "number" && configured > 0 ? configured : undefined;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
export function configuredInputModalities(prov: OcxProviderConfig, id: string): string[] | undefined {
|
|
619
|
+
const modalities = modelRecordValue(prov.modelInputModalities, id);
|
|
620
|
+
return Array.isArray(modalities) && modalities.length > 0 ? [...modalities] : undefined;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
export function configuredMaxInputTokens(prov: OcxProviderConfig, id: string): number | undefined {
|
|
624
|
+
const configured = modelRecordValue(prov.modelMaxInputTokens, id);
|
|
625
|
+
return typeof configured === "number" && configured > 0 ? configured : undefined;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
function configuredReasoningSummarySupport(prov: OcxProviderConfig | undefined, id: string): boolean | undefined {
|
|
629
|
+
if (!prov) return undefined;
|
|
630
|
+
const explicit = modelRecordValue(prov.modelSupportsReasoningSummaries, id);
|
|
631
|
+
if (explicit !== undefined) return explicit;
|
|
632
|
+
return modelRecordValue(prov.modelReasoningSummaryDelivery, id) !== undefined ? true : undefined;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
export function applyProviderConfigHints(name: string, prov: OcxProviderConfig, model: CatalogModel, providerCap?: number): CatalogModel {
|
|
636
|
+
void name;
|
|
637
|
+
const configuredCap = configuredContextWindow(prov, model.id);
|
|
638
|
+
const configuredMaxInput = configuredMaxInputTokens(prov, model.id);
|
|
639
|
+
let inputModalities = configuredInputModalities(prov, model.id);
|
|
640
|
+
// Vision-sidecar coverage: `noVisionModels` marks models whose images the PROXY describes
|
|
641
|
+
// (src/vision/index.ts). The catalog must still advertise image input for them — the Codex app
|
|
642
|
+
// gates attachments client-side on input_modalities, and a text-only entry would block images
|
|
643
|
+
// before the sidecar ever runs ("This model does not support image inputs").
|
|
644
|
+
if (modelInList(prov.noVisionModels, model.id)) {
|
|
645
|
+
const base = inputModalities ?? model.inputModalities ?? ["text"];
|
|
646
|
+
inputModalities = base.includes("image") ? [...base] : [...base, "image"];
|
|
647
|
+
}
|
|
648
|
+
const reasoningEfforts = configuredReasoningEfforts(prov, model.id);
|
|
649
|
+
const defaultReasoningEffort = modelRecordValue(prov.modelDefaultReasoningEfforts, model.id) ?? model.defaultReasoningEffort;
|
|
650
|
+
const supportsReasoningSummaries = configuredReasoningSummarySupport(prov, model.id);
|
|
651
|
+
const fastPolicy = fastPolicyForModel(prov, model.id, name);
|
|
652
|
+
const supportsServiceTier = serviceTierSupportFromPolicy(fastPolicy);
|
|
653
|
+
const {
|
|
654
|
+
supportsServiceTier: _staleServiceTier,
|
|
655
|
+
fastTierDescription: _staleFastTierDescription,
|
|
656
|
+
...modelWithoutServiceTier
|
|
657
|
+
} = model;
|
|
658
|
+
// 已发现窗口只允许被配置值压低;缺窗口时,已开的 Context cap 就是实际窗口。
|
|
659
|
+
const discoveredWindow = typeof model.contextWindow === "number" && model.contextWindow > 0
|
|
660
|
+
? model.contextWindow
|
|
661
|
+
: undefined;
|
|
662
|
+
const hintedWindow = discoveredWindow !== undefined
|
|
663
|
+
? (configuredCap !== undefined ? Math.min(discoveredWindow, configuredCap) : discoveredWindow)
|
|
664
|
+
: (configuredCap ?? (providerCap !== undefined ? resolveUnknownRoutedContextWindow(providerCap) : undefined));
|
|
665
|
+
const hinted = {
|
|
666
|
+
...modelWithoutServiceTier,
|
|
667
|
+
...(hintedWindow !== undefined ? { contextWindow: hintedWindow } : {}),
|
|
668
|
+
...(inputModalities ? { inputModalities } : {}),
|
|
669
|
+
...(reasoningEfforts !== undefined ? { reasoningEfforts } : {}),
|
|
670
|
+
...(configuredMaxInput !== undefined
|
|
671
|
+
? {
|
|
672
|
+
maxInputTokens: typeof model.maxInputTokens === "number" && model.maxInputTokens > 0
|
|
673
|
+
? Math.min(model.maxInputTokens, configuredMaxInput)
|
|
674
|
+
: configuredMaxInput,
|
|
675
|
+
}
|
|
676
|
+
: {}),
|
|
677
|
+
...(defaultReasoningEffort ? { defaultReasoningEffort } : {}),
|
|
678
|
+
...(typeof supportsReasoningSummaries === "boolean" ? { supportsReasoningSummaries } : {}),
|
|
679
|
+
...(typeof supportsServiceTier === "boolean" ? { supportsServiceTier } : {}),
|
|
680
|
+
...(supportsServiceTier === true && fastPolicy.fastTierDescription !== undefined
|
|
681
|
+
? { fastTierDescription: fastPolicy.fastTierDescription }
|
|
682
|
+
: {}),
|
|
683
|
+
...(prov.adapter === "kiro" ? { supportsVerbosity: false } : {}),
|
|
684
|
+
// Default-on for openai-chat providers (explicit false opts out); other adapters
|
|
685
|
+
// advertise only on explicit opt-in.
|
|
686
|
+
...(prov.parallelToolCalls === true || (prov.adapter === "openai-chat" && prov.parallelToolCalls !== false)
|
|
687
|
+
? { parallelToolCalls: true }
|
|
688
|
+
: {}),
|
|
689
|
+
...(prov.codexToolMode !== undefined ? { codexToolMode: prov.codexToolMode } : {}),
|
|
690
|
+
};
|
|
691
|
+
const capped = applyProviderContextCap(hinted.contextWindow, providerCap);
|
|
692
|
+
if (providerCap !== undefined && capped !== hinted.contextWindow) {
|
|
693
|
+
return { ...hinted, contextWindow: capped, contextCap: providerCap, contextCapped: true };
|
|
694
|
+
}
|
|
695
|
+
return providerCap !== undefined ? { ...hinted, contextCap: providerCap, contextCapped: false } : hinted;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
export function catalogHintsFromProviderConfig(name: string, prov: OcxProviderConfig, id: string, contextCap?: number): Partial<CatalogModel> {
|
|
699
|
+
const hinted = applyProviderConfigHints(name, prov, { id, provider: name }, contextCap);
|
|
700
|
+
const { provider: _provider, id: _id, ...hints } = hinted;
|
|
701
|
+
return hints;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
export function applyConfigHintsToCachedModels(name: string, prov: OcxProviderConfig, models: CatalogModel[], contextCap?: number): CatalogModel[] {
|
|
705
|
+
return models.map(model => applyProviderConfigHints(name, prov, model, contextCap));
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
/**
|
|
710
|
+
* Last-resort context window for combo member synthesis when discovery,
|
|
711
|
+
* provider config, and an enabled Context cap all omit one. Matches the
|
|
712
|
+
* catalog entry default in `normalizeRoutedCatalogEntry` so incomplete live
|
|
713
|
+
* rows still catalog. An enabled Context cap is the operator-facing window,
|
|
714
|
+
* not a clamp on this placeholder.
|
|
715
|
+
*/
|
|
716
|
+
const COMBO_MEMBER_CONTEXT_FALLBACK = 128_000;
|
|
717
|
+
|
|
718
|
+
interface ComboCatalogMemberFallback {
|
|
719
|
+
readonly contextWindow?: number;
|
|
720
|
+
/** Input ceiling when it is lower than the window (native GPT-5.6: 922k under 1.05M). */
|
|
721
|
+
readonly maxInputTokens?: number;
|
|
722
|
+
readonly inputModalities?: readonly string[];
|
|
723
|
+
readonly reasoningEfforts?: readonly string[];
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* Resolve a combo target to a catalog member for derivation.
|
|
728
|
+
* Prefer discovery metadata; when the target is missing from the gather map or
|
|
729
|
+
* lacks a positive contextWindow, synthesize from the (registry-enriched)
|
|
730
|
+
* provider config so combos remain catalogued when targets are configured but
|
|
731
|
+
* discovery metadata is incomplete. Disabled providers stay unresolved.
|
|
732
|
+
* When hints still omit contextWindow, prefer known maxInputTokens, else the
|
|
733
|
+
* enabled Context cap, else COMBO_MEMBER_CONTEXT_FALLBACK so a live row
|
|
734
|
+
* without ctx does not drop the whole combo from the public catalog.
|
|
735
|
+
*/
|
|
736
|
+
export function resolveComboCatalogMember(
|
|
737
|
+
target: { provider: string; model: string },
|
|
738
|
+
memberByKey: ReadonlyMap<string, CatalogModel>,
|
|
739
|
+
providers: ReadonlyMap<string, OcxProviderConfig>,
|
|
740
|
+
contextCap?: number,
|
|
741
|
+
fallback?: ComboCatalogMemberFallback,
|
|
742
|
+
): CatalogModel | undefined {
|
|
743
|
+
const existing = memberByKey.get(targetKey(target));
|
|
744
|
+
const prov = providers.get(target.provider);
|
|
745
|
+
// Disabled providers never contribute members — even a complete discovery row
|
|
746
|
+
// is unusable for catalog derivation while the provider is off.
|
|
747
|
+
if (prov?.disabled === true) return undefined;
|
|
748
|
+
|
|
749
|
+
const withFallbackMetadata = (member: CatalogModel): CatalogModel => {
|
|
750
|
+
if (!fallback) return member;
|
|
751
|
+
const contextWindow = typeof member.contextWindow === "number" && member.contextWindow > 0
|
|
752
|
+
? member.contextWindow
|
|
753
|
+
: undefined;
|
|
754
|
+
const addMaxInput = contextWindow !== undefined
|
|
755
|
+
&& !(typeof member.maxInputTokens === "number" && member.maxInputTokens > 0);
|
|
756
|
+
const addModalities = (!Array.isArray(member.inputModalities) || member.inputModalities.length === 0)
|
|
757
|
+
&& fallback.inputModalities !== undefined;
|
|
758
|
+
const addReasoning = member.reasoningEfforts === undefined
|
|
759
|
+
&& fallback.reasoningEfforts !== undefined;
|
|
760
|
+
if (!addMaxInput && !addModalities && !addReasoning) return member;
|
|
761
|
+
return {
|
|
762
|
+
...member,
|
|
763
|
+
// Never claim a larger input budget than the window, and prefer the model's own
|
|
764
|
+
// measured ceiling when the fallback carries one.
|
|
765
|
+
...(addMaxInput
|
|
766
|
+
? { maxInputTokens: Math.min(fallback.maxInputTokens ?? contextWindow!, contextWindow!) }
|
|
767
|
+
: {}),
|
|
768
|
+
...(addModalities ? { inputModalities: [...fallback.inputModalities!] } : {}),
|
|
769
|
+
...(addReasoning ? { reasoningEfforts: [...fallback.reasoningEfforts!] } : {}),
|
|
770
|
+
};
|
|
771
|
+
};
|
|
772
|
+
|
|
773
|
+
// Complete live/configured rows still honour providerContextCaps so a high
|
|
774
|
+
// discovery window cannot outrun an operator-configured cap. Native-alias
|
|
775
|
+
// fallback metadata may fill only capability gaps; it never raises an explicit
|
|
776
|
+
// discovered/configured context window.
|
|
777
|
+
if (
|
|
778
|
+
existing
|
|
779
|
+
&& typeof existing.contextWindow === "number"
|
|
780
|
+
&& existing.contextWindow > 0
|
|
781
|
+
) {
|
|
782
|
+
const capped = applyProviderContextCap(existing.contextWindow, contextCap);
|
|
783
|
+
if (capped === undefined || capped === existing.contextWindow) {
|
|
784
|
+
return withFallbackMetadata(existing);
|
|
785
|
+
}
|
|
786
|
+
const maxInput = typeof existing.maxInputTokens === "number" && existing.maxInputTokens > 0
|
|
787
|
+
? Math.min(existing.maxInputTokens, capped)
|
|
788
|
+
: Math.min(fallback?.maxInputTokens ?? capped, capped);
|
|
789
|
+
return withFallbackMetadata({
|
|
790
|
+
...existing,
|
|
791
|
+
contextWindow: capped,
|
|
792
|
+
maxInputTokens: maxInput,
|
|
793
|
+
contextCap,
|
|
794
|
+
contextCapped: true as const,
|
|
795
|
+
});
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
const base: CatalogModel = existing ?? {
|
|
799
|
+
id: target.model,
|
|
800
|
+
provider: target.provider,
|
|
801
|
+
};
|
|
802
|
+
const hinted = prov
|
|
803
|
+
? applyProviderConfigHints(target.provider, prov, base, contextCap)
|
|
804
|
+
: base;
|
|
805
|
+
const hintedContext = typeof hinted.contextWindow === "number" && hinted.contextWindow > 0
|
|
806
|
+
? hinted.contextWindow
|
|
807
|
+
: undefined;
|
|
808
|
+
const knownMaxInput = typeof hinted.maxInputTokens === "number" && hinted.maxInputTokens > 0
|
|
809
|
+
? hinted.maxInputTokens
|
|
810
|
+
: (typeof base.maxInputTokens === "number" && base.maxInputTokens > 0
|
|
811
|
+
? base.maxInputTokens
|
|
812
|
+
: undefined);
|
|
813
|
+
// Kept OUT of knownMaxInput on purpose: that value doubles as a context-window fallback
|
|
814
|
+
// below, and a native alias whose input ceiling (922k) is lower than its window (1.05M)
|
|
815
|
+
// would otherwise shrink the advertised window to the input limit.
|
|
816
|
+
const fallbackMaxInput = existing || prov ? fallback?.maxInputTokens : undefined;
|
|
817
|
+
// Real discovery/config values win. A native alias is the next fallback tier.
|
|
818
|
+
// The generic 128k/text synthesis from #1305 remains the final fallback.
|
|
819
|
+
const fallbackContext = existing || prov ? fallback?.contextWindow : undefined;
|
|
820
|
+
const uncappedContext = hintedContext
|
|
821
|
+
?? knownMaxInput
|
|
822
|
+
?? fallbackContext
|
|
823
|
+
?? (existing || prov ? resolveUnknownRoutedContextWindow(contextCap) : undefined);
|
|
824
|
+
if (uncappedContext === undefined) return undefined;
|
|
825
|
+
// 真发现值才压低。resolveUnknownRoutedContextWindow 已经把 cap 当成窗口填进去了,不能再 min 一次。
|
|
826
|
+
const usedDiscoveredWindow = hintedContext !== undefined || knownMaxInput !== undefined || fallbackContext !== undefined;
|
|
827
|
+
const cappedContext = usedDiscoveredWindow
|
|
828
|
+
? applyProviderContextCap(uncappedContext, contextCap)
|
|
829
|
+
: uncappedContext;
|
|
830
|
+
const contextWindow = cappedContext ?? uncappedContext;
|
|
831
|
+
const fallbackCapped = usedDiscoveredWindow
|
|
832
|
+
&& contextCap !== undefined
|
|
833
|
+
&& cappedContext !== undefined
|
|
834
|
+
&& cappedContext !== uncappedContext;
|
|
835
|
+
|
|
836
|
+
const inputModalities = hinted.inputModalities
|
|
837
|
+
?? base.inputModalities
|
|
838
|
+
?? (fallback?.inputModalities ? [...fallback.inputModalities] : undefined)
|
|
839
|
+
?? ["text"];
|
|
840
|
+
const reasoningEfforts = hinted.reasoningEfforts
|
|
841
|
+
?? (prov ? configuredReasoningEfforts(prov, target.model) : undefined)
|
|
842
|
+
?? base.reasoningEfforts
|
|
843
|
+
?? (fallback?.reasoningEfforts ? [...fallback.reasoningEfforts] : undefined);
|
|
844
|
+
// The model's own measured input ceiling still applies when discovery gave us nothing:
|
|
845
|
+
// GPT-5.6 advertises a 1.05M window but refuses input past 922k.
|
|
846
|
+
const effectiveMaxInput = knownMaxInput ?? fallbackMaxInput;
|
|
847
|
+
const maxInputTokens = effectiveMaxInput !== undefined
|
|
848
|
+
? Math.min(effectiveMaxInput, contextWindow)
|
|
849
|
+
: contextWindow;
|
|
850
|
+
|
|
851
|
+
return {
|
|
852
|
+
...hinted,
|
|
853
|
+
inputModalities,
|
|
854
|
+
...(reasoningEfforts !== undefined ? { reasoningEfforts } : {}),
|
|
855
|
+
contextWindow,
|
|
856
|
+
maxInputTokens,
|
|
857
|
+
...(fallbackCapped ? { contextCap, contextCapped: true as const } : {}),
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
export function isDatedVariantId(liveId: string, configuredId: string): boolean {
|
|
862
|
+
if (!liveId.startsWith(`${configuredId}-`)) return false;
|
|
863
|
+
return /^\d{8}$/.test(liveId.slice(configuredId.length + 1));
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
export const lastDropWarnSignature = new Map<string, string>();
|
|
867
|
+
let lastWarningReconciledGeneration = 0;
|
|
868
|
+
|
|
869
|
+
export function reconcileProviderFetchWarnings(generation: number): number {
|
|
870
|
+
if (generation <= lastWarningReconciledGeneration) return 0;
|
|
871
|
+
const removed = lastDropWarnSignature.size;
|
|
872
|
+
lastDropWarnSignature.clear();
|
|
873
|
+
lastWarningReconciledGeneration = generation;
|
|
874
|
+
return removed;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
export const QUIET_AUTHORITATIVE_CATALOG_PROVIDERS = new Set(["kimi", "xai"]);
|
|
878
|
+
|
|
879
|
+
export const CALLABLE_CONFIGURED_COMPATIBILITY_MODELS: Readonly<Record<string, ReadonlySet<string>>> = {
|
|
880
|
+
kimi: new Set([
|
|
881
|
+
"k3[1m]",
|
|
882
|
+
"kimi-k2.7-code",
|
|
883
|
+
"kimi-k2.7-code-highspeed",
|
|
884
|
+
"kimi-k2.6",
|
|
885
|
+
"kimi-k2.5",
|
|
886
|
+
]),
|
|
887
|
+
xai: new Set([
|
|
888
|
+
"grok-4.3",
|
|
889
|
+
"grok-4.20-0309-reasoning",
|
|
890
|
+
"grok-4.20-0309-non-reasoning",
|
|
891
|
+
"grok-build-0.1",
|
|
892
|
+
"grok-composer-2.5-fast",
|
|
893
|
+
]),
|
|
894
|
+
};
|
|
895
|
+
|
|
896
|
+
export function warnDroppedConfiguredIdsOnce(name: string, droppedConfiguredIds: string[]): void {
|
|
897
|
+
const signature = [...droppedConfiguredIds].sort().join(",");
|
|
898
|
+
if (lastDropWarnSignature.get(name) === signature) return;
|
|
899
|
+
lastDropWarnSignature.set(name, signature);
|
|
900
|
+
console.warn(
|
|
901
|
+
`[opencodex] Provider model discovery for "${name}" omitted configured model ids; dropping them from the authoritative live catalog: ${droppedConfiguredIds.join(", ")}.`,
|
|
902
|
+
);
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
/**
|
|
906
|
+
* Z.AI and Neuralwatt advertise GLM reasoning as a bare boolean, which would otherwise
|
|
907
|
+
* collapse to the four-tier default ladder that omits `max`. These two helpers name the
|
|
908
|
+
* ladder each GLM generation actually honours on the wire.
|
|
909
|
+
*/
|
|
910
|
+
/** GLM-5.2 and its 1M alias: the full five-tier ladder including `max`. */
|
|
911
|
+
export function isGlm52ModelId(id: string): boolean {
|
|
912
|
+
const normalized = id.trim().toLowerCase();
|
|
913
|
+
return normalized === "glm-5.2" || normalized === "glm-5.2[1m]";
|
|
914
|
+
}
|
|
915
|
+
/**
|
|
916
|
+
* GLM-5.3 and its 1M alias. 260814: docs.z.ai/devpack/latest-model folds every incoming
|
|
917
|
+
* effort into three effective tiers (low/minimal/light -> low, medium/high -> high,
|
|
918
|
+
* xhigh/max/ultra -> max), so a boolean capability must not be expanded to five rows.
|
|
919
|
+
*/
|
|
920
|
+
export function isGlm53ModelId(id: string): boolean {
|
|
921
|
+
const normalized = id.trim().toLowerCase();
|
|
922
|
+
return normalized === "glm-5.3" || normalized === "glm-5.3[1m]";
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
function plainRecord(value: unknown): Record<string, unknown> | undefined {
|
|
926
|
+
return value !== null && typeof value === "object" && !Array.isArray(value)
|
|
927
|
+
? value as Record<string, unknown>
|
|
928
|
+
: undefined;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
const MODEL_DISCOVERY_METADATA_CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;
|
|
932
|
+
|
|
933
|
+
function positiveSafeInteger(...values: unknown[]): number | undefined {
|
|
934
|
+
return values.find(value => typeof value === "number" && Number.isSafeInteger(value) && value > 0) as number | undefined;
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
function normalizedMetadataString(raw: string, maxLength: number): string | undefined {
|
|
938
|
+
if (raw.length > maxLength * 4 || MODEL_DISCOVERY_METADATA_CONTROL_CHARS.test(raw)) return undefined;
|
|
939
|
+
const normalized = raw.trim().toLowerCase().replace(/\s+/g, "-").slice(0, maxLength);
|
|
940
|
+
return normalized || undefined;
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
function normalizedStringList(value: unknown, maxItems = 32, maxLength = 64): string[] | undefined {
|
|
944
|
+
if (!Array.isArray(value)) return undefined;
|
|
945
|
+
const out: string[] = [];
|
|
946
|
+
const maxInspectedItems = Math.max(maxItems * 8, maxItems);
|
|
947
|
+
for (let i = 0; i < value.length && i < maxInspectedItems; i += 1) {
|
|
948
|
+
const raw = value[i];
|
|
949
|
+
if (typeof raw !== "string") continue;
|
|
950
|
+
const normalized = normalizedMetadataString(raw, maxLength);
|
|
951
|
+
if (normalized && !out.includes(normalized)) out.push(normalized);
|
|
952
|
+
if (out.length >= maxItems) break;
|
|
953
|
+
}
|
|
954
|
+
return out.length > 0 ? out : undefined;
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
function modelCapabilities(item: ProviderModelsApiItem): string[] | undefined {
|
|
958
|
+
const metadata = plainRecord(item.metadata);
|
|
959
|
+
const metadataCapabilities = metadata?.capabilities;
|
|
960
|
+
const capabilityRecord = plainRecord(metadataCapabilities)
|
|
961
|
+
?? plainRecord(item.capabilities)
|
|
962
|
+
?? plainRecord(item.features);
|
|
963
|
+
const out = new Set<string>();
|
|
964
|
+
for (const list of [item.capabilities, item.features, item.supported_features, metadataCapabilities]) {
|
|
965
|
+
for (const capability of normalizedStringList(list) ?? []) out.add(capability);
|
|
966
|
+
}
|
|
967
|
+
const capabilityFields = capabilityRecord ?? {};
|
|
968
|
+
let inspectedCapabilityFields = 0;
|
|
969
|
+
for (const key in capabilityFields) {
|
|
970
|
+
if (!Object.hasOwn(capabilityFields, key)) continue;
|
|
971
|
+
inspectedCapabilityFields += 1;
|
|
972
|
+
if (inspectedCapabilityFields > 256 || out.size >= 32) break;
|
|
973
|
+
if (capabilityFields[key] === true) {
|
|
974
|
+
const normalized = normalizedMetadataString(key, 64);
|
|
975
|
+
if (normalized) out.add(normalized);
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
for (const field of ["supports_tools", "supports_tool_calling", "supports_function_calling"] as const) {
|
|
979
|
+
if (item[field] === true) out.add("tools");
|
|
980
|
+
}
|
|
981
|
+
for (const field of ["supports_reasoning", "reasoning"] as const) {
|
|
982
|
+
if (item[field] === true) out.add("reasoning");
|
|
983
|
+
}
|
|
984
|
+
return out.size > 0 ? [...out].filter(Boolean).slice(0, 32) : undefined;
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
function modelInputModalities(
|
|
988
|
+
item: ProviderModelsApiItem,
|
|
989
|
+
capabilities: readonly string[] | undefined,
|
|
990
|
+
): string[] | undefined {
|
|
991
|
+
const metadata = plainRecord(item.metadata);
|
|
992
|
+
const capabilityRecord = plainRecord(metadata?.capabilities)
|
|
993
|
+
?? plainRecord(item.capabilities)
|
|
994
|
+
?? plainRecord(item.features);
|
|
995
|
+
const explicit = normalizedStringList(
|
|
996
|
+
item.input_modalities
|
|
997
|
+
?? item.modalities
|
|
998
|
+
?? metadata?.input_modalities
|
|
999
|
+
?? capabilityRecord?.input_modalities,
|
|
1000
|
+
8,
|
|
1001
|
+
24,
|
|
1002
|
+
)?.filter(value => (
|
|
1003
|
+
// Codex parses `input_modalities` as a closed enum of text | image | audio. A provider that
|
|
1004
|
+
// advertises anything else (zenmux reports "video") must not reach the catalog: Codex rejects
|
|
1005
|
+
// the whole file, so plugins, apps and MCP servers all stop loading over one model's metadata.
|
|
1006
|
+
value === "text" || value === "image" || value === "audio"
|
|
1007
|
+
));
|
|
1008
|
+
if (explicit && explicit.length > 0) return explicit;
|
|
1009
|
+
const architecture = plainRecord(item.architecture);
|
|
1010
|
+
const architectureModality = typeof architecture?.modality === "string"
|
|
1011
|
+
? normalizedMetadataString(architecture.modality, 64)
|
|
1012
|
+
: undefined;
|
|
1013
|
+
if (architectureModality?.includes("->")) {
|
|
1014
|
+
const [rawInput = ""] = architectureModality.split("->");
|
|
1015
|
+
const inferred = rawInput
|
|
1016
|
+
.split("+")
|
|
1017
|
+
.filter(value => value === "text" || value === "image" || value === "audio");
|
|
1018
|
+
if (inferred.length > 0) return [...new Set(inferred)];
|
|
1019
|
+
}
|
|
1020
|
+
if (capabilityRecord?.vision === false) return ["text"];
|
|
1021
|
+
if (capabilityRecord?.vision === true || capabilities?.some(value => (
|
|
1022
|
+
value === "vision" || value === "image-input" || value === "image_input"
|
|
1023
|
+
// llama.cpp and Ollama-compatible servers report vision as "multimodal" —
|
|
1024
|
+
// it is the only image signal those servers emit (#1797). Mapped to the
|
|
1025
|
+
// closed `text|image` enum rather than passed through: an out-of-enum
|
|
1026
|
+
// modality makes Codex reject the entire catalog file.
|
|
1027
|
+
|| value === "multimodal"
|
|
1028
|
+
))) {
|
|
1029
|
+
return ["text", "image"];
|
|
1030
|
+
}
|
|
1031
|
+
return undefined;
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
export function catalogHintsFromModelsApiItem(providerName: string, item: ProviderModelsApiItem): Partial<CatalogModel> {
|
|
1035
|
+
const metadata = plainRecord(item.metadata);
|
|
1036
|
+
const capabilityRecord = plainRecord(metadata?.capabilities) ?? plainRecord(item.capabilities);
|
|
1037
|
+
const limits = plainRecord(metadata?.limits);
|
|
1038
|
+
const contextWindow =
|
|
1039
|
+
positiveSafeInteger(
|
|
1040
|
+
limits?.max_context_length,
|
|
1041
|
+
metadata?.context_length,
|
|
1042
|
+
item.context_length,
|
|
1043
|
+
item.context_size,
|
|
1044
|
+
item.max_model_len,
|
|
1045
|
+
item.max_context_length,
|
|
1046
|
+
// llama.cpp reports the served context under `meta`: `n_ctx` is what the
|
|
1047
|
+
// server was actually started with, `n_ctx_train` the model's trained
|
|
1048
|
+
// maximum. Prefer the served value — routing must not promise a window the
|
|
1049
|
+
// running server will refuse. Both come LAST so no provider already
|
|
1050
|
+
// supplying a recognized field changes behavior (#1797).
|
|
1051
|
+
plainRecord(item.meta)?.n_ctx,
|
|
1052
|
+
plainRecord(item.meta)?.n_ctx_train,
|
|
1053
|
+
);
|
|
1054
|
+
const maxInputTokens = positiveSafeInteger(limits?.max_input_tokens, item.max_input_tokens);
|
|
1055
|
+
// Some OpenAI-compatible catalogs expose the selectable ladder under
|
|
1056
|
+
// `reasoning_parameters.efforts` instead of the older `reasoning_efforts` key.
|
|
1057
|
+
// Treat both as model metadata: otherwise a valid upstream capability disappears
|
|
1058
|
+
// before client exporters (including omp) can advertise it.
|
|
1059
|
+
const reasoningParameters = plainRecord(item.reasoning_parameters)
|
|
1060
|
+
?? plainRecord(metadata?.reasoning_parameters)
|
|
1061
|
+
?? plainRecord(capabilityRecord?.reasoning_parameters);
|
|
1062
|
+
const rawReasoningEfforts = capabilityRecord?.reasoning_effort
|
|
1063
|
+
?? item.reasoning_efforts
|
|
1064
|
+
?? reasoningParameters?.efforts;
|
|
1065
|
+
const listedReasoningEfforts = normalizedStringList(rawReasoningEfforts, 8, 24);
|
|
1066
|
+
const reasoningEfforts = listedReasoningEfforts
|
|
1067
|
+
? sanitizeCodexReasoningEfforts(listedReasoningEfforts)
|
|
1068
|
+
: typeof rawReasoningEfforts === "boolean"
|
|
1069
|
+
? (rawReasoningEfforts
|
|
1070
|
+
? ((providerName === "neuralwatt" || providerName === "zai") && isGlm53ModelId(item.id)
|
|
1071
|
+
? ["low", "high", "max"]
|
|
1072
|
+
: (providerName === "neuralwatt" || providerName === "zai") && isGlm52ModelId(item.id)
|
|
1073
|
+
? ["low", "medium", "high", "xhigh", "max"]
|
|
1074
|
+
: ["low", "medium", "high", "xhigh"])
|
|
1075
|
+
: [])
|
|
1076
|
+
: undefined;
|
|
1077
|
+
const capabilities = modelCapabilities(item);
|
|
1078
|
+
const inputModalities = modelInputModalities(item, capabilities);
|
|
1079
|
+
return {
|
|
1080
|
+
...(contextWindow && contextWindow > 0 ? { contextWindow } : {}),
|
|
1081
|
+
...(maxInputTokens && maxInputTokens > 0 ? { maxInputTokens } : {}),
|
|
1082
|
+
...(reasoningEfforts !== undefined ? { reasoningEfforts } : {}),
|
|
1083
|
+
...(inputModalities ? { inputModalities } : {}),
|
|
1084
|
+
...(capabilities ? { capabilities } : {}),
|
|
1085
|
+
};
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
function boundedOwnedBy(value: unknown): string | undefined {
|
|
1089
|
+
if (typeof value !== "string" || value.length === 0 || value.length > 256) return undefined;
|
|
1090
|
+
if (MODEL_DISCOVERY_METADATA_CONTROL_CHARS.test(value)) return undefined;
|
|
1091
|
+
return value;
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
const refreshingModelsAuthResolver: ModelsAuthResolver = { kind: "refreshing" };
|
|
1095
|
+
|
|
1096
|
+
function observedModelsAuthResolver(
|
|
1097
|
+
authStoreBuffer: Uint8Array | null,
|
|
1098
|
+
outcomes: CatalogGatherProviderAuthOutcome[],
|
|
1099
|
+
): ModelsAuthResolver {
|
|
1100
|
+
return {
|
|
1101
|
+
kind: "observed",
|
|
1102
|
+
resolve(name, provider) {
|
|
1103
|
+
if (provider.authMode === "forward") return { apiKey: undefined, observed: true };
|
|
1104
|
+
if (provider.authMode !== "oauth") {
|
|
1105
|
+
return { apiKey: resolveEnvValue(provider.apiKey), observed: true };
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
const observation = observeActiveOAuthAccessToken(name, authStoreBuffer);
|
|
1109
|
+
outcomes.push({ provider: name, state: observation.kind });
|
|
1110
|
+
if (observation.kind !== "available") return { apiKey: undefined, observed: true };
|
|
1111
|
+
return {
|
|
1112
|
+
apiKey: observation.snapshot.accessToken,
|
|
1113
|
+
observed: true,
|
|
1114
|
+
...(observation.snapshot.apiBaseUrl ? { oauthApiBaseUrl: observation.snapshot.apiBaseUrl } : {}),
|
|
1115
|
+
...(observation.snapshot.projectId ? { oauthProjectId: observation.snapshot.projectId } : {}),
|
|
1116
|
+
};
|
|
1117
|
+
},
|
|
1118
|
+
};
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
async function fetchProviderModelsWithAuth(
|
|
1122
|
+
captured: CapturedProviderGather,
|
|
1123
|
+
ttlMs: number,
|
|
1124
|
+
contextCap: number | undefined,
|
|
1125
|
+
resolveAuth: ModelsAuthResolver,
|
|
1126
|
+
): Promise<ProviderModelsResult> {
|
|
1127
|
+
const { name, provider: prov, discovery, request } = captured;
|
|
1128
|
+
const observed = (
|
|
1129
|
+
models: CatalogModel[],
|
|
1130
|
+
state: CatalogGatherProviderModelOutcome["state"],
|
|
1131
|
+
): ProviderModelsResult => ({ models, outcome: { provider: name, state } });
|
|
1132
|
+
// Capture before any credential refresh or outbound await. OAuth account changes clear this
|
|
1133
|
+
// generation, so a request started with the former account cannot later publish its result.
|
|
1134
|
+
const cacheGeneration = captureModelCacheGeneration(name);
|
|
1135
|
+
const isCurrentCacheGeneration = () => isModelCacheGenerationCurrent(name, cacheGeneration);
|
|
1136
|
+
if (prov.authMode === "forward") return observed([], "authoritative"); // ChatGPT backend has no /models
|
|
1137
|
+
const seedVertexDefault = prov.adapter === "google"
|
|
1138
|
+
&& prov.googleMode === "vertex"
|
|
1139
|
+
&& (prov.models?.length ?? 0) === 0
|
|
1140
|
+
&& Boolean(prov.defaultModel);
|
|
1141
|
+
const configuredIds = seedVertexDefault && prov.defaultModel ? [prov.defaultModel] : (prov.models ?? []);
|
|
1142
|
+
const configured: CatalogModel[] = configuredIds.map(id => ({
|
|
1143
|
+
id,
|
|
1144
|
+
provider: name,
|
|
1145
|
+
...catalogHintsFromProviderConfig(name, prov, id, contextCap),
|
|
1146
|
+
}));
|
|
1147
|
+
const withConfiguredRetention = (
|
|
1148
|
+
models: CatalogModel[],
|
|
1149
|
+
options?: { retainComboTargets?: boolean; warnDrops?: boolean },
|
|
1150
|
+
): CatalogModel[] => {
|
|
1151
|
+
const { models: merged, droppedConfiguredIds } = mergeConfiguredModelsIntoLiveCatalog({
|
|
1152
|
+
name,
|
|
1153
|
+
provider: prov,
|
|
1154
|
+
models,
|
|
1155
|
+
configured,
|
|
1156
|
+
retainConfiguredModelIds: captured.retainConfiguredModelIds,
|
|
1157
|
+
contextCap,
|
|
1158
|
+
seedVertexDefault,
|
|
1159
|
+
retainComboTargets: options?.retainComboTargets,
|
|
1160
|
+
});
|
|
1161
|
+
if (
|
|
1162
|
+
options?.warnDrops === true
|
|
1163
|
+
&& droppedConfiguredIds.length > 0
|
|
1164
|
+
&& name !== OPENAI_API_PROVIDER_ID
|
|
1165
|
+
&& !QUIET_AUTHORITATIVE_CATALOG_PROVIDERS.has(name)
|
|
1166
|
+
) {
|
|
1167
|
+
warnDroppedConfiguredIdsOnce(name, droppedConfiguredIds);
|
|
1168
|
+
}
|
|
1169
|
+
return merged;
|
|
1170
|
+
};
|
|
1171
|
+
// Static catalogs never need an OAuth refresh or an upstream model request. Clear any
|
|
1172
|
+
// discovery failure left by an older live configuration even when the account is logged out.
|
|
1173
|
+
if (prov.liveModels === false) {
|
|
1174
|
+
clearProviderDiscoveryStatus(name);
|
|
1175
|
+
return observed(configured, "authoritative");
|
|
1176
|
+
}
|
|
1177
|
+
const auth: ModelsAuthResolution = captured.observedAuth ?? (resolveAuth.kind === "refreshing"
|
|
1178
|
+
? prov.authMode === "oauth" && effectiveGoogleMode(name, prov) === "cloud-code-assist"
|
|
1179
|
+
? await getValidAccessTokenSnapshot(name)
|
|
1180
|
+
.then(snapshot => ({
|
|
1181
|
+
apiKey: snapshot.accessToken,
|
|
1182
|
+
observed: false,
|
|
1183
|
+
...(snapshot.projectId ? { oauthProjectId: snapshot.projectId } : {}),
|
|
1184
|
+
}))
|
|
1185
|
+
.catch(() => ({ apiKey: undefined, observed: false }))
|
|
1186
|
+
: { apiKey: await resolveModelsAuthToken(name, prov), observed: false }
|
|
1187
|
+
: resolveAuth.resolve(name, prov));
|
|
1188
|
+
const apiKey = auth.apiKey;
|
|
1189
|
+
// A configured default is a real callable selector and must remain discoverable when a
|
|
1190
|
+
// compatible provider's live /models request fails (issue #308). Keep this separate from the
|
|
1191
|
+
// explicit static list: `liveModels: false` + empty `models[]` intentionally publishes zero
|
|
1192
|
+
// rows, while a failed live discovery may degrade to the default selector.
|
|
1193
|
+
const failedDiscoveryConfigured = configured.length > 0 || !prov.defaultModel || prov.adapter !== "anthropic"
|
|
1194
|
+
? configured
|
|
1195
|
+
: [{
|
|
1196
|
+
id: prov.defaultModel,
|
|
1197
|
+
provider: name,
|
|
1198
|
+
...catalogHintsFromProviderConfig(name, prov, prov.defaultModel, contextCap),
|
|
1199
|
+
}];
|
|
1200
|
+
const vertexDefaultSeed = seedVertexDefault ? configured[0] : undefined;
|
|
1201
|
+
const withVertexDefaultSeed = (models: CatalogModel[]): CatalogModel[] => (
|
|
1202
|
+
vertexDefaultSeed && !models.some(model => model.id === vertexDefaultSeed.id)
|
|
1203
|
+
? [...models, vertexDefaultSeed]
|
|
1204
|
+
: models
|
|
1205
|
+
);
|
|
1206
|
+
if (prov.adapter === "cursor") {
|
|
1207
|
+
if (!apiKey) return observed(configured, "degraded");
|
|
1208
|
+
// Cursor uses a bespoke GetUsableModels RPC (not /models), returning the full effort-suffixed
|
|
1209
|
+
// variants this PLAN can use. Keep the base-model UX (the request builder appends the effort
|
|
1210
|
+
// suffix) but filter the static seed to the bases the account actually has — so models not on the
|
|
1211
|
+
// plan (e.g. claude-fable-5) drop out instead of failing ERROR_BAD_MODEL_NAME. Fall back to the seed.
|
|
1212
|
+
const cachedCursor = getFreshCached(name, ttlMs);
|
|
1213
|
+
if (cachedCursor) {
|
|
1214
|
+
return observed(
|
|
1215
|
+
withConfiguredRetention(applyConfigHintsToCachedModels(name, prov, cachedCursor)),
|
|
1216
|
+
"authoritative",
|
|
1217
|
+
);
|
|
1218
|
+
}
|
|
1219
|
+
if (isModelsFetchCoolingDown(name)) {
|
|
1220
|
+
const cooling = getStaleCached(name);
|
|
1221
|
+
return observed(
|
|
1222
|
+
withConfiguredRetention(
|
|
1223
|
+
cooling ? applyConfigHintsToCachedModels(name, prov, cooling) : configured,
|
|
1224
|
+
),
|
|
1225
|
+
"degraded",
|
|
1226
|
+
);
|
|
1227
|
+
}
|
|
1228
|
+
const cursorFetch = (prov as OcxProviderConfig & { fetch?: typeof globalThis.fetch }).fetch;
|
|
1229
|
+
const liveResult = await fetchCursorUsableModels({
|
|
1230
|
+
apiKey,
|
|
1231
|
+
baseUrl: prov.baseUrl,
|
|
1232
|
+
upstreamHttpVersion: prov.upstreamHttpVersion,
|
|
1233
|
+
...(cursorFetch ? { fetch: cursorFetch } : {}),
|
|
1234
|
+
});
|
|
1235
|
+
if (liveResult.ok) {
|
|
1236
|
+
const available = filterCursorConfiguredModelsByLiveDiscovery(configured, liveResult.models);
|
|
1237
|
+
const result = available.length > 0 ? available : configured;
|
|
1238
|
+
// Cache the discovery-filtered roster without combo retention so a later
|
|
1239
|
+
// gather can re-apply the current capture's retain set on read.
|
|
1240
|
+
const forCache = withConfiguredRetention(result, { retainComboTargets: false });
|
|
1241
|
+
if (!setCached(name, forCache, Date.now(), cacheGeneration)) {
|
|
1242
|
+
return observed(withConfiguredRetention(configured), "degraded");
|
|
1243
|
+
}
|
|
1244
|
+
markProviderDiscoveryOk(name, liveResult.models.length);
|
|
1245
|
+
return observed(withConfiguredRetention(forCache, { warnDrops: true }), "authoritative");
|
|
1246
|
+
}
|
|
1247
|
+
if (isCurrentCacheGeneration()) {
|
|
1248
|
+
markModelsFetchFailure(name);
|
|
1249
|
+
markProviderDiscoveryFailed(name, { reason: "provider" });
|
|
1250
|
+
console.warn(
|
|
1251
|
+
`[opencodex] Cursor model discovery for "${name}" failed [${liveResult.error}]${liveResult.detail ? `: ${liveResult.detail}` : ""}; using stale/static catalog degradation.`,
|
|
1252
|
+
);
|
|
1253
|
+
}
|
|
1254
|
+
const staleCursor = getStaleCached(name);
|
|
1255
|
+
return observed(
|
|
1256
|
+
withConfiguredRetention(
|
|
1257
|
+
staleCursor ? applyConfigHintsToCachedModels(name, prov, staleCursor) : configured,
|
|
1258
|
+
),
|
|
1259
|
+
"degraded",
|
|
1260
|
+
);
|
|
1261
|
+
}
|
|
1262
|
+
if (prov.authMode === "oauth" && !apiKey) {
|
|
1263
|
+
// No usable token (logged out, or account marked needsReauth). Still surface the
|
|
1264
|
+
// configured static catalog so the GUI Models tab / rail counts are not empty —
|
|
1265
|
+
// matching Cursor's !apiKey → configured degradation and fetch-failure fallback.
|
|
1266
|
+
return observed(configured, "degraded");
|
|
1267
|
+
}
|
|
1268
|
+
const cloudCodeAssist = effectiveGoogleMode(name, prov) === "cloud-code-assist";
|
|
1269
|
+
const project = prov.project ?? auth.oauthProjectId;
|
|
1270
|
+
if (cloudCodeAssist && !project) return observed(configured, "degraded");
|
|
1271
|
+
const fresh = getFreshCached(name, ttlMs);
|
|
1272
|
+
if (fresh) {
|
|
1273
|
+
return observed(
|
|
1274
|
+
withConfiguredRetention(
|
|
1275
|
+
withVertexDefaultSeed(applyConfigHintsToCachedModels(name, prov, fresh, contextCap)),
|
|
1276
|
+
),
|
|
1277
|
+
"authoritative",
|
|
1278
|
+
); // dedups Codex's frequent /v1/models polling within the TTL
|
|
1279
|
+
}
|
|
1280
|
+
if (isModelsFetchCoolingDown(name)) {
|
|
1281
|
+
// A recently-failed provider (unreachable API, missing proxy, bad key) must not re-pay the
|
|
1282
|
+
// fetch timeout on every catalog poll — the dashboard polls this path per page load.
|
|
1283
|
+
const stale = getStaleCached(name);
|
|
1284
|
+
return observed(
|
|
1285
|
+
withConfiguredRetention(
|
|
1286
|
+
stale
|
|
1287
|
+
? withVertexDefaultSeed(applyConfigHintsToCachedModels(name, prov, stale, contextCap))
|
|
1288
|
+
: failedDiscoveryConfigured,
|
|
1289
|
+
),
|
|
1290
|
+
"degraded",
|
|
1291
|
+
);
|
|
1292
|
+
}
|
|
1293
|
+
const url = request.url;
|
|
1294
|
+
const headers = materializeCapturedHeaders(request, apiKey);
|
|
1295
|
+
const urlClass = new URL(url).hostname.endsWith("aiplatform.googleapis.com")
|
|
1296
|
+
? "vertex-aiplatform"
|
|
1297
|
+
: "provider-models";
|
|
1298
|
+
const failedDiscoveryFallback = (
|
|
1299
|
+
failure: ProviderModelDiscoveryFailure,
|
|
1300
|
+
): { models: CatalogModel[]; fallback: "stale" | "configured"; shouldLog: boolean } => {
|
|
1301
|
+
if (!isCurrentCacheGeneration()) {
|
|
1302
|
+
return {
|
|
1303
|
+
models: withConfiguredRetention(failedDiscoveryConfigured),
|
|
1304
|
+
fallback: "configured",
|
|
1305
|
+
shouldLog: false,
|
|
1306
|
+
};
|
|
1307
|
+
}
|
|
1308
|
+
// Decide logging BEFORE recording the new status, so we can compare against the prior one and
|
|
1309
|
+
// suppress an identical repeated failure (#395 log flood). The failure stays observable via the
|
|
1310
|
+
// discovery-status API regardless.
|
|
1311
|
+
const shouldLog = shouldLogDiscoveryFailure(name, failure);
|
|
1312
|
+
markModelsFetchFailure(name);
|
|
1313
|
+
markProviderDiscoveryFailed(name, failure);
|
|
1314
|
+
const stale = getStaleCached(name);
|
|
1315
|
+
return {
|
|
1316
|
+
models: withConfiguredRetention(
|
|
1317
|
+
stale
|
|
1318
|
+
? withVertexDefaultSeed(applyConfigHintsToCachedModels(name, prov, stale, contextCap))
|
|
1319
|
+
: failedDiscoveryConfigured,
|
|
1320
|
+
),
|
|
1321
|
+
fallback: stale ? "stale" : "configured",
|
|
1322
|
+
shouldLog,
|
|
1323
|
+
};
|
|
1324
|
+
};
|
|
1325
|
+
try {
|
|
1326
|
+
const res = request.method === "POST"
|
|
1327
|
+
? await providerOutboundPost(name, prov, url, {
|
|
1328
|
+
headers,
|
|
1329
|
+
body: JSON.stringify({ project }),
|
|
1330
|
+
signal: AbortSignal.timeout(8000),
|
|
1331
|
+
})
|
|
1332
|
+
: await providerOutboundGet(name, prov, url, {
|
|
1333
|
+
headers,
|
|
1334
|
+
signal: AbortSignal.timeout(8000),
|
|
1335
|
+
});
|
|
1336
|
+
const redirectError = await providerRedirectError(res, url);
|
|
1337
|
+
if (redirectError) {
|
|
1338
|
+
const { models, fallback, shouldLog } = failedDiscoveryFallback({ reason: "http", httpStatus: res.status });
|
|
1339
|
+
if (shouldLog) {
|
|
1340
|
+
console.warn(
|
|
1341
|
+
`[opencodex] Provider model discovery for "${name}" ${redirectError} [urlClass=${urlClass}, fallback=${fallback}].`,
|
|
1342
|
+
);
|
|
1343
|
+
}
|
|
1344
|
+
return observed(models, "degraded");
|
|
1345
|
+
}
|
|
1346
|
+
if (!res.ok) {
|
|
1347
|
+
const { models, fallback, shouldLog } = failedDiscoveryFallback({ reason: "http", httpStatus: res.status });
|
|
1348
|
+
if (shouldLog) {
|
|
1349
|
+
console.warn(
|
|
1350
|
+
`[opencodex] Provider model discovery for "${name}" failed with HTTP ${res.status} [urlClass=${urlClass}, fallback=${fallback}].`,
|
|
1351
|
+
);
|
|
1352
|
+
}
|
|
1353
|
+
return observed(models, "degraded");
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
const contentType = (
|
|
1357
|
+
res.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() || "missing"
|
|
1358
|
+
).slice(0, 80);
|
|
1359
|
+
const bounded = await readBoundedDiscoveryJson(res, discovery.maxResponseBytes);
|
|
1360
|
+
if (!bounded.ok) {
|
|
1361
|
+
const { models, fallback, shouldLog } = failedDiscoveryFallback({ reason: "invalid_response" });
|
|
1362
|
+
const diagnostic = bounded.reason === "response_too_large"
|
|
1363
|
+
? `exceeded the ${discovery.maxResponseBytes}-byte response limit`
|
|
1364
|
+
: contentType === "application/json" || contentType.endsWith("+json")
|
|
1365
|
+
? "returned invalid JSON in a 2xx response"
|
|
1366
|
+
: "returned a non-JSON 2xx response";
|
|
1367
|
+
if (shouldLog) {
|
|
1368
|
+
console.warn(
|
|
1369
|
+
`[opencodex] Provider model discovery for "${name}" ${diagnostic} [status=${res.status}, contentType=${contentType}, urlClass=${urlClass}, fallback=${fallback}].`,
|
|
1370
|
+
);
|
|
1371
|
+
}
|
|
1372
|
+
return observed(models, "degraded");
|
|
1373
|
+
}
|
|
1374
|
+
const antigravity = cloudCodeAssist
|
|
1375
|
+
? parseAntigravityAvailableModels(bounded.value, discovery.maxModels)
|
|
1376
|
+
: undefined;
|
|
1377
|
+
if (cloudCodeAssist && !antigravity) {
|
|
1378
|
+
const { models, fallback, shouldLog } = failedDiscoveryFallback({ reason: "invalid_response" });
|
|
1379
|
+
if (shouldLog) {
|
|
1380
|
+
console.warn(
|
|
1381
|
+
`[opencodex] Provider model discovery for "${name}" returned malformed CCA model data [status=${res.status}, contentType=${contentType}, urlClass=${urlClass}, fallback=${fallback}].`,
|
|
1382
|
+
);
|
|
1383
|
+
}
|
|
1384
|
+
return observed(models, "degraded");
|
|
1385
|
+
}
|
|
1386
|
+
if (antigravity) {
|
|
1387
|
+
const live = antigravity.map(model => applyProviderConfigHints(name, prov, {
|
|
1388
|
+
id: model.id,
|
|
1389
|
+
provider: name,
|
|
1390
|
+
// CCA only exposes a numeric thinking budget. Until the adapter owns an exact Codex
|
|
1391
|
+
// effort-to-wire mapping for a newly discovered model, do not advertise a false ladder.
|
|
1392
|
+
reasoningEfforts: [],
|
|
1393
|
+
...(model.contextWindow ? { contextWindow: model.contextWindow } : {}),
|
|
1394
|
+
...(model.inputModalities ? { inputModalities: model.inputModalities } : {}),
|
|
1395
|
+
}, contextCap));
|
|
1396
|
+
const forCache = withConfiguredRetention(live, { retainComboTargets: false });
|
|
1397
|
+
if (!setCached(name, forCache, Date.now(), cacheGeneration)) {
|
|
1398
|
+
return observed(withConfiguredRetention(configured), "degraded");
|
|
1399
|
+
}
|
|
1400
|
+
registerAntigravityDiscoveredWireModels(prov.baseUrl, antigravity, {
|
|
1401
|
+
provider: name,
|
|
1402
|
+
cacheGeneration,
|
|
1403
|
+
});
|
|
1404
|
+
markProviderDiscoveryOk(name, live.length);
|
|
1405
|
+
return observed(withConfiguredRetention(forCache, { warnDrops: true }), "authoritative");
|
|
1406
|
+
}
|
|
1407
|
+
const extracted = extractProviderModelItems(bounded.value, discovery);
|
|
1408
|
+
if (!extracted.ok) {
|
|
1409
|
+
const { models, fallback, shouldLog } = failedDiscoveryFallback({ reason: "invalid_response" });
|
|
1410
|
+
const diagnostic: Record<ModelDiscoveryResponseFailure, string> = {
|
|
1411
|
+
response_too_large: "returned an oversized 2xx response",
|
|
1412
|
+
invalid_json: "returned invalid JSON in a 2xx response",
|
|
1413
|
+
invalid_shape: "returned malformed 2xx data",
|
|
1414
|
+
too_many_models: `exceeded the ${discovery.maxModels}-row model limit`,
|
|
1415
|
+
};
|
|
1416
|
+
if (shouldLog) {
|
|
1417
|
+
console.warn(
|
|
1418
|
+
`[opencodex] Provider model discovery for "${name}" ${diagnostic[extracted.reason]} [status=${res.status}, contentType=${contentType}, urlClass=${urlClass}, fallback=${fallback}].`,
|
|
1419
|
+
);
|
|
1420
|
+
}
|
|
1421
|
+
return observed(models, "degraded");
|
|
1422
|
+
}
|
|
1423
|
+
const items = extracted.items;
|
|
1424
|
+
const live = items.map(m => {
|
|
1425
|
+
const ownedBy = boundedOwnedBy(m.owned_by);
|
|
1426
|
+
return applyProviderConfigHints(name, prov, {
|
|
1427
|
+
id: m.id,
|
|
1428
|
+
provider: name,
|
|
1429
|
+
...(ownedBy ? { owned_by: ownedBy } : {}),
|
|
1430
|
+
...catalogHintsFromModelsApiItem(name, m),
|
|
1431
|
+
}, contextCap);
|
|
1432
|
+
})
|
|
1433
|
+
.filter(m => shouldExposeProviderModel(name, m.id));
|
|
1434
|
+
// Capture the count BEFORE the alias/configured augmentation below pushes extra rows into
|
|
1435
|
+
// `live`; otherwise configured entries would be reported as discovered ones.
|
|
1436
|
+
const liveModelCount = live.length;
|
|
1437
|
+
// Dated-release aliases + configured retention (compat allow-list, combo targets,
|
|
1438
|
+
// Vertex default). Cache without combo retention so a later gather re-applies the
|
|
1439
|
+
// current capture's retain set on read (warm-cache OCX-111 / #1308).
|
|
1440
|
+
const forCache = withConfiguredRetention(live, { retainComboTargets: false });
|
|
1441
|
+
const returned = withConfiguredRetention(forCache, { warnDrops: true });
|
|
1442
|
+
const droppedConfiguredIds = configured
|
|
1443
|
+
.map(model => model.id)
|
|
1444
|
+
.filter(id => !returned.some(model => model.id === id));
|
|
1445
|
+
if (returned.length === 0 && name !== OPENAI_API_PROVIDER_ID) {
|
|
1446
|
+
console.warn(
|
|
1447
|
+
`[opencodex] Provider model discovery for "${name}" returned an authoritative empty catalog; ${droppedConfiguredIds.length > 0 ? `dropping configured model ids: ${droppedConfiguredIds.join(", ")}` : "no models will be exposed"}.`,
|
|
1448
|
+
);
|
|
1449
|
+
}
|
|
1450
|
+
if (!setCached(name, forCache, Date.now(), cacheGeneration)) {
|
|
1451
|
+
return observed(withConfiguredRetention(configured), "degraded");
|
|
1452
|
+
}
|
|
1453
|
+
markProviderDiscoveryOk(name, liveModelCount);
|
|
1454
|
+
return observed(returned, "authoritative");
|
|
1455
|
+
} catch (error) {
|
|
1456
|
+
if (error instanceof ProviderOutboundPolicyError) {
|
|
1457
|
+
const { models, fallback, shouldLog } = failedDiscoveryFallback({ reason: "blocked" });
|
|
1458
|
+
if (shouldLog) {
|
|
1459
|
+
console.warn(
|
|
1460
|
+
`[opencodex] Provider model discovery for "${name}" was blocked by destination policy: ${error.message} [urlClass=${urlClass}, fallback=${fallback}].`,
|
|
1461
|
+
);
|
|
1462
|
+
}
|
|
1463
|
+
return observed(models, "degraded");
|
|
1464
|
+
}
|
|
1465
|
+
const { models, fallback, shouldLog } = failedDiscoveryFallback({ reason: "network" });
|
|
1466
|
+
if (shouldLog) {
|
|
1467
|
+
console.warn(
|
|
1468
|
+
`[opencodex] Provider model discovery for "${name}" threw ${error instanceof Error ? error.name : "unknown"} [urlClass=${urlClass}, fallback=${fallback}].`,
|
|
1469
|
+
);
|
|
1470
|
+
}
|
|
1471
|
+
return observed(models, "degraded");
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
export async function fetchProviderModels(
|
|
1476
|
+
name: string,
|
|
1477
|
+
prov: OcxProviderConfig,
|
|
1478
|
+
ttlMs: number,
|
|
1479
|
+
contextCap?: number,
|
|
1480
|
+
): Promise<CatalogModel[]> {
|
|
1481
|
+
const captured = captureProviderGather(name, prov, refreshingModelsAuthResolver);
|
|
1482
|
+
return (await fetchProviderModelsWithAuth(
|
|
1483
|
+
captured,
|
|
1484
|
+
ttlMs,
|
|
1485
|
+
contextCap,
|
|
1486
|
+
refreshingModelsAuthResolver,
|
|
1487
|
+
)).models;
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
export function shouldExposeProviderModel(providerName: string, modelId: string): boolean {
|
|
1491
|
+
if (providerName === "opencode-free") return modelId === "big-pickle" || modelId.endsWith("-free");
|
|
1492
|
+
return true;
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
export function shouldRetainConfiguredProviderModel(providerName: string, modelId: string): boolean {
|
|
1496
|
+
if (CALLABLE_CONFIGURED_COMPATIBILITY_MODELS[providerName]?.has(modelId)) return true;
|
|
1497
|
+
if (providerName === "opencode-free") return modelId === "big-pickle" || modelId.endsWith("-free");
|
|
1498
|
+
return false;
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
/**
|
|
1502
|
+
* Fold dated-release aliases and retain configured rows that must survive an
|
|
1503
|
+
* authoritative live roster (compatibility allow-list, combo targets, Vertex
|
|
1504
|
+
* default). Used on every discovery return — live, fresh cache, stale, and
|
|
1505
|
+
* failure fallback — so a warm cache captured before a combo existed still
|
|
1506
|
+
* surfaces the configured target (OCX-111 / #1308).
|
|
1507
|
+
*
|
|
1508
|
+
* Cache writes should pass `retainComboTargets: false` so combo retention is
|
|
1509
|
+
* re-applied on read against the current capture, not frozen into the TTL entry.
|
|
1510
|
+
*/
|
|
1511
|
+
export function mergeConfiguredModelsIntoLiveCatalog(opts: {
|
|
1512
|
+
name: string;
|
|
1513
|
+
provider: OcxProviderConfig;
|
|
1514
|
+
models: readonly CatalogModel[];
|
|
1515
|
+
configured: readonly CatalogModel[];
|
|
1516
|
+
retainConfiguredModelIds?: ReadonlySet<string>;
|
|
1517
|
+
contextCap?: number;
|
|
1518
|
+
seedVertexDefault?: boolean;
|
|
1519
|
+
retainComboTargets?: boolean;
|
|
1520
|
+
}): { models: CatalogModel[]; droppedConfiguredIds: string[] } {
|
|
1521
|
+
const {
|
|
1522
|
+
name,
|
|
1523
|
+
provider: prov,
|
|
1524
|
+
configured,
|
|
1525
|
+
retainConfiguredModelIds,
|
|
1526
|
+
contextCap,
|
|
1527
|
+
seedVertexDefault,
|
|
1528
|
+
retainComboTargets = true,
|
|
1529
|
+
} = opts;
|
|
1530
|
+
const out = [...opts.models];
|
|
1531
|
+
const present = new Set(out.map(model => model.id));
|
|
1532
|
+
const droppedConfiguredIds: string[] = [];
|
|
1533
|
+
for (const candidate of configured) {
|
|
1534
|
+
if (present.has(candidate.id)) continue;
|
|
1535
|
+
const dated = out.find(live => isDatedVariantId(live.id, candidate.id));
|
|
1536
|
+
if (dated) {
|
|
1537
|
+
out.push(applyProviderConfigHints(name, prov, { ...dated, id: candidate.id }, contextCap));
|
|
1538
|
+
present.add(candidate.id);
|
|
1539
|
+
continue;
|
|
1540
|
+
}
|
|
1541
|
+
if (
|
|
1542
|
+
seedVertexDefault === true
|
|
1543
|
+
|| shouldRetainConfiguredProviderModel(name, candidate.id)
|
|
1544
|
+
|| (retainComboTargets && retainConfiguredModelIds?.has(candidate.id) === true)
|
|
1545
|
+
) {
|
|
1546
|
+
out.push(candidate);
|
|
1547
|
+
present.add(candidate.id);
|
|
1548
|
+
continue;
|
|
1549
|
+
}
|
|
1550
|
+
droppedConfiguredIds.push(candidate.id);
|
|
1551
|
+
}
|
|
1552
|
+
return { models: out, droppedConfiguredIds };
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
export function filterCatalogVisibleModels(
|
|
1556
|
+
models: CatalogModel[],
|
|
1557
|
+
config: Pick<OcxConfig, "disabledModels" | "providers">,
|
|
1558
|
+
): CatalogModel[] {
|
|
1559
|
+
const disabled = new Set(config.disabledModels ?? []);
|
|
1560
|
+
const allowByProvider = new Map<string, Set<string>>();
|
|
1561
|
+
for (const [name, prov] of Object.entries(config.providers)) {
|
|
1562
|
+
const sel = prov.selectedModels;
|
|
1563
|
+
if (Array.isArray(sel) && sel.length > 0) allowByProvider.set(name, new Set(sel));
|
|
1564
|
+
}
|
|
1565
|
+
return models.filter(m => {
|
|
1566
|
+
const nativeAlias = m.provider === COMBO_NAMESPACE && m.nativeAlias === true;
|
|
1567
|
+
// disabledModels may be stored raw (canonical) or encoded (legacy UI writes).
|
|
1568
|
+
for (const stored of disabled) {
|
|
1569
|
+
// Combo management stores the public alias, while canonical `combo/<id>` references
|
|
1570
|
+
// remain valid for backward compatibility through slugEquals below.
|
|
1571
|
+
if (m.alias !== undefined && stored === catalogModelSlug(m) && !nativeAlias) return false;
|
|
1572
|
+
if (slugEquals(stored, m.provider, m.id)) return false;
|
|
1573
|
+
}
|
|
1574
|
+
const allow = allowByProvider.get(m.provider);
|
|
1575
|
+
return !allow || allow.has(m.id);
|
|
1576
|
+
});
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
export async function gatherRoutedModels(
|
|
1580
|
+
config: OcxConfig,
|
|
1581
|
+
options?: GatherRoutedModelsOptions,
|
|
1582
|
+
): Promise<CatalogModel[]> {
|
|
1583
|
+
return gatherRoutedModelsWithAuth(
|
|
1584
|
+
config,
|
|
1585
|
+
`refreshing:${gatherFlightKey(config)}`,
|
|
1586
|
+
() => refreshingModelsAuthResolver,
|
|
1587
|
+
options,
|
|
1588
|
+
);
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
/**
|
|
1592
|
+
* Catalog-gather model discovery using only auth-store bytes already captured by the
|
|
1593
|
+
* filesystem-evidence owner. This entry point never reaches the refreshing resolver.
|
|
1594
|
+
*/
|
|
1595
|
+
export async function gatherRoutedModelsForCatalogGather(
|
|
1596
|
+
config: OcxConfig,
|
|
1597
|
+
evidence: CatalogGatherProviderAuthEvidence,
|
|
1598
|
+
options?: GatherRoutedModelsOptions,
|
|
1599
|
+
): Promise<CatalogModel[]> {
|
|
1600
|
+
const authStoreBuffer = evidence.authStoreBuffer === null
|
|
1601
|
+
? null
|
|
1602
|
+
: Uint8Array.from(evidence.authStoreBuffer);
|
|
1603
|
+
const authIdentity = authStoreBuffer === null
|
|
1604
|
+
? "absent"
|
|
1605
|
+
: keyedGatherBytesIdentity("catalog-observed-auth-v1", authStoreBuffer);
|
|
1606
|
+
return gatherRoutedModelsWithAuth(
|
|
1607
|
+
config,
|
|
1608
|
+
`observed:${authIdentity}:${gatherFlightKey(config)}`,
|
|
1609
|
+
outcomes => observedModelsAuthResolver(authStoreBuffer, outcomes),
|
|
1610
|
+
options,
|
|
1611
|
+
);
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
async function gatherRoutedModelsWithAuth(
|
|
1615
|
+
config: OcxConfig,
|
|
1616
|
+
key: string,
|
|
1617
|
+
createAuthResolver: ModelsAuthResolverFactory,
|
|
1618
|
+
options?: GatherRoutedModelsOptions,
|
|
1619
|
+
): Promise<CatalogModel[]> {
|
|
1620
|
+
const capture = captureGatherFlight(config, createAuthResolver);
|
|
1621
|
+
const bucket = gatherInflight.get(key) ?? [];
|
|
1622
|
+
let entry = bucket.find(candidate => (
|
|
1623
|
+
candidate.discoveryPolicyIdentity === capture.discoveryPolicyIdentity
|
|
1624
|
+
&& candidate.authIdentity === capture.authIdentity
|
|
1625
|
+
&& candidate.providerGraphIdentity === capture.providerGraphIdentity
|
|
1626
|
+
));
|
|
1627
|
+
if (!entry) {
|
|
1628
|
+
const lease = gatherGate.tryAcquire();
|
|
1629
|
+
if (!lease) throw new CatalogGatherBusyError();
|
|
1630
|
+
// Claim the slot synchronously before any await so same-key callers join this flight.
|
|
1631
|
+
// Distinct authorities retain separate entries even when their legacy bucket matches.
|
|
1632
|
+
let ownedEntry!: GatherInflightEntry;
|
|
1633
|
+
const flight = gatherRoutedModelsUncached(config, capture).finally(() => {
|
|
1634
|
+
const current = gatherInflight.get(key);
|
|
1635
|
+
const index = current?.indexOf(ownedEntry) ?? -1;
|
|
1636
|
+
if (current && index >= 0) current.splice(index, 1);
|
|
1637
|
+
if (current?.length === 0) gatherInflight.delete(key);
|
|
1638
|
+
lease.release();
|
|
1639
|
+
});
|
|
1640
|
+
ownedEntry = Object.freeze({
|
|
1641
|
+
discoveryPolicyIdentity: capture.discoveryPolicyIdentity,
|
|
1642
|
+
authIdentity: capture.authIdentity,
|
|
1643
|
+
providerGraphIdentity: capture.providerGraphIdentity,
|
|
1644
|
+
promise: flight,
|
|
1645
|
+
});
|
|
1646
|
+
bucket.push(ownedEntry);
|
|
1647
|
+
gatherInflight.set(key, bucket);
|
|
1648
|
+
entry = ownedEntry;
|
|
1649
|
+
}
|
|
1650
|
+
const {
|
|
1651
|
+
models,
|
|
1652
|
+
comboOmissions,
|
|
1653
|
+
providerAuthOutcomes,
|
|
1654
|
+
providerModelOutcomes,
|
|
1655
|
+
discoveryPolicySnapshots,
|
|
1656
|
+
} = await entry.promise;
|
|
1657
|
+
if (options?.comboOmissions) {
|
|
1658
|
+
options.comboOmissions.length = 0;
|
|
1659
|
+
options.comboOmissions.push(...comboOmissions);
|
|
1660
|
+
}
|
|
1661
|
+
if (options?.providerAuthOutcomes) {
|
|
1662
|
+
options.providerAuthOutcomes.length = 0;
|
|
1663
|
+
options.providerAuthOutcomes.push(...providerAuthOutcomes);
|
|
1664
|
+
}
|
|
1665
|
+
if (options?.providerModelOutcomes) {
|
|
1666
|
+
options.providerModelOutcomes.length = 0;
|
|
1667
|
+
options.providerModelOutcomes.push(...providerModelOutcomes);
|
|
1668
|
+
}
|
|
1669
|
+
if (options?.discoveryPolicySnapshots) {
|
|
1670
|
+
options.discoveryPolicySnapshots.length = 0;
|
|
1671
|
+
options.discoveryPolicySnapshots.push(...discoveryPolicySnapshots);
|
|
1672
|
+
}
|
|
1673
|
+
return models;
|
|
1674
|
+
}
|
|
1675
|
+
|
|
1676
|
+
async function gatherRoutedModelsUncached(
|
|
1677
|
+
config: OcxConfig,
|
|
1678
|
+
capture: GatherFlightCapture,
|
|
1679
|
+
): Promise<GatherFlightResult> {
|
|
1680
|
+
// Flight-local list: joiners copy from the resolved promise, not a process-global last write.
|
|
1681
|
+
const localOmissions: ComboCatalogOmission[] = [];
|
|
1682
|
+
const localProviderAuthOutcomes = capture.providerAuthOutcomes;
|
|
1683
|
+
const resolveAuth = capture.authResolver;
|
|
1684
|
+
const ttlMs = config.modelCacheTtlMs ?? DEFAULT_MODEL_CACHE_TTL_MS;
|
|
1685
|
+
// Persisted provider entries can predate newer registry fields (noVisionModels,
|
|
1686
|
+
// modelInputModalities, ...). The ROUTER merges registry seeds at request time
|
|
1687
|
+
// (routedProviderConfig), so the proxy behaves correctly — the catalog listing must see the
|
|
1688
|
+
// same merged view or its advertisements drift from actual proxy behavior (e.g. a
|
|
1689
|
+
// vision-sidecar model advertised text-only, blocking image attachments app-side).
|
|
1690
|
+
// Enrich a CLONE: hydrated defaults must never leak into the persisted config.
|
|
1691
|
+
const activeProviders = capture.providers;
|
|
1692
|
+
const providerResults = await Promise.all(
|
|
1693
|
+
activeProviders.map(provider => fetchProviderModelsWithAuth(
|
|
1694
|
+
provider,
|
|
1695
|
+
ttlMs,
|
|
1696
|
+
providerContextCap(config, provider.name),
|
|
1697
|
+
resolveAuth,
|
|
1698
|
+
)),
|
|
1699
|
+
);
|
|
1700
|
+
const lists = providerResults.map(result => result.models);
|
|
1701
|
+
const apiAugmented = augmentRoutedModelsWithCapturedOpenAiApiRows(
|
|
1702
|
+
lists.flat(),
|
|
1703
|
+
config,
|
|
1704
|
+
capture.openAiApiPolicy,
|
|
1705
|
+
);
|
|
1706
|
+
const all = augmentRoutedModelsWithMetadata(apiAugmented, activeProviders.map(provider => provider.name), config.providers, config)
|
|
1707
|
+
// Drop image/video generation models (e.g. Grok image/video) by default. Cursor's static catalog
|
|
1708
|
+
// intentionally mirrors Cursor's public model table, including Gemini image preview, so the
|
|
1709
|
+
// exposure decision goes through shouldExposeRoutedModel (single choke point).
|
|
1710
|
+
.filter(shouldExposeRoutedModel);
|
|
1711
|
+
const memberByKey = new Map(all.map(model => [`${model.provider}/${model.id}`, model]));
|
|
1712
|
+
// [Decision Log]
|
|
1713
|
+
// - 목적과 의도: 콤보 타겟에 native OpenAI(Codex login) 모델이 포함될 때 카탈로그에서
|
|
1714
|
+
// 누락되는 버그(issue #268)를 수정. "openai" provider는 forward-auth(Codex login
|
|
1715
|
+
// passthrough)이므로 fetchProviderModels가 항상 []를 반환하고, native slugs는
|
|
1716
|
+
// 별도 정적 경로(nativeOpenAiSlugs)로만 노출됨. 따라서 memberByKey에
|
|
1717
|
+
// openai/<slug> 키가 존재하지 않아 콤보가 조용히 drop됨.
|
|
1718
|
+
// - 기존 구현 및 제약 조건: memberByKey는 routed provider /models fetch 결과로만 구성.
|
|
1719
|
+
// - 검토한 주요 대안: (A) native slugs를 all 배열에 직접 push — /v1/models와 온디스크
|
|
1720
|
+
// 카탈로그에서 native 모델이 중복 노출되는 부작용 발생. (B) memberByKey에만 synthetic
|
|
1721
|
+
// CatalogModel을 주입 — 콤보 멤버 해석에만 사용하고 all에는 추가하지 않으므로 기존
|
|
1722
|
+
// 노출 경로에 영향 없음.
|
|
1723
|
+
// - 선택한 방식: (B) — synthetic entries를 memberByKey에만 주입.
|
|
1724
|
+
// - 다른 대안 대신 이 방식을 선택한 이유: 기존 native 모델 노출 경로(/v1/models, 온디스크
|
|
1725
|
+
// 카탈로그 sync, management API)를 전혀 변경하지 않고 콤보 resolution만 수선하기 때문.
|
|
1726
|
+
// - 장점, 단점 및 영향: 장점 — 최소 수정, 기존 경로 무변경. 단점 — synthetic entries의
|
|
1727
|
+
// capability 데이터가 static/upstream snapshot 기반이므로, 사용자가 커스텀 config
|
|
1728
|
+
// 힌트(modelContextWindows 등)로 native 모델의 context window를 오버라이드한 경우
|
|
1729
|
+
// 반영되지 않음. 하지만 nativeOpenAiContextWindow가 이미 config 오버라이드를
|
|
1730
|
+
// 우선시하므로 실제 충돌 가능성은 낮음.
|
|
1731
|
+
if (!hasComboTargets(config)) {
|
|
1732
|
+
// Skip the native slug injection entirely when no combos are configured — avoids
|
|
1733
|
+
// calling nativeOpenAiSlugs() (which reads the live Codex catalog from disk) for
|
|
1734
|
+
// configs that will never need it.
|
|
1735
|
+
} else {
|
|
1736
|
+
const disabled = disabledNativeSlugs(config);
|
|
1737
|
+
const openaiContextCap = nativeContextLimits(config);
|
|
1738
|
+
const requiredNativeComboTargets = new Set(listComboIds(config).flatMap(id => {
|
|
1739
|
+
const combo = getCombo(config, id);
|
|
1740
|
+
return combo?.targets.flatMap(target => (
|
|
1741
|
+
target.provider === "openai" ? [target.model] : []
|
|
1742
|
+
)) ?? [];
|
|
1743
|
+
}));
|
|
1744
|
+
for (const slug of nativeOpenAiSlugs()) {
|
|
1745
|
+
// A bare native disable key hides the native row, not a combo that targets it.
|
|
1746
|
+
// Keep synthetic native metadata available to those combos.
|
|
1747
|
+
if (disabled.has(slug) && !requiredNativeComboTargets.has(slug)) continue;
|
|
1748
|
+
const contextWindow = nativeOpenAiContextWindow(slug, openaiContextCap);
|
|
1749
|
+
if (contextWindow === undefined) continue;
|
|
1750
|
+
const synthetic: CatalogModel = {
|
|
1751
|
+
provider: "openai",
|
|
1752
|
+
id: slug,
|
|
1753
|
+
owned_by: "openai",
|
|
1754
|
+
contextWindow,
|
|
1755
|
+
// Input limit, not the total window. These coincide for native GPT-5.6 today (the
|
|
1756
|
+
// advertised 922,000 window is already capped at its measured ceiling), but the two
|
|
1757
|
+
// stay separate fields because routed/API rows of the same family run a wider window.
|
|
1758
|
+
// Falls back to the window for slugs with no separate ceiling.
|
|
1759
|
+
maxInputTokens: Math.min(nativeOpenAiMaxInputTokens(slug, openaiContextCap) ?? contextWindow, contextWindow),
|
|
1760
|
+
inputModalities: nativeInputModalities(slug),
|
|
1761
|
+
reasoningEfforts: nativeReasoningEfforts(slug),
|
|
1762
|
+
...(nativeParallelToolCalls(slug) ? { parallelToolCalls: true } : {}),
|
|
1763
|
+
};
|
|
1764
|
+
const key = `openai/${slug}`;
|
|
1765
|
+
// Only inject when not already present from a routed provider (an API-key
|
|
1766
|
+
// "openai" provider could shadow the native one).
|
|
1767
|
+
if (!memberByKey.has(key)) memberByKey.set(key, synthetic);
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
// Enriched (registry-hydrated) provider clones — shared by combo member synthesis and
|
|
1771
|
+
// custom-model vision-sidecar inheritance so both see the same merged registry view.
|
|
1772
|
+
const enrichedByName = new Map(activeProviders.map(provider => [provider.name, provider.provider]));
|
|
1773
|
+
for (const id of listComboIds(config)) {
|
|
1774
|
+
const combo = getCombo(config, id);
|
|
1775
|
+
if (!combo) continue;
|
|
1776
|
+
const nativeContextWindow = combo.nativeAlias && combo.alias
|
|
1777
|
+
? nativeOpenAiContextWindow(combo.alias, nativeContextLimits(config))
|
|
1778
|
+
: undefined;
|
|
1779
|
+
const nativeAliasMaxInput = combo.nativeAlias && combo.alias
|
|
1780
|
+
? (combo.alias.startsWith("gpt-5.6-") || combo.alias.includes("daybreak")
|
|
1781
|
+
? NATIVE_GPT56_MAX_INPUT_TOKENS
|
|
1782
|
+
: nativeOpenAiMaxInputTokens(combo.alias) ?? nativeOpenAiContextWindow(combo.alias))
|
|
1783
|
+
: undefined;
|
|
1784
|
+
const nativeAliasFallback = combo.nativeAlias && combo.alias && nativeContextWindow !== undefined
|
|
1785
|
+
? {
|
|
1786
|
+
contextWindow: nativeContextWindow,
|
|
1787
|
+
...(nativeAliasMaxInput !== undefined ? { maxInputTokens: nativeAliasMaxInput } : {}),
|
|
1788
|
+
inputModalities: nativeInputModalities(combo.alias),
|
|
1789
|
+
reasoningEfforts: nativeReasoningEfforts(combo.alias),
|
|
1790
|
+
}
|
|
1791
|
+
: undefined;
|
|
1792
|
+
const members = combo.targets
|
|
1793
|
+
.map(target => resolveComboCatalogMember(
|
|
1794
|
+
target,
|
|
1795
|
+
memberByKey,
|
|
1796
|
+
enrichedByName,
|
|
1797
|
+
providerContextCap(config, target.provider),
|
|
1798
|
+
nativeAliasFallback,
|
|
1799
|
+
))
|
|
1800
|
+
.filter((member): member is CatalogModel => member !== undefined);
|
|
1801
|
+
const derived = deriveComboCatalogModel(id, combo, members);
|
|
1802
|
+
if (derived) {
|
|
1803
|
+
const nativeDefault = combo.nativeAlias && combo.alias
|
|
1804
|
+
? nativeDefaultReasoningEffort(combo.alias)
|
|
1805
|
+
: undefined;
|
|
1806
|
+
if (combo.defaultEffort === null
|
|
1807
|
+
&& nativeDefault
|
|
1808
|
+
&& derived.reasoningEfforts?.includes(nativeDefault)) {
|
|
1809
|
+
derived.defaultReasoningEffort = nativeDefault;
|
|
1810
|
+
}
|
|
1811
|
+
all.push(derived);
|
|
1812
|
+
}
|
|
1813
|
+
else warnUncataloguedComboOnce(id, combo, members, localOmissions);
|
|
1814
|
+
}
|
|
1815
|
+
replaceLastComboCatalogOmissions(localOmissions);
|
|
1816
|
+
all.sort((a, b) => (a.provider === b.provider ? a.id.localeCompare(b.id) : a.provider.localeCompare(b.provider)));
|
|
1817
|
+
// Provider-derived rows keyed by their Codex-facing slug: a custom override replaces the row
|
|
1818
|
+
// with the same slug below, so that row's provider capability metadata is the inheritance source.
|
|
1819
|
+
const replacedByRoutedSlug = new Map(all.map(model => [routedSlug(model.provider, model.id), model]));
|
|
1820
|
+
const customModels = (config.customModels ?? []).map(cm => {
|
|
1821
|
+
const rawProvider = config.providers[cm.provider];
|
|
1822
|
+
const effectiveProvider = enrichedByName.get(cm.provider) ?? rawProvider;
|
|
1823
|
+
// Registry routing backfills an omitted authMode on the built-in OpenAI provider to
|
|
1824
|
+
// forward. Keep the catalog projection on the same contract while still failing closed
|
|
1825
|
+
// for every explicit non-forward mode and every non-canonical endpoint.
|
|
1826
|
+
const providerForCanonicalCheck = rawProvider
|
|
1827
|
+
? withCanonicalOpenAiForwardAuthDefault(cm.provider, rawProvider)
|
|
1828
|
+
: undefined;
|
|
1829
|
+
const codexForwardNativeCapabilityAlias = cm.provider === OPENAI_CODEX_PROVIDER_ID
|
|
1830
|
+
&& providerForCanonicalCheck !== undefined
|
|
1831
|
+
&& isCanonicalOpenAiForwardProvider(providerForCanonicalCheck)
|
|
1832
|
+
&& isNativeOpenAiCapabilityAliasModel(cm.modelId);
|
|
1833
|
+
const customNativeLimits = {
|
|
1834
|
+
...nativeContextLimits(config),
|
|
1835
|
+
...(typeof cm.contextWindow === "number" && cm.contextWindow > 0
|
|
1836
|
+
? { modelWindows: { ...(nativeContextLimits(config).modelWindows ?? {}), [cm.modelId]: cm.contextWindow } }
|
|
1837
|
+
: {}),
|
|
1838
|
+
};
|
|
1839
|
+
const nativeAliasContextWindow = codexForwardNativeCapabilityAlias
|
|
1840
|
+
? nativeOpenAiContextWindow(cm.modelId, customNativeLimits)
|
|
1841
|
+
: undefined;
|
|
1842
|
+
const customContextWindow = cm.contextWindow
|
|
1843
|
+
? nativeAliasContextWindow !== undefined
|
|
1844
|
+
? nativeAliasContextWindow
|
|
1845
|
+
: cm.contextWindow
|
|
1846
|
+
: nativeAliasContextWindow;
|
|
1847
|
+
const nativeAliasMaxInputTokens = codexForwardNativeCapabilityAlias
|
|
1848
|
+
? nativeOpenAiMaxInputTokens(cm.modelId, customNativeLimits)
|
|
1849
|
+
: undefined;
|
|
1850
|
+
const customMaxInputTokens = nativeAliasMaxInputTokens !== undefined && customContextWindow !== undefined
|
|
1851
|
+
? Math.min(nativeAliasMaxInputTokens, customContextWindow)
|
|
1852
|
+
: nativeAliasMaxInputTokens;
|
|
1853
|
+
const nativeAliasDefaultEffort = codexForwardNativeCapabilityAlias
|
|
1854
|
+
? nativeDefaultReasoningEffort(cm.modelId)
|
|
1855
|
+
: undefined;
|
|
1856
|
+
const supportsReasoningSummaries = configuredReasoningSummarySupport(rawProvider, cm.modelId);
|
|
1857
|
+
const fastPolicy = effectiveProvider
|
|
1858
|
+
? fastPolicyForModel(effectiveProvider, cm.modelId, cm.provider)
|
|
1859
|
+
: undefined;
|
|
1860
|
+
const supportsServiceTier = fastPolicy
|
|
1861
|
+
? serviceTierSupportFromPolicy(fastPolicy)
|
|
1862
|
+
: undefined;
|
|
1863
|
+
const base: CatalogModel = {
|
|
1864
|
+
id: cm.modelId,
|
|
1865
|
+
provider: cm.provider,
|
|
1866
|
+
catalogKind: CODEX_CUSTOM_MODEL_CATALOG_KIND,
|
|
1867
|
+
// Display-only label: never feeds routing (customModels are keyed by routedSlug below).
|
|
1868
|
+
...(cm.displayName
|
|
1869
|
+
? { displayName: cm.displayName }
|
|
1870
|
+
: codexForwardNativeCapabilityAlias ? { displayName: "Daybreak Blue" } : {}),
|
|
1871
|
+
...(customContextWindow !== undefined ? { contextWindow: customContextWindow } : {}),
|
|
1872
|
+
...(customMaxInputTokens !== undefined ? { maxInputTokens: customMaxInputTokens } : {}),
|
|
1873
|
+
...(cm.inputModalities
|
|
1874
|
+
? { inputModalities: cm.inputModalities }
|
|
1875
|
+
: codexForwardNativeCapabilityAlias ? { inputModalities: nativeInputModalities(cm.modelId) } : {}),
|
|
1876
|
+
...(typeof supportsReasoningSummaries === "boolean" ? { supportsReasoningSummaries } : {}),
|
|
1877
|
+
// Native-alias defaults apply only where the custom row declares nothing: the explicit
|
|
1878
|
+
// spreads below must win (later in object order), so a stored `[]` stays empty and a
|
|
1879
|
+
// declared ladder is never replaced by the alias's native ladder.
|
|
1880
|
+
...(codexForwardNativeCapabilityAlias
|
|
1881
|
+
? {
|
|
1882
|
+
codexForwardNativeCapabilityAlias: true,
|
|
1883
|
+
parallelToolCalls: nativeParallelToolCalls(cm.modelId),
|
|
1884
|
+
...(Array.isArray(cm.reasoningEfforts)
|
|
1885
|
+
? {}
|
|
1886
|
+
: {
|
|
1887
|
+
reasoningEfforts: nativeReasoningEfforts(cm.modelId),
|
|
1888
|
+
...(nativeAliasDefaultEffort ? { defaultReasoningEffort: nativeAliasDefaultEffort } : {}),
|
|
1889
|
+
}),
|
|
1890
|
+
}
|
|
1891
|
+
: {}),
|
|
1892
|
+
// Explicit custom-row ladder wins over the inherited provider row below: the merge only
|
|
1893
|
+
// gap-fills, so a stored `[]` (explicit "no reasoning") or a declared ladder is kept
|
|
1894
|
+
// verbatim instead of being replaced by the replaced row's metadata.
|
|
1895
|
+
...(Array.isArray(cm.reasoningEfforts) ? { reasoningEfforts: [...cm.reasoningEfforts] } : {}),
|
|
1896
|
+
...(cm.defaultReasoningEffort ? { defaultReasoningEffort: cm.defaultReasoningEffort } : {}),
|
|
1897
|
+
...(typeof supportsServiceTier === "boolean" ? { supportsServiceTier } : {}),
|
|
1898
|
+
...(supportsServiceTier === true && fastPolicy?.fastTierDescription !== undefined
|
|
1899
|
+
? { fastTierDescription: fastPolicy.fastTierDescription }
|
|
1900
|
+
: {}),
|
|
1901
|
+
...(cm.codexToolMode !== undefined
|
|
1902
|
+
? { codexToolMode: cm.codexToolMode }
|
|
1903
|
+
: effectiveProvider?.codexToolMode !== undefined
|
|
1904
|
+
? { codexToolMode: effectiveProvider.codexToolMode }
|
|
1905
|
+
: {}),
|
|
1906
|
+
};
|
|
1907
|
+
// #962: the dedupe below drops the provider-derived row this custom row replaces. Inherit that
|
|
1908
|
+
// row's provider capability metadata (reasoning ladder, default effort, parallel tool calls,
|
|
1909
|
+
// context, ...) so the generated catalog keeps advertising what the router actually provides.
|
|
1910
|
+
// Explicit custom fields win by construction; this only fills gaps. Without it a
|
|
1911
|
+
// noReasoningModels model loses its empty ladder and the catalog synthesizes the generic one,
|
|
1912
|
+
// which Codex then rejects for spawn_agent with effort "none".
|
|
1913
|
+
const replaced = replacedByRoutedSlug.get(routedSlug(cm.provider, cm.modelId));
|
|
1914
|
+
// The final ladder is what the catalog will advertise; the inherited default only rides
|
|
1915
|
+
// along when it is actually a member — otherwise a provider default like "xhigh" would
|
|
1916
|
+
// re-apply onto a narrower custom ladder and override the fallback in applyReasoningLevels.
|
|
1917
|
+
const effectiveLadder = base.reasoningEfforts ?? replaced?.reasoningEfforts;
|
|
1918
|
+
const merged: CatalogModel = replaced ? {
|
|
1919
|
+
...base,
|
|
1920
|
+
...(base.contextWindow === undefined && replaced.contextWindow !== undefined ? { contextWindow: replaced.contextWindow } : {}),
|
|
1921
|
+
...(base.maxInputTokens === undefined && replaced.maxInputTokens !== undefined ? { maxInputTokens: replaced.maxInputTokens } : {}),
|
|
1922
|
+
...(base.inputModalities === undefined && replaced.inputModalities !== undefined ? { inputModalities: replaced.inputModalities } : {}),
|
|
1923
|
+
...(base.reasoningEfforts === undefined && replaced.reasoningEfforts !== undefined ? { reasoningEfforts: replaced.reasoningEfforts } : {}),
|
|
1924
|
+
...(base.defaultReasoningEffort === undefined && replaced.defaultReasoningEffort !== undefined
|
|
1925
|
+
&& Array.isArray(effectiveLadder) && effectiveLadder.includes(replaced.defaultReasoningEffort)
|
|
1926
|
+
? { defaultReasoningEffort: replaced.defaultReasoningEffort } : {}),
|
|
1927
|
+
...(base.parallelToolCalls === undefined && replaced.parallelToolCalls !== undefined ? { parallelToolCalls: replaced.parallelToolCalls } : {}),
|
|
1928
|
+
...(base.supportsVerbosity === undefined && replaced.supportsVerbosity !== undefined ? { supportsVerbosity: replaced.supportsVerbosity } : {}),
|
|
1929
|
+
...(base.supportsReasoningSummaries === undefined && replaced.supportsReasoningSummaries !== undefined ? { supportsReasoningSummaries: replaced.supportsReasoningSummaries } : {}),
|
|
1930
|
+
...(base.codexToolMode === undefined && replaced.codexToolMode !== undefined ? { codexToolMode: replaced.codexToolMode } : {}),
|
|
1931
|
+
...(base.capabilities === undefined && replaced.capabilities !== undefined ? { capabilities: replaced.capabilities } : {}),
|
|
1932
|
+
} : base;
|
|
1933
|
+
// Vision-sidecar coverage ONLY: if the custom model is in the enriched provider's
|
|
1934
|
+
// noVisionModels, advertise image input so the Codex app lets images reach the sidecar
|
|
1935
|
+
// (#349/#344). Deliberately NOT the full applyProviderConfigHints pass — custom rows are a
|
|
1936
|
+
// user override, so their explicit contextWindow / inputModalities / reasoning fields must be
|
|
1937
|
+
// preserved verbatim (the hint pass would cap context and overwrite modalities from registry).
|
|
1938
|
+
const enrichedProvider = enrichedByName.get(cm.provider) ?? rawProvider;
|
|
1939
|
+
if (enrichedProvider && modelInList(enrichedProvider.noVisionModels, merged.id)) {
|
|
1940
|
+
const current = merged.inputModalities ?? ["text"];
|
|
1941
|
+
if (!current.includes("image")) {
|
|
1942
|
+
return { ...merged, inputModalities: [...current, "image"] };
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
return merged;
|
|
1946
|
+
});
|
|
1947
|
+
// Custom rows override discovered rows that encode to the same Codex-facing slug.
|
|
1948
|
+
const customKeys = new Set(customModels.map(c => routedSlug(c.provider, c.id)));
|
|
1949
|
+
const deduped = all.filter(m => !customKeys.has(routedSlug(m.provider, m.id)));
|
|
1950
|
+
const providerModelOutcomes = providerResults.map(result => (
|
|
1951
|
+
result.outcome.provider === OPENAI_API_PROVIDER_ID
|
|
1952
|
+
&& capture.openAiApiPolicy.state === "captured"
|
|
1953
|
+
&& capture.openAiApiPolicy.models !== undefined
|
|
1954
|
+
? { provider: result.outcome.provider, state: "authoritative" as const }
|
|
1955
|
+
: result.outcome
|
|
1956
|
+
));
|
|
1957
|
+
return {
|
|
1958
|
+
models: [...deduped, ...customModels],
|
|
1959
|
+
comboOmissions: localOmissions,
|
|
1960
|
+
providerAuthOutcomes: localProviderAuthOutcomes,
|
|
1961
|
+
providerModelOutcomes,
|
|
1962
|
+
discoveryPolicySnapshots: capture.discoveryPolicySnapshots,
|
|
1963
|
+
};
|
|
1964
|
+
}
|
|
1965
|
+
|
|
1966
|
+
export function augmentRoutedModelsWithRegistryOpenAiApiRows(
|
|
1967
|
+
models: CatalogModel[],
|
|
1968
|
+
config: OcxConfig,
|
|
1969
|
+
): CatalogModel[] {
|
|
1970
|
+
const configured = config.providers[OPENAI_API_PROVIDER_ID];
|
|
1971
|
+
if (!configured || configured.disabled === true || !providerMatchesRegistryTransport(OPENAI_API_PROVIDER_ID, configured)) return models;
|
|
1972
|
+
return augmentRoutedModelsWithCapturedOpenAiApiRows(
|
|
1973
|
+
models,
|
|
1974
|
+
config,
|
|
1975
|
+
captureTrustedOpenAiApiPolicy(OPENAI_API_PROVIDER_ID, true),
|
|
1976
|
+
);
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1979
|
+
function augmentRoutedModelsWithCapturedOpenAiApiRows(
|
|
1980
|
+
models: CatalogModel[],
|
|
1981
|
+
config: OcxConfig,
|
|
1982
|
+
policy: CatalogTrustedOpenAiApiPolicySnapshot,
|
|
1983
|
+
): CatalogModel[] {
|
|
1984
|
+
if (policy.state !== "captured" || !policy.models) return models;
|
|
1985
|
+
const configured = config.providers[OPENAI_API_PROVIDER_ID];
|
|
1986
|
+
if (!configured || configured.disabled === true) return models;
|
|
1987
|
+
|
|
1988
|
+
const existingById = new Map(
|
|
1989
|
+
models.filter(model => model.provider === OPENAI_API_PROVIDER_ID).map(model => [model.id, model]),
|
|
1990
|
+
);
|
|
1991
|
+
const trustedRows = policy.models.map((id): CatalogModel => {
|
|
1992
|
+
const officialContext = policy.modelContextWindows?.[id];
|
|
1993
|
+
const officialMaxInput = policy.modelMaxInputTokens?.[id];
|
|
1994
|
+
const userContext = configured.modelContextWindows?.[id] ?? configured.contextWindow;
|
|
1995
|
+
const userMaxInput = configured.modelMaxInputTokens?.[id];
|
|
1996
|
+
const providerCap = providerContextCap(config, OPENAI_API_PROVIDER_ID);
|
|
1997
|
+
const contextWindow = typeof officialContext === "number"
|
|
1998
|
+
? Math.min(officialContext, userContext ?? officialContext, providerCap ?? officialContext)
|
|
1999
|
+
: undefined;
|
|
2000
|
+
const maxInputTokens = typeof officialMaxInput === "number"
|
|
2001
|
+
? Math.min(officialMaxInput, userMaxInput ?? officialMaxInput)
|
|
2002
|
+
: undefined;
|
|
2003
|
+
return {
|
|
2004
|
+
provider: OPENAI_API_PROVIDER_ID,
|
|
2005
|
+
id,
|
|
2006
|
+
owned_by: OPENAI_API_PROVIDER_ID,
|
|
2007
|
+
...(contextWindow ? { contextWindow } : {}),
|
|
2008
|
+
...(maxInputTokens ? { maxInputTokens } : {}),
|
|
2009
|
+
...(policy.modelInputModalities?.[id] ? { inputModalities: [...policy.modelInputModalities[id]!] } : {}),
|
|
2010
|
+
...(policy.modelReasoningEfforts?.[id] ? { reasoningEfforts: [...policy.modelReasoningEfforts[id]!] } : {}),
|
|
2011
|
+
};
|
|
2012
|
+
});
|
|
2013
|
+
|
|
2014
|
+
for (const trusted of trustedRows) {
|
|
2015
|
+
const live = existingById.get(trusted.id);
|
|
2016
|
+
if (!live) continue;
|
|
2017
|
+
const liveSignature = normalizedOpenAiApiSignature(live);
|
|
2018
|
+
const trustedSignature = normalizedOpenAiApiSignature(trusted);
|
|
2019
|
+
if (liveSignature === trustedSignature) continue;
|
|
2020
|
+
const warningKey = `${trusted.provider}/${trusted.id}\n${liveSignature}\n${trustedSignature}`;
|
|
2021
|
+
if (openAiApiCollisionWarnings.has(warningKey)) continue;
|
|
2022
|
+
openAiApiCollisionWarnings.add(warningKey);
|
|
2023
|
+
console.warn(`[opencodex] replacing conflicting live OpenAI API metadata for ${trusted.provider}/${trusted.id} with trusted registry metadata`);
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
return [
|
|
2027
|
+
...models.filter(model => model.provider !== OPENAI_API_PROVIDER_ID),
|
|
2028
|
+
...trustedRows,
|
|
2029
|
+
];
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
export function augmentRoutedModelsWithMetadata(
|
|
2033
|
+
models: CatalogModel[],
|
|
2034
|
+
providerNames: string[],
|
|
2035
|
+
providers?: Record<string, OcxProviderConfig>,
|
|
2036
|
+
caps?: Pick<OcxConfig, "providerContextCaps">,
|
|
2037
|
+
): CatalogModel[] {
|
|
2038
|
+
const out = [...models];
|
|
2039
|
+
const seen = new Set(out.map(m => `${m.provider}/${m.id}`));
|
|
2040
|
+
for (const provider of providerNames) {
|
|
2041
|
+
if (!JAWCODE_CATALOG_AUGMENT_PROVIDERS.has(provider)) continue;
|
|
2042
|
+
if (providers?.[provider]?.liveModels === false) continue;
|
|
2043
|
+
const jawcodeProvider = resolveMetadataProvider(provider);
|
|
2044
|
+
if (!jawcodeProvider) continue;
|
|
2045
|
+
for (const meta of listModelMetadata(jawcodeProvider)) {
|
|
2046
|
+
const key = `${provider}/${meta.id}`;
|
|
2047
|
+
if (seen.has(key)) continue;
|
|
2048
|
+
seen.add(key);
|
|
2049
|
+
const contextCap = caps ? providerContextCap(caps, provider) : undefined;
|
|
2050
|
+
const model: CatalogModel = {
|
|
2051
|
+
provider,
|
|
2052
|
+
id: meta.id,
|
|
2053
|
+
owned_by: provider,
|
|
2054
|
+
...(typeof meta.contextWindow === "number" && meta.contextWindow > 0 ? { contextWindow: meta.contextWindow } : {}),
|
|
2055
|
+
...(Array.isArray(meta.input) && meta.input.length > 0 ? { inputModalities: [...meta.input] } : {}),
|
|
2056
|
+
};
|
|
2057
|
+
out.push({
|
|
2058
|
+
...model,
|
|
2059
|
+
...(providers?.[provider] ? applyProviderConfigHints(provider, providers[provider], model, contextCap) : {}),
|
|
2060
|
+
});
|
|
2061
|
+
}
|
|
2062
|
+
}
|
|
2063
|
+
return out;
|
|
2064
|
+
}
|