Skip to main content

lean_ctx/core/config/
proxy.rs

1//! API proxy upstream overrides (`config.toml`).
2
3use serde::{Deserialize, Serialize};
4
5/// API proxy upstream overrides. `None` = use provider default.
6#[derive(Debug, Clone, Default, Serialize, Deserialize)]
7#[serde(default)]
8pub struct ProxyConfig {
9    pub anthropic_upstream: Option<String>,
10    pub openai_upstream: Option<String>,
11    pub chatgpt_upstream: Option<String>,
12    pub gemini_upstream: Option<String>,
13    /// Universal provider registry (`[[proxy.providers]]`): additional upstream
14    /// providers beyond the four built-ins, declared as data — id + wire shape +
15    /// base URL — so a new OpenAI/Anthropic/Gemini/Bedrock endpoint (Azure AI
16    /// Foundry, OpenRouter, Groq, vLLM/Ollama, a corporate gateway…) is a pure
17    /// config entry, never a code change. Reachable under
18    /// `/providers/{id}/...` on the proxy and addressable by the router.
19    /// The legacy `*_upstream` fields above stay authoritative for the four
20    /// built-in provider routes (backwards compatible).
21    pub providers: Vec<ProviderEntry>,
22    /// History-pruning strategy for proxied chat requests.
23    /// "cache-aware" (default) | "rolling" | "off". See [`HistoryMode`].
24    pub history_mode: Option<String>,
25    /// Allow a non-loopback plaintext `http://` upstream (trusted local network
26    /// only). Opt-in; see [`ProxyConfig::allows_insecure_http_upstream`]. (#440)
27    pub allow_insecure_http_upstream: Option<bool>,
28    /// Allow a custom (non-allowlisted) **HTTPS** upstream host — e.g. a corporate
29    /// gateway in front of the provider API. Opt-in; see
30    /// [`ProxyConfig::allows_custom_upstream`]. Mirrors `allow_insecure_http_upstream`
31    /// so the long-lived managed proxy (LaunchAgent / systemd), which only reads
32    /// `config.toml` and never the shell's `LEAN_CTX_ALLOW_CUSTOM_UPSTREAM`, can
33    /// honor a custom upstream too (#590).
34    pub allow_custom_upstream: Option<bool>,
35    /// Inject `stream_options.include_usage = true` into streamed OpenAI Chat
36    /// Completions so the final chunk reports real token usage for the measured
37    /// spend meter. Default on; set `false` for a client that mishandles the
38    /// trailing usage chunk. Anthropic/Gemini/OpenAI-Responses report usage
39    /// without any request change, so this only affects Chat Completions.
40    pub meter_openai_usage: Option<bool>,
41    /// Additional response header carrying the upstream gateway's billed USD
42    /// for the turn (#1189). LiteLLM's `x-litellm-response-cost` is always
43    /// recognized; set this for a corporate gateway that reports the charge
44    /// under its own header name. Measured header costs beat table estimates
45    /// (body-reported costs, e.g. OpenRouter `usage.cost`, beat headers).
46    pub cost_response_header: Option<String>,
47    /// Opt-in "big-gap cold-prefix repack" (#480). When the proxy can confidently
48    /// predict (from idle time vs the provider cache TTL) that the client-cached
49    /// prefix has already expired, it overrides the normal "never rewrite the
50    /// cached prefix" rule for that one resume request and prunes the now-cold
51    /// prefix too, re-seeding a leaner cache. `None`/`false` (the default) keeps
52    /// the prefix always protected. See [`ProxyConfig::repacks_cold_prefix`].
53    pub cold_prefix_repack: Option<bool>,
54    /// Opt-in per-role prose compression for the proxy's frozen request region
55    /// (#710). `None` for a role (the default) leaves that role untouched —
56    /// today's behaviour. See [`RoleAggressiveness`].
57    pub role_aggressiveness: RoleAggressiveness,
58    /// Live tool-result compression on the wire (#481). `true` (the default)
59    /// keeps today's behaviour: the proxy compresses non-protected `tool_result`
60    /// content on every request. `false` turns it off so the proxy can run
61    /// **meter-only** — real billed/cache token metering with zero request
62    /// rewriting (combine with `history_mode = "off"` and no `role_aggressiveness`
63    /// for a fully byte-unchanged body). Env `LEAN_CTX_PROXY_LIVE_COMPRESS`.
64    /// See [`ProxyConfig::live_compresses`].
65    pub live_compress: Option<bool>,
66    /// Per-tool exclusion list for live tool-result compression (#481). Tool
67    /// names are matched case-insensitively as substrings (the same style as
68    /// [`crate::proxy::tool_kind::classify_tool_name`]); a match is treated as
69    /// protected, exactly like a file read. `None` (the default) protects
70    /// Serena's code-reading tools (`find_symbol`/`find_referencing_symbols`/
71    /// `search_for_pattern` return source bodies the model edits, but are
72    /// mis-bucketed as `Search` by name). Set an explicit list to narrow it, or
73    /// `[]` to disable the exclusion. See [`ProxyConfig::is_tool_live_compress_excluded`].
74    pub live_compress_exclude: Option<Vec<String>>,
75    /// File-path globs whose reads are never compressed (#1150). A read whose path
76    /// matches any of these is returned verbatim (`full`) by the read tools — for
77    /// files where exact bytes matter more than token savings: golden snapshots,
78    /// byte-asserted fixtures, security-sensitive configs. Globs (`*`/`**`/`?`,
79    /// the `glob` crate) are matched against the path and its file name, so
80    /// `*.snap`, `**/golden/**`, and `tests/fixtures/*` all work. `None`/empty (the
81    /// default) protects nothing — the lossless crushers and beneficial gate
82    /// already keep compression safe, so this is an explicit escape hatch, not a
83    /// default. See [`ProxyConfig::is_path_compress_protected`].
84    pub compress_protect: Option<Vec<String>>,
85    /// Opt-in in-band CCR retrieval for a remote proxy with no shared filesystem
86    /// (#493, follow-up to #482). When enabled, a lossy stub advertises a compact
87    /// `<lc_expand:HASH>` marker (instead of a local tee path the remote agent
88    /// can't read); when the model echoes that marker back, the proxy splices the
89    /// verbatim original — recovered from its **local** tee store — inline on the
90    /// next request, costing one turn of latency and needing no MCP/FS on the
91    /// agent host. `None`/`false` (the default) keeps the path-handle stub. The
92    /// splice is a strict no-op on marker-less turns, so it never perturbs the
93    /// provider cache prefix unless the model explicitly asked to expand. See
94    /// [`ProxyConfig::ccr_inband_enabled`].
95    pub ccr_inband: Option<bool>,
96    /// Opt-in active prompt-cache breakpoint injection for Anthropic (#939). When
97    /// enabled and the client set no `cache_control` of its own, the proxy adds a
98    /// single `cache_control: {type:"ephemeral"}` breakpoint to the `system`
99    /// field so an otherwise-uncached, stable system prompt bills later turns at
100    /// the cached rate. Anthropic-only: OpenAI/Gemini cache prefixes automatically
101    /// and ignore the marker, so those paths stay byte-unchanged. The injection is
102    /// deterministic, never adds a second breakpoint, and is skipped below
103    /// Anthropic's minimum cacheable size. `None`/`false` (the default) leaves the
104    /// request untouched. See [`ProxyConfig::cache_breakpoint_enabled`].
105    pub cache_breakpoint: Option<bool>,
106    /// Opt-in counterfactual savings metering (#701). When enabled, each
107    /// *rewritten* Anthropic `/v1/messages` request additionally fires a **free**
108    /// `count_tokens` probe with the original, uncompressed body, concurrently
109    /// with the real forward. The provider-counted answer ("this request would
110    /// have cost N input tokens without lean-ctx") is paired with the actually
111    /// billed usage from the same response — provider-authoritative receipts
112    /// instead of local tokenizer estimates. The probe never mutates or delays
113    /// the forwarded request; probe failures degrade to the estimate. Off by
114    /// default: it adds one extra HTTP call per compressed request (free at
115    /// Anthropic, but latency/rate-limit surface). See
116    /// [`ProxyConfig::counterfactual_metering_enabled`].
117    pub counterfactual_metering: Option<bool>,
118    /// Opt-in cache-aligner volatile-field telemetry (#940). When enabled, the
119    /// proxy scans each *unanchored* Anthropic system prompt for volatile,
120    /// cache-busting fields (ISO dates/datetimes, UUIDs, git SHAs) and records how
121    /// many it found on `/status` `cache_safety` — purely to quantify how much
122    /// prompt-cache the client is leaking. **Measurement only**: the request body
123    /// is never mutated, so it is strictly cache-safe. `None` (the default) enables
124    /// it — every proxy ships cache-leak visibility out of the box (#986 premium
125    /// defaults); set `false` to opt out of the per-request scan. See
126    /// [`ProxyConfig::cache_aligner_enabled`].
127    pub cache_aligner: Option<bool>,
128    /// Opt-in active cache-aligner relocate (#974). When enabled, the proxy
129    /// rewrites an *unanchored* Anthropic `system` prompt into a stable block
130    /// (volatile values — ISO dates/datetimes, UUIDs, git SHAs — replaced by
131    /// constant placeholders) carrying the `cache_control` breakpoint, plus an
132    /// *uncached* trailing block that re-states the relocated values. The cacheable
133    /// prefix then stays byte-stable turn-to-turn and finally caches; only the
134    /// small tail is reprocessed. Anthropic-only, Treatment-arm, gated on a client
135    /// that anchored nothing and on Anthropic's minimum cacheable size.
136    /// Deterministic (#498) and idempotent. `None`/`false` (the default) leaves the
137    /// request untouched. The `cache_aligner` telemetry above is the precursor that
138    /// quantifies how much this would save. See
139    /// [`ProxyConfig::cache_align_relocate_enabled`].
140    pub cache_align_relocate: Option<bool>,
141    /// Cache-economics (#986), **on by default**. Bundles two strictly-safe halves
142    /// behind one flag: (1) prompt-cache **miss attribution** telemetry — per turn,
143    /// classify why the cache hit or missed (cold start / warm reuse / TTL lapse /
144    /// prefix change) and expose cumulative gauges on `/status`
145    /// ([`crate::proxy::cache_attribution`]); and (2) a **net-cost gate** on the
146    /// cold-prefix repack ([`crate::proxy::cache_policy::worth_repacking`]) that
147    /// skips re-seeding prefixes too small to be cached. The telemetry never
148    /// touches the body and the gate only makes repacking *more* conservative, so
149    /// it can never bust a cache that would otherwise have been kept. `None` (the
150    /// default) enables both — every proxy gets the diagnosis and the safer repack
151    /// out of the box (#986 premium defaults); set `false` to opt out. See
152    /// [`ProxyConfig::cache_policy_enabled`].
153    pub cache_policy: Option<bool>,
154    /// Cache-safe, cross-provider reasoning-effort control (#834). One of
155    /// `minimal|low|medium|high` pins the model's reasoning depth across every
156    /// provider; `None`/`"off"` (the default) is a strict no-op. The value is a
157    /// constant — identical on every request — so the provider prompt-cache
158    /// prefix stays byte-stable (#448/#498) and only the model's reasoning depth
159    /// changes. lean-ctx translates it to each provider's native parameter and
160    /// only ever *fills* it (never overrides a client-set value), on models that
161    /// accept it. Per-turn effort switching is deliberately unsupported — it
162    /// would invalidate the prompt cache. Env `LEAN_CTX_PROXY_EFFORT`. See
163    /// [`ProxyConfig::resolved_effort`].
164    pub effort: Option<String>,
165    #[serde(default)]
166    pub reasoning_budget: ReasoningBudgetConfig,
167    /// How the proxy squeezes prose it must shrink (#895): `"auto"` (default) and
168    /// `"extractive"` use embedding-based extractive ranking — keeping the most
169    /// central sentences instead of just the prefix — when the local embedding
170    /// engine is available, falling back to truncation otherwise; `"truncate"`
171    /// keeps the original deterministic FIFO squeeze (and no engine). Wire
172    /// rewrites are memoized per content so the engine's cold→warm transition
173    /// never changes an already-emitted frozen-region rewrite (#448/#498). Env
174    /// `LEAN_CTX_PROXY_PROSE_RANKER`. See [`ProxyConfig::resolved_prose_ranker`].
175    pub prose_ranker: Option<String>,
176    /// Fraction `0.0..=1.0` of conversations placed in the output-savings control
177    /// arm (#895 Track B). `0` (default) = no holdout (every conversation is
178    /// shaped). When `> 0`, a deterministic cohort = `blake3(system + first user
179    /// msg)` puts ~this fraction of conversations in a control arm that skips
180    /// output-shaping (effort control + verbosity steer) but is still metered —
181    /// giving an honest measured output-token reduction. The cohort is a pure
182    /// function of conversation identity, so a conversation stays in one arm
183    /// across turns (cache-safe). Env `LEAN_CTX_PROXY_OUTPUT_HOLDOUT`. See
184    /// [`ProxyConfig::output_holdout_fraction`].
185    pub output_holdout: Option<f64>,
186    /// Opt-in cache-safe wire verbosity steer (#895). When `true`, the proxy
187    /// appends a single constant "be concise" instruction to the last user turn
188    /// of each request (output-shaping for non-rules-aware API clients). The
189    /// suffix is constant and appended strictly after the last `cache_control`
190    /// breakpoint, so the provider prompt-cache prefix stays byte-stable. Default
191    /// `false`. Env `LEAN_CTX_PROXY_VERBOSITY_STEER`. See
192    /// [`ProxyConfig::verbosity_steer_enabled`].
193    pub verbosity_steer: Option<bool>,
194    /// Unified proxy operation mode (`[proxy] proxy_mode`). `"token"` (default)
195    /// or `"token"`. Sets sensible defaults for all cache-related knobs; explicit
196    /// per-knob overrides always win. Env `LEAN_CTX_PROXY_MODE`.
197    pub proxy_mode: Option<String>,
198    /// Headroom stacking compatibility (`[proxy] compat_stack`). When set to
199    /// `"headroom"`, the proxy auto-configures for running behind Headroom:
200    /// live compression off, breakpoint injection off, cache alignment on.
201    /// Also auto-detected via the `X-Headroom-Compressed` request header.
202    /// Env `LEAN_CTX_PROXY_COMPAT_STACK`.
203    pub compat_stack: Option<String>,
204    /// Opt-in: route a Codex *ChatGPT-subscription* login through the proxy for
205    /// model-turn compression. Default `None`/`false` keeps Codex native (history
206    /// visible, cloud/remote intact, no #597). When `true`, Codex setup pins the
207    /// generated `leanctx-chatgpt` provider + `chatgpt_base_url`; that scopes Codex
208    /// history to the provider (#597), so it stays opt-in. Toggle durably with
209    /// `lean-ctx proxy codex-chatgpt on|off`; resolved via
210    /// [`ProxyConfig::codex_chatgpt_proxy_enabled`].
211    pub codex_chatgpt_proxy: Option<bool>,
212    /// Active request routing (`[proxy.routing]`, enterprise#13): model aliases
213    /// and intent-tier downgrades applied in the forward path. Off by default —
214    /// an empty/absent table is a strict passthrough. See [`RoutingRules`].
215    pub routing: RoutingRules,
216    /// Counterfactual-baseline parameters (`[proxy.baseline]`, enterprise#15/#18)
217    /// for the avoided-cost evidence chain. See [`BaselineConfig`].
218    pub baseline: BaselineConfig,
219    pub pipeline: PipelineConfig,
220}
221
222/// `[proxy.baseline]` — the contract-frozen counterfactual parameters that make
223/// the success fee provable (enterprise#15, Doc 04 §6 / Doc 08 §2).
224///
225/// - `reference_model`: the model the customer *would have used* without
226///   lean-ctx. Frozen per deployment/contract (calibration: enterprise#41);
227///   every usage event stores `reference_cost_usd` = the request's
228///   **uncompressed** input tokens priced at this model's input rate — the
229///   counterfactual cost the avoided-cost ledger settles against.
230/// - `local_shadow_rate_per_mtok`: USD per 1M tokens booked as the actual cost
231///   of locally served (loopback) inference. Local compute is never free —
232///   hardware and power are real — so the shadow rate keeps local-model savings
233///   honest instead of infinite. Default: `0.25` USD/MTok, a conservative
234///   self-hosting cost estimate; calibrate per deployment.
235///
236/// Output-reasoning budget controls for triage-classified requests.
237#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
238#[serde(default)]
239pub struct ReasoningBudgetConfig {
240    /// Apply a reduced reasoning budget to simple, low-complexity requests.
241    pub enabled: bool,
242    /// Anthropic `thinking.budget_tokens` for qualifying requests.
243    pub simple_task_budget: u32,
244}
245
246impl Default for ReasoningBudgetConfig {
247    fn default() -> Self {
248        Self {
249            enabled: true,
250            simple_task_budget: 1024,
251        }
252    }
253}
254
255#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
256#[serde(default)]
257pub struct BaselineConfig {
258    /// Counterfactual reference model (`None` = baseline evidence off).
259    pub reference_model: Option<String>,
260    /// USD per 1M tokens for local/loopback inference (default 0.25, never 0).
261    pub local_shadow_rate_per_mtok: Option<f64>,
262}
263
264#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
265#[serde(default)]
266pub struct PipelineConfig {
267    pub enable_dedup: bool,
268    pub enable_prose: bool,
269    pub enable_effort: bool,
270    /// Use KnowledgeRouter references to protect relevant request context.
271    pub enable_knowledge_routing: bool,
272    pub min_savings_pct: f32,
273}
274
275impl Default for PipelineConfig {
276    fn default() -> Self {
277        Self {
278            enable_dedup: true,
279            enable_prose: true,
280            enable_effort: true,
281            enable_knowledge_routing: true,
282            min_savings_pct: 5.0,
283        }
284    }
285}
286
287/// Default local shadow rate (USD per 1M tokens) when `[proxy.baseline]` sets
288/// none: a conservative self-hosted inference cost so `is_local` usage is
289/// never booked at $0 (Doc 04 §6 "local-free ≠ cost-free").
290pub const DEFAULT_LOCAL_SHADOW_RATE_PER_MTOK: f64 = 0.25;
291
292impl BaselineConfig {
293    /// Effective shadow rate: configured value (clamped positive) or default.
294    #[must_use]
295    pub fn effective_local_shadow_rate(&self) -> f64 {
296        match self.local_shadow_rate_per_mtok {
297            Some(r) if r > 0.0 => r,
298            _ => DEFAULT_LOCAL_SHADOW_RATE_PER_MTOK,
299        }
300    }
301}
302
303/// `[proxy.routing]` — the active router's rule set (enterprise#13).
304///
305/// Two mechanisms, both **within-shape** in M1 (the target must speak the same
306/// wire dialect as the request; N×M shape translation is M2):
307///
308/// - **Aliases**: exact requested-model → target. Lets an org expose stable
309///   names (`acme/fast`) or transparently swap one concrete model for another.
310/// - **Tiers**: intent-based downgrade. The request's last user message is
311///   classified (`intent_router`); the resulting tier (`fast|standard|premium`)
312///   picks a target from this table. An absent tier key (or `""`) keeps the
313///   requested model — premium work is never silently downgraded unless the
314///   operator says so.
315///
316/// A target is `"model"` (swap the model, keep the upstream) or
317/// `"provider:model"` where `provider` is a `[[proxy.providers]]` registry id
318/// or a built-in (`anthropic|openai|gemini`) — then the request is also
319/// re-targeted to that provider's upstream.
320///
321/// **Fail-open by construction:** any lookup/classification/validation miss
322/// routes nothing and forwards the request unchanged.
323#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
324#[serde(default)]
325pub struct RoutingRules {
326    /// Master switch; `false`/absent = passthrough (no body rewrite at all).
327    pub enabled: Option<bool>,
328    /// Exact model-name aliases: requested model → `"provider:model"` | `"model"`.
329    /// BTreeMap for deterministic iteration/serialization (#498).
330    pub aliases: std::collections::BTreeMap<String, String>,
331    /// Intent-tier targets: `fast|standard|premium` → `"provider:model"` |
332    /// `"model"` | `""` (= keep requested model).
333    pub tiers: std::collections::BTreeMap<String, String>,
334}
335
336impl RoutingRules {
337    /// True when the router should run at all.
338    #[must_use]
339    pub fn is_active(&self) -> bool {
340        self.enabled.unwrap_or(false) && !(self.aliases.is_empty() && self.tiers.is_empty())
341    }
342}
343
344/// A parsed routing target: optional provider id + model name.
345/// `"foundry:gpt-4o-mini"` → provider `foundry`, model `gpt-4o-mini`;
346/// `"claude-haiku-4-5"` → model only (upstream unchanged).
347#[must_use]
348pub fn parse_route_target(target: &str) -> Option<(Option<&str>, &str)> {
349    let t = target.trim();
350    if t.is_empty() {
351        return None;
352    }
353    match t.split_once(':') {
354        Some((provider, model)) => {
355            let (provider, model) = (provider.trim(), model.trim());
356            if provider.is_empty() || model.is_empty() {
357                None
358            } else {
359                Some((Some(provider), model))
360            }
361        }
362        None => Some((None, t)),
363    }
364}
365
366/// The API dialect an upstream endpoint speaks — deliberately separate from the
367/// provider's *identity*. lean-ctx understands four wire shapes; any number of
368/// configured providers (Foundry, OpenRouter, Groq, a local vLLM…) map onto
369/// them. New shape = code; new provider = config (universal-provider-framework).
370#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
371#[serde(rename_all = "lowercase")]
372pub enum WireShape {
373    /// Anthropic Messages API (`/v1/messages`).
374    Anthropic,
375    /// OpenAI Chat Completions / Responses API (also spoken by Azure AI
376    /// Foundry, OpenRouter, Groq, vLLM, Ollama, LM Studio…).
377    OpenAi,
378    /// Google Gemini `generateContent` API.
379    Gemini,
380    /// Amazon Bedrock Runtime `InvokeModel` / event-stream API.
381    Bedrock,
382}
383
384impl WireShape {
385    /// Stable lowercase name (serde representation) for logs and `/status`.
386    #[must_use]
387    pub fn as_str(self) -> &'static str {
388        match self {
389            WireShape::Anthropic => "anthropic",
390            WireShape::OpenAi => "openai",
391            WireShape::Gemini => "gemini",
392            WireShape::Bedrock => "bedrock",
393        }
394    }
395}
396
397/// One `[[proxy.providers]]` registry entry (see [`ProxyConfig::providers`]).
398#[derive(Debug, Clone, Serialize, Deserialize)]
399pub struct ProviderEntry {
400    /// Registry id, used in the `/providers/{id}/...` route and in routing
401    /// rules. Lowercase alphanumeric plus `-`/`_`; must not shadow a built-in
402    /// provider name (`anthropic`, `openai`, `chatgpt`, `gemini`).
403    pub id: String,
404    /// Which API dialect the endpoint speaks (`anthropic|openai|gemini|bedrock`).
405    pub shape: WireShape,
406    /// Endpoint base URL. HTTPS for any non-loopback host; a declared registry
407    /// entry is itself the custom-host opt-in (no separate allowlist flag).
408    pub base_url: String,
409    /// Name of the environment variable holding the upstream API key the
410    /// gateway injects (replacing the caller's credential headers). `None` =
411    /// forward the caller's own credentials verbatim (default, loopback mode).
412    #[serde(default, skip_serializing_if = "Option::is_none")]
413    pub api_key_env: Option<String>,
414    /// AWS region for Bedrock SigV4. Bedrock uses standard AWS credential
415    /// environment variables and rejects `api_key_env`.
416    #[serde(default, skip_serializing_if = "Option::is_none")]
417    pub aws_region: Option<String>,
418    /// Set `false` to keep the entry in config but take it out of service.
419    #[serde(default, skip_serializing_if = "Option::is_none")]
420    pub enabled: Option<bool>,
421    /// Marks this endpoint as local inference (Ollama/vLLM/…): usage is booked
422    /// at the transparent `local_shadow_rate` instead of provider list prices
423    /// (enterprise#15/#18). Unset = derived from the URL (loopback hosts are
424    /// local). Set it explicitly when the endpoint is local but not loopback —
425    /// the containerized gateway reaching the host's Ollama
426    /// (`host.docker.internal`) or an in-cluster server (`ollama.svc.cluster.local`).
427    #[serde(default, skip_serializing_if = "Option::is_none")]
428    pub local: Option<bool>,
429}
430
431/// A validated, ready-to-serve registry provider (runtime view of
432/// [`ProviderEntry`], published inside [`Upstreams`]).
433#[derive(Debug, Clone, PartialEq, Eq)]
434pub struct ResolvedProvider {
435    pub id: String,
436    pub shape: WireShape,
437    pub base_url: String,
438    pub api_key_env: Option<String>,
439    /// Validated SigV4 region for Bedrock; absent for other shapes.
440    pub aws_region: Option<String>,
441    /// Billed as local inference (shadow rate). Explicit `local` flag when the
442    /// entry declares one, otherwise loopback-URL derivation.
443    pub local: bool,
444}
445
446/// Built-in provider route names a registry entry must not shadow.
447const BUILTIN_PROVIDER_IDS: &[&str] = &["anthropic", "openai", "chatgpt", "gemini"];
448
449/// True when `id` is usable as a registry id: non-empty, lowercase alnum plus
450/// `-`/`_` (it becomes a URL path segment), and not a built-in provider name.
451fn is_valid_provider_id(id: &str) -> bool {
452    !id.is_empty()
453        && !BUILTIN_PROVIDER_IDS.contains(&id)
454        && id
455            .chars()
456            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
457}
458
459fn valid_aws_region(region: &str) -> bool {
460    !region.is_empty()
461        && region.len() <= 32
462        && region
463            .bytes()
464            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
465}
466
467fn valid_bedrock_endpoint(base_url: &str, region: &str) -> bool {
468    let Ok(url) = reqwest::Url::parse(base_url) else {
469        return false;
470    };
471    if !matches!(url.path(), "" | "/") || url.query().is_some() || url.fragment().is_some() {
472        return false;
473    }
474    let Some(host) = url.host_str().map(str::to_ascii_lowercase) else {
475        return false;
476    };
477    let loopback = host == "localhost"
478        || host
479            .parse::<std::net::IpAddr>()
480            .is_ok_and(|address| address.is_loopback());
481    if loopback {
482        return true;
483    }
484    let accepted = [
485        format!("bedrock-runtime.{region}.amazonaws.com"),
486        format!("bedrock-runtime.{region}.amazonaws.com.cn"),
487        format!("bedrock-runtime.{region}.api.aws"),
488        format!("bedrock-runtime-fips.{region}.amazonaws.com"),
489        format!("bedrock-runtime-fips.{region}.api.aws"),
490    ];
491    accepted.iter().any(|candidate| candidate == &host)
492        || host.ends_with(&format!(".bedrock-runtime.{region}.vpce.amazonaws.com"))
493}
494
495impl ResolvedProvider {
496    #[must_use]
497    pub fn injects_gateway_credential(&self) -> bool {
498        self.api_key_env.is_some() || self.shape == WireShape::Bedrock
499    }
500
501    #[must_use]
502    pub fn gateway_credential_present(&self) -> bool {
503        if self.shape == WireShape::Bedrock {
504            return ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"]
505                .into_iter()
506                .all(|name| std::env::var(name).is_ok_and(|value| !value.trim().is_empty()));
507        }
508        self.api_key_env
509            .as_deref()
510            .is_some_and(|name| std::env::var(name).is_ok_and(|value| !value.trim().is_empty()))
511    }
512}
513
514/// Per-role prose-compression intensity for the proxy's frozen request region.
515///
516/// Each value is a `0.0–1.0` aggressiveness level reusing the same mapping as
517/// the `ctx_read` knob (#708): `0.0` keeps everything, `1.0` is most aggressive.
518/// `None` (the default) means "do not compress this role's prose" so the proxy
519/// stays byte-for-byte unchanged until an operator opts in. The `assistant`
520/// role is never represented here — model turns are always passed through
521/// verbatim (the #710 passthrough guarantee).
522#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
523#[serde(default)]
524pub struct RoleAggressiveness {
525    /// Aggressiveness for system prompts (Anthropic `system` / OpenAI `system`
526    /// messages / Gemini `systemInstruction`). `None` = leave untouched.
527    pub system: Option<f64>,
528    /// Aggressiveness for user prose (free-text user turns, never tool results).
529    /// `None` = leave untouched.
530    pub user: Option<f64>,
531}
532
533/// The conversation roles whose prose the proxy may compress in the frozen
534/// region. Deliberately excludes `assistant` — model turns are never rewritten.
535#[derive(Debug, Clone, Copy, PartialEq, Eq)]
536pub enum ProseRole {
537    System,
538    User,
539}
540
541/// Unified proxy operation mode that sets cache-optimal defaults for all knobs.
542///
543/// Instead of configuring 8+ individual booleans, operators pick a single mode
544/// that resolves sensible defaults. Explicit per-knob overrides always win.
545///
546/// - `Cache` (default): maximise provider prompt-cache hit rate. History is
547///   frozen at staircase boundaries, breakpoints are injected, volatile fields
548///   are detected, and the live tail is compressed — but the prefix is never
549///   rewritten.
550/// - `Token`: maximise raw token reduction. History may be rewritten, cold
551///   prefixes repacked, and volatile fields relocated. Best for short one-shot
552///   requests where cache reuse is unlikely.
553#[derive(Debug, Clone, Copy, PartialEq, Eq)]
554pub enum ProxyMode {
555    Cache,
556    Token,
557}
558
559impl ProxyMode {
560    fn parse(s: &str) -> Option<Self> {
561        match s.trim().to_ascii_lowercase().as_str() {
562            "cache" | "cache_mode" | "cost_savings" => Some(Self::Cache),
563            "token" | "token_mode" | "token_savings" => Some(Self::Token),
564            _ => None,
565        }
566    }
567
568    /// Default value for a cache-related knob under this mode.
569    pub fn preset_for(self, knob: &str) -> Option<bool> {
570        match (self, knob) {
571            (Self::Cache | Self::Token, "cache_aligner" | "cache_policy")
572            | (Self::Token, "cache_align_relocate" | "cold_prefix_repack" | "verbosity_steer") => {
573                Some(true)
574            }
575
576            (Self::Cache | Self::Token, "cache_breakpoint")
577            | (Self::Cache, "cache_align_relocate" | "cold_prefix_repack" | "verbosity_steer") => {
578                Some(false)
579            }
580
581            _ => None,
582        }
583    }
584}
585
586/// How the proxy squeezes prose it must shrink (#895).
587#[derive(Debug, Clone, Copy, PartialEq, Eq)]
588pub enum ProseRanker {
589    /// Extractive embedding ranking when the engine is available, else truncate.
590    /// The default — strictly better than truncation, and cache-safe via the
591    /// per-content memo in [`crate::proxy::prose_ranker`].
592    Auto,
593    /// Same engine path as `Auto` (kept distinct so an operator can express
594    /// intent / so a future "require engine" semantic has a name).
595    Extractive,
596    /// Original deterministic FIFO squeeze; never touches the embedding engine.
597    Truncate,
598}
599
600/// How the proxy prunes old tool results from conversation history.
601///
602/// Provider prompt caches (Anthropic `cache_control`, OpenAI automatic prompt
603/// caching) bill cached prefix tokens at a fraction of the base rate but only
604/// match *exact* prefixes. Any mutation whose position depends on the current
605/// conversation length (a rolling window) rewrites a previously-stable message
606/// every turn, invalidating the cache from that point — turning cheap cache
607/// reads into full-price writes.
608#[derive(Debug, Clone, Copy, PartialEq, Eq)]
609pub enum HistoryMode {
610    /// Prune only at frozen generation boundaries that advance in large,
611    /// deterministic steps. Between jumps the request prefix is byte-stable,
612    /// so provider prompt caches keep hitting. Content the client has marked
613    /// with a `cache_control` breakpoint is never rewritten, so an advancing
614    /// boundary can no longer invalidate the already-cached prefix (#448).
615    /// Default.
616    CacheAware,
617    /// Legacy behaviour: summarize everything older than the last N messages.
618    /// Maximum raw-token reduction, but defeats provider prompt caching.
619    Rolling,
620    /// Never prune history (tool-result compression still applies — it is
621    /// content-deterministic and therefore prefix-stable).
622    Off,
623}
624
625impl ProxyConfig {
626    /// Resolved proxy mode. `LEAN_CTX_PROXY_MODE` env wins, then config, then `Token`.
627    #[must_use]
628    pub fn resolved_proxy_mode(&self) -> ProxyMode {
629        let raw = std::env::var("LEAN_CTX_PROXY_MODE")
630            .ok()
631            .or_else(|| self.proxy_mode.clone());
632        raw.as_deref()
633            .and_then(ProxyMode::parse)
634            .unwrap_or(ProxyMode::Token)
635    }
636
637    /// Whether a Headroom-compatible stack is configured.
638    #[must_use]
639    pub fn is_headroom_compat(&self) -> bool {
640        let raw = std::env::var("LEAN_CTX_PROXY_COMPAT_STACK")
641            .ok()
642            .or_else(|| self.compat_stack.clone());
643        raw.as_deref()
644            .is_some_and(|s| s.trim().eq_ignore_ascii_case("headroom"))
645    }
646
647    /// Resolved history mode: `LEAN_CTX_PROXY_HISTORY_MODE` env var wins,
648    /// then `[proxy].history_mode` in config.toml, then cache-aware.
649    /// Unknown values fall back to the default so a typo can never silently
650    /// re-enable the cache-hostile rolling mode.
651    pub fn resolved_history_mode(&self) -> HistoryMode {
652        let raw = std::env::var("LEAN_CTX_PROXY_HISTORY_MODE")
653            .ok()
654            .or_else(|| self.history_mode.clone());
655        if let Some(mode) = raw.as_deref().map(str::trim) {
656            if mode.eq_ignore_ascii_case("rolling") {
657                return HistoryMode::Rolling;
658            }
659            if mode.eq_ignore_ascii_case("off") {
660                return HistoryMode::Off;
661            }
662        }
663        match self.resolved_proxy_mode() {
664            ProxyMode::Token => HistoryMode::Rolling,
665            ProxyMode::Cache => HistoryMode::CacheAware,
666        }
667    }
668
669    /// Whether the proxy injects `stream_options.include_usage` into streamed
670    /// OpenAI Chat Completions to meter real spend. `[proxy] meter_openai_usage`
671    /// in config.toml, default `true`.
672    pub fn meters_openai_usage(&self) -> bool {
673        self.meter_openai_usage.unwrap_or(true)
674    }
675
676    /// Operator-configured extra cost header (#1189), normalized to lowercase.
677    /// `None` when unset/blank — LiteLLM's standard header is always checked.
678    pub fn cost_response_header(&self) -> Option<String> {
679        self.cost_response_header
680            .as_deref()
681            .map(str::trim)
682            .filter(|h| !h.is_empty())
683            .map(str::to_lowercase)
684    }
685
686    /// Resolved prose-ranker strategy (#895). Precedence: the
687    /// `LEAN_CTX_PROXY_PROSE_RANKER` env var, then `[proxy] prose_ranker` in
688    /// config.toml, then `Auto`. Unknown values resolve to `Auto` so a typo can
689    /// never silently disable the premium path; `"truncate"`/`"off"` selects the
690    /// legacy squeeze.
691    #[must_use]
692    pub fn resolved_prose_ranker(&self) -> ProseRanker {
693        let raw = std::env::var("LEAN_CTX_PROXY_PROSE_RANKER")
694            .ok()
695            .or_else(|| self.prose_ranker.clone());
696        match raw.as_deref().map(str::trim) {
697            Some(s) if s.eq_ignore_ascii_case("truncate") || s.eq_ignore_ascii_case("off") => {
698                ProseRanker::Truncate
699            }
700            Some(s) if s.eq_ignore_ascii_case("extractive") => ProseRanker::Extractive,
701            _ => ProseRanker::Auto,
702        }
703    }
704
705    /// Resolved output-savings holdout fraction (#895 Track B), clamped to
706    /// `[0,1]`. Precedence: `LEAN_CTX_PROXY_OUTPUT_HOLDOUT` env > `[proxy]
707    /// output_holdout` > `0.0` (no holdout). An unparseable/blank env value is
708    /// ignored so a typo can never silently change the experiment fraction.
709    #[must_use]
710    pub fn output_holdout_fraction(&self) -> f64 {
711        let from_env = std::env::var("LEAN_CTX_PROXY_OUTPUT_HOLDOUT")
712            .ok()
713            .and_then(|v| v.trim().parse::<f64>().ok());
714        from_env
715            .or(self.output_holdout)
716            .unwrap_or(0.0)
717            .clamp(0.0, 1.0)
718    }
719
720    /// Whether the cache-safe wire verbosity steer (#895) is enabled. Precedence:
721    /// `LEAN_CTX_PROXY_VERBOSITY_STEER` env (`1`/`true`/`on`) > `[proxy]
722    /// verbosity_steer` > `false` (off).
723    #[must_use]
724    pub fn verbosity_steer_enabled(&self) -> bool {
725        if let Ok(raw) = std::env::var("LEAN_CTX_PROXY_VERBOSITY_STEER") {
726            let v = raw.trim();
727            return v.eq_ignore_ascii_case("1")
728                || v.eq_ignore_ascii_case("true")
729                || v.eq_ignore_ascii_case("on")
730                || v.eq_ignore_ascii_case("yes");
731        }
732        if let Some(v) = self.verbosity_steer {
733            return v;
734        }
735        self.resolved_proxy_mode()
736            .preset_for("verbosity_steer")
737            .unwrap_or(false)
738    }
739
740    /// Resolved Codex ChatGPT-subscription proxy opt-in (default off).
741    /// `LEAN_CTX_CODEX_CHATGPT_PROXY` (any value) forces it on for the current
742    /// process, then `[proxy] codex_chatgpt_proxy` in config.toml, else `false`.
743    pub fn codex_chatgpt_proxy_enabled(&self) -> bool {
744        std::env::var("LEAN_CTX_CODEX_CHATGPT_PROXY").is_ok()
745            || self.codex_chatgpt_proxy.unwrap_or(false)
746    }
747
748    /// Whether the opt-in cold-prefix repack (#480) is enabled. A wrong "cold"
749    /// guess re-bills cache reads as writes (~12x), so this is off by default and
750    /// must be explicitly enabled. `LEAN_CTX_PROXY_COLD_PREFIX_REPACK` (any
751    /// value) wins, then `[proxy] cold_prefix_repack` in config.toml, else
752    /// `false`.
753    pub fn repacks_cold_prefix(&self) -> bool {
754        if std::env::var("LEAN_CTX_PROXY_COLD_PREFIX_REPACK").is_ok() {
755            return true;
756        }
757        if let Some(v) = self.cold_prefix_repack {
758            return v;
759        }
760        self.resolved_proxy_mode()
761            .preset_for("cold_prefix_repack")
762            .unwrap_or(false)
763    }
764
765    /// Whether opt-in in-band CCR retrieval (#493) is enabled. Off by default:
766    /// the splice mutates provider-visible conversation content for the one turn
767    /// the model asks to expand, so it must be an explicit opt-in.
768    /// `LEAN_CTX_PROXY_CCR_INBAND` (any value) wins, then `[proxy] ccr_inband` in
769    /// config.toml, else `false`.
770    pub fn ccr_inband_enabled(&self) -> bool {
771        std::env::var("LEAN_CTX_PROXY_CCR_INBAND").is_ok() || self.ccr_inband.unwrap_or(false)
772    }
773
774    /// Whether opt-in Anthropic prompt-cache breakpoint injection (#939) is
775    /// enabled. Off by default: it mutates the provider-visible `system` shape
776    /// (string → cache-marked block array), so it must be an explicit opt-in.
777    /// `LEAN_CTX_PROXY_CACHE_BREAKPOINT` (any value) wins, then `[proxy]
778    /// cache_breakpoint` in config.toml, else `false`.
779    pub fn cache_breakpoint_enabled(&self) -> bool {
780        if std::env::var("LEAN_CTX_PROXY_CACHE_BREAKPOINT").is_ok() {
781            return true;
782        }
783        if let Some(v) = self.cache_breakpoint {
784            return v;
785        }
786        if self.is_headroom_compat() {
787            return false;
788        }
789        self.resolved_proxy_mode()
790            .preset_for("cache_breakpoint")
791            .unwrap_or(false)
792    }
793
794    /// Whether opt-in counterfactual savings metering (#701) is enabled. Off by
795    /// default: it fires one extra (free) Anthropic `count_tokens` call per
796    /// rewritten request — pure telemetry, but extra latency budget and
797    /// rate-limit surface, so it must be an explicit opt-in.
798    /// `LEAN_CTX_PROXY_COUNTERFACTUAL` (any value) wins, then `[proxy]
799    /// counterfactual_metering` in config.toml, else `false`.
800    pub fn counterfactual_metering_enabled(&self) -> bool {
801        std::env::var("LEAN_CTX_PROXY_COUNTERFACTUAL").is_ok()
802            || self.counterfactual_metering.unwrap_or(false)
803    }
804
805    /// Whether opt-in cache-aligner volatile-field telemetry (#940) is enabled.
806    /// On by default (#986 premium defaults): the scan is pure measurement and
807    /// never mutates the body, so every proxy ships cache-leak visibility out of
808    /// the box. Strictly cache-safe. `LEAN_CTX_PROXY_CACHE_ALIGNER=on|off` wins,
809    /// then `[proxy] cache_aligner` in config.toml, else `true`. Opt **out** only
810    /// to drop the per-request system-prompt scan.
811    pub fn cache_aligner_enabled(&self) -> bool {
812        env_bool_or("LEAN_CTX_PROXY_CACHE_ALIGNER", self.cache_aligner, true)
813    }
814
815    /// Whether opt-in active cache-aligner relocate (#974) is enabled. Off by
816    /// default: it reshapes the provider-visible `system` field (moving volatile
817    /// values to an uncached tail block), so it must be an explicit opt-in.
818    /// `LEAN_CTX_PROXY_CACHE_ALIGN_RELOCATE` (any value) wins, then `[proxy]
819    /// cache_align_relocate` in config.toml, else `false`.
820    pub fn cache_align_relocate_enabled(&self) -> bool {
821        if std::env::var("LEAN_CTX_PROXY_CACHE_ALIGN_RELOCATE").is_ok() {
822            return true;
823        }
824        if let Some(v) = self.cache_align_relocate {
825            return v;
826        }
827        if self.is_headroom_compat() {
828            return false;
829        }
830        self.resolved_proxy_mode()
831            .preset_for("cache_align_relocate")
832            .unwrap_or(false)
833    }
834
835    /// Whether cache-economics (#986) is enabled: prompt-cache miss attribution
836    /// telemetry plus the net-cost repack gate. Both are strictly safe
837    /// (measurement + a more-conservative repack that never busts a cache the
838    /// default kept), so this is **on by default** — every proxy gets the
839    /// diagnosis and the safer repack out of the box.
840    /// `LEAN_CTX_PROXY_CACHE_POLICY=on|off` wins, then `[proxy] cache_policy` in
841    /// config.toml, else `true`. Opt out to keep `/status` free of the attribution
842    /// gauges and skip the per-request prefix hash.
843    pub fn cache_policy_enabled(&self) -> bool {
844        env_bool_or("LEAN_CTX_PROXY_CACHE_POLICY", self.cache_policy, true)
845    }
846
847    /// Resolved cross-provider reasoning effort (#834), or `None` when the
848    /// feature is off (the default — a strict no-op that preserves the
849    /// byte-unchanged meter-only path). Precedence: `LEAN_CTX_PROXY_EFFORT` env
850    /// (`off` disables, a valid level wins, an unparseable/blank value is
851    /// ignored) > `[proxy] effort` in config.toml. Any unknown value resolves to
852    /// `None` so a typo can never silently enable reasoning steering.
853    #[must_use]
854    pub fn resolved_effort(&self) -> Option<super::Effort> {
855        if let Ok(raw) = std::env::var("LEAN_CTX_PROXY_EFFORT") {
856            let trimmed = raw.trim();
857            if trimmed.eq_ignore_ascii_case("off") {
858                return None;
859            }
860            if let Some(effort) = super::Effort::parse(trimmed) {
861                return Some(effort);
862            }
863            // Blank/unknown env → ignore and fall through to config, mirroring
864            // `live_compresses` so a typo never flips the configured behaviour.
865        }
866        self.effort.as_deref().and_then(super::Effort::parse)
867    }
868
869    /// Whether the proxy live-compresses non-protected `tool_result` content
870    /// (#481). `LEAN_CTX_PROXY_LIVE_COMPRESS` (`0`/`false`/`off`/`no` → off,
871    /// `1`/`true`/`on`/`yes` → on) wins, then `[proxy] live_compress` in
872    /// config.toml, else `true`. An unparseable/blank env value is ignored so a
873    /// typo can never silently flip the mode.
874    pub fn live_compresses(&self) -> bool {
875        if let Ok(raw) = std::env::var("LEAN_CTX_PROXY_LIVE_COMPRESS") {
876            match raw.trim().to_ascii_lowercase().as_str() {
877                "0" | "false" | "off" | "no" => return false,
878                "1" | "true" | "on" | "yes" => return true,
879                _ => {}
880            }
881        }
882        if let Some(v) = self.live_compress {
883            return v;
884        }
885        if self.is_headroom_compat() {
886            return false;
887        }
888        match self.resolved_proxy_mode() {
889            ProxyMode::Cache | ProxyMode::Token => true,
890        }
891    }
892
893    /// Resolved per-tool live-compress exclusion patterns (#481). `None` in
894    /// config falls back to the built-in default (protect Serena); an explicit
895    /// list — including the empty list — is used verbatim so operators can narrow
896    /// or fully clear it.
897    #[must_use]
898    pub fn live_compress_exclude_patterns(&self) -> Vec<String> {
899        self.live_compress_exclude
900            .clone()
901            .unwrap_or_else(default_live_compress_exclude)
902    }
903
904    /// Whether `tool_name` is on the live-compress exclusion list (#481) and must
905    /// therefore reach the model intact, like a protected file read. Matching is
906    /// case-insensitive substring, mirroring `tool_kind::classify_tool_name`.
907    #[must_use]
908    pub fn is_tool_live_compress_excluded(&self, tool_name: &str) -> bool {
909        let name = tool_name.to_ascii_lowercase();
910        self.live_compress_exclude_patterns().iter().any(|p| {
911            let p = p.trim().to_ascii_lowercase();
912            !p.is_empty() && name.contains(p.as_str())
913        })
914    }
915
916    /// Compiled `compress_protect` globs (#1150), skipping any that fail to parse
917    /// so one malformed entry never disables the rest. Empty when unset — the
918    /// default — which makes [`Self::is_path_compress_protected`] a fast no-op.
919    #[must_use]
920    pub fn compress_protect_globs(&self) -> Vec<glob::Pattern> {
921        self.compress_protect
922            .as_deref()
923            .unwrap_or_default()
924            .iter()
925            .filter_map(|p| glob::Pattern::new(p.trim()).ok())
926            .collect()
927    }
928
929    /// Whether `path` is on the never-compress list (#1150) and must be returned
930    /// verbatim. Each glob is tried against both the full path (with backslashes
931    /// normalised to `/`) and the bare file name, so `*.snap` matches anywhere
932    /// while `**/golden/**` can still target a directory. Empty list → always
933    /// `false` (today's behaviour), so a default proxy pays nothing.
934    #[must_use]
935    pub fn is_path_compress_protected(&self, path: &str) -> bool {
936        let patterns = self.compress_protect_globs();
937        if patterns.is_empty() {
938            return false;
939        }
940        let norm = path.replace('\\', "/");
941        let base = norm.rsplit('/').next().unwrap_or(norm.as_str());
942        patterns.iter().any(|p| p.matches(&norm) || p.matches(base))
943    }
944
945    /// Resolved prose-compression aggressiveness for `role`, clamped to `[0,1]`,
946    /// or `None` when prose compression is off for that role (the default).
947    ///
948    /// Precedence: the role's env override (`LEAN_CTX_PROXY_SYSTEM_AGGR` /
949    /// `LEAN_CTX_PROXY_USER_AGGR`) wins, then `[proxy.role_aggressiveness]` in
950    /// config.toml. An unparseable or blank env value is ignored so a typo can
951    /// never silently disable the configured behaviour.
952    #[must_use]
953    pub fn resolved_role_aggressiveness(&self, role: ProseRole) -> Option<f64> {
954        let (env_var, configured) = match role {
955            ProseRole::System => (
956                "LEAN_CTX_PROXY_SYSTEM_AGGR",
957                self.role_aggressiveness.system,
958            ),
959            ProseRole::User => ("LEAN_CTX_PROXY_USER_AGGR", self.role_aggressiveness.user),
960        };
961        let from_env = std::env::var(env_var)
962            .ok()
963            .and_then(|v| v.trim().parse::<f64>().ok());
964        let resolved = from_env.or(configured);
965        if resolved.is_some() {
966            return resolved.map(|a| a.clamp(0.0, 1.0));
967        }
968        if self.resolved_proxy_mode() == ProxyMode::Token && role == ProseRole::System {
969            return Some(0.5);
970        }
971        None
972    }
973
974    /// Whether a non-loopback plaintext `http://` upstream is allowed. Opt-in
975    /// only — a deliberate downgrade for a trusted local-network service such as
976    /// `http://host.docker.internal:2455` in front of codex-lb (#440).
977    /// `LEAN_CTX_ALLOW_INSECURE_HTTP_UPSTREAM` (any value) wins, then
978    /// `[proxy] allow_insecure_http_upstream` in config.toml, default `false`.
979    pub fn allows_insecure_http_upstream(&self) -> bool {
980        std::env::var("LEAN_CTX_ALLOW_INSECURE_HTTP_UPSTREAM").is_ok()
981            || self.allow_insecure_http_upstream.unwrap_or(false)
982    }
983
984    /// Whether a custom (non-allowlisted) HTTPS upstream host is allowed. Opt-in
985    /// only — lifting the built-in host allowlist points the proxy at a host you
986    /// control (e.g. a corporate gateway), so it must be deliberate.
987    /// `LEAN_CTX_ALLOW_CUSTOM_UPSTREAM` (any value) wins, then
988    /// `[proxy] allow_custom_upstream` in config.toml, default `false`.
989    ///
990    /// Unlike the env var, the **config flag reaches the managed (service-spawned)
991    /// proxy**, which only reads `config.toml` — that is the whole point of #590:
992    /// `proxy enable`/`restart` start the proxy via launchd/systemd, which never
993    /// inherits the shell's `LEAN_CTX_ALLOW_CUSTOM_UPSTREAM`.
994    pub fn allows_custom_upstream(&self) -> bool {
995        std::env::var("LEAN_CTX_ALLOW_CUSTOM_UPSTREAM").is_ok()
996            || self.allow_custom_upstream.unwrap_or(false)
997    }
998
999    /// True when any `*_upstream` configured in `config.toml` (env-independent) is a
1000    /// custom HTTPS host outside the built-in allowlist — i.e. one that resolves
1001    /// only with the [`Self::allows_custom_upstream`] opt-in. Plaintext-HTTP custom
1002    /// hosts are governed by `allow_insecure_http_upstream` instead, so they are
1003    /// excluded here. Lets `proxy enable`/`restart` persist the opt-in (so the
1004    /// managed proxy honors it) and `proxy status` explain a blocked upstream,
1005    /// without touching the allowlisted-host case (#590).
1006    #[must_use]
1007    pub fn has_custom_host_upstream(&self) -> bool {
1008        [
1009            self.anthropic_upstream.as_deref(),
1010            self.openai_upstream.as_deref(),
1011            self.chatgpt_upstream.as_deref(),
1012            self.gemini_upstream.as_deref(),
1013        ]
1014        .into_iter()
1015        .flatten()
1016        .filter_map(normalize_url_opt)
1017        .any(|u| is_custom_upstream_host(&u))
1018    }
1019
1020    /// `(env var, configured value, provider default)` for one provider.
1021    fn provider_spec(&self, provider: ProxyProvider) -> (&'static str, Option<&str>, &'static str) {
1022        match provider {
1023            ProxyProvider::Anthropic => (
1024                "LEAN_CTX_ANTHROPIC_UPSTREAM",
1025                self.anthropic_upstream.as_deref(),
1026                "https://api.anthropic.com",
1027            ),
1028            ProxyProvider::OpenAi => (
1029                "LEAN_CTX_OPENAI_UPSTREAM",
1030                self.openai_upstream.as_deref(),
1031                "https://api.openai.com",
1032            ),
1033            ProxyProvider::ChatGpt => (
1034                "LEAN_CTX_CHATGPT_UPSTREAM",
1035                self.chatgpt_upstream.as_deref(),
1036                "https://chatgpt.com",
1037            ),
1038            ProxyProvider::Gemini => (
1039                "LEAN_CTX_GEMINI_UPSTREAM",
1040                self.gemini_upstream.as_deref(),
1041                "https://generativelanguage.googleapis.com",
1042            ),
1043        }
1044    }
1045
1046    /// Resolve one upstream with precedence `LEAN_CTX_*_UPSTREAM` env var >
1047    /// `[proxy].*_upstream` (config.toml) > provider default.
1048    ///
1049    /// Returns `Err` when a value is *present but invalid* so a live reload can
1050    /// keep the last good value instead of silently rerouting to the default; an
1051    /// *absent* value resolves to the provider default (`Ok`).
1052    fn resolve_upstream_checked(&self, provider: ProxyProvider) -> Result<String, String> {
1053        self.resolve_upstream_inner(provider, true)
1054    }
1055
1056    /// Shared resolver for [`resolve_upstream_checked`] and the disk-only view.
1057    /// `use_env = false` ignores the `LEAN_CTX_*_UPSTREAM` override and yields
1058    /// the config.toml truth a freshly (re)started managed proxy would serve.
1059    fn resolve_upstream_inner(
1060        &self,
1061        provider: ProxyProvider,
1062        use_env: bool,
1063    ) -> Result<String, String> {
1064        let (env_var, config_val, default) = self.provider_spec(provider);
1065        let env_val = if use_env {
1066            std::env::var(env_var)
1067                .ok()
1068                .and_then(|v| normalize_url_opt(&v))
1069        } else {
1070            None
1071        };
1072        let candidate = env_val.or_else(|| config_val.and_then(normalize_url_opt));
1073        match candidate {
1074            None => Ok(normalize_url(default)),
1075            Some(url) => validate_upstream_url(
1076                &url,
1077                self.allows_insecure_http_upstream(),
1078                self.allows_custom_upstream(),
1079            ),
1080        }
1081    }
1082
1083    /// Effective upstream for a provider (env > config > default). An invalid
1084    /// configured/env value falls back to the provider default (logged) — the
1085    /// safe choice at startup.
1086    pub fn resolve_upstream(&self, provider: ProxyProvider) -> String {
1087        match self.resolve_upstream_checked(provider) {
1088            Ok(url) => url,
1089            Err(e) => {
1090                tracing::warn!("upstream validation failed, using default: {e}");
1091                normalize_url(self.provider_spec(provider).2)
1092            }
1093        }
1094    }
1095
1096    /// Resolve all three upstreams at once (startup snapshot, env-aware).
1097    pub fn resolve_all(&self) -> Upstreams {
1098        Upstreams {
1099            anthropic: self.resolve_upstream(ProxyProvider::Anthropic),
1100            openai: self.resolve_upstream(ProxyProvider::OpenAi),
1101            chatgpt: self.resolve_upstream(ProxyProvider::ChatGpt),
1102            gemini: self.resolve_upstream(ProxyProvider::Gemini),
1103            providers: self.resolve_providers(),
1104        }
1105    }
1106
1107    /// Validate + resolve the `[[proxy.providers]]` registry. Invalid entries
1108    /// are logged and skipped (one typo must never take the proxy down or
1109    /// disable the remaining registry); duplicates keep the first occurrence.
1110    /// A declared registry entry is itself the deliberate custom-host opt-in,
1111    /// so any HTTPS host is accepted; plaintext HTTP still requires loopback or
1112    /// the explicit insecure-HTTP opt-in (same rule as the built-ins).
1113    #[must_use]
1114    pub fn resolve_providers(&self) -> Vec<ResolvedProvider> {
1115        let mut seen: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
1116        let mut out = Vec::new();
1117        for entry in &self.providers {
1118            if !entry.enabled.unwrap_or(true) {
1119                continue;
1120            }
1121            let id = entry.id.trim();
1122            if !is_valid_provider_id(id) {
1123                tracing::warn!(
1124                    "[proxy.providers] invalid id '{id}' (lowercase alnum/-/_ only, \
1125                     must not shadow a built-in provider) — entry skipped"
1126                );
1127                continue;
1128            }
1129            if !seen.insert(id) {
1130                tracing::warn!("[proxy.providers] duplicate id '{id}' — keeping first entry");
1131                continue;
1132            }
1133            match validate_upstream_url(&entry.base_url, self.allows_insecure_http_upstream(), true)
1134            {
1135                Ok(base_url) => {
1136                    let aws_region = entry
1137                        .aws_region
1138                        .as_deref()
1139                        .map(str::trim)
1140                        .filter(|value| !value.is_empty());
1141                    if entry.shape == WireShape::Bedrock {
1142                        let Some(region) = aws_region.filter(|value| valid_aws_region(value))
1143                        else {
1144                            tracing::warn!(
1145                                "[proxy.providers] Bedrock provider '{id}' requires valid aws_region — skipped"
1146                            );
1147                            continue;
1148                        };
1149                        if entry.api_key_env.is_some() || !valid_bedrock_endpoint(&base_url, region)
1150                        {
1151                            tracing::warn!(
1152                                "[proxy.providers] Bedrock provider '{id}' has invalid credential mode or endpoint — skipped"
1153                            );
1154                            continue;
1155                        }
1156                    } else if aws_region.is_some() {
1157                        tracing::warn!(
1158                            "[proxy.providers] non-Bedrock provider '{id}' cannot set aws_region — skipped"
1159                        );
1160                        continue;
1161                    }
1162                    // Explicit `local` flag wins; otherwise loopback URLs are
1163                    // local (host.docker.internal etc. need the explicit flag).
1164                    let local = entry.local.unwrap_or_else(|| is_local_proxy_url(&base_url));
1165                    out.push(ResolvedProvider {
1166                        id: id.to_string(),
1167                        shape: entry.shape,
1168                        base_url,
1169                        api_key_env: entry
1170                            .api_key_env
1171                            .as_deref()
1172                            .map(str::trim)
1173                            .filter(|v| !v.is_empty())
1174                            .map(str::to_string),
1175                        aws_region: aws_region.map(str::to_string),
1176                        local,
1177                    });
1178                }
1179                Err(e) => {
1180                    tracing::warn!("[proxy.providers] '{id}' has invalid base_url — skipped: {e}");
1181                }
1182            }
1183        }
1184        out
1185    }
1186
1187    /// Resolve all upstreams from config.toml only (ignoring `LEAN_CTX_*` env) —
1188    /// the values a freshly (re)started managed proxy would serve. Used by
1189    /// status/doctor to detect drift from a running proxy's live upstream (#449).
1190    pub fn resolve_all_disk(&self) -> Upstreams {
1191        let pick = |provider: ProxyProvider| {
1192            self.resolve_upstream_inner(provider, false)
1193                .unwrap_or_else(|_| normalize_url(self.provider_spec(provider).2))
1194        };
1195        Upstreams {
1196            anthropic: pick(ProxyProvider::Anthropic),
1197            openai: pick(ProxyProvider::OpenAi),
1198            chatgpt: pick(ProxyProvider::ChatGpt),
1199            gemini: pick(ProxyProvider::Gemini),
1200            providers: self.resolve_providers(),
1201        }
1202    }
1203
1204    /// Re-resolve upstreams for a *running* proxy (#449). For any provider whose
1205    /// currently configured/env value fails validation, the last good value is
1206    /// kept instead of rerouting live traffic to the provider default — so a typo
1207    /// in config.toml can never silently redirect in-flight requests.
1208    pub fn refresh_upstreams(&self, last: &Upstreams) -> Upstreams {
1209        let keep = |provider: ProxyProvider, prev: &str| {
1210            self.resolve_upstream_checked(provider).unwrap_or_else(|e| {
1211                tracing::warn!("upstream invalid, keeping {prev}: {e}");
1212                prev.to_string()
1213            })
1214        };
1215        Upstreams {
1216            anthropic: keep(ProxyProvider::Anthropic, &last.anthropic),
1217            openai: keep(ProxyProvider::OpenAi, &last.openai),
1218            chatgpt: keep(ProxyProvider::ChatGpt, &last.chatgpt),
1219            gemini: keep(ProxyProvider::Gemini, &last.gemini),
1220            // Registry re-resolution is deterministic from config; an entry
1221            // that turned invalid is dropped with a warning (see
1222            // `resolve_providers`), the rest keep serving.
1223            providers: self.resolve_providers(),
1224        }
1225    }
1226}
1227
1228/// The resolved provider upstreams a running proxy forwards to. Published
1229/// to request handlers via a `tokio::sync::watch` channel so a config change is
1230/// picked up live, without a proxy restart (#449).
1231#[derive(Debug, Clone, PartialEq, Eq)]
1232pub struct Upstreams {
1233    pub anthropic: String,
1234    pub openai: String,
1235    pub chatgpt: String,
1236    pub gemini: String,
1237    /// Registry providers from `[[proxy.providers]]` (universal framework),
1238    /// validated and live-reloadable exactly like the built-ins.
1239    pub providers: Vec<ResolvedProvider>,
1240}
1241
1242impl Upstreams {
1243    /// Look up a registry provider by id (`/providers/{id}/...` route, router
1244    /// upstream overrides). Built-ins are not addressed here.
1245    #[must_use]
1246    pub fn provider_by_id(&self, id: &str) -> Option<&ResolvedProvider> {
1247        self.providers.iter().find(|p| p.id == id)
1248    }
1249}
1250
1251#[derive(Debug, Clone, Copy)]
1252pub enum ProxyProvider {
1253    Anthropic,
1254    OpenAi,
1255    ChatGpt,
1256    Gemini,
1257}
1258
1259/// Why a running proxy's live upstream differs from what the operator expects.
1260#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1261pub enum UpstreamDrift {
1262    /// A `LEAN_CTX_*_UPSTREAM` env var is set in *this* process but the proxy
1263    /// serves a different value — the env never reached the MCP/service-spawned
1264    /// proxy. This is the #449 trap: Codex (and other MCP hosts) launch the
1265    /// server with a stripped, allowlisted env that omits `LEAN_CTX_*_UPSTREAM`,
1266    /// so the proxy it spawns never sees it. Fix: persist it to config.toml,
1267    /// which the proxy reads live.
1268    EnvNotApplied,
1269    /// The proxy serves a value other than config.toml resolves to: it was
1270    /// started with an env override that now masks a later config edit. Fix:
1271    /// `lean-ctx proxy restart`.
1272    ConfigNotApplied,
1273}
1274
1275/// The `LEAN_CTX_*_UPSTREAM` override visible to *this* process for a provider,
1276/// normalized (`None` if unset/blank). Lets status/doctor explain why an env var
1277/// a user exported in their shell never reaches an MCP/service-spawned proxy.
1278pub fn env_upstream_override(provider: ProxyProvider) -> Option<String> {
1279    let var = match provider {
1280        ProxyProvider::Anthropic => "LEAN_CTX_ANTHROPIC_UPSTREAM",
1281        ProxyProvider::OpenAi => "LEAN_CTX_OPENAI_UPSTREAM",
1282        ProxyProvider::ChatGpt => "LEAN_CTX_CHATGPT_UPSTREAM",
1283        ProxyProvider::Gemini => "LEAN_CTX_GEMINI_UPSTREAM",
1284    };
1285    std::env::var(var).ok().and_then(|v| normalize_url_opt(&v))
1286}
1287
1288/// Diagnose upstream drift for one provider from the CLI-visible env override
1289/// (`env`), the config.toml value (`disk`) and the proxy's live value (`live`).
1290/// `None` means in sync.
1291pub fn diagnose_drift(env: Option<&str>, disk: &str, live: &str) -> Option<UpstreamDrift> {
1292    if let Some(env) = env {
1293        // An env override is present in this process: the proxy honours it only
1294        // if it was started with it. If the proxy serves something else, the env
1295        // never reached it (#449). If it matches, that is consistent (no drift).
1296        return (env != live).then_some(UpstreamDrift::EnvNotApplied);
1297    }
1298    // No env override here: the proxy should mirror config.toml.
1299    (disk != live).then_some(UpstreamDrift::ConfigNotApplied)
1300}
1301
1302/// Resolve a tri-state boolean toggle for the default-**on** proxy features: an
1303/// explicit `on`/`off`-style environment variable wins, then the config
1304/// `Option<bool>`, else `default`. Lets an operator force a feature on **or** off
1305/// from the shell; an unparseable value is ignored so a typo can never silently
1306/// flip it (mirrors [`ProxyConfig::live_compresses`]).
1307fn env_bool_or(env_key: &str, configured: Option<bool>, default: bool) -> bool {
1308    if let Ok(raw) = std::env::var(env_key) {
1309        match raw.trim().to_ascii_lowercase().as_str() {
1310            "1" | "true" | "yes" | "on" => return true,
1311            "0" | "false" | "no" | "off" => return false,
1312            _ => {}
1313        }
1314    }
1315    configured.unwrap_or(default)
1316}
1317
1318/// Built-in default live-compress exclusion (#481). Serena's code-reading tools
1319/// (`find_symbol`/`find_referencing_symbols`/`search_for_pattern`) return source
1320/// bodies the model edits, yet are mis-bucketed as `Search` by name, so the proxy
1321/// would otherwise gut them. Protect anything namespaced `serena` by default.
1322fn default_live_compress_exclude() -> Vec<String> {
1323    vec!["serena".to_string()]
1324}
1325
1326pub fn normalize_url(value: &str) -> String {
1327    value.trim().trim_end_matches('/').to_string()
1328}
1329
1330pub fn normalize_url_opt(value: &str) -> Option<String> {
1331    let trimmed = normalize_url(value);
1332    if trimmed.is_empty() {
1333        None
1334    } else {
1335        Some(trimmed)
1336    }
1337}
1338
1339const ALLOWED_UPSTREAM_HOSTS: &[&str] = &[
1340    "api.anthropic.com",
1341    "api.openai.com",
1342    "chatgpt.com",
1343    "generativelanguage.googleapis.com",
1344    // xAI Grok (OpenAI-compatible). Used by auto-seeded registry providers
1345    // when `lean-ctx proxy enable` wires Grok (API-key rail + subscription rail).
1346    "api.x.ai",
1347    "cli-chat-proxy.grok.com",
1348    // Command Code gateway. Used by the auto-seeded `commandcode` registry
1349    // provider when `lean-ctx proxy enable` wires Command Code.
1350    "api.commandcode.ai",
1351];
1352
1353pub(super) fn validate_upstream_url(
1354    url: &str,
1355    allow_insecure_http: bool,
1356    allow_custom_host: bool,
1357) -> Result<String, String> {
1358    let normalized = normalize_url(url);
1359    // Loopback HTTP never leaves the machine — always allowed.
1360    if is_local_proxy_url(&normalized) {
1361        return Ok(normalized);
1362    }
1363
1364    // A non-loopback plaintext `http://` upstream is reachable only through the
1365    // explicit opt-in (#440). The old code rejected it on the HTTPS check *before*
1366    // any override could apply, and pointed at `LEAN_CTX_ALLOW_CUSTOM_UPSTREAM`,
1367    // which never lifted the scheme restriction. Handle it up front: the opt-in
1368    // implies a deliberate custom host on a trusted local network, so it needs no
1369    // separate allowlist check; otherwise give a hint that actually works.
1370    if normalized.starts_with("http://") {
1371        if allow_insecure_http {
1372            return Ok(normalized);
1373        }
1374        return Err(format!(
1375            "upstream URL must use HTTPS: {normalized} (for a trusted local-network HTTP \
1376             upstream opt in with LEAN_CTX_ALLOW_INSECURE_HTTP_UPSTREAM=1 or \
1377             `[proxy] allow_insecure_http_upstream = true`)"
1378        ));
1379    }
1380    let Some(host_segment) = normalized.strip_prefix("https://") else {
1381        return Err(format!(
1382            "upstream URL must start with http:// or https://: {normalized}"
1383        ));
1384    };
1385
1386    let host = host_segment.split('/').next().unwrap_or("");
1387    let host_no_port = host.split(':').next().unwrap_or(host);
1388    if ALLOWED_UPSTREAM_HOSTS.contains(&host_no_port) || allow_custom_host {
1389        Ok(normalized)
1390    } else {
1391        Err(format!(
1392            "upstream host '{host_no_port}' not in allowlist {ALLOWED_UPSTREAM_HOSTS:?} (for a \
1393             custom upstream host opt in with LEAN_CTX_ALLOW_CUSTOM_UPSTREAM=1 or \
1394             `[proxy] allow_custom_upstream = true`)"
1395        ))
1396    }
1397}
1398
1399/// True when `url` is an HTTPS upstream whose host is not in the built-in
1400/// allowlist (and not loopback) — the case the `allow_custom_upstream` opt-in
1401/// governs. Plaintext-HTTP custom hosts are governed by
1402/// `allow_insecure_http_upstream` instead, so they are excluded here.
1403fn is_custom_upstream_host(url: &str) -> bool {
1404    let n = normalize_url(url);
1405    if is_local_proxy_url(&n) {
1406        return false;
1407    }
1408    let Some(host_segment) = n.strip_prefix("https://") else {
1409        return false;
1410    };
1411    let host = host_segment.split('/').next().unwrap_or("");
1412    let host_no_port = host.split(':').next().unwrap_or(host);
1413    !host_no_port.is_empty() && !ALLOWED_UPSTREAM_HOSTS.contains(&host_no_port)
1414}
1415
1416pub fn is_local_proxy_url(value: &str) -> bool {
1417    let n = normalize_url(value);
1418    n.starts_with("http://127.0.0.1:")
1419        || n.starts_with("http://localhost:")
1420        || n.starts_with("http://[::1]:")
1421}
1422
1423#[cfg(test)]
1424#[path = "proxy_tests.rs"]
1425mod tests;