1use serde_json::Value;
47
48pub const THRESHOLD_BYTES: usize = 180_000;
51
52pub const MIN_ELIDE_BYTES: usize = 2_000;
55
56pub const STUB_OPEN: &str = "[lean-ctx: earlier tool output elided";
58
59fn serialized_len(messages: &[Value]) -> usize {
61 struct Count(usize);
62 impl std::io::Write for Count {
63 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
64 self.0 += buf.len();
65 Ok(buf.len())
66 }
67 fn flush(&mut self) -> std::io::Result<()> {
68 Ok(())
69 }
70 }
71 let mut count = Count(0);
72 let _ = serde_json::to_writer(&mut count, messages);
73 count.0
74}
75
76pub fn elide(messages: &mut [Value], threshold: usize) -> Option<usize> {
80 if serialized_len(messages) <= threshold {
81 return None;
82 }
83 let boundary = super::history_prune::prune_boundary(
84 lean_ctx::core::config::HistoryMode::CacheAware,
85 messages.len(),
86 );
87 let mut last = None;
88 for (index, message) in messages[..boundary].iter_mut().enumerate() {
89 if message.get("role").and_then(Value::as_str) != Some("user") {
90 continue;
91 }
92 let Some(blocks) = message.get_mut("content").and_then(Value::as_array_mut) else {
93 continue;
94 };
95 for block in blocks {
96 if elide_block(block) {
97 last = Some(index);
98 }
99 }
100 }
101 last
102}
103
104fn elidable_text(content: &Value) -> Option<String> {
108 match content {
109 Value::String(text) => Some(text.clone()),
110 Value::Array(items) => {
111 let mut parts = Vec::with_capacity(items.len());
112 for item in items {
113 if item.get("type").and_then(Value::as_str) != Some("text")
114 || item.get("cache_control").is_some()
115 {
116 return None;
117 }
118 parts.push(item.get("text")?.as_str()?);
119 }
120 Some(parts.join("\n"))
121 }
122 _ => None,
123 }
124}
125
126fn elide_block(block: &mut Value) -> bool {
129 if block.get("type").and_then(Value::as_str) != Some("tool_result") {
130 return false;
131 }
132 let Some(original) = block.get("content").and_then(elidable_text) else {
133 return false;
134 };
135 if original.len() <= MIN_ELIDE_BYTES
136 || original.starts_with(STUB_OPEN)
137 || original.contains("<protect>")
138 {
139 return false;
140 }
141 let chars = original.chars().count();
142 let stub = if super::compress::protected() {
143 let call_id = block.get("tool_use_id").and_then(Value::as_str);
144 let _block = super::sticky_tools::block(call_id);
145 let Some(stub) = super::compress::shorten_with_copy(
146 &original,
147 &format!("{STUB_OPEN} ({chars} chars).]"),
148 ) else {
149 return false;
150 };
151 stub
152 } else {
153 let Some(path) = super::ccr::persist_once(&original) else {
155 return false;
156 };
157 format!(
158 "{STUB_OPEN} ({chars} chars) to keep this long session lean; full text: {}]",
159 locator(std::path::Path::new(&path))
160 )
161 };
162 block["content"] = Value::String(stub);
163 true
164}
165
166fn locator(path: &std::path::Path) -> String {
170 let home = shell_home(|key| std::env::var_os(key), cfg!(windows));
171 locator_in(path, home.as_deref())
172}
173
174pub(crate) fn shell_home(
178 var: impl Fn(&str) -> Option<std::ffi::OsString>,
179 windows: bool,
180) -> Option<std::ffi::OsString> {
181 let set = |key: &str| var(key).filter(|value| !value.is_empty());
182 set("HOME").or_else(|| if windows { set("USERPROFILE") } else { None })
183}
184
185fn locator_in(path: &std::path::Path, home: Option<&std::ffi::OsStr>) -> String {
192 if let Some(location) = home.and_then(|home| home_location_in(path, home)) {
193 return format!("cat {location}");
194 }
195 let name = path
196 .file_name()
197 .map_or_else(String::new, |n| n.to_string_lossy().into_owned());
198 format!("ctx_expand(id=\"{name}\") (LeanCTX state directory, tee/{name})")
199}
200
201pub(crate) fn home_location(path: &std::path::Path) -> Option<String> {
206 let home = shell_home(|key| std::env::var_os(key), cfg!(windows))?;
207 home_location_in(path, &home)
208}
209
210fn home_location_in(path: &std::path::Path, home: &std::ffi::OsStr) -> Option<String> {
211 let rest = path.strip_prefix(home).ok()?;
212 home_relative(rest).map(|rest| format!("~/{rest}"))
213}
214
215fn home_relative(rest: &std::path::Path) -> Option<String> {
218 let mut parts = Vec::new();
219 for component in rest.components() {
220 match component {
221 std::path::Component::Normal(part) => parts.push(part.to_str()?),
222 _ => return None,
223 }
224 }
225 if parts.is_empty() {
226 return None;
227 }
228 let joined = parts.join("/");
229 let plain = |c: char| c.is_ascii_alphanumeric() || "._-/+@%,:=".contains(c);
230 if joined.chars().all(plain) {
231 return Some(joined);
232 }
233 if joined
236 .chars()
237 .any(|c| "\"$`\\!".contains(c) || c.is_control())
238 {
239 return None;
240 }
241 Some(format!("\"{joined}\""))
242}
243
244pub fn message_is_elided(message: &Value) -> bool {
246 message
247 .get("content")
248 .and_then(Value::as_array)
249 .is_some_and(|blocks| {
250 blocks.iter().any(|block| {
251 block.get("type").and_then(Value::as_str) == Some("tool_result")
252 && block
253 .get("content")
254 .and_then(Value::as_str)
255 .is_some_and(|text| text.starts_with(STUB_OPEN))
256 })
257 })
258}
259
260pub fn newly_elided(prefix_bytes: &[u8], last: usize) -> bool {
265 let Ok(previous) = serde_json::from_slice::<Value>(prefix_bytes) else {
266 return true;
267 };
268 previous
269 .get("messages")
270 .and_then(Value::as_array)
271 .and_then(|messages| messages.get(last))
272 .is_some_and(|message| !message_is_elided(message))
273}
274
275#[cfg(test)]
276mod tests {
277 use super::*;
278 use serde_json::json;
279
280 fn session(turns: usize, size: usize) -> Vec<Value> {
282 let mut messages = vec![json!({"role": "user", "content": "fix the build"})];
283 for turn in 0..turns {
284 let id = format!("t{turn}");
285 messages.push(json!({"role": "assistant", "content": [
286 {"type": "tool_use", "id": id, "name": "Bash", "input": {"command": "make"}}
287 ]}));
288 let output = format!("output {turn} line\n").repeat(size / 15);
289 messages.push(json!({"role": "user", "content": [
290 {"type": "tool_result", "tool_use_id": id, "content": output}
291 ]}));
292 }
293 let last = messages.len() - 1;
294 messages[last]["content"][0]["cache_control"] = json!({"type": "ephemeral", "ttl": "1h"});
295 messages
296 }
297
298 #[test]
299 fn below_the_threshold_nothing_changes() {
300 let _data = lean_ctx::core::data_dir::isolated_data_dir();
301 let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
302 let mut messages = session(20, 5_000);
303 let before = messages.clone();
304 assert_eq!(elide(&mut messages, THRESHOLD_BYTES), None);
305 assert_eq!(messages, before);
306 }
307
308 #[test]
309 fn old_large_results_leave_as_a_stub_that_names_the_original() {
310 let _data = lean_ctx::core::data_dir::isolated_data_dir();
311 let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
312 let mut messages = session(30, 5_000);
313 messages[2]["content"][0]["content"] = json!("ok");
315 messages[4]["content"][0]["content"] = json!([{"type": "text", "text": "x".repeat(5_000), "cache_control": {"type": "ephemeral"}}]);
316 let original = messages[6]["content"][0]["content"]
317 .as_str()
318 .unwrap()
319 .to_owned();
320 let before = messages.clone();
321
322 let last = elide(&mut messages, 100_000).expect("elided");
323 let boundary = (messages.len() - 8) / 16 * 16;
324 assert_eq!(last, boundary - 2, "the window ends at the stride boundary");
327
328 assert_eq!(messages[2], before[2], "small result untouched");
329 assert_eq!(messages[4], before[4], "nested marker untouched");
330 let stub = messages[6]["content"][0]["content"].as_str().unwrap();
331 assert!(stub.starts_with(STUB_OPEN), "{stub}");
332 let path = if let Some(rest) = stub.split("cat ~/").nth(1) {
333 std::path::PathBuf::from(
334 shell_home(|key| std::env::var_os(key), cfg!(windows)).unwrap(),
335 )
336 .join(rest.trim_end_matches(']').trim_matches('"'))
337 } else {
338 let id = stub
339 .split("id=\"")
340 .nth(1)
341 .unwrap()
342 .split('"')
343 .next()
344 .unwrap();
345 lean_ctx::core::ccr::resolve_tee(id).expect("archive resolves")
346 };
347 if let Some(home) = std::env::var("HOME").ok().filter(|h| !h.is_empty()) {
348 assert!(!stub.contains(&home), "no account path in the stub: {stub}");
349 }
350 assert_eq!(std::fs::read_to_string(&path).unwrap(), original);
352 #[cfg(unix)]
353 {
354 use std::os::unix::fs::PermissionsExt;
355 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
356 assert_eq!(mode & 0o777, 0o600, "the archive is private");
357 }
358 assert!(message_is_elided(&messages[6]));
359 assert_eq!(
360 messages[boundary..],
361 before[boundary..],
362 "the live window, with its cache marker, is untouched"
363 );
364
365 let once = messages.clone();
368 std::fs::remove_file(&path).unwrap();
369 let mut again = before.clone();
370 elide(&mut again, 100_000);
371 assert_eq!(again, once, "content-deterministic stub (#498)");
372 assert_eq!(std::fs::read_to_string(&path).unwrap(), original);
373 }
374
375 fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<std::ffi::OsString> {
376 let pairs: Vec<(String, String)> = pairs
377 .iter()
378 .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
379 .collect();
380 move |key| {
381 pairs
382 .iter()
383 .find(|(k, _)| k == key)
384 .map(|(_, v)| std::ffi::OsString::from(v))
385 }
386 }
387
388 #[test]
389 fn windows_falls_back_to_userprofile_when_home_is_unset() {
390 let profile = env(&[("USERPROFILE", "/Users/me")]);
391 assert_eq!(shell_home(&profile, true), Some("/Users/me".into()));
392 assert_eq!(
393 shell_home(&profile, false),
394 None,
395 "only Windows reads USERPROFILE"
396 );
397 let both = env(&[("HOME", "/home/me"), ("USERPROFILE", "/Users/me")]);
398 assert_eq!(
399 shell_home(&both, true),
400 Some("/home/me".into()),
401 "HOME wins"
402 );
403 let empty = env(&[("HOME", ""), ("USERPROFILE", "/Users/me")]);
404 assert_eq!(shell_home(&empty, true), Some("/Users/me".into()));
405 assert_eq!(shell_home(env(&[]), true), None);
406
407 let home = shell_home(&profile, true);
408 let path = std::path::Path::new("/Users/me/AppData/Local/lean-ctx/tee/proxy_ab12.log");
409 assert_eq!(
410 locator_in(path, home.as_deref()),
411 "cat ~/AppData/Local/lean-ctx/tee/proxy_ab12.log"
412 );
413 }
414
415 #[cfg(windows)]
416 #[test]
417 fn windows_paths_use_forward_slashes_after_the_tilde() {
418 let path = std::path::Path::new(r"C:\Users\me\AppData\Local\lean-ctx\tee\proxy_ab12.log");
419 assert_eq!(
420 locator_in(path, Some(std::ffi::OsStr::new(r"C:\Users\me"))),
421 "cat ~/AppData/Local/lean-ctx/tee/proxy_ab12.log"
422 );
423 }
424
425 #[test]
426 fn a_path_with_spaces_is_quoted_after_the_tilde() {
427 let home = Some(std::ffi::OsStr::new("/Users/me"));
428 let path = std::path::Path::new("/Users/me/My State/lean-ctx/tee/proxy_ab12.log");
429 let once = locator_in(path, home);
430 assert_eq!(once, "cat ~/\"My State/lean-ctx/tee/proxy_ab12.log\"");
431 assert_eq!(locator_in(path, home), once, "byte-stable (#498)");
432
433 let plain = std::path::Path::new("/Users/me/.local/state/lean-ctx/tee/proxy_ab12.log");
434 assert_eq!(
435 locator_in(plain, home),
436 "cat ~/.local/state/lean-ctx/tee/proxy_ab12.log",
437 "plain paths stay unquoted"
438 );
439
440 let dollar = std::path::Path::new("/Users/me/$state/lean-ctx/tee/proxy_ab12.log");
442 assert!(
443 locator_in(dollar, home).starts_with("ctx_expand(id=\"proxy_ab12.log\")"),
444 "{}",
445 locator_in(dollar, home)
446 );
447 let outside = std::path::Path::new("/var/state/lean-ctx/tee/proxy_ab12.log");
449 assert_eq!(
450 locator_in(outside, home),
451 "ctx_expand(id=\"proxy_ab12.log\") (LeanCTX state directory, tee/proxy_ab12.log)"
452 );
453 }
454
455 #[test]
456 fn the_prefix_stays_byte_identical_within_a_stride() {
457 let _data = lean_ctx::core::data_dir::isolated_data_dir();
458 let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
459 let mut turn = session(30, 5_000);
461 let mut next = session(31, 5_000);
462 let mut jump = session(36, 5_000);
463 elide(&mut turn, 100_000);
464 elide(&mut next, 100_000);
465 let last = elide(&mut jump, 100_000).unwrap();
466 let prefix = |m: &[Value]| serde_json::to_vec(&m[..48]).unwrap();
467 assert_eq!(prefix(&turn), prefix(&next));
468 assert_eq!(prefix(&turn), prefix(&jump));
469
470 let forwarded = serde_json::to_vec(&json!({"messages": next})).unwrap();
471 assert!(newly_elided(&forwarded, last), "the stride jump is new");
472 let forwarded = serde_json::to_vec(&json!({"messages": jump})).unwrap();
473 assert!(!newly_elided(&forwarded, last), "already sent elided");
474 }
475}