Skip to main content

lean_ctx/proxy/
google.rs

1use axum::{
2    body::Body,
3    extract::State,
4    http::{Request, StatusCode},
5    response::Response,
6};
7use serde_json::Value;
8
9use super::ProxyState;
10use super::forward;
11use super::tool_kind::{self, ToolResultKind};
12use super::{cache_safety, prose};
13use crate::core::config::{HistoryMode, ProseRole};
14
15pub async fn handler(
16    State(state): State<ProxyState>,
17    req: Request<Body>,
18) -> Result<Response, StatusCode> {
19    let upstream = state.gemini_upstream();
20    // Gemini carries the model in the URL path, not the body — capture it here so
21    // the effort applier can pick the right thinking control (#840).
22    let model = super::usage::gemini_model_from_path(req.uri().path());
23    forward::forward_request(
24        State(state),
25        req,
26        &upstream,
27        "/",
28        move |body, size| compress_request_body(body, size, model.as_deref()),
29        "Gemini",
30        &["application/x-ndjson"],
31    )
32    .await
33}
34
35pub(super) fn compress_request_body(
36    parsed: Value,
37    original_size: usize,
38    model: Option<&str>,
39) -> (Vec<u8>, usize, usize) {
40    let mut doc = parsed;
41    let mut modified = false;
42
43    // Opt-in per-role prose aggressiveness (#710); both default `None` → no-op.
44    let cfg = crate::core::config::Config::load();
45    // #1905: the input-compression control arm forwards the body uncompressed.
46    let compression_control = super::holdout::in_compression_control();
47    let system_aggr = cfg
48        .proxy
49        .resolved_role_aggressiveness(ProseRole::System)
50        .filter(|_| !compression_control);
51    let user_aggr = cfg
52        .proxy
53        .resolved_role_aggressiveness(ProseRole::User)
54        .filter(|_| !compression_control);
55    let live_compress = cfg.proxy.live_compresses() && !compression_control;
56    let mode = if compression_control {
57        HistoryMode::Off
58    } else {
59        cfg.proxy.resolved_history_mode()
60    };
61    // #895 Track B: output-savings holdout arm, from the pristine body (before any
62    // mutation below) so it matches the arm the response meter records. Control
63    // conversations skip output-shaping but are still metered. Default 0 → Treatment.
64    let arm = super::holdout::assign(
65        &super::holdout::google_key(&doc),
66        cfg.proxy.output_holdout_fraction(),
67    );
68    // #493: in-band CCR expansion (opt-in). Splice any <lc_expand:HASH> the model
69    // echoed back into the verbatim original from the local tee store. A strict
70    // no-op when no marker is present (byte-identical body → cache-safe). Runs
71    // before the meter-only short-circuit so an explicit expand request is
72    // honored even when the proxy is otherwise byte-passthrough.
73    if cfg.proxy.ccr_inband_enabled() {
74        modified |= super::ccr::splice_inband_in_place(&mut doc);
75    }
76    // #834/#840: cache-safe cross-provider effort control. Default off → no-op.
77    // The level is a constant, so it never perturbs the prompt-cache prefix; it
78    // sets generationConfig.thinkingConfig (thinkingLevel on 3.x, thinkingBudget
79    // on 2.5 pro/flash) only for models that accept it and only when the client
80    // didn't pin its own thinking field. `model` is read from the URL path.
81    if arm == super::holdout::Arm::Treatment {
82        if let Some(effort) = cfg.proxy.resolved_effort() {
83            modified |= super::effort::apply_google(&mut doc, effort, model);
84        }
85        // #895: cache-safe wire verbosity steer; control arm skips it (measured).
86        if cfg.proxy.verbosity_steer_enabled() {
87            modified |= super::verbosity::apply_google(&mut doc);
88        }
89    }
90    // Meter-only (#481): no live compression, no history pruning, no prose → the
91    // body is forwarded unchanged while usage metering still runs. A pending
92    // in-band splice (`modified`) opts out: the body did change this turn.
93    if !live_compress
94        && mode == HistoryMode::Off
95        && system_aggr.is_none()
96        && user_aggr.is_none()
97        && !modified
98    {
99        let out = serde_json::to_vec(&doc).unwrap_or_default();
100        return (out, original_size, original_size);
101    }
102    let mut prose_segments: u64 = 0;
103
104    // System prose: the top-level `systemInstruction` anchor. Gemini has no
105    // client `cache_control`, and the rewrite is deterministic, so the implicit
106    // prefix cache stays byte-stable across turns — cache-safe by construction.
107    if let Some(a) = system_aggr {
108        for key in ["systemInstruction", "system_instruction"] {
109            if let Some(parts) = doc
110                .get_mut(key)
111                .and_then(|si| si.get_mut("parts"))
112                .and_then(|p| p.as_array_mut())
113            {
114                prose_segments += u64::from(prose::compress_gemini_text_parts(parts, a));
115            }
116        }
117    }
118
119    if let Some(contents) = doc.get_mut("contents").and_then(|c| c.as_array_mut()) {
120        // Gemini's implicit prompt cache is prefix-based, so the frozen OLD
121        // region is pruned at the same monotone staircase boundary as every
122        // other rail. We never remove a `contents` entry — only rewrite the
123        // `functionResponse` text in place — so the conversation structure
124        // (and any `functionCall` ↔ `functionResponse` correspondence) is intact.
125        // `mode` resolved above.
126        let boundary = super::history_prune::prune_boundary(mode, contents.len());
127
128        for (idx, content) in contents.iter_mut().enumerate() {
129            let in_old_region = idx < boundary;
130            // Own the role before the mutable `parts` borrow below.
131            let role = content
132                .get("role")
133                .and_then(|r| r.as_str())
134                .map(String::from);
135            let Some(parts) = content.get_mut("parts").and_then(|p| p.as_array_mut()) else {
136                continue;
137            };
138            for part in parts.iter_mut() {
139                let Some(func_resp) = part.get_mut("functionResponse") else {
140                    continue;
141                };
142                // Gemini carries the originating function name inline — route it
143                // to the compressor (not `None`) so tool-specific patterns apply.
144                let name = func_resp
145                    .get("name")
146                    .and_then(|v| v.as_str())
147                    .map(String::from);
148                let kind = name
149                    .as_deref()
150                    .map_or(ToolResultKind::Other, tool_kind::classify_tool_name);
151                // #481: recent-region live compression respects the global toggle
152                // and the per-tool exclusion list (Serena default). Old-region
153                // pruning stays governed by `history_mode`.
154                let live = live_compress
155                    && !name
156                        .as_deref()
157                        .is_some_and(|n| cfg.proxy.is_tool_live_compress_excluded(n));
158                let Some(response) = func_resp.get_mut("response") else {
159                    continue;
160                };
161                for field in ["result", "content"] {
162                    modified |= if in_old_region {
163                        prune_string_field(response, field, kind)
164                    } else if live {
165                        compress_string_field(response, field, name.as_deref(), kind)
166                    } else {
167                        false
168                    };
169                }
170            }
171
172            // Frozen-region user prose: free-text `text` parts of user turns in
173            // the old region `[0, boundary)`. Model turns (assistant) and tool
174            // I/O parts are never touched.
175            if in_old_region
176                && role.as_deref() == Some("user")
177                && let Some(a) = user_aggr
178            {
179                prose_segments += u64::from(prose::compress_gemini_text_parts(parts, a));
180            }
181        }
182    }
183
184    if prose_segments > 0 {
185        modified = true;
186    }
187    cache_safety::record(prose_segments, true);
188
189    let out = serde_json::to_vec(&doc).unwrap_or_default();
190    let compressed_size = if modified { out.len() } else { original_size };
191    (out, original_size, compressed_size)
192}
193
194/// Compress a recent `functionResponse.response.<field>` string. `tool_name` is
195/// routed to the compressor so tool-specific patterns (git status, ls, …) apply;
196/// protected file/source reads in the recent region are left intact.
197fn compress_string_field(
198    obj: &mut Value,
199    field: &str,
200    tool_name: Option<&str>,
201    kind: ToolResultKind,
202) -> bool {
203    if let Some(val) = obj
204        .get_mut(field)
205        .and_then(|v| v.as_str().map(String::from))
206    {
207        let mut val = val;
208        if super::tool_output::compress_text(&mut val, tool_name, kind) {
209            obj[field] = Value::String(val);
210            return true;
211        }
212    }
213    false
214}
215
216/// Cache-aware prune of an OLD `functionResponse.response.<field>`: file/source
217/// reads collapse to a re-read stub, everything else head/tail summarizes.
218/// Content-deterministic, so the cached prefix stays byte-stable across turns.
219fn prune_string_field(obj: &mut Value, field: &str, kind: ToolResultKind) -> bool {
220    if let Some(val) = obj
221        .get_mut(field)
222        .and_then(|v| v.as_str().map(String::from))
223    {
224        let mut val = val;
225        if super::tool_output::prune_text(&mut val, kind) {
226            obj[field] = Value::String(val);
227            return true;
228        }
229    }
230    false
231}
232
233#[cfg(test)]
234mod tests {
235    use super::super::compress::compress_tool_result;
236    use super::*;
237
238    /// `pairs` Gemini turns: a `model` `functionCall` then the `user`
239    /// `functionResponse` carrying a long file read.
240    fn gemini_read_turns(pairs: usize) -> Vec<Value> {
241        let code = (0..40)
242            .map(|i| format!("    let v{i} = compute_{i}(ctx, opts);"))
243            .collect::<Vec<_>>()
244            .join("\n");
245        let mut contents = Vec::new();
246        for t in 0..pairs {
247            contents.push(serde_json::json!({
248                "role": "model",
249                "parts": [{"functionCall": {"name": "read_file", "args": {}}}]
250            }));
251            contents.push(serde_json::json!({
252                "role": "user",
253                "parts": [{"functionResponse": {
254                    "name": "read_file",
255                    "response": {"result": format!("{code}\n// turn {t}")}
256                }}]
257            }));
258        }
259        contents
260    }
261
262    #[test]
263    fn recent_response_routes_tool_name_to_compressor() {
264        // Default (isolated) config; single content → boundary 0 → recent path.
265        let _iso = crate::core::data_dir::isolated_data_dir();
266        // A compressible search result. The proxy must route the inline tool name
267        // to the shared engine, so its output matches the name-routed engine
268        // byte-for-byte (the contract that distinguishes this from `None`).
269        // `infer_command`'s use of the name is unit-tested in `compress.rs`.
270        let raw = (0..60)
271            .map(|i| format!("src/matches.rs:{i}:    let matched = find(foo, bar, baz);"))
272            .collect::<Vec<_>>()
273            .join("\n");
274        let routed = compress_tool_result(&raw, Some("search_files"));
275        assert!(routed.len() < raw.len(), "fixture must be compressible");
276
277        let body = serde_json::json!({
278            "contents": [
279                {"role": "user", "parts": [{"functionResponse": {
280                    "name": "search_files", "response": {"result": raw}
281                }}]}
282            ]
283        });
284        let bytes = serde_json::to_vec(&body).unwrap();
285        let (out, orig, comp) = compress_request_body(body, bytes.len(), None);
286        assert!(comp < orig, "recent response must be compressed");
287        let parsed: Value = serde_json::from_slice(&out).unwrap();
288        assert_eq!(
289            parsed["contents"][0]["parts"][0]["functionResponse"]["response"]["result"]
290                .as_str()
291                .unwrap(),
292            routed,
293            "Gemini path must route the inline tool name to the shared compressor"
294        );
295    }
296
297    #[test]
298    fn json_envelope_function_response_is_compressed() {
299        let _iso = crate::core::data_dir::isolated_data_dir();
300        let raw = long_git_status();
301        let expected = compress_tool_result(&raw, Some("Bash"));
302        let envelope = serde_json::to_string(&serde_json::json!({
303            "content": [{"type": "text", "text": raw}],
304            "isError": false,
305        }))
306        .unwrap();
307        let body = serde_json::json!({
308            "contents": [
309                {"role": "user", "parts": [{"functionResponse": {
310                    "name": "Bash",
311                    "response": {"result": envelope}
312                }}]}
313            ]
314        });
315        let bytes = serde_json::to_vec(&body).unwrap();
316        let (out, orig, comp) = compress_request_body(body, bytes.len(), None);
317
318        assert!(comp < orig, "JSON envelope function response should shrink");
319        let parsed: Value = serde_json::from_slice(&out).unwrap();
320        let result = parsed["contents"][0]["parts"][0]["functionResponse"]["response"]["result"]
321            .as_str()
322            .unwrap();
323        let envelope: Value = serde_json::from_str(result).unwrap();
324        assert_eq!(envelope["content"][0]["text"].as_str().unwrap(), expected);
325    }
326
327    #[test]
328    fn cache_aware_prune_stubs_old_reads_keeps_recent() {
329        let _iso = crate::core::data_dir::isolated_data_dir();
330        // 13 pairs = 26 contents → staircase boundary 16.
331        let contents = gemini_read_turns(13);
332        let n = contents.len();
333        let body = serde_json::json!({ "contents": contents });
334        let bytes = serde_json::to_vec(&body).unwrap();
335        let (out, orig, comp) = compress_request_body(body, bytes.len(), None);
336        assert!(comp < orig, "old reads must be pruned for savings");
337
338        let parsed: Value = serde_json::from_slice(&out).unwrap();
339        let got = parsed["contents"].as_array().unwrap();
340        assert_eq!(got.len(), n, "no contents may be removed");
341        // OLD file read (content index 1, before boundary 16) is stubbed.
342        let old = got[1]["parts"][0]["functionResponse"]["response"]["result"]
343            .as_str()
344            .unwrap();
345        assert!(
346            old.contains("Re-read the file"),
347            "old read should be stubbed, got: {old}"
348        );
349        // RECENT file read (content index 25, after the boundary) keeps its body.
350        let recent = got[25]["parts"][0]["functionResponse"]["response"]["result"]
351            .as_str()
352            .unwrap();
353        assert!(
354            recent.contains("v39"),
355            "recent read must be protected, got: {recent}"
356        );
357    }
358
359    fn long_git_status() -> String {
360        let mut s = String::from(
361            "$ git status\nOn branch main\nYour branch is up to date with 'origin/main'.\n\nChanges not staged for commit:\n  (use \"git add <file>...\" to update what will be committed)\n",
362        );
363        for i in 0..80 {
364            s.push_str(&format!("\tmodified:   src/module_{i}/file_{i}.rs\n"));
365        }
366        s.push_str("\nno changes added to commit (use \"git add\" and/or \"git commit -a\")\n");
367        s
368    }
369
370    #[test]
371    fn short_history_is_passthrough() {
372        let _iso = crate::core::data_dir::isolated_data_dir();
373        crate::core::config::Config::update_global(|c| c.proxy.proxy_mode = Some("cache".into()))
374            .unwrap();
375        let body = serde_json::json!({
376            "contents": [
377                {"role": "user", "parts": [{"functionResponse": {
378                    "name": "read_file", "response": {"result": "ok"}
379                }}]}
380            ]
381        });
382        let bytes = serde_json::to_vec(&body).unwrap();
383        let (out, orig, comp) = compress_request_body(body.clone(), bytes.len(), None);
384        assert_eq!(comp, orig);
385        let reparsed: Value = serde_json::from_slice(&out).unwrap();
386        assert_eq!(reparsed, body);
387    }
388
389    #[test]
390    fn gemini_compression_is_deterministic() {
391        // #498: identical request → identical bytes.
392        let _iso = crate::core::data_dir::isolated_data_dir();
393        let mk = || serde_json::json!({ "contents": gemini_read_turns(13) });
394        let (a, b) = (mk(), mk());
395        let (la, lb) = (
396            serde_json::to_vec(&a).unwrap().len(),
397            serde_json::to_vec(&b).unwrap().len(),
398        );
399        let (out_a, _, _) = compress_request_body(a, la, None);
400        let (out_b, _, _) = compress_request_body(b, lb, None);
401        assert_eq!(out_a, out_b, "identical input must yield identical bytes");
402    }
403
404    fn big_prose() -> String {
405        let p = "You are a careful, senior software engineer. You always explain your \
406                 reasoning before making changes, you prefer small reviewable diffs, and \
407                 you never introduce mock data or placeholders into production code. ";
408        [p; 6].join("\n")
409    }
410
411    #[test]
412    fn system_instruction_compressed_and_model_untouched() {
413        let _iso = crate::core::data_dir::isolated_data_dir();
414        crate::core::config::Config::update_global(|c| {
415            c.proxy.role_aggressiveness.system = Some(0.6);
416        })
417        .unwrap();
418
419        let prose = big_prose();
420        let body = serde_json::json!({
421            "systemInstruction": {"parts": [{"text": prose}]},
422            "contents": [
423                {"role": "user", "parts": [{"text": "hi"}]},
424                {"role": "model", "parts": [{"text": prose}]},
425            ]
426        });
427        let bytes = serde_json::to_vec(&body).unwrap();
428        let (out, _o, _c) = compress_request_body(body, bytes.len(), None);
429        let parsed: Value = serde_json::from_slice(&out).unwrap();
430
431        assert!(
432            parsed["systemInstruction"]["parts"][0]["text"]
433                .as_str()
434                .unwrap()
435                .len()
436                < prose.len(),
437            "systemInstruction prose must be compressed when enabled"
438        );
439        assert_eq!(
440            parsed["contents"][1]["parts"][0]["text"].as_str().unwrap(),
441            prose,
442            "model (assistant) turns must pass through verbatim (#710)"
443        );
444    }
445
446    #[test]
447    fn gemini_prose_compression_is_deterministic() {
448        let _iso = crate::core::data_dir::isolated_data_dir();
449        crate::core::config::Config::update_global(|c| {
450            c.proxy.role_aggressiveness.system = Some(0.6);
451        })
452        .unwrap();
453        let prose = big_prose();
454        let mk = || {
455            serde_json::json!({
456                "systemInstruction": {"parts": [{"text": prose}]},
457                "contents": [{"role": "user", "parts": [{"text": "hi"}]}]
458            })
459        };
460        let (a, b) = (mk(), mk());
461        let la = serde_json::to_vec(&a).unwrap().len();
462        let lb = serde_json::to_vec(&b).unwrap().len();
463        assert_eq!(
464            compress_request_body(a, la, None).0,
465            compress_request_body(b, lb, None).0,
466            "identical input must yield byte-identical output (#498)"
467        );
468    }
469
470    #[test]
471    fn cache_aware_gemini_prefix_is_byte_stable_across_turns() {
472        // THE cache invariant for the Gemini rail: every `contents` entry before
473        // an already-passed boundary stays byte-identical as the chat grows.
474        let _iso = crate::core::data_dir::isolated_data_dir();
475        let mut prev: Vec<String> = Vec::new();
476        let mut prev_boundary = 0;
477        for pairs in 1..=20 {
478            let contents = gemini_read_turns(pairs);
479            let len = contents.len();
480            let body = serde_json::json!({ "contents": contents });
481            let bytes = serde_json::to_vec(&body).unwrap();
482            let (out, _, _) = compress_request_body(body, bytes.len(), None);
483            let parsed: Value = serde_json::from_slice(&out).unwrap();
484            let items: Vec<String> = parsed["contents"]
485                .as_array()
486                .unwrap()
487                .iter()
488                .map(Value::to_string)
489                .collect();
490            for i in 0..prev_boundary {
491                assert_eq!(
492                    prev[i], items[i],
493                    "Gemini content {i} changed at turn {pairs} — prompt cache prefix broken"
494                );
495            }
496            prev = items;
497            prev_boundary = crate::proxy::history_prune::prune_boundary(
498                crate::core::config::HistoryMode::CacheAware,
499                len,
500            );
501        }
502    }
503
504    #[test]
505    fn effort_control_sets_thinking_config_by_generation() {
506        // #840 end-to-end: the model is taken from the URL path, so the handler
507        // threads it in. 3.x → thinkingLevel; off / unknown model → byte no-op.
508        let _iso = crate::core::data_dir::isolated_data_dir();
509        crate::core::config::Config::update_global(|c| c.proxy.proxy_mode = Some("cache".into()))
510            .unwrap();
511        crate::test_env::remove_var("LEAN_CTX_PROXY_EFFORT");
512        crate::core::config::Config::update_global(|c| {
513            c.proxy.effort = Some("low".into());
514        })
515        .unwrap();
516
517        let body = serde_json::json!({
518            "contents": [{"role": "user", "parts": [{"text": "hi"}]}]
519        });
520        let bytes = serde_json::to_vec(&body).unwrap();
521        let (out, _o, _c) = compress_request_body(body.clone(), bytes.len(), Some("gemini-3-pro"));
522        assert_eq!(
523            serde_json::from_slice::<Value>(&out).unwrap()["generationConfig"]["thinkingConfig"]["thinkingLevel"],
524            "low"
525        );
526
527        // No model (path didn't resolve) → strict no-op, body byte-unchanged.
528        let bytes = serde_json::to_vec(&body).unwrap();
529        let (out, _o, _c) = compress_request_body(body.clone(), bytes.len(), None);
530        assert_eq!(serde_json::from_slice::<Value>(&out).unwrap(), body);
531    }
532}