Skip to main content

lean_ctx/core/config/
proxy.rs

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