Skip to main content

lean_ctx/proxy/
verbosity.rs

1//! Cache-safe wire verbosity steer (#895 Track B).
2//!
3//! Opt-in (`proxy.verbosity_steer`). When on, the proxy appends a single
4//! **constant** "be concise" instruction to the *last user turn* of each
5//! request. Output-shaping for non-rules-aware clients: lean-ctx already steers
6//! verbosity through rules injection for editors that load rules, but raw API
7//! clients (and the holdout's treatment arm) need it on the wire.
8//!
9//! Cache-safety, by construction:
10//! - The steer is **constant** (identical bytes every turn), so it never adds
11//!   per-turn entropy.
12//! - It is appended **after** all existing content of the last user turn — i.e.
13//!   strictly after the last `cache_control` breakpoint — and never modifies a
14//!   `cache_control`-anchored block. The provider's cached prefix (everything up
15//!   to the last breakpoint) stays byte-identical across turns (#448/#498); only
16//!   the always-reprocessed tail grows by the constant suffix.
17//! - For array content the suffix is a **new** trailing text element; existing
18//!   blocks (including cache anchors) are left untouched. For plain-string
19//!   content (OpenAI prefix-cached; Anthropic strings carry no `cache_control`)
20//!   the suffix is concatenated.
21//! - Idempotent: if the steer is already present it is not appended again.
22
23use serde_json::{Map, Value};
24
25/// The constant verbosity instruction. Kept short and directive; its byte
26/// stability is what makes the steer prompt-cache-safe.
27pub const STEER: &str =
28    "Be concise: answer directly and do not restate the question or surrounding context.";
29
30/// Suffix form for plain-string content (leading separation from prior text).
31fn string_suffix() -> String {
32    format!("\n\n{STEER}")
33}
34
35/// True when `text` already ends with the steer, so we never double-append
36/// (keeps the rewrite idempotent and deterministic).
37fn already_steered(text: &str) -> bool {
38    text.trim_end().ends_with(STEER)
39}
40
41/// A `{ "type": "text", "text": STEER }` block for array content.
42fn steer_text_block() -> Value {
43    let mut m = Map::new();
44    m.insert("type".to_string(), Value::String("text".to_string()));
45    m.insert("text".to_string(), Value::String(STEER.to_string()));
46    Value::Object(m)
47}
48
49/// A `{ "type": "input_text", "text": STEER }` block for OpenAI Responses API
50/// content arrays (which require `input_text`, not `text`).
51fn steer_input_text_block() -> Value {
52    let mut m = Map::new();
53    m.insert("type".to_string(), Value::String("input_text".to_string()));
54    m.insert("text".to_string(), Value::String(STEER.to_string()));
55    Value::Object(m)
56}
57
58/// A `{ "text": STEER }` part for Gemini `parts` arrays.
59fn steer_gemini_part() -> Value {
60    let mut m = Map::new();
61    m.insert("text".to_string(), Value::String(STEER.to_string()));
62    Value::Object(m)
63}
64
65/// Append the steer to a content value that is either a plain string or an array
66/// of text blocks. `block` builds the trailing element for the array case.
67/// Returns whether the value changed.
68fn append_to_content(content: &mut Value, block: impl FnOnce() -> Value) -> bool {
69    match content {
70        Value::String(s) => {
71            if already_steered(s) {
72                return false;
73            }
74            s.push_str(&string_suffix());
75            true
76        }
77        Value::Array(parts) => {
78            // Already steered if the last text element is the steer.
79            let last_text = parts
80                .iter()
81                .rev()
82                .find_map(|p| p.get("text").and_then(Value::as_str));
83            if last_text.is_some_and(already_steered) {
84                return false;
85            }
86            parts.push(block());
87            true
88        }
89        _ => false,
90    }
91}
92
93/// Index of the last message in `messages` whose `role` matches.
94fn last_role_index(messages: &[Value], role: &str) -> Option<usize> {
95    messages
96        .iter()
97        .rposition(|m| m.get("role").and_then(Value::as_str) == Some(role))
98}
99
100/// Append the steer to the last user message of an Anthropic `/v1/messages`
101/// body. No-op (returns false) when there is no user turn.
102pub fn apply_anthropic(doc: &mut Value) -> bool {
103    let Some(messages) = doc.get_mut("messages").and_then(Value::as_array_mut) else {
104        return false;
105    };
106    let Some(idx) = last_role_index(messages, "user") else {
107        return false;
108    };
109    let Some(content) = messages[idx].get_mut("content") else {
110        return false;
111    };
112    let changed = append_to_content(content, steer_text_block);
113    if changed {
114        record();
115    }
116    changed
117}
118
119/// Append the steer to the last user message of an OpenAI Chat Completions body.
120/// OpenAI prefix-caches automatically, so appending to the newest turn never
121/// disturbs a previously cached prefix.
122pub fn apply_openai_chat(doc: &mut Value) -> bool {
123    let Some(messages) = doc.get_mut("messages").and_then(Value::as_array_mut) else {
124        return false;
125    };
126    let Some(idx) = last_role_index(messages, "user") else {
127        return false;
128    };
129    let Some(content) = messages[idx].get_mut("content") else {
130        return false;
131    };
132    let changed = append_to_content(content, steer_text_block);
133    if changed {
134        record();
135    }
136    changed
137}
138
139/// Append the steer to the last user item of an OpenAI Responses body. `input`
140/// is either a plain string or an array of role/content items.
141pub fn apply_openai_responses(doc: &mut Value) -> bool {
142    let changed = match doc.get_mut("input") {
143        Some(Value::String(s)) => {
144            if already_steered(s) {
145                false
146            } else {
147                s.push_str(&string_suffix());
148                true
149            }
150        }
151        Some(Value::Array(items)) => {
152            let Some(idx) = last_role_index(items, "user") else {
153                return false;
154            };
155            match items[idx].get_mut("content") {
156                Some(content) => append_to_content(content, steer_input_text_block),
157                None => false,
158            }
159        }
160        _ => false,
161    };
162    if changed {
163        record();
164    }
165    changed
166}
167
168/// Append the steer to the last user turn of a Gemini `generateContent` body
169/// (`contents[].parts[]`).
170pub fn apply_google(doc: &mut Value) -> bool {
171    let Some(contents) = doc.get_mut("contents").and_then(Value::as_array_mut) else {
172        return false;
173    };
174    let Some(idx) = last_role_index(contents, "user") else {
175        return false;
176    };
177    let Some(parts) = contents[idx].get_mut("parts").and_then(Value::as_array_mut) else {
178        return false;
179    };
180    let last_text = parts
181        .iter()
182        .rev()
183        .find_map(|p| p.get("text").and_then(Value::as_str));
184    if last_text.is_some_and(already_steered) {
185        return false;
186    }
187    parts.push(steer_gemini_part());
188    record();
189    true
190}
191
192use std::sync::atomic::{AtomicU64, Ordering};
193
194/// Count of requests steered, surfaced via [`steered_count`] for `/status`.
195static STEERED: AtomicU64 = AtomicU64::new(0);
196
197fn record() {
198    STEERED.fetch_add(1, Ordering::Relaxed);
199}
200
201/// Total requests that received a wire verbosity steer (telemetry).
202#[must_use]
203pub fn steered_count() -> u64 {
204    STEERED.load(Ordering::Relaxed)
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210    use serde_json::json;
211
212    #[test]
213    fn anthropic_appends_block_to_last_user() {
214        let mut doc = json!({
215            "messages": [
216                {"role": "user", "content": "first"},
217                {"role": "assistant", "content": "ok"},
218                {"role": "user", "content": [{"type": "text", "text": "second"}]}
219            ]
220        });
221        assert!(apply_anthropic(&mut doc));
222        let last = &doc["messages"][2]["content"];
223        let arr = last.as_array().unwrap();
224        assert_eq!(arr.len(), 2, "new steer block appended");
225        assert_eq!(arr[1]["text"], STEER);
226        // The earlier user turn is untouched.
227        assert_eq!(doc["messages"][0]["content"], "first");
228    }
229
230    #[test]
231    fn anthropic_string_content_concatenates() {
232        let mut doc = json!({"messages": [{"role": "user", "content": "hello"}]});
233        assert!(apply_anthropic(&mut doc));
234        let s = doc["messages"][0]["content"].as_str().unwrap();
235        assert!(s.starts_with("hello"));
236        assert!(s.ends_with(STEER));
237    }
238
239    #[test]
240    fn never_modifies_cache_control_blocks() {
241        let mut doc = json!({
242            "messages": [{
243                "role": "user",
244                "content": [
245                    {"type": "text", "text": "cached", "cache_control": {"type": "ephemeral"}}
246                ]
247            }]
248        });
249        assert!(apply_anthropic(&mut doc));
250        let arr = doc["messages"][0]["content"].as_array().unwrap();
251        // The cache-anchored block survives verbatim; the steer is a NEW block
252        // appended strictly after it.
253        assert_eq!(arr.len(), 2);
254        assert!(arr[0].get("cache_control").is_some());
255        assert_eq!(arr[0]["text"], "cached");
256        assert_eq!(arr[1]["text"], STEER);
257        assert!(arr[1].get("cache_control").is_none());
258    }
259
260    #[test]
261    fn idempotent_no_double_append() {
262        let mut doc = json!({"messages": [{"role": "user", "content": "hi"}]});
263        assert!(apply_anthropic(&mut doc));
264        let once = doc.clone();
265        assert!(!apply_anthropic(&mut doc), "second pass is a no-op");
266        assert_eq!(doc, once, "byte-identical after a redundant pass");
267    }
268
269    #[test]
270    fn deterministic_constant_suffix() {
271        let mk = || json!({"messages": [{"role": "user", "content": "ask"}]});
272        let mut a = mk();
273        let mut b = mk();
274        apply_anthropic(&mut a);
275        apply_anthropic(&mut b);
276        assert_eq!(a, b, "constant steer ⇒ byte-identical rewrite");
277    }
278
279    #[test]
280    fn openai_chat_appends_to_last_user() {
281        let mut doc = json!({
282            "messages": [
283                {"role": "system", "content": "sys"},
284                {"role": "user", "content": "q"}
285            ]
286        });
287        assert!(apply_openai_chat(&mut doc));
288        let s = doc["messages"][1]["content"].as_str().unwrap();
289        assert!(s.ends_with(STEER));
290        assert_eq!(doc["messages"][0]["content"], "sys", "system untouched");
291    }
292
293    #[test]
294    fn responses_string_and_array_input() {
295        let mut s = json!({"input": "plain"});
296        assert!(apply_openai_responses(&mut s));
297        assert!(s["input"].as_str().unwrap().ends_with(STEER));
298
299        let mut a =
300            json!({"input": [{"role": "user", "content": [{"type": "input_text", "text": "q"}]}]});
301        assert!(apply_openai_responses(&mut a));
302        let parts = a["input"][0]["content"].as_array().unwrap();
303        assert_eq!(parts.last().unwrap()["type"], "input_text");
304        assert_eq!(parts.last().unwrap()["text"], STEER);
305    }
306
307    #[test]
308    fn google_appends_part_to_last_user() {
309        let mut doc = json!({
310            "contents": [
311                {"role": "user", "parts": [{"text": "q1"}]},
312                {"role": "model", "parts": [{"text": "a1"}]},
313                {"role": "user", "parts": [{"text": "q2"}]}
314            ]
315        });
316        assert!(apply_google(&mut doc));
317        let parts = doc["contents"][2]["parts"].as_array().unwrap();
318        assert_eq!(parts.len(), 2);
319        assert_eq!(parts[1]["text"], STEER);
320    }
321
322    #[test]
323    fn no_user_turn_is_noop() {
324        let mut doc = json!({"messages": [{"role": "assistant", "content": "x"}]});
325        assert!(!apply_anthropic(&mut doc));
326    }
327}