@staff0rd/assist 0.1143.1 → 0.1143.3

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 (606) hide show
  1. package/dist/acceptanceCriteria-CJ4GRITK.js +44 -0
  2. package/dist/activity-2SEJVUW5.js +73 -0
  3. package/dist/add-HXSZYGPR.js +51 -0
  4. package/dist/add-QQQ472AZ.js +250 -0
  5. package/dist/add-XWJN42HG.js +140 -0
  6. package/dist/addActivity-XDHJ7CV5.js +120 -0
  7. package/dist/addPhase-XZO6BH26.js +152 -0
  8. package/dist/addRule-J432LIS3.js +102 -0
  9. package/dist/addUserRule-XO2BNQFH.js +136 -0
  10. package/dist/adviceFragments-5XVE6JXX.js +41 -0
  11. package/dist/advise-YDAJA5NI.js +96 -0
  12. package/dist/analyze-2ECBFV3E.js +63 -0
  13. package/dist/ask-ESCDDQH5.js +47 -0
  14. package/dist/askCheck-WILQF3JN.js +303 -0
  15. package/dist/askDesign-RDIXLTMM.js +137 -0
  16. package/dist/askQuestion-EQV37YPA.js +149 -0
  17. package/dist/associateGithub-VYQUEKWJ.js +95 -0
  18. package/dist/associateJira-EUNZOJJC.js +83 -0
  19. package/dist/backup-3SNDW5JN.js +64 -0
  20. package/dist/blockCodeComments-PZHXN2WG.js +311 -0
  21. package/dist/branch-7NZ5K4AI.js +98 -0
  22. package/dist/browserConsole-6ZRED7DG.js +50 -0
  23. package/dist/browserInspect-2IOKKWOF.js +42 -0
  24. package/dist/browserRun-JJVVNL6H.js +52 -0
  25. package/dist/browserSnapshot-Q3DUNUYP.js +32 -0
  26. package/dist/browserStatus-MEQAEC3K.js +38 -0
  27. package/dist/built-version +1 -1
  28. package/dist/chart-4G75ADCW.js +80 -0
  29. package/dist/check-QRHG4J7G.js +219 -0
  30. package/dist/checkBuildLocks-UBGUSNX5.js +9 -0
  31. package/dist/chunk-2DCOBBPI.js +50 -0
  32. package/dist/chunk-2EW62DM5.js +17 -0
  33. package/dist/chunk-2HT3GIJD.js +130 -0
  34. package/dist/chunk-2JYMVJGZ.js +21 -0
  35. package/dist/chunk-2KG6ZPX4.js +52 -0
  36. package/dist/chunk-2O7TIRCQ.js +39 -0
  37. package/dist/chunk-3E7RVOMC.js +27 -0
  38. package/dist/chunk-3FSX26XC.js +25 -0
  39. package/dist/chunk-3JXMQFUS.js +14 -0
  40. package/dist/chunk-3KLTYFPV.js +57 -0
  41. package/dist/chunk-3NK55YVZ.js +48 -0
  42. package/dist/chunk-3OMKOT6D.js +14 -0
  43. package/dist/chunk-3PM5JCHE.js +72 -0
  44. package/dist/chunk-3QKE2ONF.js +39 -0
  45. package/dist/chunk-3XQHTIHW.js +20 -0
  46. package/dist/chunk-43GYFW24.js +170 -0
  47. package/dist/chunk-46B7OBV4.js +21 -0
  48. package/dist/chunk-4BVUY25U.js +21 -0
  49. package/dist/chunk-4GMAYXOS.js +18 -0
  50. package/dist/chunk-4HKB2TAG.js +11 -0
  51. package/dist/chunk-4JIXM5NT.js +21 -0
  52. package/dist/chunk-4L7TQE67.js +22 -0
  53. package/dist/chunk-4TIDERIW.js +12 -0
  54. package/dist/chunk-4XHBAEMS.js +37 -0
  55. package/dist/chunk-4Y4ADPEK.js +10 -0
  56. package/dist/chunk-4YAIQN3S.js +77 -0
  57. package/dist/chunk-4YHDWC5E.js +33 -0
  58. package/dist/chunk-547VKFOA.js +15 -0
  59. package/dist/chunk-54QTHCXV.js +12 -0
  60. package/dist/chunk-556BOFTS.js +44 -0
  61. package/dist/chunk-5CCCIT5E.js +33 -0
  62. package/dist/chunk-5G5VG5P7.js +14 -0
  63. package/dist/chunk-5JOVEUBS.js +17 -0
  64. package/dist/chunk-5KSIOK73.js +25 -0
  65. package/dist/chunk-5MFQ7T3G.js +40 -0
  66. package/dist/chunk-5PKWV3WT.js +8 -0
  67. package/dist/chunk-5VW2GS73.js +42 -0
  68. package/dist/chunk-5WQDLREX.js +40 -0
  69. package/dist/chunk-66EUBGD6.js +193 -0
  70. package/dist/chunk-6DGPQ67E.js +26 -0
  71. package/dist/chunk-6EYCU3MQ.js +41 -0
  72. package/dist/chunk-6G2ADBNV.js +19 -0
  73. package/dist/chunk-6H4DP3ZG.js +14 -0
  74. package/dist/chunk-6MNOEMDU.js +45 -0
  75. package/dist/chunk-6NDXAN45.js +90 -0
  76. package/dist/chunk-6NXP34PE.js +20 -0
  77. package/dist/chunk-6PF5BEEE.js +37 -0
  78. package/dist/chunk-6SOPR77J.js +12 -0
  79. package/dist/chunk-6T53CG7D.js +56 -0
  80. package/dist/chunk-7CEIET2O.js +31 -0
  81. package/dist/chunk-7DSWCPDZ.js +225 -0
  82. package/dist/chunk-7HNRCA3N.js +12 -0
  83. package/dist/chunk-7MUAIGYQ.js +56 -0
  84. package/dist/chunk-7NPZZRMK.js +77 -0
  85. package/dist/chunk-7O466DJY.js +36 -0
  86. package/dist/chunk-7TT6C4IC.js +100 -0
  87. package/dist/chunk-7ZN4KX7V.js +26 -0
  88. package/dist/chunk-ABLDOQ4B.js +42 -0
  89. package/dist/chunk-ADIYP3KC.js +11 -0
  90. package/dist/chunk-ADLCDG2V.js +61 -0
  91. package/dist/chunk-AKF654AT.js +32 -0
  92. package/dist/chunk-ALAS5LZJ.js +22 -0
  93. package/dist/chunk-ANCYNQJA.js +16 -0
  94. package/dist/chunk-APS7GTRT.js +23 -0
  95. package/dist/chunk-APZ6ZTDA.js +8 -0
  96. package/dist/chunk-AVLELL42.js +34 -0
  97. package/dist/chunk-AWAUWR2H.js +258 -0
  98. package/dist/chunk-B3JSQA5D.js +25 -0
  99. package/dist/chunk-B5ZOANOD.js +51 -0
  100. package/dist/chunk-B6RAZW2L.js +14 -0
  101. package/dist/chunk-B7B26YPF.js +6 -0
  102. package/dist/chunk-BAHQJHYD.js +16 -0
  103. package/dist/chunk-BBXEZVRL.js +38 -0
  104. package/dist/chunk-BFQSGIN6.js +37 -0
  105. package/dist/chunk-BJDGVLYX.js +20 -0
  106. package/dist/chunk-BO5JCCC5.js +17 -0
  107. package/dist/chunk-BV2V6RTH.js +89 -0
  108. package/dist/chunk-BVHK2VVT.js +31 -0
  109. package/dist/chunk-C3MGHR3N.js +25 -0
  110. package/dist/chunk-CDD4ZTG7.js +31 -0
  111. package/dist/chunk-CDU6M5IX.js +50 -0
  112. package/dist/chunk-CGYVYHMM.js +49 -0
  113. package/dist/chunk-CSQLE62N.js +7450 -0
  114. package/dist/chunk-CXJJGUTK.js +44 -0
  115. package/dist/chunk-D7UZLH36.js +8 -0
  116. package/dist/chunk-DBQTGW7F.js +48 -0
  117. package/dist/chunk-DIAC4XYA.js +29 -0
  118. package/dist/chunk-DISNKALJ.js +74 -0
  119. package/dist/chunk-DS2YJZZY.js +34 -0
  120. package/dist/chunk-DZGYHAE7.js +31 -0
  121. package/dist/chunk-E36L7ASL.js +19 -0
  122. package/dist/chunk-E7AZAWIV.js +478 -0
  123. package/dist/chunk-EF7AXKON.js +187 -0
  124. package/dist/chunk-EHRQ6OST.js +53 -0
  125. package/dist/chunk-ENBVLWTC.js +25 -0
  126. package/dist/chunk-ENTJ2N5Y.js +34 -0
  127. package/dist/chunk-ERAGZGT5.js +166 -0
  128. package/dist/chunk-ERG23IG5.js +12 -0
  129. package/dist/chunk-EW2ZM2PC.js +6 -0
  130. package/dist/chunk-EYM57SNL.js +60 -0
  131. package/dist/chunk-F2GXOU5H.js +171 -0
  132. package/dist/chunk-F2LP5MBV.js +26 -0
  133. package/dist/chunk-FFKJYEDJ.js +73 -0
  134. package/dist/chunk-FOPR6LRY.js +121 -0
  135. package/dist/chunk-FPWL4VRC.js +12 -0
  136. package/dist/chunk-FVZP4ULO.js +14 -0
  137. package/dist/chunk-FYYZG4GY.js +47 -0
  138. package/dist/chunk-G3ROBZ4I.js +31 -0
  139. package/dist/chunk-G44QYJ57.js +106 -0
  140. package/dist/chunk-GF4MNBOX.js +95 -0
  141. package/dist/chunk-GL5GKF5A.js +68 -0
  142. package/dist/chunk-GLIYWSW7.js +208 -0
  143. package/dist/chunk-GOGGPW2L.js +143 -0
  144. package/dist/chunk-GQF23TWI.js +14 -0
  145. package/dist/chunk-GQMP5NS4.js +15 -0
  146. package/dist/chunk-GRXFWFGP.js +49 -0
  147. package/dist/chunk-GVI4JSG7.js +13 -0
  148. package/dist/chunk-GVVK5XFZ.js +42 -0
  149. package/dist/chunk-GYAXLTV6.js +37 -0
  150. package/dist/chunk-H6LFISSF.js +40 -0
  151. package/dist/chunk-HCANRBFK.js +19 -0
  152. package/dist/chunk-HHKS3UZB.js +16 -0
  153. package/dist/chunk-HKGCLAZ7.js +8 -0
  154. package/dist/chunk-HN7MFXZ7.js +46 -0
  155. package/dist/chunk-HSWDSL22.js +50 -0
  156. package/dist/chunk-I2ZQXBOS.js +108 -0
  157. package/dist/chunk-I3TEQBTO.js +88 -0
  158. package/dist/chunk-I5MLH7WJ.js +27 -0
  159. package/dist/chunk-IBPSXDUB.js +8 -0
  160. package/dist/chunk-IDFJE5DP.js +224 -0
  161. package/dist/chunk-IEK6CQQH.js +23 -0
  162. package/dist/chunk-IIFOAUOM.js +34 -0
  163. package/dist/chunk-IMKMNPRL.js +114 -0
  164. package/dist/chunk-INBM4BQQ.js +27 -0
  165. package/dist/chunk-IOKBCYSG.js +29 -0
  166. package/dist/chunk-IOYGR6YV.js +23 -0
  167. package/dist/chunk-IRUDR6GR.js +63 -0
  168. package/dist/chunk-IV7Z4UVQ.js +150 -0
  169. package/dist/chunk-IVBWOIGE.js +33 -0
  170. package/dist/chunk-IYTAHYEL.js +98 -0
  171. package/dist/chunk-IZBQH3LW.js +17 -0
  172. package/dist/chunk-J3C454L5.js +741 -0
  173. package/dist/chunk-J3GISX67.js +23 -0
  174. package/dist/chunk-J7XASX4N.js +733 -0
  175. package/dist/chunk-JHBA5IZR.js +20 -0
  176. package/dist/chunk-JHIGA7GN.js +43 -0
  177. package/dist/chunk-JIWFLALZ.js +269 -0
  178. package/dist/chunk-JM57BCD6.js +30 -0
  179. package/dist/chunk-JNCFHWBK.js +30 -0
  180. package/dist/chunk-JNEYUOQ3.js +83 -0
  181. package/dist/chunk-JPM7HCLI.js +23 -0
  182. package/dist/chunk-JPRADR2E.js +10 -0
  183. package/dist/chunk-JRK7JDU4.js +30 -0
  184. package/dist/chunk-JVG5AJA2.js +29 -0
  185. package/dist/chunk-JVTCXR7C.js +72 -0
  186. package/dist/chunk-JW6QOUMN.js +18 -0
  187. package/dist/chunk-K45LIKCT.js +37 -0
  188. package/dist/chunk-K4T24UGW.js +18 -0
  189. package/dist/chunk-K4TQJQWA.js +44 -0
  190. package/dist/chunk-K5LOYASR.js +18 -0
  191. package/dist/chunk-K6NKWRK4.js +30 -0
  192. package/dist/chunk-KD2PWI4Z.js +48 -0
  193. package/dist/chunk-KGFZYUE2.js +54 -0
  194. package/dist/chunk-KLEL6TMJ.js +22 -0
  195. package/dist/chunk-KNXHXMFT.js +77 -0
  196. package/dist/chunk-KP5S3FE5.js +13 -0
  197. package/dist/chunk-KUCVY5R7.js +40 -0
  198. package/dist/chunk-KY77XKAU.js +26 -0
  199. package/dist/chunk-L363MNYZ.js +14 -0
  200. package/dist/chunk-LBAPKP6M.js +473 -0
  201. package/dist/chunk-LBPOEGTS.js +271 -0
  202. package/dist/chunk-LDVATRUW.js +23 -0
  203. package/dist/chunk-LFRSZIAS.js +13 -0
  204. package/dist/chunk-LGMCQUJJ.js +40 -0
  205. package/dist/chunk-LKDW2GWH.js +9 -0
  206. package/dist/chunk-LMHILP5H.js +36 -0
  207. package/dist/chunk-LMUTL44M.js +58 -0
  208. package/dist/chunk-LOP6Y256.js +18 -0
  209. package/dist/chunk-LSBUNT4X.js +32 -0
  210. package/dist/chunk-M3O2BTJG.js +12 -0
  211. package/dist/chunk-M3QEBIQL.js +855 -0
  212. package/dist/chunk-MBPVW7BY.js +63 -0
  213. package/dist/chunk-MELBVXKL.js +36 -0
  214. package/dist/chunk-MJ44T7R4.js +28 -0
  215. package/dist/chunk-MJ4RLQ5N.js +177 -0
  216. package/dist/chunk-MJLABLH5.js +58 -0
  217. package/dist/chunk-MODUPHYS.js +20 -0
  218. package/dist/chunk-MRUIXQXS.js +29 -0
  219. package/dist/chunk-MSKC2RCS.js +17 -0
  220. package/dist/chunk-MY4TNZNI.js +36 -0
  221. package/dist/chunk-N65VOEFI.js +23 -0
  222. package/dist/chunk-N755UYFK.js +58 -0
  223. package/dist/chunk-NBADZOXB.js +24 -0
  224. package/dist/chunk-NGTSPXSJ.js +9 -0
  225. package/dist/chunk-NGYZK6AF.js +18 -0
  226. package/dist/chunk-NH33OKZQ.js +23 -0
  227. package/dist/chunk-NOHNPOQK.js +49 -0
  228. package/dist/chunk-NPQGX4IO.js +16 -0
  229. package/dist/chunk-NWNODYLQ.js +25 -0
  230. package/dist/chunk-NYEGRDOK.js +191 -0
  231. package/dist/chunk-NZYSENRR.js +50 -0
  232. package/dist/chunk-O5JIFWMQ.js +39 -0
  233. package/dist/chunk-O5NYB4W5.js +31 -0
  234. package/dist/chunk-O6GPPB6G.js +26 -0
  235. package/dist/chunk-O6HFT23O.js +39 -0
  236. package/dist/chunk-OBC245PJ.js +39 -0
  237. package/dist/chunk-ODLSWRTS.js +21 -0
  238. package/dist/chunk-OGJ6AZK4.js +9 -0
  239. package/dist/chunk-ONODYZ2H.js +146 -0
  240. package/dist/chunk-ORSRBZ2X.js +15 -0
  241. package/dist/chunk-OU6Q5ZS3.js +16 -0
  242. package/dist/chunk-OUT62LF4.js +111 -0
  243. package/dist/chunk-OZNYQOQK.js +25 -0
  244. package/dist/chunk-P253KAVC.js +75 -0
  245. package/dist/chunk-P26XSDFU.js +91 -0
  246. package/dist/chunk-P3RGVQ5B.js +12 -0
  247. package/dist/chunk-P7FVAGFQ.js +52 -0
  248. package/dist/chunk-PCF66ALO.js +39 -0
  249. package/dist/chunk-PD2BTMEY.js +598 -0
  250. package/dist/chunk-PGQK356A.js +22 -0
  251. package/dist/chunk-PIDKNOD6.js +25 -0
  252. package/dist/chunk-PNOSR4S4.js +152 -0
  253. package/dist/chunk-PRYIRRAS.js +21 -0
  254. package/dist/chunk-PURNABFX.js +22 -0
  255. package/dist/chunk-PXQTFJ2N.js +216 -0
  256. package/dist/chunk-PYACTCZ2.js +13 -0
  257. package/dist/chunk-PZAEU7LL.js +23 -0
  258. package/dist/chunk-Q35724GR.js +51 -0
  259. package/dist/chunk-Q55RN3EG.js +43 -0
  260. package/dist/chunk-Q7RUUXND.js +40 -0
  261. package/dist/chunk-Q7YVMIA3.js +32 -0
  262. package/dist/chunk-QAJUCN3A.js +76 -0
  263. package/dist/chunk-QDQ6A2MZ.js +23 -0
  264. package/dist/chunk-QJRCKXTM.js +38 -0
  265. package/dist/chunk-QKHOYKUQ.js +362 -0
  266. package/dist/chunk-QPRFHNX7.js +24 -0
  267. package/dist/chunk-QR7KY3Y6.js +19 -0
  268. package/dist/chunk-QU6OQZJ2.js +56 -0
  269. package/dist/chunk-QVQ2OJXX.js +144 -0
  270. package/dist/chunk-R2HLLDFE.js +36 -0
  271. package/dist/chunk-R33SW6V2.js +104 -0
  272. package/dist/chunk-R72E45HQ.js +506 -0
  273. package/dist/chunk-RFMBA6WA.js +18 -0
  274. package/dist/chunk-RIMA7EFJ.js +35 -0
  275. package/dist/chunk-RNFWWESE.js +9 -0
  276. package/dist/chunk-ROBNJX4W.js +68 -0
  277. package/dist/chunk-ROCHUNJI.js +36 -0
  278. package/dist/chunk-RPRL6G4R.js +218 -0
  279. package/dist/chunk-RSLB4ODM.js +30 -0
  280. package/dist/chunk-RTYIICCX.js +24 -0
  281. package/dist/chunk-RVABNGZW.js +46 -0
  282. package/dist/chunk-RXKI4XAU.js +21 -0
  283. package/dist/chunk-S3I6PZTN.js +438 -0
  284. package/dist/chunk-S4S2DD5Z.js +16 -0
  285. package/dist/chunk-S4Y7TLRT.js +12 -0
  286. package/dist/chunk-S6FVZYHH.js +16 -0
  287. package/dist/chunk-S6XYTJU2.js +37 -0
  288. package/dist/chunk-SB4BG7PH.js +159 -0
  289. package/dist/chunk-SDMBTSYP.js +15 -0
  290. package/dist/chunk-SDOEWLEE.js +22 -0
  291. package/dist/chunk-SEXIHLGA.js +16 -0
  292. package/dist/chunk-SSKHLBQB.js +15 -0
  293. package/dist/chunk-STUWMYJ3.js +3941 -0
  294. package/dist/chunk-SW7FSLHP.js +26 -0
  295. package/dist/chunk-T2DY3T55.js +10 -0
  296. package/dist/chunk-T4TPIDXO.js +111 -0
  297. package/dist/chunk-T5WE33UZ.js +70 -0
  298. package/dist/chunk-T7ZPGAB5.js +192 -0
  299. package/dist/chunk-TCTX3UXU.js +19 -0
  300. package/dist/chunk-TJGF3Z72.js +12 -0
  301. package/dist/chunk-TK4AJIJZ.js +47 -0
  302. package/dist/chunk-TQCCEWWN.js +89 -0
  303. package/dist/chunk-TUPSNHFZ.js +49 -0
  304. package/dist/chunk-TVQY3HPZ.js +43 -0
  305. package/dist/chunk-TZ5PVDAR.js +48 -0
  306. package/dist/chunk-U732RAGX.js +240 -0
  307. package/dist/chunk-UEWARAPX.js +37 -0
  308. package/dist/chunk-UGGH3MEX.js +26 -0
  309. package/dist/chunk-UJAMN3ML.js +85 -0
  310. package/dist/chunk-UJBW7FVI.js +384 -0
  311. package/dist/chunk-UJX7N737.js +101 -0
  312. package/dist/chunk-UN4ABKA7.js +48 -0
  313. package/dist/chunk-UP6QV5BJ.js +14 -0
  314. package/dist/chunk-US6TNW5V.js +28 -0
  315. package/dist/chunk-USKD27FY.js +11 -0
  316. package/dist/chunk-USVQT2SR.js +94 -0
  317. package/dist/chunk-UU77KEL6.js +20 -0
  318. package/dist/chunk-UYD7R4HL.js +26 -0
  319. package/dist/chunk-VABNWHSE.js +31 -0
  320. package/dist/chunk-VAGZIGNN.js +54 -0
  321. package/dist/chunk-VDE2QVT4.js +14 -0
  322. package/dist/chunk-VDXS55BC.js +62 -0
  323. package/dist/chunk-VEZ3FL5H.js +16 -0
  324. package/dist/chunk-VF2SKQIN.js +79 -0
  325. package/dist/chunk-VNPRH5XZ.js +143 -0
  326. package/dist/chunk-VPMI4LV2.js +25 -0
  327. package/dist/chunk-VQZVG7KJ.js +46 -0
  328. package/dist/chunk-VRQ4WDF7.js +22 -0
  329. package/dist/chunk-W5FPQALS.js +36 -0
  330. package/dist/chunk-W6UBSIJA.js +50 -0
  331. package/dist/chunk-W7TRZLEM.js +23 -0
  332. package/dist/chunk-WDODIKZ4.js +72 -0
  333. package/dist/chunk-WG3TXZMV.js +70 -0
  334. package/dist/chunk-WG4UDKA2.js +12 -0
  335. package/dist/chunk-WGV2ELBS.js +41 -0
  336. package/dist/chunk-WIG7VKXE.js +92 -0
  337. package/dist/chunk-WOGUXGZS.js +32 -0
  338. package/dist/chunk-WUG2UGQC.js +136 -0
  339. package/dist/chunk-WXQ3EA5H.js +12 -0
  340. package/dist/chunk-WYNRHOR7.js +69 -0
  341. package/dist/chunk-WYVUP7Z3.js +33 -0
  342. package/dist/chunk-X44VETJF.js +13 -0
  343. package/dist/chunk-X6ETCS7E.js +656 -0
  344. package/dist/chunk-XA3VSUG6.js +72 -0
  345. package/dist/chunk-XADYGSUA.js +25 -0
  346. package/dist/chunk-XDIVXGPQ.js +73 -0
  347. package/dist/chunk-XEJODD6D.js +6 -0
  348. package/dist/chunk-XGG4NZLE.js +210 -0
  349. package/dist/chunk-XSJGIJEE.js +8 -0
  350. package/dist/chunk-XT3AOF2P.js +16 -0
  351. package/dist/chunk-XTPBXBZA.js +11 -0
  352. package/dist/chunk-XV2STPP6.js +45 -0
  353. package/dist/chunk-XV6BO5MK.js +28 -0
  354. package/dist/chunk-XXXMWMVQ.js +208 -0
  355. package/dist/chunk-XY5OS2GH.js +147 -0
  356. package/dist/chunk-XZFSW5AY.js +217 -0
  357. package/dist/chunk-Y2KEHWBZ.js +35 -0
  358. package/dist/chunk-Y3JV5CEL.js +19 -0
  359. package/dist/chunk-Y3R4C2P7.js +231 -0
  360. package/dist/chunk-Y46IKU4U.js +46 -0
  361. package/dist/chunk-YC3CIJQN.js +22 -0
  362. package/dist/chunk-YDA62L6J.js +147 -0
  363. package/dist/chunk-YIBSK5OC.js +13 -0
  364. package/dist/chunk-YJ72SXVD.js +12 -0
  365. package/dist/chunk-YKVLG4SZ.js +12 -0
  366. package/dist/chunk-YNHPTUHS.js +75 -0
  367. package/dist/chunk-YOFY27RM.js +10 -0
  368. package/dist/chunk-YPQ6OZFB.js +103 -0
  369. package/dist/chunk-YQ3CNWB3.js +54 -0
  370. package/dist/chunk-YS3HSXSJ.js +16 -0
  371. package/dist/chunk-YSNIMCKC.js +8 -0
  372. package/dist/chunk-YTIVOMM3.js +22 -0
  373. package/dist/chunk-YVL3NXEB.js +6 -0
  374. package/dist/chunk-YXXKT6LL.js +513 -0
  375. package/dist/chunk-YZ5KJFYU.js +8 -0
  376. package/dist/chunk-Z2YQQYCQ.js +64 -0
  377. package/dist/chunk-Z64YKE5O.js +208 -0
  378. package/dist/chunk-Z76MGO4R.js +284 -0
  379. package/dist/chunk-ZABRGL2F.js +45 -0
  380. package/dist/chunk-ZAMEG3EN.js +470 -0
  381. package/dist/chunk-ZDSSSQZZ.js +12 -0
  382. package/dist/chunk-ZFX4EZMW.js +20 -0
  383. package/dist/chunk-ZKVDVSCE.js +61 -0
  384. package/dist/chunk-ZLRZR64W.js +36 -0
  385. package/dist/chunk-ZMH7UZNP.js +14 -0
  386. package/dist/chunk-ZO7NYS25.js +18 -0
  387. package/dist/chunk-ZSHH4XS6.js +11 -0
  388. package/dist/chunk-ZWTRFLA6.js +31 -0
  389. package/dist/chunk-ZYE25KR3.js +12 -0
  390. package/dist/chunk-ZYK7V4PG.js +22 -0
  391. package/dist/clean-W43XKMR2.js +49 -0
  392. package/dist/cliHook-QGUENERI.js +96 -0
  393. package/dist/cliHookCheck-VLLUDLZD.js +74 -0
  394. package/dist/cloneRepo-LSIV3K3X.js +80 -0
  395. package/dist/closeSession-I2J2ICU4.js +30 -0
  396. package/dist/codeCommentConfirm-LGYBP6JX.js +69 -0
  397. package/dist/codeCommentSet-2YWQJXI2.js +115 -0
  398. package/dist/codexHook-24HGGAM3.js +200 -0
  399. package/dist/codexHookTrust-YYBCCR7P.js +59 -0
  400. package/dist/commands/sessions/web/bundle.js +257 -257
  401. package/dist/comment-R5MBHRIJ.js +46 -0
  402. package/dist/comment-SAOYKB2J.js +17 -0
  403. package/dist/commentIssue-PDIQVTZM.js +43 -0
  404. package/dist/comments-ABF3S3O5.js +56 -0
  405. package/dist/commit-OWV2KIOD.js +511 -0
  406. package/dist/commits-QFWMYJC5.js +146 -0
  407. package/dist/configGet-42P4ONFD.js +94 -0
  408. package/dist/configImportRepos-ZIUYOKHH.js +142 -0
  409. package/dist/configImportUser-NWUPLRQE.js +177 -0
  410. package/dist/configKeys-HFGEHZBT.js +69 -0
  411. package/dist/configKeys-OGJBDYG6.js +73 -0
  412. package/dist/configList-CBYHO432.js +75 -0
  413. package/dist/configSet-3UHHWKDP.js +136 -0
  414. package/dist/configUnset-LYGRTYB3.js +121 -0
  415. package/dist/configure-ETWPCRNG.js +86 -0
  416. package/dist/coverage-G7J25BUX.js +17 -0
  417. package/dist/createIssue-AIQ3U4LC.js +357 -0
  418. package/dist/cyclomatic-7ZFTN5VN.js +18 -0
  419. package/dist/daemonStatus-YXGIS55D.js +112 -0
  420. package/dist/del-NHH7NU3Y.js +44 -0
  421. package/dist/deleteCommentCmd-SAG7WMDV.js +73 -0
  422. package/dist/denyAdd-YXXNFWMO.js +29 -0
  423. package/dist/denyList-IZVZEOSD.js +43 -0
  424. package/dist/denyRemove-4IUYBEMU.js +30 -0
  425. package/dist/deps-RSUOIZPE.js +117 -0
  426. package/dist/docsConfirm-2LAEAX3R.js +97 -0
  427. package/dist/docsUnlock-SCPIWHT5.js +93 -0
  428. package/dist/doctorNodes-KURLWXJF.js +131 -0
  429. package/dist/done-ZQCDA2OJ.js +92 -0
  430. package/dist/drainDaemon-LCQQ3EP4.js +96 -0
  431. package/dist/dropRetiredTables-JBLALSG5.js +31 -0
  432. package/dist/edit-CFPOK62A.js +133 -0
  433. package/dist/editHook-YPYSRJLU.js +388 -0
  434. package/dist/editIssue-C2G7D3VJ.js +281 -0
  435. package/dist/editIssueComment-5SIYQKI6.js +68 -0
  436. package/dist/exportBacklog-NGFOXXUG.js +24 -0
  437. package/dist/extension-YYRD5EM6.js +32 -0
  438. package/dist/extract-SGYOCBTT.js +688 -0
  439. package/dist/fixConflict-SW33MRTL.js +66 -0
  440. package/dist/fixStructure-4UTN5ED6.js +436 -0
  441. package/dist/fixed-OTDA7M25.js +72 -0
  442. package/dist/forbiddenStrings-GVXIN7QW.js +88 -0
  443. package/dist/formatConfiguredCommands-WI25I2JJ.js +19 -0
  444. package/dist/getBacklogDir-AVGEKM42.js +18 -0
  445. package/dist/halstead-CMFRMXT6.js +18 -0
  446. package/dist/hardcodedColors-4NBF5Z53.js +61 -0
  447. package/dist/harnessFollowUps-PNR55PM4.js +87 -0
  448. package/dist/ignore-7E4ZV5XH.js +30 -0
  449. package/dist/importBacklog-FOGUOAIJ.js +228 -0
  450. package/dist/inSln-G4VRY7VM.js +22 -0
  451. package/dist/index.js +2832 -10
  452. package/dist/indexRules-65H3IE33.js +31 -0
  453. package/dist/init-2WH6WD64.js +9 -0
  454. package/dist/init-6Y2TC67U.js +23 -0
  455. package/dist/init-BELQ3LDU.js +25 -0
  456. package/dist/init-BNY2X74K.js +9 -0
  457. package/dist/init-PZIM2TEG.js +9 -0
  458. package/dist/inspect-OI5K5KSG.js +368 -0
  459. package/dist/jiraAuth-4Z5EVL7A.js +51 -0
  460. package/dist/launchMode-VKS5XM4V.js +85 -0
  461. package/dist/link-JDJBEJCL.js +124 -0
  462. package/dist/link-LYQZULAX.js +59 -0
  463. package/dist/linkNode-IZ7TMIBN.js +88 -0
  464. package/dist/lint-5AA42LMF.js +418 -0
  465. package/dist/list-BM6RD4CP.js +43 -0
  466. package/dist/list-GCJ6WCKC.js +34 -0
  467. package/dist/list-HCOU6YAY.js +28 -0
  468. package/dist/list-OWWW2G36.js +100 -0
  469. package/dist/list-ZR6AEAER.js +33 -0
  470. package/dist/list-ZVSHR4AA.js +113 -0
  471. package/dist/listComments-CTM5UMWI.js +203 -0
  472. package/dist/listModels-2US52LRW.js +74 -0
  473. package/dist/listNodes-HNKK3LEQ.js +54 -0
  474. package/dist/listRules-XBWM5DPH.js +41 -0
  475. package/dist/maintainability-P55FDYZW.js +19 -0
  476. package/dist/merge-MVMNYPO2.js +196 -0
  477. package/dist/mermaidExport-DKB3X763.js +108 -0
  478. package/dist/migrate-XZ562LTJ.js +37 -0
  479. package/dist/migrations-CSVJKLQC.js +206 -0
  480. package/dist/move-XAN7VFR4.js +63 -0
  481. package/dist/movePhase-AK3F6A6P.js +103 -0
  482. package/dist/moveRepo-P7LPCWIL.js +109 -0
  483. package/dist/netcap-FIHYF3LK.js +203 -0
  484. package/dist/netcapExtract-KAFERZ6V.js +462 -0
  485. package/dist/newCli-2HD56JUI.js +132 -0
  486. package/dist/newProject-5UN6N4MS.js +70 -0
  487. package/dist/next-FAAUSQLC.js +145 -0
  488. package/dist/next-XRXA7ZLN.js +83 -0
  489. package/dist/noVenv-DONW2S6P.js +34 -0
  490. package/dist/nodeLogs-NNLS5TNI.js +64 -0
  491. package/dist/notify-NRLRUDFI.js +66 -0
  492. package/dist/permitCliReads-RSRMZMGS.js +313 -0
  493. package/dist/phaseDone-FBAQDO3S.js +99 -0
  494. package/dist/piHook-WWYLIELZ.js +89 -0
  495. package/dist/plan-GBSJWMXP.js +51 -0
  496. package/dist/postSlackMessage-SJQGYGJQ.js +21 -0
  497. package/dist/posted-ZNKIE73Q.js +76 -0
  498. package/dist/printComments-7ROHUEPO.js +169 -0
  499. package/dist/printExtensionUrl-IW2WTSNS.js +19 -0
  500. package/dist/prompts-SL6SHWOA.js +55 -0
  501. package/dist/propose-PYAPK2PU.js +307 -0
  502. package/dist/prs-2SRUKVTI.js +138 -0
  503. package/dist/prsSlackChannel-DY35HNQF.js +28 -0
  504. package/dist/prsStatus-6G3ZTK36.js +319 -0
  505. package/dist/pullIfConfigured-V2H6IFDQ.js +18 -0
  506. package/dist/raise-OBGNVBLZ.js +330 -0
  507. package/dist/raiseHelpText-6TECFMWR.js +148 -0
  508. package/dist/ravendbAuth-53OAERB3.js +147 -0
  509. package/dist/ravendbCollections-2NZYZR5P.js +35 -0
  510. package/dist/ravendbQuery-EY2XGKEK.js +89 -0
  511. package/dist/ravendbSetConnection-U7X27AIP.js +16 -0
  512. package/dist/readBodyArgument-NZG3GJMF.js +7 -0
  513. package/dist/readTime-23CA6JVM.js +168 -0
  514. package/dist/recordSlack-TZH2THZH.js +60 -0
  515. package/dist/redirect-G7WS7LDE.js +32 -0
  516. package/dist/refine-NAJUWIFV.js +87 -0
  517. package/dist/refreshDocs-A5S2NQ5Z.js +65 -0
  518. package/dist/releasesConfigure-JA7QNAJF.js +211 -0
  519. package/dist/releasesList-EETLBTD2.js +39 -0
  520. package/dist/remove-CSUOZRGT.js +96 -0
  521. package/dist/remove-VIGXH42Y.js +43 -0
  522. package/dist/removePhase-S4WFO6PT.js +62 -0
  523. package/dist/rename-PM5VQUCY.js +96 -0
  524. package/dist/renameSession-IQ6RHQUJ.js +30 -0
  525. package/dist/renameSymbol-OOIIGF3B.js +78 -0
  526. package/dist/reply-4VV4LEYF.js +65 -0
  527. package/dist/reportCliError-6UDOLAIT.js +42 -0
  528. package/dist/repos-JP75ZTBU.js +130 -0
  529. package/dist/resolveHarness-A3F7CDF2.js +17 -0
  530. package/dist/resolveModel-GHXLN2T4.js +27 -0
  531. package/dist/restartDaemon-YSKQMKEQ.js +9 -0
  532. package/dist/restartNode-GAM4QS3V.js +59 -0
  533. package/dist/restructure-FJ3BME7E.js +760 -0
  534. package/dist/review-IXQ67Q2I.js +3870 -0
  535. package/dist/reviewPrComments-YELGPQIH.js +80 -0
  536. package/dist/rewindPhase-RKEURCE5.js +82 -0
  537. package/dist/run-JEUQGX5U.js +78 -0
  538. package/dist/run-KI7FYVOY.js +178 -0
  539. package/dist/runDaemon-WNUM5HUG.js +9292 -0
  540. package/dist/runExtract-IUEUT2IK.js +568 -0
  541. package/dist/runRefine-DWJATWCB.js +99 -0
  542. package/dist/runScope-LCAGTKGG.js +39 -0
  543. package/dist/scan-VM2LYP6W.js +74 -0
  544. package/dist/scheduleBackup-3UZQU67U.js +200 -0
  545. package/dist/schemaConfirm-WZCBGM7A.js +171 -0
  546. package/dist/schemaUnlock-JKXSG6BI.js +135 -0
  547. package/dist/screenshot-ARSOZ2M6.js +182 -0
  548. package/dist/search-HLB25O4S.js +79 -0
  549. package/dist/seqAuth-6IPD5OPG.js +50 -0
  550. package/dist/seqQuery-HL6H4PMX.js +233 -0
  551. package/dist/seqSetConnection-IUCGBTON.js +30 -0
  552. package/dist/sessionOutput-NXHUXIKC.js +92 -0
  553. package/dist/setSessionStatus-HPHBUHVB.js +12 -0
  554. package/dist/setStatusCommand-WBRJ4BTB.js +61 -0
  555. package/dist/show-65RGZKWW.js +327 -0
  556. package/dist/show-SPEIA7AL.js +186 -0
  557. package/dist/showClaudeCodeIcon-E4SAM3GN.js +12 -0
  558. package/dist/showCodexIcon-YUAKV4NI.js +11 -0
  559. package/dist/signExtension-VF34F7UR.js +182 -0
  560. package/dist/simulateDivergence-VB4UL4UR.js +27 -0
  561. package/dist/skip-ZZHUH3MU.js +76 -0
  562. package/dist/slack-74LWSKRK.js +221 -0
  563. package/dist/sloc-KPIIBOMR.js +18 -0
  564. package/dist/sqlAuth-IN4PYCIX.js +59 -0
  565. package/dist/sqlColumns-SNPMTHHK.js +50 -0
  566. package/dist/sqlMutate-4QC4IT4E.js +43 -0
  567. package/dist/sqlQuery-OAXPQJPY.js +53 -0
  568. package/dist/sqlSetConnection-UAX7TRB4.js +30 -0
  569. package/dist/sqlTables-ZM2PUJ7N.js +39 -0
  570. package/dist/star-2GG4JB3K.js +46 -0
  571. package/dist/start-BUUHD4ZQ.js +44 -0
  572. package/dist/startIssue-JSVKGZZR.js +135 -0
  573. package/dist/status-63OT6MGQ.js +38 -0
  574. package/dist/{chunk-W7ZLVOL6.js → statusLine-TK2QPCQO.js} +9 -4
  575. package/dist/stop-HG3UZOI6.js +52 -0
  576. package/dist/stopClaudeCodeIcon-P4AVHUOL.js +12 -0
  577. package/dist/stopCodexIcon-7O6D2SEH.js +11 -0
  578. package/dist/stopDaemon-XIYQ6SAW.js +8 -0
  579. package/dist/sync-HAAAJ4LC.js +826 -0
  580. package/dist/testflightAdd-MBJAAJGR.js +37 -0
  581. package/dist/unassignIssue-OXNUC2QQ.js +37 -0
  582. package/dist/unlink-TLLWWJIG.js +71 -0
  583. package/dist/unlinkNode-O7IZD5BN.js +41 -0
  584. package/dist/unstar-EEKVLJQI.js +46 -0
  585. package/dist/update-6NKPYHDT.js +72 -0
  586. package/dist/update-E72CS3ZO.js +160 -0
  587. package/dist/updateNode-4IYWN3MS.js +99 -0
  588. package/dist/updatePhase-USTBTRW4.js +163 -0
  589. package/dist/updatePlan-RV77RV4J.js +315 -0
  590. package/dist/version-4E3HWTDD.js +47 -0
  591. package/dist/viewIssue-CYHIPCFO.js +36 -0
  592. package/dist/watchLoop-MV7DVGC6.js +30 -0
  593. package/dist/watchReport-A4W7UOAJ.js +23 -0
  594. package/dist/watchWait-FF65XUH2.js +538 -0
  595. package/dist/web-3X54NV64.js +178 -0
  596. package/dist/web-XW33SYEX.js +169 -0
  597. package/dist/withPool-APJFDKR2.js +18 -0
  598. package/dist/wontdo-KOV5YLR6.js +52 -0
  599. package/dist/wontfix-UZTOERNG.js +79 -0
  600. package/dist/write-PH5YX6V5.js +132 -0
  601. package/dist/writeSignal-NGH5I4AX.js +8 -0
  602. package/package.json +1 -1
  603. package/dist/chunk-MYJJAJB7.js +0 -113
  604. package/dist/runCli-OSXLT6CQ.js +0 -65704
  605. package/dist/runStatusLine-6VBMFNUZ.js +0 -17
  606. package/dist/statusLine-PWO6JAR2.js +0 -7
@@ -0,0 +1,3941 @@
1
+ import {
2
+ daemonLog
3
+ } from "./chunk-MRUIXQXS.js";
4
+ import {
5
+ harnessCapabilityDeclarations,
6
+ supported,
7
+ unsupported
8
+ } from "./chunk-66EUBGD6.js";
9
+ import {
10
+ piExtensionsDir
11
+ } from "./chunk-DIAC4XYA.js";
12
+ import {
13
+ readLitellmConfig
14
+ } from "./chunk-UU77KEL6.js";
15
+ import {
16
+ spawnInherit
17
+ } from "./chunk-W7TRZLEM.js";
18
+ import {
19
+ MANAGED_BLOCK_BEGIN,
20
+ MANAGED_BLOCK_END,
21
+ assistCodexHookKeys
22
+ } from "./chunk-P26XSDFU.js";
23
+ import {
24
+ harnessLabel,
25
+ resolveHarness
26
+ } from "./chunk-K6NKWRK4.js";
27
+ import {
28
+ checkCliAvailable,
29
+ harnesses,
30
+ isHarnessAvailable
31
+ } from "./chunk-XDIVXGPQ.js";
32
+ import {
33
+ loadConfig
34
+ } from "./chunk-KGFZYUE2.js";
35
+ import {
36
+ daemonPaths
37
+ } from "./chunk-IEK6CQQH.js";
38
+ import {
39
+ promptConfirm
40
+ } from "./chunk-6DGPQ67E.js";
41
+
42
+ // src/commands/sessions/shared/findTranscriptPathSync.ts
43
+ import * as fs from "fs";
44
+ import * as path2 from "path";
45
+
46
+ // src/commands/sessions/shared/claudeProjectsRoot.ts
47
+ import * as os from "os";
48
+ import * as path from "path";
49
+ function claudeProjectsRoot() {
50
+ return path.join(os.homedir(), ".claude", "projects");
51
+ }
52
+ function projectSlug(cwd) {
53
+ return cwd.replace(/[^a-zA-Z0-9]/g, "-");
54
+ }
55
+
56
+ // src/commands/sessions/shared/findTranscriptPathSync.ts
57
+ function projectDirForCwd(cwd) {
58
+ return path2.join(claudeProjectsRoot(), projectSlug(cwd));
59
+ }
60
+ function transcriptPathFor(cwd, claudeSessionId) {
61
+ return path2.join(projectDirForCwd(cwd), `${claudeSessionId}.jsonl`);
62
+ }
63
+ function findTranscriptPathSync(cwd, claudeSessionId) {
64
+ const direct = transcriptPathFor(cwd, claudeSessionId);
65
+ if (fs.existsSync(direct)) return direct;
66
+ const dir = projectDirForCwd(cwd);
67
+ let files;
68
+ try {
69
+ files = fs.readdirSync(dir);
70
+ } catch {
71
+ return null;
72
+ }
73
+ for (const file of files) {
74
+ if (!file.endsWith(".jsonl")) continue;
75
+ if (headContainsSessionId(path2.join(dir, file), claudeSessionId))
76
+ return path2.join(dir, file);
77
+ }
78
+ return null;
79
+ }
80
+ function headContainsSessionId(filePath, claudeSessionId) {
81
+ let fd;
82
+ try {
83
+ fd = fs.openSync(filePath, "r");
84
+ const buf = Buffer.alloc(16384);
85
+ const bytesRead = fs.readSync(fd, buf, 0, buf.length, 0);
86
+ return buf.toString("utf8", 0, bytesRead).includes(claudeSessionId);
87
+ } catch {
88
+ return false;
89
+ } finally {
90
+ if (fd !== void 0) fs.closeSync(fd);
91
+ }
92
+ }
93
+
94
+ // src/commands/sessions/daemon/hasTranscriptOnDisk.ts
95
+ function hasTranscriptOnDisk(session) {
96
+ return !!session.cwd && !!session.claudeSessionId && !!findTranscriptPathSync(session.cwd, session.claudeSessionId);
97
+ }
98
+
99
+ // src/commands/sessions/daemon/ensureHooksSettings.ts
100
+ import { mkdirSync, writeFileSync } from "fs";
101
+ import { dirname } from "path";
102
+ var SET_STATUS = "assist sessions set-status";
103
+ function running(source) {
104
+ return `${SET_STATUS} running --source ${source}`;
105
+ }
106
+ function waiting(source) {
107
+ return `${SET_STATUS} waiting --source ${source}`;
108
+ }
109
+ function ackWaiting(source) {
110
+ return `${SET_STATUS} waiting --source ${source} --ack`;
111
+ }
112
+ function on(command, matcher) {
113
+ const hooks = [{ type: "command", command }];
114
+ return [matcher == null ? { hooks } : { matcher, hooks }];
115
+ }
116
+ var ASK_USER_QUESTION = "AskUserQuestion";
117
+ var NOT_ASK_USER_QUESTION = `^(?!${ASK_USER_QUESTION}$).*`;
118
+ var hooksSettings = {
119
+ theme: "auto",
120
+ hooks: {
121
+ UserPromptSubmit: on(running("prompt")),
122
+ PreToolUse: [
123
+ ...on(waiting("pretool"), ASK_USER_QUESTION),
124
+ ...on(running("pretool"), NOT_ASK_USER_QUESTION)
125
+ ],
126
+ PostToolUse: on(running("posttool")),
127
+ Stop: on(ackWaiting("stop")),
128
+ Notification: on(ackWaiting("notification")),
129
+ PermissionRequest: on(ackWaiting("permission"))
130
+ }
131
+ };
132
+ function ensureHooksSettings() {
133
+ const path15 = daemonPaths.hooksSettings;
134
+ mkdirSync(dirname(path15), { recursive: true });
135
+ writeFileSync(path15, JSON.stringify(hooksSettings, null, 2));
136
+ return path15;
137
+ }
138
+
139
+ // src/commands/sessions/daemon/spawnPty.ts
140
+ import { existsSync as existsSync3 } from "fs";
141
+ import * as pty from "node-pty";
142
+
143
+ // src/commands/sessions/daemon/ensureSpawnHelperExecutable.ts
144
+ import { chmodSync, existsSync as existsSync2, statSync } from "fs";
145
+ import { createRequire } from "module";
146
+ import path3 from "path";
147
+ var require2 = createRequire(import.meta.url);
148
+ var ensured = false;
149
+ function ensureSpawnHelperExecutable() {
150
+ if (ensured || process.platform !== "darwin") return;
151
+ ensured = true;
152
+ const ptyRoot = path3.join(path3.dirname(require2.resolve("node-pty")), "..");
153
+ const helper = path3.join(
154
+ ptyRoot,
155
+ "prebuilds",
156
+ `${process.platform}-${process.arch}`,
157
+ "spawn-helper"
158
+ );
159
+ if (!existsSync2(helper)) return;
160
+ const mode = statSync(helper).mode;
161
+ if ((mode & 73) === 0) chmodSync(helper, mode | 493);
162
+ }
163
+
164
+ // src/commands/sessions/daemon/resolvePtyCommand.ts
165
+ function resolvePtyCommand(args) {
166
+ if (process.platform !== "win32")
167
+ return {
168
+ file: process.env.SHELL ?? "bash",
169
+ args: ["-l", "-c", `exec ${args.map(shellEscape).join(" ")}`]
170
+ };
171
+ if (args[0] === "assist" && process.argv[1])
172
+ return {
173
+ file: process.execPath,
174
+ args: [process.argv[1], ...args.slice(1)]
175
+ };
176
+ return { file: "cmd.exe", args: ["/c", ...args] };
177
+ }
178
+ function shellEscape(s) {
179
+ return `'${s.replace(/'/g, String.raw`'\''`)}'`;
180
+ }
181
+
182
+ // src/commands/sessions/daemon/sessionChildEnv.ts
183
+ function sessionChildEnv(base, sessionId, extraEnv) {
184
+ const {
185
+ CLAUDE_CODE_CHILD_SESSION: _childSession,
186
+ CLAUDECODE: _claudeCode,
187
+ ...parentEnv
188
+ } = base;
189
+ return {
190
+ ...parentEnv,
191
+ ASSIST_SESSION: "1",
192
+ ...sessionId && {
193
+ ASSIST_SESSION_ID: sessionId,
194
+ ASSIST_ACTIVITY_ID: sessionId
195
+ },
196
+ ...extraEnv
197
+ };
198
+ }
199
+
200
+ // src/commands/sessions/daemon/viewerSize.ts
201
+ import { readFileSync, writeFileSync as writeFileSync2 } from "fs";
202
+ var DEFAULT_SIZE = { cols: 120, rows: 30 };
203
+ var remembered;
204
+ function rememberViewerSize(cols, rows) {
205
+ if (cols <= 0 || rows <= 0) return;
206
+ if (remembered?.cols === cols && remembered.rows === rows) return;
207
+ remembered = { cols, rows };
208
+ try {
209
+ writeFileSync2(daemonPaths.viewerSize, JSON.stringify(remembered));
210
+ } catch (error) {
211
+ daemonLog(
212
+ `viewer size ${cols}x${rows} not saved: ${error instanceof Error ? error.message : String(error)}`
213
+ );
214
+ }
215
+ }
216
+ function viewerSize() {
217
+ remembered ??= readSavedSize();
218
+ return remembered ?? DEFAULT_SIZE;
219
+ }
220
+ function readSavedSize() {
221
+ try {
222
+ const { cols, rows } = JSON.parse(
223
+ readFileSync(daemonPaths.viewerSize, "utf8")
224
+ );
225
+ if (typeof cols === "number" && typeof rows === "number" && cols > 0)
226
+ return { cols, rows };
227
+ } catch {
228
+ }
229
+ return void 0;
230
+ }
231
+
232
+ // src/commands/sessions/daemon/spawnPty.ts
233
+ var MissingCwdError = class extends Error {
234
+ constructor(cwd) {
235
+ super(`working directory no longer exists: ${cwd}`);
236
+ this.cwd = cwd;
237
+ this.name = "MissingCwdError";
238
+ }
239
+ cwd;
240
+ };
241
+ function spawnPty(args, cwd, sessionId, extraEnv) {
242
+ refuseMissingCwd(cwd, sessionId);
243
+ ensureSpawnHelperExecutable();
244
+ const command = resolvePtyCommand(args);
245
+ return pty.spawn(command.file, command.args, {
246
+ name: "xterm-256color",
247
+ ...viewerSize(),
248
+ cwd: cwd ?? process.cwd(),
249
+ env: sessionChildEnv(process.env, sessionId, extraEnv)
250
+ });
251
+ }
252
+ function refuseMissingCwd(cwd, sessionId) {
253
+ if (!cwd || existsSync3(cwd)) return;
254
+ daemonLog(
255
+ `${sessionId ? `session ${sessionId}` : "pty"} not spawned: working directory ${cwd} no longer exists`
256
+ );
257
+ throw new MissingCwdError(cwd);
258
+ }
259
+
260
+ // src/commands/sessions/daemon/spawnClaude.ts
261
+ function spawnClaude(opts2 = {}) {
262
+ return spawnPty(buildArgs(opts2), opts2.cwd, opts2.sessionId);
263
+ }
264
+ function buildArgs(opts2) {
265
+ const base = ["claude", "--settings", ensureHooksSettings()];
266
+ if (opts2.appendSystemPromptFile)
267
+ base.push("--append-system-prompt-file", opts2.appendSystemPromptFile);
268
+ if (opts2.auto) base.push("--permission-mode", "auto");
269
+ if (opts2.model) base.push("--model", opts2.model);
270
+ if (opts2.resumeSessionId) {
271
+ return opts2.prompt ? [...base, "--resume", opts2.resumeSessionId, opts2.prompt] : [...base, "--resume", opts2.resumeSessionId];
272
+ }
273
+ if (opts2.claudeSessionId) base.push("--session-id", opts2.claudeSessionId);
274
+ if (opts2.prompt) return [...base, opts2.prompt];
275
+ return base;
276
+ }
277
+
278
+ // src/commands/sessions/shared/findSessionJsonlPath.ts
279
+ import * as path6 from "path";
280
+
281
+ // src/commands/sessions/shared/parseSessionFile.ts
282
+ import * as fs2 from "fs";
283
+
284
+ // src/commands/sessions/shared/deriveHistoryFields.ts
285
+ var KNOWN = [
286
+ "draft",
287
+ "next",
288
+ "bug",
289
+ "refine",
290
+ "review",
291
+ "run",
292
+ "update"
293
+ ];
294
+ function deriveHistoryFields(commandName, commandArgs, name) {
295
+ const fields = {};
296
+ const sessionType = deriveSessionType(commandName, name);
297
+ if (sessionType) fields.sessionType = sessionType;
298
+ const itemMatch = commandArgs.match(/^(\d+)\b\s*/);
299
+ if (itemMatch) fields.itemId = Number(itemMatch[1]);
300
+ const prompt = commandArgs.slice(itemMatch?.[0].length ?? 0).trim();
301
+ if (prompt) fields.prompt = prompt;
302
+ return fields;
303
+ }
304
+ function deriveSessionType(commandName, name) {
305
+ if (commandName === "review-pr-comments" || commandName === "fix-conflict")
306
+ return "review";
307
+ if (KNOWN.includes(commandName))
308
+ return commandName;
309
+ if (commandName || name) return "prompt";
310
+ return void 0;
311
+ }
312
+
313
+ // src/commands/sessions/shared/backlogRunMarkers.ts
314
+ function backlogRunMarkers(text) {
315
+ const match = text.match(/backlog item a(\d+):[ \t]*([^\n]*)/);
316
+ if (!match) return { commandName: "", commandArgs: "" };
317
+ const title = match[2].trim();
318
+ return {
319
+ commandName: "next",
320
+ commandArgs: title ? `${match[1]} ${title}` : match[1]
321
+ };
322
+ }
323
+
324
+ // src/commands/sessions/shared/extractSessionMeta.ts
325
+ function extractSessionMeta(lines) {
326
+ let sessionId = "";
327
+ let cwd = "";
328
+ let timestamp = "";
329
+ let name = "";
330
+ let commandName = "";
331
+ let commandArgs = "";
332
+ for (const line of lines) {
333
+ const entry = safeParse(line);
334
+ if (!entry) continue;
335
+ sessionId ||= strField(entry, "sessionId");
336
+ timestamp ||= strField(entry, "timestamp");
337
+ cwd ||= strField(entry, "cwd");
338
+ if (entry.type === "user" && !entry.isMeta) {
339
+ ({ name, commandName, commandArgs } = parseFirstUserEntry(entry));
340
+ break;
341
+ }
342
+ }
343
+ return { sessionId, cwd, timestamp, name, commandName, commandArgs };
344
+ }
345
+ function parseFirstUserEntry(entry) {
346
+ const raw = messageText(entry);
347
+ const commandName = matchMarker(raw, "command-name").replace(/^\//, "");
348
+ const commandArgs = matchMarker(raw, "command-args");
349
+ const name = stripMarkers(raw);
350
+ if (commandName) return { name, commandName, commandArgs };
351
+ return { name, ...backlogRunMarkers(raw) };
352
+ }
353
+ function strField(entry, key) {
354
+ const value = entry[key];
355
+ return typeof value === "string" ? value : "";
356
+ }
357
+ function safeParse(line) {
358
+ try {
359
+ return JSON.parse(line);
360
+ } catch {
361
+ return null;
362
+ }
363
+ }
364
+ function messageText(entry) {
365
+ const msg = entry.message;
366
+ const content = msg?.content;
367
+ return typeof content === "string" ? content : Array.isArray(content) ? content.find((c) => c.type === "text")?.text ?? "" : "";
368
+ }
369
+ function stripMarkers(text) {
370
+ return text.replace(/<command-[^>]*>[^<]*<\/command-[^>]*>/g, "").trim().slice(0, 80);
371
+ }
372
+ function matchMarker(text, tag) {
373
+ const match = text.match(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`));
374
+ return match ? match[1].trim() : "";
375
+ }
376
+
377
+ // src/commands/sessions/shared/deriveProject.ts
378
+ import * as path4 from "path";
379
+ function deriveProject(cwd, filePath, origin) {
380
+ if (!cwd) return dirNameToProject(filePath);
381
+ return origin === "windows" ? path4.win32.basename(cwd) : path4.basename(cwd);
382
+ }
383
+ function dirNameToProject(filePath) {
384
+ const dirName = path4.basename(path4.dirname(filePath));
385
+ const parts = dirName.split("--");
386
+ return parts[parts.length - 1].replace(/-/g, "/");
387
+ }
388
+
389
+ // src/commands/sessions/shared/parseSessionFile.ts
390
+ async function parseSessionFile(filePath, origin = "wsl") {
391
+ let handle;
392
+ try {
393
+ handle = await fs2.promises.open(filePath, "r");
394
+ const meta = extractSessionMeta(await readHeadLines(handle));
395
+ if (!meta.sessionId) return null;
396
+ const timestamp = meta.timestamp || (await fs2.promises.stat(filePath)).mtime.toISOString();
397
+ return {
398
+ sessionId: meta.sessionId,
399
+ name: meta.name || `Session ${meta.sessionId.slice(0, 8)}`,
400
+ project: deriveProject(meta.cwd, filePath, origin),
401
+ cwd: meta.cwd,
402
+ timestamp,
403
+ origin,
404
+ ...deriveHistoryFields(meta.commandName, meta.commandArgs, meta.name)
405
+ };
406
+ } catch {
407
+ return null;
408
+ } finally {
409
+ await handle?.close();
410
+ }
411
+ }
412
+ async function readHeadLines(handle) {
413
+ const buf = Buffer.alloc(16384);
414
+ const { bytesRead } = await handle.read(buf, 0, buf.length, 0);
415
+ return buf.toString("utf8", 0, bytesRead).split("\n").filter(Boolean);
416
+ }
417
+
418
+ // src/commands/sessions/shared/discoverSessionJsonlPaths.ts
419
+ import * as fs3 from "fs";
420
+ import * as os2 from "os";
421
+ import * as path5 from "path";
422
+ async function discoverSessionJsonlPaths() {
423
+ const results = [];
424
+ await Promise.all(
425
+ sessionRoots().map(async ({ dir, origin }) => {
426
+ let projectDirs;
427
+ try {
428
+ projectDirs = await fs3.promises.readdir(dir);
429
+ } catch {
430
+ return;
431
+ }
432
+ await Promise.all(
433
+ projectDirs.map(async (dirName) => {
434
+ const dirPath = path5.join(dir, dirName);
435
+ let entries;
436
+ try {
437
+ entries = await fs3.promises.readdir(dirPath);
438
+ } catch {
439
+ return;
440
+ }
441
+ for (const file of entries) {
442
+ if (file.endsWith(".jsonl"))
443
+ results.push({ path: path5.join(dirPath, file), origin });
444
+ }
445
+ })
446
+ );
447
+ })
448
+ );
449
+ return results;
450
+ }
451
+ function sessionRoots() {
452
+ return [
453
+ { dir: path5.join(os2.homedir(), ".claude", "projects"), origin: "wsl" }
454
+ ];
455
+ }
456
+
457
+ // src/commands/sessions/shared/findSessionJsonlPath.ts
458
+ async function findSessionJsonlPath(sessionId) {
459
+ const paths = await discoverSessionJsonlPaths();
460
+ const direct = paths.find(
461
+ (p) => path6.basename(p.path, ".jsonl") === sessionId
462
+ );
463
+ if (direct) return direct.path;
464
+ for (const p of paths) {
465
+ const meta = await parseSessionFile(p.path, p.origin);
466
+ if (meta?.sessionId === sessionId) return p.path;
467
+ }
468
+ return null;
469
+ }
470
+
471
+ // src/shared/spawnClaude.ts
472
+ function withoutResumeSession(options) {
473
+ if (!options?.resumeSessionId) return options;
474
+ const { resumeSessionId: _resumeSessionId, ...rest } = options;
475
+ return rest;
476
+ }
477
+ function spawnClaude2(prompt, options = {}) {
478
+ const args = [
479
+ "--settings",
480
+ ensureHooksSettings(),
481
+ ...buildArgs2(prompt, options)
482
+ ];
483
+ const permissionMode = options.permissionMode ?? (options.allowEdits ? "auto" : void 0);
484
+ if (permissionMode) {
485
+ args.push("--permission-mode", permissionMode);
486
+ }
487
+ if (options.model && !options.resumeSessionId) {
488
+ args.push("--model", options.model);
489
+ }
490
+ return spawnInherit("claude", args);
491
+ }
492
+ function buildArgs2(prompt, options) {
493
+ if (options.resumeSessionId) {
494
+ return prompt ? ["--resume", options.resumeSessionId, prompt] : ["--resume", options.resumeSessionId];
495
+ }
496
+ if (options.sessionId) {
497
+ return prompt ? ["--session-id", options.sessionId, prompt] : ["--session-id", options.sessionId];
498
+ }
499
+ return prompt ? [prompt] : [];
500
+ }
501
+
502
+ // src/shared/harnessAdapters/buildSlashCommand.ts
503
+ function buildSlashCommand(slashCommand, description) {
504
+ const trimmed = description?.trim();
505
+ return trimmed ? `/${slashCommand} ${trimmed}` : `/${slashCommand}`;
506
+ }
507
+
508
+ // src/shared/harnessAdapters/carryTranscriptToTree.ts
509
+ import { copyFileSync, existsSync as existsSync4, mkdirSync as mkdirSync2 } from "fs";
510
+ import { join as join4 } from "path";
511
+ function carryTranscriptToTree(claudeSessionId, fromCwd, toCwd) {
512
+ const dir = projectDirForCwd(toCwd);
513
+ if (dir === projectDirForCwd(fromCwd)) {
514
+ daemonLog(
515
+ `transcript ${claudeSessionId} already lives in ${dir}: resuming in the original worktree path`
516
+ );
517
+ return;
518
+ }
519
+ const dest = join4(dir, `${claudeSessionId}.jsonl`);
520
+ if (existsSync4(dest)) {
521
+ daemonLog(`transcript ${claudeSessionId} already present in ${dir}`);
522
+ return;
523
+ }
524
+ const source = findTranscriptPathSync(fromCwd, claudeSessionId);
525
+ if (!source) {
526
+ daemonLog(
527
+ `transcript ${claudeSessionId} not found under ${projectDirForCwd(fromCwd)}: resuming in ${toCwd} without it`
528
+ );
529
+ return;
530
+ }
531
+ try {
532
+ mkdirSync2(dir, { recursive: true });
533
+ copyFileSync(source, dest);
534
+ daemonLog(
535
+ `transcript ${source} copied to ${dest} so ${toCwd} can resume it`
536
+ );
537
+ } catch (error) {
538
+ daemonLog(
539
+ `transcript ${claudeSessionId} could not be copied to ${dir}: ${error instanceof Error ? error.message : String(error)}`
540
+ );
541
+ }
542
+ }
543
+
544
+ // src/shared/harnessAdapters/claudeConnectorProbe.ts
545
+ import { readFileSync as readFileSync2 } from "fs";
546
+ import { homedir as homedir3 } from "os";
547
+ import { join as join5 } from "path";
548
+ function knownConnectedConnectors() {
549
+ const dir = process.env.CLAUDE_CONFIG_DIR ?? homedir3();
550
+ try {
551
+ const state = JSON.parse(
552
+ readFileSync2(join5(dir, ".claude.json"), "utf8")
553
+ );
554
+ const list = state.claudeAiMcpEverConnected;
555
+ return Array.isArray(list) ? list.filter((name) => typeof name === "string") : void 0;
556
+ } catch {
557
+ return void 0;
558
+ }
559
+ }
560
+ function claudeConnectorProbe(connector) {
561
+ const connected = knownConnectedConnectors();
562
+ if (!connected || connected.includes(`claude.ai ${connector}`))
563
+ return supported;
564
+ return unsupported(
565
+ `the claude.ai ${connector} connector has never connected in Claude`,
566
+ `connect ${connector} at https://claude.ai/settings/connectors, then start claude once so it connects`
567
+ );
568
+ }
569
+
570
+ // src/commands/sessions/shared/readTranscriptTail.ts
571
+ import * as fs4 from "fs";
572
+ var DEFAULT_MAX_BYTES = 256 * 1024;
573
+ function parseTailEntries(raw) {
574
+ const entries = [];
575
+ for (const line of raw.split("\n")) {
576
+ const trimmed = line.trim();
577
+ if (!trimmed) continue;
578
+ try {
579
+ const parsed = JSON.parse(trimmed);
580
+ if (parsed && typeof parsed === "object")
581
+ entries.push(parsed);
582
+ } catch {
583
+ }
584
+ }
585
+ return entries;
586
+ }
587
+ function dropPartialFirstLine(raw, sliced) {
588
+ if (!sliced) return raw;
589
+ const newline = raw.indexOf("\n");
590
+ return newline === -1 ? "" : raw.slice(newline + 1);
591
+ }
592
+ async function readTranscriptTail(filePath, maxBytes = DEFAULT_MAX_BYTES) {
593
+ let handle;
594
+ try {
595
+ handle = await fs4.promises.open(filePath, "r");
596
+ const { size } = await handle.stat();
597
+ const start = Math.max(0, size - maxBytes);
598
+ const length = size - start;
599
+ if (length === 0) return [];
600
+ const buf = Buffer.alloc(length);
601
+ await handle.read(buf, 0, length, start);
602
+ return parseTailEntries(
603
+ dropPartialFirstLine(buf.toString("utf8"), start > 0)
604
+ );
605
+ } catch {
606
+ return [];
607
+ } finally {
608
+ await handle?.close();
609
+ }
610
+ }
611
+ function readTranscriptTailSync(filePath, maxBytes = DEFAULT_MAX_BYTES) {
612
+ let fd;
613
+ try {
614
+ fd = fs4.openSync(filePath, "r");
615
+ const { size } = fs4.fstatSync(fd);
616
+ const start = Math.max(0, size - maxBytes);
617
+ const length = size - start;
618
+ if (length === 0) return [];
619
+ const buf = Buffer.alloc(length);
620
+ fs4.readSync(fd, buf, 0, length, start);
621
+ return parseTailEntries(
622
+ dropPartialFirstLine(buf.toString("utf8"), start > 0)
623
+ );
624
+ } catch {
625
+ return [];
626
+ } finally {
627
+ if (fd !== void 0) fs4.closeSync(fd);
628
+ }
629
+ }
630
+
631
+ // src/commands/sessions/shared/asRecord.ts
632
+ function asRecord(value) {
633
+ return value && typeof value === "object" ? value : null;
634
+ }
635
+
636
+ // src/commands/sessions/shared/deliberatelyStoppedTaskIds.ts
637
+ var STOP_TOOLS = /* @__PURE__ */ new Set(["KillShell", "KillBash", "TaskStop"]);
638
+ function deliberatelyStoppedTaskIds(entry) {
639
+ if (entry.type !== "assistant") return [];
640
+ const content = asRecord(entry.message)?.content;
641
+ if (!Array.isArray(content)) return [];
642
+ const ids = [];
643
+ for (const block of content) {
644
+ const b = asRecord(block);
645
+ if (b?.type !== "tool_use" || !STOP_TOOLS.has(String(b.name))) continue;
646
+ const input = asRecord(b.input);
647
+ const id = input?.task_id ?? input?.shell_id ?? input?.bash_id;
648
+ if (typeof id === "string") ids.push(id);
649
+ }
650
+ return ids;
651
+ }
652
+
653
+ // src/commands/sessions/shared/notifiedTasks.ts
654
+ var NOTIFICATION = /<task-notification>([\s\S]*?)<\/task-notification>/g;
655
+ var TASK_ID = /<task-id>([^<]+)<\/task-id>/;
656
+ var STATUS = /<status>([^<]+)<\/status>/;
657
+ function notifiedTasks(entry) {
658
+ const text = taskNotificationText(entry);
659
+ if (!text) return [];
660
+ const tasks = [];
661
+ for (const [, body] of text.matchAll(NOTIFICATION)) {
662
+ const id = body.match(TASK_ID)?.[1];
663
+ if (id) tasks.push({ id, status: body.match(STATUS)?.[1]?.trim() });
664
+ }
665
+ return tasks;
666
+ }
667
+ function taskNotificationText(entry) {
668
+ const content = asRecord(entry.message)?.content ?? entry.content;
669
+ return typeof content === "string" && content.includes("<task-notification>") ? content : void 0;
670
+ }
671
+
672
+ // src/commands/sessions/shared/unfinishedBackgroundTasks.ts
673
+ var KILLED_STATUSES = /* @__PURE__ */ new Set(["killed", "stopped"]);
674
+ function unfinishedBackgroundTasks(entries) {
675
+ const inFlight = /* @__PURE__ */ new Set();
676
+ const killedAwaitingTurn = /* @__PURE__ */ new Set();
677
+ for (const entry of entries) {
678
+ const started = startedTaskId(entry);
679
+ if (started) inFlight.add(started);
680
+ for (const finished of selfFinishedTaskIds(entry))
681
+ inFlight.delete(finished);
682
+ for (const killed of killedTaskIds(entry)) killedAwaitingTurn.add(killed);
683
+ for (const stopped of deliberatelyStoppedTaskIds(entry))
684
+ inFlight.delete(stopped);
685
+ if (entry.type === "assistant") {
686
+ for (const handled of killedAwaitingTurn) inFlight.delete(handled);
687
+ killedAwaitingTurn.clear();
688
+ }
689
+ }
690
+ return [...inFlight];
691
+ }
692
+ function killedTaskIds(entry) {
693
+ return notifiedTasks(entry).filter(({ status }) => status && KILLED_STATUSES.has(status)).map(({ id }) => id);
694
+ }
695
+ function startedTaskId(entry) {
696
+ const result = asRecord(entry.toolUseResult);
697
+ return typeof result?.backgroundTaskId === "string" ? result.backgroundTaskId : void 0;
698
+ }
699
+ function selfFinishedTaskIds(entry) {
700
+ return notifiedTasks(entry).filter(({ status }) => !(status && KILLED_STATUSES.has(status))).map(({ id }) => id);
701
+ }
702
+
703
+ // src/shared/harnessAdapters/claudeInterruptedTasks.ts
704
+ function claudeInterruptedTasks({
705
+ cwd,
706
+ claudeSessionId
707
+ }) {
708
+ if (!cwd || !claudeSessionId) return [];
709
+ const filePath = findTranscriptPathSync(cwd, claudeSessionId);
710
+ if (!filePath) return [];
711
+ return unfinishedBackgroundTasks(readTranscriptTailSync(filePath));
712
+ }
713
+
714
+ // src/commands/sessions/shared/hasPendingAskUserQuestion.ts
715
+ var ASK_USER_QUESTION2 = "AskUserQuestion";
716
+ function hasPendingAskUserQuestion(events, idx) {
717
+ const ev = events[idx];
718
+ if (ev?.kind !== "assistant") return false;
719
+ const resolved = resolvedToolUseIds(events, idx);
720
+ return ev.toolUses.some(
721
+ (tool) => tool.name === ASK_USER_QUESTION2 && !resolved.has(tool.id)
722
+ );
723
+ }
724
+ function resolvedToolUseIds(events, afterIdx) {
725
+ const ids = /* @__PURE__ */ new Set();
726
+ for (let i = afterIdx + 1; i < events.length; i++) {
727
+ const event = events[i];
728
+ if (event.kind === "toolResult") for (const id of event.ids) ids.add(id);
729
+ }
730
+ return ids;
731
+ }
732
+
733
+ // src/commands/sessions/shared/lastDecisiveIndex.ts
734
+ var NON_DECISIVE_KINDS = /* @__PURE__ */ new Set([
735
+ "toolResult",
736
+ "taskNotification"
737
+ ]);
738
+ function lastDecisiveIndex(events) {
739
+ for (let i = events.length - 1; i >= 0; i--)
740
+ if (!NON_DECISIVE_KINDS.has(events[i].kind)) return i;
741
+ return -1;
742
+ }
743
+
744
+ // src/commands/sessions/shared/normalizeUser.ts
745
+ var INTERRUPT_PREFIX = "[Request interrupted";
746
+ var TASK_NOTIFICATION = "<task-notification>";
747
+ function normalizeUser(entry) {
748
+ const content = asRecord2(entry.message)?.content;
749
+ if (typeof content === "string") return normalizeUserText(content);
750
+ if (!Array.isArray(content)) return { kind: "user" };
751
+ if (content.length === 1 && asRecord2(content[0])?.type === "text")
752
+ return normalizeUserText(asRecord2(content[0])?.text);
753
+ const toolResultIds = [];
754
+ let hasInterrupt = false;
755
+ let hasNonToolResult = false;
756
+ for (const block of content) {
757
+ const b = asRecord2(block);
758
+ if (!b) continue;
759
+ if (b.type === "tool_result") {
760
+ if (typeof b.tool_use_id === "string") toolResultIds.push(b.tool_use_id);
761
+ } else if (b.type === "text" && isInterruptText(b.text)) {
762
+ hasInterrupt = true;
763
+ } else {
764
+ hasNonToolResult = true;
765
+ }
766
+ }
767
+ if (hasInterrupt) return { kind: "interrupt" };
768
+ if (hasNonToolResult) return { kind: "user" };
769
+ return { kind: "toolResult", ids: toolResultIds };
770
+ }
771
+ function asRecord2(value) {
772
+ return value && typeof value === "object" ? value : null;
773
+ }
774
+ function normalizeUserText(text) {
775
+ if (isInterruptText(text)) return { kind: "interrupt" };
776
+ if (typeof text === "string" && text.trimStart().startsWith(TASK_NOTIFICATION))
777
+ return { kind: "taskNotification" };
778
+ return { kind: "user" };
779
+ }
780
+ function isInterruptText(value) {
781
+ return typeof value === "string" && value.startsWith(INTERRUPT_PREFIX);
782
+ }
783
+
784
+ // src/commands/sessions/shared/normalizeTranscriptEvents.ts
785
+ function normalizeTranscriptEvents(entries) {
786
+ return entries.map(normalizeEntry).filter((event) => event !== null);
787
+ }
788
+ function normalizeEntry(entry) {
789
+ if (entry.isSidechain || entry.isMeta) return null;
790
+ if (entry.type === "assistant") return normalizeAssistant(entry);
791
+ if (entry.type === "user") return normalizeUser(entry);
792
+ return null;
793
+ }
794
+ function normalizeAssistant(entry) {
795
+ const message2 = asRecord3(entry.message);
796
+ const stopReason = typeof message2?.stop_reason === "string" ? message2.stop_reason : null;
797
+ const content = message2?.content;
798
+ const toolUses = [];
799
+ if (Array.isArray(content))
800
+ for (const block of content) {
801
+ const b = asRecord3(block);
802
+ if (b?.type === "tool_use")
803
+ toolUses.push({
804
+ id: typeof b.id === "string" ? b.id : "",
805
+ name: typeof b.name === "string" ? b.name : ""
806
+ });
807
+ }
808
+ return { kind: "assistant", stopReason, toolUses };
809
+ }
810
+ function asRecord3(value) {
811
+ return value && typeof value === "object" ? value : null;
812
+ }
813
+
814
+ // src/commands/sessions/shared/pendingAskQuestionTasks.ts
815
+ var ASK_QUESTION_COMMAND = /\bassist ask-(question|check)\b/;
816
+ function pendingAskQuestionTasks(entries) {
817
+ const askQuestionToolUses = /* @__PURE__ */ new Set();
818
+ const askQuestionTasks = /* @__PURE__ */ new Set();
819
+ for (const entry of entries) {
820
+ for (const block of contentBlocks(entry)) {
821
+ const input = asRecord(block.input);
822
+ if (block.type === "tool_use" && typeof block.id === "string" && typeof input?.command === "string" && ASK_QUESTION_COMMAND.test(input.command))
823
+ askQuestionToolUses.add(block.id);
824
+ if (block.type === "tool_result" && askQuestionToolUses.has(block.tool_use_id)) {
825
+ const taskId = asRecord(entry.toolUseResult)?.backgroundTaskId;
826
+ if (typeof taskId === "string") askQuestionTasks.add(taskId);
827
+ }
828
+ }
829
+ }
830
+ return unfinishedBackgroundTasks(entries).filter(
831
+ (id) => askQuestionTasks.has(id)
832
+ );
833
+ }
834
+ function contentBlocks(entry) {
835
+ const content = asRecord(entry.message)?.content;
836
+ if (!Array.isArray(content)) return [];
837
+ return content.map(asRecord).filter((block) => block !== null);
838
+ }
839
+
840
+ // src/commands/sessions/shared/awaitsQuestionAnswer.ts
841
+ function awaitsQuestionAnswer(entries) {
842
+ const events = normalizeTranscriptEvents(entries);
843
+ return hasPendingAskUserQuestion(events, lastDecisiveIndex(events)) || pendingAskQuestionTasks(entries).length > 0;
844
+ }
845
+
846
+ // src/commands/sessions/shared/deriveTranscriptStatus.ts
847
+ var TURN_END_STOP_REASONS = /* @__PURE__ */ new Set(["end_turn", "stop_sequence"]);
848
+ function deriveTranscriptStatus(entries, opts2 = {}) {
849
+ const events = normalizeTranscriptEvents(entries);
850
+ const lastIdx = lastDecisiveIndex(events);
851
+ if (lastIdx === -1) return null;
852
+ const ev = events[lastIdx];
853
+ if (ev.kind === "interrupt") return "waiting";
854
+ if (ev.kind === "user") return "running";
855
+ if (ev.kind === "toolResult" || ev.kind === "taskNotification") return null;
856
+ if (ev.stopReason != null && TURN_END_STOP_REASONS.has(ev.stopReason))
857
+ return "waiting";
858
+ if (opts2.permissionActive) return "waiting";
859
+ if (hasPendingAskUserQuestion(events, lastIdx)) return "waiting";
860
+ return "running";
861
+ }
862
+
863
+ // src/commands/sessions/shared/transcriptTailFingerprint.ts
864
+ var CONVERSATION_TYPES = /* @__PURE__ */ new Set(["user", "assistant"]);
865
+ function transcriptTailFingerprint(entries) {
866
+ for (let i = entries.length - 1; i >= 0; i--) {
867
+ const entry = entries[i];
868
+ if (entry.isSidechain || entry.isMeta) continue;
869
+ if (typeof entry.type !== "string" || !CONVERSATION_TYPES.has(entry.type))
870
+ continue;
871
+ return typeof entry.uuid === "string" && entry.uuid ? entry.uuid : null;
872
+ }
873
+ return null;
874
+ }
875
+
876
+ // src/commands/sessions/shared/renderPrompt.ts
877
+ function renderPrompt(raw) {
878
+ const command = marker(raw, "command-name");
879
+ if (command) {
880
+ const args = marker(raw, "command-args");
881
+ const name = `/${command.replace(/^\/+/, "")}`;
882
+ return args ? `${name} ${args}` : name;
883
+ }
884
+ const bashInput = marker(raw, "bash-input");
885
+ if (bashInput) return `! ${bashInput}`;
886
+ return stripBlocks(raw);
887
+ }
888
+ function marker(raw, tag) {
889
+ const match = raw.match(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`));
890
+ return match ? match[1].trim() : "";
891
+ }
892
+ function stripBlocks(raw) {
893
+ return raw.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, "").replace(/<task-notification>[\s\S]*?<\/task-notification>/g, "").replace(/<command-[^>]*>[\s\S]*?<\/command-[^>]*>/g, "").replace(/<local-command-[^>]*>[\s\S]*?<\/local-command-[^>]*>/g, "").replace(/<bash-(stdout|stderr)>[\s\S]*?<\/bash-\1>/g, "").trim();
894
+ }
895
+
896
+ // src/commands/sessions/shared/renderUserPrompt.ts
897
+ var MAX_LENGTH = 2048;
898
+ var INTERRUPT_PREFIX2 = "[Request interrupted";
899
+ function renderUserPrompt(entry, maxLength = MAX_LENGTH) {
900
+ if (entry.isSidechain || entry.isMeta) return void 0;
901
+ if (entry.type !== "user" || isTaskNotification(entry)) return void 0;
902
+ const raw = promptTextOrNull(entry);
903
+ if (raw === null) return void 0;
904
+ const message2 = renderPrompt(raw);
905
+ return message2 ? cap(message2, maxLength) : void 0;
906
+ }
907
+ function isTaskNotification(entry) {
908
+ return asRecord4(entry.origin)?.kind === "task-notification";
909
+ }
910
+ function promptTextOrNull(entry) {
911
+ const content = asRecord4(entry.message)?.content;
912
+ if (typeof content === "string") return isInterrupt(content) ? null : content;
913
+ if (!Array.isArray(content)) return null;
914
+ const parts = [];
915
+ for (const block of content) {
916
+ const b = asRecord4(block);
917
+ if (b?.type !== "text") continue;
918
+ const text = typeof b.text === "string" ? b.text : "";
919
+ if (isInterrupt(text)) return null;
920
+ parts.push(text);
921
+ }
922
+ return parts.length === 0 ? null : parts.join("\n");
923
+ }
924
+ function cap(message2, maxLength) {
925
+ return message2.length <= maxLength ? message2 : `${message2.slice(0, maxLength).trimEnd()}\u2026`;
926
+ }
927
+ function isInterrupt(value) {
928
+ return value.trimStart().startsWith(INTERRUPT_PREFIX2);
929
+ }
930
+ function asRecord4(value) {
931
+ return value && typeof value === "object" ? value : null;
932
+ }
933
+
934
+ // src/commands/sessions/shared/toolTarget.ts
935
+ function toolTarget(input) {
936
+ if (!input || typeof input !== "object") return "";
937
+ const i = input;
938
+ const str = (v) => typeof v === "string" ? v : "";
939
+ const target = str(i.file_path) || str(i.path) || str(i.notebook_path) || str(i.command) || str(i.pattern) || str(i.url) || str(i.query) || str(i.description) || str(i.prompt);
940
+ return target.replace(/\s+/g, " ").trim().slice(0, 120);
941
+ }
942
+
943
+ // src/shared/harnessAdapters/claudeContentBlocksOf.ts
944
+ function claudeContentBlocksOf(content) {
945
+ return Array.isArray(content) ? content.filter(
946
+ (b) => !!b && typeof b === "object"
947
+ ) : [];
948
+ }
949
+
950
+ // src/shared/harnessAdapters/editTexts.ts
951
+ function editTexts(input, ...fields) {
952
+ if (!Array.isArray(input.edits)) return [];
953
+ return input.edits.flatMap((edit) => {
954
+ const record3 = edit ?? {};
955
+ const text = fields.map((field) => record3[field]).find((value) => typeof value === "string");
956
+ return text === void 0 ? [] : [text];
957
+ });
958
+ }
959
+
960
+ // src/shared/harnessAdapters/claudeToolOperations.ts
961
+ var COMMAND_TOOLS = /* @__PURE__ */ new Set(["Bash", "PowerShell"]);
962
+ var READ_TOOLS = /* @__PURE__ */ new Set(["Read", "Grep", "Glob"]);
963
+ var READ_FIELDS = ["file_path", "path", "pattern", "glob"];
964
+ var WRITE_TOOLS = /* @__PURE__ */ new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
965
+ function strings(values) {
966
+ return values.filter((value) => typeof value === "string");
967
+ }
968
+ function incomingContents(input) {
969
+ return [
970
+ ...strings([input.content, input.new_string, input.new_source]),
971
+ ...editTexts(input, "new_string")
972
+ ];
973
+ }
974
+ function claudeToolOperations({
975
+ toolName,
976
+ toolInput
977
+ }) {
978
+ if (COMMAND_TOOLS.has(toolName)) {
979
+ const { command } = toolInput;
980
+ return typeof command === "string" ? [{ kind: "command", tool: toolName, command: command.trim() }] : [];
981
+ }
982
+ if (READ_TOOLS.has(toolName)) {
983
+ const paths = strings(READ_FIELDS.map((field) => toolInput[field]));
984
+ return paths.length ? [{ kind: "fileRead", tool: toolName, paths }] : [];
985
+ }
986
+ if (WRITE_TOOLS.has(toolName)) {
987
+ const [path15] = strings([toolInput.file_path, toolInput.notebook_path]);
988
+ return path15 ? [
989
+ {
990
+ kind: "fileWrite",
991
+ tool: toolName,
992
+ path: path15,
993
+ contents: incomingContents(toolInput)
994
+ }
995
+ ] : [];
996
+ }
997
+ if (toolName === "AskUserQuestion" && Array.isArray(toolInput.questions))
998
+ return [
999
+ {
1000
+ kind: "question",
1001
+ tool: toolName,
1002
+ questionsJson: JSON.stringify({ questions: toolInput.questions })
1003
+ }
1004
+ ];
1005
+ return [];
1006
+ }
1007
+
1008
+ // src/shared/harnessAdapters/claudeAssistantEvents.ts
1009
+ function assistantText(content) {
1010
+ if (typeof content === "string") return content.trim();
1011
+ return claudeContentBlocksOf(content).filter((b) => b.type === "text" && typeof b.text === "string").map((b) => String(b.text).trim()).filter(Boolean).join("\n");
1012
+ }
1013
+ function toolEvent(block, at) {
1014
+ const tool = typeof block.name === "string" ? block.name : "tool";
1015
+ const input = block.input && typeof block.input === "object" ? block.input : {};
1016
+ return {
1017
+ kind: "tool",
1018
+ tool,
1019
+ target: toolTarget(block.input),
1020
+ operations: claudeToolOperations({ toolName: tool, toolInput: input }),
1021
+ at
1022
+ };
1023
+ }
1024
+ function claudeAssistantEvents(content, at) {
1025
+ const text = assistantText(content);
1026
+ const message2 = text ? [{ kind: "message", role: "assistant", text, at }] : [];
1027
+ return [
1028
+ ...message2,
1029
+ ...claudeContentBlocksOf(content).filter((block) => block.type === "tool_use").map((block) => toolEvent(block, at))
1030
+ ];
1031
+ }
1032
+
1033
+ // src/shared/harnessAdapters/claudeEntryEvents.ts
1034
+ function contentOf(entry) {
1035
+ return entry.message?.content;
1036
+ }
1037
+ function resultText(content) {
1038
+ if (typeof content === "string") return content;
1039
+ return claudeContentBlocksOf(content).filter((block) => block.type === "text").map((block) => String(block.text ?? "")).join("\n");
1040
+ }
1041
+ function userEvents(entry, at) {
1042
+ const events = [];
1043
+ const text = renderUserPrompt(entry, Number.POSITIVE_INFINITY);
1044
+ if (text) events.push({ kind: "message", role: "user", text, at });
1045
+ else if (normalizeUser(entry).kind === "interrupt")
1046
+ events.push({ kind: "interrupt", at });
1047
+ for (const block of claudeContentBlocksOf(contentOf(entry))) {
1048
+ if (block.type !== "tool_result" || block.is_error) continue;
1049
+ const body = resultText(block.content).trim();
1050
+ if (body) events.push({ kind: "toolResult", text: body, at });
1051
+ }
1052
+ return events;
1053
+ }
1054
+ function claudeEntryEvents(entry) {
1055
+ if (entry.isSidechain || entry.isMeta) return [];
1056
+ const at = typeof entry.timestamp === "string" ? entry.timestamp : void 0;
1057
+ if (entry.type === "user") return userEvents(entry, at);
1058
+ if (entry.type === "assistant")
1059
+ return claudeAssistantEvents(contentOf(entry), at);
1060
+ return [];
1061
+ }
1062
+
1063
+ // src/shared/harnessAdapters/claudeUnrecognisedShapes.ts
1064
+ var IGNORED_ENTRY_TYPES = /* @__PURE__ */ new Set([
1065
+ "ai-title",
1066
+ "api-request",
1067
+ "api-request-blob",
1068
+ "api-request-shape",
1069
+ "artifact-autoreact-ledger",
1070
+ "artifact-comment-monitor",
1071
+ "atis-latch",
1072
+ "attachment",
1073
+ "cost-state",
1074
+ "custom-title",
1075
+ "file-history-delta",
1076
+ "file-history-snapshot",
1077
+ "fork-context-ref",
1078
+ "frame-link",
1079
+ "isolation-latch",
1080
+ "last-prompt",
1081
+ "mode",
1082
+ "permission-mode",
1083
+ "pr-link",
1084
+ "progress",
1085
+ "queue-operation",
1086
+ "session-owner",
1087
+ "summary",
1088
+ "system",
1089
+ "tools-used"
1090
+ ]);
1091
+ var BLOCK_TYPES = /* @__PURE__ */ new Map([
1092
+ ["user", /* @__PURE__ */ new Set(["text", "tool_result", "image", "document"])],
1093
+ ["assistant", /* @__PURE__ */ new Set(["text", "thinking", "redacted_thinking", "tool_use"])]
1094
+ ]);
1095
+ function blockShapes(entry, known) {
1096
+ const content = entry.message?.content;
1097
+ if (typeof content === "string") return [];
1098
+ if (!Array.isArray(content)) return [`${String(entry.type)}/content`];
1099
+ return claudeContentBlocksOf(content).map((block) => String(block.type)).filter((type) => !known.has(type)).map((type) => `${String(entry.type)}/${type}`);
1100
+ }
1101
+ function claudeUnrecognisedShapes(entries) {
1102
+ const shapes = entries.flatMap((entry) => {
1103
+ const type = String(entry.type);
1104
+ const known = BLOCK_TYPES.get(type);
1105
+ if (known) return blockShapes(entry, known);
1106
+ return IGNORED_ENTRY_TYPES.has(type) ? [] : [type];
1107
+ });
1108
+ return [...new Set(shapes)];
1109
+ }
1110
+
1111
+ // src/shared/harnessAdapters/claudeConversationReader.ts
1112
+ var claudeConversationReader = {
1113
+ headBytes: 65536,
1114
+ locate: ({ cwd, claudeSessionId }) => cwd && claudeSessionId ? findTranscriptPathSync(cwd, claudeSessionId) : null,
1115
+ watchTarget: ({ cwd, claudeSessionId }) => cwd && claudeSessionId ? { dir: projectDirForCwd(cwd), file: `${claudeSessionId}.jsonl` } : null,
1116
+ events: (entries) => entries.flatMap(claudeEntryEvents),
1117
+ lifecycle: (entries, options) => ({
1118
+ status: deriveTranscriptStatus(entries, options),
1119
+ asking: awaitsQuestionAnswer(entries)
1120
+ }),
1121
+ fingerprint: transcriptTailFingerprint,
1122
+ unrecognised: claudeUnrecognisedShapes
1123
+ };
1124
+
1125
+ // src/shared/harnessAdapters/claudeConnectorRun.ts
1126
+ import { spawn as spawn2 } from "child_process";
1127
+
1128
+ // src/commands/review/attachLineParser.ts
1129
+ function flushBuffer(buffer, onLine) {
1130
+ let remaining = buffer;
1131
+ while (true) {
1132
+ const idx = remaining.indexOf("\n");
1133
+ if (idx === -1) return remaining;
1134
+ const line = remaining.slice(0, idx);
1135
+ remaining = remaining.slice(idx + 1);
1136
+ if (line.trim()) onLine(line);
1137
+ }
1138
+ }
1139
+ function attachLineParser(child, onLine) {
1140
+ let buffer = "";
1141
+ child.stdout?.on("data", (chunk) => {
1142
+ buffer += chunk.toString("utf8");
1143
+ buffer = flushBuffer(buffer, onLine);
1144
+ });
1145
+ return () => {
1146
+ if (buffer.trim()) onLine(buffer);
1147
+ };
1148
+ }
1149
+
1150
+ // src/commands/review/attachStderrCollector.ts
1151
+ function attachStderrCollector(child) {
1152
+ const state = { value: "" };
1153
+ child.stderr?.on("data", (chunk) => {
1154
+ state.value += chunk.toString("utf8");
1155
+ });
1156
+ return state;
1157
+ }
1158
+
1159
+ // src/shared/harnessAdapters/claudeConnectorTools.ts
1160
+ var gmail = (tool) => `mcp__claude_ai_Gmail__${tool}`;
1161
+ var slack = (tool) => `mcp__claude_ai_Slack__${tool}`;
1162
+ var nativeNames = {
1163
+ "gmail.searchThreads": gmail("search_threads"),
1164
+ "gmail.getThread": gmail("get_thread"),
1165
+ "slack.search": slack("slack_search_public_and_private"),
1166
+ "slack.readThread": slack("slack_read_thread")
1167
+ };
1168
+ var claudeConnectorTools = {
1169
+ native: (tool) => nativeNames[tool],
1170
+ fromNative: (name) => Object.keys(nativeNames).find(
1171
+ (tool) => nativeNames[tool] === name
1172
+ ),
1173
+ label(name) {
1174
+ const match = name.match(/^mcp__claude_ai_([^_]+)__(?:slack_)?(.+)$/);
1175
+ return match ? `${match[1]} ${match[2]}` : name;
1176
+ },
1177
+ denied: [
1178
+ ...[
1179
+ "apply_sensitive_message_label",
1180
+ "apply_sensitive_thread_label",
1181
+ "create_draft",
1182
+ "create_label",
1183
+ "delete_draft",
1184
+ "delete_label",
1185
+ "forward",
1186
+ "label_message",
1187
+ "label_thread",
1188
+ "mark_message_spam",
1189
+ "mark_thread_spam",
1190
+ "reply",
1191
+ "send_message",
1192
+ "trash_message",
1193
+ "trash_thread",
1194
+ "unlabel_message",
1195
+ "unlabel_thread",
1196
+ "unmark_message_spam",
1197
+ "unmark_thread_spam",
1198
+ "untrash_message",
1199
+ "untrash_thread",
1200
+ "update_draft",
1201
+ "update_label",
1202
+ "update_message_labels"
1203
+ ].map(gmail),
1204
+ ...[
1205
+ "slack_add_reaction",
1206
+ "slack_create_canvas",
1207
+ "slack_create_conversation",
1208
+ "slack_schedule_message",
1209
+ "slack_send_message",
1210
+ "slack_send_message_draft",
1211
+ "slack_update_canvas"
1212
+ ].map(slack)
1213
+ ]
1214
+ };
1215
+
1216
+ // src/shared/harnessAdapters/buildClaudeConnectorArgs.ts
1217
+ function buildClaudeConnectorArgs({
1218
+ prompt,
1219
+ schema,
1220
+ tools
1221
+ }) {
1222
+ return [
1223
+ "-p",
1224
+ "--tools",
1225
+ "",
1226
+ "--permission-mode",
1227
+ "dontAsk",
1228
+ "--allowedTools",
1229
+ ...tools.map(claudeConnectorTools.native),
1230
+ "--disallowedTools",
1231
+ ...claudeConnectorTools.denied,
1232
+ "--no-session-persistence",
1233
+ "--output-format",
1234
+ "stream-json",
1235
+ "--verbose",
1236
+ "--json-schema",
1237
+ JSON.stringify(schema),
1238
+ "--",
1239
+ prompt
1240
+ ];
1241
+ }
1242
+
1243
+ // src/shared/harnessAdapters/claudeBlockEvent.ts
1244
+ function record(value) {
1245
+ return value && typeof value === "object" ? value : {};
1246
+ }
1247
+ function claudeBlockEvent(block, tokens) {
1248
+ if (block.type === "tool_use") {
1249
+ const name = typeof block.name === "string" ? block.name : "tool";
1250
+ return {
1251
+ type: "toolCall",
1252
+ callId: String(block.id),
1253
+ tool: claudeConnectorTools.fromNative(name),
1254
+ label: claudeConnectorTools.label(name),
1255
+ input: record(block.input),
1256
+ tokens: tokens()
1257
+ };
1258
+ }
1259
+ if (block.type === "text" && typeof block.text === "string" && block.text.trim())
1260
+ return { type: "text", text: block.text, tokens: tokens() };
1261
+ return void 0;
1262
+ }
1263
+
1264
+ // src/shared/harnessAdapters/claudeConnectorResult.ts
1265
+ function parseClaudeResultLine(line) {
1266
+ return JSON.parse(line);
1267
+ }
1268
+ function claudeConnectorResult(result, failure, usage) {
1269
+ if (!result) throw new Error(failure);
1270
+ if (result.is_error) throw new Error(result.result ?? "unknown error");
1271
+ return { output: result.structured_output, usage };
1272
+ }
1273
+
1274
+ // src/shared/harnessAdapters/claudeContentBlocks.ts
1275
+ function claudeContentBlocks(content) {
1276
+ return Array.isArray(content) ? content : [];
1277
+ }
1278
+ function resultText2(content) {
1279
+ if (typeof content === "string") return content;
1280
+ return claudeContentBlocks(content).map((block) => typeof block.text === "string" ? block.text : "").join("");
1281
+ }
1282
+ function claudeToolResults(content) {
1283
+ return claudeContentBlocks(content).filter((block) => block.type === "tool_result").map((block) => ({
1284
+ type: "toolResult",
1285
+ callId: String(block.tool_use_id),
1286
+ text: resultText2(block.content)
1287
+ }));
1288
+ }
1289
+
1290
+ // src/commands/review/parseTokenUsage.ts
1291
+ function count(value) {
1292
+ return typeof value === "number" ? value : 0;
1293
+ }
1294
+ function parseTokenUsage(usage, keys) {
1295
+ if (typeof usage !== "object" || usage === null) return void 0;
1296
+ const raw = usage;
1297
+ const parsed = {
1298
+ input: count(raw.input_tokens),
1299
+ output: count(raw.output_tokens),
1300
+ cacheRead: count(raw[keys.cacheRead])
1301
+ };
1302
+ if (keys.cacheWrite) parsed.cacheWrite = count(raw[keys.cacheWrite]);
1303
+ return parsed;
1304
+ }
1305
+
1306
+ // src/commands/review/parseClaudeUsage.ts
1307
+ function parseClaudeUsage(usage) {
1308
+ return parseTokenUsage(usage, {
1309
+ cacheRead: "cache_read_input_tokens",
1310
+ cacheWrite: "cache_creation_input_tokens"
1311
+ });
1312
+ }
1313
+
1314
+ // src/commands/inbox/emptyScanUsage.ts
1315
+ function emptyScanUsage() {
1316
+ return {
1317
+ input: 0,
1318
+ output: 0,
1319
+ cacheRead: 0,
1320
+ cacheWrite: 0,
1321
+ costUsd: null,
1322
+ durationMs: null
1323
+ };
1324
+ }
1325
+
1326
+ // src/commands/inbox/scanUsageTokens.ts
1327
+ function scanUsageTokens(usage) {
1328
+ return usage.input + usage.output + usage.cacheRead + (usage.cacheWrite ?? 0);
1329
+ }
1330
+
1331
+ // src/shared/harnessAdapters/createScanUsageTracker.ts
1332
+ var numberOrNull = (value) => typeof value === "number" ? value : null;
1333
+ function createScanUsageTracker() {
1334
+ const usage = emptyScanUsage();
1335
+ const turns = /* @__PURE__ */ new Map();
1336
+ let unsettled = 0;
1337
+ return {
1338
+ current: () => ({ ...usage }),
1339
+ // stream-json repeats a message's usage on every content-block line, so
1340
+ // each turn is counted once by message id, applying only the change.
1341
+ addTurn(id, raw) {
1342
+ const parsed = parseClaudeUsage(raw);
1343
+ if (!parsed) return false;
1344
+ const key = typeof id === "string" ? id : `turn-${turns.size}`;
1345
+ const previous = turns.get(key);
1346
+ turns.set(key, parsed);
1347
+ usage.input += parsed.input - (previous?.input ?? 0);
1348
+ usage.output += parsed.output - (previous?.output ?? 0);
1349
+ usage.cacheRead += parsed.cacheRead - (previous?.cacheRead ?? 0);
1350
+ usage.cacheWrite += (parsed.cacheWrite ?? 0) - (previous?.cacheWrite ?? 0);
1351
+ unsettled += scanUsageTokens(parsed) - (previous ? scanUsageTokens(previous) : 0);
1352
+ return true;
1353
+ },
1354
+ takeTurnTokens() {
1355
+ const tokens = unsettled;
1356
+ unsettled = 0;
1357
+ return tokens > 0 ? tokens : void 0;
1358
+ },
1359
+ finish(result) {
1360
+ usage.costUsd = numberOrNull(result.total_cost_usd);
1361
+ usage.durationMs = numberOrNull(result.duration_ms);
1362
+ }
1363
+ };
1364
+ }
1365
+
1366
+ // src/shared/harnessAdapters/parseScanStreamLine.ts
1367
+ function parseScanStreamLine(line) {
1368
+ try {
1369
+ return JSON.parse(line);
1370
+ } catch {
1371
+ return void 0;
1372
+ }
1373
+ }
1374
+
1375
+ // src/shared/harnessAdapters/createClaudeConnectorStream.ts
1376
+ function createClaudeConnectorStream(onEvent) {
1377
+ const usage = createScanUsageTracker();
1378
+ let result;
1379
+ const emitUsage = () => onEvent({ type: "usage", usage: usage.current() });
1380
+ const onAssistant = (message2) => {
1381
+ const counted = usage.addTurn(message2.id, message2.usage);
1382
+ for (const block of claudeContentBlocks(message2.content)) {
1383
+ const event = claudeBlockEvent(block, usage.takeTurnTokens);
1384
+ if (event) onEvent(event);
1385
+ }
1386
+ if (counted) emitUsage();
1387
+ };
1388
+ return {
1389
+ onLine(line) {
1390
+ const event = parseScanStreamLine(line);
1391
+ if (event?.type === "system" && typeof event.model === "string")
1392
+ onEvent({ type: "model", model: event.model });
1393
+ else if (event?.type === "assistant") onAssistant(event.message ?? {});
1394
+ else if (event?.type === "user")
1395
+ claudeToolResults(event.message?.content).forEach(onEvent);
1396
+ else if (event?.type === "result") {
1397
+ result = parseClaudeResultLine(line);
1398
+ usage.finish(event);
1399
+ emitUsage();
1400
+ }
1401
+ },
1402
+ finish: (failure) => claudeConnectorResult(result, failure, usage.current())
1403
+ };
1404
+ }
1405
+
1406
+ // src/shared/harnessAdapters/claudeConnectorRun.ts
1407
+ function describeExit(code, signal) {
1408
+ return signal ? `claude was killed (${signal})` : `claude exited ${code}`;
1409
+ }
1410
+ async function claudeConnectorRun(run) {
1411
+ const child = spawn2(harnesses.claude.command, buildClaudeConnectorArgs(run), {
1412
+ stdio: ["ignore", "pipe", "pipe"],
1413
+ windowsHide: true,
1414
+ timeout: run.timeoutMs
1415
+ });
1416
+ const stream = createClaudeConnectorStream(run.onEvent);
1417
+ const flush = attachLineParser(child, stream.onLine);
1418
+ const stderr = attachStderrCollector(child);
1419
+ const exit = await new Promise((resolve, reject) => {
1420
+ child.on("error", reject);
1421
+ child.on("close", (code, signal) => resolve(describeExit(code, signal)));
1422
+ });
1423
+ flush();
1424
+ const tail = stderr.value.trim().slice(-500);
1425
+ return stream.finish(tail ? `${exit}: ${tail}` : exit);
1426
+ }
1427
+
1428
+ // src/shared/harnessAdapters/claudeOneShot.ts
1429
+ import { execFile } from "child_process";
1430
+ import { promisify } from "util";
1431
+ var execFileAsync = promisify(execFile);
1432
+ var MODEL_FOR_EFFORT = { low: "haiku", medium: "sonnet" };
1433
+ async function claudeOneShot(prompt, { timeout, effort = "low", cwd }) {
1434
+ const { stdout } = await execFileAsync(
1435
+ harnesses.claude.command,
1436
+ ["-p", "--model", MODEL_FOR_EFFORT[effort], prompt],
1437
+ { encoding: "utf8", windowsHide: true, timeout, cwd }
1438
+ );
1439
+ return stdout;
1440
+ }
1441
+
1442
+ // src/commands/review/runClaudeReviewer.ts
1443
+ import { writeFileSync as writeFileSync3 } from "fs";
1444
+
1445
+ // src/commands/review/formatToolSummary.ts
1446
+ function truncate(value, max = 80) {
1447
+ const collapsed = value.replace(/\s+/g, " ").trim();
1448
+ if (collapsed.length <= max) return collapsed;
1449
+ return `${collapsed.slice(0, max - 1)}\u2026`;
1450
+ }
1451
+ function getString(input, key) {
1452
+ const value = input[key];
1453
+ return typeof value === "string" ? value : null;
1454
+ }
1455
+ function formatToolSummary(input) {
1456
+ if (!input || typeof input !== "object") return "";
1457
+ const record3 = input;
1458
+ const pattern = getString(record3, "pattern");
1459
+ if (pattern) {
1460
+ const scope = getString(record3, "path");
1461
+ return scope ? `${pattern} in ${scope}` : pattern;
1462
+ }
1463
+ const filePath = getString(record3, "file_path") ?? getString(record3, "path");
1464
+ if (filePath) return filePath;
1465
+ const command = getString(record3, "command");
1466
+ if (command) return truncate(command);
1467
+ const url = getString(record3, "url");
1468
+ if (url) return url;
1469
+ const query2 = getString(record3, "query");
1470
+ if (query2) return truncate(query2);
1471
+ const description = getString(record3, "description");
1472
+ if (description) return truncate(description);
1473
+ return "";
1474
+ }
1475
+ function simplifyShellCommand(command) {
1476
+ const wrapped = command.match(/^\/bin\/bash\s+-lc\s+"(.*)"\s*$/s);
1477
+ const inner = wrapped ? wrapped[1].replace(/\\"/g, '"') : command;
1478
+ return truncate(inner);
1479
+ }
1480
+
1481
+ // src/commands/review/parseClaudeEvent.ts
1482
+ function isAssistantEvent(value) {
1483
+ return typeof value === "object" && value !== null && value.type === "assistant";
1484
+ }
1485
+ function isResultEvent(value) {
1486
+ return typeof value === "object" && value !== null && value.type === "result";
1487
+ }
1488
+ function extractToolUses(event) {
1489
+ const content = event.message?.content ?? [];
1490
+ const uses = [];
1491
+ for (const block of content) {
1492
+ if (block.type !== "tool_use") continue;
1493
+ const named = block;
1494
+ const name = typeof named.name === "string" ? named.name : "tool";
1495
+ uses.push({ tool: name, summary: formatToolSummary(named.input) });
1496
+ }
1497
+ return uses;
1498
+ }
1499
+ function parseClaudeEvent(line) {
1500
+ let event;
1501
+ try {
1502
+ event = JSON.parse(line);
1503
+ } catch {
1504
+ return { kind: "ignore" };
1505
+ }
1506
+ if (isAssistantEvent(event)) {
1507
+ const toolUses = extractToolUses(event);
1508
+ if (toolUses.length > 0) return { kind: "tool_uses", toolUses };
1509
+ }
1510
+ if (isResultEvent(event) && typeof event.result === "string") {
1511
+ const usage = parseClaudeUsage(event.usage);
1512
+ return usage ? { kind: "final", text: event.result, usage } : { kind: "final", text: event.result };
1513
+ }
1514
+ return { kind: "ignore" };
1515
+ }
1516
+
1517
+ // src/commands/review/formatToolText.ts
1518
+ function formatToolText(name, tool, summary) {
1519
+ const suffix = summary ? `: ${summary}` : "";
1520
+ return `${name} \u2014 ${tool}${suffix}`;
1521
+ }
1522
+
1523
+ // src/commands/review/reviewerLabel.ts
1524
+ function reviewerLabel(name, model) {
1525
+ return model ? `${name} (${model})` : name;
1526
+ }
1527
+
1528
+ // src/commands/review/reportReviewerToolUse.ts
1529
+ function reportReviewerToolUse(name, use, spinner, model) {
1530
+ const label = reviewerLabel(name, model);
1531
+ if (spinner) {
1532
+ spinner.text = formatToolText(label, use.tool, use.summary);
1533
+ return;
1534
+ }
1535
+ const suffix = use.summary ? `: ${use.summary}` : "";
1536
+ console.log(`[${label}] ${use.tool}${suffix}`);
1537
+ }
1538
+
1539
+ // src/commands/review/createClaudeLineHandler.ts
1540
+ function createClaudeLineHandler(name, spinner) {
1541
+ const state = { finalText: "" };
1542
+ const onLine = (line) => {
1543
+ const event = parseClaudeEvent(line);
1544
+ if (event.kind === "tool_uses") {
1545
+ for (const use of event.toolUses)
1546
+ reportReviewerToolUse(name, use, spinner);
1547
+ return;
1548
+ }
1549
+ if (event.kind === "final") {
1550
+ state.finalText = event.text;
1551
+ state.usage = event.usage;
1552
+ }
1553
+ };
1554
+ return { state, onLine };
1555
+ }
1556
+
1557
+ // src/commands/review/finaliseReviewerSpinner.ts
1558
+ var SUMMARY_MAX_LEN = 80;
1559
+ function summariseStderr(stderr) {
1560
+ const firstLine = stderr.split(/\r?\n/).find((l) => l.trim().length > 0);
1561
+ if (!firstLine) return "";
1562
+ const trimmed = firstLine.trim();
1563
+ return trimmed.length > SUMMARY_MAX_LEN ? `${trimmed.slice(0, SUMMARY_MAX_LEN - 1)}\u2026` : trimmed;
1564
+ }
1565
+ function finaliseReviewerSpinner(spinner, outcome) {
1566
+ const label = reviewerLabel(outcome.name, outcome.model);
1567
+ const elapsed = Math.round(outcome.elapsedMs / 1e3);
1568
+ if (outcome.exitCode === 0) {
1569
+ spinner.succeed(`${label} \u2014 done in ${elapsed}s`);
1570
+ return;
1571
+ }
1572
+ const summary = summariseStderr(outcome.stderr ?? "");
1573
+ const suffix = summary ? `: ${summary}` : "";
1574
+ spinner.fail(
1575
+ `${label} \u2014 failed in ${elapsed}s (exit ${outcome.exitCode})${suffix}`
1576
+ );
1577
+ }
1578
+
1579
+ // src/commands/review/finaliseReviewerRun.ts
1580
+ function finaliseReviewerRun(spec, spinner, result) {
1581
+ if (spinner)
1582
+ finaliseReviewerSpinner(spinner, {
1583
+ name: spec.name,
1584
+ model: spec.model,
1585
+ exitCode: result.exitCode,
1586
+ elapsedMs: result.elapsedMs,
1587
+ stderr: result.stderr
1588
+ });
1589
+ return {
1590
+ name: spec.name,
1591
+ command: spec.command,
1592
+ model: spec.model,
1593
+ outputPath: spec.outputPath,
1594
+ exitCode: result.exitCode,
1595
+ stderr: result.stderr,
1596
+ stdout: result.stdout,
1597
+ elapsedMs: result.elapsedMs
1598
+ };
1599
+ }
1600
+
1601
+ // src/commands/review/runStreamingChild.ts
1602
+ import { spawn as spawn3 } from "child_process";
1603
+
1604
+ // src/commands/review/attachStdoutTail.ts
1605
+ function attachStdoutTail(child, maxBytes = 8192) {
1606
+ const state = { value: "" };
1607
+ child.stdout?.on("data", (chunk) => {
1608
+ state.value += chunk.toString("utf8");
1609
+ if (state.value.length > maxBytes) {
1610
+ state.value = state.value.slice(state.value.length - maxBytes);
1611
+ }
1612
+ });
1613
+ return state;
1614
+ }
1615
+
1616
+ // src/commands/review/formatReviewerFailure.ts
1617
+ var FAST_FAIL_MS = 1e3;
1618
+ var STDOUT_TAIL_LINES = 20;
1619
+ function indent(text) {
1620
+ return text.split(/\r?\n/).map((line) => ` ${line}`);
1621
+ }
1622
+ function tailLines(text, maxLines) {
1623
+ const lines = text.split(/\r?\n/);
1624
+ return lines.length <= maxLines ? text : lines.slice(-maxLines).join("\n");
1625
+ }
1626
+ function isFastFail(input) {
1627
+ return input.exitCode !== 0 && input.elapsedMs !== void 0 && input.elapsedMs < FAST_FAIL_MS;
1628
+ }
1629
+ function fastFailHint(command) {
1630
+ return [
1631
+ `${command} exited almost immediately \u2014 it likely failed to start.`,
1632
+ `Common causes: not installed on PATH, not authenticated, or misconfigured.`,
1633
+ `Try \`${command} --version\` to confirm install, then \`${command} login\` if authentication may be missing.`
1634
+ ];
1635
+ }
1636
+ function outputDetail(input) {
1637
+ const stderr = input.stderr.trim();
1638
+ if (stderr) return ["stderr:", ...indent(stderr)];
1639
+ const stdout = (input.stdout ?? "").trim();
1640
+ if (stdout) {
1641
+ return [
1642
+ `stdout (no stderr was captured \u2014 showing last ${STDOUT_TAIL_LINES} lines):`,
1643
+ ...indent(tailLines(stdout, STDOUT_TAIL_LINES))
1644
+ ];
1645
+ }
1646
+ return [
1647
+ "No stderr or stdout was captured. Check the review folder for partial output, or rerun with --verbose for full streaming output."
1648
+ ];
1649
+ }
1650
+ function formatReviewerFailure(input) {
1651
+ const command = input.command ?? input.name;
1652
+ const seconds = Math.round((input.elapsedMs ?? 0) / 1e3);
1653
+ const headerLine = `${reviewerLabel(command, input.model)} CLI exited with code ${input.exitCode} after ${seconds}s`;
1654
+ const detailLines = [];
1655
+ if (isFastFail(input)) detailLines.push(...fastFailHint(command));
1656
+ detailLines.push(...outputDetail(input));
1657
+ return { headerLine, detailLines };
1658
+ }
1659
+ function printReviewerFailure(input) {
1660
+ if (input.exitCode === 0) return;
1661
+ const diagnostic = formatReviewerFailure(input);
1662
+ console.error(`[${input.name}] ${diagnostic.headerLine}`);
1663
+ for (const line of diagnostic.detailLines) console.error(line);
1664
+ }
1665
+
1666
+ // src/commands/review/logChildClose.ts
1667
+ function logChildClose(args) {
1668
+ const elapsedSeconds = Math.round(args.elapsedMs / 1e3);
1669
+ if (args.exitCode === 0) {
1670
+ console.log(`[${args.name}] done in ${elapsedSeconds}s`);
1671
+ return;
1672
+ }
1673
+ const diagnostic = formatReviewerFailure({
1674
+ name: args.name,
1675
+ command: args.command,
1676
+ model: args.model,
1677
+ exitCode: args.exitCode,
1678
+ stderr: args.stderr,
1679
+ stdout: args.stdout,
1680
+ elapsedMs: args.elapsedMs
1681
+ });
1682
+ console.error(`[${args.name}] ${diagnostic.headerLine}`);
1683
+ for (const line of diagnostic.detailLines) console.error(line);
1684
+ }
1685
+
1686
+ // src/commands/review/handleChildClose.ts
1687
+ function handleChildClose(args) {
1688
+ const elapsedMs = Date.now() - args.startedAt;
1689
+ const exitCode = args.code ?? 0;
1690
+ if (!args.quiet) {
1691
+ logChildClose({
1692
+ name: args.name,
1693
+ command: args.command,
1694
+ model: args.model,
1695
+ exitCode,
1696
+ elapsedMs,
1697
+ stderr: args.stderr,
1698
+ stdout: args.stdout
1699
+ });
1700
+ }
1701
+ return { exitCode, elapsedMs };
1702
+ }
1703
+
1704
+ // src/commands/review/handleSpawnError.ts
1705
+ function messageFor(err, command) {
1706
+ if (err.code === "ENOENT") return `command not found: ${command}`;
1707
+ return err.message || String(err);
1708
+ }
1709
+ function handleSpawnError(ctx, err) {
1710
+ const message2 = messageFor(err, ctx.command);
1711
+ const stderr = ctx.stderr ? `${ctx.stderr}
1712
+ ${message2}` : message2;
1713
+ if (!ctx.quiet) console.error(`[${ctx.name}] failed: ${message2}`);
1714
+ return {
1715
+ exitCode: 127,
1716
+ stderr,
1717
+ stdout: ctx.stdout,
1718
+ elapsedMs: Date.now() - ctx.startedAt
1719
+ };
1720
+ }
1721
+
1722
+ // src/commands/review/waitForChildExit.ts
1723
+ function onErrorResult(ctx, err) {
1724
+ ctx.flushPending();
1725
+ return handleSpawnError(
1726
+ {
1727
+ command: ctx.command,
1728
+ name: ctx.name,
1729
+ stderr: ctx.stderr.value,
1730
+ stdout: ctx.stdout.value,
1731
+ startedAt: ctx.startedAt,
1732
+ quiet: ctx.quiet
1733
+ },
1734
+ err
1735
+ );
1736
+ }
1737
+ function onCloseResult(ctx, code) {
1738
+ ctx.flushPending();
1739
+ const closed = handleChildClose({
1740
+ code,
1741
+ startedAt: ctx.startedAt,
1742
+ name: ctx.name,
1743
+ command: ctx.command,
1744
+ model: ctx.model,
1745
+ stderr: ctx.stderr.value,
1746
+ stdout: ctx.stdout.value,
1747
+ quiet: ctx.quiet
1748
+ });
1749
+ return { ...closed, stderr: ctx.stderr.value, stdout: ctx.stdout.value };
1750
+ }
1751
+ function waitForChildExit(ctx) {
1752
+ return new Promise((resolve) => {
1753
+ let settled = false;
1754
+ const settle = (result) => {
1755
+ if (settled) return;
1756
+ settled = true;
1757
+ resolve(result);
1758
+ };
1759
+ ctx.child.on("error", (err) => settle(onErrorResult(ctx, err)));
1760
+ ctx.child.on("close", (code) => settle(onCloseResult(ctx, code)));
1761
+ });
1762
+ }
1763
+
1764
+ // src/commands/review/runStreamingChild.ts
1765
+ function writeStdinSafely(child, payload) {
1766
+ child.stdin?.on("error", () => {
1767
+ });
1768
+ try {
1769
+ child.stdin?.write(payload);
1770
+ child.stdin?.end();
1771
+ } catch {
1772
+ }
1773
+ }
1774
+ function startChild(spec) {
1775
+ const child = spawn3(spec.command, spec.args, {
1776
+ stdio: ["pipe", "pipe", "pipe"],
1777
+ shell: process.platform === "win32",
1778
+ ...spec.env ? { env: { ...process.env, ...spec.env } } : {}
1779
+ });
1780
+ const flushPending = attachLineParser(child, spec.onLine);
1781
+ const stderr = attachStderrCollector(child);
1782
+ const stdout = attachStdoutTail(child);
1783
+ writeStdinSafely(child, spec.stdin);
1784
+ return { child, flushPending, stderr, stdout };
1785
+ }
1786
+ function runStreamingChild(spec) {
1787
+ const startedAt = Date.now();
1788
+ if (!spec.quiet)
1789
+ console.log(`[${reviewerLabel(spec.name, spec.model)}] starting`);
1790
+ const { child, flushPending, stderr, stdout } = startChild(spec);
1791
+ return waitForChildExit({
1792
+ child,
1793
+ flushPending,
1794
+ stderr,
1795
+ stdout,
1796
+ name: spec.name,
1797
+ command: spec.command,
1798
+ model: spec.model,
1799
+ startedAt,
1800
+ quiet: spec.quiet ?? false
1801
+ });
1802
+ }
1803
+
1804
+ // src/commands/review/runClaudeReviewer.ts
1805
+ async function runClaudeReviewer(spec) {
1806
+ const { spinner, model } = spec;
1807
+ const command = "claude";
1808
+ const { state, onLine } = createClaudeLineHandler(spec.name, spinner);
1809
+ const result = await runStreamingChild({
1810
+ name: spec.name,
1811
+ command,
1812
+ model,
1813
+ args: [
1814
+ "-p",
1815
+ ...model ? ["--model", model] : [],
1816
+ "--add-dir",
1817
+ spec.reviewDir,
1818
+ "--output-format",
1819
+ "stream-json",
1820
+ "--verbose"
1821
+ ],
1822
+ stdin: spec.stdin,
1823
+ quiet: Boolean(spinner),
1824
+ onLine
1825
+ });
1826
+ if (result.exitCode === 0 && state.finalText)
1827
+ writeFileSync3(spec.outputPath, state.finalText);
1828
+ const finalised = finaliseReviewerRun({ ...spec, command }, spinner, result);
1829
+ return state.usage ? { ...finalised, usage: state.usage } : finalised;
1830
+ }
1831
+
1832
+ // src/shared/harnessAdapters/claudeStructuredRun.ts
1833
+ function claudeStructuredRun({
1834
+ name,
1835
+ stdin,
1836
+ outputPath,
1837
+ readDir,
1838
+ model,
1839
+ spinner
1840
+ }) {
1841
+ return runClaudeReviewer({
1842
+ name,
1843
+ reviewDir: readDir,
1844
+ stdin,
1845
+ outputPath,
1846
+ model,
1847
+ spinner: spinner?.(model)
1848
+ });
1849
+ }
1850
+
1851
+ // src/shared/harnessAdapters/detectHarness.ts
1852
+ function detectHarness(kind) {
1853
+ if (isHarnessAvailable(kind)) return supported;
1854
+ const { command } = harnesses[kind];
1855
+ return unsupported(
1856
+ `${harnessLabel(kind)} is not installed (\`${command}\` is not on PATH)`,
1857
+ `install ${harnessLabel(kind)} so \`${command}\` is on PATH, or pick another harness`
1858
+ );
1859
+ }
1860
+
1861
+ // src/shared/harnessAdapters/claudeAdapter.ts
1862
+ var claudeAdapter = {
1863
+ kind: "claude",
1864
+ label: harnessLabel("claude"),
1865
+ capabilities: {
1866
+ ...harnessCapabilityDeclarations.claude,
1867
+ "connector.gmail.read": () => claudeConnectorProbe("Gmail"),
1868
+ "connector.slack.read": () => claudeConnectorProbe("Slack")
1869
+ },
1870
+ detect: () => detectHarness("claude"),
1871
+ conversation: {
1872
+ idName: "claude session id",
1873
+ findResumable: (ref) => hasTranscriptOnDisk(ref) ? ref.claudeSessionId : void 0,
1874
+ locate: findSessionJsonlPath,
1875
+ current: () => process.env.CLAUDE_CODE_SESSION_ID || void 0,
1876
+ boundId: ({ claudeSessionId }) => claudeSessionId,
1877
+ toRef: (claudeSessionId, cwd) => ({ cwd, claudeSessionId }),
1878
+ relocate: carryTranscriptToTree,
1879
+ reader: claudeConversationReader,
1880
+ interruptedTasks: claudeInterruptedTasks
1881
+ },
1882
+ toolOperations: claudeToolOperations,
1883
+ launchSkill: (skill, args, { conversationId, allowEdits, model }) => spawnClaude2(buildSlashCommand(skill, args), {
1884
+ allowEdits: allowEdits ?? true,
1885
+ sessionId: conversationId,
1886
+ model
1887
+ }),
1888
+ launchPrompt: (prompt, { conversationId, allowEdits, model }) => spawnClaude2(prompt, {
1889
+ allowEdits: allowEdits ?? true,
1890
+ sessionId: conversationId,
1891
+ model
1892
+ }),
1893
+ resume: (conversationId, nudge, { allowEdits }) => spawnClaude2(nudge, {
1894
+ allowEdits: allowEdits ?? true,
1895
+ resumeSessionId: conversationId
1896
+ }),
1897
+ interactive: ({
1898
+ sessionId,
1899
+ conversationId,
1900
+ resumeId,
1901
+ prompt,
1902
+ cwd,
1903
+ appendSystemPromptFile,
1904
+ auto,
1905
+ model
1906
+ }) => spawnClaude({
1907
+ prompt,
1908
+ cwd,
1909
+ sessionId,
1910
+ resumeSessionId: resumeId,
1911
+ claudeSessionId: conversationId,
1912
+ appendSystemPromptFile,
1913
+ auto,
1914
+ model
1915
+ }),
1916
+ oneShot: claudeOneShot,
1917
+ structured: claudeStructuredRun,
1918
+ connectorRun: claudeConnectorRun,
1919
+ activityIdentity: (conversationId) => ({ claudeSessionId: conversationId })
1920
+ };
1921
+
1922
+ // src/commands/sessions/daemon/sdk/sdkUsageSink.ts
1923
+ var sink;
1924
+ function setSdkUsageSink(next) {
1925
+ sink = next;
1926
+ }
1927
+ function sdkUsageSink() {
1928
+ return sink;
1929
+ }
1930
+
1931
+ // src/shared/resolveCodexModel.ts
1932
+ var CODEX_DEFAULT_MODEL = "codex-default";
1933
+ function resolveCodexModel(raw) {
1934
+ const model = raw?.trim();
1935
+ if (!model || model === CODEX_DEFAULT_MODEL) return void 0;
1936
+ return model;
1937
+ }
1938
+
1939
+ // src/commands/litellm/buildCodexProviderArgs.ts
1940
+ var API_KEY_ENV = "ASSIST_LITELLM_API_KEY";
1941
+ function buildCodexProviderArgs(responsesBaseUrl, apiKey, model) {
1942
+ return {
1943
+ args: [
1944
+ "-c",
1945
+ "model_providers.litellm.name=LiteLLM",
1946
+ "-c",
1947
+ `model_providers.litellm.base_url=${responsesBaseUrl}`,
1948
+ "-c",
1949
+ `model_providers.litellm.env_key=${API_KEY_ENV}`,
1950
+ "-c",
1951
+ "model_providers.litellm.wire_api=responses",
1952
+ "-c",
1953
+ "model_provider=litellm",
1954
+ "-m",
1955
+ model
1956
+ ],
1957
+ env: { [API_KEY_ENV]: apiKey },
1958
+ model
1959
+ };
1960
+ }
1961
+
1962
+ // src/commands/litellm/buildLitellmCodexArgs.ts
1963
+ function buildLitellmCodexArgs(rawModel) {
1964
+ const model = resolveCodexModel(rawModel);
1965
+ if (!model) return { args: [], env: {} };
1966
+ const { config } = readLitellmConfig();
1967
+ if (!config) return { args: [], env: {} };
1968
+ return buildCodexProviderArgs(`${config.baseUrl}/v1`, config.apiKey, model);
1969
+ }
1970
+
1971
+ // src/shared/buildHarnessCodexArgs.ts
1972
+ function buildHarnessCodexArgs() {
1973
+ return buildLitellmCodexArgs(loadConfig().harness.codexModel);
1974
+ }
1975
+
1976
+ // src/shared/codexIsolatedHookArgs.ts
1977
+ var codexIsolatedHookArgs = ["--no-daemon"];
1978
+
1979
+ // src/shared/codexSandboxArgs.ts
1980
+ import { mkdirSync as mkdirSync3 } from "fs";
1981
+ import { homedir as homedir4 } from "os";
1982
+ import { join as join6 } from "path";
1983
+ function codexSandboxArgs() {
1984
+ const assistHome = join6(homedir4(), ".assist");
1985
+ mkdirSync3(assistHome, { recursive: true });
1986
+ return [
1987
+ "-c",
1988
+ "sandbox_workspace_write.network_access=true",
1989
+ "--add-dir",
1990
+ assistHome
1991
+ ];
1992
+ }
1993
+
1994
+ // src/shared/prepareCodexHookTrust.ts
1995
+ import { spawnSync } from "child_process";
1996
+ import * as fs5 from "fs";
1997
+ import * as path7 from "path";
1998
+ var TIMEOUT_MS = 3e4;
1999
+ var verified;
2000
+ function fingerprint(configPath) {
2001
+ try {
2002
+ const stat = fs5.statSync(configPath);
2003
+ return `${stat.mtimeMs}:${stat.size}`;
2004
+ } catch {
2005
+ return void 0;
2006
+ }
2007
+ }
2008
+ function hasManagedBlock(configPath) {
2009
+ try {
2010
+ return fs5.readFileSync(configPath, "utf8").includes(MANAGED_BLOCK_BEGIN);
2011
+ } catch {
2012
+ return false;
2013
+ }
2014
+ }
2015
+ function runTrust() {
2016
+ const entry = process.argv[1];
2017
+ return entry ? spawnSync(process.execPath, [entry, "codex-hook-trust"], {
2018
+ encoding: "utf8",
2019
+ timeout: TIMEOUT_MS
2020
+ }) : spawnSync("assist", ["codex-hook-trust"], {
2021
+ encoding: "utf8",
2022
+ timeout: TIMEOUT_MS,
2023
+ shell: process.platform === "win32"
2024
+ });
2025
+ }
2026
+ function prepareCodexHookTrust() {
2027
+ const configPath = path7.join(harnesses.codex.homeDir, "config.toml");
2028
+ if (!hasManagedBlock(configPath)) return void 0;
2029
+ if (verified && verified === fingerprint(configPath)) return void 0;
2030
+ const result = runTrust();
2031
+ if (result.status === 0) {
2032
+ verified = fingerprint(configPath);
2033
+ return void 0;
2034
+ }
2035
+ verified = void 0;
2036
+ return result.stderr?.trim() || `Could not trust Assist's Codex hooks: ${result.error?.message ?? `assist codex-hook-trust exited ${result.status}`}. Codex will ask you to review Assist's hooks; choose Review hooks and trust only the \`assist codex-hook\` entries.`;
2037
+ }
2038
+
2039
+ // src/shared/codexSessionEnvArgs.ts
2040
+ var SESSION_ENV_KEYS = [
2041
+ "ASSIST_SESSION",
2042
+ "ASSIST_SESSION_ID",
2043
+ "ASSIST_BACKLOG_ITEM_ID"
2044
+ ];
2045
+ function codexSessionEnvArgs(env) {
2046
+ return SESSION_ENV_KEYS.flatMap((key) => [
2047
+ "-c",
2048
+ `shell_environment_policy.set.${key}=${JSON.stringify(env[key] ?? "")}`
2049
+ ]);
2050
+ }
2051
+
2052
+ // src/commands/sessions/daemon/codexDeveloperInstructionsArgs.ts
2053
+ import * as fs6 from "fs";
2054
+ function codexDeveloperInstructionsArgs(file) {
2055
+ if (!file) return [];
2056
+ const text = JSON.stringify(fs6.readFileSync(file, "utf8"));
2057
+ return ["-c", `developer_instructions=${text}`];
2058
+ }
2059
+
2060
+ // src/shared/trustCodexProject.ts
2061
+ import { execFileSync } from "child_process";
2062
+ import * as fs7 from "fs";
2063
+ import * as path8 from "path";
2064
+ function repoRoot(cwd) {
2065
+ try {
2066
+ const commonDir = execFileSync(
2067
+ "git",
2068
+ ["rev-parse", "--path-format=absolute", "--git-common-dir"],
2069
+ { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }
2070
+ ).trim();
2071
+ return path8.dirname(commonDir);
2072
+ } catch {
2073
+ return void 0;
2074
+ }
2075
+ }
2076
+ function trustCodexProject(cwd) {
2077
+ const root = repoRoot(cwd ?? process.cwd());
2078
+ if (!root) return void 0;
2079
+ const configPath = path8.join(harnesses.codex.homeDir, "config.toml");
2080
+ const existing = fs7.existsSync(configPath) ? fs7.readFileSync(configPath, "utf8") : "";
2081
+ const header = `[projects.${JSON.stringify(root)}]`;
2082
+ if (existing.includes(header)) return void 0;
2083
+ const base = existing.replace(/\s*$/, "");
2084
+ const entry = `${header}
2085
+ trust_level = "trusted"
2086
+ `;
2087
+ fs7.mkdirSync(path8.dirname(configPath), { recursive: true });
2088
+ fs7.writeFileSync(configPath, base ? `${base}
2089
+
2090
+ ${entry}` : entry);
2091
+ return root;
2092
+ }
2093
+
2094
+ // src/commands/sessions/daemon/spawnCodex.ts
2095
+ function spawnCodex(opts2 = {}) {
2096
+ const trusted = trustCodexProject(opts2.cwd);
2097
+ if (trusted) daemonLog(`codex: trusted ${trusted} in config.toml`);
2098
+ const untrusted = prepareCodexHookTrust();
2099
+ if (untrusted) daemonLog(`codex: ${untrusted}`);
2100
+ const override = opts2.model ? { args: ["-m", opts2.model], env: {} } : buildHarnessCodexArgs();
2101
+ const sessionEnv = codexSessionEnvArgs({
2102
+ ASSIST_SESSION: "1",
2103
+ ASSIST_SESSION_ID: opts2.sessionId,
2104
+ ASSIST_BACKLOG_ITEM_ID: process.env.ASSIST_BACKLOG_ITEM_ID
2105
+ });
2106
+ return spawnPty(
2107
+ [
2108
+ "codex",
2109
+ ...codexIsolatedHookArgs,
2110
+ ...override.args,
2111
+ ...sessionEnv,
2112
+ ...codexSandboxArgs(),
2113
+ ...codexDeveloperInstructionsArgs(opts2.appendSystemPromptFile),
2114
+ ...codexArgs(opts2)
2115
+ ],
2116
+ opts2.cwd,
2117
+ opts2.sessionId,
2118
+ override.env
2119
+ );
2120
+ }
2121
+ function codexArgs(opts2) {
2122
+ const prompt = opts2.prompt ? [opts2.prompt] : [];
2123
+ if (opts2.resumeSessionId) return ["resume", opts2.resumeSessionId, ...prompt];
2124
+ return prompt;
2125
+ }
2126
+
2127
+ // src/commands/sessions/shared/codex/findCodexRolloutPath.ts
2128
+ import * as path11 from "path";
2129
+
2130
+ // src/commands/sessions/shared/codex/discoverCodexRolloutPaths.ts
2131
+ import * as fs8 from "fs";
2132
+ import * as path10 from "path";
2133
+
2134
+ // src/commands/sessions/shared/codex/codexSessionsDir.ts
2135
+ import { existsSync as existsSync6 } from "fs";
2136
+ import * as path9 from "path";
2137
+ function codexSessionsDir() {
2138
+ return path9.join(harnesses.codex.homeDir, "sessions");
2139
+ }
2140
+ function hasCodexSessions() {
2141
+ return existsSync6(codexSessionsDir());
2142
+ }
2143
+
2144
+ // src/commands/sessions/shared/codex/discoverCodexRolloutPaths.ts
2145
+ var DATE_DEPTH = 3;
2146
+ function isCodexRolloutFile(name) {
2147
+ return name.startsWith("rollout-") && name.endsWith(".jsonl");
2148
+ }
2149
+ async function discoverCodexRolloutPaths() {
2150
+ if (!hasCodexSessions()) return [];
2151
+ return collect(codexSessionsDir(), DATE_DEPTH);
2152
+ }
2153
+ async function collect(dir, depth) {
2154
+ let entries;
2155
+ try {
2156
+ entries = await fs8.promises.readdir(dir, { withFileTypes: true });
2157
+ } catch {
2158
+ return [];
2159
+ }
2160
+ const nested = await Promise.all(
2161
+ entries.map((entry) => collectEntry(dir, entry, depth))
2162
+ );
2163
+ return nested.flat();
2164
+ }
2165
+ async function collectEntry(dir, entry, depth) {
2166
+ const full = path10.join(dir, entry.name);
2167
+ if (entry.isDirectory()) return depth > 0 ? collect(full, depth - 1) : [];
2168
+ return isCodexRolloutFile(entry.name) ? [full] : [];
2169
+ }
2170
+
2171
+ // src/commands/sessions/shared/codex/findCodexRolloutPath.ts
2172
+ async function findCodexRolloutPath(sessionId) {
2173
+ if (!sessionId) return null;
2174
+ const paths = await discoverCodexRolloutPaths();
2175
+ const suffix = `-${sessionId}.jsonl`;
2176
+ return paths.find((file) => path11.basename(file).endsWith(suffix)) ?? null;
2177
+ }
2178
+
2179
+ // src/commands/sessions/shared/codex/findCodexRolloutPathSync.ts
2180
+ import * as fs9 from "fs";
2181
+ import * as path12 from "path";
2182
+ var DATE_DEPTH2 = 3;
2183
+ function findCodexRolloutPathSync(sessionId) {
2184
+ if (!sessionId) return null;
2185
+ return findRollout(codexSessionsDir(), DATE_DEPTH2, `-${sessionId}.jsonl`);
2186
+ }
2187
+ function findRollout(dir, depth, suffix) {
2188
+ let entries;
2189
+ try {
2190
+ entries = fs9.readdirSync(dir, { withFileTypes: true });
2191
+ } catch {
2192
+ return null;
2193
+ }
2194
+ for (const entry of entries) {
2195
+ const full = path12.join(dir, entry.name);
2196
+ if (entry.isDirectory()) {
2197
+ const found = depth > 0 ? findRollout(full, depth - 1, suffix) : null;
2198
+ if (found) return found;
2199
+ } else if (entry.name.startsWith("rollout-") && entry.name.endsWith(suffix))
2200
+ return full;
2201
+ }
2202
+ return null;
2203
+ }
2204
+
2205
+ // src/commands/sessions/shared/codex/hasCodexRolloutSync.ts
2206
+ function hasCodexRolloutSync(sessionId) {
2207
+ return findCodexRolloutPathSync(sessionId) !== null;
2208
+ }
2209
+
2210
+ // src/commands/sessions/shared/codex/resolveCodexSessionId.ts
2211
+ import * as fs11 from "fs";
2212
+
2213
+ // src/commands/sessions/shared/codex/parseRolloutEntry.ts
2214
+ function parseRolloutEntry(line) {
2215
+ try {
2216
+ const parsed = JSON.parse(line);
2217
+ return parsed && typeof parsed === "object" ? parsed : null;
2218
+ } catch {
2219
+ return null;
2220
+ }
2221
+ }
2222
+ function rolloutPayload(entry) {
2223
+ return entry.payload && typeof entry.payload === "object" ? entry.payload : {};
2224
+ }
2225
+ function rolloutString(value) {
2226
+ return typeof value === "string" ? value : "";
2227
+ }
2228
+
2229
+ // src/commands/sessions/shared/codex/codexRolloutMeta.ts
2230
+ var MAX_FIRST_MESSAGE = 2e3;
2231
+ function codexRolloutMeta(lines) {
2232
+ const meta = {
2233
+ sessionId: "",
2234
+ cwd: "",
2235
+ timestamp: "",
2236
+ firstMessage: ""
2237
+ };
2238
+ for (const line of lines) {
2239
+ const entry = parseRolloutEntry(line);
2240
+ if (!entry) continue;
2241
+ applySessionMeta(meta, entry);
2242
+ meta.firstMessage ||= firstUserMessage(entry);
2243
+ if (meta.sessionId && meta.firstMessage) break;
2244
+ }
2245
+ return meta;
2246
+ }
2247
+ function applySessionMeta(meta, entry) {
2248
+ if (entry.type !== "session_meta") return;
2249
+ const payload = rolloutPayload(entry);
2250
+ meta.sessionId ||= rolloutString(payload.session_id);
2251
+ meta.cwd ||= rolloutString(payload.cwd);
2252
+ meta.timestamp ||= rolloutString(payload.timestamp);
2253
+ }
2254
+ function firstUserMessage(entry) {
2255
+ if (entry.type !== "event_msg") return "";
2256
+ const payload = rolloutPayload(entry);
2257
+ if (payload.type !== "user_message") return "";
2258
+ return rolloutString(payload.message).trim().slice(0, MAX_FIRST_MESSAGE);
2259
+ }
2260
+
2261
+ // src/commands/sessions/shared/codex/readCodexHeadLines.ts
2262
+ import * as fs10 from "fs";
2263
+ import * as readline from "readline";
2264
+ var DEFAULT_MAX_LINES = 80;
2265
+ async function readCodexHeadLines(filePath, maxLines = DEFAULT_MAX_LINES) {
2266
+ const stream = fs10.createReadStream(filePath, { encoding: "utf8" });
2267
+ const reader = readline.createInterface({ input: stream });
2268
+ const lines = [];
2269
+ try {
2270
+ for await (const line of reader) {
2271
+ if (line) lines.push(line);
2272
+ if (lines.length >= maxLines) break;
2273
+ }
2274
+ } catch {
2275
+ return lines;
2276
+ } finally {
2277
+ reader.close();
2278
+ stream.destroy();
2279
+ }
2280
+ return lines;
2281
+ }
2282
+
2283
+ // src/commands/sessions/shared/codex/resolveCodexSessionId.ts
2284
+ var META_LINES = 5;
2285
+ async function resolveCodexSessionId({
2286
+ cwd,
2287
+ launchedAt,
2288
+ sinceMs,
2289
+ claimed
2290
+ }) {
2291
+ if (!cwd) return null;
2292
+ const paths = await discoverCodexRolloutPaths();
2293
+ const touched = await Promise.all(
2294
+ paths.map((file) => touchedSince(file, sinceMs))
2295
+ );
2296
+ const candidates = await Promise.all(
2297
+ paths.filter((_, index) => touched[index]).map((file) => startedIn(file, cwd, sinceMs))
2298
+ );
2299
+ return firstUnclaimedRolloutAfterLaunch(
2300
+ candidates.filter(
2301
+ (candidate) => !!candidate && !claimed.has(candidate.sessionId)
2302
+ ),
2303
+ launchedAt
2304
+ );
2305
+ }
2306
+ function firstUnclaimedRolloutAfterLaunch(rollouts, launchedAt) {
2307
+ const byStart = [...rollouts].sort((a, b) => a.startedAt - b.startedAt);
2308
+ const afterLaunch = byStart.find((r) => r.startedAt >= launchedAt);
2309
+ return (afterLaunch ?? byStart.at(-1))?.sessionId ?? null;
2310
+ }
2311
+ async function startedIn(file, cwd, sinceMs) {
2312
+ const meta = codexRolloutMeta(await readCodexHeadLines(file, META_LINES));
2313
+ if (!meta.sessionId || meta.cwd !== cwd) return null;
2314
+ const startedAt = Date.parse(meta.timestamp);
2315
+ if (!Number.isFinite(startedAt) || startedAt < sinceMs) return null;
2316
+ return { sessionId: meta.sessionId, startedAt };
2317
+ }
2318
+ async function touchedSince(file, sinceMs) {
2319
+ try {
2320
+ return (await fs11.promises.stat(file)).mtimeMs >= sinceMs;
2321
+ } catch {
2322
+ return false;
2323
+ }
2324
+ }
2325
+
2326
+ // src/shared/harnessAdapters/codexConversationReader.ts
2327
+ import { basename as basename4, dirname as dirname4 } from "path";
2328
+
2329
+ // src/commands/sessions/shared/codex/deriveCodexRolloutStatus.ts
2330
+ var TURN_END_EVENTS = /* @__PURE__ */ new Set(["task_complete", "turn_aborted"]);
2331
+ function turnEvent(entry) {
2332
+ if (entry.type !== "event_msg") return null;
2333
+ const kind = rolloutPayload(entry).type;
2334
+ if (kind === "task_started") return "started";
2335
+ return typeof kind === "string" && TURN_END_EVENTS.has(kind) ? "ended" : null;
2336
+ }
2337
+ function hasAgentActivity(entries) {
2338
+ return entries.some((entry) => entry.type === "response_item");
2339
+ }
2340
+ function deriveCodexRolloutStatus(entries) {
2341
+ for (let i = entries.length - 1; i >= 0; i--) {
2342
+ const event = turnEvent(entries[i]);
2343
+ if (event) return event === "started" ? "running" : "waiting";
2344
+ }
2345
+ return hasAgentActivity(entries) ? "running" : null;
2346
+ }
2347
+
2348
+ // src/shared/harnessAdapters/codexCompletedToolEvents.ts
2349
+ function record2(value) {
2350
+ return value && typeof value === "object" ? value : {};
2351
+ }
2352
+ function fileWrites(changes) {
2353
+ return Object.entries(changes).flatMap(([path15, change]) => {
2354
+ const { content, move_path: movePath } = record2(change);
2355
+ const contents = typeof content === "string" ? [content] : [];
2356
+ const write = {
2357
+ kind: "fileWrite",
2358
+ tool: "apply_patch",
2359
+ path: path15,
2360
+ contents
2361
+ };
2362
+ return typeof movePath === "string" ? [write, { ...write, path: movePath }] : [write];
2363
+ });
2364
+ }
2365
+ function codexCompletedToolEvents(item, at) {
2366
+ if (item.type === "FileChange") {
2367
+ const operations2 = fileWrites(record2(item.changes));
2368
+ if (operations2.length === 0) return [];
2369
+ const target = operations2.map((op) => op.kind === "fileWrite" ? op.path : "").join(", ");
2370
+ return [{ kind: "tool", tool: "apply_patch", target, operations: operations2, at }];
2371
+ }
2372
+ if (item.type === "CommandExecution") {
2373
+ const text = rolloutString(item.aggregated_output).trim();
2374
+ return text ? [{ kind: "toolResult", text, at }] : [];
2375
+ }
2376
+ return [];
2377
+ }
2378
+
2379
+ // src/shared/harnessAdapters/codexContentText.ts
2380
+ function codexContentText(content) {
2381
+ if (typeof content === "string") return content;
2382
+ if (!Array.isArray(content)) return "";
2383
+ return content.map(
2384
+ (block) => block && typeof block === "object" ? rolloutString(block.text) : ""
2385
+ ).filter(Boolean).join("\n");
2386
+ }
2387
+
2388
+ // src/shared/harnessAdapters/codexMessageEvents.ts
2389
+ var REPLAYED_CONTEXT = [
2390
+ "<environment_context>",
2391
+ "<user_instructions>",
2392
+ "<INSTRUCTIONS>",
2393
+ "<turn_aborted>",
2394
+ "# AGENTS.md instructions",
2395
+ "# Instructions for this repo (composed by assist)"
2396
+ ];
2397
+ function isReplayedContext(text) {
2398
+ return REPLAYED_CONTEXT.some((marker2) => text.startsWith(marker2));
2399
+ }
2400
+ function message(role, raw, at) {
2401
+ const text = raw.trim();
2402
+ if (!text || role === "user" && isReplayedContext(text)) return [];
2403
+ return [{ kind: "message", role, text, at }];
2404
+ }
2405
+ function completedItem(payload, at) {
2406
+ const item = rolloutPayload({ payload: payload.item });
2407
+ if (item.type === "UserMessage")
2408
+ return message("user", codexContentText(item.content), at);
2409
+ if (item.type === "AgentMessage")
2410
+ return message("assistant", codexContentText(item.content), at);
2411
+ return codexCompletedToolEvents(item, at);
2412
+ }
2413
+ function codexMessageEvents(payload, at) {
2414
+ if (payload.type === "user_message")
2415
+ return message("user", rolloutString(payload.message), at);
2416
+ if (payload.type === "agent_message")
2417
+ return message("assistant", rolloutString(payload.message), at);
2418
+ if (payload.type === "item_completed") return completedItem(payload, at);
2419
+ return [];
2420
+ }
2421
+
2422
+ // src/commands/sessions/shared/codex/codexToolTarget.ts
2423
+ function codexToolTarget(payload) {
2424
+ const args = parseArguments(payload.arguments);
2425
+ const target = args ? commandText(args) || toolTarget(args) || rolloutString(args.input) : rolloutString(payload.input);
2426
+ return condense(target);
2427
+ }
2428
+ function commandText(args) {
2429
+ const command = args.cmd ?? args.command;
2430
+ if (Array.isArray(command)) return command.map(rolloutString).join(" ");
2431
+ return rolloutString(command);
2432
+ }
2433
+ function parseArguments(value) {
2434
+ if (typeof value !== "string") return null;
2435
+ try {
2436
+ const parsed = JSON.parse(value);
2437
+ return parsed && typeof parsed === "object" ? parsed : null;
2438
+ } catch {
2439
+ return null;
2440
+ }
2441
+ }
2442
+ function condense(value) {
2443
+ return value.replace(/\s+/g, " ").trim().slice(0, 120);
2444
+ }
2445
+
2446
+ // src/shared/harnessAdapters/codexAsyncQuestionOperation.ts
2447
+ import { z } from "zod";
2448
+ var inputSchema = z.object({
2449
+ questions: z.array(
2450
+ z.object({
2451
+ title: z.string().min(1),
2452
+ options: z.array(z.string().min(1)).min(2).max(4)
2453
+ })
2454
+ ).min(1).max(4)
2455
+ });
2456
+ function codexAsyncQuestionOperation({
2457
+ toolName,
2458
+ toolInput
2459
+ }) {
2460
+ if (toolName !== "request_user_input_async") return [];
2461
+ const input = inputSchema.safeParse(toolInput);
2462
+ if (!input.success) return [];
2463
+ return [
2464
+ {
2465
+ kind: "question",
2466
+ tool: toolName,
2467
+ questionsJson: JSON.stringify({
2468
+ questions: input.data.questions.map(({ title, options }) => ({
2469
+ question: title,
2470
+ header: "Question",
2471
+ multiSelect: false,
2472
+ options: options.map((label) => ({ label, description: "" }))
2473
+ }))
2474
+ })
2475
+ }
2476
+ ];
2477
+ }
2478
+
2479
+ // src/shared/harnessAdapters/parseApplyPatch.ts
2480
+ var FILE_HEADER = /^\*\*\* (?:Add|Update|Delete) File: (.+)$/;
2481
+ var MOVE_TO = /^\*\*\* Move to: (.+)$/;
2482
+ function parseApplyPatch(patch) {
2483
+ const files = [];
2484
+ let added;
2485
+ for (const line of patch.split(/\r?\n/)) {
2486
+ const header = FILE_HEADER.exec(line);
2487
+ if (header) {
2488
+ added = [];
2489
+ files.push({ path: header[1].trim(), added });
2490
+ continue;
2491
+ }
2492
+ const move = MOVE_TO.exec(line);
2493
+ if (move && added) {
2494
+ files.push({ path: move[1].trim(), added });
2495
+ continue;
2496
+ }
2497
+ if (added && line.startsWith("+")) added.push(line.slice(1));
2498
+ }
2499
+ return files.map(({ path: path15, added: lines }) => ({
2500
+ path: path15,
2501
+ contents: lines.length ? [lines.join("\n")] : []
2502
+ }));
2503
+ }
2504
+
2505
+ // src/shared/harnessAdapters/patchWrites.ts
2506
+ function patchWrites(tool, patch) {
2507
+ return parseApplyPatch(patch).map(({ path: path15, contents }) => ({
2508
+ kind: "fileWrite",
2509
+ tool,
2510
+ path: path15,
2511
+ contents
2512
+ }));
2513
+ }
2514
+
2515
+ // src/shared/harnessAdapters/patchText.ts
2516
+ var PATCH_MARKER = "*** Begin Patch";
2517
+ function patchText(input) {
2518
+ const candidates = [
2519
+ input.command,
2520
+ input.input,
2521
+ input.patch,
2522
+ ...Array.isArray(input.command) ? input.command : []
2523
+ ];
2524
+ return candidates.find(
2525
+ (value) => typeof value === "string" && value.includes(PATCH_MARKER)
2526
+ );
2527
+ }
2528
+
2529
+ // src/shared/harnessAdapters/codexToolOperations.ts
2530
+ var COMMAND_TOOLS2 = /* @__PURE__ */ new Set(["Bash", "PowerShell"]);
2531
+ var PATCH_TOOLS = /* @__PURE__ */ new Set(["apply_patch", "Edit", "Write"]);
2532
+ var PATCH_MARKER2 = "*** Begin Patch";
2533
+ function codexToolOperations({
2534
+ toolName,
2535
+ toolInput
2536
+ }) {
2537
+ if (toolName === "request_user_input" && Array.isArray(toolInput.questions))
2538
+ return [
2539
+ {
2540
+ kind: "question",
2541
+ tool: toolName,
2542
+ questionsJson: JSON.stringify({
2543
+ questions: toolInput.questions.map(
2544
+ ({ question, header, options }) => ({
2545
+ question,
2546
+ header,
2547
+ options,
2548
+ multiSelect: false
2549
+ })
2550
+ )
2551
+ })
2552
+ }
2553
+ ];
2554
+ if (COMMAND_TOOLS2.has(toolName)) {
2555
+ const { command } = toolInput;
2556
+ if (typeof command !== "string" || !command.trim()) return [];
2557
+ const operations2 = [
2558
+ { kind: "command", tool: toolName, command: command.trim() }
2559
+ ];
2560
+ return command.includes(PATCH_MARKER2) ? [...operations2, ...patchWrites(toolName, command)] : operations2;
2561
+ }
2562
+ if (!PATCH_TOOLS.has(toolName))
2563
+ return codexAsyncQuestionOperation({ toolName, toolInput });
2564
+ const patch = patchText(toolInput);
2565
+ if (patch) return patchWrites(toolName, patch);
2566
+ const { file_path: path15, content } = toolInput;
2567
+ if (typeof path15 !== "string") return [];
2568
+ const contents = typeof content === "string" ? [content] : [];
2569
+ return [{ kind: "fileWrite", tool: toolName, path: path15, contents }];
2570
+ }
2571
+
2572
+ // src/shared/harnessAdapters/codexToolEvents.ts
2573
+ var TOOL_CALLS = /* @__PURE__ */ new Set([
2574
+ "function_call",
2575
+ "custom_tool_call",
2576
+ "local_shell_call"
2577
+ ]);
2578
+ var TOOL_OUTPUTS = /* @__PURE__ */ new Set([
2579
+ "function_call_output",
2580
+ "custom_tool_call_output"
2581
+ ]);
2582
+ function operations(payload, target) {
2583
+ const name = rolloutString(payload.name);
2584
+ const input = rolloutString(payload.input);
2585
+ if (payload.type === "custom_tool_call")
2586
+ return codexToolOperations({
2587
+ toolName: input.includes("*** Begin Patch") ? "apply_patch" : name,
2588
+ toolInput: { input }
2589
+ });
2590
+ return target ? codexToolOperations({ toolName: "Bash", toolInput: { command: target } }) : [];
2591
+ }
2592
+ function codexToolEvents(payload, at) {
2593
+ const type = rolloutString(payload.type);
2594
+ if (TOOL_CALLS.has(type)) {
2595
+ const target = codexToolTarget(payload);
2596
+ return [
2597
+ {
2598
+ kind: "tool",
2599
+ tool: rolloutString(payload.name) || "tool",
2600
+ target,
2601
+ operations: operations(payload, target),
2602
+ at
2603
+ }
2604
+ ];
2605
+ }
2606
+ if (TOOL_OUTPUTS.has(type)) {
2607
+ const text = codexContentText(payload.output).trim();
2608
+ return text ? [{ kind: "toolResult", text, at }] : [];
2609
+ }
2610
+ return [];
2611
+ }
2612
+
2613
+ // src/shared/harnessAdapters/codexEntryShape.ts
2614
+ var PAYLOAD_TYPES = /* @__PURE__ */ new Map([
2615
+ [
2616
+ "event_msg",
2617
+ /* @__PURE__ */ new Set([
2618
+ "user_message",
2619
+ "agent_message",
2620
+ "agent_reasoning",
2621
+ "item_started",
2622
+ "token_count",
2623
+ "task_started",
2624
+ "task_complete",
2625
+ "turn_aborted",
2626
+ "thread_settings_applied"
2627
+ ])
2628
+ ],
2629
+ [
2630
+ "response_item",
2631
+ /* @__PURE__ */ new Set([
2632
+ "message",
2633
+ "reasoning",
2634
+ "additional_tools",
2635
+ "function_call",
2636
+ "function_call_output",
2637
+ "custom_tool_call",
2638
+ "custom_tool_call_output",
2639
+ "local_shell_call"
2640
+ ])
2641
+ ]
2642
+ ]);
2643
+ var IGNORED_ENTRY_TYPES2 = /* @__PURE__ */ new Set([
2644
+ "session_meta",
2645
+ "turn_context",
2646
+ "token_usage_record",
2647
+ "world_state",
2648
+ "compacted"
2649
+ ]);
2650
+ var COMPLETED_ITEM_TYPES = /* @__PURE__ */ new Set([
2651
+ "UserMessage",
2652
+ "AgentMessage",
2653
+ "Reasoning",
2654
+ "CommandExecution",
2655
+ "FileChange"
2656
+ ]);
2657
+ function codexEntryShape(entry) {
2658
+ const type = String(entry.type);
2659
+ const known = PAYLOAD_TYPES.get(type);
2660
+ if (!known) return IGNORED_ENTRY_TYPES2.has(type) ? void 0 : type;
2661
+ const payload = rolloutPayload(entry);
2662
+ const payloadType = rolloutString(payload.type);
2663
+ if (type === "event_msg" && payloadType === "item_completed") {
2664
+ const itemType = rolloutString(
2665
+ rolloutPayload({ payload: payload.item }).type
2666
+ );
2667
+ return COMPLETED_ITEM_TYPES.has(itemType) ? void 0 : `${type}:item_completed:${itemType}`;
2668
+ }
2669
+ return known.has(payloadType) ? void 0 : `${type}:${payloadType}`;
2670
+ }
2671
+
2672
+ // src/shared/harnessAdapters/codexUnrecognisedShapes.ts
2673
+ function codexUnrecognisedShapes(entries) {
2674
+ return [
2675
+ ...new Set(
2676
+ entries.map(codexEntryShape).filter((shape) => shape !== void 0)
2677
+ )
2678
+ ];
2679
+ }
2680
+
2681
+ // src/shared/harnessAdapters/codexConversationReader.ts
2682
+ function entryEvents(entry) {
2683
+ const payload = rolloutPayload(entry);
2684
+ const at = typeof entry.timestamp === "string" ? entry.timestamp : void 0;
2685
+ if (entry.type === "event_msg") return codexMessageEvents(payload, at);
2686
+ if (entry.type === "response_item") return codexToolEvents(payload, at);
2687
+ return [];
2688
+ }
2689
+ function fingerprint2(entries) {
2690
+ for (let i = entries.length - 1; i >= 0; i--) {
2691
+ const entry = entries[i];
2692
+ if (entry.type !== "event_msg" && entry.type !== "response_item") continue;
2693
+ const payload = rolloutPayload(entry);
2694
+ return [
2695
+ rolloutString(entry.timestamp),
2696
+ rolloutString(payload.type),
2697
+ rolloutString(payload.id) || rolloutString(payload.call_id)
2698
+ ].join("|");
2699
+ }
2700
+ return null;
2701
+ }
2702
+ var codexConversationReader = {
2703
+ headBytes: 2 * 1024 * 1024,
2704
+ locate: ({ harnessSessionId }) => harnessSessionId ? findCodexRolloutPathSync(harnessSessionId) : null,
2705
+ watchTarget: (ref) => {
2706
+ const path15 = codexConversationReader.locate(ref);
2707
+ return path15 ? { dir: dirname4(path15), file: basename4(path15) } : null;
2708
+ },
2709
+ events: (entries) => entries.flatMap(entryEvents),
2710
+ lifecycle: (entries) => ({
2711
+ status: deriveCodexRolloutStatus(entries),
2712
+ asking: false
2713
+ }),
2714
+ fingerprint: fingerprint2,
2715
+ unrecognised: codexUnrecognisedShapes
2716
+ };
2717
+
2718
+ // src/shared/harnessAdapters/codexHookProbe.ts
2719
+ import * as fs13 from "fs";
2720
+ import * as path13 from "path";
2721
+
2722
+ // src/shared/harnessAdapters/codexTrustedHookKeys.ts
2723
+ import * as fs12 from "fs";
2724
+ var TABLE_HEADER = /^\s*\[/;
2725
+ var STATE_HEADER = /^\s*\[\s*hooks\.state\."((?:[^"\\]|\\.)*)"\s*\]\s*(#.*)?$/;
2726
+ var TRUSTED_HASH = /^\s*trusted_hash\s*=\s*"[^"]+"/;
2727
+ var DISABLED = /^\s*enabled\s*=\s*false\b/;
2728
+ function codexTrustedHookKeys(config, configPath) {
2729
+ const trusted = /* @__PURE__ */ new Set();
2730
+ let current;
2731
+ const close = () => {
2732
+ if (current?.hash && !current.disabled) trusted.add(current.key);
2733
+ current = void 0;
2734
+ };
2735
+ for (const line of config.split("\n")) {
2736
+ if (TABLE_HEADER.test(line)) {
2737
+ close();
2738
+ const quoted = STATE_HEADER.exec(line)?.[1];
2739
+ if (!quoted) continue;
2740
+ const key = JSON.parse(`"${quoted}"`);
2741
+ const split = key.lastIndexOf(".toml:");
2742
+ if (split === -1) continue;
2743
+ const source = key.slice(0, split + ".toml".length);
2744
+ if (!samePath(source, configPath)) continue;
2745
+ current = {
2746
+ key: key.slice(split + ".toml:".length),
2747
+ hash: false,
2748
+ disabled: false
2749
+ };
2750
+ continue;
2751
+ }
2752
+ if (!current) continue;
2753
+ if (TRUSTED_HASH.test(line)) current.hash = true;
2754
+ if (DISABLED.test(line)) current.disabled = true;
2755
+ }
2756
+ close();
2757
+ return trusted;
2758
+ }
2759
+ function samePath(a, b) {
2760
+ if (a === b) return true;
2761
+ try {
2762
+ return fs12.realpathSync(a) === fs12.realpathSync(b);
2763
+ } catch {
2764
+ return false;
2765
+ }
2766
+ }
2767
+
2768
+ // src/shared/harnessAdapters/codexHookProbe.ts
2769
+ var HOOK_COMMAND = "assist codex-hook";
2770
+ var INTERCEPT_EVENT = "pre_tool_use:";
2771
+ var notInstalled = unsupported(
2772
+ "assist's codex-hook is not installed in ~/.codex/config.toml, so Codex tool calls and file patches would bypass the allowlist, restricted paths and docs/schema locks",
2773
+ "run `assist sync` to install and trust the hook, or pick another harness"
2774
+ );
2775
+ var notTrusted = unsupported(
2776
+ "assist's codex-hook is installed but not trusted (or disabled) in Codex, so Codex skips it and tool calls and file patches would bypass the allowlist, restricted paths and docs/schema locks",
2777
+ "run `assist sync` to trust the hook (or trust the `assist codex-hook` entries from Codex's hook review), or pick another harness"
2778
+ );
2779
+ var cached;
2780
+ function interceptKeys(config) {
2781
+ const begin = config.indexOf(MANAGED_BLOCK_BEGIN);
2782
+ if (begin === -1) return [];
2783
+ const end = config.indexOf(MANAGED_BLOCK_END, begin);
2784
+ const block = config.slice(
2785
+ begin + MANAGED_BLOCK_BEGIN.length,
2786
+ end === -1 ? config.length : end
2787
+ );
2788
+ return [...assistCodexHookKeys(config.slice(0, begin), block)].filter(
2789
+ ([key, command]) => key.startsWith(INTERCEPT_EVENT) && command === HOOK_COMMAND
2790
+ ).map(([key]) => key);
2791
+ }
2792
+ function probe(config, configPath) {
2793
+ const keys = interceptKeys(config);
2794
+ if (!keys.length) return notInstalled;
2795
+ const trusted = codexTrustedHookKeys(config, configPath);
2796
+ return keys.every((key) => trusted.has(key)) ? supported : notTrusted;
2797
+ }
2798
+ function codexHookProbe() {
2799
+ const configPath = path13.join(harnesses.codex.homeDir, "config.toml");
2800
+ let stat;
2801
+ try {
2802
+ stat = fs13.statSync(configPath);
2803
+ } catch {
2804
+ return notInstalled;
2805
+ }
2806
+ const fingerprint3 = `${configPath}:${stat.mtimeMs}:${stat.size}`;
2807
+ if (cached?.fingerprint === fingerprint3) return cached.status;
2808
+ const status = probe(fs13.readFileSync(configPath, "utf8"), configPath);
2809
+ cached = { fingerprint: fingerprint3, status };
2810
+ return status;
2811
+ }
2812
+
2813
+ // src/shared/readCodexRulePerms.ts
2814
+ import { existsSync as existsSync7, readdirSync as readdirSync3, readFileSync as readFileSync7 } from "fs";
2815
+ import { join as join13 } from "path";
2816
+
2817
+ // src/shared/readPatternList.ts
2818
+ function readString(text, start) {
2819
+ const quote = text[start];
2820
+ let value = "";
2821
+ let i = start + 1;
2822
+ while (i < text.length && text[i] !== quote) {
2823
+ if (text[i] === "\\") i++;
2824
+ value += text[i];
2825
+ i++;
2826
+ }
2827
+ return [value, i + 1];
2828
+ }
2829
+ function readPatternList(text, start) {
2830
+ const items = [];
2831
+ let i = start + 1;
2832
+ while (i < text.length && text[i] !== "]") {
2833
+ const ch = text[i];
2834
+ if (ch === '"' || ch === "'") {
2835
+ const [value, next] = readString(text, i);
2836
+ items.push(value);
2837
+ i = next;
2838
+ } else if (ch === "[") {
2839
+ const [list, next] = readPatternList(text, i);
2840
+ items.push(list);
2841
+ i = next;
2842
+ } else i++;
2843
+ }
2844
+ return [items, i + 1];
2845
+ }
2846
+
2847
+ // src/shared/parseCodexRules.ts
2848
+ var PREFIX_RULE_RE = /prefix_rule\s*\(/g;
2849
+ var DECISION_RE = /decision\s*=\s*["'](\w+)["']/;
2850
+ var PATTERN_RE = /pattern\s*=\s*\[/;
2851
+ function expandPattern(tokens) {
2852
+ return tokens.reduce(
2853
+ (prefixes, token) => {
2854
+ const alternatives = Array.isArray(token) ? token.filter((t) => typeof t === "string") : [token];
2855
+ return prefixes.flatMap(
2856
+ (prefix) => alternatives.map((alt) => prefix ? `${prefix} ${alt}` : alt)
2857
+ );
2858
+ },
2859
+ [""]
2860
+ );
2861
+ }
2862
+ function ruleBody(text, start) {
2863
+ let depth = 1;
2864
+ let i = start;
2865
+ while (i < text.length && depth > 0) {
2866
+ if (text[i] === "(") depth++;
2867
+ if (text[i] === ")") depth--;
2868
+ i++;
2869
+ }
2870
+ return text.slice(start, i);
2871
+ }
2872
+ function parseCodexRules(text) {
2873
+ const perms = { allow: [], deny: [] };
2874
+ for (const match of text.matchAll(PREFIX_RULE_RE)) {
2875
+ const body = ruleBody(text, match.index + match[0].length);
2876
+ const patternMatch = PATTERN_RE.exec(body);
2877
+ if (!patternMatch) continue;
2878
+ const [tokens] = readPatternList(
2879
+ body,
2880
+ patternMatch.index + patternMatch[0].length - 1
2881
+ );
2882
+ const decision = DECISION_RE.exec(body)?.[1] ?? "allow";
2883
+ const target = decision === "allow" ? perms.allow : decision === "forbidden" ? perms.deny : void 0;
2884
+ if (!target) continue;
2885
+ for (const command of expandPattern(tokens))
2886
+ if (command) target.push(`Bash(${command}:*)`);
2887
+ }
2888
+ return perms;
2889
+ }
2890
+
2891
+ // src/shared/readCodexRulePerms.ts
2892
+ function ruleFiles(dir) {
2893
+ if (!existsSync7(dir)) return [];
2894
+ try {
2895
+ return readdirSync3(dir).filter((name) => name.endsWith(".rules")).sort().map((name) => join13(dir, name));
2896
+ } catch {
2897
+ return [];
2898
+ }
2899
+ }
2900
+ function readCodexRulePerms(key) {
2901
+ const dirs = [
2902
+ join13(harnesses.codex.homeDir, "rules"),
2903
+ join13(process.cwd(), ".codex", "rules")
2904
+ ];
2905
+ return dirs.flatMap(ruleFiles).flatMap((file) => {
2906
+ try {
2907
+ return parseCodexRules(readFileSync7(file, "utf8"))[key];
2908
+ } catch {
2909
+ return [];
2910
+ }
2911
+ });
2912
+ }
2913
+
2914
+ // src/shared/neutralizeCodexSkillMentions.ts
2915
+ var WORD_JOINER = "\u2060";
2916
+ function neutralizeCodexSkillMentions(prompt) {
2917
+ return prompt.replace(/\$(?=[a-z])/g, `$${WORD_JOINER}`);
2918
+ }
2919
+
2920
+ // src/shared/spawnCodex.ts
2921
+ function spawnCodex2(prompt, options = {}) {
2922
+ const cwd = options.cwd ?? process.cwd();
2923
+ trustCodexProject(cwd);
2924
+ const untrusted = prepareCodexHookTrust();
2925
+ if (untrusted) console.error(untrusted);
2926
+ const text = [
2927
+ options.skill && `$${options.skill}`,
2928
+ prompt && neutralizeCodexSkillMentions(prompt)
2929
+ ].filter(Boolean).join(" ");
2930
+ const override = options.model && !options.resumeSessionId ? { args: ["-m", options.model], env: {} } : buildHarnessCodexArgs();
2931
+ return spawnInherit(
2932
+ harnesses.codex.command,
2933
+ [
2934
+ ...codexIsolatedHookArgs,
2935
+ ...override.args,
2936
+ ...codexSessionEnvArgs(process.env),
2937
+ ...codexSandboxArgs(),
2938
+ "-C",
2939
+ cwd,
2940
+ "--sandbox",
2941
+ options.sandbox ?? "workspace-write",
2942
+ ...options.resumeSessionId ? ["resume", options.resumeSessionId] : [],
2943
+ ...text ? [text] : []
2944
+ ],
2945
+ { env: override.env }
2946
+ );
2947
+ }
2948
+
2949
+ // src/shared/harnessAdapters/codexOneShot.ts
2950
+ import { execFile as execFile2 } from "child_process";
2951
+ import { tmpdir } from "os";
2952
+ import { promisify as promisify2 } from "util";
2953
+
2954
+ // src/shared/envDetachedFromTrackedSession.ts
2955
+ function envDetachedFromTrackedSession(extra = {}) {
2956
+ const {
2957
+ ASSIST_SESSION: _session,
2958
+ ASSIST_SESSION_ID: _sessionId,
2959
+ ASSIST_ACTIVITY_ID: _activityId,
2960
+ ...env
2961
+ } = process.env;
2962
+ return { ...env, ...extra };
2963
+ }
2964
+
2965
+ // src/shared/harnessAdapters/codexOneShot.ts
2966
+ var execFileAsync2 = promisify2(execFile2);
2967
+ async function codexOneShot(prompt, { timeout, effort = "low", cwd }) {
2968
+ const override = buildHarnessCodexArgs();
2969
+ const run = execFileAsync2(
2970
+ harnesses.codex.command,
2971
+ [
2972
+ ...codexIsolatedHookArgs,
2973
+ "exec",
2974
+ ...override.args,
2975
+ "--ephemeral",
2976
+ "--skip-git-repo-check",
2977
+ "--sandbox",
2978
+ "read-only",
2979
+ "-c",
2980
+ `model_reasoning_effort="${effort}"`,
2981
+ prompt
2982
+ ],
2983
+ {
2984
+ encoding: "utf8",
2985
+ windowsHide: true,
2986
+ timeout,
2987
+ cwd: cwd ?? tmpdir(),
2988
+ env: envDetachedFromTrackedSession(override.env)
2989
+ }
2990
+ );
2991
+ run.child?.stdin?.end();
2992
+ return (await run).stdout;
2993
+ }
2994
+
2995
+ // src/shared/harnessAdapters/codexRelocate.ts
2996
+ function codexRelocate(conversationId, fromCwd, toCwd) {
2997
+ daemonLog(
2998
+ `Codex conversation ${conversationId} resumes in ${toCwd} from its rollout, which is stored by id rather than under ${fromCwd}`
2999
+ );
3000
+ }
3001
+
3002
+ // src/commands/review/runCodexReviewer.ts
3003
+ import { existsSync as existsSync8, unlinkSync } from "fs";
3004
+
3005
+ // src/commands/review/parseCodexUsage.ts
3006
+ function parseCodexUsage(usage) {
3007
+ return parseTokenUsage(usage, { cacheRead: "cached_input_tokens" });
3008
+ }
3009
+
3010
+ // src/commands/review/parseCodexEvent.ts
3011
+ function isItemStarted(value) {
3012
+ return typeof value === "object" && value !== null && value.type === "item.started";
3013
+ }
3014
+ function isTurnCompleted(value) {
3015
+ return typeof value === "object" && value !== null && value.type === "turn.completed";
3016
+ }
3017
+ function parseCodexEvent(line) {
3018
+ let event;
3019
+ try {
3020
+ event = JSON.parse(line);
3021
+ } catch {
3022
+ return { kind: "ignore" };
3023
+ }
3024
+ if (isTurnCompleted(event)) {
3025
+ const usage = parseCodexUsage(event.usage);
3026
+ return usage ? { kind: "usage", usage } : { kind: "ignore" };
3027
+ }
3028
+ if (!isItemStarted(event)) return { kind: "ignore" };
3029
+ const item = event.item;
3030
+ if (!item) return { kind: "ignore" };
3031
+ if (item.type === "command_execution" && typeof item.command === "string") {
3032
+ return {
3033
+ kind: "tool_use",
3034
+ tool: "shell",
3035
+ summary: simplifyShellCommand(item.command)
3036
+ };
3037
+ }
3038
+ return { kind: "ignore" };
3039
+ }
3040
+
3041
+ // src/commands/review/createCodexLineHandler.ts
3042
+ function addUsage(total, turn) {
3043
+ if (!total) return turn;
3044
+ return {
3045
+ input: total.input + turn.input,
3046
+ output: total.output + turn.output,
3047
+ cacheRead: total.cacheRead + turn.cacheRead
3048
+ };
3049
+ }
3050
+ function createCodexLineHandler(name, spinner, model) {
3051
+ const state = {};
3052
+ const onLine = (line) => {
3053
+ const event = parseCodexEvent(line);
3054
+ if (event.kind === "tool_use")
3055
+ reportReviewerToolUse(name, event, spinner, model);
3056
+ else if (event.kind === "usage")
3057
+ state.usage = addUsage(state.usage, event.usage);
3058
+ };
3059
+ return { state, onLine };
3060
+ }
3061
+
3062
+ // src/commands/review/runCodexReviewer.ts
3063
+ function codexArgs2(outputPath, modelArgs) {
3064
+ return [
3065
+ "exec",
3066
+ ...modelArgs,
3067
+ "--sandbox",
3068
+ "read-only",
3069
+ "--json",
3070
+ "--output-last-message",
3071
+ outputPath
3072
+ ];
3073
+ }
3074
+ async function runCodexReviewer(spec) {
3075
+ const { spinner, override } = spec;
3076
+ const command = "codex";
3077
+ const { state, onLine } = createCodexLineHandler(
3078
+ spec.name,
3079
+ spinner,
3080
+ override.model
3081
+ );
3082
+ const result = await runStreamingChild({
3083
+ name: spec.name,
3084
+ command,
3085
+ model: override.model,
3086
+ args: codexArgs2(spec.outputPath, override.args),
3087
+ stdin: spec.stdin,
3088
+ quiet: Boolean(spinner),
3089
+ ...override.args.length > 0 ? { env: override.env } : {},
3090
+ onLine
3091
+ });
3092
+ if (result.exitCode !== 0 && existsSync8(spec.outputPath)) {
3093
+ unlinkSync(spec.outputPath);
3094
+ }
3095
+ const finalised = finaliseReviewerRun(
3096
+ {
3097
+ name: spec.name,
3098
+ command,
3099
+ model: override.model,
3100
+ outputPath: spec.outputPath
3101
+ },
3102
+ spinner,
3103
+ result
3104
+ );
3105
+ return state.usage ? { ...finalised, usage: state.usage } : finalised;
3106
+ }
3107
+
3108
+ // src/shared/harnessAdapters/codexStructuredRun.ts
3109
+ function codexStructuredRun({
3110
+ name,
3111
+ stdin,
3112
+ outputPath,
3113
+ model,
3114
+ spinner
3115
+ }) {
3116
+ const override = buildLitellmCodexArgs(model);
3117
+ return runCodexReviewer({
3118
+ name,
3119
+ stdin,
3120
+ outputPath,
3121
+ override,
3122
+ spinner: spinner?.(override.model)
3123
+ });
3124
+ }
3125
+
3126
+ // src/shared/harnessAdapters/offerCodexInstall.ts
3127
+ import { spawnSync as spawnSync2 } from "child_process";
3128
+ function runNpmInstall() {
3129
+ const result = spawnSync2("npm", ["install", "-g", "@openai/codex"], {
3130
+ stdio: "inherit",
3131
+ shell: true
3132
+ });
3133
+ return result.status === 0 && result.error === void 0;
3134
+ }
3135
+ async function offerCodexInstall() {
3136
+ const { command } = harnesses.codex;
3137
+ console.log(`${command} CLI was not found on PATH.`);
3138
+ const install = await promptConfirm(
3139
+ "Install @openai/codex globally via npm install -g @openai/codex?",
3140
+ true
3141
+ );
3142
+ if (!install) return false;
3143
+ console.log("Installing @openai/codex...");
3144
+ if (!runNpmInstall()) {
3145
+ console.error("npm install -g @openai/codex failed.");
3146
+ return false;
3147
+ }
3148
+ if (checkCliAvailable(command)) return true;
3149
+ console.error(`${command} still not found on PATH after install.`);
3150
+ return false;
3151
+ }
3152
+
3153
+ // src/shared/harnessAdapters/rejectConnectorRun.ts
3154
+ function rejectConnectorRun(harness) {
3155
+ return () => Promise.reject(
3156
+ new Error(`${harness} cannot run connector tools headlessly yet`)
3157
+ );
3158
+ }
3159
+
3160
+ // src/shared/harnessAdapters/codexAdapter.ts
3161
+ var sandbox = (allowEdits) => allowEdits === false ? "read-only" : "workspace-write";
3162
+ var codexAdapter = {
3163
+ kind: "codex",
3164
+ label: harnessLabel("codex"),
3165
+ capabilities: {
3166
+ ...harnessCapabilityDeclarations.codex,
3167
+ "intercept.command": codexHookProbe,
3168
+ "intercept.fileRead": codexHookProbe,
3169
+ "intercept.fileWrite": codexHookProbe
3170
+ },
3171
+ detect: () => detectHarness("codex"),
3172
+ conversation: {
3173
+ idName: "Codex conversation id",
3174
+ findResumable: ({ harnessSessionId }) => harnessSessionId && hasCodexRolloutSync(harnessSessionId) ? harnessSessionId : void 0,
3175
+ locate: findCodexRolloutPath,
3176
+ current: () => process.env.CODEX_THREAD_ID || void 0,
3177
+ boundId: ({ harnessSessionId }) => harnessSessionId,
3178
+ toRef: (harnessSessionId, cwd) => ({ cwd, harnessSessionId }),
3179
+ discover: resolveCodexSessionId,
3180
+ relocate: codexRelocate,
3181
+ reader: codexConversationReader
3182
+ },
3183
+ toolOperations: codexToolOperations,
3184
+ permissionRules: readCodexRulePerms,
3185
+ launchSkill: (skill, args, { cwd, allowEdits, model }) => spawnCodex2(args ?? "", {
3186
+ cwd,
3187
+ sandbox: sandbox(allowEdits),
3188
+ skill,
3189
+ model
3190
+ }),
3191
+ launchPrompt: (prompt, { cwd, allowEdits, model }) => spawnCodex2(prompt, { cwd, sandbox: sandbox(allowEdits), model }),
3192
+ resume: (conversationId, nudge, { cwd, allowEdits }) => spawnCodex2(nudge, {
3193
+ cwd,
3194
+ sandbox: sandbox(allowEdits),
3195
+ resumeSessionId: conversationId
3196
+ }),
3197
+ interactive: ({
3198
+ sessionId,
3199
+ resumeId,
3200
+ prompt,
3201
+ cwd,
3202
+ appendSystemPromptFile,
3203
+ model
3204
+ }) => spawnCodex({
3205
+ prompt,
3206
+ cwd,
3207
+ sessionId,
3208
+ resumeSessionId: resumeId,
3209
+ appendSystemPromptFile,
3210
+ model
3211
+ }),
3212
+ oneShot: codexOneShot,
3213
+ structured: codexStructuredRun,
3214
+ connectorRun: rejectConnectorRun("Codex"),
3215
+ offerInstall: offerCodexInstall,
3216
+ activityIdentity: (_conversationId, resumedId) => resumedId ? { harness: "codex", harnessSessionId: resumedId } : { harness: "codex" }
3217
+ };
3218
+
3219
+ // src/shared/piTerminalArgs.ts
3220
+ var piTerminalArgs = ["--tui-mode", "regular"];
3221
+
3222
+ // src/commands/sessions/daemon/spawnPi.ts
3223
+ function spawnPi(opts2 = {}) {
3224
+ const args = ["pi", ...piTerminalArgs];
3225
+ if (opts2.model) args.push("--model", opts2.model);
3226
+ if (opts2.prompt) args.push(opts2.prompt);
3227
+ return spawnPty(args, opts2.cwd, opts2.sessionId, { ASSIST_HARNESS: "pi" });
3228
+ }
3229
+
3230
+ // src/shared/spawnPi.ts
3231
+ function spawnPi2(prompt, options = {}) {
3232
+ const cwd = options.cwd ?? process.cwd();
3233
+ const model = options.model ? ["--model", options.model] : [];
3234
+ return spawnInherit(
3235
+ harnesses.pi.command,
3236
+ [...piTerminalArgs, ...model, prompt],
3237
+ {
3238
+ cwd,
3239
+ env: { ASSIST_HARNESS: "pi" }
3240
+ }
3241
+ );
3242
+ }
3243
+
3244
+ // src/shared/harnessAdapters/piExtensionProbe.ts
3245
+ import * as fs14 from "fs";
3246
+ import * as path14 from "path";
3247
+ function piExtensionProbe() {
3248
+ const extension = path14.join(piExtensionsDir(), "assist-permission-gate.ts");
3249
+ return fs14.existsSync(extension) ? supported : unsupported(
3250
+ `assist's pi extension is not installed (${extension} is missing), so pi tool calls would bypass the allowlist, restricted paths and docs/schema locks`,
3251
+ "run `assist sync` to install the extension, or pick another harness"
3252
+ );
3253
+ }
3254
+
3255
+ // src/shared/harnessAdapters/piToolOperations.ts
3256
+ var COMMAND_TOOLS3 = {
3257
+ bash: "Bash",
3258
+ powershell: "PowerShell"
3259
+ };
3260
+ var READ_TOOLS2 = /* @__PURE__ */ new Set(["read", "grep", "find", "ls"]);
3261
+ var WRITE_TOOLS2 = /* @__PURE__ */ new Set(["write", "edit"]);
3262
+ function stringField(input, ...fields) {
3263
+ return fields.map((field) => input[field]).find((value) => typeof value === "string");
3264
+ }
3265
+ function incomingContents2(input) {
3266
+ return [
3267
+ stringField(input, "content"),
3268
+ stringField(input, "newText", "new_string"),
3269
+ ...editTexts(input, "newText", "new_string")
3270
+ ].filter((value) => value !== void 0);
3271
+ }
3272
+ function piToolOperations({
3273
+ toolName,
3274
+ toolInput
3275
+ }) {
3276
+ const name = toolName.toLowerCase();
3277
+ const commandTool = COMMAND_TOOLS3[name];
3278
+ if (commandTool) {
3279
+ const command = stringField(toolInput, "command")?.trim();
3280
+ return command ? [{ kind: "command", tool: commandTool, command }] : [];
3281
+ }
3282
+ const path15 = stringField(toolInput, "path", "file_path", "pattern");
3283
+ if (READ_TOOLS2.has(name))
3284
+ return path15 ? [{ kind: "fileRead", tool: toolName, paths: [path15] }] : [];
3285
+ if (WRITE_TOOLS2.has(name) && path15)
3286
+ return [
3287
+ {
3288
+ kind: "fileWrite",
3289
+ tool: toolName,
3290
+ path: path15,
3291
+ contents: incomingContents2(toolInput)
3292
+ }
3293
+ ];
3294
+ return [];
3295
+ }
3296
+
3297
+ // src/shared/harnessAdapters/piAdapter.ts
3298
+ function cannotResume() {
3299
+ throw new Error("pi sessions cannot be resumed yet");
3300
+ }
3301
+ function noOneShot() {
3302
+ throw new Error("assist has no headless pi one-shot yet");
3303
+ }
3304
+ var piAdapter = {
3305
+ kind: "pi",
3306
+ label: harnessLabel("pi"),
3307
+ capabilities: {
3308
+ ...harnessCapabilityDeclarations.pi,
3309
+ "intercept.command": piExtensionProbe,
3310
+ "intercept.fileRead": piExtensionProbe,
3311
+ "intercept.fileWrite": piExtensionProbe
3312
+ },
3313
+ detect: () => detectHarness("pi"),
3314
+ conversation: {
3315
+ idName: "pi conversation id",
3316
+ findResumable: () => void 0,
3317
+ locate: () => Promise.resolve(null),
3318
+ current: () => void 0,
3319
+ boundId: () => void 0,
3320
+ toRef: (harnessSessionId, cwd) => ({ cwd, harnessSessionId }),
3321
+ relocate: cannotResume
3322
+ },
3323
+ toolOperations: piToolOperations,
3324
+ launchSkill: (skill, args, { cwd, model }) => spawnPi2(buildSlashCommand(skill, args), { cwd, model }),
3325
+ launchPrompt: (prompt, { cwd, model }) => spawnPi2(prompt, { cwd, model }),
3326
+ resume: cannotResume,
3327
+ interactive: ({ sessionId, resumeId, prompt, cwd, model }) => resumeId ? cannotResume() : spawnPi({ prompt, cwd, sessionId, model }),
3328
+ oneShot: noOneShot,
3329
+ structured: noOneShot,
3330
+ connectorRun: rejectConnectorRun("pi"),
3331
+ activityIdentity: () => ({ harness: "pi" })
3332
+ };
3333
+
3334
+ // src/commands/sessions/daemon/sdk/createSdkInput.ts
3335
+ function userMessage(text) {
3336
+ return {
3337
+ type: "user",
3338
+ message: { role: "user", content: text },
3339
+ parent_tool_use_id: null
3340
+ };
3341
+ }
3342
+ function createSdkInput() {
3343
+ const queue = [];
3344
+ let wake;
3345
+ let closed = false;
3346
+ const notify = () => {
3347
+ wake?.();
3348
+ wake = void 0;
3349
+ };
3350
+ async function* messages() {
3351
+ while (true) {
3352
+ const next = queue.shift();
3353
+ if (next) {
3354
+ yield next;
3355
+ continue;
3356
+ }
3357
+ if (closed) return;
3358
+ await new Promise((resolve) => {
3359
+ wake = resolve;
3360
+ });
3361
+ }
3362
+ }
3363
+ return {
3364
+ messages: messages(),
3365
+ push: (text) => {
3366
+ queue.push(userMessage(text));
3367
+ notify();
3368
+ },
3369
+ close: () => {
3370
+ closed = true;
3371
+ notify();
3372
+ }
3373
+ };
3374
+ }
3375
+
3376
+ // src/commands/sessions/daemon/sdk/killSdkChild.ts
3377
+ function killSdkChild(child) {
3378
+ if (!child?.pid || child.exitCode !== null) return;
3379
+ try {
3380
+ if (process.platform === "win32") child.kill();
3381
+ else process.kill(-child.pid, "SIGTERM");
3382
+ } catch {
3383
+ child.kill();
3384
+ }
3385
+ }
3386
+
3387
+ // src/commands/sessions/daemon/sdk/sdkTerminalStub.ts
3388
+ var noopDisposable = { dispose: () => {
3389
+ } };
3390
+ function sdkTerminalStub(label) {
3391
+ const skip = (path15) => () => daemonLog(`${label} ${path15} skipped: Claude (SDK) session has no terminal`);
3392
+ return {
3393
+ cols: 0,
3394
+ rows: 0,
3395
+ write: skip("input"),
3396
+ resize: skip("resize"),
3397
+ onData: () => noopDisposable
3398
+ };
3399
+ }
3400
+
3401
+ // src/commands/sessions/daemon/sdk/sdkSessionHandle.ts
3402
+ function sdkSessionHandle(label) {
3403
+ const listeners = [];
3404
+ let turn;
3405
+ const unbound = (action) => daemonLog(`${label} sdk ${action} dropped: query not started`);
3406
+ const handle = {
3407
+ onEvent: (listener) => listeners.push(listener),
3408
+ send: (text) => turn ? turn.send(text) : unbound("message"),
3409
+ interrupt: () => turn ? turn.interrupt() : unbound("interrupt")
3410
+ };
3411
+ return {
3412
+ handle,
3413
+ emit: (event) => {
3414
+ for (const listener of listeners) listener(event);
3415
+ },
3416
+ bind: (controls) => {
3417
+ turn = controls;
3418
+ }
3419
+ };
3420
+ }
3421
+
3422
+ // src/commands/sessions/daemon/sdk/createSdkSessionProcess.ts
3423
+ function createSdkSessionProcess(sessionId, abort) {
3424
+ const label = `session ${sessionId ?? "?"}`;
3425
+ const sdk = sdkSessionHandle(label);
3426
+ const exitListeners = [];
3427
+ let child;
3428
+ let exited = false;
3429
+ const sessionProcess = {
3430
+ get pid() {
3431
+ return child?.pid ?? 0;
3432
+ },
3433
+ ...sdkTerminalStub(label),
3434
+ kill: () => {
3435
+ daemonLog(
3436
+ `${label} sdk query ended by kill (child pid ${child?.pid ?? "none"})`
3437
+ );
3438
+ abort.abort();
3439
+ killSdkChild(child);
3440
+ },
3441
+ onExit: (listener) => {
3442
+ exitListeners.push(listener);
3443
+ return noopDisposable;
3444
+ },
3445
+ sdk: sdk.handle
3446
+ };
3447
+ return {
3448
+ process: sessionProcess,
3449
+ emit: sdk.emit,
3450
+ exit: (exitCode) => {
3451
+ if (exited) return;
3452
+ exited = true;
3453
+ killSdkChild(child);
3454
+ for (const listener of exitListeners) listener({ exitCode });
3455
+ },
3456
+ attach: (spawned) => {
3457
+ child = spawned;
3458
+ },
3459
+ aborted: () => abort.signal.aborted,
3460
+ bind: sdk.bind
3461
+ };
3462
+ }
3463
+
3464
+ // src/commands/sessions/daemon/sdk/createSdkInterrupt.ts
3465
+ function createSdkInterrupt(label, setInterrupting) {
3466
+ let interrupting = false;
3467
+ const set = (pending) => {
3468
+ if (pending === interrupting) return;
3469
+ interrupting = pending;
3470
+ setInterrupting(pending);
3471
+ };
3472
+ return {
3473
+ clear: () => set(false),
3474
+ request: (busy, request) => {
3475
+ if (!busy || interrupting) {
3476
+ daemonLog(
3477
+ `${label} sdk interrupt ignored: ${interrupting ? "already interrupting" : "no turn running"}`
3478
+ );
3479
+ return;
3480
+ }
3481
+ daemonLog(`${label} sdk interrupt requested`);
3482
+ set(true);
3483
+ request().then(
3484
+ () => daemonLog(`${label} sdk interrupt accepted`),
3485
+ (error) => {
3486
+ daemonLog(
3487
+ `${label} sdk interrupt failed: ${error instanceof Error ? error.message : String(error)}`
3488
+ );
3489
+ set(false);
3490
+ }
3491
+ );
3492
+ }
3493
+ };
3494
+ }
3495
+
3496
+ // src/commands/sessions/daemon/sdk/createSdkMessageQueue.ts
3497
+ var MAX_LOGGED = 200;
3498
+ function quoteForLog(text) {
3499
+ return JSON.stringify(
3500
+ text.length > MAX_LOGGED ? `${text.slice(0, MAX_LOGGED)}\u2026` : text
3501
+ );
3502
+ }
3503
+ function createSdkMessageQueue(label, control, push) {
3504
+ let queued = [];
3505
+ const publish = (next) => {
3506
+ queued = next;
3507
+ control.emit({ kind: "queued", texts: next });
3508
+ };
3509
+ return {
3510
+ add: (text) => {
3511
+ publish([...queued, text]);
3512
+ daemonLog(
3513
+ `${label} sdk message queued behind running turn (${queued.length} queued): ${quoteForLog(text)}`
3514
+ );
3515
+ },
3516
+ flush: () => {
3517
+ if (!queued.length) return false;
3518
+ daemonLog(`${label} sdk sending ${queued.length} queued message(s)`);
3519
+ const text = queued.join("\n\n");
3520
+ publish([]);
3521
+ push(text);
3522
+ return true;
3523
+ }
3524
+ };
3525
+ }
3526
+
3527
+ // src/commands/sessions/daemon/sdk/createSdkTurnEmitter.ts
3528
+ function createSdkTurnEmitter(label, control) {
3529
+ let status;
3530
+ let activity = null;
3531
+ return {
3532
+ activity: (next) => {
3533
+ if (next === activity) return;
3534
+ activity = next;
3535
+ control.emit({ kind: "activity", text: next });
3536
+ },
3537
+ status: (next) => {
3538
+ if (next === status) return;
3539
+ status = next;
3540
+ daemonLog(`${label} sdk status: ${next}`);
3541
+ control.emit({ kind: "status", status: next });
3542
+ }
3543
+ };
3544
+ }
3545
+
3546
+ // src/commands/sessions/daemon/sdk/createSdkTurnTracker.ts
3547
+ function createSdkTurnTracker(label, control, push) {
3548
+ let busy = false;
3549
+ const emit = createSdkTurnEmitter(label, control);
3550
+ const queue = createSdkMessageQueue(label, control, push);
3551
+ const interrupt = createSdkInterrupt(
3552
+ label,
3553
+ (pending) => control.emit({ kind: "interrupting", pending })
3554
+ );
3555
+ const setStatus = (next) => {
3556
+ busy = next === "running";
3557
+ if (next === "waiting") {
3558
+ emit.activity(null);
3559
+ interrupt.clear();
3560
+ busy = queue.flush();
3561
+ if (busy) return;
3562
+ }
3563
+ emit.status(next);
3564
+ };
3565
+ return {
3566
+ setActivity: emit.activity,
3567
+ setStatus,
3568
+ start: (prompt) => {
3569
+ busy = true;
3570
+ push(prompt);
3571
+ },
3572
+ send: (text) => {
3573
+ if (busy) return queue.add(text);
3574
+ daemonLog(`${label} sdk message sent: ${quoteForLog(text)}`);
3575
+ push(text);
3576
+ setStatus("running");
3577
+ },
3578
+ interrupt: (request) => interrupt.request(busy, request)
3579
+ };
3580
+ }
3581
+
3582
+ // src/commands/sessions/daemon/sdk/startSdkQuery.ts
3583
+ import { query } from "@anthropic-ai/claude-agent-sdk";
3584
+
3585
+ // src/commands/sessions/daemon/resolveClaudeExecutable.ts
3586
+ import { execFileSync as execFileSync2 } from "child_process";
3587
+ var opts = {
3588
+ encoding: "utf8",
3589
+ stdio: ["ignore", "pipe", "ignore"],
3590
+ windowsHide: true
3591
+ };
3592
+ function resolveClaudeExecutable() {
3593
+ const found = process.platform === "win32" ? execFileSync2("where", ["claude"], opts) : execFileSync2(
3594
+ process.env.SHELL ?? "bash",
3595
+ ["-l", "-c", "command -v claude"],
3596
+ opts
3597
+ );
3598
+ const lines = found.split(/\r?\n/).map((line) => line.trim()).filter((line) => /^(\/|[A-Za-z]:\\)/.test(line));
3599
+ const path15 = lines.find((line) => line.endsWith(".exe")) ?? lines.at(-1);
3600
+ if (!path15) throw new Error("claude is not on PATH");
3601
+ return path15;
3602
+ }
3603
+
3604
+ // src/commands/sessions/daemon/sdk/sdkContextUsedPct.ts
3605
+ function sdkContextTokens(usage) {
3606
+ if (!usage) return 0;
3607
+ return (usage.input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);
3608
+ }
3609
+ function sdkContextUsedPct(contextTokens, model, result) {
3610
+ const windows = Object.entries(result.modelUsage ?? {});
3611
+ const contextWindow = model && result.modelUsage?.[model]?.contextWindow || Math.max(0, ...windows.map(([, usage]) => usage.contextWindow ?? 0));
3612
+ if (!contextTokens || !contextWindow) return void 0;
3613
+ return Math.min(100, Math.round(contextTokens / contextWindow * 100));
3614
+ }
3615
+
3616
+ // src/commands/sessions/daemon/sdk/sdkRateLimits.ts
3617
+ var WINDOWS = ["five_hour", "seven_day"];
3618
+ function toWindow(info) {
3619
+ if (typeof info?.utilization !== "number") return void 0;
3620
+ return {
3621
+ used_percentage: Math.round(info.utilization * 100),
3622
+ resets_at: info.resetsAt
3623
+ };
3624
+ }
3625
+ function windowInfo(info, window) {
3626
+ const unified = info.unifiedWindows;
3627
+ if (unified) return unified[window];
3628
+ return info.rateLimitType === window ? info : void 0;
3629
+ }
3630
+ function sdkRateLimits(info) {
3631
+ const limits = {};
3632
+ for (const window of WINDOWS) {
3633
+ const observed = toWindow(windowInfo(info, window));
3634
+ if (observed) limits[window] = observed;
3635
+ }
3636
+ return Object.keys(limits).length ? limits : void 0;
3637
+ }
3638
+
3639
+ // src/commands/sessions/daemon/sdk/createSdkUsageObserver.ts
3640
+ function createSdkUsageObserver(label) {
3641
+ let contextTokens = 0;
3642
+ let model;
3643
+ let transcriptPath;
3644
+ const transcriptFor = (claudeSessionId) => {
3645
+ transcriptPath ??= findSessionJsonlPath(claudeSessionId).catch(() => null);
3646
+ return transcriptPath;
3647
+ };
3648
+ return (message2) => {
3649
+ const sink2 = sdkUsageSink();
3650
+ if (message2.type === "rate_limit_event") {
3651
+ const limits = sdkRateLimits(message2.rate_limit_info);
3652
+ if (!limits) return;
3653
+ daemonLog(
3654
+ `${label} sdk rate limits: 5h ${limits.five_hour?.used_percentage ?? "-"}% 7d ${limits.seven_day?.used_percentage ?? "-"}%`
3655
+ );
3656
+ sink2?.limits(limits);
3657
+ } else if (message2.type === "assistant" && message2.parent_tool_use_id === null) {
3658
+ contextTokens = sdkContextTokens(message2.message.usage) || contextTokens;
3659
+ model = message2.message.model ?? model;
3660
+ } else if (message2.type === "result") {
3661
+ const usedPct = sdkContextUsedPct(contextTokens, model, message2);
3662
+ const claudeSessionId = message2.session_id;
3663
+ daemonLog(
3664
+ `${label} sdk usage: claude session ${claudeSessionId} context ${usedPct ?? "-"}%`
3665
+ );
3666
+ if (!sink2) return;
3667
+ void transcriptFor(claudeSessionId).then(
3668
+ (path15) => sink2.usage(claudeSessionId, path15 ?? void 0, usedPct)
3669
+ );
3670
+ }
3671
+ };
3672
+ }
3673
+
3674
+ // src/commands/sessions/daemon/sdk/logSdkMessage.ts
3675
+ function logSdkMessage(label, message2) {
3676
+ if (message2.type === "system" && message2.subtype === "init")
3677
+ daemonLog(
3678
+ `${label} sdk init: claude session ${message2.session_id} model ${message2.model} permission mode ${message2.permissionMode}`
3679
+ );
3680
+ if (message2.type === "result")
3681
+ daemonLog(`${label} sdk turn ended: ${message2.subtype}`);
3682
+ }
3683
+
3684
+ // src/commands/sessions/daemon/sdk/sdkBackgroundTasks.ts
3685
+ function sdkBackgroundTasks(message2) {
3686
+ if (message2.type !== "system" || message2.subtype !== "background_tasks_changed")
3687
+ return void 0;
3688
+ return message2.tasks.filter((task) => !task.ambient).map((task) => task.description);
3689
+ }
3690
+
3691
+ // src/commands/sessions/daemon/sdk/sdkActivityText.ts
3692
+ var TARGET_KEYS = [
3693
+ "command",
3694
+ "file_path",
3695
+ "notebook_path",
3696
+ "path",
3697
+ "pattern",
3698
+ "url",
3699
+ "query",
3700
+ "description",
3701
+ "skill"
3702
+ ];
3703
+ var MAX_TARGET = 80;
3704
+ function toolTarget2(input) {
3705
+ if (!input || typeof input !== "object") return "";
3706
+ const record3 = input;
3707
+ const key = TARGET_KEYS.find((k) => typeof record3[k] === "string");
3708
+ if (!key) return "";
3709
+ const line = record3[key].split("\n")[0].trim();
3710
+ return line.length > MAX_TARGET ? `${line.slice(0, MAX_TARGET - 1)}\u2026` : line;
3711
+ }
3712
+ function sdkActivityText(content) {
3713
+ const tool = [...content].reverse().find((block) => block.type === "tool_use");
3714
+ if (!tool?.name) return "Working";
3715
+ const target = toolTarget2(tool.input);
3716
+ return `Working \xB7 ${tool.name}${target ? ` ${target}` : ""}`;
3717
+ }
3718
+
3719
+ // src/commands/sessions/daemon/sdk/sdkTurnStatus.ts
3720
+ function sdkTurnStatus(message2) {
3721
+ if (message2.type === "assistant" && message2.parent_tool_use_id === null)
3722
+ return "running";
3723
+ if (message2.type === "result") return "waiting";
3724
+ if (message2.type === "system" && message2.subtype === "session_state_changed")
3725
+ return message2.state === "running" ? "running" : "waiting";
3726
+ return void 0;
3727
+ }
3728
+
3729
+ // src/commands/sessions/daemon/sdk/runSdkQuery.ts
3730
+ async function runSdkQuery(messages, sessionId, control, turn) {
3731
+ const label = `session ${sessionId ?? "?"}`;
3732
+ const observeUsage = createSdkUsageObserver(label);
3733
+ try {
3734
+ for await (const message2 of messages) {
3735
+ logSdkMessage(label, message2);
3736
+ observeUsage(message2);
3737
+ const status = sdkTurnStatus(message2);
3738
+ if (status) turn.setStatus(status);
3739
+ const background = sdkBackgroundTasks(message2);
3740
+ if (background) control.emit({ kind: "background", tasks: background });
3741
+ if (message2.type === "assistant" && message2.parent_tool_use_id === null)
3742
+ turn.setActivity(sdkActivityText(message2.message.content));
3743
+ }
3744
+ daemonLog(`${label} sdk query finished`);
3745
+ control.exit(0);
3746
+ } catch (error) {
3747
+ if (control.aborted()) {
3748
+ daemonLog(`${label} sdk query stopped after kill`);
3749
+ control.exit(0);
3750
+ return;
3751
+ }
3752
+ daemonLog(
3753
+ `${label} sdk query failed: ${error instanceof Error ? error.message : String(error)}`
3754
+ );
3755
+ control.exit(1);
3756
+ }
3757
+ }
3758
+
3759
+ // src/commands/sessions/daemon/sdk/sdkQueryOptions.ts
3760
+ import { readFileSync as readFileSync8 } from "fs";
3761
+
3762
+ // src/commands/sessions/daemon/sdk/spawnSdkChild.ts
3763
+ import { spawn as spawn4 } from "child_process";
3764
+ var MAX_STDERR_LINE = 300;
3765
+ function spawnSdkChild(options, sessionId, attach) {
3766
+ const label = `session ${sessionId ?? "?"}`;
3767
+ const child = spawn4(options.command, options.args, {
3768
+ cwd: options.cwd,
3769
+ env: sessionChildEnv(options.env, sessionId),
3770
+ stdio: ["pipe", "pipe", "pipe"],
3771
+ signal: options.signal,
3772
+ /* why: its own process group, so a kill also reaches the shell commands
3773
+ * claude runs for its tools, as killPtyTree does for terminal sessions. */
3774
+ detached: process.platform !== "win32",
3775
+ windowsHide: true
3776
+ });
3777
+ daemonLog(
3778
+ `${label} sdk child spawned: pid ${child.pid ?? "none"} ${options.command}`
3779
+ );
3780
+ child.stderr.setEncoding("utf8");
3781
+ child.stderr.on("data", (chunk) => {
3782
+ for (const line of chunk.split("\n")) {
3783
+ const trimmed = line.trim();
3784
+ if (trimmed)
3785
+ daemonLog(`${label} sdk stderr: ${trimmed.slice(0, MAX_STDERR_LINE)}`);
3786
+ }
3787
+ });
3788
+ child.on(
3789
+ "exit",
3790
+ (code, signal) => daemonLog(`${label} sdk child exited: code ${code} signal ${signal}`)
3791
+ );
3792
+ attach(child);
3793
+ return child;
3794
+ }
3795
+
3796
+ // src/commands/sessions/daemon/sdk/sdkQueryOptions.ts
3797
+ function sdkQueryOptions(opts2, executable, abort, control) {
3798
+ const append = opts2.appendSystemPromptFile ? readFileSync8(opts2.appendSystemPromptFile, "utf8") : void 0;
3799
+ return {
3800
+ cwd: opts2.cwd,
3801
+ ...opts2.resumeId ? { resume: opts2.resumeId } : { sessionId: opts2.claudeSessionId },
3802
+ permissionMode: "auto",
3803
+ settings: ensureHooksSettings(),
3804
+ pathToClaudeCodeExecutable: executable,
3805
+ spawnClaudeCodeProcess: (options) => spawnSdkChild(options, opts2.sessionId, control.attach),
3806
+ abortController: abort,
3807
+ model: opts2.model,
3808
+ systemPrompt: { type: "preset", preset: "claude_code", append }
3809
+ };
3810
+ }
3811
+
3812
+ // src/commands/sessions/daemon/sdk/startSdkQuery.ts
3813
+ async function startSdkQuery(opts2, abort, control, turn, prompt) {
3814
+ const label = `session ${opts2.sessionId ?? "?"}`;
3815
+ try {
3816
+ const executable = resolveClaudeExecutable();
3817
+ daemonLog(
3818
+ `${label} sdk query starting: claude ${executable}, claude session ${opts2.claudeSessionId ?? "unassigned"}, permission mode auto, cwd ${opts2.cwd ?? process.cwd()}`
3819
+ );
3820
+ const messages = query({
3821
+ prompt,
3822
+ options: sdkQueryOptions(opts2, executable, abort, control)
3823
+ });
3824
+ if (opts2.resumeId) awaitResume(label, messages, control);
3825
+ control.bind({
3826
+ send: turn.send,
3827
+ interrupt: () => turn.interrupt(async () => {
3828
+ await messages.interrupt();
3829
+ })
3830
+ });
3831
+ await runSdkQuery(messages, opts2.sessionId, control, turn);
3832
+ } catch (error) {
3833
+ daemonLog(
3834
+ `${label} sdk query not started: ${error instanceof Error ? error.message : String(error)}`
3835
+ );
3836
+ control.exit(1);
3837
+ }
3838
+ }
3839
+ function awaitResume(label, messages, control) {
3840
+ messages.initializationResult().then(
3841
+ () => {
3842
+ daemonLog(`${label} sdk resume complete`);
3843
+ control.emit({ kind: "resumed" });
3844
+ },
3845
+ (error) => daemonLog(
3846
+ `${label} sdk resume did not complete: ${error instanceof Error ? error.message : String(error)}`
3847
+ )
3848
+ );
3849
+ }
3850
+
3851
+ // src/commands/sessions/daemon/spawnClaudeSdk.ts
3852
+ function spawnClaudeSdk(opts2) {
3853
+ refuseMissingCwd(opts2.cwd, opts2.sessionId);
3854
+ const abort = new AbortController();
3855
+ const control = createSdkSessionProcess(opts2.sessionId, abort);
3856
+ const input = createSdkInput();
3857
+ const turn = createSdkTurnTracker(
3858
+ `session ${opts2.sessionId ?? "?"}`,
3859
+ control,
3860
+ input.push
3861
+ );
3862
+ if (opts2.prompt) turn.start(opts2.prompt);
3863
+ abort.signal.addEventListener("abort", input.close);
3864
+ void startSdkQuery(opts2, abort, control, turn, input.messages);
3865
+ return control.process;
3866
+ }
3867
+
3868
+ // src/shared/harnessAdapters/claudeSdkAdapter.ts
3869
+ var claudeSdkAdapter = {
3870
+ ...claudeAdapter,
3871
+ kind: "claude-sdk",
3872
+ label: harnessLabel("claude-sdk"),
3873
+ capabilities: {
3874
+ ...harnessCapabilityDeclarations["claude-sdk"],
3875
+ "connector.gmail.read": () => claudeConnectorProbe("Gmail"),
3876
+ "connector.slack.read": () => claudeConnectorProbe("Slack")
3877
+ },
3878
+ detect: () => detectHarness("claude-sdk"),
3879
+ interactive: ({
3880
+ sessionId,
3881
+ conversationId,
3882
+ resumeId,
3883
+ prompt,
3884
+ cwd,
3885
+ appendSystemPromptFile,
3886
+ model
3887
+ }) => spawnClaudeSdk({
3888
+ prompt,
3889
+ cwd,
3890
+ sessionId,
3891
+ claudeSessionId: conversationId,
3892
+ resumeId,
3893
+ appendSystemPromptFile,
3894
+ model
3895
+ }),
3896
+ activityIdentity: (conversationId) => ({
3897
+ harness: "claude-sdk",
3898
+ claudeSessionId: conversationId
3899
+ })
3900
+ };
3901
+
3902
+ // src/shared/harnessAdapters/harnessAdapter.ts
3903
+ var adapters = {
3904
+ claude: claudeAdapter,
3905
+ "claude-sdk": claudeSdkAdapter,
3906
+ codex: codexAdapter,
3907
+ pi: piAdapter
3908
+ };
3909
+ function harnessAdapter(kind) {
3910
+ return adapters[resolveHarness(kind)];
3911
+ }
3912
+
3913
+ export {
3914
+ rememberViewerSize,
3915
+ viewerSize,
3916
+ spawnPty,
3917
+ deriveHistoryFields,
3918
+ backlogRunMarkers,
3919
+ parseSessionFile,
3920
+ discoverSessionJsonlPaths,
3921
+ withoutResumeSession,
3922
+ readTranscriptTail,
3923
+ readTranscriptTailSync,
3924
+ emptyScanUsage,
3925
+ scanUsageTokens,
3926
+ reviewerLabel,
3927
+ printReviewerFailure,
3928
+ detectHarness,
3929
+ claudeAdapter,
3930
+ setSdkUsageSink,
3931
+ resolveCodexModel,
3932
+ discoverCodexRolloutPaths,
3933
+ parseRolloutEntry,
3934
+ rolloutPayload,
3935
+ rolloutString,
3936
+ codexRolloutMeta,
3937
+ readCodexHeadLines,
3938
+ codexAdapter,
3939
+ piAdapter,
3940
+ harnessAdapter
3941
+ };