1use std::io::{Read, Write};
4use std::path::{Path, PathBuf};
5use std::process::{Command, Stdio};
6use std::time::{Duration, Instant};
7
8#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum CompactWindow {
11 Window(u64),
13 Tuned,
15 Invalid(String),
17}
18
19pub fn settings_files(d: &serde_json::Value, home: Option<&Path>) -> Vec<PathBuf> {
25 let mut files = Vec::with_capacity(4);
26 files.push(PathBuf::from(
27 "/Library/Application Support/ClaudeCode/managed-settings.json",
28 ));
29 if let Some(project_dir) = d
30 .get("workspace")
31 .and_then(|w| w.get("project_dir"))
32 .and_then(|v| v.as_str())
33 .filter(|s| !s.trim().is_empty())
34 {
35 let claude_dir = Path::new(project_dir).join(".claude");
36 files.push(claude_dir.join("settings.local.json"));
37 files.push(claude_dir.join("settings.json"));
38 }
39 if let Some(h) = home.filter(|p| !p.as_os_str().is_empty()) {
40 files.push(h.join(".claude").join("settings.json"));
41 }
42 files
43}
44
45fn normalize_model_key(mut s: &str) -> &str {
46 loop {
47 let prev = s;
48 if let Some(without_bracket) = s.strip_suffix(']') {
49 if let Some(idx) = without_bracket.rfind('[') {
50 if idx > 0 {
51 s = &without_bracket[..idx];
52 }
53 }
54 }
55 if s.len() > 9 {
56 let (prefix, suffix) = s.split_at(s.len() - 9);
57 if let Some(date) = suffix.strip_prefix('-') {
58 if date.bytes().all(|b| b.is_ascii_digit()) {
59 s = prefix;
60 }
61 }
62 }
63 if s == prev {
64 break;
65 }
66 }
67 s
68}
69
70fn parse_env_window(raw: &str) -> CompactWindow {
71 let parsed = if let Some(num_str) = raw.strip_suffix('k') {
72 num_str
73 .parse::<u64>()
74 .ok()
75 .and_then(|n| n.checked_mul(1_000))
76 .or_else(|| {
77 num_str
78 .parse::<f64>()
79 .ok()
80 .filter(|f| f.is_finite() && *f >= 0.0)
81 .map(|f| (f * 1_000.0).round() as u64)
82 })
83 } else if let Some(num_str) = raw.strip_suffix('M') {
84 num_str
85 .parse::<u64>()
86 .ok()
87 .and_then(|n| n.checked_mul(1_000_000))
88 .or_else(|| {
89 num_str
90 .parse::<f64>()
91 .ok()
92 .filter(|f| f.is_finite() && *f >= 0.0)
93 .map(|f| (f * 1_000_000.0).round() as u64)
94 })
95 } else {
96 raw.parse::<u64>().ok()
97 };
98
99 match parsed {
100 Some(n) if (100_000..=1_000_000).contains(&n) => CompactWindow::Window(n),
101 Some(n) => CompactWindow::Invalid(format!(
102 "CLAUDE_CODE_AUTO_COMPACT_WINDOW={raw} ({n}) out of range 100000..=1000000"
103 )),
104 None => CompactWindow::Invalid(format!(
105 "CLAUDE_CODE_AUTO_COMPACT_WINDOW={raw} is not a valid window"
106 )),
107 }
108}
109
110fn parse_json_window(path: &Path, key_desc: &str, v: &serde_json::Value) -> CompactWindow {
111 if v.as_str() == Some("auto") {
112 return CompactWindow::Tuned;
113 }
114 let num = v.as_u64().or_else(|| {
115 v.as_f64()
116 .filter(|f| f.is_finite() && f.fract() == 0.0 && *f >= 0.0 && *f <= u64::MAX as f64)
117 .map(|f| f as u64)
118 });
119 match num {
120 Some(n) if (100_000..=1_000_000).contains(&n) => CompactWindow::Window(n),
121 Some(n) => CompactWindow::Invalid(format!(
122 "{}: {key_desc}={n} out of range 100000..=1000000",
123 path.display()
124 )),
125 None => CompactWindow::Invalid(format!("{}: invalid {key_desc} {v}", path.display())),
126 }
127}
128
129pub fn resolve_compact_window<P: AsRef<Path>>(
132 model_id: Option<&str>,
133 env_val: Option<&str>,
134 settings_files: &[P],
135) -> CompactWindow {
136 if let Some(raw) = env_val.map(str::trim).filter(|s| !s.is_empty()) {
137 return parse_env_window(raw);
138 }
139
140 let norm_model = model_id
141 .map(str::trim)
142 .filter(|s| !s.is_empty())
143 .map(normalize_model_key);
144
145 for path_ref in settings_files {
146 let path = path_ref.as_ref();
147 let content = match std::fs::read_to_string(path) {
148 Ok(c) => c,
149 Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
150 Err(e) => return CompactWindow::Invalid(format!("{}: {e}", path.display())),
151 };
152 let val: serde_json::Value = match serde_json::from_str(&content) {
153 Ok(v) => v,
154 Err(e) => return CompactWindow::Invalid(format!("{}: {e}", path.display())),
155 };
156 let Some(root) = val.as_object() else {
157 return CompactWindow::Invalid(format!("{}: expected JSON object", path.display()));
158 };
159
160 if let (Some(target_key), Some(ms_obj)) = (
161 norm_model,
162 root.get("modelSettings").and_then(|v| v.as_object()),
163 ) {
164 let matched = model_id
165 .map(str::trim)
166 .and_then(|raw_id| {
167 ms_obj
168 .get(raw_id)
169 .and_then(|v| v.get("autoCompactWindow"))
170 .map(|acw| (raw_id, acw))
171 })
172 .or_else(|| {
173 ms_obj.iter().find_map(|(k, v)| {
174 (normalize_model_key(k) == target_key)
175 .then(|| v.get("autoCompactWindow").map(|acw| (k.as_str(), acw)))
176 .flatten()
177 })
178 });
179 if let Some((k, acw)) = matched {
180 return parse_json_window(
181 path,
182 &format!("modelSettings.{k}.autoCompactWindow"),
183 acw,
184 );
185 }
186 }
187
188 if let Some(acw) = root.get("autoCompactWindow") {
189 return parse_json_window(path, "autoCompactWindow", acw);
190 }
191 }
192
193 CompactWindow::Tuned
194}
195
196pub fn base_line(d: &serde_json::Value, compact_window: CompactWindow) -> String {
213 let model_name = d
214 .get("model")
215 .and_then(|m| {
216 m.get("display_name")
217 .and_then(|v| v.as_str())
218 .or_else(|| m.as_str())
219 })
220 .filter(|s| !s.trim().is_empty())
221 .unwrap_or("claude");
222
223 let cw = d.get("context_window");
224 let context_part = if let Some(p) = cw
225 .and_then(|c| c.get("used_percentage"))
226 .and_then(|v| v.as_f64())
227 .filter(|&p| !p.is_nan())
228 {
229 let size = cw
230 .and_then(|c| c.get("context_window_size").or_else(|| c.get("size")))
231 .and_then(|v| v.as_u64().or_else(|| v.as_f64().map(|f| f as u64)))
232 .filter(|&s| s > 0);
233
234 if let Some(size) = size {
235 let used = (p / 100.0) * (size as f64);
236 match compact_window {
237 CompactWindow::Window(w) => {
238 let limit = size.min(w);
239 let mut text = format!("context {:.0}k of {}k", used / 1000.0, limit / 1000);
240 if limit > 0 && (100.0 * used / (limit as f64)) >= 60.0 {
241 text.push_str(" — consider /compact or a new session");
242 }
243 Some(text)
244 }
245 CompactWindow::Tuned => {
246 let limit = size;
247 let mut text = format!("context {:.0}k of {}k", used / 1000.0, limit / 1000);
248 if (100.0 * used / (limit as f64)) >= 60.0 {
249 text.push_str(" — consider /compact or a new session");
250 }
251 Some(text)
252 }
253 CompactWindow::Invalid(msg) => Some(format!(
254 "context {:.0}k of {}k (auto-compact window unknown: {msg})",
255 used / 1000.0,
256 size / 1000
257 )),
258 }
259 } else {
260 Some(format!("context {:.0}%", p))
261 }
262 } else {
263 None
264 };
265
266 let cost_part = d
267 .get("cost")
268 .and_then(|c| c.get("total_cost_usd"))
269 .and_then(|v| v.as_f64())
270 .filter(|&c| !c.is_nan())
271 .map(|cost| format!("${:.2} this session", cost));
272
273 let mut parts = Vec::new();
274 parts.push(model_name.to_string());
275 if let Some(cp) = context_part {
276 parts.push(cp);
277 }
278 if let Some(cp) = cost_part {
279 parts.push(cp);
280 }
281 parts.join(" · ")
282}
283
284pub fn blyte_part(totals: &crate::cost::Totals, claude_cost: Option<f64>) -> Option<String> {
289 if totals.runs == 0 {
290 return None;
291 }
292 match claude_cost {
293 Some(cc) => Some(format!(
294 "blyte ${:.2} ({} runs) · total ${:.2}",
295 totals.implementers_usd,
296 totals.runs,
297 cc + totals.implementers_usd
298 )),
299 None => Some(format!(
300 "blyte ${:.2} ({} runs)",
301 totals.implementers_usd, totals.runs
302 )),
303 }
304}
305
306fn run_after(cmd_str: &str, stdin_bytes: &[u8], timeout: Duration) -> Option<String> {
310 let mut cmd = Command::new("sh");
311 cmd.arg("-c").arg(cmd_str);
312 cmd.stdin(Stdio::piped())
313 .stdout(Stdio::piped())
314 .stderr(Stdio::null());
315
316 #[cfg(unix)]
317 {
318 use std::os::unix::process::CommandExt;
319 cmd.process_group(0);
320 }
321
322 let mut child = cmd.spawn().ok()?;
323
324 #[cfg(unix)]
327 unsafe {
328 libc::signal(libc::SIGPIPE, libc::SIG_IGN);
329 }
330 if let Some(mut stdin) = child.stdin.take() {
331 let _ = stdin.write_all(stdin_bytes);
332 let _ = stdin.flush();
333 }
334
335 let stdout_handle = child.stdout.take();
336 let reader = std::thread::spawn(move || {
337 let mut out = Vec::new();
338 if let Some(mut r) = stdout_handle {
339 let _ = std::io::Read::read_to_end(&mut r, &mut out);
340 }
341 out
342 });
343
344 let deadline = Instant::now() + timeout;
345 let status = loop {
346 match child.try_wait() {
347 Ok(Some(s)) => break Some(s),
348 Ok(None) if Instant::now() >= deadline => {
349 #[cfg(unix)]
350 {
351 let pgid = child.id() as i32;
352 if pgid > 0 {
353 unsafe {
354 libc::kill(-pgid, libc::SIGKILL);
355 }
356 } else {
357 let _ = child.kill();
358 }
359 }
360 #[cfg(not(unix))]
361 {
362 let _ = child.kill();
363 }
364 let _ = child.wait();
365 break None;
366 }
367 Ok(None) => std::thread::sleep(Duration::from_millis(10)),
368 Err(_) => {
369 let _ = child.kill();
370 let _ = child.wait();
371 break None;
372 }
373 }
374 };
375
376 let stdout_bytes = reader.join().unwrap_or_default();
377 let status = status?;
378 if !status.success() {
379 return None;
380 }
381 let s = String::from_utf8_lossy(&stdout_bytes);
382 let first_line = s.lines().next()?.trim();
383 if first_line.is_empty() {
384 return None;
385 }
386 Some(first_line.to_string())
387}
388
389pub fn render_statusline(
390 stdin_bytes: &[u8],
391 after: Option<&str>,
392 after_timeout: Duration,
393) -> String {
394 let d: serde_json::Value = serde_json::from_slice(stdin_bytes)
395 .unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new()));
396
397 let resolve = || {
398 let model_id = d
399 .get("model")
400 .and_then(|m| m.get("id"))
401 .and_then(|v| v.as_str())
402 .filter(|s| !s.trim().is_empty());
403 let env_val = std::env::var("CLAUDE_CODE_AUTO_COMPACT_WINDOW").ok();
404 let home = std::env::var_os("HOME").map(PathBuf::from);
405 let files = settings_files(&d, home.as_deref());
406 resolve_compact_window(model_id, env_val.as_deref(), &files)
407 };
408
409 let base = match after {
410 Some(cmd) => {
411 run_after(cmd, stdin_bytes, after_timeout).unwrap_or_else(|| base_line(&d, resolve()))
412 }
413 None => base_line(&d, resolve()),
414 };
415
416 let session_id = d
417 .get("session_id")
418 .and_then(|v| v.as_str())
419 .filter(|s| !s.trim().is_empty());
420
421 let blyte_p = match session_id {
422 Some(sid) => {
423 let entries = crate::usage_log::default_path()
424 .as_deref()
425 .map(crate::usage_log::read)
426 .unwrap_or_default();
427 let totals = crate::cost::totals(&entries, Some(sid), None, None);
428 let claude_cost = d
429 .get("cost")
430 .and_then(|c| c.get("total_cost_usd"))
431 .and_then(|v| v.as_f64());
432 blyte_part(&totals, claude_cost)
433 }
434 None => None,
435 };
436
437 match blyte_p {
438 Some(part) => format!("{base} · {part}"),
439 None => base,
440 }
441}
442
443pub const DEFAULT_AFTER_TIMEOUT: Duration = Duration::from_secs(5);
445
446pub const AFTER_TIMEOUT_ENV: &str = "BLYTE_STATUSLINE_AFTER_TIMEOUT_MS";
448
449fn parse_after_timeout_ms(raw: &std::ffi::OsStr) -> Result<Duration, String> {
450 let display = raw.to_string_lossy();
451 if let Some(valid) = raw.to_str() {
452 if !valid.is_empty() && valid.bytes().all(|b| b.is_ascii_digit()) {
453 if let Ok(ms) = valid.parse::<u64>() {
454 if ms > 0 {
455 return Ok(Duration::from_millis(ms));
456 }
457 }
458 }
459 }
460 Err(format!(
461 "blyte: invalid {AFTER_TIMEOUT_ENV}={display:?}: expected a whole number greater than 0"
462 ))
463}
464
465pub fn run(args: &crate::cli::StatuslineArgs) -> i32 {
467 let after_timeout = match std::env::var_os(AFTER_TIMEOUT_ENV) {
468 Some(raw) => match parse_after_timeout_ms(&raw) {
469 Ok(timeout) => timeout,
470 Err(msg) => {
471 eprintln!("{msg}");
472 return 2;
473 }
474 },
475 None => DEFAULT_AFTER_TIMEOUT,
476 };
477 let mut stdin_bytes = Vec::new();
478 let _ = std::io::stdin().read_to_end(&mut stdin_bytes);
479 let line = render_statusline(&stdin_bytes, args.after.as_deref(), after_timeout);
480 println!("{line}");
481 0
482}