clikcode 1.0.4 → 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 +494 -112923
  319. package/dist/computer-tools.js +36642 -21259
  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,4625 @@
1
+ import { createRequire as __clikcodeCreateRequire } from 'node:module';
2
+ const require = __clikcodeCreateRequire(import.meta.url);
3
+ import {
4
+ codexMcpLaunch,
5
+ globalMcpServers,
6
+ globalMcpServersForAcp
7
+ } from "./chunk-EOBTJV32.js";
8
+ import {
9
+ nextUsableFailoverAccount,
10
+ turnBackendForAccount
11
+ } from "./chunk-IF43HIGV.js";
12
+ import {
13
+ storeQuotaRefusal
14
+ } from "./chunk-7TSQLONI.js";
15
+ import {
16
+ ACP_AUTH_REQUIRED_CODE,
17
+ classifyAccountFailure
18
+ } from "./chunk-2YPAPAR3.js";
19
+ import {
20
+ isTurnCancelled,
21
+ turnCancelledError
22
+ } from "./chunk-4LPDG57B.js";
23
+ import {
24
+ claudeRateLimitReading,
25
+ quotaRefusalHolds
26
+ } from "./chunk-XWAC3MKW.js";
27
+ import {
28
+ commandLine,
29
+ commandRoots,
30
+ outputFile,
31
+ processGroup,
32
+ processGroupMembers,
33
+ readProcessGroup,
34
+ toolCallWork
35
+ } from "./chunk-ESF3DIZY.js";
36
+ import {
37
+ COMPACTED,
38
+ COMPACTING,
39
+ readState
40
+ } from "./chunk-MXS6S2PY.js";
41
+ import {
42
+ writeState
43
+ } from "./chunk-RKUVLRZI.js";
44
+ import {
45
+ redactSecrets
46
+ } from "./chunk-IMLTL2MY.js";
47
+ import {
48
+ backgroundWork,
49
+ formatAge,
50
+ mergeBackgroundWork
51
+ } from "./chunk-BUOPJQP5.js";
52
+ import {
53
+ activityOutput,
54
+ commandOutcome,
55
+ editDiffFromInput,
56
+ eventDiff,
57
+ fileChangeActivity,
58
+ thoughtLabel,
59
+ toolCall
60
+ } from "./chunk-3B2CHX7M.js";
61
+ import {
62
+ localHarnessForCommand
63
+ } from "./chunk-KYUHIFP3.js";
64
+ import {
65
+ expandAuthPath,
66
+ spawnFailure
67
+ } from "./chunk-DF35KMXM.js";
68
+ import {
69
+ JsonRpcPeer
70
+ } from "./chunk-IGZ6C2MC.js";
71
+ import {
72
+ markTurn
73
+ } from "./chunk-4NN3XQQT.js";
74
+ import {
75
+ spawnPortable
76
+ } from "./chunk-WPB5WEZJ.js";
77
+ import {
78
+ categoryOf,
79
+ commandText,
80
+ formatToolRow,
81
+ isAgentToolName,
82
+ toolLabel
83
+ } from "./chunk-W3YYPBEA.js";
84
+ import {
85
+ asRecord,
86
+ parseJsonDocument,
87
+ parseJsonLines
88
+ } from "./chunk-XIBYREEY.js";
89
+ import {
90
+ sleep
91
+ } from "./chunk-YMCH3L2S.js";
92
+ import {
93
+ stripAnsi
94
+ } from "./chunk-G3QP67Z7.js";
95
+ import {
96
+ pidIsAlive
97
+ } from "./chunk-4L2ZZM4Q.js";
98
+ import {
99
+ diagnostic,
100
+ lifecycle,
101
+ quiet
102
+ } from "./chunk-RDDWQBEM.js";
103
+
104
+ // src/harness/events/question.ts
105
+ var CANCELLED = { kind: "cancelled" };
106
+ async function askHarnessQuestion(observer, request, signal, declinedNotice) {
107
+ if (!observer.onQuestion) {
108
+ observer.onNotice?.(declinedNotice ?? `A question was declined because this screen cannot show it: ${request.title}`);
109
+ return CANCELLED;
110
+ }
111
+ if (signal?.aborted) return CANCELLED;
112
+ try {
113
+ return await observer.onQuestion(request, signal);
114
+ } catch {
115
+ return CANCELLED;
116
+ }
117
+ }
118
+
119
+ // src/harness/events/form-questions.ts
120
+ var SECRET_NAME = /pass(word|phrase)|secret|token|api[-_ ]?key/i;
121
+ function optionsOf(schema) {
122
+ const named = (list, constKey) => {
123
+ if (!Array.isArray(list) || !list.length) return void 0;
124
+ const out = [];
125
+ for (const entry of list) {
126
+ if (!entry || typeof entry !== "object" || entry[constKey] === void 0) return void 0;
127
+ const value = String(entry[constKey]);
128
+ out.push({ value, label: typeof entry.title === "string" && entry.title ? entry.title : value, ...typeof entry.description === "string" && entry.description ? { description: entry.description } : {} });
129
+ }
130
+ return out;
131
+ };
132
+ const oneOf = named(schema.oneOf, "const") ?? named(schema.anyOf, "const");
133
+ if (oneOf) return oneOf;
134
+ if (Array.isArray(schema.enum) && schema.enum.length) {
135
+ const names = Array.isArray(schema.enumNames) ? schema.enumNames : [];
136
+ return schema.enum.map((value, index) => ({ value: String(value), label: typeof names[index] === "string" && names[index] ? String(names[index]) : String(value) }));
137
+ }
138
+ return void 0;
139
+ }
140
+ function formToQuestions(message, schema, title) {
141
+ const properties = schema && typeof schema === "object" && schema.properties && typeof schema.properties === "object" ? schema.properties : {};
142
+ const required = new Set(Array.isArray(schema?.required) ? schema.required.map(String) : []);
143
+ const keys = Object.keys(properties);
144
+ const selectLike = (key) => {
145
+ const p = properties[key];
146
+ return Boolean(p) && (p.type === "array" ? optionsOf(p.items ?? {}) !== void 0 : optionsOf(p) !== void 0);
147
+ };
148
+ const companions = new Set(keys.filter((key) => key.endsWith("_custom") && selectLike(key.slice(0, -"_custom".length)) && properties[key]?.type === "string" && !optionsOf(properties[key])));
149
+ const fields = [];
150
+ const questions = [];
151
+ const single = keys.length - companions.size === 1;
152
+ for (const key of keys) {
153
+ if (companions.has(key)) continue;
154
+ const p = properties[key] ?? {};
155
+ const heading = typeof p.title === "string" && p.title ? p.title : void 0;
156
+ const description = typeof p.description === "string" && p.description ? p.description : void 0;
157
+ const prompt = description ?? (single && message ? message : heading ?? key);
158
+ const header = heading && heading !== prompt ? heading : void 0;
159
+ const base = { id: key, ...header ? { header } : {}, prompt, ...required.has(key) ? {} : { optional: true } };
160
+ const customKey = companions.has(`${key}_custom`) ? `${key}_custom` : void 0;
161
+ const choices = p.type === "array" ? optionsOf(p.items ?? {}) : optionsOf(p);
162
+ if (choices) {
163
+ const multi = p.type === "array";
164
+ fields.push({ key, kind: multi ? "multi" : "select", values: new Map(choices.map((c) => [c.label, c.value])), ...customKey ? { custom: customKey } : {} });
165
+ questions.push({
166
+ ...base,
167
+ multiSelect: multi,
168
+ allowFreeText: customKey !== void 0,
169
+ options: choices.map((c) => ({ label: c.label, ...c.description ? { description: c.description } : {} }))
170
+ });
171
+ } else if (p.type === "boolean") {
172
+ fields.push({ key, kind: "boolean", values: /* @__PURE__ */ new Map([["Yes", "true"], ["No", "false"]]) });
173
+ questions.push({ ...base, options: [{ label: "Yes" }, { label: "No" }] });
174
+ } else if (p.type === "number" || p.type === "integer") {
175
+ fields.push({ key, kind: "number", values: /* @__PURE__ */ new Map(), integer: p.type === "integer" });
176
+ questions.push({ ...base, options: [], allowFreeText: true });
177
+ } else {
178
+ fields.push({ key, kind: "text", values: /* @__PURE__ */ new Map() });
179
+ questions.push({ ...base, options: [], allowFreeText: true, ...p.format === "password" || SECRET_NAME.test(`${key} ${heading ?? ""}`) ? { secret: true } : {} });
180
+ }
181
+ }
182
+ if (!questions.length) return void 0;
183
+ return {
184
+ request: { title: message && !single ? message : title, questions },
185
+ content(answers) {
186
+ const content = {};
187
+ for (const field of fields) {
188
+ const given = answers[field.key]?.filter((v) => v !== "");
189
+ if (!given?.length) continue;
190
+ if (field.kind === "multi" || field.kind === "select") {
191
+ const picked = given.filter((v) => field.values.has(v)).map((v) => field.values.get(v));
192
+ const typed = given.filter((v) => !field.values.has(v));
193
+ if (field.kind === "multi") {
194
+ if (picked.length) content[field.key] = picked;
195
+ } else if (picked.length) content[field.key] = picked[0];
196
+ if (typed.length && field.custom) content[field.custom] = typed.join(", ");
197
+ } else if (field.kind === "boolean") {
198
+ content[field.key] = field.values.get(given[0]) === "true";
199
+ } else if (field.kind === "number") {
200
+ const n = Number(given[0]);
201
+ if (Number.isFinite(n)) content[field.key] = field.integer ? Math.trunc(n) : n;
202
+ } else content[field.key] = given[0];
203
+ }
204
+ return content;
205
+ }
206
+ };
207
+ }
208
+
209
+ // src/harness/transport/codex-native-methods.ts
210
+ function codexTurnPermissionParams(mode) {
211
+ return mode === "bypass" ? { approvalPolicy: "never", approvalsReviewer: "user", sandboxPolicy: { type: "dangerFullAccess" } } : { approvalPolicy: "on-request", approvalsReviewer: mode === "auto" ? "auto_review" : "user", sandboxPolicy: { type: "workspaceWrite" } };
212
+ }
213
+ function codexTurnStartParams(input) {
214
+ return {
215
+ threadId: input.threadId,
216
+ input: [
217
+ { type: "text", text: input.prompt, text_elements: [] },
218
+ ...(input.images ?? []).map((path) => ({ type: "localImage", path }))
219
+ ],
220
+ cwd: input.cwd,
221
+ model: input.model ?? null,
222
+ effort: input.effort ?? null,
223
+ ...input.summary ? { summary: input.summary } : {},
224
+ ...codexTurnPermissionParams(input.permissionMode)
225
+ };
226
+ }
227
+ async function compactCodexThread(peer, threadId) {
228
+ await peer.request("thread/compact/start", { threadId });
229
+ }
230
+ async function listCodexModels(peer, options = {}) {
231
+ const models = [];
232
+ let cursor = null;
233
+ do {
234
+ const page = await peer.request("model/list", { cursor, limit: 100, includeHidden: options.includeHidden ?? false });
235
+ for (const entry of Array.isArray(page.data) ? page.data : []) {
236
+ const model = typeof entry?.model === "string" ? entry.model : typeof entry?.id === "string" ? entry.id : "";
237
+ if (!model) continue;
238
+ const efforts = (Array.isArray(entry.supportedReasoningEfforts) ? entry.supportedReasoningEfforts : []).map((option) => option?.reasoningEffort).filter((effort) => typeof effort === "string");
239
+ models.push({
240
+ id: String(entry.id ?? model),
241
+ model,
242
+ displayName: String(entry.displayName ?? model),
243
+ isDefault: entry.isDefault === true,
244
+ hidden: entry.hidden === true,
245
+ ...typeof entry.defaultReasoningEffort === "string" ? { defaultEffort: entry.defaultReasoningEffort } : {},
246
+ efforts
247
+ });
248
+ }
249
+ cursor = typeof page.nextCursor === "string" && page.nextCursor ? page.nextCursor : null;
250
+ } while (cursor);
251
+ return models;
252
+ }
253
+
254
+ // src/harness/protocol/turn-usage.ts
255
+ var finiteNumber = (...candidates) => candidates.find((candidate) => typeof candidate === "number" && Number.isFinite(candidate));
256
+ var STOP_REASONS = {
257
+ end_turn: "completed",
258
+ stop: "completed",
259
+ stop_sequence: "completed",
260
+ completed: "completed",
261
+ success: "completed",
262
+ max_tokens: "max-tokens",
263
+ length: "max-tokens",
264
+ max_output_tokens: "max-tokens",
265
+ max_turns: "max-turns",
266
+ error_max_turns: "max-turns",
267
+ max_turn_requests: "max-turns",
268
+ "max-steps": "max-turns",
269
+ refusal: "refusal",
270
+ content_filter: "refusal",
271
+ "content-filter": "refusal",
272
+ cancelled: "stopped",
273
+ interrupted: "stopped",
274
+ stopped: "stopped",
275
+ failed: "failed"
276
+ };
277
+ function turnStopReason(raw) {
278
+ return typeof raw === "string" ? STOP_REASONS[raw.replace(/-/g, "_")] ?? STOP_REASONS[raw] : void 0;
279
+ }
280
+ function stopReasonNotice(reason) {
281
+ if (reason === "max-tokens") return "The answer was cut off: the model reached its output limit.";
282
+ if (reason === "max-turns") return "The turn stopped at its step limit before the work was finished.";
283
+ if (reason === "refusal") return "The model declined to continue this answer.";
284
+ return void 0;
285
+ }
286
+ function addTurnUsage(carried, latest) {
287
+ if (!carried) return latest;
288
+ if (!latest) return carried;
289
+ const summed = { ...carried };
290
+ for (const key of ["input", "output", "cacheRead", "cacheWrite", "reasoning", "totalTokens", "costUsd", "credits"]) {
291
+ if (latest[key] !== void 0) summed[key] = (carried[key] ?? 0) + latest[key];
292
+ }
293
+ if (latest.costBreakdown || carried.costBreakdown) {
294
+ const a = carried.costBreakdown;
295
+ const b = latest.costBreakdown;
296
+ const add = (key) => a?.[key] === void 0 && b?.[key] === void 0 ? void 0 : (a?.[key] ?? 0) + (b?.[key] ?? 0);
297
+ const metered = add("meteredUsd");
298
+ const gpu = add("gpuUsd");
299
+ summed.costBreakdown = { ...metered !== void 0 ? { meteredUsd: metered } : {}, ...gpu !== void 0 ? { gpuUsd: gpu } : {} };
300
+ }
301
+ for (const key of ["contextWindow", "contextUsed", "contextPercent", "stopReason"]) {
302
+ if (latest[key] !== void 0) summed[key] = latest[key];
303
+ }
304
+ return summed;
305
+ }
306
+ function assigner(result) {
307
+ return (key, value) => {
308
+ if (value !== void 0) result[key] = value;
309
+ };
310
+ }
311
+ function modelUsageContextWindow(modelUsage) {
312
+ const windows = Object.values(modelUsage ?? {}).flatMap((entry) => {
313
+ const window = finiteNumber(asRecord(entry)?.contextWindow);
314
+ return window ? [window] : [];
315
+ });
316
+ return windows.length ? Math.max(...windows) : void 0;
317
+ }
318
+ function countsOf(usage) {
319
+ const result = {};
320
+ if (!usage) return result;
321
+ const assign = assigner(result);
322
+ const cache = asRecord(usage.cache);
323
+ const outputDetails = asRecord(usage.output_tokens_details) ?? asRecord(usage.completion_tokens_details);
324
+ assign("input", finiteNumber(usage.input_tokens, usage.inputTokens, usage.prompt_tokens, usage.promptTokens, usage.input));
325
+ assign("output", finiteNumber(usage.output_tokens, usage.outputTokens, usage.completion_tokens, usage.completionTokens, usage.output));
326
+ assign("cacheRead", finiteNumber(
327
+ usage.cache_read_input_tokens,
328
+ usage.cached_input_tokens,
329
+ usage.cachedInputTokens,
330
+ usage.cache_read_tokens,
331
+ usage.cacheReadTokens,
332
+ usage.cachedReadTokens,
333
+ usage.cacheReadInputTokens,
334
+ usage.cacheRead,
335
+ usage.cached,
336
+ usage.cachedTokens,
337
+ cache?.read
338
+ ));
339
+ assign("cacheWrite", finiteNumber(
340
+ usage.cache_creation_input_tokens,
341
+ usage.cache_write_input_tokens,
342
+ usage.cache_write_tokens,
343
+ usage.cacheWriteTokens,
344
+ usage.cachedWriteTokens,
345
+ usage.cacheCreationInputTokens,
346
+ usage.cacheWriteInputTokens,
347
+ usage.cacheWrite,
348
+ cache?.write
349
+ ));
350
+ assign("totalTokens", finiteNumber(usage.total_tokens, usage.totalTokens, usage.total));
351
+ assign("reasoning", finiteNumber(
352
+ usage.thinking_tokens,
353
+ usage.thinkingTokens,
354
+ usage.reasoning_tokens,
355
+ usage.reasoningTokens,
356
+ usage.reasoningOutputTokens,
357
+ usage.reasoning_output_tokens,
358
+ usage.thoughtTokens,
359
+ usage.reasoning,
360
+ outputDetails?.thinking_tokens,
361
+ outputDetails?.reasoning_tokens
362
+ ));
363
+ return result;
364
+ }
365
+ function nativeUsageFromValue(value) {
366
+ const record = asRecord(value);
367
+ if (!record) return void 0;
368
+ const type = String(record.type ?? record.event ?? "");
369
+ if (type && !/(?:^|[._-])(?:result|complete|completed|finish|finished|done|usage|stats?)(?:$|[._-])/i.test(type)) return void 0;
370
+ const envelope = asRecord(record.result) ?? asRecord(record.turn) ?? asRecord(record.data) ?? asRecord(record.response) ?? asRecord(record.summary);
371
+ const agentMeta = asRecord(asRecord(record.meta)?.agentMeta);
372
+ const nested = asRecord(record.usage) ?? asRecord(record.stats) ?? asRecord(record.token_usage) ?? asRecord(asRecord(record.part)?.tokens) ?? asRecord(envelope?.usage) ?? asRecord(envelope?.stats) ?? asRecord(envelope?.token_usage) ?? asRecord(agentMeta?.usage);
373
+ const usage = nested ?? (type ? record : void 0);
374
+ const result = countsOf(usage);
375
+ const assign = assigner(result);
376
+ assign("costUsd", finiteNumber(record.total_cost_usd, record.cost_usd, record.totalCostUsd, usage?.total_cost_usd, asRecord(record.part)?.cost, agentMeta?.costUsd));
377
+ assign("contextWindow", modelUsageContextWindow(asRecord(record.modelUsage)) ?? finiteNumber(agentMeta?.contextTokens));
378
+ assign("contextUsed", finiteNumber(agentMeta?.promptTokens));
379
+ if (/(?:^|[._-])result(?:$|[._-])/i.test(type)) {
380
+ assign("stopReason", turnStopReason(record.subtype) === "max-turns" ? "max-turns" : turnStopReason(record.stop_reason) ?? turnStopReason(record.terminal_reason) ?? turnStopReason(record.stopReason));
381
+ }
382
+ const { stopReason: _reason, ...counted } = result;
383
+ return Object.keys(counted).length ? result : void 0;
384
+ }
385
+ var StreamUsageTally = class {
386
+ messages = /* @__PURE__ */ new Map();
387
+ /** The message each thread (main, or a sub-agent's parent_tool_use_id) is on. */
388
+ current = /* @__PURE__ */ new Map();
389
+ /** The turn's usage so far after this record, or undefined when the record
390
+ * carries none. */
391
+ note(record) {
392
+ if (record.type === "message_end") return this.finished(asRecord(record.message));
393
+ if (record.type === "assistant") return this.assistant(record);
394
+ if (record.type !== "stream_event") return void 0;
395
+ const event = asRecord(record.event);
396
+ const thread = typeof record.parent_tool_use_id === "string" ? record.parent_tool_use_id : "";
397
+ let id;
398
+ let usage;
399
+ let stop;
400
+ if (event?.type === "message_start") {
401
+ const message = asRecord(event.message);
402
+ id = typeof message?.id === "string" ? message.id : `${thread}#${this.messages.size}`;
403
+ this.current.set(thread, id);
404
+ usage = asRecord(message?.usage);
405
+ } else if (event?.type === "message_delta") {
406
+ id = this.current.get(thread);
407
+ usage = asRecord(event.usage);
408
+ stop = asRecord(event.delta)?.stop_reason;
409
+ }
410
+ if (!id || !usage && stop === void 0) return void 0;
411
+ const reading = { ...this.messages.get(id), ...countsOf(usage) };
412
+ const reason = turnStopReason(stop);
413
+ if (reason && reason !== "completed") reading.stopReason = reason;
414
+ this.messages.set(id, reading);
415
+ return this.total(thread === "" ? reading : void 0);
416
+ }
417
+ /** A whole assistant message with its usage (Claude-shaped `assistant`
418
+ * records). Amp's `--stream-json` reports usage ONLY here -- its `result`
419
+ * carries none -- and Qwen's `message_start` carries none, so without this
420
+ * neither said anything until the turn ended, and Amp never did. Claude
421
+ * sends the same message id on its stream events and again here with a
422
+ * snapshot taken mid-message, so counts merge by the larger value: a
423
+ * snapshot can confirm a count, never lower one. A record with no id (Amp)
424
+ * is a message of its own. */
425
+ assistant(record) {
426
+ const message = asRecord(record.message);
427
+ const usage = asRecord(message?.usage);
428
+ if (!usage) return void 0;
429
+ const thread = typeof record.parent_tool_use_id === "string" ? record.parent_tool_use_id : "";
430
+ const id = typeof message?.id === "string" && message.id ? message.id : `${thread}#assistant-${this.messages.size}`;
431
+ const reading = { ...this.messages.get(id) };
432
+ for (const [key, value] of Object.entries(countsOf(usage))) {
433
+ reading[key] = Math.max(value, reading[key] ?? 0);
434
+ }
435
+ const reason = turnStopReason(message?.stop_reason);
436
+ if (reason && reason !== "completed") reading.stopReason = reason;
437
+ this.messages.set(id, reading);
438
+ this.current.set(thread, id);
439
+ return this.total(thread === "" ? reading : void 0);
440
+ }
441
+ /** One more finished model call, reported whole by a harness that prints
442
+ * it rather than streaming records (Aider's footer). Returns the turn's
443
+ * total so far. */
444
+ add(reading) {
445
+ this.messages.set(`#${this.messages.size}`, reading);
446
+ return this.total(reading);
447
+ }
448
+ /** Fields that arrive a line after the rest of the latest call's reading
449
+ * (Aider prints its cost on its own line when both cache counts appear).
450
+ * Undefined when there is no call to attach them to. */
451
+ amendLatest(fields) {
452
+ const key = [...this.messages.keys()].at(-1);
453
+ if (key === void 0) return void 0;
454
+ const reading = { ...this.messages.get(key), ...fields };
455
+ this.messages.set(key, reading);
456
+ return this.total(reading);
457
+ }
458
+ /** Pi: one finished assistant message, usage and cost complete. */
459
+ finished(message) {
460
+ const usage = asRecord(message?.usage);
461
+ if (message?.role !== "assistant" || !usage) return void 0;
462
+ const reading = countsOf(usage);
463
+ const cost = finiteNumber(asRecord(usage.cost)?.total);
464
+ if (cost !== void 0) reading.costUsd = cost;
465
+ const reason = turnStopReason(message.stopReason);
466
+ if (reason && reason !== "completed") reading.stopReason = reason;
467
+ this.messages.set(`#${this.messages.size}`, reading);
468
+ return this.total(reading);
469
+ }
470
+ total(main) {
471
+ let sum;
472
+ for (const reading of this.messages.values()) {
473
+ const { stopReason: _reason, ...counts } = reading;
474
+ sum = addTurnUsage(sum, counts);
475
+ }
476
+ const result = { ...sum };
477
+ if (main) {
478
+ const used = main.totalTokens ?? (main.input ?? 0) + (main.cacheRead ?? 0) + (main.cacheWrite ?? 0) + (main.output ?? 0);
479
+ if (used > 0) result.contextUsed = used;
480
+ if (main.stopReason) result.stopReason = main.stopReason;
481
+ }
482
+ return result;
483
+ }
484
+ };
485
+ function normalizeTurnUsage(raw) {
486
+ const top = asRecord(raw);
487
+ if (!top) return void 0;
488
+ const result = countsOf(top);
489
+ const assign = assigner(result);
490
+ const cost = asRecord(top.cost);
491
+ const currency = typeof cost?.currency === "string" ? cost.currency.toUpperCase() : "USD";
492
+ const ticks = finiteNumber(top.costUsdTicks, top.cost_usd_ticks, top.total_cost_usd_ticks);
493
+ assign("costUsd", finiteNumber(
494
+ top.totalCostUsd,
495
+ top.total_cost_usd,
496
+ top.costUsd,
497
+ currency === "USD" ? cost?.amount : void 0,
498
+ ticks === void 0 ? void 0 : ticks / 1e10
499
+ ));
500
+ assign("contextWindow", finiteNumber(top.modelContextWindow, top.model_context_window, top.contextWindow, top.size));
501
+ assign("contextUsed", finiteNumber(top.used, top.contextUsed));
502
+ return Object.keys(result).length ? result : void 0;
503
+ }
504
+ function nativeTurnUsage(harness, output) {
505
+ const values = typeof output === "string" ? harness.turn?.output === "json" ? parseJsonDocument(output) : harness.turn?.output === "text" ? [] : parseJsonLines(output).values : output;
506
+ for (let index = values.length - 1; index >= 0; index -= 1) {
507
+ const usage = nativeUsageFromValue(values[index]);
508
+ if (usage) return usage;
509
+ }
510
+ return void 0;
511
+ }
512
+ var OPENING_RECORD = /(?:^|[._-])(?:init|initialized|configured|started|ready|system|session)(?:$|[._-])/i;
513
+ function nativeSelfReportFromValue(value) {
514
+ const record = asRecord(value);
515
+ if (!record) return void 0;
516
+ const type = String(record.type ?? record.method ?? "");
517
+ const subtype = String(record.subtype ?? "");
518
+ if (!OPENING_RECORD.test(type) && !OPENING_RECORD.test(subtype)) return void 0;
519
+ const source = asRecord(record.session) ?? asRecord(record.params) ?? record;
520
+ const report = {};
521
+ const model = source.model ?? source.model_id ?? source.modelId;
522
+ if (typeof model === "string" && model.trim()) report.model = model.trim();
523
+ const mode = source.permissionMode ?? source.permission_mode ?? source.approvalMode ?? source.approval_mode;
524
+ if (typeof mode === "string" && mode.trim()) report.permissionMode = mode.trim();
525
+ const commands = source.slash_commands ?? source.slashCommands ?? source.availableCommands ?? source.available_commands ?? source.commands;
526
+ if (Array.isArray(commands)) {
527
+ const named = commands.flatMap((entry) => {
528
+ if (typeof entry === "string") return entry.trim() ? [{ name: entry.trim().replace(/^\//, "") }] : [];
529
+ const item = asRecord(entry);
530
+ const name = typeof item?.name === "string" ? item.name.trim().replace(/^\//, "") : void 0;
531
+ if (!name) return [];
532
+ const description = typeof item?.description === "string" ? item.description : void 0;
533
+ const hint = asRecord(item?.input)?.hint;
534
+ return [{ name, ...description ? { description } : {}, ...typeof hint === "string" ? { hint } : {} }];
535
+ });
536
+ if (named.length) report.commands = named;
537
+ }
538
+ return Object.keys(report).length ? report : void 0;
539
+ }
540
+ var COUNTED = ["input", "output", "cacheRead", "cacheWrite", "reasoning", "totalTokens", "costUsd"];
541
+ function acpSessionTotals(update) {
542
+ const totals = {};
543
+ const meta = asRecord(update._meta);
544
+ const candidates = meta ? [meta, ...Object.values(meta).flatMap((value) => asRecord(value) ? [asRecord(value)] : [])] : [];
545
+ for (const candidate of candidates) {
546
+ const counts = countsOf(candidate);
547
+ if (counts.input === void 0 && counts.output === void 0) continue;
548
+ Object.assign(totals, counts);
549
+ const cost = finiteNumber(candidate.cost);
550
+ if (cost !== void 0) totals.costUsd = cost;
551
+ break;
552
+ }
553
+ if (update.sessionUpdate === "usage_update") {
554
+ const cost = asRecord(update.cost);
555
+ const currency = typeof cost?.currency === "string" ? cost.currency.toUpperCase() : "USD";
556
+ const amount = currency === "USD" ? finiteNumber(cost?.amount) : void 0;
557
+ if (amount !== void 0) totals.costUsd = amount;
558
+ }
559
+ return Object.keys(totals).length ? totals : void 0;
560
+ }
561
+ function turnShareOf(total, base) {
562
+ const share = {};
563
+ for (const key of COUNTED) {
564
+ const value = total[key];
565
+ if (value !== void 0) share[key] = Math.max(0, value - (base[key] ?? 0));
566
+ }
567
+ return share;
568
+ }
569
+
570
+ // src/harness/transport/background-turn.ts
571
+ var BackgroundTurnChannel = class {
572
+ constructor(transport, reason) {
573
+ this.transport = transport;
574
+ this.reason = reason;
575
+ this.finished = new Promise((resolve) => {
576
+ this.resolveFinished = resolve;
577
+ });
578
+ const forward = (call) => {
579
+ if (this.settled) return;
580
+ if (!this.target) {
581
+ this.queue.push(call);
582
+ return;
583
+ }
584
+ try {
585
+ call(this.target);
586
+ } catch {
587
+ }
588
+ };
589
+ this.observer = {
590
+ onResponseDelta: (text, mode) => {
591
+ this.text = mode === "replace" ? text : this.text + text;
592
+ forward((observer) => observer.onResponseDelta?.(text, mode));
593
+ },
594
+ onActivity: (event) => forward((observer) => observer.onActivity?.(event)),
595
+ onThought: (text, id) => forward((observer) => observer.onThought?.(text, id)),
596
+ onPlan: (entries, explanation) => forward((observer) => observer.onPlan?.(entries, explanation)),
597
+ onUsage: (usage) => forward((observer) => observer.onUsage?.(usage)),
598
+ onNotice: (message) => forward((observer) => observer.onNotice?.(message)),
599
+ onBackgroundWork: (work2) => forward((observer) => observer.onBackgroundWork?.(work2)),
600
+ onPhase: (phase) => forward((observer) => observer.onPhase?.(phase)),
601
+ onRateLimits: (limits) => forward((observer) => observer.onRateLimits?.(limits)),
602
+ onAvailableCommands: (commands) => forward((observer) => observer.onAvailableCommands?.(commands)),
603
+ // A vendor turn nobody is watching yet still gets its answer once the
604
+ // owner attaches; an owner with no approval surface refuses.
605
+ onApproval: (title, detail, preview, signal, callId) => new Promise((resolve) => {
606
+ if (this.settled || signal?.aborted) return resolve(false);
607
+ const ask = (observer) => {
608
+ const answer = observer.onApproval?.(title, detail, preview, signal, callId);
609
+ if (!answer) return resolve(false);
610
+ answer.then((accepted) => resolve(accepted === true), () => resolve(false));
611
+ };
612
+ if (this.target) return ask(this.target);
613
+ this.unanswered.add(resolve);
614
+ signal?.addEventListener("abort", () => {
615
+ if (this.unanswered.delete(resolve)) resolve(false);
616
+ }, { once: true });
617
+ this.queue.push((observer) => {
618
+ if (this.unanswered.delete(resolve)) ask(observer);
619
+ });
620
+ }),
621
+ // The same hold as an approval: asked once the owner attaches, and
622
+ // cancelled if it never does or has no question surface.
623
+ onQuestion: (request, signal) => new Promise((resolve) => {
624
+ if (this.settled || signal?.aborted) return resolve(CANCELLED);
625
+ const ask = (observer) => {
626
+ const answer = observer.onQuestion?.(request, signal);
627
+ if (!answer) {
628
+ observer.onNotice?.(`A question was declined because this screen cannot show it: ${request.title}`);
629
+ return resolve(CANCELLED);
630
+ }
631
+ answer.then(resolve, () => resolve(CANCELLED));
632
+ };
633
+ if (this.target) return ask(this.target);
634
+ const cancel = () => resolve(CANCELLED);
635
+ this.unansweredQuestions.add(cancel);
636
+ signal?.addEventListener("abort", () => {
637
+ if (this.unansweredQuestions.delete(cancel)) cancel();
638
+ }, { once: true });
639
+ this.queue.push((observer) => {
640
+ if (this.unansweredQuestions.delete(cancel)) ask(observer);
641
+ });
642
+ })
643
+ };
644
+ }
645
+ transport;
646
+ reason;
647
+ finished;
648
+ /** What the transport reports into. Never throws into the transport. */
649
+ observer;
650
+ target;
651
+ queue = [];
652
+ text = "";
653
+ settled = false;
654
+ /** Approvals asked before the owner attached, refused if it never does. */
655
+ unanswered = /* @__PURE__ */ new Set();
656
+ unansweredQuestions = /* @__PURE__ */ new Set();
657
+ resolveFinished;
658
+ get done() {
659
+ return this.settled;
660
+ }
661
+ attach(observer) {
662
+ if (this.target) return;
663
+ this.target = observer;
664
+ for (const call of this.queue.splice(0)) {
665
+ try {
666
+ call(observer);
667
+ } catch {
668
+ }
669
+ }
670
+ }
671
+ finish(ended) {
672
+ if (this.settled) return;
673
+ this.settled = true;
674
+ for (const refuse of this.unanswered) refuse(false);
675
+ this.unanswered.clear();
676
+ for (const cancel of this.unansweredQuestions) cancel();
677
+ this.unansweredQuestions.clear();
678
+ this.resolveFinished({ text: this.text, ended });
679
+ }
680
+ };
681
+
682
+ // src/harness/transport/background-work.ts
683
+ var BackgroundWorkTracker = class {
684
+ constructor(onEnded, items = []) {
685
+ this.onEnded = onEnded;
686
+ for (const item of items) this.start(item);
687
+ }
688
+ onEnded;
689
+ items = /* @__PURE__ */ new Map();
690
+ /** The level last reported; undefined when it holds nothing. */
691
+ level;
692
+ /** False when it was already running (kept as it was). */
693
+ start(item) {
694
+ if (this.items.has(item.id)) return false;
695
+ this.items.set(item.id, item);
696
+ return true;
697
+ }
698
+ /** It leaves the set; undefined when it was not running. */
699
+ end(id) {
700
+ const item = this.items.get(id);
701
+ this.items.delete(id);
702
+ return item;
703
+ }
704
+ endAll(kind) {
705
+ const ended = this.running(kind);
706
+ for (const item of ended) this.items.delete(item.id);
707
+ return ended;
708
+ }
709
+ told(ended) {
710
+ this.onEnded?.(ended);
711
+ }
712
+ replaceLevel(update) {
713
+ this.level = mergeBackgroundWork(this.level, update);
714
+ }
715
+ /** Tell which commands run behind the terminals (their pids and stats); an empty list clears them. */
716
+ setCommands(commands) {
717
+ this.replaceLevel({ commands: commands ?? [] });
718
+ }
719
+ /** The level with every kind named (a zero is "none", not unknown). */
720
+ fullLevel() {
721
+ return { ...this.level, agents: this.level?.agents ?? 0, terminals: this.level?.terminals ?? 0, workflows: this.level?.workflows ?? 0 };
722
+ }
723
+ has(id) {
724
+ return this.items.has(id);
725
+ }
726
+ running(kind) {
727
+ return [...this.items.values()].filter((item) => !kind || item.kind === kind);
728
+ }
729
+ count(kind) {
730
+ return kind ? this.running(kind).length : this.items.size;
731
+ }
732
+ /** Items and level: everything said to be running. */
733
+ total() {
734
+ return (({ agents, terminals, workflows }) => agents + terminals + workflows + this.items.size)(this.fullLevel());
735
+ }
736
+ clear() {
737
+ this.items.clear();
738
+ this.level = void 0;
739
+ }
740
+ };
741
+
742
+ // src/harness/transport/persistent-session.ts
743
+ import { readFile as readFile2 } from "node:fs/promises";
744
+
745
+ // src/harness/transport/background-commands.ts
746
+ import { readFile, readdir, stat } from "node:fs/promises";
747
+ var KEEP_MARK = "clikcode:keep";
748
+ var envMs = (name, fallback) => {
749
+ const value = Number(process.env[name]);
750
+ return Number.isFinite(value) && value > 0 ? value : fallback;
751
+ };
752
+ function commandPolicy() {
753
+ return { maxLifetimeMs: envMs("CLIKCODE_BACKGROUND_MAX_MS", 2 * 36e5), hotMs: envMs("CLIKCODE_BACKGROUND_HOT_MS", 30 * 6e4), hotCpuPercent: 90 };
754
+ }
755
+ function staleVerdict(stats, now, policy = commandPolicy()) {
756
+ if (stats.keep || stats.startedAt === void 0) return void 0;
757
+ const age = now - stats.startedAt;
758
+ const silentSince = Math.max(stats.startedAt, stats.lastOutputAt ?? 0);
759
+ if (age >= policy.maxLifetimeMs) return `ran ${formatAge(age)}, over the ${formatAge(policy.maxLifetimeMs)} limit`;
760
+ if ((stats.cpuPercent ?? 0) > policy.hotCpuPercent && now - silentSince >= policy.hotMs) {
761
+ return `cpu ${Math.round(stats.cpuPercent)}% with no output for ${formatAge(now - silentSince)}`;
762
+ }
763
+ return void 0;
764
+ }
765
+ var TICKS_PER_SECOND = 100;
766
+ async function processTimes(pid) {
767
+ const text = await readFile(`/proc/${pid}/stat`, "utf8").catch(quiet("harness/transport/background-commands"));
768
+ if (!text) return void 0;
769
+ const fields = text.slice(text.lastIndexOf(")") + 2).split(" ");
770
+ const [pgrp, utime, stime, starttime] = [Number(fields[2]), Number(fields[11]), Number(fields[12]), Number(fields[19])];
771
+ return [pgrp, utime, stime, starttime].every(Number.isFinite) ? { startTicks: starttime, cpuTicks: utime + stime, pgrp } : void 0;
772
+ }
773
+ var bootTime;
774
+ async function bootTimeMs() {
775
+ if (bootTime !== void 0) return bootTime;
776
+ const text = await readFile("/proc/stat", "utf8").catch(quiet("harness/transport/background-commands"));
777
+ const seconds = Number(/^btime (\d+)/m.exec(text ?? "")?.[1]);
778
+ return Number.isFinite(seconds) ? bootTime = seconds * 1e3 : void 0;
779
+ }
780
+ var CommandSampler = class {
781
+ last = /* @__PURE__ */ new Map();
782
+ /** `pid` as it is now. Linux only for age and cpu; elsewhere just the label. */
783
+ async sample(pid, extras = {}, now = Date.now(), policy = commandPolicy()) {
784
+ const [times, boot, label, output] = await Promise.all([
785
+ processTimes(pid),
786
+ bootTimeMs(),
787
+ extras.label !== void 0 ? extras.label : commandLine(pid),
788
+ extras.outputFile ?? outputFile(pid)
789
+ ]);
790
+ const text = label ?? "background command";
791
+ const stats = { pid, label: text, ...output ? { outputFile: output } : {} };
792
+ if (times) {
793
+ stats.pgid = times.pgrp;
794
+ if (boot !== void 0) stats.startedAt = boot + times.startTicks / TICKS_PER_SECOND * 1e3;
795
+ const before = this.last.get(pid);
796
+ this.last.set(pid, { at: now, ticks: times.cpuTicks });
797
+ if (before && now > before.at) stats.cpuPercent = Math.max(0, (times.cpuTicks - before.ticks) / TICKS_PER_SECOND / ((now - before.at) / 1e3) * 100);
798
+ else if (stats.startedAt !== void 0 && now > stats.startedAt) stats.cpuPercent = Math.max(0, times.cpuTicks / TICKS_PER_SECOND / ((now - stats.startedAt) / 1e3) * 100);
799
+ }
800
+ if (output) {
801
+ const info = await stat(output).catch(quiet("harness/transport/background-commands"));
802
+ if (info && info.size > 0) stats.lastOutputAt = info.mtimeMs;
803
+ }
804
+ if (text.includes(KEEP_MARK)) stats.keep = true;
805
+ const stale = staleVerdict(stats, now, policy);
806
+ if (stale) stats.stale = stale;
807
+ return stats;
808
+ }
809
+ forget(alive) {
810
+ for (const pid of [...this.last.keys()]) if (!alive.has(pid)) this.last.delete(pid);
811
+ }
812
+ };
813
+ async function descendants(pid) {
814
+ const children = /* @__PURE__ */ new Map();
815
+ const entries = await readdir("/proc").catch(() => []);
816
+ await Promise.all(entries.filter((name) => /^\d+$/.test(name)).map(async (name) => {
817
+ const text = await readFile(`/proc/${name}/stat`, "utf8").catch(quiet("harness/transport/background-commands"));
818
+ if (!text) return;
819
+ const parent = Number(text.slice(text.lastIndexOf(")") + 2).split(" ")[1]);
820
+ if (Number.isFinite(parent)) children.set(parent, [...children.get(parent) ?? [], Number(name)]);
821
+ }));
822
+ const found = [];
823
+ const queue = [pid];
824
+ while (queue.length) for (const child of children.get(queue.shift()) ?? []) if (!found.includes(child)) {
825
+ found.push(child);
826
+ queue.push(child);
827
+ }
828
+ return found;
829
+ }
830
+ async function killCommand(pid, options = {}) {
831
+ const send = options.kill ?? ((target, signal) => {
832
+ process.kill(target, signal);
833
+ });
834
+ if (!Number.isInteger(pid) || pid <= 1 || pid === process.pid || !pidIsAlive(pid)) return { pid, how: "gone", signalled: [] };
835
+ const times = await processTimes(pid);
836
+ const own = times?.pgrp === pid && pid !== options.vendorPgid && pid !== process.pid && times.pgrp !== process.pid;
837
+ const below = await descendants(pid);
838
+ const signalled = [];
839
+ const attempt = (target, signal) => {
840
+ try {
841
+ send(target, signal);
842
+ signalled.push(target);
843
+ return void 0;
844
+ } catch (error2) {
845
+ return error2.code === "ESRCH" ? void 0 : String(error2.message);
846
+ }
847
+ };
848
+ let error;
849
+ if (own) error = attempt(-pid, "SIGTERM");
850
+ for (const child of [pid, ...below].reverse()) error = attempt(child, "SIGTERM") ?? error;
851
+ await sleep(options.graceMs ?? 2e3);
852
+ for (const target of [pid, ...below]) if (pidIsAlive(target)) error = attempt(target, "SIGKILL") ?? error;
853
+ if (own) error = attempt(-pid, "SIGKILL") ?? error;
854
+ return { pid, how: own ? "group" : "tree", signalled, ...error ? { error } : {} };
855
+ }
856
+
857
+ // src/harness/transport/persistent-session.ts
858
+ var RETIRED_POLL_MS = 3e3;
859
+ var ABANDONED_WORK_MS = 24 * 60 * 60 * 1e3;
860
+ var ORPHANED_TOOL_MS = 30 * 1e3;
861
+ var OUTPUT_TAIL_CHARS = 4e3;
862
+ async function outputTail(file) {
863
+ if (!file) return "";
864
+ const text = await readFile2(file, "utf8").catch(() => "");
865
+ return redactSecrets(text.length > OUTPUT_TAIL_CHARS ? `...${text.slice(-OUTPUT_TAIL_CHARS)}` : text);
866
+ }
867
+ var CANCEL_SETTLE_MS = 2e3;
868
+ var SETUP_IDLE_MS = 5 * 6e4;
869
+ var COMMAND_WATCH_MS = 6e4;
870
+ function turnFailure() {
871
+ let fail;
872
+ const failure = new Promise((_, reject) => {
873
+ fail = reject;
874
+ });
875
+ failure.catch(quiet("harness/transport/persistent-session"));
876
+ return { failure, fail };
877
+ }
878
+ async function runOneTurn(session, input) {
879
+ try {
880
+ return await session.runTurn(input);
881
+ } finally {
882
+ void session.close().catch(quiet("harness/transport/persistent-session"));
883
+ }
884
+ }
885
+ var PersistentSession = class {
886
+ constructor(options, label) {
887
+ this.label = label;
888
+ this.spawn = options.spawn ?? ((binary, argv, spawnOptions) => spawnPortable(binary, [...argv], spawnOptions));
889
+ this.onBackgroundTurn = options.backgroundTurns;
890
+ this.outOfTurnRelay = options.outOfTurn;
891
+ this.onWorkEnded = options.workEnded;
892
+ this.setupRequest = { timeoutMs: options.setupIdleMs ?? SETUP_IDLE_MS, idleReset: true };
893
+ this.retiredCeilingMs = options.retiredCeilingMs ?? ABANDONED_WORK_MS;
894
+ this.orphanedToolMs = options.orphanedToolMs ?? ORPHANED_TOOL_MS;
895
+ this.commandWatchMs = options.commandWatchMs ?? COMMAND_WATCH_MS;
896
+ this.policy = options.commandPolicy;
897
+ this.killProcess = options.killProcess;
898
+ }
899
+ label;
900
+ live;
901
+ turn;
902
+ background;
903
+ settling;
904
+ isClosed = false;
905
+ spawn;
906
+ onBackgroundTurn;
907
+ outOfTurnRelay;
908
+ onWorkEnded;
909
+ /** The request options of a setup step (SETUP_IDLE_MS). */
910
+ setupRequest;
911
+ retiredCeilingMs;
912
+ orphanedToolMs;
913
+ /** Set once the conversation has left this process with work still running in it (retire). */
914
+ retirement;
915
+ /** The child's process group when the current turn's prompt went out
916
+ * (promptSent): what was already running -- the vendor, its MCP servers. */
917
+ atPrompt;
918
+ /** The end-of-turn look at what the turn left running (noteLeftRunning), while it is still being
919
+ * taken: a retire or a background-work question right after a turn waits for it, or it would see
920
+ * none of the commands the turn just started. */
921
+ noting;
922
+ /** Processes a turn started and left running after it. Only some are the
923
+ * vendor's background work (a `run_in_background` shell, a dev server):
924
+ * the rest are helpers it started lazily (MCP servers). toolCallWork
925
+ * (process-group.ts) tells them apart. */
926
+ leftRunning = /* @__PURE__ */ new Set();
927
+ sampler = new CommandSampler();
928
+ commandWatchMs;
929
+ policy;
930
+ killProcess;
931
+ commandTimer;
932
+ /** The commands last seen, for a change to be told once. */
933
+ commandsSeen = "";
934
+ /** The commands tool calls left running, by pid, with what each is doing (background-commands.ts). */
935
+ async backgroundCommands() {
936
+ const running = await this.leftCommands();
937
+ const now = Date.now();
938
+ const stats = await Promise.all([...running.values()].map((work2) => this.sampler.sample(Number(work2.id), { label: work2.label, ...work2.outputFile ? { outputFile: work2.outputFile } : {} }, now, this.policy ?? commandPolicy())));
939
+ this.sampler.forget(new Set(stats.map((item) => item.pid)));
940
+ return stats;
941
+ }
942
+ /** Ends background commands by pid -- never by pattern -- and says so in the lifecycle log. */
943
+ async reapCommands(which, reason, only) {
944
+ const vendor = this.live?.pid;
945
+ const reaped = [];
946
+ for (const command of await this.backgroundCommands()) {
947
+ if (which === "stale" && !command.stale) continue;
948
+ if (only && !only(command)) continue;
949
+ const why = which === "stale" ? `${reason}: ${command.stale}` : reason;
950
+ const kill = await killCommand(command.pid, { ...vendor ? { vendorPgid: vendor } : {}, ...this.killProcess ? { kill: this.killProcess } : {} });
951
+ this.leftRunning.delete(command.pid);
952
+ lifecycle("background.reap", { transport: this.label, pid: command.pid, pgid: command.pgid, how: kill.how, signalled: kill.signalled.length, label: command.label.slice(0, 200), reason: why, ...kill.error ? { error: kill.error } : {} });
953
+ reaped.push({ command, reason: why, kill });
954
+ }
955
+ return reaped;
956
+ }
957
+ /** What the commands look like now, told to the transport (commandsChanged) when it changed. */
958
+ commandsChanged(_commands, _reaped) {
959
+ }
960
+ /** Whether the sub-agent that started `command` has ended, so nothing is left to want it (the transport
961
+ * knows its owners; none by default). A command that asked to be kept is not asked about. */
962
+ ownerEnded(_command) {
963
+ return false;
964
+ }
965
+ /** Look at the commands now: those whose owner ended and the stale ones are ended, the rest told. */
966
+ async watchCommands() {
967
+ if (this.isClosed) return;
968
+ const orphaned = await this.reapCommands("all", "the sub-agent that started it ended", (command) => !command.keep && this.ownerEnded(command));
969
+ const reaped = [...orphaned, ...await this.reapCommands("stale", "stale background command")];
970
+ const commands = await this.backgroundCommands();
971
+ const seen = JSON.stringify(commands.map((item) => [item.pid, Math.round(item.cpuPercent ?? 0), item.lastOutputAt, item.stale]));
972
+ if (seen !== this.commandsSeen || reaped.length) {
973
+ this.commandsSeen = seen;
974
+ this.commandsChanged(commands, reaped);
975
+ }
976
+ }
977
+ /** The watch runs while a turn left processes running; it ends itself when there are none. */
978
+ armCommandWatch(firstMs = Math.min(this.commandWatchMs, 5e3)) {
979
+ if (this.commandTimer || this.isClosed || !this.leftRunning.size) return;
980
+ const tick = () => {
981
+ this.commandTimer = void 0;
982
+ void this.watchCommands().catch(quiet("harness/transport/persistent-session")).finally(() => {
983
+ if (!this.isClosed && this.leftRunning.size) {
984
+ this.commandTimer = setTimeout(tick, this.commandWatchMs);
985
+ this.commandTimer.unref?.();
986
+ } else if (this.commandsSeen) {
987
+ this.commandsSeen = "";
988
+ this.commandsChanged([], []);
989
+ }
990
+ });
991
+ };
992
+ this.commandTimer = setTimeout(tick, firstMs);
993
+ this.commandTimer.unref?.();
994
+ }
995
+ /** Where what the vendor says out of turn goes: nowhere once retired -- the conversation is
996
+ * another process's now, and this one's follow-ups are not its words. */
997
+ get relay() {
998
+ return this.retirement ? void 0 : this.outOfTurnRelay;
999
+ }
1000
+ /** Whether the conversation has left this process (retire). */
1001
+ get retired() {
1002
+ return Boolean(this.retirement);
1003
+ }
1004
+ /** What a retired process still runs, by kind. */
1005
+ get retiredWork() {
1006
+ const retirement = this.isClosed ? void 0 : this.retirement;
1007
+ return { agents: retirement?.work.count("agent") ?? 0, terminals: retirement?.work.count("command") ?? 0 };
1008
+ }
1009
+ /** Agents the vendor is running in the background (ACP: Claude's `task_*` frames). */
1010
+ runningAgents() {
1011
+ return [];
1012
+ }
1013
+ /** The commands tool calls left running, one per command (commandRoots), with what they run and
1014
+ * where their output goes. */
1015
+ async leftCommands() {
1016
+ const commands = /* @__PURE__ */ new Map();
1017
+ await this.noting;
1018
+ const root = this.live?.pid;
1019
+ if (this.isClosed || !this.live || this.live.peer.closed || !root || !this.leftRunning.size) return commands;
1020
+ const group = await processGroup(root);
1021
+ for (const pid of this.leftRunning) if (!group.has(pid)) this.leftRunning.delete(pid);
1022
+ for (const pid of commandRoots(group, this.leftRunning, toolCallWork(group, root, this.leftRunning))) {
1023
+ const [label, output] = await Promise.all([commandLine(pid), outputFile(pid)]);
1024
+ commands.set(pid, { id: String(pid), kind: "command", label: label ?? group.get(pid)?.name ?? "background command", ...output ? { outputFile: output } : {} });
1025
+ }
1026
+ return commands;
1027
+ }
1028
+ /** What would be lost by closing this process now. */
1029
+ async runningWork() {
1030
+ return [...(await this.leftCommands()).values(), ...this.runningAgents()];
1031
+ }
1032
+ /** The conversation is leaving this process for another account or provider. Nothing it runs is
1033
+ * waited on, and nothing is killed with it: it takes no more turns and says nothing more into the
1034
+ * conversation, its commands and agents run on, and each one's end goes to `workEnded`. Closed
1035
+ * once nothing is left. False when nothing was running: the caller closes it. */
1036
+ async retire() {
1037
+ if (this.retirement) return true;
1038
+ const root = this.live?.pid;
1039
+ if (this.isClosed || !this.live || this.live.peer.closed || !root) return false;
1040
+ const commands = await this.leftCommands();
1041
+ const agents = this.runningAgents();
1042
+ if (!commands.size && !agents.length) return false;
1043
+ const work2 = new BackgroundWorkTracker((ended) => this.retiredEnded(ended), [...commands.values(), ...agents]);
1044
+ const retirement = { root, peer: this.live.peer, work: work2 };
1045
+ this.retirement = retirement;
1046
+ retirement.peer.keepGroup();
1047
+ lifecycle("vendor.retired", { transport: this.label, commands: commands.size, agents: agents.length });
1048
+ this.finishBackground("superseded");
1049
+ const poll = async () => {
1050
+ if (this.retirement !== retirement) return;
1051
+ const group = await readProcessGroup(retirement.root).catch(quiet("harness/transport/persistent-session"));
1052
+ if (this.retirement !== retirement) return;
1053
+ if (group) {
1054
+ const ended = [];
1055
+ for (const command of work2.running("command")) {
1056
+ if (group.has(Number(command.id))) continue;
1057
+ work2.end(command.id);
1058
+ ended.push({ ...command, outcome: "finished", tail: await outputTail(command.outputFile) });
1059
+ }
1060
+ work2.told(ended);
1061
+ }
1062
+ if (this.retirement === retirement && work2.count("command")) retirement.timer = setTimeout(() => void poll(), RETIRED_POLL_MS);
1063
+ };
1064
+ if (commands.size) retirement.timer = setTimeout(() => void poll(), RETIRED_POLL_MS);
1065
+ retirement.ceiling = setTimeout(() => void this.retiredCeiling(retirement), this.retiredCeilingMs);
1066
+ retirement.ceiling.unref?.();
1067
+ return true;
1068
+ }
1069
+ /** Retired work still running at the ceiling (ABANDONED_WORK_MS): told as cut off, with what it
1070
+ * wrote so far, and the process and its group closed. */
1071
+ async retiredCeiling(retirement) {
1072
+ if (this.retirement !== retirement || this.isClosed) return;
1073
+ const hours = Math.round(this.retiredCeilingMs / 36e5);
1074
+ const note = `Stopped: it was still running ${hours ? `${hours} hour${hours === 1 ? "" : "s"}` : "a long time"} after the conversation moved on, with nothing waiting on it.`;
1075
+ const commands = retirement.work.endAll("command");
1076
+ const agents = retirement.work.endAll("agent");
1077
+ const ended = [
1078
+ ...await Promise.all(commands.map(async (work2) => {
1079
+ const tail = await outputTail(work2.outputFile);
1080
+ return { ...work2, outcome: "cut-off", tail: tail ? `${tail}
1081
+ ${note}` : note };
1082
+ })),
1083
+ ...agents.map((work2) => ({ ...work2, outcome: "cut-off", tail: note }))
1084
+ ];
1085
+ lifecycle("vendor.retired.ceiling", { transport: this.label, commands: commands.length, agents: agents.length });
1086
+ retirement.work.told(ended);
1087
+ }
1088
+ /** Retired, and the vendor went: its agents went with it, cut off. Its commands are still
1089
+ * looked at -- a command can outlive the process that started it. */
1090
+ retiredVendorGone() {
1091
+ const retirement = this.retirement;
1092
+ if (!retirement?.work.count("agent")) return;
1093
+ retirement.work.told(retirement.work.endAll("agent").map((work2) => ({ ...work2, outcome: "cut-off", tail: "The process running it ended before it finished." })));
1094
+ }
1095
+ /** The child is going while it runs agents (it crashed, was killed, or was replaced for a different model or setting): they go with
1096
+ * it, and the conversation is told each was cut off, with its task, so it can resume them -- as it is for a process the
1097
+ * conversation left (retire). Not a stop the person asked for (Esc), which means "stop", and not a deliberate close, which the
1098
+ * worker answers itself (worker/handed-off-work.ts recordInterruptedAgents). */
1099
+ reportInterruptedAgents(cause) {
1100
+ if (this.isClosed || this.retirement || cause !== void 0 && isTurnCancelled(cause)) return;
1101
+ const agents = this.runningAgents();
1102
+ if (!agents.length) return;
1103
+ lifecycle("vendor.agents.interrupted", { transport: this.label, agents: agents.map((work2) => work2.id).join(",") });
1104
+ this.reportEnded(agents.map((work2) => ({ ...work2, outcome: "cut-off", tail: "The process running it ended before it finished." })), true);
1105
+ }
1106
+ /** Retired: work that ended is told, and the process is closed once nothing is left. */
1107
+ retiredEnded(ended) {
1108
+ const retirement = this.retirement;
1109
+ if (!retirement) return;
1110
+ this.reportEnded(ended, true);
1111
+ if (!retirement.work.count()) {
1112
+ if (retirement.timer) clearTimeout(retirement.timer);
1113
+ if (retirement.ceiling) clearTimeout(retirement.ceiling);
1114
+ void this.close().catch(quiet("harness/transport/persistent-session"));
1115
+ }
1116
+ }
1117
+ reportEnded(ended, retired) {
1118
+ if (!ended.length) return;
1119
+ try {
1120
+ this.onWorkEnded?.(ended, { retired });
1121
+ } catch {
1122
+ }
1123
+ }
1124
+ /** An agent ended. Every end is reported, in or out of the conversation's process: what it means
1125
+ * for the account, and whether the conversation is told, is the ledger's to decide once
1126
+ * (turn/vendor-process.ts), not each transport's. */
1127
+ agentEnded(ended) {
1128
+ const retirement = this.retirement;
1129
+ if (!retirement) return this.reportEnded([ended], false);
1130
+ if (retirement.work.end(ended.id)) retirement.work.told([ended]);
1131
+ }
1132
+ /** The turn in progress fails with `error`, as if the vendor had refused it: the turn's own
1133
+ * failover takes over. False when no turn is running. */
1134
+ failTurn(error) {
1135
+ const turn = this.turn;
1136
+ if (!turn || turn.done) return false;
1137
+ turn.fail(error);
1138
+ return true;
1139
+ }
1140
+ /** The transport is about to send the turn's prompt (awaited first): what
1141
+ * runs in the child's group from here on, and is still running when the
1142
+ * turn ends, is the vendor's background work. */
1143
+ async promptSent() {
1144
+ const pid = this.live?.pid;
1145
+ this.atPrompt = pid ? Promise.resolve(await processGroupMembers(pid).catch(() => /* @__PURE__ */ new Set())) : void 0;
1146
+ }
1147
+ /** Whether the vendor is still doing work between turns: what its
1148
+ * protocol reports still running (Codex items, tools an ACP background
1149
+ * turn follows), or what a tool call left running (toolCallWork) -- never
1150
+ * the vendor's own helpers. The session worker stays up for it
1151
+ * (session-worker.ts) instead of closing the child under it, and reports
1152
+ * it stopped when it must close it. */
1153
+ async backgroundWorkRunning() {
1154
+ if (this.retirement) return this.retirement.work.count() > 0;
1155
+ if (this.isClosed || !this.live || this.live.peer.closed) return false;
1156
+ if (this.pendingCount() > 0) return true;
1157
+ await this.noting;
1158
+ const root = this.live?.pid;
1159
+ if (this.isClosed || !this.live || this.live.peer.closed) return false;
1160
+ if (!this.leftRunning.size || !root) return false;
1161
+ const group = await processGroup(root);
1162
+ for (const pid of this.leftRunning) if (!group.has(pid)) this.leftRunning.delete(pid);
1163
+ return toolCallWork(group, root, this.leftRunning).size > 0;
1164
+ }
1165
+ async noteLeftRunning() {
1166
+ const before = this.atPrompt;
1167
+ this.atPrompt = void 0;
1168
+ const pid = this.live?.pid;
1169
+ if (!before || !pid) return;
1170
+ const [then, now] = await Promise.all([before, processGroupMembers(pid)]);
1171
+ for (const member of now) if (member !== pid && !then.has(member)) this.leftRunning.add(member);
1172
+ this.armCommandWatch(Math.min(this.commandWatchMs, 1e3));
1173
+ }
1174
+ cancel() {
1175
+ if (this.turn) this.cancelTurn(this.turn);
1176
+ }
1177
+ /** The prompts a vendor request has open on the user's screen (an approval,
1178
+ * a question). Each is aborted when the vendor withdraws it, the turn ends
1179
+ * or the child goes: the prompt closes instead of outliving what asked it. */
1180
+ openPrompts = /* @__PURE__ */ new Set();
1181
+ openPrompt() {
1182
+ const controller = new AbortController();
1183
+ this.openPrompts.add(controller);
1184
+ return { signal: controller.signal, abort: () => controller.abort(), release: () => {
1185
+ this.openPrompts.delete(controller);
1186
+ } };
1187
+ }
1188
+ closePrompts() {
1189
+ for (const controller of this.openPrompts) controller.abort();
1190
+ this.openPrompts.clear();
1191
+ }
1192
+ async close() {
1193
+ const retirement = this.retirement;
1194
+ if (retirement?.timer) clearTimeout(retirement.timer);
1195
+ if (retirement?.ceiling) clearTimeout(retirement.ceiling);
1196
+ retirement?.peer.keepGroup(false);
1197
+ this.isClosed = true;
1198
+ if (this.commandTimer) clearTimeout(this.commandTimer);
1199
+ this.commandTimer = void 0;
1200
+ if (this.turn) this.cancelTurn(this.turn);
1201
+ this.finishBackground("closed");
1202
+ this.clearPending();
1203
+ this.releaseSetup?.();
1204
+ if (this.settling) await this.settling;
1205
+ const live = this.live;
1206
+ this.live = void 0;
1207
+ if (!live) return;
1208
+ live.peer.rejectPending(new Error(`${this.label} session closed`));
1209
+ await live.peer.shutdown();
1210
+ }
1211
+ /** Throws unless a turn may start now. `name` labels the errors. */
1212
+ assertIdle(name) {
1213
+ if (this.isClosed || this.retirement) throw new Error(`${name} session is closed`);
1214
+ if (this.turn) throw new Error(`${name} session already has an active turn`);
1215
+ }
1216
+ /** Run `turn` until its flow answers or it fails. `failed` sees every
1217
+ * failure but a cancellation; `ended` runs last, once the turn is done. */
1218
+ async runActive(turn, signal, failure, flow, hooks) {
1219
+ this.finishBackground("superseded");
1220
+ this.turn = turn;
1221
+ const onAbort = () => this.cancelTurn(turn, signal?.reason);
1222
+ signal?.addEventListener("abort", onAbort, { once: true });
1223
+ let succeeded = false;
1224
+ try {
1225
+ if (this.settling) await this.settling;
1226
+ if (signal?.aborted || turn.done) throw turnCancelledError();
1227
+ const running = flow();
1228
+ running.catch(quiet("harness/transport/persistent-session"));
1229
+ const result = await Promise.race([running, failure]);
1230
+ succeeded = true;
1231
+ return result;
1232
+ } catch (error) {
1233
+ const failureError = error instanceof Error ? error : new Error(String(error));
1234
+ if (!isTurnCancelled(failureError)) hooks.failed(failureError);
1235
+ throw failureError;
1236
+ } finally {
1237
+ turn.done = true;
1238
+ this.closePrompts();
1239
+ signal?.removeEventListener("abort", onAbort);
1240
+ if (this.turn === turn) this.turn = void 0;
1241
+ hooks.ended(succeeded);
1242
+ const noting = this.noteLeftRunning().catch(quiet("harness/transport/persistent-session")).finally(() => {
1243
+ if (this.noting === noting) this.noting = void 0;
1244
+ });
1245
+ this.noting = noting;
1246
+ }
1247
+ }
1248
+ cancelTurn(turn, reason) {
1249
+ if (turn.done) return;
1250
+ turn.done = true;
1251
+ this.closePrompts();
1252
+ const live = this.live;
1253
+ const error = turnCancelledError();
1254
+ if (live && !this.interrupt(turn, live)) this.dropLive(error);
1255
+ turn.fail(error);
1256
+ }
1257
+ /** Wait up to CANCEL_SETTLE_MS for `wait` to report the cancelled turn
1258
+ * settled, so the session stays resumable; then kill the child. */
1259
+ settleCancel(live, wait, onTimeout) {
1260
+ this.settling = new Promise((resolve) => {
1261
+ const timer = setTimeout(() => {
1262
+ onTimeout?.();
1263
+ if (this.live === live) this.dropLive(turnCancelledError());
1264
+ resolve();
1265
+ }, CANCEL_SETTLE_MS);
1266
+ wait(() => {
1267
+ clearTimeout(timer);
1268
+ resolve();
1269
+ });
1270
+ }).finally(() => {
1271
+ this.settling = void 0;
1272
+ });
1273
+ }
1274
+ /** Ends the wait on a setup let finish in the background (settleSetup). */
1275
+ releaseSetup;
1276
+ /** Whether a cancelled turn's setup is still finishing in the background. */
1277
+ get setupSettling() {
1278
+ return Boolean(this.releaseSetup);
1279
+ }
1280
+ /** A turn cancelled mid-setup: the setup it started (`setup`, its flow) is left
1281
+ * to finish on the live child -- a multi-minute session load is not thrown away
1282
+ * with the child -- and the next turn waits for it, then starts where it ended.
1283
+ * Bounded by the setup's own idle window; close() stops waiting at once. */
1284
+ settleSetup(setup) {
1285
+ let release;
1286
+ const settled = new Promise((resolve) => {
1287
+ release = resolve;
1288
+ void setup.then(() => resolve(), () => resolve());
1289
+ });
1290
+ this.releaseSetup = release;
1291
+ const settling = settled.finally(() => {
1292
+ if (this.releaseSetup === release) this.releaseSetup = void 0;
1293
+ if (this.settling === settling) this.settling = void 0;
1294
+ });
1295
+ this.settling = settling;
1296
+ }
1297
+ /** Children this session let go of itself: their exit is not the current turn's failure. */
1298
+ dropped = /* @__PURE__ */ new WeakSet();
1299
+ dropLive(error) {
1300
+ const live = this.live;
1301
+ if (!live) return;
1302
+ this.reportInterruptedAgents(error);
1303
+ this.live = void 0;
1304
+ this.dropped.add(live);
1305
+ this.finishBackground("closed");
1306
+ this.clearPending();
1307
+ this.closePrompts();
1308
+ live.peer.rejectPending(error);
1309
+ void live.peer.shutdown();
1310
+ }
1311
+ /** Why a turn failed when its child closed under it. */
1312
+ closedTurnError(_turn, error) {
1313
+ return error;
1314
+ }
1315
+ /** Whether liveFor(`key`) would reuse the running child rather than spawn one. */
1316
+ reusable(key) {
1317
+ return Boolean(this.live && !this.live.peer.closed && this.live.key === key);
1318
+ }
1319
+ /** The live child for `key`, spawning one (and dropping the old one with
1320
+ * `restarted`) when there is none or its key changed. */
1321
+ liveFor(key, restarted, launch, fields) {
1322
+ if (this.live && this.reusable(key)) {
1323
+ markTurn("spawned", { reused: true, transport: this.label });
1324
+ return this.live;
1325
+ }
1326
+ if (this.live) this.dropLive(new Error(restarted));
1327
+ const detached = process.platform !== "win32";
1328
+ const child = this.spawn(launch.binary, launch.argv, {
1329
+ cwd: launch.cwd,
1330
+ env: { ...process.env, ...launch.environment },
1331
+ stdio: ["pipe", "pipe", "pipe"],
1332
+ detached
1333
+ });
1334
+ this.leftRunning.clear();
1335
+ lifecycle("vendor.child.spawn", { transport: this.label, child: child.pid });
1336
+ markTurn("spawned", { reused: false, transport: this.label });
1337
+ child.once("close", (code, signal) => lifecycle("vendor.child.exit", { transport: this.label, child: child.pid, code, signal }));
1338
+ const live = {
1339
+ ...fields,
1340
+ key,
1341
+ ...child.pid ? { pid: child.pid } : {},
1342
+ peer: new JsonRpcPeer(child, {
1343
+ ...launch.peer,
1344
+ detached,
1345
+ // Node says `spawn <binary> ENOENT` for a missing folder and a missing program alike.
1346
+ startFailure: (error) => spawnFailure(error, launch),
1347
+ onClose: (error) => {
1348
+ this.retiredVendorGone();
1349
+ if (this.live === live) {
1350
+ this.reportInterruptedAgents(error);
1351
+ this.live = void 0;
1352
+ this.finishBackground("closed");
1353
+ this.clearPending();
1354
+ }
1355
+ const turn = this.turn;
1356
+ if (turn && !turn.done && !this.dropped.has(live)) turn.fail(this.closedTurnError(turn, error));
1357
+ }
1358
+ })
1359
+ };
1360
+ this.live = live;
1361
+ return live;
1362
+ }
1363
+ /** Open a background turn (`create`) and hand it to the owner, or return
1364
+ * the one already open. Without an owner the vendor's out-of-turn work is
1365
+ * not surfaced. */
1366
+ openBackgroundRun(create) {
1367
+ if (!this.onBackgroundTurn || this.isClosed || this.retirement) return void 0;
1368
+ if (this.settling) return void 0;
1369
+ if (this.background && !this.background.channel.done) return this.background;
1370
+ const run = create();
1371
+ this.background = run;
1372
+ try {
1373
+ this.onBackgroundTurn(run.channel);
1374
+ } catch {
1375
+ }
1376
+ return run;
1377
+ }
1378
+ finishBackground(ended) {
1379
+ const run = this.background;
1380
+ if (!run) return;
1381
+ this.background = void 0;
1382
+ run.channel.finish(ended);
1383
+ }
1384
+ };
1385
+
1386
+ // src/harness/transport/codex-app-server.ts
1387
+ var SHELL = categoryOf("shell");
1388
+ function completedAgentMessageUpdate(streamed, completed) {
1389
+ if (!streamed) return completed ? { text: completed, mode: "append" } : void 0;
1390
+ return completed.startsWith(streamed) && completed.length > streamed.length ? { text: completed.slice(streamed.length), mode: "append" } : void 0;
1391
+ }
1392
+ function codexSteerParams(threadId, turnId, text) {
1393
+ return {
1394
+ threadId,
1395
+ expectedTurnId: turnId,
1396
+ input: [{ type: "text", text, text_elements: [] }]
1397
+ };
1398
+ }
1399
+ function codexCommandText(command) {
1400
+ return (typeof command === "string" || Array.isArray(command)) && command.length ? commandText(command) : void 0;
1401
+ }
1402
+ function codexActivityForItem(item, completed) {
1403
+ const type = String(item.type ?? "");
1404
+ const id = typeof item.id === "string" ? item.id : void 0;
1405
+ const completedKind = item.status === "failed" || item.status === "error" || typeof item.exitCode === "number" && item.exitCode !== 0 || typeof item.exit_code === "number" && item.exit_code !== 0 ? "tool-error" : "tool-done";
1406
+ if (completed && item.status === "declined") {
1407
+ const declined = codexActivityForItem({ ...item, status: "completed" }, false);
1408
+ if (declined && declined.kind !== "thinking") return { ...declined, kind: "tool-error", output: ["declined"] };
1409
+ }
1410
+ if (type === "commandExecution") {
1411
+ const aggregated = completed && typeof item.aggregatedOutput === "string" ? activityOutput(item.aggregatedOutput, { tail: true }) : {};
1412
+ return {
1413
+ kind: completed ? completedKind : "tool-start",
1414
+ label: formatToolRow("shell", codexCommandText(item.command) ?? "command", SHELL.category),
1415
+ ...SHELL,
1416
+ ...id ? { id } : {},
1417
+ ...codexCommandText(item.command) ? { call: toolCall("shell", { command: codexCommandText(item.command), ...typeof item.cwd === "string" ? { cwd: item.cwd } : {} }) } : {},
1418
+ ...aggregated,
1419
+ ...completed ? commandOutcome(item) : {}
1420
+ };
1421
+ }
1422
+ if (type === "fileChange") return { kind: completed ? completedKind : "tool-start", ...fileChangeActivity(item.changes), ...id ? { id } : {} };
1423
+ if (type === "collabAgentToolCall") {
1424
+ const tool = String(item.tool ?? item.name ?? "agent");
1425
+ const detail = typeof item.prompt === "string" ? item.prompt : typeof item.task === "string" ? item.task : typeof item.description === "string" ? item.description : void 0;
1426
+ return {
1427
+ kind: completed ? completedKind : "tool-start",
1428
+ label: formatToolRow("agent", detail ?? tool),
1429
+ agent: true,
1430
+ ...id ? { id } : {}
1431
+ };
1432
+ }
1433
+ if (type === "mcpToolCall" || type === "dynamicToolCall") {
1434
+ const name = typeof item.server === "string" && typeof item.tool === "string" ? `mcp__${item.server}__${item.tool}` : String(item.tool ?? item.server ?? item.name ?? "tool");
1435
+ const args = item.arguments && typeof item.arguments === "object" && !Array.isArray(item.arguments) ? item.arguments : void 0;
1436
+ const classified = categoryOf(name, args, "codex");
1437
+ const error = asRecord(item.error);
1438
+ const failed = completed && (item.success === false || error && typeof error.message === "string");
1439
+ const resultText = [
1440
+ ...Array.isArray(asRecord(item.result)?.content) ? asRecord(item.result).content : [],
1441
+ ...Array.isArray(item.contentItems) ? item.contentItems : []
1442
+ ].flatMap((part) => {
1443
+ const text = asRecord(part)?.text;
1444
+ return typeof text === "string" ? [text] : [];
1445
+ }).join("\n");
1446
+ const said = failed && typeof error?.message === "string" ? error.message : resultText;
1447
+ return {
1448
+ kind: failed ? "tool-error" : completed ? completedKind : "tool-start",
1449
+ label: toolLabel(name, args, classified.category),
1450
+ ...classified,
1451
+ ...id ? { id } : {},
1452
+ call: toolCall(name, args),
1453
+ ...completed && said ? activityOutput(said) : {},
1454
+ ...completed ? commandOutcome(item) : {}
1455
+ };
1456
+ }
1457
+ if (type === "webSearch") {
1458
+ const action = asRecord(item.action);
1459
+ const url = typeof action?.url === "string" ? action.url : void 0;
1460
+ const tool = (action?.type === "openPage" || action?.type === "findInPage") && url ? "web_fetch" : "web_search";
1461
+ const classified = categoryOf(tool);
1462
+ const label = action?.type === "openPage" && url ? formatToolRow(tool, url, classified.category) : action?.type === "findInPage" && url ? formatToolRow(tool, `${typeof action.pattern === "string" ? `"${action.pattern}" in ` : ""}${url}`, classified.category) : formatToolRow(tool, [item.query, action?.query].find((query) => typeof query === "string" && query.trim().length > 0), classified.category);
1463
+ return { kind: completed ? completedKind : "tool-start", label, ...classified, ...id ? { id } : {} };
1464
+ }
1465
+ if (type === "reasoning" && completed) {
1466
+ const summary = Array.isArray(item.summary) ? item.summary.filter((part) => typeof part === "string").join("\n\n") : "";
1467
+ if (summary) return { kind: "thinking", label: thoughtLabel(summary), ...id ? { id } : {} };
1468
+ }
1469
+ return void 0;
1470
+ }
1471
+ function codexTurnUsage(reading, start) {
1472
+ const total = asRecord(reading.total) ?? asRecord(reading.total_token_usage);
1473
+ if (!total) return void 0;
1474
+ const last2 = asRecord(reading.last) ?? asRecord(reading.last_token_usage);
1475
+ const totalCounts = countsOf(total);
1476
+ const lastCounts = countsOf(last2);
1477
+ const baseline = start ?? turnShareOf(totalCounts, lastCounts);
1478
+ const usage = turnShareOf(totalCounts, baseline);
1479
+ const window = reading.modelContextWindow ?? reading.model_context_window;
1480
+ if (typeof window === "number" && window > 0) usage.contextWindow = window;
1481
+ if (lastCounts.totalTokens) usage.contextUsed = lastCounts.totalTokens;
1482
+ return { usage, start: baseline };
1483
+ }
1484
+ function codexPermissionSettings(mode) {
1485
+ return mode === "bypass" ? { approvalPolicy: "never", sandbox: "danger-full-access", approvalsReviewer: "user" } : { approvalPolicy: "on-request", sandbox: "workspace-write", approvalsReviewer: mode === "auto" ? "auto_review" : "user" };
1486
+ }
1487
+ function codexErrorKind(error) {
1488
+ const source = error && typeof error === "object" ? error : { message: String(error ?? "") };
1489
+ const info = source.codexErrorInfo ?? source.codex_error_info ?? source.data ?? "";
1490
+ const text = `${typeof info === "string" ? info : JSON.stringify(info ?? "")} ${String(source.message ?? "")} ${typeof source.stderrTail === "string" ? source.stderrTail : ""}`;
1491
+ const status = /"?http_?status_?code"?\s*[:=]\s*(\d{3})/i.exec(text)?.[1];
1492
+ const statusCode = status ? Number(status) : void 0;
1493
+ if (/subscription:[\w-]*usage-exhausted|usage.?limit|quota (?:exceeded|exhausted|reached)|insufficient.?quota/i.test(text)) {
1494
+ return { errorKind: "quota", ...statusCode ? { statusCode } : {} };
1495
+ }
1496
+ if (statusCode === 401 || statusCode === 403 || /unauthori[sz]ed|authenticat|not logged in|log ?in required|api.?key|\b401\b|\b403\b/i.test(text)) return { errorKind: "auth", statusCode: statusCode ?? 401 };
1497
+ return { errorKind: "other", ...statusCode ? { statusCode } : {} };
1498
+ }
1499
+ function codexAgentEnd(agent, turn) {
1500
+ const work2 = { id: agent.id, kind: "agent", label: agent.label, ...agent.prompt ? { prompt: agent.prompt } : {} };
1501
+ if (turn.status !== "failed" && turn.status !== "interrupted") return { ...work2, outcome: "finished", tail: "" };
1502
+ const error = asRecord(turn.error);
1503
+ const message = typeof error?.message === "string" ? error.message : "";
1504
+ const { errorKind, statusCode } = codexErrorKind(error ?? {});
1505
+ return {
1506
+ ...work2,
1507
+ outcome: "cut-off",
1508
+ tail: message,
1509
+ failure: { vendorError: true, errorKind, ...statusCode ? { statusCode } : {}, ...message ? { text: message } : {} }
1510
+ };
1511
+ }
1512
+ function codexStructuredFields(turnError, error) {
1513
+ const thrown = asRecord(error);
1514
+ const data = asRecord(thrown?.data);
1515
+ const info = turnError?.codexErrorInfo ?? turnError?.codex_error_info ?? data?.codexErrorInfo ?? thrown?.codexErrorInfo;
1516
+ const code = typeof thrown?.rpcCode === "number" ? thrown.rpcCode : void 0;
1517
+ return { ...info !== void 0 && info !== null ? { codexErrorInfo: info } : {}, ...code !== void 0 ? { rpcCode: code } : {} };
1518
+ }
1519
+ function windowPercent(window) {
1520
+ const value = window?.usedPercent ?? window?.used_percent;
1521
+ return typeof value === "number" ? value : void 0;
1522
+ }
1523
+ function windowReset(window) {
1524
+ const value = window?.resetsAt ?? window?.resets_at ?? window?.reset_at;
1525
+ return typeof value === "number" && value > 0 ? value : void 0;
1526
+ }
1527
+ function rateLimitWindows(snapshot) {
1528
+ const buckets = [snapshot];
1529
+ const byId = asRecord(snapshot.rateLimitsByLimitId) ?? asRecord(snapshot.rate_limits_by_limit_id);
1530
+ for (const value of Object.values(byId ?? {})) {
1531
+ const bucket = asRecord(value);
1532
+ if (bucket) buckets.push(bucket);
1533
+ }
1534
+ const windows = [];
1535
+ for (const bucket of buckets) {
1536
+ for (const side of [bucket.primary, bucket.secondary]) {
1537
+ const window = asRecord(side);
1538
+ if (window) windows.push(window);
1539
+ }
1540
+ }
1541
+ return windows;
1542
+ }
1543
+ function codexUsageLimitRefusal(rateLimits) {
1544
+ const snapshot = asRecord(rateLimits);
1545
+ if (!snapshot) return void 0;
1546
+ const windows = rateLimitWindows(snapshot);
1547
+ const spent = windows.filter((item) => (windowPercent(item) ?? 0) >= 100);
1548
+ const reached = snapshot.rateLimitReachedType ?? snapshot.rate_limit_reached_type;
1549
+ const reachedText = typeof reached === "string" ? reached : "";
1550
+ const spendControl = snapshot.spendControlReached === true || snapshot.spend_control_reached === true;
1551
+ const usageClosed = snapshot.ordinaryUsageAllowed === false || snapshot.ordinary_usage_allowed === false;
1552
+ const rateLimited = reachedText === "rate_limit_reached" && !spent.length && !spendControl && !usageClosed;
1553
+ if (!spent.length && !reachedText && !spendControl && !usageClosed) return void 0;
1554
+ const resets = spent.map(windowReset).find((value) => value !== void 0);
1555
+ const when = resets !== void 0 ? new Date(resets < 1e12 ? resets * 1e3 : resets) : void 0;
1556
+ const at = when && !Number.isNaN(when.getTime()) ? ` Try again at ${when.toLocaleString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })}.` : "";
1557
+ if (rateLimited) return { message: `Codex is rate limited.${at}`, codexErrorInfo: "rateLimitExceeded" };
1558
+ return { message: `You've hit your usage limit.${at}`, codexErrorInfo: "usageLimitExceeded" };
1559
+ }
1560
+ function codexSnapshotSaysSomething(snapshot) {
1561
+ const reached = snapshot.rateLimitReachedType ?? snapshot.rate_limit_reached_type;
1562
+ return Boolean(asRecord(snapshot.primary) || asRecord(snapshot.secondary) || asRecord(snapshot.rateLimitsByLimitId) || asRecord(snapshot.rate_limits_by_limit_id) || snapshot.ordinaryUsageAllowed === false || snapshot.ordinary_usage_allowed === false || snapshot.spendControlReached === true || snapshot.spend_control_reached === true || reached !== void 0 && reached !== null && reached !== "");
1563
+ }
1564
+ function codexApprovalDetail(params, item) {
1565
+ const lines = [];
1566
+ const command = codexCommandText(params.command) ?? codexCommandText(item?.command);
1567
+ if (command) lines.push(`$ ${command}`);
1568
+ const cwd = params.cwd ?? item?.cwd;
1569
+ if (typeof cwd === "string" && cwd) lines.push(`cwd: ${cwd}`);
1570
+ const changes = params.changes ?? params.fileChanges ?? item?.changes;
1571
+ const paths = Array.isArray(changes) ? changes.flatMap((change) => typeof change?.path === "string" ? [String(change.path)] : []) : changes && typeof changes === "object" ? Object.keys(changes) : [];
1572
+ lines.push(...paths.slice(0, 8), ...paths.length > 8 ? [`... ${paths.length - 8} more files`] : []);
1573
+ if (typeof params.grantRoot === "string" && params.grantRoot) lines.push(`grants write access to ${params.grantRoot}`);
1574
+ if (typeof params.reason === "string" && params.reason) lines.push(params.reason);
1575
+ return lines.join("\n") || "Codex requested additional permission";
1576
+ }
1577
+ function codexPlanEntries(params) {
1578
+ return Array.isArray(params.plan) ? params.plan.flatMap((entry) => {
1579
+ const step = entry?.step ?? entry?.content;
1580
+ return typeof step === "string" ? [{ content: step, status: String(entry.status ?? "pending") }] : [];
1581
+ }) : [];
1582
+ }
1583
+ var OUTPUT_EMIT_INTERVAL_MS = 150;
1584
+ var OUTPUT_BUFFER_LIMIT = 4e3;
1585
+ var CONTENT_NOTIFICATION = /^(?:item\/|turn\/(?:started|completed|plan\/updated)$)/;
1586
+ function subAgentLabel(path) {
1587
+ const name = typeof path === "string" ? path.split("/").filter(Boolean).pop() : void 0;
1588
+ return name && name !== "root" ? `subagent ${name}` : "subagent";
1589
+ }
1590
+ var SYSTEM_ERROR_WAIT_MS = 1e3;
1591
+ var CodexSessionImpl = class extends PersistentSession {
1592
+ /** Work still running on the vendor's side (background-work.ts): our thread's open tool items
1593
+ * (`item:<id>`) and active sub-agent threads (`agent:<thread id>`); its level, the background terminals. */
1594
+ work = new BackgroundWorkTracker();
1595
+ /** Approval prompts open, by JSON-RPC request id: released by serverRequest/resolved. */
1596
+ openApprovals = /* @__PURE__ */ new Map();
1597
+ /** An open item of a sub-agent's thread -> the sub-agent row it belongs to
1598
+ * (`agent:<thread id>`), so its output progress is a child row too. */
1599
+ childParent = /* @__PURE__ */ new Map();
1600
+ turnCompletedWaiter;
1601
+ /** A native compaction waiting for `thread/compacted`; rejected when the server goes away. */
1602
+ compactWaiter;
1603
+ threadId;
1604
+ lastPermissionMode = "ask";
1605
+ constructor(options) {
1606
+ super(options, "Codex");
1607
+ }
1608
+ async runTurn(input) {
1609
+ this.assertIdle("Codex");
1610
+ this.lastPermissionMode = input.permissionMode;
1611
+ const { failure, fail } = turnFailure();
1612
+ let complete;
1613
+ const completion = new Promise((resolve, reject) => {
1614
+ complete = (error) => error ? reject(error) : resolve();
1615
+ });
1616
+ completion.catch(quiet("harness/transport/codex-app-server"));
1617
+ const turn = {
1618
+ input,
1619
+ observer: input,
1620
+ done: false,
1621
+ lastAgentMessage: "",
1622
+ streamedMessage: "",
1623
+ sawActivity: false,
1624
+ items: /* @__PURE__ */ new Map(),
1625
+ output: /* @__PURE__ */ new Map(),
1626
+ thoughts: /* @__PURE__ */ new Map(),
1627
+ complete,
1628
+ fail
1629
+ };
1630
+ let keepFailedWork = false;
1631
+ if (this.terminalCount) input.onBackgroundWork?.({ terminals: this.terminalCount });
1632
+ return this.runActive(turn, input.signal, failure, () => this.flow(turn, completion), {
1633
+ failed: (error) => {
1634
+ Object.assign(error, error.errorKind ? {} : codexErrorKind(turn.lastError ?? error), codexStructuredFields(turn.lastError, error));
1635
+ keepFailedWork = this.work.count() > 0;
1636
+ if (!keepFailedWork && !error.codexTurnFailed) this.dropLive(error);
1637
+ },
1638
+ ended: (succeeded) => {
1639
+ if (turn.systemErrorTimer) clearTimeout(turn.systemErrorTimer);
1640
+ input.onSteerReady?.(void 0);
1641
+ if (!succeeded && !keepFailedWork) this.terminals.clear();
1642
+ for (const terminal of this.terminals.values()) terminal.background = true;
1643
+ this.announceTerminals(turn);
1644
+ this.live?.peer.rejectPending(new Error("Codex turn ended"), (method) => method !== "turn/interrupt");
1645
+ if (!succeeded && !keepFailedWork) {
1646
+ this.work.endAll();
1647
+ this.settleBackground();
1648
+ } else if (this.work.count() && this.live) {
1649
+ const run = this.openBackground("background-work", void 0, turn.items);
1650
+ if (run && this.terminalCount) run.observer.onBackgroundWork?.({ terminals: this.terminalCount });
1651
+ }
1652
+ }
1653
+ });
1654
+ }
1655
+ async steer(text) {
1656
+ const turn = this.turn;
1657
+ const live = this.live;
1658
+ if (!turn || turn.done || !live || !turn.threadId || !turn.turnId) throw new Error("Codex has no active turn to steer");
1659
+ await live.peer.request("turn/steer", codexSteerParams(turn.threadId, turn.turnId, text));
1660
+ }
1661
+ async readSubagentThread(threadId) {
1662
+ if (!this.live || this.live.peer.closed) return [];
1663
+ const result = await this.live.peer.request("thread/read", { threadId, includeTurns: true }, { timeoutMs: 5e3 });
1664
+ const rows = [];
1665
+ for (const turn of result.thread?.turns ?? []) for (const item of turn.items ?? []) {
1666
+ if (item.type === "userMessage") {
1667
+ const text = (item.content ?? []).filter((part) => part.type === "text").map((part) => part.text ?? "").join("");
1668
+ if (text) rows.push({ kind: "prompt", text });
1669
+ } else if (item.type === "agentMessage" && typeof item.text === "string") rows.push({ kind: "text", text: item.text });
1670
+ else {
1671
+ const event = codexActivityForItem(item, item.status !== "inProgress" && item.status !== "running");
1672
+ if (event) rows.push({ kind: "activity", event });
1673
+ }
1674
+ }
1675
+ return rows;
1676
+ }
1677
+ runningAgents() {
1678
+ return this.work.running("agent").map((agent) => ({ ...agent, kind: "agent" }));
1679
+ }
1680
+ pendingCount() {
1681
+ return this.work.count();
1682
+ }
1683
+ clearPending() {
1684
+ this.work.clear();
1685
+ this.terminals.clear();
1686
+ this.compactWaiter?.fail(new Error("Codex app-server closed before it finished compacting"));
1687
+ }
1688
+ interrupt(turn, live) {
1689
+ if (!turn.threadId || !turn.turnId) return false;
1690
+ this.settleCancel(live, (settled) => {
1691
+ this.turnCompletedWaiter = () => {
1692
+ this.turnCompletedWaiter = void 0;
1693
+ settled();
1694
+ };
1695
+ }, () => {
1696
+ this.turnCompletedWaiter = void 0;
1697
+ });
1698
+ live.peer.request("turn/interrupt", { threadId: turn.threadId, turnId: turn.turnId }, { timeoutMs: CANCEL_SETTLE_MS }).catch(quiet("harness/transport/codex-app-server"));
1699
+ return true;
1700
+ }
1701
+ /** The thread's own error, or a rate-limit snapshot that already says why. */
1702
+ knownFailure(turn) {
1703
+ const thread = turn.lastError;
1704
+ if (typeof thread?.message === "string" && thread.message.trim()) return true;
1705
+ if (thread?.codexErrorInfo !== void 0 || thread?.codex_error_info !== void 0) return true;
1706
+ return codexUsageLimitRefusal(turn.rateLimits) !== void 0;
1707
+ }
1708
+ /** `systemError` ends the thread. When the reason is already here, fail
1709
+ * now. Otherwise Codex still sends the error notification (a usage limit
1710
+ * is that notification, not the status), and failing on the status reported
1711
+ * a system error instead of switching accounts. */
1712
+ noteSystemError(turn) {
1713
+ turn.systemError = true;
1714
+ if (turn.done) return;
1715
+ if (this.knownFailure(turn)) {
1716
+ this.finishSystemError(turn);
1717
+ return;
1718
+ }
1719
+ if (turn.systemErrorTimer) return;
1720
+ turn.systemErrorTimer = setTimeout(() => this.finishSystemError(turn), SYSTEM_ERROR_WAIT_MS);
1721
+ turn.systemErrorTimer.unref?.();
1722
+ }
1723
+ finishSystemError(turn) {
1724
+ if (turn.systemErrorTimer) clearTimeout(turn.systemErrorTimer);
1725
+ turn.systemErrorTimer = void 0;
1726
+ if (turn.done) return;
1727
+ if (this.knownFailure(turn)) turn.complete(this.vendorFailure(turn, "Codex reported a system error on this thread", { codexSystemError: true }));
1728
+ else this.settleSystemError(turn);
1729
+ }
1730
+ /** The error for a thread Codex gave up on or a turn it failed. The words
1731
+ * are the vendor's: the thread's error, else the account's spent-plan
1732
+ * snapshot (usage limit), else `fallback`. The structured `codexErrorInfo`
1733
+ * travels beside them, and the child's stderr tail (where a 401 is printed)
1734
+ * rides as `stderrTail` for the failover classifier -- never in the message. */
1735
+ vendorFailure(target, fallback, flags) {
1736
+ const thread = target.lastError;
1737
+ const refusal = codexUsageLimitRefusal(target.rateLimits);
1738
+ const text = typeof thread?.message === "string" && thread.message ? thread.message : refusal?.message ?? fallback;
1739
+ const stderrTail = this.live?.peer.failureDetail();
1740
+ const info = thread?.codexErrorInfo ?? thread?.codex_error_info ?? refusal?.codexErrorInfo;
1741
+ const error = Object.assign(new Error(text), flags, info !== void 0 ? { codexErrorInfo: info } : {}, stderrTail ? { stderrTail } : {});
1742
+ return Object.assign(error, codexErrorKind(error));
1743
+ }
1744
+ /** Codex gave up on the thread. It says why right after -- `error`, then turn/completed with the same
1745
+ * error ("You've hit your usage limit", `usageLimitExceeded`) -- but a turn/completed may never follow.
1746
+ * Its messages come in order, so the answer to a request sent now comes after everything it said before
1747
+ * reading it: the turn ends on the vendor's own reason if it gave one, else as a system error. The
1748
+ * request is the account's rate limits, so a spent plan is told even when no reason came. */
1749
+ settleSystemError(turn) {
1750
+ const peer = this.live?.peer;
1751
+ const end = () => {
1752
+ if (turn.done || turn !== this.turn || !turn.systemError) return;
1753
+ turn.complete(this.vendorFailure(turn, "Codex reported a system error on this thread", { codexSystemError: true }));
1754
+ };
1755
+ if (!peer) return end();
1756
+ peer.request("account/rateLimits/read", void 0, { timeoutMs: CANCEL_SETTLE_MS }).then((answer) => {
1757
+ const read = asRecord(asRecord(answer)?.rateLimits);
1758
+ if (read && codexSnapshotSaysSomething(read)) turn.rateLimits = read;
1759
+ }, () => void 0).finally(end);
1760
+ }
1761
+ closedTurnError(turn, error) {
1762
+ return typeof turn.lastError?.message === "string" ? new Error(turn.lastError.message) : error;
1763
+ }
1764
+ /** Open a background turn for the vendor's out-of-turn work. */
1765
+ openBackground(reason, vendorTurnId, items) {
1766
+ return this.openBackgroundRun(() => {
1767
+ const channel = new BackgroundTurnChannel("codex-app-server", reason);
1768
+ return {
1769
+ channel,
1770
+ observer: channel.observer,
1771
+ lastAgentMessage: "",
1772
+ streamedMessage: "",
1773
+ sawActivity: false,
1774
+ items: new Map([...items ?? []].filter(([id]) => this.work.has(`item:${id}`))),
1775
+ output: /* @__PURE__ */ new Map(),
1776
+ thoughts: /* @__PURE__ */ new Map(),
1777
+ ...vendorTurnId ? { vendorTurnId } : {}
1778
+ };
1779
+ });
1780
+ }
1781
+ /** Unified-exec processes (commandExecution items with source
1782
+ * `unifiedExecStartup`, app-server schema v2) by item id. One is a
1783
+ * BACKGROUND terminal -- Codex's own word -- once it has outlived the
1784
+ * model's wait for it: the model came back to it (an
1785
+ * `item/commandExecution/terminalInteraction`, Codex's "Waiting for
1786
+ * background terminal"), or the turn ended with it still running. Every
1787
+ * Codex command is a unified-exec process, so counting from its start would
1788
+ * make the indicator flash for each `ls`. */
1789
+ terminals = /* @__PURE__ */ new Map();
1790
+ get terminalCount() {
1791
+ return this.work.fullLevel().terminals;
1792
+ }
1793
+ trackTerminals(target, method, params) {
1794
+ if (method === "item/started" || method === "item/completed") {
1795
+ const item = params.item ?? {};
1796
+ if (item.type !== "commandExecution" || item.source !== "unifiedExecStartup" || typeof item.id !== "string") return;
1797
+ if (method === "item/completed") this.terminals.delete(item.id);
1798
+ else if (!this.terminals.has(item.id)) this.terminals.set(item.id, { ...typeof item.processId === "string" ? { processId: item.processId } : {}, background: false });
1799
+ } else if (method === "item/commandExecution/terminalInteraction") {
1800
+ const itemId = typeof params.itemId === "string" ? params.itemId : void 0;
1801
+ const processId = typeof params.processId === "string" ? params.processId : void 0;
1802
+ for (const [id, terminal] of this.terminals) {
1803
+ if (id === itemId || processId !== void 0 && terminal.processId === processId) terminal.background = true;
1804
+ }
1805
+ } else return;
1806
+ this.announceTerminals(target);
1807
+ }
1808
+ /** Tells `target` the number of background terminals when it changed. */
1809
+ announceTerminals(target) {
1810
+ const count2 = [...this.terminals.values()].filter((terminal) => terminal.background).length;
1811
+ if (count2 === this.terminalCount) return;
1812
+ this.work.replaceLevel({ terminals: count2 });
1813
+ target?.observer.onBackgroundWork?.({ terminals: count2 });
1814
+ }
1815
+ settleBackground() {
1816
+ const run = this.background;
1817
+ if (run && !run.vendorTurnId && this.work.count() === 0) this.finishBackground("completed");
1818
+ }
1819
+ async ensureLive(input, threadKey) {
1820
+ const key = JSON.stringify([input.binary, input.cwd, input.environment ?? {}, threadKey]);
1821
+ const mcp = this.reusable(key) ? { args: [], env: {} } : codexMcpLaunch(await globalMcpServers("codex", input.mcpProfile), { ...process.env, ...input.environment });
1822
+ return this.liveFor(key, "Codex app-server restarted", {
1823
+ name: "Codex",
1824
+ binary: input.binary,
1825
+ argv: ["app-server", "--stdio", ...mcp.args],
1826
+ cwd: input.cwd,
1827
+ environment: { ...input.environment, ...mcp.env },
1828
+ peer: {
1829
+ label: "Codex app-server",
1830
+ jsonrpcVersion: false,
1831
+ onRequest: (method, params, id) => this.serverRequest(method, params, id),
1832
+ onNotification: (method, params) => this.notification(method, params)
1833
+ }
1834
+ }, { initialized: false });
1835
+ }
1836
+ async flow(turn, completion) {
1837
+ const { input } = turn;
1838
+ const settings = codexPermissionSettings(input.permissionMode);
1839
+ const overrides = { ...input.configOverrides ? { config: input.configOverrides } : {}, ...input.extraThreadParams ?? {} };
1840
+ const live = await this.ensureLive(input, JSON.stringify(overrides));
1841
+ const { peer } = live;
1842
+ const setup = this.setupRequest;
1843
+ const stillRunning = () => {
1844
+ if (turn.done) throw turnCancelledError();
1845
+ };
1846
+ if (!live.initialized) {
1847
+ await peer.request("initialize", { clientInfo: { name: "clikcode", title: "ClikCode", version: "1" }, capabilities: { experimentalApi: false, requestAttestation: false } }, setup);
1848
+ peer.notify("initialized");
1849
+ live.initialized = true;
1850
+ stillRunning();
1851
+ }
1852
+ if (!live.modelsListed && input.onSessionModels) {
1853
+ live.modelsListed = true;
1854
+ void listCodexModels(peer).then((models) => {
1855
+ if (models.length) input.onSessionModels?.({ models: { availableModels: models.map((m) => ({ modelId: m.model, name: m.displayName })) } }, true);
1856
+ }).catch(quiet("harness/transport/codex-app-server"));
1857
+ }
1858
+ if (input.initializeOnly) return { text: "", nativeSessionId: input.nativeSessionId ?? "" };
1859
+ const wanted = input.nativeSessionId ?? this.threadId;
1860
+ if (!wanted || live.threadId !== wanted) {
1861
+ const params = { cwd: input.cwd, model: input.model ?? null, ...settings, ...overrides };
1862
+ const threadResult = wanted ? await peer.request("thread/resume", { threadId: wanted, excludeTurns: true, ...params }, setup) : await peer.request("thread/start", params, setup);
1863
+ stillRunning();
1864
+ const thread = threadResult.thread ?? {};
1865
+ const threadId2 = String(thread.id ?? wanted ?? "");
1866
+ if (!threadId2) throw new Error("Codex app-server did not return a thread id");
1867
+ live.threadId = threadId2;
1868
+ }
1869
+ const threadId = live.threadId;
1870
+ turn.threadId = threadId;
1871
+ this.threadId = threadId;
1872
+ if (input.prepareOnly) return { text: "", nativeSessionId: threadId };
1873
+ await input.onSessionId?.(threadId);
1874
+ if (input.compact) {
1875
+ const compacted = new Promise((resolve, reject) => {
1876
+ this.compactWaiter = { done: resolve, fail: reject };
1877
+ });
1878
+ compacted.catch(quiet("harness/transport/codex-app-server"));
1879
+ try {
1880
+ markTurn("prompt-sent");
1881
+ await compactCodexThread(peer, threadId);
1882
+ await Promise.race([compacted, completion]);
1883
+ } finally {
1884
+ this.compactWaiter = void 0;
1885
+ }
1886
+ return { text: "", nativeSessionId: threadId };
1887
+ }
1888
+ stillRunning();
1889
+ markTurn("ready");
1890
+ await this.promptSent();
1891
+ stillRunning();
1892
+ markTurn("prompt-sent");
1893
+ const turnResult = await peer.request("turn/start", codexTurnStartParams({
1894
+ threadId,
1895
+ prompt: input.prompt,
1896
+ images: input.images,
1897
+ cwd: input.cwd,
1898
+ model: input.model,
1899
+ effort: input.effort,
1900
+ permissionMode: input.permissionMode
1901
+ }), {});
1902
+ stillRunning();
1903
+ turn.turnId = String((turnResult.turn ?? {}).id ?? "");
1904
+ if (!turn.turnId) throw new Error("Codex app-server did not return a turn id");
1905
+ input.onSteerReady?.({ offer: async (text2) => {
1906
+ if (this.turn !== turn) throw new Error("Codex turn ended");
1907
+ await this.steer(text2);
1908
+ return true;
1909
+ } });
1910
+ await completion;
1911
+ const text = (turn.lastAgentMessage || turn.streamedMessage).trim();
1912
+ if (!text && !turn.sawActivity) throw new Error("Codex returned no assistant text");
1913
+ return { text, nativeSessionId: threadId };
1914
+ }
1915
+ /** Every ServerRequest of the app-server schema (codex-cli 0.155) answered
1916
+ * with its OWN response shape. A request this client cannot serve is
1917
+ * declined in the schema's terms, never -32601: the vendor waits on it. */
1918
+ serverRequest(method, params, id) {
1919
+ const stream = () => (this.turn && !this.turn.done ? this.turn : void 0) ?? this.background ?? this.openBackground("vendor-turn");
1920
+ const notice = (message) => {
1921
+ stream()?.observer.onNotice?.(message);
1922
+ };
1923
+ switch (method) {
1924
+ case "item/commandExecution/requestApproval":
1925
+ case "item/fileChange/requestApproval":
1926
+ case "item/permissions/requestApproval":
1927
+ case "execCommandApproval":
1928
+ case "applyPatchApproval":
1929
+ return this.approvalRequest(method, params, id);
1930
+ case "item/tool/requestUserInput":
1931
+ return this.userInputRequest(params, id);
1932
+ case "mcpServer/elicitation/request":
1933
+ return this.elicitationRequest(params, id);
1934
+ case "item/tool/call":
1935
+ return Promise.resolve({
1936
+ contentItems: [{ type: "inputText", text: `ClikCode does not provide the client-side tool ${String(params.tool ?? "")}`.trim() }],
1937
+ success: false
1938
+ });
1939
+ case "account/chatgptAuthTokens/refresh":
1940
+ notice("Codex asked ClikCode to refresh its ChatGPT sign-in; sign in again with `codex login`");
1941
+ return Promise.reject(Object.assign(new Error("ClikCode does not manage ChatGPT tokens: run `codex login`"), { errorKind: "auth" }));
1942
+ case "attestation/generate":
1943
+ return Promise.reject(new Error("ClikCode does not provide client attestation"));
1944
+ default:
1945
+ return void 0;
1946
+ }
1947
+ }
1948
+ approvalRequest(method, params, id) {
1949
+ const permissions = method === "item/permissions/requestApproval";
1950
+ const legacy = method === "execCommandApproval" || method === "applyPatchApproval";
1951
+ const answer = (accepted, aborted = false) => {
1952
+ if (permissions) {
1953
+ return accepted ? { permissions: asRecord(params.permissions) ?? {}, scope: "turn" } : { permissions: {} };
1954
+ }
1955
+ return legacy ? { decision: aborted ? "abort" : accepted ? "approved" : "denied" } : { decision: aborted ? "cancel" : accepted ? "accept" : "decline" };
1956
+ };
1957
+ return (async () => {
1958
+ const turn = this.turn && !this.turn.done ? this.turn : void 0;
1959
+ const stream = turn ?? this.background ?? this.openBackground("vendor-turn");
1960
+ if (!stream) return answer(false, true);
1961
+ const readLive = turn?.input.currentPermissionMode;
1962
+ const liveMode = readLive ? await readLive().catch(quiet("harness/transport/codex-app-server")) : void 0;
1963
+ const permissionMode = liveMode ?? turn?.input.permissionMode ?? this.lastPermissionMode;
1964
+ if (permissionMode === "bypass") return answer(true);
1965
+ const fileChange = /fileChange|applyPatch/.test(method);
1966
+ const item = typeof params.itemId === "string" ? stream.items.get(params.itemId) : void 0;
1967
+ let resolvedElsewhere;
1968
+ const elsewhere = new Promise((resolve) => {
1969
+ resolvedElsewhere = () => resolve("elsewhere");
1970
+ });
1971
+ const prompt = this.openPrompt();
1972
+ if (id !== void 0) this.openApprovals.set(String(id), () => {
1973
+ resolvedElsewhere();
1974
+ prompt.abort();
1975
+ });
1976
+ try {
1977
+ const diff = fileChange ? fileChangeActivity(params.changes ?? params.fileChanges ?? item?.changes).diff : void 0;
1978
+ const title = permissions ? "Approve additional permissions" : fileChange ? "Approve file changes" : "Approve command";
1979
+ stream.observer.onPhase?.(`waiting for your approval: ${title}`);
1980
+ const asked = Promise.resolve(stream.observer.onApproval?.(
1981
+ title,
1982
+ codexApprovalDetail(params, item),
1983
+ diff?.length ? { diff } : void 0,
1984
+ prompt.signal,
1985
+ typeof params.itemId === "string" ? params.itemId : void 0
1986
+ ));
1987
+ const outcome = await Promise.race([asked, elsewhere]);
1988
+ if (outcome === "elsewhere") return answer(false, true);
1989
+ return turn?.done ? answer(false, true) : answer(outcome === true);
1990
+ } finally {
1991
+ if (id !== void 0) this.openApprovals.delete(String(id));
1992
+ prompt.release();
1993
+ }
1994
+ })();
1995
+ }
1996
+ /** Puts one question to the user through whichever turn is listening, and
1997
+ * closes the prompt when Codex resolves the request elsewhere or the turn
1998
+ * ends. Never answered for the user, in any permission mode. */
1999
+ async askUser(request, id, declined) {
2000
+ const turn = this.turn && !this.turn.done ? this.turn : void 0;
2001
+ const stream = turn ?? this.background ?? this.openBackground("vendor-turn");
2002
+ if (!stream) return CANCELLED;
2003
+ const prompt = this.openPrompt();
2004
+ if (id !== void 0) this.openApprovals.set(String(id), () => prompt.abort());
2005
+ try {
2006
+ stream.observer.onPhase?.(`waiting for your answer: ${request.title}`);
2007
+ const result = await askHarnessQuestion(stream.observer, request, prompt.signal, declined);
2008
+ return turn?.done ? CANCELLED : result;
2009
+ } finally {
2010
+ if (id !== void 0) this.openApprovals.delete(String(id));
2011
+ prompt.release();
2012
+ }
2013
+ }
2014
+ /** `item/tool/requestUserInput` (ToolRequestUserInputParams): the answers
2015
+ * go back as `{answers: {<question id>: {answers: [...]}}}`. A question left
2016
+ * unanswered is absent; none answered is `{answers: {}}`. */
2017
+ async userInputRequest(params, id) {
2018
+ const asked = Array.isArray(params.questions) ? params.questions : [];
2019
+ const questions = asked.flatMap((entry) => {
2020
+ const q = asRecord(entry);
2021
+ if (!q || typeof q.id !== "string") return [];
2022
+ const options = (Array.isArray(q.options) ? q.options : []).flatMap((option) => {
2023
+ const o = asRecord(option);
2024
+ return o && typeof o.label === "string" ? [{ label: o.label, ...typeof o.description === "string" && o.description ? { description: o.description } : {} }] : [];
2025
+ });
2026
+ return [{
2027
+ id: q.id,
2028
+ ...typeof q.header === "string" && q.header ? { header: q.header } : {},
2029
+ prompt: String(q.question ?? q.header ?? q.id),
2030
+ options,
2031
+ // `isOther`: the user may type an answer beside the options. With no options it is plain text.
2032
+ allowFreeText: q.isOther === true || options.length === 0,
2033
+ ...q.isSecret === true ? { secret: true } : {}
2034
+ }];
2035
+ });
2036
+ if (!questions.length) return { answers: {} };
2037
+ const result = await this.askUser({ title: "Codex asks", questions }, id, "Codex asked a question and it was left unanswered: this screen cannot show it");
2038
+ if (result.kind !== "answered") return { answers: {} };
2039
+ return { answers: Object.fromEntries(Object.entries(result.answers).map(([key, values]) => [key, { answers: [...values] }])) };
2040
+ }
2041
+ /** `mcpServer/elicitation/request` (McpServerElicitationRequestParams): a
2042
+ * form (`form`, `openai/form`, `openaiForm`) or a link (`url`). The answer
2043
+ * is `{action: accept|decline|cancel, content}`. */
2044
+ async elicitationRequest(params, id) {
2045
+ const server = String(params.serverName ?? "").trim();
2046
+ const title = server ? `MCP server ${server} asks` : "An MCP server asks";
2047
+ const message = typeof params.message === "string" ? params.message : "";
2048
+ const declined = `${title} for input and it was declined: this screen cannot show it`;
2049
+ if (params.mode === "url") {
2050
+ const url = typeof params.url === "string" ? params.url : "";
2051
+ const result2 = await this.askUser({
2052
+ title,
2053
+ ...url ? { url } : {},
2054
+ questions: [{ id: "link", prompt: message || "Open this link to continue.", options: [{ label: "Continue (I opened the link)" }, { label: "Decline" }] }]
2055
+ }, id, declined);
2056
+ if (result2.kind !== "answered") return { action: "cancel", content: null };
2057
+ return result2.answers.link?.[0] === "Decline" ? { action: "decline", content: null } : { action: "accept", content: null };
2058
+ }
2059
+ const form = formToQuestions(message, params.requestedSchema, title);
2060
+ if (!form) {
2061
+ const result2 = await this.askUser({ title, questions: [{ id: "ok", prompt: message || title, options: [{ label: "Accept" }, { label: "Decline" }] }] }, id, declined);
2062
+ if (result2.kind !== "answered") return { action: "cancel", content: null };
2063
+ return result2.answers.ok?.[0] === "Decline" ? { action: "decline", content: null } : { action: "accept", content: {} };
2064
+ }
2065
+ const result = await this.askUser(form.request, id, declined);
2066
+ return result.kind === "answered" ? { action: "accept", content: form.content(result.answers) } : { action: "cancel", content: null };
2067
+ }
2068
+ /** Where a notification goes: the user's turn while one runs, otherwise a
2069
+ * background turn -- opened when the vendor starts a turn of its own, or
2070
+ * reports on work a finished turn left running. */
2071
+ targetFor(method, params, ours) {
2072
+ if (this.turn) return this.turn.done ? void 0 : this.turn;
2073
+ const turnId = String((params.turn ?? {}).id ?? "");
2074
+ const vendorTurn = ours && method === "turn/started" && turnId ? turnId : void 0;
2075
+ if (this.background && !this.background.channel.done) {
2076
+ if (vendorTurn) {
2077
+ this.background.vendorTurnId = vendorTurn;
2078
+ this.background.channel.reason = "vendor-turn";
2079
+ }
2080
+ return this.background;
2081
+ }
2082
+ if (vendorTurn) return this.openBackground("vendor-turn", vendorTurn);
2083
+ const childStarted = !ours && method === "turn/started";
2084
+ if ((this.work.count() || childStarted) && CONTENT_NOTIFICATION.test(method)) return this.openBackground("background-work");
2085
+ return void 0;
2086
+ }
2087
+ notification(method, params) {
2088
+ const threadId = typeof params.threadId === "string" ? params.threadId : void 0;
2089
+ const ours = threadId === void 0 || threadId === this.threadId;
2090
+ if (method === "turn/completed" && ours) this.turnCompletedWaiter?.();
2091
+ if (method === "thread/compacted" && ours) this.compactWaiter?.done();
2092
+ const target = this.targetFor(method, params, ours);
2093
+ if (ours) this.trackTerminals(target, method, params);
2094
+ if (!ours) this.otherThread(target, method, params, threadId);
2095
+ else if (target) this.ownThread(target, method, params);
2096
+ else this.bookkeeping(void 0, method, params);
2097
+ this.settleBackground();
2098
+ }
2099
+ /** Pending-work bookkeeping for our own thread, whoever is listening. */
2100
+ bookkeeping(target, method, params) {
2101
+ if (method !== "item/started" && method !== "item/completed") return;
2102
+ const item = params.item ?? {};
2103
+ if (item.type === "subAgentActivity" && typeof item.agentThreadId === "string") {
2104
+ const key2 = `agent:${item.agentThreadId}`;
2105
+ if (item.kind === "started" && method === "item/started") {
2106
+ this.work.start({ id: key2, kind: "agent", label: subAgentLabel(item.agentPath) });
2107
+ target?.observer.onActivity?.({ kind: "tool-start", label: subAgentLabel(item.agentPath), agent: true, id: key2 });
2108
+ } else if (item.kind === "completed" && this.work.end(key2)) {
2109
+ target?.observer.onActivity?.({ kind: "tool-done", label: subAgentLabel(item.agentPath), agent: true, id: key2 });
2110
+ }
2111
+ return;
2112
+ }
2113
+ if (typeof item.id !== "string") return;
2114
+ const key = `item:${item.id}`;
2115
+ if (method === "item/started") {
2116
+ if (codexActivityForItem(item, false)?.kind === "tool-start") {
2117
+ this.work.start({ id: key, kind: "tool", label: String(item.type) });
2118
+ }
2119
+ } else this.work.end(key);
2120
+ }
2121
+ /** A sub-agent thread: one row per sub-agent, open while it works, and its
2122
+ * own tool calls as that row's children (`parentId`). A child's prose and
2123
+ * reasoning are its own: neither is the turn's answer or thought. */
2124
+ otherThread(target, method, params, threadId) {
2125
+ const key = `agent:${threadId}`;
2126
+ if (method === "turn/started") {
2127
+ if (this.work.start({ id: key, kind: "agent", label: "subagent" })) target?.observer.onActivity?.({ kind: "tool-start", label: "subagent", agent: true, id: key });
2128
+ } else if (method === "turn/completed") {
2129
+ const known = this.work.end(key);
2130
+ if (known) {
2131
+ const turn = params.turn ?? {};
2132
+ const failed = turn.status === "failed";
2133
+ target?.observer.onActivity?.({ kind: failed ? "tool-error" : "tool-done", label: known.label, agent: true, id: key });
2134
+ this.agentEnded(codexAgentEnd(known, turn));
2135
+ }
2136
+ } else if (target && (method === "item/started" || method === "item/completed")) {
2137
+ const item = params.item ?? {};
2138
+ const completed = method === "item/completed";
2139
+ if (item.type === "subAgentActivity") {
2140
+ if (typeof item.agentThreadId !== "string") return;
2141
+ const id = `agent:${item.agentThreadId}`;
2142
+ const label = subAgentLabel(item.agentPath);
2143
+ if (item.kind === "started" && !completed) target.observer.onActivity?.({ kind: "tool-start", label, agent: true, id, parentId: key });
2144
+ else if (item.kind === "completed") target.observer.onActivity?.({ kind: "tool-done", label, agent: true, id, parentId: key });
2145
+ return;
2146
+ }
2147
+ if (typeof item.id !== "string") return;
2148
+ if (completed) {
2149
+ this.childParent.delete(item.id);
2150
+ target.items.delete(item.id);
2151
+ target.output.delete(item.id);
2152
+ } else {
2153
+ this.childParent.set(item.id, key);
2154
+ target.items.set(item.id, item);
2155
+ }
2156
+ const activity = codexActivityForItem(item, completed);
2157
+ if (activity && activity.kind !== "thinking") target.observer.onActivity?.({ ...activity, parentId: key });
2158
+ } else if (target && /^item\/(commandExecution|fileChange)\/outputDelta$/.test(method) && typeof params.delta === "string") {
2159
+ this.outputDelta(target, String(params.itemId ?? ""), params.delta);
2160
+ }
2161
+ }
2162
+ ownThread(target, method, params) {
2163
+ const observer = target.observer;
2164
+ this.bookkeeping(target, method, params);
2165
+ if (method === "item/agentMessage/delta" && typeof params.delta === "string") {
2166
+ target.streamedMessage += params.delta;
2167
+ observer.onResponseDelta?.(params.delta);
2168
+ observer.onPhase?.("generating response");
2169
+ } else if (method === "item/started" || method === "item/completed") {
2170
+ const item = params.item ?? {};
2171
+ if (typeof item.id === "string") {
2172
+ if (method === "item/started") target.items.set(item.id, item);
2173
+ else {
2174
+ target.items.delete(item.id);
2175
+ target.output.delete(item.id);
2176
+ target.thoughts.delete(item.id);
2177
+ target.thoughts.delete(`${item.id}:raw`);
2178
+ }
2179
+ }
2180
+ if (item.type === "contextCompaction" && method === "item/completed") this.compacted(target);
2181
+ if (item.type === "agentMessage" && method === "item/started") {
2182
+ if (target.streamedMessage) observer.onResponseDelta?.("\n\n");
2183
+ target.streamedMessage = "";
2184
+ }
2185
+ if (item.type === "agentMessage" && method === "item/completed" && typeof item.text === "string") {
2186
+ target.lastAgentMessage = item.text;
2187
+ const catchup = completedAgentMessageUpdate(target.streamedMessage, item.text);
2188
+ if (catchup) observer.onResponseDelta?.(catchup.text, catchup.mode);
2189
+ target.streamedMessage = item.text;
2190
+ }
2191
+ const activity = codexActivityForItem(item, method === "item/completed");
2192
+ if (activity) {
2193
+ if (activity.kind !== "thinking") target.sawActivity = true;
2194
+ observer.onActivity?.(activity);
2195
+ }
2196
+ } else if (/^item\/(commandExecution|fileChange)\/outputDelta$/.test(method) && typeof params.delta === "string") {
2197
+ this.outputDelta(target, String(params.itemId ?? ""), params.delta);
2198
+ } else if (/^item\/reasoning\/(summaryTextDelta|textDelta)$/.test(method) && typeof params.delta === "string") {
2199
+ const id = `${String(params.itemId ?? "")}${method.endsWith("/textDelta") ? ":raw" : ""}`;
2200
+ const thought = `${target.thoughts.get(id) ?? ""}${params.delta}`;
2201
+ target.thoughts.set(id, thought);
2202
+ observer.onThought?.(thought, id);
2203
+ } else if (method === "item/reasoning/summaryPartAdded") {
2204
+ const id = String(params.itemId ?? "");
2205
+ const thought = target.thoughts.get(id);
2206
+ if (thought) target.thoughts.set(id, `${thought}
2207
+
2208
+ `);
2209
+ } else if (method === "item/fileChange/patchUpdated" && params.changes) {
2210
+ const itemId = String(params.itemId ?? "");
2211
+ if (itemId) {
2212
+ target.sawActivity = true;
2213
+ observer.onActivity?.({ kind: "tool-start", id: itemId, ...fileChangeActivity(params.changes) });
2214
+ }
2215
+ } else if (/^(warning|configWarning|deprecationNotice|guardianWarning)$/.test(method)) {
2216
+ const message = [params.message, params.summary, params.details].find((value) => typeof value === "string" && value.trim().length > 0);
2217
+ if (message && method === "deprecationNotice") lifecycle("vendor.deprecation", { harness: "codex", message: message.trim().slice(0, 300) });
2218
+ else if (message) observer.onNotice?.(`Codex: ${message.trim()}`);
2219
+ } else if (method === "item/mcpToolCall/progress" && typeof params.message === "string") {
2220
+ this.progress(target, String(params.itemId ?? ""), { output: [String(params.message)] });
2221
+ } else if (method === "turn/diff/updated") {
2222
+ } else if (method === "model/rerouted") {
2223
+ const reason = typeof params.reason === "string" ? ` (${params.reason})` : "";
2224
+ observer.onNotice?.(`Codex moved this turn from ${String(params.fromModel ?? "the chosen model")} to ${String(params.toModel ?? "another model")}${reason}`);
2225
+ } else if (method === "thread/compacted") {
2226
+ this.compacted(target);
2227
+ } else if (method === "turn/plan/updated") {
2228
+ observer.onPlan?.(codexPlanEntries(params), typeof params.explanation === "string" ? params.explanation : void 0);
2229
+ } else if (/token_?usage|token_count/i.test(method)) {
2230
+ const reading = asRecord(params.tokenUsage) ?? asRecord(params.token_usage) ?? asRecord(params.info);
2231
+ const turnUsage = reading ? codexTurnUsage(reading, target.usageStart) : void 0;
2232
+ if (turnUsage) {
2233
+ target.usageStart = turnUsage.start;
2234
+ observer.onUsage?.(turnUsage.usage);
2235
+ }
2236
+ } else if (method === "account/rateLimits/updated") {
2237
+ const snapshot = asRecord(params.rateLimits) ?? asRecord(params.rate_limits);
2238
+ if (snapshot) {
2239
+ const merged = {
2240
+ ...snapshot,
2241
+ ...params.ordinaryUsageAllowed !== void 0 ? { ordinaryUsageAllowed: params.ordinaryUsageAllowed } : {},
2242
+ ...params.ordinary_usage_allowed !== void 0 ? { ordinaryUsageAllowed: params.ordinary_usage_allowed } : {},
2243
+ ...params.rateLimitsByLimitId !== void 0 ? { rateLimitsByLimitId: params.rateLimitsByLimitId } : {},
2244
+ ...params.rate_limits_by_limit_id !== void 0 ? { rateLimitsByLimitId: params.rate_limits_by_limit_id } : {}
2245
+ };
2246
+ if (codexSnapshotSaysSomething(merged)) target.rateLimits = merged;
2247
+ }
2248
+ observer.onRateLimits?.(params.rateLimits ?? params.rate_limits);
2249
+ } else if (method === "turn/completed") {
2250
+ const completedTurn = params.turn ?? {};
2251
+ if (target === this.background) {
2252
+ if (completedTurn.id === this.background.vendorTurnId) delete this.background.vendorTurnId;
2253
+ return;
2254
+ }
2255
+ const turn = target;
2256
+ if (turn.turnId && completedTurn.id !== void 0 && completedTurn.id !== turn.turnId) return;
2257
+ if (completedTurn.status === "failed" || turn.systemError) {
2258
+ const error = completedTurn.error ?? turn.lastError;
2259
+ if (error) turn.lastError = error;
2260
+ if (turn.systemError) {
2261
+ if (this.knownFailure(turn)) return this.finishSystemError(turn);
2262
+ if (turn.systemErrorTimer) clearTimeout(turn.systemErrorTimer);
2263
+ turn.systemErrorTimer = void 0;
2264
+ return this.settleSystemError(turn);
2265
+ }
2266
+ return turn.complete(this.vendorFailure(turn, "Codex turn failed", { codexTurnFailed: true }));
2267
+ }
2268
+ if (completedTurn.status === "interrupted") return turn.complete(turnCancelledError());
2269
+ const stopReason = turnStopReason(completedTurn.status);
2270
+ if (stopReason) observer.onUsage?.({ stopReason });
2271
+ turn.complete();
2272
+ } else if (method === "serverRequest/resolved") {
2273
+ const id = String(asRecord(params)?.requestId ?? "");
2274
+ this.openApprovals.get(id)?.();
2275
+ } else if (method === "thread/status/changed") {
2276
+ const status = asRecord(params.status);
2277
+ if (status?.type === "systemError" && target === this.turn) {
2278
+ this.noteSystemError(target);
2279
+ } else if (Array.isArray(status?.activeFlags) && status.activeFlags.includes("waitingOnUserInput")) observer.onPhase?.("waiting for input in Codex");
2280
+ } else if (method === "item/autoApprovalReview/started" || method === "autoApprovalReview/strictReviewRequired") {
2281
+ observer.onPhase?.("reviewing an approval");
2282
+ } else if (method === "mcpServer/startupStatus/updated") {
2283
+ const name = typeof params.name === "string" ? params.name : typeof params.serverName === "string" ? params.serverName : "";
2284
+ observer.onPhase?.(`starting MCP server${name ? ` ${name}` : ""}`);
2285
+ } else if (method === "model/verification") {
2286
+ observer.onPhase?.("verifying the model");
2287
+ } else if (method === "modelProvider/authRecoveryStarted") {
2288
+ observer.onPhase?.("refreshing sign-in");
2289
+ } else if (method === "item/autoApprovalReview/completed" || method === "modelProvider/authRecoveryCompleted") {
2290
+ } else if (method === "error") {
2291
+ const error = params.error ?? {};
2292
+ if (params.willRetry === true) {
2293
+ observer.onPhase?.(typeof error.message === "string" && error.message ? `retrying: ${error.message.split("\n")[0].slice(0, 120)}` : "retrying");
2294
+ if (target === this.turn) {
2295
+ const active = target;
2296
+ if (active.systemErrorTimer) clearTimeout(active.systemErrorTimer);
2297
+ active.systemErrorTimer = void 0;
2298
+ active.systemError = false;
2299
+ }
2300
+ } else if (typeof error.message === "string" || error.codexErrorInfo !== void 0 || error.codex_error_info !== void 0) {
2301
+ target.lastError = error;
2302
+ if (target === this.turn && target.systemError) this.finishSystemError(target);
2303
+ }
2304
+ }
2305
+ }
2306
+ /** Live command output. Rate-limited per item: every consumer of activity
2307
+ * events persists or repaints, and a build can emit thousands of deltas. */
2308
+ outputDelta(target, itemId, delta) {
2309
+ if (!itemId) return;
2310
+ const entry = target.output.get(itemId) ?? { text: "", emittedAt: 0 };
2311
+ const text = `${entry.text}${delta}`;
2312
+ if (text.length > OUTPUT_BUFFER_LIMIT) entry.cut = true;
2313
+ entry.text = text.slice(-OUTPUT_BUFFER_LIMIT);
2314
+ target.output.set(itemId, entry);
2315
+ const now = Date.now();
2316
+ if (now - entry.emittedAt < OUTPUT_EMIT_INTERVAL_MS) return;
2317
+ entry.emittedAt = now;
2318
+ const { outputHead, ...output } = activityOutput(entry.text, { tail: true });
2319
+ this.progress(target, itemId, entry.cut || !outputHead ? output : { ...output, outputHead });
2320
+ }
2321
+ /** What a running item has to show so far, on its own row. */
2322
+ progress(target, itemId, output) {
2323
+ if (!itemId) return;
2324
+ const item = target.items.get(itemId);
2325
+ const activity = item ? codexActivityForItem(item, false) : void 0;
2326
+ target.sawActivity = true;
2327
+ target.observer.onActivity?.({
2328
+ kind: "tool-start",
2329
+ label: activity?.label ?? "command",
2330
+ id: itemId,
2331
+ ...output,
2332
+ ...activity?.category ? { category: activity.category } : {},
2333
+ ...activity?.agent ? { agent: activity.agent } : {},
2334
+ ...this.childParent.has(itemId) ? { parentId: this.childParent.get(itemId) } : {}
2335
+ });
2336
+ }
2337
+ /** The conversation was compacted to fit the model's window: the model now
2338
+ * works from a summary of what came before. Said once per turn. */
2339
+ compacted(target) {
2340
+ if (target.compacted) return;
2341
+ target.compacted = true;
2342
+ target.observer.onNotice?.(COMPACTED);
2343
+ }
2344
+ };
2345
+ function createCodexSession(options = {}) {
2346
+ return new CodexSessionImpl(options);
2347
+ }
2348
+ function runCodexAppServerTurn(input, options = {}) {
2349
+ return runOneTurn(createCodexSession(options), input);
2350
+ }
2351
+
2352
+ // src/harness/transport/acp-client.ts
2353
+ import { readFile as readFile4 } from "node:fs/promises";
2354
+
2355
+ // src/harness/transport/silent-refusal.ts
2356
+ import { readdir as readdir2, readFile as readFile3, stat as stat2 } from "node:fs/promises";
2357
+ import { join } from "node:path";
2358
+ var RECENT_MS = 10 * 6e4;
2359
+ function refusalFromLog(text, pattern) {
2360
+ const matches = [...text.matchAll(new RegExp(pattern, "g"))];
2361
+ const raw = matches.at(-1)?.[1];
2362
+ if (!raw) return void 0;
2363
+ const said = raw.replace(/\\n/g, " ").replace(/\\(["\\/])/g, "$1").replace(/\s+/g, " ").trim();
2364
+ return said || void 0;
2365
+ }
2366
+ async function silentRefusalReason(command, environment, now = Date.now()) {
2367
+ const spec = localHarnessForCommand(command)?.acp?.silentRefusalLog;
2368
+ if (!spec) return void 0;
2369
+ try {
2370
+ const dir = expandAuthPath(spec.dir, { ...process.env, ...environment });
2371
+ const logs = (await readdir2(dir)).filter((name) => /^log-.*\.log$/.test(name));
2372
+ const dated = await Promise.all(logs.map(async (name) => ({ name, at: (await stat2(join(dir, name))).mtimeMs })));
2373
+ const newest = dated.sort((left, right) => right.at - left.at)[0];
2374
+ if (!newest || now - newest.at > RECENT_MS) return void 0;
2375
+ return refusalFromLog(await readFile3(join(dir, newest.name), "utf8"), spec.pattern);
2376
+ } catch {
2377
+ return void 0;
2378
+ }
2379
+ }
2380
+
2381
+ // src/harness/transport/acp-client.ts
2382
+ import { extname } from "node:path";
2383
+
2384
+ // src/harness/protocol/running-cost.ts
2385
+ function costBase(base, last2, reading, unknownStart) {
2386
+ if (last2 === void 0) return base ?? (unknownStart ? reading : 0);
2387
+ if (reading < last2) return 0;
2388
+ return base ?? 0;
2389
+ }
2390
+ var ProcessCost = class {
2391
+ constructor(unknownStart = false) {
2392
+ this.unknownStart = unknownStart;
2393
+ }
2394
+ unknownStart;
2395
+ base;
2396
+ last;
2397
+ /** The turn's cost so far, given the process's running total. */
2398
+ note(reading) {
2399
+ this.base = costBase(this.base, this.last, reading, this.unknownStart);
2400
+ this.last = reading;
2401
+ return Math.max(0, reading - this.base);
2402
+ }
2403
+ };
2404
+
2405
+ // src/harness/transport/rust-panic.ts
2406
+ function panicMessage(stderr) {
2407
+ const plain = stripAnsi(stderr);
2408
+ if (!/The application panicked|thread '[^']*' panicked at/.test(plain)) return void 0;
2409
+ const message = /Message:\s*([^\n]*)\n/.exec(plain) ?? /panicked at [^\n]*:\n([^\n]+)\n/.exec(plain);
2410
+ return message ? message[1].trim() || "it panicked" : void 0;
2411
+ }
2412
+
2413
+ // src/harness/events/background-agent-rows.ts
2414
+ var count = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
2415
+ var BackgroundAgentRows = class {
2416
+ /** Held rows by the launching call's id, with the label the call had. */
2417
+ held = /* @__PURE__ */ new Map();
2418
+ calls = /* @__PURE__ */ new Map();
2419
+ get size() {
2420
+ return this.held.size;
2421
+ }
2422
+ running() {
2423
+ return [...this.held].map(([id, row]) => ({ id, label: row.label ?? "Background agent" }));
2424
+ }
2425
+ /** An agent the vendor says it launched from call `id` (ACP `subagent_spawned`). */
2426
+ launched(id) {
2427
+ if (!this.held.has(id)) this.held.set(id, {});
2428
+ }
2429
+ /** That agent ended in `state` (ACP `subagent_state_update`: completed, failed, cancelled, disconnected). */
2430
+ ended(id, state) {
2431
+ const row = this.held.get(id);
2432
+ if (!row) return [];
2433
+ this.held.delete(id);
2434
+ this.calls.delete(id);
2435
+ const stopped = state === "cancelled" || state === "disconnected";
2436
+ return [{
2437
+ kind: state === "completed" ? "tool-done" : "tool-error",
2438
+ label: row.label ?? "tool",
2439
+ agent: true,
2440
+ id,
2441
+ ...row.agentId ? { agentId: row.agentId } : {},
2442
+ ...stopped ? { stopped: true } : {}
2443
+ }];
2444
+ }
2445
+ /** The activity as it should be shown: the launch call's completion is withheld (undefined). */
2446
+ filter(event, result) {
2447
+ if (event.agent && event.id && event.kind === "tool-start") this.calls.set(event.id, event.label);
2448
+ const launch = event.id && !event.parentId ? this.launchResult(event.id, result) : void 0;
2449
+ if (launch) event = { ...event, ...launch, output: void 0 };
2450
+ const row = event.id ? this.held.get(event.id) : void 0;
2451
+ if (!row) {
2452
+ if (event.id && event.kind !== "tool-start") this.calls.delete(event.id);
2453
+ return event;
2454
+ }
2455
+ if (event.agent && event.label !== "tool") row.label = event.label;
2456
+ return event.kind === "tool-start" ? { ...event, ...row.agentId ? { agentId: row.agentId } : {} } : void 0;
2457
+ }
2458
+ /** A successful async launch is also an authoritative call -> task link.
2459
+ * Some SDK versions omit task_started's optional background flag; others
2460
+ * return the launch before that notification. Never match agents by label. */
2461
+ launchResult(id, result) {
2462
+ if (!this.calls.has(id) && !this.held.has(id)) return void 0;
2463
+ const value = asRecord(result);
2464
+ const text = typeof result === "string" ? result : Array.isArray(result) ? result.flatMap((part) => {
2465
+ const block = asRecord(part);
2466
+ return block?.type === "text" && typeof block.text === "string" ? [block.text] : [];
2467
+ }).join("\n") : "";
2468
+ const agentId = value?.status === "async_launched" && typeof value.agentId === "string" ? value.agentId : /^Async agent launched successfully\./.test(text) ? /^agentId:\s*([\w-]+)\b/m.exec(text)?.[1] : void 0;
2469
+ if (!agentId) return void 0;
2470
+ if (this.held.get(id)?.agentId === agentId) return void 0;
2471
+ const row = { label: this.calls.get(id), ...this.held.get(id), agentId };
2472
+ this.held.set(id, row);
2473
+ return { kind: "tool-start", id, agent: true, agentId };
2474
+ }
2475
+ /** What one `system` record changes: the row's progress or end. */
2476
+ frame(record) {
2477
+ if (record.type === "user" && !record.parent_tool_use_id) {
2478
+ const content = asRecord(record.message)?.content;
2479
+ return (Array.isArray(content) ? content : []).flatMap((part) => {
2480
+ const result = asRecord(part);
2481
+ if (result?.type !== "tool_result" || result.is_error || typeof result.tool_use_id !== "string") return [];
2482
+ const launch = this.launchResult(result.tool_use_id, result.content);
2483
+ return launch ? [{ ...launch, label: this.held.get(result.tool_use_id)?.label ?? "tool" }] : [];
2484
+ });
2485
+ }
2486
+ if (record.type === "assistant" && !record.parent_tool_use_id) {
2487
+ const content = asRecord(record.message)?.content;
2488
+ for (const part of Array.isArray(content) ? content : []) {
2489
+ const call = asRecord(part);
2490
+ if (call?.type === "tool_use" && call.name === "Task" && typeof call.id === "string" && asRecord(call.input)?.mode === "async") this.launched(call.id);
2491
+ }
2492
+ }
2493
+ if (record.type === "system" && record.subtype === "init" && Array.isArray(record.subagents)) {
2494
+ return record.subagents.flatMap((value) => {
2495
+ const agent = asRecord(value);
2496
+ if (typeof agent?.tool_use_id !== "string") return [];
2497
+ const id = agent.tool_use_id;
2498
+ const label = typeof agent.description === "string" ? `Agent ${agent.description}` : "Background agent";
2499
+ this.held.set(id, { label });
2500
+ return [{ kind: "tool-start", id, label, agent: true }];
2501
+ });
2502
+ }
2503
+ if (record.type === "system" && record.subtype === "subagent_finished" && typeof record.tool_use_id === "string") {
2504
+ return this.ended(record.tool_use_id, String(record.status ?? "failed"));
2505
+ }
2506
+ const event = this.read(record);
2507
+ return event ? [event] : [];
2508
+ }
2509
+ read(record) {
2510
+ if (record.type !== "system") return void 0;
2511
+ const id = typeof record.tool_use_id === "string" ? record.tool_use_id : void 0;
2512
+ if (!id) return void 0;
2513
+ if (record.subtype === "task_started") {
2514
+ const type = record.task_type ?? (typeof record.subagent_type === "string" ? "local_agent" : void 0);
2515
+ if (record.is_backgrounded !== true || record.owned_by_subagent === true || type !== "local_agent") return void 0;
2516
+ const agentId = typeof record.task_id === "string" && record.task_id ? record.task_id : void 0;
2517
+ const row2 = { ...this.held.get(id), ...agentId ? { agentId } : {} };
2518
+ this.held.set(id, row2);
2519
+ return agentId ? { kind: "tool-start", label: row2.label ?? "tool", agent: true, id, agentId } : void 0;
2520
+ }
2521
+ const row = this.held.get(id);
2522
+ if (!row || record.subtype !== "task_progress" && record.subtype !== "task_notification") return void 0;
2523
+ const usage = asRecord(record.usage);
2524
+ const spent = {
2525
+ ...row.agentId ? { agentId: row.agentId } : {},
2526
+ ...count(usage?.tool_uses) !== void 0 ? { childTools: count(usage?.tool_uses) } : {},
2527
+ ...count(usage?.total_tokens) !== void 0 ? { childTokens: count(usage?.total_tokens) } : {}
2528
+ };
2529
+ const label = row.label ?? "tool";
2530
+ if (record.subtype === "task_progress") return { kind: "tool-start", label, agent: true, id, ...spent };
2531
+ this.held.delete(id);
2532
+ this.calls.delete(id);
2533
+ const status = String(record.status ?? "completed");
2534
+ const duration = count(usage?.duration_ms);
2535
+ return {
2536
+ kind: status === "completed" ? "tool-done" : "tool-error",
2537
+ label,
2538
+ agent: true,
2539
+ id,
2540
+ ...spent,
2541
+ ...status === "killed" || status === "stopped" ? { stopped: true } : {},
2542
+ ...duration !== void 0 ? { durationMs: duration } : {}
2543
+ };
2544
+ }
2545
+ /** Every row still held, closed: nothing can end them now. */
2546
+ settle(kind, stopped = false) {
2547
+ const events = [...this.held].map(([id, row]) => ({
2548
+ kind,
2549
+ label: row.label ?? "tool",
2550
+ agent: true,
2551
+ id,
2552
+ ...row.agentId ? { agentId: row.agentId } : {},
2553
+ ...stopped ? { stopped: true } : {}
2554
+ }));
2555
+ this.held.clear();
2556
+ this.calls.clear();
2557
+ return events;
2558
+ }
2559
+ };
2560
+
2561
+ // src/harness/transport/handoff-work.ts
2562
+ import { open } from "node:fs/promises";
2563
+ var RESULT_CHARS = 4e3;
2564
+ async function agentTranscriptResult(file) {
2565
+ if (!file) return { tail: "" };
2566
+ const handle = await open(file, "r").catch(quiet("harness/transport/handoff-work"));
2567
+ if (!handle) return { tail: "" };
2568
+ let text;
2569
+ try {
2570
+ const size = (await handle.stat()).size;
2571
+ const buffer = Buffer.alloc(Math.min(size, 4e5));
2572
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, Math.max(0, size - buffer.length));
2573
+ text = buffer.toString("utf8", 0, bytesRead);
2574
+ } finally {
2575
+ await handle.close();
2576
+ }
2577
+ const lines = text.slice(-4e5).split("\n");
2578
+ let lastAssistant = true;
2579
+ let failure;
2580
+ for (let index = lines.length - 1; index >= 0; index--) {
2581
+ let record;
2582
+ try {
2583
+ record = asRecord(JSON.parse(lines[index]));
2584
+ } catch {
2585
+ continue;
2586
+ }
2587
+ const message = asRecord(record?.message);
2588
+ if (record?.type !== "assistant" || !message) continue;
2589
+ const said = Array.isArray(message.content) ? message.content.map((part) => {
2590
+ const item = asRecord(part);
2591
+ return item?.type === "text" && typeof item.text === "string" ? item.text : "";
2592
+ }).join("").trim() : "";
2593
+ const apiError = record.isApiErrorMessage === true || record.error === "rate_limit" || message.model === "<synthetic>";
2594
+ if (lastAssistant && apiError) {
2595
+ failure = { vendorError: true, ...typeof record.error === "string" ? { errorKind: record.error } : {}, ...said ? { text: said } : {} };
2596
+ }
2597
+ lastAssistant = false;
2598
+ if (apiError) continue;
2599
+ if (said) return { tail: redactSecrets(said.length > RESULT_CHARS ? `${said.slice(0, RESULT_CHARS)}...` : said), ...failure ? { failure } : {} };
2600
+ }
2601
+ return { tail: "", ...failure ? { failure } : {} };
2602
+ }
2603
+ var API_ERROR_ENVELOPE = /terminated early due to an API error: ([\s\S]*?)(?: \(error type ([\w-]+)(?:, HTTP (\d{3}))?[^)]*\))?\s*$/;
2604
+ function claudeTaskFailure(status, summary) {
2605
+ if (status === "completed") return void 0;
2606
+ const envelope = API_ERROR_ENVELOPE.exec(summary);
2607
+ if (!envelope) return { vendorError: false, ...summary ? { text: summary } : {} };
2608
+ const [, detail, errorKind, statusCode] = envelope;
2609
+ return {
2610
+ vendorError: true,
2611
+ ...errorKind ? { errorKind } : {},
2612
+ ...statusCode ? { statusCode: Number(statusCode) } : {},
2613
+ ...detail?.trim() ? { text: detail.trim() } : {}
2614
+ };
2615
+ }
2616
+ async function endedAgentWork(work2, status, summary, outputFile2) {
2617
+ const result = await agentTranscriptResult(outputFile2).catch(() => ({ tail: "" }));
2618
+ const noted = claudeTaskFailure(status, summary);
2619
+ const failure = result.failure ? { ...noted?.vendorError ? noted : {}, ...result.failure, ...result.failure.text ? {} : noted?.text ? { text: noted.text } : {} } : noted;
2620
+ return {
2621
+ ...work2,
2622
+ outcome: status === "completed" && !result.failure ? "finished" : "cut-off",
2623
+ tail: result.tail || summary,
2624
+ ...outputFile2 ? { outputFile: outputFile2 } : {},
2625
+ ...failure ? { failure } : {}
2626
+ };
2627
+ }
2628
+ var VendorTasks = class {
2629
+ tasks = new BackgroundWorkTracker();
2630
+ /** Agent prompts from the launching calls, by call id: a `task_started` may not carry one. */
2631
+ prompts = /* @__PURE__ */ new Map();
2632
+ /** A tool call's input: an Agent call's prompt is kept for its task. */
2633
+ call(id, input) {
2634
+ const prompt = asRecord(input)?.prompt;
2635
+ if (!id || typeof prompt !== "string" || !prompt) return;
2636
+ this.prompts.set(id, prompt);
2637
+ if (this.prompts.size > 200) this.prompts.delete(this.prompts.keys().next().value);
2638
+ }
2639
+ /** One `system` record. A task that ended comes back with how. */
2640
+ frame(record) {
2641
+ if (record.type !== "system") return void 0;
2642
+ const id = typeof record.task_id === "string" ? record.task_id : void 0;
2643
+ if (!id) return void 0;
2644
+ if (record.subtype === "task_started") {
2645
+ const call = typeof record.tool_use_id === "string" ? record.tool_use_id : void 0;
2646
+ const type = String(record.task_type ?? (typeof record.subagent_type === "string" ? "local_agent" : ""));
2647
+ if (record.owned_by_subagent === true || type !== "local_agent" && type !== "local_bash") return void 0;
2648
+ const prompt = typeof record.prompt === "string" && record.prompt ? record.prompt : call ? this.prompts.get(call) : void 0;
2649
+ const agent = type === "local_agent";
2650
+ this.tasks.end(id);
2651
+ this.tasks.start({
2652
+ id,
2653
+ kind: agent ? "agent" : "command",
2654
+ label: String(record.description ?? "") || (agent ? "background agent" : "background command"),
2655
+ ...typeof record.session_id === "string" ? { nativeSessionId: record.session_id } : {},
2656
+ ...prompt ? { prompt } : {},
2657
+ background: record.is_backgrounded !== false
2658
+ });
2659
+ return void 0;
2660
+ }
2661
+ if (record.subtype !== "task_notification") return void 0;
2662
+ const task = this.tasks.end(id);
2663
+ if (!task) return void 0;
2664
+ return {
2665
+ work: work(task),
2666
+ status: String(record.status ?? "completed"),
2667
+ summary: typeof record.summary === "string" ? record.summary : "",
2668
+ ...typeof record.output_file === "string" && record.output_file ? { outputFile: record.output_file } : {}
2669
+ };
2670
+ }
2671
+ /** Backgrounded work still running. */
2672
+ running() {
2673
+ return this.tasks.running().filter((task) => task.background).map(work);
2674
+ }
2675
+ clear() {
2676
+ this.tasks.clear();
2677
+ }
2678
+ };
2679
+ var work = ({ background: _background, ...task }) => task;
2680
+
2681
+ // src/harness/protocol/claude-thinking-notice.ts
2682
+ var OTHER_ORG_THINKING_TITLE = "Claude can't use thinking from another organization";
2683
+ var OTHER_ORG_THINKING_BODY = `${OTHER_ORG_THINKING_TITLE}
2684
+ Claude's earlier thinking was written while you were signed in to another organization, so Claude can't use it now. It isn't deleted: resume this session signed in to that organization to use it again. Claude's next responses may be slower and use more tokens because it has to reread this session and generate new thinking. See docs for more: https://platform.claude.com/docs/en/build-with-claude/preserved-thinking`;
2685
+ function withoutOtherOrgThinkingNotice(text) {
2686
+ const notice = `**Warning:** ${OTHER_ORG_THINKING_BODY}`;
2687
+ let at = text.indexOf(notice);
2688
+ while (at >= 0) {
2689
+ const before = text.slice(0, at).replace(/\n{2}$/, "");
2690
+ const after = text.slice(at + notice.length).replace(/^\n{2}/, "");
2691
+ text = before && after ? `${before}
2692
+
2693
+ ${after}` : before + after;
2694
+ at = text.indexOf(notice);
2695
+ }
2696
+ return text;
2697
+ }
2698
+
2699
+ // src/turn/account-evidence.ts
2700
+ function evidenceError(evidence) {
2701
+ const { statusCode, errorKind, rateLimitStatus, text } = evidence;
2702
+ return Object.assign(new Error(text ?? ""), {
2703
+ ...statusCode !== void 0 ? { statusCode } : {},
2704
+ ...errorKind ? { errorKind } : {},
2705
+ ...rateLimitStatus ? { rateLimitStatus } : {}
2706
+ });
2707
+ }
2708
+ function signalsOf(evidence, extra) {
2709
+ return {
2710
+ ...evidence.statusCode !== void 0 ? { statusCode: evidence.statusCode } : {},
2711
+ ...evidence.errorKind ? { errorKind: evidence.errorKind } : {},
2712
+ ...evidence.rateLimitStatus ? { rateLimitStatus: evidence.rateLimitStatus } : {},
2713
+ ...evidence.vendorError !== void 0 ? { isResultError: evidence.vendorError } : {},
2714
+ ...extra.replyErrorPatterns ? { replyErrorPatterns: extra.replyErrorPatterns } : {}
2715
+ };
2716
+ }
2717
+ function classifyEvidence(evidence, extra = {}) {
2718
+ return classifyAccountFailure(evidenceError(evidence), signalsOf(evidence, extra));
2719
+ }
2720
+ function classifyTurnFailure(failure, evidence = {}, extra = {}) {
2721
+ return classifyAccountFailure(failure, signalsOf(evidence, extra));
2722
+ }
2723
+ function isRefusal(words) {
2724
+ return classifyEvidence({ text: words, vendorError: true }) === "quota-exhausted";
2725
+ }
2726
+ var REFUSAL_RESET = /\s*·\s*resets (?:[A-Z][a-z]{2} \d{1,2}, )?\d{1,2}(?::\d{2})?\s?[ap]m(?: \([^)\n]+\))?$/i;
2727
+ function refusalEndingReply(reply) {
2728
+ const text = reply.trimEnd();
2729
+ const reset = REFUSAL_RESET.exec(text);
2730
+ if (!reset) return void 0;
2731
+ const before = text.slice(0, reset.index);
2732
+ const sentence = before.slice(Math.max(before.lastIndexOf("\n"), before.lastIndexOf(". "), before.lastIndexOf(".")) + 1).trim();
2733
+ const refusal = `${sentence}${reset[0]}`.trim();
2734
+ return sentence && isRefusal(refusal) ? refusal : void 0;
2735
+ }
2736
+ function isVendorRefusalSaid(text) {
2737
+ const said = text.trim();
2738
+ return said.length > 0 && said.length < 300 && !said.includes("\n") && isRefusal(said);
2739
+ }
2740
+ var observing = /* @__PURE__ */ new Map();
2741
+ function oneAtATime(accountId, step) {
2742
+ const run = (observing.get(accountId) ?? Promise.resolve()).then(step);
2743
+ observing.set(accountId, run.catch(quiet("turn/account-evidence")));
2744
+ return run;
2745
+ }
2746
+ async function markSpent(accountId, error, source) {
2747
+ const account = (await readState({ transcripts: [] })).accounts.find((item) => item.id === accountId);
2748
+ if (!account || quotaRefusalHolds(account)) return;
2749
+ if (await storeQuotaRefusal(accountId, error)) lifecycle("worker.account-spent", { account: accountId.slice(0, 8), source });
2750
+ }
2751
+ async function moveOff(sessionId, from, harness, why, effects, error) {
2752
+ if (effects.refuseTurn(sessionId, from, error)) return;
2753
+ const state = await readState({ transcripts: [] });
2754
+ const session = state.sessions.find((item) => item.id === sessionId);
2755
+ const current = state.accounts.find((item) => item.id === from);
2756
+ if (!session || !current || session.accountId !== from) return;
2757
+ const to = nextUsableFailoverAccount(state, current, (candidate) => turnBackendForAccount(candidate) === "vendor", /* @__PURE__ */ new Map([[from, Date.now()]]));
2758
+ if (!to) return;
2759
+ const started = Date.now();
2760
+ session.accountId = to.id;
2761
+ await writeState(state);
2762
+ await effects.leave(sessionId, from);
2763
+ lifecycle("worker.switch", { harness: harness ?? session.nativeHarness ?? "unknown", from: from.slice(0, 8), to: to.id.slice(0, 8), why: "quota-exhausted", source: why, recordMs: Date.now() - started });
2764
+ }
2765
+ async function observeAccountHealth(input, effects) {
2766
+ const kind = classifyEvidence(input.evidence);
2767
+ if (kind !== "quota-exhausted") return kind;
2768
+ const error = evidenceError(input.evidence);
2769
+ await oneAtATime(input.accountId, async () => {
2770
+ await markSpent(input.accountId, error, input.source);
2771
+ await moveOff(input.sessionId, input.accountId, input.harness, input.source, effects, error);
2772
+ });
2773
+ return kind;
2774
+ }
2775
+
2776
+ // src/harness/transport/acp-client.ts
2777
+ var READ_LIKE_TOOL_KINDS = /* @__PURE__ */ new Set(["read", "search", "think", "fetch"]);
2778
+ var DETAIL_LINE_CAP = 12;
2779
+ var START_NOTICE_MS = 1e3;
2780
+ var TASK_NOTIFICATION_WAIT_MS = 1e3;
2781
+ var ACP_SESSION_META = {
2782
+ claudeCode: { emitRawSDKMessages: [
2783
+ { type: "system", subtype: "background_tasks_changed" },
2784
+ // A background Agent's own lifecycle: its call completes at launch, and
2785
+ // these say when it really ends (claude-agent-acp acp-agent.js, `task_*`).
2786
+ { type: "system", subtype: "task_started" },
2787
+ { type: "system", subtype: "task_progress" },
2788
+ { type: "system", subtype: "task_notification" },
2789
+ { type: "system", subtype: "task_updated" },
2790
+ // The end of every vendor turn, one the user did not start included: what closes a background turn (vendorTurnEnded).
2791
+ { type: "result" }
2792
+ ] }
2793
+ };
2794
+ var ACP_CLIENT_CAPABILITIES = {
2795
+ _meta: { terminal_output: true },
2796
+ // claude-agent-acp (0.84) sends a vendor warning as a structured `notice`
2797
+ // update when the client advertises `session.notices`, instead of appending
2798
+ // it to the answer as a bold line. Handled in `deliver` (onNotice).
2799
+ // `elicitation.form`: claude-agent-acp turns AskUserQuestion (and an MCP
2800
+ // server's form) into an `elicitation/create` request only when the client
2801
+ // says it can render one; the handler is `elicitation` below, which puts the
2802
+ // form to the user through the observer's question channel. NOT advertised:
2803
+ // the AIR `sessionFailure`/`asyncTasks`/`nativeSubagentSessions` opt-ins,
2804
+ // which need the jetbrains.air identity and replace the raw error text the
2805
+ // failover classifier reads.
2806
+ elicitation: { form: {} },
2807
+ session: { notices: {} }
2808
+ };
2809
+ function acpResponseDelta(update) {
2810
+ return update.sessionUpdate === "agent_message_chunk" && update.content?.type === "text" && typeof update.content.text === "string" ? update.content.text : void 0;
2811
+ }
2812
+ function acpVibeResponseChange(previous, incoming) {
2813
+ if (!previous) return { text: incoming, mode: "append", current: incoming };
2814
+ if (incoming.startsWith(previous)) {
2815
+ const text = incoming.slice(previous.length);
2816
+ return { text, mode: "append", current: incoming };
2817
+ }
2818
+ let sharedPrefix = 0;
2819
+ while (sharedPrefix < previous.length && sharedPrefix < incoming.length && previous[sharedPrefix] === incoming[sharedPrefix]) sharedPrefix++;
2820
+ if (sharedPrefix > 0) return { text: incoming, mode: "replace", current: incoming };
2821
+ return { text: incoming, mode: "append", current: previous + incoming };
2822
+ }
2823
+ function acpMessageChange(previous, incoming, cumulative) {
2824
+ if (cumulative) return acpVibeResponseChange(previous, incoming);
2825
+ return { text: incoming, mode: "append", current: previous + incoming };
2826
+ }
2827
+ function acpThoughtDelta(update) {
2828
+ return update.sessionUpdate === "agent_thought_chunk" && update.content?.type === "text" && typeof update.content.text === "string" ? update.content.text : void 0;
2829
+ }
2830
+ var PARENT_KEYS = ["parentToolUseId", "parentToolCallId", "parent_tool_use_id", "parent_tool_call_id"];
2831
+ function parentIn(record) {
2832
+ if (!record || typeof record !== "object") return void 0;
2833
+ for (const key of PARENT_KEYS) {
2834
+ const value = record[key];
2835
+ if (typeof value === "string" && value) return value;
2836
+ }
2837
+ return void 0;
2838
+ }
2839
+ function acpParentToolId(update) {
2840
+ const meta = update?._meta && typeof update._meta === "object" ? update._meta : void 0;
2841
+ const direct = parentIn(update) ?? parentIn(meta);
2842
+ if (direct || !meta) return direct;
2843
+ for (const namespace of Object.values(meta)) {
2844
+ const nested = parentIn(namespace);
2845
+ if (nested) return nested;
2846
+ }
2847
+ return void 0;
2848
+ }
2849
+ function acpActivityEvent(update) {
2850
+ if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") return void 0;
2851
+ const status = String(update.status);
2852
+ const completed = ["completed", "failed"].includes(status);
2853
+ const content = Array.isArray(update.content) ? update.content : [];
2854
+ const diffEntries = content.filter((entry) => entry?.type === "diff");
2855
+ const fromContent = diffEntries.flatMap((entry) => eventDiff(String(entry.oldText ?? ""), String(entry.newText ?? ""), {
2856
+ ...typeof entry.path === "string" && entry.path ? { path: entry.path } : {},
2857
+ ...typeof entry.oldText === "string" ? {} : { priorUnknown: true }
2858
+ }));
2859
+ const terminal = update._meta && typeof update._meta === "object" ? update._meta : void 0;
2860
+ const terminalText = typeof terminal?.terminal_output?.data === "string" ? terminal.terminal_output.data : void 0;
2861
+ const outputText = terminalText !== void 0 ? terminalText : content.flatMap((entry) => entry?.type === "content" && entry.content?.type === "text" && typeof entry.content.text === "string" ? [entry.content.text] : []).join("\n");
2862
+ const exitCode = terminal?.terminal_exit?.exit_code;
2863
+ const output = activityOutput(outputText, { tail: true });
2864
+ const classified = acpToolClass(update);
2865
+ const rawOutput = update.rawOutput && typeof update.rawOutput === "object" ? update.rawOutput : void 0;
2866
+ const diff = fromContent.length ? fromContent : classified.category === "edit" ? editDiffFromInput(update.rawInput && typeof update.rawInput === "object" ? update.rawInput : void 0) : void 0;
2867
+ return {
2868
+ kind: status === "failed" ? "tool-error" : completed ? "tool-done" : "tool-start",
2869
+ label: acpToolLabel(update, classified),
2870
+ ...classified,
2871
+ ...acpToolCall(update),
2872
+ ...typeof update.toolCallId === "string" ? { id: update.toolCallId } : {},
2873
+ ...acpParentToolId(update) ? { parentId: acpParentToolId(update) } : {},
2874
+ ...output,
2875
+ ...diff?.length ? { diff } : {},
2876
+ ...completed ? commandOutcome(rawOutput) : {},
2877
+ ...typeof exitCode === "number" ? { exitCode } : {}
2878
+ };
2879
+ }
2880
+ function acpToolCall(update) {
2881
+ const raw = update.rawInput && typeof update.rawInput === "object" && !Array.isArray(update.rawInput) ? update.rawInput : void 0;
2882
+ if (!raw || !Object.keys(raw).length) return {};
2883
+ const title = typeof (update.title ?? update.name) === "string" ? String(update.title ?? update.name).trim() : "";
2884
+ const name = typeof update.name === "string" && update.name.trim() || title.split(/[\s:(]/, 1)[0] || String(update.kind ?? "tool");
2885
+ return { call: toolCall(name, raw) };
2886
+ }
2887
+ function acpToolLabel(update, classified) {
2888
+ const raw = update.rawInput && typeof update.rawInput === "object" ? update.rawInput : void 0;
2889
+ const title = typeof (update.title ?? update.name) === "string" ? String(update.title ?? update.name).trim() : "";
2890
+ if (classified.agent) return formatToolRow("agent", typeof raw?.description === "string" ? raw.description : title);
2891
+ const head = title.split(/[\s:(]/, 1)[0] || "tool";
2892
+ const command = classified.category === "run" ? acpCommand(raw)?.trim() : void 0;
2893
+ if (command) return formatToolRow("shell", command, "run");
2894
+ const fromInput = raw ? toolLabel(classified.category === "run" ? "shell" : head, raw, classified.category) : void 0;
2895
+ if (fromInput && fromInput !== formatToolRow(classified.category === "run" ? "shell" : head, void 0, classified.category)) return fromInput;
2896
+ const location = Array.isArray(update.locations) ? update.locations.find((entry) => typeof entry?.path === "string")?.path : void 0;
2897
+ if (location && classified.category && classified.category !== "run") return formatToolRow(head, location, classified.category);
2898
+ return title || "tool";
2899
+ }
2900
+ var ACP_KIND_CATEGORY = {
2901
+ execute: "run",
2902
+ read: "read",
2903
+ edit: "edit",
2904
+ delete: "edit",
2905
+ move: "edit",
2906
+ search: "search",
2907
+ fetch: "fetch"
2908
+ };
2909
+ function acpCommand(raw) {
2910
+ return commandText(raw?.command) ?? (typeof raw?.cmd === "string" ? raw.cmd : void 0);
2911
+ }
2912
+ function acpToolClass(update) {
2913
+ const raw = update.rawInput && typeof update.rawInput === "object" ? update.rawInput : void 0;
2914
+ const titled = String(update.name ?? update.title ?? "");
2915
+ const head = titled.split(/[\s:(]/, 1)[0] || titled;
2916
+ const fromKind = ACP_KIND_CATEGORY[String(update.kind ?? "").toLowerCase()];
2917
+ const category = fromKind ?? (acpCommand(raw)?.trim() ? "run" : categoryOf(head, raw).category);
2918
+ const agent = isAgentToolName(head) || isAgentToolName(String(update.tool ?? "")) || typeof raw?.subagent_type === "string" ? true : void 0;
2919
+ return { ...category ? { category } : {}, ...agent ? { agent } : {} };
2920
+ }
2921
+ function acpPlanEntries(update) {
2922
+ if (update.sessionUpdate !== "plan" || !Array.isArray(update.entries)) return void 0;
2923
+ return update.entries.flatMap((entry) => typeof entry?.content === "string" ? [{ content: entry.content, status: String(entry.status ?? "pending"), ...typeof entry.priority === "string" ? { priority: entry.priority } : {} }] : []);
2924
+ }
2925
+ function acpAvailableCommands(update) {
2926
+ if (update.sessionUpdate !== "available_commands_update" || !Array.isArray(update.availableCommands)) return void 0;
2927
+ return update.availableCommands.flatMap((entry) => typeof entry?.name === "string" ? [{
2928
+ name: entry.name,
2929
+ ...typeof entry.description === "string" ? { description: entry.description } : {},
2930
+ ...typeof entry.input?.hint === "string" ? { hint: entry.input.hint } : {}
2931
+ }] : []);
2932
+ }
2933
+ function acpApprovalDetail(toolCall2) {
2934
+ if (!toolCall2) return void 0;
2935
+ const raw = toolCall2.rawInput && typeof toolCall2.rawInput === "object" ? toolCall2.rawInput : {};
2936
+ const lines = [];
2937
+ const command = acpCommand(raw);
2938
+ if (command) lines.push(`$ ${command}`);
2939
+ if (typeof raw.cwd === "string") lines.push(`cwd: ${raw.cwd}`);
2940
+ const paths = /* @__PURE__ */ new Set();
2941
+ for (const key of ["path", "file_path", "filePath", "abs_path", "url"]) if (typeof raw[key] === "string") paths.add(raw[key]);
2942
+ if (Array.isArray(toolCall2.locations)) {
2943
+ for (const location of toolCall2.locations) if (typeof location?.path === "string") paths.add(location.path);
2944
+ }
2945
+ const content = Array.isArray(toolCall2.content) ? toolCall2.content : [];
2946
+ for (const entry of content) if (entry?.type === "diff" && typeof entry.path === "string") paths.add(entry.path);
2947
+ for (const path of paths) lines.push(path);
2948
+ if (!lines.length) return void 0;
2949
+ return lines.length > DETAIL_LINE_CAP ? [...lines.slice(0, DETAIL_LINE_CAP), "..."].join("\n") : lines.join("\n");
2950
+ }
2951
+ var CURSOR_QUESTION_SKIP_ID = "__ask_question_skip__";
2952
+ function acpQuestionPermission(params) {
2953
+ const options = Array.isArray(params.options) ? params.options : [];
2954
+ const skip = options.find((option) => option?.optionId === CURSOR_QUESTION_SKIP_ID);
2955
+ if (!skip) return void 0;
2956
+ const choices = options.filter((option) => option !== skip && typeof option?.name === "string" && option.optionId !== void 0).map((option) => ({ optionId: String(option.optionId), name: String(option.name) }));
2957
+ return {
2958
+ skipOptionId: CURSOR_QUESTION_SKIP_ID,
2959
+ prompt: String(params.toolCall?.title ?? params.toolCall?.content?.[0]?.content?.text ?? "a question"),
2960
+ answers: choices.map((choice) => choice.name),
2961
+ choices
2962
+ };
2963
+ }
2964
+ function acpPlanChoices(params) {
2965
+ const options = Array.isArray(params.options) ? params.options : [];
2966
+ const choices = options.filter((option) => typeof option?.name === "string" && option.optionId !== void 0).map((option) => ({ optionId: String(option.optionId), name: String(option.name) }));
2967
+ if (!choices.some((choice) => choice.optionId.startsWith("exit-plan-"))) return void 0;
2968
+ const plan = params.toolCall?.rawInput?.plan;
2969
+ return { ...typeof plan === "string" && plan.trim() ? { plan: plan.trim() } : {}, choices };
2970
+ }
2971
+ function acpPermissionPlan(mode, params) {
2972
+ const options = Array.isArray(params.options) ? params.options : [];
2973
+ const kindOf = (option) => String(option?.kind ?? "");
2974
+ const once = options.find((option) => kindOf(option) === "allow_once") ?? options.find((option) => kindOf(option).startsWith("allow") && kindOf(option) !== "allow_always");
2975
+ const always = options.find((option) => kindOf(option) === "allow_always");
2976
+ const reject = options.find((option) => kindOf(option) === "reject_once") ?? options.find((option) => kindOf(option).startsWith("reject") && kindOf(option) !== "reject_always") ?? options.find((option) => kindOf(option).startsWith("reject"));
2977
+ const allowOption = once ?? always;
2978
+ const readLike = READ_LIKE_TOOL_KINDS.has(String(params.toolCall?.kind ?? ""));
2979
+ const automatic = once !== void 0 && (mode === "bypass" || mode === "auto" && readLike);
2980
+ return {
2981
+ action: automatic ? "allow" : "ask",
2982
+ ...allowOption?.optionId !== void 0 ? { allowOptionId: String(allowOption.optionId) } : {},
2983
+ allowIsPersistent: once === void 0 && always !== void 0,
2984
+ ...reject?.optionId !== void 0 ? { rejectOptionId: String(reject.optionId) } : {}
2985
+ };
2986
+ }
2987
+ function vendorBusyNotice(text, afterCancel) {
2988
+ const plain = text.trim().replace(/^[^\w]+/, "");
2989
+ if (/^queued for the next turn\.?(?:\s*\(\d+ queued\))?\.?$/i.test(plain)) return true;
2990
+ return afterCancel && /^(?:stopped|interrupted|cancelled|canceled)\.?$/i.test(plain);
2991
+ }
2992
+ var STARTUP_BANNER = /^\s*(?:\[acp\]|(?:info|debug|trace)\b|.*\bstarting (?:acp|the agent|agent)\b|.*\blistening on\b)/i;
2993
+ var FAILURE_WORDS = /insufficient|balance|credit|quota|limit|unauthori[sz]ed|not logged in|sign.?in|invalid|denied|forbidden|exceeded|rate|billing|payment|\b(?:error|fail(?:ed|ure)?|fatal|panic)\b|\b(?:401|402|403|429)\b/i;
2994
+ function acpFailureMessage(output) {
2995
+ const lines = output.split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !STARTUP_BANNER.test(line));
2996
+ if (!lines.length) return "";
2997
+ const why = lines.findIndex((line) => FAILURE_WORDS.test(line));
2998
+ return (why > 0 ? [lines[why], ...lines.slice(0, why), ...lines.slice(why + 1)] : lines).join("\n");
2999
+ }
3000
+ function acpSpawnArgv(input) {
3001
+ const argv = input.argv;
3002
+ if (!argv) return void 0;
3003
+ const options = [...input.extraArgv ?? []];
3004
+ const placement = input.optionPlacement ?? "before";
3005
+ return placement === "after" ? [...argv, ...options] : [...options, ...argv];
3006
+ }
3007
+ function acpModelChoice(models, model) {
3008
+ const available = Array.isArray(models?.availableModels) ? models.availableModels : [];
3009
+ const ids = available.map((entry) => entry?.modelId).filter((id) => typeof id === "string");
3010
+ if (ids.length === 0 && Array.isArray(models?.configOptions)) {
3011
+ const modelOption = models.configOptions.find((option) => (option?.id ?? option?.configId) === "model");
3012
+ if (Array.isArray(modelOption?.options)) {
3013
+ for (const option of modelOption.options) if (typeof option?.value === "string") ids.push(option.value);
3014
+ }
3015
+ }
3016
+ if (ids.includes(model)) return model;
3017
+ const named = available.filter((entry) => typeof entry?.name === "string" && entry.name.toLowerCase() === model.toLowerCase());
3018
+ if (named.length === 1 && typeof named[0].modelId === "string") return named[0].modelId;
3019
+ const suffixed = ids.filter((id) => id.endsWith(`:${model}`));
3020
+ if (suffixed.length === 1) return suffixed[0];
3021
+ const providerShaped = /^[a-z][a-z0-9_-]*:[^:]/i;
3022
+ return ids.length && ids.every((id) => providerShaped.test(id)) && providerShaped.test(model) ? model : void 0;
3023
+ }
3024
+ var IMAGE_MIME = {
3025
+ ".png": "image/png",
3026
+ ".jpg": "image/jpeg",
3027
+ ".jpeg": "image/jpeg",
3028
+ ".gif": "image/gif",
3029
+ ".webp": "image/webp"
3030
+ };
3031
+ async function acpImageBlock(path) {
3032
+ const data = await readFile4(path);
3033
+ return { type: "image", mimeType: IMAGE_MIME[extname(path).toLowerCase()] ?? "image/png", data: data.toString("base64") };
3034
+ }
3035
+ function acpModeConfigOption(options) {
3036
+ return options?.find((option) => option?.category === "mode") ?? options?.find((option) => (option?.id ?? option?.configId) === "mode");
3037
+ }
3038
+ function acpConfigValues(option) {
3039
+ const entries = Array.isArray(option?.options) ? option.options : [];
3040
+ return entries.flatMap((entry) => Array.isArray(entry?.options) ? entry.options : [entry]).map((entry) => entry?.value).filter((value) => typeof value === "string");
3041
+ }
3042
+ var COMPACTION_SETTLE_MS = 10 * 6e4;
3043
+ var CHILD_SESSION_UPDATES = /* @__PURE__ */ new Set(["tool_call", "tool_call_update", "agent_message_chunk", "agent_thought_chunk"]);
3044
+ var TURN_BOOKKEEPING_UPDATES = /* @__PURE__ */ new Set(["usage_update", "session_info_update"]);
3045
+ var toolRunning = (update) => update.status === "pending" || update.status === "in_progress" || update.status === void 0;
3046
+ var toolSettled = (update) => update.status === "completed" || update.status === "failed";
3047
+ var AcpSessionImpl = class extends PersistentSession {
3048
+ /** What the vendor runs (background-work.ts). Items: tool calls not yet settled, in the turn or
3049
+ * background turn receiving updates. Level: claude-agent-acp's `background_tasks_changed`, kept
3050
+ * between turns (it holds the worker, and its emptying ends the background turn) until the child goes. */
3051
+ work = new BackgroundWorkTracker();
3052
+ /** Background Agent calls: the call completes at launch, the agent runs on
3053
+ * and its row stays open until its own `task_notification` (heldAgentFrame). */
3054
+ heldAgents = new BackgroundAgentRows();
3055
+ /** Claude's background tasks, with each agent's task: what a conversation that moves on has to
3056
+ * answer for (handoff-work.ts). Per vendor process. */
3057
+ vendorTasks = new VendorTasks();
3058
+ sessionId;
3059
+ lastCumulativeChunks = false;
3060
+ /** The agent's out-of-turn message so far, for an agent that re-sends it whole. */
3061
+ relayedMessage = "";
3062
+ /** The live session's running totals as the agent last reported them
3063
+ * (acpSessionTotals, and a prompt response for an agent declaring
3064
+ * `usageTotals: 'session'`). Reset when a session is opened in this
3065
+ * process: an agent that restores its totals on load says so before the
3066
+ * prompt, and one that does not (Hermes) starts again from zero. */
3067
+ sessionTotals = {};
3068
+ /** The live session was loaded, not created, and the vendor may have restored
3069
+ * the cost it had reached before this process (Claude does): the first cost
3070
+ * reading then says where the conversation stands, not what a turn cost.
3071
+ * Per process, like sessionTotals. */
3072
+ costStartUnknown = false;
3073
+ constructor(options) {
3074
+ super(options, "ACP");
3075
+ }
3076
+ /** A background count may change between turns, with no live stream to receive it.
3077
+ * Keep its owner informed even then; otherwise the worker's history row keeps the last count. */
3078
+ reportBackground;
3079
+ backgroundTasks = /* @__PURE__ */ new Map();
3080
+ /** Background shells a sub-agent started (`owned_by_subagent`, or a `parent_task_id`), by task id, with the
3081
+ * agent task that owns it when the wire says which. The shell outlives the agent unless it is ended
3082
+ * (ownerEnded): nothing else wants it. */
3083
+ ownedCommandTasks = /* @__PURE__ */ new Map();
3084
+ async runTurn(input) {
3085
+ this.assertIdle(`${input.command} ACP`);
3086
+ const argv = acpSpawnArgv(input);
3087
+ if (!argv) throw new Error(`${input.command} has no ACP adapter`);
3088
+ this.reportBackground = input.onBackgroundWork;
3089
+ this.lastCumulativeChunks = input.acp?.cumulativeChunks === true;
3090
+ const { failure, fail } = turnFailure();
3091
+ const turn = {
3092
+ input,
3093
+ observer: input,
3094
+ cumulativeChunks: this.lastCumulativeChunks,
3095
+ text: "",
3096
+ messageText: "",
3097
+ sawActivity: false,
3098
+ thoughts: 0,
3099
+ base: {},
3100
+ promptStarted: false,
3101
+ done: false,
3102
+ fail,
3103
+ approvals: 0
3104
+ };
3105
+ this.relayedMessage = "";
3106
+ if (this.work.level) input.onBackgroundWork?.(this.work.fullLevel());
3107
+ return this.runActive(turn, input.signal, failure, () => turn.flowing = this.flow(turn, argv).catch((error) => {
3108
+ if (!error?.acpStaleTurn || turn.done) throw error;
3109
+ Object.assign(turn, { text: "", messageText: "", sawActivity: false, thoughts: 0, promptStarted: false, prompt: void 0, thought: void 0, sessionId: void 0 });
3110
+ return this.flow(turn, argv);
3111
+ }), {
3112
+ failed: (error) => {
3113
+ if (error.code === "ERR_JSONRPC_CLOSED") {
3114
+ const why = acpFailureMessage(error.message);
3115
+ if (why) error.message = why;
3116
+ }
3117
+ if (!this.work.count()) this.dropLive(error);
3118
+ },
3119
+ ended: () => {
3120
+ input.onSteerReady?.(void 0);
3121
+ if (!turn.setupContinues) this.live?.peer.rejectPending(new Error(`${input.command} ACP turn ended`), (method) => method !== "session/prompt");
3122
+ if (!(this.live && (this.work.level || this.work.count()))) for (const event of this.heldAgents.settle("tool-done")) input.onActivity?.(event);
3123
+ if (this.live && (this.work.count() || this.work.level)) {
3124
+ const run = this.openBackground("background-work");
3125
+ if (run) {
3126
+ if (this.work.level) run.observer.onBackgroundWork?.(this.work.fullLevel());
3127
+ this.watchOrphanedTools();
3128
+ return;
3129
+ }
3130
+ }
3131
+ this.clearPending();
3132
+ }
3133
+ });
3134
+ }
3135
+ runningAgents() {
3136
+ return this.vendorTasks.running().filter((work2) => work2.kind === "agent");
3137
+ }
3138
+ clearPending() {
3139
+ if (!this.live) {
3140
+ this.vendorTasks.clear();
3141
+ for (const { timer } of this.endingTasks.values()) clearTimeout(timer);
3142
+ this.endingTasks.clear();
3143
+ }
3144
+ this.work.clear();
3145
+ this.backgroundTasks.clear();
3146
+ this.reportBackground?.(this.work.fullLevel());
3147
+ this.heldAgents.settle("tool-done");
3148
+ }
3149
+ pendingCount() {
3150
+ return (this.background ? this.work.total() : 0) + this.vendorTasks.running().length;
3151
+ }
3152
+ interrupt(turn, live) {
3153
+ const prompt = turn.prompt;
3154
+ if (!prompt || !turn.sessionId) {
3155
+ if (!turn.flowing) return !this.setupSettling;
3156
+ turn.setupContinues = true;
3157
+ this.settleSetup(turn.flowing);
3158
+ return true;
3159
+ }
3160
+ live.peer.notify("session/cancel", { sessionId: turn.sessionId });
3161
+ live.cancelled = true;
3162
+ this.settleCancel(live, (settled) => void prompt.then(() => void 0, () => void 0).then(settled));
3163
+ return true;
3164
+ }
3165
+ /** A background run that only an unsettled tool call holds open: no level, no task, no held agent says
3166
+ * anything runs. Such a tool has no one left to settle it, so the run is let go after a quiet
3167
+ * orphanedToolMs (re-armed by every frame the run receives) instead of the day ABANDONED_WORK_MS
3168
+ * allows. Its tool rows are settled, and the windows told it ended. Real background work -- a level,
3169
+ * a task, an agent -- never starts or keeps this timer. */
3170
+ orphanWatch;
3171
+ watchOrphanedTools() {
3172
+ if (this.orphanWatch) {
3173
+ clearTimeout(this.orphanWatch);
3174
+ this.orphanWatch = void 0;
3175
+ }
3176
+ const held2 = this.background;
3177
+ if (!held2 || held2.channel.done || this.isClosed) return;
3178
+ if (this.work.level || this.vendorTasks.running().length || this.heldAgents.size || !this.work.count()) return;
3179
+ this.orphanWatch = setTimeout(() => {
3180
+ this.orphanWatch = void 0;
3181
+ const run = this.background;
3182
+ if (!run || run.channel.done || this.isClosed) return;
3183
+ if (this.work.level || this.vendorTasks.running().length || this.heldAgents.size) return;
3184
+ const orphans = this.work.endAll("tool");
3185
+ diagnostic("vendor.orphaned-tool", `${orphans.length} tool${orphans.length === 1 ? "" : "s"} never settled; no longer waiting for ${orphans.length === 1 ? "it" : "them"}`);
3186
+ for (const item of orphans) run.observer.onActivity?.({ kind: "tool-done", label: item.label, id: item.id });
3187
+ this.finishBackground("completed");
3188
+ }, this.orphanedToolMs);
3189
+ this.orphanWatch.unref?.();
3190
+ }
3191
+ /** The commands behind the terminals were looked at (persistent-session.ts): the level names them by pid, and the
3192
+ * window that follows the work (the user's turn, else the background turn, else the worker) is told. */
3193
+ commandsChanged(commands) {
3194
+ this.work.setCommands(commands.map(({ outputFile: _file, keep: _keep, ...shown }) => shown));
3195
+ const level = this.work.fullLevel();
3196
+ const listener = this.turn && !this.turn.done ? this.turn.observer.onBackgroundWork : this.background?.observer.onBackgroundWork;
3197
+ if (listener) listener.call(this.turn && !this.turn.done ? this.turn.observer : this.background.observer, level);
3198
+ else this.reportBackground?.(level);
3199
+ }
3200
+ finishBackground(ended) {
3201
+ if (this.orphanWatch) {
3202
+ clearTimeout(this.orphanWatch);
3203
+ this.orphanWatch = void 0;
3204
+ }
3205
+ if (ended === "completed") this.background?.observer.onBackgroundWork?.(this.work.fullLevel());
3206
+ super.finishBackground(ended);
3207
+ }
3208
+ /** Open a background turn for the agent's out-of-turn updates. */
3209
+ openBackground(reason = "vendor-turn") {
3210
+ return this.openBackgroundRun(() => {
3211
+ const channel = new BackgroundTurnChannel("acp", reason);
3212
+ return { channel, observer: channel.observer, cumulativeChunks: this.lastCumulativeChunks, text: "", messageText: "", sawActivity: false, thoughts: 0, base: { ...this.sessionTotals } };
3213
+ });
3214
+ }
3215
+ ensureLive(input, argv) {
3216
+ return this.liveFor(JSON.stringify([input.binary, argv, input.cwd, input.environment]), `${input.command} ACP restarted`, {
3217
+ name: input.displayName ?? input.command,
3218
+ binary: input.binary,
3219
+ argv,
3220
+ cwd: input.cwd,
3221
+ environment: input.environment,
3222
+ peer: {
3223
+ label: `${input.command} ACP`,
3224
+ // Kiro (Rust) panics and stays alive: read as the crash it is.
3225
+ crashReport: panicMessage,
3226
+ onRequest: (method, params, id) => method === "session/request_permission" ? this.permission(params, id) : method === "elicitation/create" ? this.elicitation(params, id) : void 0,
3227
+ onNotification: (method, params) => {
3228
+ if (method === "session/update") this.update(params);
3229
+ else if (method === "$/cancel_request") this.withdrawn(params.requestId);
3230
+ else if (method === "_session/retrying") this.retrying(params);
3231
+ else if (method.startsWith("_") && method !== "_kiro.dev/metadata") this.extension(method, params);
3232
+ else if (method === "_kiro.dev/metadata") this.kiroMetadata(params);
3233
+ }
3234
+ }
3235
+ }, {});
3236
+ }
3237
+ async flow(turn, argv) {
3238
+ const { input } = turn;
3239
+ const setupAt = Date.now();
3240
+ const live = this.ensureLive(input, argv);
3241
+ const cold = !live.capabilities;
3242
+ let threadLoadMs = 0;
3243
+ const { peer } = live;
3244
+ const setup = this.setupRequest;
3245
+ const control = this.setupRequest;
3246
+ let announced = Boolean(live.capabilities);
3247
+ let connectingShown = false;
3248
+ const waitOnStart = async (pending) => {
3249
+ if (announced) return pending;
3250
+ const notice = setTimeout(() => {
3251
+ announced = true;
3252
+ connectingShown = true;
3253
+ input.onPhase?.(`connecting to ${input.command}`);
3254
+ }, START_NOTICE_MS);
3255
+ notice.unref?.();
3256
+ try {
3257
+ return await pending;
3258
+ } finally {
3259
+ clearTimeout(notice);
3260
+ }
3261
+ };
3262
+ const startingRequest = (method, params) => waitOnStart(peer.request(method, params, control));
3263
+ const stillRunning = () => {
3264
+ if (turn.done) throw turnCancelledError();
3265
+ };
3266
+ const { effortConfigId, providerConfigId, permissionModeIds, planModeId, usageTotals } = input.acp ?? {};
3267
+ const modelRequiresProtocol = input.acp?.inheritCliOptions === false;
3268
+ const effortRequiresProtocol = modelRequiresProtocol && input.effort !== "medium";
3269
+ if (!live.capabilities) {
3270
+ const initialized = await waitOnStart(peer.request("initialize", {
3271
+ protocolVersion: 1,
3272
+ clientCapabilities: ACP_CLIENT_CAPABILITIES,
3273
+ clientInfo: { name: "clikcode", title: "ClikCode", version: "1" }
3274
+ }, setup));
3275
+ live.capabilities = initialized.agentCapabilities ?? {};
3276
+ const extensions = initialized._meta?.["minimax-code/extensions"]?.methods;
3277
+ live.steering = input.acp?.steering === false ? void 0 : initialized._meta?.steering?.supported === true ? "session" : Array.isArray(extensions) && extensions.includes("mcode/session/steer") ? "mcode" : void 0;
3278
+ stillRunning();
3279
+ }
3280
+ if (input.initializeOnly) return { text: "", nativeSessionId: input.nativeSessionId ?? "" };
3281
+ const call = (method, params, options = setup) => peer.request(method, params, options);
3282
+ const capabilities = live.capabilities;
3283
+ const directories = input.additionalDirectories ?? [];
3284
+ if (directories.length && !capabilities.sessionCapabilities?.additionalDirectories) {
3285
+ throw new Error(`${input.command} ACP does not accept additional directories (/add-dir); remove them or start from a common parent directory`);
3286
+ }
3287
+ let sessionParamsPending;
3288
+ const sessionParams = () => sessionParamsPending ??= globalMcpServersForAcp(input.command, capabilities, input.mcpProfile, void 0, input.cwd).then((mcpServers) => ({
3289
+ cwd: input.cwd,
3290
+ mcpServers,
3291
+ _meta: ACP_SESSION_META,
3292
+ ...directories.length ? { additionalDirectories: [...directories] } : {}
3293
+ }));
3294
+ const images = input.images ?? [];
3295
+ if (images.length && capabilities.promptCapabilities?.image !== true) {
3296
+ throw Object.assign(new Error(`${input.command} ACP does not accept image prompts`), { acpUnsupportedImages: true });
3297
+ }
3298
+ let loaded;
3299
+ const wanted = input.nativeSessionId ?? this.sessionId;
3300
+ const unclaimed = !wanted && live.unclaimed !== void 0 && live.unclaimed === live.sessionId;
3301
+ if (live.sessionId && live.sessionId !== wanted && !unclaimed && capabilities.sessionCapabilities?.close) {
3302
+ const previous = live.sessionId;
3303
+ live.sessionId = void 0;
3304
+ await call("session/close", { sessionId: previous }).catch(quiet("harness/transport/acp-client"));
3305
+ }
3306
+ if (wanted) {
3307
+ if (live.sessionId !== wanted) {
3308
+ this.sessionTotals = {};
3309
+ this.costStartUnknown = input.command === "claude";
3310
+ if (!capabilities.sessionCapabilities?.resume && !capabilities.loadSession) throw new Error(`${input.command} ACP cannot load sessions`);
3311
+ const method = capabilities.sessionCapabilities?.resume ? "session/resume" : "session/load";
3312
+ try {
3313
+ const loadAt = Date.now();
3314
+ loaded = await waitOnStart(call(method, { sessionId: wanted, ...await sessionParams() }, setup));
3315
+ threadLoadMs = Date.now() - loadAt;
3316
+ } catch (error) {
3317
+ throw markMissingThread(error, wanted);
3318
+ }
3319
+ live.sessionId = wanted;
3320
+ live.models = loaded?.models ?? { configOptions: loaded?.configOptions };
3321
+ live.modes = loaded?.modes;
3322
+ live.configOptions = loaded?.configOptions;
3323
+ if (loaded) input.onSessionModels?.(loaded, false);
3324
+ stillRunning();
3325
+ }
3326
+ turn.sessionId = wanted;
3327
+ } else if (unclaimed) {
3328
+ turn.sessionId = live.unclaimed;
3329
+ } else {
3330
+ this.sessionTotals = {};
3331
+ this.costStartUnknown = false;
3332
+ const started = await waitOnStart(call("session/new", await sessionParams(), setup));
3333
+ const sessionId = String(started.sessionId ?? "");
3334
+ if (!sessionId) throw new Error(`${input.command} ACP did not return a session id`);
3335
+ live.sessionId = sessionId;
3336
+ live.unclaimed = sessionId;
3337
+ live.models = started.models ?? { configOptions: started.configOptions };
3338
+ live.modes = started.modes;
3339
+ live.configOptions = started.configOptions;
3340
+ input.onSessionModels?.(started, true);
3341
+ stillRunning();
3342
+ turn.sessionId = sessionId;
3343
+ }
3344
+ let requestedModel = input.model;
3345
+ if (requestedModel && providerConfigId && input.modelProviderSeparator && requestedModel.includes(input.modelProviderSeparator)) {
3346
+ const boundary = requestedModel.indexOf(input.modelProviderSeparator);
3347
+ const providerId = requestedModel.slice(0, boundary);
3348
+ requestedModel = requestedModel.slice(boundary + input.modelProviderSeparator.length);
3349
+ const providerOption = live.configOptions?.find((option) => (option.id ?? option.configId) === providerConfigId);
3350
+ const choices = Array.isArray(providerOption?.options) ? providerOption.options : [];
3351
+ if (!choices.some((option) => option.value === providerId)) {
3352
+ throw Object.assign(new Error(`${input.command} ACP does not offer provider ${providerId}`), { acpUnsupportedModel: true });
3353
+ }
3354
+ if (providerOption?.currentValue !== providerId) {
3355
+ const updated = await startingRequest("session/set_config_option", { sessionId: turn.sessionId, configId: providerConfigId, value: providerId });
3356
+ stillRunning();
3357
+ live.configOptions = Array.isArray(updated?.configOptions) ? updated.configOptions : live.configOptions?.map((option) => option === providerOption ? { ...option, currentValue: providerId } : option);
3358
+ live.models = { configOptions: live.configOptions };
3359
+ }
3360
+ }
3361
+ const modelId = requestedModel ? acpModelChoice(live.models, requestedModel) ?? (providerConfigId && live.configOptions?.some((option) => (option.id ?? option.configId) === "model") ? requestedModel : void 0) : void 0;
3362
+ const offersModels = Array.isArray(live.models?.availableModels) && live.models.availableModels.length > 0 || Boolean(live.configOptions?.some((option) => (option.id ?? option.configId) === "model" && Array.isArray(option.options) && option.options.length > 0));
3363
+ if (input.model && !modelId && (modelRequiresProtocol || input.plansListModels && offersModels)) {
3364
+ throw Object.assign(new Error(`${input.command} ACP does not list model ${input.model}`), { acpUnsupportedModel: true });
3365
+ }
3366
+ const modelConfig = live.configOptions?.find((option) => (option.id ?? option.configId) === "model");
3367
+ const currentModel = live.models?.currentModelId ?? modelConfig?.currentValue;
3368
+ if (modelId && modelId !== currentModel) {
3369
+ const updated = modelConfig ? await startingRequest("session/set_config_option", { sessionId: turn.sessionId, configId: "model", value: modelId }) : await startingRequest("session/set_model", { sessionId: turn.sessionId, modelId });
3370
+ stillRunning();
3371
+ if (Array.isArray(updated?.configOptions)) {
3372
+ live.configOptions = updated.configOptions;
3373
+ live.models = { ...live.models, configOptions: live.configOptions };
3374
+ } else if (modelConfig) live.configOptions = live.configOptions?.map((option) => option === modelConfig ? { ...option, currentValue: modelId } : option);
3375
+ if (!modelConfig) live.models = { ...live.models, currentModelId: modelId };
3376
+ }
3377
+ const planning = Boolean(input.planMode && planModeId);
3378
+ const modeId = planning ? planModeId : permissionModeIds?.[input.permissionMode];
3379
+ if (modeId) {
3380
+ const available = Array.isArray(live.modes?.availableModes) ? live.modes.availableModes : [];
3381
+ const modeOption = available.length ? void 0 : acpModeConfigOption(live.configOptions);
3382
+ if (modeOption) {
3383
+ if (modeOption.currentValue !== modeId) {
3384
+ if (!acpConfigValues(modeOption).includes(modeId)) throw new Error(`${input.command} ACP does not offer ${planning ? "plan" : "permission"} mode ${modeId}`);
3385
+ const updated = await startingRequest("session/set_config_option", { sessionId: turn.sessionId, configId: modeOption.id ?? modeOption.configId, value: modeId });
3386
+ stillRunning();
3387
+ live.configOptions = Array.isArray(updated?.configOptions) ? updated.configOptions : live.configOptions?.map((option) => option === modeOption ? { ...option, currentValue: modeId } : option);
3388
+ live.models = { ...live.models, configOptions: live.configOptions };
3389
+ }
3390
+ } else if (live.modes?.currentModeId !== modeId) {
3391
+ if (!available.some((mode) => mode.id === modeId)) throw new Error(`${input.command} ACP does not offer ${planning ? "plan" : "permission"} mode ${modeId}`);
3392
+ await startingRequest("session/set_mode", { sessionId: turn.sessionId, modeId });
3393
+ stillRunning();
3394
+ live.modes = { ...live.modes, currentModeId: modeId };
3395
+ }
3396
+ }
3397
+ if (input.effort && effortConfigId) {
3398
+ const effortOption = live.configOptions?.find((option) => (option.id ?? option.configId) === effortConfigId);
3399
+ const choices = Array.isArray(effortOption?.options) ? effortOption.options : [];
3400
+ if (effortOption && choices.some((option) => option.value === input.effort) && effortOption.currentValue !== input.effort) {
3401
+ await startingRequest("session/set_config_option", { sessionId: turn.sessionId, configId: effortConfigId, value: input.effort });
3402
+ stillRunning();
3403
+ live.configOptions = live.configOptions?.map((option) => option === effortOption ? { ...option, currentValue: input.effort } : option);
3404
+ } else if ((!effortOption || !choices.some((option) => option.value === input.effort)) && effortRequiresProtocol) {
3405
+ throw Object.assign(new Error(`${input.command} ACP does not offer effort ${input.effort}`), { acpUnsupportedEffort: true });
3406
+ }
3407
+ } else if (input.effort && effortRequiresProtocol) {
3408
+ throw Object.assign(new Error(`${input.command} ACP does not offer effort control`), { acpUnsupportedEffort: true });
3409
+ }
3410
+ this.sessionId = turn.sessionId;
3411
+ if (live.unclaimed === turn.sessionId) live.unclaimed = void 0;
3412
+ if (!wanted) await input.onSessionId?.(turn.sessionId);
3413
+ stillRunning();
3414
+ if (input.prepareOnly) {
3415
+ lifecycle("vendor.acp.prepared", { harness: input.command, cold, setupMs: Date.now() - setupAt, threadLoadMs });
3416
+ return { text: "", nativeSessionId: turn.sessionId };
3417
+ }
3418
+ markTurn("ready", { cold });
3419
+ const blocks = [{ type: "text", text: input.prompt }, ...await Promise.all(images.map(acpImageBlock))];
3420
+ stillRunning();
3421
+ turn.base = { ...this.sessionTotals };
3422
+ await this.promptSent();
3423
+ stillRunning();
3424
+ lifecycle("vendor.acp.ready", { harness: input.command, cold, setupMs: Date.now() - setupAt, threadLoadMs });
3425
+ turn.promptStarted = true;
3426
+ if (connectingShown) input.onPhase?.("thinking");
3427
+ const compact = input.acp?.compactCommand;
3428
+ if (compact?.settledBy && input.prompt.trim() === compact.prompt) {
3429
+ let done;
3430
+ let fail;
3431
+ const promise = new Promise((resolve, reject) => {
3432
+ done = resolve;
3433
+ fail = reject;
3434
+ });
3435
+ promise.catch(quiet("harness/transport/acp-client"));
3436
+ turn.compactionSettled = { promise, done, fail };
3437
+ }
3438
+ turn.prompt = call("session/prompt", { sessionId: turn.sessionId, prompt: blocks }, {});
3439
+ let changing = Promise.resolve();
3440
+ const apply = (changes) => {
3441
+ changing = changing.then(async () => {
3442
+ if (turn.done || !turn.sessionId || peer.closed) return;
3443
+ const set = async (id, value) => {
3444
+ const option = live.configOptions?.find((entry) => (entry.id ?? entry.configId) === id);
3445
+ if (!option) throw new Error(`The agent does not offer ${id}`);
3446
+ if (option.currentValue === value) return;
3447
+ if (!acpConfigValues(option).includes(value)) throw new Error(`The running model does not offer ${id} ${value}`);
3448
+ const updated = await peer.request("session/set_config_option", { sessionId: turn.sessionId, configId: id, value }, { timeoutMs: 5e3 });
3449
+ live.configOptions = Array.isArray(updated.configOptions) ? updated.configOptions : live.configOptions?.map((entry) => entry === option ? { ...entry, currentValue: value } : entry);
3450
+ };
3451
+ if (typeof changes.model === "string" && changes.model !== input.model) {
3452
+ const choice = acpModelChoice({ ...live.models, configOptions: live.configOptions }, changes.model);
3453
+ if (!choice) throw new Error("The agent did not offer that model on this session");
3454
+ const option = live.configOptions?.find((entry) => (entry.id ?? entry.configId) === "model");
3455
+ if (option) await set("model", choice);
3456
+ else await peer.request("session/set_model", { sessionId: turn.sessionId, modelId: choice }, { timeoutMs: 5e3 });
3457
+ live.models = { ...live.models, currentModelId: choice };
3458
+ input.model = changes.model;
3459
+ input.onServedModel?.(changes.model);
3460
+ lifecycle("vendor.model-changed", { harness: input.command, model: changes.model });
3461
+ }
3462
+ if (changes.effort && changes.effort !== input.effort && effortConfigId) {
3463
+ await set(effortConfigId, changes.effort);
3464
+ input.effort = changes.effort;
3465
+ }
3466
+ if (Object.hasOwn(changes, "planMode") || changes.permissionMode) {
3467
+ const planning2 = Object.hasOwn(changes, "planMode") ? changes.planMode : input.liveSettings ? input.liveSettings.planMode : input.planMode;
3468
+ const mode = planning2 === true ? planModeId : permissionModeIds?.[changes.permissionMode ?? input.permissionMode];
3469
+ if (mode) {
3470
+ const option = acpModeConfigOption(live.configOptions);
3471
+ if (option) await set(option.id ?? option.configId, mode);
3472
+ else await peer.request("session/set_mode", { sessionId: turn.sessionId, modeId: mode }, { timeoutMs: 5e3 });
3473
+ }
3474
+ }
3475
+ }).catch(() => {
3476
+ input.onNotice?.("Settings saved for the next turn; this agent could not apply them while running.");
3477
+ });
3478
+ };
3479
+ const stopChanges = input.liveSettings?.subscribe(apply);
3480
+ if (input.liveSettings) apply({ model: input.liveSettings.model, effort: input.liveSettings.effort });
3481
+ markTurn("prompt-sent");
3482
+ if (live.steering) {
3483
+ turn.steerPort = { offer: (text2) => this.steer(turn, text2) };
3484
+ input.onSteerReady?.(turn.steerPort);
3485
+ }
3486
+ let completed;
3487
+ try {
3488
+ completed = await turn.prompt;
3489
+ } finally {
3490
+ stopChanges?.();
3491
+ await changing;
3492
+ }
3493
+ if (live.steering) input.onSteerReady?.(void 0);
3494
+ if (turn.compactionFailure) throw turn.compactionFailure;
3495
+ if (turn.compactionSettled && completed.stopReason !== "cancelled") {
3496
+ const stopped = new Promise((resolve) => {
3497
+ if (input.signal?.aborted) resolve();
3498
+ input.signal?.addEventListener("abort", () => resolve(), { once: true });
3499
+ setTimeout(resolve, COMPACTION_SETTLE_MS).unref();
3500
+ });
3501
+ await Promise.race([turn.compactionSettled.promise, stopped]);
3502
+ if (input.signal?.aborted) throw turnCancelledError();
3503
+ }
3504
+ if (completed.stopReason === "cancelled") {
3505
+ if (!live.cancelled && !turn.sawActivity && !turn.text.trim()) {
3506
+ const reason = await silentRefusalReason(input.command, input.environment);
3507
+ if (reason) throw new Error(`${input.command}: ${reason}`);
3508
+ throw new Error(`${input.command} ended the turn as cancelled before saying anything, which it does when its sign-in is not usable; check \`clikcode accounts status\``);
3509
+ }
3510
+ throw turnCancelledError();
3511
+ }
3512
+ let usage = normalizeTurnUsage(completed.usage ?? completed._meta?.usage ?? completed._meta?.quota?.token_count);
3513
+ if (typeof completed._meta?.totalTokens === "number") {
3514
+ const modelId2 = completed._meta.modelId ?? live.models?.currentModelId;
3515
+ const listed = Array.isArray(live.models?.availableModels) ? live.models.availableModels : [];
3516
+ const window = listed.find((item) => item?.modelId === modelId2)?._meta?.totalContextTokens;
3517
+ usage = { ...usage, contextUsed: completed._meta.totalTokens, ...typeof window === "number" ? { contextWindow: window } : {} };
3518
+ }
3519
+ if (usage && usageTotals === "session") {
3520
+ this.sessionTotals = { ...this.sessionTotals, ...turnShareOf(usage, {}) };
3521
+ usage = { ...usage, ...turnShareOf(usage, turn.base) };
3522
+ }
3523
+ const stopReason = turnStopReason(completed.stopReason);
3524
+ if (usage || stopReason) input.onUsage?.({ ...usage, ...stopReason ? { stopReason } : {} });
3525
+ const text = turn.text.trim();
3526
+ if (vendorBusyNotice(text, live.cancelled === true) && !turn.sawActivity) {
3527
+ this.dropLive(new Error(`${input.command} ACP restarted`));
3528
+ throw Object.assign(new Error(`${input.command} was still finishing the cancelled turn and answered "${text}" instead of the message`), { acpStaleTurn: true });
3529
+ }
3530
+ live.cancelled = false;
3531
+ if (!text && !turn.sawActivity) {
3532
+ const command = /^\/[\w:.-]+/.exec(input.prompt.trim())?.[0];
3533
+ if (command && completed.stopReason === "end_turn") {
3534
+ return { text: `${input.displayName ?? input.command} ran ${command} and showed nothing back here.`, nativeSessionId: turn.sessionId };
3535
+ }
3536
+ throw new Error(`${input.command} ACP returned no assistant text`);
3537
+ }
3538
+ return { text, nativeSessionId: turn.sessionId };
3539
+ }
3540
+ /** No tool call is open and the user is not being asked anything. Claude's
3541
+ * adapter injects a steer at once, which cancels a call in flight (verified
3542
+ * live: `[Request interrupted by user for tool use]`, the work redone) --
3543
+ * and a sub-agent's call is open for the sub-agent's whole run. Between
3544
+ * calls nothing is lost. */
3545
+ steerSafe(turn) {
3546
+ return !turn.done && this.turn === turn && this.work.count() === 0 && turn.approvals === 0;
3547
+ }
3548
+ /** Takes a message into the running turn through the agent's own steering request, when nothing would
3549
+ * be interrupted (steerSafe). Otherwise false: the message stays queued, and `steerPause` tells the broker
3550
+ * when a moment comes. Rejects when the turn is over. */
3551
+ async steer(turn, text) {
3552
+ const live = this.live;
3553
+ if (turn.done || this.turn !== turn || !live) throw new Error(`${turn.input.command} ACP turn ended`);
3554
+ if (!this.steerSafe(turn)) return false;
3555
+ const answer = live.steering === "mcode" ? await live.peer.request("mcode/session/steer", { sessionId: turn.sessionId, text }, {}) : await live.peer.request("_session/steering", {
3556
+ sessionId: turn.sessionId,
3557
+ prompt: [{ type: "text", text }],
3558
+ _meta: { steering: { idleBehavior: "promptRequired" } }
3559
+ }, {});
3560
+ return answer?.outcome === "injected" || live.steering === "mcode" && answer?.mode === "steered";
3561
+ }
3562
+ /** A moment that may be safe: tell the broker once this burst of updates is in (an agent announces
3563
+ * parallel calls back to back); it offers what waits, and the offer re-checks. */
3564
+ steerPause(turn) {
3565
+ const port = turn.steerPort;
3566
+ if (port?.onWindow) setImmediate(() => port.onWindow?.());
3567
+ }
3568
+ /** Where an update goes: the user's turn while one runs, otherwise a
3569
+ * background turn, opened by an update that carries work. */
3570
+ targetFor(update) {
3571
+ if (this.turn) return this.turn.done ? void 0 : this.turn;
3572
+ if (this.background && !this.background.channel.done) return this.background;
3573
+ const reportsRunning = update.sessionUpdate === "tool_call" ? toolRunning(update) : update.sessionUpdate === "tool_call_update" && (update.status === "in_progress" || update.status === "pending");
3574
+ return reportsRunning ? this.openBackground() : void 0;
3575
+ }
3576
+ /** What the agent says with no prompt open and no tool running: its words
3577
+ * go into the conversation as they arrive. It is not work in progress, so
3578
+ * nothing is shown as working for it. */
3579
+ relayOutOfTurn(update) {
3580
+ if (!this.live || this.isClosed || this.settling || !this.relay) return;
3581
+ const name = String(update.sessionUpdate);
3582
+ if (name !== "agent_message_chunk" && name !== "agent_thought_chunk") return;
3583
+ const kind = name === "agent_message_chunk" ? "message" : "thought";
3584
+ const delta = kind === "message" ? acpResponseDelta(update) : acpThoughtDelta(update);
3585
+ if (!delta) return;
3586
+ if (kind === "message") {
3587
+ const change = acpMessageChange(this.relayedMessage, delta, this.lastCumulativeChunks && typeof update.messageId === "string");
3588
+ this.relayedMessage = change.current;
3589
+ if (!change.text && change.mode === "append") return;
3590
+ this.relay({ kind, text: change.text, mode: change.mode });
3591
+ return;
3592
+ }
3593
+ this.relay({ kind, text: delta, mode: "append" });
3594
+ }
3595
+ /** Sessions an agent runs a sub-agent in (cursor-agent: `subagent_spawned`
3596
+ * names `subagentSessionId` and, in `_meta.cursor.toolCallId`, the call that
3597
+ * spawned it) -> that call. Their updates arrive under their own session id. */
3598
+ childSessions = /* @__PURE__ */ new Map();
3599
+ update(params) {
3600
+ let update = params.update ?? {};
3601
+ const turn = this.turn && !this.turn.done ? this.turn : void 0;
3602
+ const expected = turn?.sessionId ?? this.sessionId;
3603
+ if (update.sessionUpdate === "subagent_spawned" && typeof update.subagentSessionId === "string") {
3604
+ const spawner = update._meta?.cursor?.toolCallId;
3605
+ if (typeof spawner === "string" && spawner) {
3606
+ this.childSessions.set(update.subagentSessionId, spawner);
3607
+ this.heldAgents.launched(spawner);
3608
+ }
3609
+ }
3610
+ if (update.sessionUpdate === "subagent_state_update" && typeof update.subagentSessionId === "string" && typeof update.state === "string") {
3611
+ const spawner = this.childSessions.get(update.subagentSessionId);
3612
+ const target2 = this.liveTarget(params);
3613
+ if (spawner && target2) for (const event of this.heldAgents.ended(spawner, update.state)) target2.observer.onActivity?.(event);
3614
+ }
3615
+ let ofChild = false;
3616
+ if (typeof params.sessionId === "string" && expected && params.sessionId !== expected) {
3617
+ const parent = this.childSessions.get(params.sessionId);
3618
+ if (!parent || !CHILD_SESSION_UPDATES.has(String(update.sessionUpdate))) return;
3619
+ update = { ...update, _meta: { ...update._meta && typeof update._meta === "object" ? update._meta : {}, parentToolCallId: parent } };
3620
+ ofChild = true;
3621
+ }
3622
+ if (update.sessionUpdate === "current_mode_update" && typeof update.currentModeId === "string" && this.live) {
3623
+ const before = this.live.modes?.currentModeId;
3624
+ this.live.modes = { ...this.live.modes, currentModeId: update.currentModeId };
3625
+ const planModeId = turn?.input.acp?.planModeId;
3626
+ if (turn?.promptStarted && planModeId && before === planModeId && update.currentModeId !== planModeId) turn.input.onPlanModeExit?.();
3627
+ }
3628
+ if (update.sessionUpdate === "config_option_update" && Array.isArray(update.configOptions) && this.live) {
3629
+ const planModeId = turn?.input.acp?.planModeId;
3630
+ const was = acpModeConfigOption(this.live.configOptions)?.currentValue;
3631
+ const now = acpModeConfigOption(update.configOptions)?.currentValue;
3632
+ if (turn?.promptStarted && planModeId && was === planModeId && now !== void 0 && now !== planModeId) turn.input.onPlanModeExit?.();
3633
+ this.live.configOptions = update.configOptions;
3634
+ this.live.models = { ...this.live.models, configOptions: update.configOptions };
3635
+ }
3636
+ const totals = ofChild ? void 0 : acpSessionTotals(update);
3637
+ if (totals?.costUsd !== void 0) this.noteRunningCost(totals.costUsd);
3638
+ if (totals) this.sessionTotals = { ...this.sessionTotals, ...totals };
3639
+ if (turn && !turn.promptStarted) {
3640
+ const commands = acpAvailableCommands(update);
3641
+ if (commands) turn.input.onAvailableCommands?.(commands);
3642
+ return;
3643
+ }
3644
+ const target = this.targetFor(update);
3645
+ if (!target && !this.turn) this.relayOutOfTurn(update);
3646
+ this.trackTool(target, update);
3647
+ if (target) this.deliver(target, update, totals);
3648
+ if (target && target === this.background) this.watchOrphanedTools();
3649
+ const run = this.background;
3650
+ if (run && target === run && this.work.count() === 0) {
3651
+ const settledLastTool = update.sessionUpdate === "tool_call_update" && toolSettled(update);
3652
+ if (settledLastTool || TURN_BOOKKEEPING_UPDATES.has(String(update.sessionUpdate))) this.finishBackground("completed");
3653
+ }
3654
+ }
3655
+ /** Updates that are the agent's status, not its content: shown as the
3656
+ * waiting line (a warning as a notice) so a turn emitting only these is
3657
+ * seen to be working. */
3658
+ statusUpdate(input, update) {
3659
+ const name = (value, fallback) => typeof value === "string" && value.trim() ? value.trim().slice(0, 80) : fallback;
3660
+ switch (update.sessionUpdate) {
3661
+ case "notice": {
3662
+ const title = typeof update.title === "string" ? update.title.trim() : "";
3663
+ const description = typeof update.description === "string" ? update.description.trim() : "";
3664
+ const text = [title, description].filter(Boolean).join(": ");
3665
+ if (text) input.onNotice?.(text);
3666
+ return true;
3667
+ }
3668
+ case "compaction_update": {
3669
+ const status = String(update.status ?? "");
3670
+ if (status === "completed") input.onNotice?.(COMPACTED);
3671
+ else if (status !== "cancelled" && status !== "failed") input.onPhase?.(COMPACTING);
3672
+ return true;
3673
+ }
3674
+ case "compaction_summary_chunk":
3675
+ input.onPhase?.(COMPACTING);
3676
+ return true;
3677
+ case "async_task_spawned":
3678
+ case "async_task_progress":
3679
+ case "async_task_state_update":
3680
+ input.onPhase?.(`background task: ${name(update.name ?? update.description, String(update.asyncTaskId ?? "running"))}`);
3681
+ return true;
3682
+ case "subagent_spawned":
3683
+ case "subagent_state_update":
3684
+ input.onPhase?.(`sub-agent: ${name(update.name ?? update.description ?? update.title, "working")}`);
3685
+ return true;
3686
+ case "config_option_update":
3687
+ return true;
3688
+ default:
3689
+ return false;
3690
+ }
3691
+ }
3692
+ trackTool(target, update) {
3693
+ if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") return;
3694
+ const id = typeof update.toolCallId === "string" ? update.toolCallId : void 0;
3695
+ if (!id) return;
3696
+ if (update.rawInput !== void 0) this.vendorTasks.call(id, update.rawInput);
3697
+ if (toolSettled(update)) {
3698
+ this.work.end(id);
3699
+ if (target && target === this.turn && this.work.count() === 0) {
3700
+ this.steerPause(this.turn);
3701
+ }
3702
+ } else if (update.sessionUpdate === "tool_call" ? toolRunning(update) : update.status === "in_progress" || update.status === "pending") {
3703
+ this.work.start({ id, kind: "tool", label: String(update.title ?? "tool") });
3704
+ }
3705
+ }
3706
+ deliver(target, update, totals) {
3707
+ const input = target.observer;
3708
+ if (update.sessionUpdate === "notice" && update.severity === "warning" && update.title === OTHER_ORG_THINKING_TITLE) return;
3709
+ if (update.sessionUpdate === "agent_message_chunk" && update._meta?.claudeCode?.kind === "informational" && update._meta.claudeCode.level === "warning" && typeof update.content?.text === "string" && update.content.text.startsWith(`**Warning:** ${OTHER_ORG_THINKING_TITLE}
3710
+ `)) return;
3711
+ const share = totals ? turnShareOf(this.sessionTotals, target.base) : void 0;
3712
+ if (share && update.sessionUpdate !== "usage_update") input.onUsage?.(share);
3713
+ const commands = acpAvailableCommands(update);
3714
+ if (commands) return input.onAvailableCommands?.(commands);
3715
+ const parentId = acpParentToolId(update);
3716
+ if (parentId && (update.sessionUpdate === "agent_message_chunk" || update.sessionUpdate === "agent_thought_chunk")) {
3717
+ const text = typeof update.content?.text === "string" ? update.content.text : "";
3718
+ if (!text) return;
3719
+ target.subagentText ??= /* @__PURE__ */ new Map();
3720
+ const prior = target.subagentText.get(parentId);
3721
+ const said = `${prior && prior.kind === update.sessionUpdate ? prior.text : ""}${text}`.slice(-2e3);
3722
+ target.subagentText.set(parentId, { kind: String(update.sessionUpdate), text: said });
3723
+ const latest = said.trim().split(/\n+/).pop()?.trim() ?? "";
3724
+ if (latest) input.onActivity?.({ kind: "thinking", label: thoughtLabel(latest), parentId });
3725
+ return;
3726
+ }
3727
+ const thought = acpThoughtDelta(update);
3728
+ if (!thought && update.sessionUpdate !== "usage_update") target.thought = void 0;
3729
+ const delta = acpResponseDelta(update);
3730
+ if (delta) {
3731
+ const freshMessage = Boolean(target.needsSeparator && target.text);
3732
+ if (freshMessage) target.messageText = "";
3733
+ const previousMessage = target.messageText;
3734
+ const change = acpMessageChange(previousMessage, delta, target.cumulativeChunks && typeof update.messageId === "string");
3735
+ target.messageText = change.current;
3736
+ if (change.mode === "replace") {
3737
+ target.needsSeparator = false;
3738
+ target.text = target.text.slice(0, -previousMessage.length) + change.current;
3739
+ input.onResponseDelta?.(target.text, change.mode);
3740
+ return;
3741
+ }
3742
+ if (!change.text) return;
3743
+ const separator = freshMessage ? target.text.endsWith("\n\n") ? "" : target.text.endsWith("\n") ? "\n" : "\n\n" : "";
3744
+ target.needsSeparator = false;
3745
+ target.text += separator + change.text;
3746
+ input.onResponseDelta?.(separator + change.text);
3747
+ return;
3748
+ }
3749
+ if (thought) {
3750
+ target.thought ??= { id: `thought-${++target.thoughts}`, text: "" };
3751
+ target.thought.text += thought;
3752
+ return input.onThought?.(target.thought.text, target.thought.id);
3753
+ }
3754
+ const parsedActivity = acpActivityEvent(update);
3755
+ let activity = parsedActivity ? this.heldAgents.filter(parsedActivity, update.status === "completed" ? update.rawOutput : void 0) : void 0;
3756
+ if (parsedActivity && !activity) return;
3757
+ if (activity) {
3758
+ const active = this.turn;
3759
+ const compact = active?.input.acp?.compactCommand;
3760
+ if (active && target === active && compact && (active.input.prompt === compact.prompt || active.input.prompt.startsWith(`${compact.prompt} `)) && activity.kind === "tool-error" && activity.label.toLowerCase() === compact.toolLabel?.toLowerCase()) {
3761
+ const reason = activity.output?.join("\n") ?? "";
3762
+ if (classifyEvidence({ vendorError: true, text: reason }) === "quota-exhausted") {
3763
+ active.compactionFailure = new Error(reason);
3764
+ }
3765
+ }
3766
+ target.settledTools ??= /* @__PURE__ */ new Set();
3767
+ if (activity.id && activity.kind === "tool-start" && target.settledTools.has(activity.id)) {
3768
+ activity = { ...activity, kind: "tool-done" };
3769
+ } else if (activity.id && activity.kind !== "tool-start") target.settledTools.add(activity.id);
3770
+ target.sawActivity = true;
3771
+ if (activity.parentId) target.subagentText?.delete(activity.parentId);
3772
+ if (target.text && !activity.parentId) target.needsSeparator = true;
3773
+ input.onActivity?.(activity);
3774
+ return;
3775
+ }
3776
+ const plan = acpPlanEntries(update);
3777
+ if (plan) return input.onPlan?.(plan);
3778
+ if (this.statusUpdate(input, update)) return;
3779
+ const claudeLimits = update._meta?.["_claude/rateLimit"];
3780
+ if (claudeLimits && typeof claudeLimits === "object" && target === this.turn) {
3781
+ const reading = claudeRateLimitReading(claudeLimits);
3782
+ if (reading) this.turn.input.onQuotaReading?.(reading);
3783
+ }
3784
+ if (update.sessionUpdate === "usage_update" || update.usage && typeof update.usage === "object") {
3785
+ const usage = normalizeTurnUsage(update.usage && typeof update.usage === "object" ? update.usage : update) ?? {};
3786
+ if (update.sessionUpdate === "usage_update") delete usage.costUsd;
3787
+ Object.assign(usage, share);
3788
+ if (Object.keys(usage).length) input.onUsage?.(usage);
3789
+ }
3790
+ }
3791
+ /** The agent's cost is its process's running total (running-cost.ts): a
3792
+ * reading below the one before means it began again, and a resumed Claude
3793
+ * conversation's first reading is where it stands, not a turn's cost. Moves
3794
+ * the point each open stream measures its share from. */
3795
+ noteRunningCost(reading) {
3796
+ const last2 = this.sessionTotals.costUsd;
3797
+ for (const stream of [this.turn, this.background]) {
3798
+ if (!stream) continue;
3799
+ stream.base = { ...stream.base, costUsd: costBase(stream.base.costUsd, last2, reading, this.costStartUnknown) };
3800
+ }
3801
+ this.costStartUnknown = false;
3802
+ }
3803
+ /** Kiro reports no tokens. Its `_kiro.dev/metadata` notification carries
3804
+ * the share of the context window in use and, once per turn, what the turn
3805
+ * cost in credits (`meteringUsage` [{value, unit: "credit"}]). Verified on
3806
+ * kiro-cli 2.23: credits arrive once, beside `turnDurationMs`. */
3807
+ kiroMetadata(params) {
3808
+ const turn = this.turn;
3809
+ if (!turn || turn.done || !turn.promptStarted) return;
3810
+ if (typeof params.sessionId === "string" && turn.sessionId && params.sessionId !== turn.sessionId) return;
3811
+ const usage = {};
3812
+ if (typeof params.contextUsagePercentage === "number" && Number.isFinite(params.contextUsagePercentage)) usage.contextPercent = params.contextUsagePercentage;
3813
+ const metered = Array.isArray(params.meteringUsage) ? params.meteringUsage : [];
3814
+ const credits = metered.filter((item) => item?.unit === "credit" && typeof item.value === "number").reduce((sum, item) => sum + item.value, 0);
3815
+ if (metered.length && credits > 0) usage.credits = credits;
3816
+ if (Object.keys(usage).length) turn.input.onUsage?.(usage);
3817
+ }
3818
+ /** The agent's own notice that it is retrying a failed model call
3819
+ * (`_session/retrying`, Vibe: `{category:"rate_limited", detail:"HTTP 429"}`).
3820
+ * Shown as a phase, nothing more: the agent retries by its own backoff and
3821
+ * may well succeed. Its own failure or stop reason ends the turn. */
3822
+ retrying(params) {
3823
+ const target = this.liveTarget(params);
3824
+ if (!target) return;
3825
+ const command = this.turn?.input.command ?? "the agent";
3826
+ const detail = typeof params.detail === "string" ? params.detail : "";
3827
+ const category = typeof params.category === "string" ? params.category : "";
3828
+ target.observer.onPhase?.(`${command} is retrying${category || detail ? ` (${[category.replace(/_/g, " "), detail].filter(Boolean).join(": ")})` : ""}`);
3829
+ }
3830
+ /** Where a session-scoped extension notification goes: the user's turn, or
3831
+ * the background turn. A notice for another session is not ours. */
3832
+ liveTarget(params) {
3833
+ const expected = this.turn?.sessionId ?? this.sessionId;
3834
+ if (typeof params.sessionId === "string" && expected && params.sessionId !== expected) return void 0;
3835
+ const target = this.turn ? this.turn.done || !this.turn.promptStarted ? void 0 : this.turn : this.background;
3836
+ return target;
3837
+ }
3838
+ /** Extension notifications the agent sends beside session/update. None is
3839
+ * content, but each is proof of life, and some say something worth showing. */
3840
+ extension(method, params) {
3841
+ if (method === "_auth/status_update") return this.authStatus(params);
3842
+ const settling = this.turn?.compactionSettled;
3843
+ if (settling && method === this.turn?.input.acp?.compactCommand?.settledBy) {
3844
+ const status = typeof params.status === "string" ? params.status : params.status?.type;
3845
+ if (status === "completed") settling.done();
3846
+ else if (status === "failed" || status === "error") settling.fail(new Error(`${this.turn.input.command} reported that its compaction failed`));
3847
+ return;
3848
+ }
3849
+ let message = method === "_claude/sdkMessage" && params.message && typeof params.message === "object" ? params.message : void 0;
3850
+ const sent = message;
3851
+ if (message?.type === "system" && message.subtype === "task_updated" && ["completed", "failed", "killed"].includes(String(message.patch?.status))) {
3852
+ message = { ...message, subtype: "task_notification", status: message.patch.status };
3853
+ }
3854
+ if (message) {
3855
+ this.heldAgentFrame(params, message);
3856
+ this.taskFrame(sent, message);
3857
+ this.noteOwnedCommands(message);
3858
+ }
3859
+ if (message?.type === "system" && message.subtype === "background_tasks_changed" && Array.isArray(message.tasks)) {
3860
+ this.backgroundTasks = new Map(message.tasks.filter((task) => typeof task?.task_id === "string").map((task) => [task.task_id, task]));
3861
+ } else if (message?.type === "system" && message.subtype === "task_notification" && typeof message.task_id === "string" && this.backgroundTasks.delete(message.task_id)) {
3862
+ this.backgroundWorkChanged(params, backgroundWork({ type: "system", subtype: "background_tasks_changed", tasks: [...this.backgroundTasks.values()] }));
3863
+ }
3864
+ if (message?.type === "result") return this.vendorTurnEnded(params);
3865
+ const update = message ? backgroundWork(message) : void 0;
3866
+ if (update) return this.backgroundWorkChanged(params, update);
3867
+ const target = this.liveTarget(params);
3868
+ if (!target) return;
3869
+ if (method === "_session/goal") target.observer.onPhase?.("goal updated");
3870
+ else if (method === "_session/steering") target.observer.onPhase?.("message taken into the turn");
3871
+ }
3872
+ /** Which background shells a sub-agent started, from the frames that say so; a sub-agent's end is a reason to look. */
3873
+ noteOwnedCommands(message) {
3874
+ if (message.type !== "system") return;
3875
+ const owner = (value) => typeof value === "string" && value ? value : void 0;
3876
+ if (message.subtype === "task_started" && message.task_type === "local_bash" && message.owned_by_subagent === true && typeof message.task_id === "string") {
3877
+ this.ownedCommandTasks.set(message.task_id, owner(message.parent_task_id));
3878
+ } else if (message.subtype === "background_tasks_changed" && Array.isArray(message.tasks)) {
3879
+ for (const task of message.tasks) if (task?.task_type === "local_bash" && typeof task.task_id === "string" && owner(task.parent_task_id)) this.ownedCommandTasks.set(task.task_id, owner(task.parent_task_id));
3880
+ } else if (message.subtype === "task_notification" && typeof message.task_id === "string") {
3881
+ if (!this.ownedCommandTasks.delete(message.task_id) && this.ownedCommandTasks.size) setTimeout(() => void this.watchCommands().catch(quiet("harness/transport/acp-client")), 0).unref?.();
3882
+ }
3883
+ }
3884
+ /** A sub-agent that started the shell is gone: the agent task that owns it is no longer running and, when the wire
3885
+ * names no owner, no agent is (a foreground sub-agent runs inside the user's turn). */
3886
+ ownerEnded(command) {
3887
+ for (const [taskId, owner] of this.ownedCommandTasks) {
3888
+ if (!command.outputFile?.includes(taskId)) continue;
3889
+ const running = (task) => task?.task_type === "local_agent" && task.ambient !== true;
3890
+ const alive = owner ? running(this.backgroundTasks.get(owner)) : Boolean(this.turn && !this.turn.done) || this.heldAgents.size > 0 || [...this.backgroundTasks.values()].some(running);
3891
+ if (!alive) return true;
3892
+ }
3893
+ return false;
3894
+ }
3895
+ /** The vendor finished a turn of its own (a task's notification, a goal): its `result`. That is the vendor
3896
+ * saying it has nothing more to do, so a background turn it opened ends here -- whatever the work counters
3897
+ * hold. A tool still unsettled has no one left to settle it. Real background work (a level, a held agent)
3898
+ * keeps the run: its own end comes later as a frame of its own. */
3899
+ vendorTurnEnded(params) {
3900
+ const run = this.background;
3901
+ if (!run || run.channel.done || this.turn || this.liveTarget(params) !== run) return;
3902
+ if (this.work.level || this.heldAgents.size) return;
3903
+ for (const item of this.work.endAll("tool")) run.observer.onActivity?.({ kind: "tool-done", label: item.label, id: item.id });
3904
+ this.finishBackground("completed");
3905
+ }
3906
+ /** The vendor's level changed. Remembered whoever is listening; told to
3907
+ * the user's turn, or to the background turn -- opened for it when work
3908
+ * runs and nothing else is following (a terminal outliving its turn), and
3909
+ * ended when the level empties and no tool is left. */
3910
+ backgroundWorkChanged(params, update) {
3911
+ this.work.replaceLevel(update);
3912
+ let target = this.liveTarget(params);
3913
+ let opened = false;
3914
+ const expected = this.turn?.sessionId ?? this.sessionId;
3915
+ const ours = typeof params.sessionId !== "string" || !expected || params.sessionId === expected;
3916
+ if (!target && ours && !this.turn && this.work.level && this.live) {
3917
+ target = this.openBackground("background-work");
3918
+ opened = Boolean(target);
3919
+ }
3920
+ if (target) target.observer.onBackgroundWork?.(opened ? this.work.fullLevel() : update);
3921
+ else if (ours) this.reportBackground?.(this.work.fullLevel());
3922
+ this.watchOrphanedTools();
3923
+ const run = this.background;
3924
+ if (!run || run.channel.done) return;
3925
+ if (!this.work.level && target === run && this.work.count() === 0 && !this.heldAgents.size) this.finishBackground("completed");
3926
+ }
3927
+ /** Tasks whose terminal `task_updated` patch arrived and whose `task_notification` has not yet,
3928
+ * by task id, each with the timer that ends it from the patch alone. */
3929
+ endingTasks = /* @__PURE__ */ new Map();
3930
+ /** A background task's start or end (handoff-work.ts). An agent's end is told with its result or,
3931
+ * when it stopped short, why -- in the fields of the vendor's own envelope.
3932
+ *
3933
+ * The SDK ends a task with a terminal `task_updated` patch and, right behind it, the
3934
+ * `task_notification` that carries the summary and the transcript (the order of
3935
+ * native/fixtures/claude-background-bash.jsonl). The patch says only the status, so it ends
3936
+ * nothing here: read as the end, it dropped the notification that said the agent died on the usage
3937
+ * limit (2026-10-30). Some SDK versions send the patch alone: any frame after a patch other than
3938
+ * its notification ends the task by the patch (TASK_NOTIFICATION_WAIT_MS if none comes). `sent`
3939
+ * is the frame as the SDK sent it, `message` the same as a notification. */
3940
+ taskFrame(sent, message) {
3941
+ const id = typeof message.task_id === "string" ? message.task_id : void 0;
3942
+ const ownNotification = id !== void 0 && sent.subtype === "task_notification";
3943
+ for (const [waiting, entry] of [...this.endingTasks]) {
3944
+ if (waiting === id && (ownNotification || sent.subtype === "task_updated")) continue;
3945
+ clearTimeout(entry.timer);
3946
+ this.endingTasks.delete(waiting);
3947
+ this.settleTask(entry.message);
3948
+ }
3949
+ if (id && sent.subtype === "task_updated") {
3950
+ if (this.endingTasks.has(id)) return;
3951
+ const timer = setTimeout(() => {
3952
+ this.endingTasks.delete(id);
3953
+ this.settleTask(message);
3954
+ }, TASK_NOTIFICATION_WAIT_MS);
3955
+ timer.unref?.();
3956
+ this.endingTasks.set(id, { timer, message });
3957
+ return;
3958
+ }
3959
+ if (id) {
3960
+ const waiting = this.endingTasks.get(id);
3961
+ if (waiting) clearTimeout(waiting.timer);
3962
+ this.endingTasks.delete(id);
3963
+ }
3964
+ this.settleTask(message);
3965
+ }
3966
+ settleTask(message) {
3967
+ const ended = this.vendorTasks.frame(message);
3968
+ if (!ended || ended.work.kind !== "agent") return;
3969
+ void endedAgentWork(ended.work, ended.status, ended.summary, ended.outputFile).then((work2) => this.agentEnded(work2)).catch(quiet("harness/transport/acp-client"));
3970
+ }
3971
+ /** A background Agent's lifecycle, from the raw `task_*` frames
3972
+ * (events/background-agent-rows.ts). The level above drops a moment before
3973
+ * the agent's end, so the level cannot end its row. */
3974
+ heldAgentFrame(params, message) {
3975
+ const [event] = this.heldAgents.frame(message);
3976
+ if (!event) return;
3977
+ const target = this.liveTarget(params);
3978
+ target?.observer.onActivity?.(event);
3979
+ const run = this.background;
3980
+ if (event.kind !== "tool-start" && run && target === run && !this.work.level && this.work.count() === 0 && !this.heldAgents.size) this.finishBackground("completed");
3981
+ }
3982
+ /** claude-agent-acp pushes the identity it runs as (`_auth/status_update`
3983
+ * {authStatus:{kind,label}}). `none` is a known sign-out -- "cannot
3984
+ * determine" is silence -- so the turn ends now with the sign-in path
3985
+ * rather than waiting for the vendor to fail the prompt itself. */
3986
+ authStatus(params) {
3987
+ const status = params.authStatus;
3988
+ if (!status || typeof status !== "object" || status.kind !== "none") return;
3989
+ const turn = this.turn;
3990
+ if (!turn || turn.done) return;
3991
+ const command = turn.input.command;
3992
+ turn.fail(Object.assign(
3993
+ new Error(`${command} is not signed in${typeof status.label === "string" && status.label ? ` (${status.label})` : ""}: sign in with \`${command} auth login\` or your account's sign-in`),
3994
+ { rpcCode: ACP_AUTH_REQUIRED_CODE, statusCode: 401, acpSignedOut: true }
3995
+ ));
3996
+ }
3997
+ /** Prompts open for the agent's requests, by JSON-RPC id: the agent
3998
+ * withdrawing one (`$/cancel_request`) closes the prompt on screen. */
3999
+ requestPrompts = /* @__PURE__ */ new Map();
4000
+ withdrawn(requestId) {
4001
+ if (typeof requestId === "string" || typeof requestId === "number") this.requestPrompts.get(String(requestId))?.();
4002
+ }
4003
+ /** Puts a question to the user through `stream`, with steering held while it
4004
+ * is open. Never answered for the user. */
4005
+ async askUser(stream, turn, request, id, declined) {
4006
+ if (turn) turn.approvals++;
4007
+ const prompt = this.openPrompt();
4008
+ if (id !== void 0) this.requestPrompts.set(String(id), prompt.abort);
4009
+ try {
4010
+ stream.observer.onPhase?.(`waiting for your answer: ${request.title}`);
4011
+ return await askHarnessQuestion(stream.observer, request, prompt.signal, declined);
4012
+ } finally {
4013
+ if (id !== void 0) this.requestPrompts.delete(String(id));
4014
+ prompt.release();
4015
+ if (turn) {
4016
+ turn.approvals--;
4017
+ this.steerPause(turn);
4018
+ }
4019
+ }
4020
+ }
4021
+ /** `elicitation/create`: a form (claude-agent-acp's AskUserQuestion, an MCP
4022
+ * server's input request). Answered `accept` with the form's content, or
4023
+ * `cancel`. A url-mode request is declined: it was not advertised. */
4024
+ async elicitation(params, id) {
4025
+ const turn = this.turn && !this.turn.done ? this.turn : void 0;
4026
+ const stream = turn ?? (this.turn ? void 0 : this.background ?? this.openBackground());
4027
+ if (!stream) return { action: "cancel" };
4028
+ if (params.mode && params.mode !== "form") return { action: "decline" };
4029
+ const agent = turn?.input.command ?? "The agent";
4030
+ const form = formToQuestions(typeof params.message === "string" ? params.message : "", params.requestedSchema, `${agent} asks`);
4031
+ if (!form) return { action: "decline" };
4032
+ const result = await this.askUser(stream, turn, form.request, id, `${agent} asked a question and it was left unanswered: this screen cannot show it`);
4033
+ if (turn?.done || result.kind !== "answered") return { action: "cancel" };
4034
+ return { action: "accept", content: form.content(result.answers) };
4035
+ }
4036
+ async permission(params, id) {
4037
+ const turn = this.turn && !this.turn.done ? this.turn : void 0;
4038
+ const cancelled = { outcome: { outcome: "cancelled" } };
4039
+ const stream = turn ?? (this.turn ? void 0 : this.background ?? this.openBackground());
4040
+ if (!stream) return cancelled;
4041
+ const command = turn?.input.command ?? "The agent";
4042
+ const optionAnswer = (optionId2) => turn?.done ? cancelled : { outcome: { outcome: "selected", optionId: optionId2 } };
4043
+ const question = acpQuestionPermission(params);
4044
+ if (question && !stream.observer.onQuestion) {
4045
+ stream.observer.onNotice?.(`${command} asked "${question.prompt}"${question.answers.length ? ` (${question.answers.join(" / ")})` : ""} and it was skipped: this screen cannot show it`);
4046
+ return optionAnswer(question.skipOptionId);
4047
+ }
4048
+ if (question) {
4049
+ const result = await this.askUser(stream, turn, {
4050
+ title: `${command} asks`,
4051
+ questions: [{ id: "answer", prompt: question.prompt, options: question.choices.map((choice) => ({ label: choice.name })), optional: true }]
4052
+ }, id, `${command} asked "${question.prompt}"${question.answers.length ? ` (${question.answers.join(" / ")})` : ""} and it was skipped: this screen cannot show it`);
4053
+ if (result.kind === "cancelled") return cancelled;
4054
+ const picked = result.answers.answer?.[0];
4055
+ return optionAnswer(question.choices.find((choice) => choice.name === picked)?.optionId ?? question.skipOptionId);
4056
+ }
4057
+ const exit = stream.observer.onQuestion ? acpPlanChoices(params) : void 0;
4058
+ if (exit) {
4059
+ const result = await this.askUser(stream, turn, {
4060
+ title: `${command} has a plan`,
4061
+ questions: [{ id: "plan", header: "Plan", prompt: exit.plan ?? String(params.toolCall?.title ?? "Leave plan mode?"), options: exit.choices.map((choice2) => ({ label: choice2.name })) }]
4062
+ }, id, `${command} asked to leave plan mode and it was left unanswered: this screen cannot show it`);
4063
+ if (result.kind === "cancelled") return cancelled;
4064
+ const picked = result.answers.plan?.[0];
4065
+ const choice = exit.choices.find((candidate) => candidate.name === picked);
4066
+ return choice ? optionAnswer(choice.optionId) : cancelled;
4067
+ }
4068
+ const readLive = turn?.input.currentPermissionMode;
4069
+ const liveMode = readLive ? await readLive().catch(quiet("harness/transport/acp-client")) : void 0;
4070
+ const plan = acpPermissionPlan(liveMode ?? turn?.input.permissionMode ?? "ask", params);
4071
+ let accepted = plan.action === "allow";
4072
+ const callId = typeof params.toolCall?.toolCallId === "string" ? params.toolCall.toolCallId : void 0;
4073
+ const opened = Boolean(turn && callId && !this.work.has(callId));
4074
+ if (opened) this.work.start({ id: callId, kind: "tool", label: String(params.toolCall?.title ?? "tool") });
4075
+ if (!accepted) {
4076
+ const title = String(params.toolCall?.title ?? params.toolCall?.name ?? "Approve tool");
4077
+ const detail = [
4078
+ acpApprovalDetail(params.toolCall),
4079
+ plan.allowIsPersistent ? "Approving grants this permanently: the agent offers no one-time option." : void 0
4080
+ ].filter(Boolean).join("\n") || void 0;
4081
+ if (turn) turn.approvals++;
4082
+ const prompt = this.openPrompt();
4083
+ if (id !== void 0) this.requestPrompts.set(String(id), prompt.abort);
4084
+ try {
4085
+ stream.observer.onPhase?.(`waiting for your approval: ${title}`);
4086
+ const diff = acpActivityEvent({ ...params.toolCall, sessionUpdate: "tool_call" })?.diff;
4087
+ accepted = plan.allowOptionId !== void 0 && await stream.observer.onApproval?.(title, detail, diff?.length ? { diff } : void 0, prompt.signal, callId) === true;
4088
+ } finally {
4089
+ if (id !== void 0) this.requestPrompts.delete(String(id));
4090
+ prompt.release();
4091
+ if (turn) {
4092
+ turn.approvals--;
4093
+ this.steerPause(turn);
4094
+ }
4095
+ }
4096
+ }
4097
+ if (opened && !accepted && turn) {
4098
+ this.work.end(callId);
4099
+ if (this.work.count() === 0) {
4100
+ this.steerPause(turn);
4101
+ }
4102
+ }
4103
+ if (turn?.done) return cancelled;
4104
+ const optionId = accepted ? plan.allowOptionId : plan.rejectOptionId;
4105
+ return optionId !== void 0 ? { outcome: { outcome: "selected", optionId } } : cancelled;
4106
+ }
4107
+ };
4108
+ function markMissingThread(error, wanted) {
4109
+ if (!(error instanceof Error)) return error;
4110
+ const code = error.rpcCode;
4111
+ const text = error.message;
4112
+ const notFound = code === -32002 || /not\s+found|does not exist|no such/i.test(text) && (text.includes(wanted) || /\b(session|thread|conversation|resource)\b/i.test(text));
4113
+ return notFound ? Object.assign(error, { nativeThreadInvalid: true }) : error;
4114
+ }
4115
+ function createAcpSession(options = {}) {
4116
+ return new AcpSessionImpl(options);
4117
+ }
4118
+ function runAcpTurn(input, options = {}) {
4119
+ return runOneTurn(createAcpSession(options), input);
4120
+ }
4121
+
4122
+ // src/turn/out-of-turn-record.ts
4123
+ var last = /* @__PURE__ */ new Map();
4124
+ var writing = /* @__PURE__ */ new Map();
4125
+ function outOfTurnRecorder(sessionId) {
4126
+ return (said) => {
4127
+ const previous = writing.get(sessionId) ?? Promise.resolve();
4128
+ const next = previous.then(async () => {
4129
+ const state = await readState({ transcripts: [sessionId] });
4130
+ const session = state.sessions.find((item) => item.id === sessionId);
4131
+ if (!session) return;
4132
+ const messages = [...session.messages ?? []];
4133
+ const tail = messages.at(-1);
4134
+ const known = last.get(sessionId);
4135
+ const continues = tail?.role === "assistant" && known?.kind === said.kind && tail.content === known.content;
4136
+ const content = said.mode === "replace" ? said.text : `${continues ? tail.content : ""}${said.text}`;
4137
+ if (continues) messages[messages.length - 1] = { ...tail, content };
4138
+ else messages.push({ role: "assistant", content });
4139
+ session.messages = messages;
4140
+ session.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
4141
+ last.set(sessionId, { kind: said.kind, content });
4142
+ await writeState(state);
4143
+ }).catch(quiet("turn/out-of-turn-record"));
4144
+ writing.set(sessionId, next);
4145
+ return next;
4146
+ };
4147
+ }
4148
+
4149
+ // src/harness/transport/native/held-vendor.ts
4150
+ var RELEASE_WAIT_MS = 5 * 60 * 1e3;
4151
+ var STOP_WAIT_MS = 2e3;
4152
+ var held = /* @__PURE__ */ new Map();
4153
+ var retiredHeld = /* @__PURE__ */ new Map();
4154
+ var gone = /* @__PURE__ */ new Map();
4155
+ function forget(sessionId, vendor) {
4156
+ if (held.get(sessionId) === vendor) {
4157
+ held.delete(sessionId);
4158
+ lifecycle("vendor.released");
4159
+ }
4160
+ const retired = retiredHeld.get(sessionId);
4161
+ if (retired?.delete(vendor) && !retired.size) retiredHeld.delete(sessionId);
4162
+ if (held.has(sessionId) || retiredHeld.has(sessionId)) return;
4163
+ for (const resolve of gone.get(sessionId)?.splice(0) ?? []) resolve();
4164
+ }
4165
+ function opensBackgroundTurn(record) {
4166
+ return record.type === "system" && (record.subtype === "init" || record.subtype === "task_notification");
4167
+ }
4168
+ function holdVendorProcess(options) {
4169
+ let channel;
4170
+ let exited = false;
4171
+ let closing = false;
4172
+ let resolveExit;
4173
+ const exit = new Promise((resolve) => {
4174
+ resolveExit = resolve;
4175
+ });
4176
+ const end = (ended) => {
4177
+ channel?.finish(ended);
4178
+ channel = void 0;
4179
+ };
4180
+ let retiredAgents;
4181
+ let inputEnded = false;
4182
+ let told;
4183
+ const tell = (ended) => {
4184
+ if (!ended.length) return;
4185
+ try {
4186
+ told?.(ended);
4187
+ } catch {
4188
+ }
4189
+ };
4190
+ const agentEnded = (agent, record) => {
4191
+ void endedAgentWork(
4192
+ agent,
4193
+ String(record.status ?? "completed"),
4194
+ typeof record.summary === "string" ? record.summary : "",
4195
+ typeof record.output_file === "string" ? record.output_file : void 0
4196
+ ).then((work2) => {
4197
+ if (told) tell([work2]);
4198
+ else options.workEnded?.([work2]);
4199
+ }).catch(quiet("harness/transport/native/held-vendor"));
4200
+ };
4201
+ const retiredRecord = (record) => {
4202
+ if (record.type !== "system" || record.subtype !== "task_notification" || typeof record.task_id !== "string") return;
4203
+ const agent = retiredAgents?.get(record.task_id);
4204
+ if (!agent) return;
4205
+ retiredAgents.delete(record.task_id);
4206
+ agentEnded(agent, record);
4207
+ };
4208
+ const vendor = {
4209
+ get agentWork() {
4210
+ return options.background.agentWork;
4211
+ },
4212
+ owner: options.owner,
4213
+ get retired() {
4214
+ return Boolean(retiredAgents);
4215
+ },
4216
+ agents: () => retiredAgents ? [...retiredAgents.values()] : options.background.agents(),
4217
+ retire(onEnded) {
4218
+ if (closing || exited || retiredAgents) return false;
4219
+ const running = options.background.agents();
4220
+ if (!running.length) return false;
4221
+ retiredAgents = new Map(running.map((agent) => [agent.id, agent]));
4222
+ told = onEnded;
4223
+ end("superseded");
4224
+ if (held.get(options.sessionId) === vendor) held.delete(options.sessionId);
4225
+ const set = retiredHeld.get(options.sessionId) ?? /* @__PURE__ */ new Set();
4226
+ set.add(vendor);
4227
+ retiredHeld.set(options.sessionId, set);
4228
+ lifecycle("vendor.held.retired", { agents: running.length });
4229
+ return true;
4230
+ },
4231
+ line(text, record) {
4232
+ if (retiredAgents) {
4233
+ if (record) {
4234
+ retiredRecord(record);
4235
+ options.background.note(record);
4236
+ }
4237
+ if (!retiredAgents.size && !inputEnded && !options.background.settled && options.background.quiet) {
4238
+ inputEnded = true;
4239
+ options.endInput();
4240
+ }
4241
+ return;
4242
+ }
4243
+ if (record?.type === "system" && record.subtype === "task_notification" && typeof record.task_id === "string") {
4244
+ const agent = options.background.agents().find((work2) => work2.id === record.task_id);
4245
+ if (agent && !closing) agentEnded(agent, record);
4246
+ }
4247
+ if (!channel && !closing && record && opensBackgroundTurn(record) && !options.background.settled) {
4248
+ channel = new BackgroundTurnChannel("structured-cli", "background-work");
4249
+ try {
4250
+ options.handler(channel);
4251
+ } catch {
4252
+ }
4253
+ }
4254
+ if (channel) {
4255
+ try {
4256
+ options.report(text, channel.observer, record);
4257
+ } catch {
4258
+ }
4259
+ }
4260
+ if (record) options.background.note(record);
4261
+ },
4262
+ quiet() {
4263
+ end("completed");
4264
+ },
4265
+ async close(stop = false) {
4266
+ closing = true;
4267
+ retiredAgents = void 0;
4268
+ forget(options.sessionId, vendor);
4269
+ end("superseded");
4270
+ options.endInput();
4271
+ if (exited) return;
4272
+ let timer;
4273
+ const stopped = await Promise.race([
4274
+ exit.then(() => false),
4275
+ new Promise((resolve) => {
4276
+ timer = setTimeout(() => resolve(true), stop ? STOP_WAIT_MS : RELEASE_WAIT_MS);
4277
+ timer.unref();
4278
+ })
4279
+ ]);
4280
+ if (timer) clearTimeout(timer);
4281
+ if (stopped) {
4282
+ options.release.terminate();
4283
+ await exit;
4284
+ }
4285
+ }
4286
+ };
4287
+ const released = options.release.release(() => {
4288
+ exited = true;
4289
+ end(options.background.settled ? "completed" : "closed");
4290
+ const lost = [...retiredAgents?.values() ?? []];
4291
+ retiredAgents = void 0;
4292
+ tell(lost.map((agent) => ({ ...agent, outcome: "cut-off", tail: "The process running it ended before it finished." })));
4293
+ forget(options.sessionId, vendor);
4294
+ resolveExit();
4295
+ });
4296
+ if (!released) return void 0;
4297
+ const previous = held.get(options.sessionId);
4298
+ held.set(options.sessionId, vendor);
4299
+ lifecycle("vendor.held", { pending: options.background.pending });
4300
+ if (previous) void previous.close();
4301
+ return vendor;
4302
+ }
4303
+ async function releaseHeldVendorProcess(sessionId) {
4304
+ const vendor = held.get(sessionId);
4305
+ if (!vendor) return false;
4306
+ await vendor.close();
4307
+ return true;
4308
+ }
4309
+ async function stopHeldVendorProcess(sessionId) {
4310
+ const vendors = [held.get(sessionId), ...retiredHeld.get(sessionId) ?? []].filter((vendor) => Boolean(vendor));
4311
+ await Promise.all(vendors.map((vendor) => vendor.close(true)));
4312
+ return vendors.length > 0;
4313
+ }
4314
+ function heldVendorOwner(sessionId) {
4315
+ return held.get(sessionId)?.owner;
4316
+ }
4317
+ function retireHeldVendorProcess(sessionId, onEnded) {
4318
+ return held.get(sessionId)?.retire(onEnded) ?? false;
4319
+ }
4320
+ function retiredHeldAgentCount(sessionId) {
4321
+ let count2 = 0;
4322
+ for (const vendor of retiredHeld.get(sessionId) ?? []) count2 += vendor.agents().length;
4323
+ return count2;
4324
+ }
4325
+ function hasHeldVendorProcess(sessionId) {
4326
+ return held.has(sessionId);
4327
+ }
4328
+ function whenHeldVendorGone(sessionId) {
4329
+ if (!held.has(sessionId) && !retiredHeld.has(sessionId)) return Promise.resolve();
4330
+ return new Promise((resolve) => {
4331
+ const waiting = gone.get(sessionId) ?? [];
4332
+ waiting.push(resolve);
4333
+ gone.set(sessionId, waiting);
4334
+ });
4335
+ }
4336
+ async function waitForHeldVendorSubagents(sessionId, signal) {
4337
+ while (held.get(sessionId)?.agentWork) {
4338
+ if (signal?.aborted) throw turnCancelledError();
4339
+ await sleep(200);
4340
+ }
4341
+ if (signal?.aborted) throw turnCancelledError();
4342
+ }
4343
+
4344
+ // src/turn/vendor-process.ts
4345
+ var nativeAvailableCommands = /* @__PURE__ */ new Map();
4346
+ function sessionNativeCommands(sessionId) {
4347
+ return nativeAvailableCommands.get(sessionId) ?? [];
4348
+ }
4349
+ var persistentTransports = /* @__PURE__ */ new Map();
4350
+ var TRANSPORT_SESSIONS = { codex: createCodexSession, acp: createAcpSession };
4351
+ var outOfTurnHandlers = /* @__PURE__ */ new Map();
4352
+ function setOutOfTurnHandler(sessionId, handler) {
4353
+ if (handler) outOfTurnHandlers.set(sessionId, handler);
4354
+ else outOfTurnHandlers.delete(sessionId);
4355
+ }
4356
+ var outOfTurnFor = (sessionId) => {
4357
+ const record = outOfTurnRecorder(sessionId);
4358
+ return (said) => {
4359
+ const handler = outOfTurnHandlers.get(sessionId);
4360
+ if (handler) handler(said);
4361
+ else void record(said);
4362
+ };
4363
+ };
4364
+ var workEndedHandlers = /* @__PURE__ */ new Map();
4365
+ function setWorkEndedHandler(sessionId, handler) {
4366
+ if (handler) workEndedHandlers.set(sessionId, handler);
4367
+ else {
4368
+ workEndedHandlers.delete(sessionId);
4369
+ ledgers.delete(sessionId);
4370
+ ledgerQueue.delete(sessionId);
4371
+ }
4372
+ }
4373
+ var accountMoveEffects = {
4374
+ leave: (sessionId, accountId) => leavePersistentTransport(sessionId, { accountId }),
4375
+ refuseTurn: (sessionId, accountId, error) => {
4376
+ const live = persistentTransports.get(sessionId);
4377
+ return live !== void 0 && keyOwner(live.key).accountId === accountId && live.session.failTurn(error);
4378
+ }
4379
+ };
4380
+ function observeSessionAccount(input) {
4381
+ return observeAccountHealth(input, accountMoveEffects);
4382
+ }
4383
+ var LEDGER_LIMIT = 500;
4384
+ var ledgers = /* @__PURE__ */ new Map();
4385
+ var ledgerQueue = /* @__PURE__ */ new Map();
4386
+ function reportEndedWork(sessionId, ended, from = {}) {
4387
+ if (!ended.length) return;
4388
+ const run = (ledgerQueue.get(sessionId) ?? Promise.resolve()).then(async () => {
4389
+ const ledger = ledgers.get(sessionId) ?? /* @__PURE__ */ new Map();
4390
+ ledgers.set(sessionId, ledger);
4391
+ const toTell = [];
4392
+ for (const work2 of ended) {
4393
+ const key = `${from.accountId ?? ""}:${work2.kind}:${work2.id}`;
4394
+ const previous = ledger.get(key);
4395
+ const failure = JSON.stringify(work2.failure ?? null);
4396
+ if (previous && previous.failure === failure) continue;
4397
+ const entry = { failure, told: previous?.told ?? false };
4398
+ ledger.set(key, entry);
4399
+ if (ledger.size > LEDGER_LIMIT) ledger.delete(ledger.keys().next().value);
4400
+ const kind = work2.failure && from.accountId ? await observeSessionAccount({ sessionId, accountId: from.accountId, evidence: work2.failure, source: work2.kind, ...from.harness ? { harness: from.harness } : {} }) : void 0;
4401
+ if (entry.told) continue;
4402
+ if (from.retired || kind === "quota-exhausted") {
4403
+ entry.told = true;
4404
+ toTell.push(work2);
4405
+ }
4406
+ }
4407
+ if (toTell.length) workEndedHandlers.get(sessionId)?.(toTell, from);
4408
+ }).catch(quiet("turn/vendor-process"));
4409
+ ledgerQueue.set(sessionId, run);
4410
+ }
4411
+ function keyOwner(key) {
4412
+ try {
4413
+ const [harness, accountId] = JSON.parse(key);
4414
+ return { ...typeof harness === "string" ? { harness } : {}, ...typeof accountId === "string" ? { accountId } : {} };
4415
+ } catch {
4416
+ return {};
4417
+ }
4418
+ }
4419
+ function childOptions(sessionId, key) {
4420
+ return {
4421
+ backgroundTurns: (turn) => vendorBackgroundTurnHandlers.get(sessionId)?.(turn),
4422
+ outOfTurn: outOfTurnFor(sessionId),
4423
+ workEnded: (ended, via) => {
4424
+ reportEndedWork(sessionId, ended, { ...keyOwner(key), retired: via.retired });
4425
+ retiredWorkChanged(sessionId);
4426
+ }
4427
+ };
4428
+ }
4429
+ var vendorBackgroundTurnHandlers = /* @__PURE__ */ new Map();
4430
+ function setVendorBackgroundTurnHandler(sessionId, handler) {
4431
+ if (handler) vendorBackgroundTurnHandlers.set(sessionId, handler);
4432
+ else vendorBackgroundTurnHandlers.delete(sessionId);
4433
+ }
4434
+ function vendorBackgroundTurnHandlerFor(sessionId) {
4435
+ return vendorBackgroundTurnHandlers.get(sessionId);
4436
+ }
4437
+ function vendorChildKey(harness, account, environment, workspace) {
4438
+ return JSON.stringify([harness.command, account.id, account.signedInAt, environment, workspace]);
4439
+ }
4440
+ function persistentTransportFor(sessionId, transport, key) {
4441
+ const existing = persistentTransports.get(sessionId);
4442
+ if (existing && existing.key === key && existing.transport === transport) return existing;
4443
+ if (existing) void leaveTransport(sessionId, existing);
4444
+ const standby = standbyTransports.get(sessionId);
4445
+ if (standby && standby.transport.key === key && standby.transport.transport === transport) {
4446
+ standbyTransports.delete(sessionId);
4447
+ persistentTransports.set(sessionId, standby.transport);
4448
+ return standby.transport;
4449
+ }
4450
+ const background = childOptions(sessionId, key);
4451
+ const created = {
4452
+ key,
4453
+ transport,
4454
+ session: transport === "codex-app-server" ? TRANSPORT_SESSIONS.codex(background) : TRANSPORT_SESSIONS.acp(background)
4455
+ };
4456
+ persistentTransports.set(sessionId, created);
4457
+ return created;
4458
+ }
4459
+ async function runningAgentCount(sessionId) {
4460
+ const work2 = await persistentTransports.get(sessionId)?.session.runningWork().catch(() => []);
4461
+ return (work2 ?? []).filter((item) => item.kind === "agent").length;
4462
+ }
4463
+ async function reapPersistentCommands(sessionId, which, reason) {
4464
+ const sessions = [persistentTransports.get(sessionId), ...retiredTransports.get(sessionId) ?? []];
4465
+ const reaped = [];
4466
+ for (const transport of sessions) reaped.push(...await transport?.session.reapCommands?.(which, reason).catch(() => []) ?? []);
4467
+ return reaped;
4468
+ }
4469
+ function hasPersistentTransport(sessionId) {
4470
+ return persistentTransports.has(sessionId);
4471
+ }
4472
+ var retiredTransports = /* @__PURE__ */ new Map();
4473
+ async function retiredRunning(sessionId) {
4474
+ const set = retiredTransports.get(sessionId);
4475
+ if (!set) return [];
4476
+ const running = [];
4477
+ for (const retired of [...set]) {
4478
+ if (await retired.session.backgroundWorkRunning().catch(() => false)) running.push(retired);
4479
+ else set.delete(retired);
4480
+ }
4481
+ if (!set.size) retiredTransports.delete(sessionId);
4482
+ return running;
4483
+ }
4484
+ async function persistentWorkRunning(sessionId) {
4485
+ if (await persistentTransports.get(sessionId)?.session.backgroundWorkRunning?.().catch(() => false)) return true;
4486
+ if (retiredHeldAgentCount(sessionId) > 0) return true;
4487
+ return (await retiredRunning(sessionId)).length > 0;
4488
+ }
4489
+ var retiredWorkListeners = /* @__PURE__ */ new Map();
4490
+ function setRetiredWorkListener(sessionId, listener) {
4491
+ if (listener) retiredWorkListeners.set(sessionId, listener);
4492
+ else retiredWorkListeners.delete(sessionId);
4493
+ }
4494
+ function retiredWorkChanged(sessionId) {
4495
+ const listener = retiredWorkListeners.get(sessionId);
4496
+ if (!listener) return;
4497
+ const work2 = { agents: 0, terminals: 0 };
4498
+ for (const retired of retiredTransports.get(sessionId) ?? []) {
4499
+ work2.agents += retired.session.retiredWork.agents;
4500
+ work2.terminals += retired.session.retiredWork.terminals;
4501
+ }
4502
+ work2.agents += retiredHeldAgentCount(sessionId);
4503
+ try {
4504
+ listener(work2);
4505
+ } catch {
4506
+ }
4507
+ }
4508
+ async function runningVendorAgents(sessionId) {
4509
+ const live = persistentTransports.get(sessionId);
4510
+ if (!live) return [];
4511
+ return (await live.session.runningWork().catch(() => [])).filter((work2) => work2.kind === "agent");
4512
+ }
4513
+ async function leaveTransport(sessionId, live) {
4514
+ if (await live.session.retire().catch(() => false)) {
4515
+ const set = retiredTransports.get(sessionId) ?? /* @__PURE__ */ new Set();
4516
+ set.add(live);
4517
+ retiredTransports.set(sessionId, set);
4518
+ retiredWorkChanged(sessionId);
4519
+ return;
4520
+ }
4521
+ await live.session.close().catch(quiet("turn/vendor-process"));
4522
+ }
4523
+ async function leavePersistentTransport(sessionId, only) {
4524
+ const live = persistentTransports.get(sessionId);
4525
+ if (!live) return;
4526
+ if (only && keyOwner(live.key).accountId !== only.accountId) return;
4527
+ persistentTransports.delete(sessionId);
4528
+ await leaveTransport(sessionId, live);
4529
+ }
4530
+ async function closePersistentTransport(sessionId) {
4531
+ if (sessionId === void 0) await Promise.all([...standbyTransports.keys()].map((id) => closeStandby(id)));
4532
+ const ids = sessionId === void 0 ? [.../* @__PURE__ */ new Set([...persistentTransports.keys(), ...retiredTransports.keys()])] : [sessionId];
4533
+ await Promise.all(ids.map(async (id) => {
4534
+ const live = persistentTransports.get(id);
4535
+ const retired = [...retiredTransports.get(id) ?? []];
4536
+ retiredTransports.delete(id);
4537
+ if (live) persistentTransports.delete(id);
4538
+ await Promise.all([live, ...retired].map((item) => item?.session.close().catch(quiet("turn/vendor-process"))));
4539
+ if (retired.length) retiredWorkChanged(id);
4540
+ }));
4541
+ }
4542
+ var standbyTransports = /* @__PURE__ */ new Map();
4543
+ function standbyFor(sessionId, accountId) {
4544
+ const standby = standbyTransports.get(sessionId);
4545
+ return standby?.accountId === accountId ? standby : void 0;
4546
+ }
4547
+ function openStandby(sessionId, accountId, transport, key, prepare) {
4548
+ void closeStandby(sessionId);
4549
+ const background = childOptions(sessionId, key);
4550
+ const created = {
4551
+ key,
4552
+ transport,
4553
+ session: transport === "codex-app-server" ? TRANSPORT_SESSIONS.codex(background) : TRANSPORT_SESSIONS.acp(background)
4554
+ };
4555
+ const standby = {
4556
+ accountId,
4557
+ transport: created,
4558
+ ready: prepare(created.session).then(() => true, () => {
4559
+ if (standbyTransports.get(sessionId) === standby) void closeStandby(sessionId);
4560
+ return false;
4561
+ })
4562
+ };
4563
+ standbyTransports.set(sessionId, standby);
4564
+ return standby;
4565
+ }
4566
+ async function closeStandby(sessionId) {
4567
+ const standby = standbyTransports.get(sessionId);
4568
+ if (!standby) return;
4569
+ standbyTransports.delete(sessionId);
4570
+ await standby.transport.session.close().catch(quiet("turn/vendor-process"));
4571
+ }
4572
+
4573
+ export {
4574
+ withoutOtherOrgThinkingNotice,
4575
+ turnStopReason,
4576
+ stopReasonNotice,
4577
+ countsOf,
4578
+ nativeUsageFromValue,
4579
+ StreamUsageTally,
4580
+ nativeTurnUsage,
4581
+ nativeSelfReportFromValue,
4582
+ turnShareOf,
4583
+ BackgroundWorkTracker,
4584
+ ABANDONED_WORK_MS,
4585
+ runCodexAppServerTurn,
4586
+ ProcessCost,
4587
+ BackgroundAgentRows,
4588
+ classifyTurnFailure,
4589
+ refusalEndingReply,
4590
+ isVendorRefusalSaid,
4591
+ acpAvailableCommands,
4592
+ runAcpTurn,
4593
+ outOfTurnRecorder,
4594
+ holdVendorProcess,
4595
+ releaseHeldVendorProcess,
4596
+ stopHeldVendorProcess,
4597
+ heldVendorOwner,
4598
+ retireHeldVendorProcess,
4599
+ hasHeldVendorProcess,
4600
+ whenHeldVendorGone,
4601
+ waitForHeldVendorSubagents,
4602
+ nativeAvailableCommands,
4603
+ sessionNativeCommands,
4604
+ persistentTransports,
4605
+ setOutOfTurnHandler,
4606
+ setWorkEndedHandler,
4607
+ observeSessionAccount,
4608
+ reportEndedWork,
4609
+ setVendorBackgroundTurnHandler,
4610
+ vendorBackgroundTurnHandlerFor,
4611
+ vendorChildKey,
4612
+ persistentTransportFor,
4613
+ runningAgentCount,
4614
+ reapPersistentCommands,
4615
+ hasPersistentTransport,
4616
+ persistentWorkRunning,
4617
+ setRetiredWorkListener,
4618
+ retiredWorkChanged,
4619
+ runningVendorAgents,
4620
+ leavePersistentTransport,
4621
+ closePersistentTransport,
4622
+ standbyFor,
4623
+ openStandby,
4624
+ closeStandby
4625
+ };