Skip to main content

termden_core/
stats.rs

1//! Per-harness usage, read from the agents' own session data.
2//!
3//! termden does not count tokens itself and persists nothing: Claude Code's
4//! transcript JSONL and opencode's SQLite database are the source of truth, so
5//! the numbers match what the agents report and survive app restarts.
6//!
7//! Every read here is read-only and best effort. A missing or half-written
8//! file means "unknown" (`None`), never zero.
9
10use std::collections::HashMap;
11use std::fs::{self, File};
12use std::io::{BufRead, BufReader, Seek, SeekFrom};
13use std::path::{Path, PathBuf};
14use std::sync::Mutex;
15use std::time::{Duration, SystemTime};
16
17use serde_json::Value;
18
19use crate::state::runtime_dir;
20use crate::{HarnessId, HarnessKind};
21
22/// Token counts as the providers report them.
23#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
24pub struct Usage {
25    pub input: u64,
26    pub output: u64,
27    pub cache_read: u64,
28    pub cache_write: u64,
29}
30
31impl Usage {
32    /// Prompt tokens the model processed from scratch. Claude reports these
33    /// split into uncached input and cache writes; both are new input.
34    pub fn fresh_input(self) -> u64 {
35        self.input + self.cache_write
36    }
37
38    /// Everything that passed through the model, cache included.
39    pub fn total(self) -> u64 {
40        self.input + self.output + self.cache_read + self.cache_write
41    }
42
43    pub fn add(&mut self, other: Usage) {
44        self.input += other.input;
45        self.output += other.output;
46        self.cache_read += other.cache_read;
47        self.cache_write += other.cache_write;
48    }
49
50    fn sub(&mut self, other: Usage) {
51        self.input -= other.input.min(self.input);
52        self.output -= other.output.min(self.output);
53        self.cache_read -= other.cache_read.min(self.cache_read);
54        self.cache_write -= other.cache_write.min(self.cache_write);
55    }
56}
57
58/// Every Claude Code session a harness has been in, oldest first: its
59/// SessionStart hook (`termdenctl session-hook`) adds one line on start,
60/// `/clear` and `--resume`.
61///
62/// A harness launched without that hook has none until it is restarted.
63pub fn claude_sessions(id: HarnessId) -> Vec<String> {
64    fs::read_to_string(harness_dir(id).join("session.id"))
65        .unwrap_or_default()
66        .lines()
67        .map(str::trim)
68        .filter(|line| !line.is_empty())
69        .map(String::from)
70        .collect()
71}
72
73/// One plan limit window (a 5-hour session, a week, a month).
74#[derive(Debug, Clone, Copy, PartialEq)]
75pub struct Limit {
76    pub label: &'static str,
77    pub used_percent: f64,
78    /// Unix seconds.
79    pub resets_at: Option<u64>,
80}
81
82/// What the status line input of one Claude tile says.
83#[derive(Debug, Clone, PartialEq)]
84pub struct ClaudeStatus {
85    /// Unix seconds the status line last ran.
86    pub at: u64,
87    pub context_percent: Option<f64>,
88    /// Plan limits; empty for API-key sessions.
89    pub limits: Vec<Limit>,
90}
91
92/// The status line input `termdenctl statusline` saved for a harness.
93pub fn claude_status(id: HarnessId) -> Option<ClaudeStatus> {
94    let path = harness_dir(id).join("status.json");
95    let at = fs::metadata(&path)
96        .and_then(|meta| meta.modified())
97        .ok()?
98        .duration_since(SystemTime::UNIX_EPOCH)
99        .ok()?
100        .as_secs();
101    parse_status(&fs::read_to_string(path).ok()?, at)
102}
103
104fn parse_status(text: &str, at: u64) -> Option<ClaudeStatus> {
105    let value: Value = serde_json::from_str(text).ok()?;
106    let limits = [("5h session", "five_hour"), ("week", "seven_day")]
107        .into_iter()
108        .filter_map(|(label, key)| {
109            let limit = &value["rate_limits"][key];
110            Some(Limit {
111                label,
112                used_percent: limit["used_percentage"].as_f64()?,
113                resets_at: limit["resets_at"].as_u64(),
114            })
115        })
116        .collect();
117    Some(ClaudeStatus {
118        at,
119        context_percent: value["context_window"]["used_percentage"].as_f64(),
120        limits,
121    })
122}
123
124/// opencode Go plan limits, asked of opencode itself (it holds the key):
125/// `opencode api --standalone GET /api/experimental/usage/limits`. Takes a
126/// couple of seconds; `None` when opencode is missing or the account has no Go
127/// plan.
128pub fn opencode_go_limits() -> Option<Vec<Limit>> {
129    let out = std::process::Command::new("timeout")
130        .args(["30", "opencode", "api", "--standalone", "GET"])
131        .arg("/api/experimental/usage/limits")
132        .current_dir(std::env::temp_dir())
133        .stdin(std::process::Stdio::null())
134        .stderr(std::process::Stdio::null())
135        .output()
136        .ok()?;
137    out.status.success().then_some(())?;
138    parse_go_limits(&String::from_utf8_lossy(&out.stdout))
139}
140
141fn parse_go_limits(text: &str) -> Option<Vec<Limit>> {
142    let value: Value = serde_json::from_str(text).ok()?;
143    let go = value["data"]["go"].as_object()?;
144    let limits: Vec<Limit> = [
145        ("5h session", "rolling"),
146        ("week", "weekly"),
147        ("month", "monthly"),
148    ]
149    .into_iter()
150    .filter_map(|(label, key)| {
151        let limit = go.get(key)?;
152        Some(Limit {
153            label,
154            used_percent: limit["percent"].as_f64()?,
155            resets_at: limit["resetsAt"].as_u64().map(|ms| ms / 1000),
156        })
157    })
158    .collect();
159    (!limits.is_empty()).then_some(limits)
160}
161
162pub fn harness_dir(id: HarnessId) -> PathBuf {
163    runtime_dir().join("harness").join(id.raw().to_string())
164}
165
166fn claude_dir() -> Option<PathBuf> {
167    if let Ok(dir) = std::env::var("CLAUDE_CONFIG_DIR")
168        && !dir.is_empty()
169    {
170        return Some(PathBuf::from(dir));
171    }
172    let home = std::env::var("HOME").ok()?;
173    Some(Path::new(&home).join(".claude"))
174}
175
176fn opencode_db() -> Option<PathBuf> {
177    let data = match std::env::var("XDG_DATA_HOME") {
178        Ok(dir) if !dir.is_empty() => PathBuf::from(dir),
179        _ => PathBuf::from(std::env::var("HOME").ok()?).join(".local/share"),
180    };
181    let path = data.join("opencode").join("opencode.db");
182    path.is_file().then_some(path)
183}
184
185fn opencode_config_dir() -> Option<PathBuf> {
186    let config = match std::env::var("XDG_CONFIG_HOME") {
187        Ok(dir) if !dir.is_empty() => PathBuf::from(dir),
188        _ => PathBuf::from(std::env::var("HOME").ok()?).join(".config"),
189    };
190    Some(config.join("opencode"))
191}
192
193/// Incremental reader for one Claude Code session: its transcript plus the
194/// subagent transcripts Claude Code keeps in `<session>/subagents/`.
195///
196/// Transcripts grow to tens of megabytes, so each file is only read from its
197/// last offset and usage is kept per assistant message id: Claude Code repeats
198/// the same message as it streams and for each content block (and a forked
199/// subagent starts with a copy of its parent's last message), and only the
200/// last copy carries the final count.
201pub struct ClaudeLog {
202    session: String,
203    path: Option<PathBuf>,
204    offsets: HashMap<PathBuf, u64>,
205    seen: HashMap<String, Usage>,
206    usage: Usage,
207}
208
209impl ClaudeLog {
210    pub fn new(session: &str) -> Self {
211        Self {
212            session: session.to_string(),
213            path: None,
214            offsets: HashMap::new(),
215            seen: HashMap::new(),
216            usage: Usage::default(),
217        }
218    }
219
220    pub fn usage(&self) -> Usage {
221        self.usage
222    }
223
224    /// Whether the transcript was found; before the first message it is not
225    /// written yet and the agent's usage is simply unknown.
226    pub fn found(&self) -> bool {
227        self.path.is_some()
228    }
229
230    /// Where the transcript lives: `~/.claude/projects/<encoded cwd>/<id>.jsonl`
231    /// but the encoding is not ours to guess, so look for the id.
232    fn locate(&mut self) -> Option<PathBuf> {
233        if let Some(path) = &self.path
234            && path.exists()
235        {
236            return Some(path.clone());
237        }
238        let projects = claude_dir()?.join("projects");
239        let file = format!("{}.jsonl", self.session);
240        self.path = fs::read_dir(&projects)
241            .ok()?
242            .flatten()
243            .map(|entry| entry.path().join(&file))
244            .find(|candidate| candidate.is_file());
245        self.path.clone()
246    }
247
248    /// Read whatever was appended since last time. Returns whether the numbers
249    /// moved.
250    pub fn refresh(&mut self) -> bool {
251        let Some(main) = self.locate() else {
252            return false;
253        };
254        let mut files = vec![main.clone()];
255        if let Ok(entries) = fs::read_dir(main.with_extension("").join("subagents")) {
256            files.extend(
257                entries
258                    .flatten()
259                    .map(|entry| entry.path())
260                    .filter(|path| path.extension().is_some_and(|ext| ext == "jsonl")),
261            );
262        }
263        // A file replaced under us (shorter than what we read) would leave its
264        // old messages counted; start over rather than read junk.
265        let shrunk = files.iter().any(|file| {
266            let offset = self.offsets.get(file).copied().unwrap_or(0);
267            fs::metadata(file).is_ok_and(|meta| meta.len() < offset)
268        });
269        if shrunk {
270            self.offsets.clear();
271            self.seen.clear();
272            self.usage = Usage::default();
273        }
274        let mut changed = shrunk;
275        for file in files {
276            changed |= self.read(&file);
277        }
278        changed
279    }
280
281    fn read(&mut self, path: &Path) -> bool {
282        let offset = self.offsets.get(path).copied().unwrap_or(0);
283        if fs::metadata(path).map_or(true, |meta| meta.len() == offset) {
284            return false;
285        }
286        let Ok(mut file) = File::open(path) else {
287            return false;
288        };
289        if file.seek(SeekFrom::Start(offset)).is_err() {
290            return false;
291        }
292        let mut reader = BufReader::with_capacity(64 * 1024, file);
293        let mut changed = false;
294        let mut read_to = offset;
295        let mut line = String::new();
296        loop {
297            line.clear();
298            let Ok(read) = reader.read_line(&mut line) else {
299                break;
300            };
301            // A write may be caught mid-line; leave it for the next refresh.
302            if read == 0 || !line.ends_with('\n') {
303                break;
304            }
305            read_to += read as u64;
306            changed |= self.parse(&line);
307        }
308        self.offsets.insert(path.to_path_buf(), read_to);
309        changed
310    }
311
312    fn parse(&mut self, line: &str) -> bool {
313        if !line.contains("\"usage\"") {
314            return false;
315        }
316        let Ok(value) = serde_json::from_str::<Value>(line) else {
317            return false;
318        };
319        let Some(message) = value.get("message") else {
320            return false;
321        };
322        let Some(usage) = message.get("usage") else {
323            return false;
324        };
325        // Without an id the copy cannot be deduplicated; leave it out rather
326        // than inflate the total.
327        let Some(id) = message.get("id").and_then(Value::as_str) else {
328            return false;
329        };
330        let count = |key: &str| usage.get(key).and_then(Value::as_u64).unwrap_or(0);
331        let usage = Usage {
332            input: count("input_tokens"),
333            output: count("output_tokens"),
334            cache_read: count("cache_read_input_tokens"),
335            cache_write: count("cache_creation_input_tokens"),
336        };
337        if let Some(previous) = self.seen.insert(id.to_string(), usage) {
338            self.usage.sub(previous);
339        }
340        self.usage.add(usage);
341        true
342    }
343}
344
345/// Tokens an opencode session (and its child sessions) used, from its database.
346///
347/// Newer opencode builds write `session_v2`, older ones `session`; both carry
348/// the same token columns. Unknown schemas mean `None`, not zero.
349pub fn opencode_usage(session: &str) -> Option<Usage> {
350    use rusqlite::{Connection, OpenFlags};
351
352    let db = opencode_db()?;
353    let flags = OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX;
354    let conn = Connection::open_with_flags(db, flags).ok()?;
355    let _ = conn.busy_timeout(Duration::from_millis(400));
356    for table in ["session_v2", "session"] {
357        // A missing session still returns one row of zeros, so count as well.
358        let sql = format!(
359            "SELECT COUNT(*), COALESCE(SUM(tokens_input),0), COALESCE(SUM(tokens_output),0), \
360             COALESCE(SUM(tokens_cache_read),0), COALESCE(SUM(tokens_cache_write),0) \
361             FROM {table} WHERE id = ?1 OR parent_id = ?1"
362        );
363        let row = conn.query_row(&sql, [session], |row| {
364            Ok((
365                row.get::<_, i64>(0)?,
366                Usage {
367                    input: row.get::<_, i64>(1)? as u64,
368                    output: row.get::<_, i64>(2)? as u64,
369                    cache_read: row.get::<_, i64>(3)? as u64,
370                    cache_write: row.get::<_, i64>(4)? as u64,
371                },
372            ))
373        });
374        if let Ok((count, usage)) = row
375            && count > 0
376        {
377            return Some(usage);
378        }
379    }
380    None
381}
382
383/// Prompt-cache lifetime assumed for a model with too little history to
384/// measure: the Go gateway keeps a prefix about five minutes.
385pub const OPENCODE_DEFAULT_TTL_MS: u64 = 5 * 60 * 1000;
386
387/// A session's latest finished reply: when it finished (unix ms), the context
388/// it read (input + cache), and its `provider/model`.
389pub struct LastReply {
390    pub completed_ms: u64,
391    pub context: u64,
392    pub model: String,
393}
394
395pub fn opencode_last_reply(session: &str) -> Option<LastReply> {
396    use rusqlite::{Connection, OpenFlags};
397
398    let flags = OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX;
399    let conn = Connection::open_with_flags(opencode_db()?, flags).ok()?;
400    let _ = conn.busy_timeout(Duration::from_millis(400));
401    conn.query_row(
402        "SELECT json_extract(data,'$.time.completed'), \
403                COALESCE(json_extract(data,'$.tokens.input'),0) \
404                + COALESCE(json_extract(data,'$.tokens.cache.read'),0) \
405                + COALESCE(json_extract(data,'$.tokens.cache.write'),0), \
406                json_extract(data,'$.model.providerID') || '/' || json_extract(data,'$.model.id') \
407         FROM session_message \
408         WHERE session_id = ?1 AND type = 'assistant' \
409           AND json_extract(data,'$.time.completed') IS NOT NULL \
410         ORDER BY seq DESC LIMIT 1",
411        [session],
412        |row| {
413            Ok(LastReply {
414                completed_ms: row.get::<_, i64>(0)? as u64,
415                context: row.get::<_, i64>(1)? as u64,
416                model: row.get::<_, Option<String>>(2)?.unwrap_or_default(),
417            })
418        },
419    )
420    .ok()
421}
422
423/// How long a model's prompt cache really lived, measured from the user's own
424/// history: every reply that followed another reply of the same model after a
425/// pause of a minute or more, with whether it still read most of the previous
426/// context from cache. `(pause seconds, was a hit)`.
427pub fn opencode_gap_samples(model: &str) -> Vec<(u64, bool)> {
428    use rusqlite::{Connection, OpenFlags};
429
430    let flags = OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX;
431    let Some(conn) = opencode_db().and_then(|db| Connection::open_with_flags(db, flags).ok())
432    else {
433        return Vec::new();
434    };
435    let _ = conn.busy_timeout(Duration::from_millis(2000));
436    let sql = "WITH a AS (SELECT session_id, seq, \
437          json_extract(data,'$.model.providerID') || '/' || json_extract(data,'$.model.id') AS m, \
438          json_extract(data,'$.time.created') AS c, json_extract(data,'$.time.completed') AS d, \
439          COALESCE(json_extract(data,'$.tokens.input'),0) + COALESCE(json_extract(data,'$.tokens.cache.read'),0) \
440            + COALESCE(json_extract(data,'$.tokens.cache.write'),0) AS ctx, \
441          COALESCE(json_extract(data,'$.tokens.cache.read'),0) AS rd \
442        FROM session_message WHERE type = 'assistant' AND json_extract(data,'$.time.completed') IS NOT NULL), \
443      p AS (SELECT m, (c - LAG(d) OVER w) / 1000 AS gap, LAG(ctx) OVER w AS pctx, rd, LAG(m) OVER w AS pm \
444        FROM a WINDOW w AS (PARTITION BY session_id ORDER BY seq)) \
445      SELECT gap, rd >= 0.5 * pctx FROM p WHERE m = ?1 AND pm = m AND pctx > 20000 AND gap >= 60";
446    let Ok(mut stmt) = conn.prepare(sql) else {
447        return Vec::new();
448    };
449    let Ok(rows) = stmt.query_map([model], |row| {
450        Ok((row.get::<_, i64>(0)? as u64, row.get::<_, bool>(1)?))
451    }) else {
452        return Vec::new();
453    };
454    rows.flatten().collect()
455}
456
457/// Cache lifetime (ms) from pause samples: walk pause buckets upward and keep
458/// extending while at least 60% of replies in a bucket (three or more of
459/// them) still hit; stop at the first bucket that mostly misses.
460pub fn cache_ttl_ms(samples: &[(u64, bool)]) -> u64 {
461    const LADDER_MIN: [u64; 9] = [5, 10, 20, 30, 60, 120, 240, 720, 1440];
462    let mut ttl = OPENCODE_DEFAULT_TTL_MS;
463    let mut low = 0;
464    for minutes in LADDER_MIN {
465        let high = minutes * 60;
466        let bucket: Vec<bool> = samples
467            .iter()
468            .filter(|(gap, _)| *gap > low && *gap <= high)
469            .map(|(_, hit)| *hit)
470            .collect();
471        low = high;
472        if bucket.len() < 3 {
473            continue;
474        }
475        let hits = bucket.iter().filter(|hit| **hit).count();
476        if hits * 10 < bucket.len() * 6 {
477            break;
478        }
479        ttl = high * 1000;
480    }
481    ttl
482}
483
484/// The opencode sessions a termden tile has used since `since_ms`, found
485/// through the per-harness instructions file opencode records with every
486/// session (`/new` adds one).
487///
488/// `--session <unknown-id>` is not an option: the TUI ignores it and resumes
489/// the previous session instead. The instructions path is unique to the
490/// harness.
491pub fn opencode_sessions(id: HarnessId, since_ms: u64) -> Vec<String> {
492    use rusqlite::{Connection, OpenFlags};
493
494    let mut sessions = Vec::new();
495    let Some(db) = opencode_db() else {
496        return sessions;
497    };
498    let flags = OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX;
499    let Ok(conn) = Connection::open_with_flags(db, flags) else {
500        return sessions;
501    };
502    let _ = conn.busy_timeout(Duration::from_millis(400));
503    let needle = format!("termden/harness/{}/instructions.md", id.raw());
504    let Ok(mut stmt) = conn.prepare(
505        "SELECT s.id, i.initial_values FROM session_v2 s \
506             JOIN instruction_state i ON i.session_id = s.id \
507             WHERE s.parent_id IS NULL AND s.time_created >= ?1 \
508             ORDER BY s.time_created",
509    ) else {
510        return sessions;
511    };
512    let Ok(mut rows) = stmt.query([since_ms as i64]) else {
513        return sessions;
514    };
515    loop {
516        let row = match rows.next() {
517            Ok(Some(row)) => row,
518            _ => return sessions,
519        };
520        let Ok(session) = row.get::<_, String>(0) else {
521            continue;
522        };
523        let Ok(initial) = row.get::<_, String>(1) else {
524            continue;
525        };
526        let Ok(values) = serde_json::from_str::<Value>(&initial) else {
527            continue;
528        };
529        let Some(hash) = values.get("core/instructions").and_then(Value::as_str) else {
530            continue;
531        };
532        let blob: Option<String> = conn
533            .query_row(
534                "SELECT value FROM instruction_blob WHERE hash = ?1",
535                [hash],
536                |row| row.get(0),
537            )
538            .ok();
539        if blob.is_some_and(|blob| blob.contains(&needle)) {
540            sessions.push(session);
541        }
542    }
543}
544
545/// MCP servers that will actually be on for a harness started in `cwd`.
546///
547/// Read from the config termden writes for the harness, the project files the
548/// agent loads itself (`.mcp.json`, `opencode.json`), the user's config
549/// (`~/.claude.json` user and project scope, enabled Claude plugins, opencode's
550/// global config). Not listed: claude.ai connectors and servers only an
551/// agent's CLI knows about.
552pub fn mcp_servers(cwd: &Path, id: HarnessId, kind: HarnessKind) -> Vec<String> {
553    let mut names: Vec<String> = Vec::new();
554    match kind {
555        HarnessKind::ClaudeCode => {
556            push_keys(&mut names, &harness_dir(id).join("mcp.json"), "mcpServers");
557            push_keys(&mut names, &cwd.join(".mcp.json"), "mcpServers");
558            for name in claude_json_servers(cwd)
559                .into_iter()
560                .chain(claude_plugin_servers())
561            {
562                push_name(&mut names, name);
563            }
564        }
565        HarnessKind::OpenCode => {
566            push_mcp_block(&mut names, &harness_dir(id).join("opencode.json"));
567            for name in ["opencode.json", "opencode.jsonc"] {
568                push_mcp_block(&mut names, &cwd.join(name));
569                push_mcp_block(&mut names, &cwd.join(".opencode").join(name));
570            }
571            if let Some(dir) = opencode_config_dir() {
572                for name in ["opencode.json", "opencode.jsonc"] {
573                    push_mcp_block(&mut names, &dir.join(name));
574                }
575            }
576        }
577        HarnessKind::Pi | HarnessKind::Shell => {}
578    }
579    names.sort();
580    names
581}
582
583fn push_name(names: &mut Vec<String>, name: String) {
584    if !names.iter().any(|existing| existing == &name) {
585        names.push(name);
586    }
587}
588
589fn push_keys(names: &mut Vec<String>, path: &Path, key: &str) {
590    let Some(value) = load_json(path) else {
591        return;
592    };
593    let Some(servers) = value.get(key).and_then(Value::as_object) else {
594        return;
595    };
596    for name in servers.keys() {
597        push_name(names, name.clone());
598    }
599}
600
601/// `{"mcp": {"name": {"enabled": false, ...}}}`; disabled servers are off.
602/// Some opencode configs wrap the servers one level deeper
603/// (`{"mcp": {"servers": {"name": ...}}}`), so unwrap that too.
604fn push_mcp_block(names: &mut Vec<String>, path: &Path) {
605    let Some(value) = load_json(path) else {
606        return;
607    };
608    let Some(servers) = value.get("mcp").and_then(Value::as_object) else {
609        return;
610    };
611    for (name, config) in servers {
612        let server = config.get("type").is_some()
613            || config.get("command").is_some()
614            || config.get("url").is_some();
615        if server {
616            if enabled(config) {
617                push_name(names, name.clone());
618            }
619        } else if let Some(inner) = config.as_object() {
620            for (name, config) in inner {
621                if config.is_object() && enabled(config) {
622                    push_name(names, name.clone());
623                }
624            }
625        }
626    }
627}
628
629fn enabled(config: &Value) -> bool {
630    !config
631        .get("enabled")
632        .and_then(Value::as_bool)
633        .is_some_and(|enabled| !enabled)
634}
635
636/// Config files may be `.jsonc` (opencode documents that flavour): comments
637/// and trailing commas are legal there, not in `serde_json`.
638fn load_json(path: &Path) -> Option<Value> {
639    let text = fs::read_to_string(path).ok()?;
640    serde_json::from_str(&text)
641        .ok()
642        .or_else(|| serde_json::from_str(&strip_jsonc(&text)).ok())
643}
644
645fn strip_jsonc(text: &str) -> String {
646    let bytes = text.as_bytes();
647    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
648    let mut string = false;
649    let mut escaped = false;
650    let mut i = 0;
651    while i < bytes.len() {
652        let byte = bytes[i];
653        if string {
654            out.push(byte);
655            if escaped {
656                escaped = false;
657            } else if byte == b'\\' {
658                escaped = true;
659            } else if byte == b'"' {
660                string = false;
661            }
662            i += 1;
663            continue;
664        }
665        if byte == b'"' {
666            string = true;
667            out.push(byte);
668            i += 1;
669        } else if byte == b'/' && bytes.get(i + 1) == Some(&b'/') {
670            while i < bytes.len() && bytes[i] != b'\n' {
671                i += 1;
672            }
673        } else if byte == b'/' && bytes.get(i + 1) == Some(&b'*') {
674            i += 2;
675            while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
676                i += 1;
677            }
678            i = (i + 2).min(bytes.len());
679        } else {
680            out.push(byte);
681            i += 1;
682        }
683    }
684    // Drop commas that are followed only by whitespace and a closing bracket.
685    let mut cleaned: Vec<u8> = Vec::with_capacity(out.len());
686    let mut string = false;
687    let mut escaped = false;
688    for (index, &byte) in out.iter().enumerate() {
689        if string {
690            cleaned.push(byte);
691            if escaped {
692                escaped = false;
693            } else if byte == b'\\' {
694                escaped = true;
695            } else if byte == b'"' {
696                string = false;
697            }
698            continue;
699        }
700        if byte == b'"' {
701            string = true;
702            cleaned.push(byte);
703            continue;
704        }
705        if byte == b',' {
706            let next = out[index + 1..]
707                .iter()
708                .find(|b| !b.is_ascii_whitespace())
709                .copied();
710            if matches!(next, Some(b'}') | Some(b']')) {
711                continue;
712            }
713        }
714        cleaned.push(byte);
715    }
716    String::from_utf8_lossy(&cleaned).into_owned()
717}
718
719/// MCP servers from `~/.claude.json`: user scope plus the project scope of
720/// `cwd`. That file is large and rewritten often, so keep the parsed names
721/// until its mtime moves.
722fn claude_json_servers(cwd: &Path) -> Vec<String> {
723    type Parsed = (Vec<String>, HashMap<String, Vec<String>>);
724    static CACHE: Mutex<Option<(SystemTime, Parsed)>> = Mutex::new(None);
725    let Some(path) = std::env::var("HOME")
726        .ok()
727        .map(|home| Path::new(&home).join(".claude.json"))
728    else {
729        return Vec::new();
730    };
731    let Ok(modified) = fs::metadata(&path).and_then(|meta| meta.modified()) else {
732        return Vec::new();
733    };
734    let pick = |(user, projects): &Parsed| {
735        let mut names = user.clone();
736        names.extend(
737            projects
738                .get(&*cwd.to_string_lossy())
739                .into_iter()
740                .flatten()
741                .cloned(),
742        );
743        names
744    };
745    let mut cache = CACHE.lock().unwrap_or_else(|error| error.into_inner());
746    if let Some((stamp, parsed)) = cache.as_ref()
747        && *stamp == modified
748    {
749        return pick(parsed);
750    }
751    let keys = |value: &Value| -> Vec<String> {
752        value
753            .get("mcpServers")
754            .and_then(Value::as_object)
755            .map(|servers| servers.keys().cloned().collect())
756            .unwrap_or_default()
757    };
758    let value = load_json(&path).unwrap_or(Value::Null);
759    let projects = value
760        .get("projects")
761        .and_then(Value::as_object)
762        .map(|projects| {
763            projects
764                .iter()
765                .map(|(dir, project)| (dir.clone(), keys(project)))
766                .filter(|(_, names)| !names.is_empty())
767                .collect()
768        })
769        .unwrap_or_default();
770    let parsed = (keys(&value), projects);
771    let names = pick(&parsed);
772    *cache = Some((modified, parsed));
773    names
774}
775
776/// MCP servers bundled with the Claude Code plugins enabled in
777/// `~/.claude/settings.json`: a plugin's `.mcp.json`, or `mcpServers` in its
778/// manifest (inline or a path).
779fn claude_plugin_servers() -> Vec<String> {
780    let mut names = Vec::new();
781    let Some(dir) = claude_dir() else {
782        return names;
783    };
784    let Some(settings) = load_json(&dir.join("settings.json")) else {
785        return names;
786    };
787    let Some(installed) = load_json(&dir.join("plugins").join("installed_plugins.json")) else {
788        return names;
789    };
790    let enabled = settings
791        .get("enabledPlugins")
792        .and_then(Value::as_object)
793        .into_iter()
794        .flatten()
795        .filter(|(_, on)| on.as_bool() == Some(true));
796    for (plugin, _) in enabled {
797        let Some(root) = installed["plugins"][plugin][0]["installPath"].as_str() else {
798            continue;
799        };
800        let root = Path::new(root);
801        let manifest = load_json(&root.join(".claude-plugin").join("plugin.json"));
802        let servers = match manifest.as_ref().map(|manifest| &manifest["mcpServers"]) {
803            Some(Value::Object(inline)) => Some(Value::Object(inline.clone())),
804            Some(Value::String(file)) => load_json(&root.join(file)),
805            _ => load_json(&root.join(".mcp.json")),
806        };
807        // `.mcp.json` files come with and without the `mcpServers` wrapper.
808        let servers = servers.map(|value| match value.get("mcpServers") {
809            Some(inner) => inner.clone(),
810            None => value,
811        });
812        for name in servers
813            .as_ref()
814            .and_then(Value::as_object)
815            .into_iter()
816            .flatten()
817            .map(|(name, _)| name)
818        {
819            push_name(&mut names, name.clone());
820        }
821    }
822    names
823}
824
825/// Compact token count for the sidebar: `842`, `9.8k`, `98k`, `1.28M`.
826/// Trailing zeros are dropped (`1M`, not `1.00M`).
827pub fn short_tokens(tokens: u64) -> String {
828    match tokens {
829        0..=999 => tokens.to_string(),
830        1_000..=9_999 => format!("{}k", trim_zeros(format!("{:.1}", tokens as f64 / 1_000.))),
831        10_000..=999_999 => format!("{:.0}k", tokens as f64 / 1_000.),
832        1_000_000..=9_999_999 => format!(
833            "{}M",
834            trim_zeros(format!("{:.2}", tokens as f64 / 1_000_000.))
835        ),
836        _ => format!("{:.0}M", tokens as f64 / 1_000_000.),
837    }
838}
839
840fn trim_zeros(mut text: String) -> String {
841    if text.contains('.') {
842        while text.ends_with('0') {
843            text.pop();
844        }
845        if text.ends_with('.') {
846            text.pop();
847        }
848    }
849    text
850}
851
852/// How long ago something started: `<1m`, `41m`, `2h 14m`, `3d 4h`.
853pub fn short_age(seconds: u64) -> String {
854    let minutes = seconds / 60;
855    let hours = minutes / 60;
856    let days = hours / 24;
857    match seconds {
858        0..=59 => "<1m".into(),
859        60..=3599 => format!("{minutes}m"),
860        3600..=86_399 => match minutes % 60 {
861            0 => format!("{hours}h"),
862            rest => format!("{hours}h {rest:02}m"),
863        },
864        _ => format!("{days}d {}h", hours % 24),
865    }
866}
867
868#[cfg(test)]
869mod tests {
870    use super::*;
871
872    fn assistant(id: &str, input: u64, output: u64) -> String {
873        format!(
874            r#"{{"type":"assistant","message":{{"id":"{id}","usage":{{"input_tokens":{input},"output_tokens":{output},"cache_read_input_tokens":10,"cache_creation_input_tokens":5}}}}}}"#
875        )
876    }
877
878    #[test]
879    fn repeated_message_ids_are_counted_once_with_their_last_numbers() {
880        let mut log = ClaudeLog::new("session");
881        assert!(log.parse(&assistant("a", 100, 10)));
882        // The same message is written again as it streams; keep the newer one.
883        assert!(log.parse(&assistant("a", 140, 12)));
884        assert!(log.parse(&assistant("b", 7, 3)));
885        assert_eq!(
886            log.usage(),
887            Usage {
888                input: 147,
889                output: 15,
890                cache_read: 20,
891                cache_write: 10,
892            }
893        );
894    }
895
896    #[test]
897    fn subagent_transcripts_count_once_and_appends_are_picked_up() {
898        let dir = std::env::temp_dir().join(format!("termden-claude-{}", std::process::id()));
899        let subagents = dir.join("s").join("subagents");
900        fs::create_dir_all(&subagents).unwrap();
901        let main = dir.join("s.jsonl");
902        fs::write(&main, assistant("parent", 100, 10) + "\n").unwrap();
903        // A forked subagent starts with a copy of the parent's message.
904        let sub = [assistant("parent", 100, 10), assistant("child", 50, 5)].join("\n");
905        fs::write(subagents.join("agent-a.jsonl"), sub + "\n").unwrap();
906        let mut log = ClaudeLog::new("s");
907        log.path = Some(main.clone());
908        assert!(log.refresh());
909        assert_eq!((log.usage().input, log.usage().output), (150, 15));
910        assert!(!log.refresh());
911        let mut file = fs::OpenOptions::new().append(true).open(&main).unwrap();
912        std::io::Write::write_all(&mut file, (assistant("next", 1, 1) + "\n").as_bytes()).unwrap();
913        assert!(log.refresh());
914        assert_eq!(log.usage().input, 151);
915        let _ = fs::remove_dir_all(&dir);
916    }
917
918    #[test]
919    fn lines_without_a_message_id_are_ignored() {
920        let mut log = ClaudeLog::new("session");
921        let line =
922            r#"{"type":"assistant","message":{"usage":{"input_tokens":5,"output_tokens":5}}}"#;
923        assert!(!log.parse(line));
924        assert_eq!(log.usage(), Usage::default());
925    }
926
927    #[test]
928    fn status_line_input_gives_limits_and_context() {
929        let text = r#"{"context_window":{"used_percentage":4},"rate_limits":{"five_hour":{"used_percentage":68,"resets_at":1795013400},"seven_day":{"used_percentage":29.5}}}"#;
930        let status = parse_status(text, 7).unwrap();
931        assert_eq!(status.context_percent, Some(4.));
932        assert_eq!(
933            status.limits,
934            [
935                Limit {
936                    label: "5h session",
937                    used_percent: 68.,
938                    resets_at: Some(1_795_013_400)
939                },
940                Limit {
941                    label: "week",
942                    used_percent: 29.5,
943                    resets_at: None
944                },
945            ]
946        );
947        assert!(parse_status("{}", 7).unwrap().limits.is_empty());
948    }
949
950    #[test]
951    fn cache_ttl_follows_where_hits_stop() {
952        let mut samples = Vec::new();
953        for _ in 0..5 {
954            samples.push((200, true)); // 1-5 min
955            samples.push((500, true)); // 5-10 min
956            samples.push((2400, true)); // 30-60 min
957            samples.push((5000, false)); // 1-2 h
958        }
959        assert_eq!(cache_ttl_ms(&samples), 60 * 60 * 1000);
960        assert_eq!(cache_ttl_ms(&[(100, true)]), OPENCODE_DEFAULT_TTL_MS);
961        let misses = vec![(200, false); 4];
962        assert_eq!(cache_ttl_ms(&misses), OPENCODE_DEFAULT_TTL_MS);
963    }
964
965    #[test]
966    fn opencode_go_limits_come_in_seconds() {
967        let text = r#"{"data":{"go":{"rolling":{"percent":0,"limited":false,"resetsAt":1795024623239},"weekly":{"percent":8,"resetsAt":1795392000000},"monthly":{"percent":4,"resetsAt":1796897924000}},"budgets":[]}}"#;
968        let limits = parse_go_limits(text).unwrap();
969        assert_eq!(limits.len(), 3);
970        assert_eq!(limits[0].resets_at, Some(1_795_024_623));
971        assert_eq!((limits[2].label, limits[2].used_percent), ("month", 4.));
972        assert_eq!(parse_go_limits(r#"{"data":{"go":null}}"#), None);
973    }
974
975    #[test]
976    fn token_counts_stay_readable() {
977        assert_eq!(short_tokens(0), "0");
978        assert_eq!(short_tokens(842), "842");
979        assert_eq!(short_tokens(1_000), "1k");
980        assert_eq!(short_tokens(9_800), "9.8k");
981        assert_eq!(short_tokens(98_200), "98k");
982        assert_eq!(short_tokens(1_000_000), "1M");
983        assert_eq!(short_tokens(1_280_000), "1.28M");
984        assert_eq!(short_tokens(9_800_000), "9.8M");
985        assert_eq!(short_tokens(83_000_000), "83M");
986    }
987
988    #[test]
989    fn ages_use_the_largest_sensible_unit() {
990        assert_eq!(short_age(42), "<1m");
991        assert_eq!(short_age(900), "15m");
992        assert_eq!(short_age(3_600), "1h");
993        assert_eq!(short_age(8_040), "2h 14m");
994        assert_eq!(short_age(90_000), "1d 1h");
995    }
996
997    #[test]
998    fn jsonc_comments_and_trailing_commas_are_accepted() {
999        let path = std::env::temp_dir().join(format!("termden-jsonc-{}.jsonc", std::process::id()));
1000        std::fs::write(
1001            &path,
1002            "{\n  // enabled servers only\n  \"mcp\": {\n    \"a\": { \"type\": \"local\", \"enabled\": true, },\n    /* not this one */ \"b\": { \"enabled\": false },\n  },\n}\n",
1003        )
1004        .unwrap();
1005        let mut names = Vec::new();
1006        push_mcp_block(&mut names, &path);
1007        let _ = std::fs::remove_file(&path);
1008        assert_eq!(names, ["a"]);
1009    }
1010
1011    #[test]
1012    fn an_mcp_servers_wrapper_is_unwrapped() {
1013        let path =
1014            std::env::temp_dir().join(format!("termden-mcp-wrap-{}.json", std::process::id()));
1015        std::fs::write(
1016            &path,
1017            r#"{"mcp":{"servers":{"atlas":{"type":"local"},"off":{"type":"local","enabled":false}}}}"#,
1018        )
1019        .unwrap();
1020        let mut names = Vec::new();
1021        push_mcp_block(&mut names, &path);
1022        let _ = std::fs::remove_file(&path);
1023        assert_eq!(names, ["atlas"]);
1024    }
1025
1026    #[test]
1027    fn disabled_opencode_mcp_servers_are_not_listed() {
1028        let path = std::env::temp_dir().join(format!("termden-mcp-{}.json", std::process::id()));
1029        std::fs::write(
1030            &path,
1031            r#"{"mcp":{"termden":{"type":"local","enabled":true},"gone":{"type":"local","enabled":false},"plain":{"command":["x"]}}}"#,
1032        )
1033        .unwrap();
1034        let mut names = Vec::new();
1035        push_mcp_block(&mut names, &path);
1036        let _ = std::fs::remove_file(&path);
1037        names.sort();
1038        assert_eq!(names, ["plain", "termden"]);
1039    }
1040}