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