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,1291 @@
1
+ import { createRequire as __clikcodeCreateRequire } from 'node:module';
2
+ const require = __clikcodeCreateRequire(import.meta.url);
3
+ import {
4
+ renderActivityLine
5
+ } from "./chunk-BTJDSTQP.js";
6
+ import {
7
+ closePersistentTransport,
8
+ countsOf,
9
+ hasHeldVendorProcess,
10
+ heldVendorOwner,
11
+ openStandby,
12
+ persistentTransportFor,
13
+ releaseHeldVendorProcess,
14
+ reportEndedWork,
15
+ retireHeldVendorProcess,
16
+ retiredWorkChanged,
17
+ runAcpTurn,
18
+ runCodexAppServerTurn,
19
+ stopReasonNotice,
20
+ turnShareOf,
21
+ vendorChildKey,
22
+ waitForHeldVendorSubagents
23
+ } from "./chunk-TVT45XNH.js";
24
+ import {
25
+ codexRateLimitsReading,
26
+ recordDerivedUsage
27
+ } from "./chunk-N3SFDYM7.js";
28
+ import {
29
+ isTurnCancelled
30
+ } from "./chunk-4LPDG57B.js";
31
+ import {
32
+ locateNativeSessionFile,
33
+ nativeSessionRoot,
34
+ nativeSessionStore,
35
+ placeArtifact
36
+ } from "./chunk-M3FO5UMK.js";
37
+ import {
38
+ recordLiveModelCatalog
39
+ } from "./chunk-QQRLPY25.js";
40
+ import {
41
+ modelsDevFiles
42
+ } from "./chunk-QJP7EYGL.js";
43
+ import {
44
+ nativeAccountEnvironment
45
+ } from "./chunk-ZGX3ERAT.js";
46
+ import {
47
+ COMPACTED,
48
+ compactAt
49
+ } from "./chunk-MXS6S2PY.js";
50
+ import {
51
+ forgetNativeThread,
52
+ optionIdsForControl
53
+ } from "./chunk-TWCVV2JO.js";
54
+ import {
55
+ FAILOVER_PREAMBLE,
56
+ canonicalRecord,
57
+ escapeFailoverContent,
58
+ withoutRecapLine
59
+ } from "./chunk-FF7ZVYJF.js";
60
+ import {
61
+ normalizeActivityEvent
62
+ } from "./chunk-3B2CHX7M.js";
63
+ import {
64
+ harnessAcpLaunch,
65
+ harnessPreferredTransport,
66
+ harnessSupportsPermissionMode,
67
+ homeRedirectEnvironment,
68
+ localHarnessCapabilityManifest,
69
+ localHarnessForCommand,
70
+ maxPromptArgvBytes,
71
+ modelProvider,
72
+ promptExceedsArgvLimit
73
+ } from "./chunk-KYUHIFP3.js";
74
+ import {
75
+ clearNativeHarnessInspectionCache,
76
+ expandAuthPath,
77
+ inspectNativeHarness,
78
+ refreshAcpAgent
79
+ } from "./chunk-DF35KMXM.js";
80
+ import {
81
+ markTurn
82
+ } from "./chunk-4NN3XQQT.js";
83
+ import {
84
+ asRecord
85
+ } from "./chunk-XIBYREEY.js";
86
+ import {
87
+ isJsonDefaultMode
88
+ } from "./chunk-5B6TVO4A.js";
89
+ import {
90
+ source_default
91
+ } from "./chunk-LVRRWP4W.js";
92
+ import {
93
+ diagnostic,
94
+ lifecycle,
95
+ quiet
96
+ } from "./chunk-RDDWQBEM.js";
97
+ import {
98
+ stateDirectory
99
+ } from "./chunk-MPAJ446F.js";
100
+
101
+ // src/turn/turn-environment.ts
102
+ import { homedir } from "node:os";
103
+ import { existsSync, lstatSync, mkdirSync, readdirSync, renameSync, symlinkSync } from "node:fs";
104
+ import { dirname, join } from "node:path";
105
+ function turnEnvironment(harness, account, permissionMode) {
106
+ const environment = homeRedirectEnvironment(harness, nativeAccountEnvironment(harness, account), { home: homedir(), exists: existsSync });
107
+ if (environment.HOME && environment.HOME !== homedir()) linkUserDirectories(environment.HOME, homedir());
108
+ const permission = permissionMode ? harness.permissionEnv?.[permissionMode] : void 0;
109
+ const turn = permissionMode ? harness.turnEnv : void 0;
110
+ const session = permissionMode ? { CLIKDEPLOY_PERMISSION_MODE: permissionMode } : {};
111
+ return { ...environment, ...turn ?? {}, ...permission ?? {}, ...session };
112
+ }
113
+ var linked = /* @__PURE__ */ new Set();
114
+ function freeName(path) {
115
+ return lstatSync(path, { throwIfNoEntry: false }) ? `${path}-${Date.now()}` : path;
116
+ }
117
+ var USER_TOOL_DIRECTORIES = [".clikdeploy", ".clikcode", ".config/clikdeploy"];
118
+ function linkUserDirectories(profileHome, realHome) {
119
+ if (linked.has(profileHome)) return;
120
+ if (!existsSync(profileHome)) return;
121
+ let entries;
122
+ try {
123
+ entries = readdirSync(realHome);
124
+ } catch {
125
+ return;
126
+ }
127
+ let failed = false;
128
+ for (const name of entries) {
129
+ if (name.startsWith(".")) continue;
130
+ const real = join(realHome, name);
131
+ try {
132
+ if (!lstatSync(real).isDirectory()) continue;
133
+ if (lstatSync(join(profileHome, name), { throwIfNoEntry: false })) continue;
134
+ symlinkSync(real, join(profileHome, name));
135
+ } catch {
136
+ failed = true;
137
+ }
138
+ }
139
+ for (const name of USER_TOOL_DIRECTORIES) {
140
+ const real = join(realHome, name);
141
+ const mine = join(profileHome, name);
142
+ try {
143
+ if (!lstatSync(real, { throwIfNoEntry: false })?.isDirectory()) continue;
144
+ const have = lstatSync(mine, { throwIfNoEntry: false });
145
+ if (have?.isSymbolicLink()) continue;
146
+ mkdirSync(dirname(mine), { recursive: true });
147
+ if (have) renameSync(mine, freeName(`${mine}.before-link`));
148
+ symlinkSync(real, mine);
149
+ } catch {
150
+ failed = true;
151
+ }
152
+ }
153
+ if (!failed) linked.add(profileHome);
154
+ }
155
+
156
+ // src/session/carry.ts
157
+ import { join as join2, relative } from "node:path";
158
+ function sharesVendorProfile(harness, from, to) {
159
+ const key = harness.profileEnv;
160
+ const read = (env, name) => env[name];
161
+ if (key) return read(from, key) === read(to, key);
162
+ const names = /* @__PURE__ */ new Set([...Object.keys(from), ...Object.keys(to)]);
163
+ for (const name of names) {
164
+ if (!/HOME$|_DIR$|_CONFIG/i.test(name)) continue;
165
+ if (read(from, name) !== read(to, name)) return false;
166
+ }
167
+ return true;
168
+ }
169
+ async function moveThreadToAccount(session, harness, from, to) {
170
+ const carried = harness && from ? await carryNativeSession({
171
+ harness,
172
+ nativeId: session.nativeSessionPreallocated ? void 0 : session.nativeSessionId,
173
+ workspace: session.workspace,
174
+ from: turnEnvironment(harness, from),
175
+ to: turnEnvironment(harness, to)
176
+ }).catch(quiet("session/carry")) : void 0;
177
+ if (carried) session.nativeThreadAccountId = to.id;
178
+ else forgetNativeThread(session);
179
+ return carried;
180
+ }
181
+ var hasVendorThread = (session) => Boolean(session.nativeSessionId) && !session.nativeSessionPreallocated;
182
+ async function reconcileNativeThread(session, harness, accounts, to) {
183
+ if (!harness || !hasVendorThread(session)) return "none";
184
+ if (session.nativeThreadAccountId === to.id) return "present";
185
+ const holder = session.nativeThreadAccountId ? accounts.find((item) => item.id === session.nativeThreadAccountId) : void 0;
186
+ const sources = holder ? [holder] : accounts.filter((item) => item.id !== to.id && item.provider === to.provider && item.authKind === "vendor-cli");
187
+ for (const from of sources) {
188
+ const carried = await carryNativeSession({
189
+ harness,
190
+ nativeId: session.nativeSessionId,
191
+ workspace: session.workspace,
192
+ from: turnEnvironment(harness, from),
193
+ to: turnEnvironment(harness, to)
194
+ }).catch(quiet("session/carry"));
195
+ if (carried) {
196
+ session.nativeThreadAccountId = to.id;
197
+ return carried;
198
+ }
199
+ }
200
+ if (!holder) {
201
+ const here = await locateNativeSessionFile(harness, session.nativeSessionId, session.workspace ?? "", turnEnvironment(harness, to)).catch(quiet("session/carry"));
202
+ if (here || !nativeSessionStore(harness)?.locate) {
203
+ session.nativeThreadAccountId = to.id;
204
+ return "present";
205
+ }
206
+ }
207
+ forgetNativeThread(session);
208
+ return "forgotten";
209
+ }
210
+ async function carryNativeSession(input) {
211
+ const { harness, nativeId, workspace } = input;
212
+ if (!nativeId) return void 0;
213
+ if (sharesVendorProfile(harness, input.from, input.to)) return "present";
214
+ if (!workspace) return void 0;
215
+ const target = nativeSessionRoot(harness, input.to);
216
+ if (!target) return void 0;
217
+ if (target === nativeSessionRoot(harness, input.from)) return "present";
218
+ const store = nativeSessionStore(harness);
219
+ if (store?.carry) {
220
+ const carried = await store.carry({ nativeId, workspace, from: input.from, to: input.to }).catch(() => false);
221
+ return carried ? "carried" : void 0;
222
+ }
223
+ const source = await locateNativeSessionFile(harness, nativeId, workspace, input.from);
224
+ if (!source) return void 0;
225
+ const destination = join2(target, relative(source.root, source.path));
226
+ try {
227
+ if (!await placeArtifact(source.path, destination)) return void 0;
228
+ return !store?.reconcile || await store.reconcile({ nativeId, path: destination, environment: input.to }).catch(() => false) ? "carried" : void 0;
229
+ } catch {
230
+ return void 0;
231
+ }
232
+ }
233
+
234
+ // src/harness/transport/select.ts
235
+ function harnessTurnTransport(harness) {
236
+ return harnessPreferredTransport(harness);
237
+ }
238
+ function sessionTurnTransport(harness, session) {
239
+ const pinnedSharedFallback = Boolean(harness.acp?.pinCliFallback && (session.nativeTransport === "structured-cli" || session.nativeTransport === "text-cli"));
240
+ if (session.nativeSessionId && !session.nativeSessionPreallocated && (!harness.acp?.sharedSessions || harness.acp.pinCliFallback) || pinnedSharedFallback) {
241
+ if (session.nativeTransport === "acp" && harness.acp) return "acp";
242
+ if ((session.nativeTransport === "structured-cli" || session.nativeTransport === "text-cli") && harness.turn) return session.nativeTransport;
243
+ }
244
+ return harnessTurnTransport(harness);
245
+ }
246
+ function cliThreadTransport(harness) {
247
+ if (!harness.acp || harness.acp.sharedSessions || !harness.turn) return void 0;
248
+ return harness.turn.output === "text" ? "text-cli" : "structured-cli";
249
+ }
250
+
251
+ // src/turn/turn-output.ts
252
+ import { randomUUID } from "node:crypto";
253
+ import { stdout as output } from "node:process";
254
+ function recordInvocation(state, turn) {
255
+ const { usage } = turn;
256
+ const invocation = {
257
+ id: randomUUID(),
258
+ sessionId: turn.sessionId,
259
+ accountId: turn.accountId,
260
+ provider: turn.provider,
261
+ ...turn.kind ? { kind: turn.kind } : {},
262
+ ...turn.model ? { model: turn.model } : {},
263
+ at: (/* @__PURE__ */ new Date()).toISOString(),
264
+ latencyMs: Date.now() - turn.startedAt,
265
+ ...usage?.input !== void 0 ? { inputTokens: usage.input } : {},
266
+ ...usage?.output !== void 0 ? { outputTokens: usage.output } : {},
267
+ ...usage?.cacheRead !== void 0 ? { cacheReadTokens: usage.cacheRead } : {},
268
+ ...usage?.cacheWrite !== void 0 ? { cacheWriteTokens: usage.cacheWrite } : {},
269
+ ...usage?.totalTokens !== void 0 ? { totalTokens: usage.totalTokens } : {},
270
+ ...usage?.costUsd !== void 0 ? { costUsd: usage.costUsd } : {},
271
+ ...usage?.costBreakdown ? { costBreakdown: usage.costBreakdown } : {},
272
+ ...usage?.credits !== void 0 ? { credits: usage.credits } : {},
273
+ ...turn.contextProfile ? { contextProfile: turn.contextProfile } : {},
274
+ ...turn.stopReason ? { stopReason: turn.stopReason } : {}
275
+ };
276
+ state.invocations.push(invocation);
277
+ return invocation;
278
+ }
279
+ function recordUnfinishedInvocation(state, turn, ended) {
280
+ const usage = turn.usage;
281
+ const spent = usage && ["input", "output", "cacheRead", "cacheWrite", "reasoning", "totalTokens", "costUsd", "credits"].some((key) => (usage[key] ?? 0) > 0);
282
+ if (!spent) return void 0;
283
+ return recordInvocation(state, { ...turn, usage: { ...usage, stopReason: ended === "stopped" ? "stopped" : "failed" }, stopReason: ended });
284
+ }
285
+ function showStopReason(prompter, reason) {
286
+ const stopped = stopReasonNotice(reason);
287
+ if (!stopped) return;
288
+ if (prompter) prompter.activity(source_default.yellow(stopped));
289
+ else diagnostic("turn.stop-reason", stopped);
290
+ }
291
+ function showActivity(prompter, event) {
292
+ if (prompter) prompter.activityEvent(event);
293
+ else if (!isJsonDefaultMode()) for (const activity of renderActivityLine(event)) output.write(`${activity}
294
+ `);
295
+ }
296
+ function turnSink(checkpoint, prompter, options = {}) {
297
+ let shown = "";
298
+ return {
299
+ response(text, mode = "append") {
300
+ if (!text || options.keep && !options.keep(text, mode)) return;
301
+ const whole = mode === "replace" ? text : `${shown}${text}`;
302
+ const clean = withoutRecapLine(whole);
303
+ shown = clean;
304
+ if (clean !== whole) {
305
+ markTurn("first-event");
306
+ checkpoint.response(text, mode);
307
+ prompter?.response(clean, "replace");
308
+ return;
309
+ }
310
+ markTurn("first-event");
311
+ if (text.trim()) markTurn("first-text");
312
+ checkpoint.response(text, mode);
313
+ prompter?.response(text, mode);
314
+ },
315
+ activity(raw) {
316
+ const event = normalizeActivityEvent(raw);
317
+ markTurn("first-event");
318
+ checkpoint.activity(event);
319
+ showActivity(prompter, event);
320
+ }
321
+ };
322
+ }
323
+
324
+ // src/turn/turn-steps.ts
325
+ function unfinishedUsageRecorder(state, checkpoint, attempt) {
326
+ return (ended) => {
327
+ const turn = attempt();
328
+ if (turn && recordUnfinishedInvocation(state, turn, ended)) checkpoint?.touch();
329
+ };
330
+ }
331
+ function setPlanMode(session, checkpoint, prompter, on, alsoOnExit) {
332
+ if (on) session.planMode = true;
333
+ else {
334
+ delete session.planMode;
335
+ alsoOnExit?.();
336
+ }
337
+ checkpoint?.touch();
338
+ prompter?.render(session);
339
+ }
340
+ async function settleHeldVendor(sessionId, prompter, signal, options = {}) {
341
+ if (!hasHeldVendorProcess(sessionId)) return;
342
+ const owner = heldVendorOwner(sessionId);
343
+ const leaving = Boolean(options.failed || options.to && owner && (owner.harness !== options.to.harness || owner.accountId !== options.to.accountId));
344
+ if (leaving) {
345
+ const from = options.from ?? owner ?? {};
346
+ const retired = retireHeldVendorProcess(sessionId, (ended) => {
347
+ reportEndedWork(sessionId, ended, { ...from, retired: true });
348
+ retiredWorkChanged(sessionId);
349
+ });
350
+ if (retired) {
351
+ retiredWorkChanged(sessionId);
352
+ return;
353
+ }
354
+ }
355
+ if (!options.failed) {
356
+ prompter?.phase("waiting for running work");
357
+ await waitForHeldVendorSubagents(sessionId, signal);
358
+ }
359
+ await releaseHeldVendorProcess(sessionId);
360
+ }
361
+
362
+ // src/harness/transport/options.ts
363
+ var NORMALIZED_IDS = /* @__PURE__ */ new Set(["model", "workspace", "effort", "permissions"]);
364
+ function renderedItems(option, raw) {
365
+ const items = (Array.isArray(raw) ? raw : [raw]).map((item) => String(item ?? "").trim()).filter(Boolean);
366
+ for (const item of items) {
367
+ if (option.values?.length && !option.values.includes(item)) throw new Error(`${option.label} must be one of ${option.values.join(", ")}`);
368
+ }
369
+ return items;
370
+ }
371
+ function declaredOptionArgv(options, values, resumed = false) {
372
+ if (!values) return [];
373
+ const declared = new Map(options.map((option) => [option.id, option]));
374
+ const argv = [];
375
+ for (const [id, raw] of Object.entries(values)) {
376
+ const option = declared.get(id);
377
+ if (!option?.argv || NORMALIZED_IDS.has(id)) continue;
378
+ if (option.appliesTo === "start" && resumed) continue;
379
+ if (option.appliesTo === "resume" && !resumed) continue;
380
+ if (option.kind === "boolean") {
381
+ if (raw === true) argv.push(...option.argv);
382
+ continue;
383
+ }
384
+ const items = renderedItems(option, raw);
385
+ if (option.argvStyle === "csv") {
386
+ if (items.length) argv.push(...option.argv, items.join(","));
387
+ continue;
388
+ }
389
+ for (const item of items) argv.push(...option.argv, item);
390
+ }
391
+ return argv;
392
+ }
393
+ function parseConfigValue(text) {
394
+ try {
395
+ return JSON.parse(text);
396
+ } catch {
397
+ return text;
398
+ }
399
+ }
400
+ function appServerThreadOverrides(options, values) {
401
+ const config = {};
402
+ const unmapped = [];
403
+ const declared = new Map(options.map((option) => [option.id, option]));
404
+ for (const [id, raw] of Object.entries(values ?? {})) {
405
+ const option = declared.get(id);
406
+ if (!option || NORMALIZED_IDS.has(id) || raw === false || raw === void 0 || raw === null || raw === "") continue;
407
+ const argv = option.argv ?? [];
408
+ const inlineConfig = argv.length === 2 && argv[0] === "--config" && argv[1].includes("=");
409
+ if (inlineConfig && raw === true) {
410
+ const [key, ...rest] = argv[1].split("=");
411
+ config[key] = parseConfigValue(rest.join("="));
412
+ } else if (id === "profile") config.profile = renderedItems(option, raw)[0];
413
+ else if (id === "search" && raw === true) config["tools.web_search"] = true;
414
+ else if (id === "add-dir") config["sandbox_workspace_write.writable_roots"] = renderedItems(option, raw);
415
+ else if (id === "oss" && raw === true) config.model_provider = "oss";
416
+ else if (id === "local-provider") config.oss_provider = renderedItems(option, raw)[0];
417
+ else unmapped.push(id);
418
+ }
419
+ return { ...Object.keys(config).length ? { configOverrides: config } : {}, unmapped };
420
+ }
421
+
422
+ // src/harness/transport/acp-usage-file.ts
423
+ import { readFile } from "node:fs/promises";
424
+ async function readAcpUsageFile(declaration, sessionId, environment) {
425
+ if (!/^[A-Za-z0-9_.-]+$/.test(sessionId) || sessionId.startsWith(".")) return void 0;
426
+ const path = expandAuthPath(declaration.path.replaceAll("{id}", sessionId), { ...process.env, ...environment });
427
+ let value;
428
+ try {
429
+ value = JSON.parse(await readFile(path, "utf8"));
430
+ } catch {
431
+ return void 0;
432
+ }
433
+ for (const key of declaration.field) value = asRecord(value)?.[key];
434
+ const usage = asRecord(value);
435
+ if (!usage) return void 0;
436
+ const totals = countsOf(usage);
437
+ const cost = [usage.totalCost, usage.cost].find((candidate) => typeof candidate === "number" && Number.isFinite(candidate));
438
+ if (cost !== void 0) totals.costUsd = cost;
439
+ return Object.keys(totals).length ? totals : void 0;
440
+ }
441
+
442
+ // src/turn/turn-permission.ts
443
+ function turnPermissionMode(harness, chosen) {
444
+ const mode = chosen ?? "ask";
445
+ if (mode === "bypass" && harness.bypassRefusedAsRoot && !harnessSupportsPermissionMode(harness, "bypass")) {
446
+ return harnessSupportsPermissionMode(harness, "auto") ? "auto" : "ask";
447
+ }
448
+ return mode;
449
+ }
450
+
451
+ // src/turn/vendor-session-attempt.ts
452
+ var ignoredOptionsSaid = /* @__PURE__ */ new Map();
453
+ async function runVendorSessionAttempt(input) {
454
+ const { harness, account, session, transport, turnText, model, environment, images, signal, run, checkpoint, sharedObserver, effort, onSessionId, runCli } = input;
455
+ const prompter = run.prompter;
456
+ let result;
457
+ if (session.nativeSessionPreallocated) {
458
+ session.nativeSessionId = void 0;
459
+ delete session.nativeSessionPreallocated;
460
+ }
461
+ const onSteerReady = (port) => run.liveInput?.setSteerPort(port);
462
+ const persistent = run.persistentTransports ? persistentTransportFor(session.id, transport, vendorChildKey(harness, account, environment, session.workspace)) : void 0;
463
+ try {
464
+ if (transport === "codex-app-server") {
465
+ const launch = codexLaunchInput({ harness, account, session, model, effort, environment, live: run.liveSettings });
466
+ const ignored = launch.unmapped.join(", ");
467
+ if (ignored && ignoredOptionsSaid.get(session.id) !== ignored) {
468
+ ignoredOptionsSaid.set(session.id, ignored);
469
+ diagnostic("vendor.app-server-ignores", `${harness.displayName}: ${ignored}`);
470
+ }
471
+ const codexInput = {
472
+ ...launch.input,
473
+ prompt: turnText,
474
+ images,
475
+ signal,
476
+ onSessionId,
477
+ ...run.compaction ? { compact: true } : {},
478
+ ...sharedObserver,
479
+ onSteerReady
480
+ };
481
+ result = persistent ? await persistent.session.runTurn(codexInput) : await runCodexAppServerTurn(codexInput);
482
+ } else {
483
+ const acpInput = {
484
+ ...acpLaunchInput({ harness, account, session, model, effort, environment, checkpoint, prompter, live: run.liveSettings }),
485
+ prompt: turnText,
486
+ signal,
487
+ images,
488
+ onSessionId,
489
+ ...sharedObserver,
490
+ onSteerReady
491
+ };
492
+ const usageFile = harness.acp?.usageFile;
493
+ const usageBefore = usageFile && session.nativeSessionId ? await readAcpUsageFile(usageFile, session.nativeSessionId, environment) ?? {} : {};
494
+ const runAcp = async () => {
495
+ try {
496
+ return persistent ? await persistent.session.runTurn(acpInput) : await runAcpTurn(acpInput);
497
+ } catch (error) {
498
+ if (!error.acpUnsupportedEffort || !promptExceedsArgvLimit(harness, turnText)) throw error;
499
+ lifecycle("vendor.acp-effort-default", { harness: harness.command, effort: effort ?? null, reason: "prompt past the CLI argv limit" });
500
+ const atDefault = { ...acpInput, effort: void 0 };
501
+ return persistent ? await persistent.session.runTurn(atDefault) : await runAcpTurn(atDefault);
502
+ }
503
+ };
504
+ try {
505
+ try {
506
+ result = await runAcp();
507
+ } finally {
508
+ await run.liveInput?.settled();
509
+ }
510
+ const usageAfter = usageFile && result.nativeSessionId ? await readAcpUsageFile(usageFile, result.nativeSessionId, environment) : void 0;
511
+ if (usageAfter) sharedObserver.onUsage?.(turnShareOf(usageAfter, usageBefore));
512
+ } catch (error) {
513
+ const unsupported = error;
514
+ if (!(unsupported.acpUnsupportedImages || unsupported.acpUnsupportedModel || unsupported.acpUnsupportedEffort) || !harness.turn) throw error;
515
+ if (unsupported.acpUnsupportedModel && harness.freePlan?.listed && harness.command !== "antigravity") throw Object.assign(unsupported, { errorKind: "model_not_on_plan" });
516
+ const shared = Boolean(harness.acp?.sharedSessions);
517
+ if (session.nativeSessionId && !shared) throw error;
518
+ if (session.planMode && harness.acp?.planModeId) throw error;
519
+ const pinned = cliThreadTransport(harness);
520
+ const fallbackTransport = pinned ?? (harness.acp?.pinCliFallback && harness.turn ? harness.turn.output === "text" ? "text-cli" : "structured-cli" : void 0);
521
+ if (fallbackTransport) {
522
+ session.nativeTransport = fallbackTransport;
523
+ delete session.nativeSessionPreallocated;
524
+ await checkpoint.persistNow();
525
+ }
526
+ lifecycle("vendor.acp-fallback", { harness: harness.command, reason: unsupported.message.slice(0, 300) });
527
+ if (unsupported.acpUnsupportedModel) void refreshAcpAgent(harness).then((fresh) => {
528
+ if (fresh) clearNativeHarnessInspectionCache(harness.command);
529
+ });
530
+ prompter?.phase("using structured CLI fallback");
531
+ try {
532
+ result = await runCli();
533
+ } catch (cliError) {
534
+ if (!session.nativeSessionId && !shared) delete session.nativeTransport;
535
+ throw cliError;
536
+ }
537
+ }
538
+ }
539
+ } catch (error) {
540
+ if (persistent && !isTurnCancelled(error) && !await persistent.session.backgroundWorkRunning()) await closePersistentTransport(session.id);
541
+ throw error;
542
+ }
543
+ return result;
544
+ }
545
+ function acpLaunchInput(input) {
546
+ const { harness, account, session, model, effort, environment, checkpoint, prompter, live } = input;
547
+ const declaredOptions = localHarnessCapabilityManifest(harness).options;
548
+ const launch = harnessAcpLaunch(harness, { model, effort, permissionMode: turnPermissionMode(harness, session.permissionMode) });
549
+ if (!launch) throw new Error(`${harness.displayName} does not declare an ACP launch`);
550
+ const planOption = harness.acp?.planModeId ? harness.planMode : void 0;
551
+ const storedPlan = planOption ? session.harnessOptions?.[planOption.option] : void 0;
552
+ const planStored = storedPlan !== void 0 && storedPlan !== false && storedPlan !== "" && (planOption.value === true || storedPlan === planOption.value);
553
+ const launchOptions = planOption && session.harnessOptions ? Object.fromEntries(Object.entries(session.harnessOptions).filter(([id]) => id !== planOption.option)) : session.harnessOptions;
554
+ const protocolDirectories = harness.acp?.inheritCliOptions === false ? optionIdsForControl("/add-dir") : [];
555
+ const additionalDirectories = protocolDirectories.flatMap((id) => {
556
+ const value = launchOptions?.[id];
557
+ return (Array.isArray(value) ? value : typeof value === "string" && value ? [value] : []).map(String);
558
+ });
559
+ const argvOptions = additionalDirectories.length && launchOptions ? Object.fromEntries(Object.entries(launchOptions).filter(([id]) => !protocolDirectories.includes(id))) : launchOptions;
560
+ const optionArgv = declaredOptionArgv(declaredOptions, argvOptions, Boolean(session.nativeSessionId));
561
+ if (harness.acp?.inheritCliOptions === false && optionArgv.length) {
562
+ throw new Error(`${harness.displayName} ACP does not accept the selected CLI-only options. Clear them before sending.`);
563
+ }
564
+ return {
565
+ binary: launch.binary,
566
+ command: harness.command,
567
+ displayName: harness.displayName,
568
+ argv: launch.modeArgv,
569
+ optionPlacement: launch.optionPlacement,
570
+ extraArgv: [...launch.optionArgv, ...optionArgv],
571
+ ...session.nativeSessionId ? { nativeSessionId: session.nativeSessionId } : {},
572
+ cwd: session.workspace,
573
+ model,
574
+ effort,
575
+ permissionMode: turnPermissionMode(harness, session.permissionMode),
576
+ ...live ? { liveSettings: live } : {},
577
+ ...live ? { currentPermissionMode: async () => live.permissionMode && turnPermissionMode(harness, live.permissionMode) } : {},
578
+ ...additionalDirectories.length ? { additionalDirectories } : {},
579
+ acp: harness.acp,
580
+ // Plan mode as an ACP session mode (catalog acp.planModeId); the
581
+ // agent leaving it -- its plan approved -- turns the chat's off.
582
+ ...(session.planMode || planStored) && harness.acp?.planModeId ? {
583
+ planMode: true,
584
+ onPlanModeExit: () => setPlanMode(session, checkpoint, prompter, false, () => {
585
+ if (planOption && session.harnessOptions) delete session.harnessOptions[planOption.option];
586
+ })
587
+ } : {},
588
+ modelProviderSeparator: harness.modelProviderSeparator,
589
+ // Antigravity's ACP list omits native Claude/GPT models; it is not a plan inventory.
590
+ plansListModels: Boolean(harness.freePlan?.listed && harness.command !== "antigravity"),
591
+ // Claude Code's quota, carried by the turn itself: published like a
592
+ // stream reading, so the composer and the account picker see it.
593
+ onQuotaReading: (reading) => {
594
+ void recordDerivedUsage(session, reading).catch(quiet("turn/vendor-session-attempt"));
595
+ },
596
+ // The models this session offers are the catalog model discovery
597
+ // would otherwise start a second copy of the agent to read.
598
+ onSessionModels: (answer, fresh) => {
599
+ void recordLiveModelCatalog(harness, account, answer, fresh).catch(quiet("turn/vendor-session-attempt"));
600
+ },
601
+ environment: launch.env && Object.keys(launch.env).length ? { ...environment, ...launch.env } : environment,
602
+ // The account's own config is what the agent reads: global servers it already has there are not sent again.
603
+ ...account.nativeProfile ? { mcpProfile: { env: account.nativeProfile.env, path: account.nativeProfile.path } } : {}
604
+ };
605
+ }
606
+ function standbyOf(input, kind, prepare) {
607
+ return openStandby(input.session.id, input.account.id, kind, vendorChildKey(input.harness, input.account, input.environment, input.session.workspace), prepare).ready;
608
+ }
609
+ function prepareAcpStandby(input) {
610
+ const launch = acpLaunchInput(input);
611
+ return standbyOf(input, "acp", async (child) => {
612
+ await child.runTurn({ ...launch, prompt: "", initializeOnly: true });
613
+ });
614
+ }
615
+ async function pingPromptCache(input) {
616
+ const { nativeSessionPreallocated: _fresh, ...rest } = input.session;
617
+ const session = { ...rest, nativeSessionId: input.copyId, permissionMode: "ask" };
618
+ let usage = {};
619
+ await runAcpTurn({
620
+ ...acpLaunchInput({ ...input, session }),
621
+ prompt: "ClikCode keeping this conversation's cache warm, not a request: reply with only the word ok.",
622
+ signal: input.signal,
623
+ onUsage: (reported) => {
624
+ usage = { ...usage, ...reported };
625
+ input.onUsage?.(usage);
626
+ }
627
+ });
628
+ return usage;
629
+ }
630
+ function codexLaunchInput(input) {
631
+ const { harness, account, session, model, effort, environment, live } = input;
632
+ const overrides = appServerThreadOverrides(localHarnessCapabilityManifest(harness).options, session.harnessOptions);
633
+ const configOverrides = { ...overrides.configOverrides ? overrides.configOverrides : {} };
634
+ return {
635
+ unmapped: overrides.unmapped,
636
+ input: {
637
+ binary: harness.binary,
638
+ nativeSessionId: session.nativeSessionId,
639
+ cwd: session.workspace,
640
+ model,
641
+ effort,
642
+ permissionMode: turnPermissionMode(harness, session.permissionMode),
643
+ environment,
644
+ ...live ? { currentPermissionMode: async () => live.permissionMode && turnPermissionMode(harness, live.permissionMode) } : {},
645
+ ...Object.keys(configOverrides).length ? { configOverrides } : {},
646
+ ...overrides.extraThreadParams ? { extraThreadParams: overrides.extraThreadParams } : {},
647
+ // The account's own config is what Codex reads: global servers it already has there are not sent again.
648
+ ...account.nativeProfile ? { mcpProfile: { env: account.nativeProfile.env, path: account.nativeProfile.path } } : {},
649
+ // Codex reports its own quota on this connection during the turn,
650
+ // which is the same figure codexUsageProbe otherwise spawns a whole
651
+ // second app-server to ask for.
652
+ onRateLimits: (rateLimits) => {
653
+ void recordDerivedUsage(session, codexRateLimitsReading(rateLimits)).catch(quiet("turn/vendor-session-attempt"));
654
+ }
655
+ }
656
+ };
657
+ }
658
+ function prepareCodexStandby(input) {
659
+ const launch = codexLaunchInput(input).input;
660
+ return standbyOf(input, "codex-app-server", async (child) => {
661
+ await child.runTurn({ ...launch, prompt: "", initializeOnly: true });
662
+ });
663
+ }
664
+ async function prepareVendorAhead(input) {
665
+ const { harness, account, session, transport, environment } = input;
666
+ const live = persistentTransportFor(session.id, transport, vendorChildKey(harness, account, environment, session.workspace));
667
+ try {
668
+ if (transport === "codex-app-server") await live.session.runTurn({ ...codexLaunchInput(input).input, prompt: "", prepareOnly: true });
669
+ else await live.session.runTurn({ ...acpLaunchInput(input), prompt: "", prepareOnly: true });
670
+ } catch (error) {
671
+ await closePersistentTransport(session.id);
672
+ throw error;
673
+ }
674
+ }
675
+
676
+ // src/session/full-record.ts
677
+ import { mkdir, readFile as readFile2, rename, writeFile } from "node:fs/promises";
678
+ import { dirname as dirname2, join as join3 } from "node:path";
679
+ function fullRecordPath(stateDir, sessionId) {
680
+ return join3(stateDir, "records", `${sessionId}.md`);
681
+ }
682
+ async function writeFullRecord(session, stateDir) {
683
+ try {
684
+ const { transcriptMarkdown } = await import("./chunk-GTOAT5D3.js");
685
+ const path = fullRecordPath(stateDir, session.id);
686
+ await mkdir(join3(stateDir, "records"), { recursive: true, mode: 448 });
687
+ const markdown = transcriptMarkdown(session);
688
+ await setAsideLongerRecord(path, session.id, recordTurns(markdown));
689
+ await writeFile(path, markdown, { encoding: "utf8", mode: 384 });
690
+ return path;
691
+ } catch {
692
+ return void 0;
693
+ }
694
+ }
695
+ function recordTurns(markdown) {
696
+ return (markdown.match(/^## You$/gm) ?? []).length;
697
+ }
698
+ async function setAsideLongerRecord(path, id, turns) {
699
+ const existing = await readFile2(path, "utf8").catch(quiet("session/full-record"));
700
+ if (existing === void 0 || recordTurns(existing) <= turns) return;
701
+ const older = join3(dirname2(path), "older");
702
+ await mkdir(older, { recursive: true, mode: 448 });
703
+ await rename(path, join3(older, `${id}.${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`));
704
+ }
705
+ function fullRecordNote(path) {
706
+ return `The complete conversation, every request and answer, is saved at ${path}. Read or search that file when something is not above.`;
707
+ }
708
+
709
+ // src/agent/ran-note.ts
710
+ var BRIEF_CALLS = 12;
711
+ function ranNote(labels) {
712
+ const unique = [...new Set(labels)];
713
+ return unique.length ? `
714
+
715
+ (ClikCode note, not the user's words: answering this, the assistant ran ${unique.slice(0, BRIEF_CALLS).join("; ")}${unique.length > BRIEF_CALLS ? `; and ${unique.length - BRIEF_CALLS} more` : ""}.)` : "";
716
+ }
717
+ var OLD_CALLS_LINE = /^\[Tool calls: ([\s\S]*?)\](?:\n\n|$)/;
718
+ function callsAsUserNotes(items) {
719
+ const out = [];
720
+ for (const item of items) {
721
+ const match = item.type === "text" && item.role === "assistant" && typeof item.text === "string" ? OLD_CALLS_LINE.exec(item.text) : null;
722
+ const before = out.at(-1);
723
+ if (!match || !before || before.type !== "text" || before.role !== "user" || typeof before.text !== "string") {
724
+ out.push(item);
725
+ continue;
726
+ }
727
+ out[out.length - 1] = { ...before, text: `${before.text}${ranNote([match[1]])}` };
728
+ out.push({ ...item, text: item.text.slice(match[0].length) || "(no reply)" });
729
+ }
730
+ return out;
731
+ }
732
+
733
+ // src/turn/transfer.ts
734
+ import { readFile as readFile3 } from "node:fs/promises";
735
+ var TRANSFER_MIN_BYTES = 48 * 1024;
736
+ var TRANSFER_UNKNOWN_WINDOW_BYTES = 400 * 1024;
737
+ var TRANSFER_MAX_BYTES = 1024 * 1024;
738
+ var TRANSFER_WINDOW_SHARE = 0.5;
739
+ var BYTES_PER_TOKEN = 4;
740
+ var ARGV_HEADROOM_BYTES = 4 * 1024;
741
+ var bytes = (text) => Buffer.byteLength(text, "utf8");
742
+ function transferBudget(input) {
743
+ const byWindow = input.contextWindow && input.contextWindow > 0 ? Math.floor(input.contextWindow * TRANSFER_WINDOW_SHARE * BYTES_PER_TOKEN) : TRANSFER_UNKNOWN_WINDOW_BYTES;
744
+ const fromWindow = input.capTokens && input.capTokens > 0 ? Math.min(byWindow, input.capTokens * BYTES_PER_TOKEN) : byWindow;
745
+ const sized = Math.min(TRANSFER_MAX_BYTES, Math.max(TRANSFER_MIN_BYTES, fromWindow));
746
+ return input.argvLimit ? Math.min(sized, Math.max(8 * 1024, input.argvLimit - ARGV_HEADROOM_BYTES)) : sized;
747
+ }
748
+ async function targetContextWindow(sessions, harness, model, catalogFiles = []) {
749
+ if (!model) return void 0;
750
+ const reported = sessions.filter((session) => session.nativeHarness === harness && (session.model === model || session.reported?.model === model) && (session.lastUsage?.contextWindow ?? 0) > 0).sort((left, right) => Date.parse(right.lastUsage?.at ?? "") - Date.parse(left.lastUsage?.at ?? ""))[0];
751
+ if (reported) return reported.lastUsage.contextWindow;
752
+ const bare = model.replace(/\[.*\]$/, "").split("/").at(-1);
753
+ const plain = bare.replace(/-(?:thinking|minimal|low|medium|high|xhigh|max)$/i, "");
754
+ for (const file of catalogFiles) {
755
+ const text = await readFile3(file, "utf8").catch(() => "");
756
+ if (!text) continue;
757
+ try {
758
+ const catalog = JSON.parse(text);
759
+ for (const provider of Object.values(catalog)) {
760
+ const context = (provider?.models?.[model] ?? provider?.models?.[bare] ?? provider?.models?.[plain])?.limit?.context;
761
+ if (typeof context === "number" && context > 0) return context;
762
+ }
763
+ } catch {
764
+ }
765
+ }
766
+ return void 0;
767
+ }
768
+ function sliceBytes(text, maxBytes, from) {
769
+ const buffer = Buffer.from(text, "utf8");
770
+ if (buffer.length <= maxBytes) return text;
771
+ const part = from === "start" ? buffer.subarray(0, Math.max(0, maxBytes)) : buffer.subarray(buffer.length - Math.max(0, maxBytes));
772
+ return part.toString("utf8").replace(/^�+|�+$/g, "");
773
+ }
774
+ function truncateMiddle(text, maxBytes) {
775
+ const total = bytes(text);
776
+ if (total <= maxBytes) return text;
777
+ const room = Math.max(64, maxBytes - 64);
778
+ const head = sliceBytes(text, Math.ceil(room * 0.6), "start");
779
+ const tail = sliceBytes(text, Math.floor(room * 0.4), "end");
780
+ return `${head}
781
+ [\u2026 ${total - bytes(head) - bytes(tail)} bytes left out \u2026]
782
+ ${tail}`;
783
+ }
784
+ var oneLine = (text) => text.replace(/\s+/g, " ").trim();
785
+ function clipLine(text, max) {
786
+ const flat = oneLine(text);
787
+ return flat.length > max ? `${flat.slice(0, Math.max(1, max - 1))}\u2026` : flat;
788
+ }
789
+ function extractiveSummary(text, maxChars = 400) {
790
+ const prose = text.replace(/```[\s\S]*?(```|$)/g, "\n").trim();
791
+ const sentences = prose.split(/(?<=[.!?])\s+|\n+/).map(oneLine).filter(Boolean);
792
+ if (!sentences.length) return "";
793
+ const half = Math.floor(maxChars / 2) - 4;
794
+ const first = clipLine(sentences[0], sentences.length > 1 ? half : maxChars);
795
+ if (sentences.length === 1) return first;
796
+ const last = clipLine(sentences.at(-1), half);
797
+ return sentences.length === 2 ? `${first} ${last}` : `${first} \u2026 ${last}`;
798
+ }
799
+ function outcome(call) {
800
+ if (call.status === "failed") return call.exitCode !== void 0 ? ` (failed, exit ${call.exitCode})` : " (failed)";
801
+ if (call.status === "unfinished") return " (not finished)";
802
+ return "";
803
+ }
804
+ function callDigest(call, max = 100) {
805
+ const kind = call.agent ? "agent" : call.category ?? call.name;
806
+ const target = call.target ?? (call.files[0] || "");
807
+ return `${kind}${target ? ` ${clipLine(target, max)}` : ""}${outcome(call)}`;
808
+ }
809
+ function turnDigest(turn, compact) {
810
+ const label = `T${turn.index + 1}${turn.origin.harness ? ` (${turn.origin.harness})` : ""}: `;
811
+ if (!compact) return `${label}${turn.tools.map((call) => callDigest(call)).join("; ")}`;
812
+ const counts = /* @__PURE__ */ new Map();
813
+ for (const call of turn.tools) {
814
+ const kind = call.agent ? "agent" : call.category ?? "other";
815
+ const entry = counts.get(kind) ?? { all: 0, failed: 0 };
816
+ entry.all += 1;
817
+ if (call.status === "failed") entry.failed += 1;
818
+ counts.set(kind, entry);
819
+ }
820
+ const parts = [...counts].map(([kind, { all, failed }]) => `${all} ${kind}${failed ? ` (${failed} failed)` : ""}`);
821
+ const files = turn.touchedFiles.length ? ` changed ${turn.touchedFiles.slice(0, 4).join(", ")}${turn.touchedFiles.length > 4 ? ` +${turn.touchedFiles.length - 4}` : ""}` : "";
822
+ return `${label}${parts.join(", ")}${files}`;
823
+ }
824
+ function fitNewestFirst(rows, budget) {
825
+ const lines = [];
826
+ let room = budget;
827
+ let index = rows.length - 1;
828
+ for (; index >= 0; index -= 1) {
829
+ const row = rows[index];
830
+ const line = bytes(row.full) + 1 <= room ? row.full : row.compact && bytes(row.compact) + 1 <= room ? row.compact : void 0;
831
+ if (line === void 0) break;
832
+ lines.unshift(line);
833
+ room -= bytes(line) + 1;
834
+ }
835
+ return { lines, dropped: index + 1 };
836
+ }
837
+ function verbatimTurn(turn, withOutput) {
838
+ const blocks = [];
839
+ if (turn.user.trim() || turn.attachments.length) {
840
+ const attached = turn.attachments.length ? `
841
+ [attached: ${turn.attachments.join(", ")}]` : "";
842
+ blocks.push(`<message role="user">
843
+ ${escapeFailoverContent(turn.user)}${escapeFailoverContent(attached)}
844
+ </message>`);
845
+ }
846
+ const answer = turn.parts.map((part) => {
847
+ if (part.type === "text") return part.text;
848
+ const output2 = withOutput && part.call.output?.length ? `
849
+ ${part.call.outputTail && part.call.outputOmitted ? ` \u2026 ${part.call.outputOmitted} earlier lines
850
+ ` : ""}${part.call.output.slice(-12).map((line) => ` ${line}`).join("\n")}${!part.call.outputTail && part.call.outputOmitted ? `
851
+ \u2026 ${part.call.outputOmitted} more lines` : ""}` : "";
852
+ return `
853
+ [tool: ${part.call.label}${outcome(part.call)}]${output2}
854
+ `;
855
+ }).join("").trim();
856
+ const interrupted = turn.interrupted ? "\n[interrupted here: this answer was cut off]" : "";
857
+ if (answer || interrupted) blocks.push(`<message role="assistant">
858
+ ${escapeFailoverContent(answer)}${interrupted}
859
+ </message>`);
860
+ return blocks.join("\n");
861
+ }
862
+ function condensedTurn(turn) {
863
+ const user = turn.user.trim() ? `<message role="user">
864
+ ${escapeFailoverContent(clipLine(turn.user, 300))}
865
+ </message>
866
+ ` : "";
867
+ const summary = extractiveSummary(turn.assistant);
868
+ const calls = turn.tools.length ? ` [${turn.tools.length} tool call${turn.tools.length === 1 ? "" : "s"}]` : "";
869
+ return `${user}<message role="assistant" condensed="true">
870
+ ${escapeFailoverContent(summary || "(no text)")}${calls}
871
+ </message>`;
872
+ }
873
+ function transferPrompt(record, request, options = {}) {
874
+ const maxBytes = Math.max(4 * 1024, options.maxBytes ?? TRANSFER_MIN_BYTES);
875
+ const turns = record.turns.map((turn, index2) => options.interrupted && index2 === record.turns.length - 1 ? { ...turn, interrupted: true } : turn);
876
+ const current = truncateMiddle(escapeFailoverContent(request), Math.floor(maxBytes * 0.5));
877
+ const fixed = bytes(FAILOVER_PREAMBLE) + bytes(current) + 400;
878
+ const room = Math.max(1024, maxBytes - fixed);
879
+ const sections = [];
880
+ let used = 0;
881
+ const add = (text) => {
882
+ sections.push(text);
883
+ used += bytes(text) + 2;
884
+ };
885
+ const runs = [];
886
+ for (const turn of turns) {
887
+ const name = turn.origin.harness ? options.displayName?.(turn.origin.harness) ?? turn.origin.harness : turn.origin.route ?? "ClikCode";
888
+ const who = `${name}${turn.origin.model ? ` (${turn.origin.model})` : ""}`;
889
+ const last = runs.at(-1);
890
+ const range = (from, to) => from === to ? `turn ${from}` : `turns ${from}-${to}`;
891
+ const match = last && /^(.*): turns? (\d+)(?:-\d+)?$/.exec(last);
892
+ if (match && match[1] === who) runs[runs.length - 1] = `${who}: ${range(Number(match[2]), turn.index + 1)}`;
893
+ else runs.push(`${who}: ${range(turn.index + 1, turn.index + 1)}`);
894
+ }
895
+ if (turns.length) {
896
+ const total = turns.length;
897
+ add(`This chat has ${total} earlier turn${total === 1 ? "" : "s"} (${runs.join("; ")}).`);
898
+ }
899
+ if (options.recordPath && turns.length) add(escapeFailoverContent(fullRecordNote(options.recordPath)));
900
+ const asked = turns.filter((turn) => turn.user.trim());
901
+ if (asked.length) {
902
+ const share = Math.floor(room * 0.25);
903
+ const per = Math.max(24, Math.min(600, Math.floor(share / asked.length) - 12));
904
+ const lines = asked.map((turn) => `${turn.index + 1}. ${escapeFailoverContent(clipLine(turn.user, per))}${turn.attachments.length ? ` [attached: ${escapeFailoverContent(turn.attachments.join(", "))}]` : ""}`);
905
+ let skipped = 0;
906
+ let listed = lines.reduce((sum, line) => sum + bytes(line) + 1, 0);
907
+ while (listed > share && skipped < lines.length - 1) {
908
+ listed -= bytes(lines[skipped]) + 1;
909
+ skipped += 1;
910
+ }
911
+ const lead = skipped ? `(${skipped} earlier request${skipped === 1 ? "" : "s"} not listed: they are in the file named above)
912
+ ` : "";
913
+ add(`<requests>
914
+ ${lead}${lines.slice(skipped).join("\n")}
915
+ </requests>`);
916
+ }
917
+ const called = turns.filter((turn) => turn.tools.length);
918
+ if (called.length) {
919
+ const fit = fitNewestFirst(called.map((turn) => ({ full: escapeFailoverContent(turnDigest(turn, false)), compact: escapeFailoverContent(turnDigest(turn, true)) })), Math.floor(room * 0.15));
920
+ const note2 = fit.dropped ? `(${fit.dropped} earlier turn${fit.dropped === 1 ? "" : "s"} with tool calls not listed)
921
+ ` : "";
922
+ add(`<tool_digest>
923
+ ${note2}${fit.lines.join("\n")}
924
+ </tool_digest>`);
925
+ }
926
+ if (record.touchedFiles.length) {
927
+ const last = turns.at(-1);
928
+ const partial = options.interrupted && last?.touchedFiles.length ? `
929
+ The interrupted turn had started changing ${last.touchedFiles.map(escapeFailoverContent).join(", ")}.` : "";
930
+ const fit = fitNewestFirst(record.touchedFiles.map((file) => ({ full: `- ${escapeFailoverContent(file)}` })), Math.floor(room * 0.06));
931
+ const note2 = fit.dropped ? `(+${fit.dropped} more)
932
+ ` : "";
933
+ add(`<touched_files>
934
+ Files changed in this chat:
935
+ ${note2}${fit.lines.join("\n")}${partial}
936
+ </touched_files>`);
937
+ }
938
+ if (record.attachments.length) {
939
+ const fit = fitNewestFirst(record.attachments.map((file) => ({ full: `- ${escapeFailoverContent(file)}` })), Math.floor(room * 0.04));
940
+ add(`<attachments>
941
+ Files attached to earlier requests:
942
+ ${fit.dropped ? `(+${fit.dropped} more)
943
+ ` : ""}${fit.lines.join("\n")}
944
+ </attachments>`);
945
+ }
946
+ if (record.openTodos.length) {
947
+ const fit = fitNewestFirst(record.openTodos.map((todo) => ({ full: `- [${todo.status ?? "pending"}] ${escapeFailoverContent(clipLine(todo.content, 200))}` })), Math.floor(room * 0.04));
948
+ add(`<open_todos>
949
+ ${fit.lines.join("\n")}
950
+ </open_todos>`);
951
+ }
952
+ let remaining = room - used;
953
+ const condensed = turns.map(condensedTurn);
954
+ const reserve = Math.min(Math.floor(remaining * 0.35), condensed.reduce((sum, text) => sum + bytes(text) + 1, 0));
955
+ let wholeRoom = remaining - reserve;
956
+ const told = [];
957
+ let whole = true;
958
+ let index = turns.length - 1;
959
+ for (; index >= 0; index -= 1) {
960
+ const turn = turns[index];
961
+ const age = turns.length - 1 - index;
962
+ let text = whole ? verbatimTurn(turn, age < 3) : void 0;
963
+ if (text !== void 0 && bytes(text) + 1 > wholeRoom) {
964
+ if (age === 0 && wholeRoom > 2048) text = truncateMiddle(text, wholeRoom - 64);
965
+ else {
966
+ whole = false;
967
+ text = void 0;
968
+ }
969
+ }
970
+ if (text !== void 0) wholeRoom -= bytes(text) + 1;
971
+ text ??= condensed[index];
972
+ if (bytes(text) + 1 > remaining) break;
973
+ told.unshift(text);
974
+ remaining -= bytes(text) + 1;
975
+ }
976
+ const omitted = index + 1;
977
+ const note = omitted > 0 ? `
978
+ (${omitted} earlier turn${omitted === 1 ? "" : "s"} not retold; their requests are listed above.)` : "";
979
+ const conversation = turns.length ? `
980
+
981
+ <conversation>${note}
982
+ ${told.join("\n")}
983
+ </conversation>` : "";
984
+ const head = sections.length ? `
985
+
986
+ ${sections.join("\n\n")}` : "";
987
+ return `${FAILOVER_PREAMBLE}${head}${conversation}
988
+
989
+ <current_request>
990
+ ${current}
991
+ </current_request>`;
992
+ }
993
+
994
+ // src/turn/thread-start.ts
995
+ function keepsNoHistory(harness, model, session) {
996
+ if (harness.turn?.stateless) return true;
997
+ if (session?.statelessRoutes?.includes(statelessRouteKey(harness, model))) return true;
998
+ if (!model) return false;
999
+ const stateless = [...harness.turn?.statelessProviders ?? [], ...harness.turn?.statelessRoute?.values ?? []];
1000
+ return stateless.length > 0 && stateless.includes(modelProvider(harness, model) ?? "");
1001
+ }
1002
+ var statelessRouteKey = (harness, model) => `${harness.command}:${model ?? ""}`;
1003
+ function rememberStatelessRoute(session, harness, model) {
1004
+ const key = statelessRouteKey(harness, model);
1005
+ if (!session.statelessRoutes?.includes(key)) session.statelessRoutes = [...session.statelessRoutes ?? [], key];
1006
+ }
1007
+ var NATIVE_WINDOW_SHARE = 0.5;
1008
+ var NATIVE_DEFAULT_BYTES = 400 * 1024;
1009
+ function nativeThreadBudget(contextWindow, capTokens) {
1010
+ const byWindow = contextWindow && contextWindow > 0 ? Math.floor(contextWindow * NATIVE_WINDOW_SHARE * BYTES_PER_TOKEN) : NATIVE_DEFAULT_BYTES;
1011
+ return capTokens && capTokens > 0 ? Math.min(byWindow, capTokens * BYTES_PER_TOKEN) : byWindow;
1012
+ }
1013
+ function writtenBytes(turn) {
1014
+ return Buffer.byteLength(turn.user, "utf8") + Buffer.byteLength(JSON.stringify(turn.parts), "utf8");
1015
+ }
1016
+ function briefTurn(turn) {
1017
+ const ran = ranNote(turn.tools.map((call) => call.label));
1018
+ return { ...turn, user: `${turn.user}${ran}`, parts: turn.assistant ? [{ type: "text", text: turn.assistant }] : [], tools: [] };
1019
+ }
1020
+ function clipMiddle(text, limit) {
1021
+ const flat = text.replace(/\s+/g, " ").trim();
1022
+ if (Buffer.byteLength(flat, "utf8") <= limit) return flat;
1023
+ if (limit < 24) return Buffer.from(flat).subarray(0, Math.max(0, limit)).toString("utf8").replace(/�+$/g, "");
1024
+ const marker = " \u2026 ";
1025
+ const room = Math.max(0, limit - Buffer.byteLength(marker));
1026
+ const head = Buffer.from(flat).subarray(0, Math.ceil(room * 0.65)).toString("utf8").replace(/�+$/g, "");
1027
+ const tail = Buffer.from(flat).subarray(-Math.floor(room * 0.35)).toString("utf8").replace(/^�+/g, "");
1028
+ return `${head}${marker}${tail}`;
1029
+ }
1030
+ function compactTurn(turn, maxBytes, recordPath) {
1031
+ const recordNote = turn.index === 0 && recordPath ? ` Full transcript: ${recordPath}.` : "";
1032
+ const lead = `[ClikCode history, turn ${turn.index + 1}] Request:${recordNote} `;
1033
+ const room = Math.max(0, maxBytes - Buffer.byteLength(lead, "utf8") - 44);
1034
+ const requestLimit = Math.floor(room * 0.46);
1035
+ const summaryLimit = Math.floor(room * 0.34);
1036
+ const actionsLimit = Math.max(0, room - requestLimit - summaryLimit);
1037
+ const request = clipMiddle(turn.user || "(continued work)", requestLimit);
1038
+ const prose = turn.assistant.replace(/```[\s\S]*?```/g, " ").replace(/\s+/g, " ").trim();
1039
+ const sentences = prose.split(/(?<=[.!?])\s+/).filter(Boolean);
1040
+ const outcome2 = clipMiddle(sentences.length > 1 ? `${sentences[0]} \u2026 ${sentences.at(-1)}` : prose, summaryLimit);
1041
+ const actionText = [.../* @__PURE__ */ new Set([
1042
+ ...turn.tools.map((tool) => `${tool.label}${tool.status === "failed" ? " (failed)" : ""}`),
1043
+ ...turn.touchedFiles.map((file) => `changed ${file}`)
1044
+ ])].join("; ");
1045
+ const actions = actionText ? clipMiddle(actionText, actionsLimit) : "";
1046
+ const user = `${lead}${request}${actions ? `
1047
+ Work: ${actions}` : ""}`;
1048
+ const assistant = outcome2 || (turn.interrupted ? "[The turn was interrupted before a response.]" : "");
1049
+ return {
1050
+ ...turn,
1051
+ user,
1052
+ assistant,
1053
+ parts: assistant ? [{ type: "text", text: assistant }] : [],
1054
+ tools: [],
1055
+ touchedFiles: turn.touchedFiles.slice(0, 8)
1056
+ };
1057
+ }
1058
+ function writtenRecordBytes(turns) {
1059
+ return turns.reduce((sum, turn) => sum + writtenBytes(turn), 0);
1060
+ }
1061
+ var OUTLINE_SHARE = 0.1;
1062
+ var NOTE_FIXED_BYTES = 600;
1063
+ function requestsOutline(turns, maxBytes) {
1064
+ const asked = turns.filter((turn) => turn.user.trim());
1065
+ if (!asked.length || maxBytes < 256) return "";
1066
+ const per = Math.max(40, Math.min(240, Math.floor(maxBytes / asked.length) - 12));
1067
+ const lines = asked.map((turn) => {
1068
+ const text = turn.user.replace(/\s+/g, " ").trim();
1069
+ return `${turn.index + 1}. ${text.length > per ? `${text.slice(0, per - 1)}\u2026` : text}`;
1070
+ });
1071
+ let used = lines.reduce((sum, line) => sum + Buffer.byteLength(line, "utf8") + 1, 0);
1072
+ let dropped = 0;
1073
+ while (used > maxBytes && dropped < lines.length - 1) {
1074
+ used -= Buffer.byteLength(lines[dropped], "utf8") + 1;
1075
+ dropped += 1;
1076
+ }
1077
+ return `${dropped ? `(${dropped} earlier request${dropped === 1 ? "" : "s"} not listed)
1078
+ ` : ""}${lines.slice(dropped).join("\n")}`;
1079
+ }
1080
+ function fitRecord(record, maxBytes, options = {}) {
1081
+ const turns = record.turns;
1082
+ const brief = turns.map(briefTurn);
1083
+ let totalBytes = writtenRecordBytes(brief);
1084
+ let compacted = 0;
1085
+ const compactedIndices = /* @__PURE__ */ new Set();
1086
+ if (totalBytes > maxBytes && turns.length > 1) {
1087
+ const perTurn = Math.floor((maxBytes - (options.recordPath ? Buffer.byteLength(options.recordPath, "utf8") + 48 : 0)) / turns.length);
1088
+ if (perTurn >= 192) {
1089
+ for (let index = 0; index < turns.length - 1 && totalBytes > maxBytes; index += 1) {
1090
+ const compact = compactTurn(turns[index], perTurn, options.recordPath);
1091
+ const before = writtenBytes(brief[index]);
1092
+ const after = writtenBytes(compact);
1093
+ if (after < before) {
1094
+ brief[index] = compact;
1095
+ totalBytes += after - before;
1096
+ compacted += 1;
1097
+ compactedIndices.add(index);
1098
+ }
1099
+ }
1100
+ }
1101
+ }
1102
+ const select = (room) => {
1103
+ let used = 0;
1104
+ let first2 = turns.length;
1105
+ while (first2 > 0 && (first2 === turns.length || used + writtenBytes(brief[first2 - 1]) <= room)) {
1106
+ used += writtenBytes(brief[first2 - 1]);
1107
+ first2 -= 1;
1108
+ }
1109
+ const kept2 = brief.slice(first2);
1110
+ for (let index = kept2.length - 1; index >= 0; index -= 1) {
1111
+ const full = turns[first2 + index];
1112
+ const extra = writtenBytes(full) - writtenBytes(kept2[index]);
1113
+ if (used + extra > room) break;
1114
+ used += extra;
1115
+ kept2[index] = full;
1116
+ }
1117
+ return { first: first2, kept: kept2 };
1118
+ };
1119
+ let { first, kept } = select(maxBytes);
1120
+ const summarisedIn = () => kept.filter(
1121
+ (turn, index) => !compactedIndices.has(first + index) && turn !== turns[first + index] && turns[first + index].tools.length > 0
1122
+ ).length;
1123
+ if (first === 0 && compacted === 0 && kept.every((turn, index) => turn === turns[index])) return { record, omitted: 0, summarised: 0 };
1124
+ if (first === 0) return { record: { ...record, turns: kept }, omitted: 0, summarised: compacted + summarisedIn() };
1125
+ const outlineRoom = Math.floor(maxBytes * OUTLINE_SHARE);
1126
+ ({ first, kept } = select(Math.max(0, maxBytes - outlineRoom - NOTE_FIXED_BYTES)));
1127
+ const summarised = compacted + summarisedIn();
1128
+ const outline = requestsOutline(turns.slice(0, first), outlineRoom);
1129
+ const note = `[ClikCode: the ${first} earlier turn${first === 1 ? " is" : "s are"} left out to fit this model.${options.recordPath ? ` ${fullRecordNote(options.recordPath)}` : ""}${outline ? `
1130
+ What was asked in them, oldest first:
1131
+ ${outline}` : ""}]
1132
+
1133
+ `;
1134
+ return { record: { ...record, turns: [{ ...kept[0], user: `${note}${kept[0].user}` }, ...kept.slice(1)] }, omitted: first, summarised };
1135
+ }
1136
+ async function written(input) {
1137
+ const writer = input.writer;
1138
+ if (!writer || !input.record.turns.length) return void 0;
1139
+ if (keepsNoHistory(input.harness, input.model, input.session)) {
1140
+ input.onFallback?.(`${input.model} keeps no history: a written ${input.harness.command} thread would not reach it`);
1141
+ return void 0;
1142
+ }
1143
+ try {
1144
+ const context = {
1145
+ harness: input.harness,
1146
+ workspace: input.workspace,
1147
+ environment: input.environment,
1148
+ model: input.model,
1149
+ version: await input.version?.().catch(quiet("turn/thread-start"))
1150
+ };
1151
+ if (!await writer.versionOk(context)) {
1152
+ input.onFallback?.(`${input.harness.command} ${context.version ?? "(version unknown)"} is not a build its thread writer was verified against (${writer.testedVersions.join(", ") || "none"})`);
1153
+ return void 0;
1154
+ }
1155
+ const fitted = fitRecord(input.record, nativeThreadBudget(input.contextWindow, input.capTokens), input.recordPath ? { recordPath: input.recordPath } : {});
1156
+ const result = await writer.write(fitted.record, context);
1157
+ if (!result?.nativeId) input.onFallback?.(`${input.harness.command} thread writer declined`);
1158
+ return result?.nativeId ? { written: result, omitted: fitted.omitted, summarised: fitted.summarised } : void 0;
1159
+ } catch (error) {
1160
+ input.onFallback?.(`${input.harness.command} thread writer failed: ${error instanceof Error ? error.message : String(error)}`);
1161
+ return void 0;
1162
+ }
1163
+ }
1164
+ async function startConversationThread(input) {
1165
+ const native = await written(input);
1166
+ if (native) return { kind: "native", ...native, prompt: input.request };
1167
+ const budget = transferBudget({
1168
+ ...input.contextWindow ? { contextWindow: input.contextWindow } : {},
1169
+ ...input.argvLimit ? { argvLimit: input.argvLimit } : {},
1170
+ ...input.capTokens ? { capTokens: input.capTokens } : {}
1171
+ });
1172
+ return {
1173
+ kind: "transfer",
1174
+ budget,
1175
+ prompt: transferPrompt(input.record, input.request, {
1176
+ maxBytes: budget,
1177
+ interrupted: input.interrupted,
1178
+ ...input.displayName ? { displayName: input.displayName } : {},
1179
+ ...input.recordPath ? { recordPath: input.recordPath } : {}
1180
+ })
1181
+ };
1182
+ }
1183
+ function carriedLine(turns, start) {
1184
+ if (!turns) return void 0;
1185
+ return start.kind === "transfer" || start.omitted || start.summarised ? COMPACTED : void 0;
1186
+ }
1187
+
1188
+ // src/turn/vendor-thread-takeup.ts
1189
+ var RETRY_EDITS = { clear: ["", "replace"], "new-paragraph": ["\n\n", "append"] };
1190
+ function editAnswer(ctx, edit) {
1191
+ ctx.checkpoint.response(RETRY_EDITS[edit][0], RETRY_EDITS[edit][1]);
1192
+ ctx.prompter?.response(RETRY_EDITS[edit][0], RETRY_EDITS[edit][1]);
1193
+ }
1194
+ function continueAnswer(ctx, edit) {
1195
+ if (edit === "clear" || !/\n\s*\n\s*$/.test(ctx.session.pendingTurn?.response ?? "")) editAnswer(ctx, edit);
1196
+ }
1197
+ async function takeUp(ctx, request, options) {
1198
+ const { session, harness, state, checkpoint } = ctx;
1199
+ const view = options.withJournal ? session : { ...session, pendingTurn: void 0 };
1200
+ const record = canonicalRecord(view);
1201
+ const last = record.turns.at(-1);
1202
+ if (options.interrupted && options.requestContext && last) last.user = `${last.user}${options.requestContext}`;
1203
+ const transport = sessionTurnTransport(harness, session);
1204
+ const argvBound = (transport === "structured-cli" || transport === "text-cli") && harness.turn?.promptInput !== "stdin";
1205
+ const contextWindow = await targetContextWindow(state.sessions, harness.command, ctx.model, modelsDevFiles()).catch(quiet("turn/vendor-thread-takeup"));
1206
+ const writer = nativeSessionStore(harness)?.writer;
1207
+ const recordPath = record.turns.length ? await writeFullRecord(view, stateDirectory()) : void 0;
1208
+ const threshold = compactAt(state.globalSettings);
1209
+ const rewrite = Boolean(session.compaction?.rewrite);
1210
+ const capTokens = rewrite ? Math.floor(threshold / 2) : threshold;
1211
+ const start = await startConversationThread({
1212
+ record,
1213
+ request,
1214
+ interrupted: options.interrupted,
1215
+ harness,
1216
+ model: ctx.model,
1217
+ session,
1218
+ ...recordPath ? { recordPath } : {},
1219
+ workspace: session.workspace ?? process.cwd(),
1220
+ environment: turnEnvironment(harness, ctx.account),
1221
+ ...contextWindow ? { contextWindow } : {},
1222
+ ...argvBound ? { argvLimit: maxPromptArgvBytes() } : {},
1223
+ capTokens,
1224
+ ...writer ? { writer } : {},
1225
+ version: async () => (await inspectNativeHarness(harness)).version,
1226
+ displayName: (command) => localHarnessForCommand(command)?.displayName,
1227
+ onFallback: (reason) => lifecycle("thread.writer-fallback", { harness: harness.command, reason })
1228
+ });
1229
+ lifecycle("thread.take-up", {
1230
+ harness: harness.command,
1231
+ how: start.kind,
1232
+ turns: record.turns.length,
1233
+ interrupted: options.interrupted,
1234
+ ...recordPath ? { record: recordPath } : {},
1235
+ ...start.kind === "transfer" ? { budget: start.budget, bytes: Buffer.byteLength(start.prompt, "utf8"), contextWindow } : { omitted: start.omitted, contextWindow }
1236
+ });
1237
+ const carried = carriedLine(record.turns.length, start);
1238
+ if (carried && options.reportCarry !== false && !rewrite) ctx.prompter?.activity(carried);
1239
+ if (rewrite) delete session.compaction.rewrite;
1240
+ if (start.kind === "native") {
1241
+ session.nativeSessionId = start.written.nativeId;
1242
+ session.nativeThreadAccountId = ctx.account.id;
1243
+ delete session.nativeSessionPreallocated;
1244
+ if (start.written.transport) session.nativeTransport = start.written.transport;
1245
+ else delete session.nativeTransport;
1246
+ await checkpoint.persistNow();
1247
+ }
1248
+ return start.prompt;
1249
+ }
1250
+ async function retell(ctx, request, edit, wrote) {
1251
+ const prompt = await takeUp(ctx, request, { interrupted: wrote, withJournal: wrote, requestContext: ctx.requestContext, reportCarry: false });
1252
+ continueAnswer(ctx, edit);
1253
+ return prompt;
1254
+ }
1255
+
1256
+ export {
1257
+ turnEnvironment,
1258
+ fullRecordPath,
1259
+ writeFullRecord,
1260
+ fullRecordNote,
1261
+ BYTES_PER_TOKEN,
1262
+ transferBudget,
1263
+ targetContextWindow,
1264
+ transferPrompt,
1265
+ ranNote,
1266
+ callsAsUserNotes,
1267
+ recordInvocation,
1268
+ showStopReason,
1269
+ turnSink,
1270
+ unfinishedUsageRecorder,
1271
+ setPlanMode,
1272
+ settleHeldVendor,
1273
+ keepsNoHistory,
1274
+ rememberStatelessRoute,
1275
+ nativeThreadBudget,
1276
+ fitRecord,
1277
+ moveThreadToAccount,
1278
+ reconcileNativeThread,
1279
+ sessionTurnTransport,
1280
+ cliThreadTransport,
1281
+ turnPermissionMode,
1282
+ runVendorSessionAttempt,
1283
+ prepareAcpStandby,
1284
+ pingPromptCache,
1285
+ prepareCodexStandby,
1286
+ prepareVendorAhead,
1287
+ editAnswer,
1288
+ continueAnswer,
1289
+ takeUp,
1290
+ retell
1291
+ };