1use crate::streaming::{JsonRecordEvent, JsonRecordScanner};
10use regex::{Captures, Regex};
11use serde_json::Value;
12use std::collections::{HashMap, HashSet};
13use std::sync::LazyLock;
14
15const MONTH: &str = "(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:t(?:ember)?)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)";
16const MONTHS: [&str; 12] = [
17 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
18];
19
20fn regex(pattern: &str) -> Regex {
21 Regex::new(pattern).expect("valid built-in pattern")
22}
23
24static USAGE_LIMIT_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
25 [
26 r"(?i)hit your (?:\w+ )?limit".to_string(),
28 r"(?i)you have exceeded your rate limit".to_string(),
29 r"(?i)usage limit (?:reached|exceeded)".to_string(),
30 r"(?i)rate[_\s-]?limit[_\s-]?(?:reached|exceeded)".to_string(),
34 r"(?i)limit (?:has been )?reached".to_string(),
35 r"(?i)billing hard limit".to_string(),
36 r"(?i)please try again at".to_string(),
37 r"(?i)available again at".to_string(),
38 format!(r"(?i)resets\s+(?:(?:at\s+)?[0-9]|{MONTH}\b)"),
40 r"(?i)freeusagelimiterror".to_string(),
41 ]
42 .iter()
43 .map(|pattern| regex(pattern))
44 .collect()
45});
46static THROTTLE: LazyLock<Regex> = LazyLock::new(|| regex(r"(?i)not your usage limit"));
47static RAW_RESET_TIME_PATTERNS: LazyLock<[Regex; 2]> = LazyLock::new(|| {
48 [
49 regex(r#"(?i)(?:resets?|try again|available again|available)\s+(?:at|on)?\s*([^\n."]+)"#),
50 regex(r#"(?i)(?:reset time|limit resets at)\s*:?\s*([^\n."]+)"#),
51 ]
52});
53static DATE_RESET: LazyLock<Regex> = LazyLock::new(|| {
54 regex(&format!(
55 r"(?i)({MONTH})\s+(\d{{1,2}})(?:st|nd|rd|th)?(?:,?\s+(\d{{4}}))?,?\s+(?:at\s+)?([0-9]{{1,2}})(?::([0-9]{{2}}))?\s*([ap]m)"
56 ))
57});
58static KEYWORD_RESET: LazyLock<Regex> = LazyLock::new(|| {
59 regex(
60 r"(?i)(?:try again|available(?: again)?|resets?)(?:\s+at)?\s+([0-9]{1,2})(?::([0-9]{2}))?\s*([ap]m)\b",
61 )
62});
63static RESET_24H: LazyLock<Regex> =
64 LazyLock::new(|| regex(r"(?i)resets?(?:\s+at)?\s+([0-2]?[0-9]):([0-5][0-9])"));
65static AM_PM_AHEAD: LazyLock<Regex> = LazyLock::new(|| regex(r"(?i)^\s*[ap]m"));
66static TIMEZONE: LazyLock<Regex> = LazyLock::new(|| {
67 regex(r"\b(?:UTC(?:[+-]\d{1,2}(?::\d{2})?)?|[A-Z]{2,5}|[A-Za-z]+/[A-Za-z_/-]+)\b")
68});
69static IANA_PARENTHETICAL: LazyLock<Regex> =
70 LazyLock::new(|| regex(r"\(([A-Za-z_]+(?:/[A-Za-z_]+){0,2})\)"));
71static PARENTHETICAL: LazyLock<Regex> = LazyLock::new(|| regex(r"\(([^)]+)\)"));
72static TIMEZONE_LABEL: LazyLock<Regex> =
73 LazyLock::new(|| regex(r"(?i)\btimezone\s*:?\s*([A-Za-z_/-]+|UTC[+-]?\d*)\b"));
74
75static DEBUG_BLOCK_START: LazyLock<Regex> = LazyLock::new(|| regex(r"(?i)^\[log_[0-9a-f]+\]\s"));
77static DEBUG_RESPONSE_ERROR: LazyLock<Regex> =
78 LazyLock::new(|| regex(r"(?i)^\[log_[0-9a-f]+\]\s+response error\b"));
79static BASE64_DUMP_LINE: LazyLock<Regex> = LazyLock::new(|| regex(r"^[A-Za-z0-9+/=]{120,}$"));
81static HEADER_LINE: LazyLock<Regex> =
82 LazyLock::new(|| regex(r#"(?i)^\s*"?([a-z0-9-]+)"?\s*:\s*"?([^",]*)"?,?\s*$"#));
83static RATE_LIMIT_HEADER: LazyLock<Regex> =
84 LazyLock::new(|| regex(r"(?i)^(?:anthropic-ratelimit-.*|retry-after)$"));
85static STATUS_LINE: LazyLock<Regex> = LazyLock::new(|| regex(r"^\s*status:\s*(\d{3}),?\s*$"));
86static BLOCK_END: LazyLock<Regex> = LazyLock::new(|| regex(r"^}\s*$"));
87static BLOCK_OPEN: LazyLock<Regex> = LazyLock::new(|| regex(r"\{\s*$"));
88
89#[derive(Debug, Clone, Default, PartialEq, Eq)]
91pub struct UsageLimitVerdict {
92 pub reached: bool,
94 pub throttled: bool,
96 pub reset_time: Option<String>,
98 pub timezone: Option<String>,
100 pub resets_at: Option<i64>,
102 pub window: Option<String>,
104}
105
106pub fn is_usage_limit_text(text: &str) -> bool {
108 USAGE_LIMIT_PATTERNS
109 .iter()
110 .any(|pattern| pattern.is_match(text))
111}
112
113fn clean_reset_time(value: &str) -> Option<String> {
114 let mut cleaned = value
115 .trim()
116 .trim_end_matches([',', ';', '}', ']'])
117 .to_string();
118 if cleaned.ends_with(')') && !cleaned.contains('(') {
120 cleaned = cleaned.trim_end_matches(')').to_string();
121 }
122 if cleaned.is_empty() || cleaned.chars().count() > 120 {
123 return None;
124 }
125 Some(cleaned)
126}
127
128fn twelve_hour(hour: &str, minute: Option<&str>, ampm: &str) -> String {
129 format!(
130 "{}:{} {}",
131 hour,
132 minute.unwrap_or("00"),
133 ampm.to_uppercase()
134 )
135}
136
137fn group<'t>(captures: &Captures<'t>, index: usize) -> Option<&'t str> {
138 captures.get(index).map(|m| m.as_str())
139}
140
141fn raw_reset_time(text: &str) -> Option<String> {
142 RAW_RESET_TIME_PATTERNS.iter().find_map(|pattern| {
143 pattern
144 .captures(text)
145 .and_then(|captures| clean_reset_time(group(&captures, 1)?))
146 })
147}
148
149pub fn extract_reset_time(text: &str) -> Option<String> {
154 let normalized = text.split_whitespace().collect::<Vec<_>>().join(" ");
155
156 if let Some(captures) = DATE_RESET.captures(&normalized) {
158 let time = twelve_hour(&captures[4], group(&captures, 5), &captures[6]);
159 return Some(match group(&captures, 3) {
160 Some(year) => format!("{} {}, {}, {}", &captures[1], &captures[2], year, time),
161 None => format!("{} {}, {}", &captures[1], &captures[2], time),
162 });
163 }
164
165 if let Some(captures) = KEYWORD_RESET.captures(&normalized) {
166 return Some(twelve_hour(&captures[1], group(&captures, 2), &captures[3]));
167 }
168
169 for captures in RESET_24H.captures_iter(&normalized) {
170 let rest = &normalized[captures.get(0).map_or(0, |m| m.end())..];
171 if AM_PM_AHEAD.is_match(rest)
172 || rest.starts_with(|c: char| c == '-' || c == ':' || c.is_ascii_digit())
173 {
174 continue;
175 }
176 let hour: u32 = captures[1].parse().unwrap_or(0);
177 let hour12 = if hour.is_multiple_of(12) {
178 12
179 } else {
180 hour % 12
181 };
182 let ampm = if hour >= 12 { "PM" } else { "AM" };
183 return Some(format!("{}:{} {}", hour12, &captures[2], ampm));
184 }
185
186 raw_reset_time(&normalized)
187}
188
189fn find_timezone(text: &str) -> Option<String> {
190 TIMEZONE
191 .find_iter(text)
192 .map(|m| m.as_str())
193 .find(|candidate| *candidate != "AM" && *candidate != "PM")
194 .map(ToString::to_string)
195}
196
197pub fn extract_timezone(text: &str, reset_time: Option<&str>) -> Option<String> {
199 if let Some(iana) = IANA_PARENTHETICAL
200 .captures(text)
201 .and_then(|captures| group(&captures, 1))
202 {
203 if find_timezone(iana).is_some() {
204 return Some(iana.to_string());
205 }
206 }
207 PARENTHETICAL
208 .captures(text)
209 .and_then(|captures| find_timezone(group(&captures, 1)?))
210 .or_else(|| reset_time.and_then(find_timezone))
211 .or_else(|| {
212 TIMEZONE_LABEL
213 .captures(text)
214 .and_then(|captures| group(&captures, 1).map(ToString::to_string))
215 })
216}
217
218pub fn format_epoch_reset_time_utc(epoch_seconds: i64) -> Option<String> {
220 if epoch_seconds <= 0 {
221 return None;
222 }
223 let days = epoch_seconds.div_euclid(86_400);
224 let seconds_of_day = epoch_seconds.rem_euclid(86_400);
225 let z = days + 719_468;
227 let era = z.div_euclid(146_097);
228 let doe = z - era * 146_097;
229 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
230 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
231 let mp = (5 * doy + 2) / 153;
232 let day = doy - (153 * mp + 2) / 5 + 1;
233 let month = if mp < 10 { mp + 3 } else { mp - 9 };
234 let year = yoe + era * 400 + i64::from(month <= 2);
235 let hours = seconds_of_day / 3600;
236 let minutes = (seconds_of_day % 3600) / 60;
237 let hour12 = if hours % 12 == 0 { 12 } else { hours % 12 };
238 let ampm = if hours < 12 { "AM" } else { "PM" };
239 let month_name = MONTHS[usize::try_from(month - 1).ok()?];
240 Some(format!(
241 "{month_name} {day}, {year}, {hour12}:{minutes:02} {ampm}"
242 ))
243}
244
245fn number(value: &Value) -> Option<f64> {
246 value
247 .as_f64()
248 .or_else(|| value.as_str().and_then(|text| text.trim().parse().ok()))
249}
250
251#[allow(clippy::cast_possible_truncation)]
252fn epoch(value: &Value) -> Option<i64> {
253 number(value)
254 .filter(|seconds| seconds.is_finite() && *seconds > 0.0)
255 .map(|seconds| seconds as i64)
256}
257
258fn epoch_verdict(resets_at: i64, window: Option<&str>) -> UsageLimitVerdict {
259 UsageLimitVerdict {
260 reached: true,
261 throttled: false,
262 reset_time: format_epoch_reset_time_utc(resets_at),
263 timezone: Some("UTC".to_string()),
264 resets_at: Some(resets_at),
265 window: window.map(ToString::to_string),
266 }
267}
268
269pub fn classify_rate_limit_event(info: &Value) -> UsageLimitVerdict {
274 if !info.is_object() {
275 return UsageLimitVerdict::default();
276 }
277 let resets_at = epoch(&info["resetsAt"]);
278 let overage_status = info["overageStatus"].as_str();
279 let overage_unavailable = info["isUsingOverage"] != true
280 && (info.get("overageStatus").is_none_or(Value::is_null)
281 || overage_status == Some("rejected")
282 || info["overageEnabled"] == false);
283 let exhausted =
284 number(&info["utilization"]).is_some_and(|value| value >= 1.0) && overage_unavailable;
285 let rejected = info["status"] == "rejected";
286 match resets_at {
287 Some(resets_at) if rejected || exhausted => {
288 epoch_verdict(resets_at, info["rateLimitType"].as_str())
289 }
290 _ => UsageLimitVerdict {
291 throttled: resets_at.is_none() && rejected,
292 ..UsageLimitVerdict::default()
293 },
294 }
295}
296
297#[derive(Debug, Clone, Default)]
299pub struct DebugLines {
300 pub debug_lines: HashSet<usize>,
302 pub verdict: UsageLimitVerdict,
304}
305
306struct DebugBlock {
307 skip: bool,
308 status: Option<u16>,
309 headers: HashMap<String, String>,
310}
311
312pub fn classify_debug_lines(lines: &[String]) -> DebugLines {
314 let mut result = DebugLines::default();
315 let mut block: Option<DebugBlock> = None;
316
317 for (index, raw_line) in lines.iter().enumerate() {
318 let line = raw_line.strip_suffix('\r').unwrap_or(raw_line);
319 if let Some(open) = block.as_mut() {
320 result.debug_lines.insert(index);
321 if BLOCK_END.is_match(line) {
322 let resets_at = open
323 .headers
324 .get("anthropic-ratelimit-unified-reset")
325 .and_then(|value| epoch(&Value::String(value.clone())));
326 if let Some(resets_at) = resets_at {
327 if open.status == Some(429)
328 && open
329 .headers
330 .get("anthropic-ratelimit-unified-status")
331 .is_some_and(|status| status == "rejected")
332 {
333 result.verdict = epoch_verdict(
334 resets_at,
335 open.headers
336 .get("anthropic-ratelimit-unified-representative-claim")
337 .map(String::as_str),
338 );
339 }
340 }
341 block = None;
342 } else if !open.skip {
343 if let Some(captures) = STATUS_LINE.captures(line) {
344 open.status = captures[1].parse().ok();
345 }
346 if let Some(captures) = HEADER_LINE.captures(line) {
347 if RATE_LIMIT_HEADER.is_match(&captures[1]) {
348 open.headers.insert(
349 captures[1].to_ascii_lowercase(),
350 captures[2].trim().to_string(),
351 );
352 }
353 }
354 }
355 continue;
356 }
357 if DEBUG_BLOCK_START.is_match(line) {
358 result.debug_lines.insert(index);
359 if BLOCK_OPEN.is_match(line) {
360 block = Some(DebugBlock {
361 skip: !DEBUG_RESPONSE_ERROR.is_match(line),
362 status: None,
363 headers: HashMap::new(),
364 });
365 }
366 } else if BASE64_DUMP_LINE.is_match(line.trim()) {
367 result.debug_lines.insert(index);
368 }
369 }
370
371 result
372}
373
374pub fn is_recoverable_tool_error(event: &Value) -> bool {
376 if !matches!(event["type"].as_str(), Some("error" | "step_error")) {
377 return false;
378 }
379 event["recoverable"] == true
380 || (event.pointer("/part/type") == Some(&Value::from("tool"))
381 && event.pointer("/part/state/status") == Some(&Value::from("error")))
382}
383
384fn is_truthy(value: &Value) -> bool {
385 match value {
386 Value::Null => false,
387 Value::Bool(flag) => *flag,
388 Value::Number(number) => number.as_f64().is_some_and(|n| n != 0.0),
389 Value::String(text) => !text.is_empty(),
390 _ => true,
391 }
392}
393
394fn is_tool_output_event(event: &Value) -> bool {
397 if !event.is_object() {
398 return false;
399 }
400 let kind = event["type"].as_str().unwrap_or("");
401 is_truthy(&event["parent_tool_use_id"])
402 || matches!(kind, "user" | "tool_use" | "tool_result")
403 || (kind.starts_with("item.") && event.pointer("/item/type") != Some(&Value::from("error")))
404 || is_recoverable_tool_error(event)
405}
406
407fn collect_strings(value: &Value, out: &mut Vec<String>) {
408 match value {
409 Value::String(text) => out.push(text.clone()),
410 Value::Array(values) => values.iter().for_each(|entry| collect_strings(entry, out)),
411 Value::Object(map) => {
412 if matches!(
413 map.get("type").and_then(Value::as_str),
414 Some("tool_use" | "tool_result")
415 ) {
416 return;
417 }
418 for (key, entry) in map {
419 if key != "tool_use_result" {
420 collect_strings(entry, out);
421 }
422 }
423 }
424 _ => {}
425 }
426}
427
428pub fn split_output(output: &str) -> (Vec<Value>, Vec<String>) {
430 let mut scanner = JsonRecordScanner::new();
431 let mut events = scanner.write(output);
432 events.extend(scanner.flush());
433 let mut records = Vec::new();
434 let mut lines = Vec::new();
435 for event in events {
436 match event {
437 JsonRecordEvent::Json { value, .. } => records.push(value),
438 JsonRecordEvent::Text(line) => lines.push(line),
439 JsonRecordEvent::Invalid(_) => {}
440 }
441 }
442 (records, lines)
443}
444
445fn scan_text(
446 plain_output: &str,
447 records: &[Value],
448 lines: &[String],
449 debug_lines: &HashSet<usize>,
450 messages: &[Value],
451) -> String {
452 let mut strings = lines
453 .iter()
454 .enumerate()
455 .filter(|(index, _)| !debug_lines.contains(index))
456 .map(|(_, line)| line.clone())
457 .collect::<Vec<_>>();
458 let events = if plain_output.trim().is_empty() {
459 messages
460 } else {
461 records
462 };
463 for record in events {
464 let entries = match record {
465 Value::Array(values) => values.iter().collect::<Vec<_>>(),
466 value => vec![value],
467 };
468 for entry in entries {
469 if !is_tool_output_event(entry) {
470 collect_strings(entry, &mut strings);
471 }
472 }
473 }
474 strings.join("\n")
475}
476
477pub fn limit_scan_text(plain_output: &str, messages: &[Value]) -> String {
480 let (records, lines) = split_output(plain_output);
481 let debug = classify_debug_lines(&lines);
482 scan_text(plain_output, &records, &lines, &debug.debug_lines, messages)
483}
484
485pub fn detect_usage_limit_sources(plain_output: &str, messages: &[Value]) -> UsageLimitVerdict {
487 let (records, lines) = split_output(plain_output);
488 let debug = classify_debug_lines(&lines);
489 let text = scan_text(plain_output, &records, &lines, &debug.debug_lines, messages);
490 let rate_limit_event = messages
491 .iter()
492 .rev()
493 .find(|event| event["type"] == "rate_limit_event")
494 .map(|event| classify_rate_limit_event(&event["rate_limit_info"]))
495 .unwrap_or_default();
496 let result = messages
497 .iter()
498 .rev()
499 .find(|event| event["type"] == "result");
500 let api_usage_limit = result.is_some_and(|event| event["api_error"] == "usage_limit_reached");
501 let structured = [&rate_limit_event, &debug.verdict]
502 .into_iter()
503 .find(|verdict| verdict.reached);
504
505 if !is_usage_limit_text(&text) && !api_usage_limit && structured.is_none() {
506 return UsageLimitVerdict {
507 throttled: rate_limit_event.throttled
508 || THROTTLE.is_match(&text)
509 || result.is_some_and(|event| event["api_error_status"] == 429),
510 ..UsageLimitVerdict::default()
511 };
512 }
513
514 if let Some(structured) = structured {
516 return structured.clone();
517 }
518 let reset_time = extract_reset_time(&text);
519 let timezone = reset_time
520 .as_ref()
521 .and_then(|_| extract_timezone(&text, raw_reset_time(&text).as_deref()));
522 UsageLimitVerdict {
523 reached: true,
524 reset_time,
525 timezone,
526 ..UsageLimitVerdict::default()
527 }
528}