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