Skip to main content

lean_ctx/proxy/
openai.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.openai_upstream();
21    forward::forward_request(
22        State(state),
23        req,
24        &upstream,
25        "/v1/chat/completions",
26        compress_request_body,
27        "OpenAI",
28        &[],
29    )
30    .await
31}
32
33/// One pass over a Chat Completions request, as on the Messages path: the
34/// unit in which a block that leaves with a recovery stub and the
35/// conversation it belongs to are brought together (`sticky_tools`).
36pub(super) fn compress_request_body(
37    parsed: Value,
38    original_size: usize,
39) -> (Vec<u8>, usize, usize) {
40    sticky_tools::in_pass(|| compress_in_pass(parsed, original_size))
41}
42
43fn compress_in_pass(parsed: Value, original_size: usize) -> (Vec<u8>, usize, usize) {
44    let mut doc = parsed;
45    let mut modified = false;
46    // Under protection a block leaves shortened only with a stub that names
47    // the Engine's expand tool as the host listed it in this request's own
48    // `tools[].function.name`. Whether the request lists it and lets its
49    // model call it is settled before any block is touched; if not, blocks
50    // stay whole. The proxy adds no tool.
51    sticky_tools::begin(Shape::Chat, &doc);
52
53    // Opt-in per-role prose aggressiveness (#710); both default `None` → no-op.
54    let cfg = crate::core::config::Config::load();
55    // #1905: the input-compression control arm forwards the body uncompressed.
56    let compression_control = super::holdout::in_compression_control();
57    let system_aggr = cfg
58        .proxy
59        .resolved_role_aggressiveness(ProseRole::System)
60        .filter(|_| !compression_control);
61    let user_aggr = cfg
62        .proxy
63        .resolved_role_aggressiveness(ProseRole::User)
64        .filter(|_| !compression_control);
65    let live_compress = cfg.proxy.live_compresses() && !compression_control;
66    let mode = if compression_control {
67        HistoryMode::Off
68    } else {
69        cfg.proxy.resolved_history_mode()
70    };
71    // #895 Track B: output-savings holdout arm, from the pristine body (before any
72    // mutation below) so it matches the arm the response meter records. Control
73    // conversations skip output-shaping but are still metered. Default 0 → Treatment.
74    let arm = super::holdout::assign(
75        &super::holdout::openai_chat_key(&doc),
76        cfg.proxy.output_holdout_fraction(),
77    );
78    // #493: in-band CCR expansion (opt-in). Splice any <lc_expand:HASH> the model
79    // echoed back into the verbatim original from the local tee store. A strict
80    // no-op when no marker is present (byte-identical body → cache-safe). Runs
81    // before the meter-only short-circuit so an explicit expand request is
82    // honored even when the proxy is otherwise byte-passthrough.
83    if cfg.proxy.ccr_inband_enabled() {
84        modified |= super::ccr::splice_inband_in_place(&mut doc);
85    }
86    // #834: cache-safe cross-provider effort control. Default off → no-op. The
87    // value is a constant, so it never perturbs the prompt-cache prefix; it sets
88    // `reasoning_effort` only on reasoning models and never overrides a
89    // client-set value.
90    if arm == super::holdout::Arm::Treatment {
91        if let Some(effort) = cfg.proxy.resolved_effort() {
92            modified |= super::effort::apply_openai_chat(&mut doc, effort);
93        }
94        // #895: cache-safe wire verbosity steer; control arm skips it (measured).
95        if cfg.proxy.verbosity_steer_enabled() {
96            modified |= super::verbosity::apply_openai_chat(&mut doc);
97        }
98    }
99    // Meter-only (#481): nothing rewrites the body, so skip all work and let
100    // forward + usage metering run against the byte-unchanged request. A pending
101    // in-band splice (`modified`) opts out: the body did change this turn.
102    if !live_compress
103        && mode == HistoryMode::Off
104        && system_aggr.is_none()
105        && user_aggr.is_none()
106        && !modified
107    {
108        let out = serde_json::to_vec(&doc).unwrap_or_default();
109        return (out, original_size, original_size);
110    }
111    // K26: large tool descriptions leave shortened (see the Messages path).
112    if live_compress {
113        modified |= super::tool_descriptions::shorten(&mut doc);
114    }
115    let mut prose_segments: u64 = 0;
116
117    if let Some(messages) = doc.get_mut("messages").and_then(|m| m.as_array_mut()) {
118        let tool_names = tool_kind::openai_tool_names(messages);
119
120        // OpenAI's automatic prompt caching is prefix-based like Anthropic's,
121        // so history is pruned at the same frozen, cache-aware boundary. `mode`
122        // resolved above.
123        let boundary = super::history_prune::prune_boundary(mode, messages.len());
124        // Mirror the Anthropic guard: never rewrite content behind a client
125        // `cache_control` breakpoint (#448). OpenAI requests carry none, so this
126        // resolves to 0 and pruning is byte-for-byte unchanged — but the code
127        // path stays uniform across providers.
128        let cached = super::history_prune::cached_prefix_len(messages);
129        modified |=
130            super::history_prune::prune_history_range(messages, cached, boundary, &tool_names);
131
132        for msg in messages.iter_mut() {
133            let role = msg.get("role").and_then(|r| r.as_str()).unwrap_or("");
134            if role != "tool" {
135                continue;
136            }
137
138            let call_id = msg.get("tool_call_id").and_then(|v| v.as_str());
139            // One tool-result block: what is shortened below is text of the
140            // call with this id (`sticky_tools::block`).
141            let _block = sticky_tools::block(call_id);
142            let name = call_id
143                .and_then(|id| tool_names.get(id))
144                .map(String::as_str);
145            let kind = name.map_or(ToolResultKind::Other, tool_kind::classify_tool_name);
146
147            // #481: skip live compression when globally off or tool excluded.
148            if !live_compress || name.is_some_and(|n| cfg.proxy.is_tool_live_compress_excluded(n)) {
149                continue;
150            }
151            if let Some(mut content) = msg
152                .get_mut("content")
153                .and_then(|c| c.as_str().map(String::from))
154                && super::tool_output::compress_text(&mut content, name, kind)
155            {
156                msg["content"] = Value::String(content);
157                modified = true;
158            }
159        }
160
161        // Frozen-region prose: system anchors (deterministic rewrite keeps the
162        // auto-cached prefix byte-stable, so safe at any position outside the
163        // client-cached prefix) and user turns in `[cached, boundary)`. The
164        // `assistant` and `tool` roles are never touched (passthrough). Both
165        // knobs default off, so this is inert unless an operator opts in.
166        if system_aggr.is_some() || user_aggr.is_some() {
167            for (i, msg) in messages.iter_mut().enumerate() {
168                if i < cached {
169                    continue;
170                }
171                let role = msg.get("role").and_then(|r| r.as_str()).unwrap_or("");
172                let aggr = match role {
173                    "system" | "developer" => system_aggr,
174                    "user" if i < boundary => user_aggr,
175                    _ => None,
176                };
177                if let Some(a) = aggr {
178                    prose_segments += u64::from(prose::compress_message_content(msg, a));
179                }
180            }
181        }
182    }
183
184    if prose_segments > 0 {
185        modified = true;
186    }
187    cache_safety::record(prose_segments, true);
188
189    // Ask OpenAI to append a final usage chunk so the proxy can meter real
190    // spend. Not counted as compression (it slightly grows the body), so it
191    // never inflates the savings figure.
192    maybe_inject_usage_reporting(&mut doc);
193
194    let out = serde_json::to_vec(&doc).unwrap_or_default();
195    let compressed_size = if modified { out.len() } else { original_size };
196    (out, original_size, compressed_size)
197}
198
199/// Config-gated wrapper around [`inject_usage_reporting`].
200fn maybe_inject_usage_reporting(doc: &mut Value) {
201    if crate::core::config::Config::load()
202        .proxy
203        .meters_openai_usage()
204    {
205        inject_usage_reporting(doc);
206    }
207}
208
209/// Injects `stream_options.include_usage = true` into a streamed Chat
210/// Completions request so the final SSE chunk carries `usage` (OpenAI omits it
211/// otherwise). No-op for non-streamed requests or when the client already
212/// configured `stream_options.include_usage`.
213fn inject_usage_reporting(doc: &mut Value) {
214    if doc.get("stream").and_then(Value::as_bool) != Some(true) {
215        return;
216    }
217    let Some(obj) = doc.as_object_mut() else {
218        return;
219    };
220    let opts = obj
221        .entry("stream_options")
222        .or_insert_with(|| Value::Object(serde_json::Map::new()));
223    if let Some(opts_obj) = opts.as_object_mut() {
224        opts_obj.entry("include_usage").or_insert(Value::Bool(true));
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::super::compress::compress_tool_result;
231    use super::*;
232
233    #[test]
234    fn read_file_tool_result_protected() {
235        let code = (0..60)
236            .map(|i| format!("    const value{i} = computeValue{i}(ctx, opts);"))
237            .collect::<Vec<_>>()
238            .join("\n");
239        let body = serde_json::json!({
240            "model": "gpt-5",
241            "messages": [
242                {"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "read_file"}}]},
243                {"role": "tool", "tool_call_id": "call_1", "content": code}
244            ]
245        });
246        let bytes = serde_json::to_vec(&body).unwrap();
247        let (out, _orig, _comp) = compress_request_body(body, bytes.len());
248        let parsed: Value = serde_json::from_slice(&out).unwrap();
249        assert!(
250            parsed["messages"][1]["content"]
251                .as_str()
252                .unwrap()
253                .contains("value59")
254        );
255    }
256
257    #[test]
258    fn json_envelope_tool_output_is_compressed() {
259        let _iso = crate::core::data_dir::isolated_data_dir();
260        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
261        let raw = long_git_status();
262        let expected = compress_tool_result(&raw, Some("Bash"));
263        let envelope = serde_json::to_string(&serde_json::json!({
264            "content": [{"type": "text", "text": raw}],
265            "isError": false,
266        }))
267        .unwrap();
268        let body = serde_json::json!({
269            "model": "gpt-5",
270            "messages": [
271                {"role": "assistant", "tool_calls": [{
272                    "id": "call_1",
273                    "type": "function",
274                    "function": {"name": "Bash"}
275                }]},
276                {"role": "tool", "tool_call_id": "call_1", "content": envelope}
277            ]
278        });
279        let bytes = serde_json::to_vec(&body).unwrap();
280        let (out, orig, comp) = compress_request_body(body, bytes.len());
281
282        assert!(comp < orig, "JSON envelope tool output should shrink");
283        let parsed: Value = serde_json::from_slice(&out).unwrap();
284        let content = parsed["messages"][1]["content"].as_str().unwrap();
285        let envelope: Value = serde_json::from_str(content).unwrap();
286        assert_eq!(envelope["content"][0]["text"].as_str().unwrap(), expected);
287    }
288
289    #[test]
290    fn injects_include_usage_for_streaming() {
291        let mut doc = serde_json::json!({"model": "gpt-5.4", "stream": true, "messages": []});
292        inject_usage_reporting(&mut doc);
293        assert_eq!(doc["stream_options"]["include_usage"], Value::Bool(true));
294    }
295
296    fn long_git_status() -> String {
297        let mut s = String::from(
298            "$ 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",
299        );
300        for i in 0..80 {
301            s.push_str(&format!("\tmodified:   src/module_{i}/file_{i}.rs\n"));
302        }
303        s.push_str("\nno changes added to commit (use \"git add\" and/or \"git commit -a\")\n");
304        s
305    }
306
307    #[test]
308    fn no_injection_for_non_streaming() {
309        let mut doc = serde_json::json!({"model": "gpt-5.4", "messages": []});
310        inject_usage_reporting(&mut doc);
311        assert!(
312            doc.get("stream_options").is_none(),
313            "non-streamed requests get usage in the body, no injection needed"
314        );
315    }
316
317    #[test]
318    fn respects_client_set_include_usage() {
319        let mut doc = serde_json::json!({
320            "model": "gpt-5.4",
321            "stream": true,
322            "stream_options": {"include_usage": false},
323            "messages": []
324        });
325        inject_usage_reporting(&mut doc);
326        assert_eq!(
327            doc["stream_options"]["include_usage"],
328            Value::Bool(false),
329            "an explicit client value must be preserved"
330        );
331    }
332
333    fn big_prose() -> String {
334        let p = "You are a careful, senior software engineer. You always explain your \
335                 reasoning before making changes, you prefer small reviewable diffs, and \
336                 you never introduce mock data or placeholders into production code. ";
337        [p; 6].join("\n")
338    }
339
340    #[test]
341    fn system_message_compressed_and_assistant_untouched() {
342        let _iso = crate::core::data_dir::isolated_data_dir();
343        crate::core::config::Config::update_global(|c| {
344            c.proxy.role_aggressiveness.system = Some(0.6);
345        })
346        .unwrap();
347
348        let prose = big_prose();
349        let body = serde_json::json!({
350            "model": "gpt-5",
351            "messages": [
352                {"role": "system", "content": prose},
353                {"role": "user", "content": "hi"},
354                {"role": "assistant", "content": prose},
355            ]
356        });
357        let bytes = serde_json::to_vec(&body).unwrap();
358        let (out, _o, _c) = compress_request_body(body, bytes.len());
359        let parsed: Value = serde_json::from_slice(&out).unwrap();
360
361        assert!(
362            parsed["messages"][0]["content"].as_str().unwrap().len() < prose.len(),
363            "system message prose must be compressed when enabled"
364        );
365        assert_eq!(
366            parsed["messages"][2]["content"].as_str().unwrap(),
367            prose,
368            "assistant turns must pass through verbatim (#710)"
369        );
370    }
371
372    #[test]
373    fn openai_prose_compression_is_deterministic() {
374        let _iso = crate::core::data_dir::isolated_data_dir();
375        crate::core::config::Config::update_global(|c| {
376            c.proxy.role_aggressiveness.system = Some(0.6);
377        })
378        .unwrap();
379        let prose = big_prose();
380        let mk = || {
381            serde_json::json!({
382                "model": "gpt-5",
383                "messages": [{"role": "system", "content": prose}, {"role": "user", "content": "hi"}]
384            })
385        };
386        let (a, b) = (mk(), mk());
387        let la = serde_json::to_vec(&a).unwrap().len();
388        let lb = serde_json::to_vec(&b).unwrap().len();
389        assert_eq!(
390            compress_request_body(a, la).0,
391            compress_request_body(b, lb).0,
392            "identical input must yield byte-identical output (#498)"
393        );
394    }
395
396    #[test]
397    fn effort_control_sets_reasoning_effort_and_off_is_noop() {
398        // #834 end-to-end through the Chat Completions request path.
399        let _iso = crate::core::data_dir::isolated_data_dir();
400        crate::core::config::Config::update_global(|c| c.proxy.proxy_mode = Some("cache".into()))
401            .unwrap();
402        crate::test_env::remove_var("LEAN_CTX_PROXY_EFFORT");
403        let body = serde_json::json!({
404            "model": "gpt-5.5", "messages": [{"role": "user", "content": "hi"}]
405        });
406        let bytes = serde_json::to_vec(&body).unwrap();
407
408        // Off by default: a cache-safe no-op (size unchanged, no param added).
409        let (off, o, c) = compress_request_body(body.clone(), bytes.len());
410        assert_eq!(c, o, "effort off must be a passthrough");
411        assert!(
412            serde_json::from_slice::<Value>(&off)
413                .unwrap()
414                .get("reasoning_effort")
415                .is_none()
416        );
417
418        // Enabled: reasoning_effort is filled on the reasoning model.
419        crate::core::config::Config::update_global(|cfg| {
420            cfg.proxy.effort = Some("low".into());
421        })
422        .unwrap();
423        let (on, _o, _c) = compress_request_body(body, bytes.len());
424        assert_eq!(
425            serde_json::from_slice::<Value>(&on).unwrap()["reasoning_effort"],
426            "low"
427        );
428    }
429}