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