agent_commander/
claude_transcript.rs1use regex::Regex;
12use serde_json::Value;
13use std::path::PathBuf;
14use std::sync::LazyLock;
15
16use crate::file_tail::{default_home_dir, read_file_tail};
17use crate::result_metadata::ResultMetadata;
18use crate::usage_limit::{extract_reset_time, extract_timezone, is_usage_limit_text};
19
20pub const TRANSCRIPT_TAIL_BYTES: u64 = 1024 * 1024;
22
23pub const CLAUDE_TRANSCRIPT_LIMIT_SOURCE: &str = "claude-transcript";
25
26const CONVERSATION_TYPES: [&str; 2] = ["assistant", "user"];
27
28static SESSION_ID_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
30 Regex::new(r"^[0-9a-zA-Z][0-9a-zA-Z_-]{7,127}$").expect("valid session id regex")
31});
32
33#[derive(Debug, Clone, Default, PartialEq, Eq)]
35pub struct ClaudeTranscriptOptions {
36 pub working_directory: Option<PathBuf>,
38 pub claude_config_dir: Option<PathBuf>,
40 pub home_dir: Option<PathBuf>,
42 pub max_bytes: Option<u64>,
44}
45
46impl ClaudeTranscriptOptions {
47 pub fn for_run_env(
53 working_directory: &str,
54 extra_env: &[(String, String)],
55 unset_env: &[String],
56 ) -> Self {
57 let passed = extra_env
58 .iter()
59 .rev()
60 .find(|(name, value)| name == "CLAUDE_CONFIG_DIR" && !value.is_empty())
61 .map(|(_, value)| PathBuf::from(value));
62 let claude_config_dir = passed.or_else(|| {
63 unset_env
64 .iter()
65 .any(|name| name == "CLAUDE_CONFIG_DIR")
66 .then(|| default_home_dir().join(".claude"))
67 });
68 Self {
69 working_directory: Some(PathBuf::from(working_directory))
70 .filter(|path| !path.as_os_str().is_empty()),
71 claude_config_dir,
72 ..Self::default()
73 }
74 }
75
76 fn max_bytes(&self) -> u64 {
77 self.max_bytes.unwrap_or(TRANSCRIPT_TAIL_BYTES)
78 }
79}
80
81pub fn claude_project_slugs(working_directory: &str) -> Vec<String> {
84 let old = working_directory.replace('/', "-");
85 let new: String = working_directory
86 .chars()
87 .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
88 .collect();
89 if old == new {
90 vec![old]
91 } else {
92 vec![old, new]
93 }
94}
95
96pub fn claude_transcript_candidates(
98 session_id: &str,
99 options: &ClaudeTranscriptOptions,
100) -> Vec<PathBuf> {
101 let Some(working_directory) = options.working_directory.as_deref() else {
102 return Vec::new();
103 };
104 if !SESSION_ID_PATTERN.is_match(session_id) {
105 return Vec::new();
106 }
107 let config_dir = options
108 .claude_config_dir
109 .clone()
110 .filter(|path| !path.as_os_str().is_empty())
111 .or_else(|| {
112 std::env::var_os("CLAUDE_CONFIG_DIR")
113 .filter(|value| !value.is_empty())
114 .map(PathBuf::from)
115 });
116 let home = options.home_dir.clone().unwrap_or_else(default_home_dir);
117 let roots = config_dir
118 .map(|dir| dir.join("projects"))
119 .into_iter()
120 .chain(std::iter::once(home.join(".claude").join("projects")));
121 let slugs = claude_project_slugs(&working_directory.to_string_lossy());
122 let mut candidates: Vec<PathBuf> = Vec::new();
123 for root in roots {
124 for slug in &slugs {
125 let path = root.join(slug).join(format!("{session_id}.jsonl"));
126 if !candidates.contains(&path) {
127 candidates.push(path);
128 }
129 }
130 }
131 candidates
132}
133
134#[derive(Debug, Clone, Default, PartialEq, Eq)]
136pub struct ClaudeTranscriptApiError {
137 pub text: String,
139 pub error: Option<Value>,
141 pub timestamp: Option<String>,
143}
144
145pub fn claude_transcript_api_error(text: &str) -> Result<ClaudeTranscriptApiError, String> {
148 for line in text.lines().rev() {
149 let Ok(entry) = serde_json::from_str::<Value>(line) else {
150 continue;
151 };
152 let Some(kind) = entry
154 .get("type")
155 .and_then(Value::as_str)
156 .filter(|kind| CONVERSATION_TYPES.contains(kind))
157 else {
158 continue;
159 };
160 if kind != "assistant" || entry.get("isApiErrorMessage") != Some(&Value::Bool(true)) {
161 return Err(format!("last entry is a {kind} message, not an API error"));
162 }
163 let text = entry
164 .pointer("/message/content")
165 .and_then(Value::as_array)
166 .map(|content| {
167 content
168 .iter()
169 .filter(|item| item.get("type").and_then(Value::as_str) == Some("text"))
170 .filter_map(|item| item.get("text").and_then(Value::as_str))
171 .filter(|text| !text.is_empty())
172 .collect::<Vec<_>>()
173 .join("\n")
174 })
175 .unwrap_or_default();
176 return Ok(ClaudeTranscriptApiError {
177 text,
178 error: entry.get("error").filter(|value| !value.is_null()).cloned(),
179 timestamp: entry
180 .get("timestamp")
181 .and_then(Value::as_str)
182 .map(String::from),
183 });
184 }
185 Err("no conversation entry in transcript tail".to_string())
186}
187
188pub fn read_claude_transcript_api_error(
192 session_id: &str,
193 options: &ClaudeTranscriptOptions,
194) -> Result<(PathBuf, ClaudeTranscriptApiError), String> {
195 if session_id.is_empty() || options.working_directory.is_none() {
196 return Err("no session id".to_string());
197 }
198 for path in claude_transcript_candidates(session_id, options) {
199 if let Ok(text) = read_file_tail(&path, options.max_bytes()) {
200 return claude_transcript_api_error(&text).map(|error| (path, error));
201 }
202 }
203 Err("transcript not found".to_string())
204}
205
206fn is_claude_transcript_candidate(metadata: &ResultMetadata) -> bool {
207 metadata.tool == "claude"
208 && !metadata.success
209 && metadata.signal.is_none()
210 && !metadata.limit_reached
211 && metadata
212 .session_id
213 .as_deref()
214 .is_some_and(|id| !id.is_empty())
215}
216
217pub fn apply_claude_transcript_usage_limit(
222 metadata: &mut ResultMetadata,
223 options: &ClaudeTranscriptOptions,
224) -> bool {
225 if !is_claude_transcript_candidate(metadata) {
226 return false;
227 }
228 let session_id = metadata.session_id.clone().unwrap_or_default();
229 let Ok((_, transcript)) = read_claude_transcript_api_error(&session_id, options) else {
230 return false;
231 };
232 if !is_usage_limit_text(&transcript.text) {
233 return false;
234 }
235 let reset_time = extract_reset_time(&transcript.text);
236 metadata.success = false;
237 metadata.limit_reached = true;
238 metadata.limit_timezone = extract_timezone(&transcript.text, reset_time.as_deref());
239 metadata.limit_reset_time = reset_time;
240 metadata.limit_source = Some(CLAUDE_TRANSCRIPT_LIMIT_SOURCE.to_string());
241 true
242}