Skip to main content

lean_ctx/proxy/
routing.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Explicit model targets — operator-written aliases in the forward path.
3//!
4//! Runs between body parse and body compression: an exact alias match
5//! (`[proxy.routing.aliases]`, [`RoutingRules`]) may replace the `model` field
6//! and re-target the request to another upstream of the **same wire shape** —
7//! or, with the `shape-xlat` feature (enterprise#16), route an Anthropic
8//! `/v1/messages` request onto an OpenAI-shape upstream with the translation
9//! flag set. `"acme/fast" = "foundry:gpt-4o-mini"` gives clients a stable org
10//! name for an approved endpoint; a `local` target keeps traffic on-device.
11//!
12//! LeanCTX never picks a model on its own. The rewrite is recorded as
13//! `routed_from` on the usage record so the operator can see it happened.
14//! Missing rules/model and unavailable target shapes leave the body unchanged.
15
16use crate::core::config::{
17    ResolvedProvider, RoutingRules, Upstreams, WireShape, parse_route_target,
18};
19
20/// What an alias resolved to for one request. Applied by the forward path:
21/// `model` already swapped in the body by [`route_request`]; the caller
22/// re-targets the upstream and injects the registry credential if set.
23#[derive(Debug, Clone, PartialEq)]
24pub struct RouteDecision {
25    /// Model now in the body.
26    pub model: String,
27    /// Originally requested model (usage record `routed_from`).
28    pub routed_from: String,
29    /// Registry/builtin provider id serving the request after routing
30    /// (usage attribution); `None` = upstream unchanged.
31    pub provider_id: Option<String>,
32    /// Override for the upstream base URL; `None` = keep the handler's.
33    pub upstream_base: Option<String>,
34    /// Registry entry whose `api_key_env` credential must be injected before
35    /// the request leaves (gateway-held keys, enterprise#7).
36    pub credential: Option<ResolvedProvider>,
37    /// Target's local-inference flag (shadow-rate billing): `Some` for
38    /// registry targets, `None` for built-ins (URL heuristic applies).
39    pub local: Option<bool>,
40    /// Cross-shape route (enterprise#16, feature `shape-xlat`): the Anthropic
41    /// request body must be translated to OpenAI Chat Completions before it
42    /// leaves, and the response translated back. Always `false` within-shape.
43    pub xlat: bool,
44}
45
46/// Applies the alias rules to a parsed request body. On a match the body's
47/// `model` field is rewritten in place and the decision is returned; without a
48/// match or reachable target the body is untouched and `None` is returned.
49///
50/// `xlat_ok` — the caller vouches that this request may be shape-translated
51/// (exact messages-create path, `shape-xlat` compiled in). Subpaths like
52/// `count_tokens`/`batches` have no OpenAI equivalent and must stay
53/// within-shape.
54pub fn route_request(
55    parsed: &mut serde_json::Value,
56    provider_label: &str,
57    upstreams: &Upstreams,
58    rules: &RoutingRules,
59    xlat_ok: bool,
60) -> Option<RouteDecision> {
61    if !rules.is_active() {
62        return None;
63    }
64    // Body-addressed model dialects route. Gemini keys the model in the URL
65    // path and ChatGPT-backend is OAuth'd Codex traffic — both passthrough.
66    let request_shape = match provider_label {
67        "Anthropic" => WireShape::Anthropic,
68        "OpenAI" => WireShape::OpenAi,
69        _ => return None,
70    };
71    let requested = parsed
72        .get("model")
73        .and_then(serde_json::Value::as_str)?
74        .trim()
75        .to_string();
76    let target = rules.aliases.get(&requested)?;
77    let (provider, new_model) = parse_route_target(target)?;
78    let new_model = new_model.to_string();
79
80    let resolved = match provider {
81        None => ResolvedTarget::default(),
82        Some(p) => resolve_provider(p, request_shape, upstreams, xlat_ok)?,
83    };
84
85    if new_model == requested && resolved.upstream_base.is_none() {
86        return None; // no-op rule
87    }
88
89    parsed["model"] = serde_json::Value::String(new_model.clone());
90    Some(RouteDecision {
91        model: new_model,
92        routed_from: requested,
93        provider_id: resolved.provider_id,
94        upstream_base: resolved.upstream_base,
95        credential: resolved.credential,
96        local: resolved.local,
97        xlat: resolved.xlat,
98    })
99}
100
101/// A resolved route target. `Default` = model-only rewrite (upstream unchanged).
102#[derive(Default)]
103struct ResolvedTarget {
104    provider_id: Option<String>,
105    upstream_base: Option<String>,
106    credential: Option<ResolvedProvider>,
107    local: Option<bool>,
108    xlat: bool,
109}
110
111/// Resolves a route-target provider name, enforcing the shape rules: same
112/// shape always routes; Anthropic→OpenAI routes with the translation flag when
113/// the `shape-xlat` feature is compiled in and the caller allowed it. Unknown
114/// ids and untranslatable shape pairs are logged and route nothing.
115fn resolve_provider(
116    name: &str,
117    request_shape: WireShape,
118    upstreams: &Upstreams,
119    xlat_ok: bool,
120) -> Option<ResolvedTarget> {
121    let (target_shape, base_url, credential, local) = match name {
122        "anthropic" => (
123            WireShape::Anthropic,
124            upstreams.anthropic.clone(),
125            None,
126            None,
127        ),
128        "openai" => (WireShape::OpenAi, upstreams.openai.clone(), None, None),
129        "gemini" => (WireShape::Gemini, upstreams.gemini.clone(), None, None),
130        id => {
131            let Some(p) = upstreams.provider_by_id(id) else {
132                tracing::warn!(
133                    "[proxy.routing] target provider '{id}' not in [[proxy.providers]] — passthrough"
134                );
135                return None;
136            };
137            (
138                p.shape,
139                p.base_url.clone(),
140                p.api_key_env.is_some().then(|| p.clone()),
141                Some(p.local),
142            )
143        }
144    };
145    let xlat = if target_shape == request_shape {
146        false
147    } else if can_translate(
148        request_shape,
149        target_shape,
150        xlat_ok,
151        credential.as_ref(),
152        local,
153    ) {
154        true
155    } else {
156        tracing::warn!(
157            "[proxy.routing] target '{name}' speaks {} but the request is {} — \
158             not translatable here, passthrough",
159            target_shape.as_str(),
160            request_shape.as_str()
161        );
162        return None;
163    };
164    Some(ResolvedTarget {
165        provider_id: Some(name.to_string()),
166        upstream_base: Some(base_url),
167        credential,
168        local,
169        xlat,
170    })
171}
172
173/// Anthropic→OpenAI is the supported translation pair (enterprise#16). The
174/// upstream must be gateway-authenticated (`api_key_env`) or a local endpoint
175/// (no auth) — the caller's Anthropic credentials mean nothing to an
176/// OpenAI-shape provider.
177#[cfg(feature = "shape-xlat")]
178fn can_translate(
179    request_shape: WireShape,
180    target_shape: WireShape,
181    xlat_ok: bool,
182    credential: Option<&ResolvedProvider>,
183    local: Option<bool>,
184) -> bool {
185    xlat_ok
186        && request_shape == WireShape::Anthropic
187        && target_shape == WireShape::OpenAi
188        && (credential.is_some() || local == Some(true))
189}
190
191#[cfg(not(feature = "shape-xlat"))]
192fn can_translate(
193    _request_shape: WireShape,
194    _target_shape: WireShape,
195    _xlat_ok: bool,
196    _credential: Option<&ResolvedProvider>,
197    _local: Option<bool>,
198) -> bool {
199    false
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205    use serde_json::json;
206
207    fn upstreams_with_foundry() -> Upstreams {
208        Upstreams {
209            anthropic: "https://api.anthropic.com".into(),
210            openai: "https://api.openai.com".into(),
211            chatgpt: "https://chatgpt.com".into(),
212            gemini: "https://generativelanguage.googleapis.com".into(),
213            providers: vec![
214                ResolvedProvider {
215                    id: "foundry".into(),
216                    shape: WireShape::OpenAi,
217                    base_url: "https://acme.services.ai.azure.com/openai".into(),
218                    api_key_env: Some("FOUNDRY_API_KEY".into()),
219                    aws_region: None,
220                    local: false,
221                },
222                ResolvedProvider {
223                    id: "claudeish".into(),
224                    shape: WireShape::Anthropic,
225                    base_url: "https://anthropic-gw.example.com".into(),
226                    api_key_env: None,
227                    aws_region: None,
228                    local: false,
229                },
230            ],
231        }
232    }
233
234    fn rules(aliases: &[(&str, &str)]) -> RoutingRules {
235        RoutingRules {
236            enabled: Some(true),
237            aliases: aliases
238                .iter()
239                .map(|(k, v)| (k.to_string(), v.to_string()))
240                .collect(),
241            ..RoutingRules::default()
242        }
243    }
244
245    #[test]
246    fn alias_routes_to_registry_provider_and_rewrites_model() {
247        let mut body = json!({"model": "acme/fast", "messages": [{"role":"user","content":"hi"}]});
248        let d = route_request(
249            &mut body,
250            "OpenAI",
251            &upstreams_with_foundry(),
252            &rules(&[("acme/fast", "foundry:gpt-4o-mini")]),
253            false,
254        )
255        .expect("routed");
256        assert_eq!(body["model"], "gpt-4o-mini");
257        assert_eq!(d.routed_from, "acme/fast");
258        assert_eq!(d.provider_id.as_deref(), Some("foundry"));
259        assert_eq!(
260            d.upstream_base.as_deref(),
261            Some("https://acme.services.ai.azure.com/openai")
262        );
263        assert!(
264            d.credential.is_some(),
265            "foundry has api_key_env — credential must be injected"
266        );
267    }
268
269    #[test]
270    fn alias_model_only_keeps_upstream() {
271        let mut body =
272            json!({"model": "claude-opus-4-5", "messages": [{"role":"user","content":"hi"}]});
273        let d = route_request(
274            &mut body,
275            "Anthropic",
276            &upstreams_with_foundry(),
277            &rules(&[("claude-opus-4-5", "claude-sonnet-4-5")]),
278            false,
279        )
280        .expect("routed");
281        assert_eq!(body["model"], "claude-sonnet-4-5");
282        assert_eq!(d.upstream_base, None);
283        assert_eq!(d.provider_id, None);
284        assert_eq!(d.credential, None);
285    }
286
287    #[test]
288    fn cross_shape_target_is_passthrough_when_xlat_not_allowed() {
289        // Anthropic request → OpenAI-shape foundry with xlat_ok=false (wrong
290        // path, e.g. count_tokens): must stay passthrough.
291        let mut body =
292            json!({"model": "claude-opus-4-5", "messages": [{"role":"user","content":"hi"}]});
293        let before = body.clone();
294        let d = route_request(
295            &mut body,
296            "Anthropic",
297            &upstreams_with_foundry(),
298            &rules(&[("claude-opus-4-5", "foundry:gpt-4o-mini")]),
299            false,
300        );
301        assert_eq!(d, None);
302        assert_eq!(body, before, "fail-open must leave the body untouched");
303    }
304
305    #[cfg(feature = "shape-xlat")]
306    #[test]
307    fn cross_shape_target_routes_with_translation_flag() {
308        // enterprise#16: with the feature compiled in and the caller vouching
309        // for the path, Anthropic → OpenAI-shape routes and marks xlat.
310        let mut body =
311            json!({"model": "claude-opus-4-5", "messages": [{"role":"user","content":"hi"}]});
312        let d = route_request(
313            &mut body,
314            "Anthropic",
315            &upstreams_with_foundry(),
316            &rules(&[("claude-opus-4-5", "foundry:gpt-4o-mini")]),
317            true,
318        )
319        .expect("cross-shape route with translation");
320        assert!(d.xlat, "decision must carry the translation flag");
321        assert_eq!(body["model"], "gpt-4o-mini");
322        assert_eq!(d.provider_id.as_deref(), Some("foundry"));
323        assert!(d.credential.is_some());
324
325        // Within-shape decisions never set xlat.
326        let mut body2 = json!({"model": "acme/fast", "messages": [{"role":"user","content":"hi"}]});
327        let d2 = route_request(
328            &mut body2,
329            "OpenAI",
330            &upstreams_with_foundry(),
331            &rules(&[("acme/fast", "foundry:gpt-4o-mini")]),
332            true,
333        )
334        .expect("within-shape route");
335        assert!(!d2.xlat);
336    }
337
338    #[cfg(feature = "shape-xlat")]
339    #[test]
340    fn cross_shape_needs_gateway_credential_or_local_target() {
341        // An OpenAI-shape target without api_key_env and not local cannot be
342        // reached with the caller's Anthropic credentials → passthrough.
343        let mut upstreams = upstreams_with_foundry();
344        upstreams.providers.push(ResolvedProvider {
345            id: "openaiish".into(),
346            shape: WireShape::OpenAi,
347            base_url: "https://oai-compat.example.com".into(),
348            api_key_env: None,
349            aws_region: None,
350            local: false,
351        });
352        let mut body =
353            json!({"model": "claude-opus-4-5", "messages": [{"role":"user","content":"hi"}]});
354        let before = body.clone();
355        let d = route_request(
356            &mut body,
357            "Anthropic",
358            &upstreams,
359            &rules(&[("claude-opus-4-5", "openaiish:gpt-4o-mini")]),
360            true,
361        );
362        assert_eq!(d, None);
363        assert_eq!(body, before);
364
365        // The same target declared local (e.g. Ollama) needs no credential.
366        upstreams.providers.last_mut().unwrap().local = true;
367        let d = route_request(
368            &mut body,
369            "Anthropic",
370            &upstreams,
371            &rules(&[("claude-opus-4-5", "openaiish:llama3.3")]),
372            true,
373        )
374        .expect("local cross-shape target routes");
375        assert!(d.xlat);
376        assert_eq!(d.local, Some(true));
377    }
378
379    #[cfg(feature = "shape-xlat")]
380    #[test]
381    fn openai_to_anthropic_direction_stays_passthrough() {
382        // Only Anthropic→OpenAI is translated; the reverse pair passes through.
383        let mut body = json!({"model": "gpt-5.2", "messages": [{"role":"user","content":"hi"}]});
384        let d = route_request(
385            &mut body,
386            "OpenAI",
387            &upstreams_with_foundry(),
388            &rules(&[("gpt-5.2", "claudeish:claude-sonnet-4-5")]),
389            true,
390        );
391        assert_eq!(d, None);
392    }
393
394    #[test]
395    fn unknown_provider_and_disabled_rules_are_passthrough() {
396        let mut body = json!({"model": "m", "messages": [{"role":"user","content":"hi"}]});
397        let before = body.clone();
398        assert_eq!(
399            route_request(
400                &mut body,
401                "OpenAI",
402                &upstreams_with_foundry(),
403                &rules(&[("m", "nope:x")]),
404                false,
405            ),
406            None
407        );
408        // enabled=false → inactive even with rules present.
409        let mut off = rules(&[("m", "foundry:x")]);
410        off.enabled = Some(false);
411        assert_eq!(
412            route_request(&mut body, "OpenAI", &upstreams_with_foundry(), &off, false),
413            None
414        );
415        assert_eq!(body, before);
416    }
417
418    #[test]
419    fn gemini_and_chatgpt_labels_are_passthrough() {
420        let mut body = json!({"model":"m","messages":[{"role":"user","content":"hi"}]});
421        for label in ["Gemini", "ChatGPT"] {
422            assert_eq!(
423                route_request(
424                    &mut body,
425                    label,
426                    &upstreams_with_foundry(),
427                    &rules(&[("m", "x")]),
428                    false,
429                ),
430                None,
431                "{label} must not route in M1"
432            );
433        }
434    }
435
436    #[test]
437    fn a_removed_tier_table_never_rewrites_the_model() {
438        // v4 removed automatic model selection: a legacy `[proxy.routing.tiers]`
439        // table must neither activate the router nor change the request.
440        let mut legacy = rules(&[]);
441        legacy
442            .tiers
443            .insert("fast".to_string(), "foundry:phi-4".to_string());
444        assert!(!legacy.is_active());
445        let mut body = json!({"model":"gpt-5.2","messages":[{"role":"user","content":"where is the config?"}]});
446        let before = body.clone();
447        assert_eq!(
448            route_request(
449                &mut body,
450                "OpenAI",
451                &upstreams_with_foundry(),
452                &legacy,
453                false
454            ),
455            None
456        );
457        assert_eq!(body, before);
458    }
459}