lean_ctx/proxy/
verbosity.rs1use serde_json::{Map, Value};
24
25pub const STEER: &str =
28 "Be concise: answer directly and do not restate the question or surrounding context.";
29
30fn string_suffix() -> String {
32 format!("\n\n{STEER}")
33}
34
35fn already_steered(text: &str) -> bool {
38 text.trim_end().ends_with(STEER)
39}
40
41fn 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
49fn 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
58fn 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
65fn 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 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
93fn 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
100pub 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
119pub 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
139pub 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
168pub 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
194static STEERED: AtomicU64 = AtomicU64::new(0);
196
197fn record() {
198 STEERED.fetch_add(1, Ordering::Relaxed);
199}
200
201#[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 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 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}