diff --git a/docs-site/src/content/docs/guides/claude-code.md b/docs-site/src/content/docs/guides/claude-code.md index 176723e7533..eb4e6d804ba 100644 --- a/docs-site/src/content/docs/guides/claude-code.md +++ b/docs-site/src/content/docs/guides/claude-code.md @@ -699,7 +699,7 @@ express fall back to the hashed alias. Model ids MAY contain `--` (resolution sp `--` only); native slugs containing `--` fall back to the hashed form. **Model resolution order:** `[1m]` marker stripped → readable alias decoded → Desktop hashed -alias decoded → `modelMap` exact match → date-stripped match (`-20250514` removed) → passthrough. +alias decoded → `modelMap` exact match → date-stripped match (`-20250514` removed) → explicit classifier route → `tierRoutes` → passthrough. @@ -873,7 +873,50 @@ entirely). The stub keeps tool call/result pairing intact. } ``` -Lookup order: discovery alias → exact id → id with date suffix stripped (`-20250514`) → passthrough. +Lookup order: discovery alias → exact id → id with date suffix stripped (`-20250514`) → explicit +classifier route (`classifierModel`, then `classifierFallbacks`) → tier route → passthrough. + +### Opt-in tier routing + +`claudeCode.tierRoutes` selects a route from the tier of a bare incoming Claude model ID. +Unlike `tierModels`, it runs in the proxy for requests already arriving through Claude ingress; +it does not change launcher defaults or Claude Code settings. + +```json +{ + "claudeCode": { + "tierRoutes": { + "opus": "openai/gpt-5.5", + "sonnet": "gemini/gemini-3-pro", + "haiku": "gemini/gemini-3-flash" + } + } +} +``` + +The optional keys are `opus`, `sonnet`, `haiku`, and `fable`. Targets use the same route selectors +as `modelMap`, including provider/model, combo, and policy routes. Configure only the tiers you +want to redirect. Unset tiers and an absent policy preserve existing behavior. + +Both current IDs (`claude-sonnet-5-5`) and older version-first IDs +(`claude-3-5-sonnet-20241022`) are recognized, as are `-latest` IDs and a trailing `[1m]` marker. +Discovery aliases and provider-qualified IDs such as `anthropic/claude-sonnet-5-5` retain their +explicit destination. Exact and date-stripped `modelMap` entries (including intercept bindings) +and explicit classifier routes take precedence. A selected target is resolved once by the +normal router, not fed back through tier routing. A tier redirected away from its incoming ID +uses the routed path rather than caller-credential native passthrough. Responses and Chat +Completions model selection is unchanged. + +Provider/account-qualified selectors, including their `--high` effort rows, retain their +explicit destination. A bare synthetic effort row is decoded by the existing ingress first; +its bare base can use tier routing while the requested effort is preserved. Future numeric +versions of the four known tiers are recognized; unknown tier names and nonstandard suffixes +pass through unchanged. + +Protocol preview resolves the same tier target without dispatching. `count_tokens` retains its +local estimate for combo/policy targets and does not select a combo member. Combo renames and +public-alias changes migrate saved tier routes in the same transaction as `modelMap` and +launcher `tierModels`, preserving unrelated routes. See [Desktop alias resolution](#desktop-alias-resolution) for the rejection policy. diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index a61f3c0d32b..88a98f0a0df 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -435,7 +435,7 @@ "claude-gateway-cache.test.ts": "claude-integration", "claude-inbound-cache-stabilize.test.ts": "claude-integration", "claude-inbound-token-footer.test.ts": "claude-integration", "claude-inbound-debug.test.ts": "claude-integration", - "claude-inbound.test.ts": "claude-integration", "claude-inbound-tool-reference.test.ts": "claude-integration", "claude-native-reasoning-continuity.test.ts": "claude-integration", "claude-native-reasoning-provenance.test.ts": "claude-integration", + "claude-inbound.test.ts": "claude-integration", "claude-tier-routing.test.ts": "claude-integration", "claude-inbound-tool-reference.test.ts": "claude-integration", "claude-native-reasoning-continuity.test.ts": "claude-integration", "claude-native-reasoning-provenance.test.ts": "claude-integration", "claude-output-schema-strict.test.ts": "claude-integration", "claude-intercept-integration.test.ts": "server", "claude-intercept-local-ca.test.ts": "claude-integration", diff --git a/src/claude/inbound-model-options.ts b/src/claude/inbound-model-options.ts index 7176e0302d1..58bc20f787f 100644 --- a/src/claude/inbound-model-options.ts +++ b/src/claude/inbound-model-options.ts @@ -36,7 +36,7 @@ function configuredClassifierRoute(cc?: OcxClaudeCodeConfig): string | undefined return undefined; } -/** Alias first, then modelMap: exact id, then date-suffix-stripped (`-\d{8}$`), then classifier affinity/config, else passthrough. */ +/** Aliases, exact/date-stripped modelMap, explicit classifier route, tier route, then passthrough. */ export function resolveInboundModel(model: string, cc?: OcxClaudeCodeConfig): string { // Defensive: Desktop/CLI strip the [1m] context-variant marker client-side, but a // leaking build must not break alias decode (devlog 138 — the 1M signal is the @@ -73,6 +73,11 @@ export function resolveInboundModel(model: string, cc?: OcxClaudeCodeConfig): st const configured = configuredClassifierRoute(cc); if (configured) return configured; } + // Only bare native tier ids participate. Qualified routes and aliases select a destination. + const tierMatch = /^claude-(?:(opus|sonnet|haiku|fable)(?:-\d+(?:[.-]\d+)*|-latest)?|\d+(?:[.-]\d+)*-(opus|sonnet|haiku|fable)(?:-\d{8}|-latest)?)$/.exec(model); + const tier = (tierMatch?.[1] ?? tierMatch?.[2]) as keyof NonNullable | undefined; + const target = tier ? cc?.tierRoutes?.[tier] : undefined; + if (typeof target === "string" && target.length > 0 && !/\s/.test(target)) return target; return model; } diff --git a/src/config/salvage.ts b/src/config/salvage.ts index 154283dc94b..6cafbdade52 100644 --- a/src/config/salvage.ts +++ b/src/config/salvage.ts @@ -31,6 +31,7 @@ const SALVAGEABLE_CONFIG_SECTIONS = ["routingProfiles", "combos"] as const; /** Optional nested fields that can be dropped whole without changing the rest of the document. */ const SALVAGEABLE_OPTIONAL_FIELDS: ReadonlyArray = [ ["claudeCode", "desktopProfile"], + ["claudeCode", "tierRoutes"], ["claudeCode", "appendOnlyToolLoadingModels"], ]; diff --git a/src/config/schema/config-schema.ts b/src/config/schema/config-schema.ts index 0565f9efc35..57cc77c108e 100644 --- a/src/config/schema/config-schema.ts +++ b/src/config/schema/config-schema.ts @@ -420,7 +420,15 @@ export const configSchema = z.object({ if (claudeCode !== undefined && (!claudeCode || typeof claudeCode !== "object" || Array.isArray(claudeCode))) { ctx.addIssue({ code: "custom", path: ["claudeCode"], message: "claudeCode must be an object" }); } else if (claudeCode) { - const claude = claudeCode as { desktopProfile?: unknown; desktopMode?: unknown; intercept?: unknown; appendOnlyToolLoadingModels?: unknown }; + const claude = claudeCode as { desktopProfile?: unknown; desktopMode?: unknown; intercept?: unknown; tierRoutes?: unknown; appendOnlyToolLoadingModels?: unknown }; + if (claude.tierRoutes !== undefined) { + const route = z.string().min(1).regex(/^\S+$/).optional(); + const parsed = z.object({ opus: route, sonnet: route, haiku: route, fable: route }).strict().safeParse(claude.tierRoutes); + if (!parsed.success) ctx.addIssue({ + code: "custom", path: ["claudeCode", "tierRoutes"], + message: "tierRoutes must contain only opus, sonnet, haiku or fable with non-empty routes without whitespace", + }); + } if (claude.appendOnlyToolLoadingModels !== undefined && !isAppendOnlyToolLoadingModels(claude.appendOnlyToolLoadingModels)) { ctx.addIssue({ code: "custom", path: ["claudeCode", "appendOnlyToolLoadingModels"], message: "appendOnlyToolLoadingModels must be up to 128 provider/model selectors (max 512 characters each), optionally ending in a single wildcard" }); } diff --git a/src/server/management/combo-routes.ts b/src/server/management/combo-routes.ts index 9336019b4e8..0f149603b8b 100644 --- a/src/server/management/combo-routes.ts +++ b/src/server/management/combo-routes.ts @@ -491,10 +491,12 @@ export async function handleComboRoutes(ctx: ManagementContext): Promise [tier, migrateAgentReference(model)]), - ); + for (const field of ["tierModels", "tierRoutes"] as const) { + if (claudeCode[field]) { + claudeCode[field] = Object.fromEntries( + Object.entries(claudeCode[field]).map(([tier, model]) => [tier, migrateAgentReference(model)]), + ); + } } if (claudeCode.modelMap) { claudeCode.modelMap = Object.fromEntries( diff --git a/src/types/config.ts b/src/types/config.ts index 30da5d1a18a..c3985853ad3 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -94,6 +94,8 @@ export interface OcxClaudeCodeConfig { smallFastModel?: string; /** Inbound model id remaps: exact id first, then date-stripped (`-\d{8}$`). */ modelMap?: Record; + /** Opt-in routes for bare Claude model tiers, after modelMap and explicit classifier routes. */ + tierRoutes?: { opus?: string; sonnet?: string; haiku?: string; fable?: string }; /** * Explicit classifier model for Claude Code Auto Mode safety checks (e.g. "RelayA/claude-opus-5"). * When unset, bare classifier requests check modelMap, then same-provider affinity from diff --git a/structure/INDEX.md b/structure/INDEX.md index 909e73fc0df..334f33e66dd 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -66,6 +66,7 @@ The wire surfaces a client actually talks to. | [`data-planes/search.md`](data-planes/search.md) | Hosted search relay and exact account selectors. | | [`data-planes/inbound-compat.md`](data-planes/inbound-compat.md) | Chat Completions inbound, Anthropic-shaped clients, and JSON-upstream streaming clients. | | [`data-planes/claude-tool-loading.md`](data-planes/claude-tool-loading.md) | Physical-adapter tool-loading projection, preserved catalogs, fallback exclusions and opt-in prerequisites. | +| [`data-planes/claude-tier-routing.md`](data-planes/claude-tier-routing.md) | Opt-in claudeCode.tierRoutes resolution on Claude ingress, precedence against modelMap and classifier routes, preview and count_tokens. | | [`data-planes/chat-reasoning-details.md`](data-planes/chat-reasoning-details.md) | The reasoning_details carrier that lets Chat Completions clients round-trip signed Anthropic thinking across tool steps (#7429). | | [`data-planes/protocol-paths.md`](data-planes/protocol-paths.md) | Shared protocol vocabulary, declared feature dispositions, the ingress-by-upstream baseline, plan/trace shapes, and protocol settings. | | [`fallback-policy.md`](fallback-policy.md) | OCX-11 fallback off: what is a model or provider fallback (and what intra-pool rotation is not), scope precedence, the guarded hop sites, the fallback_refused and home_unreachable contracts, and the ocx.fallback/1 state. | @@ -221,7 +222,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/chat/` | [`runtime.md`](runtime.md)
[`transports/byte-accounting.md`](transports/byte-accounting.md)
[`transports/inventory.md`](transports/inventory.md)
[`data-planes/inbound-compat.md`](data-planes/inbound-compat.md)
[`providers-and-adapters.md`](providers-and-adapters.md)
[`providers/chat-compat.md`](providers/chat-compat.md) | | `src/chat/reasoning-details.ts` | [`data-planes/chat-reasoning-details.md`](data-planes/chat-reasoning-details.md) | | `src/chatgpt/` | [`clients/chatgpt-desktop.md`](clients/chatgpt-desktop.md) | -| `src/claude/` | [`runtime.md`](runtime.md)
[`data-planes/claude-tool-loading.md`](data-planes/claude-tool-loading.md)
[`providers/anthropic-progress.md`](providers/anthropic-progress.md)
[`clients/claude-desktop.md`](clients/claude-desktop.md)
[`clients/claude-desktop-config-reads.md`](clients/claude-desktop-config-reads.md) | +| `src/claude/` | [`runtime.md`](runtime.md)
[`data-planes/claude-tool-loading.md`](data-planes/claude-tool-loading.md)
[`data-planes/claude-tier-routing.md`](data-planes/claude-tier-routing.md)
[`providers/anthropic-progress.md`](providers/anthropic-progress.md)
[`clients/claude-desktop.md`](clients/claude-desktop.md)
[`clients/claude-desktop-config-reads.md`](clients/claude-desktop-config-reads.md) | | `src/cli.ts` | [`runtime.md`](runtime.md)
[`ops/docs-and-release.md`](ops/docs-and-release.md) | | `src/cli/` | [`runtime.md`](runtime.md)
[`config.md`](config.md)
[`remote-messaging.md`](remote-messaging.md)
[`local-messaging.md`](local-messaging.md)
[`cli-management.md`](cli-management.md)
[`provider-completion-diagnostic.md`](provider-completion-diagnostic.md)
[`fallback-policy.md`](fallback-policy.md)
[`clients/export-model-names.md`](clients/export-model-names.md)
[`clients/integrations.md`](clients/integrations.md)
[`clients/codex-desktop.md`](clients/codex-desktop.md)
[`clients/chatgpt-desktop.md`](clients/chatgpt-desktop.md)
[`clients/claude-desktop.md`](clients/claude-desktop.md)
[`clients/hermes.md`](clients/hermes.md)
[`ops/docs-and-release.md`](ops/docs-and-release.md) | | `src/cli/account-preservation.ts` | [`providers/openai-signed-in-preservation.md`](providers/openai-signed-in-preservation.md) | @@ -323,7 +324,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/oauth/meta-muse.ts` | [`providers/meta-muse.md`](providers/meta-muse.md) | | `src/oauth/workbuddy.ts` | [`providers/workbuddy.md`](providers/workbuddy.md) | | `src/plugins/` | [`ops/plugins.md`](ops/plugins.md) | -| `src/protocols/` | [`data-planes/protocol-paths.md`](data-planes/protocol-paths.md) | +| `src/protocols/` | [`data-planes/claude-tier-routing.md`](data-planes/claude-tier-routing.md)
[`data-planes/protocol-paths.md`](data-planes/protocol-paths.md) | | `src/providers/` | [`runtime.md`](runtime.md)
[`subagents.md`](subagents.md)
[`transports/inventory.md`](transports/inventory.md)
[`providers-and-adapters.md`](providers-and-adapters.md)
[`providers/anthropic-account-pool.md`](providers/anthropic-account-pool.md)
[`providers/xai-grok.md`](providers/xai-grok.md) | | `src/providers/account-quota-disk.ts` | [`quota-snapshots.md`](quota-snapshots.md) | | `src/providers/anthropic-billing-ownership.ts` | [`providers/anthropic-key-billing.md`](providers/anthropic-key-billing.md) | @@ -354,7 +355,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/router.ts` | [`runtime.md`](runtime.md) | | `src/routing/` | [`catalog.md`](catalog.md)
[`fallback-policy.md`](fallback-policy.md) | | `src/routing/history/` | [`dashboard-and-usage.md`](dashboard-and-usage.md) | -| `src/server/` | [`transports/timeouts.md`](transports/timeouts.md)
[`providers/generic-account-pool.md`](providers/generic-account-pool.md)
[`runtime.md`](runtime.md)
[`codex-prompts.md`](codex-prompts.md)
[`catalog.md`](catalog.md)
[`subagents.md`](subagents.md)
[`transports/byte-accounting.md`](transports/byte-accounting.md)
[`transports/responses.md`](transports/responses.md)
[`transports/native-reasoning-retention.md`](transports/native-reasoning-retention.md)
[`transports/responses-wire-shapes.md`](transports/responses-wire-shapes.md)
[`transports/responses-failover.md`](transports/responses-failover.md)
[`transports/responses-combo-boundaries.md`](transports/responses-combo-boundaries.md)
[`transports/policy-fallback.md`](transports/policy-fallback.md)
[`transports/streaming-health.md`](transports/streaming-health.md)
[`transports/inventory.md`](transports/inventory.md)
[`data-planes/images.md`](data-planes/images.md)
[`data-planes/inbound-compat.md`](data-planes/inbound-compat.md)
[`providers/anthropic-progress.md`](providers/anthropic-progress.md)
[`providers-and-adapters.md`](providers-and-adapters.md)
[`providers/jev-decision.md`](providers/jev-decision.md)
[`providers/xai-grok.md`](providers/xai-grok.md)
[`adapters/registry.md`](adapters/registry.md)
[`gui-and-management-api.md`](gui-and-management-api.md)
[`provider-completion-diagnostic.md`](provider-completion-diagnostic.md)
[`dashboard-and-usage.md`](dashboard-and-usage.md)
[`fallback-policy.md`](fallback-policy.md)
[`clients/claude-desktop.md`](clients/claude-desktop.md)
[`clients/hermes.md`](clients/hermes.md)
[`ops/service-and-sidecars.md`](ops/service-and-sidecars.md) | +| `src/server/` | [`transports/timeouts.md`](transports/timeouts.md)
[`providers/generic-account-pool.md`](providers/generic-account-pool.md)
[`runtime.md`](runtime.md)
[`codex-prompts.md`](codex-prompts.md)
[`catalog.md`](catalog.md)
[`subagents.md`](subagents.md)
[`transports/byte-accounting.md`](transports/byte-accounting.md)
[`transports/responses.md`](transports/responses.md)
[`transports/native-reasoning-retention.md`](transports/native-reasoning-retention.md)
[`transports/responses-wire-shapes.md`](transports/responses-wire-shapes.md)
[`transports/responses-failover.md`](transports/responses-failover.md)
[`transports/responses-combo-boundaries.md`](transports/responses-combo-boundaries.md)
[`transports/policy-fallback.md`](transports/policy-fallback.md)
[`transports/streaming-health.md`](transports/streaming-health.md)
[`transports/inventory.md`](transports/inventory.md)
[`data-planes/images.md`](data-planes/images.md)
[`data-planes/inbound-compat.md`](data-planes/inbound-compat.md)
[`data-planes/claude-tier-routing.md`](data-planes/claude-tier-routing.md)
[`providers/anthropic-progress.md`](providers/anthropic-progress.md)
[`providers-and-adapters.md`](providers-and-adapters.md)
[`providers/jev-decision.md`](providers/jev-decision.md)
[`providers/xai-grok.md`](providers/xai-grok.md)
[`adapters/registry.md`](adapters/registry.md)
[`gui-and-management-api.md`](gui-and-management-api.md)
[`provider-completion-diagnostic.md`](provider-completion-diagnostic.md)
[`dashboard-and-usage.md`](dashboard-and-usage.md)
[`fallback-policy.md`](fallback-policy.md)
[`clients/claude-desktop.md`](clients/claude-desktop.md)
[`clients/hermes.md`](clients/hermes.md)
[`ops/service-and-sidecars.md`](ops/service-and-sidecars.md) | | `src/server/advisor-admission-scope.ts` | [`advisor.md`](advisor.md) | | `src/server/auth-cors.ts` | [`transports/response-turn-membership.md`](transports/response-turn-membership.md) | | `src/server/gui-pair-delivery.ts` | [`remote-link.md`](remote-link.md) | diff --git a/structure/config.md b/structure/config.md index 5b3301556a4..0baf64bc04f 100644 --- a/structure/config.md +++ b/structure/config.md @@ -1,5 +1,5 @@ # Config Surface -See [local timeout policy and OpenCode export](transports/timeouts.md). Pasted GCP JSON persists only as `gcp-sa:` references in one pool transaction in `src/providers/api-keys.ts`; post-commit deletion follows [Vertex credential markers](providers/google.md#vertex-credential-markers). +See [local timeout policy and OpenCode export](transports/timeouts.md). Pasted GCP JSON persists only as `gcp-sa:` references in one pool transaction in `src/providers/api-keys.ts`; post-commit deletion follows [Vertex credential markers](providers/google.md#vertex-credential-markers). `src/types/config.ts` declares optional `claudeCode.tierRoutes`; `src/config/schema/config-schema.ts` validates sparse opus/sonnet/haiku/fable route strings. Its ingress-only precedence is defined in [Claude ingress tier routing](data-planes/claude-tier-routing.md). Invalid hand edits drop only the policy through normal schema salvage, preserving unrelated configuration. `src/server/management/combo-routes.ts` migrates saved `tierRoutes` alongside `tierModels` and `modelMap` during combo renames and public-alias changes, within the existing atomic configuration transaction. `src/config/schema/leaf-validators.ts` accepts only boolean `apiKeys[].allowMeteredComboTargets`; malformed entries are dropped rather than promoted. `src/types/config.ts` and combo validation define optional boolean target `metered`, normalized false when omitted, and optional per-combo `allowMeteredTargets` (default false, literal boolean validation shared by config schema and management API). Explicit consent is required under the [combo runtime contract](runtime.md#request-local-target-compatibility). Model-price overrides follow the [pricing contract](pricing.md). Quota activation reuses the existing next-reset fields without adding a polling configuration key. See the [quota activation contract](providers/openai-tiers.md#public-provider-contract). `src/types/config.ts` defines `anthropicAccountPool.routes` as ordered model rules. `src/oauth/anthropic-model-routes.ts` validates bounded names, full case-sensitive globs and stored account IDs; `src/config/diagnostics.ts` rejects malformed candidate writes. Load retains a malformed hand edit so unrelated providers survive, while the enabled Anthropic selector refuses it locally before dispatch. Saved rules remain inert when the pool is disabled; affinity is process-local. Request logs use only the rule’s 1-based `route:#` position, never its configured name. `src/cli/hub-disable.ts` removes interdependent hub/loopback/role/hostname settings through `mutatePersistedConfig` and `validateConfigCandidate` in one commit. Top-level deletion intent uses `src/config/rebase-provenance.ts` and authoritative disk provenance in `src/config/live-reconcile.ts` to preserve removed hub bindings through later live saves, `src/config/live-topology.ts` keeps an independent active-topology baseline and merges desired next-start settings into a separate persistence projection, retaining actual socket identity and live hub/client topology during guarded saves and OAuth disk adoption. Client connections and runtimeRole remain one topology unit through connect/disconnect, including fresh disk-only connections. Disk additions/value updates and deletions all survive repeated saves without changing active topology. `src/config/api-key-reconcile.ts` merges key rows by stable ID under the existing save lock; either side's revocation defeats stale edits while disjoint names and rotations merge; unchanged live key membership/order adopts persisted ordering. `tests/config/hub-disable-live-save.test.ts` exercises disable followed by live key creation, rename, rotation, unrelated settings and repeated saves. Saved API keys have no immutable enrollment marker; explicit exact-ID revocation preserves all unselected keys. The WorkBuddy AI account row pins its adapter and origin under the [WorkBuddy contract](providers/workbuddy.md). JEV `decisionQuotaSignals` and partial `decisionQuotaTiers` use the shared validator and sparse preserve/clear/strategy-switch contract in [loaded advisory quota](providers/jev-decision.md#loaded-advisory-quota); the opt-in JEV `sessionPin` follows the same contract under [session pin](providers/jev-decision.md#session-pin). Native reasoning retention follows [its optional configuration contract](transports/native-reasoning-retention.md#configuration-and-management). Native function-result injection follows [the separate opt-in control contract](transports/streaming-health.md#experimental-native-function-result-injection); this surface does not infer upstream support or alter its defaults. diff --git a/structure/data-planes/claude-tier-routing.md b/structure/data-planes/claude-tier-routing.md new file mode 100644 index 00000000000..d6eecf0b067 --- /dev/null +++ b/structure/data-planes/claude-tier-routing.md @@ -0,0 +1,6 @@ +# Claude Ingress Tier Routing + +`src/claude/inbound-model-options.ts` resolves optional `claudeCode.tierRoutes` after discovery aliases, exact/date-stripped `modelMap` (including intercept bindings), and explicit classifier routes. Only bare current or historical Claude tier IDs participate. Unset tiers and qualified selectors retain existing behavior. +Targets enter the normal router once. The same resolver prevents caller native passthrough when a tier rewrites the ID. Launch `tierModels` and non-Claude ingresses are independent. Provider/account-qualified effort rows retain their destination; existing ingress parsing removes a bare synthetic effort suffix before tier resolution and preserves the effort. Future numeric versions of known tiers match; unknown families and nonstandard suffixes pass through. `src/protocols/plan-snapshot.ts` previews the selected target without dispatch or combo selection. `src/server/messages-native.ts` leaves combo/policy `count_tokens` on its local estimate without advancing selection. `tests/claude-integration/claude-tier-routing.test.ts` covers these boundaries. + +Schema validation, salvage and combo-rename migration of the saved policy are owned by [Config Surface](../config.md). diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index 0cc92f63148..71034837dd7 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -572,7 +572,7 @@ Pairing-grant source limiting applies only to invalid guesses from an allowed br ## Durable provider PATCH -Provider editor snapshots and management writes validate provider-wide `inputModalities` through `providerManagementConfigError` in `src/server/auth-cors.ts`, sharing the [config modality contract](config.md#explicit-per-model-capability-declarations). Malformed declarations are refused before persistence or catalog refresh; the field remains editor-owned rather than a credential or derived DTO field. `PUT /api/combos` shares this transaction for combo changes, rename references, disabled selectors and request-only Vision Sidecar enrollment; see `tests/routing/combo-vision-enrollment.test.ts`. +Provider editor snapshots and management writes validate provider-wide `inputModalities` through `providerManagementConfigError` in `src/server/auth-cors.ts`, sharing the [config modality contract](config.md#explicit-per-model-capability-declarations). Malformed declarations are refused before persistence or catalog refresh; the field remains editor-owned rather than a credential or derived DTO field. `PUT /api/combos` shares this transaction for combo changes, rename references, disabled selectors and request-only Vision Sidecar enrollment; see `tests/routing/combo-vision-enrollment.test.ts`. `src/server/management/combo-routes.ts` includes sparse Claude ingress `tierRoutes` in the same reference migration as launcher `tierModels` and `modelMap`; canonical and public-alias references follow the rename while unrelated/native selectors retain their meaning. `tests/routing/combo-management-api.test.ts` covers in-memory and persisted tier-route migration. `src/server/management/provider-routes.ts` commits every provider PATCH variant through `src/server/management/provider-patch-transaction.ts`, including standalone default-provider diff --git a/structure/manifest.json b/structure/manifest.json index 9fa23803f1e..7d37649ed90 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -496,6 +496,13 @@ "scope": "Physical-adapter tool-loading projection, preserved catalogs, fallback exclusions and opt-in prerequisites.", "documents": ["src/claude/", "src/server/responses/"] }, + { + "path": "data-planes/claude-tier-routing.md", + "tier": 3, + "title": "Claude Ingress Tier Routing", + "scope": "Opt-in claudeCode.tierRoutes resolution on Claude ingress, precedence against modelMap and classifier routes, preview and count_tokens.", + "documents": ["src/claude/", "src/protocols/", "src/server/"] + }, { "path": "data-planes/chat-reasoning-details.md", "tier": 3, diff --git a/tests/claude-integration/claude-tier-routing.test.ts b/tests/claude-integration/claude-tier-routing.test.ts new file mode 100644 index 00000000000..92e003270e4 --- /dev/null +++ b/tests/claude-integration/claude-tier-routing.test.ts @@ -0,0 +1,162 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { resolveInboundModel, anthropicToResponsesBody } from "../../src/claude/inbound"; +import { claudeCodeForIngress } from "../../src/claude/intercept/model-bindings"; +import { DesktopModelMappingUnavailableError } from "../../src/claude/inbound-records"; +import { getConfigPath, getDefaultConfig, loadConfig, saveConfig, validateConfigCandidate } from "../../src/config"; +import { routeModel } from "../../src/router"; +import { startServer } from "../../src/server"; +import { buildProtocolPlanSnapshot } from "../../src/protocols/plan-snapshot"; +import type { OcxClaudeCodeConfig, OcxConfig } from "../../src/types"; +import { managementFetch } from "../helpers/management-auth"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const tierRoutes = { + opus: "mock/opus-target", sonnet: "mock/sonnet-target", + haiku: "mock/haiku-target", fable: "mock/fable-target", +}; +const cc: OcxClaudeCodeConfig = { tierRoutes }; + +function requestBody(model: string) { + return { model, max_tokens: 16, messages: [{ role: "user", content: "hello" }] }; +} + +describe("Claude ingress tier routing", () => { + test.each([ + ["claude-opus-5-5", "opus"], ["claude-sonnet-5-5", "sonnet"], + ["claude-haiku-5-5", "haiku"], ["claude-fable-5-1", "fable"], + ["claude-opus-99-1", "opus"], ["claude-sonnet-4-5-20250929", "sonnet"], + ["claude-3-opus-20240229", "opus"], ["claude-3-5-sonnet-20241022", "sonnet"], + ["claude-3-haiku-20240307", "haiku"], ["claude-3-5-sonnet-latest", "sonnet"], + ["claude-sonnet-latest", "sonnet"], ["claude-sonnet-5-5[1M]", "sonnet"], + ])("routes %s by tier", (model, tier) => { + expect(resolveInboundModel(model, cc)).toBe(tierRoutes[tier as keyof typeof tierRoutes]); + }); + + test("unset policy and missing tiers preserve existing behavior and launcher defaults", () => { + expect(resolveInboundModel("claude-sonnet-5-5")).toBe("claude-sonnet-5-5"); + expect(resolveInboundModel("claude-sonnet-5-5", { tierRoutes: { opus: "mock/opus" } })).toBe("claude-sonnet-5-5"); + expect(resolveInboundModel("claude-sonnet-5-5", { tierModels: { sonnet: "mock/launch-only" } })).toBe("claude-sonnet-5-5"); + }); + + test.each(["anthropic/claude-sonnet-5-5", "combo/claude-sonnet-5-5", "policy/claude-sonnet-5-5", "pool/claude-sonnet-5-5", "anthropic/claude-sonnet-5-5--high", "pool/claude-sonnet-5-5--high", "gpt-5.5", "sonnet", "claude-sonnet-custom", "claude-not-sonnet-5", "claude-nebula-1", "claude-sonnet-5-5-preview"])("preserves explicit or non-tier selector %s", model => { + expect(resolveInboundModel(model, cc)).toBe(model); + }); + + test("discovery aliases and exact and dateless modelMap entries win", () => { + const mapped = { ...cc, modelMap: { "claude-sonnet-5-5": "mock/dateless", "claude-sonnet-5-5-20250929": "mock/exact" } }; + expect(resolveInboundModel("ocx-claude-mock--claude-sonnet-5-5", mapped)).toBe("mock/claude-sonnet-5-5"); + expect(resolveInboundModel("claude-sonnet-5-5-20250929", mapped)).toBe("mock/exact"); + expect(resolveInboundModel("claude-sonnet-5-5-20260101", mapped)).toBe("mock/dateless"); + expect(resolveInboundModel("claude-sonnet-5-5", mapped)).toBe("mock/dateless"); + }); + + test("explicit classifier configuration retains priority", () => { + expect(resolveInboundModel("claude-opus-5-5", { ...cc, classifierModel: "mock/classifier" })).toBe("mock/classifier"); + expect(resolveInboundModel("claude-opus-5-5", { ...cc, classifierFallbacks: ["mock/fallback"] })).toBe("mock/fallback"); + }); + + test("intercept bindings retain priority over global mappings and tiers", () => { + const intercepted = claudeCodeForIngress({ ...cc, intercept: { modelMap: { "claude-sonnet-5-5": "mock/intercept" } } }, true); + expect(resolveInboundModel("claude-sonnet-5-5", intercepted)).toBe("mock/intercept"); + }); + + test("unresolved Desktop aliases retain their refusal rather than picking a tier", () => { + expect(() => resolveInboundModel("claude-opus-4-8-20261231", cc)).toThrow(DesktopModelMappingUnavailableError); + }); + + test("translation forwards the target once, without recursively remapping it", () => { + const policy = { tierRoutes: { sonnet: "claude-haiku-5-5", haiku: "mock/other" } }; + expect(anthropicToResponsesBody(requestBody("claude-sonnet-5-5"), policy).model).toBe("claude-haiku-5-5"); + for (const target of ["combo/balanced", "policy/quality"]) { + expect(resolveInboundModel("claude-sonnet-5-5", { tierRoutes: { sonnet: target } })).toBe(target); + } + }); + + test.each(["", " mock/model", "mock/model\n", 42, null])("ignores malformed runtime target %j", target => { + expect(resolveInboundModel("claude-sonnet-5-5", { tierRoutes: { sonnet: target } } as OcxClaudeCodeConfig)).toBe("claude-sonnet-5-5"); + }); +}); + +let home = ""; +let previousHome: string | undefined; +beforeEach(() => { + previousHome = process.env.OPENCODEX_HOME; + home = mkdtempSync(join(tmpdir(), "ocx-tier-routing-")); + process.env.OPENCODEX_HOME = home; +}); +afterEach(() => { + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousHome; + removeTreeWithRetry(home); +}); + +test("config validates sparse policies and rejects malformed tier keys and routes", () => { + for (const policy of [{}, tierRoutes, { sonnet: "combo/balanced" }]) { + expect(validateConfigCandidate({ ...getDefaultConfig(), claudeCode: { tierRoutes: policy } }).ok).toBe(true); + } + for (const policy of [null, [], "mock/model", { unknown: "mock/model" }, { opus: "" }, { opus: " mock/model" }, { opus: 42 }]) { + expect(validateConfigCandidate({ ...getDefaultConfig(), claudeCode: { tierRoutes: policy } }).ok).toBe(false); + } +}); + +test("malformed persisted policy drops only tier routing, preserving providers and modelMap", () => { + const config = { ...getDefaultConfig(), claudeCode: { modelMap: { "claude-sonnet-5-5": "mock/preserved" }, tierRoutes: { sonnet: 42 } } }; + writeFileSync(getConfigPath(), JSON.stringify(config)); + const loaded = loadConfig(); + expect(loaded.providers).toEqual(config.providers); + expect(loaded.claudeCode?.modelMap).toEqual(config.claudeCode.modelMap); + expect(loaded.claudeCode?.tierRoutes).toBeUndefined(); +}); + +test("generic router does not apply Claude ingress tier policy", () => { + const config = { ...getDefaultConfig(), defaultProvider: "mock", providers: { mock: { adapter: "openai-chat", baseUrl: "https://example.com/v1", models: ["claude-sonnet-5-5"] } }, claudeCode: cc } as OcxConfig; + expect(routeModel(config, "mock/claude-sonnet-5-5").modelId).toBe("claude-sonnet-5-5"); +}); + +test.each(["mock/sonnet-target", "combo/tier-balanced"])("Messages, preview and count_tokens share tier target %s without extra dispatch", async target => { + const captured: Array<{ model: string; authorization: string | null }> = []; + let nativeCalls = 0; + const upstream = Bun.serve({ port: 0, async fetch(req) { + if (new URL(req.url).pathname.startsWith("/native")) { nativeCalls++; return Response.json({ error: "unexpected native call" }, { status: 500 }); } + const body = await req.json() as { model: string }; + captured.push({ model: body.model, authorization: req.headers.get("authorization") }); + const chunk = { id: "chat-test", object: "chat.completion.chunk", model: body.model, choices: [{ index: 0, delta: { role: "assistant", content: "routed" }, finish_reason: "stop" }], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } }; + return new Response(`data: ${JSON.stringify(chunk)}\n\ndata: [DONE]\n\n`, { headers: { "content-type": "text/event-stream" } }); + } }); + const config = { + ...getDefaultConfig(), port: 0, defaultProvider: "mock", + providers: { mock: { adapter: "openai-chat", baseUrl: new URL("/v1", upstream.url).toString(), apiKey: "test-provider-key", authMode: "key", allowPrivateNetwork: true, liveModels: false, models: ["sonnet-target"] } }, + combos: { "tier-balanced": { strategy: "failover", targets: [{ provider: "mock", model: "sonnet-target" }] } }, + claudeCode: { tierRoutes: { sonnet: target }, anthropicBaseUrl: new URL("/native", upstream.url).toString() }, + } as OcxConfig; + saveConfig(config); + const server = startServer(0); + try { + const preview = buildProtocolPlanSnapshot(config, { model: "claude-sonnet-5-5", inbound: "messages", features: [] }); + expect(preview.routeKind).toBe(target.startsWith("combo/") ? "combo" : "direct"); + expect(preview.candidates.map(candidate => [candidate.provider, candidate.model])).toEqual([["mock", "sonnet-target"]]); + const count = await managementFetch(new URL("/v1/messages/count_tokens", server.url), { + method: "POST", headers: { "content-type": "application/json", authorization: "Bearer sk-ant-oat01-tst" }, + body: JSON.stringify(requestBody("claude-sonnet-5-5")), + }); + expect(count.status).toBe(200); + expect((await count.json() as { input_tokens: number }).input_tokens).toBeGreaterThan(0); + expect(captured).toEqual([]); + expect(nativeCalls).toBe(0); + const response = await managementFetch(new URL("/v1/messages", server.url), { + method: "POST", headers: { "content-type": "application/json", authorization: "Bearer sk-ant-oat01-tst" }, + body: JSON.stringify(requestBody("claude-sonnet-5-5")), + }); + const text = await response.text(); + expect(response.status, text).toBe(200); + expect(text).toContain("routed"); + expect(captured).toEqual([{ model: "sonnet-target", authorization: "Bearer test-provider-key" }]); + expect(nativeCalls).toBe(0); + } finally { + await server.stop(true); + upstream.stop(true); + } +}); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 0b5ed542af8..8bbc3155a0e 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -451,7 +451,7 @@ "claude-first-party-agent-sync.test.ts": "claude-integration", "claude-first-party-union.test.ts": "claude-integration", "claude-desktop-system-proxy.test.ts": "claude-integration", "claude-gateway-cache.test.ts": "claude-integration", "claude-config-home-isolation.test.ts": "claude-integration", "claude-inbound-cache-stabilize.test.ts": "claude-integration", "claude-inbound-token-footer.test.ts": "claude-integration", - "claude-inbound-debug.test.ts": "claude-integration", "claude-inbound.test.ts": "claude-integration", + "claude-inbound-debug.test.ts": "claude-integration", "claude-inbound.test.ts": "claude-integration", "claude-tier-routing.test.ts": "claude-integration", "claude-inbound-tool-loading.test.ts": "claude-integration", "claude-inbound-tool-reference.test.ts": "claude-integration", "claude-native-reasoning-continuity.test.ts": "claude-integration", "claude-native-reasoning-provenance.test.ts": "claude-integration", "claude-output-schema-strict.test.ts": "claude-integration", "claude-intercept-integration.test.ts": "server", diff --git a/tests/routing/combo-management-api.test.ts b/tests/routing/combo-management-api.test.ts index 453429a0e21..4fef4f2f051 100644 --- a/tests/routing/combo-management-api.test.ts +++ b/tests/routing/combo-management-api.test.ts @@ -1084,6 +1084,7 @@ describe("combo management API", () => { model: "combo/old", smallFastModel: "old-public", tierModels: { opus: "combo/old", sonnet: "a/m1", haiku: "old-public" }, + tierRoutes: { opus: "combo/old", sonnet: "a/m1", haiku: "old-public", fable: "b/m2" }, modelMap: { inbound: "combo/old", stable: "a/m1" }, }, combos: { @@ -1135,6 +1136,7 @@ describe("combo management API", () => { model: "new-public", smallFastModel: "new-public", tierModels: { opus: "new-public", sonnet: "a/m1", haiku: "new-public" }, + tierRoutes: { opus: "new-public", sonnet: "a/m1", haiku: "new-public", fable: "b/m2" }, modelMap: { inbound: "new-public", stable: "a/m1" }, }); const agentBodies = readdirSync(join(process.env.CLAUDE_CONFIG_DIR!, "agents")) @@ -1159,6 +1161,7 @@ describe("combo management API", () => { model: "new-public", smallFastModel: "new-public", tierModels: { opus: "new-public", sonnet: "a/m1", haiku: "new-public" }, + tierRoutes: { opus: "new-public", sonnet: "a/m1", haiku: "new-public", fable: "b/m2" }, modelMap: { inbound: "new-public", stable: "a/m1" }, }); }); @@ -1202,6 +1205,7 @@ describe("combo management API", () => { model: "gpt-5.6-sol", smallFastModel: "gpt-5.6-sol", tierModels: { opus: "gpt-5.6-sol", sonnet: "combo/old" }, + tierRoutes: { opus: "gpt-5.6-sol", sonnet: "combo/old" }, modelMap: { native: "gpt-5.6-sol", combo: "combo/old" }, }, combos: { @@ -1235,6 +1239,7 @@ describe("combo management API", () => { model: "gpt-5.6-sol", smallFastModel: "gpt-5.6-sol", tierModels: { opus: "gpt-5.6-sol", sonnet: "combo/new" }, + tierRoutes: { opus: "gpt-5.6-sol", sonnet: "combo/new" }, modelMap: { native: "gpt-5.6-sol", combo: "combo/new" }, }); expect(routeModel(config, "gpt-5.6-terra")).toMatchObject({ @@ -1278,6 +1283,7 @@ describe("combo management API", () => { const config = baseConfig({ disabledModels: ["combo/free"], subagentModels: ["combo/free"], + claudeCode: { tierRoutes: { sonnet: "combo/free" } }, }); saveConfig(config); const response = await comboApi(config, "PUT", "/api/combos", { @@ -1287,6 +1293,8 @@ describe("combo management API", () => { expect(response?.status).toBe(200); expect(config.disabledModels).toEqual(["free-public"]); expect(config.subagentModels).toEqual(["free-public"]); + expect(config.claudeCode?.tierRoutes).toEqual({ sonnet: "free-public" }); + expect(JSON.parse(readFileSync(getConfigPath(), "utf8")).claudeCode.tierRoutes).toEqual({ sonnet: "free-public" }); }); });