dirge-agent 0.21.0

Minimalistic coding agent written in Rust, optimized for memory footprint and performance
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
use super::file_store::OPENAI_ACCOUNT_ID_ALIASES as ACCOUNT_ID_KEYS;
use serde::Deserialize;
use serde_json::{Map, Value, json};
use std::fmt;
use std::path::{Path, PathBuf};

type Result<T> = std::result::Result<T, AuthStoreError>;

#[derive(Debug, thiserror::Error)]
pub(crate) enum AuthStoreError {
    // The Io/CorruptJson/Serialize messages are provider-neutral: one
    // auth.json serves every provider key (`openai`, `kimi`, …).
    #[error("auth store I/O failed for {path:?}: {source}")]
    Io {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error(
        "auth store JSON is corrupt at {path:?}; fix or remove the file and log in again: {source}"
    )]
    CorruptJson {
        path: PathBuf,
        #[source]
        source: serde_json::Error,
    },
    #[error("OpenAI auth entry is invalid at {path:?}; run `dirge auth openai` again: {reason}")]
    InvalidOpenAiCredential { path: PathBuf, reason: String },
    #[error("Kimi auth entry is invalid at {path:?}; run `dirge auth kimi` again: {reason}")]
    InvalidKimiCredential { path: PathBuf, reason: String },
    #[error("auth store serialization failed for {path:?}: {source}")]
    Serialize {
        path: PathBuf,
        #[source]
        source: serde_json::Error,
    },
}

#[derive(Clone, PartialEq, Eq)]
pub(crate) struct OpenAiOAuthCredential {
    access_token: String,
    refresh_token: String,
    id_token: Option<String>,
    account_id: Option<String>,
    expires_at_epoch_ms: i64,
}

impl OpenAiOAuthCredential {
    pub(crate) fn new(
        access_token: impl Into<String>,
        refresh_token: impl Into<String>,
        id_token: Option<String>,
        account_id: Option<String>,
        expires_at_epoch_ms: i64,
    ) -> Self {
        Self {
            access_token: access_token.into(),
            refresh_token: refresh_token.into(),
            id_token,
            account_id: normalize_optional_string(account_id),
            expires_at_epoch_ms,
        }
    }

    pub(crate) fn access_token(&self) -> &str {
        &self.access_token
    }

    pub(crate) fn refresh_token(&self) -> &str {
        &self.refresh_token
    }

    pub(crate) fn id_token(&self) -> Option<&str> {
        self.id_token.as_deref()
    }

    pub(crate) fn account_id(&self) -> Option<&str> {
        self.account_id.as_deref()
    }

    pub(crate) fn expires_at_epoch_ms(&self) -> i64 {
        self.expires_at_epoch_ms
    }

    pub(crate) fn is_expired_at(&self, epoch_ms: i64) -> bool {
        super::file_store::epoch_ms_is_expired(self.expires_at_epoch_ms, epoch_ms)
    }

    pub(crate) fn is_fresh_at(&self, epoch_ms: i64) -> bool {
        !self.is_expired_at(epoch_ms)
    }
}

impl fmt::Debug for OpenAiOAuthCredential {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let id_token = self.id_token.as_ref().map(|_| "[REDACTED]");
        f.debug_struct("OpenAiOAuthCredential")
            .field("access_token", &"[REDACTED]")
            .field("refresh_token", &"[REDACTED]")
            .field("id_token", &id_token)
            .field("account_id", &self.account_id)
            .field("expires_at_epoch_ms", &self.expires_at_epoch_ms)
            .finish()
    }
}

#[derive(Clone, Debug)]
pub(crate) struct OpenAiAuthStore {
    path: PathBuf,
}

impl Default for OpenAiAuthStore {
    fn default() -> Self {
        Self::at(crate::session::storage::dirs_path().join("auth.json"))
    }
}

impl OpenAiAuthStore {
    pub(crate) fn at(path: impl Into<PathBuf>) -> Self {
        Self { path: path.into() }
    }

    pub(crate) fn path(&self) -> &Path {
        &self.path
    }

    pub(crate) fn load_openai(&self) -> Result<Option<OpenAiOAuthCredential>> {
        let Some(mut document) = self.load_document()? else {
            return Ok(None);
        };
        let Some(openai) = document.remove("openai") else {
            return Ok(None);
        };
        let mut openai = match openai {
            Value::Object(openai) => openai,
            _ => return Ok(None),
        };
        if openai.get("type").and_then(Value::as_str) != Some("oauth") {
            return Ok(None);
        }
        canonicalize_account_id_aliases(&mut openai);
        let entry: StoredOpenAiCredential =
            serde_json::from_value(Value::Object(openai)).map_err(|_source| {
                AuthStoreError::InvalidOpenAiCredential {
                    path: self.path.clone(),
                    reason: "stored OpenAI OAuth credential fields are malformed".to_string(),
                }
            })?;
        Ok(Some(entry.into_credential()))
    }

    pub(crate) fn save_openai(&self, credential: &OpenAiOAuthCredential) -> Result<()> {
        let mut document = self.load_document()?.unwrap_or_default();
        let mut openai = match document.remove("openai") {
            Some(Value::Object(map)) => map,
            _ => Map::new(),
        };
        openai.insert("type".to_string(), json!("oauth"));
        openai.insert("access".to_string(), json!(credential.access_token));
        openai.insert("refresh".to_string(), json!(credential.refresh_token));
        openai.insert("expires".to_string(), json!(credential.expires_at_epoch_ms));
        match credential.id_token.as_deref() {
            Some(id_token) => {
                openai.insert("id_token".to_string(), json!(id_token));
            }
            None => {
                openai.remove("id_token");
            }
        }
        for key in ACCOUNT_ID_KEYS {
            openai.remove(*key);
        }
        if let Some(account_id) = credential.account_id.as_deref() {
            openai.insert("account_id".to_string(), json!(account_id));
        }
        document.insert("openai".to_string(), Value::Object(openai));

        super::file_store::save_json_0600(&self.path, &Value::Object(document)).map_err(|source| {
            AuthStoreError::Io {
                path: self.path.clone(),
                source: std::io::Error::other(source.to_string()),
            }
        })
    }

    fn load_document(&self) -> Result<Option<Map<String, Value>>> {
        let contents = match std::fs::read_to_string(&self.path) {
            Ok(contents) => contents,
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(source) => {
                return Err(AuthStoreError::Io {
                    path: self.path.clone(),
                    source,
                });
            }
        };
        let value: Value =
            serde_json::from_str(&contents).map_err(|source| AuthStoreError::CorruptJson {
                path: self.path.clone(),
                source,
            })?;
        match value {
            Value::Object(document) => Ok(Some(document)),
            _ => Err(AuthStoreError::InvalidOpenAiCredential {
                path: self.path.clone(),
                reason: "top-level auth document must be a JSON object".to_string(),
            }),
        }
    }

    #[cfg(unix)]
    fn prepare_existing_file_for_private_replace(&self) -> Result<()> {
        match std::fs::metadata(&self.path) {
            Ok(_) => self.restrict_file_permissions(),
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(source) => Err(AuthStoreError::Io {
                path: self.path.clone(),
                source,
            }),
        }
    }

    #[cfg(not(unix))]
    fn prepare_existing_file_for_private_replace(&self) -> Result<()> {
        Ok(())
    }

    #[cfg(unix)]
    fn restrict_file_permissions(&self) -> Result<()> {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&self.path, std::fs::Permissions::from_mode(0o600)).map_err(
            |source| AuthStoreError::Io {
                path: self.path.clone(),
                source,
            },
        )
    }

    #[cfg(not(unix))]
    fn restrict_file_permissions(&self) -> Result<()> {
        Ok(())
    }
}

#[derive(Deserialize)]
struct StoredOpenAiCredential {
    access: String,
    refresh: String,
    id_token: Option<String>,
    #[serde(
        default,
        alias = "chatgpt_account_id",
        alias = "chatgptAccountId",
        alias = "chatgpt_account",
        alias = "accountId"
    )]
    account_id: Option<String>,
    expires: i64,
}

impl StoredOpenAiCredential {
    fn into_credential(self) -> OpenAiOAuthCredential {
        OpenAiOAuthCredential::new(
            self.access,
            self.refresh,
            self.id_token,
            self.account_id,
            self.expires,
        )
    }
}

fn normalize_optional_string(value: Option<String>) -> Option<String> {
    value
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
}

fn canonicalize_account_id_aliases(openai: &mut Map<String, Value>) {
    let account_id = super::file_store::extract_account_id(&Value::Object(openai.clone()));
    for key in ACCOUNT_ID_KEYS {
        openai.remove(*key);
    }
    if let Some(account_id) = account_id {
        openai.insert("account_id".to_string(), json!(account_id));
    }
}

// ── Kimi Code (Moonshot) OAuth — key "kimi" in the same auth.json ──────

/// Refresh a Kimi token this long before it actually expires (dirge-iki5).
///
/// Kimi access tokens live 15 minutes, so the expiry boundary is crossed
/// every 15 minutes of an active session — orders of magnitude more often
/// than on the OpenAI/Anthropic paths, whose tokens are long-lived and which
/// therefore keep the bare `now >= expires_at` comparison. Without slack a
/// request can pass the freshness check and still arrive after the token has
/// died; the 401 that comes back is non-retryable (`ErrorKind::Auth`), so the
/// turn dies outright.
///
/// 60s is ~7% of the token's life — comfortably longer than any plausible
/// request latency plus clock skew, and far short of thrashing (it costs at
/// most one extra refresh per token).
pub(crate) const KIMI_REFRESH_MARGIN_MS: i64 = 60_000;

/// Dirge-managed Kimi OAuth credential. Same access/refresh/expires shape
/// as the OpenAI credential, minus the OpenAI-only id_token/account_id —
/// the Kimi token bundle carries neither.
#[derive(Clone, PartialEq, Eq)]
pub(crate) struct KimiOAuthCredential {
    access_token: String,
    refresh_token: String,
    expires_at_epoch_ms: i64,
}

impl KimiOAuthCredential {
    pub(crate) fn new(
        access_token: impl Into<String>,
        refresh_token: impl Into<String>,
        expires_at_epoch_ms: i64,
    ) -> Self {
        Self {
            access_token: access_token.into(),
            refresh_token: refresh_token.into(),
            expires_at_epoch_ms,
        }
    }

    pub(crate) fn access_token(&self) -> &str {
        &self.access_token
    }

    pub(crate) fn refresh_token(&self) -> &str {
        &self.refresh_token
    }

    pub(crate) fn expires_at_epoch_ms(&self) -> i64 {
        self.expires_at_epoch_ms
    }

    pub(crate) fn is_expired_at(&self, epoch_ms: i64) -> bool {
        super::file_store::epoch_ms_is_expired_within(
            self.expires_at_epoch_ms,
            epoch_ms,
            KIMI_REFRESH_MARGIN_MS,
        )
    }

    pub(crate) fn is_fresh_at(&self, epoch_ms: i64) -> bool {
        !self.is_expired_at(epoch_ms)
    }
}

impl fmt::Debug for KimiOAuthCredential {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("KimiOAuthCredential")
            .field("access_token", &"[REDACTED]")
            .field("refresh_token", &"[REDACTED]")
            .field("expires_at_epoch_ms", &self.expires_at_epoch_ms)
            .finish()
    }
}

#[derive(Clone, Debug)]
pub(crate) struct KimiAuthStore {
    path: PathBuf,
}

impl Default for KimiAuthStore {
    fn default() -> Self {
        Self::at(crate::session::storage::dirs_path().join("auth.json"))
    }
}

impl KimiAuthStore {
    pub(crate) fn at(path: impl Into<PathBuf>) -> Self {
        Self { path: path.into() }
    }

    pub(crate) fn path(&self) -> &Path {
        &self.path
    }

    pub(crate) fn load_kimi(&self) -> Result<Option<KimiOAuthCredential>> {
        let Some(document) = self.load_document()? else {
            return Ok(None);
        };
        let Some(kimi) = document.get("kimi") else {
            return Ok(None);
        };
        let kimi = match kimi {
            Value::Object(kimi) => kimi,
            _ => return Ok(None),
        };
        if kimi.get("type").and_then(Value::as_str) != Some("oauth") {
            return Ok(None);
        }
        let entry: StoredKimiCredential = serde_json::from_value(Value::Object(kimi.clone()))
            .map_err(|_source| AuthStoreError::InvalidKimiCredential {
                path: self.path.clone(),
                reason: "stored Kimi OAuth credential fields are malformed".to_string(),
            })?;
        Ok(Some(entry.into_credential()))
    }

    pub(crate) fn save_kimi(&self, credential: &KimiOAuthCredential) -> Result<()> {
        let mut document = self.load_document()?.unwrap_or_default();
        document.insert(
            "kimi".to_string(),
            json!({
                "type": "oauth",
                "access": credential.access_token,
                "refresh": credential.refresh_token,
                "expires": credential.expires_at_epoch_ms,
            }),
        );

        super::file_store::save_json_0600(&self.path, &Value::Object(document)).map_err(|source| {
            AuthStoreError::Io {
                path: self.path.clone(),
                source: std::io::Error::other(source.to_string()),
            }
        })
    }

    fn load_document(&self) -> Result<Option<Map<String, Value>>> {
        let contents = match std::fs::read_to_string(&self.path) {
            Ok(contents) => contents,
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(source) => {
                return Err(AuthStoreError::Io {
                    path: self.path.clone(),
                    source,
                });
            }
        };
        let value: Value =
            serde_json::from_str(&contents).map_err(|source| AuthStoreError::CorruptJson {
                path: self.path.clone(),
                source,
            })?;
        match value {
            Value::Object(document) => Ok(Some(document)),
            _ => Err(AuthStoreError::InvalidKimiCredential {
                path: self.path.clone(),
                reason: "top-level auth document must be a JSON object".to_string(),
            }),
        }
    }
}

#[derive(Deserialize)]
struct StoredKimiCredential {
    access: String,
    refresh: String,
    expires: i64,
}

impl StoredKimiCredential {
    fn into_credential(self) -> KimiOAuthCredential {
        KimiOAuthCredential::new(self.access, self.refresh, self.expires)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::path::{Path, PathBuf};

    const ACCOUNT_ID_KEYS: &[&str] = &[
        "account_id",
        "chatgpt_account_id",
        "chatgptAccountId",
        "chatgpt_account",
        "accountId",
    ];

    struct TestDir(PathBuf);

    impl TestDir {
        fn new(tag: &str) -> Self {
            let path = std::env::temp_dir().join(format!(
                "dirge_auth_store_{tag}_{}_{}",
                std::process::id(),
                uuid::Uuid::new_v4().simple()
            ));
            std::fs::create_dir_all(&path).unwrap();
            Self(path)
        }

        fn path(&self) -> &Path {
            &self.0
        }

        fn auth_path(&self) -> PathBuf {
            self.path().join("auth.json")
        }
    }

    impl Drop for TestDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    fn credential() -> OpenAiOAuthCredential {
        OpenAiOAuthCredential::new(
            "ACCESS-TOKEN",
            "REFRESH-TOKEN",
            Some("ID-TOKEN".to_string()),
            Some("acct-new".to_string()),
            1_900_000_000_000,
        )
    }

    #[test]
    fn missing_auth_file_loads_as_none() {
        let dir = TestDir::new("missing");
        let store = OpenAiAuthStore::at(dir.auth_path());

        assert!(store.load_openai().unwrap().is_none());
    }

    #[test]
    fn valid_openai_oauth_entry_loads() {
        let dir = TestDir::new("valid");
        std::fs::write(
            dir.auth_path(),
            json!({
                "openai": {
                    "type": "oauth",
                    "access": "ACCESS-TOKEN",
                    "refresh": "REFRESH-TOKEN",
                    "id_token": "ID-TOKEN",
                    "account_id": "acct-load",
                    "expires": 1900000000000_i64
                }
            })
            .to_string(),
        )
        .unwrap();
        let store = OpenAiAuthStore::at(dir.auth_path());

        let loaded = store.load_openai().unwrap().unwrap();

        assert_eq!(loaded.access_token(), "ACCESS-TOKEN");
        assert_eq!(loaded.refresh_token(), "REFRESH-TOKEN");
        assert_eq!(loaded.id_token(), Some("ID-TOKEN"));
        assert_eq!(loaded.account_id(), Some("acct-load"));
        assert_eq!(loaded.expires_at_epoch_ms(), 1_900_000_000_000);
    }

    #[test]
    fn openai_oauth_entry_with_canonical_and_alias_account_ids_loads_canonical() {
        let dir = TestDir::new("load_duplicate_account_aliases");
        std::fs::write(
            dir.auth_path(),
            json!({
                "openai": {
                    "type": "oauth",
                    "access": "ACCESS-TOKEN",
                    "refresh": "REFRESH-TOKEN",
                    "id_token": "ID-TOKEN",
                    "account_id": "acct-canonical",
                    "chatgpt_account_id": "acct-stale-alias",
                    "expires": 1900000000000_i64
                }
            })
            .to_string(),
        )
        .unwrap();
        let store = OpenAiAuthStore::at(dir.auth_path());

        let loaded = store.load_openai().unwrap().unwrap();

        assert_eq!(loaded.account_id(), Some("acct-canonical"));
    }

    #[test]
    fn legacy_openai_oauth_entry_without_account_id_loads() {
        let dir = TestDir::new("legacy_without_account");
        std::fs::write(
            dir.auth_path(),
            json!({
                "openai": {
                    "type": "oauth",
                    "access": "ACCESS-TOKEN",
                    "refresh": "REFRESH-TOKEN",
                    "id_token": "ID-TOKEN",
                    "expires": 1900000000000_i64
                }
            })
            .to_string(),
        )
        .unwrap();
        let store = OpenAiAuthStore::at(dir.auth_path());

        let loaded = store.load_openai().unwrap().unwrap();

        assert_eq!(loaded.account_id(), None);
        assert_eq!(loaded.access_token(), "ACCESS-TOKEN");
    }

    #[test]
    fn corrupt_auth_file_errors_without_deleting_or_echoing_secrets() {
        let dir = TestDir::new("corrupt");
        let secret_body = "{ ACCESS-TOKEN REFRESH-TOKEN ID-TOKEN USER-CODE";
        std::fs::write(dir.auth_path(), secret_body).unwrap();
        let store = OpenAiAuthStore::at(dir.auth_path());

        let err = store.load_openai().unwrap_err();
        let message = err.to_string();

        assert!(matches!(err, AuthStoreError::CorruptJson { .. }));
        assert_eq!(
            std::fs::read_to_string(dir.auth_path()).unwrap(),
            secret_body
        );
        assert!(!message.contains("ACCESS-TOKEN"));
        assert!(!message.contains("REFRESH-TOKEN"));
        assert!(!message.contains("ID-TOKEN"));
        assert!(!message.contains("USER-CODE"));
    }

    #[test]
    fn save_openai_preserves_other_providers_and_unknown_openai_fields() {
        let dir = TestDir::new("preserve");
        std::fs::write(
            dir.auth_path(),
            json!({
                "anthropic": {
                    "type": "api_key",
                    "key": "ANTHROPIC-SECRET",
                    "extra": { "keep": true }
                },
                "openai": {
                    "type": "oauth",
                    "access": "OLD-ACCESS",
                    "refresh": "OLD-REFRESH",
                    "id_token": "OLD-ID",
                    "expires": 1_i64,
                    "account_id": "acct_keep",
                    "fedramp": true
                },
                "custom": "keep-me"
            })
            .to_string(),
        )
        .unwrap();
        let store = OpenAiAuthStore::at(dir.auth_path());

        store.save_openai(&credential()).unwrap();

        let saved: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(dir.auth_path()).unwrap()).unwrap();
        assert_eq!(saved["anthropic"]["key"], "ANTHROPIC-SECRET");
        assert_eq!(saved["custom"], "keep-me");
        assert_eq!(saved["openai"]["type"], "oauth");
        assert_eq!(saved["openai"]["access"], "ACCESS-TOKEN");
        assert_eq!(saved["openai"]["refresh"], "REFRESH-TOKEN");
        assert_eq!(saved["openai"]["id_token"], "ID-TOKEN");
        assert_eq!(saved["openai"]["expires"], 1_900_000_000_000_i64);
        assert_eq!(saved["openai"]["account_id"], "acct-new");
        assert_eq!(saved["openai"]["fedramp"], true);
    }

    #[test]
    fn save_openai_removes_stale_account_id_when_new_credential_has_none() {
        let dir = TestDir::new("remove_account_id");
        std::fs::write(
            dir.auth_path(),
            json!({
                "openai": {
                    "type": "oauth",
                    "access": "OLD-ACCESS",
                    "refresh": "OLD-REFRESH",
                    "expires": 1_i64,
                    "account_id": "acct-stale"
                }
            })
            .to_string(),
        )
        .unwrap();
        let store = OpenAiAuthStore::at(dir.auth_path());
        let credential = OpenAiOAuthCredential::new(
            "ACCESS-TOKEN",
            "REFRESH-TOKEN",
            Some("ID-TOKEN".to_string()),
            None,
            1_900_000_000_000,
        );

        store.save_openai(&credential).unwrap();

        let saved: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(dir.auth_path()).unwrap()).unwrap();
        assert!(saved["openai"].get("account_id").is_none());
    }

    #[test]
    fn save_openai_removes_stale_account_id_aliases_when_new_credential_has_none() {
        let dir = TestDir::new("remove_account_id_aliases");
        std::fs::write(
            dir.auth_path(),
            json!({
                "openai": {
                    "type": "oauth",
                    "access": "OLD-ACCESS",
                    "refresh": "OLD-REFRESH",
                    "expires": 1_i64,
                    "account_id": "acct-stale-canonical",
                    "chatgpt_account_id": "acct-stale-snake",
                    "chatgptAccountId": "acct-stale-camel",
                    "chatgpt_account": "acct-stale-short",
                    "accountId": "acct-stale-account-id"
                }
            })
            .to_string(),
        )
        .unwrap();
        let store = OpenAiAuthStore::at(dir.auth_path());
        let credential = OpenAiOAuthCredential::new(
            "ACCESS-TOKEN",
            "REFRESH-TOKEN",
            Some("ID-TOKEN".to_string()),
            None,
            1_900_000_000_000,
        );

        store.save_openai(&credential).unwrap();

        let saved: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(dir.auth_path()).unwrap()).unwrap();
        for key in ACCOUNT_ID_KEYS {
            assert!(
                saved["openai"].get(key).is_none(),
                "stale alias {key} remained"
            );
        }
    }

    #[test]
    fn save_openai_canonicalizes_account_id_aliases_when_new_credential_has_account_id() {
        let dir = TestDir::new("canonicalize_account_id_aliases");
        std::fs::write(
            dir.auth_path(),
            json!({
                "openai": {
                    "type": "oauth",
                    "access": "OLD-ACCESS",
                    "refresh": "OLD-REFRESH",
                    "expires": 1_i64,
                    "chatgpt_account_id": "acct-stale-snake",
                    "chatgptAccountId": "acct-stale-camel",
                    "chatgpt_account": "acct-stale-short",
                    "accountId": "acct-stale-account-id"
                }
            })
            .to_string(),
        )
        .unwrap();
        let store = OpenAiAuthStore::at(dir.auth_path());

        store.save_openai(&credential()).unwrap();

        let saved: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(dir.auth_path()).unwrap()).unwrap();
        assert_eq!(saved["openai"]["account_id"], "acct-new");
        for key in ACCOUNT_ID_KEYS
            .iter()
            .copied()
            .filter(|key| *key != "account_id")
        {
            assert!(
                saved["openai"].get(key).is_none(),
                "stale alias {key} remained"
            );
        }
    }

    #[test]
    fn save_openai_creates_private_auth_file_on_unix() {
        let dir = TestDir::new("permissions");
        let store = OpenAiAuthStore::at(dir.auth_path());

        store.save_openai(&credential()).unwrap();

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(dir.auth_path())
                .unwrap()
                .permissions()
                .mode()
                & 0o777;
            assert_eq!(mode, 0o600);
        }
    }

    #[cfg(unix)]
    #[test]
    fn save_openai_tightens_existing_auth_file_permissions_on_unix() {
        use std::os::unix::fs::PermissionsExt;

        let dir = TestDir::new("tighten_permissions");
        std::fs::write(dir.auth_path(), "{}").unwrap();
        std::fs::set_permissions(dir.auth_path(), std::fs::Permissions::from_mode(0o644)).unwrap();
        let store = OpenAiAuthStore::at(dir.auth_path());

        store.save_openai(&credential()).unwrap();

        let mode = std::fs::metadata(dir.auth_path())
            .unwrap()
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(mode, 0o600);
    }

    #[cfg(unix)]
    #[test]
    fn prepares_existing_auth_file_private_before_atomic_replacement_on_unix() {
        use std::os::unix::fs::PermissionsExt;

        let dir = TestDir::new("prepare_permissions");
        std::fs::write(dir.auth_path(), "{}").unwrap();
        std::fs::set_permissions(dir.auth_path(), std::fs::Permissions::from_mode(0o644)).unwrap();
        let store = OpenAiAuthStore::at(dir.auth_path());

        store.prepare_existing_file_for_private_replace().unwrap();

        let mode = std::fs::metadata(dir.auth_path())
            .unwrap()
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(mode, 0o600);
    }

    #[test]
    fn expiry_helpers_distinguish_fresh_and_expired_tokens() {
        let token = OpenAiOAuthCredential::new("ACCESS-TOKEN", "REFRESH-TOKEN", None, None, 1_000);

        assert!(token.is_fresh_at(999));
        assert!(!token.is_expired_at(999));
        assert!(token.is_expired_at(1_000));
        assert!(!token.is_fresh_at(1_000));
    }

    #[test]
    fn default_store_uses_dirge_data_dir_override() {
        let _guard = crate::auth::DIRGE_DATA_DIR_ENV_LOCK.lock().unwrap();
        let dir = TestDir::new("env");
        let previous = std::env::var_os("DIRGE_DATA_DIR");
        // SAFETY: auth tests serialize DIRGE_DATA_DIR changes with DIRGE_DATA_DIR_ENV_LOCK.
        unsafe {
            std::env::set_var("DIRGE_DATA_DIR", dir.path());
        }

        let store = OpenAiAuthStore::default();

        assert_eq!(store.path(), dir.auth_path());
        // SAFETY: DIRGE_DATA_DIR_ENV_LOCK remains held until after restoration.
        unsafe {
            match previous {
                Some(value) => std::env::set_var("DIRGE_DATA_DIR", value),
                None => std::env::remove_var("DIRGE_DATA_DIR"),
            }
        }
    }

    #[test]
    fn debug_and_errors_redact_secret_values() {
        let dir = TestDir::new("redact");
        let token = credential();
        let debug = format!("{token:?}");

        assert!(debug.contains("[REDACTED]"));
        assert!(!debug.contains("ACCESS-TOKEN"));
        assert!(!debug.contains("REFRESH-TOKEN"));
        assert!(!debug.contains("ID-TOKEN"));

        std::fs::write(
            dir.auth_path(),
            json!({
                "openai": {
                    "type": "oauth",
                    "access": "ACCESS-TOKEN",
                    "refresh": "REFRESH-TOKEN",
                    "id_token": "ID-TOKEN",
                    "expires": "ACCESS-TOKEN"
                }
            })
            .to_string(),
        )
        .unwrap();
        let err = OpenAiAuthStore::at(dir.auth_path())
            .load_openai()
            .unwrap_err();
        let message = err.to_string();
        let error_debug = format!("{err:?}");

        assert!(!message.contains("ACCESS-TOKEN"));
        assert!(!message.contains("REFRESH-TOKEN"));
        assert!(!message.contains("ID-TOKEN"));
        assert!(!message.contains("USER-CODE"));
        assert!(!error_debug.contains("ACCESS-TOKEN"));
        assert!(!error_debug.contains("REFRESH-TOKEN"));
        assert!(!error_debug.contains("ID-TOKEN"));
        assert!(!error_debug.contains("USER-CODE"));
    }

    // ── Kimi store (key "kimi" in the same auth.json) ──────────────────

    fn kimi_credential() -> KimiOAuthCredential {
        KimiOAuthCredential::new("KIMI-ACCESS", "KIMI-REFRESH", 1_900_000_000_000)
    }

    #[test]
    fn missing_auth_file_loads_kimi_as_none() {
        let dir = TestDir::new("kimi_missing");
        let store = KimiAuthStore::at(dir.auth_path());

        assert!(store.load_kimi().unwrap().is_none());
    }

    #[test]
    fn kimi_credential_roundtrips_through_auth_json() {
        let dir = TestDir::new("kimi_roundtrip");
        let store = KimiAuthStore::at(dir.auth_path());

        store.save_kimi(&kimi_credential()).unwrap();
        let loaded = store.load_kimi().unwrap().unwrap();

        assert_eq!(loaded.access_token(), "KIMI-ACCESS");
        assert_eq!(loaded.refresh_token(), "KIMI-REFRESH");
        assert_eq!(loaded.expires_at_epoch_ms(), 1_900_000_000_000);
    }

    #[test]
    fn save_kimi_preserves_other_provider_keys() {
        let dir = TestDir::new("kimi_preserve");
        let store = OpenAiAuthStore::at(dir.auth_path());
        store.save_openai(&credential()).unwrap();
        std::fs::write(
            dir.auth_path(),
            std::fs::read_to_string(dir.auth_path())
                .unwrap()
                .replace('}', ",\"custom\": \"keep-me\"}"),
        )
        .unwrap();

        let kimi_store = KimiAuthStore::at(dir.auth_path());
        kimi_store.save_kimi(&kimi_credential()).unwrap();

        let saved: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(dir.auth_path()).unwrap()).unwrap();
        assert_eq!(saved["openai"]["access"], "ACCESS-TOKEN");
        assert_eq!(saved["custom"], "keep-me");
        assert_eq!(saved["kimi"]["type"], "oauth");
        assert_eq!(saved["kimi"]["access"], "KIMI-ACCESS");
        assert_eq!(saved["kimi"]["refresh"], "KIMI-REFRESH");
        assert_eq!(saved["kimi"]["expires"], 1_900_000_000_000_i64);
        // The OpenAI credential still loads after the kimi write.
        assert!(store.load_openai().unwrap().is_some());
    }

    #[test]
    fn non_oauth_kimi_entry_loads_as_none() {
        let dir = TestDir::new("kimi_non_oauth");
        std::fs::write(
            dir.auth_path(),
            json!({"kimi": {"type": "api_key", "key": "KIMI-KEY"}}).to_string(),
        )
        .unwrap();
        let store = KimiAuthStore::at(dir.auth_path());

        assert!(store.load_kimi().unwrap().is_none());
    }

    #[test]
    fn malformed_kimi_entry_errors_without_echoing_secrets() {
        let dir = TestDir::new("kimi_malformed");
        std::fs::write(
            dir.auth_path(),
            json!({"kimi": {"type": "oauth", "access": "KIMI-ACCESS", "expires": "KIMI-REFRESH"}})
                .to_string(),
        )
        .unwrap();
        let store = KimiAuthStore::at(dir.auth_path());

        let err = store.load_kimi().unwrap_err();
        let message = err.to_string();
        let debug = format!("{err:?}");

        assert!(matches!(err, AuthStoreError::InvalidKimiCredential { .. }));
        for secret in ["KIMI-ACCESS", "KIMI-REFRESH"] {
            assert!(!message.contains(secret), "Display leaked {secret}");
            assert!(!debug.contains(secret), "Debug leaked {secret}");
        }
    }

    #[test]
    fn save_kimi_creates_private_auth_file_on_unix() {
        let dir = TestDir::new("kimi_permissions");
        let store = KimiAuthStore::at(dir.auth_path());

        store.save_kimi(&kimi_credential()).unwrap();

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(dir.auth_path())
                .unwrap()
                .permissions()
                .mode()
                & 0o777;
            assert_eq!(mode, 0o600);
        }
    }

    #[test]
    fn kimi_expiry_helpers_distinguish_fresh_and_expired_tokens() {
        // Expiry far enough out that the refresh margin doesn't reach it.
        let expires_at = 10 * KIMI_REFRESH_MARGIN_MS;
        let token = KimiOAuthCredential::new("KIMI-ACCESS", "KIMI-REFRESH", expires_at);

        assert!(token.is_fresh_at(0));
        assert!(token.is_expired_at(expires_at));
        assert!(!token.is_fresh_at(expires_at));
    }

    /// dirge-iki5: a Kimi token inside the refresh margin counts as expired, so
    /// it gets renewed while the current one still works. Without this a
    /// request could pass the check with milliseconds left and still land after
    /// expiry — and the resulting 401 is classified `ErrorKind::Auth`, which is
    /// never retried, so the whole turn dies.
    #[test]
    fn kimi_token_inside_the_refresh_margin_is_treated_as_expired() {
        let expires_at = 10 * KIMI_REFRESH_MARGIN_MS;
        let token = KimiOAuthCredential::new("KIMI-ACCESS", "KIMI-REFRESH", expires_at);

        // One ms before the margin opens: still fresh.
        assert!(token.is_fresh_at(expires_at - KIMI_REFRESH_MARGIN_MS - 1));
        // Exactly at the margin boundary, and inside it: refresh now.
        assert!(token.is_expired_at(expires_at - KIMI_REFRESH_MARGIN_MS));
        assert!(token.is_expired_at(expires_at - 1));
    }

    #[test]
    fn kimi_credential_debug_redacts_tokens() {
        let debug = format!("{:?}", kimi_credential());

        assert!(debug.contains("[REDACTED]"));
        assert!(!debug.contains("KIMI-ACCESS"));
        assert!(!debug.contains("KIMI-REFRESH"));
    }
}