-
-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathpoller.rs
More file actions
1129 lines (982 loc) · 33.9 KB
/
Copy pathpoller.rs
File metadata and controls
1129 lines (982 loc) · 33.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::path::PathBuf;
use std::process::Command;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use serde::Deserialize;
use std::os::windows::process::CommandExt;
use crate::diagnose;
use crate::localization::Strings;
use crate::models::{AppUsageData, UsageData, UsageSection};
const USAGE_URL: &str = "https://api.anthropic.com/api/oauth/usage";
const MESSAGES_URL: &str = "https://api.anthropic.com/v1/messages";
const CODEX_USAGE_URL: &str = "https://chatgpt.com/backend-api/wham/usage";
const CREATE_NO_WINDOW: u32 = 0x08000000;
const MODEL_FALLBACK_CHAIN: &[&str] = &["claude-3-haiku-20240307", "claude-haiku-4-5-20251001"];
#[derive(Debug)]
pub enum PollError {
AuthRequired,
NoCredentials,
TokenExpired,
RequestFailed,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CredentialWatchMode {
ActiveSource,
AllSources,
}
pub type CredentialWatchSnapshot = Vec<String>;
#[derive(Deserialize)]
struct UsageResponse {
five_hour: Option<UsageBucket>,
seven_day: Option<UsageBucket>,
}
#[derive(Deserialize)]
struct UsageBucket {
utilization: f64,
resets_at: Option<String>,
}
#[derive(Deserialize)]
struct CodexAuthFile {
tokens: Option<CodexTokenData>,
}
#[derive(Clone, Deserialize)]
struct CodexTokenData {
access_token: String,
account_id: Option<String>,
}
#[derive(Deserialize)]
struct CodexUsageResponse {
rate_limit: Option<Option<Box<CodexRateLimitDetails>>>,
}
#[derive(Deserialize)]
struct CodexRateLimitDetails {
primary_window: Option<Option<Box<CodexRateLimitWindow>>>,
secondary_window: Option<Option<Box<CodexRateLimitWindow>>>,
}
#[derive(Deserialize)]
struct CodexRateLimitWindow {
used_percent: f64,
reset_at: i64,
}
pub fn poll(show_claude_code: bool, show_codex: bool) -> Result<AppUsageData, PollError> {
let mut data = AppUsageData::default();
if show_claude_code {
data.claude_code = Some(poll_claude_code()?);
}
if show_codex {
match poll_codex() {
Ok(codex) => data.codex = Some(codex),
Err(error) if !show_claude_code => return Err(error),
Err(error) => diagnose::log(format!("Codex usage poll failed: {error:?}")),
}
}
if data.claude_code.is_none() && data.codex.is_none() {
Err(PollError::RequestFailed)
} else {
Ok(data)
}
}
fn poll_claude_code() -> Result<UsageData, PollError> {
let creds = match read_first_credentials() {
Some(c) => c,
None => {
diagnose::log("poll failed: no Claude credentials found");
return Err(PollError::NoCredentials);
}
};
let creds = refresh_or_fallback(creds)?;
fetch_usage_with_fallback(&creds.access_token)
}
fn poll_codex() -> Result<UsageData, PollError> {
let creds = match read_codex_credentials() {
Some(creds) => creds,
None => {
diagnose::log("Codex usage poll failed: no Codex credentials found");
return Err(PollError::NoCredentials);
}
};
match fetch_codex_usage(&creds.access_token, creds.account_id.as_deref()) {
Ok(data) => Ok(data),
Err(PollError::AuthRequired) => {
cli_refresh_codex_token();
let refreshed = read_codex_credentials().ok_or(PollError::TokenExpired)?;
fetch_codex_usage(&refreshed.access_token, refreshed.account_id.as_deref())
}
Err(error) => Err(error),
}
}
fn refresh_or_fallback(mut creds: Credentials) -> Result<Credentials, PollError> {
loop {
if !is_token_expired(creds.expires_at) {
return Ok(creds);
}
let source = creds.source.clone();
cli_refresh_token(&source);
match read_credentials_from_source(&source) {
Some(refreshed) if !is_token_expired(refreshed.expires_at) => return Ok(refreshed),
Some(_) => diagnose::log(format!(
"credentials from {source:?} still expired after refresh attempt"
)),
None => diagnose::log(format!(
"credentials from {source:?} unavailable after refresh attempt"
)),
}
match read_next_credentials_after(&source) {
Some(next) => creds = next,
None => return Err(PollError::TokenExpired),
}
}
}
/// Invoke the Claude CLI with a minimal prompt to force its internal
/// OAuth token refresh.
fn cli_refresh_token(source: &CredentialSource) {
match source {
CredentialSource::Windows(_) => cli_refresh_windows_token(),
CredentialSource::Wsl { distro } => cli_refresh_wsl_token(distro),
}
}
fn cli_refresh_windows_token() {
let claude_path = resolve_windows_claude_path();
let is_cmd = claude_path.to_lowercase().ends_with(".cmd");
diagnose::log(format!(
"attempting Windows Claude token refresh via {claude_path}"
));
let args: &[&str] = &["-p", "."];
let mut cmd = if is_cmd {
let mut c = Command::new("cmd.exe");
c.arg("/c").arg(&claude_path).args(args);
c
} else {
let mut c = Command::new(&claude_path);
c.args(args);
c
};
cmd.env_remove("CLAUDECODE")
.env_remove("CLAUDE_CODE_ENTRYPOINT")
.creation_flags(CREATE_NO_WINDOW)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(error) => {
diagnose::log_error("unable to spawn Windows Claude token refresh", error);
return;
}
};
// Wait up to 30 seconds — don't block the poll thread forever
let start = std::time::Instant::now();
loop {
match child.try_wait() {
Ok(Some(_)) => break,
Ok(None) => {
if start.elapsed() > Duration::from_secs(30) {
let _ = child.kill();
break;
}
std::thread::sleep(Duration::from_millis(500));
}
Err(_) => break,
}
}
}
fn cli_refresh_wsl_token(distro: &str) {
diagnose::log(format!(
"attempting WSL Claude token refresh in distro {distro}"
));
let mut cmd = Command::new("wsl.exe");
cmd.arg("-d")
.arg(distro)
.arg("--")
.arg("bash")
.arg("-lic")
.arg("if command -v claude >/dev/null 2>&1; then claude -p .; elif [ -x \"$HOME/.local/bin/claude\" ]; then \"$HOME/.local/bin/claude\" -p .; else exit 127; fi")
.env_remove("CLAUDECODE")
.env_remove("CLAUDE_CODE_ENTRYPOINT")
.creation_flags(CREATE_NO_WINDOW)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(error) => {
diagnose::log_error("unable to spawn WSL Claude token refresh", error);
return;
}
};
wait_for_refresh(&mut child);
}
fn cli_refresh_codex_token() {
let codex_path = resolve_windows_codex_path();
let is_cmd = codex_path.to_lowercase().ends_with(".cmd");
let is_ps1 = codex_path.to_lowercase().ends_with(".ps1");
diagnose::log(format!(
"attempting Windows Codex token refresh via {codex_path}"
));
let args: &[&str] = &["exec", "."];
let mut cmd = if is_cmd {
let mut c = Command::new("cmd.exe");
c.arg("/c").arg(&codex_path).args(args);
c
} else if is_ps1 {
let mut c = Command::new("powershell.exe");
c.arg("-NoProfile")
.arg("-ExecutionPolicy")
.arg("Bypass")
.arg("-File")
.arg(&codex_path)
.args(args);
c
} else {
let mut c = Command::new(&codex_path);
c.args(args);
c
};
cmd.creation_flags(CREATE_NO_WINDOW)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(error) => {
diagnose::log_error("unable to spawn Windows Codex token refresh", error);
return;
}
};
wait_for_refresh(&mut child);
}
/// Spawn a command and wait up to `timeout` for it to finish.
/// Returns None if the process fails to start or exceeds the deadline.
fn run_with_timeout(cmd: &mut Command, timeout: Duration) -> Option<std::process::Output> {
let mut child = cmd.spawn().ok()?;
let start = std::time::Instant::now();
loop {
match child.try_wait() {
Ok(Some(_)) => return child.wait_with_output().ok(),
Ok(None) => {
if start.elapsed() > timeout {
let _ = child.kill();
let _ = child.wait();
return None;
}
std::thread::sleep(Duration::from_millis(100));
}
Err(_) => return None,
}
}
}
fn wait_for_refresh(child: &mut std::process::Child) {
// Wait up to 30 seconds; don't block the poll thread forever.
let start = std::time::Instant::now();
loop {
match child.try_wait() {
Ok(Some(_)) => break,
Ok(None) => {
if start.elapsed() > Duration::from_secs(30) {
let _ = child.kill();
break;
}
std::thread::sleep(Duration::from_millis(500));
}
Err(_) => break,
}
}
}
/// Resolve the full path to the `claude` CLI executable.
fn resolve_windows_claude_path() -> String {
for name in &["claude.cmd", "claude"] {
if Command::new(name)
.arg("--version")
.creation_flags(CREATE_NO_WINDOW)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok()
{
return name.to_string();
}
}
for name in &["claude.cmd", "claude"] {
if let Ok(output) = Command::new("where.exe")
.arg(name)
.creation_flags(CREATE_NO_WINDOW)
.output()
{
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
if let Some(first_line) = stdout.lines().next() {
let path = first_line.trim().to_string();
if !path.is_empty() {
return path;
}
}
}
}
}
"claude.cmd".to_string()
}
fn resolve_windows_codex_path() -> String {
for name in &["codex.cmd", "codex.ps1", "codex.exe", "codex"] {
if Command::new(name)
.arg("--version")
.creation_flags(CREATE_NO_WINDOW)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok()
{
return name.to_string();
}
}
for name in &["codex.cmd", "codex.ps1", "codex.exe", "codex"] {
if let Ok(output) = Command::new("where.exe")
.arg(name)
.creation_flags(CREATE_NO_WINDOW)
.output()
{
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
if let Some(first_line) = stdout.lines().next() {
let path = first_line.trim().to_string();
if !path.is_empty() {
return path;
}
}
}
}
}
"codex.cmd".to_string()
}
fn build_agent() -> Result<ureq::Agent, PollError> {
let tls = native_tls::TlsConnector::new().map_err(|_| PollError::RequestFailed)?;
Ok(ureq::AgentBuilder::new()
.timeout(Duration::from_secs(30))
.tls_connector(std::sync::Arc::new(tls))
.build())
}
pub fn credential_watch_snapshot(mode: CredentialWatchMode) -> CredentialWatchSnapshot {
let sources = match mode {
CredentialWatchMode::ActiveSource => read_first_credentials()
.map(|creds| vec![creds.source])
.unwrap_or_else(all_known_credential_sources),
CredentialWatchMode::AllSources => all_known_credential_sources(),
};
let mut snapshot: CredentialWatchSnapshot = sources
.into_iter()
.filter_map(|source| credential_watch_signature(&source))
.collect();
snapshot.sort();
snapshot.dedup();
snapshot
}
fn all_known_credential_sources() -> Vec<CredentialSource> {
let mut sources = Vec::new();
if let Some(source) = windows_credential_source() {
sources.push(source);
}
for distro in list_wsl_distros() {
sources.push(CredentialSource::Wsl { distro });
}
sources
}
fn windows_credential_source() -> Option<CredentialSource> {
let home = dirs::home_dir()?;
Some(CredentialSource::Windows(
home.join(".claude").join(".credentials.json"),
))
}
fn credential_watch_signature(source: &CredentialSource) -> Option<String> {
match source {
CredentialSource::Windows(path) => Some(windows_credential_watch_signature(path)),
CredentialSource::Wsl { distro } => wsl_credential_watch_signature(distro),
}
}
fn windows_credential_watch_signature(path: &PathBuf) -> String {
let key = format!("win:{}", path.display());
match std::fs::metadata(path) {
Ok(metadata) => {
let modified = metadata
.modified()
.ok()
.and_then(|value| value.duration_since(UNIX_EPOCH).ok())
.map(|value| value.as_secs())
.unwrap_or(0);
format!("{key}|present|{}|{modified}", metadata.len())
}
Err(_) => format!("{key}|missing"),
}
}
fn wsl_credential_watch_signature(distro: &str) -> Option<String> {
let output = run_with_timeout(
Command::new("wsl.exe")
.arg("-d")
.arg(distro)
.arg("--")
.arg("sh")
.arg("-lc")
.arg(
"if [ -f ~/.claude/.credentials.json ]; then \
stat -c 'present|%s|%Y' ~/.claude/.credentials.json; \
else echo missing; fi",
)
.creation_flags(CREATE_NO_WINDOW)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null()),
Duration::from_secs(5),
)?;
let state = if output.status.success() {
decode_wsl_text(&output.stdout).trim().to_string()
} else {
format!("status-{}", output.status)
};
Some(format!("wsl:{distro}|{state}"))
}
fn fetch_usage_with_fallback(token: &str) -> Result<UsageData, PollError> {
// Try the dedicated usage endpoint first
match try_usage_endpoint(token)? {
Some(data) => {
// If reset timers are missing, fill them in from the Messages API
if data.session.resets_at.is_none() || data.weekly.resets_at.is_none() {
if let Ok(fallback) = fetch_usage_via_messages(token) {
let mut merged = data;
if merged.session.resets_at.is_none() {
merged.session.resets_at = fallback.session.resets_at;
}
if merged.weekly.resets_at.is_none() {
merged.weekly.resets_at = fallback.weekly.resets_at;
}
return Ok(merged);
}
}
return Ok(data);
}
None => {}
}
// Fall back to Messages API with rate limit headers
let result = fetch_usage_via_messages(token);
if result.is_err() {
diagnose::log("usage endpoint and Messages API fallback both failed");
}
result
}
fn try_usage_endpoint(token: &str) -> Result<Option<UsageData>, PollError> {
let agent = build_agent()?;
let resp = match agent
.get(USAGE_URL)
.set("Authorization", &format!("Bearer {token}"))
.set("anthropic-beta", "oauth-2025-04-20")
.call()
{
Ok(resp) => resp,
Err(ureq::Error::Status(code, _)) if code == 401 || code == 403 => {
diagnose::log(format!(
"usage endpoint returned auth error status {code}; re-login required"
));
return Err(PollError::AuthRequired);
}
Err(_) => return Ok(None),
};
let response: UsageResponse = match resp.into_json() {
Ok(response) => response,
Err(_) => return Ok(None),
};
let mut data = UsageData::default();
if let Some(bucket) = &response.five_hour {
data.session.percentage = bucket.utilization;
data.session.resets_at = parse_iso8601(bucket.resets_at.as_deref());
}
if let Some(bucket) = &response.seven_day {
data.weekly.percentage = bucket.utilization;
data.weekly.resets_at = parse_iso8601(bucket.resets_at.as_deref());
}
Ok(Some(data))
}
fn fetch_usage_via_messages(token: &str) -> Result<UsageData, PollError> {
let agent = build_agent()?;
for model in MODEL_FALLBACK_CHAIN {
let body = serde_json::json!({
"model": model,
"max_tokens": 1,
"messages": [{"role": "user", "content": "."}]
});
let response = match agent
.post(MESSAGES_URL)
.set("Authorization", &format!("Bearer {token}"))
.set("anthropic-version", "2023-06-01")
.set("anthropic-beta", "oauth-2025-04-20")
.send_json(&body)
{
Ok(resp) => resp,
Err(ureq::Error::Status(code, _)) if code == 401 || code == 403 => {
diagnose::log(format!(
"messages endpoint returned auth error status {code}; re-login required"
));
return Err(PollError::AuthRequired);
}
Err(ureq::Error::Status(_code, resp)) => resp,
Err(_) => continue,
};
let h5 = response.header("anthropic-ratelimit-unified-5h-utilization");
let h7 = response.header("anthropic-ratelimit-unified-7d-utilization");
let hs = response.header("anthropic-ratelimit-unified-status");
if h5.is_some() || h7.is_some() || hs.is_some() {
return Ok(parse_rate_limit_headers(&response));
}
}
Err(PollError::RequestFailed)
}
fn parse_rate_limit_headers(response: &ureq::Response) -> UsageData {
let mut data = UsageData::default();
data.session.percentage =
get_header_f64(response, "anthropic-ratelimit-unified-5h-utilization") * 100.0;
data.session.resets_at = unix_to_system_time(get_header_i64(
response,
"anthropic-ratelimit-unified-5h-reset",
));
data.weekly.percentage =
get_header_f64(response, "anthropic-ratelimit-unified-7d-utilization") * 100.0;
data.weekly.resets_at = unix_to_system_time(get_header_i64(
response,
"anthropic-ratelimit-unified-7d-reset",
));
let overall_reset = get_header_i64(response, "anthropic-ratelimit-unified-reset");
if data.session.percentage == 0.0 && data.weekly.percentage == 0.0 {
let status = response.header("anthropic-ratelimit-unified-status");
if status == Some("rejected") {
let claim = response.header("anthropic-ratelimit-unified-representative-claim");
match claim {
Some("five_hour") => data.session.percentage = 100.0,
Some("seven_day") => data.weekly.percentage = 100.0,
_ => {}
}
}
if data.session.resets_at.is_none() && overall_reset.is_some() {
data.session.resets_at = unix_to_system_time(overall_reset);
}
}
data
}
fn fetch_codex_usage(token: &str, account_id: Option<&str>) -> Result<UsageData, PollError> {
let agent = build_agent()?;
let mut request = agent
.get(CODEX_USAGE_URL)
.set("Authorization", &format!("Bearer {token}"))
.set("User-Agent", "codex-cli");
if let Some(account_id) = account_id.filter(|value| !value.is_empty()) {
request = request.set("ChatGPT-Account-Id", account_id);
}
let resp = match request.call() {
Ok(resp) => resp,
Err(ureq::Error::Status(code, _)) if code == 401 || code == 403 => {
diagnose::log(format!(
"Codex usage endpoint returned auth error status {code}; refresh required"
));
return Err(PollError::AuthRequired);
}
Err(error) => {
diagnose::log_error("Codex usage endpoint request failed", error);
return Err(PollError::RequestFailed);
}
};
let response: CodexUsageResponse = match resp.into_json() {
Ok(response) => response,
Err(error) => {
diagnose::log_error("unable to parse Codex usage response", error);
return Err(PollError::RequestFailed);
}
};
codex_usage_from_response(response).ok_or(PollError::RequestFailed)
}
fn codex_usage_from_response(response: CodexUsageResponse) -> Option<UsageData> {
let details = *response.rate_limit.flatten()?;
let mut data = UsageData::default();
if let Some(window) = details.primary_window.flatten() {
data.session = codex_section_from_window(&window);
}
if let Some(window) = details.secondary_window.flatten() {
data.weekly = codex_section_from_window(&window);
}
Some(data)
}
fn codex_section_from_window(window: &CodexRateLimitWindow) -> UsageSection {
UsageSection {
percentage: window.used_percent,
resets_at: unix_to_system_time(Some(window.reset_at)),
}
}
fn get_header_f64(response: &ureq::Response, name: &str) -> f64 {
response
.header(name)
.and_then(|s| s.parse::<f64>().ok())
.unwrap_or(0.0)
}
fn get_header_i64(response: &ureq::Response, name: &str) -> Option<i64> {
response.header(name).and_then(|s| s.parse::<i64>().ok())
}
fn unix_to_system_time(unix_secs: Option<i64>) -> Option<SystemTime> {
let secs = unix_secs?;
if secs < 0 {
return None;
}
Some(UNIX_EPOCH + Duration::from_secs(secs as u64))
}
struct Credentials {
access_token: String,
expires_at: Option<i64>,
source: CredentialSource,
}
#[derive(Clone, Debug)]
enum CredentialSource {
Windows(PathBuf),
Wsl { distro: String },
}
fn read_first_credentials() -> Option<Credentials> {
if let Some(creds) = read_windows_credentials() {
return Some(creds);
}
for distro in list_wsl_distros() {
if let Some(creds) = read_wsl_credentials(&distro) {
return Some(creds);
}
}
None
}
fn read_windows_credentials() -> Option<Credentials> {
let CredentialSource::Windows(cred_path) = windows_credential_source()? else {
return None;
};
let content = match std::fs::read_to_string(&cred_path) {
Ok(content) => content,
Err(error) => {
if diagnose::is_enabled() {
diagnose::log_error(
&format!(
"unable to read Windows credentials at {}",
cred_path.display()
),
error,
);
}
return None;
}
};
parse_credentials(&content, CredentialSource::Windows(cred_path))
}
fn read_credentials_from_source(source: &CredentialSource) -> Option<Credentials> {
match source {
CredentialSource::Windows(path) => {
let content = std::fs::read_to_string(path).ok()?;
parse_credentials(&content, source.clone())
}
CredentialSource::Wsl { distro } => read_wsl_credentials(distro),
}
}
fn codex_auth_path() -> Option<PathBuf> {
if let Some(codex_home) = std::env::var_os("CODEX_HOME").map(PathBuf::from) {
return Some(codex_home.join("auth.json"));
}
Some(dirs::home_dir()?.join(".codex").join("auth.json"))
}
fn read_codex_credentials() -> Option<CodexTokenData> {
let auth_path = codex_auth_path()?;
let content = match std::fs::read_to_string(&auth_path) {
Ok(content) => content,
Err(error) => {
diagnose::log_error(
&format!(
"unable to read Codex credentials at {}",
auth_path.display()
),
error,
);
return None;
}
};
let auth: CodexAuthFile = serde_json::from_str(&content).ok()?;
auth.tokens.filter(|tokens| !tokens.access_token.is_empty())
}
fn read_wsl_credentials(distro: &str) -> Option<Credentials> {
let output = run_with_timeout(
Command::new("wsl.exe")
.arg("-d")
.arg(distro)
.arg("--")
.arg("sh")
.arg("-lc")
.arg("cat ~/.claude/.credentials.json")
.creation_flags(CREATE_NO_WINDOW)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null()),
Duration::from_secs(5),
)?;
if !output.status.success() {
diagnose::log(format!(
"WSL credentials probe failed for distro {distro} with status {}",
output.status
));
return None;
}
let content = String::from_utf8(output.stdout).ok()?;
parse_credentials(
&content,
CredentialSource::Wsl {
distro: distro.to_string(),
},
)
}
fn parse_credentials(content: &str, source: CredentialSource) -> Option<Credentials> {
let json: serde_json::Value = serde_json::from_str(content).ok()?;
let oauth = json.get("claudeAiOauth")?;
let access_token = oauth
.get("accessToken")
.and_then(|v| v.as_str())?
.to_string();
let expires_at = oauth.get("expiresAt").and_then(|v| v.as_i64());
Some(Credentials {
access_token,
expires_at,
source,
})
}
fn read_next_credentials_after(source: &CredentialSource) -> Option<Credentials> {
match source {
CredentialSource::Windows(_) => {
for distro in list_wsl_distros() {
if let Some(creds) = read_wsl_credentials(&distro) {
return Some(creds);
}
}
}
CredentialSource::Wsl { distro } => {
let mut past_current = false;
for candidate_distro in list_wsl_distros() {
if !past_current {
past_current = candidate_distro == *distro;
continue;
}
if let Some(creds) = read_wsl_credentials(&candidate_distro) {
return Some(creds);
}
}
}
}
None
}
fn list_wsl_distros() -> Vec<String> {
let output = match run_with_timeout(
Command::new("wsl.exe")
.args(["-l", "-q"])
.creation_flags(CREATE_NO_WINDOW)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null()),
Duration::from_secs(5),
) {
Some(output) if output.status.success() => output,
_ => {
diagnose::log("unable to enumerate WSL distros");
return Vec::new();
}
};
let stdout = decode_wsl_text(&output.stdout);
stdout
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.map(ToOwned::to_owned)
.collect()
}
fn decode_wsl_text(bytes: &[u8]) -> String {
if bytes.is_empty() {
return String::new();
}
if let Some(decoded) = decode_utf16le(bytes) {
return decoded;
}
String::from_utf8_lossy(bytes).into_owned()
}
fn decode_utf16le(bytes: &[u8]) -> Option<String> {
if bytes.len() < 2 || bytes.len() % 2 != 0 {
return None;
}
let body = if bytes.starts_with(&[0xFF, 0xFE]) {
&bytes[2..]
} else if looks_like_utf16le(bytes) {
bytes
} else {
return None;
};
let units: Vec<u16> = body
.chunks_exact(2)
.map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
.collect();
Some(String::from_utf16_lossy(&units))
}
fn looks_like_utf16le(bytes: &[u8]) -> bool {
let sample_len = bytes.len().min(128);
let units = sample_len / 2;
if units == 0 {
return false;
}
let nul_high_bytes = bytes[..sample_len]
.chunks_exact(2)
.filter(|chunk| chunk[1] == 0)
.count();
nul_high_bytes * 2 >= units
}
fn is_token_expired(expires_at: Option<i64>) -> bool {
let Some(exp) = expires_at else { return false };
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as i64;
now >= exp
}
/// Parse an ISO 8601 timestamp string into a SystemTime.
fn parse_iso8601(s: Option<&str>) -> Option<SystemTime> {
let s = s?;
// Strip timezone offset to get "YYYY-MM-DDTHH:MM:SS" or with fractional seconds
// The API returns formats like "2026-03-05T08:00:00.321598+00:00"
let datetime_part = s.split('+').next().unwrap_or(s);
let datetime_part = datetime_part.split('Z').next().unwrap_or(datetime_part);
// Try parsing with and without fractional seconds
let formats = ["%Y-%m-%dT%H:%M:%S%.f", "%Y-%m-%dT%H:%M:%S"];
for fmt in &formats {
if let Ok(secs) = parse_datetime_to_unix(datetime_part, fmt) {
return Some(UNIX_EPOCH + Duration::from_secs(secs));
}
}
None
}
/// Minimal datetime parser — avoids pulling in chrono/time crates.
fn parse_datetime_to_unix(s: &str, _fmt: &str) -> Result<u64, ()> {
// Extract date and time parts from "YYYY-MM-DDTHH:MM:SS[.frac]"
let (date_str, time_str) = s.split_once('T').ok_or(())?;
let date_parts: Vec<&str> = date_str.split('-').collect();
if date_parts.len() != 3 {
return Err(());
}
let year: u64 = date_parts[0].parse().map_err(|_| ())?;
let month: u64 = date_parts[1].parse().map_err(|_| ())?;
let day: u64 = date_parts[2].parse().map_err(|_| ())?;
// Strip fractional seconds
let time_base = time_str.split('.').next().unwrap_or(time_str);
let time_parts: Vec<&str> = time_base.split(':').collect();
if time_parts.len() != 3 {
return Err(());
}
let hour: u64 = time_parts[0].parse().map_err(|_| ())?;
let min: u64 = time_parts[1].parse().map_err(|_| ())?;
let sec: u64 = time_parts[2].parse().map_err(|_| ())?;