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