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