1use std::collections::HashMap;
6use std::fs::File;
7use std::io::{BufRead, BufReader};
8use std::path::{Path, PathBuf};
9
10use serde_json::Value;
11
12use super::{Scope, claude_project_dir, estimate_tokens};
13
14const LONGEST_LINE: usize = 8 * 1024 * 1024;
16
17pub fn transcript_path(claude: &Path, project: &Path, session: &str) -> PathBuf {
19 claude_project_dir(claude, project).join(format!("{session}.jsonl"))
20}
21
22#[derive(Clone, Debug, PartialEq)]
24pub struct Loaded {
25 pub path: PathBuf,
26 pub scope: Scope,
27 pub text: String,
28}
29
30#[derive(Clone, Debug, Default, PartialEq)]
32pub struct FileRead {
33 pub path: PathBuf,
34 pub reads: usize,
35 pub searches: usize,
36 pub edits: usize,
37 pub tokens: usize,
39 pub turns: Vec<usize>,
41 pub last_read: Option<u64>,
43 pub last_edit: Option<u64>,
45}
46
47#[derive(Clone, Debug, PartialEq)]
49pub struct Search {
50 pub tool: String,
51 pub pattern: String,
52 pub path: Option<String>,
53 pub tokens: usize,
54 pub turn: usize,
55}
56
57#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
59pub struct Breakdown {
60 pub system: usize,
61 pub tools: usize,
62 pub instructions: usize,
63 pub listings: usize,
65 pub mcp: usize,
66 pub files: usize,
67 pub output: usize,
68 pub messages: usize,
69 pub total: usize,
71}
72
73impl Breakdown {
74 pub fn before(&self) -> usize {
76 self.system + self.tools + self.instructions + self.listings + self.mcp
77 }
78
79 pub fn conversation(&self) -> usize {
80 self.files + self.output + self.messages
81 }
82}
83
84#[derive(Clone, Debug, Default)]
85pub struct Session {
86 pub loaded: Vec<Loaded>,
87 pub skills: String,
89 pub subagents: Vec<String>,
91 pub mcp: Vec<(String, String)>,
93 pub invoked: Vec<String>,
95 pub files: Vec<FileRead>,
96 pub searches: Vec<Search>,
97 pub turns: usize,
98 pub model: Option<String>,
99 pub breakdown: Breakdown,
100 pub compactions: usize,
102}
103
104impl Session {
105 pub fn window(&self) -> usize {
107 let model = self.model.as_deref().unwrap_or("");
108 claude_window(model, self.breakdown.total as u64) as usize
109 }
110
111 pub fn stale(&self) -> Vec<&FileRead> {
113 self.files
114 .iter()
115 .filter(|f| {
116 let Some(read) = f.last_read else {
117 return false;
118 };
119 let own = f.last_edit.is_some_and(|e| e >= read);
120 let modified = std::fs::metadata(&f.path).and_then(|m| m.modified()).ok();
121 let modified = modified.and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok());
122 !own && modified.is_some_and(|m| m.as_secs() > read + 1)
123 })
124 .collect()
125 }
126}
127
128pub fn claude_window(model: &str, used: u64) -> u64 {
134 const SHORT: u64 = 200_000;
135 const LONG: u64 = 1_000_000;
136 let long_named = model.contains("[1m]") || model.ends_with("-1m");
137 if short_windowed(model) && !long_named && used <= SHORT {
138 SHORT
139 } else {
140 LONG
141 }
142}
143
144fn short_windowed(model: &str) -> bool {
147 let Some(at) = model.find("claude-") else {
148 return false;
149 };
150 let mut parts = model[at + "claude-".len()..].split(['-', '[', '@']);
151 let first = parts.next().unwrap_or("");
152 if first.parse::<u32>().is_ok_and(|major| major < 4) {
153 return true;
154 }
155 let Some(Ok(major)) = parts.next().map(str::parse::<u32>) else {
156 return false;
157 };
158 let minor = parts
160 .next()
161 .filter(|p| (1..=2).contains(&p.len()))
162 .and_then(|p| p.parse::<u32>().ok())
163 .unwrap_or(0);
164 major < 4 || (major == 4 && minor <= 5)
165}
166
167pub(crate) fn unix_seconds(stamp: &str) -> Option<u64> {
169 let (date, time) = stamp.split_once('T')?;
170 let mut d = date.split('-').map(|p| p.parse::<i64>().ok());
171 let (y, m, day) = (d.next()??, d.next()??, d.next()??);
172 let time = time.trim_end_matches('Z');
173 let time = time.split(['+', '-']).next()?;
174 let mut t = time.split(':');
175 let h: i64 = t.next()?.parse().ok()?;
176 let min: i64 = t.next()?.parse().ok()?;
177 let s: f64 = t.next().unwrap_or("0").parse().ok()?;
178 let y = if m <= 2 { y - 1 } else { y };
180 let era = y.div_euclid(400);
181 let yoe = y - era * 400;
182 let mp = (m + 9) % 12;
183 let doy = (153 * mp + 2) / 5 + day - 1;
184 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
185 let days = era * 146_097 + doe - 719_468;
186 u64::try_from(days * 86_400 + h * 3600 + min * 60 + s as i64).ok()
187}
188
189fn text_of(content: &Value) -> String {
190 match content {
191 Value::String(s) => s.clone(),
192 Value::Array(parts) => parts
193 .iter()
194 .filter_map(|p| p["text"].as_str().or_else(|| p.as_str()))
195 .collect::<Vec<_>>()
196 .join("\n"),
197 _ => String::new(),
198 }
199}
200
201pub fn read_session(path: &Path) -> std::io::Result<Session> {
204 let reader = BufReader::new(File::open(path)?);
205 let mut session = Session::default();
206 let mut index: HashMap<PathBuf, usize> = HashMap::new();
207 let mut pending: HashMap<String, (String, Option<usize>, Option<usize>)> = HashMap::new();
209 let mut since_compact_files = 0;
210 let mut since_compact_output = 0;
211 let mut usage_total = 0;
212 for line in reader.split(b'\n') {
213 let Ok(line) = line else { break };
214 if line.len() > LONGEST_LINE {
215 continue;
216 }
217 let Ok(record) = serde_json::from_slice::<Value>(&line) else {
218 continue;
219 };
220 if record["isSidechain"].as_bool() == Some(true) {
221 continue;
222 }
223 let when = record["timestamp"].as_str().and_then(unix_seconds);
224 match record["type"].as_str() {
225 Some("attachment") => attachment(&record["attachment"], &mut session),
226 Some("api-request-shape") => {
227 let shape = &record["shape"];
228 session.breakdown.system = estimate_tokens(&text_of(&shape["system"]));
229 session.breakdown.tools = estimate_tokens(&shape["tools"].to_string());
230 }
231 Some("system") if record["subtype"] == "compact_boundary" => {
232 session.compactions += 1;
233 since_compact_files = 0;
234 since_compact_output = 0;
235 }
236 Some("assistant") => {
237 let message = &record["message"];
238 if let Some(model) = message["model"].as_str().filter(|m| !m.starts_with('<')) {
239 session.model = Some(model.to_string());
240 }
241 let usage = &message["usage"];
242 let total: u64 = [
243 "input_tokens",
244 "cache_creation_input_tokens",
245 "cache_read_input_tokens",
246 ]
247 .iter()
248 .filter_map(|k| usage[*k].as_u64())
249 .sum();
250 if total > 0 {
251 usage_total = total as usize;
252 }
253 for block in message["content"].as_array().into_iter().flatten() {
254 if block["type"] == "tool_use" {
255 let id = block["id"].as_str().unwrap_or("").to_string();
256 let call = tool_call(block, &mut session, &mut index, when);
257 pending.insert(id, call);
258 }
259 }
260 }
261 Some("user") => {
262 let content = &record["message"]["content"];
263 let prompt = match content {
264 Value::String(_) => true,
265 Value::Array(parts) => parts.iter().any(|p| p["type"] == "text"),
266 _ => false,
267 };
268 let own = ["isMeta", "isCompactSummary", "isVisibleInTranscriptOnly"]
269 .iter()
270 .any(|flag| record[*flag].as_bool() == Some(true));
271 if prompt && !own {
272 session.turns += 1;
273 }
274 for part in content.as_array().into_iter().flatten() {
275 if part["type"] != "tool_result" {
276 continue;
277 }
278 let tokens = estimate_tokens(&text_of(&part["content"]));
279 let id = part["tool_use_id"].as_str().unwrap_or("");
280 match pending.remove(id) {
281 Some((tool, Some(file), _)) if tool == "Read" => {
282 session.files[file].tokens += tokens;
283 since_compact_files += tokens;
284 }
285 Some((_, _, Some(search))) => {
286 session.searches[search].tokens += tokens;
287 since_compact_output += tokens;
288 }
289 _ => since_compact_output += tokens,
290 }
291 }
292 }
293 _ => {}
294 }
295 }
296 let b = &mut session.breakdown;
297 b.instructions = session
298 .loaded
299 .iter()
300 .map(|l| estimate_tokens(&l.text))
301 .sum();
302 b.listings = estimate_tokens(&session.skills)
303 + session
304 .subagents
305 .iter()
306 .map(|s| estimate_tokens(s))
307 .sum::<usize>();
308 b.mcp = session.mcp.iter().map(|(_, t)| estimate_tokens(t)).sum();
309 b.total = usage_total;
310 b.files = since_compact_files;
311 b.output = since_compact_output;
312 let known = b.before() + b.files + b.output;
313 b.messages = usage_total.saturating_sub(known);
314 session
315 .files
316 .sort_by(|a, b| b.tokens.cmp(&a.tokens).then(a.path.cmp(&b.path)));
317 Ok(session)
318}
319
320fn attachment(a: &Value, session: &mut Session) {
321 match a["type"].as_str() {
322 Some("instructions") => {
323 for file in a["files"].as_array().into_iter().flatten() {
324 let Some(path) = file["path"].as_str() else {
325 continue;
326 };
327 let loaded = Loaded {
328 path: PathBuf::from(path),
329 scope: Scope::from_claude(file["type"].as_str().unwrap_or("")),
330 text: file["content"].as_str().unwrap_or("").to_string(),
331 };
332 match session.loaded.iter_mut().find(|l| l.path == loaded.path) {
333 Some(known) => *known = loaded,
334 None => session.loaded.push(loaded),
335 }
336 }
337 }
338 Some("skill_listing") => session.skills = a["content"].as_str().unwrap_or("").to_string(),
339 Some("agent_listing_delta") => {
340 for line in a["addedLines"]
341 .as_array()
342 .into_iter()
343 .flatten()
344 .filter_map(Value::as_str)
345 {
346 if !session.subagents.iter().any(|s| s == line) {
347 session.subagents.push(line.to_string());
348 }
349 }
350 }
351 Some("mcp_instructions_delta") => {
352 let names = a["addedNames"]
353 .as_array()
354 .into_iter()
355 .flatten()
356 .filter_map(Value::as_str);
357 let blocks = a["addedBlocks"]
358 .as_array()
359 .into_iter()
360 .flatten()
361 .filter_map(Value::as_str);
362 for (name, block) in names.zip(blocks) {
363 session.mcp.retain(|(n, _)| n != name);
364 session.mcp.push((name.to_string(), block.to_string()));
365 }
366 }
367 Some("invoked_skills") => {
368 for skill in a["skills"].as_array().into_iter().flatten() {
369 if let Some(name) = skill["name"].as_str()
370 && !session.invoked.iter().any(|n| n == name)
371 {
372 session.invoked.push(name.to_string());
373 }
374 }
375 }
376 _ => {}
377 }
378}
379
380fn tool_call(
382 block: &Value,
383 session: &mut Session,
384 index: &mut HashMap<PathBuf, usize>,
385 when: Option<u64>,
386) -> (String, Option<usize>, Option<usize>) {
387 let tool = block["name"].as_str().unwrap_or("").to_string();
388 let input = &block["input"];
389 let turn = session.turns.max(1);
390 let mut file_at = |path: &str, session: &mut Session| -> usize {
391 let path = PathBuf::from(path);
392 *index.entry(path.clone()).or_insert_with(|| {
393 session.files.push(FileRead {
394 path,
395 ..FileRead::default()
396 });
397 session.files.len() - 1
398 })
399 };
400 match tool.as_str() {
401 "Read" | "NotebookRead" => {
402 let path = input["file_path"]
403 .as_str()
404 .or_else(|| input["notebook_path"].as_str());
405 let Some(path) = path else {
406 return (tool, None, None);
407 };
408 let i = file_at(path, session);
409 let file = &mut session.files[i];
410 file.reads += 1;
411 file.last_read = when.or(file.last_read);
412 if !file.turns.contains(&turn) {
413 file.turns.push(turn);
414 }
415 (tool, Some(i), None)
416 }
417 "Edit" | "Write" | "MultiEdit" | "NotebookEdit" => {
418 let path = input["file_path"]
419 .as_str()
420 .or_else(|| input["notebook_path"].as_str());
421 if let Some(path) = path {
422 let i = file_at(path, session);
423 session.files[i].edits += 1;
424 session.files[i].last_edit = when.or(session.files[i].last_edit);
425 }
426 (tool, None, None)
427 }
428 "Grep" | "Glob" => {
429 let pattern = input["pattern"].as_str().unwrap_or("").to_string();
430 let path = input["path"].as_str().map(str::to_string);
431 if let Some(p) = &path
432 && tool == "Grep"
433 && Path::new(p).extension().is_some()
434 {
435 let i = file_at(p, session);
436 session.files[i].searches += 1;
437 }
438 session.searches.push(Search {
439 tool: tool.clone(),
440 pattern,
441 path,
442 tokens: 0,
443 turn,
444 });
445 let at = session.searches.len() - 1;
446 (tool, None, Some(at))
447 }
448 _ => (tool, None, None),
449 }
450}