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