Swadhin Biswas feat: implement mervelas cli engine, built-in tools, and reactive UI · 4/3/2026
0358986
2373 lines · 73.7 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
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
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
import chalk from "chalk";
import { exec } from "child_process";
import { execa } from "execa";
import { mkdir, readFile, stat } from "fs/promises";
import memoize from "lodash-es/memoize.js";
import { homedir } from "os";
import { join } from "path";
import { PRODUCT_NAME, PRODUCT_SLUG } from "src/constants/product.js";
import { CLAUDE_AI_PROFILE_SCOPE } from "src/constants/oauth.js";
import {
  type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
  logEvent,
} from "src/services/analytics/index.js";
import { getModelStrings } from "src/utils/model/modelStrings.js";
import { getAPIProvider } from "src/utils/model/providers.js";
import {
  getIsNonInteractiveSession,
  preferThirdPartyAuthentication,
} from "../bootstrap/state.js";
import {
  getMockSubscriptionType,
  shouldUseMockSubscription,
} from "../services/mockRateLimits.js";
import {
  isOAuthTokenExpired,
  refreshOAuthToken,
  shouldUseClaudeAIAuth,
} from "../services/oauth/client.js";
import { getOauthProfileFromOauthToken } from "../services/oauth/getOauthProfile.js";
import type { OAuthTokens, SubscriptionType } from "../services/oauth/types.js";
import {
  getApiKeyFromFileDescriptor,
  getOAuthTokenFromFileDescriptor,
} from "./authFileDescriptor.js";
import {
  maybeRemoveApiKeyFromMacOSKeychainThrows,
  normalizeApiKeyForConfig,
} from "./authPortable.js";
import {
  checkStsCallerIdentity,
  clearAwsIniCache,
  isValidAwsStsOutput,
} from "./aws.js";
import { AwsAuthStatusManager } from "./awsAuthStatusManager.js";
import { clearBetasCaches } from "./betas.js";
import {
  type AccountInfo,
  checkHasTrustDialogAccepted,
  getGlobalConfig,
  saveGlobalConfig,
} from "./config.js";
import { logAntError, logForDebugging } from "./debug.js";
import {
  getClaudeConfigHomeDir,
  isBareMode,
  isEnvTruthy,
  isRunningOnHomespace,
} from "./envUtils.js";
import { errorMessage } from "./errors.js";
import { execSyncWithDefaults_DEPRECATED } from "./execFileNoThrow.js";
import * as lockfile from "./lockfile.js";
import { logError } from "./log.js";
import { memoizeWithTTLAsync } from "./memoize.js";
import { getSecureStorage } from "./secureStorage/index.js";
import {
  clearLegacyApiKeyPrefetch,
  getLegacyApiKeyPrefetchResult,
} from "./secureStorage/keychainPrefetch.js";
import {
  clearKeychainCache,
  getMacOsKeychainStorageServiceName,
  getMacOsKeychainStorageServiceNames,
  getUsername,
} from "./secureStorage/macOsKeychainHelpers.js";
import {
  getSettings_DEPRECATED,
  getSettingsForSource,
} from "./settings/settings.js";
import { sleep } from "./sleep.js";
import { jsonParse } from "./slowOperations.js";
import { clearToolSchemaCache } from "./toolSchemaCache.js";

/** Default TTL for API key helper cache in milliseconds (5 minutes) */
const DEFAULT_API_KEY_HELPER_TTL = 5 * 60 * 1000;

/**
 * CCR and Claude Desktop spawn the CLI with OAuth and should never fall back
 * to the user's ~/.mervelas/settings.json API-key config (apiKeyHelper,
 * env.ANTHROPIC_API_KEY, env.ANTHROPIC_AUTH_TOKEN). Those settings exist for
 * the user's terminal CLI, not managed sessions. Without this guard, a user
 * who runs `claude` in their terminal with an API key sees every CCD session
 * also use that key — and fail if it's stale/wrong-org.
 */
function isManagedOAuthContext(): boolean {
  return (
    isEnvTruthy(process.env.CLAUDE_CODE_REMOTE) ||
    process.env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop"
  );
}

/** Whether we are supporting direct 1P auth. */
// this code is closely related to getAuthTokenSource
export function isAnthropicAuthEnabled(): boolean {
  // --bare: API-key-only, never OAuth.
  if (isBareMode()) return false;

  if (getAPIProvider() !== "firstParty") {
    return false;
  }

  // `claude ssh` remote: ANTHROPIC_UNIX_SOCKET tunnels API calls through a
  // local auth-injecting proxy. The launcher sets CLAUDE_CODE_OAUTH_TOKEN as a
  // placeholder iff the local side is a subscriber (so the remote includes the
  // oauth-2025 beta header to match what the proxy will inject). The remote's
  // ~/.claude settings (apiKeyHelper, settings.env.ANTHROPIC_API_KEY) MUST NOT
  // flip this — they'd cause a header mismatch with the proxy and a bogus
  // "invalid x-api-key" from the API. See src/ssh/sshAuthProxy.ts.
  if (process.env.ANTHROPIC_UNIX_SOCKET) {
    return !!process.env.CLAUDE_CODE_OAUTH_TOKEN;
  }

  const is3P =
    isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK) ||
    isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX) ||
    isEnvTruthy(process.env.CLAUDE_CODE_USE_FOUNDRY);

  // Check if user has configured an external API key source
  // This allows externally-provided API keys to work (without requiring proxy configuration)
  const settings = getSettings_DEPRECATED() || {};
  const apiKeyHelper = settings.apiKeyHelper;
  const hasExternalAuthToken =
    process.env.ANTHROPIC_AUTH_TOKEN ||
    apiKeyHelper ||
    process.env.CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR;

  // Check if API key is from an external source (not managed by /login)
  const { source: apiKeySource } = getAnthropicApiKeyWithSource({
    skipRetrievingKeyFromApiKeyHelper: true,
  });
  const hasExternalApiKey =
    apiKeySource === "ANTHROPIC_API_KEY" || apiKeySource === "apiKeyHelper";

  // Disable Anthropic auth if:
  // 1. Using 3rd party services (Bedrock/Vertex/Foundry)
  // 2. User has an external API key (regardless of proxy configuration)
  // 3. User has an external auth token (regardless of proxy configuration)
  // this may cause issues if users have complex proxy / gateway "client-side creds" auth scenarios,
  // e.g. if they want to set X-Api-Key to a gateway key but use Anthropic OAuth for the Authorization
  // if we get reports of that, we should probably add an env var to force OAuth enablement
  const shouldDisableAuth =
    is3P ||
    (hasExternalAuthToken && !isManagedOAuthContext()) ||
    (hasExternalApiKey && !isManagedOAuthContext());

  return !shouldDisableAuth;
}

/** Where the auth token is being sourced from, if any. */
// this code is closely related to isAnthropicAuthEnabled
export function getAuthTokenSource() {
  // --bare: API-key-only. apiKeyHelper (from --settings) is the only
  // bearer-token-shaped source allowed. OAuth env vars, FD tokens, and
  // keychain are ignored.
  if (isBareMode()) {
    if (getConfiguredApiKeyHelper()) {
      return { source: "apiKeyHelper" as const, hasToken: true };
    }
    return { source: "none" as const, hasToken: false };
  }

  if (getAPIProvider() !== "firstParty") {
    return { source: "none" as const, hasToken: false };
  }

  if (process.env.ANTHROPIC_AUTH_TOKEN && !isManagedOAuthContext()) {
    return { source: "ANTHROPIC_AUTH_TOKEN" as const, hasToken: true };
  }

  if (process.env.CLAUDE_CODE_OAUTH_TOKEN) {
    return { source: "CLAUDE_CODE_OAUTH_TOKEN" as const, hasToken: true };
  }

  // Check for OAuth token from file descriptor (or its CCR disk fallback)
  const oauthTokenFromFd = getOAuthTokenFromFileDescriptor();
  if (oauthTokenFromFd) {
    // getOAuthTokenFromFileDescriptor has a disk fallback for CCR subprocesses
    // that can't inherit the pipe FD. Distinguish by env var presence so the
    // org-mismatch message doesn't tell the user to unset a variable that
    // doesn't exist. Call sites fall through correctly — the new source is
    // !== 'none' (cli/handlers/auth.ts → oauth_token) and not in the
    // isEnvVarToken set (auth.ts:1844 → generic re-login message).
    if (process.env.CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR) {
      return {
        source: "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR" as const,
        hasToken: true,
      };
    }
    return {
      source: "CCR_OAUTH_TOKEN_FILE" as const,
      hasToken: true,
    };
  }

  // Check if apiKeyHelper is configured without executing it
  // This prevents security issues where arbitrary code could execute before trust is established
  const apiKeyHelper = getConfiguredApiKeyHelper();
  if (apiKeyHelper && !isManagedOAuthContext()) {
    return { source: "apiKeyHelper" as const, hasToken: true };
  }

  const oauthTokens = getClaudeAIOAuthTokens();
  if (shouldUseClaudeAIAuth(oauthTokens?.scopes) && oauthTokens?.accessToken) {
    return { source: "claude.ai" as const, hasToken: true };
  }

  return { source: "none" as const, hasToken: false };
}

export type ApiKeySource =
  | "ANTHROPIC_API_KEY"
  | "apiKeyHelper"
  | "/login managed key"
  | "none";

export type OpenAIApiKeySource =
  | "OPENAI_API_KEY"
  | "OPENAI_ACCESS_TOKEN"
  | "CODEX_ACCESS_TOKEN"
  | "/login managed OpenAI auth"
  | "/login managed OpenAI key"
  | "none";

export type OpenRouterApiKeySource =
  | "OPENROUTER_API_KEY"
  | "ANTHROPIC_AUTH_TOKEN"
  | "/login managed OpenRouter key"
  | "none";

export type OpenCodeApiKeySource =
  | "OPENCODE_API_KEY"
  | "/login managed OpenCode key"
  | "none";

export type NvidiaApiKeySource =
  | "NVIDIA_API_KEY"
  | "/login managed Nvidia key"
  | "none";

export function getAnthropicApiKey(): null | string {
  const { key } = getAnthropicApiKeyWithSource();
  return key;
}

export function hasAnthropicApiKeyAuth(): boolean {
  const { key, source } = getAnthropicApiKeyWithSource({
    skipRetrievingKeyFromApiKeyHelper: true,
  });
  return key !== null && source !== "none";
}

export function getOpenAIApiKey(): null | string {
  return getOpenAIApiKeyWithSource().key;
}

export function getOpenAIApiKeyWithSource(): {
  key: null | string;
  source: OpenAIApiKeySource;
} {
  if (process.env.OPENAI_API_KEY) {
    return { key: process.env.OPENAI_API_KEY, source: "OPENAI_API_KEY" };
  }
  if (process.env.OPENAI_ACCESS_TOKEN) {
    return {
      key: process.env.OPENAI_ACCESS_TOKEN,
      source: "OPENAI_ACCESS_TOKEN",
    };
  }
  if (process.env.CODEX_ACCESS_TOKEN) {
    return {
      key: process.env.CODEX_ACCESS_TOKEN,
      source: "CODEX_ACCESS_TOKEN",
    };
  }

  const accessToken = getGlobalConfig().openAiAccessToken;
  if (accessToken) {
    return { key: accessToken, source: "/login managed OpenAI auth" };
  }

  const key = getGlobalConfig().openAiApiKey;
  return key
    ? { key, source: "/login managed OpenAI key" }
    : { key: null, source: "none" };
}

export function getOpenRouterApiKey(): null | string {
  return getOpenRouterApiKeyWithSource().key;
}

export function getOpenRouterApiKeyWithSource(): {
  key: null | string;
  source: OpenRouterApiKeySource;
} {
  if (process.env.OPENROUTER_API_KEY) {
    return {
      key: process.env.OPENROUTER_API_KEY,
      source: "OPENROUTER_API_KEY",
    };
  }
  if (process.env.ANTHROPIC_AUTH_TOKEN && getAPIProvider() === "openrouter") {
    return {
      key: process.env.ANTHROPIC_AUTH_TOKEN,
      source: "ANTHROPIC_AUTH_TOKEN",
    };
  }

  const key = getGlobalConfig().openRouterApiKey;
  return key
    ? { key, source: "/login managed OpenRouter key" }
    : { key: null, source: "none" };
}

export function getOpenCodeApiKey(): null | string {
  return getOpenCodeApiKeyWithSource().key;
}

export function getOpenCodeApiKeyWithSource(): {
  key: null | string;
  source: OpenCodeApiKeySource;
} {
  if (process.env.OPENCODE_API_KEY) {
    return { key: process.env.OPENCODE_API_KEY, source: "OPENCODE_API_KEY" };
  }

  const key = getGlobalConfig().openCodeApiKey;
  return key
    ? { key, source: "/login managed OpenCode key" }
    : { key: null, source: "none" };
}

export function getNvidiaApiKey(): null | string {
  return getNvidiaApiKeyWithSource().key;
}

export function getNvidiaApiKeyWithSource(): {
  key: null | string;
  source: NvidiaApiKeySource;
} {
  if (process.env.NVIDIA_API_KEY) {
    return { key: process.env.NVIDIA_API_KEY, source: "NVIDIA_API_KEY" };
  }

  const key = getGlobalConfig().nvidiaApiKey;
  return key
    ? { key, source: "/login managed Nvidia key" }
    : { key: null, source: "none" };
}

export function getConfiguredAuthProvider():
  | "anthropic"
  | "openrouter"
  | "openai"
  | "opencode"
  | "nvidia" {
  const storedProvider = getGlobalConfig().authProvider;
  if (storedProvider) {
    return storedProvider;
  }

  const provider = getAPIProvider();
  switch (provider) {
    case "openrouter":
      return "openrouter";
    case "openai":
      return "openai";
    case "opencode":
      return "opencode";
    case "nvidia":
      return "nvidia";
      return "openai";
    case "opencode":
      return "opencode";
    default:
      return "anthropic";
  }
}

export type OpenAIAuthTokens = {
  accessToken: string;
  refreshToken?: string | null;
  expiresAt?: number | null;
  workspaceId?: string | null;
  lastRefresh?: string | number | null;
};

export function getOpenAIAuthTokens(): OpenAIAuthTokens | null {
  const config = getGlobalConfig();
  if (!config.openAiAccessToken) {
    return null;
  }

  return {
    accessToken: config.openAiAccessToken,
    refreshToken: config.openAiRefreshToken,
    expiresAt: config.openAiTokenExpiresAt,
    workspaceId: config.openAiWorkspaceId,
  };
}

export function saveOpenAIAuthTokens(tokens: OpenAIAuthTokens): void {
  saveGlobalConfig((current) => ({
    ...current,
    authProvider: "openai",
    openAiApiKey: undefined,
    openAiAccessToken: tokens.accessToken,
    openAiRefreshToken: tokens.refreshToken ?? undefined,
    openAiTokenExpiresAt: tokens.expiresAt ?? undefined,
    openAiWorkspaceId: tokens.workspaceId ?? undefined,
  }));
}

function getCodexHomeDir(): string {
  return process.env.CODEX_HOME || join(homedir(), ".codex");
}

export async function importOpenAIAuthFromCodexCache(): Promise<OpenAIAuthTokens> {
  const authFilePath = join(getCodexHomeDir(), "auth.json");
  const raw = await readFile(authFilePath, "utf8");
  const parsed = jsonParse(raw) as {
    auth_mode?: string;
    tokens?: {
      access_token?: string;
      refresh_token?: string;
      expires_at?: number | string;
    };
    workspace_id?: string;
    last_refresh?: string | number;
  };

  const accessToken = parsed.tokens?.access_token;
  if (!accessToken) {
    throw new Error(
      `Codex auth cache at ${authFilePath} does not contain an access token.`,
    );
  }

  const expiresAtRaw = parsed.tokens?.expires_at;
  const expiresAt =
    typeof expiresAtRaw === "number"
      ? expiresAtRaw
      : typeof expiresAtRaw === "string"
        ? Date.parse(expiresAtRaw)
        : undefined;

  const tokens = {
    accessToken,
    refreshToken: parsed.tokens?.refresh_token,
    expiresAt: Number.isFinite(expiresAt) ? expiresAt : undefined,
    workspaceId: parsed.workspace_id,
    lastRefresh: parsed.last_refresh,
  } satisfies OpenAIAuthTokens;

  saveOpenAIAuthTokens(tokens);
  return tokens;
}

export async function runCodexLogin(opts?: {
  deviceAuth?: boolean;
}): Promise<OpenAIAuthTokens> {
  const args = ["login"];
  if (opts?.deviceAuth) {
    args.push("--device-auth");
  }

  const result = await execa("codex", args, {
    stdio: "inherit",
    reject: false,
  });
  if (result.exitCode !== 0) {
    throw new Error(
      `codex ${args.join(" ")} exited with code ${result.exitCode}`,
    );
  }

  return importOpenAIAuthFromCodexCache();
}

export async function refreshOpenAIAuthTokenIfNeeded(): Promise<boolean> {
  const tokens = getOpenAIAuthTokens();
  if (!tokens?.expiresAt || Date.now() < tokens.expiresAt) {
    return false;
  }

  try {
    await importOpenAIAuthFromCodexCache();
    return true;
  } catch {
    return false;
  }
}

export function getAnthropicApiKeyWithSource(
  opts: { skipRetrievingKeyFromApiKeyHelper?: boolean } = {},
): {
  key: null | string;
  source: ApiKeySource;
} {
  // --bare: hermetic auth. Only ANTHROPIC_API_KEY env or apiKeyHelper from
  // the --settings flag. Never touches keychain, config file, or approval
  // lists. 3P (Bedrock/Vertex/Foundry) uses provider creds, not this path.
  if (isBareMode()) {
    if (process.env.ANTHROPIC_API_KEY) {
      return {
        key: process.env.ANTHROPIC_API_KEY,
        source: "ANTHROPIC_API_KEY",
      };
    }
    if (getConfiguredApiKeyHelper()) {
      return {
        key: opts.skipRetrievingKeyFromApiKeyHelper
          ? null
          : getApiKeyFromApiKeyHelperCached(),
        source: "apiKeyHelper",
      };
    }
    return { key: null, source: "none" };
  }

  // On homespace, don't use ANTHROPIC_API_KEY (use Console key instead)
  // https://anthropic.slack.com/archives/C08428WSLKV/p1747331773214779
  const apiKeyEnv = isRunningOnHomespace()
    ? undefined
    : process.env.ANTHROPIC_API_KEY;

  // Always check for direct environment variable when the user ran claude --print.
  // This is useful for CI, etc.
  if (preferThirdPartyAuthentication() && apiKeyEnv) {
    return {
      key: apiKeyEnv,
      source: "ANTHROPIC_API_KEY",
    };
  }

  if (isEnvTruthy(process.env.CI) || process.env.NODE_ENV === "test") {
    // Check for API key from file descriptor first
    const apiKeyFromFd = getApiKeyFromFileDescriptor();
    if (apiKeyFromFd) {
      return {
        key: apiKeyFromFd,
        source: "ANTHROPIC_API_KEY",
      };
    }

    if (
      !apiKeyEnv &&
      !process.env.CLAUDE_CODE_OAUTH_TOKEN &&
      !process.env.CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR
    ) {
      throw new Error(
        "ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN env var is required",
      );
    }

    if (apiKeyEnv) {
      return {
        key: apiKeyEnv,
        source: "ANTHROPIC_API_KEY",
      };
    }

    // OAuth token is present but this function returns API keys only
    return {
      key: null,
      source: "none",
    };
  }
  // Check for ANTHROPIC_API_KEY before checking the apiKeyHelper or /login-managed key
  if (
    apiKeyEnv &&
    getGlobalConfig().customApiKeyResponses?.approved?.includes(
      normalizeApiKeyForConfig(apiKeyEnv),
    )
  ) {
    return {
      key: apiKeyEnv,
      source: "ANTHROPIC_API_KEY",
    };
  }

  // Check for API key from file descriptor
  const apiKeyFromFd = getApiKeyFromFileDescriptor();
  if (apiKeyFromFd) {
    return {
      key: apiKeyFromFd,
      source: "ANTHROPIC_API_KEY",
    };
  }

  // Check for apiKeyHelper — use sync cache, never block
  const apiKeyHelperCommand = getConfiguredApiKeyHelper();
  if (apiKeyHelperCommand) {
    if (opts.skipRetrievingKeyFromApiKeyHelper) {
      return {
        key: null,
        source: "apiKeyHelper",
      };
    }
    // Cache may be cold (helper hasn't finished yet). Return null with
    // source='apiKeyHelper' rather than falling through to keychain —
    // apiKeyHelper must win. Callers needing a real key must await
    // getApiKeyFromApiKeyHelper() first (client.ts, useApiKeyVerification do).
    return {
      key: getApiKeyFromApiKeyHelperCached(),
      source: "apiKeyHelper",
    };
  }

  const apiKeyFromConfigOrMacOSKeychain = getApiKeyFromConfigOrMacOSKeychain();
  if (apiKeyFromConfigOrMacOSKeychain) {
    return apiKeyFromConfigOrMacOSKeychain;
  }

  return {
    key: null,
    source: "none",
  };
}

/**
 * Get the configured apiKeyHelper from settings.
 * In bare mode, only the --settings flag source is consulted — apiKeyHelper
 * from ~/.mervelas/settings.json or project settings is ignored.
 */
export function getConfiguredApiKeyHelper(): string | undefined {
  if (isBareMode()) {
    return getSettingsForSource("flagSettings")?.apiKeyHelper;
  }
  const mergedSettings = getSettings_DEPRECATED() || {};
  return mergedSettings.apiKeyHelper;
}

/**
 * Check if the configured apiKeyHelper comes from project settings (projectSettings or localSettings)
 */
function isApiKeyHelperFromProjectOrLocalSettings(): boolean {
  const apiKeyHelper = getConfiguredApiKeyHelper();
  if (!apiKeyHelper) {
    return false;
  }

  const projectSettings = getSettingsForSource("projectSettings");
  const localSettings = getSettingsForSource("localSettings");
  return (
    projectSettings?.apiKeyHelper === apiKeyHelper ||
    localSettings?.apiKeyHelper === apiKeyHelper
  );
}

/**
 * Get the configured awsAuthRefresh from settings
 */
function getConfiguredAwsAuthRefresh(): string | undefined {
  const mergedSettings = getSettings_DEPRECATED() || {};
  return mergedSettings.awsAuthRefresh;
}

/**
 * Check if the configured awsAuthRefresh comes from project settings
 */
export function isAwsAuthRefreshFromProjectSettings(): boolean {
  const awsAuthRefresh = getConfiguredAwsAuthRefresh();
  if (!awsAuthRefresh) {
    return false;
  }

  const projectSettings = getSettingsForSource("projectSettings");
  const localSettings = getSettingsForSource("localSettings");
  return (
    projectSettings?.awsAuthRefresh === awsAuthRefresh ||
    localSettings?.awsAuthRefresh === awsAuthRefresh
  );
}

/**
 * Get the configured awsCredentialExport from settings
 */
function getConfiguredAwsCredentialExport(): string | undefined {
  const mergedSettings = getSettings_DEPRECATED() || {};
  return mergedSettings.awsCredentialExport;
}

/**
 * Check if the configured awsCredentialExport comes from project settings
 */
export function isAwsCredentialExportFromProjectSettings(): boolean {
  const awsCredentialExport = getConfiguredAwsCredentialExport();
  if (!awsCredentialExport) {
    return false;
  }

  const projectSettings = getSettingsForSource("projectSettings");
  const localSettings = getSettingsForSource("localSettings");
  return (
    projectSettings?.awsCredentialExport === awsCredentialExport ||
    localSettings?.awsCredentialExport === awsCredentialExport
  );
}

/**
 * Calculate TTL in milliseconds for the API key helper cache
 * Uses CLAUDE_CODE_API_KEY_HELPER_TTL_MS env var if set and valid,
 * otherwise defaults to 5 minutes
 */
export function calculateApiKeyHelperTTL(): number {
  const envTtl = process.env.CLAUDE_CODE_API_KEY_HELPER_TTL_MS;

  if (envTtl) {
    const parsed = parseInt(envTtl, 10);
    if (!Number.isNaN(parsed) && parsed >= 0) {
      return parsed;
    }
    logForDebugging(
      `Found CLAUDE_CODE_API_KEY_HELPER_TTL_MS env var, but it was not a valid number. Got ${envTtl}`,
      { level: "error" },
    );
  }

  return DEFAULT_API_KEY_HELPER_TTL;
}

// Async API key helper with sync cache for non-blocking reads.
// Epoch bumps on clearApiKeyHelperCache() — orphaned executions check their
// captured epoch before touching module state so a settings-change or 401-retry
// mid-flight can't clobber the newer cache/inflight.
let _apiKeyHelperCache: { value: string; timestamp: number } | null = null;
let _apiKeyHelperInflight: {
  promise: Promise<string | null>;
  // Only set on cold launches (user is waiting); null for SWR background refreshes.
  startedAt: number | null;
} | null = null;
let _apiKeyHelperEpoch = 0;

export function getApiKeyHelperElapsedMs(): number {
  const startedAt = _apiKeyHelperInflight?.startedAt;
  return startedAt ? Date.now() - startedAt : 0;
}

export async function getApiKeyFromApiKeyHelper(
  isNonInteractiveSession: boolean,
): Promise<string | null> {
  if (!getConfiguredApiKeyHelper()) return null;
  const ttl = calculateApiKeyHelperTTL();
  if (_apiKeyHelperCache) {
    if (Date.now() - _apiKeyHelperCache.timestamp < ttl) {
      return _apiKeyHelperCache.value;
    }
    // Stale — return stale value now, refresh in the background.
    // `??=` banned here by eslint no-nullish-assign-object-call (bun bug).
    if (!_apiKeyHelperInflight) {
      _apiKeyHelperInflight = {
        promise: _runAndCache(
          isNonInteractiveSession,
          false,
          _apiKeyHelperEpoch,
        ),
        startedAt: null,
      };
    }
    return _apiKeyHelperCache.value;
  }
  // Cold cache — deduplicate concurrent calls
  if (_apiKeyHelperInflight) return _apiKeyHelperInflight.promise;
  _apiKeyHelperInflight = {
    promise: _runAndCache(isNonInteractiveSession, true, _apiKeyHelperEpoch),
    startedAt: Date.now(),
  };
  return _apiKeyHelperInflight.promise;
}

async function _runAndCache(
  isNonInteractiveSession: boolean,
  isCold: boolean,
  epoch: number,
): Promise<string | null> {
  try {
    const value = await _executeApiKeyHelper(isNonInteractiveSession);
    if (epoch !== _apiKeyHelperEpoch) return value;
    if (value !== null) {
      _apiKeyHelperCache = { value, timestamp: Date.now() };
    }
    return value;
  } catch (e) {
    if (epoch !== _apiKeyHelperEpoch) return " ";
    const detail = e instanceof Error ? e.message : String(e);
    // biome-ignore lint/suspicious/noConsole: user-configured script failed; must be visible without --debug
    console.error(chalk.red(`apiKeyHelper failed: ${detail}`));
    logForDebugging(`Error getting API key from apiKeyHelper: ${detail}`, {
      level: "error",
    });
    // SWR path: a transient failure shouldn't replace a working key with
    // the ' ' sentinel — keep serving the stale value and bump timestamp
    // so we don't hammer-retry every call.
    if (!isCold && _apiKeyHelperCache && _apiKeyHelperCache.value !== " ") {
      _apiKeyHelperCache = { ..._apiKeyHelperCache, timestamp: Date.now() };
      return _apiKeyHelperCache.value;
    }
    // Cold cache or prior error — cache ' ' so callers don't fall back to OAuth
    _apiKeyHelperCache = { value: " ", timestamp: Date.now() };
    return " ";
  } finally {
    if (epoch === _apiKeyHelperEpoch) {
      _apiKeyHelperInflight = null;
    }
  }
}

async function _executeApiKeyHelper(
  isNonInteractiveSession: boolean,
): Promise<string | null> {
  const apiKeyHelper = getConfiguredApiKeyHelper();
  if (!apiKeyHelper) {
    return null;
  }

  if (isApiKeyHelperFromProjectOrLocalSettings()) {
    const hasTrust = checkHasTrustDialogAccepted();
    if (!hasTrust && !isNonInteractiveSession) {
      const error = new Error(
        `Security: apiKeyHelper executed before workspace trust is confirmed. If you see this message, post in ${MACRO.FEEDBACK_CHANNEL}.`,
      );
      logAntError("apiKeyHelper invoked before trust check", error);
      logEvent("tengu_apiKeyHelper_missing_trust11", {});
      return null;
    }
  }

  const result = await execa(apiKeyHelper, {
    shell: true,
    timeout: 10 * 60 * 1000,
    reject: false,
  });
  if (result.failed) {
    // reject:false — execa resolves on exit≠0/timeout, stderr is on result
    const why = result.timedOut ? "timed out" : `exited ${result.exitCode}`;
    const stderr = result.stderr?.trim();
    throw new Error(stderr ? `${why}: ${stderr}` : why);
  }
  const stdout = result.stdout?.trim();
  if (!stdout) {
    throw new Error("did not return a value");
  }
  return stdout;
}

/**
 * Sync cache reader — returns the last fetched apiKeyHelper value without executing.
 * Returns stale values to match SWR semantics of the async reader.
 * Returns null only if the async fetch hasn't completed yet.
 */
export function getApiKeyFromApiKeyHelperCached(): string | null {
  return _apiKeyHelperCache?.value ?? null;
}

export function clearApiKeyHelperCache(): void {
  _apiKeyHelperEpoch++;
  _apiKeyHelperCache = null;
  _apiKeyHelperInflight = null;
}

export function prefetchApiKeyFromApiKeyHelperIfSafe(
  isNonInteractiveSession: boolean,
): void {
  // Skip if trust not yet accepted — the inner _executeApiKeyHelper check
  // would catch this too, but would fire a false-positive analytics event.
  if (
    isApiKeyHelperFromProjectOrLocalSettings() &&
    !checkHasTrustDialogAccepted()
  ) {
    return;
  }
  void getApiKeyFromApiKeyHelper(isNonInteractiveSession);
}

/** Default STS credentials are one hour. We manually manage invalidation, so not too worried about this being accurate. */
const DEFAULT_AWS_STS_TTL = 60 * 60 * 1000;

/**
 * Run awsAuthRefresh to perform interactive authentication (e.g., aws sso login)
 * Streams output in real-time for user visibility
 */
async function runAwsAuthRefresh(): Promise<boolean> {
  const awsAuthRefresh = getConfiguredAwsAuthRefresh();

  if (!awsAuthRefresh) {
    return false; // Not configured, treat as success
  }

  // SECURITY: Check if awsAuthRefresh is from project settings
  if (isAwsAuthRefreshFromProjectSettings()) {
    // Check if trust has been established for this project
    const hasTrust = checkHasTrustDialogAccepted();
    if (!hasTrust && !getIsNonInteractiveSession()) {
      const error = new Error(
        `Security: awsAuthRefresh executed before workspace trust is confirmed. If you see this message, post in ${MACRO.FEEDBACK_CHANNEL}.`,
      );
      logAntError("awsAuthRefresh invoked before trust check", error);
      logEvent("tengu_awsAuthRefresh_missing_trust", {});
      return false;
    }
  }

  try {
    logForDebugging(
      "Fetching AWS caller identity for AWS auth refresh command",
    );
    await checkStsCallerIdentity();
    logForDebugging(
      "Fetched AWS caller identity, skipping AWS auth refresh command",
    );
    return false;
  } catch {
    // only actually do the refresh if caller-identity calls
    return refreshAwsAuth(awsAuthRefresh);
  }
}

// Timeout for AWS auth refresh command (3 minutes).
// Long enough for browser-based SSO flows, short enough to prevent indefinite hangs.
const AWS_AUTH_REFRESH_TIMEOUT_MS = 3 * 60 * 1000;

export function refreshAwsAuth(awsAuthRefresh: string): Promise<boolean> {
  logForDebugging("Running AWS auth refresh command");
  // Start tracking authentication status
  const authStatusManager = AwsAuthStatusManager.getInstance();
  authStatusManager.startAuthentication();

  return new Promise((resolve) => {
    const refreshProc = exec(awsAuthRefresh, {
      timeout: AWS_AUTH_REFRESH_TIMEOUT_MS,
    });
    refreshProc.stdout!.on("data", (data) => {
      const output = data.toString().trim();
      if (output) {
        // Add output to status manager for UI display
        authStatusManager.addOutput(output);
        // Also log for debugging
        logForDebugging(output, { level: "debug" });
      }
    });

    refreshProc.stderr!.on("data", (data) => {
      const error = data.toString().trim();
      if (error) {
        authStatusManager.setError(error);
        logForDebugging(error, { level: "error" });
      }
    });

    refreshProc.on("close", (code, signal) => {
      if (code === 0) {
        logForDebugging("AWS auth refresh completed successfully");
        authStatusManager.endAuthentication(true);
        void resolve(true);
      } else {
        const timedOut = signal === "SIGTERM";
        const message = timedOut
          ? chalk.red(
              "AWS auth refresh timed out after 3 minutes. Run your auth command manually in a separate terminal.",
            )
          : chalk.red(
              "Error running awsAuthRefresh (in settings or ~/.claude.json):",
            );
        // biome-ignore lint/suspicious/noConsole:: intentional console output
        console.error(message);
        authStatusManager.endAuthentication(false);
        void resolve(false);
      }
    });
  });
}

/**
 * Run awsCredentialExport to get credentials and set environment variables
 * Expects JSON output containing AWS credentials
 */
async function getAwsCredsFromCredentialExport(): Promise<{
  accessKeyId: string;
  secretAccessKey: string;
  sessionToken: string;
} | null> {
  const awsCredentialExport = getConfiguredAwsCredentialExport();

  if (!awsCredentialExport) {
    return null;
  }

  // SECURITY: Check if awsCredentialExport is from project settings
  if (isAwsCredentialExportFromProjectSettings()) {
    // Check if trust has been established for this project
    const hasTrust = checkHasTrustDialogAccepted();
    if (!hasTrust && !getIsNonInteractiveSession()) {
      const error = new Error(
        `Security: awsCredentialExport executed before workspace trust is confirmed. If you see this message, post in ${MACRO.FEEDBACK_CHANNEL}.`,
      );
      logAntError("awsCredentialExport invoked before trust check", error);
      logEvent("tengu_awsCredentialExport_missing_trust", {});
      return null;
    }
  }

  try {
    logForDebugging(
      "Fetching AWS caller identity for credential export command",
    );
    await checkStsCallerIdentity();
    logForDebugging(
      "Fetched AWS caller identity, skipping AWS credential export command",
    );
    return null;
  } catch {
    // only actually do the export if caller-identity calls
    try {
      logForDebugging("Running AWS credential export command");
      const result = await execa(awsCredentialExport, {
        shell: true,
        reject: false,
      });
      if (result.exitCode !== 0 || !result.stdout) {
        throw new Error("awsCredentialExport did not return a valid value");
      }

      // Parse the JSON output from aws sts commands
      const awsOutput = jsonParse(result.stdout.trim());

      if (!isValidAwsStsOutput(awsOutput)) {
        throw new Error(
          "awsCredentialExport did not return valid AWS STS output structure",
        );
      }

      logForDebugging("AWS credentials retrieved from awsCredentialExport");
      return {
        accessKeyId: awsOutput.Credentials.AccessKeyId,
        secretAccessKey: awsOutput.Credentials.SecretAccessKey,
        sessionToken: awsOutput.Credentials.SessionToken,
      };
    } catch (e) {
      const message = chalk.red(
        "Error getting AWS credentials from awsCredentialExport (in settings or ~/.claude.json):",
      );
      if (e instanceof Error) {
        // biome-ignore lint/suspicious/noConsole:: intentional console output
        console.error(message, e.message);
      } else {
        // biome-ignore lint/suspicious/noConsole:: intentional console output
        console.error(message, e);
      }
      return null;
    }
  }
}

/**
 * Refresh AWS authentication and get credentials with cache clearing
 * This combines runAwsAuthRefresh, getAwsCredsFromCredentialExport, and clearAwsIniCache
 * to ensure fresh credentials are always used
 */
export const refreshAndGetAwsCredentials = memoizeWithTTLAsync(
  async (): Promise<{
    accessKeyId: string;
    secretAccessKey: string;
    sessionToken: string;
  } | null> => {
    // First run auth refresh if needed
    const refreshed = await runAwsAuthRefresh();

    // Get credentials from export
    const credentials = await getAwsCredsFromCredentialExport();

    // Clear AWS INI cache to ensure fresh credentials are used
    if (refreshed || credentials) {
      await clearAwsIniCache();
    }

    return credentials;
  },
  DEFAULT_AWS_STS_TTL,
);

export function clearAwsCredentialsCache(): void {
  refreshAndGetAwsCredentials.cache.clear();
}

/**
 * Get the configured gcpAuthRefresh from settings
 */
function getConfiguredGcpAuthRefresh(): string | undefined {
  const mergedSettings = getSettings_DEPRECATED() || {};
  return mergedSettings.gcpAuthRefresh;
}

/**
 * Check if the configured gcpAuthRefresh comes from project settings
 */
export function isGcpAuthRefreshFromProjectSettings(): boolean {
  const gcpAuthRefresh = getConfiguredGcpAuthRefresh();
  if (!gcpAuthRefresh) {
    return false;
  }

  const projectSettings = getSettingsForSource("projectSettings");
  const localSettings = getSettingsForSource("localSettings");
  return (
    projectSettings?.gcpAuthRefresh === gcpAuthRefresh ||
    localSettings?.gcpAuthRefresh === gcpAuthRefresh
  );
}

/** Short timeout for the GCP credentials probe. Without this, when no local
 *  credential source exists (no ADC file, no env var), google-auth-library falls
 *  through to the GCE metadata server which hangs ~12s outside GCP. */
const GCP_CREDENTIALS_CHECK_TIMEOUT_MS = 5_000;

/**
 * Check if GCP credentials are currently valid by attempting to get an access token.
 * This uses the same authentication chain that the Vertex SDK uses.
 */
export async function checkGcpCredentialsValid(): Promise<boolean> {
  try {
    // Dynamically import to avoid loading google-auth-library unnecessarily
    const { GoogleAuth } = await import("google-auth-library");
    const auth = new GoogleAuth({
      scopes: ["https://www.googleapis.com/auth/cloud-platform"],
    });
    const probe = (async () => {
      const client = await auth.getClient();
      await client.getAccessToken();
    })();
    const timeout = sleep(GCP_CREDENTIALS_CHECK_TIMEOUT_MS).then(() => {
      throw new GcpCredentialsTimeoutError("GCP credentials check timed out");
    });
    await Promise.race([probe, timeout]);
    return true;
  } catch {
    return false;
  }
}

/** Default GCP credential TTL - 1 hour to match typical ADC token lifetime */
const DEFAULT_GCP_CREDENTIAL_TTL = 60 * 60 * 1000;

/**
 * Run gcpAuthRefresh to perform interactive authentication (e.g., gcloud auth application-default login)
 * Streams output in real-time for user visibility
 */
async function runGcpAuthRefresh(): Promise<boolean> {
  const gcpAuthRefresh = getConfiguredGcpAuthRefresh();

  if (!gcpAuthRefresh) {
    return false; // Not configured, treat as success
  }

  // SECURITY: Check if gcpAuthRefresh is from project settings
  if (isGcpAuthRefreshFromProjectSettings()) {
    // Check if trust has been established for this project
    // Pass true to indicate this is a dangerous feature that requires trust
    const hasTrust = checkHasTrustDialogAccepted();
    if (!hasTrust && !getIsNonInteractiveSession()) {
      const error = new Error(
        `Security: gcpAuthRefresh executed before workspace trust is confirmed. If you see this message, post in ${MACRO.FEEDBACK_CHANNEL}.`,
      );
      logAntError("gcpAuthRefresh invoked before trust check", error);
      logEvent("tengu_gcpAuthRefresh_missing_trust", {});
      return false;
    }
  }

  try {
    logForDebugging("Checking GCP credentials validity for auth refresh");
    const isValid = await checkGcpCredentialsValid();
    if (isValid) {
      logForDebugging(
        "GCP credentials are valid, skipping auth refresh command",
      );
      return false;
    }
  } catch {
    // Credentials check failed, proceed with refresh
  }

  return refreshGcpAuth(gcpAuthRefresh);
}

// Timeout for GCP auth refresh command (3 minutes).
// Long enough for browser-based auth flows, short enough to prevent indefinite hangs.
const GCP_AUTH_REFRESH_TIMEOUT_MS = 3 * 60 * 1000;

export function refreshGcpAuth(gcpAuthRefresh: string): Promise<boolean> {
  logForDebugging("Running GCP auth refresh command");
  // Start tracking authentication status. AwsAuthStatusManager is cloud-provider-agnostic
  // despite the name — print.ts emits its updates as generic SDK 'auth_status' messages.
  const authStatusManager = AwsAuthStatusManager.getInstance();
  authStatusManager.startAuthentication();

  return new Promise((resolve) => {
    const refreshProc = exec(gcpAuthRefresh, {
      timeout: GCP_AUTH_REFRESH_TIMEOUT_MS,
    });
    refreshProc.stdout!.on("data", (data) => {
      const output = data.toString().trim();
      if (output) {
        // Add output to status manager for UI display
        authStatusManager.addOutput(output);
        // Also log for debugging
        logForDebugging(output, { level: "debug" });
      }
    });

    refreshProc.stderr!.on("data", (data) => {
      const error = data.toString().trim();
      if (error) {
        authStatusManager.setError(error);
        logForDebugging(error, { level: "error" });
      }
    });

    refreshProc.on("close", (code, signal) => {
      if (code === 0) {
        logForDebugging("GCP auth refresh completed successfully");
        authStatusManager.endAuthentication(true);
        void resolve(true);
      } else {
        const timedOut = signal === "SIGTERM";
        const message = timedOut
          ? chalk.red(
              "GCP auth refresh timed out after 3 minutes. Run your auth command manually in a separate terminal.",
            )
          : chalk.red(
              "Error running gcpAuthRefresh (in settings or ~/.claude.json):",
            );
        // biome-ignore lint/suspicious/noConsole:: intentional console output
        console.error(message);
        authStatusManager.endAuthentication(false);
        void resolve(false);
      }
    });
  });
}

/**
 * Refresh GCP authentication if needed.
 * This function checks if credentials are valid and runs the refresh command if not.
 * Memoized with TTL to avoid excessive refresh attempts.
 */
export const refreshGcpCredentialsIfNeeded = memoizeWithTTLAsync(
  async (): Promise<boolean> => {
    // Run auth refresh if needed
    const refreshed = await runGcpAuthRefresh();
    return refreshed;
  },
  DEFAULT_GCP_CREDENTIAL_TTL,
);

export function clearGcpCredentialsCache(): void {
  refreshGcpCredentialsIfNeeded.cache.clear();
}

/**
 * Prefetches GCP credentials only if workspace trust has already been established.
 * This allows us to start the potentially slow GCP commands early for trusted workspaces
 * while maintaining security for untrusted ones.
 *
 * Returns void to prevent misuse - use refreshGcpCredentialsIfNeeded() to actually refresh.
 */
export function prefetchGcpCredentialsIfSafe(): void {
  // Check if gcpAuthRefresh is configured
  const gcpAuthRefresh = getConfiguredGcpAuthRefresh();

  if (!gcpAuthRefresh) {
    return;
  }

  // Check if gcpAuthRefresh is from project settings
  if (isGcpAuthRefreshFromProjectSettings()) {
    // Only prefetch if trust has already been established
    const hasTrust = checkHasTrustDialogAccepted();
    if (!hasTrust && !getIsNonInteractiveSession()) {
      // Don't prefetch - wait for trust to be established first
      return;
    }
  }

  // Safe to prefetch - either not from project settings or trust already established
  void refreshGcpCredentialsIfNeeded();
}

/**
 * Prefetches AWS credentials only if workspace trust has already been established.
 * This allows us to start the potentially slow AWS commands early for trusted workspaces
 * while maintaining security for untrusted ones.
 *
 * Returns void to prevent misuse - use refreshAndGetAwsCredentials() to actually retrieve credentials.
 */
export function prefetchAwsCredentialsAndBedRockInfoIfSafe(): void {
  // Check if either AWS command is configured
  const awsAuthRefresh = getConfiguredAwsAuthRefresh();
  const awsCredentialExport = getConfiguredAwsCredentialExport();

  if (!awsAuthRefresh && !awsCredentialExport) {
    return;
  }

  // Check if either command is from project settings
  if (
    isAwsAuthRefreshFromProjectSettings() ||
    isAwsCredentialExportFromProjectSettings()
  ) {
    // Only prefetch if trust has already been established
    const hasTrust = checkHasTrustDialogAccepted();
    if (!hasTrust && !getIsNonInteractiveSession()) {
      // Don't prefetch - wait for trust to be established first
      return;
    }
  }

  // Safe to prefetch - either not from project settings or trust already established
  void refreshAndGetAwsCredentials();
  getModelStrings();
}

/** @private Use {@link getAnthropicApiKey} or {@link getAnthropicApiKeyWithSource} */
export const getApiKeyFromConfigOrMacOSKeychain = memoize(
  (): { key: string; source: ApiKeySource } | null => {
    if (isBareMode()) return null;
    // TODO: migrate to SecureStorage
    if (process.platform === "darwin") {
      // keychainPrefetch.ts fires this read at main.tsx top-level in parallel
      // with module imports. If it completed, use that instead of spawning a
      // sync `security` subprocess here (~33ms).
      const prefetch = getLegacyApiKeyPrefetchResult();
      if (prefetch) {
        if (prefetch.stdout) {
          return { key: prefetch.stdout, source: "/login managed key" };
        }
        // Prefetch completed with no key — fall through to config, not keychain.
      } else {
        try {
          for (const storageServiceName of getMacOsKeychainStorageServiceNames()) {
            const result = execSyncWithDefaults_DEPRECATED(
              `security find-generic-password -a $USER -w -s "${storageServiceName}"`,
            );
            if (result) {
              return { key: result, source: "/login managed key" };
            }
          }
        } catch (e) {
          logError(e);
        }
      }
    }

    const config = getGlobalConfig();
    if (!config.primaryApiKey) {
      return null;
    }

    return { key: config.primaryApiKey, source: "/login managed key" };
  },
);

function isValidApiKey(apiKey: string): boolean {
  // Only allow alphanumeric characters, dashes, and underscores
  return /^[a-zA-Z0-9-_]+$/.test(apiKey);
}

export async function saveApiKey(apiKey: string): Promise<void> {
  if (!isValidApiKey(apiKey)) {
    throw new Error(
      "Invalid API key format. API key must contain only alphanumeric characters, dashes, and underscores.",
    );
  }

  // Store as primary API key
  await maybeRemoveApiKeyFromMacOSKeychain();
  let savedToKeychain = false;
  if (process.platform === "darwin") {
    try {
      // TODO: migrate to SecureStorage
      const storageServiceName = getMacOsKeychainStorageServiceName();
      const username = getUsername();

      // Convert to hexadecimal to avoid any escaping issues
      const hexValue = Buffer.from(apiKey, "utf-8").toString("hex");

      // Use security's interactive mode (-i) with -X (hexadecimal) option
      // This ensures credentials never appear in process command-line arguments
      // Process monitors only see "security -i", not the password
      const command = `add-generic-password -U -a "${username}" -s "${storageServiceName}" -X "${hexValue}"\n`;

      await execa("security", ["-i"], {
        input: command,
        reject: false,
      });

      logEvent("tengu_api_key_saved_to_keychain", {});
      savedToKeychain = true;
    } catch (e) {
      logError(e);
      logEvent("tengu_api_key_keychain_error", {
        error: errorMessage(
          e,
        ) as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
      });
      logEvent("tengu_api_key_saved_to_config", {});
    }
  } else {
    logEvent("tengu_api_key_saved_to_config", {});
  }

  const normalizedKey = normalizeApiKeyForConfig(apiKey);

  // Save config with all updates
  saveGlobalConfig((current) => {
    const approved = current.customApiKeyResponses?.approved ?? [];
    return {
      ...current,
      // Only save to config if keychain save failed or not on darwin
      primaryApiKey: savedToKeychain ? current.primaryApiKey : apiKey,
      customApiKeyResponses: {
        ...current.customApiKeyResponses,
        approved: approved.includes(normalizedKey)
          ? approved
          : [...approved, normalizedKey],
        rejected: current.customApiKeyResponses?.rejected ?? [],
      },
    };
  });

  // Clear memo cache
  getApiKeyFromConfigOrMacOSKeychain.cache.clear?.();
  clearLegacyApiKeyPrefetch();
}

export async function saveOpenAIApiKey(apiKey: string): Promise<void> {
  if (!isValidApiKey(apiKey)) {
    throw new Error(
      "Invalid API key format. API key must contain only alphanumeric characters, dashes, and underscores.",
    );
  }
  saveGlobalConfig((current) => ({
    ...current,
    authProvider: "openai",
    openAiAccessToken: undefined,
    openAiRefreshToken: undefined,
    openAiTokenExpiresAt: undefined,
    openAiWorkspaceId: undefined,
    openAiApiKey: apiKey,
  }));
}

export async function saveOpenRouterApiKey(apiKey: string): Promise<void> {
  if (!isValidApiKey(apiKey)) {
    throw new Error(
      "Invalid API key format. API key must contain only alphanumeric characters, dashes, and underscores.",
    );
  }
  saveGlobalConfig((current) => ({
    ...current,
    authProvider: "openrouter",
    openRouterApiKey: apiKey,
  }));
}

export async function saveOpenCodeApiKey(apiKey: string): Promise<void> {
  if (!isValidApiKey(apiKey)) {
    throw new Error(
      "Invalid API key format. API key must contain only alphanumeric characters, dashes, and underscores.",
    );
  }
  saveGlobalConfig((current) => ({
    ...current,
    authProvider: "opencode",
    openCodeApiKey: apiKey,
  }));
}

export async function saveNvidiaApiKey(apiKey: string): Promise<void> {
  if (!isValidApiKey(apiKey)) {
    throw new Error(
      "Invalid API key format. API key must contain only alphanumeric characters, dashes, and underscores.",
    );
  }
  saveGlobalConfig((current) => ({
    ...current,
    authProvider: "nvidia",
    nvidiaApiKey: apiKey,
  }));
}

export function isCustomApiKeyApproved(apiKey: string): boolean {
  const config = getGlobalConfig();
  const normalizedKey = normalizeApiKeyForConfig(apiKey);
  return (
    config.customApiKeyResponses?.approved?.includes(normalizedKey) ?? false
  );
}

export async function removeApiKey(): Promise<void> {
  await maybeRemoveApiKeyFromMacOSKeychain();

  // Also remove from config instead of returning early, for older clients
  // that set keys before we supported keychain.
  saveGlobalConfig((current) => ({
    ...current,
    primaryApiKey: undefined,
  }));

  // Clear memo cache
  getApiKeyFromConfigOrMacOSKeychain.cache.clear?.();
  clearLegacyApiKeyPrefetch();
}

export async function removeOpenAIApiKey(): Promise<void> {
  saveGlobalConfig((current) => ({
    ...current,
    openAiApiKey: undefined,
    openAiAccessToken: undefined,
    openAiRefreshToken: undefined,
    openAiTokenExpiresAt: undefined,
    openAiWorkspaceId: undefined,
  }));
}

export async function removeOpenRouterApiKey(): Promise<void> {
  saveGlobalConfig((current) => ({
    ...current,
    openRouterApiKey: undefined,
  }));
}

export async function removeOpenCodeApiKey(): Promise<void> {
  saveGlobalConfig((current) => ({
    ...current,
    openCodeApiKey: undefined,
  }));
}

export async function removeNvidiaApiKey(): Promise<void> {
  saveGlobalConfig((current) => ({
    ...current,
    nvidiaApiKey: undefined,
  }));
}

async function maybeRemoveApiKeyFromMacOSKeychain(): Promise<void> {
  try {
    await maybeRemoveApiKeyFromMacOSKeychainThrows();
  } catch (e) {
    logError(e);
  }
}

// Function to store OAuth tokens in secure storage
export function saveOAuthTokensIfNeeded(tokens: OAuthTokens): {
  success: boolean;
  warning?: string;
} {
  if (!shouldUseClaudeAIAuth(tokens.scopes)) {
    logEvent("tengu_oauth_tokens_not_claude_ai", {});
    return { success: true };
  }

  // Skip saving inference-only tokens (they come from env vars)
  if (!tokens.refreshToken || !tokens.expiresAt) {
    logEvent("tengu_oauth_tokens_inference_only", {});
    return { success: true };
  }

  const secureStorage = getSecureStorage();
  const storageBackend =
    secureStorage.name as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS;

  try {
    const storageData = secureStorage.read() || {};
    const existingOauth = storageData.claudeAiOauth;

    storageData.claudeAiOauth = {
      accessToken: tokens.accessToken,
      refreshToken: tokens.refreshToken,
      expiresAt: tokens.expiresAt,
      scopes: tokens.scopes,
      // Profile fetch in refreshOAuthToken swallows errors and returns null on
      // transient failures (network, 5xx, rate limit). Don't clobber a valid
      // stored subscription with null — fall back to the existing value.
      subscriptionType:
        tokens.subscriptionType ?? existingOauth?.subscriptionType ?? null,
      rateLimitTier:
        tokens.rateLimitTier ?? existingOauth?.rateLimitTier ?? null,
    };

    const updateStatus = secureStorage.update(storageData);

    if (updateStatus.success) {
      logEvent("tengu_oauth_tokens_saved", { storageBackend });
    } else {
      logEvent("tengu_oauth_tokens_save_failed", { storageBackend });
    }

    getClaudeAIOAuthTokens.cache?.clear?.();
    clearBetasCaches();
    clearToolSchemaCache();
    return updateStatus;
  } catch (error) {
    logError(error);
    logEvent("tengu_oauth_tokens_save_exception", {
      storageBackend,
      error: errorMessage(
        error,
      ) as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
    });
    return { success: false, warning: "Failed to save OAuth tokens" };
  }
}

export const getClaudeAIOAuthTokens = memoize((): OAuthTokens | null => {
  // --bare: API-key-only. No OAuth env tokens, no keychain, no credentials file.
  if (isBareMode()) return null;

  // Check for force-set OAuth token from environment variable
  if (process.env.CLAUDE_CODE_OAUTH_TOKEN) {
    // Return an inference-only token (unknown refresh and expiry)
    return {
      accessToken: process.env.CLAUDE_CODE_OAUTH_TOKEN,
      refreshToken: null,
      expiresAt: null,
      scopes: ["user:inference"],
      subscriptionType: null,
      rateLimitTier: null,
    };
  }

  // Check for OAuth token from file descriptor
  const oauthTokenFromFd = getOAuthTokenFromFileDescriptor();
  if (oauthTokenFromFd) {
    // Return an inference-only token (unknown refresh and expiry)
    return {
      accessToken: oauthTokenFromFd,
      refreshToken: null,
      expiresAt: null,
      scopes: ["user:inference"],
      subscriptionType: null,
      rateLimitTier: null,
    };
  }

  try {
    const secureStorage = getSecureStorage();
    const storageData = secureStorage.read();
    const oauthData = storageData?.claudeAiOauth;

    if (!oauthData?.accessToken) {
      return null;
    }

    return oauthData;
  } catch (error) {
    logError(error);
    return null;
  }
});

/**
 * Clears all OAuth token caches. Call this on 401 errors to ensure
 * the next token read comes from secure storage, not stale in-memory caches.
 * This handles the case where the local expiration check disagrees with the
 * server (e.g., due to clock corrections after token was issued).
 */
export function clearOAuthTokenCache(): void {
  getClaudeAIOAuthTokens.cache?.clear?.();
  clearKeychainCache();
}

let lastCredentialsMtimeMs = 0;

// Cross-process staleness: another CC instance may write fresh tokens to
// disk (refresh or /login), but this process's memoize caches forever.
// Without this, terminal 1's /login fixes terminal 1; terminal 2's /login
// then revokes terminal 1 server-side, and terminal 1's memoize never
// re-reads — infinite /login regress (CC-1096, GH#24317).
async function invalidateOAuthCacheIfDiskChanged(): Promise<void> {
  try {
    const { mtimeMs } = await stat(
      join(getClaudeConfigHomeDir(), ".credentials.json"),
    );
    if (mtimeMs !== lastCredentialsMtimeMs) {
      lastCredentialsMtimeMs = mtimeMs;
      clearOAuthTokenCache();
    }
  } catch {
    // ENOENT — macOS keychain path (file deleted on migration). Clear only
    // the memoize so it delegates to the keychain cache's 30s TTL instead
    // of caching forever on top. `security find-generic-password` is
    // ~15ms; bounded to once per 30s by the keychain cache.
    getClaudeAIOAuthTokens.cache?.clear?.();
  }
}

// In-flight dedup: when N claude.ai proxy connectors hit 401 with the same
// token simultaneously (common at startup — #20930), only one should clear
// caches and re-read the keychain. Without this, each call's clearOAuthTokenCache()
// nukes readInFlight in macOsKeychainStorage and triggers a fresh spawn —
// sync spawns stacked to 800ms+ of blocked render frames.
const pending401Handlers = new Map<string, Promise<boolean>>();

/**
 * Handle a 401 "OAuth token has expired" error from the API.
 *
 * This function forces a token refresh when the server says the token is expired,
 * even if our local expiration check disagrees (which can happen due to clock
 * issues when the token was issued).
 *
 * Safety: We compare the failed token with what's in keychain. If another tab
 * already refreshed (different token in keychain), we use that instead of
 * refreshing again. Concurrent calls with the same failedAccessToken are
 * deduplicated to a single keychain read.
 *
 * @param failedAccessToken - The access token that was rejected with 401
 * @returns true if we now have a valid token, false otherwise
 */
export function handleOAuth401Error(
  failedAccessToken: string,
): Promise<boolean> {
  const pending = pending401Handlers.get(failedAccessToken);
  if (pending) return pending;

  const promise = handleOAuth401ErrorImpl(failedAccessToken).finally(() => {
    pending401Handlers.delete(failedAccessToken);
  });
  pending401Handlers.set(failedAccessToken, promise);
  return promise;
}

async function handleOAuth401ErrorImpl(
  failedAccessToken: string,
): Promise<boolean> {
  // Clear caches and re-read from keychain (async — sync read blocks ~100ms/call)
  clearOAuthTokenCache();
  const currentTokens = await getClaudeAIOAuthTokensAsync();

  if (!currentTokens?.refreshToken) {
    return false;
  }

  // If keychain has a different token, another tab already refreshed - use it
  if (currentTokens.accessToken !== failedAccessToken) {
    logEvent("tengu_oauth_401_recovered_from_keychain", {});
    return true;
  }

  // Same token that failed - force refresh, bypassing local expiration check
  return checkAndRefreshOAuthTokenIfNeeded(0, true);
}

/**
 * Reads OAuth tokens asynchronously, avoiding blocking keychain reads.
 * Delegates to the sync memoized version for env var / file descriptor tokens
 * (which don't hit the keychain), and only uses async for storage reads.
 */
export async function getClaudeAIOAuthTokensAsync(): Promise<OAuthTokens | null> {
  if (isBareMode()) return null;

  // Env var and FD tokens are sync and don't hit the keychain
  if (
    process.env.CLAUDE_CODE_OAUTH_TOKEN ||
    getOAuthTokenFromFileDescriptor()
  ) {
    return getClaudeAIOAuthTokens();
  }

  try {
    const secureStorage = getSecureStorage();
    const storageData = await secureStorage.readAsync();
    const oauthData = storageData?.claudeAiOauth;
    if (!oauthData?.accessToken) {
      return null;
    }
    return oauthData;
  } catch (error) {
    logError(error);
    return null;
  }
}

// In-flight promise for deduplicating concurrent calls
let pendingRefreshCheck: Promise<boolean> | null = null;

export function checkAndRefreshOAuthTokenIfNeeded(
  retryCount = 0,
  force = false,
): Promise<boolean> {
  // Deduplicate concurrent non-retry, non-force calls
  if (retryCount === 0 && !force) {
    if (pendingRefreshCheck) {
      return pendingRefreshCheck;
    }

    const promise = checkAndRefreshOAuthTokenIfNeededImpl(retryCount, force);
    pendingRefreshCheck = promise.finally(() => {
      pendingRefreshCheck = null;
    });
    return pendingRefreshCheck;
  }

  return checkAndRefreshOAuthTokenIfNeededImpl(retryCount, force);
}

async function checkAndRefreshOAuthTokenIfNeededImpl(
  retryCount: number,
  force: boolean,
): Promise<boolean> {
  const MAX_RETRIES = 5;

  await invalidateOAuthCacheIfDiskChanged();

  // First check if token is expired with cached value
  // Skip this check if force=true (server already told us token is bad)
  const tokens = getClaudeAIOAuthTokens();
  if (!force) {
    if (!tokens?.refreshToken || !isOAuthTokenExpired(tokens.expiresAt)) {
      return false;
    }
  }

  if (!tokens?.refreshToken) {
    return false;
  }

  if (!shouldUseClaudeAIAuth(tokens.scopes)) {
    return false;
  }

  // Re-read tokens async to check if they're still expired
  // Another process might have refreshed them
  getClaudeAIOAuthTokens.cache?.clear?.();
  clearKeychainCache();
  const freshTokens = await getClaudeAIOAuthTokensAsync();
  if (
    !freshTokens?.refreshToken ||
    !isOAuthTokenExpired(freshTokens.expiresAt)
  ) {
    return false;
  }

  // Tokens are still expired, try to acquire lock and refresh
  const claudeDir = getClaudeConfigHomeDir();
  await mkdir(claudeDir, { recursive: true });

  let release;
  try {
    logEvent("tengu_oauth_token_refresh_lock_acquiring", {});
    release = await lockfile.lock(claudeDir);
    logEvent("tengu_oauth_token_refresh_lock_acquired", {});
  } catch (err) {
    if ((err as { code?: string }).code === "ELOCKED") {
      // Another process has the lock, let's retry if we haven't exceeded max retries
      if (retryCount < MAX_RETRIES) {
        logEvent("tengu_oauth_token_refresh_lock_retry", {
          retryCount: retryCount + 1,
        });
        // Wait a bit before retrying
        await sleep(1000 + Math.random() * 1000);
        return checkAndRefreshOAuthTokenIfNeededImpl(retryCount + 1, force);
      }
      logEvent("tengu_oauth_token_refresh_lock_retry_limit_reached", {
        maxRetries: MAX_RETRIES,
      });
      return false;
    }
    logError(err);
    logEvent("tengu_oauth_token_refresh_lock_error", {
      error: errorMessage(
        err,
      ) as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
    });
    return false;
  }
  try {
    // Check one more time after acquiring lock
    getClaudeAIOAuthTokens.cache?.clear?.();
    clearKeychainCache();
    const lockedTokens = await getClaudeAIOAuthTokensAsync();
    if (
      !lockedTokens?.refreshToken ||
      !isOAuthTokenExpired(lockedTokens.expiresAt)
    ) {
      logEvent("tengu_oauth_token_refresh_race_resolved", {});
      return false;
    }

    logEvent("tengu_oauth_token_refresh_starting", {});
    const refreshedTokens = await refreshOAuthToken(lockedTokens.refreshToken, {
      // For Claude.ai subscribers, omit scopes so the default
      // CLAUDE_AI_OAUTH_SCOPES applies — this allows scope expansion
      // (e.g. adding user:file_upload) on refresh without re-login.
      scopes: shouldUseClaudeAIAuth(lockedTokens.scopes)
        ? undefined
        : lockedTokens.scopes,
    });
    saveOAuthTokensIfNeeded(refreshedTokens);

    // Clear the cache after refreshing token
    getClaudeAIOAuthTokens.cache?.clear?.();
    clearKeychainCache();
    return true;
  } catch (error) {
    logError(error);

    getClaudeAIOAuthTokens.cache?.clear?.();
    clearKeychainCache();
    const currentTokens = await getClaudeAIOAuthTokensAsync();
    if (currentTokens && !isOAuthTokenExpired(currentTokens.expiresAt)) {
      logEvent("tengu_oauth_token_refresh_race_recovered", {});
      return true;
    }

    return false;
  } finally {
    logEvent("tengu_oauth_token_refresh_lock_releasing", {});
    await release();
    logEvent("tengu_oauth_token_refresh_lock_released", {});
  }
}

export function isClaudeAISubscriber(): boolean {
  if (!isAnthropicAuthEnabled()) {
    return false;
  }

  return shouldUseClaudeAIAuth(getClaudeAIOAuthTokens()?.scopes);
}

/**
 * Check if the current OAuth token has the user:profile scope.
 *
 * Real /login tokens always include this scope. Env-var and file-descriptor
 * tokens (service keys) hardcode scopes to ['user:inference'] only. Use this
 * to gate calls to profile-scoped endpoints so service key sessions don't
 * generate 403 storms against /api/oauth/profile, bootstrap, etc.
 */
export function hasProfileScope(): boolean {
  return (
    getClaudeAIOAuthTokens()?.scopes?.includes(CLAUDE_AI_PROFILE_SCOPE) ?? false
  );
}

export function is1PApiCustomer(): boolean {
  // 1P API customers are users who are NOT:
  // 1. Claude.ai subscribers (Max, Pro, Enterprise, Team)
  // 2. Vertex AI users
  // 3. AWS Bedrock users
  // 4. Foundry users

  // Exclude Vertex, Bedrock, and Foundry customers
  if (
    isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK) ||
    isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX) ||
    isEnvTruthy(process.env.CLAUDE_CODE_USE_FOUNDRY)
  ) {
    return false;
  }

  // Exclude Claude.ai subscribers
  if (isClaudeAISubscriber()) {
    return false;
  }

  // Everyone else is an API customer (OAuth API customers, direct API key users, etc.)
  return true;
}

/**
 * Gets OAuth account information when Anthropic auth is enabled.
 * Returns undefined when using external API keys or third-party services.
 */
export function getOauthAccountInfo(): AccountInfo | undefined {
  return isAnthropicAuthEnabled() ? getGlobalConfig().oauthAccount : undefined;
}

/**
 * Checks if overage/extra usage provisioning is allowed for this organization.
 * This mirrors the logic in apps/claude-ai `useIsOverageProvisioningAllowed` hook as closely as possible.
 */
export function isOverageProvisioningAllowed(): boolean {
  const accountInfo = getOauthAccountInfo();
  const billingType = accountInfo?.billingType;

  // Must be a Claude subscriber with a supported subscription type
  if (!isClaudeAISubscriber() || !billingType) {
    return false;
  }

  // only allow Stripe and mobile billing types to purchase extra usage
  if (
    billingType !== "stripe_subscription" &&
    billingType !== "stripe_subscription_contracted" &&
    billingType !== "apple_subscription" &&
    billingType !== "google_play_subscription"
  ) {
    return false;
  }

  return true;
}

// Returns whether the user has Opus access at all, regardless of whether they
// are a subscriber or PayG.
export function hasOpusAccess(): boolean {
  const subscriptionType = getSubscriptionType();

  return (
    subscriptionType === "max" ||
    subscriptionType === "enterprise" ||
    subscriptionType === "team" ||
    subscriptionType === "pro" ||
    // subscriptionType === null covers both API users and the case where
    // subscribers do not have subscription type populated. For those
    // subscribers, when in doubt, we should not limit their access to Opus.
    subscriptionType === null
  );
}

export function getSubscriptionType(): SubscriptionType | null {
  // Check for mock subscription type first (ANT-only testing)
  if (shouldUseMockSubscription()) {
    return getMockSubscriptionType();
  }

  if (!isAnthropicAuthEnabled()) {
    return null;
  }
  const oauthTokens = getClaudeAIOAuthTokens();
  if (!oauthTokens) {
    return null;
  }

  return oauthTokens.subscriptionType ?? null;
}

export function isMaxSubscriber(): boolean {
  return getSubscriptionType() === "max";
}

export function isTeamSubscriber(): boolean {
  return getSubscriptionType() === "team";
}

export function isTeamPremiumSubscriber(): boolean {
  return (
    getSubscriptionType() === "team" &&
    getRateLimitTier() === "default_claude_max_5x"
  );
}

export function isEnterpriseSubscriber(): boolean {
  return getSubscriptionType() === "enterprise";
}

export function isProSubscriber(): boolean {
  return getSubscriptionType() === "pro";
}

export function getRateLimitTier(): string | null {
  if (!isAnthropicAuthEnabled()) {
    return null;
  }
  const oauthTokens = getClaudeAIOAuthTokens();
  if (!oauthTokens) {
    return null;
  }

  return oauthTokens.rateLimitTier ?? null;
}

export function getSubscriptionName(): string {
  const subscriptionType = getSubscriptionType();

  switch (subscriptionType) {
    case "enterprise":
      return "Anthropic Enterprise";
    case "team":
      return "Anthropic Team";
    case "max":
      return "Anthropic Max";
    case "pro":
      return "Anthropic Pro";
    default:
      return `${PRODUCT_NAME} API`;
  }
}

/** Check if using third-party services (Bedrock or Vertex or Foundry) */
export function isUsing3PServices(): boolean {
  return !!(
    isEnvTruthy(process.env.CLAUDE_CODE_USE_BEDROCK) ||
    isEnvTruthy(process.env.CLAUDE_CODE_USE_VERTEX) ||
    isEnvTruthy(process.env.CLAUDE_CODE_USE_FOUNDRY)
  );
}

/**
 * Get the configured otelHeadersHelper from settings
 */
function getConfiguredOtelHeadersHelper(): string | undefined {
  const mergedSettings = getSettings_DEPRECATED() || {};
  return mergedSettings.otelHeadersHelper;
}

/**
 * Check if the configured otelHeadersHelper comes from project settings (projectSettings or localSettings)
 */
export function isOtelHeadersHelperFromProjectOrLocalSettings(): boolean {
  const otelHeadersHelper = getConfiguredOtelHeadersHelper();
  if (!otelHeadersHelper) {
    return false;
  }

  const projectSettings = getSettingsForSource("projectSettings");
  const localSettings = getSettingsForSource("localSettings");
  return (
    projectSettings?.otelHeadersHelper === otelHeadersHelper ||
    localSettings?.otelHeadersHelper === otelHeadersHelper
  );
}

// Cache for debouncing otelHeadersHelper calls
let cachedOtelHeaders: Record<string, string> | null = null;
let cachedOtelHeadersTimestamp = 0;
const DEFAULT_OTEL_HEADERS_DEBOUNCE_MS = 29 * 60 * 1000; // 29 minutes

export function getOtelHeadersFromHelper(): Record<string, string> {
  const otelHeadersHelper = getConfiguredOtelHeadersHelper();

  if (!otelHeadersHelper) {
    return {};
  }

  // Return cached headers if still valid (debounce)
  const debounceMs = parseInt(
    process.env.CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS ||
      DEFAULT_OTEL_HEADERS_DEBOUNCE_MS.toString(),
  );
  if (
    cachedOtelHeaders &&
    Date.now() - cachedOtelHeadersTimestamp < debounceMs
  ) {
    return cachedOtelHeaders;
  }

  if (isOtelHeadersHelperFromProjectOrLocalSettings()) {
    // Check if trust has been established for this project
    const hasTrust = checkHasTrustDialogAccepted();
    if (!hasTrust) {
      return {};
    }
  }

  try {
    const result = execSyncWithDefaults_DEPRECATED(otelHeadersHelper, {
      timeout: 30000, // 30 seconds - allows for auth service latency
    })
      ?.toString()
      .trim();
    if (!result) {
      throw new Error("otelHeadersHelper did not return a valid value");
    }

    const headers = jsonParse(result);
    if (
      typeof headers !== "object" ||
      headers === null ||
      Array.isArray(headers)
    ) {
      throw new Error(
        "otelHeadersHelper must return a JSON object with string key-value pairs",
      );
    }

    // Validate all values are strings
    for (const [key, value] of Object.entries(headers)) {
      if (typeof value !== "string") {
        throw new Error(
          `otelHeadersHelper returned non-string value for key "${key}": ${typeof value}`,
        );
      }
    }

    // Cache the result
    cachedOtelHeaders = headers as Record<string, string>;
    cachedOtelHeadersTimestamp = Date.now();

    return cachedOtelHeaders;
  } catch (error) {
    logError(
      new Error(
        `Error getting OpenTelemetry headers from otelHeadersHelper (in settings): ${errorMessage(error)}`,
      ),
    );
    throw error;
  }
}

function isConsumerPlan(plan: SubscriptionType): plan is "max" | "pro" {
  return plan === "max" || plan === "pro";
}

export function isConsumerSubscriber(): boolean {
  const subscriptionType = getSubscriptionType();
  return (
    isClaudeAISubscriber() &&
    subscriptionType !== null &&
    isConsumerPlan(subscriptionType)
  );
}

export type UserAccountInfo = {
  subscription?: string;
  tokenSource?: string;
  apiKeySource?: ApiKeySource;
  organization?: string;
  email?: string;
};

export function getAccountInformation() {
  const apiProvider = getAPIProvider();
  // Only provide account info for first-party Anthropic API
  if (apiProvider !== "firstParty") {
    return undefined;
  }
  const { source: authTokenSource } = getAuthTokenSource();
  const accountInfo: UserAccountInfo = {};
  if (
    authTokenSource === "CLAUDE_CODE_OAUTH_TOKEN" ||
    authTokenSource === "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR"
  ) {
    accountInfo.tokenSource = authTokenSource;
  } else if (isClaudeAISubscriber()) {
    accountInfo.subscription = getSubscriptionName();
  } else {
    accountInfo.tokenSource = authTokenSource;
  }
  const { key: apiKey, source: apiKeySource } = getAnthropicApiKeyWithSource();
  if (apiKey) {
    accountInfo.apiKeySource = apiKeySource;
  }

  // We don't know the organization if we're relying on an external API key or auth token
  if (
    authTokenSource === "claude.ai" ||
    apiKeySource === "/login managed key"
  ) {
    // Get organization name from OAuth account info
    const orgName = getOauthAccountInfo()?.organizationName;
    if (orgName) {
      accountInfo.organization = orgName;
    }
  }
  const email = getOauthAccountInfo()?.emailAddress;
  if (
    (authTokenSource === "claude.ai" ||
      apiKeySource === "/login managed key") &&
    email
  ) {
    accountInfo.email = email;
  }
  return accountInfo;
}

/**
 * Result of org validation — either success or a descriptive error.
 */
export type OrgValidationResult =
  | { valid: true }
  | { valid: false; message: string };

/**
 * Validate that the active OAuth token belongs to the organization required
 * by `forceLoginOrgUUID` in managed settings. Returns a result object
 * rather than throwing so callers can choose how to surface the error.
 *
 * Fails closed: if `forceLoginOrgUUID` is set and we cannot determine the
 * token's org (network error, missing profile data), validation fails.
 */
export async function validateForceLoginOrg(): Promise<OrgValidationResult> {
  // `claude ssh` remote: real auth lives on the local machine and is injected
  // by the proxy. The placeholder token can't be validated against the profile
  // endpoint. The local side already ran this check before establishing the session.
  if (process.env.ANTHROPIC_UNIX_SOCKET) {
    return { valid: true };
  }

  if (!isAnthropicAuthEnabled()) {
    return { valid: true };
  }

  const requiredOrgUuid =
    getSettingsForSource("policySettings")?.forceLoginOrgUUID;
  if (!requiredOrgUuid) {
    return { valid: true };
  }

  // Ensure the access token is fresh before hitting the profile endpoint.
  // No-op for env-var tokens (refreshToken is null).
  await checkAndRefreshOAuthTokenIfNeeded();

  const tokens = getClaudeAIOAuthTokens();
  if (!tokens) {
    return { valid: true };
  }

  // Always fetch the authoritative org UUID from the profile endpoint.
  // Even keychain-sourced tokens verify server-side: the cached org UUID
  // in ~/.claude.json is user-writable and cannot be trusted.
  const { source } = getAuthTokenSource();
  const isEnvVarToken =
    source === "CLAUDE_CODE_OAUTH_TOKEN" ||
    source === "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR";

  const profile = await getOauthProfileFromOauthToken(tokens.accessToken);
  if (!profile) {
    // Fail closed — we can't verify the org
    return {
      valid: false,
      message:
        `Unable to verify organization for the current authentication token.\n` +
        `This machine requires organization ${requiredOrgUuid} but the profile could not be fetched.\n` +
        `This may be a network error, or the token may lack the user:profile scope required for\n` +
        `verification (tokens from 'mervelas setup-token' do not include this scope).\n` +
        `Try again, or obtain a full-scope token via 'mervelas auth login'.`,
    };
  }

  const tokenOrgUuid = profile.organization.uuid;
  if (tokenOrgUuid === requiredOrgUuid) {
    return { valid: true };
  }

  if (isEnvVarToken) {
    const envVarName =
      source === "CLAUDE_CODE_OAUTH_TOKEN"
        ? "CLAUDE_CODE_OAUTH_TOKEN"
        : "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR";
    return {
      valid: false,
      message:
        `The ${envVarName} environment variable provides a token for a\n` +
        `different organization than required by this machine's managed settings.\n\n` +
        `Required organization: ${requiredOrgUuid}\n` +
        `Token organization:   ${tokenOrgUuid}\n\n` +
        `Remove the environment variable or obtain a token for the correct organization.`,
    };
  }

  return {
    valid: false,
    message:
      `Your authentication token belongs to organization ${tokenOrgUuid},\n` +
      `but this machine requires organization ${requiredOrgUuid}.\n\n` +
      `Please log in with the correct organization: mervelas auth login`,
  };
}

class GcpCredentialsTimeoutError extends Error {}