| 1 | # Models and providers |
| 2 | |
| 3 | This document is the single owner for how Codewhale knows providers and models: |
| 4 | where bundled provider and model data lives, how model IDs are resolved, how |
| 5 | limits, capabilities and prices follow the resolved route, how signed |
| 6 | `registry.json` updates are verified and applied, and how to add a model or an |
| 7 | OpenAI-compatible provider without writing Rust code. |
| 8 | |
| 9 | Two invariants govern the stack: |
| 10 | |
| 11 | 1. **One data schema.** Provider metadata, model-ID naming rules (`ids` policy, |
| 12 | accepted globs, stripped prefixes, aliases, vendor wire slugs) and intrinsic |
| 13 | model facts live in data, compiled and validated once. Rust code is reserved |
| 14 | for wire protocols, authentication flows and billing rules that are genuine |
| 15 | runtime behavior. |
| 16 | 2. **One resolver.** `codewhale_config::route::resolve_model` |
| 17 | (`crates/config/src/route/resolver.rs`) is the sole function that turns |
| 18 | `(provider, raw_model_id, base_url)` into the logical model ID, the outbound |
| 19 | wire ID, the canonical `ModelId` and the matched catalog offering. Every |
| 20 | caller — the CLI (`codewhale model resolve`, `codewhale exec`), the TUI |
| 21 | (`/model` picker and shorthands), the Runtime API (`crates/app-server`), |
| 22 | subagent routing, speech and vision selection, context/output budgeting and |
| 23 | token pricing — consumes that result. |
| 24 | |
| 25 | Related documents own their specific surfaces rather than restating model |
| 26 | resolution: |
| 27 | |
| 28 | - [Provider routes](PROVIDERS.md) — per-provider credentials, base URLs, wire |
| 29 | dialects and reasoning-effort mappings. |
| 30 | - [Catalog refresh](CATALOG_REFRESH.md) — runtime Models.dev refresh, cache |
| 31 | layers and offline seed regeneration commands. |
| 32 | - [Signed cloud facts](CLOUD_FACTS.md) — Ed25519 envelope format, pinned key |
| 33 | roles, rollback floors and public relay transport. |
| 34 | - [Configuration](CONFIGURATION.md) — `config.toml` keys, environment variable |
| 35 | precedence and per-route `context_window` overrides. |
| 36 | |
| 37 | --- |
| 38 | |
| 39 | ## 1. Where bundled data lives today |
| 40 | |
| 41 | Until the Platform database cutover ([Section 6](#6-planned-not-shipped-yet)) |
| 42 | completes, the Engine repository's checked-in assets are the offline and |
| 43 | build-time authority: |
| 44 | |
| 45 | | Asset / script | Role | Compiled / checked by | |
| 46 | | --- | --- | --- | |
| 47 | | `crates/config/assets/provider_descriptors.json` | Single provider metadata file: `providers[]` (built-in `ProviderKind` routes), `descriptors[]` (data-only compatible hosts without a `ProviderKind` variant) and `legacy_tui` (`deepseek-cn` compatibility row). Every entry carries its `models` naming block alongside base URL, default model, auth env vars, secret slot, aliases and wire policy. | `crates/config/build.rs` → `crates/config/src/descriptors.rs`; `scripts/check-provider-registry.py` | |
| 48 | | `crates/config/assets/catalog_corrections.json` | Deliberate field patches (`providers`, `models`) applied to both offline and live Models.dev rows (`pricing_withheld`, `max_output`, capability holds), plus the `reviewed` supplement (`intrinsic` model facts, `thought_signatures_required`, `thinking_can_disable`, `transports`, `public_models`, `selections`, `search_models`, `route_model_sets`, `reference_prices` and `source_receipts`). | `crates/config/src/catalog/corrections.rs`, `crates/config/src/catalog/reviewed.rs` | |
| 49 | | `crates/config/assets/models_dev.bundled.json` | Generated offline Models.dev seed (`_meta.role`); reviewed facts stay in `catalog_corrections.json`. Never hand-edited; rendered deterministically from `scripts/catalog/models_dev_seed.toml`, `scripts/catalog/models_dev_seed.lock.json` and `catalog_corrections.json`. | `python3 scripts/catalog/catalog_models_dev.py seed render --check` and `seed age --max-days 30` | |
| 50 | | `crates/config/assets/responses_dialects.json` | Declarative OpenAI Responses API dialect profiles (`standard`, `codex`, and gateway profiles) and route bindings (`default_profile`, `custom_allowed_profiles`, `profiles`, `bindings`). | `crates/config/src/responses_dialect_data.rs`, `crates/config/build.rs` | |
| 51 | | `scripts/catalog/catalog_models_dev.py` | Secret-free maintainer CLI for upstream dry-run inspection (`refresh`), pinning (`seed lock`), deterministic rendering (`seed render`), staleness checks (`seed age`) and new-model discovery (`seed discover`). | `python3 -m unittest scripts/catalog/catalog_models_dev_test.py` | |
| 52 | |
| 53 | Downstream surfaces derive from these same files instead of keeping parallel |
| 54 | lists: |
| 55 | |
| 56 | - **Website (`web/`):** `web/scripts/derive-facts.mjs` (via |
| 57 | `web/scripts/facts-lib.mjs` and `web/lib/provider-descriptors.mjs`) generates |
| 58 | `web/lib/facts.generated.ts` and `web/data/agent-docs.generated.json` at |
| 59 | prebuild time; `web/scripts/check-facts.mjs` fails CI on drift. |
| 60 | - **Desktop and browser clients:** read providers, models, limits and readiness |
| 61 | from the Engine's Runtime API (`GET /v1/providers`, |
| 62 | `GET /v1/providers/{id}/models`) and keep no separate model table. |
| 63 | |
| 64 | --- |
| 65 | |
| 66 | ## 2. Per-provider model naming rules (`models` block) |
| 67 | |
| 68 | Every row in `providers[]`, `descriptors[]` and `legacy_tui` inside |
| 69 | `crates/config/assets/provider_descriptors.json` carries a `models` object: |
| 70 | |
| 71 | ```json |
| 72 | "models": { |
| 73 | "ids": "catalog", |
| 74 | "accept": [], |
| 75 | "strip_prefixes": ["models/"], |
| 76 | "aliases": { |
| 77 | "gemini-3.7-flash": "gemini-3.8-flash" |
| 78 | }, |
| 79 | "wire_slugs": { |
| 80 | "deepseek-v4-pro": "deepseek-ai/DeepSeek-V4-Pro" |
| 81 | } |
| 82 | } |
| 83 | ``` |
| 84 | |
| 85 | ### The four `models.ids` policies |
| 86 | |
| 87 | `ModelIdsPolicy` (`crates/config/src/descriptors.rs`) controls how a provider |
| 88 | treats model IDs after prefix stripping and alias lookup: |
| 89 | |
| 90 | | Policy | Behavior | Examples | |
| 91 | | --- | --- | --- | |
| 92 | | `catalog` | Resolves declared `aliases` and matches the provider's offerings (exact wire/canonical ID, unambiguous ASCII case-insensitive match, and — except on `zai` — unambiguous `/`-tail match for namespaced aggregators). Unknown IDs pass through unchanged with unknown catalog facts unless live `/models` discovery or `config.toml` supplies them. Default for compatible-host descriptors. | `google`, `anthropic`, `openrouter`, `orcarouter`, `together`, `deepinfra`, `fireworks`, `nvidia-nim`, `siliconflow`, `moonshot`, `zai`, `minimax`, `mistral`, `stepfun`, `opencode-zen`, all `descriptors[]` rows | |
| 93 | | `strict` | Accepts only declared `aliases`, known offerings for that provider, or IDs matching one of the `accept` globs (matched case-insensitively within `/` segments). Rejects any other ID with `RouteError::ForeignModelForDirectProvider`. | `deepseek`, `deepseek-anthropic` (`accept: ["deepseek*", "*/deepseek*"]`) | |
| 94 | | `roster` | Accepts only declared `aliases` and offerings on the provider's curated roster. Rejects unproven IDs — even when a custom `base_url` is set — with `RouteError::UnsupportedModelProtocol`. | `opencode-go` | |
| 95 | | `verbatim` | Never rewrites aliases or case-folds unknown strings after trimming and stripping `strip_prefixes`. Preserves the caller's exact wire spelling while still attaching catalog metadata when an exact offering exists. | `custom`, `codewhale`, `concentrate`, `openai`, `xai`, `meta`, `ollama`, `ollama-cloud`, `modelscope`, `qianfan`, `openmodel`, `atlascloud`, `telecomjs`, `edenai`, `zenmux`, `csdn`, `modelstudio-*` | |
| 96 | |
| 97 | ### Supporting fields in `models` |
| 98 | |
| 99 | - **`accept`** (`string[]`): segment-scoped `*` wildcard globs evaluated against |
| 100 | the lowercased candidate when `ids` is `"strict"`. Must be empty for all other |
| 101 | `ids` policies. |
| 102 | - **`strip_prefixes`** (`string[]`): case-insensitive prefixes stripped once |
| 103 | before lookup. Examples: `["models/"]` on `google` (so |
| 104 | `models/gemini-4-hydrogen` from Google's model list resolves identically to |
| 105 | `gemini-4-hydrogen`), `["opencode/", "opencode-zen/"]` on `opencode-zen`, |
| 106 | `["opencode-go/"]` on `opencode-go` and `["concentrate/"]` on `concentrate`. |
| 107 | - **`aliases`** (`Record<string, string>`): maps a normalized lookup key |
| 108 | (`normalize_model_lookup_key`: trimmed, ASCII-lowercased, with `_` and spaces |
| 109 | folded to `-`) to the provider's target model spelling. Examples: |
| 110 | `deepseek-chat` and `flash` → `deepseek-flash` on `deepseek`; `kimi` → |
| 111 | `kimi-k2.7-code` on `moonshot`; `mimo-v2.5-pro` → `mimo-v2.6-pro` on |
| 112 | `xiaomi-mimo`; `codestral-latest` → `mistral-code-latest` on `mistral`. |
| 113 | - **`wire_slugs`** (`Record<string, string>`): maps a normalized candidate ID to |
| 114 | the vendor wire slug expected on that host's API while preserving the logical |
| 115 | candidate name. Examples: `deepseek-v4-pro` → |
| 116 | `deepseek-ai/DeepSeek-V4-Pro` on `siliconflow`, `together`, `deepinfra`, |
| 117 | `huggingface`, `sglang` and `vllm`; |
| 118 | `accounts/fireworks/models/deepseek-v4-pro` on `fireworks`; |
| 119 | `deepseek/deepseek-v4-pro` on `openrouter`, `orcarouter` and `novita`; |
| 120 | `inkling` → `thinkingmachines/inkling` on `together`. |
| 121 | |
| 122 | ### Compile-time validation (`crates/config/build.rs`) |
| 123 | |
| 124 | `crates/config/build.rs` validates `provider_descriptors.json` at compile time |
| 125 | and fails the build if: |
| 126 | |
| 127 | - any JSON object contains duplicate keys (`UniqueKeys`); |
| 128 | - `models` is missing, contains an unknown field, or names an unknown `ids` |
| 129 | policy; |
| 130 | - `accept` is non-empty when `ids != "strict"`; |
| 131 | - any `aliases` or `wire_slugs` key is empty or not in normalized lookup form |
| 132 | (`key.trim().to_ascii_lowercase().replace(['_', ' '], "-") == key`); |
| 133 | - any `aliases` or `wire_slugs` target is empty or has leading/trailing |
| 134 | whitespace; |
| 135 | - a `verbatim` provider declares non-empty `aliases`; |
| 136 | - an alias target on a `strict` provider is neither a known offering nor matched |
| 137 | by `accept`, or an alias target on a `roster` provider is not on its roster. |
| 138 | |
| 139 | --- |
| 140 | |
| 141 | ## 3. One resolver, one selection chain, and route-derived facts |
| 142 | |
| 143 | ### `resolve_model` step order |
| 144 | |
| 145 | `codewhale_config::route::resolve_model(provider, raw, base_url)` |
| 146 | (`crates/config/src/route/resolver.rs`) returns |
| 147 | `Result<ResolvedModel, RouteError>`, where `ResolvedModel` carries `logical` |
| 148 | (the resolved provider-scoped model name), `wire_id` (the exact string sent on |
| 149 | the wire), `offering: Option<ProviderModelOffering>`, `model: Option<ModelId>` |
| 150 | (the canonical cross-provider catalog join, such as |
| 151 | `google/gemini-4-hydrogen`), `alias_matched` and `is_auto`. |
| 152 | |
| 153 | It executes these steps in order: |
| 154 | |
| 155 | 1. **Trim and check `auto`.** Leading and trailing whitespace is removed; empty |
| 156 | input returns `RouteError::EmptyModel`. An ASCII case-insensitive `"auto"` |
| 157 | returns `is_auto: true` (`logical = "auto"`, `wire_id = "auto"`). |
| 158 | 2. **Configured offerings and custom `base_url` verbatim rule.** The public |
| 159 | `resolve_model` passes no configured offerings; `RouteResolver` and the |
| 160 | config path `resolve_model_for_configured_route` pass the user-declared |
| 161 | custom models, and for every policy except `roster` an exact match there |
| 162 | wins immediately. Otherwise, when `base_url` is a |
| 163 | custom endpoint for that provider |
| 164 | (`provider_preserves_custom_base_url_model(provider, url)`), the trimmed ID |
| 165 | is returned verbatim (`logical` and `wire_id` equal the trimmed string, |
| 166 | attaching an exact-match offering if one exists). Custom-endpoint |
| 167 | pass-through is decided here and nowhere else. |
| 168 | 3. **Strip declared prefixes.** The first case-insensitively matching entry in |
| 169 | `models.strip_prefixes` is stripped and the remainder is trimmed; an empty |
| 170 | remainder (such as bare `"models/"`) returns `RouteError::EmptyModel`. If |
| 171 | `models.ids` is `verbatim`, resolution finishes here with exact-match |
| 172 | offering lookup. |
| 173 | 4. **Look up aliases.** The stripped string is normalized with |
| 174 | `normalize_model_lookup_key` and looked up in `models.aliases` (including |
| 175 | active verified registry overlay aliases when enabled). |
| 176 | 5. **Match offerings and `wire_slugs`.** `configured_offerings` is checked for |
| 177 | the candidate, then the provider's catalog offerings are searched (exact wire |
| 178 | or canonical ID first, then unambiguous ASCII case-insensitive match, then |
| 179 | unambiguous `/`-tail match on `catalog` providers other than `zai`). If |
| 180 | `models.wire_slugs` has an entry for the candidate, `wire_id` becomes the |
| 181 | mapped vendor slug, `logical` stays the candidate, and offering metadata is |
| 182 | joined on the slug. A `wire_slugs` hit returns here, before the `ids` policy |
| 183 | in step 6 runs. |
| 184 | 6. **Enforce `models.ids` and emit authoritative spelling.** `roster` without a |
| 185 | matched offering returns `RouteError::UnsupportedModelProtocol`; `strict` |
| 186 | without an alias match, offering match or `accept` glob match returns |
| 187 | `RouteError::ForeignModelForDirectProvider`. Otherwise, a matched offering |
| 188 | supplies its authoritative `wire_model_id` spelling (keeping an alias |
| 189 | target's case when it matches the offering case-insensitively), and an |
| 190 | unmatched `catalog` ID passes through as-is with `offering: None` and |
| 191 | `model: None`. |
| 192 | |
| 193 | ### Unified configured-model selection chain (`CW-8250`) |
| 194 | |
| 195 | Both `ConfigToml::resolve_runtime_options_with_secrets` |
| 196 | (`crates/config/src/config_resolve.rs`) and `Config::default_model` |
| 197 | (`crates/runtime/src/config.rs`) call one shared configured-model selection |
| 198 | chain in `crates/config`: |
| 199 | |
| 200 | 1. CLI `--model` override (`ModelSource::Cli`). |
| 201 | 2. Process environment override (`CODEWHALE_MODEL`, legacy `DEEPSEEK_MODEL`, or |
| 202 | the active provider's `<PROVIDER>_MODEL` when targeting that provider's |
| 203 | endpoint; `ModelSource::Env`). |
| 204 | 3. Provider table `[providers.<name>].model` (`ModelSource::ProviderConfig`). |
| 205 | 4. Root `default_text_model` when it names a declared custom model; otherwise, |
| 206 | only when `default_text_model` is unset, a legacy root `model` that names a |
| 207 | declared custom model. |
| 208 | 5. Moonshot Kimi Code default (`k3`) when using the Kimi Code endpoint or |
| 209 | imported Kimi token auth (`ModelSource::ProviderDefault`). |
| 210 | 6. Root `default_text_model`, guarded so a stale DeepSeek ID left behind after |
| 211 | switching providers is not forwarded to a foreign direct provider |
| 212 | (`ModelSource::RootDefaultTextModel`). |
| 213 | 7. Legacy root `model`, consulted only when `default_text_model` is unset, with |
| 214 | the same guard (`ModelSource::RootModel`). |
| 215 | 8. Route default (`ModelSource::ProviderDefault`): the verified `cloud_facts` |
| 216 | route default, then the ChatGPT/Codex OAuth preferred roster model, and |
| 217 | finally the descriptor's `default_model`. |
| 218 | |
| 219 | The chosen raw string is then passed through |
| 220 | `resolve_model_for_configured_route`, which checks declared custom models |
| 221 | before calling `resolve_model(provider, raw, Some(base_url))`. When `resolve_model` rejects an |
| 222 | ID (such as an unknown non-DeepSeek ID on `deepseek`, an unlisted ID on |
| 223 | `opencode-go`, or an empty string after prefix stripping), configuration loading, |
| 224 | `codewhale model resolve`, the TUI and the Runtime API all fail loud with the |
| 225 | same error naming the provider and model ID instead of silently sending the raw |
| 226 | string. |
| 227 | |
| 228 | ### How limits, capabilities and prices follow the resolved route (`CW-8251`, `CW-8252`) |
| 229 | |
| 230 | Downstream subsystems read the resolved route and catalog model facts rather |
| 231 | than re-normalizing strings or maintaining separate per-provider tables: |
| 232 | |
| 233 | - **Context windows, max output, thinking and payload mode** |
| 234 | (`crates/engine/src/provider_lake.rs`): derived from `resolve_model`'s matched |
| 235 | offering and canonical catalog model facts plus the provider's `wire_policy()` |
| 236 | (retaining only genuine route-protocol rules: explicit `config.toml` |
| 237 | `model_context_windows` / `context_window` overrides, Kimi Code safe floor, |
| 238 | `openai-codex` preview budget, Anthropic Messages 200K/64K unknown-model |
| 239 | floor, local `ollama` 8,192 fallback and 128,000 unknown fallback). |
| 240 | - **Unknown-output-ceiling route budgets** |
| 241 | (`crates/engine/src/route_budget.rs`): read descriptor and catalog metadata |
| 242 | instead of hard-coded provider allowlists; when a route publishes no output |
| 243 | ceiling, Codewhale omits artificial `max_tokens` clamps rather than inventing |
| 244 | a number. |
| 245 | - **Google Gemini thought signatures and thinking controls** |
| 246 | (`crates/engine/src/client/chat.rs`): resolve the model through |
| 247 | `resolve_model(ProviderKind::Google, model, None)` (applying `models/` prefix |
| 248 | stripping and aliases) and read `thought_signatures_required` and |
| 249 | `thinking_can_disable` from reviewed intrinsic catalog facts in |
| 250 | `catalog_corrections.json` rather than prefix-matching raw strings. |
| 251 | - **Pricing** (`crates/engine/src/pricing.rs`): resolves logical model IDs via |
| 252 | `resolve_model` so aliases and vendor wire slugs price against the same model |
| 253 | the request sends. Time-of-day and retirement-cutoff pricing rules (such as |
| 254 | DeepSeek windows and product-keyed subscription routes) remain explicit Rust |
| 255 | policy. |
| 256 | - **Interactive and auxiliary selectors** (`CW-8252`): TUI `/model` shorthands, |
| 257 | Runtime API config normalization (`crates/app-server/src/runtime_api.rs`), |
| 258 | subagent model selection, speech/vision model selection and |
| 259 | `route_preferences` all delegate directly to `resolve_model`. |
| 260 | |
| 261 | Catalog source precedence (from layer 0 bundled seed up through layer 20 live |
| 262 | provider `/models` rosters, layer 25 account rosters and layers 30–40 user |
| 263 | config overrides) is documented in [Catalog refresh](CATALOG_REFRESH.md#layers-lowest--highest-priority). |
| 264 | |
| 265 | --- |
| 266 | |
| 267 | ## 4. Signed `registry.json` (`codewhale.registry.v1`) updates |
| 268 | |
| 269 | When `[cloud_facts]` is enabled (`enabled = false` by default; overridden by |
| 270 | `CODEWHALE_CLOUD_FACTS=1|0` and hard-disabled by |
| 271 | `CODEWHALE_DISABLE_CLOUD_FACTS=1`), Codewhale can pull signed updates to the |
| 272 | models-and-providers registry without waiting for a binary release |
| 273 | (`crates/config/src/cloud_facts/registry.rs`, |
| 274 | `crates/cloud-facts/src/registry.rs`). |
| 275 | |
| 276 | ### Channel, endpoint and cache |
| 277 | |
| 278 | - **Envelope and channel:** UTF-8 JSON bytes of `registry.json` are signed inside |
| 279 | the standard Ed25519 `facts/v1` envelope (`channel: "registry"`, `envelope: 1`, |
| 280 | `alg: "ed25519"`, maximum payload `8 MiB`). See |
| 281 | [Signed cloud facts](CLOUD_FACTS.md) for the byte-level signature format and |
| 282 | pinned trust table (`crates/config/src/cloud_facts/keys.rs` and |
| 283 | `web/lib/cloud-facts/keys.ts`). |
| 284 | - **Source URL:** defaults to `https://codewhale.net/api/facts/v1/registry` (or |
| 285 | `CODEWHALE_CLOUD_FACTS_URL` when it contains `{channel}`), overridable with |
| 286 | `CODEWHALE_REGISTRY_URL` or a local signed envelope at |
| 287 | `CODEWHALE_REGISTRY_PATH`. Network fetches are suppressed automatically in CI. |
| 288 | - **Disk cache and rollback floor:** verified envelopes are written atomically to |
| 289 | `$CODEWHALE_HOME/facts/registry-cache.json`; the cache is reset when the |
| 290 | source changes. No bundled `registry.json` sets an initial floor: the floor is |
| 291 | the highest revision this client has cached. Startup |
| 292 | loads a verified cached copy without blocking on the network; background |
| 293 | refresh and `/model refresh` update it. `envelope.facts_version` must equal |
| 294 | `registry.revision` (`>= 1`), `envelope.published_at` must equal |
| 295 | `registry.generated_at` (RFC 3339 UTC ending in `Z`, not in the future beyond |
| 296 | clock tolerance), `sha256` must match, and `revision` must be greater than or |
| 297 | equal to the highest revision previously accepted. Failed or rejected pulls |
| 298 | preserve the active copy, and a rejected cache file is cleared while its |
| 299 | revision floor is kept. Disabling `[cloud_facts]`, setting |
| 300 | `CODEWHALE_DISABLE_CLOUD_FACTS=1`, expiry past `not_after` or an invalid facts |
| 301 | source drops the active registry overlay. |
| 302 | |
| 303 | ### Payload shape (`codewhale.registry.v1`) |
| 304 | |
| 305 | A verified `registry.json` document carries: |
| 306 | |
| 307 | - `schema`: `"codewhale.registry.v1"` |
| 308 | - `revision`: monotonic positive integer (`u64 >= 1`) |
| 309 | - `content_hash`: `"sha256:<64 lowercase hex>"` over canonical key-sorted |
| 310 | `{ dialects, engine_compat, models, offerings, providers }` |
| 311 | - `generated_at`: RFC 3339 UTC timestamp (`...Z`) |
| 312 | - `providers`: ordered built-in and `origin: "descriptor"` provider rows |
| 313 | - `models`: canonical model fact rows ordered by `id` |
| 314 | - `offerings`: provider × wire-ID offerings ordered by `(provider, id)` |
| 315 | - `dialects`: Responses dialect object matching `responses_dialects.json` |
| 316 | (without `schema_version`) |
| 317 | - `engine_compat`: lossless Engine round-trip projection |
| 318 | |
| 319 | When active in `crates/config/src/cloud_facts/overlay.rs`, verified pulled |
| 320 | models, offerings, built-in `models.aliases` / `wire_slugs` updates and admitted |
| 321 | pulled providers take precedence over bundled seed rows in `resolve_model`, |
| 322 | `RouteResolver`, catalog lookups and provider discovery, and the config-crate |
| 323 | resolvers revert to the seed when `overlay::clear()` runs. The Engine's |
| 324 | process-wide catalog snapshot (`BUNDLED_SNAPSHOT` in |
| 325 | `crates/engine/src/provider_lake.rs`) is still built once, on first use, so |
| 326 | the Engine picker and route catalog keep whatever registry was active then. |
| 327 | |
| 328 | ### Key roles: `automation` vs `founder` |
| 329 | |
| 330 | Pinned keys enforce strict separation between routine model updates and provider |
| 331 | admission: |
| 332 | |
| 333 | - **`automation` key (`KeyRole::Automation`):** accepted on the `registry` |
| 334 | channel only when the signed payload carries a valid, non-expired `not_after` |
| 335 | within the bounded automation window (`MAX_AUTOMATION_WINDOW_SECS`, at most 7 |
| 336 | days after `generated_at`). Its scope is enforced at verification |
| 337 | (`automation_provider_violation` and `automation_offering_violation` in |
| 338 | `crates/config/src/cloud_facts/registry.rs`): |
| 339 | - **May change:** `models` (canonical model facts), `offerings`, and a |
| 340 | built-in provider row's `models.aliases` and `models.wire_slugs`. On a |
| 341 | `strict` provider an alias or wire slug admits the mapped ID without an |
| 342 | `accept` match; the host, key and protocol stay the release's. |
| 343 | - **Must not change:** every `providers[]` row must name a bundled |
| 344 | `provider_descriptors.json` provider or descriptor and carry no |
| 345 | `admission.founder_signature` of any value. Any other provider field that is |
| 346 | present must equal the bundled value: the frozen trust fields (`kind`, |
| 347 | `base_url`, `wire_policy`, `wire`, `auth`, `api_key_env`, `env_vars`, |
| 348 | `secret_store_slot`), `default_model` (route and descriptor defaults), |
| 349 | `models.ids`, `models.accept`, `models.strip_prefixes`, and every other key |
| 350 | such as `label`, `catalog` (`api`/`npm` headers) or `corrections`. An |
| 351 | offering may not set `pricing_withheld`, carry `corrections`, or set a |
| 352 | provider default (`default` / `default_for_provider` at the top level, in |
| 353 | `catalog` or in `transport`). |
| 354 | Anything outside that scope rejects the whole envelope |
| 355 | (`FactsRejection::OutOfScope`). |
| 356 | - **`founder` key (`KeyRole::Founder`):** may sign everything above, newly |
| 357 | admitted OpenAI-compatible descriptor providers, and the naming-rule, default, |
| 358 | header, correction and `pricing_withheld` changes an automation key may not |
| 359 | make. Even a founder-signed row that names a built-in provider cannot change |
| 360 | its address, auth or wire protocol: `compile_registry` reads only its |
| 361 | `models`, `catalog`, `corrections` and `default_model`. |
| 362 | |
| 363 | ### Pulled provider admission, SSRF and credential isolation |
| 364 | |
| 365 | Pulled data can **never** delete a built-in or bundled provider or alter an |
| 366 | existing provider's `kind`, `base_url`, `auth`, `env_vars`, `secret_store_slot`, |
| 367 | `config_key` or `wire_policy`. A new provider row in a founder-signed |
| 368 | `registry.json` is admitted (`admit_registry` in |
| 369 | `crates/config/src/cloud_facts/registry.rs`) only when every check passes: |
| 370 | |
| 371 | 1. **Data-only OpenAI-compatible wire:** `kind` is absent and `wire_policy` |
| 372 | (and `wire`, when present) is `"openai-compatible"`. Pulled providers use |
| 373 | OpenAI-compatible Chat Completions only; Responses `dialects` remain compiled |
| 374 | wire behavior in `crates/config`. |
| 375 | 2. **Collision-free slug:** `id` (and every entry in `aliases`) matches |
| 376 | `^[a-z][a-z0-9-]{0,47}$` with no trailing `-`, and does not collide (after |
| 377 | normalizing `[_.]` to `-`) with any built-in or bundled provider ID, config |
| 378 | key, secret slot, catalog ID, `tui_wire_tag`, `legacy_tui`, selector/subagent |
| 379 | alias or earlier row in the same payload. |
| 380 | 3. **SSRF-safe public HTTPS endpoint:** `base_url` is at most 512 characters, |
| 381 | uses `https://` on a multi-label public domain name with the default port |
| 382 | (`443` / omitted) and no userinfo, query or fragment. IP literals, |
| 383 | single-label hosts, `localhost`, `*.localhost`, `*.local` and `*.internal` |
| 384 | are rejected at admission. That check is static: a public host name that |
| 385 | resolves to a private address is not caught when the row is admitted. |
| 386 | At request time, the Engine's model client (`http_client_builder_with_auth_mode` |
| 387 | in `crates/engine/src/client.rs`) builds a `custom` provider whose |
| 388 | `base_url` host equals the host of a provider in the active verified registry |
| 389 | on `codewhale_net::guard::public_address_reqwest_client_builder`: ambient |
| 390 | proxies are off and every connection resolves the host through |
| 391 | `PublicAddressResolver`, which refuses an answer containing a private, |
| 392 | loopback, link-local, cloud-metadata or other restricted address |
| 393 | (`is_restricted_ip`), including after a DNS rebind. This covers the chat, |
| 394 | HTTP/1.1 fallback and `/models` clients of that route. It does not cover a |
| 395 | saved custom provider whose registry row is no longer active (expired, |
| 396 | disabled or removed), which then uses the ordinary platform client like any |
| 397 | user-configured endpoint, or any request that does not go through the Engine |
| 398 | model client. |
| 399 | 4. **Strict credential isolation:** `auth.secret_slot` may only be `<id>`, and |
| 400 | `auth.env_vars` may only be `["<UPPER_ID>_API_KEY"]` (with `-` replaced by |
| 401 | `_`). That variable must not start with `CODEWHALE_` or `DEEPSEEK_`, match |
| 402 | any built-in provider's environment variable, or match a product or search |
| 403 | credential (`PRODUCT_RESERVED_ENV_VARS`: for example `TAVILY_API_KEY`, |
| 404 | `EXA_API_KEY`, `GEMINI_API_KEY`, `OLLAMA_API_KEY`, `ZHIPU_API_KEY`). A |
| 405 | pulled provider is inert until the user supplies a key in its own secret slot |
| 406 | or derived `<UPPER_ID>_API_KEY`; it never borrows another provider's |
| 407 | credentials. Account-scoped availability and billing overlays are never |
| 408 | accepted in public registry rows. |
| 409 | |
| 410 | A refused row is kept on the admitted registry with its reason |
| 411 | (`AdmittedRegistry::refused`), and every offering that names it is dropped. |
| 412 | |
| 413 | --- |
| 414 | |
| 415 | ## 5. How to add a model or a provider |
| 416 | |
| 417 | ### Add or update a model on an existing provider (data-only) |
| 418 | |
| 419 | No Rust edits are needed when adding a model, alias, prefix rule or capability |
| 420 | fact to an existing provider: |
| 421 | |
| 422 | 1. **Model facts and seed selection:** |
| 423 | - If the model is in upstream Models.dev, reference it in |
| 424 | `scripts/catalog/models_dev_seed.toml` (or run |
| 425 | `python3 scripts/catalog/catalog_models_dev.py seed discover --write`) and add any |
| 426 | needed holds or source-verified overrides in |
| 427 | `crates/config/assets/catalog_corrections.json`. |
| 428 | - Record reviewed intrinsic facts (`context_window`, `max_output`, |
| 429 | `reasoning`, `thought_signatures_required`, `thinking_can_disable`, |
| 430 | modalities) and their vendor doc URLs in `reviewed.intrinsic`, |
| 431 | `reviewed.public_models` and `reviewed.source_receipts` inside |
| 432 | `crates/config/assets/catalog_corrections.json`. |
| 433 | 2. **Naming rules:** add any shorthand, retired-ID redirect, `strip_prefixes` |
| 434 | entry or aggregator `wire_slugs` mapping to that provider's `models` block in |
| 435 | `crates/config/assets/provider_descriptors.json`. |
| 436 | 3. **Regenerate and verify:** |
| 437 | ```sh |
| 438 | python3 scripts/catalog/catalog_models_dev.py seed render |
| 439 | python3 -m unittest scripts/catalog/catalog_models_dev_test.py |
| 440 | python3 scripts/check-provider-registry.py |
| 441 | (cd web && node scripts/derive-facts.mjs && node scripts/check-facts.mjs) |
| 442 | ``` |
| 443 | Then run `codewhale-config` and `codewhale-runtime` unit tests (including |
| 444 | `config::model_resolution_golden`). |
| 445 | |
| 446 | ### Add a plain OpenAI-compatible provider (data-only) |
| 447 | |
| 448 | - **For your own machine or project (no repo changes):** add a |
| 449 | `[providers.<name>]` table in `~/.codewhale/config.toml` with |
| 450 | `kind = "openai-compatible"`, `base_url`, `api_key_env` and `model` (or paste |
| 451 | the base URL and key in `/provider`). See |
| 452 | [Configuration](CONFIGURATION.md#custom-openai-compatible-gateways). |
| 453 | - **As a bundled compatible host in Codewhale (JSON + docs, zero Rust):** add an |
| 454 | entry to `"descriptors"` in `crates/config/assets/provider_descriptors.json` |
| 455 | with `id`, `label`, `wire: "openai-compatible"`, `base_url`, `api_key_env`, |
| 456 | `default_model`, `discovery` (`"models_endpoint"`, `"public_models_endpoint"` |
| 457 | or `"none"`), optional `aliases` / `docs_url` / `credential_url` / `guidance`, |
| 458 | and a `models` block (`"ids": "catalog"`, `accept: []`, `strip_prefixes: []`, |
| 459 | `aliases: {}`, `wire_slugs: {}`). Document the host in `docs/PROVIDERS.md` |
| 460 | (and `docs/features.toml` when user-facing), regenerate website facts with |
| 461 | `(cd web && node scripts/derive-facts.mjs)` and run |
| 462 | `python3 scripts/check-provider-registry.py`. Do **not** add a `ProviderKind` |
| 463 | enum variant for a standard OpenAI-compatible host. |
| 464 | |
| 465 | ### When Rust changes are required |
| 466 | |
| 467 | Write Rust code only when a provider introduces a distinct wire protocol, |
| 468 | authentication mechanism (such as OAuth PKCE or device-code sign-in), or |
| 469 | provider-specific billing/time-of-day calculation — and key that behavior off a |
| 470 | descriptor or catalog field rather than scattering provider-name matches across |
| 471 | crates. |
| 472 | |
| 473 | --- |
| 474 | |
| 475 | ## 6. Planned, not shipped yet |
| 476 | |
| 477 | The Engine-side single resolver, unified configured-model chain, route-derived |
| 478 | facts and signed `registry.json` pull client are in tree. The cross-repository |
| 479 | cutover making the Platform database the sole upstream authoring home remains |
| 480 | **planned** (not deployed or active by default in this checkout): |
| 481 | |
| 482 | - **Platform registry database (`CW-8249`):** database registry tables on the |
| 483 | Codewhale Platform with reviewed admission and source receipts, importing the |
| 484 | Engine's catalog assets and exporting deterministic `registry.json` |
| 485 | (`codewhale.registry.v1`), while keeping account-scoped availability and |
| 486 | billing overlays outside the public export. |
| 487 | - **Signed publication and snapshot sync (`CW-8253`):** the website relay |
| 488 | (`web/app/api/facts/v1/[channel]/route.ts`, serving `registry`) and publisher (`web/scripts/facts-publish.mjs`) |
| 489 | that verify and serve the `registry` channel are in tree; activating the |
| 490 | public channel row, founder signing, and a scheduled sync job that updates the |
| 491 | Engine's bundled snapshot via pull request remain gated on signing-key custody |
| 492 | and deployment authorization. |
| 493 | - **Platform consumer migration:** migrating Platform API (`/v1/models`) and |
| 494 | web/account surfaces to read the same registry and deleting their separate |
| 495 | hand-edited model and capability lists. The Engine already reads account |
| 496 | `/v1/models` `codewhale.pricing` prices (`CW-8254`). |
| 497 | - **Engine asset cutover (`CW-8255`):** loading the bundled `registry.json` |
| 498 | export directly at Engine build/startup and retiring the split Engine seed |
| 499 | files (`models_dev.bundled.json`, `catalog_corrections.json`, |
| 500 | `scripts/catalog/catalog_models_dev.py`) and `.github/workflows/catalog-refresh.yml` |
| 501 | once Models.dev moves behind Platform intake. |
| 502 |