clikcode 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (323) hide show
  1. package/README.md +25 -14
  2. package/dist/chunk-23TDEBGZ.js +71 -0
  3. package/dist/chunk-25T3GVS7.js +425 -0
  4. package/dist/chunk-2BBELGHY.js +11 -0
  5. package/dist/chunk-2EOL5PZL.js +208 -0
  6. package/dist/chunk-2GAB36IE.js +26 -0
  7. package/dist/chunk-2OLS7V66.js +2440 -0
  8. package/dist/chunk-2QFO2URB.js +179 -0
  9. package/dist/chunk-2QWPQRSU.js +254 -0
  10. package/dist/chunk-2YPAPAR3.js +184 -0
  11. package/dist/chunk-2ZAG5372.js +33 -0
  12. package/dist/chunk-32IKAIZC.js +12507 -0
  13. package/dist/chunk-34AZEGYW.js +95 -0
  14. package/dist/chunk-34JQYQCA.js +175 -0
  15. package/dist/chunk-34ZISPAO.js +67 -0
  16. package/dist/chunk-3AAAARE6.js +46 -0
  17. package/dist/chunk-3AJ6Q3OY.js +510 -0
  18. package/dist/chunk-3B2CHX7M.js +884 -0
  19. package/dist/chunk-3BUFORRX.js +59 -0
  20. package/dist/chunk-3QLHYYFK.js +30 -0
  21. package/dist/chunk-3RXBMYKZ.js +140 -0
  22. package/dist/chunk-3TFNIJWS.js +52 -0
  23. package/dist/chunk-3W3IPDFP.js +119 -0
  24. package/dist/chunk-3WMS7SEE.js +417 -0
  25. package/dist/chunk-435ZNSZ3.js +23 -0
  26. package/dist/chunk-4AQ5NINV.js +39 -0
  27. package/dist/chunk-4GVEJ5FK.js +168 -0
  28. package/dist/chunk-4GXAO3UY.js +262 -0
  29. package/dist/chunk-4L2ZZM4Q.js +332 -0
  30. package/dist/chunk-4LPDG57B.js +17 -0
  31. package/dist/chunk-4NN3XQQT.js +223 -0
  32. package/dist/chunk-4QZEZME7.js +54 -0
  33. package/dist/chunk-4R6CSC3S.js +38 -0
  34. package/dist/chunk-4RHXTL3W.js +514 -0
  35. package/dist/chunk-4SJMPTVQ.js +18 -0
  36. package/dist/chunk-4VY7G6TX.js +114 -0
  37. package/dist/chunk-5642PBF7.js +124 -0
  38. package/dist/chunk-5B6TVO4A.js +33 -0
  39. package/dist/chunk-5BJLDUPL.js +62 -0
  40. package/dist/chunk-5HMFFJWU.js +19 -0
  41. package/dist/chunk-5IKLK33T.js +69 -0
  42. package/dist/chunk-5NQ5FFMX.js +44 -0
  43. package/dist/chunk-5QNNW5L6.js +176 -0
  44. package/dist/chunk-5SM5UAWN.js +239 -0
  45. package/dist/chunk-5WYJTA6O.js +74 -0
  46. package/dist/chunk-5ZSR2Y5T.js +227 -0
  47. package/dist/chunk-5ZWUM5GH.js +39 -0
  48. package/dist/chunk-64E7D4HY.js +364 -0
  49. package/dist/chunk-6CK466BC.js +99 -0
  50. package/dist/chunk-6ES45HHO.js +138 -0
  51. package/dist/chunk-6HYEZFGL.js +277 -0
  52. package/dist/chunk-6Y7HLXGW.js +29 -0
  53. package/dist/chunk-6YKK4FYR.js +258 -0
  54. package/dist/chunk-74WNMLMS.js +117 -0
  55. package/dist/chunk-7AULZ7OD.js +55 -0
  56. package/dist/chunk-7DOKGSUN.js +101 -0
  57. package/dist/chunk-7IH5LTIZ.js +195 -0
  58. package/dist/chunk-7ISTS5NS.js +21 -0
  59. package/dist/chunk-7NMUTGOW.js +527 -0
  60. package/dist/chunk-7PNHUZEL.js +153 -0
  61. package/dist/chunk-7TSQLONI.js +88 -0
  62. package/dist/chunk-AE7TOLD5.js +30 -0
  63. package/dist/chunk-AEMHSXKA.js +130 -0
  64. package/dist/chunk-AKRYTS2D.js +211 -0
  65. package/dist/chunk-AMNSE36L.js +59 -0
  66. package/dist/chunk-AZVD74ZV.js +23 -0
  67. package/dist/chunk-B35DVOTK.js +1981 -0
  68. package/dist/chunk-B4HNJRAH.js +626 -0
  69. package/dist/chunk-B5WYPPHS.js +13 -0
  70. package/dist/chunk-BBOVDXQM.js +59 -0
  71. package/dist/chunk-BD3ECZLK.js +62 -0
  72. package/dist/chunk-BDGSOT74.js +4578 -0
  73. package/dist/chunk-BF5VEOPK.js +31 -0
  74. package/dist/chunk-BFFRW4XH.js +47 -0
  75. package/dist/chunk-BFPC6PEW.js +208 -0
  76. package/dist/chunk-BGEMY2JJ.js +376 -0
  77. package/dist/chunk-BISGNHKD.js +35 -0
  78. package/dist/chunk-BMRAEBRY.js +21 -0
  79. package/dist/chunk-BNTXAZXW.js +127 -0
  80. package/dist/chunk-BOQBXGSN.js +75 -0
  81. package/dist/chunk-BTJDSTQP.js +213 -0
  82. package/dist/chunk-BUOPJQP5.js +218 -0
  83. package/dist/chunk-BXFJS65Q.js +52 -0
  84. package/dist/chunk-BXPQFSX5.js +59 -0
  85. package/dist/chunk-C57LIWNY.js +1269 -0
  86. package/dist/chunk-C6YVCCWR.js +74 -0
  87. package/dist/chunk-CAADDF6M.js +167 -0
  88. package/dist/chunk-CBANJFBO.js +69 -0
  89. package/dist/chunk-CERF3RIB.js +597 -0
  90. package/dist/chunk-COAS5ETR.js +46 -0
  91. package/dist/chunk-CQ7J6UQ7.js +78 -0
  92. package/dist/chunk-CRUVYGO2.js +26 -0
  93. package/dist/chunk-CVFVFRGN.js +58 -0
  94. package/dist/chunk-D2UK66HM.js +37 -0
  95. package/dist/chunk-D2W7SA4R.js +18 -0
  96. package/dist/chunk-DA44ZENT.js +501 -0
  97. package/dist/chunk-DAJ76TOC.js +99 -0
  98. package/dist/chunk-DCZ6CIUM.js +147 -0
  99. package/dist/chunk-DF35KMXM.js +1314 -0
  100. package/dist/chunk-DGASQT26.js +151 -0
  101. package/dist/chunk-DJT57C5P.js +55 -0
  102. package/dist/chunk-DKDPZTD3.js +44 -0
  103. package/dist/chunk-DQYVQ2N7.js +77 -0
  104. package/dist/chunk-DRTP2RTY.js +266 -0
  105. package/dist/chunk-DW2BMUKY.js +61 -0
  106. package/dist/chunk-DW5T5ZVU.js +307 -0
  107. package/dist/chunk-DXKNDNFC.js +164 -0
  108. package/dist/chunk-DZEQ7UYR.js +291 -0
  109. package/dist/chunk-E4F4OUAC.js +463 -0
  110. package/dist/chunk-EE4B6A7W.js +69 -0
  111. package/dist/chunk-EISKIYWG.js +23 -0
  112. package/dist/chunk-EKAQK7UQ.js +235 -0
  113. package/dist/chunk-EOBTJV32.js +123 -0
  114. package/dist/chunk-ESF3DIZY.js +325 -0
  115. package/dist/chunk-EVOHOZ4U.js +45 -0
  116. package/dist/chunk-EXN4KHLB.js +110 -0
  117. package/dist/chunk-F252T6Y3.js +78 -0
  118. package/dist/chunk-F3DP4ZA2.js +40 -0
  119. package/dist/chunk-F6F47QAY.js +58 -0
  120. package/dist/chunk-FA3Y23ZW.js +57 -0
  121. package/dist/chunk-FBKXE4EJ.js +640 -0
  122. package/dist/chunk-FCGEB3H6.js +23 -0
  123. package/dist/chunk-FF7ZVYJF.js +3732 -0
  124. package/dist/chunk-FFGKN6L3.js +39 -0
  125. package/dist/chunk-FFGU4GCC.js +94 -0
  126. package/dist/chunk-FSFDAOVP.js +74 -0
  127. package/dist/chunk-FT5TX7OX.js +1573 -0
  128. package/dist/chunk-G3QP67Z7.js +232 -0
  129. package/dist/chunk-G5ORJKV2.js +179 -0
  130. package/dist/chunk-GFNC62PE.js +111 -0
  131. package/dist/chunk-GGK43Q3N.js +67 -0
  132. package/dist/chunk-GGYKY4GF.js +11537 -0
  133. package/dist/chunk-GGYNHGNJ.js +55 -0
  134. package/dist/chunk-GLY7RM3C.js +354 -0
  135. package/dist/chunk-GQBZU6EO.js +20 -0
  136. package/dist/chunk-GSXENUZL.js +9 -0
  137. package/dist/chunk-GTOAT5D3.js +40 -0
  138. package/dist/chunk-GWCMDPQU.js +1007 -0
  139. package/dist/chunk-GXYSMYHJ.js +152 -0
  140. package/dist/chunk-GYMAI5NY.js +14 -0
  141. package/dist/chunk-H2VZMKPE.js +30 -0
  142. package/dist/chunk-H4THUNBM.js +2091 -0
  143. package/dist/chunk-HGRVSNUZ.js +361 -0
  144. package/dist/chunk-HI4VY473.js +27 -0
  145. package/dist/chunk-HOJRSD3Q.js +447 -0
  146. package/dist/chunk-HRX25W35.js +82 -0
  147. package/dist/chunk-HSE4AQYV.js +55 -0
  148. package/dist/chunk-HU5SSUFX.js +383 -0
  149. package/dist/chunk-I3GDBJLH.js +196 -0
  150. package/dist/chunk-I75EDU75.js +684 -0
  151. package/dist/chunk-IBA7DMIO.js +20 -0
  152. package/dist/chunk-IC6N4NZA.js +231 -0
  153. package/dist/chunk-IF43HIGV.js +284 -0
  154. package/dist/chunk-IGZ6C2MC.js +439 -0
  155. package/dist/chunk-IMLTL2MY.js +192 -0
  156. package/dist/chunk-IMZL6SGR.js +33 -0
  157. package/dist/chunk-IS4USJPY.js +516 -0
  158. package/dist/chunk-ISFSPN2F.js +82 -0
  159. package/dist/chunk-IXE7GTFI.js +55 -0
  160. package/dist/chunk-IZ77QJQG.js +36 -0
  161. package/dist/chunk-J2PACWRQ.js +34 -0
  162. package/dist/chunk-J6EGFVQX.js +180 -0
  163. package/dist/chunk-JEKOD43D.js +22 -0
  164. package/dist/chunk-JGIWATSG.js +30 -0
  165. package/dist/chunk-JYBONKD4.js +43 -0
  166. package/dist/chunk-K2NLG2HK.js +454 -0
  167. package/dist/chunk-KCQ4TBLS.js +164 -0
  168. package/dist/chunk-KD5KIVMS.js +176 -0
  169. package/dist/chunk-KHW6TX6I.js +63 -0
  170. package/dist/chunk-KI5GZFCE.js +520 -0
  171. package/dist/chunk-KN34B7NO.js +105 -0
  172. package/dist/chunk-KYUHIFP3.js +136 -0
  173. package/dist/chunk-KZL5VS4B.js +300 -0
  174. package/dist/chunk-L3VW3QIH.js +48 -0
  175. package/dist/chunk-LA6MG4ET.js +2110 -0
  176. package/dist/chunk-LAVFOA3S.js +66 -0
  177. package/dist/chunk-LB4OA77N.js +13 -0
  178. package/dist/chunk-LBFRF2K4.js +196 -0
  179. package/dist/chunk-LM6EIA4B.js +93 -0
  180. package/dist/chunk-LPCNRGJ7.js +692 -0
  181. package/dist/chunk-LSLNL5T3.js +168 -0
  182. package/dist/chunk-LVRRWP4W.js +568 -0
  183. package/dist/chunk-LWCFBRHL.js +33 -0
  184. package/dist/chunk-LXFTMGZZ.js +166 -0
  185. package/dist/chunk-M33LVA4M.js +151 -0
  186. package/dist/chunk-M3FO5UMK.js +4944 -0
  187. package/dist/chunk-M5QNDBAY.js +66 -0
  188. package/dist/chunk-M6ND6KBE.js +1291 -0
  189. package/dist/chunk-M7H3WQTE.js +76 -0
  190. package/dist/chunk-MCBRVPA7.js +191 -0
  191. package/dist/chunk-MCSDWZET.js +91 -0
  192. package/dist/chunk-MDT5XDXL.js +289 -0
  193. package/dist/chunk-MJG3IQY4.js +91 -0
  194. package/dist/chunk-MOU3N2UL.js +44 -0
  195. package/dist/chunk-MP4KZOQC.js +3451 -0
  196. package/dist/chunk-MPAJ446F.js +66 -0
  197. package/dist/chunk-MVJZZ6AL.js +16 -0
  198. package/dist/chunk-MXS6S2PY.js +253 -0
  199. package/dist/chunk-N3SFDYM7.js +291 -0
  200. package/dist/chunk-NAOX3JUB.js +13 -0
  201. package/dist/chunk-NEKKIBCX.js +283 -0
  202. package/dist/chunk-NKDATMEM.js +133 -0
  203. package/dist/chunk-NR4FMC4K.js +395 -0
  204. package/dist/chunk-NSOHOJBR.js +221 -0
  205. package/dist/chunk-NTDB6QKF.js +29 -0
  206. package/dist/chunk-NWEYRBWK.js +25 -0
  207. package/dist/chunk-O2YSNYWD.js +23 -0
  208. package/dist/chunk-O3EW7LAY.js +54 -0
  209. package/dist/chunk-O7BNJIXU.js +366 -0
  210. package/dist/chunk-OARL2NXZ.js +116 -0
  211. package/dist/chunk-OHKZUEJW.js +351 -0
  212. package/dist/chunk-OKU45BXA.js +647 -0
  213. package/dist/chunk-OL4JBD3J.js +59 -0
  214. package/dist/chunk-OLUO5DDR.js +192 -0
  215. package/dist/chunk-OQ245JLA.js +196 -0
  216. package/dist/chunk-P72UZAQI.js +289 -0
  217. package/dist/chunk-PAL2ENB6.js +20 -0
  218. package/dist/chunk-PAXYQZH7.js +53 -0
  219. package/dist/chunk-PDPEM5VW.js +51 -0
  220. package/dist/chunk-PEWCDI2C.js +668 -0
  221. package/dist/chunk-PGZ54EDX.js +27 -0
  222. package/dist/chunk-PRWVLDZF.js +73 -0
  223. package/dist/chunk-PSQQ75VJ.js +52 -0
  224. package/dist/chunk-PUOVIFHW.js +118 -0
  225. package/dist/chunk-PWBF2X3V.js +107 -0
  226. package/dist/chunk-PWXII6HF.js +43 -0
  227. package/dist/chunk-Q35VLJRT.js +80 -0
  228. package/dist/chunk-QJP7EYGL.js +128 -0
  229. package/dist/chunk-QPQKX2MK.js +8836 -0
  230. package/dist/chunk-QQRLPY25.js +1053 -0
  231. package/dist/chunk-QUS4ER2W.js +407 -0
  232. package/dist/chunk-QYHI3YET.js +29 -0
  233. package/dist/chunk-QYRU2UQI.js +32 -0
  234. package/dist/chunk-R6XVVQGC.js +13 -0
  235. package/dist/chunk-R7QN6ONS.js +483 -0
  236. package/dist/chunk-RD23MPGC.js +221 -0
  237. package/dist/chunk-RDDWQBEM.js +185 -0
  238. package/dist/chunk-RDLLDYFO.js +104 -0
  239. package/dist/chunk-RE4TGORR.js +84 -0
  240. package/dist/chunk-RJLHVYQY.js +217 -0
  241. package/dist/chunk-RJLPTWHW.js +905 -0
  242. package/dist/chunk-RKUVLRZI.js +295 -0
  243. package/dist/chunk-ROGXPGYR.js +37 -0
  244. package/dist/chunk-RSZGEL5U.js +163 -0
  245. package/dist/chunk-RVUOIJXN.js +909 -0
  246. package/dist/chunk-RW7F4JRP.js +11 -0
  247. package/dist/chunk-S4UO3AO3.js +53 -0
  248. package/dist/chunk-S5JAAF6S.js +585 -0
  249. package/dist/chunk-SNU37TQI.js +56 -0
  250. package/dist/chunk-SQVUDO2O.js +31 -0
  251. package/dist/chunk-SYVHIYQT.js +66 -0
  252. package/dist/chunk-SZBQMTG2.js +85 -0
  253. package/dist/chunk-T5VCXA3J.js +25 -0
  254. package/dist/chunk-TK6NSP56.js +30 -0
  255. package/dist/chunk-TKWVMA6L.js +22 -0
  256. package/dist/chunk-TQDKJHWX.js +59 -0
  257. package/dist/chunk-TQDM7S5N.js +127 -0
  258. package/dist/chunk-TULAXS77.js +23 -0
  259. package/dist/chunk-TVT45XNH.js +4625 -0
  260. package/dist/chunk-TWCVV2JO.js +467 -0
  261. package/dist/chunk-U4DKAD6S.js +47 -0
  262. package/dist/chunk-UA5K2BTI.js +564 -0
  263. package/dist/chunk-UAMKCMOK.js +40 -0
  264. package/dist/chunk-UBMVADBF.js +51 -0
  265. package/dist/chunk-UFQ5A5PW.js +645 -0
  266. package/dist/chunk-UOD2SOLL.js +1301 -0
  267. package/dist/chunk-UTSB4LOW.js +156 -0
  268. package/dist/chunk-UVXNIUTN.js +412 -0
  269. package/dist/chunk-UXVPXYPE.js +90 -0
  270. package/dist/chunk-UYEEMIWR.js +374 -0
  271. package/dist/chunk-VBGM5ZBW.js +54 -0
  272. package/dist/chunk-VEWPCZPG.js +762 -0
  273. package/dist/chunk-VIRDLZ5E.js +108 -0
  274. package/dist/chunk-VMPO7WKN.js +52 -0
  275. package/dist/chunk-W2NVSDO5.js +5122 -0
  276. package/dist/chunk-W3YYPBEA.js +176 -0
  277. package/dist/chunk-W5AYOICN.js +280 -0
  278. package/dist/chunk-W5GZOIUF.js +27 -0
  279. package/dist/chunk-WHKNLZ3C.js +76 -0
  280. package/dist/chunk-WKBEPPQ5.js +1409 -0
  281. package/dist/chunk-WM3Z6QKQ.js +151 -0
  282. package/dist/chunk-WMI2TPMA.js +31 -0
  283. package/dist/chunk-WNX5VD7S.js +150 -0
  284. package/dist/chunk-WOVTYST3.js +60 -0
  285. package/dist/chunk-WPB5WEZJ.js +546 -0
  286. package/dist/chunk-WUO5EOAT.js +44 -0
  287. package/dist/chunk-WWLJMP6D.js +133 -0
  288. package/dist/chunk-WZMLH3XP.js +58 -0
  289. package/dist/chunk-WZYVLUVQ.js +79 -0
  290. package/dist/chunk-X2OCPVU5.js +135 -0
  291. package/dist/chunk-X3CL6DTR.js +95 -0
  292. package/dist/chunk-X6WF7JEV.js +354 -0
  293. package/dist/chunk-XAHGBPWT.js +44 -0
  294. package/dist/chunk-XCKQ5BM2.js +228 -0
  295. package/dist/chunk-XIBYREEY.js +106 -0
  296. package/dist/chunk-XKW5NDMR.js +378 -0
  297. package/dist/chunk-XRDALAO3.js +100 -0
  298. package/dist/chunk-XUP22EAS.js +41 -0
  299. package/dist/chunk-XWAC3MKW.js +243 -0
  300. package/dist/chunk-Y3R7JMXB.js +59 -0
  301. package/dist/chunk-Y54LTP4W.js +82 -0
  302. package/dist/chunk-Y7UECI4M.js +99 -0
  303. package/dist/chunk-YACGDFHC.js +47 -0
  304. package/dist/chunk-YHNIQPKY.js +71 -0
  305. package/dist/chunk-YMBR6HYP.js +111 -0
  306. package/dist/chunk-YMCH3L2S.js +26 -0
  307. package/dist/chunk-Z4ZU6T7V.js +99 -0
  308. package/dist/chunk-ZDPF67ZZ.js +173 -0
  309. package/dist/chunk-ZFC2Q67K.js +101 -0
  310. package/dist/chunk-ZGHNNSCT.js +114 -0
  311. package/dist/chunk-ZGX3ERAT.js +173 -0
  312. package/dist/chunk-ZI3YHEBY.js +37 -0
  313. package/dist/chunk-ZN7G6JLS.js +639 -0
  314. package/dist/chunk-ZNPFQMXT.js +47 -0
  315. package/dist/chunk-ZOU3LV4U.js +63 -0
  316. package/dist/chunk-ZT7B4H2V.js +117 -0
  317. package/dist/chunk-ZZCBDNZI.js +58 -0
  318. package/dist/cli.js +498 -112593
  319. package/dist/computer-tools.js +36642 -21258
  320. package/dist/harness-catalog.cjs +88 -43
  321. package/dist/index.js +1 -1
  322. package/dist/local-model-supervisor.cjs +555 -0
  323. package/package.json +3 -4
@@ -0,0 +1,2110 @@
1
+ import { createRequire as __clikcodeCreateRequire } from 'node:module';
2
+ const require = __clikcodeCreateRequire(import.meta.url);
3
+ import {
4
+ NATIVE_STREAM_USAGE_READINGS,
5
+ NATIVE_USAGE_PROBES,
6
+ accountUsageFrom
7
+ } from "./chunk-N3SFDYM7.js";
8
+ import {
9
+ callbacksReachable,
10
+ completeLoginUrl,
11
+ extractLoginUrl,
12
+ hasLocalDisplay,
13
+ loginLinkLine,
14
+ loginUrlNotice,
15
+ openLoginUrl
16
+ } from "./chunk-RE4TGORR.js";
17
+ import {
18
+ FS_SESSION_DISCOVERY,
19
+ nativeTranscriptReader
20
+ } from "./chunk-M3FO5UMK.js";
21
+ import {
22
+ USAGE_RECHECK_MS,
23
+ accountCanTakeTurn,
24
+ accountDisplayUsage,
25
+ clearQuotaMark,
26
+ nativeUsageCache,
27
+ settleQuotaMark,
28
+ usageAskedAt,
29
+ usageCacheKey,
30
+ usageReadingIsCurrent,
31
+ usageResetLabel,
32
+ vendorWindows,
33
+ windowSpent
34
+ } from "./chunk-XWAC3MKW.js";
35
+ import {
36
+ apiKeyAccountEmail,
37
+ deriveAccountLabel,
38
+ matchingVendorAccount,
39
+ nameAccount,
40
+ vendorCredentialCapture
41
+ } from "./chunk-ZN7G6JLS.js";
42
+ import {
43
+ keyVariables,
44
+ nativeAccountEnvironment,
45
+ nativeProfileEnvironment,
46
+ profileExtraEnvironment,
47
+ readProfileKey,
48
+ writeProfileKey
49
+ } from "./chunk-ZGX3ERAT.js";
50
+ import {
51
+ readState
52
+ } from "./chunk-MXS6S2PY.js";
53
+ import {
54
+ writeState
55
+ } from "./chunk-RKUVLRZI.js";
56
+ import {
57
+ builtInHarnesses,
58
+ harnessAdapterVersion,
59
+ harnessIntegrationLevel,
60
+ harnessSupportsEffort,
61
+ harnessSupportsModelSelection,
62
+ homeRedirectEnvironment,
63
+ keyProviders,
64
+ localHarnessForCommand,
65
+ localHarnessForProvider
66
+ } from "./chunk-KYUHIFP3.js";
67
+ import {
68
+ INERT_DEADLINE_MS,
69
+ PROBE_DEADLINE_MS,
70
+ adoptAuthFiles,
71
+ authEvidencePresent,
72
+ authFilePresent,
73
+ authFilesStamp,
74
+ captureNativeHarnessOutput,
75
+ ensureNativeHarness,
76
+ expandAuthPath,
77
+ harnessCanLogout,
78
+ harnessInstallRoute,
79
+ hasAuthEvidence,
80
+ inspectNativeHarness,
81
+ logoutNativeHarness,
82
+ manualInstallCommand,
83
+ prepareAuthFilesForLogin,
84
+ saveVersionMemo,
85
+ vendorCommandText
86
+ } from "./chunk-DF35KMXM.js";
87
+ import {
88
+ forwardParentSignals
89
+ } from "./chunk-IGZ6C2MC.js";
90
+ import {
91
+ BROWSER_OPENERS,
92
+ loginPortForwardHint
93
+ } from "./chunk-4AQ5NINV.js";
94
+ import {
95
+ killProcessTreePortable,
96
+ spawnPortable,
97
+ terminatePortable
98
+ } from "./chunk-WPB5WEZJ.js";
99
+ import {
100
+ sleep
101
+ } from "./chunk-YMCH3L2S.js";
102
+ import {
103
+ emitResult
104
+ } from "./chunk-JGIWATSG.js";
105
+ import {
106
+ source_default
107
+ } from "./chunk-LVRRWP4W.js";
108
+ import {
109
+ stripAnsi
110
+ } from "./chunk-G3QP67Z7.js";
111
+ import {
112
+ LOCK_TUNING,
113
+ lockLooksStale
114
+ } from "./chunk-4L2ZZM4Q.js";
115
+ import {
116
+ ensurePrivateDirectory
117
+ } from "./chunk-F6F47QAY.js";
118
+ import {
119
+ lifecycle,
120
+ quiet
121
+ } from "./chunk-RDDWQBEM.js";
122
+ import {
123
+ stateDirectory
124
+ } from "./chunk-MPAJ446F.js";
125
+
126
+ // src/commands/account.ts
127
+ import { randomUUID } from "node:crypto";
128
+ import { mkdir as mkdir2 } from "node:fs/promises";
129
+ import { join as join4 } from "node:path";
130
+
131
+ // src/harness/transport/native/login.ts
132
+ import { AsyncLocalStorage } from "node:async_hooks";
133
+ import { createInterface } from "node:readline/promises";
134
+
135
+ // src/gateway/login/vendor-sign-in.ts
136
+ import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
137
+ import { tmpdir } from "node:os";
138
+ import { delimiter, join } from "node:path";
139
+
140
+ // src/gateway/login/pty.ts
141
+ function shellQuote(parts) {
142
+ return parts.map((part) => `'${part.replace(/'/g, `'\\''`)}'`).join(" ");
143
+ }
144
+ var SIGN_IN_ROWS = 40;
145
+ var SIGN_IN_COLUMNS = 100;
146
+ var SIZED = `stty rows ${SIGN_IN_ROWS} cols ${SIGN_IN_COLUMNS} 2>/dev/null; exec`;
147
+ function scriptArgv(binary, args, platform = process.platform) {
148
+ if (platform === "win32") return void 0;
149
+ if (platform === "darwin") return ["-q", "/dev/null", "/bin/sh", "-c", `${SIZED} "$0" "$@"`, binary, ...args];
150
+ return ["-q", "-e", "-f", "-c", `${SIZED} ${shellQuote([binary, ...args])}`, "/dev/null"];
151
+ }
152
+ var DARWIN_PIPE = [
153
+ 't="$(mktemp "${TMPDIR:-/tmp}/clikcode-pty.XXXXXX")" || exit 127',
154
+ `/bin/sh -c 'echo $$ > "$1"; exec dd bs=4096 2>/dev/null' sh "$t" | {`,
155
+ ' script "$@"; s=$?',
156
+ ' while [ ! -s "$t" ]; do sleep 0.05; done',
157
+ ' kill -PIPE "$(cat "$t")" 2>/dev/null; rm -f "$t"; exit "$s"',
158
+ "}"
159
+ ].join("\n");
160
+ function ptyCommand(binary, args, platform = process.platform) {
161
+ const argv = scriptArgv(binary, args, platform);
162
+ if (!argv) return void 0;
163
+ return platform === "darwin" ? { file: "/bin/sh", argv: ["-c", DARWIN_PIPE, "sh", ...argv] } : { file: "script", argv };
164
+ }
165
+ var STOP_KILL_MS = 250;
166
+ async function runInPty(input) {
167
+ const command = ptyCommand(input.binary, input.args, input.platform);
168
+ if (!command) return { teed: false, exitCode: null };
169
+ const group = (input.platform ?? process.platform) === "darwin";
170
+ return new Promise((resolve2, reject) => {
171
+ const child = spawnPortable(command.file, [...command.argv], {
172
+ stdio: ["pipe", "pipe", "pipe"],
173
+ ...group ? { detached: true } : {},
174
+ // A terminal of a known kind: under ClikCode's own TERM=dumb (a
175
+ // script, a test) some vendors draw differently, or not at all.
176
+ env: { ...process.env, ...!process.env.TERM || process.env.TERM === "dumb" ? { TERM: "xterm-256color" } : {}, ...input.env }
177
+ });
178
+ child.stdin?.on("error", () => {
179
+ });
180
+ input.onStdin((text) => {
181
+ child.stdin?.write(text);
182
+ });
183
+ child.stdout?.setEncoding("utf8");
184
+ child.stderr?.setEncoding("utf8");
185
+ const read = (chunk) => {
186
+ try {
187
+ input.onOutput(chunk);
188
+ } catch {
189
+ }
190
+ };
191
+ child.stdout?.on("data", read);
192
+ child.stderr?.on("data", read);
193
+ let kill;
194
+ const stop = () => {
195
+ killProcessTreePortable(child, "SIGTERM", group);
196
+ kill ??= setTimeout(() => killProcessTreePortable(child, "SIGKILL", group), STOP_KILL_MS);
197
+ kill.unref();
198
+ };
199
+ input.signal?.addEventListener("abort", stop, { once: true });
200
+ const cleanup = () => {
201
+ if (kill) clearTimeout(kill);
202
+ input.signal?.removeEventListener("abort", stop);
203
+ };
204
+ child.on("error", (error) => {
205
+ cleanup();
206
+ if (error.code === "ENOENT") resolve2({ teed: false, exitCode: null });
207
+ else reject(error);
208
+ });
209
+ child.on("close", (code) => {
210
+ cleanup();
211
+ resolve2({ teed: true, exitCode: code });
212
+ });
213
+ });
214
+ }
215
+
216
+ // src/gateway/login/screen.ts
217
+ var Screen = class {
218
+ constructor(rows, columns) {
219
+ this.rows = rows;
220
+ this.columns = columns;
221
+ this.grid = Array.from({ length: rows }, () => this.blank());
222
+ }
223
+ rows;
224
+ columns;
225
+ grid;
226
+ row = 0;
227
+ column = 0;
228
+ saved = { row: 0, column: 0 };
229
+ pending = "";
230
+ blank() {
231
+ return Array.from({ length: this.columns }, () => " ");
232
+ }
233
+ lineFeed() {
234
+ if (this.row === this.rows - 1) {
235
+ this.grid.shift();
236
+ this.grid.push(this.blank());
237
+ } else this.row += 1;
238
+ }
239
+ put(char) {
240
+ if (this.column >= this.columns) {
241
+ this.column = 0;
242
+ this.lineFeed();
243
+ }
244
+ this.grid[this.row][this.column] = char;
245
+ this.column += 1;
246
+ }
247
+ clamp() {
248
+ this.row = Math.max(0, Math.min(this.rows - 1, this.row));
249
+ this.column = Math.max(0, Math.min(this.columns - 1, this.column));
250
+ }
251
+ eraseLine(mode, row = this.row) {
252
+ const line = this.grid[row];
253
+ const [from, to] = mode === 0 ? [this.column, this.columns] : mode === 1 ? [0, this.column + 1] : [0, this.columns];
254
+ for (let index = from; index < to; index += 1) line[index] = " ";
255
+ }
256
+ eraseDisplay(mode) {
257
+ if (mode === 2 || mode === 3) {
258
+ this.grid = Array.from({ length: this.rows }, () => this.blank());
259
+ return;
260
+ }
261
+ this.eraseLine(mode);
262
+ const rows = mode === 0 ? [this.row + 1, this.rows] : [0, this.row];
263
+ for (let index = rows[0]; index < rows[1]; index += 1) this.grid[index] = this.blank();
264
+ }
265
+ csi(params, final) {
266
+ if (params.startsWith("?")) {
267
+ if (/\b(?:1049|47|1047)\b/.test(params) && (final === "h" || final === "l")) this.eraseDisplay(2);
268
+ return;
269
+ }
270
+ if (/^[<=>]/.test(params)) return;
271
+ const numbers = params.split(";").map((part) => Number.parseInt(part, 10));
272
+ const n = (index, fallback = 1) => Number.isFinite(numbers[index]) && numbers[index] > 0 ? numbers[index] : fallback;
273
+ switch (final) {
274
+ case "A":
275
+ this.row -= n(0);
276
+ break;
277
+ case "B":
278
+ case "e":
279
+ this.row += n(0);
280
+ break;
281
+ case "C":
282
+ case "a":
283
+ this.column += n(0);
284
+ break;
285
+ case "D":
286
+ this.column -= n(0);
287
+ break;
288
+ case "E":
289
+ this.row += n(0);
290
+ this.column = 0;
291
+ break;
292
+ case "F":
293
+ this.row -= n(0);
294
+ this.column = 0;
295
+ break;
296
+ case "G":
297
+ case "`":
298
+ this.column = n(0) - 1;
299
+ break;
300
+ case "d":
301
+ this.row = n(0) - 1;
302
+ break;
303
+ case "H":
304
+ case "f":
305
+ this.row = n(0) - 1;
306
+ this.column = n(1) - 1;
307
+ break;
308
+ case "J":
309
+ this.eraseDisplay(Number.isFinite(numbers[0]) ? numbers[0] : 0);
310
+ break;
311
+ case "K":
312
+ this.eraseLine(Number.isFinite(numbers[0]) ? numbers[0] : 0);
313
+ break;
314
+ case "X":
315
+ for (let index = 0; index < n(0) && this.column + index < this.columns; index += 1) this.grid[this.row][this.column + index] = " ";
316
+ break;
317
+ case "P": {
318
+ const line = this.grid[this.row];
319
+ line.splice(this.column, n(0));
320
+ while (line.length < this.columns) line.push(" ");
321
+ break;
322
+ }
323
+ case "@": {
324
+ const line = this.grid[this.row];
325
+ line.splice(this.column, 0, ...Array.from({ length: n(0) }, () => " "));
326
+ line.length = this.columns;
327
+ break;
328
+ }
329
+ case "L":
330
+ for (let index = 0; index < n(0); index += 1) {
331
+ this.grid.splice(this.row, 0, this.blank());
332
+ this.grid.length = this.rows;
333
+ }
334
+ break;
335
+ case "M":
336
+ for (let index = 0; index < n(0); index += 1) {
337
+ this.grid.splice(this.row, 1);
338
+ this.grid.push(this.blank());
339
+ }
340
+ break;
341
+ case "S":
342
+ for (let index = 0; index < n(0); index += 1) {
343
+ this.grid.shift();
344
+ this.grid.push(this.blank());
345
+ }
346
+ break;
347
+ case "T":
348
+ for (let index = 0; index < n(0); index += 1) {
349
+ this.grid.pop();
350
+ this.grid.unshift(this.blank());
351
+ }
352
+ break;
353
+ case "s":
354
+ this.saved = { row: this.row, column: this.column };
355
+ break;
356
+ case "u":
357
+ ({ row: this.row, column: this.column } = this.saved);
358
+ break;
359
+ default:
360
+ break;
361
+ }
362
+ this.clamp();
363
+ }
364
+ write(text) {
365
+ const data = this.pending + text;
366
+ this.pending = "";
367
+ let index = 0;
368
+ while (index < data.length) {
369
+ const char = data[index];
370
+ if (char === "\x1B") {
371
+ const rest = data.slice(index);
372
+ const csi = /^\u001b\[([0-9;?<=>]*)[ -/]*([@-~])/.exec(rest);
373
+ if (csi) {
374
+ this.csi(csi[1], csi[2]);
375
+ index += csi[0].length;
376
+ continue;
377
+ }
378
+ const osc = /^\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/.exec(rest) ?? /^\u001b[P^_][^\u001b]*\u001b\\/.exec(rest);
379
+ if (osc) {
380
+ index += osc[0].length;
381
+ continue;
382
+ }
383
+ if (rest.length >= 2 && /^\u001b[78]/.test(rest)) {
384
+ if (rest[1] === "7") this.saved = { row: this.row, column: this.column };
385
+ else ({ row: this.row, column: this.column } = this.saved);
386
+ index += 2;
387
+ continue;
388
+ }
389
+ if (/^\u001b[()#%][\s\S]/.test(rest)) {
390
+ index += 3;
391
+ continue;
392
+ }
393
+ if (/^\u001b[=>DEMc]/.test(rest)) {
394
+ if (rest[1] === "D" || rest[1] === "E") {
395
+ this.lineFeed();
396
+ if (rest[1] === "E") this.column = 0;
397
+ }
398
+ if (rest[1] === "M") {
399
+ if (this.row === 0) {
400
+ this.grid.pop();
401
+ this.grid.unshift(this.blank());
402
+ } else this.row -= 1;
403
+ }
404
+ index += 2;
405
+ continue;
406
+ }
407
+ if (/^\u001b(?:\[[0-9;?<=>]*[ -/]*|\][^\u0007\u001b]*|[P^_][^\u001b]*|[()#%])?$/.test(rest)) {
408
+ this.pending = rest;
409
+ return;
410
+ }
411
+ index += 1;
412
+ continue;
413
+ }
414
+ if (char === "\r") this.column = 0;
415
+ else if (char === "\n") {
416
+ this.column = 0;
417
+ this.lineFeed();
418
+ } else if (char === "\b") this.column = Math.max(0, this.column - 1);
419
+ else if (char === " ") this.column = Math.min(this.columns - 1, (Math.floor(this.column / 8) + 1) * 8);
420
+ else if (char >= " " && char !== "\x7F") this.put(char);
421
+ index += 1;
422
+ }
423
+ }
424
+ state() {
425
+ const lines = this.grid.map((line) => line.join("").trimEnd());
426
+ while (lines.length > this.row + 1 && !lines.at(-1)) lines.pop();
427
+ return { lines, row: this.row, column: this.column };
428
+ }
429
+ };
430
+
431
+ // src/gateway/login/vendor-sign-in.ts
432
+ function isKeyShaped(text) {
433
+ return text.length >= 16 && !/\s/.test(text);
434
+ }
435
+ function extractLoginCode(text, url) {
436
+ if (url) {
437
+ try {
438
+ const fromUrl = new URL(url).searchParams.get("user_code");
439
+ if (fromUrl) return fromUrl;
440
+ } catch {
441
+ }
442
+ }
443
+ const prose = stripAnsi(text).replace(/https?:\/\/\S+/g, " ");
444
+ return prose.match(/(?<![\w-])[A-Z0-9]{4,5}-[A-Z0-9]{4,5}(?![\w-])/)?.[0];
445
+ }
446
+ function chooseLoginLink(input) {
447
+ const opened = input.opened && completeLoginUrl(input.opened) ? input.opened : void 0;
448
+ const printed = input.printed && completeLoginUrl(input.printed) ? input.printed : void 0;
449
+ return input.local ? opened ?? printed : printed ?? opened;
450
+ }
451
+ var SECRET_WORDS = /api[ _-]?key|(?:\b|_)(?:key|token|secret|password)\b/i;
452
+ function isSecret(prompt) {
453
+ return SECRET_WORDS.test(prompt.replace(/\([^)]*\)/g, ""));
454
+ }
455
+ var KEYS = {
456
+ "{enter}": "\r",
457
+ "{down}": "\x1B[B",
458
+ "{up}": "\x1B[A",
459
+ "{right}": "\x1B[C",
460
+ "{left}": "\x1B[D",
461
+ "{tab}": " ",
462
+ "{esc}": "\x1B",
463
+ "{space}": " ",
464
+ "{ctrl-c}": "",
465
+ "{ctrl-d}": ""
466
+ };
467
+ function titleAbove(lines, start, fallback = "") {
468
+ return [...lines.slice(0, start)].reverse().map((line) => line.replace(/[│┃║]/g, " ").trim()).find((line) => /[A-Za-z]/.test(line) && !/^[┌└╭╰─━]|^>\s/.test(line) && !/\b(?:navigate|ENTER|ESC|select)\b.*\b(?:select|cancel|confirm)\b/i.test(line))?.replace(/^\?\s*/, "") ?? fallback;
469
+ }
470
+ function keystrokes(send) {
471
+ return send.replace(/\{[a-z-]+\}/g, (token) => KEYS[token] ?? token);
472
+ }
473
+ function drawText(text) {
474
+ const screen = new Screen(Math.max(24, text.split("\n").length + 2), 400);
475
+ screen.write(text);
476
+ return screen.state();
477
+ }
478
+ function screenLines(text) {
479
+ return stripAnsi(text).split("\n").map((line) => (line.split("\r").filter((part) => part.trim()).pop() ?? "").trimEnd());
480
+ }
481
+ function readScreenPrompt(shown) {
482
+ const state = typeof shown === "string" ? drawText(shown) : shown;
483
+ const lines = state.lines;
484
+ const before = (lines[state.row] ?? "").slice(0, state.column);
485
+ const after = (lines[state.row] ?? "").slice(state.column);
486
+ const last = !after.trim() ? before.trim() : "";
487
+ if (last) {
488
+ const yesNo = /^(.*?)\s*(?:\(Y\)es\/\(N\)o|\[(?:Y\/n|y\/N|y\/n|Y\/N)\])\s*(?:\[(Yes|No)\])?\s*:?$/i.exec(last);
489
+ if (yesNo) {
490
+ const defaultNo = /\[(?:y\/N)\]/.test(last) || yesNo[2]?.toLowerCase() === "no";
491
+ return { kind: "choice", title: yesNo[1].trim(), choices: ["Yes", "No"], selected: defaultNo ? 1 : 0, style: "yes-no" };
492
+ }
493
+ if (/[:>?]$/.test(last) && last.length <= 140 && !/https?:\/\//.test(last.replace(/\[[^\]]*\]/g, ""))) {
494
+ const prompt = last.replace(/\s*[:>?]$/, "").trim();
495
+ const asksNumber = /\b(?:choice|choose|select|option|number)\b/i.test(prompt);
496
+ const list = asksNumber ? numberedList(lines.slice(0, state.row), true) : void 0;
497
+ if (list && list.prompt.kind === "choice") {
498
+ const fallback = /\[default (\d+)\]/i.exec(prompt)?.[1];
499
+ return { ...list.prompt, title: list.prompt.title || prompt, selected: fallback ? Number(fallback) - 1 : list.prompt.selected, style: "number" };
500
+ }
501
+ if (prompt) return { kind: "input", prompt, secret: isSecret(prompt), .../\(optional\b|\bdefault\b|\[[^\]]+\]$/i.test(prompt) ? { optional: true } : {} };
502
+ }
503
+ }
504
+ const drawn = [readClack(lines), readEnquirer(lines), readNumbered(lines), readRadio(lines), readPointer(lines), readCards(lines), readInputBox(lines), readTitledField(state)].filter((found2) => Boolean(found2));
505
+ const found = drawn.sort((left, right) => right.at - left.at)[0]?.prompt;
506
+ if (found?.kind === "choice" && found.style === "arrows" && lines.some((line) => /\btype to (?:search|filter)\b|\bsearch [a-z]+\.\.\.|\bsearch:|\d+ more\b|^\s*\(\d+\/\d+\)\s*$/i.test(line))) {
507
+ return { ...found, searchable: true };
508
+ }
509
+ return found;
510
+ }
511
+ function readTitledField(state) {
512
+ const { lines, row } = state;
513
+ for (let index = row - 1; index >= 0 && row - index <= 4; index -= 1) {
514
+ const title = /^\s*[┌╭]─+\s*([^─┐╮]+?)\s*─/.exec(lines[index])?.[1];
515
+ if (!title) continue;
516
+ const closed = lines.slice(row + 1, row + 5).some((line) => /^\s*[└╰]─/.test(line));
517
+ if (!closed || !/[A-Za-z]/.test(title)) return void 0;
518
+ return { prompt: { kind: "input", prompt: title, secret: isSecret(title) }, at: index };
519
+ }
520
+ return void 0;
521
+ }
522
+ function readCards(lines) {
523
+ const cards = [];
524
+ let open = -1;
525
+ for (let index = 0; index < lines.length; index += 1) {
526
+ const line = lines[index];
527
+ if (/^\s*[╭┌]─/.test(line)) {
528
+ open = index;
529
+ continue;
530
+ }
531
+ if (/^\s*[╰└]─/.test(line) && open >= 0) {
532
+ const rows = lines.slice(open + 1, index);
533
+ const first = rows.map((row) => row.replace(/^\s*>?\s*│\s?|\s*│\s*$/g, "").trim()).find(Boolean);
534
+ const current = first !== void 0 && /→\s*$/.test(first) || rows.some((row) => /^\s*>\s*│/.test(row));
535
+ if (first) cards.push({ at: open, label: first.replace(/^[^\p{L}\p{N}(]+\s*/u, "").replace(/\s*→$/, "").trim(), current });
536
+ open = -1;
537
+ }
538
+ }
539
+ const run = [];
540
+ for (const card of cards.reverse()) {
541
+ if (run.length && run[0].at - card.at > 8) break;
542
+ run.unshift(card);
543
+ }
544
+ const selected = run.findIndex((card) => card.current);
545
+ if (run.length < 2 || selected < 0) return void 0;
546
+ if (!lines.slice(run.at(-1).at).some((line) => /↑|↓|\bnavigate\b|\benter (?:to )?select\b/i.test(line))) return void 0;
547
+ return { prompt: { kind: "choice", title: titleAbove(lines, run[0].at), choices: run.map((card) => card.label), selected, style: "arrows" }, at: run[0].at };
548
+ }
549
+ function readRadio(lines) {
550
+ const option = (line) => /^\s*(?:[→>›❯]\s*)?\((●|○)\)\s+(?!\d+\.\s)(.+?)\s*$/.exec(line);
551
+ let end = -1;
552
+ for (let index = lines.length - 1; index >= 0; index -= 1) if (option(lines[index])) {
553
+ end = index;
554
+ break;
555
+ }
556
+ if (end < 0) return void 0;
557
+ let start = end;
558
+ while (start > 0 && option(lines[start - 1])) start -= 1;
559
+ const found = lines.slice(start, end + 1).map((line) => option(line));
560
+ const selected = found.findIndex((match) => match[1] === "\u25CF");
561
+ if (found.length < 2 || selected < 0) return void 0;
562
+ const title = titleAbove(lines, start, "Choose one");
563
+ return { prompt: { kind: "choice", title, choices: found.map((match) => match[2]), selected, style: "arrows" }, at: start };
564
+ }
565
+ function readInputBox(lines) {
566
+ const hint = (line) => /\benter to (?:submit|save|confirm|continue)\b|↵\s*submit\b/i.test(line);
567
+ let at = -1;
568
+ for (let index = lines.length - 1; index >= 0; index -= 1) if (hint(lines[index])) {
569
+ at = index;
570
+ break;
571
+ }
572
+ if (at < 0) return void 0;
573
+ const content = (line) => line.replace(/^\s*[│┃]\s?|\s*[│┃]\s*$/g, "").trim();
574
+ let top = -1;
575
+ for (let index = at; index >= 0 && at - index < 40; index -= 1) {
576
+ if (/^\s*[┌╭]/.test(lines[index])) {
577
+ top = index;
578
+ break;
579
+ }
580
+ }
581
+ let bottom = -1;
582
+ if (top >= 0) {
583
+ for (let index = top + 1; index < lines.length; index += 1) if (/^\s*[└╰]/.test(lines[index])) {
584
+ bottom = index;
585
+ break;
586
+ }
587
+ }
588
+ if (top >= 0 && bottom >= 0 && (bottom >= at || at - bottom <= 3)) {
589
+ const inside = lines.slice(top + 1, bottom).map(content).filter(Boolean).filter((line) => !hint(line));
590
+ const parts = (inside[0] ?? "").split(/\s+·\s+/).filter((part) => !/^Step \d+\/\d+$/i.test(part));
591
+ const label = [lines[top - 1], lines[top - 2]].map((line) => (line ?? "").trim()).find((line) => /[A-Za-z]/.test(line) && line.length <= 60);
592
+ const field = inside.length <= 1 && label ? label : parts.at(-1) ?? label ?? "";
593
+ if (!field) return void 0;
594
+ const prompt = parts.length > 1 ? `${parts[0]}: ${field}` : field;
595
+ return { prompt: { kind: "input", prompt, secret: isSecret(field) || inside.length <= 1 && isSecret(inside[0] ?? "") }, at: top };
596
+ }
597
+ const typing = lines.slice(Math.max(0, at - 4), at).find((line) => /^\s*[>❭]/.test(line));
598
+ if (typing === void 0) return void 0;
599
+ const placeholder = typing.replace(/^\s*[>❭]\s*/, "").trim();
600
+ for (let index = at - 1; index >= 0; index -= 1) {
601
+ const line = lines[index].trim();
602
+ if (!line || /^[>❭]/.test(line)) continue;
603
+ const label = line.replace(/\s*:$/, "");
604
+ const prompt = placeholder.length > label.length && /[A-Za-z]{3}/.test(placeholder) ? placeholder : label;
605
+ return { prompt: { kind: "input", prompt, secret: isSecret(prompt) || isSecret(label) }, at: index };
606
+ }
607
+ return void 0;
608
+ }
609
+ function readPointer(lines) {
610
+ const plain = lines.map((line) => line.replace(/[│┃║]/g, " ").trimEnd());
611
+ const marker = (line) => /^\s*[›>→❯]\s+(?!\([●○]\)|[│┃])\S/.test(line);
612
+ let at = -1;
613
+ for (let index = plain.length - 1; index >= 0; index -= 1) if (marker(plain[index]) && !/^\s*[›>→❯]\s*[│┃]/.test(lines[index])) {
614
+ at = index;
615
+ break;
616
+ }
617
+ if (at < 0) return void 0;
618
+ const indent = (line) => {
619
+ const shown = line.replace(/[›>→❯]/, " ");
620
+ return shown.length - shown.trimStart().length;
621
+ };
622
+ const column = indent(plain[at]);
623
+ const inMenu = (line) => !/^\s*[─━]{3,}|^\s*\(\d+\/\d+\)\s*$/.test(line) && (!line.trim() || indent(line) === column);
624
+ const entryAt = (index) => Boolean(plain[index]?.trim()) && indent(plain[index]) === column;
625
+ const heading = (index) => Boolean(plain[index].trim()) && indent(plain[index]) < column && entryAt(index - 1) && entryAt(index + 1);
626
+ let first = at;
627
+ while (first > 0 && (inMenu(plain[first - 1]) || heading(first - 1))) first -= 1;
628
+ let last = at;
629
+ while (last < plain.length - 1 && (inMenu(plain[last + 1]) || heading(last + 1))) last += 1;
630
+ const groups = [];
631
+ for (let index = first; index <= last; index += 1) {
632
+ if (heading(index)) continue;
633
+ if (!plain[index].trim()) {
634
+ if (groups.at(-1)?.length) groups.push([]);
635
+ continue;
636
+ }
637
+ if (!groups.length) groups.push([]);
638
+ groups.at(-1).push(index);
639
+ }
640
+ const filled = groups.filter((group) => group.length);
641
+ const entries = filled.length > 1 ? filled.map((group) => group[0]) : filled[0] ?? [];
642
+ if (!entries.includes(at) || entries.length < (/^\s*[❯→]/.test(plain[at]) ? 1 : 2)) return void 0;
643
+ const title = titleAbove(lines, entries[0]);
644
+ return {
645
+ prompt: {
646
+ kind: "choice",
647
+ title,
648
+ choices: entries.map((index) => plain[index].trim().replace(/^[›>→❯]\s*/, "")),
649
+ selected: entries.indexOf(at),
650
+ style: "arrows"
651
+ },
652
+ at: entries[0]
653
+ };
654
+ }
655
+ function readClack(lines) {
656
+ let at = -1;
657
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
658
+ const line = lines[index];
659
+ if (/[◇■▲]/.test(line)) return void 0;
660
+ if (line.includes("\u25C6")) {
661
+ at = index;
662
+ break;
663
+ }
664
+ }
665
+ if (at < 0) return void 0;
666
+ const title = lines[at].replace(/^.*◆\s*/, "").trim();
667
+ const choices = [];
668
+ let selected = 0;
669
+ for (const line of lines.slice(at + 1)) {
670
+ const inline = /^\s*[│|]?\s*([●○])\s+(.+?)\s+\/\s+([●○])\s+(.+?)\s*$/.exec(line);
671
+ if (inline) {
672
+ return { prompt: { kind: "choice", title, choices: [inline[2], inline[4]], selected: inline[3] === "\u25CF" ? 1 : 0, style: "sideways" }, at };
673
+ }
674
+ const option = /^\s*[│|]?\s*([●○])\s+(.+?)\s*$/.exec(line);
675
+ if (!option) continue;
676
+ if (option[1] === "\u25CF") selected = choices.length;
677
+ choices.push(option[2]);
678
+ }
679
+ if (choices.length) return { prompt: { kind: "choice", title, choices, selected, style: "arrows" }, at };
680
+ return title ? { prompt: { kind: "input", prompt: title, secret: isSecret(title) }, at } : void 0;
681
+ }
682
+ function readEnquirer(lines) {
683
+ let at = -1;
684
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
685
+ if (/^\s*\?\s+\S/.test(lines[index])) {
686
+ at = index;
687
+ break;
688
+ }
689
+ }
690
+ if (at < 0) return void 0;
691
+ const options = lines.slice(at + 1).filter((line) => line.trim());
692
+ const firstRepeat = options.findIndex((line, index) => index > 0 && line.trim().replace(/^❯\s*/, "") === options[0].trim().replace(/^❯\s*/, ""));
693
+ const drawing = firstRepeat > 0 ? options.slice(options.length - firstRepeat) : options;
694
+ if (!drawing.some((line) => /^\s*❯/.test(line))) return void 0;
695
+ const choices = drawing.map((line) => line.trim().replace(/^❯\s*/, ""));
696
+ const selected = Math.max(0, drawing.findIndex((line) => /^\s*❯/.test(line)));
697
+ const title = lines[at].replace(/^\s*\?\s*/, "").replace(/\s*[›»].*$/, "").trim();
698
+ const shownAt = lines.lastIndexOf(drawing[0]);
699
+ return { prompt: { kind: "choice", title, choices, selected, style: "arrows" }, at: Math.max(at, shownAt) };
700
+ }
701
+ function numberedList(lines, unmarked = false) {
702
+ const plain = lines.map((line) => line.replace(/[│┃║]/g, " ").trimEnd());
703
+ const option = (line) => /^\s*(?:([●›❯>❭])|\((●|○)\))?\s*(\d+)[.)]?\s+(\S.*?)\s*$/.exec(line);
704
+ let index = plain.length - 1;
705
+ while (index >= 0 && !option(plain[index])) index -= 1;
706
+ if (index < 0) return void 0;
707
+ const found = [];
708
+ let expected = Number(option(plain[index])[3]);
709
+ if (expected < 2) return void 0;
710
+ let gap = 0;
711
+ for (; index >= 0 && expected >= 1; index -= 1) {
712
+ const match = option(plain[index]);
713
+ if (match && Number(match[3]) === expected) {
714
+ found.unshift({ at: index, match });
715
+ expected -= 1;
716
+ gap = 0;
717
+ continue;
718
+ }
719
+ if (++gap > 3) return void 0;
720
+ }
721
+ if (expected !== 0) return void 0;
722
+ const marked = found.findIndex(({ match }) => match[1] || match[2] === "\u25CF");
723
+ if (marked < 0 && !unmarked) return void 0;
724
+ const start = found[0].at;
725
+ const title = titleAbove(lines, start);
726
+ return {
727
+ prompt: { kind: "choice", title: title.replace(/^\?\s*/, ""), choices: found.map(({ match }) => match[4]), selected: Math.max(0, marked), style: "arrows" },
728
+ at: start,
729
+ marked: marked >= 0
730
+ };
731
+ }
732
+ function readNumbered(lines) {
733
+ return numberedList(lines);
734
+ }
735
+ function choiceKeys(prompt, to) {
736
+ if (prompt.style === "yes-no") return to === 0 ? "y\r" : "n\r";
737
+ if (prompt.style === "number") return `${to + 1}\r`;
738
+ const moves = to - prompt.selected;
739
+ if (prompt.style === "sideways") return `${(moves >= 0 ? "\x1B[C" : "\x1B[D").repeat(Math.abs(moves))}\r`;
740
+ return `${(moves >= 0 ? KEYS["{down}"] : KEYS["{up}"]).repeat(Math.abs(moves))}\r`;
741
+ }
742
+ function terminalReplies(chunk, cursor) {
743
+ let reply = "";
744
+ for (const match of chunk.matchAll(/\u001b\[(?:0?c|6n|\?(\d+)\$p|>0?q|5n)|\u001b\](1[01]);\?(?:\u0007|\u001b\\)/g)) {
745
+ const query = match[0];
746
+ if (/^\u001b\[0?c$/.test(query)) reply += "\x1B[?62;22c";
747
+ else if (query === "\x1B[6n") reply += `\x1B[${cursor.row + 1};${cursor.column + 1}R`;
748
+ else if (query === "\x1B[5n") reply += "\x1B[0n";
749
+ else if (match[1]) reply += `\x1B[?${match[1]};2$y`;
750
+ else if (/^\u001b\[>0?q$/.test(query)) reply += "\x1BP>|xterm(388)\x1B\\";
751
+ else if (match[2]) reply += `\x1B]${match[2]};rgb:${match[2] === "10" ? "ffff/ffff/ffff" : "0000/0000/0000"}\x1B\\`;
752
+ }
753
+ return reply;
754
+ }
755
+ function compact(text) {
756
+ return stripAnsi(text).replace(/\s+/g, "").toLowerCase();
757
+ }
758
+ async function openerStandIns() {
759
+ const dir = await mkdtemp(join(tmpdir(), "clikcode-open-"));
760
+ const log = join(dir, "opened");
761
+ const script = `#!/bin/sh
762
+ for a; do case "$a" in http://*|https://*) printf '%s\\n' "$a" >> "$CLIKCODE_OPENED";; esac; done
763
+ `;
764
+ await Promise.all(BROWSER_OPENERS.map(async (name) => {
765
+ await writeFile(join(dir, name), script);
766
+ await chmod(join(dir, name), 493);
767
+ }));
768
+ return { dir, log };
769
+ }
770
+ var SEARCH_CHOICE = "Search for another\u2026";
771
+ var SETTLE_MS = 350;
772
+ var REDRAW_MS = 4e3;
773
+ var SIGNED_IN_TIMINGS = { pollMs: 1e3, graceMs: 1500 };
774
+ var STEP_AGAIN_MS = 2e3;
775
+ var MAX_UNREAD_MS = 1e3;
776
+ var KEY_GAP_MS = 100;
777
+ async function runVendorSignIn(input) {
778
+ const timings = input.timings ?? SIGNED_IN_TIMINGS;
779
+ const { ui: given } = input;
780
+ const cancelled = () => new SignInCancelled(input.displayName);
781
+ const secrets = [];
782
+ const ui = {
783
+ show: (link) => given.show(link),
784
+ ...given.hide ? { hide: () => given.hide() } : {},
785
+ choose: (title, choices, selected) => given.choose(title, choices, selected),
786
+ ...given.signal ? { signal: given.signal } : {},
787
+ ask: async (prompt, secret, optional, alongside) => {
788
+ const typed = await given.ask(prompt, secret, optional, alongside);
789
+ if (secret && typed) secrets.push(typed);
790
+ return typed;
791
+ }
792
+ };
793
+ if (ui.signal?.aborted) throw cancelled();
794
+ const controller = new AbortController();
795
+ let stopped = false;
796
+ const cancel = () => {
797
+ if (controller.signal.aborted) return;
798
+ stopped = true;
799
+ controller.abort();
800
+ };
801
+ const finish = () => controller.abort();
802
+ ui.signal?.addEventListener("abort", cancel, { once: true });
803
+ const releaseSignals = forwardParentSignals(cancel, ["SIGTERM", "SIGHUP"]);
804
+ const standIns = process.platform === "win32" ? void 0 : await openerStandIns();
805
+ const env = {
806
+ ...input.env,
807
+ ...standIns ? {
808
+ PATH: `${standIns.dir}${delimiter}${input.env.PATH ?? process.env.PATH ?? ""}`,
809
+ BROWSER: join(standIns.dir, "xdg-open"),
810
+ CLIKCODE_OPENED: standIns.log
811
+ } : {}
812
+ };
813
+ let raw = "";
814
+ const screen = new Screen(SIGN_IN_ROWS, SIGN_IN_COLUMNS);
815
+ let changed = false;
816
+ let opened;
817
+ let shown;
818
+ let write = () => void 0;
819
+ let exited = false;
820
+ const fired = /* @__PURE__ */ new Map();
821
+ let answeredAt = 0;
822
+ let answering = false;
823
+ let lastPrompt;
824
+ let settle;
825
+ const publishLink = () => {
826
+ const url = chooseLoginLink({ printed: extractLoginUrl(raw), opened, local: input.local });
827
+ if (!url) return;
828
+ const code = extractLoginCode(raw, url);
829
+ if (shown && shown.url === url && shown.code === code) return;
830
+ shown = { url, ...code ? { code } : {} };
831
+ try {
832
+ ui.show(shown);
833
+ } catch {
834
+ }
835
+ };
836
+ const answer = async (work) => {
837
+ answering = true;
838
+ try {
839
+ const keys = await work();
840
+ if (exited) return;
841
+ if (keys === void 0) {
842
+ cancel();
843
+ return;
844
+ }
845
+ answeredAt = raw.length;
846
+ changed = false;
847
+ for (const key of keys.match(/\u001b\[[A-D]|[\r\u0003\u0004]|[^\r\u0003\u0004\u001b]+|\u001b/g) ?? []) {
848
+ if (exited) return;
849
+ write(key);
850
+ await sleep(KEY_GAP_MS);
851
+ }
852
+ } finally {
853
+ answering = false;
854
+ }
855
+ };
856
+ const read = () => {
857
+ if (answering || exited) return;
858
+ publishLink();
859
+ const since = compact(raw.slice(answeredAt));
860
+ const index = input.steps?.findIndex((rule, at) => Date.now() - (fired.get(at) ?? 0) >= STEP_AGAIN_MS && since.includes(compact(rule.when))) ?? -1;
861
+ const next = index >= 0 ? input.steps[index] : void 0;
862
+ if (next) {
863
+ fired.set(index, Date.now());
864
+ void answer(async () => next.ask ? `${await ui.ask(next.ask.prompt, Boolean(next.ask.secret))}\r` : keystrokes(next.send ?? "")).finally(schedule);
865
+ return;
866
+ }
867
+ if (!changed) return;
868
+ const prompt = readScreenPrompt(screen.state());
869
+ if (!prompt) return;
870
+ const key = `${prompt.kind}:${prompt.kind === "choice" ? `${prompt.title}
871
+ ${prompt.choices.join("\n")}` : prompt.prompt}`;
872
+ if (lastPrompt && lastPrompt.key === key && Date.now() - lastPrompt.at < REDRAW_MS) return;
873
+ lastPrompt = { key, at: Date.now() };
874
+ void answer(async () => {
875
+ if (await landed()) {
876
+ await sleep(timings.graceMs);
877
+ finish();
878
+ return "";
879
+ }
880
+ if (prompt.kind === "input") return `${await ui.ask(prompt.prompt, prompt.secret, prompt.optional)}\r`;
881
+ const choices = prompt.searchable ? [...prompt.choices, SEARCH_CHOICE] : prompt.choices;
882
+ const index2 = await ui.choose(prompt.title, choices, prompt.selected);
883
+ if (index2 === void 0) return void 0;
884
+ if (index2 === prompt.choices.length) return ui.ask(`Search ${prompt.title.replace(/:$/, "")}`, false);
885
+ return choiceKeys(prompt, index2);
886
+ }).finally(() => {
887
+ lastPrompt = { key, at: Date.now() };
888
+ schedule();
889
+ });
890
+ };
891
+ let deadline;
892
+ const readNow = () => {
893
+ if (settle) clearTimeout(settle);
894
+ if (deadline) clearTimeout(deadline);
895
+ settle = void 0;
896
+ deadline = void 0;
897
+ read();
898
+ };
899
+ const schedule = () => {
900
+ if (settle) clearTimeout(settle);
901
+ settle = setTimeout(readNow, SETTLE_MS);
902
+ deadline ??= setTimeout(readNow, MAX_UNREAD_MS);
903
+ };
904
+ const onOutput = (chunk) => {
905
+ raw += chunk;
906
+ screen.write(chunk);
907
+ const replies = terminalReplies(chunk, screen.state());
908
+ if (replies) write(replies);
909
+ changed = true;
910
+ schedule();
911
+ };
912
+ let succeeded = false;
913
+ const landed = async () => {
914
+ if (!succeeded && input.signedIn) succeeded = await input.signedIn().catch(() => false);
915
+ return succeeded;
916
+ };
917
+ const watch = input.signedIn ? setInterval(() => {
918
+ if (succeeded) return;
919
+ void landed().then((done) => {
920
+ if (done) setTimeout(finish, timings.graceMs);
921
+ });
922
+ }, timings.pollMs) : void 0;
923
+ const poll = standIns ? setInterval(() => {
924
+ void readFile(standIns.log, "utf8").then((text) => {
925
+ const last = text.trim().split("\n").pop();
926
+ if (last && last !== opened) {
927
+ opened = last;
928
+ publishLink();
929
+ }
930
+ }, () => void 0);
931
+ }, 200) : void 0;
932
+ let exitCode;
933
+ try {
934
+ const teed = await runInPty({
935
+ binary: input.binary,
936
+ args: input.args,
937
+ env,
938
+ onOutput,
939
+ onStdin: (send) => {
940
+ write = send;
941
+ },
942
+ signal: controller.signal
943
+ });
944
+ exitCode = teed.teed ? teed.exitCode : await runPiped(input.binary, input.args, env, onOutput, (send) => {
945
+ write = send;
946
+ }, controller.signal);
947
+ } finally {
948
+ exited = true;
949
+ ui.signal?.removeEventListener("abort", cancel);
950
+ releaseSignals();
951
+ if (poll) clearInterval(poll);
952
+ if (watch) clearInterval(watch);
953
+ if (settle) clearTimeout(settle);
954
+ if (deadline) clearTimeout(deadline);
955
+ if (standIns) await rm(standIns.dir, { recursive: true, force: true }).catch(quiet("gateway/login/vendor-sign-in"));
956
+ }
957
+ if (stopped) throw cancelled();
958
+ if (succeeded) return;
959
+ if (exitCode !== 0) {
960
+ throw new Error(`${input.displayName} sign-in exited with status ${exitCode}${failureReason(raw, secrets)}`);
961
+ }
962
+ }
963
+ var SignInCancelled = class extends Error {
964
+ constructor(name) {
965
+ super(`sign-in to ${name} was cancelled`);
966
+ }
967
+ };
968
+ function builtForNewerMacos(raw) {
969
+ const text = screenLines(raw).join("\n");
970
+ return /\bdyld\b/i.test(text) ? /built for (?:Mac OS X|macOS) (\d+(?:\.\d+)*)/i.exec(text)?.[1] : void 0;
971
+ }
972
+ function failureReason(raw, secrets) {
973
+ const newer = builtForNewerMacos(raw);
974
+ if (newer) return `: it was built for macOS ${newer} or newer and this Mac is older, so it cannot run here at all. Sign in to it on a newer computer, or use another provider on this one`;
975
+ const said = screenLines(raw).map((line) => line.trim()).filter(Boolean).filter((line) => !secrets.some((secret) => line.includes(secret)) && !(secrets.length && isSecret(line))).pop();
976
+ return said ? `: ${said}` : "";
977
+ }
978
+ function runPiped(binary, args, env, onOutput, onStdin, signal) {
979
+ return new Promise((resolve2, reject) => {
980
+ const child = spawnPortable(binary, [...args], { stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ...env } });
981
+ const abort = () => {
982
+ terminatePortable(child, "SIGTERM");
983
+ };
984
+ signal.addEventListener("abort", abort, { once: true });
985
+ child.stdin?.on("error", () => {
986
+ });
987
+ onStdin((text) => {
988
+ child.stdin?.write(text);
989
+ });
990
+ child.stdout?.setEncoding("utf8");
991
+ child.stderr?.setEncoding("utf8");
992
+ child.stdout?.on("data", onOutput);
993
+ child.stderr?.on("data", onOutput);
994
+ child.on("error", (error) => {
995
+ signal.removeEventListener("abort", abort);
996
+ reject(error);
997
+ });
998
+ child.on("close", (code) => {
999
+ signal.removeEventListener("abort", abort);
1000
+ resolve2(code);
1001
+ });
1002
+ });
1003
+ }
1004
+
1005
+ // src/harness/transport/native/login.ts
1006
+ import { mkdir, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
1007
+ import { dirname } from "node:path";
1008
+ var screens = new AsyncLocalStorage();
1009
+ function withSignInScreen(screen, work) {
1010
+ return screens.run(screen, work);
1011
+ }
1012
+ function plainSignInScreen(name, environment = process.env) {
1013
+ let opened = false;
1014
+ const controller = new AbortController();
1015
+ let withdraw;
1016
+ const line = (prompt) => new Promise((resolve2) => {
1017
+ withdraw?.();
1018
+ const reader = createInterface({ input: process.stdin, output: process.stdout });
1019
+ const settle = (text) => {
1020
+ if (withdraw === cancel) withdraw = void 0;
1021
+ reader.close();
1022
+ resolve2(text);
1023
+ };
1024
+ const cancel = () => settle("");
1025
+ withdraw = cancel;
1026
+ reader.question(prompt).then(settle, cancel);
1027
+ });
1028
+ return {
1029
+ signal: controller.signal,
1030
+ show: (link) => {
1031
+ const local = hasLocalDisplay(environment);
1032
+ if (local && !opened) {
1033
+ opened = true;
1034
+ openLoginUrl(link.url);
1035
+ }
1036
+ const hint = loginPortForwardHint(link.url, environment);
1037
+ process.stdout.write(`${local ? "" : loginUrlNotice(link.url, environment).clipboard}Sign in to ${name}:
1038
+ ${loginLinkLine(link.url)}
1039
+ ${hint ? `${hint}
1040
+ ` : ""}${link.code ? `Code: ${link.code}
1041
+ ` : ""}`);
1042
+ },
1043
+ ask: (prompt) => line(`${prompt}: `),
1044
+ choose: async (title, choices) => {
1045
+ process.stdout.write(`${title}
1046
+ ${choices.map((choice, index) => ` ${index + 1}. ${choice}`).join("\n")}
1047
+ `);
1048
+ const picked = Number.parseInt(await line("Number: "), 10);
1049
+ return picked >= 1 && picked <= choices.length ? picked - 1 : void 0;
1050
+ },
1051
+ stop: () => {
1052
+ withdraw?.();
1053
+ process.stdin.pause();
1054
+ }
1055
+ };
1056
+ }
1057
+ async function loginNativeHarness(spec, envOverrides = {}) {
1058
+ lifecycle("signin.start", { harness: spec.command });
1059
+ try {
1060
+ await loginNativeHarnessInner(spec, envOverrides);
1061
+ lifecycle("signin.end", { harness: spec.command, outcome: "signed in" });
1062
+ } catch (error) {
1063
+ lifecycle("signin.end", { harness: spec.command, outcome: (error instanceof Error ? error.message : String(error)).slice(0, 200) });
1064
+ throw error;
1065
+ }
1066
+ }
1067
+ async function loginNativeHarnessInner(spec, envOverrides) {
1068
+ await ensureNativeHarness(spec);
1069
+ const own = screens.getStore();
1070
+ const loginEnvironment = { ...process.env, ...envOverrides };
1071
+ const screen = own ?? plainSignInScreen(spec.displayName, loginEnvironment);
1072
+ const local = hasLocalDisplay(loginEnvironment);
1073
+ try {
1074
+ if (spec.loginKeyCommand) {
1075
+ const key = spec.loginKeyRoutes ? await askKey(spec, screen) : "";
1076
+ const route = key ? await routeFor(spec, spec.loginKeyRoutes, key, screen.signal) : void 0;
1077
+ await signInWithKey(spec, spec.loginKeyCommand, envOverrides, screen, route && { provider: route.choose[0], key });
1078
+ return;
1079
+ }
1080
+ await prepareAuthFilesForLogin(spec, envOverrides);
1081
+ const before = spec.authFiles?.length ? await authFilesStamp(spec, envOverrides) : void 0;
1082
+ const run = (ui) => runVendorSignIn({
1083
+ ...before !== void 0 ? { signedIn: async () => await authFilesStamp(spec, envOverrides) !== before && authFilePresent(spec, envOverrides) } : {},
1084
+ binary: spec.binary,
1085
+ // The order, everywhere: a sign-in whose localhost callback reaches this machine (a browser here, or ClikDeploy Mobile forwarding
1086
+ // the port), else the vendor's device sign-in, else a key. loginRemoteArgv is the device sign-in, for plain SSH only.
1087
+ args: !callbacksReachable(loginEnvironment) && spec.loginRemoteArgv ? spec.loginRemoteArgv : spec.loginArgv ?? [],
1088
+ env: envOverrides,
1089
+ displayName: spec.displayName,
1090
+ local,
1091
+ ...spec.loginSteps ? { steps: spec.loginSteps } : {},
1092
+ ui
1093
+ });
1094
+ const harness = localHarnessForCommand(spec.command);
1095
+ if (!harness || !ownLogin(spec)) {
1096
+ await run(screen);
1097
+ return;
1098
+ }
1099
+ const routes = spec.loginKeyRoutes;
1100
+ if (routes) {
1101
+ const instead2 = spec.loginAccountChoose ? await accountFirst(spec.displayName, spec.loginAccountChoose, screen, run, {
1102
+ prompt: `Or paste your ${spec.displayName} API key \xB7 Enter for other sign-ins`,
1103
+ others: true,
1104
+ isKey: async (text) => keyCandidates(routes, text, keyProviders()).length > 0 && Boolean(await routeFor(spec, routes, text, screen.signal).catch(quiet("harness/transport/native/login")))
1105
+ }) : { key: void 0 };
1106
+ if (!instead2) return;
1107
+ const key = instead2.key ?? (keyVariables(harness).length ? await askKey(spec, screen) : void 0);
1108
+ if (key && (await keyVariableFor(harness, key, screen.signal))?.checked) {
1109
+ await storeKey(harness, spec, envOverrides, key, screen.signal);
1110
+ return;
1111
+ }
1112
+ await run(await keyRoutedScreen(spec, routes, screen, keyProviders(), key ?? instead2.key, callbacksReachable(loginEnvironment)));
1113
+ return;
1114
+ }
1115
+ if (!harness.localAuth.includes("api-key") || spec.loginKeyCommand || !keyVariables(harness).length) {
1116
+ await run(screen);
1117
+ return;
1118
+ }
1119
+ const instead = await accountFirst(spec.displayName, spec.loginAccountChoose ?? [], screen, run, {
1120
+ prompt: `Or paste your ${spec.displayName} API key`,
1121
+ others: false,
1122
+ isKey: async (text) => (await keyVariableFor(harness, text, screen.signal))?.checked === true
1123
+ });
1124
+ if (instead?.key) await storeKey(harness, spec, envOverrides, instead.key, screen.signal);
1125
+ } finally {
1126
+ if (!own) screen.stop();
1127
+ }
1128
+ }
1129
+ async function accountFirst(name, labels, screen, run, offer) {
1130
+ const stop = new AbortController();
1131
+ const signal = AbortSignal.any([screen.signal, stop.signal]);
1132
+ const left = [...labels];
1133
+ let instead;
1134
+ let answered = () => void 0;
1135
+ const pasted = new Promise((resolve2) => {
1136
+ answered = resolve2;
1137
+ });
1138
+ const take = (key) => {
1139
+ instead = key;
1140
+ stop.abort();
1141
+ answered();
1142
+ };
1143
+ let current = 0;
1144
+ let withdrawn = false;
1145
+ const openField = () => {
1146
+ const asked = ++current;
1147
+ void screen.ask(offer.prompt, true, offer.others, true).then((text) => {
1148
+ if (asked === current && !signal.aborted) take(text.trim());
1149
+ });
1150
+ };
1151
+ const ui = {
1152
+ signal,
1153
+ show: (link) => screen.show(link),
1154
+ choose: async (title, choices, selected) => {
1155
+ const at = left.length ? optionFor(choices, left[0]) : -1;
1156
+ if (at >= 0) {
1157
+ left.shift();
1158
+ return at;
1159
+ }
1160
+ const remaining = choices.map((label, index) => ({ label, index })).filter(({ label }) => !/^(?:(?:use|(?:manually\s+)?enter|paste|sign in with|login with)\s+)?(?:(?:an?|your(?: own)?)\s+)?api[ -]?key(?:\s*\([^)]*\))?$/i.test(label.trim()));
1161
+ if (remaining.length < choices.length) {
1162
+ if (!remaining.length) return 0;
1163
+ if (remaining.length === 1) return remaining[0].index;
1164
+ const picked = await screen.choose(
1165
+ title,
1166
+ remaining.map(({ label }) => label),
1167
+ selected === void 0 ? void 0 : remaining.findIndex(({ index }) => index === selected)
1168
+ );
1169
+ return picked === void 0 ? void 0 : remaining[picked]?.index;
1170
+ }
1171
+ return screen.choose(title, choices, selected);
1172
+ },
1173
+ ask: async (prompt, secret, optional) => {
1174
+ const asked = ++current;
1175
+ if (secret) withdrawn = true;
1176
+ if (withdrawn) return screen.ask(prompt, secret, optional);
1177
+ const text = await screen.ask(`${prompt} \xB7 or paste your ${name} API key`, secret, optional);
1178
+ if (asked === current && text.trim() && await offer.isKey(text.trim())) {
1179
+ take(text.trim());
1180
+ return "";
1181
+ }
1182
+ if (!signal.aborted) openField();
1183
+ return text;
1184
+ }
1185
+ };
1186
+ openField();
1187
+ const finished = run(ui).then(() => true, (error) => {
1188
+ if (instead !== void 0) return false;
1189
+ throw error;
1190
+ });
1191
+ const done = await Promise.race([finished, pasted.then(() => false)]);
1192
+ if (done) {
1193
+ current++;
1194
+ return void 0;
1195
+ }
1196
+ await finished.catch(quiet("harness/transport/native/login"));
1197
+ if (screen.signal.aborted) throw new Error(`sign-in to ${name} was cancelled`);
1198
+ return { key: instead ?? "" };
1199
+ }
1200
+ async function keyVariableFor(harness, key, signal, providers = keyProviders()) {
1201
+ const variables = keyVariables(harness);
1202
+ const routes = variables.flatMap((variable) => {
1203
+ const provider = providerOfVariable(variable, providers);
1204
+ return provider ? [{ provider, choose: [variable] }] : [];
1205
+ });
1206
+ const candidates = keyCandidates(routes, key, providers);
1207
+ const accepted = await Promise.all(candidates.map((route) => acceptsKey(route, key, providers, signal)));
1208
+ const found = candidates[accepted.indexOf(true)];
1209
+ if (found) return { variable: found.choose[0], checked: true };
1210
+ return variables.length === 1 && !routes.length ? { variable: variables[0], checked: false } : void 0;
1211
+ }
1212
+ function providerOfVariable(variable, providers) {
1213
+ if (variable === "GEMINI_API_KEY" || variable === "GOOGLE_API_KEY") return "google";
1214
+ return Object.keys(providers).find((id) => `${id.toUpperCase().replace(/-/g, "_")}_API_KEY` === variable);
1215
+ }
1216
+ async function mergeVendorSettings(vendor, path, set) {
1217
+ let settings = {};
1218
+ const raw = await readFile2(path, "utf8").catch((error) => {
1219
+ if (error.code === "ENOENT") return void 0;
1220
+ throw error;
1221
+ });
1222
+ if (raw !== void 0) {
1223
+ try {
1224
+ settings = JSON.parse(raw);
1225
+ } catch {
1226
+ throw new Error(`${vendor}'s settings file ${path} is not plain JSON, so ClikCode left it alone. Fix or remove it, then paste the key again.`);
1227
+ }
1228
+ }
1229
+ await mkdir(dirname(path), { recursive: true });
1230
+ await writeFile2(path, `${JSON.stringify({ ...settings, ...set }, null, 2)}
1231
+ `, "utf8");
1232
+ }
1233
+ async function storeKey(harness, spec, env, key, signal) {
1234
+ const found = await keyVariableFor(harness, key, signal);
1235
+ if (!found) throw new Error(`${harness.displayName} does not accept that key -- check it was copied whole`);
1236
+ if (harness.loginKeyStdinArgv) {
1237
+ await captureNativeHarnessOutput(spec, harness.loginKeyStdinArgv, env, void 0, void 0, `${key}
1238
+ `);
1239
+ return;
1240
+ }
1241
+ const profile = harness.profileEnv ? env[harness.profileEnv] : void 0;
1242
+ if (!profile) throw new Error(`${harness.displayName} keeps a pasted key in an account of its own -- add one from /account`);
1243
+ await writeProfileKey(profile, found.variable, key);
1244
+ if (harness.apiKeySettings) {
1245
+ await mergeVendorSettings(harness.displayName, expandAuthPath(harness.apiKeySettings.path, env), harness.apiKeySettings.set);
1246
+ }
1247
+ }
1248
+ function ownLogin(spec) {
1249
+ return JSON.stringify(spec.loginArgv ?? []) === JSON.stringify(localHarnessForCommand(spec.command)?.loginArgv ?? []);
1250
+ }
1251
+ async function signInWithKey(spec, command, env, screen, routed) {
1252
+ const set = (provider, key2) => captureNativeHarnessOutput(spec, command.setArgv.map((part) => part.replace("{provider}", provider)), env, void 0, void 0, `${key2}
1253
+ `);
1254
+ if (routed) {
1255
+ await set(routed.provider, routed.key);
1256
+ return;
1257
+ }
1258
+ const cancelled = () => new Error(`sign-in to ${spec.displayName} was cancelled`);
1259
+ const listed = await captureNativeHarnessOutput(spec, command.providersArgv, env);
1260
+ const providers = [...new Set(listed.split("\n").map((line) => line.trim().split(/\s+/)[0] ?? "").filter((word) => /^[a-z][\w.-]*$/i.test(word)))];
1261
+ if (!providers.length) throw new Error(`${spec.displayName} listed no providers to sign in to`);
1262
+ const index = await screen.choose(`Sign in to ${spec.displayName} with`, providers);
1263
+ if (index === void 0 || screen.signal.aborted) throw cancelled();
1264
+ const key = (await screen.ask(`${providers[index]} API key`, true)).trim();
1265
+ if (!key || screen.signal.aborted) throw cancelled();
1266
+ await set(providers[index], key);
1267
+ }
1268
+ async function keyRoutedScreen(spec, routes, screen, providers = keyProviders(), given, callbacks) {
1269
+ const key = given ?? await askKey(spec, screen);
1270
+ if (!key) return callbacks === void 0 ? screen : preferredSignInMethod(screen, callbacks);
1271
+ const route = await routeFor(spec, routes, key, screen.signal, providers);
1272
+ const labels = [...route.choose];
1273
+ let searched;
1274
+ let keyGiven = false;
1275
+ const defaults = () => keyGiven && !labels.length;
1276
+ return {
1277
+ signal: screen.signal,
1278
+ show: (link) => screen.show(link),
1279
+ choose: async (title, choices, selected) => {
1280
+ while (labels[0]?.startsWith("?") && optionFor(choices, labels[0].slice(1)) < 0) labels.shift();
1281
+ const label = labels[0]?.replace(/^\?/, "");
1282
+ const at = label === void 0 ? -1 : optionFor(choices, label);
1283
+ if (at >= 0) {
1284
+ labels.shift();
1285
+ searched = void 0;
1286
+ return at;
1287
+ }
1288
+ const search = choices.at(-1) === SEARCH_CHOICE ? choices.length - 1 : choices.findIndex(isSearch);
1289
+ if (label !== void 0 && searched === void 0 && search >= 0) {
1290
+ searched = label;
1291
+ return search;
1292
+ }
1293
+ if (defaults() && selected !== void 0) return isSearch(choices[selected] ?? "") ? choices.findIndex((choice) => !isSearch(choice)) : selected;
1294
+ return screen.choose(title, choices, selected);
1295
+ },
1296
+ ask: async (prompt, secret, optional) => {
1297
+ if (searched !== void 0 && prompt.startsWith("Search ")) return searched.replace(/\s*\(.*$/, "");
1298
+ if (secret && !keyGiven) {
1299
+ keyGiven = true;
1300
+ return key;
1301
+ }
1302
+ if (defaults() && /\[[^\]]+\]$/.test(prompt)) return "";
1303
+ return screen.ask(prompt, secret, optional);
1304
+ }
1305
+ };
1306
+ }
1307
+ function isSearch(choice) {
1308
+ return choice === SEARCH_CHOICE || /^search\b/i.test(choice);
1309
+ }
1310
+ async function askKey(spec, screen) {
1311
+ const page = localHarnessForCommand(spec.command)?.loginKeyPage;
1312
+ if (page) {
1313
+ try {
1314
+ screen.show({ url: page });
1315
+ } catch {
1316
+ }
1317
+ }
1318
+ const key = (await screen.ask(`${spec.displayName} API key${page ? ` (make one at ${page})` : ""}, or Enter to choose a provider`, true, true)).trim();
1319
+ if (screen.signal.aborted) throw new Error(`sign-in to ${spec.displayName} was cancelled`);
1320
+ if (!key && page) screen.hide?.();
1321
+ return key;
1322
+ }
1323
+ function preferredSignInMethod(screen, callbacks) {
1324
+ const wanted = callbacks ? /\bbrowser\b/i : /\b(headless|device)\b/i;
1325
+ return {
1326
+ ...screen,
1327
+ show: (link) => screen.show(link),
1328
+ ask: (...args) => screen.ask(...args),
1329
+ choose: async (title, choices, selected) => {
1330
+ const pick = /login method|sign.?in method/i.test(title) ? choices.findIndex((choice) => wanted.test(choice)) : -1;
1331
+ return pick >= 0 ? pick : screen.choose(title, choices, selected);
1332
+ }
1333
+ };
1334
+ }
1335
+ async function routeFor(spec, routes, key, signal, providers = keyProviders()) {
1336
+ const candidates = keyCandidates(routes, key, providers);
1337
+ const accepted = await Promise.all(candidates.map((route2) => acceptsKey(route2, key, providers, signal)));
1338
+ const route = candidates[accepted.indexOf(true)];
1339
+ if (!route) throw new Error(`no provider ${spec.displayName} signs in to accepts that key -- check it was copied whole`);
1340
+ return route;
1341
+ }
1342
+ function optionFor(choices, label) {
1343
+ const want = label.toLowerCase();
1344
+ const lower = choices.map((choice) => choice.toLowerCase());
1345
+ const exact = lower.indexOf(want);
1346
+ return exact >= 0 ? exact : lower.findIndex((choice) => choice.startsWith(want) && /^\s+[^\p{L}\p{N}\s]/u.test(choice.slice(want.length)));
1347
+ }
1348
+ function keyCandidates(routes, key, providers) {
1349
+ const issues = (provider) => Boolean(provider.prefixes?.some((prefix) => key.startsWith(prefix)));
1350
+ const claimed = Object.values(providers).some(issues);
1351
+ return routes.filter((route) => {
1352
+ if (!("provider" in route)) return true;
1353
+ const provider = providers[route.provider];
1354
+ return claimed ? issues(provider) : !provider.prefixes || Boolean(provider.unprefixed);
1355
+ });
1356
+ }
1357
+ async function acceptsKey(route, key, providers, signal) {
1358
+ const provider = "provider" in route ? providers[route.provider] : void 0;
1359
+ const auth = provider?.header ? { [provider.header]: key } : { authorization: `Bearer ${key}` };
1360
+ try {
1361
+ const response = provider ? await fetch(provider.probe, { headers: { ...auth, ...provider.headers }, signal }) : await fetch(route.url, {
1362
+ method: "POST",
1363
+ headers: { ...auth, "content-type": "application/json" },
1364
+ body: JSON.stringify({ model: "probe", messages: [] }),
1365
+ signal
1366
+ });
1367
+ await response.body?.cancel();
1368
+ return provider ? response.ok : response.status !== 401 && response.status !== 403;
1369
+ } catch {
1370
+ return false;
1371
+ }
1372
+ }
1373
+
1374
+ // src/session/state/views.ts
1375
+ function accountView(account) {
1376
+ const { credentialRef: _credentialRef, ...safe } = account;
1377
+ return safe;
1378
+ }
1379
+
1380
+ // src/harness/accounts/account-usage.ts
1381
+ import { randomBytes } from "node:crypto";
1382
+ import { readFile as readFile3, unlink, utimes, writeFile as writeFile3 } from "node:fs/promises";
1383
+ import { hostname } from "node:os";
1384
+ import { dirname as dirname2, join as join2 } from "node:path";
1385
+ var probesInFlight = /* @__PURE__ */ new Map();
1386
+ var USAGE_PROBE_DEADLINE_MS = 6e4;
1387
+ function probeOnce(key, probe, deadlineMs = USAGE_PROBE_DEADLINE_MS) {
1388
+ const running = probesInFlight.get(key);
1389
+ if (running) return running;
1390
+ let timer;
1391
+ const deadline = new Promise((resolve2) => {
1392
+ timer = setTimeout(resolve2, deadlineMs, void 0);
1393
+ timer.unref();
1394
+ });
1395
+ const asked = Promise.race([probe().catch(quiet("harness/accounts/account-usage")), deadline]).finally(() => {
1396
+ clearTimeout(timer);
1397
+ if (probesInFlight.get(key) === asked) probesInFlight.delete(key);
1398
+ });
1399
+ probesInFlight.set(key, asked);
1400
+ return asked;
1401
+ }
1402
+ function probeInFlight(account) {
1403
+ const harness = localHarnessForProvider(account.provider);
1404
+ return Boolean(harness) && probesInFlight.has(usageCacheKey(harness.command, account.id, void 0));
1405
+ }
1406
+ var USAGE_PAINT_WAIT_MS = 3e3;
1407
+ async function nativeUsageReading(session, state, options = {}) {
1408
+ const reading = await reportedNativeUsageReading(session, state, options);
1409
+ return accountDisplayUsage(state.accounts.find((account) => account.id === session.accountId), reading);
1410
+ }
1411
+ async function reportedNativeUsageReading(session, state, options) {
1412
+ const probe = session.nativeHarness ? NATIVE_USAGE_PROBES[session.nativeHarness] : void 0;
1413
+ const reportsOnStream = session.nativeHarness ? NATIVE_STREAM_USAGE_READINGS[session.nativeHarness] !== void 0 : false;
1414
+ const account = session.accountId ? state.accounts.find((item) => item.id === session.accountId) : void 0;
1415
+ if (!probe && !reportsOnStream) return void 0;
1416
+ const cacheKey = usageCacheKey(session.nativeHarness, account?.id, session.nativeSessionId);
1417
+ const cached = nativeUsageCache.get(cacheKey);
1418
+ const shared = account?.usage;
1419
+ const sharedEntry = shared && {
1420
+ at: Date.parse(shared.at),
1421
+ ...shared.label === void 0 ? {} : { label: shared.label },
1422
+ ...shared.failed ? { failed: true } : {},
1423
+ ...shared.windows?.length ? { windows: shared.windows } : {}
1424
+ };
1425
+ const entry = cached && sharedEntry ? sharedEntry.at > cached.at ? sharedEntry : cached : cached ?? sharedEntry;
1426
+ const turnSinceReading = entry !== void 0 && account !== void 0 && state.invocations.some((invocation) => invocation.accountId === account.id && Date.parse(invocation.at) - invocation.latencyMs > entry.at);
1427
+ const askedAt = Math.max(entry?.at ?? Number.NEGATIVE_INFINITY, account ? usageAskedAt(account) : Number.NEGATIVE_INFINITY);
1428
+ const reusable = entry && Date.now() - askedAt < USAGE_RECHECK_MS && !turnSinceReading && (entry.failed || usageReadingIsCurrent(entry)) ? entry : void 0;
1429
+ if (options.cachedOnly) {
1430
+ const known = entry && entry.label !== void 0 && (!entry.windows?.length || usageReadingIsCurrent(entry)) ? entry : void 0;
1431
+ return known?.label === void 0 ? void 0 : { windows: known.windows ?? [], label: known.label };
1432
+ }
1433
+ if (reusable && !options.network) {
1434
+ nativeUsageCache.set(cacheKey, reusable);
1435
+ return reusable.label === void 0 ? void 0 : { windows: reusable.windows ?? [], label: reusable.label };
1436
+ }
1437
+ if (!account || account.status !== "ready" || account.verification) {
1438
+ return entry?.label === void 0 ? void 0 : { windows: entry.windows ?? [], label: entry.label };
1439
+ }
1440
+ account.usageCheckedAt = (/* @__PURE__ */ new Date()).toISOString();
1441
+ if (probe) await writeState(state).catch(quiet("harness/accounts/account-usage"));
1442
+ const harness = localHarnessForProvider(account.provider);
1443
+ const environment = harness ? nativeAccountEnvironment(harness, account) : nativeProfileEnvironment(account.nativeProfile);
1444
+ const settle = async (reading) => {
1445
+ const carried = entry && usageReadingIsCurrent(entry) ? entry : void 0;
1446
+ const probedAt = Date.now();
1447
+ const next = reading?.label !== void 0 ? { at: probedAt, label: reading.label, ...reading.windows.length ? { windows: reading.windows } : {} } : { at: probedAt, failed: true, ...carried?.label === void 0 ? {} : { label: carried.label }, ...carried?.windows?.length ? { windows: carried.windows } : {} };
1448
+ nativeUsageCache.set(cacheKey, next);
1449
+ if (reading?.plan) account.plan = reading.plan;
1450
+ if (reading?.account === "signed-out") account.status = "needs_login";
1451
+ else if (reading?.account) account.verification = { ...reading.account.verify ? { url: reading.account.verify } : {}, at: new Date(probedAt).toISOString() };
1452
+ if (reading?.label !== void 0) {
1453
+ account.usage = accountUsageFrom(next);
1454
+ settleQuotaMark(account);
1455
+ } else if (carried?.windows?.length && account.usage?.failed) {
1456
+ account.usage = {
1457
+ at: new Date(carried.at).toISOString(),
1458
+ ...carried.label === void 0 ? {} : { label: carried.label },
1459
+ windows: carried.windows
1460
+ };
1461
+ } else if (!carried?.windows?.length) {
1462
+ account.usage = accountUsageFrom(next);
1463
+ }
1464
+ await writeState(state).catch(quiet("harness/accounts/account-usage"));
1465
+ const shown = !reading?.label && carried?.windows?.length ? carried : next;
1466
+ return {
1467
+ windows: shown.windows ?? [],
1468
+ ...shown.label === void 0 ? {} : { label: shown.label },
1469
+ ...reading?.plan ? { plan: reading.plan } : {}
1470
+ };
1471
+ };
1472
+ const asking = probe ? probeOnce(cacheKey, () => probe(environment)) : Promise.resolve(void 0);
1473
+ const settled = asking.then(settle);
1474
+ if (options.network || !probe) return settled;
1475
+ settled.catch(quiet("harness/accounts/account-usage"));
1476
+ const stale = entry?.label === void 0 ? void 0 : { windows: entry.windows ?? [], label: entry.label };
1477
+ return Promise.race([settled, new Promise((resolve2) => {
1478
+ setTimeout(() => resolve2(stale), USAGE_PAINT_WAIT_MS).unref();
1479
+ })]);
1480
+ }
1481
+ function accountPseudoSession(account, state, harnessCommand) {
1482
+ const related = state.sessions.find((item) => item.accountId === account.id && item.nativeSessionId);
1483
+ return related ?? {
1484
+ id: `account:${account.id}`,
1485
+ route: "local",
1486
+ accountId: account.id,
1487
+ provider: account.provider,
1488
+ model: null,
1489
+ effort: "medium",
1490
+ createdAt: "",
1491
+ updatedAt: "",
1492
+ status: "active",
1493
+ nativeHarness: harnessCommand
1494
+ };
1495
+ }
1496
+ async function accountUsageLabel(account, state, options = {}) {
1497
+ return (await accountUsageReading(account, state, options))?.label;
1498
+ }
1499
+ async function accountUsageReading(account, state, options = {}) {
1500
+ if (account.authKind !== "vendor-cli") return void 0;
1501
+ const harness = localHarnessForProvider(account.provider);
1502
+ if (!harness) return void 0;
1503
+ return nativeUsageReading(accountPseudoSession(account, state, harness.command), state, options);
1504
+ }
1505
+ function cachedAccountUsageLabel(account, state) {
1506
+ if (account.authKind !== "vendor-cli") return void 0;
1507
+ const harness = localHarnessForProvider(account.provider);
1508
+ if (!harness) return void 0;
1509
+ const reported = nativeUsageCache.get(usageCacheKey(harness.command, account.id));
1510
+ const shared = account.usage;
1511
+ const sharedAt = Date.parse(shared?.at ?? "");
1512
+ const latest = shared && Number.isFinite(sharedAt) && (!reported || sharedAt > reported.at) ? { at: sharedAt, label: shared.label, failed: shared.failed, windows: shared.windows } : reported;
1513
+ if (!latest || latest.failed || latest.label === void 0) return void 0;
1514
+ if (latest.windows?.length) return usageReadingIsCurrent(latest) ? accountDisplayUsage(account, { windows: latest.windows, label: latest.label })?.label : void 0;
1515
+ return Date.now() - latest.at < USAGE_RECHECK_MS ? latest.label : void 0;
1516
+ }
1517
+ function accountUsageCanBeAsked(account) {
1518
+ let command;
1519
+ try {
1520
+ command = localHarnessForProvider(account.provider)?.command;
1521
+ } catch {
1522
+ command = void 0;
1523
+ }
1524
+ return Boolean(command && NATIVE_USAGE_PROBES[command]);
1525
+ }
1526
+ var USAGE_IDLE_RECHECK_MS = 15 * 6e4;
1527
+ function accountsDueForUsageRecheck(state, now = Date.now(), canBeAsked = accountUsageCanBeAsked) {
1528
+ return state.accounts.filter((account) => {
1529
+ if (account.authKind !== "vendor-cli" || account.status !== "ready" || !canBeAsked(account)) return false;
1530
+ const held = account.quotaState === "exhausted" || vendorWindows(account).some(windowSpent);
1531
+ return now - usageAskedAt(account) >= (held ? USAGE_RECHECK_MS : USAGE_IDLE_RECHECK_MS);
1532
+ });
1533
+ }
1534
+ function recheckRecoveredAccounts(state, options = {}) {
1535
+ const ask = options.ask ?? ((account, latest) => accountUsageReading(account, latest, { network: true }));
1536
+ const canBeAsked = options.canBeAsked ?? accountUsageCanBeAsked;
1537
+ rechecking ??= (async () => {
1538
+ const due = accountsDueForUsageRecheck(state, options.now, canBeAsked);
1539
+ if (!due.length) return;
1540
+ const release = await takeRecheckLease();
1541
+ if (!release) return;
1542
+ try {
1543
+ for (const { id } of due) {
1544
+ const latest = await readState({ transcripts: [] });
1545
+ const account = latest.accounts.find((item) => item.id === id);
1546
+ if (!account || !accountsDueForUsageRecheck({ ...latest, accounts: [account] }, Date.now(), canBeAsked).length) continue;
1547
+ await ask(account, latest).catch(quiet("harness/accounts/account-usage"));
1548
+ }
1549
+ } finally {
1550
+ await release();
1551
+ }
1552
+ })().finally(() => {
1553
+ rechecking = void 0;
1554
+ });
1555
+ return rechecking;
1556
+ }
1557
+ var rechecking;
1558
+ async function takeRecheckLease() {
1559
+ const path = join2(stateDirectory(), "cache", "usage-recheck.lease");
1560
+ await ensurePrivateDirectory(dirname2(path));
1561
+ const mine = JSON.stringify({ pid: process.pid, host: hostname(), nonce: randomBytes(9).toString("hex"), at: (/* @__PURE__ */ new Date()).toISOString() });
1562
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1563
+ try {
1564
+ await writeFile3(path, mine, { encoding: "utf8", mode: 384, flag: "wx" });
1565
+ } catch (error) {
1566
+ if (error.code !== "EEXIST") return void 0;
1567
+ const raw = await readFile3(path, "utf8").catch(quiet("harness/accounts/account-usage"));
1568
+ if (raw !== void 0 && !await lockLooksStale(path, raw)) return void 0;
1569
+ if (raw !== void 0) await unlink(path).catch(quiet("harness/accounts/account-usage"));
1570
+ continue;
1571
+ }
1572
+ const heartbeat = setInterval(() => {
1573
+ const now = /* @__PURE__ */ new Date();
1574
+ void utimes(path, now, now).catch(quiet("harness/accounts/account-usage"));
1575
+ }, LOCK_TUNING.heartbeatMs);
1576
+ heartbeat.unref();
1577
+ return async () => {
1578
+ clearInterval(heartbeat);
1579
+ if (await readFile3(path, "utf8").catch(quiet("harness/accounts/account-usage")) === mine) await unlink(path).catch(quiet("harness/accounts/account-usage"));
1580
+ };
1581
+ }
1582
+ return void 0;
1583
+ }
1584
+
1585
+ // src/harness/accounts/profiles.ts
1586
+ import { existsSync } from "node:fs";
1587
+ import { chmod as chmod2, lstat, readdir, realpath, rm as rm2 } from "node:fs/promises";
1588
+ import { homedir } from "node:os";
1589
+ import { join as join3, relative, resolve, sep } from "node:path";
1590
+ function profileEnvironment(harness, account) {
1591
+ return homeRedirectEnvironment(harness, nativeProfileEnvironment(account?.nativeProfile), { home: homedir(), exists: existsSync });
1592
+ }
1593
+ function clikcodeProfilesRoot() {
1594
+ return resolve(join3(stateDirectory(), "profiles"));
1595
+ }
1596
+ async function resolvePurgeableProfile(profilePath) {
1597
+ const root = clikcodeProfilesRoot();
1598
+ const target = resolve(profilePath);
1599
+ const inside = relative(root, target);
1600
+ if (!inside || inside.startsWith("..") || resolve(root, inside) !== target) return { refused: "outside the ClikCode profiles directory" };
1601
+ const segments = inside.split(sep);
1602
+ if (segments.length !== 2 || segments.some((segment) => !segment || segment === "." || segment === "..")) {
1603
+ return { refused: "not a <harness>/<profile> directory" };
1604
+ }
1605
+ let info;
1606
+ try {
1607
+ info = await lstat(target);
1608
+ } catch {
1609
+ return { refused: "already gone" };
1610
+ }
1611
+ if (info.isSymbolicLink()) return { refused: "a symbolic link" };
1612
+ if (!info.isDirectory()) return { refused: "not a directory" };
1613
+ try {
1614
+ const [realRoot, realTarget] = await Promise.all([realpath(root), realpath(target)]);
1615
+ if (realTarget !== join3(realRoot, ...segments)) return { refused: "resolves outside the ClikCode profiles directory" };
1616
+ } catch {
1617
+ return { refused: "could not be resolved" };
1618
+ }
1619
+ return { path: target };
1620
+ }
1621
+ async function purgeAccountProfile(account, remainingAccounts) {
1622
+ const profilePath = account.nativeProfile?.path;
1623
+ if (!profilePath) return void 0;
1624
+ const target = resolve(profilePath);
1625
+ if (remainingAccounts.some((other) => other.nativeProfile?.path && resolve(other.nativeProfile.path) === target)) return void 0;
1626
+ const verdict = await resolvePurgeableProfile(profilePath);
1627
+ if ("refused" in verdict) return void 0;
1628
+ await removeTree(verdict.path);
1629
+ return verdict.path;
1630
+ }
1631
+ async function removeTree(path) {
1632
+ try {
1633
+ await rm2(path, { recursive: true, force: true });
1634
+ } catch (error) {
1635
+ if (error.code !== "EACCES" && error.code !== "EPERM") throw error;
1636
+ await makeWritable(path);
1637
+ await rm2(path, { recursive: true, force: true });
1638
+ }
1639
+ }
1640
+ async function makeWritable(path) {
1641
+ const info = await lstat(path);
1642
+ if (!info.isDirectory()) return;
1643
+ await chmod2(path, info.mode | 448);
1644
+ for (const name of await readdir(path)) await makeWritable(join3(path, name));
1645
+ }
1646
+
1647
+ // src/commands/account.ts
1648
+ var emitHarnessOutput = () => {
1649
+ };
1650
+ function setEmitHarnessOutput(fn) {
1651
+ emitHarnessOutput = fn;
1652
+ }
1653
+ var ACCOUNT_LIMIT_NOTE = "At an account's usage limit, ClikCode moves the chat to another account of the same provider that has usage left (`fallbacks`), and the turn carries on. With none left, it offers another provider.";
1654
+ var ACCOUNT_LIST_PROBE_WAIT_MS = 1500;
1655
+ async function accountSignedOutOnDisk(account) {
1656
+ if (account.authKind !== "vendor-cli" || account.status !== "ready") return false;
1657
+ const harness = localHarnessForProvider(account.provider);
1658
+ if (!harness || !hasAuthEvidence(harness)) return false;
1659
+ return !await authEvidencePresent(harness, profileEnvironment(harness, account));
1660
+ }
1661
+ async function aiAccountsList(options = {}) {
1662
+ const state = await readState({ transcripts: [] });
1663
+ const signedOut = new Set((await Promise.all(state.accounts.map(async (account) => await accountSignedOutOnDisk(account) ? account.id : void 0))).filter(Boolean));
1664
+ const ready = (account) => account.status === "ready" && !signedOut.has(account.id) && accountCanTakeTurn(account);
1665
+ const now = Date.now();
1666
+ const asking = state.accounts.filter((account) => account.status === "ready" && accountUsageCanBeAsked(account) && now - usageAskedAt(account) >= USAGE_RECHECK_MS);
1667
+ await Promise.race([
1668
+ Promise.allSettled(asking.map((account) => accountUsageReading(account, state))),
1669
+ new Promise((resolve2) => {
1670
+ setTimeout(resolve2, ACCOUNT_LIST_PROBE_WAIT_MS).unref();
1671
+ })
1672
+ ]);
1673
+ const accounts = await Promise.all(state.accounts.map(async (account) => {
1674
+ const reading = await accountUsageReading(account, state, { cachedOnly: true });
1675
+ const checking = !reading && account.status === "ready" && accountUsageCanBeAsked(account) && (probeInFlight(account) || !account.usage && now - usageAskedAt(account) < USAGE_RECHECK_MS);
1676
+ const resets = usageResetLabel(reading?.windows);
1677
+ const { models: _models, nativeProfile: _profile, ...brief } = accountView(account);
1678
+ const fallbacks = state.accounts.filter((other) => other.id !== account.id && other.provider === account.provider && ready(other)).length;
1679
+ return {
1680
+ ...options.models ? accountView(account) : brief,
1681
+ ...signedOut.has(account.id) ? { status: "needs_login" } : {},
1682
+ usage: reading?.label ?? (checking ? "checking\u2026" : "not reported"),
1683
+ ...resets ? { resets } : {},
1684
+ canTakeTurn: ready(account),
1685
+ fallbacks,
1686
+ // An account kept from a harness the catalog has since retired (Crush)
1687
+ // can run nothing. Its stored status is the user's, so it stays; this
1688
+ // says what it is worth.
1689
+ ...localHarnessForProvider(account.provider) ? {} : {
1690
+ supported: false,
1691
+ note: `${account.provider} is no longer a supported tool; remove this account with \`clikcode accounts remove ${account.id}\``
1692
+ }
1693
+ };
1694
+ }));
1695
+ emitResult({ accounts, onLimit: ACCOUNT_LIMIT_NOTE });
1696
+ }
1697
+ async function aiAccountProviders() {
1698
+ emitResult({ harnesses: builtInHarnesses() });
1699
+ }
1700
+ function installSummary(harness) {
1701
+ const route = harnessInstallRoute(harness);
1702
+ if (route.kind === "none") return { kind: "none", automatic: false, note: route.reason };
1703
+ return {
1704
+ kind: route.kind,
1705
+ automatic: true,
1706
+ ...route.kind === "npm" ? { package: route.package } : route.kind === "script" ? { url: route.step.url } : { package: route.step.package },
1707
+ command: manualInstallCommand(route)
1708
+ };
1709
+ }
1710
+ function versionFromOutput(text) {
1711
+ return text.split(/\r?\n/).map((line) => line.trim()).find((line) => /\bv?\d+\.\d+(?:\.\d+)?/.test(line) && !/deprecat|warning/i.test(line));
1712
+ }
1713
+ async function aiDoctor() {
1714
+ const flush = async () => {
1715
+ await saveVersionMemo().catch(quiet("commands/account"));
1716
+ };
1717
+ const harnesses = await Promise.all(builtInHarnesses().map(async (harness) => {
1718
+ const inspection = await inspectNativeHarness(harness);
1719
+ if (inspection.installed && inspection.version && !/\d+\.\d+/.test(inspection.version)) {
1720
+ const found = versionFromOutput(await vendorCommandText({ gate: { inert: "version" }, binary: harness.binary, argv: harness.versionArgv ?? ["--version"], environment: {}, deadlineMs: INERT_DEADLINE_MS }).catch(() => ""));
1721
+ if (found) inspection.version = found;
1722
+ }
1723
+ return {
1724
+ command: harness.command,
1725
+ displayName: harness.displayName,
1726
+ provider: harness.provider,
1727
+ binary: harness.binary,
1728
+ integration: harnessIntegrationLevel(harness),
1729
+ install: installSummary(harness),
1730
+ ...inspection,
1731
+ capabilities: {
1732
+ centralizedTurns: Boolean(harness.turn),
1733
+ scriptedLogin: Boolean(harness.loginArgv?.length),
1734
+ interactiveAuthHandoff: harness.loginArgv !== void 0 && harness.loginArgv.length === 0,
1735
+ accountAdd: harness.localAuth.includes("api-key") || harness.loginArgv !== void 0,
1736
+ accountStatus: Boolean(harness.statusArgv) || hasAuthEvidence(harness),
1737
+ logout: harnessCanLogout(harness),
1738
+ isolatedProfiles: Boolean(harness.profileEnv),
1739
+ modelSelection: harnessSupportsModelSelection(harness),
1740
+ workspaceSelection: Boolean(harness.workspaceArgvPrefix),
1741
+ effortSelection: harnessSupportsEffort(harness),
1742
+ permissionModeSelection: (harness.permissionModes?.length ?? 0) > 0,
1743
+ permissionModes: harness.permissionModes ?? [],
1744
+ exactResume: Boolean(harness.session?.resumeIdPrefix),
1745
+ preallocatedSessionIdentity: Boolean(harness.session?.createIdPrefix || harness.session?.createSessionArgv),
1746
+ sessionDiscovery: Boolean(harness.session?.discoverArgv || FS_SESSION_DISCOVERY[harness.command]),
1747
+ transcriptImport: Boolean(nativeTranscriptReader(harness))
1748
+ }
1749
+ };
1750
+ }));
1751
+ await flush();
1752
+ emitResult({ adapterVersion: harnessAdapterVersion(), harnesses, localModelCatalog: { diagnostics: (await import("./chunk-3QLHYYFK.js")).catalogDiagnostics() } });
1753
+ }
1754
+ async function settleReauthenticatedProfile(harness, existing, fresh, state) {
1755
+ if (!fresh || existing.nativeProfile?.path === fresh.path) return void 0;
1756
+ const keepsChats = existing.nativeProfile && state.sessions.some((session) => session.accountId === existing.id && session.nativeSessionId);
1757
+ if (keepsChats && await adoptAuthFiles(
1758
+ harness,
1759
+ { root: fresh.path, environment: profileEnvironment(harness, { nativeProfile: fresh }) },
1760
+ { root: existing.nativeProfile.path, environment: profileEnvironment(harness, existing) }
1761
+ )) return void 0;
1762
+ const left = keepsChats ? void 0 : existing.nativeProfile?.path;
1763
+ existing.nativeProfile = fresh;
1764
+ return left;
1765
+ }
1766
+ async function syncAccountIdentityAfterLogin(harness, account, state) {
1767
+ account.status = "ready";
1768
+ account.signedInAt = (/* @__PURE__ */ new Date()).toISOString();
1769
+ delete account.neverSignedIn;
1770
+ const captureCredential = vendorCredentialCapture(harness);
1771
+ if (captureCredential && account.nativeProfile?.path) {
1772
+ if (!await captureCredential(account.nativeProfile.path)) {
1773
+ throw new Error(`${harness.displayName} login completed, but ClikCode could not save its API key into this account\u2019s isolated profile. The account was not updated.`);
1774
+ }
1775
+ }
1776
+ const derived = await deriveAccountLabel(harness, account.nativeProfile?.path);
1777
+ if (!derived) {
1778
+ await writeState(state);
1779
+ return account;
1780
+ }
1781
+ const existingMatch = await matchingVendorAccount(state.accounts, harness, derived, account.id);
1782
+ if (existingMatch) {
1783
+ existingMatch.label = nameAccount(state.accounts.filter((item) => item.id !== account.id), harness, derived, existingMatch.id);
1784
+ existingMatch.status = "ready";
1785
+ existingMatch.signedInAt = account.signedInAt;
1786
+ await settleReauthenticatedProfile(harness, existingMatch, account.nativeProfile, state);
1787
+ state.accounts = state.accounts.filter((item) => item.id !== account.id);
1788
+ for (const session of state.sessions) if (session.accountId === account.id) session.accountId = existingMatch.id;
1789
+ for (const invocation of state.invocations) if (invocation.accountId === account.id) invocation.accountId = existingMatch.id;
1790
+ await writeState(state);
1791
+ return existingMatch;
1792
+ }
1793
+ account.label = nameAccount(state.accounts, harness, derived, account.id);
1794
+ await writeState(state);
1795
+ return account;
1796
+ }
1797
+ async function aiAccountLogin(harnessCommandName, label) {
1798
+ const touched = /* @__PURE__ */ new Set();
1799
+ try {
1800
+ return await signInAccount(harnessCommandName, label, touched);
1801
+ } finally {
1802
+ if (touched.size) {
1803
+ const { accounts } = await readState({ transcripts: [] });
1804
+ for (const path of touched) await purgeAccountProfile({ nativeProfile: { env: "", path } }, accounts).catch(quiet("commands/account"));
1805
+ }
1806
+ }
1807
+ }
1808
+ function forgetOldCredential(account) {
1809
+ account.models = [];
1810
+ clearQuotaMark(account);
1811
+ }
1812
+ async function signInAccount(harnessCommandName, label, touched) {
1813
+ const harness = localHarnessForCommand(harnessCommandName);
1814
+ if (!harness) throw new Error(`unknown local harness: ${harnessCommandName}`);
1815
+ const state = await readState({ transcripts: [] });
1816
+ const explicit = label?.trim();
1817
+ let accountLabel = explicit || nameAccount(state.accounts, harness);
1818
+ if (!accountLabel) throw new Error("account label cannot be empty");
1819
+ const singleSlotExisting = !harness.profileEnv ? state.accounts.find((account) => account.provider === harness.provider && account.authKind === "vendor-cli") : void 0;
1820
+ if (singleSlotExisting) {
1821
+ await loginNativeHarness(harness, {});
1822
+ const signedIn = await syncAccountIdentityAfterLogin(harness, singleSlotExisting, state);
1823
+ emitHarnessOutput({ status: "connected", harness: harness.command, account: signedIn.label, credentialBoundary: "local-only" });
1824
+ return signedIn.label;
1825
+ }
1826
+ const accountId = randomUUID();
1827
+ const profilePath = harness.profileEnv ? join4(stateDirectory(), "profiles", harness.command, accountId) : void 0;
1828
+ if (profilePath) {
1829
+ touched.add(profilePath);
1830
+ await mkdir2(profilePath, { recursive: true, mode: 448 });
1831
+ }
1832
+ const extraEnv = profilePath ? profileExtraEnvironment(harness, profilePath) : void 0;
1833
+ const nativeProfile = profilePath && harness.profileEnv ? { env: harness.profileEnv, path: profilePath, ...extraEnv ? { extraEnv } : {} } : void 0;
1834
+ const captureCredential = vendorCredentialCapture(harness);
1835
+ if (captureCredential && profilePath && harness.profileEnv) {
1836
+ for (const previous of state.accounts.filter((account) => account.provider === harness.provider && !account.nativeProfile)) {
1837
+ const previousPath = join4(stateDirectory(), "profiles", harness.command, previous.id);
1838
+ touched.add(previousPath);
1839
+ await mkdir2(previousPath, { recursive: true, mode: 448 });
1840
+ if (await captureCredential(previousPath)) previous.nativeProfile = { env: harness.profileEnv, path: previousPath };
1841
+ }
1842
+ await writeState(state);
1843
+ }
1844
+ await loginNativeHarness(harness, profileEnvironment(harness, { nativeProfile }));
1845
+ if (captureCredential && profilePath && !await captureCredential(profilePath)) {
1846
+ throw new Error(`${harness.displayName} login completed, but ClikCode could not save its API key into this account\u2019s isolated profile. The account was not added.`);
1847
+ }
1848
+ if (profilePath && harness.authFiles?.length && !captureCredential && !Object.keys(readProfileKey(profilePath)).length && !await authFilePresent(harness, profileEnvironment(harness, { nativeProfile }))) {
1849
+ throw new Error(`${harness.displayName}'s sign-in ended without signing in, so no account was added. Run it again and finish the sign-in.`);
1850
+ }
1851
+ const derived = await deriveAccountLabel(harness, profilePath);
1852
+ const keyed = Object.keys(readProfileKey(profilePath)).length > 0;
1853
+ if (derived) {
1854
+ const existingMatch = keyed ? void 0 : await matchingVendorAccount(state.accounts, harness, derived);
1855
+ if (existingMatch) {
1856
+ existingMatch.label = nameAccount(state.accounts, harness, derived, existingMatch.id);
1857
+ existingMatch.status = "ready";
1858
+ existingMatch.signedInAt = (/* @__PURE__ */ new Date()).toISOString();
1859
+ delete existingMatch.neverSignedIn;
1860
+ const left = await settleReauthenticatedProfile(harness, existingMatch, nativeProfile, state);
1861
+ if (left) touched.add(left);
1862
+ existingMatch.verification = void 0;
1863
+ forgetOldCredential(existingMatch);
1864
+ await writeState(state);
1865
+ emitHarnessOutput({ status: "connected", harness: harness.command, account: existingMatch.label, credentialBoundary: "local-only" });
1866
+ return existingMatch.label;
1867
+ }
1868
+ accountLabel = nameAccount(state.accounts, harness, derived);
1869
+ } else {
1870
+ const same = state.accounts.filter((account) => account.provider === harness.provider && account.authKind === "vendor-cli");
1871
+ const named = explicit ? same.find((account) => account.label.toLowerCase() === explicit.toLowerCase()) : void 0;
1872
+ const onlyOne = !explicit && same.length === 1 && (same[0].status === "needs_login" || same[0].verification) ? same[0] : void 0;
1873
+ const again = named ?? onlyOne;
1874
+ if (again) {
1875
+ again.status = "ready";
1876
+ again.signedInAt = (/* @__PURE__ */ new Date()).toISOString();
1877
+ delete again.neverSignedIn;
1878
+ const left = await settleReauthenticatedProfile(harness, again, nativeProfile, state);
1879
+ if (left) touched.add(left);
1880
+ again.verification = void 0;
1881
+ forgetOldCredential(again);
1882
+ await writeState(state);
1883
+ emitHarnessOutput({ status: "connected", harness: harness.command, account: again.label, credentialBoundary: "local-only" });
1884
+ return again.label;
1885
+ }
1886
+ accountLabel = nameAccount(state.accounts, harness, accountLabel);
1887
+ }
1888
+ const created = { id: accountId, provider: harness.provider, label: accountLabel, authKind: "vendor-cli", models: [], status: "ready", credentialRef: `native:${harness.binary}`, ...nativeProfile ? { nativeProfile } : {} };
1889
+ state.accounts.push(created);
1890
+ await writeState(state);
1891
+ emitHarnessOutput({ status: "connected", harness: harness.command, account: accountLabel, credentialBoundary: "local-only" });
1892
+ return accountLabel;
1893
+ }
1894
+ async function withSignIn(prompter, name, work) {
1895
+ const screen = prompter?.signInScreen?.(name);
1896
+ if (!screen) return work();
1897
+ try {
1898
+ const result = await withSignInScreen(screen, work);
1899
+ screen.stop();
1900
+ return result;
1901
+ } catch (error) {
1902
+ screen.stop();
1903
+ const cancelled = screen.signal.aborted || error instanceof SignInCancelled;
1904
+ if (!cancelled) prompter?.activity?.(`${source_default.yellow(`sign-in to ${name} did not finish`)}${error instanceof Error && error.message ? source_default.dim(` \xB7 ${error.message.split("\n")[0]}`) : ""}`);
1905
+ throw Object.assign(error instanceof Error ? error : new Error(String(error)), {
1906
+ [SIGN_IN_SAID]: cancelled ? "cancelled" : "failed",
1907
+ ...cancelled ? { [SIGN_IN_CANCELLED_LINE]: `Sign-in to ${name} cancelled` } : {}
1908
+ });
1909
+ }
1910
+ }
1911
+ var SIGN_IN_SAID = /* @__PURE__ */ Symbol("sign-in outcome said");
1912
+ var SIGN_IN_CANCELLED_LINE = /* @__PURE__ */ Symbol("sign-in cancelled line");
1913
+ function signInCancelledLine(error) {
1914
+ for (let at = error, depth = 0; at && depth < 5; at = at.cause, depth += 1) {
1915
+ const line = at[SIGN_IN_CANCELLED_LINE];
1916
+ if (line) return line;
1917
+ }
1918
+ return void 0;
1919
+ }
1920
+ function signInOutcomeSaid(error) {
1921
+ return error?.[SIGN_IN_SAID];
1922
+ }
1923
+ function nativeAccountContext(state, labelOrId) {
1924
+ const account = state.accounts.find((item) => item.id === labelOrId || item.label.toLowerCase() === labelOrId.toLowerCase());
1925
+ if (!account) throw new Error(`No account named "${labelOrId}"`);
1926
+ if (account.authKind !== "vendor-cli") throw new Error(`account "${account.label}" is not owned by a vendor CLI`);
1927
+ const harness = localHarnessForProvider(account.provider);
1928
+ if (!harness) throw new Error(`no native harness is registered for provider ${account.provider}`);
1929
+ const environment = profileEnvironment(harness, account);
1930
+ return { account, harness, environment };
1931
+ }
1932
+ async function aiAccountStatus(labelOrId) {
1933
+ const state = await readState({ transcripts: [] });
1934
+ const { account, harness, environment } = nativeAccountContext(state, labelOrId);
1935
+ if (!harness.statusArgv && !hasAuthEvidence(harness)) throw new Error(`${harness.displayName} does not publish a non-destructive account-status command`);
1936
+ let nativeStatus;
1937
+ if (hasAuthEvidence(harness) && !await authEvidencePresent(harness, environment)) {
1938
+ nativeStatus = "not signed in";
1939
+ } else if (harness.statusArgv) {
1940
+ try {
1941
+ nativeStatus = (await vendorCommandText({ gate: harness, argv: harness.statusArgv, environment, deadlineMs: PROBE_DEADLINE_MS })).trim();
1942
+ } catch (error) {
1943
+ nativeStatus = (error instanceof Error ? error.message : String(error)).trim();
1944
+ }
1945
+ } else {
1946
+ nativeStatus = "signed in";
1947
+ }
1948
+ const signedIn = nativeStatusSignedIn(nativeStatus);
1949
+ if (signedIn !== void 0) {
1950
+ account.status = signedIn ? "ready" : "needs_login";
1951
+ if (signedIn) {
1952
+ account.signedInAt ??= (/* @__PURE__ */ new Date()).toISOString();
1953
+ delete account.neverSignedIn;
1954
+ const email = statusEmail(nativeStatus);
1955
+ if (email) account.label = nameAccount(state.accounts, harness, email, account.id);
1956
+ } else {
1957
+ delete account.signedInAt;
1958
+ delete account.neverSignedIn;
1959
+ }
1960
+ await writeState(state);
1961
+ }
1962
+ const usage = await accountUsageLabel(account, state, { network: true });
1963
+ emitResult({ account: { ...accountView(account), usage }, nativeStatus, credentialBoundary: "local-only" });
1964
+ }
1965
+ function nativeStatusSignedIn(nativeStatus) {
1966
+ try {
1967
+ const parsed = JSON.parse(nativeStatus);
1968
+ if (parsed.loggedIn === true || parsed.isAuthenticated === true) return true;
1969
+ if (parsed.loggedIn === false || parsed.isAuthenticated === false) return false;
1970
+ if (typeof parsed.planName === "string" || "amountRemaining" in parsed) return true;
1971
+ } catch {
1972
+ }
1973
+ const normalized = nativeStatus.toLowerCase();
1974
+ if (/\b(not(?: currently)? logged in|not signed in|signed out|logged out|unauthenticated|login required)\b/.test(normalized)) return false;
1975
+ if (/\b(logged in|signed in|authenticated)\b/.test(normalized)) return true;
1976
+ return void 0;
1977
+ }
1978
+ function statusEmail(nativeStatus) {
1979
+ try {
1980
+ const parsed = JSON.parse(nativeStatus);
1981
+ const email = parsed.userInfo?.email ?? parsed.email;
1982
+ return typeof email === "string" && email.includes("@") ? email.trim() : void 0;
1983
+ } catch {
1984
+ return void 0;
1985
+ }
1986
+ }
1987
+ async function aiAccountLogout(labelOrId) {
1988
+ const account = await signOutAccount(labelOrId);
1989
+ emitResult({ account: accountView(account), loggedOut: true, credentialBoundary: "local-only" });
1990
+ }
1991
+ async function signOutAccount(labelOrId) {
1992
+ const state = await readState({ transcripts: [] });
1993
+ const { account, harness, environment } = nativeAccountContext(state, labelOrId);
1994
+ if (!harnessCanLogout(harness)) throw new Error(`${harness.displayName} has no way to sign out from outside its own session.`);
1995
+ await logoutNativeHarness(harness, environment);
1996
+ account.status = "needs_login";
1997
+ delete account.signedInAt;
1998
+ delete account.neverSignedIn;
1999
+ await writeState(state);
2000
+ return account;
2001
+ }
2002
+ async function harnessNeedsLogin(harness, environment) {
2003
+ if (keyVariables(harness).some((name) => environment[name]?.trim())) return false;
2004
+ if (!hasAuthEvidence(harness)) return false;
2005
+ return !await authEvidencePresent(harness, environment);
2006
+ }
2007
+ function requireAuthKind(value) {
2008
+ if (value === "oauth" || value === "api-key" || value === "vendor-cli") return value;
2009
+ throw new Error("auth kind must be oauth, api-key, or vendor-cli");
2010
+ }
2011
+ async function aiAccountAdd(options) {
2012
+ const provider = options.provider.trim();
2013
+ const given = options.label?.trim() ?? "";
2014
+ const credentialRef = options.credentialRef.trim();
2015
+ if (!provider || options.label !== void 0 && !given || !credentialRef) throw new Error("provider, label, and local credential reference are required");
2016
+ const auth = requireAuthKind(options.auth);
2017
+ if (auth === "oauth") {
2018
+ throw new Error("OAuth accounts must be created through the harness\u2019s own sign-in flow; manual OAuth credential references are not supported.");
2019
+ }
2020
+ if (auth === "api-key" && !/^env:[A-Z][A-Z0-9_]*$/.test(credentialRef)) {
2021
+ throw new Error("API-key accounts require an env:VARIABLE credential reference; raw provider keys are never stored");
2022
+ }
2023
+ if (auth !== "api-key" && !/^(?:keychain|native):[^\s]+$/.test(credentialRef)) {
2024
+ throw new Error(`${auth} accounts require a keychain: or native: credential reference; raw credentials are never stored`);
2025
+ }
2026
+ const harness = localHarnessForProvider(provider);
2027
+ if (harness && !harness.localAuth.includes(auth)) throw new Error(`${harness.displayName} does not support local ${auth} accounts`);
2028
+ const state = await readState({ transcripts: [] });
2029
+ if (given && state.accounts.some((account2) => account2.label.toLowerCase() === given.toLowerCase())) {
2030
+ throw new Error(`An account named "${given}" already exists`);
2031
+ }
2032
+ if (state.accounts.some((account2) => account2.provider === provider && account2.authKind === auth && account2.credentialRef === credentialRef)) {
2033
+ throw new Error(`this ${provider} credential is already connected`);
2034
+ }
2035
+ let label = given;
2036
+ if (!label) {
2037
+ const envName = auth === "api-key" ? credentialRef.slice("env:".length) : void 0;
2038
+ const identity = envName ? await apiKeyAccountEmail({ provider, envName, key: process.env[envName], harness }) : void 0;
2039
+ const everyone = state.accounts.map((account2) => ({ ...account2, provider }));
2040
+ const naming = { provider, displayName: harness?.displayName ?? provider };
2041
+ label = identity ? nameAccount(everyone, naming, identity) : options.placeholder && !everyone.some((account2) => account2.label.toLowerCase() === options.placeholder.toLowerCase()) ? options.placeholder : nameAccount(everyone, naming);
2042
+ }
2043
+ const account = {
2044
+ id: randomUUID(),
2045
+ provider,
2046
+ label,
2047
+ authKind: auth,
2048
+ models: [...new Set(options.model ?? [])],
2049
+ status: "ready",
2050
+ credentialRef
2051
+ };
2052
+ state.accounts.push(account);
2053
+ await writeState(state);
2054
+ emitResult({ account: accountView(account), credentialBoundary: "local-only" });
2055
+ return label;
2056
+ }
2057
+ async function aiAccountRemove(labelOrId, options = {}) {
2058
+ const state = await readState({ transcripts: [] });
2059
+ const index = state.accounts.findIndex((account) => account.id === labelOrId || account.label === labelOrId);
2060
+ if (index < 0) throw new Error(`No account named "${labelOrId}"`);
2061
+ const [removed] = state.accounts.splice(index, 1);
2062
+ const isolated = Boolean(removed.nativeProfile?.path) && "path" in await resolvePurgeableProfile(removed.nativeProfile.path);
2063
+ let loggedOut = false;
2064
+ if (removed.authKind === "vendor-cli" && (options.logout ?? isolated)) {
2065
+ let harness;
2066
+ try {
2067
+ harness = localHarnessForProvider(removed.provider);
2068
+ } catch {
2069
+ harness = void 0;
2070
+ }
2071
+ if (harness && harnessCanLogout(harness)) {
2072
+ loggedOut = await logoutNativeHarness(harness, profileEnvironment(harness, removed)).then(() => true, () => false);
2073
+ }
2074
+ }
2075
+ state.sessions = state.sessions.map((session) => session.accountId === removed.id ? { ...session, accountId: null } : session);
2076
+ await writeState(state);
2077
+ const purged = await purgeAccountProfile(removed, state.accounts).catch(quiet("commands/account"));
2078
+ emitHarnessOutput({ panel: "account-removed", account: removed.label, loggedOut, ...purged ? { profileRemoved: purged } : {} });
2079
+ }
2080
+
2081
+ export {
2082
+ isKeyShaped,
2083
+ SignInCancelled,
2084
+ loginNativeHarness,
2085
+ accountView,
2086
+ nativeUsageReading,
2087
+ accountUsageLabel,
2088
+ accountUsageReading,
2089
+ cachedAccountUsageLabel,
2090
+ recheckRecoveredAccounts,
2091
+ setEmitHarnessOutput,
2092
+ accountSignedOutOnDisk,
2093
+ aiAccountsList,
2094
+ aiAccountProviders,
2095
+ versionFromOutput,
2096
+ aiDoctor,
2097
+ syncAccountIdentityAfterLogin,
2098
+ aiAccountLogin,
2099
+ withSignIn,
2100
+ signInCancelledLine,
2101
+ signInOutcomeSaid,
2102
+ aiAccountStatus,
2103
+ nativeStatusSignedIn,
2104
+ statusEmail,
2105
+ aiAccountLogout,
2106
+ signOutAccount,
2107
+ harnessNeedsLogin,
2108
+ aiAccountAdd,
2109
+ aiAccountRemove
2110
+ };