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